github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/net/http/sniff_test.go (about)

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