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