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