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