Source file src/net/http/sniff_test.go

Documentation: net/http

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package http_test
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"io"
    11  	"io/ioutil"
    12  	"log"
    13  	. "net/http"
    14  	"reflect"
    15  	"strconv"
    16  	"strings"
    17  	"testing"
    18  )
    19  
    20  var sniffTests = []struct {
    21  	desc        string
    22  	data        []byte
    23  	contentType string
    24  }{
    25  	// Some nonsense.
    26  	{"Empty", []byte{}, "text/plain; charset=utf-8"},
    27  	{"Binary", []byte{1, 2, 3}, "application/octet-stream"},
    28  
    29  	{"HTML document #1", []byte(`<HtMl><bOdY>blah blah blah</body></html>`), "text/html; charset=utf-8"},
    30  	{"HTML document #2", []byte(`<HTML></HTML>`), "text/html; charset=utf-8"},
    31  	{"HTML document #3 (leading whitespace)", []byte(`   <!DOCTYPE HTML>...`), "text/html; charset=utf-8"},
    32  	{"HTML document #4 (leading CRLF)", []byte("\r\n<html>..."), "text/html; charset=utf-8"},
    33  
    34  	{"Plain text", []byte(`This is not HTML. It has ☃ though.`), "text/plain; charset=utf-8"},
    35  
    36  	{"XML", []byte("\n<?xml!"), "text/xml; charset=utf-8"},
    37  
    38  	// Image types.
    39  	{"Windows icon", []byte("\x00\x00\x01\x00"), "image/x-icon"},
    40  	{"Windows cursor", []byte("\x00\x00\x02\x00"), "image/x-icon"},
    41  	{"BMP image", []byte("BM..."), "image/bmp"},
    42  	{"GIF 87a", []byte(`GIF87a`), "image/gif"},
    43  	{"GIF 89a", []byte(`GIF89a...`), "image/gif"},
    44  	{"WEBP image", []byte("RIFF\x00\x00\x00\x00WEBPVP"), "image/webp"},
    45  	{"PNG image", []byte("\x89PNG\x0D\x0A\x1A\x0A"), "image/png"},
    46  	{"JPEG image", []byte("\xFF\xD8\xFF"), "image/jpeg"},
    47  
    48  	// Audio types.
    49  	{"MIDI audio", []byte("MThd\x00\x00\x00\x06\x00\x01"), "audio/midi"},
    50  	{"MP3 audio/MPEG audio", []byte("ID3\x03\x00\x00\x00\x00\x0f"), "audio/mpeg"},
    51  	{"WAV audio #1", []byte("RIFFb\xb8\x00\x00WAVEfmt \x12\x00\x00\x00\x06"), "audio/wave"},
    52  	{"WAV audio #2", []byte("RIFF,\x00\x00\x00WAVEfmt \x12\x00\x00\x00\x06"), "audio/wave"},
    53  	{"AIFF audio #1", []byte("FORM\x00\x00\x00\x00AIFFCOMM\x00\x00\x00\x12\x00\x01\x00\x00\x57\x55\x00\x10\x40\x0d\xf3\x34"), "audio/aiff"},
    54  
    55  	{"OGG audio", []byte("OggS\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x7e\x46\x00\x00\x00\x00\x00\x00\x1f\xf6\xb4\xfc\x01\x1e\x01\x76\x6f\x72"), "application/ogg"},
    56  	{"Must not match OGG", []byte("owow\x00"), "application/octet-stream"},
    57  	{"Must not match OGG", []byte("oooS\x00"), "application/octet-stream"},
    58  	{"Must not match OGG", []byte("oggS\x00"), "application/octet-stream"},
    59  
    60  	// Video types.
    61  	{"MP4 video", []byte("\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom<\x06t\xbfmdat"), "video/mp4"},
    62  	{"AVI video #1", []byte("RIFF,O\n\x00AVI LISTÀ"), "video/avi"},
    63  	{"AVI video #2", []byte("RIFF,\n\x00\x00AVI LISTÀ"), "video/avi"},
    64  
    65  	// Font types.
    66  	// {"MS.FontObject", []byte("\x00\x00")},
    67  	{"TTF sample  I", []byte("\x00\x01\x00\x00\x00\x17\x01\x00\x00\x04\x01\x60\x4f"), "font/ttf"},
    68  	{"TTF sample II", []byte("\x00\x01\x00\x00\x00\x0e\x00\x80\x00\x03\x00\x60\x46"), "font/ttf"},
    69  
    70  	{"OTTO sample  I", []byte("\x4f\x54\x54\x4f\x00\x0e\x00\x80\x00\x03\x00\x60\x42\x41\x53\x45"), "font/otf"},
    71  
    72  	{"woff sample  I", []byte("\x77\x4f\x46\x46\x00\x01\x00\x00\x00\x00\x30\x54\x00\x0d\x00\x00"), "font/woff"},
    73  	{"woff2 sample", []byte("\x77\x4f\x46\x32\x00\x01\x00\x00\x00"), "font/woff2"},
    74  	{"wasm sample", []byte("\x00\x61\x73\x6d\x01\x00"), "application/wasm"},
    75  
    76  	// Archive types
    77  	{"RAR v1.5-v4.0", []byte("Rar!\x1A\x07\x00"), "application/x-rar-compressed"},
    78  	{"RAR v5+", []byte("Rar!\x1A\x07\x01\x00"), "application/x-rar-compressed"},
    79  	{"Incorrect RAR v1.5-v4.0", []byte("Rar \x1A\x07\x00"), "application/octet-stream"},
    80  	{"Incorrect RAR v5+", []byte("Rar \x1A\x07\x01\x00"), "application/octet-stream"},
    81  }
    82  
    83  func TestDetectContentType(t *testing.T) {
    84  	for _, tt := range sniffTests {
    85  		ct := DetectContentType(tt.data)
    86  		if ct != tt.contentType {
    87  			t.Errorf("%v: DetectContentType = %q, want %q", tt.desc, ct, tt.contentType)
    88  		}
    89  	}
    90  }
    91  
    92  func TestServerContentType_h1(t *testing.T) { testServerContentType(t, h1Mode) }
    93  func TestServerContentType_h2(t *testing.T) { testServerContentType(t, h2Mode) }
    94  
    95  func testServerContentType(t *testing.T, h2 bool) {
    96  	setParallel(t)
    97  	defer afterTest(t)
    98  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
    99  		i, _ := strconv.Atoi(r.FormValue("i"))
   100  		tt := sniffTests[i]
   101  		n, err := w.Write(tt.data)
   102  		if n != len(tt.data) || err != nil {
   103  			log.Fatalf("%v: Write(%q) = %v, %v want %d, nil", tt.desc, tt.data, n, err, len(tt.data))
   104  		}
   105  	}))
   106  	defer cst.close()
   107  
   108  	for i, tt := range sniffTests {
   109  		resp, err := cst.c.Get(cst.ts.URL + "/?i=" + strconv.Itoa(i))
   110  		if err != nil {
   111  			t.Errorf("%v: %v", tt.desc, err)
   112  			continue
   113  		}
   114  		// DetectContentType is defined to return
   115  		// text/plain; charset=utf-8 for an empty body,
   116  		// but as of Go 1.10 the HTTP server has been changed
   117  		// to return no content-type at all for an empty body.
   118  		// Adjust the expectation here.
   119  		wantContentType := tt.contentType
   120  		if len(tt.data) == 0 {
   121  			wantContentType = ""
   122  		}
   123  		if ct := resp.Header.Get("Content-Type"); ct != wantContentType {
   124  			t.Errorf("%v: Content-Type = %q, want %q", tt.desc, ct, wantContentType)
   125  		}
   126  		data, err := ioutil.ReadAll(resp.Body)
   127  		if err != nil {
   128  			t.Errorf("%v: reading body: %v", tt.desc, err)
   129  		} else if !bytes.Equal(data, tt.data) {
   130  			t.Errorf("%v: data is %q, want %q", tt.desc, data, tt.data)
   131  		}
   132  		resp.Body.Close()
   133  	}
   134  }
   135  
   136  // Issue 5953: shouldn't sniff if the handler set a Content-Type header,
   137  // even if it's the empty string.
   138  func TestServerIssue5953_h1(t *testing.T) { testServerIssue5953(t, h1Mode) }
   139  func TestServerIssue5953_h2(t *testing.T) { testServerIssue5953(t, h2Mode) }
   140  func testServerIssue5953(t *testing.T, h2 bool) {
   141  	defer afterTest(t)
   142  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
   143  		w.Header()["Content-Type"] = []string{""}
   144  		fmt.Fprintf(w, "<html><head></head><body>hi</body></html>")
   145  	}))
   146  	defer cst.close()
   147  
   148  	resp, err := cst.c.Get(cst.ts.URL)
   149  	if err != nil {
   150  		t.Fatal(err)
   151  	}
   152  
   153  	got := resp.Header["Content-Type"]
   154  	want := []string{""}
   155  	if !reflect.DeepEqual(got, want) {
   156  		t.Errorf("Content-Type = %q; want %q", got, want)
   157  	}
   158  	resp.Body.Close()
   159  }
   160  
   161  func TestContentTypeWithCopy_h1(t *testing.T) { testContentTypeWithCopy(t, h1Mode) }
   162  func TestContentTypeWithCopy_h2(t *testing.T) { testContentTypeWithCopy(t, h2Mode) }
   163  func testContentTypeWithCopy(t *testing.T, h2 bool) {
   164  	defer afterTest(t)
   165  
   166  	const (
   167  		input    = "\n<html>\n\t<head>\n"
   168  		expected = "text/html; charset=utf-8"
   169  	)
   170  
   171  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
   172  		// Use io.Copy from a bytes.Buffer to trigger ReadFrom.
   173  		buf := bytes.NewBuffer([]byte(input))
   174  		n, err := io.Copy(w, buf)
   175  		if int(n) != len(input) || err != nil {
   176  			t.Errorf("io.Copy(w, %q) = %v, %v want %d, nil", input, n, err, len(input))
   177  		}
   178  	}))
   179  	defer cst.close()
   180  
   181  	resp, err := cst.c.Get(cst.ts.URL)
   182  	if err != nil {
   183  		t.Fatalf("Get: %v", err)
   184  	}
   185  	if ct := resp.Header.Get("Content-Type"); ct != expected {
   186  		t.Errorf("Content-Type = %q, want %q", ct, expected)
   187  	}
   188  	data, err := ioutil.ReadAll(resp.Body)
   189  	if err != nil {
   190  		t.Errorf("reading body: %v", err)
   191  	} else if !bytes.Equal(data, []byte(input)) {
   192  		t.Errorf("data is %q, want %q", data, input)
   193  	}
   194  	resp.Body.Close()
   195  }
   196  
   197  func TestSniffWriteSize_h1(t *testing.T) { testSniffWriteSize(t, h1Mode) }
   198  func TestSniffWriteSize_h2(t *testing.T) { testSniffWriteSize(t, h2Mode) }
   199  func testSniffWriteSize(t *testing.T, h2 bool) {
   200  	setParallel(t)
   201  	defer afterTest(t)
   202  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
   203  		size, _ := strconv.Atoi(r.FormValue("size"))
   204  		written, err := io.WriteString(w, strings.Repeat("a", size))
   205  		if err != nil {
   206  			t.Errorf("write of %d bytes: %v", size, err)
   207  			return
   208  		}
   209  		if written != size {
   210  			t.Errorf("write of %d bytes wrote %d bytes", size, written)
   211  		}
   212  	}))
   213  	defer cst.close()
   214  	for _, size := range []int{0, 1, 200, 600, 999, 1000, 1023, 1024, 512 << 10, 1 << 20} {
   215  		res, err := cst.c.Get(fmt.Sprintf("%s/?size=%d", cst.ts.URL, size))
   216  		if err != nil {
   217  			t.Fatalf("size %d: %v", size, err)
   218  		}
   219  		if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
   220  			t.Fatalf("size %d: io.Copy of body = %v", size, err)
   221  		}
   222  		if err := res.Body.Close(); err != nil {
   223  			t.Fatalf("size %d: body Close = %v", size, err)
   224  		}
   225  	}
   226  }
   227  

View as plain text