forked from emersion/go-imap
/
fetch.go
1183 lines (1011 loc) · 26.6 KB
/
fetch.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 imapclient
import (
"fmt"
"io"
netmail "net/mail"
"strings"
"time"
"github.com/emersion/go-imap/v2"
"github.com/emersion/go-imap/v2/internal"
"github.com/emersion/go-imap/v2/internal/imapwire"
"github.com/emersion/go-message/mail"
)
// Fetch sends a FETCH command.
//
// The caller must fully consume the FetchCommand. A simple way to do so is to
// defer a call to FetchCommand.Close.
//
// A nil options pointer is equivalent to a zero options value.
func (c *Client) Fetch(numSet imap.NumSet, options *imap.FetchOptions) *FetchCommand {
if options == nil {
options = new(imap.FetchOptions)
}
numKind := imapwire.NumSetKind(numSet)
cmd := &FetchCommand{
numSet: numSet,
msgs: make(chan *FetchMessageData, 128),
}
enc := c.beginCommand(uidCmdName("FETCH", numKind), cmd)
enc.SP().NumSet(numSet).SP()
writeFetchItems(enc.Encoder, numKind, options)
if options.ChangedSince != 0 {
enc.SP().Special('(').Atom("CHANGEDSINCE").SP().ModSeq(options.ChangedSince).Special(')')
}
enc.end()
return cmd
}
func writeFetchItems(enc *imapwire.Encoder, numKind imapwire.NumKind, options *imap.FetchOptions) {
listEnc := enc.BeginList()
// Ensure we request UID as the first data item for UID FETCH, to be safer.
// We want to get it before any literal.
if options.UID || numKind == imapwire.NumKindUID {
listEnc.Item().Atom("UID")
}
m := map[string]bool{
"BODY": options.BodyStructure != nil && !options.BodyStructure.Extended,
"BODYSTRUCTURE": options.BodyStructure != nil && options.BodyStructure.Extended,
"ENVELOPE": options.Envelope,
"FLAGS": options.Flags,
"INTERNALDATE": options.InternalDate,
"RFC822.SIZE": options.RFC822Size,
"MODSEQ": options.ModSeq,
}
for k, req := range m {
if req {
listEnc.Item().Atom(k)
}
}
for _, bs := range options.BodySection {
writeFetchItemBodySection(listEnc.Item(), bs)
}
for _, bs := range options.BinarySection {
writeFetchItemBinarySection(listEnc.Item(), bs)
}
for _, bss := range options.BinarySectionSize {
writeFetchItemBinarySectionSize(listEnc.Item(), bss)
}
listEnc.End()
}
func writeFetchItemBodySection(enc *imapwire.Encoder, item *imap.FetchItemBodySection) {
enc.Atom("BODY")
if item.Peek {
enc.Atom(".PEEK")
}
enc.Special('[')
writeSectionPart(enc, item.Part)
if len(item.Part) > 0 && item.Specifier != imap.PartSpecifierNone {
enc.Special('.')
}
if item.Specifier != imap.PartSpecifierNone {
enc.Atom(string(item.Specifier))
var headerList []string
if len(item.HeaderFields) > 0 {
headerList = item.HeaderFields
enc.Atom(".FIELDS")
} else if len(item.HeaderFieldsNot) > 0 {
headerList = item.HeaderFieldsNot
enc.Atom(".FIELDS.NOT")
}
if len(headerList) > 0 {
enc.SP().List(len(headerList), func(i int) {
enc.String(headerList[i])
})
}
}
enc.Special(']')
writeSectionPartial(enc, item.Partial)
}
func writeFetchItemBinarySection(enc *imapwire.Encoder, item *imap.FetchItemBinarySection) {
enc.Atom("BINARY")
if item.Peek {
enc.Atom(".PEEK")
}
enc.Special('[')
writeSectionPart(enc, item.Part)
enc.Special(']')
writeSectionPartial(enc, item.Partial)
}
func writeFetchItemBinarySectionSize(enc *imapwire.Encoder, item *imap.FetchItemBinarySectionSize) {
enc.Atom("BINARY.SIZE")
enc.Special('[')
writeSectionPart(enc, item.Part)
enc.Special(']')
}
func writeSectionPart(enc *imapwire.Encoder, part []int) {
if len(part) == 0 {
return
}
var l []string
for _, num := range part {
l = append(l, fmt.Sprintf("%v", num))
}
enc.Atom(strings.Join(l, "."))
}
func writeSectionPartial(enc *imapwire.Encoder, partial *imap.SectionPartial) {
if partial == nil {
return
}
enc.Special('<').Number64(partial.Offset).Special('.').Number64(partial.Size).Special('>')
}
// FetchCommand is a FETCH command.
type FetchCommand struct {
cmd
numSet imap.NumSet
recvSeqSet imap.SeqSet
recvUIDSet imap.UIDSet
msgs chan *FetchMessageData
prev *FetchMessageData
}
func (cmd *FetchCommand) recvSeqNum(seqNum uint32) bool {
set, ok := cmd.numSet.(imap.SeqSet)
if !ok || !set.Contains(seqNum) {
return false
}
if cmd.recvSeqSet.Contains(seqNum) {
return false
}
cmd.recvSeqSet.AddNum(seqNum)
return true
}
func (cmd *FetchCommand) recvUID(uid imap.UID) bool {
set, ok := cmd.numSet.(imap.UIDSet)
if !ok || !set.Contains(uid) {
return false
}
if cmd.recvUIDSet.Contains(uid) {
return false
}
cmd.recvUIDSet.AddNum(uid)
return true
}
// Next advances to the next message.
//
// On success, the message is returned. On error or if there are no more
// messages, nil is returned. To check the error value, use Close.
func (cmd *FetchCommand) Next() *FetchMessageData {
if cmd.prev != nil {
cmd.prev.discard()
}
cmd.prev = <-cmd.msgs
return cmd.prev
}
// Close releases the command.
//
// Calling Close unblocks the IMAP client decoder and lets it read the next
// responses. Next will always return nil after Close.
func (cmd *FetchCommand) Close() error {
for cmd.Next() != nil {
// ignore
}
return cmd.cmd.Wait()
}
// Collect accumulates message data into a list.
//
// This method will read and store message contents in memory. This is
// acceptable when the message contents have a reasonable size, but may not be
// suitable when fetching e.g. attachments.
//
// This is equivalent to calling Next repeatedly and then Close.
func (cmd *FetchCommand) Collect() ([]*FetchMessageBuffer, error) {
defer cmd.Close()
var l []*FetchMessageBuffer
for {
msg := cmd.Next()
if msg == nil {
break
}
buf, err := msg.Collect()
if err != nil {
return l, err
}
l = append(l, buf)
}
return l, cmd.Close()
}
// FetchMessageData contains a message's FETCH data.
type FetchMessageData struct {
SeqNum uint32
items chan FetchItemData
prev FetchItemData
}
// Next advances to the next data item for this message.
//
// If there is one or more data items left, the next item is returned.
// Otherwise nil is returned.
func (data *FetchMessageData) Next() FetchItemData {
if d, ok := data.prev.(discarder); ok {
d.discard()
}
item := <-data.items
data.prev = item
return item
}
func (data *FetchMessageData) discard() {
for {
if item := data.Next(); item == nil {
break
}
}
}
// Collect accumulates message data into a struct.
//
// This method will read and store message contents in memory. This is
// acceptable when the message contents have a reasonable size, but may not be
// suitable when fetching e.g. attachments.
func (data *FetchMessageData) Collect() (*FetchMessageBuffer, error) {
defer data.discard()
buf := &FetchMessageBuffer{SeqNum: data.SeqNum}
for {
item := data.Next()
if item == nil {
break
}
if err := buf.populateItemData(item); err != nil {
return buf, err
}
}
return buf, nil
}
// FetchItemData contains a message's FETCH item data.
type FetchItemData interface {
fetchItemData()
}
var (
_ FetchItemData = FetchItemDataBodySection{}
_ FetchItemData = FetchItemDataBinarySection{}
_ FetchItemData = FetchItemDataFlags{}
_ FetchItemData = FetchItemDataEnvelope{}
_ FetchItemData = FetchItemDataInternalDate{}
_ FetchItemData = FetchItemDataRFC822Size{}
_ FetchItemData = FetchItemDataUID{}
_ FetchItemData = FetchItemDataBodyStructure{}
)
type discarder interface {
discard()
}
var (
_ discarder = FetchItemDataBodySection{}
_ discarder = FetchItemDataBinarySection{}
)
// FetchItemDataBodySection holds data returned by FETCH BODY[].
type FetchItemDataBodySection struct {
Section *imap.FetchItemBodySection
Literal imap.LiteralReader
}
func (FetchItemDataBodySection) fetchItemData() {}
func (item FetchItemDataBodySection) discard() {
io.Copy(io.Discard, item.Literal)
}
// FetchItemDataBinarySection holds data returned by FETCH BINARY[].
type FetchItemDataBinarySection struct {
Section *imap.FetchItemBinarySection
Literal imap.LiteralReader
}
func (FetchItemDataBinarySection) fetchItemData() {}
func (item FetchItemDataBinarySection) discard() {
io.Copy(io.Discard, item.Literal)
}
// FetchItemDataFlags holds data returned by FETCH FLAGS.
type FetchItemDataFlags struct {
Flags []imap.Flag
}
func (FetchItemDataFlags) fetchItemData() {}
// FetchItemDataEnvelope holds data returned by FETCH ENVELOPE.
type FetchItemDataEnvelope struct {
Envelope *imap.Envelope
}
func (FetchItemDataEnvelope) fetchItemData() {}
// FetchItemDataInternalDate holds data returned by FETCH INTERNALDATE.
type FetchItemDataInternalDate struct {
Time time.Time
}
func (FetchItemDataInternalDate) fetchItemData() {}
// FetchItemDataRFC822Size holds data returned by FETCH RFC822.SIZE.
type FetchItemDataRFC822Size struct {
Size int64
}
func (FetchItemDataRFC822Size) fetchItemData() {}
// FetchItemDataUID holds data returned by FETCH UID.
type FetchItemDataUID struct {
UID imap.UID
}
func (FetchItemDataUID) fetchItemData() {}
// FetchItemDataBodyStructure holds data returned by FETCH BODYSTRUCTURE or
// FETCH BODY.
type FetchItemDataBodyStructure struct {
BodyStructure imap.BodyStructure
IsExtended bool // True if BODYSTRUCTURE, false if BODY
}
func (FetchItemDataBodyStructure) fetchItemData() {}
// FetchItemDataBinarySectionSize holds data returned by FETCH BINARY.SIZE[].
type FetchItemDataBinarySectionSize struct {
Part []int
Size uint32
}
func (FetchItemDataBinarySectionSize) fetchItemData() {}
// FetchItemDataModSeq holds data returned by FETCH MODSEQ.
//
// This requires the CONDSTORE extension.
type FetchItemDataModSeq struct {
ModSeq uint64
}
func (FetchItemDataModSeq) fetchItemData() {}
// FetchMessageBuffer is a buffer for the data returned by FetchMessageData.
//
// The SeqNum field is always populated. All remaining fields are optional.
type FetchMessageBuffer struct {
SeqNum uint32
Flags []imap.Flag
Envelope *imap.Envelope
InternalDate time.Time
RFC822Size int64
UID imap.UID
BodyStructure imap.BodyStructure
BodySection map[*imap.FetchItemBodySection][]byte
BinarySection map[*imap.FetchItemBinarySection][]byte
BinarySectionSize []FetchItemDataBinarySectionSize
ModSeq uint64 // requires CONDSTORE
}
func (buf *FetchMessageBuffer) populateItemData(item FetchItemData) error {
switch item := item.(type) {
case FetchItemDataBodySection:
b, err := io.ReadAll(item.Literal)
if err != nil {
return err
}
if buf.BodySection == nil {
buf.BodySection = make(map[*imap.FetchItemBodySection][]byte)
}
buf.BodySection[item.Section] = b
case FetchItemDataBinarySection:
b, err := io.ReadAll(item.Literal)
if err != nil {
return err
}
if buf.BinarySection == nil {
buf.BinarySection = make(map[*imap.FetchItemBinarySection][]byte)
}
buf.BinarySection[item.Section] = b
case FetchItemDataFlags:
buf.Flags = item.Flags
case FetchItemDataEnvelope:
buf.Envelope = item.Envelope
case FetchItemDataInternalDate:
buf.InternalDate = item.Time
case FetchItemDataRFC822Size:
buf.RFC822Size = item.Size
case FetchItemDataUID:
buf.UID = item.UID
case FetchItemDataBodyStructure:
buf.BodyStructure = item.BodyStructure
case FetchItemDataBinarySectionSize:
buf.BinarySectionSize = append(buf.BinarySectionSize, item)
case FetchItemDataModSeq:
buf.ModSeq = item.ModSeq
default:
panic(fmt.Errorf("unsupported fetch item data %T", item))
}
return nil
}
func (c *Client) handleFetch(seqNum uint32) error {
dec := c.dec
items := make(chan FetchItemData, 32)
defer close(items)
msg := &FetchMessageData{SeqNum: seqNum, items: items}
// We're in a tricky situation: to know whether this FETCH response needs
// to be handled by a pending command, we may need to look at the UID in
// the response data. But the response data comes in in a streaming
// fashion: it can contain literals. Assume that the UID will be returned
// before any literal.
var uid imap.UID
handled := false
handleMsg := func() {
if handled {
return
}
cmd := c.findPendingCmdFunc(func(anyCmd command) bool {
cmd, ok := anyCmd.(*FetchCommand)
if !ok {
return false
}
// Skip if we haven't requested or already handled this message
if _, ok := cmd.numSet.(imap.UIDSet); ok {
return uid != 0 && cmd.recvUID(uid)
} else {
return seqNum != 0 && cmd.recvSeqNum(seqNum)
}
})
if cmd != nil {
cmd := cmd.(*FetchCommand)
cmd.msgs <- msg
} else if handler := c.options.unilateralDataHandler().Fetch; handler != nil {
go handler(msg)
} else {
go msg.discard()
}
handled = true
}
defer handleMsg()
numAtts := 0
return dec.ExpectList(func() error {
var attName string
if !dec.Expect(dec.Func(&attName, isMsgAttNameChar), "msg-att name") {
return dec.Err()
}
attName = strings.ToUpper(attName)
var (
item FetchItemData
done chan struct{}
)
switch attName {
case "FLAGS":
if !dec.ExpectSP() {
return dec.Err()
}
flags, err := internal.ExpectFlagList(dec)
if err != nil {
return err
}
item = FetchItemDataFlags{Flags: flags}
case "ENVELOPE":
if !dec.ExpectSP() {
return dec.Err()
}
envelope, err := readEnvelope(dec, &c.options)
if err != nil {
return fmt.Errorf("in envelope: %v", err)
}
item = FetchItemDataEnvelope{Envelope: envelope}
case "INTERNALDATE":
if !dec.ExpectSP() {
return dec.Err()
}
t, err := internal.ExpectDateTime(dec)
if err != nil {
return err
}
item = FetchItemDataInternalDate{Time: t}
case "RFC822.SIZE":
var size int64
if !dec.ExpectSP() || !dec.ExpectNumber64(&size) {
return dec.Err()
}
item = FetchItemDataRFC822Size{Size: size}
case "UID":
if !dec.ExpectSP() || !dec.ExpectUID(&uid) {
return dec.Err()
}
item = FetchItemDataUID{UID: uid}
case "BODY", "BINARY":
if dec.Special('[') {
var section interface{}
switch attName {
case "BODY":
var err error
section, err = readSectionSpec(dec)
if err != nil {
return fmt.Errorf("in section-spec: %v", err)
}
case "BINARY":
part, dot := readSectionPart(dec)
if dot {
return fmt.Errorf("in section-binary: expected number after dot")
}
if !dec.ExpectSpecial(']') {
return dec.Err()
}
section = &imap.FetchItemBinarySection{Part: part}
}
if !dec.ExpectSP() {
return dec.Err()
}
// Ignore literal8 marker, if any
if attName == "BINARY" {
dec.Special('~')
}
lit, _, ok := dec.ExpectNStringReader()
if !ok {
return dec.Err()
}
var fetchLit imap.LiteralReader
if lit != nil {
done = make(chan struct{})
fetchLit = &fetchLiteralReader{
LiteralReader: lit,
ch: done,
}
}
switch section := section.(type) {
case *imap.FetchItemBodySection:
item = FetchItemDataBodySection{
Section: section,
Literal: fetchLit,
}
case *imap.FetchItemBinarySection:
item = FetchItemDataBinarySection{
Section: section,
Literal: fetchLit,
}
}
break
}
if !dec.Expect(attName == "BODY", "'['") {
return dec.Err()
}
fallthrough
case "BODYSTRUCTURE":
if !dec.ExpectSP() {
return dec.Err()
}
bodyStruct, err := readBody(dec, &c.options)
if err != nil {
return err
}
item = FetchItemDataBodyStructure{
BodyStructure: bodyStruct,
IsExtended: attName == "BODYSTRUCTURE",
}
case "BINARY.SIZE":
part, dot := readSectionPart(dec)
if dot {
return fmt.Errorf("in section-binary: expected number after dot")
}
var size uint32
if !dec.ExpectSpecial(']') || !dec.ExpectSP() || !dec.ExpectNumber(&size) {
return dec.Err()
}
item = FetchItemDataBinarySectionSize{
Part: part,
Size: size,
}
case "MODSEQ":
var modSeq uint64
if !dec.ExpectSP() || !dec.ExpectSpecial('(') || !dec.ExpectModSeq(&modSeq) || !dec.ExpectSpecial(')') {
return dec.Err()
}
item = FetchItemDataModSeq{ModSeq: modSeq}
default:
return fmt.Errorf("unsupported msg-att name: %q", attName)
}
numAtts++
if numAtts > cap(items) || done != nil {
// To avoid deadlocking we need to ask the message handler to
// consume the data
handleMsg()
}
if done != nil {
c.setReadTimeout(literalReadTimeout)
}
items <- item
if done != nil {
<-done
c.setReadTimeout(respReadTimeout)
}
return nil
})
}
func isMsgAttNameChar(ch byte) bool {
return ch != '[' && imapwire.IsAtomChar(ch)
}
func readEnvelope(dec *imapwire.Decoder, options *Options) (*imap.Envelope, error) {
var envelope imap.Envelope
if !dec.ExpectSpecial('(') {
return nil, dec.Err()
}
var date, subject string
if !dec.ExpectNString(&date) || !dec.ExpectSP() || !dec.ExpectNString(&subject) || !dec.ExpectSP() {
return nil, dec.Err()
}
// TODO: handle error
envelope.Date, _ = netmail.ParseDate(date)
envelope.Subject, _ = options.decodeText(subject)
addrLists := []struct {
name string
out *[]imap.Address
}{
{"env-from", &envelope.From},
{"env-sender", &envelope.Sender},
{"env-reply-to", &envelope.ReplyTo},
{"env-to", &envelope.To},
{"env-cc", &envelope.Cc},
{"env-bcc", &envelope.Bcc},
}
for _, addrList := range addrLists {
l, err := readAddressList(dec, options)
if err != nil {
return nil, fmt.Errorf("in %v: %v", addrList.name, err)
} else if !dec.ExpectSP() {
return nil, dec.Err()
}
*addrList.out = l
}
var inReplyTo, messageID string
if !dec.ExpectNString(&inReplyTo) || !dec.ExpectSP() || !dec.ExpectNString(&messageID) {
return nil, dec.Err()
}
// TODO: handle errors
envelope.InReplyTo, _ = parseMsgIDList(inReplyTo)
envelope.MessageID, _ = parseMsgID(messageID)
if !dec.ExpectSpecial(')') {
return nil, dec.Err()
}
return &envelope, nil
}
func readAddressList(dec *imapwire.Decoder, options *Options) ([]imap.Address, error) {
var l []imap.Address
err := dec.ExpectNList(func() error {
addr, err := readAddress(dec, options)
if err != nil {
return err
}
l = append(l, *addr)
return nil
})
return l, err
}
func readAddress(dec *imapwire.Decoder, options *Options) (*imap.Address, error) {
var (
addr imap.Address
name string
obsRoute string
)
ok := dec.ExpectSpecial('(') &&
dec.ExpectNString(&name) && dec.ExpectSP() &&
dec.ExpectNString(&obsRoute) && dec.ExpectSP() &&
dec.ExpectNString(&addr.Mailbox) && dec.ExpectSP() &&
dec.ExpectNString(&addr.Host) && dec.ExpectSpecial(')')
if !ok {
return nil, fmt.Errorf("in address: %v", dec.Err())
}
// TODO: handle error
addr.Name, _ = options.decodeText(name)
return &addr, nil
}
func parseMsgID(s string) (string, error) {
var h mail.Header
h.Set("Message-Id", s)
return h.MessageID()
}
func parseMsgIDList(s string) ([]string, error) {
var h mail.Header
h.Set("In-Reply-To", s)
return h.MsgIDList("In-Reply-To")
}
func readBody(dec *imapwire.Decoder, options *Options) (imap.BodyStructure, error) {
if !dec.ExpectSpecial('(') {
return nil, dec.Err()
}
var (
mediaType string
token string
bs imap.BodyStructure
err error
)
if dec.String(&mediaType) {
token = "body-type-1part"
bs, err = readBodyType1part(dec, mediaType, options)
} else {
token = "body-type-mpart"
bs, err = readBodyTypeMpart(dec, options)
}
if err != nil {
return nil, fmt.Errorf("in %v: %v", token, err)
}
for dec.SP() {
if !dec.DiscardValue() {
return nil, dec.Err()
}
}
if !dec.ExpectSpecial(')') {
return nil, dec.Err()
}
return bs, nil
}
func readBodyType1part(dec *imapwire.Decoder, typ string, options *Options) (*imap.BodyStructureSinglePart, error) {
bs := imap.BodyStructureSinglePart{Type: typ}
if !dec.ExpectSP() || !dec.ExpectString(&bs.Subtype) || !dec.ExpectSP() {
return nil, dec.Err()
}
var err error
bs.Params, err = readBodyFldParam(dec, options)
if err != nil {
return nil, err
}
var description string
if !dec.ExpectSP() || !dec.ExpectNString(&bs.ID) || !dec.ExpectSP() || !dec.ExpectNString(&description) || !dec.ExpectSP() || !dec.ExpectNString(&bs.Encoding) || !dec.ExpectSP() || !dec.ExpectBodyFldOctets(&bs.Size) {
return nil, dec.Err()
}
// Content-Transfer-Encoding should always be set, but some non-standard
// servers leave it NIL. Default to 7BIT.
if bs.Encoding == "" {
bs.Encoding = "7BIT"
}
// TODO: handle errors
bs.Description, _ = options.decodeText(description)
// Some servers don't include the extra fields for message and text
// (see https://github.com/emersion/go-imap/issues/557)
hasSP := dec.SP()
if !hasSP {
return &bs, nil
}
if strings.EqualFold(bs.Type, "message") && (strings.EqualFold(bs.Subtype, "rfc822") || strings.EqualFold(bs.Subtype, "global")) {
var msg imap.BodyStructureMessageRFC822
msg.Envelope, err = readEnvelope(dec, options)
if err != nil {
return nil, err
}
if !dec.ExpectSP() {
return nil, dec.Err()
}
msg.BodyStructure, err = readBody(dec, options)
if err != nil {
return nil, err
}
if !dec.ExpectSP() || !dec.ExpectNumber64(&msg.NumLines) {
return nil, dec.Err()
}
bs.MessageRFC822 = &msg
hasSP = false
} else if strings.EqualFold(bs.Type, "text") {
var text imap.BodyStructureText
if !dec.ExpectNumber64(&text.NumLines) {
return nil, dec.Err()
}
bs.Text = &text
hasSP = false
}
if !hasSP {
hasSP = dec.SP()
}
if hasSP {
bs.Extended, err = readBodyExt1part(dec, options)
if err != nil {
return nil, fmt.Errorf("in body-ext-1part: %v", err)
}
}
return &bs, nil
}
func readBodyExt1part(dec *imapwire.Decoder, options *Options) (*imap.BodyStructureSinglePartExt, error) {
var ext imap.BodyStructureSinglePartExt
var md5 string
if !dec.ExpectNString(&md5) {
return nil, dec.Err()
}
if !dec.SP() {
return &ext, nil
}
var err error
ext.Disposition, err = readBodyFldDsp(dec, options)
if err != nil {
return nil, fmt.Errorf("in body-fld-dsp: %v", err)
}
if !dec.SP() {
return &ext, nil
}
ext.Language, err = readBodyFldLang(dec)
if err != nil {
return nil, fmt.Errorf("in body-fld-lang: %v", err)
}
if !dec.SP() {
return &ext, nil
}
if !dec.ExpectNString(&ext.Location) {
return nil, dec.Err()
}
return &ext, nil
}
func readBodyTypeMpart(dec *imapwire.Decoder, options *Options) (*imap.BodyStructureMultiPart, error) {
var bs imap.BodyStructureMultiPart
for {
child, err := readBody(dec, options)
if err != nil {
return nil, err
}
bs.Children = append(bs.Children, child)
if dec.SP() && dec.String(&bs.Subtype) {
break
}
}
if dec.SP() {
var err error
bs.Extended, err = readBodyExtMpart(dec, options)
if err != nil {
return nil, fmt.Errorf("in body-ext-mpart: %v", err)
}
}
return &bs, nil
}
func readBodyExtMpart(dec *imapwire.Decoder, options *Options) (*imap.BodyStructureMultiPartExt, error) {
var ext imap.BodyStructureMultiPartExt
var err error
ext.Params, err = readBodyFldParam(dec, options)
if err != nil {
return nil, fmt.Errorf("in body-fld-param: %v", err)
}
if !dec.SP() {
return &ext, nil
}
ext.Disposition, err = readBodyFldDsp(dec, options)
if err != nil {
return nil, fmt.Errorf("in body-fld-dsp: %v", err)
}
if !dec.SP() {
return &ext, nil
}
ext.Language, err = readBodyFldLang(dec)
if err != nil {
return nil, fmt.Errorf("in body-fld-lang: %v", err)
}
if !dec.SP() {
return &ext, nil
}
if !dec.ExpectNString(&ext.Location) {
return nil, dec.Err()
}
return &ext, nil
}
func readBodyFldDsp(dec *imapwire.Decoder, options *Options) (*imap.BodyStructureDisposition, error) {
if !dec.Special('(') {