-
Notifications
You must be signed in to change notification settings - Fork 5
/
header.go
1686 lines (1533 loc) · 43.4 KB
/
header.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"
"fmt"
"math"
"strings"
"time"
"encoding/json"
)
type headerMode int
const (
RFC5322Header headerMode = iota
MIMEHeader
)
type defaultContentType int
const (
TextPlainContentType defaultContentType = iota // default
MessageRFC822ContentType
)
type Header struct {
Fields []Field
defaultType defaultContentType
mode headerMode
numBytes int
err error
verified bool
}
func (h *Header) MarshalJSON() ([]byte, error) {
hs := make([]map[string]interface{}, 0, 8)
for _, f := range h.Fields {
h := make(map[string]interface{})
h["name"] = f.Name()
h["value"] = f.Value()
hs = append(hs, h)
}
return json.Marshal(hs)
}
func (h *Header) UnmarshalJSON(data []byte) error {
hs := make([]map[string]interface{}, 0, 8)
err := json.Unmarshal(data, &hs)
if err != nil {
return err
}
for _, f := range hs {
// TODO: Should we handle failed type assertions differently?
name, ok := f["name"].(string)
value, ok := f["value"].(string)
if ok {
h.Add(name, value)
}
}
return nil
}
func ReadHeader(rfc5322 string, m headerMode) (h *Header, err error) {
h = &Header{mode: m}
done := false
i := 0
end := len(rfc5322)
for !done {
if i >= end {
done = true
}
// Skip past UTF8 byte order mark (BOM) if present
if i+2 < end && rfc5322[i] == 0xEF && rfc5322[i+1] == 0xBB && rfc5322[i+2] == 0xBF {
i += 3
}
j := i
for j < end && rfc5322[j] >= 33 && rfc5322[j] <= 127 && rfc5322[j] != ':' {
j++
}
if j == i+4 && m == RFC5322Header && strings.ToLower(rfc5322[i:j+1]) == "from " {
for i < end && rfc5322[i] != '\r' && rfc5322[i] != '\n' {
i++
}
for rfc5322[i] == '\r' {
i++
}
if rfc5322[i] == '\n' {
i++
}
} else if j > i && rfc5322[j] == ':' {
name := rfc5322[i:j]
i = j
i++
for rfc5322[i] == ' ' || rfc5322[i] == '\t' {
i++
}
j = i
// Find the end of the value, including multiline values
// NOTE: Deviates from https://github.com/aox/aox/blob/master/message/message.cpp#L224
for j < end && (rfc5322[j] != '\n' || (j+1 < end && (rfc5322[j+1] == ' ' || rfc5322[j+1] == '\t'))) {
j++
}
if j > 0 && rfc5322[j-1] == '\r' {
j--
}
value := rfc5322[i:j]
//233-237
if simplify(value) != "" || strings.HasPrefix(strings.ToLower(name), "x-") {
h.Add(name, value)
}
i = j
if i+1 < end && rfc5322[i] == '\r' && rfc5322[i+1] == '\n' {
i++
}
i++
} else {
done = true
}
}
// PR: chomped second newline at header end
if i+1 < len(rfc5322) && rfc5322[i] == '\r' && rfc5322[i+1] == '\n' {
i += 2
} else if i < len(rfc5322) && rfc5322[i] == '\n' {
i++
}
h.numBytes = i
return h, nil
}
// Returns true if this Header fills all the conditions laid out in RFC 2821
// for validity, and false if not.
func (h *Header) Valid() bool {
h.verify()
return h.err == nil
}
// Add adds the key, value pair to the header. It appends to any existing
// values associated with the key.
func (h *Header) Add(key, value string) {
h.addField(NewHeaderField(key, value))
}
func (h *Header) addField(f Field) {
if f.Name() == ToFieldName || f.Name() == CcFieldName ||
f.Name() == BccFieldName || f.Name() == ReplyToFieldName ||
f.Name() == FromFieldName {
first := h.addressField(f.Name(), 0)
next := f.(*AddressField)
if first != nil {
for _, a := range next.Addresses {
first.Addresses = append(first.Addresses, a)
}
return
}
}
// TODO: aox implementation allows insertion at specified position
h.Fields = append(h.Fields, f)
h.verified = false
}
func (h *Header) RemoveAt(i int) {
h.Fields = append(h.Fields[:i], h.Fields[i+1:]...)
}
func (h *Header) Remove(r Field) {
for i, f := range h.Fields {
if f == r {
h.RemoveAt(i)
}
}
}
func (h *Header) RemoveAllNamed(name string) {
i := 0
name = strings.ToLower(name)
for i < len(h.Fields) {
if strings.ToLower(h.Fields[i].Name()) == name {
h.RemoveAt(i)
} else {
i++
}
}
}
// Get gets the first value associated with the given key. If there are no
// values associated with the key, Get returns "".
func (h *Header) Get(key string) string {
f := h.field(key, 0)
if f == nil {
return ""
} else {
return f.Value()
}
}
func (h *Header) field(fn string, n int) Field {
for _, field := range h.Fields {
if field.Name() == fn {
if n > 0 {
n--
} else {
return field
}
}
}
return nil
}
// Returns a pointer to the address field of type \a t at index \a n in this
// header, or a null pointer if no such field exists.
func (h *Header) addressField(fn string, n int) *AddressField {
switch fn {
case FromFieldName, ResentFromFieldName, SenderFieldName, ResentSenderFieldName,
ReturnPathFieldName, ReplyToFieldName, ToFieldName, CcFieldName, BccFieldName,
ResentToFieldName, ResentCcFieldName, ResentBccFieldName, MessageIDFieldName,
ContentIDFieldName, ResentMessageIDFieldName, ReferencesFieldName:
f, _ := h.field(fn, n).(*AddressField)
return f
}
return nil
}
// Returns the header's data \a t, which is the normal date by default, but can
// also be orig-date or resent-date. If there is no such field or \a t is
// meaningless, date() returns a null pointer.
func (h *Header) Date() *time.Time {
hf := h.field(DateFieldName, 0).(*DateField)
if hf == nil {
return nil
}
return hf.Date
}
// Returns the value of the first Subject header field. If there is no such
// field, returns the empty string.
func (h *Header) Subject() string {
f := h.field(SubjectFieldName, 0)
if f == nil {
return ""
}
return f.Value()
}
// Returns a pointer to the addresses in the \a t header field, which must be
// an address field such as From or Bcc. If not, or if the field is empty,
// addresses() returns a null pointer.
func (h *Header) Addresses(fn string) []Address {
af := h.addressField(fn, 0)
if af == nil {
return nil
}
return af.Addresses
}
// Returns a pointer to the Content-Type header field, or a null pointer if
// there isn't one.
func (h *Header) ContentType() *ContentType {
f := h.field(ContentTypeFieldName, 0)
if f == nil {
return nil
}
return f.(*ContentType)
}
// Returns a pointer to the Content-Transfer-Encoding header field, or a null
// pointer if there isn't one.
func (h *Header) ContentTransferEncoding() *ContentTransferEncoding {
f := h.field(ContentTransferEncodingFieldName, 0)
if f == nil {
return nil
}
return f.(*ContentTransferEncoding)
}
// Returns a pointer to the Content-Disposition header field, or a null pointer
// if there isn't one.
func (h *Header) ContentDisposition() *ContentDisposition {
f := h.field(ContentDispositionFieldName, 0)
if f == nil {
return nil
}
return f.(*ContentDisposition)
}
// Returns the value of the Content-Description field, or an empty string if
// there isn't one. RFC 2047 encoding is not considered - should it be?
func (h *Header) ContentDescription() string {
f := h.field(ContentDescriptionFieldName, 0)
if f == nil {
return ""
}
return simplify(f.rfc822(false))
}
// Returns the value of the Content-Location field, or an empty string if there
// isn't one. The URI is not validated in any way.
func (h *Header) ContentLocation() string {
f := h.field(ContentLocationFieldName, 0)
if f == nil {
return ""
}
return f.rfc822(false)
}
// Returns a pointer to the Content-Language header field, or a null pointer if
// there isn't one.
func (h *Header) ContentLanguage() *ContentLanguage {
f := h.field(ContentLanguageFieldName, 0)
if f == nil {
return nil
}
return f.(*ContentLanguage)
}
// Returns the value of the Message-ID field, or an empty string if there isn't one
// or if there are multiple (which is illegal).
func (h *Header) MessageID() string {
ids := h.Addresses(MessageIDFieldName)
if len(ids) != 1 {
return ""
}
id := ids[0]
return fmt.Sprintf("<%s@%s>", id.Localpart, id.Domain)
}
func (h *Header) ToMap() map[string][]string {
headers := make(map[string][]string)
for _, f := range h.Fields {
headers[f.Name()] = append(headers[f.Name()], f.Value())
}
return headers
}
type HeaderFieldCondition struct {
name string
min, max int
m headerMode
}
var conditions = []HeaderFieldCondition{
HeaderFieldCondition{SenderFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{ReplyToFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{ToFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{CcFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{BccFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{MessageIDFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{ReferencesFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{SubjectFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{FromFieldName, 1, 1, RFC5322Header},
HeaderFieldCondition{DateFieldName, 1, 1, RFC5322Header},
HeaderFieldCondition{MIMEVersionFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{MIMEVersionFieldName, 0, 1, MIMEHeader},
HeaderFieldCondition{ContentTypeFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{ContentTypeFieldName, 0, 1, MIMEHeader},
HeaderFieldCondition{ContentTransferEncodingFieldName, 0, 1, RFC5322Header},
HeaderFieldCondition{ContentTransferEncodingFieldName, 0, 1, MIMEHeader},
HeaderFieldCondition{ReturnPathFieldName, 0, 1, RFC5322Header},
}
// This private function verifies that the entire header is consistent and
// legal, and that each contained HeaderField is legal.
func (h *Header) verify() {
if h.verified {
return
}
h.verified = true
h.err = nil
for _, f := range h.Fields {
if !f.Valid() {
h.err = fmt.Errorf("%s: %s", f.Name(), f.Error())
return
}
}
occurrences := make(map[string]int)
for _, f := range h.Fields {
occurrences[f.Name()]++
}
i := 0
for h.err == nil && i < len(conditions) {
if conditions[i].m == h.mode &&
occurrences[conditions[i].name] < conditions[i].min ||
occurrences[conditions[i].name] > conditions[i].max {
if conditions[i].max < occurrences[conditions[i].name] {
h.err = fmt.Errorf("%d %s fields seen. At most %d may be present.",
occurrences[conditions[i].name], conditions[i].name, conditions[i].max)
} else {
h.err = fmt.Errorf("%d %s fields seen. At least %d must be present.",
occurrences[conditions[i].name], conditions[i].name, conditions[i].min)
}
}
i++
}
// strictly speaking, if From contains more than one address,
// sender should contain one. we don't enforce that, because it
// causes too much spam to be rejected that would otherwise go
// through. we'll filter spam with something that's a little less
// accidental, and which does not clutter up the logs with so many
// misleading error messages.
// we graciously ignore all the Resent-This-Or-That restrictions.
}
func sameAddresses(a, b *AddressField) bool {
if a == nil || b == nil {
return false
}
l := a.Addresses
m := b.Addresses
if l == nil || m == nil {
return false
}
if len(l) != len(m) {
return false
}
lmap := make(map[string]bool)
for _, a := range l {
n := fmt.Sprintf("%s@%s", a.Localpart, strings.ToTitle(a.Domain))
lmap[n] = true
}
mmap := make(map[string]bool)
for _, a := range l {
n := fmt.Sprintf("%s@%s", a.Localpart, strings.ToTitle(a.Domain))
mmap[n] = true
}
for _, a := range l {
n := fmt.Sprintf("%s@%s", a.Localpart, strings.ToTitle(a.Domain))
if !mmap[n] {
return false
}
}
for _, a := range m {
n := fmt.Sprintf("%s@%s", a.Localpart, strings.ToTitle(a.Domain))
if !lmap[n] {
return false
}
}
return true
}
// Removes any redundant header fields from this header, and simplifies the
// value of some.
//
// For example, if 'sender' or 'reply-to' points to the same address as 'from',
// that field can be removed, and if 'from' contains the same address twice,
// one can be removed.
func (h *Header) Simplify() {
if !h.Valid() {
return
}
for _, fn := range addressFieldNames {
af := h.addressField(fn, 0)
if af != nil {
af.Addresses.Uniquify()
}
}
cde := h.field(ContentDescriptionFieldName, 0)
if cde != nil && cde.rfc822(false) == "" {
h.RemoveAllNamed(ContentDescriptionFieldName)
cde = nil
}
cte := h.ContentTransferEncoding()
if cte != nil && cte.Encoding == BinaryEncoding {
h.RemoveAllNamed(ContentTransferEncodingFieldName)
}
cdi := h.ContentDisposition()
if cdi != nil {
ct := h.ContentType()
if h.mode == RFC5322Header && (ct == nil || ct.Type == "text") &&
cdi.Disposition == "inline" &&
len(cdi.Parameters) == 0 {
h.RemoveAllNamed(ContentDispositionFieldName)
cdi = nil
}
}
ct := h.ContentType()
if ct != nil {
if len(ct.Parameters) == 0 && cte == nil && cdi == nil && cde == nil &&
h.defaultType == TextPlainContentType &&
ct.Type == "text" && ct.Subtype == "plain" {
h.RemoveAllNamed(ContentTypeFieldName)
ct = nil
}
} else if h.defaultType == MessageRFC822ContentType {
h.Add("Content-Type", "message/rfc822")
ct = h.ContentType()
}
if h.mode == MIMEHeader {
h.RemoveAllNamed(MIMEVersionFieldName)
} else if ct == nil && cte == nil && cde == nil && cdi == nil &&
h.field(ContentLocationFieldName, 0) == nil &&
h.field(ContentBaseFieldName, 0) == nil {
h.RemoveAllNamed(MIMEVersionFieldName)
} else {
if h.mode == RFC5322Header && h.field(MIMEVersionFieldName, 0) == nil {
h.Add("MIME-Version", "1.0")
}
}
if ct != nil &&
(ct.Type == "multipart" || ct.Type == "message" ||
ct.Type == "image" || ct.Type == "audio" ||
ct.Type == "video") {
ct.removeParameter("charset")
}
if h.field(ErrorsToFieldName, 0) != nil {
et := ascii(h.field(ErrorsToFieldName, 0).Value())
rp := h.Addresses(ReturnPathFieldName)
if rp != nil && len(rp) == 1 &&
strings.ToLower(rp[0].lpdomain()) == strings.ToLower(et) {
h.RemoveAllNamed(ErrorsToFieldName)
}
}
m := h.field(MessageIDFieldName, 0)
if m != nil && m.rfc822(false) == "" {
h.RemoveAllNamed(MessageIDFieldName)
}
if sameAddresses(h.addressField(FromFieldName, 0), h.addressField(ReplyToFieldName, 0)) {
h.RemoveAllNamed(ReplyToFieldName)
}
if sameAddresses(h.addressField(FromFieldName, 0), h.addressField(SenderFieldName, 0)) {
h.RemoveAllNamed(SenderFieldName)
}
if len(h.Addresses(SenderFieldName)) == 0 {
h.RemoveAllNamed(SenderFieldName)
}
if len(h.Addresses(ReturnPathFieldName)) == 0 {
h.RemoveAllNamed(ReturnPathFieldName)
}
if len(h.Addresses(ToFieldName)) == 0 {
h.RemoveAllNamed(ToFieldName)
}
if len(h.Addresses(CcFieldName)) == 0 {
h.RemoveAllNamed(CcFieldName)
}
if len(h.Addresses(BccFieldName)) == 0 {
h.RemoveAllNamed(BccFieldName)
}
if len(h.Addresses(ReplyToFieldName)) == 0 {
h.RemoveAllNamed(ReplyToFieldName)
}
}
// Repairs problems that can be repaired without knowing the associated
// bodypart.
func (h *Header) Repair() {
if h.Valid() {
return
}
// We remove duplicates of any field that may occur only once.
// (Duplication has been observed for Date/Subject/M-V/C-T-E/C-T/M-I.)
occurrences := make(map[string]int)
for _, f := range h.Fields {
occurrences[f.Name()]++
}
i := 0
for i < len(conditions) {
if conditions[i].m == h.mode &&
occurrences[conditions[i].name] > conditions[i].max {
n := 0
j := 0
hf := h.field(conditions[i].name, 0)
for j < len(h.Fields) {
if h.Fields[j].Name() == conditions[i].name {
n++
if n > 1 && hf.rfc822(false) == h.Fields[j].rfc822(false) {
h.RemoveAt(j)
} else {
j++
}
} else {
j++
}
}
}
i++
}
// If there are several content-type fields, and they agree except
// that one has options and the others not, remove the option-less
// ones.
if occurrences[ContentTypeFieldName] > 1 {
ct := h.ContentType()
other := ct
var good *ContentType
n := 0
bad := false
for other != nil && !bad {
if other.Type != ct.Type ||
other.Subtype != ct.Subtype {
bad = true
} else if len(other.Parameters) > 0 {
if good != nil {
bad = true
}
good = other
}
n++
tmp := h.field(ContentTypeFieldName, n)
if tmp != nil {
other = tmp.(*ContentType)
} else {
other = nil
}
}
if good != nil && !bad {
i := 0
for i < len(h.Fields) {
if h.Fields[i].Name() == ContentTypeFieldName && h.Fields[i] != good {
h.RemoveAt(i)
} else {
i++
}
}
}
}
// We retain only the first valid Date field, Return-Path,
// Message-Id, References and Content-Type fields. If there is one
// or more valid such field, we delete all invalid fields,
// otherwise we leave the fields as they are.
// For most of these, we also delete subsequent valid fields. For
// Content-Type we only delete invalid fields, since there isn't
// any strong reason to believe that the one we would keep enables
// correct interpretation of the body.
// Several senders appear to send duplicate dates. qmail is
// mentioned in the references chains of most examples we have.
// We don't know who adds duplicate message-id, return-path and
// content-type fields.
// The only case we've seen of duplicate references involved
// Thunderbird 1.5.0.4 and Scalix. Uncertain whose
// bug. Thunderbird 1.5.0.5 looks correct.
for _, name := range fieldNames {
if occurrences[name] > 1 &&
(name == DateFieldName ||
name == ReturnPathFieldName ||
name == MessageIDFieldName ||
name == ContentTypeFieldName ||
name == ReferencesFieldName) {
var firstValid Field
for _, f := range h.Fields {
if f.Name() == name && f.Valid() {
firstValid = f
break
}
}
if firstValid != nil {
alsoValid := true
if name == ContentTypeFieldName {
alsoValid = false
}
i := 0
for i < len(h.Fields) {
if h.Fields[i].Name() == name && h.Fields[i] != firstValid &&
(alsoValid || !h.Fields[i].Valid()) {
h.RemoveAt(i)
} else {
i++
}
}
}
}
}
// MIME-Version is occasionally seen more than once, usually on
// spam or mainsleaze.
if h.field(MIMEVersionFieldName, 1) != nil {
h.Remove(h.field(MIMEVersionFieldName, 1))
fmv := h.field(MIMEVersionFieldName, 0)
fmv.Parse(fmt.Sprintf("1.0 (Note: original message contained %d MIME-Version fields)", occurrences[MIMEVersionFieldName]))
}
// Content-Transfer-Encoding: should not occur on multiparts, and
// when it does it usually has a syntax error. We don't care about
// that error.
if occurrences[ContentTransferEncodingFieldName] > 0 {
ct := h.ContentType()
if ct != nil && ct.Type == "multipart" || ct.Type == "message" {
h.RemoveAllNamed(ContentTransferEncodingFieldName)
}
}
// Sender sometimes is a straight copy of From, even if From
// contains more than one address. If it's a copy, or even an
// illegal subset, we drop it.
senders := h.Addresses(SenderFieldName)
if occurrences[SenderFieldName] > 0 && len(senders) != 1 {
from := make(map[string]bool)
for _, a := range h.Addresses(FromFieldName) {
from[strings.ToLower(a.lpdomain())] = true
}
sender := []string{}
for _, a := range h.Addresses(FromFieldName) {
sender = append(sender, strings.ToLower(a.lpdomain()))
}
i := 0
difference := false
for i < len(sender) && difference {
if !from[sender[i]] {
difference = true
}
i++
}
if !difference {
h.RemoveAllNamed(SenderFieldName)
}
}
}
// Repairs a few harmless and common problems, such as inserting two Date
// fields with the same value. Assumes that \a p is its companion body (whose
// text is in \a body), and may look at it to decide what/how to repair.
func (h *Header) RepairWithBody(p *Part, body string) {
if h.Valid() {
return
}
// Duplicated from above.
occurrences := make(map[string]int)
for _, f := range h.Fields {
occurrences[f.Name()]++
}
i := 0
for i < len(conditions) {
if conditions[i].m == h.mode &&
occurrences[conditions[i].name] > conditions[i].max {
n := 0
j := 0
hf := h.field(conditions[i].name, 0)
for j < len(h.Fields) {
if h.Fields[j].Name() == conditions[i].name {
n++
if n > 1 && hf.rfc822(false) == h.Fields[j].rfc822(false) {
h.RemoveAt(j)
} else {
j++
}
} else {
j++
}
}
}
i++
}
// If there is no valid Date field and this is an RFC822 header,
// we look for a sensible date.
if h.mode == RFC5322Header &&
(occurrences[DateFieldName] == 0 ||
!h.field(DateFieldName, 0).Valid() ||
h.Date() != nil) {
var date *time.Time
for _, f := range h.Fields {
// First, we take the date from the oldest plausible
// Received field.
if f.Name() == ReceivedFieldName {
v := f.rfc822(false)
i := 0
for strings.Index(v[i+1:], ";") > 0 {
i = i + 1 + strings.Index(v[i+1:], ";")
}
if i >= 0 {
tmp := parseDate(v[i+1:])
if tmp != nil {
if date == nil {
// first plausible we've seen
date = tmp
} else {
// if it took more than an hour to
// deliver, or less than no time, we don't
// trust this received field at all.
// FIXME: aox has a buggy extra comparison here, do we need it?
if tmp.Before(*date) {
date = tmp
}
}
}
}
}
}
if date == nil && p != nil {
parent := p.parent
for parent != nil && parent.Header != nil && parent.Header.Date() == nil {
parent = parent.parent
}
if parent != nil {
date = parent.Header.Date()
}
}
if date == nil && occurrences[DateFieldName] == 0 {
// Try to see if the top-level message has an internaldate,
// just in case it might be valid.
parent := p
for parent != nil && parent.parent != nil {
parent = parent.parent
}
// FIXME: reference message internalDate or remove this clause
}
if date == nil && occurrences[DateFieldName] == 0 {
// As last resort, use the current date, time and
// timezone. Only do this if there isn't a date field. If
// there is one, we'll reject the message (at least for
// now) since this happens only for submission in
// practice.
tmp := time.Now()
date = &tmp
}
if date != nil {
// FIXME: aox inserts at position of existing field, or at end
h.Add(DateFieldName, date.Format(time.RFC822Z))
}
}
// If there is no From field, try to use either Return-Path or
// Sender from this Header, or From, Return-Path or Sender from
// the Header of the closest encompassing Multipart that has such
// a field.
if occurrences[FromFieldName] == 0 && h.mode == RFC5322Header {
parent := p
head := h
a := []Address{}
for (head != nil || parent != nil) && len(a) == 0 {
if head != nil {
a = h.Addresses(FromFieldName)
}
if head != nil && (len(a) == 0 || a[0].t != NormalAddressType) {
a = h.Addresses(ReturnPathFieldName)
}
if head != nil && (len(a) == 0 || a[0].t != NormalAddressType) {
a = h.Addresses(SenderFieldName)
}
if head != nil && (len(a) == 0 || a[0].t != NormalAddressType) {
a = []Address{}
}
if parent != nil {
parent = parent.parent
}
if parent != nil {
head = parent.Header
} else {
head = nil
}
}
if len(a) == 0 {
// if there is an X-From-Line, it could be old damaged
// gnus mail, fcc'd before a From line was added. Let's
// try.
for _, f := range h.Fields {
if f.Name() == "X-From-Line" {
ap := NewAddressParser(section(f.rfc822(false), " ", 1))
ap.assertSingleAddress()
if ap.firstError == nil {
a = ap.Addresses
}
break
}
}
}
if len(a) > 0 {
h.Add(FromFieldName, a[0].toString(false))
}
}
// Some spammers like to get return receipts while hiding their
// Fromness, so if From is bad and either Return-Receipt-To or
// Disposition-Notification-To is good, use those.
if h.mode == RFC5322Header &&
(h.field(FromFieldName, 0) == nil ||
!h.field(FromFieldName, 0).Valid() &&
len(h.Addresses(FromFieldName)) == 0) {
a := []Address{}
for _, f := range h.Fields {
if f.Name() == "Return-Receipt-To" ||
f.Name() == "Disposition-Notification-To" {
ap := NewAddressParser(section(f.rfc822(false), " ", 1))
ap.assertSingleAddress()
if ap.firstError == nil {
a = ap.Addresses
}
}
if len(a) > 0 {
break
}
}
if len(a) > 0 {
h.RemoveAllNamed(FromFieldName)
h.Add(FromFieldName, a[0].toString(false))
}
}
// If there is an unacceptable Received field somewhere, remove it and all
// the older Received fields.
if occurrences[ReceivedFieldName] > 0 {
bad := false
i := 0
for i < len(h.Fields) {
if h.Fields[i].Name() == ReceivedFieldName {
if !h.Valid() {
bad = true
}
if bad {
h.RemoveAt(i)
} else {
i++
}
} else {
i++
}
}
}
// For some header fields which can contain errors, our best
// option is to remove them. A field belongs here if it can be
// parsed somehow and can be dropped without changing the meaning
// of the rest of the message.
if occurrences[ContentLocationFieldName] > 0 ||
occurrences[ContentDispositionFieldName] > 0 ||
occurrences[ContentIDFieldName] > 0 ||
occurrences[MessageIDFieldName] > 0 {
i := 0
for i < len(h.Fields) {
if (h.Fields[i].Name() == ContentLocationFieldName ||
h.Fields[i].Name() == ContentDispositionFieldName ||
h.Fields[i].Name() == ContentIDFieldName ||
h.Fields[i].Name() == MessageIDFieldName) &&
!h.Fields[i].Valid() {
h.RemoveAt(i)
} else {
i++
}
}
}
// If there's more than one Sender field, preserve the first that