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