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