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");
255 * Check to see if the room's contents have changed.
256 * If not, we can avoid this rescan.
258 getroom(&CC->room, CC->room.QRname);
259 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
263 /* Load the *current* message list from disk, so we can compare it
264 * to what we have in memory.
266 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
268 msglist = malloc(cdbfr->len);
269 if (msglist == NULL) {
270 lprintf(CTDL_CRIT, "malloc() failed\n");
273 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
274 num_msgs = cdbfr->len / sizeof(long);
281 * Check to see if any of the messages we know about have been expunged
283 if (IMAP->num_msgs > 0)
284 for (i = 0; i < IMAP->num_msgs; ++i) {
286 message_still_exists = 0;
288 for (j = 0; j < num_msgs; ++j) {
289 if (msglist[j] == IMAP->msgids[i]) {
290 message_still_exists = 1;
294 if (message_still_exists == 0) {
295 cprintf("* %d EXPUNGE\r\n", i + 1);
297 /* Here's some nice stupid nonsense. When a
298 * message is expunged, we have to slide all
299 * the existing messages up in the message
303 memcpy(&IMAP->msgids[i],
304 &IMAP->msgids[i + 1],
306 (IMAP->num_msgs - i)));
307 memcpy(&IMAP->flags[i],
310 (IMAP->num_msgs - i)));
318 * Remember how many messages were here before we re-scanned.
320 original_num_msgs = IMAP->num_msgs;
321 if (IMAP->num_msgs > 0) {
322 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
324 original_highest = 0L;
328 * Now peruse the room for *new* messages only.
331 for (j = 0; j < num_msgs; ++j) {
332 if (msglist[j] > original_highest) {
333 imap_add_single_msgid(msglist[j], NULL);
337 imap_set_seen_flags();
340 * If new messages have arrived, tell the client about them.
342 if (IMAP->num_msgs > original_num_msgs) {
344 for (j = 0; j < num_msgs; ++j) {
345 if (IMAP->flags[j] & IMAP_RECENT) {
350 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
351 cprintf("* %d RECENT\r\n", num_recent);
357 IMAP->last_mtime = CC->room.QRmtime;
367 * This cleanup function blows away the temporary memory and files used by
370 void imap_cleanup_function(void)
373 /* Don't do this stuff if this is not a IMAP session! */
374 if (CC->h_command_function != imap_command_loop)
377 /* If there is a mailbox selected, auto-expunge it. */
378 if (IMAP->selected) {
382 lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
384 imap_free_transmitted_message();
386 if (IMAP->cached_rfc822_data != NULL) {
387 free(IMAP->cached_rfc822_data);
388 IMAP->cached_rfc822_data = NULL;
389 IMAP->cached_rfc822_msgnum = (-1);
390 IMAP->cached_rfc822_withbody = 0;
393 if (IMAP->cached_body != NULL) {
394 free(IMAP->cached_body);
395 IMAP->cached_body = NULL;
396 IMAP->cached_body_len = 0;
397 IMAP->cached_bodymsgnum = (-1);
401 lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
406 * Does the actual work of the CAPABILITY command (because we need to
407 * output this stuff in other places as well)
409 void imap_output_capability_string(void) {
410 cprintf("CAPABILITY IMAP4REV1 NAMESPACE AUTH=LOGIN");
412 if (!CC->redirect_ssl) cprintf(" STARTTLS");
417 * implements the CAPABILITY command
419 void imap_capability(int num_parms, char *parms[])
422 imap_output_capability_string();
424 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
430 * Here's where our IMAP session begins its happy day.
432 void imap_greeting(void)
435 strcpy(CC->cs_clientname, "IMAP session");
436 IMAP = malloc(sizeof (struct citimap));
437 memset(IMAP, 0, sizeof(struct citimap));
438 IMAP->authstate = imap_as_normal;
439 IMAP->cached_rfc822_data = NULL;
440 IMAP->cached_rfc822_msgnum = (-1);
441 IMAP->cached_rfc822_withbody = 0;
444 imap_output_capability_string();
445 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
449 * IMAPS is just like IMAP, except it goes crypto right away.
452 void imaps_greeting(void) {
453 CtdlStartTLS(NULL, NULL, NULL);
460 * implements the LOGIN command (ordinary username/password login)
462 void imap_login(int num_parms, char *parms[])
464 if (num_parms != 4) {
465 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
469 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
470 if (CtdlTryPassword(parms[3]) == pass_ok) {
471 cprintf("%s OK [", parms[0]);
472 imap_output_capability_string();
473 cprintf("] Hello, %s\r\n", CC->user.fullname);
478 cprintf("%s BAD Login incorrect\r\n", parms[0]);
483 * Implements the AUTHENTICATE command
485 void imap_authenticate(int num_parms, char *parms[])
489 if (num_parms != 3) {
490 cprintf("%s BAD incorrect number of parameters\r\n",
496 cprintf("%s BAD Already logged in.\r\n", parms[0]);
500 if (!strcasecmp(parms[2], "LOGIN")) {
501 CtdlEncodeBase64(buf, "Username:", 9);
502 cprintf("+ %s\r\n", buf);
503 IMAP->authstate = imap_as_expecting_username;
504 strcpy(IMAP->authseq, parms[0]);
509 cprintf("%s NO AUTHENTICATE %s failed\r\n",
514 void imap_auth_login_user(char *cmd)
518 CtdlDecodeBase64(buf, cmd, SIZ);
519 CtdlLoginExistingUser(buf);
520 CtdlEncodeBase64(buf, "Password:", 9);
521 cprintf("+ %s\r\n", buf);
522 IMAP->authstate = imap_as_expecting_password;
526 void imap_auth_login_pass(char *cmd)
530 CtdlDecodeBase64(buf, cmd, SIZ);
531 if (CtdlTryPassword(buf) == pass_ok) {
532 cprintf("%s OK authentication succeeded\r\n",
535 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
537 IMAP->authstate = imap_as_normal;
543 * implements the STARTTLS command (Citadel API version)
546 void imap_starttls(int num_parms, char *parms[])
548 char ok_response[SIZ];
549 char nosup_response[SIZ];
550 char error_response[SIZ];
553 "%s OK begin TLS negotiation now\r\n",
555 sprintf(nosup_response,
556 "%s NO TLS not supported here\r\n",
558 sprintf(error_response,
559 "%s BAD Internal error\r\n",
561 CtdlStartTLS(ok_response, nosup_response, error_response);
567 * implements the SELECT command
569 void imap_select(int num_parms, char *parms[])
572 char augmented_roomname[ROOMNAMELEN];
576 struct ctdlroom QRscratch;
582 /* Convert the supplied folder name to a roomname */
583 i = imap_roomname(towhere, sizeof towhere, parms[2]);
585 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
589 floornum = (i & 0x00ff);
590 roomflags = (i & 0xff00);
592 /* First try a regular match */
593 c = getroom(&QRscratch, towhere);
595 /* Then try a mailbox name match */
597 MailboxName(augmented_roomname, sizeof augmented_roomname,
599 c = getroom(&QRscratch, augmented_roomname);
601 strcpy(towhere, augmented_roomname);
604 /* If the room exists, check security/access */
606 /* See if there is an existing user/room relationship */
607 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
609 /* normal clients have to pass through security */
615 /* Fail here if no such room */
617 cprintf("%s NO ... no such room, or access denied\r\n",
622 /* If we already had some other folder selected, auto-expunge it */
626 * usergoto() formally takes us to the desired room, happily returning
627 * the number of messages and number of new messages.
629 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
630 usergoto(NULL, 0, 0, &msgs, &new);
633 if (!strcasecmp(parms[1], "EXAMINE")) {
640 IMAP->last_mtime = CC->room.QRmtime;
642 cprintf("* %d EXISTS\r\n", msgs);
643 cprintf("* %d RECENT\r\n", new);
645 cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
646 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
648 /* Note that \Deleted is a valid flag, but not a permanent flag,
649 * because we don't maintain its state across sessions. Citadel
650 * automatically expunges mailboxes when they are de-selected.
652 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
653 cprintf("* OK [PERMANENTFLAGS (\\Seen \\Answered)] "
654 "permanent flags\r\n");
656 cprintf("%s OK [%s] %s completed\r\n",
658 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
664 * does the real work for expunge
666 int imap_do_expunge(void)
669 int num_expunged = 0;
671 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
672 if (IMAP->selected == 0) {
676 if (IMAP->num_msgs > 0)
677 for (i = 0; i < IMAP->num_msgs; ++i) {
678 if (IMAP->flags[i] & IMAP_DELETED) {
679 CtdlDeleteMessages(CC->room.QRname,
680 IMAP->msgids[i], "");
685 if (num_expunged > 0) {
686 imap_rescan_msgids();
689 lprintf(CTDL_DEBUG, "Expunged %d messages.\n", num_expunged);
690 return (num_expunged);
695 * implements the EXPUNGE command syntax
697 void imap_expunge(int num_parms, char *parms[])
699 int num_expunged = 0;
701 num_expunged = imap_do_expunge();
702 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
707 * implements the CLOSE command
709 void imap_close(int num_parms, char *parms[])
712 /* Yes, we always expunge on close. */
713 if (IMAP->selected) {
720 cprintf("%s OK CLOSE completed\r\n", parms[0]);
725 * Implements the NAMESPACE command.
727 void imap_namespace(int num_parms, char *parms[])
734 cprintf("* NAMESPACE ");
736 /* All personal folders are subordinate to INBOX. */
737 cprintf("((\"INBOX/\" \"/\")) ");
739 /* Other users' folders ... coming soon! FIXME */
742 /* Show all floors as shared namespaces. Neato! */
744 for (i = 0; i < MAXFLOORS; ++i) {
746 if (fl->f_flags & F_INUSE) {
747 if (floors > 0) cprintf(" ");
749 sprintf(buf, "%s/", fl->f_name);
757 /* Wind it up with a newline and a completion message. */
759 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
765 * Used by LIST and LSUB to show the floors in the listing
767 void imap_list_floors(char *cmd, char *pattern)
772 for (i = 0; i < MAXFLOORS; ++i) {
774 if (fl->f_flags & F_INUSE) {
775 if (imap_mailbox_matches_pattern
776 (pattern, fl->f_name)) {
777 cprintf("* %s (\\NoSelect) \"/\" ", cmd);
778 imap_strout(fl->f_name);
788 * Back end for imap_lsub()
790 * IMAP "subscribed folder" is equivocated to Citadel "known rooms." This
791 * may or may not be the desired behavior in the future.
793 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data)
799 pattern = (char *) data;
801 /* Only list rooms to which the user has access!! */
802 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
804 imap_mailboxname(buf, sizeof buf, qrbuf);
805 if (imap_mailbox_matches_pattern(pattern, buf)) {
806 cprintf("* LSUB () \"/\" ");
815 * Implements the LSUB command
817 void imap_lsub(int num_parms, char *parms[])
821 cprintf("%s BAD arguments invalid\r\n", parms[0]);
824 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
826 if (strlen(parms[3]) == 0) {
827 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
831 imap_list_floors("LSUB", pattern);
832 ForEachRoom(imap_lsub_listroom, pattern);
835 cprintf("%s OK LSUB completed\r\n", parms[0]);
841 * Back end for imap_list()
843 void imap_list_listroom(struct ctdlroom *qrbuf, void *data)
849 pattern = (char *) data;
851 /* Only list rooms to which the user has access!! */
852 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
854 || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
855 imap_mailboxname(buf, sizeof buf, qrbuf);
856 if (imap_mailbox_matches_pattern(pattern, buf)) {
857 cprintf("* LIST () \"/\" ");
866 * Implements the LIST command
868 void imap_list(int num_parms, char *parms[])
872 cprintf("%s BAD arguments invalid\r\n", parms[0]);
875 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
877 if (strlen(parms[3]) == 0) {
878 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
882 imap_list_floors("LIST", pattern);
883 ForEachRoom(imap_list_listroom, pattern);
886 cprintf("%s OK LIST completed\r\n", parms[0]);
892 * Implements the CREATE command
895 void imap_create(int num_parms, char *parms[])
898 char roomname[ROOMNAMELEN];
904 if (strchr(parms[2], '\\') != NULL) {
905 cprintf("%s NO Invalid character in folder name\r\n",
907 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
911 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
913 cprintf("%s NO Invalid mailbox name or location\r\n",
915 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
918 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
919 flags = (ret & 0xff00); /* upper 8 bits = flags */
921 if (flags & IR_MAILBOX) {
922 if (strncasecmp(parms[2], "INBOX/", 6)) {
923 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
924 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
929 if (flags & IR_MAILBOX) {
930 newroomtype = 4; /* private mailbox */
931 newroomview = VIEW_MAILBOX;
933 newroomtype = 0; /* public folder */
934 newroomview = VIEW_BBS;
937 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
938 roomname, floornum, newroomtype);
940 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
943 ("%s NO Mailbox already exists, or create failed\r\n",
946 cprintf("%s OK CREATE completed\r\n", parms[0]);
948 lprintf(CTDL_DEBUG, "imap_create() completed\n");
953 * Locate a room by its IMAP folder name, and check access to it.
954 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
956 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
959 char augmented_roomname[ROOMNAMELEN];
960 char roomname[ROOMNAMELEN];
962 struct ctdlroom QRscratch;
966 ret = imap_roomname(roomname, sizeof roomname, foldername);
971 /* First try a regular match */
972 c = getroom(&QRscratch, roomname);
974 /* Then try a mailbox name match */
976 MailboxName(augmented_roomname, sizeof augmented_roomname,
977 &CC->user, roomname);
978 c = getroom(&QRscratch, augmented_roomname);
980 strcpy(roomname, augmented_roomname);
983 /* If the room exists, check security/access */
985 /* See if there is an existing user/room relationship */
986 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
988 /* normal clients have to pass through security */
992 if ((zapped_ok) && (ra & UA_ZAPPED)) {
997 /* Fail here if no such room */
999 strcpy(returned_roomname, "");
1002 strcpy(returned_roomname, QRscratch.QRname);
1009 * Implements the STATUS command (sort of)
1012 void imap_status(int num_parms, char *parms[])
1015 char roomname[ROOMNAMELEN];
1017 char savedroom[ROOMNAMELEN];
1020 ret = imap_grabroom(roomname, parms[2], 0);
1023 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1029 * usergoto() formally takes us to the desired room, happily returning
1030 * the number of messages and number of new messages. (If another
1031 * folder is selected, save its name so we can return there!!!!!)
1033 if (IMAP->selected) {
1034 strcpy(savedroom, CC->room.QRname);
1036 usergoto(roomname, 0, 0, &msgs, &new);
1039 * Tell the client what it wants to know. In fact, tell it *more* than
1040 * it wants to know. We happily IGnore the supplied status data item
1041 * names and simply spew all possible data items. It's far easier to
1042 * code and probably saves us some processing time too.
1044 imap_mailboxname(buf, sizeof buf, &CC->room);
1045 cprintf("* STATUS ");
1047 cprintf(" (MESSAGES %d ", msgs);
1048 cprintf("RECENT %d ", new); /* Initially, new==recent */
1049 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1050 cprintf("UNSEEN %d)\r\n", new);
1053 * If another folder is selected, go back to that room so we can resume
1054 * our happy day without violent explosions.
1056 if (IMAP->selected) {
1057 usergoto(savedroom, 0, 0, &msgs, &new);
1061 * Oooh, look, we're done!
1063 cprintf("%s OK STATUS completed\r\n", parms[0]);
1069 * Implements the SUBSCRIBE command
1072 void imap_subscribe(int num_parms, char *parms[])
1075 char roomname[ROOMNAMELEN];
1076 char savedroom[ROOMNAMELEN];
1079 ret = imap_grabroom(roomname, parms[2], 1);
1082 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1090 * usergoto() formally takes us to the desired room, which has the side
1091 * effect of marking the room as not-zapped ... exactly the effect
1092 * we're looking for.
1094 if (IMAP->selected) {
1095 strcpy(savedroom, CC->room.QRname);
1097 usergoto(roomname, 0, 0, &msgs, &new);
1100 * If another folder is selected, go back to that room so we can resume
1101 * our happy day without violent explosions.
1103 if (IMAP->selected) {
1104 usergoto(savedroom, 0, 0, &msgs, &new);
1107 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1112 * Implements the UNSUBSCRIBE command
1115 void imap_unsubscribe(int num_parms, char *parms[])
1118 char roomname[ROOMNAMELEN];
1119 char savedroom[ROOMNAMELEN];
1122 ret = imap_grabroom(roomname, parms[2], 0);
1125 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1131 * usergoto() formally takes us to the desired room.
1133 if (IMAP->selected) {
1134 strcpy(savedroom, CC->room.QRname);
1136 usergoto(roomname, 0, 0, &msgs, &new);
1139 * Now make the API call to zap the room
1141 if (CtdlForgetThisRoom() == 0) {
1142 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1145 ("%s NO You may not unsubscribe from this folder.\r\n",
1150 * If another folder is selected, go back to that room so we can resume
1151 * our happy day without violent explosions.
1153 if (IMAP->selected) {
1154 usergoto(savedroom, 0, 0, &msgs, &new);
1161 * Implements the DELETE command
1164 void imap_delete(int num_parms, char *parms[])
1167 char roomname[ROOMNAMELEN];
1168 char savedroom[ROOMNAMELEN];
1171 ret = imap_grabroom(roomname, parms[2], 0);
1173 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1179 * usergoto() formally takes us to the desired room, happily returning
1180 * the number of messages and number of new messages. (If another
1181 * folder is selected, save its name so we can return there!!!!!)
1183 if (IMAP->selected) {
1184 strcpy(savedroom, CC->room.QRname);
1186 usergoto(roomname, 0, 0, &msgs, &new);
1189 * Now delete the room.
1191 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1192 schedule_room_for_deletion(&CC->room);
1193 cprintf("%s OK DELETE completed\r\n", parms[0]);
1195 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1199 * If another folder is selected, go back to that room so we can resume
1200 * our happy day without violent explosions.
1202 if (IMAP->selected) {
1203 usergoto(savedroom, 0, 0, &msgs, &new);
1209 * Back end function for imap_rename()
1211 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1213 char foldername[SIZ];
1214 char newfoldername[SIZ];
1215 char newroomname[ROOMNAMELEN];
1217 struct irl *irlp = NULL; /* scratch pointer */
1218 struct irlparms *irlparms;
1220 irlparms = (struct irlparms *) data;
1221 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1223 /* Rename subfolders */
1224 if ((!strncasecmp(foldername, irlparms->oldname,
1225 strlen(irlparms->oldname))
1226 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1228 sprintf(newfoldername, "%s/%s",
1230 &foldername[strlen(irlparms->oldname) + 1]
1233 newfloor = imap_roomname(newroomname,
1235 newfoldername) & 0xFF;
1237 irlp = (struct irl *) malloc(sizeof(struct irl));
1238 strcpy(irlp->irl_newroom, newroomname);
1239 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1240 irlp->irl_newfloor = newfloor;
1241 irlp->next = *(irlparms->irl);
1242 *(irlparms->irl) = irlp;
1248 * Implements the RENAME command
1251 void imap_rename(int num_parms, char *parms[])
1253 char old_room[ROOMNAMELEN];
1254 char new_room[ROOMNAMELEN];
1258 struct irl *irl = NULL; /* the list */
1259 struct irl *irlp = NULL; /* scratch pointer */
1260 struct irlparms irlparms;
1262 if (strchr(parms[3], '\\') != NULL) {
1263 cprintf("%s NO Invalid character in folder name\r\n",
1268 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1269 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1270 new_floor = (newr & 0xFF);
1272 r = CtdlRenameRoom(old_room, new_room, new_floor);
1274 if (r == crr_room_not_found) {
1275 cprintf("%s NO Could not locate this folder\r\n",
1279 if (r == crr_already_exists) {
1280 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1283 if (r == crr_noneditable) {
1284 cprintf("%s This folder is not editable.\r\n", parms[0]);
1287 if (r == crr_invalid_floor) {
1288 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1291 if (r == crr_access_denied) {
1292 cprintf("%s You do not have permission to edit "
1293 "this folder.\r\n", parms[0]);
1297 cprintf("%s NO Rename failed - undefined error %d\r\n",
1303 /* If this is the INBOX, then RFC2060 says we have to just move the
1304 * contents. In a Citadel environment it's easier to rename the room
1305 * (already did that) and create a new inbox.
1307 if (!strcasecmp(parms[2], "INBOX")) {
1308 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1311 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1313 irlparms.oldname = parms[2];
1314 irlparms.newname = parms[3];
1315 irlparms.irl = &irl;
1316 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1318 /* ... and now rename them. */
1319 while (irl != NULL) {
1320 r = CtdlRenameRoom(irl->irl_oldroom,
1324 /* FIXME handle error returns better */
1325 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n",
1334 cprintf("%s OK RENAME completed\r\n", parms[0]);
1341 * Main command loop for IMAP sessions.
1343 void imap_command_loop(void)
1349 CC->lastcmd = time(NULL);
1350 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1352 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1353 lprintf(CTDL_ERR, "IMAP socket is broken. Ending session.\r\n");
1358 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1359 while (strlen(cmdbuf) < 5)
1360 strcat(cmdbuf, " ");
1362 /* strip off l/t whitespace and CRLF */
1363 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1364 cmdbuf[strlen(cmdbuf) - 1] = 0;
1365 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1366 cmdbuf[strlen(cmdbuf) - 1] = 0;
1369 /* If we're in the middle of a multi-line command, handle that */
1370 if (IMAP->authstate == imap_as_expecting_username) {
1371 imap_auth_login_user(cmdbuf);
1374 if (IMAP->authstate == imap_as_expecting_password) {
1375 imap_auth_login_pass(cmdbuf);
1379 /* Ok, at this point we're in normal command mode. The first thing
1380 * we do is print any incoming pages (yeah! we really do!)
1382 imap_print_instant_messages();
1385 * Before processing the command that was just entered... if we happen
1386 * to have a folder selected, we'd like to rescan that folder for new
1387 * messages, and for deletions/changes of existing messages. This
1388 * could probably be optimized somehow, but IMAP sucks...
1390 if (IMAP->selected) {
1391 imap_rescan_msgids();
1394 /* Now for the command set. */
1396 /* Grab the tag, command, and parameters. Check syntax. */
1397 num_parms = imap_parameterize(parms, cmdbuf);
1398 if (num_parms < 2) {
1399 cprintf("BAD syntax error\r\n");
1402 /* The commands below may be executed in any state */
1404 else if ((!strcasecmp(parms[1], "NOOP"))
1405 || (!strcasecmp(parms[1], "CHECK"))) {
1406 cprintf("%s OK This command successfully did nothing.\r\n",
1410 else if (!strcasecmp(parms[1], "LOGOUT")) {
1411 if (IMAP->selected) {
1412 imap_do_expunge(); /* yes, we auto-expunge */
1414 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1415 cprintf("%s OK thank you for using Citadel IMAP\r\n",
1421 else if (!strcasecmp(parms[1], "LOGIN")) {
1422 imap_login(num_parms, parms);
1425 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1426 imap_authenticate(num_parms, parms);
1429 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1430 imap_capability(num_parms, parms);
1433 else if (!strcasecmp(parms[1], "STARTTLS")) {
1434 imap_starttls(num_parms, parms);
1437 else if (!CC->logged_in) {
1438 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1441 /* The commans below require a logged-in state */
1443 else if (!strcasecmp(parms[1], "SELECT")) {
1444 imap_select(num_parms, parms);
1447 else if (!strcasecmp(parms[1], "EXAMINE")) {
1448 imap_select(num_parms, parms);
1451 else if (!strcasecmp(parms[1], "LSUB")) {
1452 imap_lsub(num_parms, parms);
1455 else if (!strcasecmp(parms[1], "LIST")) {
1456 imap_list(num_parms, parms);
1459 else if (!strcasecmp(parms[1], "CREATE")) {
1460 imap_create(num_parms, parms);
1463 else if (!strcasecmp(parms[1], "DELETE")) {
1464 imap_delete(num_parms, parms);
1467 else if (!strcasecmp(parms[1], "RENAME")) {
1468 imap_rename(num_parms, parms);
1471 else if (!strcasecmp(parms[1], "STATUS")) {
1472 imap_status(num_parms, parms);
1475 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1476 imap_subscribe(num_parms, parms);
1479 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1480 imap_unsubscribe(num_parms, parms);
1483 else if (!strcasecmp(parms[1], "APPEND")) {
1484 imap_append(num_parms, parms);
1487 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1488 imap_namespace(num_parms, parms);
1491 else if (IMAP->selected == 0) {
1492 cprintf("%s BAD no folder selected\r\n", parms[0]);
1495 /* The commands below require the SELECT state on a mailbox */
1497 else if (!strcasecmp(parms[1], "FETCH")) {
1498 imap_fetch(num_parms, parms);
1501 else if ((!strcasecmp(parms[1], "UID"))
1502 && (!strcasecmp(parms[2], "FETCH"))) {
1503 imap_uidfetch(num_parms, parms);
1506 else if (!strcasecmp(parms[1], "SEARCH")) {
1507 imap_search(num_parms, parms);
1510 else if ((!strcasecmp(parms[1], "UID"))
1511 && (!strcasecmp(parms[2], "SEARCH"))) {
1512 imap_uidsearch(num_parms, parms);
1515 else if (!strcasecmp(parms[1], "STORE")) {
1516 imap_store(num_parms, parms);
1519 else if ((!strcasecmp(parms[1], "UID"))
1520 && (!strcasecmp(parms[2], "STORE"))) {
1521 imap_uidstore(num_parms, parms);
1524 else if (!strcasecmp(parms[1], "COPY")) {
1525 imap_copy(num_parms, parms);
1528 else if ((!strcasecmp(parms[1], "UID"))
1529 && (!strcasecmp(parms[2], "COPY"))) {
1530 imap_uidcopy(num_parms, parms);
1533 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1534 imap_expunge(num_parms, parms);
1537 else if (!strcasecmp(parms[1], "CLOSE")) {
1538 imap_close(num_parms, parms);
1541 /* End of commands. If we get here, the command is either invalid
1546 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1549 /* If the client transmitted a message we can free it now */
1550 imap_free_transmitted_message();
1556 * This function is called to register the IMAP extension with Citadel.
1558 char *serv_imap_init(void)
1560 CtdlRegisterServiceHook(config.c_imap_port,
1561 NULL, imap_greeting, imap_command_loop, NULL);
1563 CtdlRegisterServiceHook(config.c_imaps_port,
1564 NULL, imaps_greeting, imap_command_loop, NULL);
1566 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);