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