github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/net/mail/message.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 /* 6 Package mail implements parsing of mail messages. 7 8 For the most part, this package follows the syntax as specified by RFC 5322 and 9 extended by RFC 6532. 10 Notable divergences: 11 * Obsolete address formats are not parsed, including addresses with 12 embedded route information. 13 * The full range of spacing (the CFWS syntax element) is not supported, 14 such as breaking addresses across lines. 15 * No unicode normalization is performed. 16 * Address with some RFC 5322 3.2.3 specials without quotes are parsed. 17 */ 18 package mail 19 20 import ( 21 "bufio" 22 "bytes" 23 "errors" 24 "fmt" 25 "io" 26 "log" 27 "mime" 28 "net/textproto" 29 "strings" 30 "time" 31 "unicode/utf8" 32 ) 33 34 var debug = debugT(false) 35 36 type debugT bool 37 38 func (d debugT) Printf(format string, args ...interface{}) { 39 if d { 40 log.Printf(format, args...) 41 } 42 } 43 44 // A Message represents a parsed mail message. 45 type Message struct { 46 Header Header 47 Body io.Reader 48 } 49 50 // ReadMessage reads a message from r. 51 // The headers are parsed, and the body of the message will be available 52 // for reading from msg.Body. 53 func ReadMessage(r io.Reader) (msg *Message, err error) { 54 tp := textproto.NewReader(bufio.NewReader(r)) 55 56 hdr, err := tp.ReadMIMEHeader() 57 if err != nil { 58 return nil, err 59 } 60 61 return &Message{ 62 Header: Header(hdr), 63 Body: tp.R, 64 }, nil 65 } 66 67 // Layouts suitable for passing to time.Parse. 68 // These are tried in order. 69 var dateLayouts []string 70 71 func init() { 72 // Generate layouts based on RFC 5322, section 3.3. 73 74 dows := [...]string{"", "Mon, "} // day-of-week 75 days := [...]string{"2", "02"} // day = 1*2DIGIT 76 years := [...]string{"2006", "06"} // year = 4*DIGIT / 2*DIGIT 77 seconds := [...]string{":05", ""} // second 78 // "-0700 (MST)" is not in RFC 5322, but is common. 79 zones := [...]string{"-0700", "MST", "-0700 (MST)"} // zone = (("+" / "-") 4DIGIT) / "GMT" / ... 80 81 for _, dow := range dows { 82 for _, day := range days { 83 for _, year := range years { 84 for _, second := range seconds { 85 for _, zone := range zones { 86 s := dow + day + " Jan " + year + " 15:04" + second + " " + zone 87 dateLayouts = append(dateLayouts, s) 88 } 89 } 90 } 91 } 92 } 93 } 94 95 // ParseDate parses an RFC 5322 date string. 96 func ParseDate(date string) (time.Time, error) { 97 for _, layout := range dateLayouts { 98 t, err := time.Parse(layout, date) 99 if err == nil { 100 return t, nil 101 } 102 } 103 return time.Time{}, errors.New("mail: header could not be parsed") 104 } 105 106 // A Header represents the key-value pairs in a mail message header. 107 type Header map[string][]string 108 109 // Get gets the first value associated with the given key. 110 // It is case insensitive; CanonicalMIMEHeaderKey is used 111 // to canonicalize the provided key. 112 // If there are no values associated with the key, Get returns "". 113 // To access multiple values of a key, or to use non-canonical keys, 114 // access the map directly. 115 func (h Header) Get(key string) string { 116 return textproto.MIMEHeader(h).Get(key) 117 } 118 119 var ErrHeaderNotPresent = errors.New("mail: header not in message") 120 121 // Date parses the Date header field. 122 func (h Header) Date() (time.Time, error) { 123 hdr := h.Get("Date") 124 if hdr == "" { 125 return time.Time{}, ErrHeaderNotPresent 126 } 127 return ParseDate(hdr) 128 } 129 130 // AddressList parses the named header field as a list of addresses. 131 func (h Header) AddressList(key string) ([]*Address, error) { 132 hdr := h.Get(key) 133 if hdr == "" { 134 return nil, ErrHeaderNotPresent 135 } 136 return ParseAddressList(hdr) 137 } 138 139 // Address represents a single mail address. 140 // An address such as "Barry Gibbs <bg@example.com>" is represented 141 // as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. 142 type Address struct { 143 Name string // Proper name; may be empty. 144 Address string // user@domain 145 } 146 147 // Parses a single RFC 5322 address, e.g. "Barry Gibbs <bg@example.com>" 148 func ParseAddress(address string) (*Address, error) { 149 return (&addrParser{s: address}).parseSingleAddress() 150 } 151 152 // ParseAddressList parses the given string as a list of addresses. 153 func ParseAddressList(list string) ([]*Address, error) { 154 return (&addrParser{s: list}).parseAddressList() 155 } 156 157 // An AddressParser is an RFC 5322 address parser. 158 type AddressParser struct { 159 // WordDecoder optionally specifies a decoder for RFC 2047 encoded-words. 160 WordDecoder *mime.WordDecoder 161 } 162 163 // Parse parses a single RFC 5322 address of the 164 // form "Gogh Fir <gf@example.com>" or "foo@example.com". 165 func (p *AddressParser) Parse(address string) (*Address, error) { 166 return (&addrParser{s: address, dec: p.WordDecoder}).parseSingleAddress() 167 } 168 169 // ParseList parses the given string as a list of comma-separated addresses 170 // of the form "Gogh Fir <gf@example.com>" or "foo@example.com". 171 func (p *AddressParser) ParseList(list string) ([]*Address, error) { 172 return (&addrParser{s: list, dec: p.WordDecoder}).parseAddressList() 173 } 174 175 // String formats the address as a valid RFC 5322 address. 176 // If the address's name contains non-ASCII characters 177 // the name will be rendered according to RFC 2047. 178 func (a *Address) String() string { 179 // Format address local@domain 180 at := strings.LastIndex(a.Address, "@") 181 var local, domain string 182 if at < 0 { 183 // This is a malformed address ("@" is required in addr-spec); 184 // treat the whole address as local-part. 185 local = a.Address 186 } else { 187 local, domain = a.Address[:at], a.Address[at+1:] 188 } 189 190 // Add quotes if needed 191 quoteLocal := false 192 for i, r := range local { 193 if isAtext(r, false, false) { 194 continue 195 } 196 if r == '.' { 197 // Dots are okay if they are surrounded by atext. 198 // We only need to check that the previous byte is 199 // not a dot, and this isn't the end of the string. 200 if i > 0 && local[i-1] != '.' && i < len(local)-1 { 201 continue 202 } 203 } 204 quoteLocal = true 205 break 206 } 207 if quoteLocal { 208 local = quoteString(local) 209 210 } 211 212 s := "<" + local + "@" + domain + ">" 213 214 if a.Name == "" { 215 return s 216 } 217 218 // If every character is printable ASCII, quoting is simple. 219 allPrintable := true 220 for _, r := range a.Name { 221 // isWSP here should actually be isFWS, 222 // but we don't support folding yet. 223 if !isVchar(r) && !isWSP(r) || isMultibyte(r) { 224 allPrintable = false 225 break 226 } 227 } 228 if allPrintable { 229 return quoteString(a.Name) + " " + s 230 } 231 232 // Text in an encoded-word in a display-name must not contain certain 233 // characters like quotes or parentheses (see RFC 2047 section 5.3). 234 // When this is the case encode the name using base64 encoding. 235 if strings.ContainsAny(a.Name, "\"#$%&'(),.:;<>@[]^`{|}~") { 236 return mime.BEncoding.Encode("utf-8", a.Name) + " " + s 237 } 238 return mime.QEncoding.Encode("utf-8", a.Name) + " " + s 239 } 240 241 type addrParser struct { 242 s string 243 dec *mime.WordDecoder // may be nil 244 } 245 246 func (p *addrParser) parseAddressList() ([]*Address, error) { 247 var list []*Address 248 for { 249 p.skipSpace() 250 addrs, err := p.parseAddress(true) 251 if err != nil { 252 return nil, err 253 } 254 list = append(list, addrs...) 255 256 if !p.skipCfws() { 257 return nil, errors.New("mail: misformatted parenthetical comment") 258 } 259 if p.empty() { 260 break 261 } 262 if !p.consume(',') { 263 return nil, errors.New("mail: expected comma") 264 } 265 } 266 return list, nil 267 } 268 269 func (p *addrParser) parseSingleAddress() (*Address, error) { 270 addrs, err := p.parseAddress(true) 271 if err != nil { 272 return nil, err 273 } 274 if !p.skipCfws() { 275 return nil, errors.New("mail: misformatted parenthetical comment") 276 } 277 if !p.empty() { 278 return nil, fmt.Errorf("mail: expected single address, got %q", p.s) 279 } 280 if len(addrs) == 0 { 281 return nil, errors.New("mail: empty group") 282 } 283 if len(addrs) > 1 { 284 return nil, errors.New("mail: group with multiple addresses") 285 } 286 return addrs[0], nil 287 } 288 289 // parseAddress parses a single RFC 5322 address at the start of p. 290 func (p *addrParser) parseAddress(handleGroup bool) ([]*Address, error) { 291 debug.Printf("parseAddress: %q", p.s) 292 p.skipSpace() 293 if p.empty() { 294 return nil, errors.New("mail: no address") 295 } 296 297 // address = mailbox / group 298 // mailbox = name-addr / addr-spec 299 // group = display-name ":" [group-list] ";" [CFWS] 300 301 // addr-spec has a more restricted grammar than name-addr, 302 // so try parsing it first, and fallback to name-addr. 303 // TODO(dsymonds): Is this really correct? 304 spec, err := p.consumeAddrSpec() 305 if err == nil { 306 return []*Address{{ 307 Address: spec, 308 }}, err 309 } 310 debug.Printf("parseAddress: not an addr-spec: %v", err) 311 debug.Printf("parseAddress: state is now %q", p.s) 312 313 // display-name 314 var displayName string 315 if p.peek() != '<' { 316 displayName, err = p.consumePhrase() 317 if err != nil { 318 return nil, err 319 } 320 } 321 debug.Printf("parseAddress: displayName=%q", displayName) 322 323 p.skipSpace() 324 if handleGroup { 325 if p.consume(':') { 326 return p.consumeGroupList() 327 } 328 } 329 // angle-addr = "<" addr-spec ">" 330 if !p.consume('<') { 331 return nil, errors.New("mail: no angle-addr") 332 } 333 spec, err = p.consumeAddrSpec() 334 if err != nil { 335 return nil, err 336 } 337 if !p.consume('>') { 338 return nil, errors.New("mail: unclosed angle-addr") 339 } 340 debug.Printf("parseAddress: spec=%q", spec) 341 342 return []*Address{{ 343 Name: displayName, 344 Address: spec, 345 }}, nil 346 } 347 348 func (p *addrParser) consumeGroupList() ([]*Address, error) { 349 var group []*Address 350 // handle empty group. 351 p.skipSpace() 352 if p.consume(';') { 353 p.skipCfws() 354 return group, nil 355 } 356 357 for { 358 p.skipSpace() 359 // embedded groups not allowed. 360 addrs, err := p.parseAddress(false) 361 if err != nil { 362 return nil, err 363 } 364 group = append(group, addrs...) 365 366 if !p.skipCfws() { 367 return nil, errors.New("mail: misformatted parenthetical comment") 368 } 369 if p.consume(';') { 370 p.skipCfws() 371 break 372 } 373 if !p.consume(',') { 374 return nil, errors.New("mail: expected comma") 375 } 376 } 377 return group, nil 378 } 379 380 // consumeAddrSpec parses a single RFC 5322 addr-spec at the start of p. 381 func (p *addrParser) consumeAddrSpec() (spec string, err error) { 382 debug.Printf("consumeAddrSpec: %q", p.s) 383 384 orig := *p 385 defer func() { 386 if err != nil { 387 *p = orig 388 } 389 }() 390 391 // local-part = dot-atom / quoted-string 392 var localPart string 393 p.skipSpace() 394 if p.empty() { 395 return "", errors.New("mail: no addr-spec") 396 } 397 if p.peek() == '"' { 398 // quoted-string 399 debug.Printf("consumeAddrSpec: parsing quoted-string") 400 localPart, err = p.consumeQuotedString() 401 if localPart == "" { 402 err = errors.New("mail: empty quoted string in addr-spec") 403 } 404 } else { 405 // dot-atom 406 debug.Printf("consumeAddrSpec: parsing dot-atom") 407 localPart, err = p.consumeAtom(true, false) 408 } 409 if err != nil { 410 debug.Printf("consumeAddrSpec: failed: %v", err) 411 return "", err 412 } 413 414 if !p.consume('@') { 415 return "", errors.New("mail: missing @ in addr-spec") 416 } 417 418 // domain = dot-atom / domain-literal 419 var domain string 420 p.skipSpace() 421 if p.empty() { 422 return "", errors.New("mail: no domain in addr-spec") 423 } 424 // TODO(dsymonds): Handle domain-literal 425 domain, err = p.consumeAtom(true, false) 426 if err != nil { 427 return "", err 428 } 429 430 return localPart + "@" + domain, nil 431 } 432 433 // consumePhrase parses the RFC 5322 phrase at the start of p. 434 func (p *addrParser) consumePhrase() (phrase string, err error) { 435 debug.Printf("consumePhrase: [%s]", p.s) 436 // phrase = 1*word 437 var words []string 438 var isPrevEncoded bool 439 for { 440 // word = atom / quoted-string 441 var word string 442 p.skipSpace() 443 if p.empty() { 444 break 445 } 446 isEncoded := false 447 if p.peek() == '"' { 448 // quoted-string 449 word, err = p.consumeQuotedString() 450 } else { 451 // atom 452 // We actually parse dot-atom here to be more permissive 453 // than what RFC 5322 specifies. 454 word, err = p.consumeAtom(true, true) 455 if err == nil { 456 word, isEncoded, err = p.decodeRFC2047Word(word) 457 } 458 } 459 460 if err != nil { 461 break 462 } 463 debug.Printf("consumePhrase: consumed %q", word) 464 if isPrevEncoded && isEncoded { 465 words[len(words)-1] += word 466 } else { 467 words = append(words, word) 468 } 469 isPrevEncoded = isEncoded 470 } 471 // Ignore any error if we got at least one word. 472 if err != nil && len(words) == 0 { 473 debug.Printf("consumePhrase: hit err: %v", err) 474 return "", fmt.Errorf("mail: missing word in phrase: %v", err) 475 } 476 phrase = strings.Join(words, " ") 477 return phrase, nil 478 } 479 480 // consumeQuotedString parses the quoted string at the start of p. 481 func (p *addrParser) consumeQuotedString() (qs string, err error) { 482 // Assume first byte is '"'. 483 i := 1 484 qsb := make([]rune, 0, 10) 485 486 escaped := false 487 488 Loop: 489 for { 490 r, size := utf8.DecodeRuneInString(p.s[i:]) 491 492 switch { 493 case size == 0: 494 return "", errors.New("mail: unclosed quoted-string") 495 496 case size == 1 && r == utf8.RuneError: 497 return "", fmt.Errorf("mail: invalid utf-8 in quoted-string: %q", p.s) 498 499 case escaped: 500 // quoted-pair = ("\" (VCHAR / WSP)) 501 502 if !isVchar(r) && !isWSP(r) { 503 return "", fmt.Errorf("mail: bad character in quoted-string: %q", r) 504 } 505 506 qsb = append(qsb, r) 507 escaped = false 508 509 case isQtext(r) || isWSP(r): 510 // qtext (printable US-ASCII excluding " and \), or 511 // FWS (almost; we're ignoring CRLF) 512 qsb = append(qsb, r) 513 514 case r == '"': 515 break Loop 516 517 case r == '\\': 518 escaped = true 519 520 default: 521 return "", fmt.Errorf("mail: bad character in quoted-string: %q", r) 522 523 } 524 525 i += size 526 } 527 p.s = p.s[i+1:] 528 return string(qsb), nil 529 } 530 531 // consumeAtom parses an RFC 5322 atom at the start of p. 532 // If dot is true, consumeAtom parses an RFC 5322 dot-atom instead. 533 // If permissive is true, consumeAtom will not fail on: 534 // - leading/trailing/double dots in the atom (see golang.org/issue/4938) 535 // - special characters (RFC 5322 3.2.3) except '<', '>', ':' and '"' (see golang.org/issue/21018) 536 func (p *addrParser) consumeAtom(dot bool, permissive bool) (atom string, err error) { 537 i := 0 538 539 Loop: 540 for { 541 r, size := utf8.DecodeRuneInString(p.s[i:]) 542 switch { 543 case size == 1 && r == utf8.RuneError: 544 return "", fmt.Errorf("mail: invalid utf-8 in address: %q", p.s) 545 546 case size == 0 || !isAtext(r, dot, permissive): 547 break Loop 548 549 default: 550 i += size 551 552 } 553 } 554 555 if i == 0 { 556 return "", errors.New("mail: invalid string") 557 } 558 atom, p.s = p.s[:i], p.s[i:] 559 if !permissive { 560 if strings.HasPrefix(atom, ".") { 561 return "", errors.New("mail: leading dot in atom") 562 } 563 if strings.Contains(atom, "..") { 564 return "", errors.New("mail: double dot in atom") 565 } 566 if strings.HasSuffix(atom, ".") { 567 return "", errors.New("mail: trailing dot in atom") 568 } 569 } 570 return atom, nil 571 } 572 573 func (p *addrParser) consume(c byte) bool { 574 if p.empty() || p.peek() != c { 575 return false 576 } 577 p.s = p.s[1:] 578 return true 579 } 580 581 // skipSpace skips the leading space and tab characters. 582 func (p *addrParser) skipSpace() { 583 p.s = strings.TrimLeft(p.s, " \t") 584 } 585 586 func (p *addrParser) peek() byte { 587 return p.s[0] 588 } 589 590 func (p *addrParser) empty() bool { 591 return p.len() == 0 592 } 593 594 func (p *addrParser) len() int { 595 return len(p.s) 596 } 597 598 // skipCfws skips CFWS as defined in RFC5322. 599 func (p *addrParser) skipCfws() bool { 600 p.skipSpace() 601 602 for { 603 if !p.consume('(') { 604 break 605 } 606 607 if !p.skipComment() { 608 return false 609 } 610 611 p.skipSpace() 612 } 613 614 return true 615 } 616 617 func (p *addrParser) skipComment() bool { 618 // '(' already consumed. 619 depth := 1 620 621 for { 622 if p.empty() || depth == 0 { 623 break 624 } 625 626 if p.peek() == '\\' && p.len() > 1 { 627 p.s = p.s[1:] 628 } else if p.peek() == '(' { 629 depth++ 630 } else if p.peek() == ')' { 631 depth-- 632 } 633 p.s = p.s[1:] 634 } 635 636 return depth == 0 637 } 638 639 func (p *addrParser) decodeRFC2047Word(s string) (word string, isEncoded bool, err error) { 640 if p.dec != nil { 641 word, err = p.dec.Decode(s) 642 } else { 643 word, err = rfc2047Decoder.Decode(s) 644 } 645 646 if err == nil { 647 return word, true, nil 648 } 649 650 if _, ok := err.(charsetError); ok { 651 return s, true, err 652 } 653 654 // Ignore invalid RFC 2047 encoded-word errors. 655 return s, false, nil 656 } 657 658 var rfc2047Decoder = mime.WordDecoder{ 659 CharsetReader: func(charset string, input io.Reader) (io.Reader, error) { 660 return nil, charsetError(charset) 661 }, 662 } 663 664 type charsetError string 665 666 func (e charsetError) Error() string { 667 return fmt.Sprintf("charset not supported: %q", string(e)) 668 } 669 670 // isAtext reports whether r is an RFC 5322 atext character. 671 // If dot is true, period is included. 672 // If permissive is true, RFC 5322 3.2.3 specials is included, 673 // except '<', '>', ':' and '"'. 674 func isAtext(r rune, dot, permissive bool) bool { 675 switch r { 676 case '.': 677 return dot 678 679 // RFC 5322 3.2.3. specials 680 case '(', ')', '[', ']', ';', '@', '\\', ',': 681 return permissive 682 683 case '<', '>', '"', ':': 684 return false 685 } 686 return isVchar(r) 687 } 688 689 // isQtext reports whether r is an RFC 5322 qtext character. 690 func isQtext(r rune) bool { 691 // Printable US-ASCII, excluding backslash or quote. 692 if r == '\\' || r == '"' { 693 return false 694 } 695 return isVchar(r) 696 } 697 698 // quoteString renders a string as an RFC 5322 quoted-string. 699 func quoteString(s string) string { 700 var buf bytes.Buffer 701 buf.WriteByte('"') 702 for _, r := range s { 703 if isQtext(r) || isWSP(r) { 704 buf.WriteRune(r) 705 } else if isVchar(r) { 706 buf.WriteByte('\\') 707 buf.WriteRune(r) 708 } 709 } 710 buf.WriteByte('"') 711 return buf.String() 712 } 713 714 // isVchar reports whether r is an RFC 5322 VCHAR character. 715 func isVchar(r rune) bool { 716 // Visible (printing) characters. 717 return '!' <= r && r <= '~' || isMultibyte(r) 718 } 719 720 // isMultibyte reports whether r is a multi-byte UTF-8 character 721 // as supported by RFC 6532 722 func isMultibyte(r rune) bool { 723 return r >= utf8.RuneSelf 724 } 725 726 // isWSP reports whether r is a WSP (white space). 727 // WSP is a space or horizontal tab (RFC 5234 Appendix B). 728 func isWSP(r rune) bool { 729 return r == ' ' || r == '\t' 730 }