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