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