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