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