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