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