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