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