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