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