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