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