e3c55ae4ff7739a718f165f323fc7daa5ae5d62b
[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", Params[3].Key);
642                                 return;
643                         }
644                 }
645
646                 IReply("BAD Login incorrect");
647                 return;
648         default:
649                 IReply("BAD incorrect number of parameters");
650                 return;
651         }
652
653 }
654
655
656 /*
657  * Implements the AUTHENTICATE command
658  */
659 void imap_authenticate(int num_parms, ConstStr *Params)
660 {
661         char UsrBuf[SIZ];
662
663         if (num_parms != 3) {
664                 IReply("BAD incorrect number of parameters");
665                 return;
666         }
667
668         if (CC->logged_in) {
669                 IReply("BAD Already logged in.");
670                 return;
671         }
672
673         if (!strcasecmp(Params[2].Key, "LOGIN")) {
674                 size_t len = CtdlEncodeBase64(UsrBuf, "Username:", 9, 0);
675                 if (UsrBuf[len - 1] == '\n') {
676                         UsrBuf[len - 1] = '\0';
677                 }
678
679                 IAPrintf("+ %s\r\n", UsrBuf);
680                 IMAP->authstate = imap_as_expecting_username;
681                 strcpy(IMAP->authseq, Params[0].Key);
682                 return;
683         }
684
685         if (!strcasecmp(Params[2].Key, "PLAIN")) {
686                 // size_t len = CtdlEncodeBase64(UsrBuf, "Username:", 9, 0);
687                 // if (UsrBuf[len - 1] == '\n') {
688                 //   UsrBuf[len - 1] = '\0';
689                 // }
690                 // IAPuts("+ %s\r\n", UsrBuf);
691                 IAPuts("+ \r\n");
692                 IMAP->authstate = imap_as_expecting_plainauth;
693                 strcpy(IMAP->authseq, Params[0].Key);
694                 return;
695         }
696
697         else {
698                 IReplyPrintf("NO AUTHENTICATE %s failed",
699                              Params[1].Key);
700         }
701 }
702
703
704 void imap_auth_plain(void)
705 {
706         citimap *Imap = IMAP;
707         const char *decoded_authstring;
708         char ident[256] = "";
709         char user[256] = "";
710         char pass[256] = "";
711         int result;
712         long decoded_len;
713         long len = 0;
714         long plen = 0;
715
716         memset(pass, 0, sizeof(pass));
717         decoded_len = StrBufDecodeBase64(Imap->Cmd.CmdBuf);
718
719         if (decoded_len > 0)
720         {
721                 decoded_authstring = ChrPtr(Imap->Cmd.CmdBuf);
722
723                 len = safestrncpy(ident, decoded_authstring, sizeof ident);
724
725                 decoded_len -= len - 1;
726                 decoded_authstring += len + 1;
727
728                 if (decoded_len > 0)
729                 {
730                         len = safestrncpy(user, decoded_authstring, sizeof user);
731
732                         decoded_authstring += len + 1;
733                         decoded_len -= len - 1;
734                 }
735
736                 if (decoded_len > 0)
737                 {
738                         plen = safestrncpy(pass, decoded_authstring, sizeof pass);
739
740                         if (plen < 0)
741                                 plen = sizeof(pass) - 1;
742                 }
743         }
744         Imap->authstate = imap_as_normal;
745
746         if (!IsEmptyStr(ident)) {
747                 result = CtdlLoginExistingUser(user, ident);
748         }
749         else {
750                 result = CtdlLoginExistingUser(NULL, user);
751         }
752
753         if (result == login_ok) {
754                 if (CtdlTryPassword(pass, plen) == pass_ok) {
755                         IAPrintf("%s OK authentication succeeded\r\n", Imap->authseq);
756                         return;
757                 }
758         }
759         IAPrintf("%s NO authentication failed\r\n", Imap->authseq);
760 }
761
762
763 void imap_auth_login_user(long state)
764 {
765         char PWBuf[SIZ];
766         citimap *Imap = IMAP;
767
768         switch (state){
769         case imap_as_expecting_username:
770                 StrBufDecodeBase64(Imap->Cmd.CmdBuf);
771                 CtdlLoginExistingUser(NULL, ChrPtr(Imap->Cmd.CmdBuf));
772                 size_t len = CtdlEncodeBase64(PWBuf, "Password:", 9, 0);
773                 if (PWBuf[len - 1] == '\n') {
774                         PWBuf[len - 1] = '\0';
775                 }
776
777                 IAPrintf("+ %s\r\n", PWBuf);
778                 
779                 Imap->authstate = imap_as_expecting_password;
780                 return;
781         case imap_as_expecting_multilineusername:
782                 extract_token(PWBuf, ChrPtr(Imap->Cmd.CmdBuf), 1, ' ', sizeof(PWBuf));
783                 CtdlLoginExistingUser(NULL, ChrPtr(Imap->Cmd.CmdBuf));
784                 IAPuts("+ go ahead\r\n");
785                 Imap->authstate = imap_as_expecting_multilinepassword;
786                 return;
787         }
788 }
789
790
791 void imap_auth_login_pass(long state)
792 {
793         citimap *Imap = IMAP;
794         const char *pass = NULL;
795         long len = 0;
796
797         switch (state) {
798         default:
799         case imap_as_expecting_password:
800                 StrBufDecodeBase64(Imap->Cmd.CmdBuf);
801                 pass = ChrPtr(Imap->Cmd.CmdBuf);
802                 len = StrLength(Imap->Cmd.CmdBuf);
803                 break;
804         case imap_as_expecting_multilinepassword:
805                 pass = ChrPtr(Imap->Cmd.CmdBuf);
806                 len = StrLength(Imap->Cmd.CmdBuf);
807                 break;
808         }
809         if (len > USERNAME_SIZE)
810                 StrBufCutAt(Imap->Cmd.CmdBuf, USERNAME_SIZE, NULL);
811
812         if (CtdlTryPassword(pass, len) == pass_ok) {
813                 IAPrintf("%s OK authentication succeeded\r\n", Imap->authseq);
814         } else {
815                 IAPrintf("%s NO authentication failed\r\n", Imap->authseq);
816         }
817         Imap->authstate = imap_as_normal;
818         return;
819 }
820
821
822 /*
823  * implements the STARTTLS command (Citadel API version)
824  */
825 void imap_starttls(int num_parms, ConstStr *Params)
826 {
827         char ok_response[SIZ];
828         char nosup_response[SIZ];
829         char error_response[SIZ];
830
831         snprintf(ok_response, SIZ,      "%s OK begin TLS negotiation now\r\n",  Params[0].Key);
832         snprintf(nosup_response, SIZ,   "%s NO TLS not supported here\r\n",     Params[0].Key);
833         snprintf(error_response, SIZ,   "%s BAD Internal error\r\n",            Params[0].Key);
834         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
835 }
836
837
838 /*
839  * implements the SELECT command
840  */
841 void imap_select(int num_parms, ConstStr *Params)
842 {
843         citimap *Imap = IMAP;
844         char towhere[ROOMNAMELEN];
845         char augmented_roomname[ROOMNAMELEN];
846         int c = 0;
847         int ok = 0;
848         int ra = 0;
849         struct ctdlroom QRscratch;
850         int msgs, new;
851         int i;
852
853         /* Convert the supplied folder name to a roomname */
854         i = imap_roomname(towhere, sizeof towhere, Params[2].Key);
855         if (i < 0) {
856                 IReply("NO Invalid mailbox name.");
857                 Imap->selected = 0;
858                 return;
859         }
860
861         /* First try a regular match */
862         c = CtdlGetRoom(&QRscratch, towhere);
863
864         /* Then try a mailbox name match */
865         if (c != 0) {
866                 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, towhere);
867                 c = CtdlGetRoom(&QRscratch, augmented_roomname);
868                 if (c == 0) {
869                         safestrncpy(towhere, augmented_roomname, sizeof(towhere));
870                 }
871         }
872
873         /* If the room exists, check security/access */
874         if (c == 0) {
875                 /* See if there is an existing user/room relationship */
876                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
877
878                 /* normal clients have to pass through security */
879                 if (ra & UA_KNOWN) {
880                         ok = 1;
881                 }
882         }
883
884         /* Fail here if no such room */
885         if (!ok) {
886                 IReply("NO ... no such room, or access denied");
887                 return;
888         }
889
890         /* If we already had some other folder selected, auto-expunge it */
891         imap_do_expunge();
892
893         /*
894          * CtdlUserGoto() formally takes us to the desired room, happily returning
895          * the number of messages and number of new messages.
896          */
897         memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
898         CtdlUserGoto(NULL, 0, 0, &msgs, &new, NULL, NULL);
899         Imap->selected = 1;
900
901         if (!strcasecmp(Params[1].Key, "EXAMINE")) {
902                 Imap->readonly = 1;
903         } else {
904                 Imap->readonly = 0;
905         }
906
907         imap_load_msgids();
908         Imap->last_mtime = CC->room.QRmtime;
909
910         IAPrintf("* %d EXISTS\r\n", msgs);
911         IAPrintf("* %d RECENT\r\n", new);
912
913         IAPrintf("* OK [UIDVALIDITY %ld] UID validity status\r\n", GLOBAL_UIDVALIDITY_VALUE);
914         IAPrintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CtdlGetConfigLong("MMhighest") + 1);
915
916         /* Technically, \Deleted is a valid flag, but not a permanent flag,
917          * because we don't maintain its state across sessions.  Citadel
918          * automatically expunges mailboxes when they are de-selected.
919          * 
920          * Unfortunately, omitting \Deleted as a PERMANENTFLAGS flag causes
921          * some clients (particularly Thunderbird) to misbehave -- they simply
922          * elect not to transmit the flag at all.  So we have to advertise
923          * \Deleted as a PERMANENTFLAGS flag, even though it technically isn't.
924          */
925         IAPuts("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
926         IAPuts("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] permanent flags\r\n");
927
928         IReplyPrintf("OK [%s] %s completed",
929                 (Imap->readonly ? "READ-ONLY" : "READ-WRITE"), Params[1].Key
930         );
931 }
932
933
934 /*
935  * Does the real work for expunge.
936  */
937 int imap_do_expunge(void)
938 {
939         struct CitContext *CCC = CC;
940         citimap *Imap = CCCIMAP;
941         int i;
942         int num_expunged = 0;
943         long *delmsgs = NULL;
944         int num_delmsgs = 0;
945
946         syslog(LOG_DEBUG, "imap_do_expunge() called");
947         if (Imap->selected == 0) {
948                 return (0);
949         }
950
951         if (Imap->num_msgs > 0) {
952                 delmsgs = malloc(Imap->num_msgs * sizeof(long));
953                 for (i = 0; i < Imap->num_msgs; ++i) {
954                         if (Imap->flags[i] & IMAP_DELETED) {
955                                 delmsgs[num_delmsgs++] = Imap->msgids[i];
956                         }
957                 }
958                 if (num_delmsgs > 0) {
959                         CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
960                 }
961                 num_expunged += num_delmsgs;
962                 free(delmsgs);
963         }
964
965         if (num_expunged > 0) {
966                 imap_rescan_msgids();
967         }
968
969         syslog(LOG_DEBUG, "Expunged %d messages from <%s>", num_expunged, CC->room.QRname);
970         return (num_expunged);
971 }
972
973
974 /*
975  * implements the EXPUNGE command syntax
976  */
977 void imap_expunge(int num_parms, ConstStr *Params)
978 {
979         int num_expunged = 0;
980
981         num_expunged = imap_do_expunge();
982         IReplyPrintf("OK expunged %d messages.", num_expunged);
983 }
984
985
986 /*
987  * implements the CLOSE command
988  */
989 void imap_close(int num_parms, ConstStr *Params)
990 {
991
992         /* Yes, we always expunge on close. */
993         if (IMAP->selected) {
994                 imap_do_expunge();
995         }
996
997         IMAP->selected = 0;
998         IMAP->readonly = 0;
999         imap_free_msgids();
1000         IReply("OK CLOSE completed");
1001 }
1002
1003
1004 /*
1005  * Implements the NAMESPACE command.
1006  */
1007 void imap_namespace(int num_parms, ConstStr *Params)
1008 {
1009         long len;
1010         int i;
1011         struct floor *fl;
1012         int floors = 0;
1013         char Namespace[SIZ];
1014
1015         IAPuts("* NAMESPACE ");
1016
1017         /* All personal folders are subordinate to INBOX. */
1018         IAPuts("((\"INBOX/\" \"/\")) ");
1019
1020         /* Other users' folders ... coming soon! FIXME */
1021         IAPuts("NIL ");
1022
1023         /* Show all floors as shared namespaces.  Neato! */
1024         IAPuts("(");
1025         for (i = 0; i < MAXFLOORS; ++i) {
1026                 fl = CtdlGetCachedFloor(i);
1027                 if (fl->f_flags & F_INUSE) {
1028                         /* if (floors > 0) IAPuts(" "); samjam says this confuses javamail */
1029                         IAPuts("(");
1030                         len = snprintf(Namespace, sizeof(Namespace), "%s/", fl->f_name);
1031                         IPutStr(Namespace, len);
1032                         IAPuts(" \"/\")");
1033                         ++floors;
1034                 }
1035         }
1036         IAPuts(")");
1037
1038         /* Wind it up with a newline and a completion message. */
1039         IAPuts("\r\n");
1040         IReply("OK NAMESPACE completed");
1041 }
1042
1043
1044 /*
1045  * Implements the CREATE command
1046  *
1047  */
1048 void imap_create(int num_parms, ConstStr *Params)
1049 {
1050         int ret;
1051         char roomname[ROOMNAMELEN];
1052         int floornum;
1053         int flags;
1054         int newroomtype = 0;
1055         int newroomview = 0;
1056         char *notification_message = NULL;
1057
1058         if (num_parms < 3) {
1059                 IReply("NO A foder name must be specified");
1060                 return;
1061         }
1062
1063         if (strchr(Params[2].Key, '\\') != NULL) {
1064                 IReply("NO Invalid character in folder name");
1065                 syslog(LOG_ERR, "invalid character in folder name");
1066                 return;
1067         }
1068
1069         ret = imap_roomname(roomname, sizeof roomname, Params[2].Key);
1070         if (ret < 0) {
1071                 IReply("NO Invalid mailbox name or location");
1072                 syslog(LOG_ERR, "invalid mailbox name or location");
1073                 return;
1074         }
1075         floornum = (ret & 0x00ff);      /* lower 8 bits = floor number */
1076         flags = (ret & 0xff00); /* upper 8 bits = flags        */
1077
1078         if (flags & IR_MAILBOX) {
1079                 if (strncasecmp(Params[2].Key, "INBOX/", 6)) {
1080                         IReply("NO Personal folders must be created under INBOX");
1081                         syslog(LOG_ERR, "not subordinate to inbox");
1082                         return;
1083                 }
1084         }
1085
1086         if (flags & IR_MAILBOX) {
1087                 newroomtype = 4;                /* private mailbox */
1088                 newroomview = VIEW_MAILBOX;
1089         } else {
1090                 newroomtype = 0;                /* public folder */
1091                 newroomview = VIEW_BBS;
1092         }
1093
1094         syslog(LOG_INFO, "Create new room <%s> on floor <%d> with type <%d>",
1095                     roomname, floornum, newroomtype);
1096
1097         ret = CtdlCreateRoom(roomname, newroomtype, "", floornum, 1, 0, newroomview);
1098         if (ret == 0) {
1099                 /*** DO NOT CHANGE THIS ERROR MESSAGE IN ANY WAY!  BYNARI CONNECTOR DEPENDS ON IT! ***/
1100                 IReply("NO Mailbox already exists, or create failed");
1101         } else {
1102                 IReply("OK CREATE completed");
1103                 /* post a message in Aide> describing the new room */
1104                 notification_message = malloc(1024);
1105                 snprintf(notification_message, 1024,
1106                         "A new room called \"%s\" has been created by %s%s%s%s\n",
1107                         roomname,
1108                         CC->user.fullname,
1109                         ((ret & QR_MAILBOX) ? " [personal]" : ""),
1110                         ((ret & QR_PRIVATE) ? " [private]" : ""),
1111                         ((ret & QR_GUESSNAME) ? " [hidden]" : "")
1112                 );
1113                 CtdlAideMessage(notification_message, "Room Creation Message");
1114                 free(notification_message);
1115         }
1116         syslog(LOG_DEBUG, "imap_create() completed");
1117 }
1118
1119
1120 /*
1121  * Locate a room by its IMAP folder name, and check access to it.
1122  * If zapped_ok is nonzero, we can also look for the room in the zapped list.
1123  */
1124 int imap_grabroom(char *returned_roomname, const char *foldername, int zapped_ok)
1125 {
1126         int ret;
1127         char augmented_roomname[ROOMNAMELEN];
1128         char roomname[ROOMNAMELEN];
1129         int c;
1130         struct ctdlroom QRscratch;
1131         int ra;
1132         int ok = 0;
1133
1134         ret = imap_roomname(roomname, sizeof roomname, foldername);
1135         if (ret < 0) {
1136                 return (1);
1137         }
1138
1139         /* First try a regular match */
1140         c = CtdlGetRoom(&QRscratch, roomname);
1141
1142         /* Then try a mailbox name match */
1143         if (c != 0) {
1144                 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname,
1145                             &CC->user, roomname);
1146                 c = CtdlGetRoom(&QRscratch, augmented_roomname);
1147                 if (c == 0)
1148                         safestrncpy(roomname, augmented_roomname, sizeof(roomname));
1149         }
1150
1151         /* If the room exists, check security/access */
1152         if (c == 0) {
1153                 /* See if there is an existing user/room relationship */
1154                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1155
1156                 /* normal clients have to pass through security */
1157                 if (ra & UA_KNOWN) {
1158                         ok = 1;
1159                 }
1160                 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1161                         ok = 1;
1162                 }
1163         }
1164
1165         /* Fail here if no such room */
1166         if (!ok) {
1167                 strcpy(returned_roomname, "");
1168                 return (2);
1169         } else {
1170                 safestrncpy(returned_roomname, QRscratch.QRname, ROOMNAMELEN);
1171                 return (0);
1172         }
1173 }
1174
1175
1176 /*
1177  * Implements the STATUS command (sort of)
1178  *
1179  */
1180 void imap_status(int num_parms, ConstStr *Params)
1181 {
1182         long len;
1183         int ret;
1184         char roomname[ROOMNAMELEN];
1185         char imaproomname[SIZ];
1186         char savedroom[ROOMNAMELEN];
1187         int msgs, new;
1188
1189         ret = imap_grabroom(roomname, Params[2].Key, 1);
1190         if (ret != 0) {
1191                 IReply("NO Invalid mailbox name or location, or access denied");
1192                 return;
1193         }
1194
1195         /*
1196          * CtdlUserGoto() formally takes us to the desired room, happily returning
1197          * the number of messages and number of new messages.  (If another
1198          * folder is selected, save its name so we can return there!!!!!)
1199          */
1200         if (IMAP->selected) {
1201                 strcpy(savedroom, CC->room.QRname);
1202         }
1203         CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1204
1205         /*
1206          * Tell the client what it wants to know.  In fact, tell it *more* than
1207          * it wants to know.  We happily IGnore the supplied status data item
1208          * names and simply spew all possible data items.  It's far easier to
1209          * code and probably saves us some processing time too.
1210          */
1211         len = imap_mailboxname(imaproomname, sizeof imaproomname, &CC->room);
1212         IAPuts("* STATUS ");
1213         IPutStr(imaproomname, len);
1214         IAPrintf(" (MESSAGES %d ", msgs);
1215         IAPrintf("RECENT %d ", new);    /* Initially, new==recent */
1216         IAPrintf("UIDNEXT %ld ", CtdlGetConfigLong("MMhighest") + 1);
1217         IAPrintf("UNSEEN %d)\r\n", new);
1218         
1219         /*
1220          * If another folder is selected, go back to that room so we can resume
1221          * our happy day without violent explosions.
1222          */
1223         if (IMAP->selected) {
1224                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1225         }
1226
1227         /*
1228          * Oooh, look, we're done!
1229          */
1230         IReply("OK STATUS completed");
1231 }
1232
1233
1234 /*
1235  * Implements the SUBSCRIBE command
1236  *
1237  */
1238 void imap_subscribe(int num_parms, ConstStr *Params)
1239 {
1240         int ret;
1241         char roomname[ROOMNAMELEN];
1242         char savedroom[ROOMNAMELEN];
1243         int msgs, new;
1244
1245         ret = imap_grabroom(roomname, Params[2].Key, 1);
1246         if (ret != 0) {
1247                 IReplyPrintf(
1248                         "NO Error %d: invalid mailbox name or location, or access denied",
1249                         ret
1250                 );
1251                 return;
1252         }
1253
1254         /*
1255          * CtdlUserGoto() formally takes us to the desired room, which has the side
1256          * effect of marking the room as not-zapped ... exactly the effect
1257          * we're looking for.
1258          */
1259         if (IMAP->selected) {
1260                 strcpy(savedroom, CC->room.QRname);
1261         }
1262         CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1263
1264         /*
1265          * If another folder is selected, go back to that room so we can resume
1266          * our happy day without violent explosions.
1267          */
1268         if (IMAP->selected) {
1269                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1270         }
1271
1272         IReply("OK SUBSCRIBE completed");
1273 }
1274
1275
1276 /*
1277  * Implements the UNSUBSCRIBE command
1278  *
1279  */
1280 void imap_unsubscribe(int num_parms, ConstStr *Params)
1281 {
1282         int ret;
1283         char roomname[ROOMNAMELEN];
1284         char savedroom[ROOMNAMELEN];
1285         int msgs, new;
1286
1287         ret = imap_grabroom(roomname, Params[2].Key, 1);
1288         if (ret != 0) {
1289                 IReply("NO Invalid mailbox name or location, or access denied");
1290                 return;
1291         }
1292
1293         /*
1294          * CtdlUserGoto() formally takes us to the desired room.
1295          */
1296         if (IMAP->selected) {
1297                 strcpy(savedroom, CC->room.QRname);
1298         }
1299         CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1300
1301         /* 
1302          * Now make the API call to zap the room
1303          */
1304         if (CtdlForgetThisRoom() == 0) {
1305                 IReply("OK UNSUBSCRIBE completed");
1306         } else {
1307                 IReply("NO You may not unsubscribe from this folder.");
1308         }
1309
1310         /*
1311          * If another folder is selected, go back to that room so we can resume
1312          * our happy day without violent explosions.
1313          */
1314         if (IMAP->selected) {
1315                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1316         }
1317 }
1318
1319
1320 /*
1321  * Implements the DELETE command
1322  *
1323  */
1324 void imap_delete(int num_parms, ConstStr *Params)
1325 {
1326         int ret;
1327         char roomname[ROOMNAMELEN];
1328         char savedroom[ROOMNAMELEN];
1329         int msgs, new;
1330
1331         ret = imap_grabroom(roomname, Params[2].Key, 1);
1332         if (ret != 0) {
1333                 IReply("NO Invalid mailbox name, or access denied");
1334                 return;
1335         }
1336
1337         /*
1338          * CtdlUserGoto() formally takes us to the desired room, happily returning
1339          * the number of messages and number of new messages.  (If another
1340          * folder is selected, save its name so we can return there!!!!!)
1341          */
1342         if (IMAP->selected) {
1343                 strcpy(savedroom, CC->room.QRname);
1344         }
1345         CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1346
1347         /*
1348          * Now delete the room.
1349          */
1350         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1351                 CtdlScheduleRoomForDeletion(&CC->room);
1352                 IReply("OK DELETE completed");
1353         } else {
1354                 IReply("NO Can't delete this folder.");
1355         }
1356
1357         /*
1358          * If another folder is selected, go back to that room so we can resume
1359          * our happy day without violent explosions.
1360          */
1361         if (IMAP->selected) {
1362                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1363         }
1364 }
1365
1366
1367 /*
1368  * Back end function for imap_rename()
1369  */
1370 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1371 {
1372         char foldername[SIZ];
1373         char newfoldername[SIZ];
1374         char newroomname[ROOMNAMELEN];
1375         int newfloor = 0;
1376         struct irl *irlp = NULL;        /* scratch pointer */
1377         irlparms *myirlparms;
1378
1379         myirlparms = (irlparms *) data;
1380         imap_mailboxname(foldername, sizeof foldername, qrbuf);
1381
1382         /* Rename subfolders */
1383         if ((!strncasecmp(foldername, myirlparms->oldname,
1384                           myirlparms->oldnamelen)
1385             && (foldername[myirlparms->oldnamelen] == '/'))) {
1386
1387                 sprintf(newfoldername, "%s/%s",
1388                         myirlparms->newname,
1389                         &foldername[myirlparms->oldnamelen + 1]
1390                     );
1391
1392                 newfloor = imap_roomname(newroomname,
1393                                          sizeof newroomname,
1394                                          newfoldername) & 0xFF;
1395
1396                 irlp = (struct irl *) malloc(sizeof(struct irl));
1397                 strcpy(irlp->irl_newroom, newroomname);
1398                 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1399                 irlp->irl_newfloor = newfloor;
1400                 irlp->next = *(myirlparms->irl);
1401                 *(myirlparms->irl) = irlp;
1402         }
1403 }
1404
1405
1406 /*
1407  * Implements the RENAME command
1408  *
1409  */
1410 void imap_rename(int num_parms, ConstStr *Params)
1411 {
1412         char old_room[ROOMNAMELEN];
1413         char new_room[ROOMNAMELEN];
1414         int newr;
1415         int new_floor;
1416         int r;
1417         struct irl *irl = NULL; /* the list */
1418         struct irl *irlp = NULL;        /* scratch pointer */
1419         irlparms irlparms;
1420         char aidemsg[1024];
1421
1422         if (strchr(Params[3].Key, '\\') != NULL) {
1423                 IReply("NO Invalid character in folder name");
1424                 return;
1425         }
1426
1427         imap_roomname(old_room, sizeof old_room, Params[2].Key);
1428         newr = imap_roomname(new_room, sizeof new_room, Params[3].Key);
1429         new_floor = (newr & 0xFF);
1430
1431         r = CtdlRenameRoom(old_room, new_room, new_floor);
1432
1433         if (r == crr_room_not_found) {
1434                 IReply("NO Could not locate this folder");
1435                 return;
1436         }
1437         if (r == crr_already_exists) {
1438                 IReplyPrintf("NO '%s' already exists.");
1439                 return;
1440         }
1441         if (r == crr_noneditable) {
1442                 IReply("NO This folder is not editable.");
1443                 return;
1444         }
1445         if (r == crr_invalid_floor) {
1446                 IReply("NO Folder root does not exist.");
1447                 return;
1448         }
1449         if (r == crr_access_denied) {
1450                 IReply("NO You do not have permission to edit this folder.");
1451                 return;
1452         }
1453         if (r != crr_ok) {
1454                 IReplyPrintf("NO Rename failed - undefined error %d", r);
1455                 return;
1456         }
1457
1458         /* If this is the INBOX, then RFC2060 says we have to just move the
1459          * contents.  In a Citadel environment it's easier to rename the room
1460          * (already did that) and create a new inbox.
1461          */
1462         if (!strcasecmp(Params[2].Key, "INBOX")) {
1463                 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1464         }
1465
1466         /* Otherwise, do the subfolders.  Build a list of rooms to rename... */
1467         else {
1468                 irlparms.oldname = Params[2].Key;
1469                 irlparms.oldnamelen = Params[2].len;
1470                 irlparms.newname = Params[3].Key;
1471                 irlparms.newnamelen = Params[3].len;
1472                 irlparms.irl = &irl;
1473                 CtdlForEachRoom(imap_rename_backend, (void *) &irlparms);
1474
1475                 /* ... and now rename them. */
1476                 while (irl != NULL) {
1477                         r = CtdlRenameRoom(irl->irl_oldroom,
1478                                            irl->irl_newroom,
1479                                            irl->irl_newfloor);
1480                         if (r != crr_ok) {
1481                                 /* FIXME handle error returns better */
1482                                 syslog(LOG_ERR, "CtdlRenameRoom() error %d", r);
1483                         }
1484                         irlp = irl;
1485                         irl = irl->next;
1486                         free(irlp);
1487                 }
1488         }
1489
1490         snprintf(aidemsg, sizeof aidemsg, "IMAP folder \"%s\" renamed to \"%s\" by %s\n",
1491                 Params[2].Key,
1492                 Params[3].Key,
1493                 CC->curr_user
1494         );
1495         CtdlAideMessage(aidemsg, "IMAP folder rename");
1496
1497         IReply("OK RENAME completed");
1498 }
1499
1500
1501 /* 
1502  * Main command loop for IMAP sessions.
1503  */
1504 void imap_command_loop(void)
1505 {
1506         struct CitContext *CCC = CC;
1507         struct timeval tv1, tv2;
1508         suseconds_t total_time = 0;
1509         citimap *Imap;
1510         const char *pchs, *pche;
1511         const imap_handler_hook *h;
1512
1513         gettimeofday(&tv1, NULL);
1514         CCC->lastcmd = time(NULL);
1515         Imap = CCCIMAP;
1516
1517         flush_output();
1518         if (Imap->Cmd.CmdBuf == NULL)
1519                 Imap->Cmd.CmdBuf = NewStrBufPlain(NULL, SIZ);
1520         else
1521                 FlushStrBuf(Imap->Cmd.CmdBuf);
1522
1523         if (CtdlClientGetLine(Imap->Cmd.CmdBuf) < 1) {
1524                 syslog(LOG_ERR, "client disconnected: ending session.");
1525                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1526                 return;
1527         }
1528
1529         if (Imap->authstate == imap_as_expecting_password) {
1530                 syslog(LOG_INFO, "<password>");
1531         }
1532         else if (Imap->authstate == imap_as_expecting_plainauth) {
1533                 syslog(LOG_INFO, "<plain_auth>");
1534         }
1535         else if ((Imap->authstate == imap_as_expecting_multilineusername) || 
1536                  cbmstrcasestr(ChrPtr(Imap->Cmd.CmdBuf), " LOGIN ")) {
1537                 syslog(LOG_INFO, "LOGIN...");
1538         }
1539         else {
1540                 syslog(LOG_DEBUG, "%s", ChrPtr(Imap->Cmd.CmdBuf));
1541         }
1542
1543         pchs = ChrPtr(Imap->Cmd.CmdBuf);
1544         pche = pchs + StrLength(Imap->Cmd.CmdBuf);
1545
1546         while ((pche > pchs) &&
1547                ((*pche == '\n') ||
1548                 (*pche == '\r')))
1549         {
1550                 pche --;
1551                 StrBufCutRight(Imap->Cmd.CmdBuf, 1);
1552         }
1553         StrBufTrim(Imap->Cmd.CmdBuf);
1554
1555         /* If we're in the middle of a multi-line command, handle that */
1556         switch (Imap->authstate){
1557         case imap_as_expecting_username:
1558                 imap_auth_login_user(imap_as_expecting_username);
1559                 IUnbuffer();
1560                 return;
1561         case imap_as_expecting_multilineusername:
1562                 imap_auth_login_user(imap_as_expecting_multilineusername);
1563                 IUnbuffer();
1564                 return;
1565         case imap_as_expecting_plainauth:
1566                 imap_auth_plain();
1567                 IUnbuffer();
1568                 return;
1569         case imap_as_expecting_password:
1570                 imap_auth_login_pass(imap_as_expecting_password);
1571                 IUnbuffer();
1572                 return;
1573         case imap_as_expecting_multilinepassword:
1574                 imap_auth_login_pass(imap_as_expecting_multilinepassword);
1575                 IUnbuffer();
1576                 return;
1577         default:
1578                 break;
1579         }
1580
1581         /* Ok, at this point we're in normal command mode.
1582          * If the command just submitted does not contain a literal, we
1583          * might think about delivering some untagged stuff...
1584          */
1585
1586         /* Grab the tag, command, and parameters. */
1587         imap_parameterize(&Imap->Cmd);
1588 #if 0 
1589 /* debug output the parsed vector */
1590         {
1591                 int i;
1592                 syslog(LOG_DEBUG, "----- %ld params", Imap->Cmd.num_parms);
1593
1594         for (i=0; i < Imap->Cmd.num_parms; i++) {
1595                 if (Imap->Cmd.Params[i].len != strlen(Imap->Cmd.Params[i].Key))
1596                         syslog(LOG_DEBUG, "*********** %ld != %ld : %s",
1597                                     Imap->Cmd.Params[i].len, 
1598                                     strlen(Imap->Cmd.Params[i].Key),
1599                                       Imap->Cmd.Params[i].Key);
1600                 else
1601                         syslog(LOG_DEBUG, "%ld : %s",
1602                                     Imap->Cmd.Params[i].len, 
1603                                     Imap->Cmd.Params[i].Key);
1604         }}
1605 #endif
1606
1607         /* Now for the command set. */
1608         h = imap_lookup(Imap->Cmd.num_parms, Imap->Cmd.Params);
1609
1610         if (h == NULL)
1611         {
1612                 IReply("BAD command unrecognized");
1613                 goto BAIL;
1614         }
1615
1616         /* RFC3501 says that we cannot output untagged data during these commands */
1617         if ((h->Flags & I_FLAG_UNTAGGED) == 0) {
1618
1619                 /* we can put any additional untagged stuff right here in the future */
1620
1621                 /*
1622                  * Before processing the command that was just entered... if we happen
1623                  * to have a folder selected, we'd like to rescan that folder for new
1624                  * messages, and for deletions/changes of existing messages.  This
1625                  * could probably be optimized better with some deep thought...
1626                  */
1627                 if (Imap->selected) {
1628                         imap_rescan_msgids();
1629                 }
1630         }
1631
1632         /* does our command require a logged-in state */
1633         if ((!CC->logged_in) && ((h->Flags & I_FLAG_LOGGED_IN) != 0)) {
1634                 IReply("BAD Not logged in.");
1635                 goto BAIL;
1636         }
1637
1638         /* does our command require the SELECT state on a mailbox */
1639         if ((Imap->selected == 0) && ((h->Flags & I_FLAG_SELECT) != 0)){
1640                 IReply("BAD no folder selected");
1641                 goto BAIL;
1642         }
1643         h->h(Imap->Cmd.num_parms, Imap->Cmd.Params);
1644
1645         /* If the client transmitted a message we can free it now */
1646
1647 BAIL:
1648         IUnbuffer();
1649
1650         imap_free_transmitted_message();
1651
1652         gettimeofday(&tv2, NULL);
1653         total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1654         syslog(LOG_DEBUG, "IMAP command completed in %ld.%ld seconds",
1655                     (total_time / 1000000),
1656                     (total_time % 1000000)
1657                 );
1658 }
1659
1660 void imap_noop (int num_parms, ConstStr *Params)
1661 {
1662         IReply("OK No operation");
1663 }
1664
1665 void imap_logout(int num_parms, ConstStr *Params)
1666 {
1667         if (IMAP->selected) {
1668                 imap_do_expunge();      /* yes, we auto-expunge at logout */
1669         }
1670         IAPrintf("* BYE %s logging out\r\n", CtdlGetConfigStr("c_fqdn"));
1671         IReply("OK Citadel IMAP session ended.");
1672         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1673         return;
1674 }
1675
1676 const char *CitadelServiceIMAP="IMAP";
1677 const char *CitadelServiceIMAPS="IMAPS";
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                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_imap_port"),
1735                                         NULL, imap_greeting, imap_command_loop, NULL, CitadelServiceIMAP);
1736 #ifdef HAVE_OPENSSL
1737                 CtdlRegisterServiceHook(CtdlGetConfigInt("c_imaps_port"),
1738                                         NULL, imaps_greeting, imap_command_loop, NULL, CitadelServiceIMAPS);
1739 #endif
1740                 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP, PRIO_STOP + 30);
1741                 CtdlRegisterCleanupHook(imap_cleanup);
1742         }
1743         
1744         /* return our module name for the log */
1745         return "imap";
1746 }