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");
402 * Here's where our IMAP session begins its happy day.
404 void imap_greeting(void)
407 strcpy(CC->cs_clientname, "IMAP session");
408 IMAP = malloc(sizeof (struct citimap));
409 memset(IMAP, 0, sizeof(struct citimap));
410 IMAP->authstate = imap_as_normal;
411 IMAP->cached_rfc822_data = NULL;
412 IMAP->cached_rfc822_msgnum = (-1);
413 IMAP->cached_rfc822_withbody = 0;
415 cprintf("* OK %s Citadel IMAP4rev1 server ready\r\n",
420 * IMAPS is just like IMAP, except it goes crypto right away.
423 void imaps_greeting(void) {
424 CtdlStartTLS(NULL, NULL, NULL);
431 * implements the LOGIN command (ordinary username/password login)
433 void imap_login(int num_parms, char *parms[])
435 if (num_parms != 4) {
436 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
440 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
441 if (CtdlTryPassword(parms[3]) == pass_ok) {
442 cprintf("%s OK login successful\r\n", parms[0]);
447 cprintf("%s BAD Login incorrect\r\n", parms[0]);
452 * Implements the AUTHENTICATE command
454 void imap_authenticate(int num_parms, char *parms[])
458 if (num_parms != 3) {
459 cprintf("%s BAD incorrect number of parameters\r\n",
465 cprintf("%s BAD Already logged in.\r\n", parms[0]);
469 if (!strcasecmp(parms[2], "LOGIN")) {
470 CtdlEncodeBase64(buf, "Username:", 9);
471 cprintf("+ %s\r\n", buf);
472 IMAP->authstate = imap_as_expecting_username;
473 strcpy(IMAP->authseq, parms[0]);
478 cprintf("%s NO AUTHENTICATE %s failed\r\n",
483 void imap_auth_login_user(char *cmd)
487 CtdlDecodeBase64(buf, cmd, SIZ);
488 CtdlLoginExistingUser(buf);
489 CtdlEncodeBase64(buf, "Password:", 9);
490 cprintf("+ %s\r\n", buf);
491 IMAP->authstate = imap_as_expecting_password;
495 void imap_auth_login_pass(char *cmd)
499 CtdlDecodeBase64(buf, cmd, SIZ);
500 if (CtdlTryPassword(buf) == pass_ok) {
501 cprintf("%s OK authentication succeeded\r\n",
504 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
506 IMAP->authstate = imap_as_normal;
512 * implements the CAPABILITY command
514 void imap_capability(int num_parms, char *parms[])
516 cprintf("* CAPABILITY IMAP4 IMAP4REV1 NAMESPACE AUTH=LOGIN");
519 cprintf(" STARTTLS");
523 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
529 * implements the STARTTLS command (Citadel API version)
532 void imap_starttls(int num_parms, char *parms[])
534 char ok_response[SIZ];
535 char nosup_response[SIZ];
536 char error_response[SIZ];
539 "%s OK begin TLS negotiation now\r\n",
541 sprintf(nosup_response,
542 "%s NO TLS not supported here\r\n",
544 sprintf(error_response,
545 "%s BAD Internal error\r\n",
547 CtdlStartTLS(ok_response, nosup_response, error_response);
553 * implements the SELECT command
555 void imap_select(int num_parms, char *parms[])
558 char augmented_roomname[ROOMNAMELEN];
562 struct ctdlroom QRscratch;
568 /* Convert the supplied folder name to a roomname */
569 i = imap_roomname(towhere, sizeof towhere, parms[2]);
571 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
575 floornum = (i & 0x00ff);
576 roomflags = (i & 0xff00);
578 /* First try a regular match */
579 c = getroom(&QRscratch, towhere);
581 /* Then try a mailbox name match */
583 MailboxName(augmented_roomname, sizeof augmented_roomname,
585 c = getroom(&QRscratch, augmented_roomname);
587 strcpy(towhere, augmented_roomname);
590 /* If the room exists, check security/access */
592 /* See if there is an existing user/room relationship */
593 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
595 /* normal clients have to pass through security */
601 /* Fail here if no such room */
603 cprintf("%s NO ... no such room, or access denied\r\n",
608 /* If we already had some other folder selected, auto-expunge it */
612 * usergoto() formally takes us to the desired room, happily returning
613 * the number of messages and number of new messages.
615 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
616 usergoto(NULL, 0, 0, &msgs, &new);
619 if (!strcasecmp(parms[1], "EXAMINE")) {
626 IMAP->last_mtime = CC->room.QRmtime;
628 cprintf("* %d EXISTS\r\n", msgs);
629 cprintf("* %d RECENT\r\n", new);
631 /* Note that \Deleted is a valid flag, but not a permanent flag,
632 * because we don't maintain its state across sessions. Citadel
633 * automatically expunges mailboxes when they are de-selected.
635 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
636 cprintf("* OK [PERMANENTFLAGS (\\Seen \\Answered)] "
637 "permanent flags\r\n");
639 cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
640 cprintf("%s OK [%s] %s completed\r\n",
642 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
648 * does the real work for expunge
650 int imap_do_expunge(void)
653 int num_expunged = 0;
655 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
656 if (IMAP->selected == 0) {
660 if (IMAP->num_msgs > 0)
661 for (i = 0; i < IMAP->num_msgs; ++i) {
662 if (IMAP->flags[i] & IMAP_DELETED) {
663 CtdlDeleteMessages(CC->room.QRname,
664 IMAP->msgids[i], "");
669 if (num_expunged > 0) {
670 imap_rescan_msgids();
673 lprintf(CTDL_DEBUG, "Expunged %d messages.\n", num_expunged);
674 return (num_expunged);
679 * implements the EXPUNGE command syntax
681 void imap_expunge(int num_parms, char *parms[])
683 int num_expunged = 0;
685 num_expunged = imap_do_expunge();
686 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
691 * implements the CLOSE command
693 void imap_close(int num_parms, char *parms[])
696 /* Yes, we always expunge on close. */
697 if (IMAP->selected) {
704 cprintf("%s OK CLOSE completed\r\n", parms[0]);
709 * Implements the NAMESPACE command.
711 void imap_namespace(int num_parms, char *parms[])
718 cprintf("* NAMESPACE ");
720 /* All personal folders are subordinate to INBOX. */
721 cprintf("((\"INBOX/\" \"/\")) ");
723 /* Other users' folders ... coming soon! FIXME */
726 /* Show all floors as shared namespaces. Neato! */
728 for (i = 0; i < MAXFLOORS; ++i) {
730 if (fl->f_flags & F_INUSE) {
731 if (floors > 0) cprintf(" ");
733 sprintf(buf, "%s/", fl->f_name);
741 /* Wind it up with a newline and a completion message. */
743 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
749 * Used by LIST and LSUB to show the floors in the listing
751 void imap_list_floors(char *cmd, char *pattern)
756 for (i = 0; i < MAXFLOORS; ++i) {
758 if (fl->f_flags & F_INUSE) {
759 if (imap_mailbox_matches_pattern
760 (pattern, fl->f_name)) {
761 cprintf("* %s (\\NoSelect) \"/\" ", cmd);
762 imap_strout(fl->f_name);
772 * Back end for imap_lsub()
774 * IMAP "subscribed folder" is equivocated to Citadel "known rooms." This
775 * may or may not be the desired behavior in the future.
777 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data)
783 pattern = (char *) data;
785 /* Only list rooms to which the user has access!! */
786 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
788 imap_mailboxname(buf, sizeof buf, qrbuf);
789 if (imap_mailbox_matches_pattern(pattern, buf)) {
790 cprintf("* LSUB () \"/\" ");
799 * Implements the LSUB command
801 void imap_lsub(int num_parms, char *parms[])
805 cprintf("%s BAD arguments invalid\r\n", parms[0]);
808 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
810 if (strlen(parms[3]) == 0) {
811 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
815 imap_list_floors("LSUB", pattern);
816 ForEachRoom(imap_lsub_listroom, pattern);
819 cprintf("%s OK LSUB completed\r\n", parms[0]);
825 * Back end for imap_list()
827 void imap_list_listroom(struct ctdlroom *qrbuf, void *data)
833 pattern = (char *) data;
835 /* Only list rooms to which the user has access!! */
836 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
838 || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
839 imap_mailboxname(buf, sizeof buf, qrbuf);
840 if (imap_mailbox_matches_pattern(pattern, buf)) {
841 cprintf("* LIST () \"/\" ");
850 * Implements the LIST command
852 void imap_list(int num_parms, char *parms[])
856 cprintf("%s BAD arguments invalid\r\n", parms[0]);
859 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
861 if (strlen(parms[3]) == 0) {
862 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
866 imap_list_floors("LIST", pattern);
867 ForEachRoom(imap_list_listroom, pattern);
870 cprintf("%s OK LIST completed\r\n", parms[0]);
876 * Implements the CREATE command
879 void imap_create(int num_parms, char *parms[])
882 char roomname[ROOMNAMELEN];
888 if (strchr(parms[2], '\\') != NULL) {
889 cprintf("%s NO Invalid character in folder name\r\n",
891 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
895 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
897 cprintf("%s NO Invalid mailbox name or location\r\n",
899 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
902 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
903 flags = (ret & 0xff00); /* upper 8 bits = flags */
905 if (flags & IR_MAILBOX) {
906 if (strncasecmp(parms[2], "INBOX/", 6)) {
907 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
908 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
913 if (flags & IR_MAILBOX) {
914 newroomtype = 4; /* private mailbox */
915 newroomview = VIEW_MAILBOX;
917 newroomtype = 0; /* public folder */
918 newroomview = VIEW_BBS;
921 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
922 roomname, floornum, newroomtype);
924 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
927 ("%s NO Mailbox already exists, or create failed\r\n",
930 cprintf("%s OK CREATE completed\r\n", parms[0]);
932 lprintf(CTDL_DEBUG, "imap_create() completed\n");
937 * Locate a room by its IMAP folder name, and check access to it.
938 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
940 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
943 char augmented_roomname[ROOMNAMELEN];
944 char roomname[ROOMNAMELEN];
946 struct ctdlroom QRscratch;
950 ret = imap_roomname(roomname, sizeof roomname, foldername);
955 /* First try a regular match */
956 c = getroom(&QRscratch, roomname);
958 /* Then try a mailbox name match */
960 MailboxName(augmented_roomname, sizeof augmented_roomname,
961 &CC->user, roomname);
962 c = getroom(&QRscratch, augmented_roomname);
964 strcpy(roomname, augmented_roomname);
967 /* If the room exists, check security/access */
969 /* See if there is an existing user/room relationship */
970 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
972 /* normal clients have to pass through security */
976 if ((zapped_ok) && (ra & UA_ZAPPED)) {
981 /* Fail here if no such room */
983 strcpy(returned_roomname, "");
986 strcpy(returned_roomname, QRscratch.QRname);
993 * Implements the STATUS command (sort of)
996 void imap_status(int num_parms, char *parms[])
999 char roomname[ROOMNAMELEN];
1001 char savedroom[ROOMNAMELEN];
1004 ret = imap_grabroom(roomname, parms[2], 0);
1007 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1013 * usergoto() formally takes us to the desired room, happily returning
1014 * the number of messages and number of new messages. (If another
1015 * folder is selected, save its name so we can return there!!!!!)
1017 if (IMAP->selected) {
1018 strcpy(savedroom, CC->room.QRname);
1020 usergoto(roomname, 0, 0, &msgs, &new);
1023 * Tell the client what it wants to know. In fact, tell it *more* than
1024 * it wants to know. We happily IGnore the supplied status data item
1025 * names and simply spew all possible data items. It's far easier to
1026 * code and probably saves us some processing time too.
1028 imap_mailboxname(buf, sizeof buf, &CC->room);
1029 cprintf("* STATUS ");
1031 cprintf(" (MESSAGES %d ", msgs);
1032 cprintf("RECENT %d ", new); /* Initially, new==recent */
1033 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1034 cprintf("UNSEEN %d)\r\n", new);
1037 * If another folder is selected, go back to that room so we can resume
1038 * our happy day without violent explosions.
1040 if (IMAP->selected) {
1041 usergoto(savedroom, 0, 0, &msgs, &new);
1045 * Oooh, look, we're done!
1047 cprintf("%s OK STATUS completed\r\n", parms[0]);
1053 * Implements the SUBSCRIBE command
1056 void imap_subscribe(int num_parms, char *parms[])
1059 char roomname[ROOMNAMELEN];
1060 char savedroom[ROOMNAMELEN];
1063 ret = imap_grabroom(roomname, parms[2], 1);
1066 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1074 * usergoto() formally takes us to the desired room, which has the side
1075 * effect of marking the room as not-zapped ... exactly the effect
1076 * we're looking for.
1078 if (IMAP->selected) {
1079 strcpy(savedroom, CC->room.QRname);
1081 usergoto(roomname, 0, 0, &msgs, &new);
1084 * If another folder is selected, go back to that room so we can resume
1085 * our happy day without violent explosions.
1087 if (IMAP->selected) {
1088 usergoto(savedroom, 0, 0, &msgs, &new);
1091 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1096 * Implements the UNSUBSCRIBE command
1099 void imap_unsubscribe(int num_parms, char *parms[])
1102 char roomname[ROOMNAMELEN];
1103 char savedroom[ROOMNAMELEN];
1106 ret = imap_grabroom(roomname, parms[2], 0);
1109 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1115 * usergoto() formally takes us to the desired room.
1117 if (IMAP->selected) {
1118 strcpy(savedroom, CC->room.QRname);
1120 usergoto(roomname, 0, 0, &msgs, &new);
1123 * Now make the API call to zap the room
1125 if (CtdlForgetThisRoom() == 0) {
1126 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1129 ("%s NO You may not unsubscribe from this folder.\r\n",
1134 * If another folder is selected, go back to that room so we can resume
1135 * our happy day without violent explosions.
1137 if (IMAP->selected) {
1138 usergoto(savedroom, 0, 0, &msgs, &new);
1145 * Implements the DELETE command
1148 void imap_delete(int num_parms, char *parms[])
1151 char roomname[ROOMNAMELEN];
1152 char savedroom[ROOMNAMELEN];
1155 ret = imap_grabroom(roomname, parms[2], 0);
1157 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1163 * usergoto() formally takes us to the desired room, happily returning
1164 * the number of messages and number of new messages. (If another
1165 * folder is selected, save its name so we can return there!!!!!)
1167 if (IMAP->selected) {
1168 strcpy(savedroom, CC->room.QRname);
1170 usergoto(roomname, 0, 0, &msgs, &new);
1173 * Now delete the room.
1175 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1176 delete_room(&CC->room);
1177 cprintf("%s OK DELETE completed\r\n", parms[0]);
1179 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
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);
1193 * Back end function for imap_rename()
1195 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1197 char foldername[SIZ];
1198 char newfoldername[SIZ];
1199 char newroomname[ROOMNAMELEN];
1201 struct irl *irlp = NULL; /* scratch pointer */
1202 struct irlparms *irlparms;
1204 irlparms = (struct irlparms *) data;
1205 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1207 /* Rename subfolders */
1208 if ((!strncasecmp(foldername, irlparms->oldname,
1209 strlen(irlparms->oldname))
1210 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1212 sprintf(newfoldername, "%s/%s",
1214 &foldername[strlen(irlparms->oldname) + 1]
1217 newfloor = imap_roomname(newroomname,
1219 newfoldername) & 0xFF;
1221 irlp = (struct irl *) malloc(sizeof(struct irl));
1222 strcpy(irlp->irl_newroom, newroomname);
1223 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1224 irlp->irl_newfloor = newfloor;
1225 irlp->next = *(irlparms->irl);
1226 *(irlparms->irl) = irlp;
1232 * Implements the RENAME command
1235 void imap_rename(int num_parms, char *parms[])
1237 char old_room[ROOMNAMELEN];
1238 char new_room[ROOMNAMELEN];
1242 struct irl *irl = NULL; /* the list */
1243 struct irl *irlp = NULL; /* scratch pointer */
1244 struct irlparms irlparms;
1246 if (strchr(parms[3], '\\') != NULL) {
1247 cprintf("%s NO Invalid character in folder name\r\n",
1252 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1253 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1254 new_floor = (newr & 0xFF);
1256 r = CtdlRenameRoom(old_room, new_room, new_floor);
1258 if (r == crr_room_not_found) {
1259 cprintf("%s NO Could not locate this folder\r\n",
1263 if (r == crr_already_exists) {
1264 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1267 if (r == crr_noneditable) {
1268 cprintf("%s This folder is not editable.\r\n", parms[0]);
1271 if (r == crr_invalid_floor) {
1272 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1275 if (r == crr_access_denied) {
1276 cprintf("%s You do not have permission to edit "
1277 "this folder.\r\n", parms[0]);
1281 cprintf("%s NO Rename failed - undefined error %d\r\n",
1287 /* If this is the INBOX, then RFC2060 says we have to just move the
1288 * contents. In a Citadel environment it's easier to rename the room
1289 * (already did that) and create a new inbox.
1291 if (!strcasecmp(parms[2], "INBOX")) {
1292 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1295 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1297 irlparms.oldname = parms[2];
1298 irlparms.newname = parms[3];
1299 irlparms.irl = &irl;
1300 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1302 /* ... and now rename them. */
1303 while (irl != NULL) {
1304 r = CtdlRenameRoom(irl->irl_oldroom,
1308 /* FIXME handle error returns better */
1309 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n",
1318 cprintf("%s OK RENAME completed\r\n", parms[0]);
1325 * Main command loop for IMAP sessions.
1327 void imap_command_loop(void)
1333 CC->lastcmd = time(NULL);
1334 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1336 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1337 lprintf(CTDL_ERR, "IMAP socket is broken. Ending session.\r\n");
1342 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1343 while (strlen(cmdbuf) < 5)
1344 strcat(cmdbuf, " ");
1346 /* strip off l/t whitespace and CRLF */
1347 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1348 cmdbuf[strlen(cmdbuf) - 1] = 0;
1349 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1350 cmdbuf[strlen(cmdbuf) - 1] = 0;
1353 /* If we're in the middle of a multi-line command, handle that */
1354 if (IMAP->authstate == imap_as_expecting_username) {
1355 imap_auth_login_user(cmdbuf);
1358 if (IMAP->authstate == imap_as_expecting_password) {
1359 imap_auth_login_pass(cmdbuf);
1363 /* Ok, at this point we're in normal command mode. The first thing
1364 * we do is print any incoming pages (yeah! we really do!)
1366 imap_print_instant_messages();
1369 * Before processing the command that was just entered... if we happen
1370 * to have a folder selected, we'd like to rescan that folder for new
1371 * messages, and for deletions/changes of existing messages. This
1372 * could probably be optimized somehow, but IMAP sucks...
1374 if (IMAP->selected) {
1375 imap_rescan_msgids();
1378 /* Now for the command set. */
1380 /* Grab the tag, command, and parameters. Check syntax. */
1381 num_parms = imap_parameterize(parms, cmdbuf);
1382 if (num_parms < 2) {
1383 cprintf("BAD syntax error\r\n");
1386 /* The commands below may be executed in any state */
1388 else if ((!strcasecmp(parms[1], "NOOP"))
1389 || (!strcasecmp(parms[1], "CHECK"))) {
1390 cprintf("%s OK This command successfully did nothing.\r\n",
1394 else if (!strcasecmp(parms[1], "LOGOUT")) {
1395 if (IMAP->selected) {
1396 imap_do_expunge(); /* yes, we auto-expunge */
1398 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1399 cprintf("%s OK thank you for using Citadel IMAP\r\n",
1405 else if (!strcasecmp(parms[1], "LOGIN")) {
1406 imap_login(num_parms, parms);
1409 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1410 imap_authenticate(num_parms, parms);
1413 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1414 imap_capability(num_parms, parms);
1417 else if (!strcasecmp(parms[1], "STARTTLS")) {
1418 imap_starttls(num_parms, parms);
1421 else if (!CC->logged_in) {
1422 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1425 /* The commans below require a logged-in state */
1427 else if (!strcasecmp(parms[1], "SELECT")) {
1428 imap_select(num_parms, parms);
1431 else if (!strcasecmp(parms[1], "EXAMINE")) {
1432 imap_select(num_parms, parms);
1435 else if (!strcasecmp(parms[1], "LSUB")) {
1436 imap_lsub(num_parms, parms);
1439 else if (!strcasecmp(parms[1], "LIST")) {
1440 imap_list(num_parms, parms);
1443 else if (!strcasecmp(parms[1], "CREATE")) {
1444 imap_create(num_parms, parms);
1447 else if (!strcasecmp(parms[1], "DELETE")) {
1448 imap_delete(num_parms, parms);
1451 else if (!strcasecmp(parms[1], "RENAME")) {
1452 imap_rename(num_parms, parms);
1455 else if (!strcasecmp(parms[1], "STATUS")) {
1456 imap_status(num_parms, parms);
1459 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1460 imap_subscribe(num_parms, parms);
1463 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1464 imap_unsubscribe(num_parms, parms);
1467 else if (!strcasecmp(parms[1], "APPEND")) {
1468 imap_append(num_parms, parms);
1471 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1472 imap_namespace(num_parms, parms);
1475 else if (IMAP->selected == 0) {
1476 cprintf("%s BAD no folder selected\r\n", parms[0]);
1479 /* The commands below require the SELECT state on a mailbox */
1481 else if (!strcasecmp(parms[1], "FETCH")) {
1482 imap_fetch(num_parms, parms);
1485 else if ((!strcasecmp(parms[1], "UID"))
1486 && (!strcasecmp(parms[2], "FETCH"))) {
1487 imap_uidfetch(num_parms, parms);
1490 else if (!strcasecmp(parms[1], "SEARCH")) {
1491 imap_search(num_parms, parms);
1494 else if ((!strcasecmp(parms[1], "UID"))
1495 && (!strcasecmp(parms[2], "SEARCH"))) {
1496 imap_uidsearch(num_parms, parms);
1499 else if (!strcasecmp(parms[1], "STORE")) {
1500 imap_store(num_parms, parms);
1503 else if ((!strcasecmp(parms[1], "UID"))
1504 && (!strcasecmp(parms[2], "STORE"))) {
1505 imap_uidstore(num_parms, parms);
1508 else if (!strcasecmp(parms[1], "COPY")) {
1509 imap_copy(num_parms, parms);
1512 else if ((!strcasecmp(parms[1], "UID"))
1513 && (!strcasecmp(parms[2], "COPY"))) {
1514 imap_uidcopy(num_parms, parms);
1517 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1518 imap_expunge(num_parms, parms);
1521 else if (!strcasecmp(parms[1], "CLOSE")) {
1522 imap_close(num_parms, parms);
1525 /* End of commands. If we get here, the command is either invalid
1530 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1533 /* If the client transmitted a message we can free it now */
1534 imap_free_transmitted_message();
1540 * This function is called to register the IMAP extension with Citadel.
1542 char *serv_imap_init(void)
1544 CtdlRegisterServiceHook(config.c_imap_port,
1545 NULL, imap_greeting, imap_command_loop, NULL);
1547 CtdlRegisterServiceHook(config.c_imaps_port,
1548 NULL, imaps_greeting, imap_command_loop, NULL);
1550 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);