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