]> code.citadel.org Git - citadel.git/blob - citadel/serv_imap.c
Don't advertise the ACL extension. It isn't finished
[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         cprintf("CAPABILITY IMAP4REV1 NAMESPACE ID AUTH=LOGIN");
440 #ifdef HAVE_OPENSSL
441         if (!CC->redirect_ssl) cprintf(" STARTTLS");
442 #endif
443 }
444
445 /*
446  * implements the CAPABILITY command
447  */
448 void imap_capability(int num_parms, char *parms[])
449 {
450         cprintf("* ");
451         imap_output_capability_string();
452         cprintf("\r\n");
453         cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
454 }
455
456
457
458 /*
459  * Implements the ID command (specified by RFC2971)
460  *
461  * We ignore the client-supplied information, and output a NIL response.
462  * Although this is technically a valid implementation of the extension, it
463  * is quite useless.  It exists only so that we may see which clients are
464  * making use of this extension.
465  * 
466  */
467 void imap_id(int num_parms, char *parms[])
468 {
469         cprintf("* ID NIL\r\n");
470         cprintf("%s OK ID completed\r\n", parms[0]);
471 }
472
473
474
475 /*
476  * Here's where our IMAP session begins its happy day.
477  */
478 void imap_greeting(void)
479 {
480
481         strcpy(CC->cs_clientname, "IMAP session");
482         IMAP = malloc(sizeof (struct citimap));
483         memset(IMAP, 0, sizeof(struct citimap));
484         IMAP->authstate = imap_as_normal;
485         IMAP->cached_rfc822_data = NULL;
486         IMAP->cached_rfc822_msgnum = (-1);
487         IMAP->cached_rfc822_withbody = 0;
488
489         cprintf("* OK [");
490         imap_output_capability_string();
491         cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
492 }
493
494 /*
495  * IMAPS is just like IMAP, except it goes crypto right away.
496  */
497 #ifdef HAVE_OPENSSL
498 void imaps_greeting(void) {
499         CtdlStartTLS(NULL, NULL, NULL);
500         imap_greeting();
501 }
502 #endif
503
504
505 /*
506  * implements the LOGIN command (ordinary username/password login)
507  */
508 void imap_login(int num_parms, char *parms[])
509 {
510         if (num_parms != 4) {
511                 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
512                 return;
513         }
514
515         if (CtdlLoginExistingUser(parms[2]) == login_ok) {
516                 if (CtdlTryPassword(parms[3]) == pass_ok) {
517                         cprintf("%s OK [", parms[0]);
518                         imap_output_capability_string();
519                         cprintf("] Hello, %s\r\n", CC->user.fullname);
520                         return;
521                 }
522         }
523
524         cprintf("%s BAD Login incorrect\r\n", parms[0]);
525 }
526
527
528 /*
529  * Implements the AUTHENTICATE command
530  */
531 void imap_authenticate(int num_parms, char *parms[])
532 {
533         char buf[SIZ];
534
535         if (num_parms != 3) {
536                 cprintf("%s BAD incorrect number of parameters\r\n",
537                         parms[0]);
538                 return;
539         }
540
541         if (CC->logged_in) {
542                 cprintf("%s BAD Already logged in.\r\n", parms[0]);
543                 return;
544         }
545
546         if (!strcasecmp(parms[2], "LOGIN")) {
547                 CtdlEncodeBase64(buf, "Username:", 9);
548                 cprintf("+ %s\r\n", buf);
549                 IMAP->authstate = imap_as_expecting_username;
550                 strcpy(IMAP->authseq, parms[0]);
551                 return;
552         }
553
554         else {
555                 cprintf("%s NO AUTHENTICATE %s failed\r\n",
556                         parms[0], parms[1]);
557         }
558 }
559
560 void imap_auth_login_user(char *cmd)
561 {
562         char buf[SIZ];
563
564         CtdlDecodeBase64(buf, cmd, SIZ);
565         CtdlLoginExistingUser(buf);
566         CtdlEncodeBase64(buf, "Password:", 9);
567         cprintf("+ %s\r\n", buf);
568         IMAP->authstate = imap_as_expecting_password;
569         return;
570 }
571
572 void imap_auth_login_pass(char *cmd)
573 {
574         char buf[SIZ];
575
576         CtdlDecodeBase64(buf, cmd, SIZ);
577         if (CtdlTryPassword(buf) == pass_ok) {
578                 cprintf("%s OK authentication succeeded\r\n",
579                         IMAP->authseq);
580         } else {
581                 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
582         }
583         IMAP->authstate = imap_as_normal;
584         return;
585 }
586
587
588 /*
589  * implements the STARTTLS command (Citadel API version)
590  */
591 #ifdef HAVE_OPENSSL
592 void imap_starttls(int num_parms, char *parms[])
593 {
594         char ok_response[SIZ];
595         char nosup_response[SIZ];
596         char error_response[SIZ];
597
598         sprintf(ok_response,
599                 "%s OK begin TLS negotiation now\r\n",
600                 parms[0]);
601         sprintf(nosup_response,
602                 "%s NO TLS not supported here\r\n",
603                 parms[0]);
604         sprintf(error_response,
605                 "%s BAD Internal error\r\n",
606                 parms[0]);
607         CtdlStartTLS(ok_response, nosup_response, error_response);
608 }
609 #endif
610
611
612 /*
613  * implements the SELECT command
614  */
615 void imap_select(int num_parms, char *parms[])
616 {
617         char towhere[SIZ];
618         char augmented_roomname[ROOMNAMELEN];
619         int c = 0;
620         int ok = 0;
621         int ra = 0;
622         struct ctdlroom QRscratch;
623         int msgs, new;
624         int floornum;
625         int roomflags;
626         int i;
627
628         /* Convert the supplied folder name to a roomname */
629         i = imap_roomname(towhere, sizeof towhere, parms[2]);
630         if (i < 0) {
631                 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
632                 IMAP->selected = 0;
633                 return;
634         }
635         floornum = (i & 0x00ff);
636         roomflags = (i & 0xff00);
637
638         /* First try a regular match */
639         c = getroom(&QRscratch, towhere);
640
641         /* Then try a mailbox name match */
642         if (c != 0) {
643                 MailboxName(augmented_roomname, sizeof augmented_roomname,
644                             &CC->user, towhere);
645                 c = getroom(&QRscratch, augmented_roomname);
646                 if (c == 0)
647                         strcpy(towhere, augmented_roomname);
648         }
649
650         /* If the room exists, check security/access */
651         if (c == 0) {
652                 /* See if there is an existing user/room relationship */
653                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
654
655                 /* normal clients have to pass through security */
656                 if (ra & UA_KNOWN) {
657                         ok = 1;
658                 }
659         }
660
661         /* Fail here if no such room */
662         if (!ok) {
663                 cprintf("%s NO ... no such room, or access denied\r\n",
664                         parms[0]);
665                 return;
666         }
667
668         /* If we already had some other folder selected, auto-expunge it */
669         imap_do_expunge();
670
671         /*
672          * usergoto() formally takes us to the desired room, happily returning
673          * the number of messages and number of new messages.
674          */
675         memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
676         usergoto(NULL, 0, 0, &msgs, &new);
677         IMAP->selected = 1;
678
679         if (!strcasecmp(parms[1], "EXAMINE")) {
680                 IMAP->readonly = 1;
681         } else {
682                 IMAP->readonly = 0;
683         }
684
685         imap_load_msgids();
686         IMAP->last_mtime = CC->room.QRmtime;
687
688         cprintf("* %d EXISTS\r\n", msgs);
689         cprintf("* %d RECENT\r\n", new);
690
691         cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
692         cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
693
694         /* Note that \Deleted is a valid flag, but not a permanent flag,
695          * because we don't maintain its state across sessions.  Citadel
696          * automatically expunges mailboxes when they are de-selected.
697          */
698         cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
699         cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] "
700                 "permanent flags\r\n");
701
702         cprintf("%s OK [%s] %s completed\r\n",
703                 parms[0],
704                 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
705 }
706
707
708
709 /*
710  * Does the real work for expunge.
711  */
712 int imap_do_expunge(void)
713 {
714         int i;
715         int num_expunged = 0;
716         long *delmsgs = NULL;
717         int num_delmsgs = 0;
718
719         lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
720         if (IMAP->selected == 0) {
721                 return (0);
722         }
723
724         if (IMAP->num_msgs > 0) {
725                 delmsgs = malloc(IMAP->num_msgs * sizeof(long));
726                 for (i = 0; i < IMAP->num_msgs; ++i) {
727                         if (IMAP->flags[i] & IMAP_DELETED) {
728                                 delmsgs[num_delmsgs++] = IMAP->msgids[i];
729                         }
730                 }
731                 if (num_delmsgs > 0) {
732                         CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
733                 }
734                 num_expunged += num_delmsgs;
735                 free(delmsgs);
736         }
737
738         if (num_expunged > 0) {
739                 imap_rescan_msgids();
740         }
741
742         lprintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n",
743                 num_expunged, CC->room.QRname);
744         return (num_expunged);
745 }
746
747
748 /*
749  * implements the EXPUNGE command syntax
750  */
751 void imap_expunge(int num_parms, char *parms[])
752 {
753         int num_expunged = 0;
754
755         num_expunged = imap_do_expunge();
756         cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
757 }
758
759
760 /*
761  * implements the CLOSE command
762  */
763 void imap_close(int num_parms, char *parms[])
764 {
765
766         /* Yes, we always expunge on close. */
767         if (IMAP->selected) {
768                 imap_do_expunge();
769         }
770
771         IMAP->selected = 0;
772         IMAP->readonly = 0;
773         imap_free_msgids();
774         cprintf("%s OK CLOSE completed\r\n", parms[0]);
775 }
776
777
778 /*
779  * Implements the NAMESPACE command.
780  */
781 void imap_namespace(int num_parms, char *parms[])
782 {
783         int i;
784         struct floor *fl;
785         int floors = 0;
786         char buf[SIZ];
787
788         cprintf("* NAMESPACE ");
789
790         /* All personal folders are subordinate to INBOX. */
791         cprintf("((\"INBOX/\" \"/\")) ");
792
793         /* Other users' folders ... coming soon! FIXME */
794         cprintf("NIL ");
795
796         /* Show all floors as shared namespaces.  Neato! */
797         cprintf("(");
798         for (i = 0; i < MAXFLOORS; ++i) {
799                 fl = cgetfloor(i);
800                 if (fl->f_flags & F_INUSE) {
801                         if (floors > 0) cprintf(" ");
802                         cprintf("(");
803                         sprintf(buf, "%s/", fl->f_name);
804                         imap_strout(buf);
805                         cprintf(" \"/\")");
806                         ++floors;
807                 }
808         }
809         cprintf(")");
810
811         /* Wind it up with a newline and a completion message. */
812         cprintf("\r\n");
813         cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
814 }
815
816
817
818 /*
819  * Used by LIST and LSUB to show the floors in the listing
820  */
821 void imap_list_floors(char *cmd, char *pattern)
822 {
823         int i;
824         struct floor *fl;
825
826         for (i = 0; i < MAXFLOORS; ++i) {
827                 fl = cgetfloor(i);
828                 if (fl->f_flags & F_INUSE) {
829                         if (imap_mailbox_matches_pattern
830                             (pattern, fl->f_name)) {
831                                 cprintf("* %s (\\NoSelect) \"/\" ", cmd);
832                                 imap_strout(fl->f_name);
833                                 cprintf("\r\n");
834                         }
835                 }
836         }
837 }
838
839
840
841 /*
842  * Back end for imap_lsub()
843  *
844  * IMAP "subscribed folder" is equivocated to Citadel "known rooms."  This
845  * may or may not be the desired behavior in the future.
846  */
847 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data)
848 {
849         char buf[SIZ];
850         int ra;
851         char *pattern;
852
853         pattern = (char *) data;
854
855         /* Only list rooms to which the user has access!! */
856         CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
857         if (ra & UA_KNOWN) {
858                 imap_mailboxname(buf, sizeof buf, qrbuf);
859                 if (imap_mailbox_matches_pattern(pattern, buf)) {
860                         cprintf("* LSUB () \"/\" ");
861                         imap_strout(buf);
862                         cprintf("\r\n");
863                 }
864         }
865 }
866
867
868 /*
869  * Implements the LSUB command
870  */
871 void imap_lsub(int num_parms, char *parms[])
872 {
873         char pattern[SIZ];
874         if (num_parms < 4) {
875                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
876                 return;
877         }
878         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
879
880         if (strlen(parms[3]) == 0) {
881                 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
882         }
883
884         else {
885                 imap_list_floors("LSUB", pattern);
886                 ForEachRoom(imap_lsub_listroom, pattern);
887         }
888
889         cprintf("%s OK LSUB completed\r\n", parms[0]);
890 }
891
892
893
894 /*
895  * Back end for imap_list()
896  */
897 void imap_list_listroom(struct ctdlroom *qrbuf, void *data)
898 {
899         char buf[SIZ];
900         int ra;
901         char *pattern;
902
903         pattern = (char *) data;
904
905         /* Only list rooms to which the user has access!! */
906         CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
907         if ((ra & UA_KNOWN)
908             || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
909                 imap_mailboxname(buf, sizeof buf, qrbuf);
910                 if (imap_mailbox_matches_pattern(pattern, buf)) {
911                         cprintf("* LIST () \"/\" ");
912                         imap_strout(buf);
913                         cprintf("\r\n");
914                 }
915         }
916 }
917
918
919 /*
920  * Implements the LIST command
921  */
922 void imap_list(int num_parms, char *parms[])
923 {
924         char pattern[SIZ];
925         if (num_parms < 4) {
926                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
927                 return;
928         }
929         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
930
931         if (strlen(parms[3]) == 0) {
932                 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
933         }
934
935         else {
936                 imap_list_floors("LIST", pattern);
937                 ForEachRoom(imap_list_listroom, pattern);
938         }
939
940         cprintf("%s OK LIST completed\r\n", parms[0]);
941 }
942
943
944
945 /*
946  * Implements the CREATE command
947  *
948  */
949 void imap_create(int num_parms, char *parms[])
950 {
951         int ret;
952         char roomname[ROOMNAMELEN];
953         int floornum;
954         int flags;
955         int newroomtype = 0;
956         int newroomview = 0;
957
958         if (strchr(parms[2], '\\') != NULL) {
959                 cprintf("%s NO Invalid character in folder name\r\n",
960                         parms[0]);
961                 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
962                 return;
963         }
964
965         ret = imap_roomname(roomname, sizeof roomname, parms[2]);
966         if (ret < 0) {
967                 cprintf("%s NO Invalid mailbox name or location\r\n",
968                         parms[0]);
969                 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
970                 return;
971         }
972         floornum = (ret & 0x00ff);      /* lower 8 bits = floor number */
973         flags = (ret & 0xff00); /* upper 8 bits = flags        */
974
975         if (flags & IR_MAILBOX) {
976                 if (strncasecmp(parms[2], "INBOX/", 6)) {
977                         cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
978                         lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
979                         return;
980                 }
981         }
982
983         if (flags & IR_MAILBOX) {
984                 newroomtype = 4;                /* private mailbox */
985                 newroomview = VIEW_MAILBOX;
986         } else {
987                 newroomtype = 0;                /* public folder */
988                 newroomview = VIEW_BBS;
989         }
990
991         lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
992                 roomname, floornum, newroomtype);
993
994         ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
995         if (ret == 0) {
996                 cprintf
997                     ("%s NO Mailbox already exists, or create failed\r\n",
998                      parms[0]);
999         } else {
1000                 cprintf("%s OK CREATE completed\r\n", parms[0]);
1001         }
1002         lprintf(CTDL_DEBUG, "imap_create() completed\n");
1003 }
1004
1005
1006 /*
1007  * Locate a room by its IMAP folder name, and check access to it.
1008  * If zapped_ok is nonzero, we can also look for the room in the zapped list.
1009  */
1010 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
1011 {
1012         int ret;
1013         char augmented_roomname[ROOMNAMELEN];
1014         char roomname[ROOMNAMELEN];
1015         int c;
1016         struct ctdlroom QRscratch;
1017         int ra;
1018         int ok = 0;
1019
1020         ret = imap_roomname(roomname, sizeof roomname, foldername);
1021         if (ret < 0) {
1022                 return (1);
1023         }
1024
1025         /* First try a regular match */
1026         c = getroom(&QRscratch, roomname);
1027
1028         /* Then try a mailbox name match */
1029         if (c != 0) {
1030                 MailboxName(augmented_roomname, sizeof augmented_roomname,
1031                             &CC->user, roomname);
1032                 c = getroom(&QRscratch, augmented_roomname);
1033                 if (c == 0)
1034                         strcpy(roomname, augmented_roomname);
1035         }
1036
1037         /* If the room exists, check security/access */
1038         if (c == 0) {
1039                 /* See if there is an existing user/room relationship */
1040                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1041
1042                 /* normal clients have to pass through security */
1043                 if (ra & UA_KNOWN) {
1044                         ok = 1;
1045                 }
1046                 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1047                         ok = 1;
1048                 }
1049         }
1050
1051         /* Fail here if no such room */
1052         if (!ok) {
1053                 strcpy(returned_roomname, "");
1054                 return (2);
1055         } else {
1056                 strcpy(returned_roomname, QRscratch.QRname);
1057                 return (0);
1058         }
1059 }
1060
1061
1062 /*
1063  * Implements the STATUS command (sort of)
1064  *
1065  */
1066 void imap_status(int num_parms, char *parms[])
1067 {
1068         int ret;
1069         char roomname[ROOMNAMELEN];
1070         char buf[SIZ];
1071         char savedroom[ROOMNAMELEN];
1072         int msgs, new;
1073
1074         ret = imap_grabroom(roomname, parms[2], 0);
1075         if (ret != 0) {
1076                 cprintf
1077                     ("%s NO Invalid mailbox name or location, or access denied\r\n",
1078                      parms[0]);
1079                 return;
1080         }
1081
1082         /*
1083          * usergoto() formally takes us to the desired room, happily returning
1084          * the number of messages and number of new messages.  (If another
1085          * folder is selected, save its name so we can return there!!!!!)
1086          */
1087         if (IMAP->selected) {
1088                 strcpy(savedroom, CC->room.QRname);
1089         }
1090         usergoto(roomname, 0, 0, &msgs, &new);
1091
1092         /*
1093          * Tell the client what it wants to know.  In fact, tell it *more* than
1094          * it wants to know.  We happily IGnore the supplied status data item
1095          * names and simply spew all possible data items.  It's far easier to
1096          * code and probably saves us some processing time too.
1097          */
1098         imap_mailboxname(buf, sizeof buf, &CC->room);
1099         cprintf("* STATUS ");
1100         imap_strout(buf);
1101         cprintf(" (MESSAGES %d ", msgs);
1102         cprintf("RECENT %d ", new);     /* Initially, new==recent */
1103         cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1104         cprintf("UNSEEN %d)\r\n", new);
1105
1106         /*
1107          * If another folder is selected, go back to that room so we can resume
1108          * our happy day without violent explosions.
1109          */
1110         if (IMAP->selected) {
1111                 usergoto(savedroom, 0, 0, &msgs, &new);
1112         }
1113
1114         /*
1115          * Oooh, look, we're done!
1116          */
1117         cprintf("%s OK STATUS completed\r\n", parms[0]);
1118 }
1119
1120
1121
1122 /*
1123  * Implements the SUBSCRIBE command
1124  *
1125  */
1126 void imap_subscribe(int num_parms, char *parms[])
1127 {
1128         int ret;
1129         char roomname[ROOMNAMELEN];
1130         char savedroom[ROOMNAMELEN];
1131         int msgs, new;
1132
1133         ret = imap_grabroom(roomname, parms[2], 1);
1134         if (ret != 0) {
1135                 cprintf(
1136                         "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1137                         parms[0],
1138                         ret
1139                 );
1140                 return;
1141         }
1142
1143         /*
1144          * usergoto() formally takes us to the desired room, which has the side
1145          * effect of marking the room as not-zapped ... exactly the effect
1146          * we're looking for.
1147          */
1148         if (IMAP->selected) {
1149                 strcpy(savedroom, CC->room.QRname);
1150         }
1151         usergoto(roomname, 0, 0, &msgs, &new);
1152
1153         /*
1154          * If another folder is selected, go back to that room so we can resume
1155          * our happy day without violent explosions.
1156          */
1157         if (IMAP->selected) {
1158                 usergoto(savedroom, 0, 0, &msgs, &new);
1159         }
1160
1161         cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1162 }
1163
1164
1165 /*
1166  * Implements the UNSUBSCRIBE command
1167  *
1168  */
1169 void imap_unsubscribe(int num_parms, char *parms[])
1170 {
1171         int ret;
1172         char roomname[ROOMNAMELEN];
1173         char savedroom[ROOMNAMELEN];
1174         int msgs, new;
1175
1176         ret = imap_grabroom(roomname, parms[2], 0);
1177         if (ret != 0) {
1178                 cprintf
1179                     ("%s NO Invalid mailbox name or location, or access denied\r\n",
1180                      parms[0]);
1181                 return;
1182         }
1183
1184         /*
1185          * usergoto() formally takes us to the desired room.
1186          */
1187         if (IMAP->selected) {
1188                 strcpy(savedroom, CC->room.QRname);
1189         }
1190         usergoto(roomname, 0, 0, &msgs, &new);
1191
1192         /* 
1193          * Now make the API call to zap the room
1194          */
1195         if (CtdlForgetThisRoom() == 0) {
1196                 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1197         } else {
1198                 cprintf
1199                     ("%s NO You may not unsubscribe from this folder.\r\n",
1200                      parms[0]);
1201         }
1202
1203         /*
1204          * If another folder is selected, go back to that room so we can resume
1205          * our happy day without violent explosions.
1206          */
1207         if (IMAP->selected) {
1208                 usergoto(savedroom, 0, 0, &msgs, &new);
1209         }
1210 }
1211
1212
1213
1214 /*
1215  * Implements the DELETE command
1216  *
1217  */
1218 void imap_delete(int num_parms, char *parms[])
1219 {
1220         int ret;
1221         char roomname[ROOMNAMELEN];
1222         char savedroom[ROOMNAMELEN];
1223         int msgs, new;
1224
1225         ret = imap_grabroom(roomname, parms[2], 1);
1226         if (ret != 0) {
1227                 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1228                         parms[0]);
1229                 return;
1230         }
1231
1232         /*
1233          * usergoto() formally takes us to the desired room, happily returning
1234          * the number of messages and number of new messages.  (If another
1235          * folder is selected, save its name so we can return there!!!!!)
1236          */
1237         if (IMAP->selected) {
1238                 strcpy(savedroom, CC->room.QRname);
1239         }
1240         usergoto(roomname, 0, 0, &msgs, &new);
1241
1242         /*
1243          * Now delete the room.
1244          */
1245         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1246                 schedule_room_for_deletion(&CC->room);
1247                 cprintf("%s OK DELETE completed\r\n", parms[0]);
1248         } else {
1249                 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1250         }
1251
1252         /*
1253          * If another folder is selected, go back to that room so we can resume
1254          * our happy day without violent explosions.
1255          */
1256         if (IMAP->selected) {
1257                 usergoto(savedroom, 0, 0, &msgs, &new);
1258         }
1259 }
1260
1261
1262 /*
1263  * Back end function for imap_rename()
1264  */
1265 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1266 {
1267         char foldername[SIZ];
1268         char newfoldername[SIZ];
1269         char newroomname[ROOMNAMELEN];
1270         int newfloor = 0;
1271         struct irl *irlp = NULL;        /* scratch pointer */
1272         struct irlparms *irlparms;
1273
1274         irlparms = (struct irlparms *) data;
1275         imap_mailboxname(foldername, sizeof foldername, qrbuf);
1276
1277         /* Rename subfolders */
1278         if ((!strncasecmp(foldername, irlparms->oldname,
1279                           strlen(irlparms->oldname))
1280              && (foldername[strlen(irlparms->oldname)] == '/'))) {
1281
1282                 sprintf(newfoldername, "%s/%s",
1283                         irlparms->newname,
1284                         &foldername[strlen(irlparms->oldname) + 1]
1285                     );
1286
1287                 newfloor = imap_roomname(newroomname,
1288                                          sizeof newroomname,
1289                                          newfoldername) & 0xFF;
1290
1291                 irlp = (struct irl *) malloc(sizeof(struct irl));
1292                 strcpy(irlp->irl_newroom, newroomname);
1293                 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1294                 irlp->irl_newfloor = newfloor;
1295                 irlp->next = *(irlparms->irl);
1296                 *(irlparms->irl) = irlp;
1297         }
1298 }
1299
1300
1301 /*
1302  * Implements the RENAME command
1303  *
1304  */
1305 void imap_rename(int num_parms, char *parms[])
1306 {
1307         char old_room[ROOMNAMELEN];
1308         char new_room[ROOMNAMELEN];
1309         int oldr, newr;
1310         int new_floor;
1311         int r;
1312         struct irl *irl = NULL; /* the list */
1313         struct irl *irlp = NULL;        /* scratch pointer */
1314         struct irlparms irlparms;
1315
1316         if (strchr(parms[3], '\\') != NULL) {
1317                 cprintf("%s NO Invalid character in folder name\r\n",
1318                         parms[0]);
1319                 return;
1320         }
1321
1322         oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1323         newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1324         new_floor = (newr & 0xFF);
1325
1326         r = CtdlRenameRoom(old_room, new_room, new_floor);
1327
1328         if (r == crr_room_not_found) {
1329                 cprintf("%s NO Could not locate this folder\r\n",
1330                         parms[0]);
1331                 return;
1332         }
1333         if (r == crr_already_exists) {
1334                 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1335                 return;
1336         }
1337         if (r == crr_noneditable) {
1338                 cprintf("%s This folder is not editable.\r\n", parms[0]);
1339                 return;
1340         }
1341         if (r == crr_invalid_floor) {
1342                 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1343                 return;
1344         }
1345         if (r == crr_access_denied) {
1346                 cprintf("%s You do not have permission to edit "
1347                         "this folder.\r\n", parms[0]);
1348                 return;
1349         }
1350         if (r != crr_ok) {
1351                 cprintf("%s NO Rename failed - undefined error %d\r\n",
1352                         parms[0], r);
1353                 return;
1354         }
1355
1356
1357         /* If this is the INBOX, then RFC2060 says we have to just move the
1358          * contents.  In a Citadel environment it's easier to rename the room
1359          * (already did that) and create a new inbox.
1360          */
1361         if (!strcasecmp(parms[2], "INBOX")) {
1362                 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1363         }
1364
1365         /* Otherwise, do the subfolders.  Build a list of rooms to rename... */
1366         else {
1367                 irlparms.oldname = parms[2];
1368                 irlparms.newname = parms[3];
1369                 irlparms.irl = &irl;
1370                 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1371
1372                 /* ... and now rename them. */
1373                 while (irl != NULL) {
1374                         r = CtdlRenameRoom(irl->irl_oldroom,
1375                                            irl->irl_newroom,
1376                                            irl->irl_newfloor);
1377                         if (r != crr_ok) {
1378                                 /* FIXME handle error returns better */
1379                                 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n", r);
1380                         }
1381                         irlp = irl;
1382                         irl = irl->next;
1383                         free(irlp);
1384                 }
1385         }
1386
1387         cprintf("%s OK RENAME completed\r\n", parms[0]);
1388 }
1389
1390
1391
1392
1393 /* 
1394  * Main command loop for IMAP sessions.
1395  */
1396 void imap_command_loop(void)
1397 {
1398         char cmdbuf[SIZ];
1399         char *parms[SIZ];
1400         int num_parms;
1401         struct timeval tv1, tv2;
1402         suseconds_t total_time = 0;
1403
1404         gettimeofday(&tv1, NULL);
1405         CC->lastcmd = time(NULL);
1406         memset(cmdbuf, 0, sizeof cmdbuf);       /* Clear it, just in case */
1407         flush_output();
1408         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1409                 lprintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1410                 CC->kill_me = 1;
1411                 return;
1412         }
1413
1414         if (IMAP->authstate == imap_as_expecting_password) {
1415                 lprintf(CTDL_INFO, "IMAP: <password>\n");
1416         }
1417         else if (bmstrcasestr(cmdbuf, " LOGIN ")) {
1418                 lprintf(CTDL_INFO, "IMAP: LOGIN...\n");
1419         }
1420         else {
1421                 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1422         }
1423
1424         while (strlen(cmdbuf) < 5)
1425                 strcat(cmdbuf, " ");
1426
1427         /* strip off l/t whitespace and CRLF */
1428         if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1429                 cmdbuf[strlen(cmdbuf) - 1] = 0;
1430         if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1431                 cmdbuf[strlen(cmdbuf) - 1] = 0;
1432         striplt(cmdbuf);
1433
1434         /* If we're in the middle of a multi-line command, handle that */
1435         if (IMAP->authstate == imap_as_expecting_username) {
1436                 imap_auth_login_user(cmdbuf);
1437                 return;
1438         }
1439         if (IMAP->authstate == imap_as_expecting_password) {
1440                 imap_auth_login_pass(cmdbuf);
1441                 return;
1442         }
1443
1444         /* Ok, at this point we're in normal command mode.  The first thing
1445          * we do is print any incoming pages (yeah! we really do!)
1446          */
1447         imap_print_instant_messages();
1448
1449         /*
1450          * Before processing the command that was just entered... if we happen
1451          * to have a folder selected, we'd like to rescan that folder for new
1452          * messages, and for deletions/changes of existing messages.  This
1453          * could probably be optimized somehow, but IMAP sucks...
1454          */
1455         if (IMAP->selected) {
1456                 imap_rescan_msgids();
1457         }
1458
1459         /* Now for the command set. */
1460
1461         /* Grab the tag, command, and parameters.  Check syntax. */
1462         num_parms = imap_parameterize(parms, cmdbuf);
1463         if (num_parms < 2) {
1464                 cprintf("BAD syntax error\r\n");
1465         }
1466
1467         /* The commands below may be executed in any state */
1468
1469         else if ((!strcasecmp(parms[1], "NOOP"))
1470                  || (!strcasecmp(parms[1], "CHECK"))) {
1471                 cprintf("%s OK This command successfully did nothing.\r\n",
1472                         parms[0]);
1473         }
1474
1475         else if (!strcasecmp(parms[1], "ID")) {
1476                 imap_id(num_parms, parms);
1477         }
1478
1479
1480         else if (!strcasecmp(parms[1], "LOGOUT")) {
1481                 if (IMAP->selected) {
1482                         imap_do_expunge();      /* yes, we auto-expunge */
1483                 }
1484                 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1485                 cprintf("%s OK thank you for using Citadel IMAP\r\n",
1486                         parms[0]);
1487                 CC->kill_me = 1;
1488                 return;
1489         }
1490
1491         else if (!strcasecmp(parms[1], "LOGIN")) {
1492                 imap_login(num_parms, parms);
1493         }
1494
1495         else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1496                 imap_authenticate(num_parms, parms);
1497         }
1498
1499         else if (!strcasecmp(parms[1], "CAPABILITY")) {
1500                 imap_capability(num_parms, parms);
1501         }
1502 #ifdef HAVE_OPENSSL
1503         else if (!strcasecmp(parms[1], "STARTTLS")) {
1504                 imap_starttls(num_parms, parms);
1505         }
1506 #endif
1507         else if (!CC->logged_in) {
1508                 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1509         }
1510
1511         /* The commans below require a logged-in state */
1512
1513         else if (!strcasecmp(parms[1], "SELECT")) {
1514                 imap_select(num_parms, parms);
1515         }
1516
1517         else if (!strcasecmp(parms[1], "EXAMINE")) {
1518                 imap_select(num_parms, parms);
1519         }
1520
1521         else if (!strcasecmp(parms[1], "LSUB")) {
1522                 imap_lsub(num_parms, parms);
1523         }
1524
1525         else if (!strcasecmp(parms[1], "LIST")) {
1526                 imap_list(num_parms, parms);
1527         }
1528
1529         else if (!strcasecmp(parms[1], "CREATE")) {
1530                 imap_create(num_parms, parms);
1531         }
1532
1533         else if (!strcasecmp(parms[1], "DELETE")) {
1534                 imap_delete(num_parms, parms);
1535         }
1536
1537         else if (!strcasecmp(parms[1], "RENAME")) {
1538                 imap_rename(num_parms, parms);
1539         }
1540
1541         else if (!strcasecmp(parms[1], "STATUS")) {
1542                 imap_status(num_parms, parms);
1543         }
1544
1545         else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1546                 imap_subscribe(num_parms, parms);
1547         }
1548
1549         else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1550                 imap_unsubscribe(num_parms, parms);
1551         }
1552
1553         else if (!strcasecmp(parms[1], "APPEND")) {
1554                 imap_append(num_parms, parms);
1555         }
1556
1557         else if (!strcasecmp(parms[1], "NAMESPACE")) {
1558                 imap_namespace(num_parms, parms);
1559         }
1560
1561         else if (!strcasecmp(parms[1], "SETACL")) {
1562                 imap_setacl(num_parms, parms);
1563         }
1564
1565         else if (!strcasecmp(parms[1], "DELETEACL")) {
1566                 imap_deleteacl(num_parms, parms);
1567         }
1568
1569         else if (!strcasecmp(parms[1], "GETACL")) {
1570                 imap_getacl(num_parms, parms);
1571         }
1572
1573         else if (!strcasecmp(parms[1], "LISTRIGHTS")) {
1574                 imap_listrights(num_parms, parms);
1575         }
1576
1577         else if (!strcasecmp(parms[1], "MYRIGHTS")) {
1578                 imap_myrights(num_parms, parms);
1579         }
1580
1581         else if (IMAP->selected == 0) {
1582                 cprintf("%s BAD no folder selected\r\n", parms[0]);
1583         }
1584
1585         /* The commands below require the SELECT state on a mailbox */
1586
1587         else if (!strcasecmp(parms[1], "FETCH")) {
1588                 imap_fetch(num_parms, parms);
1589         }
1590
1591         else if ((!strcasecmp(parms[1], "UID"))
1592                  && (!strcasecmp(parms[2], "FETCH"))) {
1593                 imap_uidfetch(num_parms, parms);
1594         }
1595
1596         else if (!strcasecmp(parms[1], "SEARCH")) {
1597                 imap_search(num_parms, parms);
1598         }
1599
1600         else if ((!strcasecmp(parms[1], "UID"))
1601                  && (!strcasecmp(parms[2], "SEARCH"))) {
1602                 imap_uidsearch(num_parms, parms);
1603         }
1604
1605         else if (!strcasecmp(parms[1], "STORE")) {
1606                 imap_store(num_parms, parms);
1607         }
1608
1609         else if ((!strcasecmp(parms[1], "UID"))
1610                  && (!strcasecmp(parms[2], "STORE"))) {
1611                 imap_uidstore(num_parms, parms);
1612         }
1613
1614         else if (!strcasecmp(parms[1], "COPY")) {
1615                 imap_copy(num_parms, parms);
1616         }
1617
1618         else if ((!strcasecmp(parms[1], "UID"))
1619                  && (!strcasecmp(parms[2], "COPY"))) {
1620                 imap_uidcopy(num_parms, parms);
1621         }
1622
1623         else if (!strcasecmp(parms[1], "EXPUNGE")) {
1624                 imap_expunge(num_parms, parms);
1625         }
1626
1627         else if (!strcasecmp(parms[1], "CLOSE")) {
1628                 imap_close(num_parms, parms);
1629         }
1630
1631         /* End of commands.  If we get here, the command is either invalid
1632          * or unimplemented.
1633          */
1634
1635         else {
1636                 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1637         }
1638
1639         /* If the client transmitted a message we can free it now */
1640         imap_free_transmitted_message();
1641
1642         gettimeofday(&tv2, NULL);
1643         total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1644         lprintf(CTDL_DEBUG, "IMAP command completed in %ld.%ld seconds\n",
1645                 (total_time / 1000000),
1646                 (total_time % 1000000)
1647         );
1648 }
1649
1650
1651
1652 /*
1653  * This function is called to register the IMAP extension with Citadel.
1654  */
1655 char *serv_imap_init(void)
1656 {
1657         CtdlRegisterServiceHook(config.c_imap_port,
1658                                 NULL, imap_greeting, imap_command_loop, NULL);
1659 #ifdef HAVE_OPENSSL
1660         CtdlRegisterServiceHook(config.c_imaps_port,
1661                                 NULL, imaps_greeting, imap_command_loop, NULL);
1662 #endif
1663         CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1664         return "$Id$";
1665 }