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