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