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