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