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