-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimap.c
executable file
·3610 lines (3277 loc) · 113 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
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
/*
* evergreen -- online only terminal mail user agent
*
* Copyright (C) 2024, Naveen Albert
*
* Naveen Albert <[email protected]>
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief IMAP protocol operations
*
* \author Naveen Albert <[email protected]>
*/
#include "evergreen.h"
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <poll.h>
#include <search.h>
#include <libetpan/libetpan.h>
/* Smartly rebuilds the mailboxes array using existing data, for massive performance boost */
#define OPTIMIZE_CREATE_DELETE_RENAME_OPERATIONS
/* Uncomment to debug mailboxes merge when OPTIMIZE_CREATE_DELETE_RENAME_OPERATIONS is defined */
/* #define DEBUG_MERGE */
/* Uncomment to debug folder name sorting */
/* #define DEBUG_FOLDER_ORDER */
/* Uncomment to run tests on startup */
/* #define TEST_MODE */
static inline void free_mailbox_keywords(struct mailbox *mbox)
{
int i;
for (i = 0; i < mbox->num_keywords && mbox->keywords[i]; i++) {
free(mbox->keywords[i]);
mbox->keywords[i] = NULL;
}
}
static void free_mailboxes(struct mailbox *mailboxes, int num_mailboxes)
{
int i;
for (i = 0; i < num_mailboxes; i++) {
free_mailbox_keywords(&mailboxes[i]);
free_if(mailboxes[i].name);
free_if(mailboxes[i].display);
}
free(mailboxes);
}
static void cleanup_mailboxes(struct client *client)
{
/* Free mailbox structures */
if (client->mailboxes) {
free_mailboxes(client->mailboxes, client->num_mailboxes);
client->mailboxes = NULL;
}
}
void client_destroy(struct client *client)
{
if (client->idling) {
/* If we're still idling at exit time, stop */
client_idle_stop(client);
}
mailimap_logout(client->imap);
mailimap_free(client->imap);
cleanup_mailboxes(client);
}
static int client_load_capabilities(struct client *client)
{
struct mailimap_capability_data *capdata;
int res = mailimap_capability(client->imap, &capdata);
if (MAILIMAP_ERROR(res)) {
return -1;
}
/* Now that we've called mailimap_capability, libetpan is aware of what capabilities are available. */
mailimap_capability_data_free(capdata);
/* Be nice, and identify ourselves, if possible */
if (mailimap_has_id(client->imap)) {
res = mailimap_custom_command(client->imap, "ID (\"name\" \"evergreen (libetpan)\" \"version\" \"" EVERGREEN_VERSION "\")");
}
#define SET_CAPABILITY(flag, res) if ((res)) { client->capabilities |= flag; }
SET_CAPABILITY(IMAP_CAPABILITY_IDLE, mailimap_has_idle(client->imap));
SET_CAPABILITY(IMAP_CAPABILITY_MOVE, mailimap_has_extension(client->imap, "MOVE"));
SET_CAPABILITY(IMAP_CAPABILITY_SORT, mailimap_has_sort(client->imap));
SET_CAPABILITY(IMAP_CAPABILITY_THREAD_REFERENCES, mailimap_has_extension(client->imap, "THREAD=REFERENCES"));
SET_CAPABILITY(IMAP_CAPABILITY_STATUS_SIZE, mailimap_has_extension(client->imap, "STATUS=SIZE"));
SET_CAPABILITY(IMAP_CAPABILITY_LIST_STATUS, mailimap_has_extension(client->imap, "LIST-STATUS"));
SET_CAPABILITY(IMAP_CAPABILITY_NOTIFY, mailimap_has_extension(client->imap, "NOTIFY"));
SET_CAPABILITY(IMAP_CAPABILITY_UNSELECT, mailimap_has_extension(client->imap, "UNSELECT"));
SET_CAPABILITY(IMAP_CAPABILITY_QUOTA, mailimap_has_quota(client->imap));
#undef SET_CAPABILITY
return res;
}
int client_connect(struct client *client, struct config *config)
{
int res;
struct mailimap *imap = mailimap_new(0, NULL);
if (!imap) {
client_error("Failed to create IMAP session");
return -1;
}
client->imap = imap;
client_status("Connecting to %s:%d", config->imap_hostname, config->imap_port);
mailimap_set_timeout(imap, 15); /* If the IMAP server hasn't responded by now, I doubt it ever will */
if (config->imap_security == SECURITY_TLS) {
res = mailimap_ssl_connect(imap, config->imap_hostname, config->imap_port);
} else {
res = mailimap_socket_connect(imap, config->imap_hostname, config->imap_port);
}
if (MAILIMAP_ERROR(res)) {
client_error("Failed to establish IMAP session to %s:%d (%s)", config->imap_hostname, config->imap_port, maildriver_strerror(res));
mailimap_free(client->imap);
return -1;
}
/* Timeout needs to be sufficiently large... e.g. FETCH 1:* (SIZE) can take quite a few seconds on large mailboxes. */
mailimap_set_timeout(imap, 60); /* If the IMAP server hasn't responded by now, I doubt it ever will */
if (client_load_capabilities(client)) {
mailimap_free(client->imap);
return -1;
}
return 0;
}
int client_login(struct client *client, struct config *config)
{
int res;
client_status("Authenticating to IMAP server");
/* Authenticate using LOGIN */
res = mailimap_login(client->imap, config->imap_username, config->imap_password);
explicit_bzero(config->imap_password, sizeof(config->imap_password)); /* Zero the password out from memory */
if (res) {
client_error("IMAP login failed: %s", config->imap_username);
return -1;
}
/* Save the file descriptor, for IDLE */
client->imapfd = mailimap_idle_get_fd(client->imap);
/* Some servers only advertise certain capabilities after authenticated, so load again. */
return client_load_capabilities(client);
}
static inline char *find_mailbox_response_line(char *restrict s, const char *cmd, const char *mb, int *skiplenptr)
{
char *tmp;
int skiplen;
char findbuf[64];
skiplen = snprintf(findbuf, sizeof(findbuf), "* %s \"%s\" (", cmd, mb);
tmp = strstr(s, findbuf);
if (!tmp && !strchr(mb, ' ')) { /* If not found, try the unquoted version */
skiplen = snprintf(findbuf, sizeof(findbuf), "* %s %s (", cmd, mb);
tmp = strstr(s, findbuf);
}
*skiplenptr = skiplen;
return tmp;
}
/*!
* \brief Parse a STATUS line
* \param client
* \param mbox
* \param tmp Line to parse
* \param expect_full Whether we expect a full STATUS response line or not (1 for LIST-STATUS, 0 for STATUS during IDLE)
*/
static void parse_status(struct client *client, struct mailbox *mbox, char *restrict tmp, int expect_full)
{
char *str;
if (strlen_zero(tmp)) {
client_warning("Malformed STATUS response");
return;
}
str = strstr(tmp, "MESSAGES ");
if (str) {
str += STRLEN("MESSAGES ");
if (!strlen_zero(str)) {
mbox->total = (uint32_t) atol(str);
}
} else if (expect_full) {
client_warning("Failed to parse MESSAGES");
}
str = strstr(tmp, "RECENT ");
if (str) {
str += STRLEN("RECENT ");
if (!strlen_zero(str)) {
mbox->recent = (uint32_t) atol(str);
}
} else if (expect_full) {
client_warning("Failed to parse RECENT");
}
str = strstr(tmp, "UNSEEN ");
if (str) {
str += STRLEN("UNSEEN ");
if (!strlen_zero(str)) {
mbox->unseen = (uint32_t) atol(str);
}
} else if (expect_full) {
client_warning("Failed to parse UNSEEN");
}
if (IMAP_HAS_CAPABILITY(client, IMAP_CAPABILITY_STATUS_SIZE)) {
str = strstr(tmp, "SIZE ");
if (str) {
str += STRLEN("SIZE ");
if (!strlen_zero(str)) {
mbox->size = (size_t) atol(str);
}
} else if (expect_full) {
client_warning("Failed to parse SIZE");
}
}
}
int client_status_command(struct client *client, struct mailbox *mbox, char *restrict list_status_resp)
{
int res = 0;
struct mailimap_status_att_list *att_list;
struct mailimap_mailbox_data_status *status;
clistiter *cur;
/* If LIST-STATUS is supported, we might not need to make a STATUS request at all */
if (list_status_resp) {
char *tmp;
int skiplen;
/* See if we can get what we want from the log message. */
tmp = find_mailbox_response_line(list_status_resp, "STATUS", mbox->name, &skiplen);
if (!tmp) {
client_warning("No STATUS response for mailbox '%s'", mbox->name);
/* Manually ask for it now, as usual */
} else {
/* Parse what we want from the STATUS response.
* Normally not a great idea, but STATUS responses are easy to parse. */
tmp += skiplen;
parse_status(client, mbox, tmp, 1);
/* Look at all the time we saved! Profit and return */
return 0;
}
}
att_list = mailimap_status_att_list_new_empty();
if (!att_list) {
return -1;
}
res |= mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_UNSEEN);
res |= mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_MESSAGES);
res |= mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_RECENT);
if (client->capabilities & IMAP_CAPABILITY_STATUS_SIZE) {
/* If the server does not support STATUS=SIZE, then
* the size statistics for a mailbox will gradually drift from what
* the actual size is. We could manually compute the size like
* we do in client_list, but this would be very expensive and slow
* for large mailboxes to do frequently, so we just live with this.
*
* The only special logic is if a mailbox becomes empty, then obviously
* the size is 0. */
res |= mailimap_status_att_list_add(att_list, MAILIMAP_STATUS_ATT_SIZE);
}
if (res) {
client_error("Failed to construct STATUS: %s", maildriver_strerror(res));
goto cleanup;
}
res = mailimap_status(client->imap, mbox->name, att_list, &status);
if (res != MAILIMAP_NO_ERROR) {
client_error("STATUS failed: %s", maildriver_strerror(res));
goto cleanup;
}
res = 0;
client_debug(6, "Issued STATUS command for %s", mbox->name);
for (cur = clist_begin(status->st_info_list); cur; cur = clist_next(cur)) {
struct mailimap_status_info *status_info = clist_content(cur);
switch (status_info->st_att) {
case MAILIMAP_STATUS_ATT_UNSEEN:
client->mailboxes[0].unseen -= mbox->unseen; /* Autocorrect aggregate stats as needed */
mbox->unseen = status_info->st_value;
client->mailboxes[0].unseen += mbox->unseen;
break;
case MAILIMAP_STATUS_ATT_MESSAGES:
client->mailboxes[0].total -= mbox->total;
mbox->total = status_info->st_value;
client->mailboxes[0].total += mbox->total;
break;
case MAILIMAP_STATUS_ATT_RECENT:
client->mailboxes[0].recent -= mbox->recent;
mbox->recent = status_info->st_value;
client->mailboxes[0].recent += mbox->recent;
break;
case MAILIMAP_STATUS_ATT_SIZE:
client->mailboxes[0].size -= mbox->size;
mbox->size = status_info->st_value;
client->mailboxes[0].size += mbox->size;
break;
default:
break;
}
}
mailimap_mailbox_data_status_free(status);
if (!(client->capabilities & IMAP_CAPABILITY_STATUS_SIZE) && !mbox->total && mbox->size) {
client_debug(5, "Deducing that mailbox size is now 0, since it has no messages");
client->mailboxes[0].size -= mbox->size;
mbox->size = 0;
}
cleanup:
mailimap_status_att_list_free(att_list);
return res;
}
static inline uint32_t fetch_size(struct mailimap_msg_att *msg_att)
{
clistiter *cur;
for (cur = clist_begin(msg_att->att_list); cur; cur = clist_next(cur)) {
struct mailimap_msg_att_item *item = clist_content(cur);
if (item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC && item->att_data.att_static->att_type == MAILIMAP_MSG_ATT_RFC822_SIZE) {
return item->att_data.att_static->att_data.att_rfc822_size;
}
}
return 0;
}
struct list_status_cb {
struct client *client;
char *buf;
size_t len;
};
static void list_status_logger(mailstream *imap_stream, int log_type, const char *str, size_t size, void *context)
{
int len;
/* This is a hack due to the limitations of libetpan.
* It is very tricky to be able to send an arbitrary command and be able to read the raw response from it.
* Ideally, libetpan would populate a list of STATUS, but it only does this for one mailbox,
* so with LIST-STATUS, the status returned would just be that of the last mailbox for which an untagged STATUS
* was received. This doesn't help us at all.
*
* Instead, we use this logger callback as a callback to be able to receive the raw data received.
* We'll analyze any STATUS lines that appear here, store the info we want from it,
* and then use that later.
* The LIST response is still parsed as usual in mailimap_list_status.
* We still let libetpan handle parsing the LIST responses and we only manually parse the STATUS responses.
*/
struct list_status_cb *cb = context;
struct client *client = cb->client;
(void) imap_stream;
if (!size || log_type != MAILSTREAM_LOG_TYPE_DATA_RECEIVED) {
return;
} else if (unlikely(!cb->len)) {
return;
}
/* Can be broken up across multiple log callback calls, so append to a dynstr */
client_debug(6, "Log callback of %lu bytes for LIST-STATUS", size);
/* Since this can take quite a bit of time, send an update here */
/* Look for "* STATUS " */
if (size > 8 && !strncmp(str, "* STATUS ", STRLEN("* STATUS "))) {
const char *mb = str + STRLEN("* STATUS ");
size_t maxlen = size - STRLEN("* STATUS ");
if (maxlen > 1) {
const char *end = memchr(mb + 1, *mb == '"' ? '"' : ' ', maxlen);
size_t mblen = end ? (size_t) (end - mb) : maxlen;
if (*mb == '"') {
mb++;
mblen--;
}
client_status("Queried status of %.*s", (int) mblen, mb);
}
}
len = snprintf(cb->buf, cb->len, "%.*s", (int) size, str);
cb->buf += len;
cb->len -= len;
}
/*! \brief Basically mailimap_list, but sending a custom command */
static int mailimap_list_status(mailimap *session, clist **list_result)
{
struct mailimap_response *response;
int r;
int error_code;
#define LIST_STATUS_CMD "LIST \"\" \"*\" RETURN (STATUS (MESSAGES RECENT UNSEEN SIZE))\r\n"
/* RFC 5258 Sec 4: Technically, if the server supports LIST-EXTENDED and we don't ask for CHILDREN explicitly,
* it's not obligated to return these attributes */
#define LIST_STATUS_CHILDREN_CMD "LIST \"\" \"*\" RETURN (CHILDREN STATUS (MESSAGES RECENT UNSEEN SIZE))\r\n"
if ((session->imap_state != MAILIMAP_STATE_AUTHENTICATED) && (session->imap_state != MAILIMAP_STATE_SELECTED)) {
return MAILIMAP_ERROR_BAD_STATE;
}
r = mailimap_send_current_tag(session);
if (r != MAILIMAP_NO_ERROR) {
return r;
}
/* XXX mailimap_send_crlf and mailimap_send_custom_command aren't public */
if (mailimap_has_extension(session, "LIST-EXTENDED")) {
r = (int) mailstream_write(session->imap_stream, LIST_STATUS_CHILDREN_CMD, STRLEN(LIST_STATUS_CHILDREN_CMD));
if (r != STRLEN(LIST_STATUS_CHILDREN_CMD)) {
return MAILIMAP_ERROR_STREAM;
}
} else {
r = (int) mailstream_write(session->imap_stream, LIST_STATUS_CMD, STRLEN(LIST_STATUS_CMD));
if (r != STRLEN(LIST_STATUS_CMD)) {
return MAILIMAP_ERROR_STREAM;
}
}
if (mailstream_flush(session->imap_stream) == -1) {
return MAILIMAP_ERROR_STREAM;
}
if (mailimap_read_line(session) == NULL) {
return MAILIMAP_ERROR_STREAM;
}
r = mailimap_parse_response(session, &response);
if (r != MAILIMAP_NO_ERROR) {
return r;
}
*list_result = session->imap_response_info->rsp_mailbox_list;
session->imap_response_info->rsp_mailbox_list = NULL;
/* session->imap_response only contains the last line (e.g. LIST completed) */
error_code = response->rsp_resp_done->rsp_data.rsp_tagged->rsp_cond_state->rsp_type;
mailimap_response_free(response);
switch (error_code) {
case MAILIMAP_RESP_COND_STATE_OK:
return MAILIMAP_NO_ERROR;
default:
return MAILIMAP_ERROR_LIST;
}
}
static int mailbox_attr_from_string(const char *s)
{
if (!strcasecmp(s, "NonExistent") || !strcasecmp(s, "NoSelect")) {
return IMAP_MAILBOX_NOSELECT;
} else if (!strcasecmp(s, "HasNoChildren")) {
return IMAP_MAILBOX_NOCHILDREN;
} else if (!strcasecmp(s, "HasChildren")) {
return IMAP_MAILBOX_HASCHILDREN;
} else if (!strcasecmp(s, "Drafts")) {
return IMAP_MAILBOX_DRAFTS;
} else if (!strcasecmp(s, "Junk")) {
return IMAP_MAILBOX_JUNK;
} else if (!strcasecmp(s, "Sent")) {
return IMAP_MAILBOX_SENT;
} else if (!strcasecmp(s, "Trash")) {
return IMAP_MAILBOX_TRASH;
} else {
client_debug(1, "Ignoring unknown mailbox attribute: %s", s);
return 0;
}
}
struct mailbox_ref {
const char *name;
struct mailimap_mailbox_list *mb_list;
int flags;
char data[];
};
#define STR_STARTS_WITH_CASE(s, str) !strncasecmp(s, str, STRLEN(str))
#define STR_ENDS_WITH_CASE(s, str) !strcasecmp(s + strlen(s) - STRLEN(str), str)
static int mailbox_name_score(struct mailbox_ref *r)
{
/* Done this way so that the smaller the value, the earlier it sorts */
if (!strcasecmp(r->name, "INBOX")) {
return -10 + 1;
}
/* It can end with INBOX too, the mailbox might not be named that exactly */
if (STR_ENDS_WITH_CASE(r->name, "INBOX")) {
return -10 + 1;
}
if (r->flags & IMAP_MAILBOX_DRAFTS) {
return -10 + 2;
} else if (r->flags & IMAP_MAILBOX_SENT) {
return -10 + 3;
/* Archives */
} else if (r->flags & IMAP_MAILBOX_JUNK) {
return -10 + 5;
} else if (r->flags & IMAP_MAILBOX_TRASH) {
return -10 + 6;
}
return 0;
}
static int namespace_score(struct mailbox_ref *r)
{
/* Other namespaces sort last */
/* XXX Should use LIST to determine what the other/shared namespace prefixes actually are */
if (STR_STARTS_WITH_CASE(r->name, "Other Users")) {
return 1;
} else if (STR_STARTS_WITH_CASE(r->name, "Shared Folders")) {
return 2;
} else {
return 0;
}
}
static int mktopparent(struct client *client, char *restrict buf, size_t len, const char *child)
{
char *tmp;
safe_strncpy(buf, child, len);
tmp = strchr(buf, client->delimiter);
if (tmp) {
*tmp = '\0';
return 1;
}
return 0;
}
static int mkparent(struct client *client, char *restrict buf, size_t len, const char *child)
{
char *tmp;
safe_strncpy(buf, child, len);
tmp = strrchr(buf, client->delimiter);
if (tmp) {
*tmp = '\0';
return 1;
}
return 0;
}
static inline int mbox_name_cmp(const char *a, const char *b)
{
/*! \todo Make [ sort before alphabetic characters, for things like [Gmail] where that makes sense */
int res = strcasecmp(a, b);
if (res < 0) {
res = -1;
} else if (res > 0) {
res = 1;
}
return res;
}
static struct mailbox_ref **global_mb_names; /* Hack to get access to all mailbox_ref's from __mailbox_name_cmp without adjusting the args for qsort */
static int global_num_mb_names; /* Ditto */
static struct mailbox_ref *find_mailbox_ref(const char *name)
{
int i;
for (i = 0; i < global_num_mb_names; i++) {
if (!strcmp(global_mb_names[i]->name, name)) {
return global_mb_names[i];
}
}
return NULL;
}
static int __mailbox_name_cmp(struct client *client, struct mailbox_ref *a, struct mailbox_ref *b, int cmp_attrs)
{
int res = 0;
int ns_a, ns_b;
char parent_a[512], parent_b[512];
ns_a = namespace_score(a);
ns_b = namespace_score(b);
if (ns_a < ns_b) {
res = -1;
} else if (ns_b < ns_a) {
res = 1;
} else {
/* If one folder is a prefix of the other,
* then it is its parent */
if (!strncmp(a->name, b->name, strlen(a->name))) {
/* b starts with a */
res = -1;
} else if (!strncmp(a->name, b->name, strlen(b->name))) {
/* a starts with b */
res = 1;
} else {
/* We should compare the top-level only,
* since a subfolder of a special folder should
* come before any non-special folder, regardless of
* which sorts first alphabetically. */
mktopparent(client, parent_a, sizeof(parent_a), a->name);
mktopparent(client, parent_b, sizeof(parent_b), b->name);
if (cmp_attrs) {
int score_a, score_b;
struct mailbox_ref *ra, *rb;
ra = find_mailbox_ref(parent_a);
rb = find_mailbox_ref(parent_b);
/* If it's a SPECIAL-USE mailbox, it ranks earlier */
if (!ra || !rb) {
client_error("ra = %p (%s), rb = %p (%s)", ra, parent_a, rb, parent_b);
assert(ra != NULL);
assert(rb != NULL);
}
score_a = mailbox_name_score(ra);
score_b = mailbox_name_score(rb);
/* Lower score means the folder should be earlier */
if (score_a < score_b) {
res = -1;
} else if (score_b < score_a) {
res = 1;
} else {
res = mbox_name_cmp(a->name, b->name);
}
} else {
res = mbox_name_cmp(a->name, b->name);
}
}
}
#ifdef DEBUG_FOLDER_ORDER
client_debug(3, "--- %s %c %s", a->name, res == -1 ? '<' : '>', b->name);
#endif
return res;
}
static int mailbox_name_cmp(const void *arg1, const void *arg2, void *varg)
{
struct mailbox_ref *const *ap = arg1;
struct mailbox_ref *const *bp = arg2;
struct mailbox_ref *a = *ap, *b = *bp;
struct client *client = varg;
return __mailbox_name_cmp(client, a, b, 1);
}
#ifdef TEST_MODE
static int test_cmp(struct client *client)
{
#define ARRAY_LEN(a) (size_t) (sizeof(a) / sizeof(a[0]))
size_t i;
struct {
const char *name;
int flags;
} mailboxes[] =
{
{ "INBOX", 0 },
{ "Drafts", IMAP_MAILBOX_DRAFTS },
{ "Trash", IMAP_MAILBOX_TRASH },
{ "Trash.foo", 0 },
{ "aa", 0 },
{ "bb", 0 },
{ "cc", 0 },
{ "dd", 0 },
{ "Other Users", IMAP_MAILBOX_NOSELECT },
{ "Other Users.1aa", IMAP_MAILBOX_NOSELECT },
{ "Other Users.1aa.INBOX", 0 },
{ "Other Users.1aa.Trash", IMAP_MAILBOX_TRASH },
{ "Other Users.1aa.foo", 0 },
{ "Other Users.1bb", IMAP_MAILBOX_NOSELECT },
{ "Other Users.1bb.INBOX", 0 },
{ "Other Users.1bb.Trash", IMAP_MAILBOX_TRASH },
{ "Other Users.1bb.foo", 0 },
{ "Other Users.2.foo", 0 },
{ "Other Users.2.INBOX", 0 },
{ "Other Users.2.[Gmail]", 0 },
{ "Other Users.2.[Gmail].Trash", IMAP_MAILBOX_TRASH },
};
/* Seed the test data */
struct mailbox_ref **mb_names = malloc(sizeof(struct mailbox_ref*) * ARRAY_LEN(mailboxes));
assert(mb_names != NULL);
client->delimiter = '.';
global_mb_names = mb_names;
for (i = 0; i < ARRAY_LEN(mailboxes); i++) {
mb_names[i] = calloc(1, sizeof(struct mailbox_ref));
assert(mb_names != NULL);
mb_names[i]->name = mailboxes[i].name;
mb_names[i]->flags = mailboxes[i].flags;
client->num_mailboxes++;
}
global_num_mb_names = client->num_mailboxes;
/* Run tests */
#define FOLDER_SORT_ORDER_EXPECT(f1, cmp, f2) { \
struct mailbox_ref *r1 = find_mailbox_ref(f1); \
struct mailbox_ref *r2 = find_mailbox_ref(f2); \
assert(r1 != NULL); \
assert(r2 != NULL); \
assert(r1->name != NULL); \
assert(__mailbox_name_cmp(client, r1, r2, 1) == (cmp == '<' ? -1 : 1)); \
}
FOLDER_SORT_ORDER_EXPECT("INBOX", '<', "Drafts");
FOLDER_SORT_ORDER_EXPECT("Drafts", '<', "Trash");
FOLDER_SORT_ORDER_EXPECT("aa", '<', "bb");
FOLDER_SORT_ORDER_EXPECT("aa", '<', "dd");
FOLDER_SORT_ORDER_EXPECT("Trash.foo", '<', "aa");
FOLDER_SORT_ORDER_EXPECT("Other Users.1aa", '>', "dd");
FOLDER_SORT_ORDER_EXPECT("Other Users.1aa.INBOX", '>', "dd");
FOLDER_SORT_ORDER_EXPECT("Other Users.1aa.INBOX", '>', "Other Users.1aa");
FOLDER_SORT_ORDER_EXPECT("Other Users.1bb.INBOX", '>', "Other Users.1bb");
FOLDER_SORT_ORDER_EXPECT("Other Users.1bb", '>', "Other Users.1aa.foo");
FOLDER_SORT_ORDER_EXPECT("Other Users.2.[Gmail]", '<', "Other Users.2.[Gmail].Trash");
/* Currently, Other Users...INBOX is not expected to sort first within its sub-mailbox,
* so we don't test that */
/* Cleanup */
for (i = 0; i < ARRAY_LEN(mailboxes); i++) {
free(mb_names[i]);
}
free(mb_names);
return 0;
}
#endif /* TEST_MODE */
static inline int mailbox_has_direct_parent(struct mailbox_ref **restrict mb_names, const char *restrict mb, int num_mailboxes, char delim, char *restrict parent, size_t parentlen)
{
int i;
char *end;
safe_strncpy(parent, mb, parentlen);
end = strrchr(parent, delim);
if (!end) {
/* This mailbox is at the top level (doesn't have a parent).
* For the purposes of what we care about, pretend it has
* a parent already since it's good to go */
return 1;
}
*end = '\0';
for (i = 0; i < num_mailboxes; i++) {
if (!strcmp(mb_names[i]->name, parent)) {
return 1;
}
}
/* Not at top-level and doesn't have a direct ancestor */
return 0;
}
/*! \brief Create a list of all mailboxes, properly sorted, with flags */
static struct mailbox_ref **populate_mailboxes(struct client *client, clist *imap_list)
{
int i;
clistiter *cur;
struct mailbox_ref **mb_names;
/* While we could just iterate over the list and add these to client->mailboxes
* in the order the mailboxes were listed by the server, this is a bad idea.
* The mailboxes could be provided in any order; there is no guarantee as to ordering.
* To present folders in a sane order, we first sort all of the folders,
* then adjust based on SPECIAL-USE mailboxes, and then use that order. */
mb_names = malloc(sizeof(struct mailbox_ref*) * clist_count(imap_list));
if (!mb_names) {
mailimap_list_result_free(imap_list);
return NULL;
}
client->num_mailboxes = 0;
for (i = 0, cur = clist_begin(imap_list); cur; i++, cur = clist_next(cur)) {
struct mailimap_mailbox_list *mb_list = clist_content(cur);
const char *name = mb_list->mb_name;
struct mailimap_mbx_list_flags *flags = mb_list->mb_flag;
mb_names[i] = malloc(sizeof(struct mailbox_ref) + strlen(name) + 1);
if (!mb_names[i]) {
mailimap_list_result_free(imap_list);
/* Leaks mb_names and its individual strings, but we're exiting anyways */
return NULL;
}
strcpy(mb_names[i]->data, name); /* Safe */
mb_names[i]->name = mb_names[i]->data;
mb_names[i]->mb_list = mb_list;
mb_names[i]->flags = 0;
client->num_mailboxes++;
/* Determine the hierarchy delimiter (should be same for all). */
client->delimiter = mb_list->mb_delimiter;
if (flags) {
clistiter *cur2;
if (flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
switch (flags->mbf_sflag) {
case MAILIMAP_MBX_LIST_SFLAG_MARKED:
mb_names[i]->flags |= IMAP_MAILBOX_MARKED;
break;
case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
break;
case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
mb_names[i]->flags |= IMAP_MAILBOX_NOSELECT;
break;
}
}
for (cur2 = clist_begin(flags->mbf_oflags); cur2; cur2 = clist_next(cur2)) {
struct mailimap_mbx_list_oflag *oflag = clist_content(cur2);
switch (oflag->of_type) {
case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
break;
case MAILIMAP_MBX_LIST_OFLAG_FLAG_EXT:
/* These don't include any backslashes, so don't in the other ones above either: */
mb_names[i]->flags |= mailbox_attr_from_string(oflag->of_flag_ext);
break;
}
}
}
}
/* The RFC does not state servers must include \NonExistent mailboxes
* for folders with no ancestors, so autocreate dummy mailboxes if needed.
* Use client->num_mailboxes as loop invariant since we need to also
* check anything we add during the loop. */
for (i = 0; i < client->num_mailboxes; i++) {
char parent[1024]; /* No mailbox name is going to be longer than this... */
struct mailbox_ref **new_mb_names;
if (mailbox_has_direct_parent(mb_names, mb_names[i]->name, client->num_mailboxes, client->delimiter, parent, sizeof(parent))) {
continue;
}
client_debug(3, "Mailbox '%s' does not have a direct parent, autocreating '%s'", mb_names[i]->name, parent);
new_mb_names = realloc(mb_names, sizeof(struct mailbox_ref *) * (client->num_mailboxes + 1));
if (!new_mb_names) {
client_error("realloc failed");
return NULL;
}
mb_names = new_mb_names;
mb_names[client->num_mailboxes] = malloc(sizeof(struct mailbox_ref) + strlen(parent) + 1);
if (!mb_names[client->num_mailboxes]) {
return NULL;
}
strcpy(mb_names[client->num_mailboxes]->data, parent); /* Safe */
mb_names[client->num_mailboxes]->name = mb_names[client->num_mailboxes]->data;
mb_names[client->num_mailboxes]->mb_list = NULL;
mb_names[client->num_mailboxes]->flags = IMAP_MAILBOX_NONEXISTENT;
client->num_mailboxes++;
}
global_mb_names = mb_names;
global_num_mb_names = client->num_mailboxes;
qsort_r(mb_names, client->num_mailboxes, sizeof(struct mailbox_ref *), mailbox_name_cmp, client);
global_mb_names = NULL;
global_num_mb_names = 0;
/* mb_names is now sorted */
return mb_names;
}
static int __client_list(struct client *client)
{
clist *imap_list;
int res, i;
int needunselect = 0;
/* This is a single-threaded application, so there is no concurrency risk to making this static/global,
* and it's probably better to put such a large buffer in the global segment rather than on the stack. */
static char list_status_buf[32768]; /* Hopefully big enough to fit the entire LIST-STATUS response */
#ifdef TEST_MODE
if (test_cmp(client)) {
return -1;
}
#endif
client_status("Querying mailbox list");
if (IMAP_HAS_CAPABILITY(client, IMAP_CAPABILITY_LIST_STATUS) && IMAP_HAS_CAPABILITY(client, IMAP_CAPABILITY_STATUS_SIZE)) {
struct list_status_cb cb = {
.buf = list_status_buf,
.len = sizeof(list_status_buf),
.client = client,
};
list_status_buf[0] = '\0';
/* Fundamentally, libetpan does not support LIST-STATUS.
* It did not support STATUS=SIZE either, but it was easy to patch it support that
* (and mod_webmail requires such a patched version of libetpan).
* Rather than trying to kludge libetpan to support LIST-STATUS,
* it's easier to just send it the command we want and parse it ourselves. */
mailstream_set_logger(client->imap->imap_stream, list_status_logger, &cb);
res = mailimap_list_status(client->imap, &imap_list);
mailstream_set_logger(client->imap->imap_stream, NULL, NULL);
} else {
res = mailimap_list(client->imap, "", "*", &imap_list);
}
if (res != MAILIMAP_NO_ERROR) {
client_error("%s", maildriver_strerror(res));
return -1;
}
if (!clist_begin(imap_list)) {
client_error("List is empty?");
mailimap_list_result_free(imap_list);
return -1;
}
if (!client->mailboxes) {
struct mailbox_ref **mb_names = populate_mailboxes(client, imap_list);
if (!mb_names) {
return -1;
}
/* This does mean we won't see new mailboxes created at runtime,
* which is fine since most mail clients wouldn't know anyways,
* without the user triggering a LIST/LSUB command. */
client->num_mailboxes++; /* Plus one for aggregate stats */
client->mailboxes = calloc(client->num_mailboxes, sizeof(struct mailbox));
if (!client->mailboxes) {
mailimap_list_result_free(imap_list);
return -1;
}
i = 0;
client->mailboxes[i].name = strdup("ALL");
client->mailboxes[i].flags |= IMAP_MAILBOX_NOSELECT; /* Not a real mailbox! */
/* Now, add items in the order they appear in mb_names */
for (i = 1; i < client->num_mailboxes; i++) {
const char *name;
/* Use i-1 for indexing mb_names but i for indexing client->mailboxes */
struct mailimap_mailbox_list *mb_list = mb_names[i - 1]->mb_list;
client->mailboxes[i].flags = mb_names[i - 1]->flags;
if (!mb_list) {
/* If we can't find it, it's a \NonExistent mailbox we just created. */
client->mailboxes[i].name = strdup(mb_names[i - 1]->name);
if (!client->mailboxes[i].name) {
return -1; /* Leaks but exiting */
}
continue;
}
name = mb_list->mb_name;
client->delimiter = mb_list->mb_delimiter;
client->mailboxes[i].name = strdup(name);
if (client->mailboxes[i].flags & IMAP_MAILBOX_NOSELECT) {
continue;
}
/* STATUS: ideally we could get all the details we want from a single STATUS command. */
if (!client_status_command(client, &client->mailboxes[i], list_status_buf)) {
if (!IMAP_HAS_CAPABILITY(client, IMAP_CAPABILITY_STATUS_SIZE)) { /* Lacks RFC 8438 support */
uint32_t size = 0;
if (client->mailboxes[i].total > 0) {
/* Do it the manual way. */
struct mailimap_fetch_type *fetch_type;
struct mailimap_fetch_att *fetch_att;
clist *fetch_result;
struct mailimap_set *set = mailimap_set_new_interval(1, 0); /* fetch in interval 1:* */
client_status("Calculating size of %s", name);
/* Must EXAMINE mailbox */
res = mailimap_examine(client->imap, name);
if (res != MAILIMAP_NO_ERROR) {
client_error("Failed to EXAMINE mailbox '%s'", name);
} else {
fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
fetch_att = mailimap_fetch_att_new_rfc822_size();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
res = mailimap_fetch(client->imap, set, fetch_type, &fetch_result);
if (res != MAILIMAP_NO_ERROR) {
client_error("Failed to calculate size of mailbox %s: %s", name, maildriver_strerror(res));
} else {
clistiter *cur2;
/* Iterate over each message size */
for (cur2 = clist_begin(fetch_result); cur2; cur2 = clist_next(cur2)) {
struct mailimap_msg_att *msg_att = clist_content(cur2);
size += fetch_size(msg_att);
}
mailimap_fetch_list_free(fetch_result);
mailimap_fetch_type_free(fetch_type);
}
/* UNSELECT the mailbox, since we weren't supposed to do this.
* XXX If a mailbox was previously selected, after we're done with all this,
* reselect that one. */
needunselect = 1;
}