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