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