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