-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimap.c
659 lines (539 loc) · 14.6 KB
/
imap.c
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
#include <assert.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/x509_vfy.h>
#include <openssl/x509v3.h>
#include <string.h>
#include <sys/socket.h>
#include <syslog.h>
#include "channel.h"
#include "mbconfig.h"
#include "mbidled.h"
static char const NAMESPACE[] = "INBOX.";
struct imap_store {
struct channel *chan;
struct mbconfig_store *mb_store;
char *mailbox;
int list_mailboxes;
ev_timer timeout_watcher;
ev_io io_watcher;
enum state {
STATE_GROUND,
STATE_CONNECTING,
STATE_CONNECTED,
STATE_SSL_GROUND,
STATE_SSL_HANDSHAKING,
STATE_SSL_ESTABLISHED,
STATE_ESTABLISHED,
STATE_IMAP_GROUND,
STATE_IMAP_CAPABILITY,
STATE_IMAP_STARTTLS,
STATE_IMAP_LOGIN,
STATE_IMAP_LIST,
STATE_IMAP_EXAMINE,
STATE_IMAP_IDLE,
STATE_DISCONNECTED,
STATE_ERROR,
STATE_RESET,
} state;
enum {
CAP_IDLE = 1 << 0,
CAP_LOGINDISABLED = 1 << 1,
CAP_STARTTLS = 1 << 2,
} cap;
BIO *bio;
BIO *ssl_bio;
BIO *sink_bio;
int expected_tag;
int seq_num;
};
DEFINE_CHANNEL_STORE_LOGGER(imap, "IMAP")
static void do_poll(struct imap_store *store);
static void
io_cb(EV_P_ ev_io *w, int revents)
{
(void)revents;
struct imap_store *store = container_of(w, struct imap_store, io_watcher);
do_poll(store);
}
static void
update_io_interest(EV_P_ struct imap_store *store)
{
int events = EV_READ;
if (BIO_wpending(store->bio))
events |= EV_WRITE;
if (BIO_should_retry(store->bio) && BIO_should_io_special(store->bio))
events |= EV_WRITE;
if (events != (store->io_watcher.events & (EV_READ | EV_WRITE))) {
ev_io_stop(EV_A_ & store->io_watcher);
ev_io_modify(&store->io_watcher, events);
ev_io_start(EV_A_ & store->io_watcher);
}
}
static void
timeout_cb(EV_P_ ev_timer *w, int revents)
{
(void)revents;
struct imap_store *store = container_of(w, struct imap_store, timeout_watcher);
store->state = STATE_GROUND;
do_poll(store);
}
static void
imap_open_mailbox(struct channel *chan, struct mbconfig_store *mb_store, char const *mailbox)
{
int inbox = !strcmp(mailbox, "INBOX");
if (!mbconfig_patterns_test(&chan->mb_chan->patterns, mailbox)) {
channel_log(chan, LOG_DEBUG, "Mailbox [%s] not matched", mailbox);
/* INBOX must be always watced. */
if (!inbox)
return;
}
struct imap_store *store;
ASSERT(store = malloc(sizeof *store));
store->chan = chan;
store->mb_store = mb_store;
ASSERT(store->mailbox = strdup(mailbox));
store->list_mailboxes = inbox;
imap_log(store, LOG_INFO, "Watching");
ev_init(&store->io_watcher, io_cb);
ev_init(&store->timeout_watcher, timeout_cb);
store->state = STATE_GROUND;
do_poll(store);
}
void
imap_open_store(struct channel *chan, struct mbconfig_store *mb_store)
{
assert(mb_store->type == MBCONFIG_STORE_IMAP);
imap_open_mailbox(chan, mb_store, "INBOX");
}
static void
write_cmdf(struct imap_store *store, enum state next_state, char const *fmt, ...)
{
++store->seq_num;
BIO_printf(store->bio, "%" PRIu32 " ", store->seq_num);
va_list ap;
va_start(ap, fmt);
for (char const *from = fmt;;) {
char const *to = strchr(from, '%');
if (!to)
to = from + strlen(from);
int n = (int)(to - from);
BIO_write(store->bio, from, n);
if (!*to)
break;
char const *arg = va_arg(ap, char *);
switch (to[1]) {
case 's':
BIO_puts(store->bio, arg);
break;
case 'q':
for (char const *s = arg;;) {
size_t n = strcspn(s, "\"\\");
BIO_write(store->bio, s, n);
s += n;
if (!*s)
break;
BIO_write(store->bio, "\\", 1);
BIO_write(store->bio, s, 1);
s += 1;
}
break;
default:
abort();
}
from = to + 2;
}
va_end(ap);
BIO_write(store->bio, "\r\n", 2);
store->state = next_state;
store->expected_tag = store->seq_num;
}
static void
imap_notify_change(struct imap_store *store)
{
imap_log(store, LOG_DEBUG, "Changed");
channel_notify_change(store->chan, store->mb_store, store->mailbox);
}
static void
feed(struct imap_store *store, char *line)
{
imap_log(store, LOG_DEBUG, "S: %s", line);
if (*line == '*' || *line == '+') {
switch (store->state) {
case STATE_IMAP_GROUND:
if (strncmp(line, "* OK ", 5)) {
imap_log(store, LOG_ERR, "OK expected");
store->state = STATE_ERROR;
return;
}
write_cmdf(store, STATE_IMAP_CAPABILITY, "CAPABILITY");
return;
case STATE_IMAP_CAPABILITY:
if (strncmp(line, "* CAPABILITY ", 13))
return; /* Ignore. */
line += 12;
store->cap = 0;
if (strstr(line, " IDLE"))
store->cap |= CAP_IDLE;
if (strstr(line, " LOGINDISABLED"))
store->cap |= CAP_LOGINDISABLED;
if (strstr(line, " STARTTLS"))
store->cap |= CAP_STARTTLS;
return;
case STATE_IMAP_LIST:
if (strncmp(line, "* LIST ", 7))
return; /* Ignore. */
line += 7;
{
/* Simple and stupid. */
char const *mailbox = strstr(line, NAMESPACE);
if (mailbox) {
mailbox += sizeof NAMESPACE - 1;
imap_open_mailbox(store->chan, store->mb_store, mailbox);
}
}
return;
case STATE_IMAP_IDLE:
if (!('0' <= line[2] && line[2] <= '9'))
return; /* Ignore. */
imap_notify_change(store);
return;
default:
/* Ignore. */
return;
}
}
int line_tag = strtol(line, &line, 10);
if (line_tag != store->expected_tag) {
imap_log(store, LOG_ERR, "Received response with unknown tag %d", line_tag);
return;
}
if (memcmp(line, " OK ", 4)) {
imap_log(store, LOG_ERR, "OK expected");
store->state = STATE_ERROR;
return;
}
switch (store->state) {
case STATE_IMAP_CAPABILITY:
{
struct mbconfig_imap_account *mb_account = store->mb_store->imap_store->account;
if (!(store->cap & CAP_IDLE)) {
imap_log(store, LOG_ERR, "IDLE not supported");
store->state = STATE_ERROR;
return;
}
if (store->ssl_bio == NULL && mb_account->ssl == MBCONFIG_SSL_STARTTLS) {
if (!(store->cap & CAP_STARTTLS)) {
imap_log(store, LOG_ERR, "STARTTLS not supported");
store->state = STATE_ERROR;
return;
}
write_cmdf(store, STATE_IMAP_STARTTLS, "STARTTLS");
return;
}
if (store->cap & CAP_LOGINDISABLED) {
imap_log(store, LOG_ERR, "LOGIN disabled by the server");
store->state = STATE_ERROR;
return;
}
imap_log(store, LOG_DEBUG, "Logging in...");
if (!mb_account->login_auth) {
imap_log(store, LOG_ERR, "LOGIN disabled by the user");
store->state = STATE_ERROR;
return;
}
mbconfig_eval_cmd_option(&mb_account->user, mb_account->user_cmd);
mbconfig_eval_cmd_option(&mb_account->pass, mb_account->pass_cmd);
if (!mb_account->user || !mb_account->pass) {
imap_log(store, LOG_ERR, "Missing User and/or Pass");
store->state = STATE_ERROR;
return;
}
write_cmdf(
store,
STATE_IMAP_LOGIN,
"LOGIN \"%q\" \"%q\"",
mb_account->user,
mb_account->pass
);
break;
}
case STATE_IMAP_STARTTLS:
store->state = STATE_SSL_GROUND;
return;
case STATE_IMAP_LOGIN:
imap_log(store, LOG_NOTICE, "Logged in");
if (store->list_mailboxes) {
write_cmdf(store, STATE_IMAP_LIST, "LIST \"%q\" \"%q\"", NAMESPACE, "*");
break;
}
/* FALLTHROUGH */
case STATE_IMAP_LIST:
store->list_mailboxes = 0;
write_cmdf(
store,
STATE_IMAP_EXAMINE,
"EXAMINE \"%q%q\"",
!strcmp(store->mailbox, "INBOX") ? "" : NAMESPACE,
store->mailbox
);
break;
case STATE_IMAP_EXAMINE:
write_cmdf(store, STATE_IMAP_IDLE, "IDLE");
/* Bring other side up-to-date. */
imap_notify_change(store);
break;
default:
/* Ignore unneeded completion responses. */
break;
}
}
static BIO *
create_source_bio(struct imap_store const *store)
{
(void)store;
return BIO_new(BIO_f_buffer());
}
static BIO *
create_ssl_bio(struct imap_store const *store)
{
struct mbconfig_imap_account const *mb_account = store->mb_store->imap_store->account;
SSL_CTX *ctx = NULL;
BIO *bio = NULL;
if ((ctx = SSL_CTX_new(TLS_client_method())) == NULL ||
(mb_account->system_certs && SSL_CTX_set_default_verify_paths(ctx) != 1) ||
(mb_account->cert_file != NULL &&
X509_STORE_load_locations(SSL_CTX_get_cert_store(ctx), mb_account->cert_file, NULL) !=
1))
goto fail;
/* Continue handshake even if certificate seems invalid.
* Errored certificate will be checked against certificates
* explicitly trusted by the user. */
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
SSL_CTX_set_options(ctx, mb_account->ssl_versions);
SSL *ssl = NULL;
if ((bio = BIO_new_ssl(ctx, 1 /* Client. */)) == NULL || BIO_get_ssl(bio, &ssl) != 1 ||
(mb_account->host != NULL && SSL_set1_host(ssl, mb_account->host) != 1) ||
(mb_account->ciphers != NULL && SSL_set_cipher_list(ssl, mb_account->ciphers) != 1) ||
(mb_account->host != NULL && SSL_set_tlsext_host_name(ssl, mb_account->host) != 1))
goto fail;
SSL_set_mode(
ssl,
SSL_MODE_AUTO_RETRY | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
SSL_MODE_ENABLE_PARTIAL_WRITE
);
SSL_CTX_free(ctx);
return bio;
fail:
SSL_CTX_free(ctx);
BIO_free(bio);
return NULL;
}
static BIO *
create_tunnel_bio(struct imap_store const *store, char const *cmd)
{
BIO *bio = NULL;
int pair[2];
int type = SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
if (socketpair(PF_UNIX, type, 0, pair) < 0)
goto fail;
if (!fork()) {
if (dup2(pair[0], STDIN_FILENO) < 0 || dup2(pair[0], STDOUT_FILENO) < 0 ||
execl("/bin/sh", "sh", "-c", cmd, NULL) < 0)
imap_log(store, LOG_ERR, "exec() failed: %s", strerror(errno));
_exit(EXIT_FAILURE);
}
close(pair[0]);
if ((bio = BIO_new_fd(pair[1], 1 /* Close. */)) == NULL || BIO_set_nbio(bio, 1) != 1)
goto fail;
return bio;
fail:
BIO_free(bio);
return NULL;
}
static BIO *
create_connect_bio(struct imap_store const *store)
{
struct mbconfig_imap_account const *mb_account = store->mb_store->imap_store->account;
BIO *bio = NULL;
char const *port = mb_account->port;
if (port == NULL) {
if (mb_account->ssl == MBCONFIG_SSL_IMAPS)
port = "993";
else
port = "143";
}
if ((bio = BIO_new(BIO_s_connect())) == NULL || BIO_set_nbio(bio, 1) != 1 ||
BIO_set_conn_hostname(bio, mb_account->host) != 1 || BIO_set_conn_port(bio, port) != 1)
goto fail;
return bio;
fail:
BIO_free(bio);
return NULL;
}
static BIO *
create_sink_bio(struct imap_store *store)
{
struct mbconfig_imap_account const *mb_account = store->mb_store->imap_store->account;
if (mb_account->tunnel_cmd != NULL)
return create_tunnel_bio(store, mb_account->tunnel_cmd);
else
return create_connect_bio(store);
}
static void
do_poll(struct imap_store *store)
{
struct channel *chan = store->chan;
#ifdef EV_MULTIPLICITY
struct ev_loop *loop = chan->loop;
#endif
for (int rc;;)
switch (store->state) {
case STATE_GROUND:
imap_log(store, LOG_DEBUG, "Connecting...");
store->bio = create_source_bio(store);
if (store->bio == NULL) {
store->state = STATE_ERROR;
break;
}
store->sink_bio = create_sink_bio(store);
if (store->sink_bio == NULL) {
store->state = STATE_ERROR;
break;
}
BIO_push(store->bio, store->sink_bio);
store->ssl_bio = NULL;
store->expected_tag = 0;
store->seq_num = 0;
store->state = STATE_CONNECTING;
break;
case STATE_CONNECTING:
if ((rc = BIO_do_connect(store->bio)) != 1) {
if (!BIO_should_retry(store->bio)) {
store->state = STATE_ERROR;
break;
}
}
if (!ev_is_active(&store->io_watcher)) {
int fd = BIO_get_fd(store->bio, NULL);
ev_io_set(&store->io_watcher, fd, EV_READ | EV_WRITE);
ev_io_start(EV_A_ & store->io_watcher);
}
if (rc != 1) {
update_io_interest(EV_A_ store);
return;
}
store->state = STATE_CONNECTED;
break;
case STATE_CONNECTED:
imap_log(store, LOG_DEBUG, "Connected");
if (store->mb_store->imap_store->account->ssl == MBCONFIG_SSL_IMAPS)
store->state = STATE_SSL_GROUND;
else
store->state = STATE_ESTABLISHED;
break;
case STATE_SSL_GROUND:
imap_log(store, LOG_DEBUG, "Performing SSL handshake...");
store->ssl_bio = create_ssl_bio(store);
if (store->ssl_bio == NULL) {
store->state = STATE_ERROR;
break;
}
BIO_pop(store->sink_bio);
BIO_push(store->bio, store->ssl_bio);
BIO_push(store->bio, store->sink_bio);
store->state = STATE_SSL_HANDSHAKING;
break;
case STATE_SSL_HANDSHAKING:
if (BIO_do_handshake(store->bio) != 1) {
if (BIO_should_retry(store->bio)) {
update_io_interest(EV_A_ store);
return;
}
store->state = STATE_ERROR;
break;
}
store->state = STATE_SSL_ESTABLISHED;
break;
case STATE_SSL_ESTABLISHED:
{
SSL *ssl;
X509 *untrusted_cert;
int err;
BIO_get_ssl(store->bio, &ssl);
if ((untrusted_cert = SSL_get_peer_certificate(ssl)) == NULL) {
imap_log(store, LOG_ERR, "No certificate");
store->state = STATE_ERROR;
break;
} else if ((err = SSL_get_verify_result(ssl)) != X509_V_OK) {
SSL_CTX *ctx = SSL_get_SSL_CTX(ssl);
X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx);
STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(cert_store);
for (int i = 0; i < sk_X509_OBJECT_num(objs); ++i) {
X509_OBJECT *obj = sk_X509_OBJECT_value(objs, i);
X509 *trusted_cert = X509_OBJECT_get0_X509(obj);
if (!X509_cmp(untrusted_cert, trusted_cert))
goto cert_trusted;
}
imap_log(
store,
LOG_ERR,
"Certificate verification failed: %s",
X509_verify_cert_error_string(err)
);
if (opt_verbose)
X509_print_fp(stdout, untrusted_cert);
store->state = STATE_ERROR;
break;
cert_trusted:;
}
}
imap_log(store, LOG_DEBUG, "SSL connection established");
if (store->mb_store->imap_store->account->ssl == MBCONFIG_SSL_STARTTLS)
write_cmdf(store, STATE_IMAP_CAPABILITY, "CAPABILITY");
else
store->state = STATE_ESTABLISHED;
break;
case STATE_ESTABLISHED:
imap_log(store, LOG_DEBUG, "Connection established");
store->state = STATE_IMAP_GROUND;
break;
case STATE_DISCONNECTED:
imap_log(store, LOG_ERR, "Disconnected");
ev_timer_stop(EV_A_ & store->timeout_watcher);
ev_timer_set(&store->timeout_watcher, 3, 0);
ev_timer_start(EV_A_ & store->timeout_watcher);
store->state = STATE_RESET;
break;
case STATE_ERROR:
imap_log(store, LOG_ERR, "Error");
ERR_print_errors_fp(stderr);
ev_timer_stop(EV_A_ & store->timeout_watcher);
ev_timer_set(&store->timeout_watcher, 5 * 60, 0);
ev_timer_start(EV_A_ & store->timeout_watcher);
store->state = STATE_RESET;
break;
case STATE_RESET:
BIO_free_all(store->bio);
store->bio = NULL;
ev_io_stop(EV_A_ & store->io_watcher);
return;
default:
{
char line[4096];
rc = BIO_gets(store->bio, line, sizeof line);
if (2 <= rc) {
line[rc - 2] = '\0';
feed(store, line);
} else if (BIO_should_retry(store->bio)) {
BIO_flush(store->bio);
update_io_interest(EV_A_ store);
return;
} else {
store->state = STATE_DISCONNECTED;
}
break;
}
}
}