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