-
Notifications
You must be signed in to change notification settings - Fork 5
/
fields.go
1359 lines (1242 loc) · 33.5 KB
/
fields.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package mail
import (
"bytes"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/paulrosania/go-charset/charset"
)
const (
FromFieldName = "From"
ResentFromFieldName = "Resent-From"
SenderFieldName = "Sender"
ResentSenderFieldName = "Resent-Sender"
ReturnPathFieldName = "Return-Path"
ReplyToFieldName = "Reply-To"
ToFieldName = "To"
CcFieldName = "Cc"
BccFieldName = "Bcc"
ResentToFieldName = "Resent-To"
ResentCcFieldName = "Resent-Cc"
ResentBccFieldName = "Resent-Bcc"
MessageIDFieldName = "Message-ID"
ResentMessageIDFieldName = "Resent-Message-ID"
InReplyToFieldName = "In-Reply-To"
ReferencesFieldName = "References"
DateFieldName = "Date"
OrigDateFieldName = "Orig-Date"
ResentDateFieldName = "Resent-Date"
SubjectFieldName = "Subject"
CommentsFieldName = "Comments"
KeywordsFieldName = "Keywords"
ContentTypeFieldName = "Content-Type"
ContentTransferEncodingFieldName = "Content-Transfer-Encoding"
ContentDispositionFieldName = "Content-Disposition"
ContentDescriptionFieldName = "Content-Description"
ContentIDFieldName = "Content-ID"
MIMEVersionFieldName = "MIME-Version"
ReceivedFieldName = "Received"
ContentLanguageFieldName = "Content-Language"
ContentLocationFieldName = "Content-Location"
ContentMd5FieldName = "Content-Md5"
ListIdFieldName = "List-Id"
ContentBaseFieldName = "Content-Base"
ErrorsToFieldName = "Errors-To"
)
var addressFieldNames = []string{
FromFieldName,
ResentFromFieldName,
SenderFieldName,
ResentSenderFieldName,
ReturnPathFieldName,
ReplyToFieldName,
ToFieldName,
CcFieldName,
BccFieldName,
ResentToFieldName,
ResentCcFieldName,
ResentBccFieldName,
}
var fieldNames = []string{
FromFieldName,
ResentFromFieldName,
SenderFieldName,
ResentSenderFieldName,
ReturnPathFieldName,
ReplyToFieldName,
ToFieldName,
CcFieldName,
BccFieldName,
ResentToFieldName,
ResentCcFieldName,
ResentBccFieldName,
MessageIDFieldName,
ResentMessageIDFieldName,
InReplyToFieldName,
ReferencesFieldName,
DateFieldName,
OrigDateFieldName,
ResentDateFieldName,
SubjectFieldName,
CommentsFieldName,
KeywordsFieldName,
ContentTypeFieldName,
ContentTransferEncodingFieldName,
ContentDispositionFieldName,
ContentDescriptionFieldName,
ContentIDFieldName,
MIMEVersionFieldName,
ReceivedFieldName,
ContentLanguageFieldName,
ContentLocationFieldName,
ContentMd5FieldName,
ListIdFieldName,
ContentBaseFieldName,
ErrorsToFieldName,
}
var isKnownField map[string]bool
func init() {
isKnownField = make(map[string]bool)
for _, n := range fieldNames {
isKnownField[n] = true
}
}
type Field interface {
Name() string
Value() string
Error() error
Parse(value string)
Valid() bool
UnparsedValue() string
SetUnparsedValue(value string)
rfc822(avoidUTF8 bool) string
}
type HeaderField struct {
name, value string
unparsedValue string
err error
}
func (f *HeaderField) Name() string {
return f.name
}
func (f *HeaderField) Value() string {
return f.value
}
func (f *HeaderField) Error() error {
return f.err
}
// Every HeaderField subclass must define a parse() function that takes a
// string \a s from a message and sets the field value(). This default function
// handles fields that are not specially handled by subclasses using functions
// like parseText().
func (f *HeaderField) Parse(s string) {
switch f.name {
case FromFieldName, ResentFromFieldName, SenderFieldName, ReturnPathFieldName,
ResentSenderFieldName, ToFieldName, CcFieldName, BccFieldName, ReplyToFieldName,
ResentToFieldName, ResentCcFieldName, ResentBccFieldName, MessageIDFieldName,
ContentIDFieldName, ResentMessageIDFieldName, ReferencesFieldName, DateFieldName,
OrigDateFieldName, ResentDateFieldName, ContentTypeFieldName,
ContentTransferEncodingFieldName, ContentDispositionFieldName,
ContentLanguageFieldName:
// These should be handled by their own parse()
case ContentDescriptionFieldName, SubjectFieldName, CommentsFieldName:
f.parseText(s)
case MIMEVersionFieldName:
f.parseMIMEVersion(s)
case ContentLocationFieldName:
f.parseContentLocation(s)
case InReplyToFieldName, KeywordsFieldName, ReceivedFieldName, ContentMd5FieldName:
f.parseOther(s)
case ContentBaseFieldName:
f.parseContentBase(s)
case ErrorsToFieldName:
f.parseErrorsTo(s)
default:
f.parseOther(s)
}
}
// Parses the *text production from \a s, as modified to include encoded-words
// by RFC 2047. This is used to parse the Subject and Comments fields.
func (f *HeaderField) parseText(s string) {
h := false
if !h {
p := newParser(s)
t := p.Text()
if p.AtEnd() {
f.value = trim(t)
h = true
}
}
if !h {
p := newParser(simplify(s))
t := p.Text()
if p.AtEnd() {
f.value = t
h = true
}
}
if (!h && strings.Contains(s, "=?") && strings.Contains(s, "?=")) ||
(strings.Contains(f.value, "=?") && strings.Contains(f.value, "?=")) {
// common: Subject: =?ISO-8859-1?q?foo bar baz?=
// unusual, but seen: Subject: =?ISO-8859-1?q?foo bar?= baz
p1 := newParser(simplify(s))
var tmp bytes.Buffer
inWord := false
for !p1.AtEnd() {
if p1.Present("=?") {
inWord = true
tmp.WriteString(" =?")
} else if p1.Present("?=") {
inWord = false
tmp.WriteString("?= ")
} else if p1.Whitespace() == "" {
tmp.WriteByte(p1.NextChar())
p1.Step(1)
} else {
if inWord {
tmp.WriteByte('_')
} else {
tmp.WriteByte(' ')
}
}
}
p2 := newParser(tmp.String())
t := simplify(p2.Text())
if p2.AtEnd() && !strings.Contains(t, "?=") {
f.value = t
h = true
}
}
if !h {
f.err = errors.New("Error parsing text")
}
}
// Parses the MIME-Version field from \a s and resolutely ignores all problems
// seen.
//
// Only version 1.0 is legal. Since vast numbers of spammers send other version
// numbers, we replace other version numbers with 1.0 and a comment. Bayesian
// analysis tools will probably find the comment to be a sure spam sign.
func (f *HeaderField) parseMIMEVersion(s string) {
p := newParser(s)
p.Comment()
v := p.DotAtom()
p.Comment()
c, err := decode(simplify(p.lc), "us-ascii")
if err != nil || strings.ContainsAny(c, "()\\") {
c = ""
}
if v != "1.0" || !p.AtEnd() {
c = "Note: Original mime-version had syntax problems"
}
result := "1.0"
if c != "" {
result += " (" + c + ")"
}
f.value = result
}
// Parses the Content-Location header field in \a s and records the first
// problem found.
func (f *HeaderField) parseContentLocation(s string) {
p := newParser(unquote(trim(s), '"', '\''))
p.Whitespace()
e := p.Pos()
ok := true
var buf bytes.Buffer
for ok {
ok = true
c := p.NextChar()
p.Step(1)
if c == '%' {
hex := make([]byte, 2)
hex[0] = p.NextChar()
p.Step(1)
hex[1] = p.NextChar()
p.Step(1)
i, err := strconv.ParseUint(string(hex), 16, 8)
if err != nil {
ok = false
}
c = byte(i)
}
if (c >= 'a' && c <= 'z') || // alpha
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || // letter
c == '$' || c == '-' || // safe
c == '_' || c == '.' ||
c == '+' ||
c == '!' || c == '*' || // extra
c == '\'' || c == '(' ||
c == ')' || c == ',' {
// RFC 1738 unreserved
buf.WriteByte(c)
} else if c == ';' || c == '/' || c == '?' ||
c == ':' || c == '@' || c == '&' ||
c == '=' {
// RFC 1738 reserved
buf.WriteByte(c)
} else if c == '%' || c >= 127 {
// RFC 1738 escape
hex := strconv.FormatInt(int64(c), 16)
buf.WriteByte('%')
if len(hex) < 2 {
buf.WriteByte('0')
}
buf.WriteString(hex)
} else if c == ' ' {
// seen in real life, sent by buggy programs
buf.WriteString("%20")
} else if c == '\r' || c == '\n' {
// and another kind of bug, except that in this case, is there a
// right kind of way? let's not flame programs which do this.
p.Whitespace()
} else {
ok = false
}
if ok {
e = p.Pos()
}
}
p.Whitespace()
v, err := decode(buf.String(), "us-ascii")
f.value = v
if !p.AtEnd() {
f.err = fmt.Errorf("Junk at position %d: %s", e, s[e:])
} else if err != nil {
f.err = err
}
}
// Tries to parses any (otherwise uncovered and presumably unstructured) field
// in \a s, and records an error if it contains NULs or 8-bit characters.
func (f *HeaderField) parseOther(s string) {
v, err := decode(s, "us-ascii")
if err != nil {
f.err = err
}
f.value = v
}
// Parses the Content-Base header field in \a s and records the first problem
// found. Somewhat overflexibly assumes that if there is a colon, the URL is
// absolute, so it accepts -:/asr as a valid URL.
func (f *HeaderField) parseContentBase(s string) {
f.parseContentLocation(s)
if !f.Valid() {
return
}
if !strings.Contains(f.value, ":") {
f.err = errors.New("URL has no scheme")
}
}
// Parses Errors-To field \a s. Stores localpart@domain if it looks like a
// single address (and reasonably error-free) and an empty value if there's any
// doubt what to store.
func (f *HeaderField) parseErrorsTo(s string) {
ap := NewAddressParser(s)
if ap.firstError != nil || len(ap.Addresses) != 1 {
return
}
a := ap.Addresses[0]
if a.t != NormalAddressType {
return
}
v, err := decode(a.lpdomain(), "us-ascii")
f.value = v
f.err = err
}
// Returns true if this header field is valid (or unparsed, as is the case for
// all unknown fields), and false if an error was detected during parsing.
func (f *HeaderField) Valid() bool {
return f.err == nil
}
func (f *HeaderField) UnparsedValue() string {
return f.unparsedValue
}
func (f *HeaderField) SetUnparsedValue(value string) {
f.unparsedValue = value
}
type AddressField struct {
HeaderField
Addresses Addresses
}
func NewAddressField(name string) *AddressField {
hf := HeaderField{name: name}
return &AddressField{HeaderField: hf}
}
// Generates the RFC 822 representation of the field, based on the addresses().
// If \a avoidUTf8 is true, rfc822() will be lossy rather than include any
// UTF-8.
func (f *AddressField) rfc822(avoidUTF8 bool) string {
s := ""
name := f.Name()
if name == ReturnPathFieldName {
if len(f.Addresses) == 0 {
} else if f.Addresses[0].t == BounceAddressType {
s = "<>"
} else if f.Addresses[0].t == NormalAddressType {
s = "<" + f.Addresses[0].lpdomain() + ">"
}
} else if name == MessageIDFieldName ||
name == ResentMessageIDFieldName ||
name == ContentIDFieldName ||
name == ReferencesFieldName && len(f.Addresses) == 0 {
if len(f.Addresses) > 0 {
s = "<" + f.Addresses[0].toString(false) + ">"
} else {
s = f.Name() + ": " + ascii(f.Value())
s = wrap(simplify(s), 78, "", " ", false)
p := len(f.Name()) + 1
for p < len(s) &&
(s[p] == ' ' || s[p] == '\r' || s[p] == '\n') {
p++
}
s = s[p:]
}
} else if name == FromFieldName ||
name == ResentFromFieldName ||
name == SenderFieldName ||
name == ResentSenderFieldName ||
name == ReturnPathFieldName ||
name == ReplyToFieldName ||
name == ToFieldName || name == CcFieldName || name == BccFieldName ||
name == ResentToFieldName || name == ResentCcFieldName || name == ResentBccFieldName ||
name == ReferencesFieldName {
first := true
wsep := ""
lsep := ""
c := len(f.Name()) + 2
lpos := 0
if f.Name() == ReferencesFieldName {
wsep = " "
lsep = "\r\n "
lpos = 1
} else {
wsep = ", "
lsep = ",\r\n "
lpos = 4
}
for i, addr := range f.Addresses {
a := addr.toString(avoidUTF8)
if f.Name() == ReferencesFieldName {
a = "<" + a + ">"
}
if first {
first = false
} else if (c+len(wsep)+len(a) > 78) ||
(c+len(wsep)+len(a) == 78 && len(f.Addresses) > i+1) {
s += lsep
c = lpos
} else {
s += wsep
c += len(wsep)
}
s += a
c += len(a)
}
}
return s
}
func (f *AddressField) Value() string {
if len(f.Addresses) == 0 {
return f.HeaderField.Value()
}
// and for message-id, content-id and references:
v, _ := decode(simplify(f.rfc822(true)), "us-ascii")
return v
}
func (f *AddressField) Parse(s string) {
switch f.Name() {
case SenderFieldName:
f.parseMailbox(s)
if !f.Valid() && len(f.Addresses) == 0 {
// sender is quite often wrong in otherwise perfectly
// legible messages. so we'll nix out the error. Header
// will probably remove the field completely, since an
// empty Sender field isn't sensible.
f.err = nil
}
case ReturnPathFieldName:
f.parseMailbox(s)
if !f.Valid() || len(f.Addresses) != 1 ||
(f.Addresses[0].t != BounceAddressType && f.Addresses[0].t != NormalAddressType) {
// return-path sometimes contains strange addresses when
// migrating from older stores. if it does, just kill
// it. this never happens when receiving mail, since we'll
// make a return-path of our own.
f.err = nil
f.Addresses = nil
}
case ResentSenderFieldName:
f.parseMailbox(s)
case FromFieldName, ResentFromFieldName:
f.parseMailboxList(s)
case ToFieldName, CcFieldName, BccFieldName, ReplyToFieldName,
ResentToFieldName, ResentCcFieldName, ResentBccFieldName:
f.parseAddressList(s)
if f.Name() == CcFieldName && !f.Valid() && len(f.Addresses) <= 1 {
// /bin/mail tempts people to type escape, ctrl-d or
// similar into the cc field, so we try to recover from
// that.
i := 0
for i < len(s) && s[i] >= ' ' && s[i] != 127 {
i++
}
if i < len(s) {
f.err = nil
f.Addresses = nil
}
}
if !f.Valid() && len(simplify(s)) == 1 {
f.err = nil
f.Addresses = nil
}
if f.Valid() && strings.Contains(s, "<>") {
// some spammers attempt to send 'To: asdfsaf <>'.
bounces := 0
otherProblems := 0
for _, a := range f.Addresses {
if a.t == BounceAddressType {
bounces++
} else if a.err != nil {
otherProblems++
}
}
if bounces > 0 && otherProblems == 0 {
// there's one or more <>, but nothing else bad.
clean := make([]Address, 0, len(f.Addresses)-bounces)
for _, a := range f.Addresses {
if a.t != BounceAddressType {
clean = append(clean, a)
}
}
f.Addresses = clean
}
if !f.Valid() && len(f.Addresses) == 0 && !strings.Contains(s, "@") {
// some spammers send total garbage. we can't detect all
// instances of garbage, but if it doesn't contain even
// one "@" and also not even one parsable address, surely
// it's garbage.
f.err = nil
}
if !f.Valid() && len(f.Addresses) <= 1 &&
(strings.HasPrefix(s, "@") || strings.Contains(s, "<@")) {
f.Addresses = nil
f.err = nil
}
}
case ContentIDFieldName:
f.parseContentID(s)
case MessageIDFieldName, ResentMessageIDFieldName:
f.parseMessageID(s)
case ReferencesFieldName:
f.parseReferences(s)
default:
// Should not happen.
}
if f.Name() != ReturnPathFieldName {
f.outlawBounce()
}
}
// Parses the RFC 2822 address-list production from \a s and records the first
// problem found.
func (f *AddressField) parseAddressList(s string) {
ap := NewAddressParser(s)
f.err = ap.firstError
f.Addresses = ap.Addresses
}
// Parses the RFC 2822 mailbox-list production from \a s and records the first
// problem found.
func (f *AddressField) parseMailboxList(s string) {
f.parseAddressList(s)
// A mailbox-list is an address-list where groups aren't allowed.
for _, a := range f.Addresses {
if !f.Valid() {
break
}
if a.t == EmptyGroupAddressType {
f.err = fmt.Errorf("Invalid mailbox: %q", a.toString(false))
}
}
}
// Parses the RFC 2822 mailbox production from \a s and records the first
// problem found.
func (f *AddressField) parseMailbox(s string) {
f.parseAddressList(s)
// A mailbox in our world is just a mailbox-list with one entry.
if f.Valid() && len(f.Addresses) > 1 {
f.err = errors.New("Only one address is allowed")
}
}
// Parses the contents of an RFC 2822 references field in \a s. This is
// nominally 1*msg-id, but in practice we need to be a little more flexible.
// Overlooks common problems and records the first serious problems found.
func (f *AddressField) parseReferences(s string) {
ap := references(s)
f.Addresses = ap.Addresses
f.err = ap.firstError
}
// Parses the RFC 2822 msg-id production from \a s and/or records the first
// serious error found.
func (f *AddressField) parseMessageID(s string) {
ap := references(s)
if ap.firstError != nil {
f.err = ap.firstError
} else if len(ap.Addresses) == 1 {
f.Addresses = ap.Addresses
} else {
f.err = errors.New("Need exactly one")
}
}
// Like parseMessageID( \a s ), except that it also accepts <blah>.
func (f *AddressField) parseContentID(s string) {
ap := NewAddressParser(s)
f.err = ap.firstError
if len(ap.Addresses) != 1 {
f.err = errors.New("Need exactly one")
return
}
switch ap.Addresses[0].t {
case NormalAddressType:
f.Addresses = ap.Addresses
case BounceAddressType:
f.err = errors.New("<> is not legal, it has to be <some@thing>")
case EmptyGroupAddressType:
f.err = errors.New("Error parsing Content-Id")
case LocalAddressType:
f.Addresses = ap.Addresses
case InvalidAddressType:
f.err = errors.New("Error parsing Content-Id")
}
}
// Checks whether '<>' is present in this address field, and records an error
// if it is. '<>' is legal in Return-Path, but as of April 2005, not in any
// other field.
func (f *AddressField) outlawBounce() {
for _, a := range f.Addresses {
if a.t == BounceAddressType {
f.err = errors.New("No-bounce address not allowed in this field")
}
}
}
// This static function parses the references field \a r. This is in
// AddressParser because References and Message-ID both use the address
// productions in RFC 822/1034.
//
// This function does it best to skip ahead to the next message-id if there is
// a syntax error in one. It silently ignores the errors. This is because it's
// so common to have a bad message-id in the references field of an otherwise
// impeccable message.
func references(r string) AddressParser {
ap := NewAddressParser("")
ap.s = r
i := len(r) - 1
i = ap.comment(i)
for i > 0 {
l := i
ok := true
dom := ""
lp := ""
if r[i] != '>' {
ok = false
} else {
i--
dom, i = ap.domain(i)
if i >= 0 && r[i] == '@' {
i--
} else {
ok = false
}
lp, i = ap.localpart(i)
if i >= 0 && r[i] == '<' {
i--
} else {
ok = false
}
i = ap.comment(i)
if i >= 0 && ap.s[i] == ',' {
i--
i = ap.comment(i)
}
}
if ok && dom != "" && lp != "" {
ap.add("", lp, dom)
} else {
i = l
i--
for i >= 0 && r[i] != ' ' {
i--
}
i = ap.comment(i)
}
}
ap.firstError = nil
return ap
}
type DateField struct {
HeaderField
Date *time.Time
}
func NewDateField() *DateField {
hf := HeaderField{name: DateFieldName}
return &DateField{HeaderField: hf}
}
// Layouts suitable for passing to time.Parse.
// These are tried in order.
var dateLayouts []string
func init() {
// Generate layouts based on RFC 5322, section 3.3.
dows := [...]string{"", "Mon, "} // day-of-week
days := [...]string{"2", "02"} // day = 1*2DIGIT
years := [...]string{"2006", "06"} // year = 4*DIGIT / 2*DIGIT
seconds := [...]string{":05", ""} // second
// "-0700 (MST)" is not in RFC 5322, but is common.
zones := [...]string{"-0700", "MST", "-0700 (MST)"} // zone = (("+" / "-") 4DIGIT) / "GMT" / ...
for _, dow := range dows {
for _, day := range days {
for _, year := range years {
for _, second := range seconds {
for _, zone := range zones {
s := dow + day + " Jan " + year + " 15:04" + second + " " + zone
dateLayouts = append(dateLayouts, s)
}
}
}
}
}
}
func parseDate(s string) *time.Time {
s = simplify(stripcomments(s))
for _, layout := range dateLayouts {
t, err := time.Parse(layout, s)
if err == nil {
return &t
}
}
return nil
}
// TODO: Evaluate aox implementation, might be more lenient
func (f *DateField) Parse(s string) {
t := parseDate(s)
if t != nil {
f.value = t.Format("Mon, 02 Jan 2006 15:04:05 -0700")
f.Date = t
return
}
f.err = errors.New("mail: header could not be parsed")
}
type MIMEParameter struct {
Name, Value string
Parts []string
}
func NewMIMEParameter(name, value string) MIMEParameter {
return MIMEParameter{
Name: name,
Value: value,
}
}
type MIMEField struct {
HeaderField
baseValue string
Parameters []MIMEParameter
}
// Returns the value of the parameter named \a n (ignoring the case of the
// name). If there is no such parameter, this function returns an empty string.
func (f *MIMEField) parameter(n string) string {
s := strings.ToLower(n)
for _, p := range f.Parameters {
if p.Name == s {
return p.Value
}
}
return ""
}
// Adds a parameter named \a n with value \a v, replacing any previous setting.
func (f *MIMEField) addParameter(n, v string) {
s := strings.ToLower(n)
found := false
for i := 0; i < len(f.Parameters); i++ {
if f.Parameters[i].Name == s {
f.Parameters[i].Value = v
found = true
}
}
if !found {
p := MIMEParameter{Name: n, Value: v}
f.Parameters = append(f.Parameters, p)
}
}
// Removes the parameter named \a n (without regard to case), or does nothing
// if there is no such parameter.
func (f *MIMEField) removeParameter(n string) {
s := strings.ToLower(n)
for i, p := range f.Parameters {
if p.Name == s {
f.Parameters = append(f.Parameters[:i], f.Parameters[i+1:]...)
break
}
}
}
// Parses \a p, which is expected to refer to a string whose next characters
// form the RFC 2045 production '*(";"parameter)'.
func (f *MIMEField) parseParameters(p *parser) {
done := false
first := true
for f.Valid() && !done {
done = true
i := p.Pos()
for p.NextChar() == ';' ||
p.NextChar() == ' ' || p.NextChar() == '\t' ||
p.NextChar() == '\r' || p.NextChar() == '\n' ||
p.NextChar() == '"' {
p.Step(1)
}
if i < p.Pos() {
done = false
}
if first {
done = false
}
if p.AtEnd() {
done = true
}
first = false
if !done {
n := strings.ToLower(p.MIMEToken())
p.Comment()
havePart := false
partNumber := 0
if n == "" {
return
}
if strings.Contains(n, "*") {
star := strings.Index(n, "*")
var err error
partNumber, err = strconv.Atoi(n[star+1:])
if err == nil {
havePart = true
n = n[:star]
}
}
if f.Name() == ContentTypeFieldName && p.AtEnd() && charset.Info(n) != nil {
// sometimes we see just iso-8859-1 instead of charset=iso-8859-1.
exists := false
for _, param := range f.Parameters {
if param.Name == "charset" {
exists = true
break
}
}
if !exists {
param := NewMIMEParameter("charset", n)
f.Parameters = append(f.Parameters, param)
return
}
}
if p.NextChar() == ':' && isKnownField[n] {
// some spammers send e.g. 'c-t: stuff subject:
// stuff'. we ignore the second field entirely. who
// cares about spammers.
n = ""
p.Step(len(p.str))
} else if p.NextChar() != '=' {
return
}
p.Step(1)
p.Whitespace()
v := ""
if p.NextChar() == '"' {
v = p.MIMEValue()
} else {
start := p.Pos()
v = p.MIMEValue()
ok := true
for ok && !p.AtEnd() &&
p.NextChar() != ';' &&
p.NextChar() != '"' {
if p.DotAtom() == "" && p.MIMEValue() == "" {
ok = false
}
}
if ok {
v = p.str[start:p.Pos()]
}
}
p.Comment()
if n != "" {
i := 0
for i < len(f.Parameters) {
if f.Parameters[i].Name == n {
break
}
i++
}
if i >= len(f.Parameters) {
param := NewMIMEParameter(n, "")
f.Parameters = append(f.Parameters, param)
}
if havePart {
gap := partNumber - len(f.Parameters[i].Parts)
if gap > 0 {
// extend so append works
f.Parameters[i].Parts = append(f.Parameters[i].Parts, make([]string, gap)...)
}
f.Parameters[i].Parts = append(f.Parameters[i].Parts, v)
} else {
f.Parameters[i].Value = v
}
}
}
}
for _, p := range f.Parameters {
if p.Value == "" && len(p.Parts) > 0 {
for _, v := range p.Parts {
p.Value += v
}
}
}
}
// This reimplementation of rfc822() never generates UTF-8 at the moment.
// Merely a SMoP, but I haven't the guts to do it at the moment.
func (f *MIMEField) rfc822(avoidUTF8 bool) string {
s := f.baseValue
lineLength := len(f.Name()) + 2 + len(s)
words := []string{}
for _, p := range f.Parameters {
s := p.Value
if !isBoring(s, MIMEBoring) {
s = quote(s, '"', '\'')
}
words = append(words, p.Name+"="+s)
}
for len(words) > 0 {
i := 0
for i < len(words) && lineLength+2+len(words[i]) > 78 {
i++
}
if i < len(words) {
s += "; "