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