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