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