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