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