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 * first_msg should be set to 0 to rescan the flags for every message in the
118 * room, or some other value if we're only interested in an incremental
121 void imap_set_seen_flags(int first_msg)
127 char setstr[64], lostr[64], histr[64];
130 if (IMAP->num_msgs < 1) return;
131 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
133 for (i = first_msg; i < IMAP->num_msgs; ++i) {
134 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
135 IMAP->flags[i] |= IMAP_RECENT;
136 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
140 * Do the "\Seen" flag.
141 * (Any message not "\Seen" is considered "\Recent".)
143 num_sets = num_tokens(vbuf.v_seen, ',');
144 for (s=0; s<num_sets; ++s) {
145 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
147 extract_token(lostr, setstr, 0, ':', sizeof lostr);
148 if (num_tokens(setstr, ':') >= 2) {
149 extract_token(histr, setstr, 1, ':', sizeof histr);
150 if (!strcmp(histr, "*")) {
151 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
155 strcpy(histr, lostr);
160 for (i = first_msg; i < IMAP->num_msgs; ++i) {
161 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
162 IMAP->flags[i] |= IMAP_SEEN;
163 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
168 /* Do the ANSWERED flag */
169 num_sets = num_tokens(vbuf.v_answered, ',');
170 for (s=0; s<num_sets; ++s) {
171 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
173 extract_token(lostr, setstr, 0, ':', sizeof lostr);
174 if (num_tokens(setstr, ':') >= 2) {
175 extract_token(histr, setstr, 1, ':', sizeof histr);
176 if (!strcmp(histr, "*")) {
177 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
181 strcpy(histr, lostr);
186 for (i = first_msg; i < IMAP->num_msgs; ++i) {
187 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
188 IMAP->flags[i] |= IMAP_ANSWERED;
198 * Back end for imap_load_msgids()
200 * Optimization: instead of calling realloc() to add each message, we
201 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
202 * allows the mapping to proceed much faster.
204 void imap_add_single_msgid(long msgnum, void *userdata)
208 if (IMAP->num_msgs > IMAP->num_alloc) {
209 IMAP->num_alloc += REALLOC_INCREMENT;
210 IMAP->msgids = realloc(IMAP->msgids,
211 (IMAP->num_alloc * sizeof(long)) );
212 IMAP->flags = realloc(IMAP->flags,
213 (IMAP->num_alloc * sizeof(long)) );
215 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
216 IMAP->flags[IMAP->num_msgs - 1] = 0;
222 * Set up a message ID map for the current room (folder)
224 void imap_load_msgids(void)
227 if (IMAP->selected == 0) {
229 "imap_load_msgids() can't run; no room selected\n");
234 imap_free_msgids(); /* If there was already a map, free it */
237 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
238 imap_add_single_msgid, NULL);
241 imap_set_seen_flags(0);
247 * Re-scan the selected room (folder) and see if it's been changed at all
249 void imap_rescan_msgids(void)
252 int original_num_msgs = 0;
253 long original_highest = 0L;
255 int message_still_exists;
256 struct cdbdata *cdbfr;
257 long *msglist = NULL;
261 if (IMAP->selected == 0) {
263 "imap_load_msgids() can't run; no room selected\n");
269 * Check to see if the room's contents have changed.
270 * If not, we can avoid this rescan.
272 getroom(&CC->room, CC->room.QRname);
273 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
278 /* Load the *current* message list from disk, so we can compare it
279 * to what we have in memory.
281 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
283 msglist = malloc(cdbfr->len);
284 if (msglist == NULL) {
285 lprintf(CTDL_CRIT, "malloc() failed\n");
288 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
289 num_msgs = cdbfr->len / sizeof(long);
297 * Check to see if any of the messages we know about have been expunged
299 if (IMAP->num_msgs > 0) {
301 for (i = 0; i < IMAP->num_msgs; ++i) {
303 message_still_exists = 0;
305 for (j = jstart; j < num_msgs; ++j) {
306 if (msglist[j] == IMAP->msgids[i]) {
307 message_still_exists = 1;
314 if (message_still_exists == 0) {
315 cprintf("* %d EXPUNGE\r\n", i + 1);
317 /* Here's some nice stupid nonsense. When a
318 * message is expunged, we have to slide all
319 * the existing messages up in the message
323 memcpy(&IMAP->msgids[i],
324 &IMAP->msgids[i + 1],
326 (IMAP->num_msgs - i)));
327 memcpy(&IMAP->flags[i],
330 (IMAP->num_msgs - i)));
340 * Remember how many messages were here before we re-scanned.
342 original_num_msgs = IMAP->num_msgs;
343 if (IMAP->num_msgs > 0) {
344 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
346 original_highest = 0L;
351 * Now peruse the room for *new* messages only.
354 for (j = 0; j < num_msgs; ++j) {
355 if (msglist[j] > original_highest) {
356 imap_add_single_msgid(msglist[j], NULL);
360 imap_set_seen_flags(original_num_msgs);
364 * If new messages have arrived, tell the client about them.
366 if (IMAP->num_msgs > original_num_msgs) {
368 for (j = 0; j < num_msgs; ++j) {
369 if (IMAP->flags[j] & IMAP_RECENT) {
374 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
375 cprintf("* %d RECENT\r\n", num_recent);
382 IMAP->last_mtime = CC->room.QRmtime;
392 * This cleanup function blows away the temporary memory and files used by
395 void imap_cleanup_function(void)
398 /* Don't do this stuff if this is not a IMAP session! */
399 if (CC->h_command_function != imap_command_loop)
402 /* If there is a mailbox selected, auto-expunge it. */
403 if (IMAP->selected) {
407 lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
409 imap_free_transmitted_message();
411 if (IMAP->cached_rfc822_data != NULL) {
412 free(IMAP->cached_rfc822_data);
413 IMAP->cached_rfc822_data = NULL;
414 IMAP->cached_rfc822_msgnum = (-1);
415 IMAP->cached_rfc822_withbody = 0;
418 if (IMAP->cached_body != NULL) {
419 free(IMAP->cached_body);
420 IMAP->cached_body = NULL;
421 IMAP->cached_body_len = 0;
422 IMAP->cached_bodymsgnum = (-1);
426 lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
431 * Does the actual work of the CAPABILITY command (because we need to
432 * output this stuff in other places as well)
434 void imap_output_capability_string(void) {
435 cprintf("CAPABILITY IMAP4REV1 NAMESPACE AUTH=LOGIN");
437 if (!CC->redirect_ssl) cprintf(" STARTTLS");
442 * implements the CAPABILITY command
444 void imap_capability(int num_parms, char *parms[])
447 imap_output_capability_string();
449 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
455 * Here's where our IMAP session begins its happy day.
457 void imap_greeting(void)
460 strcpy(CC->cs_clientname, "IMAP session");
461 IMAP = malloc(sizeof (struct citimap));
462 memset(IMAP, 0, sizeof(struct citimap));
463 IMAP->authstate = imap_as_normal;
464 IMAP->cached_rfc822_data = NULL;
465 IMAP->cached_rfc822_msgnum = (-1);
466 IMAP->cached_rfc822_withbody = 0;
469 imap_output_capability_string();
470 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
474 * IMAPS is just like IMAP, except it goes crypto right away.
477 void imaps_greeting(void) {
478 CtdlStartTLS(NULL, NULL, NULL);
485 * implements the LOGIN command (ordinary username/password login)
487 void imap_login(int num_parms, char *parms[])
489 if (num_parms != 4) {
490 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
494 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
495 if (CtdlTryPassword(parms[3]) == pass_ok) {
496 cprintf("%s OK [", parms[0]);
497 imap_output_capability_string();
498 cprintf("] Hello, %s\r\n", CC->user.fullname);
503 cprintf("%s BAD Login incorrect\r\n", parms[0]);
508 * Implements the AUTHENTICATE command
510 void imap_authenticate(int num_parms, char *parms[])
514 if (num_parms != 3) {
515 cprintf("%s BAD incorrect number of parameters\r\n",
521 cprintf("%s BAD Already logged in.\r\n", parms[0]);
525 if (!strcasecmp(parms[2], "LOGIN")) {
526 CtdlEncodeBase64(buf, "Username:", 9);
527 cprintf("+ %s\r\n", buf);
528 IMAP->authstate = imap_as_expecting_username;
529 strcpy(IMAP->authseq, parms[0]);
534 cprintf("%s NO AUTHENTICATE %s failed\r\n",
539 void imap_auth_login_user(char *cmd)
543 CtdlDecodeBase64(buf, cmd, SIZ);
544 CtdlLoginExistingUser(buf);
545 CtdlEncodeBase64(buf, "Password:", 9);
546 cprintf("+ %s\r\n", buf);
547 IMAP->authstate = imap_as_expecting_password;
551 void imap_auth_login_pass(char *cmd)
555 CtdlDecodeBase64(buf, cmd, SIZ);
556 if (CtdlTryPassword(buf) == pass_ok) {
557 cprintf("%s OK authentication succeeded\r\n",
560 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
562 IMAP->authstate = imap_as_normal;
568 * implements the STARTTLS command (Citadel API version)
571 void imap_starttls(int num_parms, char *parms[])
573 char ok_response[SIZ];
574 char nosup_response[SIZ];
575 char error_response[SIZ];
578 "%s OK begin TLS negotiation now\r\n",
580 sprintf(nosup_response,
581 "%s NO TLS not supported here\r\n",
583 sprintf(error_response,
584 "%s BAD Internal error\r\n",
586 CtdlStartTLS(ok_response, nosup_response, error_response);
592 * implements the SELECT command
594 void imap_select(int num_parms, char *parms[])
597 char augmented_roomname[ROOMNAMELEN];
601 struct ctdlroom QRscratch;
607 /* Convert the supplied folder name to a roomname */
608 i = imap_roomname(towhere, sizeof towhere, parms[2]);
610 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
614 floornum = (i & 0x00ff);
615 roomflags = (i & 0xff00);
617 /* First try a regular match */
618 c = getroom(&QRscratch, towhere);
620 /* Then try a mailbox name match */
622 MailboxName(augmented_roomname, sizeof augmented_roomname,
624 c = getroom(&QRscratch, augmented_roomname);
626 strcpy(towhere, augmented_roomname);
629 /* If the room exists, check security/access */
631 /* See if there is an existing user/room relationship */
632 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
634 /* normal clients have to pass through security */
640 /* Fail here if no such room */
642 cprintf("%s NO ... no such room, or access denied\r\n",
647 /* If we already had some other folder selected, auto-expunge it */
652 * usergoto() formally takes us to the desired room, happily returning
653 * the number of messages and number of new messages.
656 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
658 usergoto(NULL, 0, 0, &msgs, &new);
663 if (!strcasecmp(parms[1], "EXAMINE")) {
672 IMAP->last_mtime = CC->room.QRmtime;
675 cprintf("* %d EXISTS\r\n", msgs);
676 cprintf("* %d RECENT\r\n", new);
678 cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
679 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
681 /* Note that \Deleted is a valid flag, but not a permanent flag,
682 * because we don't maintain its state across sessions. Citadel
683 * automatically expunges mailboxes when they are de-selected.
685 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
686 cprintf("* OK [PERMANENTFLAGS (\\Seen \\Answered)] "
687 "permanent flags\r\n");
689 cprintf("%s OK [%s] %s completed\r\n",
691 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
697 * does the real work for expunge
699 int imap_do_expunge(void)
702 int num_expunged = 0;
704 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
705 if (IMAP->selected == 0) {
709 if (IMAP->num_msgs > 0)
710 for (i = 0; i < IMAP->num_msgs; ++i) {
711 if (IMAP->flags[i] & IMAP_DELETED) {
712 CtdlDeleteMessages(CC->room.QRname,
713 IMAP->msgids[i], "");
718 if (num_expunged > 0) {
719 imap_rescan_msgids();
722 lprintf(CTDL_DEBUG, "Expunged %d messages.\n", num_expunged);
723 return (num_expunged);
728 * implements the EXPUNGE command syntax
730 void imap_expunge(int num_parms, char *parms[])
732 int num_expunged = 0;
734 num_expunged = imap_do_expunge();
735 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
740 * implements the CLOSE command
742 void imap_close(int num_parms, char *parms[])
745 /* Yes, we always expunge on close. */
746 if (IMAP->selected) {
753 cprintf("%s OK CLOSE completed\r\n", parms[0]);
758 * Implements the NAMESPACE command.
760 void imap_namespace(int num_parms, char *parms[])
767 cprintf("* NAMESPACE ");
769 /* All personal folders are subordinate to INBOX. */
770 cprintf("((\"INBOX/\" \"/\")) ");
772 /* Other users' folders ... coming soon! FIXME */
775 /* Show all floors as shared namespaces. Neato! */
777 for (i = 0; i < MAXFLOORS; ++i) {
779 if (fl->f_flags & F_INUSE) {
780 if (floors > 0) cprintf(" ");
782 sprintf(buf, "%s/", fl->f_name);
790 /* Wind it up with a newline and a completion message. */
792 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
798 * Used by LIST and LSUB to show the floors in the listing
800 void imap_list_floors(char *cmd, char *pattern)
805 for (i = 0; i < MAXFLOORS; ++i) {
807 if (fl->f_flags & F_INUSE) {
808 if (imap_mailbox_matches_pattern
809 (pattern, fl->f_name)) {
810 cprintf("* %s (\\NoSelect) \"/\" ", cmd);
811 imap_strout(fl->f_name);
821 * Back end for imap_lsub()
823 * IMAP "subscribed folder" is equivocated to Citadel "known rooms." This
824 * may or may not be the desired behavior in the future.
826 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data)
832 pattern = (char *) data;
834 /* Only list rooms to which the user has access!! */
835 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
837 imap_mailboxname(buf, sizeof buf, qrbuf);
838 if (imap_mailbox_matches_pattern(pattern, buf)) {
839 cprintf("* LSUB () \"/\" ");
848 * Implements the LSUB command
850 void imap_lsub(int num_parms, char *parms[])
854 cprintf("%s BAD arguments invalid\r\n", parms[0]);
857 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
859 if (strlen(parms[3]) == 0) {
860 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
864 imap_list_floors("LSUB", pattern);
865 ForEachRoom(imap_lsub_listroom, pattern);
868 cprintf("%s OK LSUB completed\r\n", parms[0]);
874 * Back end for imap_list()
876 void imap_list_listroom(struct ctdlroom *qrbuf, void *data)
882 pattern = (char *) data;
884 /* Only list rooms to which the user has access!! */
885 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
887 || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
888 imap_mailboxname(buf, sizeof buf, qrbuf);
889 if (imap_mailbox_matches_pattern(pattern, buf)) {
890 cprintf("* LIST () \"/\" ");
899 * Implements the LIST command
901 void imap_list(int num_parms, char *parms[])
905 cprintf("%s BAD arguments invalid\r\n", parms[0]);
908 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
910 if (strlen(parms[3]) == 0) {
911 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
915 imap_list_floors("LIST", pattern);
916 ForEachRoom(imap_list_listroom, pattern);
919 cprintf("%s OK LIST completed\r\n", parms[0]);
925 * Implements the CREATE command
928 void imap_create(int num_parms, char *parms[])
931 char roomname[ROOMNAMELEN];
937 if (strchr(parms[2], '\\') != NULL) {
938 cprintf("%s NO Invalid character in folder name\r\n",
940 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
944 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
946 cprintf("%s NO Invalid mailbox name or location\r\n",
948 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
951 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
952 flags = (ret & 0xff00); /* upper 8 bits = flags */
954 if (flags & IR_MAILBOX) {
955 if (strncasecmp(parms[2], "INBOX/", 6)) {
956 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
957 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
962 if (flags & IR_MAILBOX) {
963 newroomtype = 4; /* private mailbox */
964 newroomview = VIEW_MAILBOX;
966 newroomtype = 0; /* public folder */
967 newroomview = VIEW_BBS;
970 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
971 roomname, floornum, newroomtype);
973 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
976 ("%s NO Mailbox already exists, or create failed\r\n",
979 cprintf("%s OK CREATE completed\r\n", parms[0]);
981 lprintf(CTDL_DEBUG, "imap_create() completed\n");
986 * Locate a room by its IMAP folder name, and check access to it.
987 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
989 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
992 char augmented_roomname[ROOMNAMELEN];
993 char roomname[ROOMNAMELEN];
995 struct ctdlroom QRscratch;
999 ret = imap_roomname(roomname, sizeof roomname, foldername);
1004 /* First try a regular match */
1005 c = getroom(&QRscratch, roomname);
1007 /* Then try a mailbox name match */
1009 MailboxName(augmented_roomname, sizeof augmented_roomname,
1010 &CC->user, roomname);
1011 c = getroom(&QRscratch, augmented_roomname);
1013 strcpy(roomname, augmented_roomname);
1016 /* If the room exists, check security/access */
1018 /* See if there is an existing user/room relationship */
1019 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1021 /* normal clients have to pass through security */
1022 if (ra & UA_KNOWN) {
1025 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1030 /* Fail here if no such room */
1032 strcpy(returned_roomname, "");
1035 strcpy(returned_roomname, QRscratch.QRname);
1042 * Implements the STATUS command (sort of)
1045 void imap_status(int num_parms, char *parms[])
1048 char roomname[ROOMNAMELEN];
1050 char savedroom[ROOMNAMELEN];
1053 ret = imap_grabroom(roomname, parms[2], 0);
1056 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1062 * usergoto() formally takes us to the desired room, happily returning
1063 * the number of messages and number of new messages. (If another
1064 * folder is selected, save its name so we can return there!!!!!)
1066 if (IMAP->selected) {
1067 strcpy(savedroom, CC->room.QRname);
1069 usergoto(roomname, 0, 0, &msgs, &new);
1072 * Tell the client what it wants to know. In fact, tell it *more* than
1073 * it wants to know. We happily IGnore the supplied status data item
1074 * names and simply spew all possible data items. It's far easier to
1075 * code and probably saves us some processing time too.
1077 imap_mailboxname(buf, sizeof buf, &CC->room);
1078 cprintf("* STATUS ");
1080 cprintf(" (MESSAGES %d ", msgs);
1081 cprintf("RECENT %d ", new); /* Initially, new==recent */
1082 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1083 cprintf("UNSEEN %d)\r\n", new);
1086 * If another folder is selected, go back to that room so we can resume
1087 * our happy day without violent explosions.
1089 if (IMAP->selected) {
1090 usergoto(savedroom, 0, 0, &msgs, &new);
1094 * Oooh, look, we're done!
1096 cprintf("%s OK STATUS completed\r\n", parms[0]);
1102 * Implements the SUBSCRIBE command
1105 void imap_subscribe(int num_parms, char *parms[])
1108 char roomname[ROOMNAMELEN];
1109 char savedroom[ROOMNAMELEN];
1112 ret = imap_grabroom(roomname, parms[2], 1);
1115 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1123 * usergoto() formally takes us to the desired room, which has the side
1124 * effect of marking the room as not-zapped ... exactly the effect
1125 * we're looking for.
1127 if (IMAP->selected) {
1128 strcpy(savedroom, CC->room.QRname);
1130 usergoto(roomname, 0, 0, &msgs, &new);
1133 * If another folder is selected, go back to that room so we can resume
1134 * our happy day without violent explosions.
1136 if (IMAP->selected) {
1137 usergoto(savedroom, 0, 0, &msgs, &new);
1140 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1145 * Implements the UNSUBSCRIBE command
1148 void imap_unsubscribe(int num_parms, char *parms[])
1151 char roomname[ROOMNAMELEN];
1152 char savedroom[ROOMNAMELEN];
1155 ret = imap_grabroom(roomname, parms[2], 0);
1158 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1164 * usergoto() formally takes us to the desired room.
1166 if (IMAP->selected) {
1167 strcpy(savedroom, CC->room.QRname);
1169 usergoto(roomname, 0, 0, &msgs, &new);
1172 * Now make the API call to zap the room
1174 if (CtdlForgetThisRoom() == 0) {
1175 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1178 ("%s NO You may not unsubscribe from this folder.\r\n",
1183 * If another folder is selected, go back to that room so we can resume
1184 * our happy day without violent explosions.
1186 if (IMAP->selected) {
1187 usergoto(savedroom, 0, 0, &msgs, &new);
1194 * Implements the DELETE command
1197 void imap_delete(int num_parms, char *parms[])
1200 char roomname[ROOMNAMELEN];
1201 char savedroom[ROOMNAMELEN];
1204 ret = imap_grabroom(roomname, parms[2], 0);
1206 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1212 * usergoto() formally takes us to the desired room, happily returning
1213 * the number of messages and number of new messages. (If another
1214 * folder is selected, save its name so we can return there!!!!!)
1216 if (IMAP->selected) {
1217 strcpy(savedroom, CC->room.QRname);
1219 usergoto(roomname, 0, 0, &msgs, &new);
1222 * Now delete the room.
1224 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1225 schedule_room_for_deletion(&CC->room);
1226 cprintf("%s OK DELETE completed\r\n", parms[0]);
1228 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1232 * If another folder is selected, go back to that room so we can resume
1233 * our happy day without violent explosions.
1235 if (IMAP->selected) {
1236 usergoto(savedroom, 0, 0, &msgs, &new);
1242 * Back end function for imap_rename()
1244 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1246 char foldername[SIZ];
1247 char newfoldername[SIZ];
1248 char newroomname[ROOMNAMELEN];
1250 struct irl *irlp = NULL; /* scratch pointer */
1251 struct irlparms *irlparms;
1253 irlparms = (struct irlparms *) data;
1254 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1256 /* Rename subfolders */
1257 if ((!strncasecmp(foldername, irlparms->oldname,
1258 strlen(irlparms->oldname))
1259 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1261 sprintf(newfoldername, "%s/%s",
1263 &foldername[strlen(irlparms->oldname) + 1]
1266 newfloor = imap_roomname(newroomname,
1268 newfoldername) & 0xFF;
1270 irlp = (struct irl *) malloc(sizeof(struct irl));
1271 strcpy(irlp->irl_newroom, newroomname);
1272 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1273 irlp->irl_newfloor = newfloor;
1274 irlp->next = *(irlparms->irl);
1275 *(irlparms->irl) = irlp;
1281 * Implements the RENAME command
1284 void imap_rename(int num_parms, char *parms[])
1286 char old_room[ROOMNAMELEN];
1287 char new_room[ROOMNAMELEN];
1291 struct irl *irl = NULL; /* the list */
1292 struct irl *irlp = NULL; /* scratch pointer */
1293 struct irlparms irlparms;
1295 if (strchr(parms[3], '\\') != NULL) {
1296 cprintf("%s NO Invalid character in folder name\r\n",
1301 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1302 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1303 new_floor = (newr & 0xFF);
1305 r = CtdlRenameRoom(old_room, new_room, new_floor);
1307 if (r == crr_room_not_found) {
1308 cprintf("%s NO Could not locate this folder\r\n",
1312 if (r == crr_already_exists) {
1313 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1316 if (r == crr_noneditable) {
1317 cprintf("%s This folder is not editable.\r\n", parms[0]);
1320 if (r == crr_invalid_floor) {
1321 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1324 if (r == crr_access_denied) {
1325 cprintf("%s You do not have permission to edit "
1326 "this folder.\r\n", parms[0]);
1330 cprintf("%s NO Rename failed - undefined error %d\r\n",
1336 /* If this is the INBOX, then RFC2060 says we have to just move the
1337 * contents. In a Citadel environment it's easier to rename the room
1338 * (already did that) and create a new inbox.
1340 if (!strcasecmp(parms[2], "INBOX")) {
1341 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1344 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1346 irlparms.oldname = parms[2];
1347 irlparms.newname = parms[3];
1348 irlparms.irl = &irl;
1349 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1351 /* ... and now rename them. */
1352 while (irl != NULL) {
1353 r = CtdlRenameRoom(irl->irl_oldroom,
1357 /* FIXME handle error returns better */
1358 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n",
1367 cprintf("%s OK RENAME completed\r\n", parms[0]);
1374 * Main command loop for IMAP sessions.
1376 void imap_command_loop(void)
1382 CC->lastcmd = time(NULL);
1383 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1385 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1386 lprintf(CTDL_ERR, "IMAP socket is broken. Ending session.\r\n");
1391 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1392 while (strlen(cmdbuf) < 5)
1393 strcat(cmdbuf, " ");
1395 /* strip off l/t whitespace and CRLF */
1396 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1397 cmdbuf[strlen(cmdbuf) - 1] = 0;
1398 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1399 cmdbuf[strlen(cmdbuf) - 1] = 0;
1402 /* If we're in the middle of a multi-line command, handle that */
1403 if (IMAP->authstate == imap_as_expecting_username) {
1404 imap_auth_login_user(cmdbuf);
1407 if (IMAP->authstate == imap_as_expecting_password) {
1408 imap_auth_login_pass(cmdbuf);
1412 /* Ok, at this point we're in normal command mode. The first thing
1413 * we do is print any incoming pages (yeah! we really do!)
1415 imap_print_instant_messages();
1418 * Before processing the command that was just entered... if we happen
1419 * to have a folder selected, we'd like to rescan that folder for new
1420 * messages, and for deletions/changes of existing messages. This
1421 * could probably be optimized somehow, but IMAP sucks...
1423 if (IMAP->selected) {
1424 imap_rescan_msgids();
1427 /* Now for the command set. */
1429 /* Grab the tag, command, and parameters. Check syntax. */
1430 num_parms = imap_parameterize(parms, cmdbuf);
1431 if (num_parms < 2) {
1432 cprintf("BAD syntax error\r\n");
1435 /* The commands below may be executed in any state */
1437 else if ((!strcasecmp(parms[1], "NOOP"))
1438 || (!strcasecmp(parms[1], "CHECK"))) {
1439 cprintf("%s OK This command successfully did nothing.\r\n",
1443 else if (!strcasecmp(parms[1], "LOGOUT")) {
1444 if (IMAP->selected) {
1445 imap_do_expunge(); /* yes, we auto-expunge */
1447 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1448 cprintf("%s OK thank you for using Citadel IMAP\r\n",
1454 else if (!strcasecmp(parms[1], "LOGIN")) {
1455 imap_login(num_parms, parms);
1458 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1459 imap_authenticate(num_parms, parms);
1462 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1463 imap_capability(num_parms, parms);
1466 else if (!strcasecmp(parms[1], "STARTTLS")) {
1467 imap_starttls(num_parms, parms);
1470 else if (!CC->logged_in) {
1471 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1474 /* The commans below require a logged-in state */
1476 else if (!strcasecmp(parms[1], "SELECT")) {
1477 imap_select(num_parms, parms);
1480 else if (!strcasecmp(parms[1], "EXAMINE")) {
1481 imap_select(num_parms, parms);
1484 else if (!strcasecmp(parms[1], "LSUB")) {
1485 imap_lsub(num_parms, parms);
1488 else if (!strcasecmp(parms[1], "LIST")) {
1489 imap_list(num_parms, parms);
1492 else if (!strcasecmp(parms[1], "CREATE")) {
1493 imap_create(num_parms, parms);
1496 else if (!strcasecmp(parms[1], "DELETE")) {
1497 imap_delete(num_parms, parms);
1500 else if (!strcasecmp(parms[1], "RENAME")) {
1501 imap_rename(num_parms, parms);
1504 else if (!strcasecmp(parms[1], "STATUS")) {
1505 imap_status(num_parms, parms);
1508 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1509 imap_subscribe(num_parms, parms);
1512 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1513 imap_unsubscribe(num_parms, parms);
1516 else if (!strcasecmp(parms[1], "APPEND")) {
1517 imap_append(num_parms, parms);
1520 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1521 imap_namespace(num_parms, parms);
1524 else if (IMAP->selected == 0) {
1525 cprintf("%s BAD no folder selected\r\n", parms[0]);
1528 /* The commands below require the SELECT state on a mailbox */
1530 else if (!strcasecmp(parms[1], "FETCH")) {
1531 imap_fetch(num_parms, parms);
1534 else if ((!strcasecmp(parms[1], "UID"))
1535 && (!strcasecmp(parms[2], "FETCH"))) {
1536 imap_uidfetch(num_parms, parms);
1539 else if (!strcasecmp(parms[1], "SEARCH")) {
1540 imap_search(num_parms, parms);
1543 else if ((!strcasecmp(parms[1], "UID"))
1544 && (!strcasecmp(parms[2], "SEARCH"))) {
1545 imap_uidsearch(num_parms, parms);
1548 else if (!strcasecmp(parms[1], "STORE")) {
1549 imap_store(num_parms, parms);
1552 else if ((!strcasecmp(parms[1], "UID"))
1553 && (!strcasecmp(parms[2], "STORE"))) {
1554 imap_uidstore(num_parms, parms);
1557 else if (!strcasecmp(parms[1], "COPY")) {
1558 imap_copy(num_parms, parms);
1561 else if ((!strcasecmp(parms[1], "UID"))
1562 && (!strcasecmp(parms[2], "COPY"))) {
1563 imap_uidcopy(num_parms, parms);
1566 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1567 imap_expunge(num_parms, parms);
1570 else if (!strcasecmp(parms[1], "CLOSE")) {
1571 imap_close(num_parms, parms);
1574 /* End of commands. If we get here, the command is either invalid
1579 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1582 /* If the client transmitted a message we can free it now */
1583 imap_free_transmitted_message();
1589 * This function is called to register the IMAP extension with Citadel.
1591 char *serv_imap_init(void)
1593 CtdlRegisterServiceHook(config.c_imap_port,
1594 NULL, imap_greeting, imap_command_loop, NULL);
1596 CtdlRegisterServiceHook(config.c_imaps_port,
1597 NULL, imaps_greeting, imap_command_loop, NULL);
1599 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);