forked from NerdGGuy/go-imap
-
Notifications
You must be signed in to change notification settings - Fork 2
/
imap.go
358 lines (310 loc) · 7.14 KB
/
imap.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
package imap
import (
"errors"
"fmt"
"io"
"strings"
"sync"
)
func check(err error) {
if err != nil {
panic(err)
}
}
type IMAP struct {
// Client thread.
nextTag int
Unsolicited chan interface{}
// Background thread.
r *reader
w io.Writer
pendingLock sync.Mutex
pendingTag tag
pendingChan chan interface{}
}
func New(r io.Reader, w io.Writer) *IMAP {
return &IMAP{
r: &reader{newParser(r)},
w: w,
}
}
func (imap *IMAP) Start() (string, error) {
tag, r, err := imap.r.readResponse()
if err != nil {
return "", err
}
if tag != untagged {
return "", fmt.Errorf("expected untagged server hello. got %q", tag)
}
resp := r.(*ResponseStatus)
if resp.Status != OK {
return "", &IMAPError{resp.Status, resp.Text}
}
go func() {
defer func() {
if err := recover(); err != nil {
imap.pendingLock.Lock()
imap.pendingTag = 0
close(imap.pendingChan)
imap.pendingLock.Unlock()
}
}()
imap.readLoop()
}()
return resp.Text, nil
}
func (imap *IMAP) Send(ch chan interface{}, format string, args ...interface{}) error {
tag := tag(imap.nextTag)
imap.nextTag++
toSend := []byte(fmt.Sprintf("a%d %s\r\n", int(tag), fmt.Sprintf(format, args...)))
if ch != nil {
imap.pendingLock.Lock()
imap.pendingTag = tag
imap.pendingChan = ch
imap.pendingLock.Unlock()
}
_, err := imap.w.Write(toSend)
return err
}
func (imap *IMAP) SendSync(format string, args ...interface{}) (*ResponseStatus, error) {
ch := make(chan interface{}, 1)
err := imap.Send(ch, format, args...)
if err != nil {
return nil, err
}
var response *ResponseStatus
extra := make([]interface{}, 0)
L:
for {
r, open := <-ch
if !open {
return nil, errors.New("read failure")
}
switch r := r.(type) {
case *ResponseStatus:
response = r
break L
default:
extra = append(extra, r)
}
}
if len(extra) > 0 {
response.Extra = extra
}
// XXX callers discard unsolicited responses if this is not OK
if response.Status != OK {
return response, &IMAPError{response.Status, response.Text}
}
return response, nil
}
func (imap *IMAP) Auth(user string, pass string) (string, []string, error) {
resp, err := imap.SendSync("LOGIN %s %s", user, pass)
if err != nil {
return "", nil, err
}
var caps []string
for _, extra := range resp.Extra {
switch extra := extra.(type) {
case *ResponseCapabilities:
caps = extra.Capabilities
default:
imap.Unsolicited <- extra
}
}
return resp.Text, caps, nil
}
func (imap *IMAP) Capability() ([]string, error) {
resp, err := imap.SendSync("CAPABILITY")
if err != nil {
return nil, err
}
for _, extra := range resp.Extra {
switch extra := extra.(type) {
case *ResponseCapabilities:
return extra.Capabilities, nil
}
}
panic("Didn't get CAPABILITY reply from the server!")
}
func (imap *IMAP) Idle() (chan interface{}, error) {
ch := make(chan interface{})
err := imap.Send(ch, "IDLE")
return ch, err
}
func (imap *IMAP) Done() (error) {
_, err := imap.w.Write([]byte("DONE\r\n"))
return err
}
func quote(in string) string {
if strings.IndexAny(in, "\r\n") >= 0 {
panic("invalid characters in string to quote")
}
return "\"" + in + "\""
}
func (imap *IMAP) List(reference string, name string) ([]*ResponseList, error) {
/* Responses: untagged responses: LIST */
response, err := imap.SendSync("LIST %s %s", quote(reference), quote(name))
if err != nil {
return nil, err
}
lists := make([]*ResponseList, 0)
for _, extra := range response.Extra {
if list, ok := extra.(*ResponseList); ok {
lists = append(lists, list)
} else {
imap.Unsolicited <- extra
}
}
return lists, nil
}
// ResponseExamine contains the response to examining a mailbox.
type ResponseExamine struct {
Flags []string
Exists int
Recent int
PermanentFlags []string
UIDValidity int
UIDNext int
}
func (imap *IMAP) Examine(mailbox string) (*ResponseExamine, error) {
/*
Responses: REQUIRED untagged responses: FLAGS, EXISTS, RECENT
REQUIRED OK untagged responses: UNSEEN, PERMANENTFLAGS,
UIDNEXT, UIDVALIDITY
*/
resp, err := imap.SendSync("EXAMINE %s", quote(mailbox))
if err != nil {
return nil, err
}
r := &ResponseExamine{}
for _, extra := range resp.Extra {
switch extra := extra.(type) {
case (*ResponseFlags):
r.Flags = extra.Flags
case (*ResponseExists):
r.Exists = extra.Count
case (*ResponseRecent):
r.Recent = extra.Count
// XXX unseen
case (*ResponsePermanentFlags):
r.PermanentFlags = extra.Flags
case (*ResponseUIDNext):
value := extra.Value
r.UIDNext = value
case (*ResponseUIDValidity):
value := extra.Value
r.UIDValidity = value
default:
imap.Unsolicited <- extra
}
}
return r, nil
}
func formatFetch(sequence string, fields []string) string {
var fieldsStr string
if len(fields) == 1 {
fieldsStr = fields[0]
} else {
fieldsStr = "(" + strings.Join(fields, " ") + ")"
}
return fmt.Sprintf("FETCH %s %s", sequence, fieldsStr)
}
func (imap *IMAP) Fetch(sequence string, fields []string) ([]*ResponseFetch, error) {
resp, err := imap.SendSync("%s", formatFetch(sequence, fields))
if err != nil {
return nil, err
}
lists := make([]*ResponseFetch, 0)
for _, extra := range resp.Extra {
if list, ok := extra.(*ResponseFetch); ok {
lists = append(lists, list)
} else {
imap.Unsolicited <- extra
}
}
return lists, nil
}
func (imap *IMAP) FetchAsync(sequence string, fields []string) (chan interface{}, error) {
ch := make(chan interface{})
err := imap.Send(ch, formatFetch(sequence, fields))
if err != nil {
return nil, err
}
// Stream all responses to this message into outChan, and everything
// else into unsolicited.
outChan := make(chan interface{})
go func() {
for {
r := <-ch
switch r := r.(type) {
case *ResponseFetch:
outChan <- r
case *ResponseStatus:
outChan <- r
return
default:
imap.Unsolicited <- r
}
}
}()
return outChan, nil
}
// Repeatedly reads messages off the connection and dispatches them.
func (imap *IMAP) readLoop() error {
var msgChan chan interface{}
for {
tag, r, err := imap.r.readResponse()
check(err)
if msgChan == nil {
imap.pendingLock.Lock()
msgChan = imap.pendingChan
imap.pendingLock.Unlock()
}
if tag == untagged {
if msgChan != nil {
msgChan <- r
} else {
imap.Unsolicited <- r
}
} else {
resp := r.(*ResponseStatus)
imap.pendingLock.Lock()
if imap.pendingTag != tag {
return fmt.Errorf("expected response tag %s, got %s", imap.pendingTag, tag)
}
imap.pendingChan = nil
imap.pendingLock.Unlock()
msgChan <- resp
msgChan = nil
}
}
panic("not reached")
}
type Address struct {
Name, Source, Address string
}
func (a *Address) fromSexp(s []sexp) {
if name := nilOrString(s[0]); name != nil {
a.Name = *name
}
if source := nilOrString(s[1]); source != nil {
a.Source = *source
}
mbox := nilOrString(s[2])
host := nilOrString(s[3])
if mbox != nil && host != nil {
address := *mbox + "@" + *host
a.Address = address
}
}
func addressListFromSexp(s sexp) []Address {
if s == nil {
return nil
}
saddrs := s.([]sexp)
addrs := make([]Address, len(saddrs))
for i, s := range saddrs {
addrs[i].fromSexp(s.([]sexp))
}
return addrs
}