4 * IMAP server for the Citadel system
5 * Copyright (C) 2000-2005 by Art Cancro and others.
6 * This code is released under the terms of the GNU General Public License.
8 * WARNING: the IMAP protocol is badly designed. No implementation of it
9 * is perfect. Indeed, with so much gratuitous complexity, *all* IMAP
10 * implementations have bugs.
21 #include <sys/types.h>
23 #if TIME_WITH_SYS_TIME
24 # include <sys/time.h>
28 # include <sys/time.h>
40 #include "sysdep_decls.h"
41 #include "citserver.h"
44 #include "serv_extensions.h"
51 #include "internet_addressing.h"
52 #include "serv_imap.h"
53 #include "imap_tools.h"
54 #include "imap_fetch.h"
55 #include "imap_search.h"
56 #include "imap_store.h"
57 #include "imap_misc.h"
60 #include "serv_crypto.h"
63 /* imap_rename() uses this struct containing list of rooms to rename */
66 char irl_oldroom[ROOMNAMELEN];
67 char irl_newroom[ROOMNAMELEN];
71 /* Data which is passed between imap_rename() and imap_rename_backend() */
80 * If there is a message ID map in memory, free it
82 void imap_free_msgids(void)
84 if (IMAP->msgids != NULL) {
90 if (IMAP->flags != NULL) {
94 IMAP->last_mtime = (-1);
99 * If there is a transmitted message in memory, free it
101 void imap_free_transmitted_message(void)
103 if (IMAP->transmitted_message != NULL) {
104 free(IMAP->transmitted_message);
105 IMAP->transmitted_message = NULL;
106 IMAP->transmitted_length = 0;
112 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
113 * sets stored in the visit record for this user/room. Note that we have
114 * to parse each sequence set manually here, because calling the utility
115 * function is_msg_in_sequence_set() over and over again is too expensive.
117 void imap_set_seen_flags(void)
123 char setstr[SIZ], lostr[SIZ], histr[SIZ];
126 if (IMAP->num_msgs < 1) return;
127 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
129 for (i = 0; i < IMAP->num_msgs; ++i) {
130 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
131 IMAP->flags[i] |= IMAP_RECENT;
132 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
135 /* Do the "\Seen" flag. (Any message not "\Seen" is considered "\Recent".) */
136 num_sets = num_tokens(vbuf.v_seen, ',');
137 for (s=0; s<num_sets; ++s) {
138 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
140 extract_token(lostr, setstr, 0, ':', sizeof lostr);
141 if (num_tokens(setstr, ':') >= 2) {
142 extract_token(histr, setstr, 1, ':', sizeof histr);
143 if (!strcmp(histr, "*")) {
144 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
148 strcpy(histr, lostr);
153 for (i = 0; i < IMAP->num_msgs; ++i) {
154 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)) {
155 IMAP->flags[i] |= IMAP_SEEN;
156 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
161 /* Do the ANSWERED flag */
162 num_sets = num_tokens(vbuf.v_answered, ',');
163 for (s=0; s<num_sets; ++s) {
164 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
166 extract_token(lostr, setstr, 0, ':', sizeof lostr);
167 if (num_tokens(setstr, ':') >= 2) {
168 extract_token(histr, setstr, 1, ':', sizeof histr);
169 if (!strcmp(histr, "*")) {
170 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
174 strcpy(histr, lostr);
179 for (i = 0; i < IMAP->num_msgs; ++i) {
180 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)) {
181 IMAP->flags[i] |= IMAP_ANSWERED;
191 * Back end for imap_load_msgids()
193 * Optimization: instead of calling realloc() to add each message, we
194 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
195 * allows the mapping to proceed much faster.
197 void imap_add_single_msgid(long msgnum, void *userdata)
201 if (IMAP->num_msgs > IMAP->num_alloc) {
202 IMAP->num_alloc += REALLOC_INCREMENT;
203 IMAP->msgids = realloc(IMAP->msgids, (IMAP->num_alloc * sizeof(long)));
204 IMAP->flags = realloc(IMAP->flags, (IMAP->num_alloc * sizeof(long)));
206 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
207 IMAP->flags[IMAP->num_msgs - 1] = 0;
213 * Set up a message ID map for the current room (folder)
215 void imap_load_msgids(void)
218 if (IMAP->selected == 0) {
220 "imap_load_msgids() can't run; no room selected\n");
224 imap_free_msgids(); /* If there was already a map, free it */
226 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
227 imap_add_single_msgid, NULL);
229 imap_set_seen_flags();
234 * Re-scan the selected room (folder) and see if it's been changed at all
236 void imap_rescan_msgids(void)
239 int original_num_msgs = 0;
240 long original_highest = 0L;
242 int message_still_exists;
243 struct cdbdata *cdbfr;
244 long *msglist = NULL;
248 if (IMAP->selected == 0) {
250 "imap_load_msgids() can't run; no room selected\n");
254 /* Check to see if the room's contents have changed. If not, we can avoid rescan */
255 getroom(&CC->room, CC->room.QRname);
256 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
260 /* Load the *current* message list from disk, so we can compare it
261 * to what we have in memory.
263 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
265 msglist = malloc(cdbfr->len);
266 if (msglist == NULL) {
267 lprintf(CTDL_CRIT, "malloc() failed\n");
270 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
271 num_msgs = cdbfr->len / sizeof(long);
278 * Check to see if any of the messages we know about have been expunged
280 if (IMAP->num_msgs > 0)
281 for (i = 0; i < IMAP->num_msgs; ++i) {
283 message_still_exists = 0;
285 for (j = 0; j < num_msgs; ++j) {
286 if (msglist[j] == IMAP->msgids[i]) {
287 message_still_exists = 1;
291 if (message_still_exists == 0) {
292 cprintf("* %d EXPUNGE\r\n", i + 1);
294 /* Here's some nice stupid nonsense. When a message
295 * is expunged, we have to slide all the existing
296 * messages up in the message array.
299 memcpy(&IMAP->msgids[i],
300 &IMAP->msgids[i + 1],
302 (IMAP->num_msgs - i)));
303 memcpy(&IMAP->flags[i],
306 (IMAP->num_msgs - i)));
314 * Remember how many messages were here before we re-scanned.
316 original_num_msgs = IMAP->num_msgs;
317 if (IMAP->num_msgs > 0) {
318 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
320 original_highest = 0L;
324 * Now peruse the room for *new* messages only.
327 for (j = 0; j < num_msgs; ++j) {
328 if (msglist[j] > original_highest) {
329 imap_add_single_msgid(msglist[j], NULL);
332 imap_set_seen_flags();
335 * If new messages have arrived, tell the client about them.
337 if (IMAP->num_msgs > original_num_msgs) {
339 for (j = 0; j < num_msgs; ++j) {
340 if (IMAP->flags[j] & IMAP_RECENT) {
345 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
346 cprintf("* %d RECENT\r\n", num_recent);
352 IMAP->last_mtime = CC->room.QRmtime;
362 * This cleanup function blows away the temporary memory and files used by
365 void imap_cleanup_function(void)
368 /* Don't do this stuff if this is not a IMAP session! */
369 if (CC->h_command_function != imap_command_loop)
372 /* If there is a mailbox selected, auto-expunge it. */
373 if (IMAP->selected) {
377 lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
379 imap_free_transmitted_message();
381 if (IMAP->cached_rfc822_data != NULL) {
382 free(IMAP->cached_rfc822_data);
383 IMAP->cached_rfc822_data = NULL;
384 IMAP->cached_rfc822_msgnum = (-1);
385 IMAP->cached_rfc822_withbody = 0;
388 if (IMAP->cached_body != NULL) {
389 free(IMAP->cached_body);
390 IMAP->cached_body = NULL;
391 IMAP->cached_body_len = 0;
392 IMAP->cached_bodymsgnum = (-1);
396 lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
401 * Does the actual work of the CAPABILITY command (because we need to
402 * output this stuff in other places as well)
404 void imap_output_capability_string(void) {
405 cprintf("CAPABILITY IMAP4REV1 NAMESPACE AUTH=LOGIN");
407 if (!CC->redirect_ssl) cprintf(" STARTTLS");
412 * implements the CAPABILITY command
414 void imap_capability(int num_parms, char *parms[])
417 imap_output_capability_string();
419 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
425 * Here's where our IMAP session begins its happy day.
427 void imap_greeting(void)
430 strcpy(CC->cs_clientname, "IMAP session");
431 IMAP = malloc(sizeof (struct citimap));
432 memset(IMAP, 0, sizeof(struct citimap));
433 IMAP->authstate = imap_as_normal;
434 IMAP->cached_rfc822_data = NULL;
435 IMAP->cached_rfc822_msgnum = (-1);
436 IMAP->cached_rfc822_withbody = 0;
439 imap_output_capability_string();
440 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
444 * IMAPS is just like IMAP, except it goes crypto right away.
447 void imaps_greeting(void) {
448 CtdlStartTLS(NULL, NULL, NULL);
455 * implements the LOGIN command (ordinary username/password login)
457 void imap_login(int num_parms, char *parms[])
459 if (num_parms != 4) {
460 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
464 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
465 if (CtdlTryPassword(parms[3]) == pass_ok) {
466 cprintf("%s OK [", parms[0]);
467 imap_output_capability_string();
468 cprintf("] Hello, %s\r\n", CC->user.fullname);
473 cprintf("%s BAD Login incorrect\r\n", parms[0]);
478 * Implements the AUTHENTICATE command
480 void imap_authenticate(int num_parms, char *parms[])
484 if (num_parms != 3) {
485 cprintf("%s BAD incorrect number of parameters\r\n",
491 cprintf("%s BAD Already logged in.\r\n", parms[0]);
495 if (!strcasecmp(parms[2], "LOGIN")) {
496 CtdlEncodeBase64(buf, "Username:", 9);
497 cprintf("+ %s\r\n", buf);
498 IMAP->authstate = imap_as_expecting_username;
499 strcpy(IMAP->authseq, parms[0]);
504 cprintf("%s NO AUTHENTICATE %s failed\r\n",
509 void imap_auth_login_user(char *cmd)
513 CtdlDecodeBase64(buf, cmd, SIZ);
514 CtdlLoginExistingUser(buf);
515 CtdlEncodeBase64(buf, "Password:", 9);
516 cprintf("+ %s\r\n", buf);
517 IMAP->authstate = imap_as_expecting_password;
521 void imap_auth_login_pass(char *cmd)
525 CtdlDecodeBase64(buf, cmd, SIZ);
526 if (CtdlTryPassword(buf) == pass_ok) {
527 cprintf("%s OK authentication succeeded\r\n",
530 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
532 IMAP->authstate = imap_as_normal;
538 * implements the STARTTLS command (Citadel API version)
541 void imap_starttls(int num_parms, char *parms[])
543 char ok_response[SIZ];
544 char nosup_response[SIZ];
545 char error_response[SIZ];
548 "%s OK begin TLS negotiation now\r\n",
550 sprintf(nosup_response,
551 "%s NO TLS not supported here\r\n",
553 sprintf(error_response,
554 "%s BAD Internal error\r\n",
556 CtdlStartTLS(ok_response, nosup_response, error_response);
562 * implements the SELECT command
564 void imap_select(int num_parms, char *parms[])
567 char augmented_roomname[ROOMNAMELEN];
571 struct ctdlroom QRscratch;
577 /* Convert the supplied folder name to a roomname */
578 i = imap_roomname(towhere, sizeof towhere, parms[2]);
580 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
584 floornum = (i & 0x00ff);
585 roomflags = (i & 0xff00);
587 /* First try a regular match */
588 c = getroom(&QRscratch, towhere);
590 /* Then try a mailbox name match */
592 MailboxName(augmented_roomname, sizeof augmented_roomname,
594 c = getroom(&QRscratch, augmented_roomname);
596 strcpy(towhere, augmented_roomname);
599 /* If the room exists, check security/access */
601 /* See if there is an existing user/room relationship */
602 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
604 /* normal clients have to pass through security */
610 /* Fail here if no such room */
612 cprintf("%s NO ... no such room, or access denied\r\n",
617 /* If we already had some other folder selected, auto-expunge it */
621 * usergoto() formally takes us to the desired room, happily returning
622 * the number of messages and number of new messages.
624 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
625 usergoto(NULL, 0, 0, &msgs, &new);
628 if (!strcasecmp(parms[1], "EXAMINE")) {
635 IMAP->last_mtime = CC->room.QRmtime;
637 cprintf("* %d EXISTS\r\n", msgs);
638 cprintf("* %d RECENT\r\n", new);
640 cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
641 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
643 /* Note that \Deleted is a valid flag, but not a permanent flag,
644 * because we don't maintain its state across sessions. Citadel
645 * automatically expunges mailboxes when they are de-selected.
647 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
648 cprintf("* OK [PERMANENTFLAGS (\\Seen \\Answered)] "
649 "permanent flags\r\n");
651 cprintf("%s OK [%s] %s completed\r\n",
653 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
659 * does the real work for expunge
661 int imap_do_expunge(void)
664 int num_expunged = 0;
666 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
667 if (IMAP->selected == 0) {
671 if (IMAP->num_msgs > 0)
672 for (i = 0; i < IMAP->num_msgs; ++i) {
673 if (IMAP->flags[i] & IMAP_DELETED) {
674 CtdlDeleteMessages(CC->room.QRname,
675 IMAP->msgids[i], "");
680 if (num_expunged > 0) {
681 imap_rescan_msgids();
684 lprintf(CTDL_DEBUG, "Expunged %d messages.\n", num_expunged);
685 return (num_expunged);
690 * implements the EXPUNGE command syntax
692 void imap_expunge(int num_parms, char *parms[])
694 int num_expunged = 0;
696 num_expunged = imap_do_expunge();
697 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
702 * implements the CLOSE command
704 void imap_close(int num_parms, char *parms[])
707 /* Yes, we always expunge on close. */
708 if (IMAP->selected) {
715 cprintf("%s OK CLOSE completed\r\n", parms[0]);
720 * Implements the NAMESPACE command.
722 void imap_namespace(int num_parms, char *parms[])
729 cprintf("* NAMESPACE ");
731 /* All personal folders are subordinate to INBOX. */
732 cprintf("((\"INBOX/\" \"/\")) ");
734 /* Other users' folders ... coming soon! FIXME */
737 /* Show all floors as shared namespaces. Neato! */
739 for (i = 0; i < MAXFLOORS; ++i) {
741 if (fl->f_flags & F_INUSE) {
742 if (floors > 0) cprintf(" ");
744 sprintf(buf, "%s/", fl->f_name);
752 /* Wind it up with a newline and a completion message. */
754 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
760 * Used by LIST and LSUB to show the floors in the listing
762 void imap_list_floors(char *cmd, char *pattern)
767 for (i = 0; i < MAXFLOORS; ++i) {
769 if (fl->f_flags & F_INUSE) {
770 if (imap_mailbox_matches_pattern
771 (pattern, fl->f_name)) {
772 cprintf("* %s (\\NoSelect) \"/\" ", cmd);
773 imap_strout(fl->f_name);
783 * Back end for imap_lsub()
785 * IMAP "subscribed folder" is equivocated to Citadel "known rooms." This
786 * may or may not be the desired behavior in the future.
788 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data)
794 pattern = (char *) data;
796 /* Only list rooms to which the user has access!! */
797 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
799 imap_mailboxname(buf, sizeof buf, qrbuf);
800 if (imap_mailbox_matches_pattern(pattern, buf)) {
801 cprintf("* LSUB () \"/\" ");
810 * Implements the LSUB command
812 void imap_lsub(int num_parms, char *parms[])
816 cprintf("%s BAD arguments invalid\r\n", parms[0]);
819 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
821 if (strlen(parms[3]) == 0) {
822 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
826 imap_list_floors("LSUB", pattern);
827 ForEachRoom(imap_lsub_listroom, pattern);
830 cprintf("%s OK LSUB completed\r\n", parms[0]);
836 * Back end for imap_list()
838 void imap_list_listroom(struct ctdlroom *qrbuf, void *data)
844 pattern = (char *) data;
846 /* Only list rooms to which the user has access!! */
847 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
849 || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
850 imap_mailboxname(buf, sizeof buf, qrbuf);
851 if (imap_mailbox_matches_pattern(pattern, buf)) {
852 cprintf("* LIST () \"/\" ");
861 * Implements the LIST command
863 void imap_list(int num_parms, char *parms[])
867 cprintf("%s BAD arguments invalid\r\n", parms[0]);
870 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
872 if (strlen(parms[3]) == 0) {
873 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
877 imap_list_floors("LIST", pattern);
878 ForEachRoom(imap_list_listroom, pattern);
881 cprintf("%s OK LIST completed\r\n", parms[0]);
887 * Implements the CREATE command
890 void imap_create(int num_parms, char *parms[])
893 char roomname[ROOMNAMELEN];
899 if (strchr(parms[2], '\\') != NULL) {
900 cprintf("%s NO Invalid character in folder name\r\n",
902 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
906 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
908 cprintf("%s NO Invalid mailbox name or location\r\n",
910 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
913 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
914 flags = (ret & 0xff00); /* upper 8 bits = flags */
916 if (flags & IR_MAILBOX) {
917 if (strncasecmp(parms[2], "INBOX/", 6)) {
918 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
919 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
924 if (flags & IR_MAILBOX) {
925 newroomtype = 4; /* private mailbox */
926 newroomview = VIEW_MAILBOX;
928 newroomtype = 0; /* public folder */
929 newroomview = VIEW_BBS;
932 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
933 roomname, floornum, newroomtype);
935 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
938 ("%s NO Mailbox already exists, or create failed\r\n",
941 cprintf("%s OK CREATE completed\r\n", parms[0]);
943 lprintf(CTDL_DEBUG, "imap_create() completed\n");
948 * Locate a room by its IMAP folder name, and check access to it.
949 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
951 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
954 char augmented_roomname[ROOMNAMELEN];
955 char roomname[ROOMNAMELEN];
957 struct ctdlroom QRscratch;
961 ret = imap_roomname(roomname, sizeof roomname, foldername);
966 /* First try a regular match */
967 c = getroom(&QRscratch, roomname);
969 /* Then try a mailbox name match */
971 MailboxName(augmented_roomname, sizeof augmented_roomname,
972 &CC->user, roomname);
973 c = getroom(&QRscratch, augmented_roomname);
975 strcpy(roomname, augmented_roomname);
978 /* If the room exists, check security/access */
980 /* See if there is an existing user/room relationship */
981 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
983 /* normal clients have to pass through security */
987 if ((zapped_ok) && (ra & UA_ZAPPED)) {
992 /* Fail here if no such room */
994 strcpy(returned_roomname, "");
997 strcpy(returned_roomname, QRscratch.QRname);
1004 * Implements the STATUS command (sort of)
1007 void imap_status(int num_parms, char *parms[])
1010 char roomname[ROOMNAMELEN];
1012 char savedroom[ROOMNAMELEN];
1015 ret = imap_grabroom(roomname, parms[2], 0);
1018 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1024 * usergoto() formally takes us to the desired room, happily returning
1025 * the number of messages and number of new messages. (If another
1026 * folder is selected, save its name so we can return there!!!!!)
1028 if (IMAP->selected) {
1029 strcpy(savedroom, CC->room.QRname);
1031 usergoto(roomname, 0, 0, &msgs, &new);
1034 * Tell the client what it wants to know. In fact, tell it *more* than
1035 * it wants to know. We happily IGnore the supplied status data item
1036 * names and simply spew all possible data items. It's far easier to
1037 * code and probably saves us some processing time too.
1039 imap_mailboxname(buf, sizeof buf, &CC->room);
1040 cprintf("* STATUS ");
1042 cprintf(" (MESSAGES %d ", msgs);
1043 cprintf("RECENT %d ", new); /* Initially, new==recent */
1044 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1045 cprintf("UNSEEN %d)\r\n", new);
1048 * If another folder is selected, go back to that room so we can resume
1049 * our happy day without violent explosions.
1051 if (IMAP->selected) {
1052 usergoto(savedroom, 0, 0, &msgs, &new);
1056 * Oooh, look, we're done!
1058 cprintf("%s OK STATUS completed\r\n", parms[0]);
1064 * Implements the SUBSCRIBE command
1067 void imap_subscribe(int num_parms, char *parms[])
1070 char roomname[ROOMNAMELEN];
1071 char savedroom[ROOMNAMELEN];
1074 ret = imap_grabroom(roomname, parms[2], 1);
1077 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1085 * usergoto() formally takes us to the desired room, which has the side
1086 * effect of marking the room as not-zapped ... exactly the effect
1087 * we're looking for.
1089 if (IMAP->selected) {
1090 strcpy(savedroom, CC->room.QRname);
1092 usergoto(roomname, 0, 0, &msgs, &new);
1095 * If another folder is selected, go back to that room so we can resume
1096 * our happy day without violent explosions.
1098 if (IMAP->selected) {
1099 usergoto(savedroom, 0, 0, &msgs, &new);
1102 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1107 * Implements the UNSUBSCRIBE command
1110 void imap_unsubscribe(int num_parms, char *parms[])
1113 char roomname[ROOMNAMELEN];
1114 char savedroom[ROOMNAMELEN];
1117 ret = imap_grabroom(roomname, parms[2], 0);
1120 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1126 * usergoto() formally takes us to the desired room.
1128 if (IMAP->selected) {
1129 strcpy(savedroom, CC->room.QRname);
1131 usergoto(roomname, 0, 0, &msgs, &new);
1134 * Now make the API call to zap the room
1136 if (CtdlForgetThisRoom() == 0) {
1137 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1140 ("%s NO You may not unsubscribe from this folder.\r\n",
1145 * If another folder is selected, go back to that room so we can resume
1146 * our happy day without violent explosions.
1148 if (IMAP->selected) {
1149 usergoto(savedroom, 0, 0, &msgs, &new);
1156 * Implements the DELETE command
1159 void imap_delete(int num_parms, char *parms[])
1162 char roomname[ROOMNAMELEN];
1163 char savedroom[ROOMNAMELEN];
1166 ret = imap_grabroom(roomname, parms[2], 0);
1168 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1174 * usergoto() formally takes us to the desired room, happily returning
1175 * the number of messages and number of new messages. (If another
1176 * folder is selected, save its name so we can return there!!!!!)
1178 if (IMAP->selected) {
1179 strcpy(savedroom, CC->room.QRname);
1181 usergoto(roomname, 0, 0, &msgs, &new);
1184 * Now delete the room.
1186 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1187 schedule_room_for_deletion(&CC->room);
1188 cprintf("%s OK DELETE completed\r\n", parms[0]);
1190 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1194 * If another folder is selected, go back to that room so we can resume
1195 * our happy day without violent explosions.
1197 if (IMAP->selected) {
1198 usergoto(savedroom, 0, 0, &msgs, &new);
1204 * Back end function for imap_rename()
1206 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1208 char foldername[SIZ];
1209 char newfoldername[SIZ];
1210 char newroomname[ROOMNAMELEN];
1212 struct irl *irlp = NULL; /* scratch pointer */
1213 struct irlparms *irlparms;
1215 irlparms = (struct irlparms *) data;
1216 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1218 /* Rename subfolders */
1219 if ((!strncasecmp(foldername, irlparms->oldname,
1220 strlen(irlparms->oldname))
1221 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1223 sprintf(newfoldername, "%s/%s",
1225 &foldername[strlen(irlparms->oldname) + 1]
1228 newfloor = imap_roomname(newroomname,
1230 newfoldername) & 0xFF;
1232 irlp = (struct irl *) malloc(sizeof(struct irl));
1233 strcpy(irlp->irl_newroom, newroomname);
1234 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1235 irlp->irl_newfloor = newfloor;
1236 irlp->next = *(irlparms->irl);
1237 *(irlparms->irl) = irlp;
1243 * Implements the RENAME command
1246 void imap_rename(int num_parms, char *parms[])
1248 char old_room[ROOMNAMELEN];
1249 char new_room[ROOMNAMELEN];
1253 struct irl *irl = NULL; /* the list */
1254 struct irl *irlp = NULL; /* scratch pointer */
1255 struct irlparms irlparms;
1257 if (strchr(parms[3], '\\') != NULL) {
1258 cprintf("%s NO Invalid character in folder name\r\n",
1263 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1264 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1265 new_floor = (newr & 0xFF);
1267 r = CtdlRenameRoom(old_room, new_room, new_floor);
1269 if (r == crr_room_not_found) {
1270 cprintf("%s NO Could not locate this folder\r\n",
1274 if (r == crr_already_exists) {
1275 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1278 if (r == crr_noneditable) {
1279 cprintf("%s This folder is not editable.\r\n", parms[0]);
1282 if (r == crr_invalid_floor) {
1283 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1286 if (r == crr_access_denied) {
1287 cprintf("%s You do not have permission to edit "
1288 "this folder.\r\n", parms[0]);
1292 cprintf("%s NO Rename failed - undefined error %d\r\n",
1298 /* If this is the INBOX, then RFC2060 says we have to just move the
1299 * contents. In a Citadel environment it's easier to rename the room
1300 * (already did that) and create a new inbox.
1302 if (!strcasecmp(parms[2], "INBOX")) {
1303 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1306 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1308 irlparms.oldname = parms[2];
1309 irlparms.newname = parms[3];
1310 irlparms.irl = &irl;
1311 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1313 /* ... and now rename them. */
1314 while (irl != NULL) {
1315 r = CtdlRenameRoom(irl->irl_oldroom,
1319 /* FIXME handle error returns better */
1320 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n",
1329 cprintf("%s OK RENAME completed\r\n", parms[0]);
1336 * Main command loop for IMAP sessions.
1338 void imap_command_loop(void)
1344 CC->lastcmd = time(NULL);
1345 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1347 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1348 lprintf(CTDL_ERR, "IMAP socket is broken. Ending session.\r\n");
1353 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1354 while (strlen(cmdbuf) < 5)
1355 strcat(cmdbuf, " ");
1357 /* strip off l/t whitespace and CRLF */
1358 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1359 cmdbuf[strlen(cmdbuf) - 1] = 0;
1360 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1361 cmdbuf[strlen(cmdbuf) - 1] = 0;
1364 /* If we're in the middle of a multi-line command, handle that */
1365 if (IMAP->authstate == imap_as_expecting_username) {
1366 imap_auth_login_user(cmdbuf);
1369 if (IMAP->authstate == imap_as_expecting_password) {
1370 imap_auth_login_pass(cmdbuf);
1374 /* Ok, at this point we're in normal command mode. The first thing
1375 * we do is print any incoming pages (yeah! we really do!)
1377 imap_print_instant_messages();
1380 * Before processing the command that was just entered... if we happen
1381 * to have a folder selected, we'd like to rescan that folder for new
1382 * messages, and for deletions/changes of existing messages. This
1383 * could probably be optimized somehow, but IMAP sucks...
1385 if (IMAP->selected) {
1386 imap_rescan_msgids();
1389 /* Now for the command set. */
1391 /* Grab the tag, command, and parameters. Check syntax. */
1392 num_parms = imap_parameterize(parms, cmdbuf);
1393 if (num_parms < 2) {
1394 cprintf("BAD syntax error\r\n");
1397 /* The commands below may be executed in any state */
1399 else if ((!strcasecmp(parms[1], "NOOP"))
1400 || (!strcasecmp(parms[1], "CHECK"))) {
1401 cprintf("%s OK This command successfully did nothing.\r\n",
1405 else if (!strcasecmp(parms[1], "LOGOUT")) {
1406 if (IMAP->selected) {
1407 imap_do_expunge(); /* yes, we auto-expunge */
1409 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1410 cprintf("%s OK thank you for using Citadel IMAP\r\n",
1416 else if (!strcasecmp(parms[1], "LOGIN")) {
1417 imap_login(num_parms, parms);
1420 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1421 imap_authenticate(num_parms, parms);
1424 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1425 imap_capability(num_parms, parms);
1428 else if (!strcasecmp(parms[1], "STARTTLS")) {
1429 imap_starttls(num_parms, parms);
1432 else if (!CC->logged_in) {
1433 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1436 /* The commans below require a logged-in state */
1438 else if (!strcasecmp(parms[1], "SELECT")) {
1439 imap_select(num_parms, parms);
1442 else if (!strcasecmp(parms[1], "EXAMINE")) {
1443 imap_select(num_parms, parms);
1446 else if (!strcasecmp(parms[1], "LSUB")) {
1447 imap_lsub(num_parms, parms);
1450 else if (!strcasecmp(parms[1], "LIST")) {
1451 imap_list(num_parms, parms);
1454 else if (!strcasecmp(parms[1], "CREATE")) {
1455 imap_create(num_parms, parms);
1458 else if (!strcasecmp(parms[1], "DELETE")) {
1459 imap_delete(num_parms, parms);
1462 else if (!strcasecmp(parms[1], "RENAME")) {
1463 imap_rename(num_parms, parms);
1466 else if (!strcasecmp(parms[1], "STATUS")) {
1467 imap_status(num_parms, parms);
1470 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1471 imap_subscribe(num_parms, parms);
1474 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1475 imap_unsubscribe(num_parms, parms);
1478 else if (!strcasecmp(parms[1], "APPEND")) {
1479 imap_append(num_parms, parms);
1482 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1483 imap_namespace(num_parms, parms);
1486 else if (IMAP->selected == 0) {
1487 cprintf("%s BAD no folder selected\r\n", parms[0]);
1490 /* The commands below require the SELECT state on a mailbox */
1492 else if (!strcasecmp(parms[1], "FETCH")) {
1493 imap_fetch(num_parms, parms);
1496 else if ((!strcasecmp(parms[1], "UID"))
1497 && (!strcasecmp(parms[2], "FETCH"))) {
1498 imap_uidfetch(num_parms, parms);
1501 else if (!strcasecmp(parms[1], "SEARCH")) {
1502 imap_search(num_parms, parms);
1505 else if ((!strcasecmp(parms[1], "UID"))
1506 && (!strcasecmp(parms[2], "SEARCH"))) {
1507 imap_uidsearch(num_parms, parms);
1510 else if (!strcasecmp(parms[1], "STORE")) {
1511 imap_store(num_parms, parms);
1514 else if ((!strcasecmp(parms[1], "UID"))
1515 && (!strcasecmp(parms[2], "STORE"))) {
1516 imap_uidstore(num_parms, parms);
1519 else if (!strcasecmp(parms[1], "COPY")) {
1520 imap_copy(num_parms, parms);
1523 else if ((!strcasecmp(parms[1], "UID"))
1524 && (!strcasecmp(parms[2], "COPY"))) {
1525 imap_uidcopy(num_parms, parms);
1528 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1529 imap_expunge(num_parms, parms);
1532 else if (!strcasecmp(parms[1], "CLOSE")) {
1533 imap_close(num_parms, parms);
1536 /* End of commands. If we get here, the command is either invalid
1541 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1544 /* If the client transmitted a message we can free it now */
1545 imap_free_transmitted_message();
1551 * This function is called to register the IMAP extension with Citadel.
1553 char *serv_imap_init(void)
1555 CtdlRegisterServiceHook(config.c_imap_port,
1556 NULL, imap_greeting, imap_command_loop, NULL);
1558 CtdlRegisterServiceHook(config.c_imaps_port,
1559 NULL, imaps_greeting, imap_command_loop, NULL);
1561 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);