aboutsummaryrefslogtreecommitdiffstats
path: root/worker/imap/worker.go
blob: 7ef759d43295c657b1986227e117b07d3cae92b1 (plain) (blame)
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
package imap

import (
	"fmt"
	"net/url"
	"time"

	"github.com/emersion/go-imap"
	sortthread "github.com/emersion/go-imap-sortthread"
	"github.com/emersion/go-imap/client"
	"github.com/pkg/errors"
	"github.com/syndtr/goleveldb/leveldb"

	"git.sr.ht/~rjarry/aerc/lib"
	"git.sr.ht/~rjarry/aerc/models"
	"git.sr.ht/~rjarry/aerc/worker/handlers"
	"git.sr.ht/~rjarry/aerc/worker/imap/extensions"
	"git.sr.ht/~rjarry/aerc/worker/middleware"
	"git.sr.ht/~rjarry/aerc/worker/types"
)

func init() {
	handlers.RegisterWorkerFactory("imap", NewIMAPWorker)
	handlers.RegisterWorkerFactory("imaps", NewIMAPWorker)
}

var (
	errUnsupported      = fmt.Errorf("unsupported command")
	errClientNotReady   = fmt.Errorf("client not ready")
	errNotConnected     = fmt.Errorf("not connected")
	errAlreadyConnected = fmt.Errorf("already connected")
)

type imapClient struct {
	*client.Client
	thread     *sortthread.ThreadClient
	sort       *sortthread.SortClient
	liststatus *extensions.ListStatusClient
}

type imapConfig struct {
	name              string
	scheme            string
	insecure          bool
	addr              string
	user              *url.Userinfo
	headers           []string
	headersExclude    []string
	folders           []string
	oauthBearer       lib.OAuthBearer
	xoauth2           lib.Xoauth2
	idle_timeout      time.Duration
	idle_debounce     time.Duration
	reconnect_maxwait time.Duration
	// tcp connection parameters
	connection_timeout time.Duration
	keepalive_period   time.Duration
	keepalive_probes   int
	keepalive_interval int
	cacheEnabled       bool
	cacheMaxAge        time.Duration
	useXGMEXT          bool
}

type IMAPWorker struct {
	config imapConfig

	client    *imapClient
	selected  *imap.MailboxStatus
	updates   chan client.Update
	worker    types.WorkerInteractor
	seqMap    SeqMap
	delimiter string

	idler    *idler
	observer *observer
	cache    *leveldb.DB

	caps *models.Capabilities

	threadAlgorithm sortthread.ThreadAlgorithm
	liststatus      bool
}

func NewIMAPWorker(worker *types.Worker) (types.Backend, error) {
	return &IMAPWorker{
		updates:  make(chan client.Update, 50),
		worker:   worker,
		selected: &imap.MailboxStatus{},
		idler:    newIdler(imapConfig{}, worker),
		observer: newObserver(imapConfig{}, worker),
		caps:     &models.Capabilities{},
	}, nil
}

func (w *IMAPWorker) newClient(c *client.Client) {
	c.Updates = w.updates
	w.client = &imapClient{
		c,
		sortthread.NewThreadClient(c),
		sortthread.NewSortClient(c),
		extensions.NewListStatusClient(c),
	}
	w.idler.SetClient(w.client)
	w.observer.SetClient(w.client)
	sort, err := w.client.sort.SupportSort()
	if err == nil && sort {
		w.caps.Sort = true
		w.worker.Debugf("Server Capability found: Sort")
	}
	for _, alg := range []sortthread.ThreadAlgorithm{sortthread.References, sortthread.OrderedSubject} {
		ok, err := w.client.Support(fmt.Sprintf("THREAD=%s", string(alg)))
		if err == nil && ok {
			w.threadAlgorithm = alg
			w.caps.Thread = true
			w.worker.Debugf("Server Capability found: Thread (algorithm: %s)", string(alg))
			break
		}
	}
	lStatus, err := w.client.liststatus.SupportListStatus()
	if err == nil && lStatus {
		w.liststatus = true
		w.worker.Debugf("Server Capability found: LIST-STATUS")
	}
	xgmext, err := w.client.Support("X-GM-EXT-1")
	if err == nil && xgmext && w.config.useXGMEXT {
		w.worker.Debugf("Server Capability found: X-GM-EXT-1")
		w.worker = middleware.NewGmailWorker(w.worker, w.client.Client, w.idler)
	}
	if err == nil && !xgmext && w.config.useXGMEXT {
		w.worker.Infof("X-GM-EXT-1 requested, but it is not supported")
	}
}

func (w *IMAPWorker) handleMessage(msg types.WorkerMessage) error {
	defer func() {
		w.idler.Start()
	}()
	if err := w.idler.Stop(); err != nil {
		return err
	}

	var reterr error // will be returned at the end, needed to support idle

	// when client is nil allow only certain messages to be handled
	if w.client == nil {
		switch msg.(type) {
		case *types.Connect, *types.Reconnect, *types.Disconnect, *types.Configure:
		default:
			return errClientNotReady
		}
	}

	// set connection timeout for calls to imap server
	if w.client != nil {
		w.client.Timeout = w.config.connection_timeout
	}

	switch msg := msg.(type) {
	case *types.Unsupported:
		// No-op
	case *types.Configure:
		reterr = w.handleConfigure(msg)
	case *types.Connect:
		if w.client != nil && w.client.State() == imap.SelectedState {
			if !w.observer.AutoReconnect() {
				w.observer.SetAutoReconnect(true)
				w.observer.EmitIfNotConnected()
			}
			reterr = errAlreadyConnected
			break
		}

		w.observer.SetAutoReconnect(true)
		c, err := w.connect()
		if err != nil {
			w.observer.EmitIfNotConnected()
			reterr = err
			break
		}

		w.newClient(c)

		w.worker.PostMessage(&types.Done{Message: types.RespondTo(msg)}, nil)
	case *types.Reconnect:
		if !w.observer.AutoReconnect() {
			reterr = fmt.Errorf("auto-reconnect is disabled; run connect to enable it")
			break
		}
		c, err := w.connect()
		if err != nil {
			errReconnect := w.observer.DelayedReconnect()
			reterr = errors.Wrap(errReconnect, err.Error())
			break
		}

		w.newClient(c)

		w.worker.PostMessage(&types.Done{Message: types.RespondTo(msg)}, nil)
	case *types.Disconnect:
		w.observer.SetAutoReconnect(false)
		w.observer.Stop()
		if w.client == nil || w.client.State() != imap.SelectedState {
			reterr = errNotConnected
			break
		}

		if err := w.client.Logout(); err != nil {
			reterr = err
			break
		}
		w.worker.PostMessage(&types.Done{Message: types.RespondTo(msg)}, nil)
	case *types.ListDirectories:
		w.handleListDirectories(msg)
	case *types.OpenDirectory:
		w.handleOpenDirectory(msg)
	case *types.FetchDirectoryContents:
		w.handleFetchDirectoryContents(msg)
	case *types.FetchDirectoryThreaded:
		w.handleDirectoryThreaded(msg)
	case *types.CreateDirectory:
		w.handleCreateDirectory(msg)
	case *types.RemoveDirectory:
		w.handleRemoveDirectory(msg)
	case *types.FetchMessageHeaders:
		w.handleFetchMessageHeaders(msg)
	case *types.FetchMessageBodyPart:
		w.handleFetchMessageBodyPart(msg)
	case *types.FetchFullMessages:
		w.handleFetchFullMessages(msg)
	case *types.FetchMessageFlags:
		w.handleFetchMessageFlags(msg)
	case *types.DeleteMessages:
		w.handleDeleteMessages(msg)
	case *types.FlagMessages:
		w.handleFlagMessages(msg)
	case *types.AnsweredMessages:
		w.handleAnsweredMessages(msg)
	case *types.CopyMessages:
		w.handleCopyMessages(msg)
	case *types.MoveMessages:
		w.handleMoveMessages(msg)
	case *types.AppendMessage:
		w.handleAppendMessage(msg)
	case *types.SearchDirectory:
		w.handleSearchDirectory(msg)
	case *types.CheckMail:
		w.handleCheckMailMessage(msg)
	default:
		reterr = errUnsupported
	}

	// we don't want idle to timeout, so set timeout to zero
	if w.client != nil {
		w.client.Timeout = 0
	}

	return reterr
}

func (w *IMAPWorker) handleImapUpdate(update client.Update) {
	w.worker.Tracef("(= %T", update)
	switch update := update.(type) {
	case *client.MailboxUpdate:
		w.worker.PostAction(&types.CheckMail{
			Directories: []string{update.Mailbox.Name},
		}, nil)
	case *client.MessageUpdate:
		msg := update.Message
		if msg.Uid == 0 {
			if uid, found := w.seqMap.Get(msg.SeqNum); !found {
				w.worker.Errorf("MessageUpdate unknown seqnum: %d", msg.SeqNum)
				return
			} else {
				msg.Uid = uid
			}
		}
		if int(msg.SeqNum) > w.seqMap.Size() {
			w.seqMap.Put(msg.Uid)
		}
		w.worker.PostMessage(&types.MessageInfo{
			Info: &models.MessageInfo{
				BodyStructure: translateBodyStructure(msg.BodyStructure),
				Envelope:      translateEnvelope(msg.Envelope),
				Flags:         translateImapFlags(msg.Flags),
				InternalDate:  msg.InternalDate,
				Uid:           msg.Uid,
			},
		}, nil)
	case *client.ExpungeUpdate:
		if uid, found := w.seqMap.Pop(update.SeqNum); !found {
			w.worker.Errorf("ExpungeUpdate unknown seqnum: %d", update.SeqNum)
		} else {
			w.worker.PostMessage(&types.MessagesDeleted{
				Uids: []uint32{uid},
			}, nil)
		}
	}
}

func (w *IMAPWorker) Run() {
	for {
		select {
		case msg := <-w.worker.Actions():
			msg = w.worker.ProcessAction(msg)

			if err := w.handleMessage(msg); errors.Is(err, errUnsupported) {
				w.worker.PostMessage(&types.Unsupported{
					Message: types.RespondTo(msg),
				}, nil)
			} else if err != nil {
				w.worker.PostMessage(&types.Error{
					Message: types.RespondTo(msg),
					Error:   err,
				}, nil)
			}

		case update := <-w.updates:
			w.handleImapUpdate(update)
		}
	}
}

func (w *IMAPWorker) Capabilities() *models.Capabilities {
	return w.caps
}

func (w *IMAPWorker) PathSeparator() string {
	if w.delimiter == "" {
		return "/"
	}
	return w.delimiter
}