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