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