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