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