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