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