]> code.citadel.org Git - citadel.git/blob - citadel/serv_imap.c
* Removed excessive trace messages that were slowing the server down
[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 = 0;
832         int newroomview = 0;
833
834         if (strchr(parms[2], '\\') != NULL) {
835                 cprintf("%s NO Invalid character in folder name\r\n",
836                         parms[0]);
837                 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
838                 return;
839         }
840
841         ret = imap_roomname(roomname, sizeof roomname, parms[2]);
842         if (ret < 0) {
843                 cprintf("%s NO Invalid mailbox name or location\r\n",
844                         parms[0]);
845                 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
846                 return;
847         }
848         floornum = (ret & 0x00ff);      /* lower 8 bits = floor number */
849         flags = (ret & 0xff00); /* upper 8 bits = flags        */
850
851         if (flags & IR_MAILBOX) {
852                 if (strncasecmp(parms[2], "INBOX/", 6)) {
853                         cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
854                         lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
855                         return;
856                 }
857         }
858
859         if (flags & IR_MAILBOX) {
860                 newroomtype = 4;                /* private mailbox */
861                 newroomview = VIEW_MAILBOX;
862         } else {
863                 newroomtype = 0;                /* public folder */
864                 newroomview = VIEW_BBS;
865         }
866
867         lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
868                 roomname, floornum, newroomtype);
869
870         ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
871         if (ret == 0) {
872                 cprintf
873                     ("%s NO Mailbox already exists, or create failed\r\n",
874                      parms[0]);
875         } else {
876                 cprintf("%s OK CREATE completed\r\n", parms[0]);
877         }
878         lprintf(CTDL_DEBUG, "imap_create() completed\n");
879 }
880
881
882 /*
883  * Locate a room by its IMAP folder name, and check access to it.
884  * If zapped_ok is nonzero, we can also look for the room in the zapped list.
885  */
886 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
887 {
888         int ret;
889         char augmented_roomname[ROOMNAMELEN];
890         char roomname[ROOMNAMELEN];
891         int c;
892         struct ctdlroom QRscratch;
893         int ra;
894         int ok = 0;
895
896         ret = imap_roomname(roomname, sizeof roomname, foldername);
897         if (ret < 0) {
898                 return (1);
899         }
900
901         /* First try a regular match */
902         c = getroom(&QRscratch, roomname);
903
904         /* Then try a mailbox name match */
905         if (c != 0) {
906                 MailboxName(augmented_roomname, sizeof augmented_roomname,
907                             &CC->user, roomname);
908                 c = getroom(&QRscratch, augmented_roomname);
909                 if (c == 0)
910                         strcpy(roomname, augmented_roomname);
911         }
912
913         /* If the room exists, check security/access */
914         if (c == 0) {
915                 /* See if there is an existing user/room relationship */
916                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
917
918                 /* normal clients have to pass through security */
919                 if (ra & UA_KNOWN) {
920                         ok = 1;
921                 }
922                 if ((zapped_ok) && (ra & UA_ZAPPED)) {
923                         ok = 1;
924                 }
925         }
926
927         /* Fail here if no such room */
928         if (!ok) {
929                 strcpy(returned_roomname, "");
930                 return (2);
931         } else {
932                 strcpy(returned_roomname, QRscratch.QRname);
933                 return (0);
934         }
935 }
936
937
938 /*
939  * Implements the STATUS command (sort of)
940  *
941  */
942 void imap_status(int num_parms, char *parms[])
943 {
944         int ret;
945         char roomname[ROOMNAMELEN];
946         char buf[SIZ];
947         char savedroom[ROOMNAMELEN];
948         int msgs, new;
949
950         ret = imap_grabroom(roomname, parms[2], 0);
951         if (ret != 0) {
952                 cprintf
953                     ("%s NO Invalid mailbox name or location, or access denied\r\n",
954                      parms[0]);
955                 return;
956         }
957
958         /*
959          * usergoto() formally takes us to the desired room, happily returning
960          * the number of messages and number of new messages.  (If another
961          * folder is selected, save its name so we can return there!!!!!)
962          */
963         if (IMAP->selected) {
964                 strcpy(savedroom, CC->room.QRname);
965         }
966         usergoto(roomname, 0, 0, &msgs, &new);
967
968         /*
969          * Tell the client what it wants to know.  In fact, tell it *more* than
970          * it wants to know.  We happily IGnore the supplied status data item
971          * names and simply spew all possible data items.  It's far easier to
972          * code and probably saves us some processing time too.
973          */
974         imap_mailboxname(buf, sizeof buf, &CC->room);
975         cprintf("* STATUS ");
976         imap_strout(buf);
977         cprintf(" (MESSAGES %d ", msgs);
978         cprintf("RECENT %d ", new);     /* Initially, new==recent */
979         cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
980         cprintf("UNSEEN %d)\r\n", new);
981
982         /*
983          * If another folder is selected, go back to that room so we can resume
984          * our happy day without violent explosions.
985          */
986         if (IMAP->selected) {
987                 usergoto(savedroom, 0, 0, &msgs, &new);
988         }
989
990         /*
991          * Oooh, look, we're done!
992          */
993         cprintf("%s OK STATUS completed\r\n", parms[0]);
994 }
995
996
997
998 /*
999  * Implements the SUBSCRIBE command
1000  *
1001  */
1002 void imap_subscribe(int num_parms, char *parms[])
1003 {
1004         int ret;
1005         char roomname[ROOMNAMELEN];
1006         char savedroom[ROOMNAMELEN];
1007         int msgs, new;
1008
1009         ret = imap_grabroom(roomname, parms[2], 1);
1010         if (ret != 0) {
1011                 cprintf(
1012                         "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1013                         parms[0],
1014                         ret
1015                 );
1016                 return;
1017         }
1018
1019         /*
1020          * usergoto() formally takes us to the desired room, which has the side
1021          * effect of marking the room as not-zapped ... exactly the effect
1022          * we're looking for.
1023          */
1024         if (IMAP->selected) {
1025                 strcpy(savedroom, CC->room.QRname);
1026         }
1027         usergoto(roomname, 0, 0, &msgs, &new);
1028
1029         /*
1030          * If another folder is selected, go back to that room so we can resume
1031          * our happy day without violent explosions.
1032          */
1033         if (IMAP->selected) {
1034                 usergoto(savedroom, 0, 0, &msgs, &new);
1035         }
1036
1037         cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1038 }
1039
1040
1041 /*
1042  * Implements the UNSUBSCRIBE command
1043  *
1044  */
1045 void imap_unsubscribe(int num_parms, char *parms[])
1046 {
1047         int ret;
1048         char roomname[ROOMNAMELEN];
1049         char savedroom[ROOMNAMELEN];
1050         int msgs, new;
1051
1052         ret = imap_grabroom(roomname, parms[2], 0);
1053         if (ret != 0) {
1054                 cprintf
1055                     ("%s NO Invalid mailbox name or location, or access denied\r\n",
1056                      parms[0]);
1057                 return;
1058         }
1059
1060         /*
1061          * usergoto() formally takes us to the desired room.
1062          */
1063         if (IMAP->selected) {
1064                 strcpy(savedroom, CC->room.QRname);
1065         }
1066         usergoto(roomname, 0, 0, &msgs, &new);
1067
1068         /* 
1069          * Now make the API call to zap the room
1070          */
1071         if (CtdlForgetThisRoom() == 0) {
1072                 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1073         } else {
1074                 cprintf
1075                     ("%s NO You may not unsubscribe from this folder.\r\n",
1076                      parms[0]);
1077         }
1078
1079         /*
1080          * If another folder is selected, go back to that room so we can resume
1081          * our happy day without violent explosions.
1082          */
1083         if (IMAP->selected) {
1084                 usergoto(savedroom, 0, 0, &msgs, &new);
1085         }
1086 }
1087
1088
1089
1090 /*
1091  * Implements the DELETE command
1092  *
1093  */
1094 void imap_delete(int num_parms, char *parms[])
1095 {
1096         int ret;
1097         char roomname[ROOMNAMELEN];
1098         char savedroom[ROOMNAMELEN];
1099         int msgs, new;
1100
1101         ret = imap_grabroom(roomname, parms[2], 0);
1102         if (ret != 0) {
1103                 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1104                         parms[0]);
1105                 return;
1106         }
1107
1108         /*
1109          * usergoto() formally takes us to the desired room, happily returning
1110          * the number of messages and number of new messages.  (If another
1111          * folder is selected, save its name so we can return there!!!!!)
1112          */
1113         if (IMAP->selected) {
1114                 strcpy(savedroom, CC->room.QRname);
1115         }
1116         usergoto(roomname, 0, 0, &msgs, &new);
1117
1118         /*
1119          * Now delete the room.
1120          */
1121         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1122                 cprintf("%s OK DELETE completed\r\n", parms[0]);
1123                 delete_room(&CC->room);
1124         } else {
1125                 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1126         }
1127
1128         /*
1129          * If another folder is selected, go back to that room so we can resume
1130          * our happy day without violent explosions.
1131          */
1132         if (IMAP->selected) {
1133                 usergoto(savedroom, 0, 0, &msgs, &new);
1134         }
1135 }
1136
1137
1138 /*
1139  * Back end function for imap_rename()
1140  */
1141 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1142 {
1143         char foldername[SIZ];
1144         char newfoldername[SIZ];
1145         char newroomname[ROOMNAMELEN];
1146         int newfloor = 0;
1147         struct irl *irlp = NULL;        /* scratch pointer */
1148         struct irlparms *irlparms;
1149
1150         irlparms = (struct irlparms *) data;
1151         imap_mailboxname(foldername, sizeof foldername, qrbuf);
1152
1153         /* Rename subfolders */
1154         if ((!strncasecmp(foldername, irlparms->oldname,
1155                           strlen(irlparms->oldname))
1156              && (foldername[strlen(irlparms->oldname)] == '/'))) {
1157
1158                 sprintf(newfoldername, "%s/%s",
1159                         irlparms->newname,
1160                         &foldername[strlen(irlparms->oldname) + 1]
1161                     );
1162
1163                 newfloor = imap_roomname(newroomname,
1164                                          sizeof newroomname,
1165                                          newfoldername) & 0xFF;
1166
1167                 irlp = (struct irl *) malloc(sizeof(struct irl));
1168                 strcpy(irlp->irl_newroom, newroomname);
1169                 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1170                 irlp->irl_newfloor = newfloor;
1171                 irlp->next = *(irlparms->irl);
1172                 *(irlparms->irl) = irlp;
1173         }
1174 }
1175
1176
1177 /*
1178  * Implements the RENAME command
1179  *
1180  */
1181 void imap_rename(int num_parms, char *parms[])
1182 {
1183         char old_room[ROOMNAMELEN];
1184         char new_room[ROOMNAMELEN];
1185         int oldr, newr;
1186         int new_floor;
1187         int r;
1188         struct irl *irl = NULL; /* the list */
1189         struct irl *irlp = NULL;        /* scratch pointer */
1190         struct irlparms irlparms;
1191
1192         if (strchr(parms[3], '\\') != NULL) {
1193                 cprintf("%s NO Invalid character in folder name\r\n",
1194                         parms[0]);
1195                 return;
1196         }
1197
1198         oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1199         newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1200         new_floor = (newr & 0xFF);
1201
1202         r = CtdlRenameRoom(old_room, new_room, new_floor);
1203
1204         if (r == crr_room_not_found) {
1205                 cprintf("%s NO Could not locate this folder\r\n",
1206                         parms[0]);
1207                 return;
1208         }
1209         if (r == crr_already_exists) {
1210                 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1211                 return;
1212         }
1213         if (r == crr_noneditable) {
1214                 cprintf("%s This folder is not editable.\r\n", parms[0]);
1215                 return;
1216         }
1217         if (r == crr_invalid_floor) {
1218                 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1219                 return;
1220         }
1221         if (r == crr_access_denied) {
1222                 cprintf("%s You do not have permission to edit "
1223                         "this folder.\r\n", parms[0]);
1224                 return;
1225         }
1226         if (r != crr_ok) {
1227                 cprintf("%s NO Rename failed - undefined error %d\r\n",
1228                         parms[0], r);
1229                 return;
1230         }
1231
1232
1233         /* If this is the INBOX, then RFC2060 says we have to just move the
1234          * contents.  In a Citadel environment it's easier to rename the room
1235          * (already did that) and create a new inbox.
1236          */
1237         if (!strcasecmp(parms[2], "INBOX")) {
1238                 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1239         }
1240
1241         /* Otherwise, do the subfolders.  Build a list of rooms to rename... */
1242         else {
1243                 irlparms.oldname = parms[2];
1244                 irlparms.newname = parms[3];
1245                 irlparms.irl = &irl;
1246                 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1247
1248                 /* ... and now rename them. */
1249                 while (irl != NULL) {
1250                         r = CtdlRenameRoom(irl->irl_oldroom,
1251                                            irl->irl_newroom,
1252                                            irl->irl_newfloor);
1253                         if (r != crr_ok) {
1254                                 /* FIXME handle error returns better */
1255                                 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n",
1256                                         r);
1257                         }
1258                         irlp = irl;
1259                         irl = irl->next;
1260                         free(irlp);
1261                 }
1262         }
1263
1264         cprintf("%s OK RENAME completed\r\n", parms[0]);
1265 }
1266
1267
1268
1269
1270 /* 
1271  * Main command loop for IMAP sessions.
1272  */
1273 void imap_command_loop(void)
1274 {
1275         char cmdbuf[SIZ];
1276         char *parms[SIZ];
1277         int num_parms;
1278
1279         CC->lastcmd = time(NULL);
1280         memset(cmdbuf, 0, sizeof cmdbuf);       /* Clear it, just in case */
1281         flush_output();
1282         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1283                 lprintf(CTDL_ERR, "IMAP socket is broken.  Ending session.\r\n");
1284                 CC->kill_me = 1;
1285                 return;
1286         }
1287
1288         lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1289         while (strlen(cmdbuf) < 5)
1290                 strcat(cmdbuf, " ");
1291
1292         /* strip off l/t whitespace and CRLF */
1293         if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1294                 cmdbuf[strlen(cmdbuf) - 1] = 0;
1295         if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1296                 cmdbuf[strlen(cmdbuf) - 1] = 0;
1297         striplt(cmdbuf);
1298
1299         /* If we're in the middle of a multi-line command, handle that */
1300         if (IMAP->authstate == imap_as_expecting_username) {
1301                 imap_auth_login_user(cmdbuf);
1302                 return;
1303         }
1304         if (IMAP->authstate == imap_as_expecting_password) {
1305                 imap_auth_login_pass(cmdbuf);
1306                 return;
1307         }
1308
1309         /* Ok, at this point we're in normal command mode.  The first thing
1310          * we do is print any incoming pages (yeah! we really do!)
1311          */
1312         imap_print_instant_messages();
1313
1314         /*
1315          * Before processing the command that was just entered... if we happen
1316          * to have a folder selected, we'd like to rescan that folder for new
1317          * messages, and for deletions/changes of existing messages.  This
1318          * could probably be optimized somehow, but IMAP sucks...
1319          */
1320         if (IMAP->selected) {
1321                 imap_rescan_msgids();
1322         }
1323
1324         /* Now for the command set. */
1325
1326         /* Grab the tag, command, and parameters.  Check syntax. */
1327         num_parms = imap_parameterize(parms, cmdbuf);
1328         if (num_parms < 2) {
1329                 cprintf("BAD syntax error\r\n");
1330         }
1331
1332         /* The commands below may be executed in any state */
1333
1334         else if ((!strcasecmp(parms[1], "NOOP"))
1335                  || (!strcasecmp(parms[1], "CHECK"))) {
1336                 cprintf("%s OK This command successfully did nothing.\r\n",
1337                         parms[0]);
1338         }
1339
1340         else if (!strcasecmp(parms[1], "LOGOUT")) {
1341                 if (IMAP->selected) {
1342                         imap_do_expunge();      /* yes, we auto-expunge */
1343                 }
1344                 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1345                 cprintf("%s OK thank you for using Citadel IMAP\r\n",
1346                         parms[0]);
1347                 CC->kill_me = 1;
1348                 return;
1349         }
1350
1351         else if (!strcasecmp(parms[1], "LOGIN")) {
1352                 imap_login(num_parms, parms);
1353         }
1354
1355         else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1356                 imap_authenticate(num_parms, parms);
1357         }
1358
1359         else if (!strcasecmp(parms[1], "CAPABILITY")) {
1360                 imap_capability(num_parms, parms);
1361         }
1362 #ifdef HAVE_OPENSSL
1363         else if (!strcasecmp(parms[1], "STARTTLS")) {
1364                 imap_starttls(num_parms, parms);
1365         }
1366 #endif
1367         else if (!CC->logged_in) {
1368                 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1369         }
1370
1371         /* The commans below require a logged-in state */
1372
1373         else if (!strcasecmp(parms[1], "SELECT")) {
1374                 imap_select(num_parms, parms);
1375         }
1376
1377         else if (!strcasecmp(parms[1], "EXAMINE")) {
1378                 imap_select(num_parms, parms);
1379         }
1380
1381         else if (!strcasecmp(parms[1], "LSUB")) {
1382                 imap_lsub(num_parms, parms);
1383         }
1384
1385         else if (!strcasecmp(parms[1], "LIST")) {
1386                 imap_list(num_parms, parms);
1387         }
1388
1389         else if (!strcasecmp(parms[1], "CREATE")) {
1390                 imap_create(num_parms, parms);
1391         }
1392
1393         else if (!strcasecmp(parms[1], "DELETE")) {
1394                 imap_delete(num_parms, parms);
1395         }
1396
1397         else if (!strcasecmp(parms[1], "RENAME")) {
1398                 imap_rename(num_parms, parms);
1399         }
1400
1401         else if (!strcasecmp(parms[1], "STATUS")) {
1402                 imap_status(num_parms, parms);
1403         }
1404
1405         else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1406                 imap_subscribe(num_parms, parms);
1407         }
1408
1409         else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1410                 imap_unsubscribe(num_parms, parms);
1411         }
1412
1413         else if (!strcasecmp(parms[1], "APPEND")) {
1414                 imap_append(num_parms, parms);
1415         }
1416
1417         else if (!strcasecmp(parms[1], "NAMESPACE")) {
1418                 imap_namespace(num_parms, parms);
1419         }
1420
1421         else if (IMAP->selected == 0) {
1422                 cprintf("%s BAD no folder selected\r\n", parms[0]);
1423         }
1424
1425         /* The commands below require the SELECT state on a mailbox */
1426
1427         else if (!strcasecmp(parms[1], "FETCH")) {
1428                 imap_fetch(num_parms, parms);
1429         }
1430
1431         else if ((!strcasecmp(parms[1], "UID"))
1432                  && (!strcasecmp(parms[2], "FETCH"))) {
1433                 imap_uidfetch(num_parms, parms);
1434         }
1435
1436         else if (!strcasecmp(parms[1], "SEARCH")) {
1437                 imap_search(num_parms, parms);
1438         }
1439
1440         else if ((!strcasecmp(parms[1], "UID"))
1441                  && (!strcasecmp(parms[2], "SEARCH"))) {
1442                 imap_uidsearch(num_parms, parms);
1443         }
1444
1445         else if (!strcasecmp(parms[1], "STORE")) {
1446                 imap_store(num_parms, parms);
1447         }
1448
1449         else if ((!strcasecmp(parms[1], "UID"))
1450                  && (!strcasecmp(parms[2], "STORE"))) {
1451                 imap_uidstore(num_parms, parms);
1452         }
1453
1454         else if (!strcasecmp(parms[1], "COPY")) {
1455                 imap_copy(num_parms, parms);
1456         }
1457
1458         else if ((!strcasecmp(parms[1], "UID"))
1459                  && (!strcasecmp(parms[2], "COPY"))) {
1460                 imap_uidcopy(num_parms, parms);
1461         }
1462
1463         else if (!strcasecmp(parms[1], "EXPUNGE")) {
1464                 imap_expunge(num_parms, parms);
1465         }
1466
1467         else if (!strcasecmp(parms[1], "CLOSE")) {
1468                 imap_close(num_parms, parms);
1469         }
1470
1471         /* End of commands.  If we get here, the command is either invalid
1472          * or unimplemented.
1473          */
1474
1475         else {
1476                 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1477         }
1478
1479         /* If the client transmitted a message we can free it now */
1480         imap_free_transmitted_message();
1481 }
1482
1483
1484
1485 /*
1486  * This function is called to register the IMAP extension with Citadel.
1487  */
1488 char *serv_imap_init(void)
1489 {
1490         CtdlRegisterServiceHook(config.c_imap_port,
1491                                 NULL, imap_greeting, imap_command_loop, NULL);
1492 #ifdef HAVE_OPENSSL
1493         CtdlRegisterServiceHook(config.c_imaps_port,
1494                                 NULL, imaps_greeting, imap_command_loop, NULL);
1495 #endif
1496         CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1497         return "$Id$";
1498 }