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