Source file src/net/textproto/reader_test.go

     1  // Copyright 2010 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 textproto
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"io"
    11  	"net"
    12  	"reflect"
    13  	"runtime"
    14  	"slices"
    15  	"strings"
    16  	"sync"
    17  	"testing"
    18  )
    19  
    20  func reader(s string) *Reader {
    21  	return NewReader(bufio.NewReader(strings.NewReader(s)))
    22  }
    23  
    24  func TestReadLine(t *testing.T) {
    25  	r := reader("line1\nline2\n")
    26  	s, err := r.ReadLine()
    27  	if s != "line1" || err != nil {
    28  		t.Fatalf("Line 1: %s, %v", s, err)
    29  	}
    30  	s, err = r.ReadLine()
    31  	if s != "line2" || err != nil {
    32  		t.Fatalf("Line 2: %s, %v", s, err)
    33  	}
    34  	s, err = r.ReadLine()
    35  	if s != "" || err != io.EOF {
    36  		t.Fatalf("EOF: %s, %v", s, err)
    37  	}
    38  }
    39  
    40  func TestReadLineLongLine(t *testing.T) {
    41  	line := strings.Repeat("12345", 10000)
    42  	r := reader(line + "\r\n")
    43  	s, err := r.ReadLine()
    44  	if err != nil {
    45  		t.Fatalf("Line 1: %v", err)
    46  	}
    47  	if s != line {
    48  		t.Fatalf("%v-byte line does not match expected %v-byte line", len(s), len(line))
    49  	}
    50  }
    51  
    52  func TestReadContinuedLine(t *testing.T) {
    53  	r := reader("line1\nline\n 2\nline3\n")
    54  	s, err := r.ReadContinuedLine()
    55  	if s != "line1" || err != nil {
    56  		t.Fatalf("Line 1: %s, %v", s, err)
    57  	}
    58  	s, err = r.ReadContinuedLine()
    59  	if s != "line 2" || err != nil {
    60  		t.Fatalf("Line 2: %s, %v", s, err)
    61  	}
    62  	s, err = r.ReadContinuedLine()
    63  	if s != "line3" || err != nil {
    64  		t.Fatalf("Line 3: %s, %v", s, err)
    65  	}
    66  	s, err = r.ReadContinuedLine()
    67  	if s != "" || err != io.EOF {
    68  		t.Fatalf("EOF: %s, %v", s, err)
    69  	}
    70  }
    71  
    72  func TestReadCodeLine(t *testing.T) {
    73  	r := reader("123 hi\n234 bye\n345 no way\n")
    74  	code, msg, err := r.ReadCodeLine(0)
    75  	if code != 123 || msg != "hi" || err != nil {
    76  		t.Fatalf("Line 1: %d, %s, %v", code, msg, err)
    77  	}
    78  	code, msg, err = r.ReadCodeLine(23)
    79  	if code != 234 || msg != "bye" || err != nil {
    80  		t.Fatalf("Line 2: %d, %s, %v", code, msg, err)
    81  	}
    82  	code, msg, err = r.ReadCodeLine(346)
    83  	if code != 345 || msg != "no way" || err == nil {
    84  		t.Fatalf("Line 3: %d, %s, %v", code, msg, err)
    85  	}
    86  	if e, ok := err.(*Error); !ok || e.Code != code || e.Msg != msg {
    87  		t.Fatalf("Line 3: wrong error %v\n", err)
    88  	}
    89  	code, msg, err = r.ReadCodeLine(1)
    90  	if code != 0 || msg != "" || err != io.EOF {
    91  		t.Fatalf("EOF: %d, %s, %v", code, msg, err)
    92  	}
    93  }
    94  
    95  func TestReadDotLines(t *testing.T) {
    96  	r := reader("dotlines\r\n.foo\r\n..bar\n...baz\nquux\r\n\r\n.\r\nanother\n")
    97  	s, err := r.ReadDotLines()
    98  	want := []string{"dotlines", "foo", ".bar", "..baz", "quux", ""}
    99  	if !slices.Equal(s, want) || err != nil {
   100  		t.Fatalf("ReadDotLines: %v, %v", s, err)
   101  	}
   102  
   103  	s, err = r.ReadDotLines()
   104  	want = []string{"another"}
   105  	if !slices.Equal(s, want) || err != io.ErrUnexpectedEOF {
   106  		t.Fatalf("ReadDotLines2: %v, %v", s, err)
   107  	}
   108  }
   109  
   110  func TestReadDotBytes(t *testing.T) {
   111  	r := reader("dotlines\r\n.foo\r\n..bar\n...baz\nquux\r\n\r\n.\r\nanot.her\r\n")
   112  	b, err := r.ReadDotBytes()
   113  	want := []byte("dotlines\nfoo\n.bar\n..baz\nquux\n\n")
   114  	if !slices.Equal(b, want) || err != nil {
   115  		t.Fatalf("ReadDotBytes: %q, %v", b, err)
   116  	}
   117  
   118  	b, err = r.ReadDotBytes()
   119  	want = []byte("anot.her\n")
   120  	if !slices.Equal(b, want) || err != io.ErrUnexpectedEOF {
   121  		t.Fatalf("ReadDotBytes2: %q, %v", b, err)
   122  	}
   123  }
   124  
   125  func TestReadMIMEHeader(t *testing.T) {
   126  	r := reader("my-key: Value 1  \r\nLong-key: Even \n Longer Value\r\nmy-Key: Value 2\r\n\n")
   127  	m, err := r.ReadMIMEHeader()
   128  	want := MIMEHeader{
   129  		"My-Key":   {"Value 1", "Value 2"},
   130  		"Long-Key": {"Even Longer Value"},
   131  	}
   132  	if !reflect.DeepEqual(m, want) || err != nil {
   133  		t.Fatalf("ReadMIMEHeader: %v, %v; want %v", m, err, want)
   134  	}
   135  }
   136  
   137  func TestReadMIMEHeaderSingle(t *testing.T) {
   138  	r := reader("Foo: bar\n\n")
   139  	m, err := r.ReadMIMEHeader()
   140  	want := MIMEHeader{"Foo": {"bar"}}
   141  	if !reflect.DeepEqual(m, want) || err != nil {
   142  		t.Fatalf("ReadMIMEHeader: %v, %v; want %v", m, err, want)
   143  	}
   144  }
   145  
   146  // TestReaderUpcomingHeaderKeys is testing an internal function, but it's very
   147  // difficult to test well via the external API.
   148  func TestReaderUpcomingHeaderKeys(t *testing.T) {
   149  	for _, test := range []struct {
   150  		input string
   151  		want  int
   152  	}{{
   153  		input: "",
   154  		want:  0,
   155  	}, {
   156  		input: "A: v",
   157  		want:  1,
   158  	}, {
   159  		input: "A: v\r\nB: v\r\n",
   160  		want:  2,
   161  	}, {
   162  		input: "A: v\nB: v\n",
   163  		want:  2,
   164  	}, {
   165  		input: "A: v\r\n  continued\r\n  still continued\r\nB: v\r\n\r\n",
   166  		want:  2,
   167  	}, {
   168  		input: "A: v\r\n\r\nB: v\r\nC: v\r\n",
   169  		want:  1,
   170  	}, {
   171  		input: "A: v" + strings.Repeat("\n", 1000),
   172  		want:  1,
   173  	}} {
   174  		r := reader(test.input)
   175  		got := r.upcomingHeaderKeys()
   176  		if test.want != got {
   177  			t.Fatalf("upcomingHeaderKeys(%q): %v; want %v", test.input, got, test.want)
   178  		}
   179  	}
   180  }
   181  
   182  func TestReadMIMEHeaderNoKey(t *testing.T) {
   183  	r := reader(": bar\ntest-1: 1\n\n")
   184  	m, err := r.ReadMIMEHeader()
   185  	want := MIMEHeader{}
   186  	if !reflect.DeepEqual(m, want) || err == nil {
   187  		t.Fatalf("ReadMIMEHeader: %v, %v; want %v", m, err, want)
   188  	}
   189  }
   190  
   191  func TestLargeReadMIMEHeader(t *testing.T) {
   192  	data := make([]byte, 16*1024)
   193  	for i := 0; i < len(data); i++ {
   194  		data[i] = 'x'
   195  	}
   196  	sdata := string(data)
   197  	r := reader("Cookie: " + sdata + "\r\n\n")
   198  	m, err := r.ReadMIMEHeader()
   199  	if err != nil {
   200  		t.Fatalf("ReadMIMEHeader: %v", err)
   201  	}
   202  	cookie := m.Get("Cookie")
   203  	if cookie != sdata {
   204  		t.Fatalf("ReadMIMEHeader: %v bytes, want %v bytes", len(cookie), len(sdata))
   205  	}
   206  }
   207  
   208  // TestReadMIMEHeaderNonCompliant checks that we don't normalize headers
   209  // with spaces before colons, and accept spaces in keys.
   210  func TestReadMIMEHeaderNonCompliant(t *testing.T) {
   211  	// These invalid headers will be rejected by net/http according to RFC 7230.
   212  	r := reader("Foo: bar\r\n" +
   213  		"Content-Language: en\r\n" +
   214  		"SID : 0\r\n" +
   215  		"Audio Mode : None\r\n" +
   216  		"Privilege : 127\r\n\r\n")
   217  	m, err := r.ReadMIMEHeader()
   218  	want := MIMEHeader{
   219  		"Foo":              {"bar"},
   220  		"Content-Language": {"en"},
   221  		"SID ":             {"0"},
   222  		"Audio Mode ":      {"None"},
   223  		"Privilege ":       {"127"},
   224  	}
   225  	if !reflect.DeepEqual(m, want) || err != nil {
   226  		t.Fatalf("ReadMIMEHeader =\n%v, %v; want:\n%v", m, err, want)
   227  	}
   228  }
   229  
   230  func TestReadMIMEHeaderMalformed(t *testing.T) {
   231  	inputs := []string{
   232  		"No colon first line\r\nFoo: foo\r\n\r\n",
   233  		" No colon first line with leading space\r\nFoo: foo\r\n\r\n",
   234  		"\tNo colon first line with leading tab\r\nFoo: foo\r\n\r\n",
   235  		" First: line with leading space\r\nFoo: foo\r\n\r\n",
   236  		"\tFirst: line with leading tab\r\nFoo: foo\r\n\r\n",
   237  		"Foo: foo\r\nNo colon second line\r\n\r\n",
   238  		"Foo-\n\tBar: foo\r\n\r\n",
   239  		"Foo-\r\n\tBar: foo\r\n\r\n",
   240  		"Foo\r\n\t: foo\r\n\r\n",
   241  		"Foo-\n\tBar",
   242  		"Foo \tBar: foo\r\n\r\n",
   243  		": empty key\r\n\r\n",
   244  	}
   245  	for _, input := range inputs {
   246  		r := reader(input)
   247  		if m, err := r.ReadMIMEHeader(); err == nil || err == io.EOF {
   248  			t.Errorf("ReadMIMEHeader(%q) = %v, %v; want nil, err", input, m, err)
   249  		}
   250  	}
   251  }
   252  
   253  func TestReadMIMEHeaderBytes(t *testing.T) {
   254  	for i := 0; i <= 0xff; i++ {
   255  		s := "Foo" + string(rune(i)) + "Bar: foo\r\n\r\n"
   256  		r := reader(s)
   257  		wantErr := true
   258  		switch {
   259  		case i >= '0' && i <= '9':
   260  			wantErr = false
   261  		case i >= 'a' && i <= 'z':
   262  			wantErr = false
   263  		case i >= 'A' && i <= 'Z':
   264  			wantErr = false
   265  		case i == '!' || i == '#' || i == '$' || i == '%' || i == '&' || i == '\'' || i == '*' || i == '+' || i == '-' || i == '.' || i == '^' || i == '_' || i == '`' || i == '|' || i == '~':
   266  			wantErr = false
   267  		case i == ':':
   268  			// Special case: "Foo:Bar: foo" is the header "Foo".
   269  			wantErr = false
   270  		case i == ' ':
   271  			wantErr = false
   272  		}
   273  		m, err := r.ReadMIMEHeader()
   274  		if err != nil != wantErr {
   275  			t.Errorf("ReadMIMEHeader(%q) = %v, %v; want error=%v", s, m, err, wantErr)
   276  		}
   277  	}
   278  	for i := 0; i <= 0xff; i++ {
   279  		s := "Foo: foo" + string(rune(i)) + "bar\r\n\r\n"
   280  		r := reader(s)
   281  		wantErr := true
   282  		switch {
   283  		case i >= 0x21 && i <= 0x7e:
   284  			wantErr = false
   285  		case i == ' ':
   286  			wantErr = false
   287  		case i == '\t':
   288  			wantErr = false
   289  		case i >= 0x80 && i <= 0xff:
   290  			wantErr = false
   291  		}
   292  		m, err := r.ReadMIMEHeader()
   293  		if (err != nil) != wantErr {
   294  			t.Errorf("ReadMIMEHeader(%q) = %v, %v; want error=%v", s, m, err, wantErr)
   295  		}
   296  	}
   297  }
   298  
   299  // Test that continued lines are properly trimmed. Issue 11204.
   300  func TestReadMIMEHeaderTrimContinued(t *testing.T) {
   301  	// In this header, \n and \r\n terminated lines are mixed on purpose.
   302  	// We expect each line to be trimmed (prefix and suffix) before being concatenated.
   303  	// Keep the spaces as they are.
   304  	r := reader("" + // for code formatting purpose.
   305  		"a:\n" +
   306  		" 0 \r\n" +
   307  		"b:1 \t\r\n" +
   308  		"c: 2\r\n" +
   309  		" 3\t\n" +
   310  		"  \t 4  \r\n\n")
   311  	m, err := r.ReadMIMEHeader()
   312  	if err != nil {
   313  		t.Fatal(err)
   314  	}
   315  	want := MIMEHeader{
   316  		"A": {"0"},
   317  		"B": {"1"},
   318  		"C": {"2 3 4"},
   319  	}
   320  	if !reflect.DeepEqual(m, want) {
   321  		t.Fatalf("ReadMIMEHeader mismatch.\n got: %q\nwant: %q", m, want)
   322  	}
   323  }
   324  
   325  // Test that reading a header doesn't overallocate. Issue 58975.
   326  func TestReadMIMEHeaderAllocations(t *testing.T) {
   327  	var totalAlloc uint64
   328  	const count = 200
   329  	for i := 0; i < count; i++ {
   330  		r := reader("A: b\r\n\r\n" + strings.Repeat("\n", 4096))
   331  		var m1, m2 runtime.MemStats
   332  		runtime.ReadMemStats(&m1)
   333  		_, err := r.ReadMIMEHeader()
   334  		if err != nil {
   335  			t.Fatalf("ReadMIMEHeader: %v", err)
   336  		}
   337  		runtime.ReadMemStats(&m2)
   338  		totalAlloc += m2.TotalAlloc - m1.TotalAlloc
   339  	}
   340  	// 32k is large and we actually allocate substantially less,
   341  	// but prior to the fix for #58975 we allocated ~400k in this case.
   342  	if got, want := totalAlloc/count, uint64(32768); got > want {
   343  		t.Fatalf("ReadMIMEHeader allocated %v bytes, want < %v", got, want)
   344  	}
   345  }
   346  
   347  type readResponseTest struct {
   348  	in       string
   349  	inCode   int
   350  	wantCode int
   351  	wantMsg  string
   352  }
   353  
   354  var readResponseTests = []readResponseTest{
   355  	{"230-Anonymous access granted, restrictions apply\n" +
   356  		"Read the file README.txt,\n" +
   357  		"230  please",
   358  		23,
   359  		230,
   360  		"Anonymous access granted, restrictions apply\nRead the file README.txt,\n please",
   361  	},
   362  
   363  	{"230 Anonymous access granted, restrictions apply\n",
   364  		23,
   365  		230,
   366  		"Anonymous access granted, restrictions apply",
   367  	},
   368  
   369  	{"400-A\n400-B\n400 C",
   370  		4,
   371  		400,
   372  		"A\nB\nC",
   373  	},
   374  
   375  	{"400-A\r\n400-B\r\n400 C\r\n",
   376  		4,
   377  		400,
   378  		"A\nB\nC",
   379  	},
   380  }
   381  
   382  // See https://www.ietf.org/rfc/rfc959.txt page 36.
   383  func TestRFC959Lines(t *testing.T) {
   384  	for i, tt := range readResponseTests {
   385  		r := reader(tt.in + "\nFOLLOWING DATA")
   386  		code, msg, err := r.ReadResponse(tt.inCode)
   387  		if err != nil {
   388  			t.Errorf("#%d: ReadResponse: %v", i, err)
   389  			continue
   390  		}
   391  		if code != tt.wantCode {
   392  			t.Errorf("#%d: code=%d, want %d", i, code, tt.wantCode)
   393  		}
   394  		if msg != tt.wantMsg {
   395  			t.Errorf("#%d: msg=%q, want %q", i, msg, tt.wantMsg)
   396  		}
   397  	}
   398  }
   399  
   400  // Test that multi-line errors are appropriately and fully read. Issue 10230.
   401  func TestReadMultiLineError(t *testing.T) {
   402  	r := reader("550-5.1.1 The email account that you tried to reach does not exist. Please try\n" +
   403  		"550-5.1.1 double-checking the recipient's email address for typos or\n" +
   404  		"550-5.1.1 unnecessary spaces. Learn more at\n" +
   405  		"Unexpected but legal text!\n" +
   406  		"550 5.1.1 https://support.google.com/mail/answer/6596 h20si25154304pfd.166 - gsmtp\n")
   407  
   408  	wantMsg := "5.1.1 The email account that you tried to reach does not exist. Please try\n" +
   409  		"5.1.1 double-checking the recipient's email address for typos or\n" +
   410  		"5.1.1 unnecessary spaces. Learn more at\n" +
   411  		"Unexpected but legal text!\n" +
   412  		"5.1.1 https://support.google.com/mail/answer/6596 h20si25154304pfd.166 - gsmtp"
   413  
   414  	code, msg, err := r.ReadResponse(250)
   415  	if err == nil {
   416  		t.Errorf("ReadResponse: no error, want error")
   417  	}
   418  	if code != 550 {
   419  		t.Errorf("ReadResponse: code=%d, want %d", code, 550)
   420  	}
   421  	if msg != wantMsg {
   422  		t.Errorf("ReadResponse: msg=%q, want %q", msg, wantMsg)
   423  	}
   424  	if err != nil && err.Error() != "550 "+wantMsg {
   425  		t.Errorf("ReadResponse: error=%q, want %q", err.Error(), "550 "+wantMsg)
   426  	}
   427  }
   428  
   429  func TestCommonHeaders(t *testing.T) {
   430  	commonHeaderOnce.Do(initCommonHeader)
   431  	for h := range commonHeader {
   432  		if h != CanonicalMIMEHeaderKey(h) {
   433  			t.Errorf("Non-canonical header %q in commonHeader", h)
   434  		}
   435  	}
   436  	b := []byte("content-Length")
   437  	want := "Content-Length"
   438  	n := testing.AllocsPerRun(200, func() {
   439  		if x, _ := canonicalMIMEHeaderKey(b); x != want {
   440  			t.Fatalf("canonicalMIMEHeaderKey(%q) = %q; want %q", b, x, want)
   441  		}
   442  	})
   443  	if n > 0 {
   444  		t.Errorf("canonicalMIMEHeaderKey allocs = %v; want 0", n)
   445  	}
   446  }
   447  
   448  func TestIssue46363(t *testing.T) {
   449  	// Regression test for data race reported in issue 46363:
   450  	// ReadMIMEHeader reads commonHeader before commonHeader has been initialized.
   451  	// Run this test with the race detector enabled to catch the reported data race.
   452  
   453  	// Reset commonHeaderOnce, so that commonHeader will have to be initialized
   454  	commonHeaderOnce = sync.Once{}
   455  	commonHeader = nil
   456  
   457  	// Test for data race by calling ReadMIMEHeader and CanonicalMIMEHeaderKey concurrently
   458  
   459  	// Send MIME header over net.Conn
   460  	r, w := net.Pipe()
   461  	go func() {
   462  		// ReadMIMEHeader calls canonicalMIMEHeaderKey, which reads from commonHeader
   463  		NewConn(r).ReadMIMEHeader()
   464  	}()
   465  	w.Write([]byte("A: 1\r\nB: 2\r\nC: 3\r\n\r\n"))
   466  
   467  	// CanonicalMIMEHeaderKey calls commonHeaderOnce.Do(initCommonHeader) which initializes commonHeader
   468  	CanonicalMIMEHeaderKey("a")
   469  
   470  	if commonHeader == nil {
   471  		t.Fatal("CanonicalMIMEHeaderKey should initialize commonHeader")
   472  	}
   473  }
   474  
   475  var clientHeaders = strings.Replace(`Host: golang.org
   476  Connection: keep-alive
   477  Cache-Control: max-age=0
   478  Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
   479  User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3
   480  Accept-Encoding: gzip,deflate,sdch
   481  Accept-Language: en-US,en;q=0.8,fr-CH;q=0.6
   482  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
   483  COOKIE: __utma=000000000.0000000000.0000000000.0000000000.0000000000.00; __utmb=000000000.0.00.0000000000; __utmc=000000000; __utmz=000000000.0000000000.00.0.utmcsr=code.google.com|utmccn=(referral)|utmcmd=referral|utmcct=/p/go/issues/detail
   484  Non-Interned: test
   485  
   486  `, "\n", "\r\n", -1)
   487  
   488  var serverHeaders = strings.Replace(`Content-Type: text/html; charset=utf-8
   489  Content-Encoding: gzip
   490  Date: Thu, 27 Sep 2012 09:03:33 GMT
   491  Server: Google Frontend
   492  Cache-Control: private
   493  Content-Length: 2298
   494  VIA: 1.1 proxy.example.com:80 (XXX/n.n.n-nnn)
   495  Connection: Close
   496  Non-Interned: test
   497  
   498  `, "\n", "\r\n", -1)
   499  
   500  func BenchmarkReadMIMEHeader(b *testing.B) {
   501  	b.ReportAllocs()
   502  	for _, set := range []struct {
   503  		name    string
   504  		headers string
   505  	}{
   506  		{"client_headers", clientHeaders},
   507  		{"server_headers", serverHeaders},
   508  	} {
   509  		b.Run(set.name, func(b *testing.B) {
   510  			var buf bytes.Buffer
   511  			br := bufio.NewReader(&buf)
   512  			r := NewReader(br)
   513  
   514  			for i := 0; i < b.N; i++ {
   515  				buf.WriteString(set.headers)
   516  				if _, err := r.ReadMIMEHeader(); err != nil {
   517  					b.Fatal(err)
   518  				}
   519  			}
   520  		})
   521  	}
   522  }
   523  
   524  func BenchmarkUncommon(b *testing.B) {
   525  	b.ReportAllocs()
   526  	var buf bytes.Buffer
   527  	br := bufio.NewReader(&buf)
   528  	r := NewReader(br)
   529  	for i := 0; i < b.N; i++ {
   530  		buf.WriteString("uncommon-header-for-benchmark: foo\r\n\r\n")
   531  		h, err := r.ReadMIMEHeader()
   532  		if err != nil {
   533  			b.Fatal(err)
   534  		}
   535  		if _, ok := h["Uncommon-Header-For-Benchmark"]; !ok {
   536  			b.Fatal("Missing result header.")
   537  		}
   538  	}
   539  }
   540  

View as plain text