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