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