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