Source file src/net/mail/message_test.go

     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 mail
     6  
     7  import (
     8  	"bytes"
     9  	"io"
    10  	"mime"
    11  	"reflect"
    12  	"strings"
    13  	"testing"
    14  	"time"
    15  )
    16  
    17  var parseTests = []struct {
    18  	in     string
    19  	header Header
    20  	body   string
    21  }{
    22  	{
    23  		// RFC 5322, Appendix A.1.1
    24  		in: `From: John Doe <jdoe@machine.example>
    25  To: Mary Smith <mary@example.net>
    26  Subject: Saying Hello
    27  Date: Fri, 21 Nov 1997 09:55:06 -0600
    28  Message-ID: <1234@local.machine.example>
    29  
    30  This is a message just to say hello.
    31  So, "Hello".
    32  `,
    33  		header: Header{
    34  			"From":       []string{"John Doe <jdoe@machine.example>"},
    35  			"To":         []string{"Mary Smith <mary@example.net>"},
    36  			"Subject":    []string{"Saying Hello"},
    37  			"Date":       []string{"Fri, 21 Nov 1997 09:55:06 -0600"},
    38  			"Message-Id": []string{"<1234@local.machine.example>"},
    39  		},
    40  		body: "This is a message just to say hello.\nSo, \"Hello\".\n",
    41  	},
    42  	{
    43  		// RFC 5965, Appendix B.1, a part of the multipart message (a header-only sub message)
    44  		in: `Feedback-Type: abuse
    45  User-Agent: SomeGenerator/1.0
    46  Version: 1
    47  `,
    48  		header: Header{
    49  			"Feedback-Type": []string{"abuse"},
    50  			"User-Agent":    []string{"SomeGenerator/1.0"},
    51  			"Version":       []string{"1"},
    52  		},
    53  		body: "",
    54  	},
    55  	{
    56  		// RFC 5322 permits any printable ASCII character,
    57  		// except colon, in a header key. Issue #58862.
    58  		in: `From: iant@golang.org
    59  Custom/Header: v
    60  
    61  Body
    62  `,
    63  		header: Header{
    64  			"From":          []string{"iant@golang.org"},
    65  			"Custom/Header": []string{"v"},
    66  		},
    67  		body: "Body\n",
    68  	},
    69  	{
    70  		// RFC 4155 mbox format. We've historically permitted this,
    71  		// so we continue to permit it. Issue #60332.
    72  		in: `From iant@golang.org Mon Jun 19 00:00:00 2023
    73  From: iant@golang.org
    74  
    75  Hello, gophers!
    76  `,
    77  		header: Header{
    78  			"From":                               []string{"iant@golang.org"},
    79  			"From iant@golang.org Mon Jun 19 00": []string{"00:00 2023"},
    80  		},
    81  		body: "Hello, gophers!\n",
    82  	},
    83  }
    84  
    85  func TestParsing(t *testing.T) {
    86  	for i, test := range parseTests {
    87  		msg, err := ReadMessage(bytes.NewBuffer([]byte(test.in)))
    88  		if err != nil {
    89  			t.Errorf("test #%d: Failed parsing message: %v", i, err)
    90  			continue
    91  		}
    92  		if !headerEq(msg.Header, test.header) {
    93  			t.Errorf("test #%d: Incorrectly parsed message header.\nGot:\n%+v\nWant:\n%+v",
    94  				i, msg.Header, test.header)
    95  		}
    96  		body, err := io.ReadAll(msg.Body)
    97  		if err != nil {
    98  			t.Errorf("test #%d: Failed reading body: %v", i, err)
    99  			continue
   100  		}
   101  		bodyStr := string(body)
   102  		if bodyStr != test.body {
   103  			t.Errorf("test #%d: Incorrectly parsed message body.\nGot:\n%+v\nWant:\n%+v",
   104  				i, bodyStr, test.body)
   105  		}
   106  	}
   107  }
   108  
   109  func headerEq(a, b Header) bool {
   110  	if len(a) != len(b) {
   111  		return false
   112  	}
   113  	for k, as := range a {
   114  		bs, ok := b[k]
   115  		if !ok {
   116  			return false
   117  		}
   118  		if !reflect.DeepEqual(as, bs) {
   119  			return false
   120  		}
   121  	}
   122  	return true
   123  }
   124  
   125  func TestDateParsing(t *testing.T) {
   126  	tests := []struct {
   127  		dateStr string
   128  		exp     time.Time
   129  	}{
   130  		// RFC 5322, Appendix A.1.1
   131  		{
   132  			"Fri, 21 Nov 1997 09:55:06 -0600",
   133  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   134  		},
   135  		// RFC 5322, Appendix A.6.2
   136  		// Obsolete date.
   137  		{
   138  			"21 Nov 97 09:55:06 GMT",
   139  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("GMT", 0)),
   140  		},
   141  		// Commonly found format not specified by RFC 5322.
   142  		{
   143  			"Fri, 21 Nov 1997 09:55:06 -0600 (MDT)",
   144  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   145  		},
   146  		{
   147  			"Thu, 20 Nov 1997 09:55:06 -0600 (MDT)",
   148  			time.Date(1997, 11, 20, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   149  		},
   150  		{
   151  			"Thu, 20 Nov 1997 09:55:06 GMT (GMT)",
   152  			time.Date(1997, 11, 20, 9, 55, 6, 0, time.UTC),
   153  		},
   154  		{
   155  			"Fri, 21 Nov 1997 09:55:06 +1300 (TOT)",
   156  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", +13*60*60)),
   157  		},
   158  	}
   159  	for _, test := range tests {
   160  		hdr := Header{
   161  			"Date": []string{test.dateStr},
   162  		}
   163  		date, err := hdr.Date()
   164  		if err != nil {
   165  			t.Errorf("Header(Date: %s).Date(): %v", test.dateStr, err)
   166  		} else if !date.Equal(test.exp) {
   167  			t.Errorf("Header(Date: %s).Date() = %+v, want %+v", test.dateStr, date, test.exp)
   168  		}
   169  
   170  		date, err = ParseDate(test.dateStr)
   171  		if err != nil {
   172  			t.Errorf("ParseDate(%s): %v", test.dateStr, err)
   173  		} else if !date.Equal(test.exp) {
   174  			t.Errorf("ParseDate(%s) = %+v, want %+v", test.dateStr, date, test.exp)
   175  		}
   176  	}
   177  }
   178  
   179  func TestDateParsingCFWS(t *testing.T) {
   180  	tests := []struct {
   181  		dateStr string
   182  		exp     time.Time
   183  		valid   bool
   184  	}{
   185  		// FWS-only. No date.
   186  		{
   187  			"   ",
   188  			// nil is not allowed
   189  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   190  			false,
   191  		},
   192  		// FWS is allowed before optional day of week.
   193  		{
   194  			"   Fri, 21 Nov 1997 09:55:06 -0600",
   195  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   196  			true,
   197  		},
   198  		{
   199  			"21 Nov 1997 09:55:06 -0600",
   200  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   201  			true,
   202  		},
   203  		{
   204  			"Fri 21 Nov 1997 09:55:06 -0600",
   205  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   206  			false, // missing ,
   207  		},
   208  		// FWS is allowed before day of month but HTAB fails.
   209  		{
   210  			"Fri,        21 Nov 1997 09:55:06 -0600",
   211  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   212  			true,
   213  		},
   214  		// FWS is allowed before and after year but HTAB fails.
   215  		{
   216  			"Fri, 21 Nov       1997     09:55:06 -0600",
   217  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   218  			true,
   219  		},
   220  		// FWS is allowed before zone but HTAB is not handled. Obsolete timezone is handled.
   221  		{
   222  			"Fri, 21 Nov 1997 09:55:06           CST",
   223  			time.Time{},
   224  			true,
   225  		},
   226  		// FWS is allowed after date and a CRLF is already replaced.
   227  		{
   228  			"Fri, 21 Nov 1997 09:55:06           CST (no leading FWS and a trailing CRLF) \r\n",
   229  			time.Time{},
   230  			true,
   231  		},
   232  		// CFWS is a reduced set of US-ASCII where space and accentuated are obsolete. No error.
   233  		{
   234  			"Fri, 21    Nov 1997    09:55:06 -0600 (MDT and non-US-ASCII signs éèç )",
   235  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   236  			true,
   237  		},
   238  		// CFWS is allowed after zone including a nested comment.
   239  		// Trailing FWS is allowed.
   240  		{
   241  			"Fri, 21 Nov 1997 09:55:06 -0600    \r\n (thisisa(valid)cfws)   \t ",
   242  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   243  			true,
   244  		},
   245  		// CRLF is incomplete and misplaced.
   246  		{
   247  			"Fri, 21 Nov 1997 \r 09:55:06 -0600    \r\n (thisisa(valid)cfws)   \t ",
   248  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   249  			false,
   250  		},
   251  		// CRLF is complete but misplaced. No error is returned.
   252  		{
   253  			"Fri, 21 Nov 199\r\n7  09:55:06 -0600    \r\n (thisisa(valid)cfws)   \t ",
   254  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   255  			true, // should be false in the strict interpretation of RFC 5322.
   256  		},
   257  		// Invalid ASCII in date.
   258  		{
   259  			"Fri, 21 Nov 1997 ù 09:55:06 -0600    \r\n (thisisa(valid)cfws)   \t ",
   260  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   261  			false,
   262  		},
   263  		// CFWS chars () in date.
   264  		{
   265  			"Fri, 21 Nov () 1997 09:55:06 -0600    \r\n (thisisa(valid)cfws)   \t ",
   266  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   267  			false,
   268  		},
   269  		// Timezone is invalid but T is found in comment.
   270  		{
   271  			"Fri, 21 Nov 1997 09:55:06 -060    \r\n (Thisisa(valid)cfws)   \t ",
   272  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   273  			false,
   274  		},
   275  		// Date has no month.
   276  		{
   277  			"Fri, 21  1997 09:55:06 -0600",
   278  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   279  			false,
   280  		},
   281  		// Invalid month : OCT iso Oct
   282  		{
   283  			"Fri, 21 OCT 1997 09:55:06 CST",
   284  			time.Time{},
   285  			false,
   286  		},
   287  		// A too short time zone.
   288  		{
   289  			"Fri, 21 Nov 1997 09:55:06 -060",
   290  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   291  			false,
   292  		},
   293  		// A too short obsolete time zone.
   294  		{
   295  			"Fri, 21  1997 09:55:06 GT",
   296  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.FixedZone("", -6*60*60)),
   297  			false,
   298  		},
   299  		// Ensure that the presence of "T" in the date
   300  		// doesn't trip out ParseDate, as per issue 39260.
   301  		{
   302  			"Tue, 26 May 2020 14:04:40 GMT",
   303  			time.Date(2020, 05, 26, 14, 04, 40, 0, time.UTC),
   304  			true,
   305  		},
   306  		{
   307  			"Tue, 26 May 2020 14:04:40 UT",
   308  			time.Date(2020, 05, 26, 14, 04, 40, 0, time.UTC),
   309  			true,
   310  		},
   311  		{
   312  			"Thu, 21 May 2020 14:04:40 UT",
   313  			time.Date(2020, 05, 21, 14, 04, 40, 0, time.UTC),
   314  			true,
   315  		},
   316  		{
   317  			"Tue, 26 May 2020 14:04:40 XT",
   318  			time.Date(2020, 05, 26, 14, 04, 40, 0, time.UTC),
   319  			false,
   320  		},
   321  		{
   322  			"Thu, 21 May 2020 14:04:40 XT",
   323  			time.Date(2020, 05, 21, 14, 04, 40, 0, time.UTC),
   324  			false,
   325  		},
   326  		{
   327  			"Thu, 21 May 2020 14:04:40 UTC",
   328  			time.Date(2020, 05, 21, 14, 04, 40, 0, time.UTC),
   329  			true,
   330  		},
   331  		{
   332  			"Fri, 21 Nov 1997 09:55:06 GMT (GMT)",
   333  			time.Date(1997, 11, 21, 9, 55, 6, 0, time.UTC),
   334  			true,
   335  		},
   336  	}
   337  	for _, test := range tests {
   338  		hdr := Header{
   339  			"Date": []string{test.dateStr},
   340  		}
   341  		date, err := hdr.Date()
   342  		if err != nil && test.valid {
   343  			t.Errorf("Header(Date: %s).Date(): %v", test.dateStr, err)
   344  		} else if err == nil && test.exp.IsZero() {
   345  			// OK.  Used when exact result depends on the
   346  			// system's local zoneinfo.
   347  		} else if err == nil && !date.Equal(test.exp) && test.valid {
   348  			t.Errorf("Header(Date: %s).Date() = %+v, want %+v", test.dateStr, date, test.exp)
   349  		} else if err == nil && !test.valid { // an invalid expression was tested
   350  			t.Errorf("Header(Date: %s).Date() did not return an error but %v", test.dateStr, date)
   351  		}
   352  
   353  		date, err = ParseDate(test.dateStr)
   354  		if err != nil && test.valid {
   355  			t.Errorf("ParseDate(%s): %v", test.dateStr, err)
   356  		} else if err == nil && test.exp.IsZero() {
   357  			// OK.  Used when exact result depends on the
   358  			// system's local zoneinfo.
   359  		} else if err == nil && !test.valid { // an invalid expression was tested
   360  			t.Errorf("ParseDate(%s) did not return an error but %v", test.dateStr, date)
   361  		} else if err == nil && test.valid && !date.Equal(test.exp) {
   362  			t.Errorf("ParseDate(%s) = %+v, want %+v", test.dateStr, date, test.exp)
   363  		}
   364  	}
   365  }
   366  
   367  func TestAddressParsingError(t *testing.T) {
   368  	mustErrTestCases := [...]struct {
   369  		text        string
   370  		wantErrText string
   371  	}{
   372  		0:  {"=?iso-8859-2?Q?Bogl=E1rka_Tak=E1cs?= <unknown@gmail.com>", "charset not supported"},
   373  		1:  {"a@gmail.com b@gmail.com", "expected single address"},
   374  		2:  {string([]byte{0xed, 0xa0, 0x80}) + " <micro@example.net>", "invalid utf-8 in address"},
   375  		3:  {"\"" + string([]byte{0xed, 0xa0, 0x80}) + "\" <half-surrogate@example.com>", "invalid utf-8 in quoted-string"},
   376  		4:  {"\"\\" + string([]byte{0x80}) + "\" <escaped-invalid-unicode@example.net>", "invalid utf-8 in quoted-string"},
   377  		5:  {"\"\x00\" <null@example.net>", "bad character in quoted-string"},
   378  		6:  {"\"\\\x00\" <escaped-null@example.net>", "bad character in quoted-string"},
   379  		7:  {"John Doe", "no angle-addr"},
   380  		8:  {`<jdoe#machine.example>`, "missing @ in addr-spec"},
   381  		9:  {`John <middle> Doe <jdoe@machine.example>`, "missing @ in addr-spec"},
   382  		10: {"cfws@example.com (", "misformatted parenthetical comment"},
   383  		11: {"empty group: ;", "empty group"},
   384  		12: {"root group: embed group: null@example.com;", "no angle-addr"},
   385  		13: {"group not closed: null@example.com", "expected comma"},
   386  		14: {"group: first@example.com, second@example.com;", "group with multiple addresses"},
   387  		15: {"john.doe", "missing '@' or angle-addr"},
   388  		16: {"john.doe@", "no angle-addr"},
   389  		17: {"John Doe@foo.bar", "no angle-addr"},
   390  	}
   391  
   392  	for i, tc := range mustErrTestCases {
   393  		_, err := ParseAddress(tc.text)
   394  		if err == nil || !strings.Contains(err.Error(), tc.wantErrText) {
   395  			t.Errorf(`mail.ParseAddress(%q) #%d want %q, got %v`, tc.text, i, tc.wantErrText, err)
   396  		}
   397  	}
   398  
   399  	t.Run("CustomWordDecoder", func(t *testing.T) {
   400  		p := &AddressParser{WordDecoder: &mime.WordDecoder{}}
   401  		for i, tc := range mustErrTestCases {
   402  			_, err := p.Parse(tc.text)
   403  			if err == nil || !strings.Contains(err.Error(), tc.wantErrText) {
   404  				t.Errorf(`p.Parse(%q) #%d want %q, got %v`, tc.text, i, tc.wantErrText, err)
   405  			}
   406  		}
   407  	})
   408  
   409  }
   410  
   411  func TestAddressParsing(t *testing.T) {
   412  	tests := []struct {
   413  		addrsStr string
   414  		exp      []*Address
   415  	}{
   416  		// Bare address
   417  		{
   418  			`jdoe@machine.example`,
   419  			[]*Address{{
   420  				Address: "jdoe@machine.example",
   421  			}},
   422  		},
   423  		// RFC 5322, Appendix A.1.1
   424  		{
   425  			`John Doe <jdoe@machine.example>`,
   426  			[]*Address{{
   427  				Name:    "John Doe",
   428  				Address: "jdoe@machine.example",
   429  			}},
   430  		},
   431  		// RFC 5322, Appendix A.1.2
   432  		{
   433  			`"Joe Q. Public" <john.q.public@example.com>`,
   434  			[]*Address{{
   435  				Name:    "Joe Q. Public",
   436  				Address: "john.q.public@example.com",
   437  			}},
   438  		},
   439  		{
   440  			`"John (middle) Doe" <jdoe@machine.example>`,
   441  			[]*Address{{
   442  				Name:    "John (middle) Doe",
   443  				Address: "jdoe@machine.example",
   444  			}},
   445  		},
   446  		{
   447  			`John (middle) Doe <jdoe@machine.example>`,
   448  			[]*Address{{
   449  				Name:    "John (middle) Doe",
   450  				Address: "jdoe@machine.example",
   451  			}},
   452  		},
   453  		{
   454  			`John !@M@! Doe <jdoe@machine.example>`,
   455  			[]*Address{{
   456  				Name:    "John !@M@! Doe",
   457  				Address: "jdoe@machine.example",
   458  			}},
   459  		},
   460  		{
   461  			`"John <middle> Doe" <jdoe@machine.example>`,
   462  			[]*Address{{
   463  				Name:    "John <middle> Doe",
   464  				Address: "jdoe@machine.example",
   465  			}},
   466  		},
   467  		{
   468  			`Mary Smith <mary@x.test>, jdoe@example.org, Who? <one@y.test>`,
   469  			[]*Address{
   470  				{
   471  					Name:    "Mary Smith",
   472  					Address: "mary@x.test",
   473  				},
   474  				{
   475  					Address: "jdoe@example.org",
   476  				},
   477  				{
   478  					Name:    "Who?",
   479  					Address: "one@y.test",
   480  				},
   481  			},
   482  		},
   483  		{
   484  			`<boss@nil.test>, "Giant; \"Big\" Box" <sysservices@example.net>`,
   485  			[]*Address{
   486  				{
   487  					Address: "boss@nil.test",
   488  				},
   489  				{
   490  					Name:    `Giant; "Big" Box`,
   491  					Address: "sysservices@example.net",
   492  				},
   493  			},
   494  		},
   495  		// RFC 5322, Appendix A.6.1
   496  		{
   497  			`Joe Q. Public <john.q.public@example.com>`,
   498  			[]*Address{{
   499  				Name:    "Joe Q. Public",
   500  				Address: "john.q.public@example.com",
   501  			}},
   502  		},
   503  		// RFC 5322, Appendix A.1.3
   504  		{
   505  			`group1: groupaddr1@example.com;`,
   506  			[]*Address{
   507  				{
   508  					Name:    "",
   509  					Address: "groupaddr1@example.com",
   510  				},
   511  			},
   512  		},
   513  		{
   514  			`empty group: ;`,
   515  			[]*Address(nil),
   516  		},
   517  		{
   518  			`A Group:Ed Jones <c@a.test>,joe@where.test,John <jdoe@one.test>;`,
   519  			[]*Address{
   520  				{
   521  					Name:    "Ed Jones",
   522  					Address: "c@a.test",
   523  				},
   524  				{
   525  					Name:    "",
   526  					Address: "joe@where.test",
   527  				},
   528  				{
   529  					Name:    "John",
   530  					Address: "jdoe@one.test",
   531  				},
   532  			},
   533  		},
   534  		// RFC5322 4.4 obs-addr-list
   535  		{
   536  			` , joe@where.test,,John <jdoe@one.test>,`,
   537  			[]*Address{
   538  				{
   539  					Name:    "",
   540  					Address: "joe@where.test",
   541  				},
   542  				{
   543  					Name:    "John",
   544  					Address: "jdoe@one.test",
   545  				},
   546  			},
   547  		},
   548  		{
   549  			` , joe@where.test,,John <jdoe@one.test>,,`,
   550  			[]*Address{
   551  				{
   552  					Name:    "",
   553  					Address: "joe@where.test",
   554  				},
   555  				{
   556  					Name:    "John",
   557  					Address: "jdoe@one.test",
   558  				},
   559  			},
   560  		},
   561  		{
   562  			`Group1: <addr1@example.com>;, Group 2: addr2@example.com;, John <addr3@example.com>`,
   563  			[]*Address{
   564  				{
   565  					Name:    "",
   566  					Address: "addr1@example.com",
   567  				},
   568  				{
   569  					Name:    "",
   570  					Address: "addr2@example.com",
   571  				},
   572  				{
   573  					Name:    "John",
   574  					Address: "addr3@example.com",
   575  				},
   576  			},
   577  		},
   578  		// RFC 2047 "Q"-encoded ISO-8859-1 address.
   579  		{
   580  			`=?iso-8859-1?q?J=F6rg_Doe?= <joerg@example.com>`,
   581  			[]*Address{
   582  				{
   583  					Name:    `Jörg Doe`,
   584  					Address: "joerg@example.com",
   585  				},
   586  			},
   587  		},
   588  		// RFC 2047 "Q"-encoded US-ASCII address. Dumb but legal.
   589  		{
   590  			`=?us-ascii?q?J=6Frg_Doe?= <joerg@example.com>`,
   591  			[]*Address{
   592  				{
   593  					Name:    `Jorg Doe`,
   594  					Address: "joerg@example.com",
   595  				},
   596  			},
   597  		},
   598  		// RFC 2047 "Q"-encoded UTF-8 address.
   599  		{
   600  			`=?utf-8?q?J=C3=B6rg_Doe?= <joerg@example.com>`,
   601  			[]*Address{
   602  				{
   603  					Name:    `Jörg Doe`,
   604  					Address: "joerg@example.com",
   605  				},
   606  			},
   607  		},
   608  		// RFC 2047 "Q"-encoded UTF-8 address with multiple encoded-words.
   609  		{
   610  			`=?utf-8?q?J=C3=B6rg?=  =?utf-8?q?Doe?= <joerg@example.com>`,
   611  			[]*Address{
   612  				{
   613  					Name:    `JörgDoe`,
   614  					Address: "joerg@example.com",
   615  				},
   616  			},
   617  		},
   618  		// RFC 2047, Section 8.
   619  		{
   620  			`=?ISO-8859-1?Q?Andr=E9?= Pirard <PIRARD@vm1.ulg.ac.be>`,
   621  			[]*Address{
   622  				{
   623  					Name:    `André Pirard`,
   624  					Address: "PIRARD@vm1.ulg.ac.be",
   625  				},
   626  			},
   627  		},
   628  		// Custom example of RFC 2047 "B"-encoded ISO-8859-1 address.
   629  		{
   630  			`=?ISO-8859-1?B?SvZyZw==?= <joerg@example.com>`,
   631  			[]*Address{
   632  				{
   633  					Name:    `Jörg`,
   634  					Address: "joerg@example.com",
   635  				},
   636  			},
   637  		},
   638  		// Custom example of RFC 2047 "B"-encoded UTF-8 address.
   639  		{
   640  			`=?UTF-8?B?SsO2cmc=?= <joerg@example.com>`,
   641  			[]*Address{
   642  				{
   643  					Name:    `Jörg`,
   644  					Address: "joerg@example.com",
   645  				},
   646  			},
   647  		},
   648  		// Custom example with "." in name. For issue 4938
   649  		{
   650  			`Asem H. <noreply@example.com>`,
   651  			[]*Address{
   652  				{
   653  					Name:    `Asem H.`,
   654  					Address: "noreply@example.com",
   655  				},
   656  			},
   657  		},
   658  		// RFC 6532 3.2.3, qtext /= UTF8-non-ascii
   659  		{
   660  			`"Gø Pher" <gopher@example.com>`,
   661  			[]*Address{
   662  				{
   663  					Name:    `Gø Pher`,
   664  					Address: "gopher@example.com",
   665  				},
   666  			},
   667  		},
   668  		// RFC 6532 3.2, atext /= UTF8-non-ascii
   669  		{
   670  			`µ <micro@example.com>`,
   671  			[]*Address{
   672  				{
   673  					Name:    `µ`,
   674  					Address: "micro@example.com",
   675  				},
   676  			},
   677  		},
   678  		// RFC 6532 3.2.2, local address parts allow UTF-8
   679  		{
   680  			`Micro <µ@example.com>`,
   681  			[]*Address{
   682  				{
   683  					Name:    `Micro`,
   684  					Address: "µ@example.com",
   685  				},
   686  			},
   687  		},
   688  		// RFC 6532 3.2.4, domains parts allow UTF-8
   689  		{
   690  			`Micro <micro@µ.example.com>`,
   691  			[]*Address{
   692  				{
   693  					Name:    `Micro`,
   694  					Address: "micro@µ.example.com",
   695  				},
   696  			},
   697  		},
   698  		// Issue 14866
   699  		{
   700  			`"" <emptystring@example.com>`,
   701  			[]*Address{
   702  				{
   703  					Name:    "",
   704  					Address: "emptystring@example.com",
   705  				},
   706  			},
   707  		},
   708  		// CFWS
   709  		{
   710  			`<cfws@example.com> (CFWS (cfws))  (another comment)`,
   711  			[]*Address{
   712  				{
   713  					Name:    "",
   714  					Address: "cfws@example.com",
   715  				},
   716  			},
   717  		},
   718  		{
   719  			`<cfws@example.com> ()  (another comment), <cfws2@example.com> (another)`,
   720  			[]*Address{
   721  				{
   722  					Name:    "",
   723  					Address: "cfws@example.com",
   724  				},
   725  				{
   726  					Name:    "",
   727  					Address: "cfws2@example.com",
   728  				},
   729  			},
   730  		},
   731  		// Comment as display name
   732  		{
   733  			`john@example.com (John Doe)`,
   734  			[]*Address{
   735  				{
   736  					Name:    "John Doe",
   737  					Address: "john@example.com",
   738  				},
   739  			},
   740  		},
   741  		// Comment and display name
   742  		{
   743  			`John Doe <john@example.com> (Joey)`,
   744  			[]*Address{
   745  				{
   746  					Name:    "John Doe",
   747  					Address: "john@example.com",
   748  				},
   749  			},
   750  		},
   751  		// Comment as display name, no space
   752  		{
   753  			`john@example.com(John Doe)`,
   754  			[]*Address{
   755  				{
   756  					Name:    "John Doe",
   757  					Address: "john@example.com",
   758  				},
   759  			},
   760  		},
   761  		// Comment as display name, Q-encoded
   762  		{
   763  			`asjo@example.com (Adam =?utf-8?Q?Sj=C3=B8gren?=)`,
   764  			[]*Address{
   765  				{
   766  					Name:    "Adam Sjøgren",
   767  					Address: "asjo@example.com",
   768  				},
   769  			},
   770  		},
   771  		// Comment as display name, Q-encoded and tab-separated
   772  		{
   773  			`asjo@example.com (Adam	=?utf-8?Q?Sj=C3=B8gren?=)`,
   774  			[]*Address{
   775  				{
   776  					Name:    "Adam Sjøgren",
   777  					Address: "asjo@example.com",
   778  				},
   779  			},
   780  		},
   781  		// Nested comment as display name, Q-encoded
   782  		{
   783  			`asjo@example.com (Adam =?utf-8?Q?Sj=C3=B8gren?= (Debian))`,
   784  			[]*Address{
   785  				{
   786  					Name:    "Adam Sjøgren (Debian)",
   787  					Address: "asjo@example.com",
   788  				},
   789  			},
   790  		},
   791  	}
   792  	for _, test := range tests {
   793  		if len(test.exp) == 1 {
   794  			addr, err := ParseAddress(test.addrsStr)
   795  			if err != nil {
   796  				t.Errorf("Failed parsing (single) %q: %v", test.addrsStr, err)
   797  				continue
   798  			}
   799  			if !reflect.DeepEqual([]*Address{addr}, test.exp) {
   800  				t.Errorf("Parse (single) of %q: got %+v, want %+v", test.addrsStr, addr, test.exp)
   801  			}
   802  		}
   803  
   804  		addrs, err := ParseAddressList(test.addrsStr)
   805  		if err != nil {
   806  			t.Errorf("Failed parsing (list) %q: %v", test.addrsStr, err)
   807  			continue
   808  		}
   809  		if !reflect.DeepEqual(addrs, test.exp) {
   810  			t.Errorf("Parse (list) of %q: got %+v, want %+v", test.addrsStr, addrs, test.exp)
   811  		}
   812  	}
   813  }
   814  
   815  func TestAddressParser(t *testing.T) {
   816  	tests := []struct {
   817  		addrsStr string
   818  		exp      []*Address
   819  	}{
   820  		// Bare address
   821  		{
   822  			`jdoe@machine.example`,
   823  			[]*Address{{
   824  				Address: "jdoe@machine.example",
   825  			}},
   826  		},
   827  		// RFC 5322, Appendix A.1.1
   828  		{
   829  			`John Doe <jdoe@machine.example>`,
   830  			[]*Address{{
   831  				Name:    "John Doe",
   832  				Address: "jdoe@machine.example",
   833  			}},
   834  		},
   835  		// RFC 5322, Appendix A.1.2
   836  		{
   837  			`"Joe Q. Public" <john.q.public@example.com>`,
   838  			[]*Address{{
   839  				Name:    "Joe Q. Public",
   840  				Address: "john.q.public@example.com",
   841  			}},
   842  		},
   843  		{
   844  			`Mary Smith <mary@x.test>, jdoe@example.org, Who? <one@y.test>`,
   845  			[]*Address{
   846  				{
   847  					Name:    "Mary Smith",
   848  					Address: "mary@x.test",
   849  				},
   850  				{
   851  					Address: "jdoe@example.org",
   852  				},
   853  				{
   854  					Name:    "Who?",
   855  					Address: "one@y.test",
   856  				},
   857  			},
   858  		},
   859  		{
   860  			`<boss@nil.test>, "Giant; \"Big\" Box" <sysservices@example.net>`,
   861  			[]*Address{
   862  				{
   863  					Address: "boss@nil.test",
   864  				},
   865  				{
   866  					Name:    `Giant; "Big" Box`,
   867  					Address: "sysservices@example.net",
   868  				},
   869  			},
   870  		},
   871  		// RFC 2047 "Q"-encoded ISO-8859-1 address.
   872  		{
   873  			`=?iso-8859-1?q?J=F6rg_Doe?= <joerg@example.com>`,
   874  			[]*Address{
   875  				{
   876  					Name:    `Jörg Doe`,
   877  					Address: "joerg@example.com",
   878  				},
   879  			},
   880  		},
   881  		// RFC 2047 "Q"-encoded US-ASCII address. Dumb but legal.
   882  		{
   883  			`=?us-ascii?q?J=6Frg_Doe?= <joerg@example.com>`,
   884  			[]*Address{
   885  				{
   886  					Name:    `Jorg Doe`,
   887  					Address: "joerg@example.com",
   888  				},
   889  			},
   890  		},
   891  		// RFC 2047 "Q"-encoded ISO-8859-15 address.
   892  		{
   893  			`=?ISO-8859-15?Q?J=F6rg_Doe?= <joerg@example.com>`,
   894  			[]*Address{
   895  				{
   896  					Name:    `Jörg Doe`,
   897  					Address: "joerg@example.com",
   898  				},
   899  			},
   900  		},
   901  		// RFC 2047 "B"-encoded windows-1252 address.
   902  		{
   903  			`=?windows-1252?q?Andr=E9?= Pirard <PIRARD@vm1.ulg.ac.be>`,
   904  			[]*Address{
   905  				{
   906  					Name:    `André Pirard`,
   907  					Address: "PIRARD@vm1.ulg.ac.be",
   908  				},
   909  			},
   910  		},
   911  		// Custom example of RFC 2047 "B"-encoded ISO-8859-15 address.
   912  		{
   913  			`=?ISO-8859-15?B?SvZyZw==?= <joerg@example.com>`,
   914  			[]*Address{
   915  				{
   916  					Name:    `Jörg`,
   917  					Address: "joerg@example.com",
   918  				},
   919  			},
   920  		},
   921  		// Custom example of RFC 2047 "B"-encoded UTF-8 address.
   922  		{
   923  			`=?UTF-8?B?SsO2cmc=?= <joerg@example.com>`,
   924  			[]*Address{
   925  				{
   926  					Name:    `Jörg`,
   927  					Address: "joerg@example.com",
   928  				},
   929  			},
   930  		},
   931  		// Custom example with "." in name. For issue 4938
   932  		{
   933  			`Asem H. <noreply@example.com>`,
   934  			[]*Address{
   935  				{
   936  					Name:    `Asem H.`,
   937  					Address: "noreply@example.com",
   938  				},
   939  			},
   940  		},
   941  	}
   942  
   943  	ap := AddressParser{WordDecoder: &mime.WordDecoder{
   944  		CharsetReader: func(charset string, input io.Reader) (io.Reader, error) {
   945  			in, err := io.ReadAll(input)
   946  			if err != nil {
   947  				return nil, err
   948  			}
   949  
   950  			switch charset {
   951  			case "iso-8859-15":
   952  				in = bytes.ReplaceAll(in, []byte("\xf6"), []byte("ö"))
   953  			case "windows-1252":
   954  				in = bytes.ReplaceAll(in, []byte("\xe9"), []byte("é"))
   955  			}
   956  
   957  			return bytes.NewReader(in), nil
   958  		},
   959  	}}
   960  
   961  	for _, test := range tests {
   962  		if len(test.exp) == 1 {
   963  			addr, err := ap.Parse(test.addrsStr)
   964  			if err != nil {
   965  				t.Errorf("Failed parsing (single) %q: %v", test.addrsStr, err)
   966  				continue
   967  			}
   968  			if !reflect.DeepEqual([]*Address{addr}, test.exp) {
   969  				t.Errorf("Parse (single) of %q: got %+v, want %+v", test.addrsStr, addr, test.exp)
   970  			}
   971  		}
   972  
   973  		addrs, err := ap.ParseList(test.addrsStr)
   974  		if err != nil {
   975  			t.Errorf("Failed parsing (list) %q: %v", test.addrsStr, err)
   976  			continue
   977  		}
   978  		if !reflect.DeepEqual(addrs, test.exp) {
   979  			t.Errorf("Parse (list) of %q: got %+v, want %+v", test.addrsStr, addrs, test.exp)
   980  		}
   981  	}
   982  }
   983  
   984  func TestAddressString(t *testing.T) {
   985  	tests := []struct {
   986  		addr *Address
   987  		exp  string
   988  	}{
   989  		{
   990  			&Address{Address: "bob@example.com"},
   991  			"<bob@example.com>",
   992  		},
   993  		{ // quoted local parts: RFC 5322, 3.4.1. and 3.2.4.
   994  			&Address{Address: `my@idiot@address@example.com`},
   995  			`<"my@idiot@address"@example.com>`,
   996  		},
   997  		{ // quoted local parts
   998  			&Address{Address: ` @example.com`},
   999  			`<" "@example.com>`,
  1000  		},
  1001  		{
  1002  			&Address{Name: "Bob", Address: "bob@example.com"},
  1003  			`"Bob" <bob@example.com>`,
  1004  		},
  1005  		{
  1006  			// note the ö (o with an umlaut)
  1007  			&Address{Name: "Böb", Address: "bob@example.com"},
  1008  			`=?utf-8?q?B=C3=B6b?= <bob@example.com>`,
  1009  		},
  1010  		{
  1011  			&Address{Name: "Bob Jane", Address: "bob@example.com"},
  1012  			`"Bob Jane" <bob@example.com>`,
  1013  		},
  1014  		{
  1015  			&Address{Name: "Böb Jacöb", Address: "bob@example.com"},
  1016  			`=?utf-8?q?B=C3=B6b_Jac=C3=B6b?= <bob@example.com>`,
  1017  		},
  1018  		{ // https://golang.org/issue/12098
  1019  			&Address{Name: "Rob", Address: ""},
  1020  			`"Rob" <@>`,
  1021  		},
  1022  		{ // https://golang.org/issue/12098
  1023  			&Address{Name: "Rob", Address: "@"},
  1024  			`"Rob" <@>`,
  1025  		},
  1026  		{
  1027  			&Address{Name: "Böb, Jacöb", Address: "bob@example.com"},
  1028  			`=?utf-8?b?QsO2YiwgSmFjw7Zi?= <bob@example.com>`,
  1029  		},
  1030  		{
  1031  			&Address{Name: "=??Q?x?=", Address: "hello@world.com"},
  1032  			`"=??Q?x?=" <hello@world.com>`,
  1033  		},
  1034  		{
  1035  			&Address{Name: "=?hello", Address: "hello@world.com"},
  1036  			`"=?hello" <hello@world.com>`,
  1037  		},
  1038  		{
  1039  			&Address{Name: "world?=", Address: "hello@world.com"},
  1040  			`"world?=" <hello@world.com>`,
  1041  		},
  1042  		{
  1043  			// should q-encode even for invalid utf-8.
  1044  			&Address{Name: string([]byte{0xed, 0xa0, 0x80}), Address: "invalid-utf8@example.net"},
  1045  			"=?utf-8?q?=ED=A0=80?= <invalid-utf8@example.net>",
  1046  		},
  1047  	}
  1048  	for _, test := range tests {
  1049  		s := test.addr.String()
  1050  		if s != test.exp {
  1051  			t.Errorf("Address%+v.String() = %v, want %v", *test.addr, s, test.exp)
  1052  			continue
  1053  		}
  1054  
  1055  		// Check round-trip.
  1056  		if test.addr.Address != "" && test.addr.Address != "@" {
  1057  			a, err := ParseAddress(test.exp)
  1058  			if err != nil {
  1059  				t.Errorf("ParseAddress(%#q): %v", test.exp, err)
  1060  				continue
  1061  			}
  1062  			if a.Name != test.addr.Name || a.Address != test.addr.Address {
  1063  				t.Errorf("ParseAddress(%#q) = %#v, want %#v", test.exp, a, test.addr)
  1064  			}
  1065  		}
  1066  	}
  1067  }
  1068  
  1069  // Check if all valid addresses can be parsed, formatted and parsed again
  1070  func TestAddressParsingAndFormatting(t *testing.T) {
  1071  
  1072  	// Should pass
  1073  	tests := []string{
  1074  		`<Bob@example.com>`,
  1075  		`<bob.bob@example.com>`,
  1076  		`<".bob"@example.com>`,
  1077  		`<" "@example.com>`,
  1078  		`<some.mail-with-dash@example.com>`,
  1079  		`<"dot.and space"@example.com>`,
  1080  		`<"very.unusual.@.unusual.com"@example.com>`,
  1081  		`<admin@mailserver1>`,
  1082  		`<postmaster@localhost>`,
  1083  		"<#!$%&'*+-/=?^_`{}|~@example.org>",
  1084  		`<"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com>`, // escaped quotes
  1085  		`<"()<>[]:,;@\\\"!#$%&'*+-/=?^_{}| ~.a"@example.org>`,                      // escaped backslashes
  1086  		`<"Abc\\@def"@example.com>`,
  1087  		`<"Joe\\Blow"@example.com>`,
  1088  		`<test1/test2=test3@example.com>`,
  1089  		`<def!xyz%abc@example.com>`,
  1090  		`<_somename@example.com>`,
  1091  		`<joe@uk>`,
  1092  		`<~@example.com>`,
  1093  		`<"..."@test.com>`,
  1094  		`<"john..doe"@example.com>`,
  1095  		`<"john.doe."@example.com>`,
  1096  		`<".john.doe"@example.com>`,
  1097  		`<"."@example.com>`,
  1098  		`<".."@example.com>`,
  1099  		`<"0:"@0>`,
  1100  	}
  1101  
  1102  	for _, test := range tests {
  1103  		addr, err := ParseAddress(test)
  1104  		if err != nil {
  1105  			t.Errorf("Couldn't parse address %s: %s", test, err.Error())
  1106  			continue
  1107  		}
  1108  		str := addr.String()
  1109  		addr, err = ParseAddress(str)
  1110  		if err != nil {
  1111  			t.Errorf("ParseAddr(%q) error: %v", test, err)
  1112  			continue
  1113  		}
  1114  
  1115  		if addr.String() != test {
  1116  			t.Errorf("String() round-trip = %q; want %q", addr, test)
  1117  			continue
  1118  		}
  1119  
  1120  	}
  1121  
  1122  	// Should fail
  1123  	badTests := []string{
  1124  		`<Abc.example.com>`,
  1125  		`<A@b@c@example.com>`,
  1126  		`<a"b(c)d,e:f;g<h>i[j\k]l@example.com>`,
  1127  		`<just"not"right@example.com>`,
  1128  		`<this is"not\allowed@example.com>`,
  1129  		`<this\ still\"not\\allowed@example.com>`,
  1130  		`<john..doe@example.com>`,
  1131  		`<john.doe@example..com>`,
  1132  		`<john.doe@example..com>`,
  1133  		`<john.doe.@example.com>`,
  1134  		`<john.doe.@.example.com>`,
  1135  		`<.john.doe@example.com>`,
  1136  		`<@example.com>`,
  1137  		`<.@example.com>`,
  1138  		`<test@.>`,
  1139  		`< @example.com>`,
  1140  		`<""test""blah""@example.com>`,
  1141  		`<""@0>`,
  1142  	}
  1143  
  1144  	for _, test := range badTests {
  1145  		_, err := ParseAddress(test)
  1146  		if err == nil {
  1147  			t.Errorf("Should have failed to parse address: %s", test)
  1148  			continue
  1149  		}
  1150  
  1151  	}
  1152  
  1153  }
  1154  
  1155  func TestAddressFormattingAndParsing(t *testing.T) {
  1156  	tests := []*Address{
  1157  		{Name: "@lïce", Address: "alice@example.com"},
  1158  		{Name: "Böb O'Connor", Address: "bob@example.com"},
  1159  		{Name: "???", Address: "bob@example.com"},
  1160  		{Name: "Böb ???", Address: "bob@example.com"},
  1161  		{Name: "Böb (Jacöb)", Address: "bob@example.com"},
  1162  		{Name: "à#$%&'(),.:;<>@[]^`{|}~'", Address: "bob@example.com"},
  1163  		// https://golang.org/issue/11292
  1164  		{Name: "\"\\\x1f,\"", Address: "0@0"},
  1165  		// https://golang.org/issue/12782
  1166  		{Name: "naé, mée", Address: "test.mail@gmail.com"},
  1167  	}
  1168  
  1169  	for i, test := range tests {
  1170  		parsed, err := ParseAddress(test.String())
  1171  		if err != nil {
  1172  			t.Errorf("test #%d: ParseAddr(%q) error: %v", i, test.String(), err)
  1173  			continue
  1174  		}
  1175  		if parsed.Name != test.Name {
  1176  			t.Errorf("test #%d: Parsed name = %q; want %q", i, parsed.Name, test.Name)
  1177  		}
  1178  		if parsed.Address != test.Address {
  1179  			t.Errorf("test #%d: Parsed address = %q; want %q", i, parsed.Address, test.Address)
  1180  		}
  1181  	}
  1182  }
  1183  
  1184  func TestEmptyAddress(t *testing.T) {
  1185  	parsed, err := ParseAddress("")
  1186  	if parsed != nil || err == nil {
  1187  		t.Errorf(`ParseAddress("") = %v, %v, want nil, error`, parsed, err)
  1188  	}
  1189  	list, err := ParseAddressList("")
  1190  	if len(list) > 0 || err == nil {
  1191  		t.Errorf(`ParseAddressList("") = %v, %v, want nil, error`, list, err)
  1192  	}
  1193  	list, err = ParseAddressList(",")
  1194  	if len(list) > 0 || err == nil {
  1195  		t.Errorf(`ParseAddressList("") = %v, %v, want nil, error`, list, err)
  1196  	}
  1197  	list, err = ParseAddressList("a@b c@d")
  1198  	if len(list) > 0 || err == nil {
  1199  		t.Errorf(`ParseAddressList("") = %v, %v, want nil, error`, list, err)
  1200  	}
  1201  }
  1202  

View as plain text