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