Where gettimeofday() is required, include both time.h and sys/time.h
[citadel.git] / citadel / server / modules / imap / serv_imap.c
1 // IMAP server for the Citadel system
2 //
3 // Copyright (c) 1987-2023 by the citadel.org team
4 //
5 // This program is open source software.  Use, duplication, or disclosure
6 // is subject to the terms of the GNU General Public License, version 3.
7
8 #include "../../sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <pwd.h>
15 #include <errno.h>
16 #include <sys/types.h>
17 #include <time.h>
18 #include <sys/time.h>
19 #include <sys/wait.h>
20 #include <ctype.h>
21 #include <string.h>
22 #include <limits.h>
23 #include <libcitadel.h>
24 #include "../../citadel_defs.h"
25 #include "../../server.h"
26 #include "../../citserver.h"
27 #include "../../support.h"
28 #include "../../config.h"
29 #include "../../user_ops.h"
30 #include "../../room_ops.h"
31 #include "../../database.h"
32 #include "../../msgbase.h"
33 #include "../../internet_addressing.h"
34 #include "serv_imap.h"
35 #include "imap_tools.h"
36 #include "imap_list.h"
37 #include "imap_fetch.h"
38 #include "imap_search.h"
39 #include "imap_store.h"
40 #include "imap_acl.h"
41 #include "imap_metadata.h"
42 #include "imap_misc.h"
43
44 #include "../../ctdl_module.h"
45 HashList *ImapCmds = NULL;
46 void registerImapCMD(const char *First, long FLen, const char *Second, long SLen, imap_handler H, int Flags) {
47         imap_handler_hook *h;
48
49         h = (imap_handler_hook*) malloc(sizeof(imap_handler_hook));
50         memset(h, 0, sizeof(imap_handler_hook));
51
52         h->Flags = Flags;
53         h->h = H;
54         if (SLen == 0) {
55                 Put(ImapCmds, First, FLen, h, NULL);
56         }
57         else {
58                 char CMD[SIZ];
59                 memcpy(CMD, First, FLen);
60                 memcpy(CMD+FLen, Second, SLen);
61                 CMD[FLen+SLen] = '\0';
62                 Put(ImapCmds, CMD, FLen + SLen, h, NULL);
63         }
64 }
65
66
67 const imap_handler_hook *imap_lookup(int num_parms, ConstStr *Params) {
68         void *v;
69         citimap *Imap = IMAP;
70
71         if (num_parms < 1)
72                 return NULL;
73
74         /* we abuse the Reply-buffer for uppercasing... */
75         StrBufPlain(Imap->Reply, CKEY(Params[1]));
76         StrBufUpCase(Imap->Reply);
77
78         syslog(LOG_DEBUG, "---- Looking up [%s] -----", ChrPtr(Imap->Reply));
79         if (GetHash(ImapCmds, SKEY(Imap->Reply), &v)) {
80                 syslog(LOG_DEBUG, "Found."); 
81                 FlushStrBuf(Imap->Reply);
82                 return (imap_handler_hook *) v;
83         }
84
85         if (num_parms == 1) {
86                 syslog(LOG_DEBUG, "NOT Found."); 
87                 FlushStrBuf(Imap->Reply);
88                 return NULL;
89         }
90         
91         syslog(LOG_DEBUG, "---- Looking up [%s] -----", ChrPtr(Imap->Reply));
92         StrBufAppendBufPlain(Imap->Reply, CKEY(Params[2]), 0);
93         StrBufUpCase(Imap->Reply);
94         if (GetHash(ImapCmds, SKEY(Imap->Reply), &v)) {
95                 syslog(LOG_DEBUG, "Found."); 
96                 FlushStrBuf(Imap->Reply);
97                 return (imap_handler_hook *) v;
98         }
99         syslog(LOG_DEBUG, "NOT Found."); 
100         FlushStrBuf(Imap->Reply);
101         return NULL;
102 }
103
104
105 /* imap_rename() uses this struct containing list of rooms to rename */
106 struct irl {
107         struct irl *next;
108         char irl_oldroom[ROOMNAMELEN];
109         char irl_newroom[ROOMNAMELEN];
110         int irl_newfloor;
111 };
112
113
114 /* Data which is passed between imap_rename() and imap_rename_backend() */
115 typedef struct __irlparms {
116         const char *oldname;
117         long oldnamelen;
118         const char *newname;
119         long newnamelen;
120         struct irl **irl;
121 } irlparms;
122
123
124 /*
125  * If there is a message ID map in memory, free it
126  */
127 void imap_free_msgids(void) {
128         citimap *Imap = IMAP;
129         if (Imap->msgids != NULL) {
130                 free(Imap->msgids);
131                 Imap->msgids = NULL;
132                 Imap->num_msgs = 0;
133                 Imap->num_alloc = 0;
134         }
135         if (Imap->flags != NULL) {
136                 free(Imap->flags);
137                 Imap->flags = NULL;
138         }
139         Imap->last_mtime = (-1);
140 }
141
142
143 /*
144  * If there is a transmitted message in memory, free it
145  */
146 void imap_free_transmitted_message(void) {
147         FreeStrBuf(&IMAP->TransmittedMessage);
148 }
149
150
151 /*
152  * Set the \Seen, \Recent. and \Answered flags, based on the sequence
153  * sets stored in the visit record for this user/room.  Note that we have
154  * to parse each sequence set manually here, because calling the utility
155  * function is_msg_in_sequence_set() over and over again is too expensive.
156  *
157  * first_msg should be set to 0 to rescan the flags for every message in the
158  * room, or some other value if we're only interested in an incremental
159  * update.
160  */
161 void imap_set_seen_flags(int first_msg) {
162         citimap *Imap = IMAP;
163         struct visit vbuf;
164         int i;
165         int num_sets;
166         int s;
167         char setstr[64], lostr[64], histr[64];
168         long lo, hi;
169
170         if (Imap->num_msgs < 0) return;
171         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
172
173         for (i = first_msg; i < Imap->num_msgs; ++i) {
174                 Imap->flags[i] = Imap->flags[i] & ~IMAP_SEEN;
175                 Imap->flags[i] |= IMAP_RECENT;
176                 Imap->flags[i] = Imap->flags[i] & ~IMAP_ANSWERED;
177         }
178
179         /*
180          * Do the "\Seen" flag.
181          * (Any message not "\Seen" is considered "\Recent".)
182          */
183         num_sets = num_tokens(vbuf.v_seen, ',');
184         for (s=0; s<num_sets; ++s) {
185                 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
186
187                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
188                 if (num_tokens(setstr, ':') >= 2) {
189                         extract_token(histr, setstr, 1, ':', sizeof histr);
190                         if (!strcmp(histr, "*")) {
191                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
192                         }
193                 } 
194                 else {
195                         strcpy(histr, lostr);
196                 }
197                 lo = atol(lostr);
198                 hi = atol(histr);
199
200                 for (i = first_msg; i < Imap->num_msgs; ++i) {
201                         if ((Imap->msgids[i] >= lo) && (Imap->msgids[i] <= hi)){
202                                 Imap->flags[i] |= IMAP_SEEN;
203                                 Imap->flags[i] = Imap->flags[i] & ~IMAP_RECENT;
204                         }
205                 }
206         }
207
208         /* Do the ANSWERED flag */
209         num_sets = num_tokens(vbuf.v_answered, ',');
210         for (s=0; s<num_sets; ++s) {
211                 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
212
213                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
214                 if (num_tokens(setstr, ':') >= 2) {
215                         extract_token(histr, setstr, 1, ':', sizeof histr);
216                         if (!strcmp(histr, "*")) {
217                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
218                         }
219                 } 
220                 else {
221                         strcpy(histr, lostr);
222                 }
223                 lo = atol(lostr);
224                 hi = atol(histr);
225
226                 for (i = first_msg; i < Imap->num_msgs; ++i) {
227                         if ((Imap->msgids[i] >= lo) && (Imap->msgids[i] <= hi)){
228                                 Imap->flags[i] |= IMAP_ANSWERED;
229                         }
230                 }
231         }
232
233 }
234
235
236 /*
237  * Back end for imap_load_msgids()
238  *
239  * Optimization: instead of calling realloc() to add each message, we
240  * allocate space in the list for REALLOC_INCREMENT messages at a time.  This
241  * allows the mapping to proceed much faster.
242  */
243 void imap_add_single_msgid(long msgnum, void *userdata) {
244         citimap *Imap = IMAP;
245
246         ++Imap->num_msgs;
247         if (Imap->num_msgs > Imap->num_alloc) {
248                 Imap->num_alloc += REALLOC_INCREMENT;
249                 Imap->msgids = realloc(Imap->msgids, (Imap->num_alloc * sizeof(long)) );
250                 Imap->flags = realloc(Imap->flags, (Imap->num_alloc * sizeof(unsigned int)) );
251         }
252         Imap->msgids[Imap->num_msgs - 1] = msgnum;
253         Imap->flags[Imap->num_msgs - 1] = 0;
254 }
255
256
257 /*
258  * Set up a message ID map for the current room (folder)
259  */
260 void imap_load_msgids(void) {
261         citimap *Imap = IMAP;
262
263         if (Imap->selected == 0) {
264                 syslog(LOG_ERR, "imap_load_msgids() can't run; no room selected");
265                 return;
266         }
267
268         imap_free_msgids();     /* If there was already a map, free it */
269
270         /* Load the message list */
271         Imap->num_msgs = CtdlFetchMsgList(CC->room.QRnumber, &Imap->msgids);
272         Imap->num_alloc = Imap->num_msgs;
273
274         if (Imap->num_msgs) {
275                 Imap->flags = malloc(Imap->num_alloc * sizeof(unsigned int));
276                 memset(Imap->flags, 0, (Imap->num_alloc * sizeof(unsigned int)) );
277         }
278         imap_set_seen_flags(0);
279 }
280
281
282 /*
283  * Re-scan the selected room (folder) and see if it's been changed at all
284  */
285 void imap_rescan_msgids(void) {
286         citimap *Imap = IMAP;
287         int original_num_msgs = 0;
288         long original_highest = 0L;
289         int i, j, jstart;
290         int message_still_exists;
291         long *msglist = NULL;
292         int num_msgs = 0;
293         int num_recent = 0;
294
295         if (Imap->selected == 0) {
296                 syslog(LOG_ERR, "imap_load_msgids() can't run; no room selected");
297                 return;
298         }
299
300         /*
301          * Check to see if the room's contents have changed.
302          * If not, we can avoid this rescan.
303          */
304         CtdlGetRoom(&CC->room, CC->room.QRname);
305         if (Imap->last_mtime == CC->room.QRmtime) {     /* No changes! */
306                 return;
307         }
308
309         /* Load the *current* message list from disk, so we can compare it
310          * to what we have in memory.
311          */
312         num_msgs = CtdlFetchMsgList(CC->room.QRnumber, &msglist);
313
314         /*
315          * Check to see if any of the messages we know about have been expunged
316          */
317         if (Imap->num_msgs > 0) {
318                 jstart = 0;
319                 for (i = 0; i < Imap->num_msgs; ++i) {
320
321                         message_still_exists = 0;
322                         if (num_msgs > 0) {
323                                 for (j = jstart; j < num_msgs; ++j) {
324                                         if (msglist[j] == Imap->msgids[i]) {
325                                                 message_still_exists = 1;
326                                                 jstart = j;
327                                                 break;
328                                         }
329                                 }
330                         }
331
332                         if (message_still_exists == 0) {
333                                 IAPrintf("* %d EXPUNGE\r\n", i + 1);
334
335                                 // When a message is expunged, we have to slide all the existing messages up in the message array.
336                                 --Imap->num_msgs;
337                                 memmove(&Imap->msgids[i], &Imap->msgids[i + 1], (sizeof(long) * (Imap->num_msgs - i)));
338                                 memmove(&Imap->flags[i], &Imap->flags[i + 1], (sizeof(unsigned int) * (Imap->num_msgs - i)));
339                                 --i;
340                         }
341
342                 }
343         }
344
345         // Remember how many messages were here before we re-scanned.
346         original_num_msgs = Imap->num_msgs;
347         if (Imap->num_msgs > 0) {
348                 original_highest = Imap->msgids[Imap->num_msgs - 1];
349         }
350         else {
351                 original_highest = 0L;
352         }
353
354         // Now peruse the room for *new* messages only.
355         // This logic is probably the cause of Bug # 368
356         // [ http://bugzilla.citadel.org/show_bug.cgi?id=368 ]
357         if (num_msgs > 0) {
358                 for (j = 0; j < num_msgs; ++j) {
359                         if (msglist[j] > original_highest) {
360                                 imap_add_single_msgid(msglist[j], NULL);
361                         }
362                 }
363         }
364         imap_set_seen_flags(original_num_msgs);
365
366         /*
367          * If new messages have arrived, tell the client about them.
368          */
369         if (Imap->num_msgs > original_num_msgs) {
370
371                 for (j = 0; j < num_msgs; ++j) {
372                         if (Imap->flags[j] & IMAP_RECENT) {
373                                 ++num_recent;
374                         }
375                 }
376
377                 IAPrintf("* %d EXISTS\r\n", Imap->num_msgs);
378                 IAPrintf("* %d RECENT\r\n", num_recent);
379         }
380
381         free(msglist);
382         Imap->last_mtime = CC->room.QRmtime;
383 }
384
385
386 /*
387  * This cleanup function blows away the temporary memory and files used by
388  * the IMAP server.
389  */
390 void imap_cleanup_function(void) {
391         citimap *Imap = IMAP;
392
393         /* Don't do this stuff if this is not a Imap session! */
394         if (CC->h_command_function != imap_command_loop)
395                 return;
396
397         /* If there is a mailbox selected, auto-expunge it. */
398         if (Imap->selected) {
399                 imap_do_expunge();
400         }
401
402         syslog(LOG_DEBUG, "Performing IMAP cleanup hook");
403         imap_free_msgids();
404         imap_free_transmitted_message();
405
406         if (Imap->cached_rfc822 != NULL) {
407                 FreeStrBuf(&Imap->cached_rfc822);
408                 Imap->cached_rfc822_msgnum = (-1);
409                 Imap->cached_rfc822_withbody = 0;
410         }
411
412         if (Imap->cached_body != NULL) {
413                 free(Imap->cached_body);
414                 Imap->cached_body = NULL;
415                 Imap->cached_body_len = 0;
416                 Imap->cached_bodymsgnum = (-1);
417         }
418         FreeStrBuf(&Imap->Cmd.CmdBuf);
419         FreeStrBuf(&Imap->Reply);
420         if (Imap->Cmd.Params != NULL) free(Imap->Cmd.Params);
421         free(Imap);
422         syslog(LOG_DEBUG, "Finished IMAP cleanup hook");
423 }
424
425
426 /*
427  * Does the actual work of the CAPABILITY command (because we need to output this stuff in other places as well)
428  */
429 void imap_output_capability_string(void) {
430         IAPuts("CAPABILITY IMAP4REV1 NAMESPACE ID AUTH=PLAIN AUTH=LOGIN UIDPLUS");
431
432 #ifdef HAVE_OPENSSL
433         if (!CC->redirect_ssl) IAPuts(" STARTTLS");
434 #endif
435
436 #ifndef DISABLE_IMAP_ACL
437         IAPuts(" ACL");
438 #endif
439
440         /* We are building a partial implementation of METADATA for the sole purpose
441          * of interoperating with the ical/vcard version of the Bynari Insight Connector.
442          * It is not a full RFC5464 implementation, but it should refuse non-Bynari
443          * metadata in a compatible and graceful way.
444          */
445         IAPuts(" METADATA");
446
447         /*
448          * LIST-EXTENDED was originally going to be required by the METADATA extension.
449          * It was mercifully removed prior to the finalization of RFC5464.  We started
450          * implementing this but stopped when we learned that it would not be needed.
451          * If you uncomment this declaration you are responsible for writing a lot of new
452          * code.
453          *
454          * IAPuts(" LIST-EXTENDED")
455          */
456 }
457
458
459 /*
460  * implements the CAPABILITY command
461  */
462 void imap_capability(int num_parms, ConstStr *Params) {
463         IAPuts("* ");
464         imap_output_capability_string();
465         IAPuts("\r\n");
466         IReply("OK CAPABILITY completed");
467 }
468
469
470 /*
471  * Implements the ID command (specified by RFC2971)
472  *
473  * We ignore the client-supplied information, and output a NIL response.
474  * Although this is technically a valid implementation of the extension, it
475  * is quite useless.  It exists only so that we may see which clients are
476  * making use of this extension.
477  * 
478  */
479 void imap_id(int num_parms, ConstStr *Params) {
480         IAPuts("* ID NIL\r\n");
481         IReply("OK ID completed");
482 }
483
484
485 /*
486  * Here's where our IMAP session begins its happy day.
487  */
488 void imap_greeting(void) {
489         citimap *Imap;
490
491         strcpy(CC->cs_clientname, "IMAP session");
492         CC->session_specific_data = malloc(sizeof(citimap));
493         Imap = (citimap *)CC->session_specific_data;
494         memset(Imap, 0, sizeof(citimap));
495         Imap->authstate = imap_as_normal;
496         Imap->cached_rfc822_msgnum = (-1);
497         Imap->cached_rfc822_withbody = 0;
498         Imap->Reply = NewStrBufPlain(NULL, SIZ * 10); /* 40k */
499
500         if (CC->nologin) {
501                 IAPuts("* BYE; Server busy, try later\r\n");
502                 CC->kill_me = KILLME_NOLOGIN;
503                 IUnbuffer();
504                 return;
505         }
506
507         IAPuts("* OK [");
508         imap_output_capability_string();
509         IAPrintf("] %s IMAP4rev1 %s ready\r\n", CtdlGetConfigStr("c_fqdn"), CITADEL);
510         IUnbuffer();
511 }
512
513
514 /*
515  * IMAPS is just like IMAP, except it goes crypto right away.
516  */
517 void imaps_greeting(void) {
518         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
519 #ifdef HAVE_OPENSSL
520         if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO;          /* kill session if no crypto */
521 #endif
522         imap_greeting();
523 }
524
525
526 /*
527  * implements the LOGIN command (ordinary username/password login)
528  */
529 void imap_login(int num_parms, ConstStr *Params) {
530
531         switch (num_parms) {
532         case 3:
533                 if (Params[2].len && (Params[2].Key[0] == '{')) {
534                         IAPuts("+ go ahead\r\n");
535                         IMAP->authstate = imap_as_expecting_multilineusername;
536                         strcpy(IMAP->authseq, Params[0].Key);
537                         return;
538                 }
539                 else {
540                         IReply("BAD incorrect number of parameters");
541                         return;
542                 }
543         case 4:
544                 if (CtdlLoginExistingUser(Params[2].Key) == login_ok) {
545                         if (CtdlTryPassword(Params[3].Key, Params[3].len) == pass_ok) {
546                                 /* hm, thats not doable by IReply :-( */
547                                 IAPrintf("%s OK [", Params[0].Key);
548                                 imap_output_capability_string();
549                                 IAPrintf("] Hello, %s\r\n", CC->user.fullname);
550                                 return;
551                         }
552                         else {
553                                 IReplyPrintf("NO AUTHENTICATE %s failed", Params[3].Key);
554                                 return;
555                         }
556                 }
557
558                 IReply("BAD Login incorrect");
559                 return;
560         default:
561                 IReply("BAD incorrect number of parameters");
562                 return;
563         }
564
565 }
566
567
568 /*
569  * Implements the AUTHENTICATE command
570  */
571 void imap_authenticate(int num_parms, ConstStr *Params) {
572         char UsrBuf[SIZ];
573
574         if (num_parms != 3) {
575                 IReply("BAD incorrect number of parameters");
576                 return;
577         }
578
579         if (CC->logged_in) {
580                 IReply("BAD Already logged in.");
581                 return;
582         }
583
584         if (!strcasecmp(Params[2].Key, "LOGIN")) {
585                 size_t len = CtdlEncodeBase64(UsrBuf, "Username:", 9, BASE64_NO_LINEBREAKS);
586                 if (UsrBuf[len - 1] == '\n') {
587                         UsrBuf[len - 1] = '\0';
588                 }
589
590                 IAPrintf("+ %s\r\n", UsrBuf);
591                 IMAP->authstate = imap_as_expecting_username;
592                 strcpy(IMAP->authseq, Params[0].Key);
593                 return;
594         }
595
596         if (!strcasecmp(Params[2].Key, "PLAIN")) {
597                 // size_t len = CtdlEncodeBase64(UsrBuf, "Username:", 9, BASE64_NO_LINEBREAKS);
598                 // if (UsrBuf[len - 1] == '\n') {
599                 //   UsrBuf[len - 1] = '\0';
600                 // }
601                 // IAPuts("+ %s\r\n", UsrBuf);
602                 IAPuts("+ \r\n");
603                 IMAP->authstate = imap_as_expecting_plainauth;
604                 strcpy(IMAP->authseq, Params[0].Key);
605                 return;
606         }
607
608         else {
609                 IReplyPrintf("NO AUTHENTICATE %s failed",
610                              Params[1].Key);
611         }
612 }
613
614
615 void imap_auth_plain(void) {
616         citimap *Imap = IMAP;
617         const char *decoded_authstring;
618         char ident[256] = "";
619         char user[256] = "";
620         char pass[256] = "";
621         int result;
622         long decoded_len;
623         long len = 0;
624         long plen = 0;
625
626         memset(pass, 0, sizeof(pass));
627         decoded_len = StrBufDecodeBase64(Imap->Cmd.CmdBuf);
628
629         if (decoded_len > 0) {
630                 decoded_authstring = ChrPtr(Imap->Cmd.CmdBuf);
631
632                 len = safestrncpy(ident, decoded_authstring, sizeof ident);
633
634                 decoded_len -= len - 1;
635                 decoded_authstring += len + 1;
636
637                 if (decoded_len > 0) {
638                         len = safestrncpy(user, decoded_authstring, sizeof user);
639
640                         decoded_authstring += len + 1;
641                         decoded_len -= len - 1;
642                 }
643
644                 if (decoded_len > 0) {
645                         plen = safestrncpy(pass, decoded_authstring, sizeof pass);
646
647                         if (plen < 0)
648                                 plen = sizeof(pass) - 1;
649                 }
650         }
651         Imap->authstate = imap_as_normal;
652
653         if (!IsEmptyStr(ident)) {
654                 result = CtdlLoginExistingUser(ident);
655         }
656         else {
657                 result = CtdlLoginExistingUser(user);
658         }
659
660         if (result == login_ok) {
661                 if (CtdlTryPassword(pass, plen) == pass_ok) {
662                         IAPrintf("%s OK authentication succeeded\r\n", Imap->authseq);
663                         return;
664                 }
665         }
666         IAPrintf("%s NO authentication failed\r\n", Imap->authseq);
667 }
668
669
670 void imap_auth_login_user(long state) {
671         char PWBuf[SIZ];
672         citimap *Imap = IMAP;
673
674         switch (state) {
675         case imap_as_expecting_username:
676                 StrBufDecodeBase64(Imap->Cmd.CmdBuf);
677                 CtdlLoginExistingUser(ChrPtr(Imap->Cmd.CmdBuf));
678                 size_t len = CtdlEncodeBase64(PWBuf, "Password:", 9, BASE64_NO_LINEBREAKS);
679                 if (PWBuf[len - 1] == '\n') {
680                         PWBuf[len - 1] = '\0';
681                 }
682
683                 IAPrintf("+ %s\r\n", PWBuf);
684                 
685                 Imap->authstate = imap_as_expecting_password;
686                 return;
687         case imap_as_expecting_multilineusername:
688                 extract_token(PWBuf, ChrPtr(Imap->Cmd.CmdBuf), 1, ' ', sizeof(PWBuf));
689                 CtdlLoginExistingUser(ChrPtr(Imap->Cmd.CmdBuf));
690                 IAPuts("+ go ahead\r\n");
691                 Imap->authstate = imap_as_expecting_multilinepassword;
692                 return;
693         }
694 }
695
696
697 void imap_auth_login_pass(long state) {
698         citimap *Imap = IMAP;
699         const char *pass = NULL;
700         long len = 0;
701
702         switch (state) {
703         default:
704         case imap_as_expecting_password:
705                 StrBufDecodeBase64(Imap->Cmd.CmdBuf);
706                 pass = ChrPtr(Imap->Cmd.CmdBuf);
707                 len = StrLength(Imap->Cmd.CmdBuf);
708                 break;
709         case imap_as_expecting_multilinepassword:
710                 pass = ChrPtr(Imap->Cmd.CmdBuf);
711                 len = StrLength(Imap->Cmd.CmdBuf);
712                 break;
713         }
714         if (len > USERNAME_SIZE)
715                 StrBufCutAt(Imap->Cmd.CmdBuf, USERNAME_SIZE, NULL);
716
717         if (CtdlTryPassword(pass, len) == pass_ok) {
718                 IAPrintf("%s OK authentication succeeded\r\n", Imap->authseq);
719         }
720         else {
721                 IAPrintf("%s NO authentication failed\r\n", Imap->authseq);
722         }
723         Imap->authstate = imap_as_normal;
724         return;
725 }
726
727
728 /*
729  * implements the STARTTLS command (Citadel API version)
730  */
731 void imap_starttls(int num_parms, ConstStr *Params) {
732         char ok_response[SIZ];
733         char nosup_response[SIZ];
734         char error_response[SIZ];
735
736         snprintf(ok_response, SIZ,      "%s OK begin TLS negotiation now\r\n",  Params[0].Key);
737         snprintf(nosup_response, SIZ,   "%s NO TLS not supported here\r\n",     Params[0].Key);
738         snprintf(error_response, SIZ,   "%s BAD Internal error\r\n",            Params[0].Key);
739         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
740 }
741
742
743 /*
744  * implements the SELECT command
745  */
746 void imap_select(int num_parms, ConstStr *Params) {
747         citimap *Imap = IMAP;
748         char towhere[ROOMNAMELEN];
749         char augmented_roomname[ROOMNAMELEN];
750         int c = 0;
751         int ok = 0;
752         int ra = 0;
753         struct ctdlroom QRscratch;
754         int msgs, new;
755         int i;
756
757         /* Convert the supplied folder name to a roomname */
758         i = imap_roomname(towhere, sizeof towhere, Params[2].Key);
759         if (i < 0) {
760                 IReply("NO Invalid mailbox name.");
761                 Imap->selected = 0;
762                 return;
763         }
764
765         /* First try a regular match */
766         c = CtdlGetRoom(&QRscratch, towhere);
767
768         /* Then try a mailbox name match */
769         if (c != 0) {
770                 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, towhere);
771                 c = CtdlGetRoom(&QRscratch, augmented_roomname);
772                 if (c == 0) {
773                         safestrncpy(towhere, augmented_roomname, sizeof(towhere));
774                 }
775         }
776
777         /* If the room exists, check security/access */
778         if (c == 0) {
779                 /* See if there is an existing user/room relationship */
780                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
781
782                 /* normal clients have to pass through security */
783                 if (ra & UA_KNOWN) {
784                         ok = 1;
785                 }
786         }
787
788         /* Fail here if no such room */
789         if (!ok) {
790                 IReply("NO ... no such room, or access denied");
791                 return;
792         }
793
794         /* If we already had some other folder selected, auto-expunge it */
795         imap_do_expunge();
796
797         /*
798          * CtdlUserGoto() formally takes us to the desired room, happily returning
799          * the number of messages and number of new messages.
800          */
801         memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
802         CtdlUserGoto(NULL, 0, 0, &msgs, &new, NULL, NULL);
803         Imap->selected = 1;
804
805         if (!strcasecmp(Params[1].Key, "EXAMINE")) {
806                 Imap->readonly = 1;
807         }
808         else {
809                 Imap->readonly = 0;
810         }
811
812         imap_load_msgids();
813         Imap->last_mtime = CC->room.QRmtime;
814
815         IAPrintf("* %d EXISTS\r\n", msgs);
816         IAPrintf("* %d RECENT\r\n", new);
817
818         IAPrintf("* OK [UIDVALIDITY %ld] UID validity status\r\n", GLOBAL_UIDVALIDITY_VALUE);
819         IAPrintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CtdlGetConfigLong("MMhighest") + 1);
820
821         /* Technically, \Deleted is a valid flag, but not a permanent flag,
822          * because we don't maintain its state across sessions.  Citadel
823          * automatically expunges mailboxes when they are de-selected.
824          * 
825          * Unfortunately, omitting \Deleted as a PERMANENTFLAGS flag causes
826          * some clients (particularly Thunderbird) to misbehave -- they simply
827          * elect not to transmit the flag at all.  So we have to advertise
828          * \Deleted as a PERMANENTFLAGS flag, even though it technically isn't.
829          */
830         IAPuts("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
831         IAPuts("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] permanent flags\r\n");
832         IReplyPrintf("OK [%s] %s completed", (Imap->readonly ? "READ-ONLY" : "READ-WRITE"), Params[1].Key);
833 }
834
835
836 /*
837  * Does the real work for expunge.
838  */
839 int imap_do_expunge(void) {
840         citimap *Imap = IMAP;
841         int i;
842         int num_expunged = 0;
843         long *delmsgs = NULL;
844         int num_delmsgs = 0;
845
846         syslog(LOG_DEBUG, "imap_do_expunge() called");
847         if (Imap->selected == 0) {
848                 return (0);
849         }
850
851         if (Imap->num_msgs > 0) {
852                 delmsgs = malloc(Imap->num_msgs * sizeof(long));
853                 for (i = 0; i < Imap->num_msgs; ++i) {
854                         if (Imap->flags[i] & IMAP_DELETED) {
855                                 delmsgs[num_delmsgs++] = Imap->msgids[i];
856                         }
857                 }
858                 if (num_delmsgs > 0) {
859                         CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
860                 }
861                 num_expunged += num_delmsgs;
862                 free(delmsgs);
863         }
864
865         if (num_expunged > 0) {
866                 imap_rescan_msgids();
867         }
868
869         syslog(LOG_DEBUG, "Expunged %d messages from <%s>", num_expunged, CC->room.QRname);
870         return (num_expunged);
871 }
872
873
874 /*
875  * implements the EXPUNGE command syntax
876  */
877 void imap_expunge(int num_parms, ConstStr *Params) {
878         int num_expunged = 0;
879
880         num_expunged = imap_do_expunge();
881         IReplyPrintf("OK expunged %d messages.", num_expunged);
882 }
883
884
885 /*
886  * implements the CLOSE command
887  */
888 void imap_close(int num_parms, ConstStr *Params) {
889
890         /* Yes, we always expunge on close. */
891         if (IMAP->selected) {
892                 imap_do_expunge();
893         }
894
895         IMAP->selected = 0;
896         IMAP->readonly = 0;
897         imap_free_msgids();
898         IReply("OK CLOSE completed");
899 }
900
901
902 /*
903  * Implements the NAMESPACE command.
904  */
905 void imap_namespace(int num_parms, ConstStr *Params) {
906         long len;
907         int i;
908         struct floor *fl;
909         int floors = 0;
910         char Namespace[SIZ];
911
912         IAPuts("* NAMESPACE ");
913
914         /* All personal folders are subordinate to INBOX. */
915         IAPuts("((\"INBOX/\" \"/\")) ");
916
917         /* Other users' folders ... eventually? FIXME */
918         IAPuts("NIL ");
919
920         /* Show all floors as shared namespaces.  Neato! */
921         IAPuts("(");
922         for (i = 0; i < MAXFLOORS; ++i) {
923                 fl = CtdlGetCachedFloor(i);
924                 if (fl->f_flags & F_INUSE) {
925                         /* if (floors > 0) IAPuts(" "); samjam says this confuses javamail */
926                         IAPuts("(");
927                         len = snprintf(Namespace, sizeof(Namespace), "%s/", fl->f_name);
928                         IPutStr(Namespace, len);
929                         IAPuts(" \"/\")");
930                         ++floors;
931                 }
932         }
933         IAPuts(")");
934
935         /* Wind it up with a newline and a completion message. */
936         IAPuts("\r\n");
937         IReply("OK NAMESPACE completed");
938 }
939
940
941 /*
942  * Implements the CREATE command
943  *
944  */
945 void imap_create(int num_parms, ConstStr *Params) {
946         int ret;
947         char roomname[ROOMNAMELEN];
948         int floornum;
949         int flags;
950         int newroomtype = 0;
951         int newroomview = 0;
952         char *notification_message = NULL;
953
954         if (num_parms < 3) {
955                 IReply("NO A foder name must be specified");
956                 return;
957         }
958
959         if (strchr(Params[2].Key, '\\') != NULL) {
960                 IReply("NO Invalid character in folder name");
961                 syslog(LOG_ERR, "invalid character in folder name");
962                 return;
963         }
964
965         ret = imap_roomname(roomname, sizeof roomname, Params[2].Key);
966         if (ret < 0) {
967                 IReply("NO Invalid mailbox name or location");
968                 syslog(LOG_ERR, "invalid mailbox name or location");
969                 return;
970         }
971         floornum = (ret & 0x00ff);      /* lower 8 bits = floor number */
972         flags = (ret & 0xff00); /* upper 8 bits = flags        */
973
974         if (flags & IR_MAILBOX) {
975                 if (strncasecmp(Params[2].Key, "INBOX/", 6)) {
976                         IReply("NO Personal folders must be created under INBOX");
977                         syslog(LOG_ERR, "not subordinate to inbox");
978                         return;
979                 }
980         }
981
982         if (flags & IR_MAILBOX) {
983                 newroomtype = 4;                /* private mailbox */
984                 newroomview = VIEW_MAILBOX;
985         }
986         else {
987                 newroomtype = 0;                /* public folder */
988                 newroomview = VIEW_BBS;
989         }
990
991         syslog(LOG_INFO, "Create new room <%s> on floor <%d> with type <%d>",
992                     roomname, floornum, newroomtype);
993
994         ret = CtdlCreateRoom(roomname, newroomtype, "", floornum, 1, 0, newroomview);
995         if (ret == 0) {
996                 IReply("NO Mailbox already exists, or create failed");
997         }
998         else {
999                 IReply("OK CREATE completed");
1000                 // post a message in Aide> describing the new room
1001                 notification_message = malloc(1024);
1002                 snprintf(notification_message, 1024,
1003                         "A new room called \"%s\" has been created by %s%s%s%s\n",
1004                         roomname,
1005                         CC->user.fullname,
1006                         ((ret & QR_MAILBOX) ? " [personal]" : ""),
1007                         ((ret & QR_PRIVATE) ? " [private]" : ""),
1008                         ((ret & QR_GUESSNAME) ? " [hidden]" : "")
1009                 );
1010                 CtdlAideMessage(notification_message, "Room Creation Message");
1011                 free(notification_message);
1012         }
1013         syslog(LOG_DEBUG, "imap_create() completed");
1014 }
1015
1016
1017 /*
1018  * Locate a room by its IMAP folder name, and check access to it.
1019  * If zapped_ok is nonzero, we can also look for the room in the zapped list.
1020  */
1021 int imap_grabroom(char *returned_roomname, const char *foldername, int zapped_ok) {
1022         int ret;
1023         char augmented_roomname[ROOMNAMELEN];
1024         char roomname[ROOMNAMELEN];
1025         int c;
1026         struct ctdlroom QRscratch;
1027         int ra;
1028         int ok = 0;
1029
1030         ret = imap_roomname(roomname, sizeof roomname, foldername);
1031         if (ret < 0) {
1032                 return (1);
1033         }
1034
1035         /* First try a regular match */
1036         c = CtdlGetRoom(&QRscratch, roomname);
1037
1038         /* Then try a mailbox name match */
1039         if (c != 0) {
1040                 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, roomname);
1041                 c = CtdlGetRoom(&QRscratch, augmented_roomname);
1042                 if (c == 0)
1043                         safestrncpy(roomname, augmented_roomname, sizeof(roomname));
1044         }
1045
1046         /* If the room exists, check security/access */
1047         if (c == 0) {
1048                 /* See if there is an existing user/room relationship */
1049                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1050
1051                 /* normal clients have to pass through security */
1052                 if (ra & UA_KNOWN) {
1053                         ok = 1;
1054                 }
1055                 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1056                         ok = 1;
1057                 }
1058         }
1059
1060         /* Fail here if no such room */
1061         if (!ok) {
1062                 strcpy(returned_roomname, "");
1063                 return (2);
1064         }
1065         else {
1066                 safestrncpy(returned_roomname, QRscratch.QRname, ROOMNAMELEN);
1067                 return (0);
1068         }
1069 }
1070
1071
1072 /*
1073  * Implements the STATUS command (sort of)
1074  *
1075  */
1076 void imap_status(int num_parms, ConstStr *Params) {
1077         long len;
1078         int ret;
1079         char roomname[ROOMNAMELEN];
1080         char imaproomname[SIZ];
1081         char savedroom[ROOMNAMELEN];
1082         int msgs, new;
1083
1084         ret = imap_grabroom(roomname, Params[2].Key, 1);
1085         if (ret != 0) {
1086                 IReply("NO Invalid mailbox name or location, or access denied");
1087                 return;
1088         }
1089
1090         /*
1091          * CtdlUserGoto() formally takes us to the desired room, happily returning
1092          * the number of messages and number of new messages.  (If another
1093          * folder is selected, save its name so we can return there!!!!!)
1094          */
1095         if (IMAP->selected) {
1096                 strcpy(savedroom, CC->room.QRname);
1097         }
1098         CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1099
1100         /*
1101          * Tell the client what it wants to know.  In fact, tell it *more* than
1102          * it wants to know.  We happily IGnore the supplied status data item
1103          * names and simply spew all possible data items.  It's far easier to
1104          * code and probably saves us some processing time too.
1105          */
1106         len = imap_mailboxname(imaproomname, sizeof imaproomname, &CC->room);
1107         IAPuts("* STATUS ");
1108         IPutStr(imaproomname, len);
1109         IAPrintf(" (MESSAGES %d ", msgs);
1110         IAPrintf("RECENT %d ", new);    /* Initially, new==recent */
1111         IAPrintf("UIDNEXT %ld ", CtdlGetConfigLong("MMhighest") + 1);
1112         IAPrintf("UNSEEN %d)\r\n", new);
1113         
1114         /*
1115          * If another folder is selected, go back to that room so we can resume
1116          * our happy day without violent explosions.
1117          */
1118         if (IMAP->selected) {
1119                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1120         }
1121
1122         /*
1123          * Oooh, look, we're done!
1124          */
1125         IReply("OK STATUS completed");
1126 }
1127
1128
1129 /*
1130  * Implements the SUBSCRIBE command
1131  *
1132  */
1133 void imap_subscribe(int num_parms, ConstStr *Params) {
1134         int ret;
1135         char roomname[ROOMNAMELEN];
1136         char savedroom[ROOMNAMELEN];
1137         int msgs, new;
1138
1139         ret = imap_grabroom(roomname, Params[2].Key, 1);
1140         if (ret != 0) {
1141                 IReplyPrintf(
1142                         "NO Error %d: invalid mailbox name or location, or access denied",
1143                         ret
1144                 );
1145                 return;
1146         }
1147
1148         /*
1149          * CtdlUserGoto() formally takes us to the desired room, which has the side
1150          * effect of marking the room as not-zapped ... exactly the effect
1151          * we're looking for.
1152          */
1153         if (IMAP->selected) {
1154                 strcpy(savedroom, CC->room.QRname);
1155         }
1156         CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1157
1158         /*
1159          * If another folder is selected, go back to that room so we can resume
1160          * our happy day without violent explosions.
1161          */
1162         if (IMAP->selected) {
1163                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1164         }
1165
1166         IReply("OK SUBSCRIBE completed");
1167 }
1168
1169
1170 /*
1171  * Implements the UNSUBSCRIBE command
1172  *
1173  */
1174 void imap_unsubscribe(int num_parms, ConstStr *Params) {
1175         int ret;
1176         char roomname[ROOMNAMELEN];
1177         char savedroom[ROOMNAMELEN];
1178         int msgs, new;
1179
1180         ret = imap_grabroom(roomname, Params[2].Key, 1);
1181         if (ret != 0) {
1182                 IReply("NO Invalid mailbox name or location, or access denied");
1183                 return;
1184         }
1185
1186         /*
1187          * CtdlUserGoto() formally takes us to the desired room.
1188          */
1189         if (IMAP->selected) {
1190                 strcpy(savedroom, CC->room.QRname);
1191         }
1192         CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1193
1194         /* 
1195          * Now make the API call to zap the room
1196          */
1197         if (CtdlForgetThisRoom() == 0) {
1198                 IReply("OK UNSUBSCRIBE completed");
1199         }
1200         else {
1201                 IReply("NO You may not unsubscribe from this folder.");
1202         }
1203
1204         /*
1205          * If another folder is selected, go back to that room so we can resume
1206          * our happy day without violent explosions.
1207          */
1208         if (IMAP->selected) {
1209                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1210         }
1211 }
1212
1213
1214 /*
1215  * Implements the DELETE command
1216  *
1217  */
1218 void imap_delete(int num_parms, ConstStr *Params) {
1219         int ret;
1220         char roomname[ROOMNAMELEN];
1221         char savedroom[ROOMNAMELEN];
1222         int msgs, new;
1223
1224         ret = imap_grabroom(roomname, Params[2].Key, 1);
1225         if (ret != 0) {
1226                 IReply("NO Invalid mailbox name, or access denied");
1227                 return;
1228         }
1229
1230         /*
1231          * CtdlUserGoto() formally takes us to the desired room, happily returning
1232          * the number of messages and number of new messages.  (If another
1233          * folder is selected, save its name so we can return there!!!!!)
1234          */
1235         if (IMAP->selected) {
1236                 strcpy(savedroom, CC->room.QRname);
1237         }
1238         CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1239
1240         /*
1241          * Now delete the room.
1242          */
1243         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1244                 CtdlScheduleRoomForDeletion(&CC->room);
1245                 IReply("OK DELETE completed");
1246         }
1247         else {
1248                 IReply("NO Can't delete this folder.");
1249         }
1250
1251         /*
1252          * If another folder is selected, go back to that room so we can resume
1253          * our happy day without violent explosions.
1254          */
1255         if (IMAP->selected) {
1256                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1257         }
1258 }
1259
1260
1261 /*
1262  * Back end function for imap_rename()
1263  */
1264 void imap_rename_backend(struct ctdlroom *qrbuf, void *data) {
1265         char foldername[SIZ];
1266         char newfoldername[SIZ];
1267         char newroomname[ROOMNAMELEN];
1268         int newfloor = 0;
1269         struct irl *irlp = NULL;        /* scratch pointer */
1270         irlparms *myirlparms;
1271
1272         myirlparms = (irlparms *) data;
1273         imap_mailboxname(foldername, sizeof foldername, qrbuf);
1274
1275         /* Rename subfolders */
1276         if ((!strncasecmp(foldername, myirlparms->oldname, myirlparms->oldnamelen) && (foldername[myirlparms->oldnamelen] == '/'))) {
1277                 snprintf(newfoldername, sizeof newfoldername, "%s/%s", myirlparms->newname, &foldername[myirlparms->oldnamelen + 1]);
1278                 newfloor = imap_roomname(newroomname, sizeof newroomname, newfoldername) & 0xFF;
1279                 irlp = (struct irl *) malloc(sizeof(struct irl));
1280                 strcpy(irlp->irl_newroom, newroomname);
1281                 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1282                 irlp->irl_newfloor = newfloor;
1283                 irlp->next = *(myirlparms->irl);
1284                 *(myirlparms->irl) = irlp;
1285         }
1286 }
1287
1288
1289 /*
1290  * Implements the RENAME command
1291  *
1292  */
1293 void imap_rename(int num_parms, ConstStr *Params) {
1294         char old_room[ROOMNAMELEN];
1295         char new_room[ROOMNAMELEN];
1296         int newr;
1297         int new_floor;
1298         int r;
1299         struct irl *irl = NULL; /* the list */
1300         struct irl *irlp = NULL;        /* scratch pointer */
1301         irlparms irlparms;
1302         char aidemsg[1024];
1303
1304         if (strchr(Params[3].Key, '\\') != NULL) {
1305                 IReply("NO Invalid character in folder name");
1306                 return;
1307         }
1308
1309         imap_roomname(old_room, sizeof old_room, Params[2].Key);
1310         newr = imap_roomname(new_room, sizeof new_room, Params[3].Key);
1311         new_floor = (newr & 0xFF);
1312
1313         r = CtdlRenameRoom(old_room, new_room, new_floor);
1314
1315         if (r == crr_room_not_found) {
1316                 IReply("NO Could not locate this folder");
1317                 return;
1318         }
1319         if (r == crr_already_exists) {
1320                 IReplyPrintf("NO '%s' already exists.");
1321                 return;
1322         }
1323         if (r == crr_noneditable) {
1324                 IReply("NO This folder is not editable.");
1325                 return;
1326         }
1327         if (r == crr_invalid_floor) {
1328                 IReply("NO Folder root does not exist.");
1329                 return;
1330         }
1331         if (r == crr_access_denied) {
1332                 IReply("NO You do not have permission to edit this folder.");
1333                 return;
1334         }
1335         if (r != crr_ok) {
1336                 IReplyPrintf("NO Rename failed - undefined error %d", r);
1337                 return;
1338         }
1339
1340         /* If this is the INBOX, then RFC2060 says we have to just move the
1341          * contents.  In a Citadel environment it's easier to rename the room
1342          * (already did that) and create a new inbox.
1343          */
1344         if (!strcasecmp(Params[2].Key, "INBOX")) {
1345                 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1346         }
1347
1348         /* Otherwise, do the subfolders.  Build a list of rooms to rename... */
1349         else {
1350                 irlparms.oldname = Params[2].Key;
1351                 irlparms.oldnamelen = Params[2].len;
1352                 irlparms.newname = Params[3].Key;
1353                 irlparms.newnamelen = Params[3].len;
1354                 irlparms.irl = &irl;
1355                 CtdlForEachRoom(imap_rename_backend, (void *) &irlparms);
1356
1357                 /* ... and now rename them. */
1358                 while (irl != NULL) {
1359                         r = CtdlRenameRoom(irl->irl_oldroom, irl->irl_newroom, irl->irl_newfloor);
1360                         if (r != crr_ok) {
1361                                 /* FIXME handle error returns better */
1362                                 syslog(LOG_ERR, "CtdlRenameRoom() error %d", r);
1363                         }
1364                         irlp = irl;
1365                         irl = irl->next;
1366                         free(irlp);
1367                 }
1368         }
1369
1370         snprintf(aidemsg, sizeof aidemsg, "IMAP folder \"%s\" renamed to \"%s\" by %s\n",
1371                 Params[2].Key,
1372                 Params[3].Key,
1373                 CC->curr_user
1374         );
1375         CtdlAideMessage(aidemsg, "IMAP folder rename");
1376
1377         IReply("OK RENAME completed");
1378 }
1379
1380
1381 /* 
1382  * Main command loop for IMAP sessions.
1383  */
1384 void imap_command_loop(void) {
1385         struct timeval tv1, tv2;
1386         suseconds_t total_time = 0;
1387         citimap *Imap;
1388         const char *pchs, *pche;
1389         const imap_handler_hook *h;
1390
1391         gettimeofday(&tv1, NULL);
1392         CC->lastcmd = time(NULL);
1393         Imap = IMAP;
1394
1395         flush_output();
1396         if (Imap->Cmd.CmdBuf == NULL)
1397                 Imap->Cmd.CmdBuf = NewStrBufPlain(NULL, SIZ);
1398         else
1399                 FlushStrBuf(Imap->Cmd.CmdBuf);
1400
1401         if (CtdlClientGetLine(Imap->Cmd.CmdBuf) < 1) {
1402                 syslog(LOG_ERR, "client disconnected: ending session.");
1403                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1404                 return;
1405         }
1406
1407         if (Imap->authstate == imap_as_expecting_password) {
1408                 syslog(LOG_INFO, "<password>");
1409         }
1410         else if (Imap->authstate == imap_as_expecting_plainauth) {
1411                 syslog(LOG_INFO, "<plain_auth>");
1412         }
1413         else if ((Imap->authstate == imap_as_expecting_multilineusername) || cbmstrcasestr(ChrPtr(Imap->Cmd.CmdBuf), " LOGIN ")) {
1414                 syslog(LOG_INFO, "LOGIN...");
1415         }
1416         else {
1417                 syslog(LOG_DEBUG, "%s", ChrPtr(Imap->Cmd.CmdBuf));
1418         }
1419
1420         pchs = ChrPtr(Imap->Cmd.CmdBuf);
1421         pche = pchs + StrLength(Imap->Cmd.CmdBuf);
1422
1423         while ((pche > pchs) && ((*pche == '\n') || (*pche == '\r'))) {
1424                 pche --;
1425                 StrBufCutRight(Imap->Cmd.CmdBuf, 1);
1426         }
1427         StrBufTrim(Imap->Cmd.CmdBuf);
1428
1429         /* If we're in the middle of a multi-line command, handle that */
1430         switch (Imap->authstate){
1431         case imap_as_expecting_username:
1432                 imap_auth_login_user(imap_as_expecting_username);
1433                 IUnbuffer();
1434                 return;
1435         case imap_as_expecting_multilineusername:
1436                 imap_auth_login_user(imap_as_expecting_multilineusername);
1437                 IUnbuffer();
1438                 return;
1439         case imap_as_expecting_plainauth:
1440                 imap_auth_plain();
1441                 IUnbuffer();
1442                 return;
1443         case imap_as_expecting_password:
1444                 imap_auth_login_pass(imap_as_expecting_password);
1445                 IUnbuffer();
1446                 return;
1447         case imap_as_expecting_multilinepassword:
1448                 imap_auth_login_pass(imap_as_expecting_multilinepassword);
1449                 IUnbuffer();
1450                 return;
1451         default:
1452                 break;
1453         }
1454
1455         /* Ok, at this point we're in normal command mode.
1456          * If the command just submitted does not contain a literal, we
1457          * might think about delivering some untagged stuff...
1458          */
1459
1460         /* Grab the tag, command, and parameters. */
1461         imap_parameterize(&Imap->Cmd);
1462
1463         /* Now for the command set. */
1464         h = imap_lookup(Imap->Cmd.num_parms, Imap->Cmd.Params);
1465
1466         if (h == NULL) {
1467                 IReply("BAD command unrecognized");
1468                 goto BAIL;
1469         }
1470
1471         /* RFC3501 says that we cannot output untagged data during these commands */
1472         if ((h->Flags & I_FLAG_UNTAGGED) == 0) {
1473
1474                 // we can put any additional untagged stuff right here in the future
1475
1476                 // Before processing the command that was just entered... if we happen
1477                 // to have a folder selected, we'd like to rescan that folder for new
1478                 // messages, and for deletions/changes of existing messages.  This
1479                 // could probably be optimized better with some deep thought...
1480                 if (Imap->selected) {
1481                         imap_rescan_msgids();
1482                 }
1483         }
1484
1485         /* does our command require a logged-in state */
1486         if ((!CC->logged_in) && ((h->Flags & I_FLAG_LOGGED_IN) != 0)) {
1487                 IReply("BAD Not logged in.");
1488                 goto BAIL;
1489         }
1490
1491         /* does our command require the SELECT state on a mailbox */
1492         if ((Imap->selected == 0) && ((h->Flags & I_FLAG_SELECT) != 0)){
1493                 IReply("BAD no folder selected");
1494                 goto BAIL;
1495         }
1496         h->h(Imap->Cmd.num_parms, Imap->Cmd.Params);
1497
1498         /* If the client transmitted a message we can free it now */
1499
1500 BAIL:
1501         IUnbuffer();
1502
1503         imap_free_transmitted_message();
1504
1505         gettimeofday(&tv2, NULL);
1506         total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1507         syslog(LOG_DEBUG, "IMAP command completed in %ld.%ld seconds",
1508                     (total_time / 1000000),
1509                     (total_time % 1000000)
1510                 );
1511 }
1512
1513
1514 void imap_noop(int num_parms, ConstStr *Params) {
1515         IReply("OK No operation");
1516 }
1517
1518
1519 void imap_logout(int num_parms, ConstStr *Params) {
1520         if (IMAP->selected) {
1521                 imap_do_expunge();      /* yes, we auto-expunge at logout */
1522         }
1523         IAPrintf("* BYE %s logging out\r\n", CtdlGetConfigStr("c_fqdn"));
1524         IReply("OK Citadel IMAP session ended.");
1525         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1526         return;
1527 }
1528
1529
1530 const char *CitadelServiceIMAP="IMAP";
1531 const char *CitadelServiceIMAPS="IMAPS";
1532
1533
1534 // Initialization function, called from modules_init.c
1535 char *ctdl_module_init_imap(void) {
1536         if (ImapCmds == NULL) {
1537                 ImapCmds = NewHash(1, NULL);
1538         }
1539
1540         RegisterImapCMD("NOOP", "", imap_noop, I_FLAG_NONE);
1541         RegisterImapCMD("CHECK", "", imap_noop, I_FLAG_NONE);
1542         RegisterImapCMD("ID", "", imap_id, I_FLAG_NONE);
1543         RegisterImapCMD("LOGOUT", "", imap_logout, I_FLAG_NONE);
1544         RegisterImapCMD("LOGIN", "", imap_login, I_FLAG_NONE);
1545         RegisterImapCMD("AUTHENTICATE", "", imap_authenticate, I_FLAG_NONE);
1546         RegisterImapCMD("CAPABILITY", "", imap_capability, I_FLAG_NONE);
1547 #ifdef HAVE_OPENSSL
1548         RegisterImapCMD("STARTTLS", "", imap_starttls, I_FLAG_NONE);
1549 #endif
1550
1551         /* The commans below require a logged-in state */
1552         RegisterImapCMD("SELECT", "", imap_select, I_FLAG_LOGGED_IN);
1553         RegisterImapCMD("EXAMINE", "", imap_select, I_FLAG_LOGGED_IN);
1554         RegisterImapCMD("LSUB", "", imap_list, I_FLAG_LOGGED_IN);
1555         RegisterImapCMD("LIST", "", imap_list, I_FLAG_LOGGED_IN);
1556         RegisterImapCMD("CREATE", "", imap_create, I_FLAG_LOGGED_IN);
1557         RegisterImapCMD("DELETE", "", imap_delete, I_FLAG_LOGGED_IN);
1558         RegisterImapCMD("RENAME", "", imap_rename, I_FLAG_LOGGED_IN);
1559         RegisterImapCMD("STATUS", "", imap_status, I_FLAG_LOGGED_IN);
1560         RegisterImapCMD("SUBSCRIBE", "", imap_subscribe, I_FLAG_LOGGED_IN);
1561         RegisterImapCMD("UNSUBSCRIBE", "", imap_unsubscribe, I_FLAG_LOGGED_IN);
1562         RegisterImapCMD("APPEND", "", imap_append, I_FLAG_LOGGED_IN);
1563         RegisterImapCMD("NAMESPACE", "", imap_namespace, I_FLAG_LOGGED_IN);
1564         RegisterImapCMD("SETACL", "", imap_setacl, I_FLAG_LOGGED_IN);
1565         RegisterImapCMD("DELETEACL", "", imap_deleteacl, I_FLAG_LOGGED_IN);
1566         RegisterImapCMD("GETACL", "", imap_getacl, I_FLAG_LOGGED_IN);
1567         RegisterImapCMD("LISTRIGHTS", "", imap_listrights, I_FLAG_LOGGED_IN);
1568         RegisterImapCMD("MYRIGHTS", "", imap_myrights, I_FLAG_LOGGED_IN);
1569         RegisterImapCMD("GETMETADATA", "", imap_getmetadata, I_FLAG_LOGGED_IN);
1570         RegisterImapCMD("SETMETADATA", "", imap_setmetadata, I_FLAG_LOGGED_IN);
1571
1572         /* The commands below require the SELECT state on a mailbox */
1573         RegisterImapCMD("FETCH", "", imap_fetch, I_FLAG_LOGGED_IN | I_FLAG_SELECT | I_FLAG_UNTAGGED);
1574         RegisterImapCMD("UID", "FETCH", imap_uidfetch, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1575         RegisterImapCMD("SEARCH", "", imap_search, I_FLAG_LOGGED_IN | I_FLAG_SELECT | I_FLAG_UNTAGGED);
1576         RegisterImapCMD("UID", "SEARCH", imap_uidsearch, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1577         RegisterImapCMD("STORE", "", imap_store, I_FLAG_LOGGED_IN | I_FLAG_SELECT | I_FLAG_UNTAGGED);
1578         RegisterImapCMD("UID", "STORE", imap_uidstore, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1579         RegisterImapCMD("COPY", "", imap_copy, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1580         RegisterImapCMD("UID", "COPY", imap_uidcopy, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1581         RegisterImapCMD("EXPUNGE", "", imap_expunge, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1582         RegisterImapCMD("UID", "EXPUNGE", imap_expunge, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1583         RegisterImapCMD("CLOSE", "", imap_close, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1584
1585         if (!threading) {
1586                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_imap_port"), NULL, imap_greeting, imap_command_loop, NULL, CitadelServiceIMAP);
1587 #ifdef HAVE_OPENSSL
1588                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_imaps_port"), NULL, imaps_greeting, imap_command_loop, NULL, CitadelServiceIMAPS);
1589 #endif
1590                 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP, PRIO_STOP + 30);
1591         }
1592         
1593         // return our module name for the log
1594         return "imap";
1595 }