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