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) {
98 * If there is a transmitted message in memory, free it
100 void imap_free_transmitted_message(void)
102 if (IMAP->transmitted_message != NULL) {
103 free(IMAP->transmitted_message);
104 IMAP->transmitted_message = NULL;
105 IMAP->transmitted_length = 0;
111 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
112 * sets stored in the visit record for this user/room. Note that we have
113 * to parse each sequence set manually here, because calling the utility
114 * function is_msg_in_sequence_set() over and over again is too expensive.
116 void imap_set_seen_flags(void)
122 char setstr[SIZ], lostr[SIZ], histr[SIZ];
125 if (IMAP->num_msgs < 1) return;
126 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
128 for (i = 0; i < IMAP->num_msgs; ++i) {
129 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
130 IMAP->flags[i] |= IMAP_RECENT;
131 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
134 /* Do the "\Seen" flag. (Any message not "\Seen" is considered "\Recent".) */
135 num_sets = num_tokens(vbuf.v_seen, ',');
136 for (s=0; s<num_sets; ++s) {
137 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
139 extract_token(lostr, setstr, 0, ':', sizeof lostr);
140 if (num_tokens(setstr, ':') >= 2) {
141 extract_token(histr, setstr, 1, ':', sizeof histr);
142 if (!strcmp(histr, "*")) {
143 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
147 strcpy(histr, lostr);
152 for (i = 0; i < IMAP->num_msgs; ++i) {
153 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)) {
154 IMAP->flags[i] |= IMAP_SEEN;
155 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
160 /* Do the ANSWERED flag */
161 num_sets = num_tokens(vbuf.v_answered, ',');
162 for (s=0; s<num_sets; ++s) {
163 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
165 extract_token(lostr, setstr, 0, ':', sizeof lostr);
166 if (num_tokens(setstr, ':') >= 2) {
167 extract_token(histr, setstr, 1, ':', sizeof histr);
168 if (!strcmp(histr, "*")) {
169 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
173 strcpy(histr, lostr);
178 for (i = 0; i < IMAP->num_msgs; ++i) {
179 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)) {
180 IMAP->flags[i] |= IMAP_ANSWERED;
190 * Back end for imap_load_msgids()
192 * Optimization: instead of calling realloc() to add each message, we
193 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
194 * allows the mapping to proceed much faster.
196 void imap_add_single_msgid(long msgnum, void *userdata)
200 if (IMAP->num_msgs > IMAP->num_alloc) {
201 IMAP->num_alloc += REALLOC_INCREMENT;
202 IMAP->msgids = realloc(IMAP->msgids, (IMAP->num_alloc * sizeof(long)));
203 IMAP->flags = realloc(IMAP->flags, (IMAP->num_alloc * sizeof(long)));
205 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
206 IMAP->flags[IMAP->num_msgs - 1] = 0;
212 * Set up a message ID map for the current room (folder)
214 void imap_load_msgids(void)
217 if (IMAP->selected == 0) {
219 "imap_load_msgids() can't run; no room selected\n");
223 imap_free_msgids(); /* If there was already a map, free it */
225 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
226 imap_add_single_msgid, NULL);
228 imap_set_seen_flags();
233 * Re-scan the selected room (folder) and see if it's been changed at all
235 void imap_rescan_msgids(void)
238 int original_num_msgs = 0;
239 long original_highest = 0L;
241 int message_still_exists;
242 struct cdbdata *cdbfr;
243 long *msglist = NULL;
247 if (IMAP->selected == 0) {
249 "imap_load_msgids() can't run; no room selected\n");
253 /* Load the *current* message list from disk, so we can compare it
254 * to what we have in memory.
256 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
258 msglist = malloc(cdbfr->len);
259 if (msglist == NULL) {
260 lprintf(CTDL_CRIT, "malloc() failed\n");
263 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
264 num_msgs = cdbfr->len / sizeof(long);
271 * Check to see if any of the messages we know about have been expunged
273 if (IMAP->num_msgs > 0)
274 for (i = 0; i < IMAP->num_msgs; ++i) {
276 message_still_exists = 0;
278 for (j = 0; j < num_msgs; ++j) {
279 if (msglist[j] == IMAP->msgids[i]) {
280 message_still_exists = 1;
284 if (message_still_exists == 0) {
285 cprintf("* %d EXPUNGE\r\n", i + 1);
287 /* Here's some nice stupid nonsense. When a message
288 * is expunged, we have to slide all the existing
289 * messages up in the message array.
292 memcpy(&IMAP->msgids[i],
293 &IMAP->msgids[i + 1],
295 (IMAP->num_msgs - i)));
296 memcpy(&IMAP->flags[i],
299 (IMAP->num_msgs - i)));
307 * Remember how many messages were here before we re-scanned.
309 original_num_msgs = IMAP->num_msgs;
310 if (IMAP->num_msgs > 0) {
311 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
313 original_highest = 0L;
317 * Now peruse the room for *new* messages only.
320 for (j = 0; j < num_msgs; ++j) {
321 if (msglist[j] > original_highest) {
322 imap_add_single_msgid(msglist[j], NULL);
325 imap_set_seen_flags();
328 * If new messages have arrived, tell the client about them.
330 if (IMAP->num_msgs > original_num_msgs) {
332 for (j = 0; j < num_msgs; ++j) {
333 if (IMAP->flags[j] & IMAP_RECENT) {
338 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
339 cprintf("* %d RECENT\r\n", num_recent);
353 * This cleanup function blows away the temporary memory and files used by
356 void imap_cleanup_function(void)
359 /* Don't do this stuff if this is not a IMAP session! */
360 if (CC->h_command_function != imap_command_loop)
363 /* If there is a mailbox selected, auto-expunge it. */
364 if (IMAP->selected) {
368 lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
370 imap_free_transmitted_message();
372 if (IMAP->cached_rfc822_data != NULL) {
373 free(IMAP->cached_rfc822_data);
374 IMAP->cached_rfc822_data = NULL;
375 IMAP->cached_rfc822_msgnum = (-1);
378 if (IMAP->cached_body != NULL) {
379 free(IMAP->cached_body);
380 IMAP->cached_body = NULL;
381 IMAP->cached_body_len = 0;
382 IMAP->cached_bodymsgnum = (-1);
386 lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
392 * Here's where our IMAP session begins its happy day.
394 void imap_greeting(void)
397 strcpy(CC->cs_clientname, "IMAP session");
398 IMAP = malloc(sizeof (struct citimap));
399 memset(IMAP, 0, sizeof(struct citimap));
400 IMAP->authstate = imap_as_normal;
401 IMAP->cached_rfc822_data = NULL;
402 IMAP->cached_rfc822_msgnum = (-1);
404 cprintf("* OK %s Citadel IMAP4rev1 server ready\r\n",
409 * IMAPS is just like IMAP, except it goes crypto right away.
412 void imaps_greeting(void) {
413 CtdlStartTLS(NULL, NULL, NULL);
420 * implements the LOGIN command (ordinary username/password login)
422 void imap_login(int num_parms, char *parms[])
424 if (num_parms != 4) {
425 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
429 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
430 if (CtdlTryPassword(parms[3]) == pass_ok) {
431 cprintf("%s OK login successful\r\n", parms[0]);
436 cprintf("%s BAD Login incorrect\r\n", parms[0]);
441 * Implements the AUTHENTICATE command
443 void imap_authenticate(int num_parms, char *parms[])
447 if (num_parms != 3) {
448 cprintf("%s BAD incorrect number of parameters\r\n",
454 cprintf("%s BAD Already logged in.\r\n", parms[0]);
458 if (!strcasecmp(parms[2], "LOGIN")) {
459 CtdlEncodeBase64(buf, "Username:", 9);
460 cprintf("+ %s\r\n", buf);
461 IMAP->authstate = imap_as_expecting_username;
462 strcpy(IMAP->authseq, parms[0]);
467 cprintf("%s NO AUTHENTICATE %s failed\r\n",
472 void imap_auth_login_user(char *cmd)
476 CtdlDecodeBase64(buf, cmd, SIZ);
477 CtdlLoginExistingUser(buf);
478 CtdlEncodeBase64(buf, "Password:", 9);
479 cprintf("+ %s\r\n", buf);
480 IMAP->authstate = imap_as_expecting_password;
484 void imap_auth_login_pass(char *cmd)
488 CtdlDecodeBase64(buf, cmd, SIZ);
489 if (CtdlTryPassword(buf) == pass_ok) {
490 cprintf("%s OK authentication succeeded\r\n",
493 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
495 IMAP->authstate = imap_as_normal;
501 * implements the CAPABILITY command
503 void imap_capability(int num_parms, char *parms[])
505 cprintf("* CAPABILITY IMAP4 IMAP4REV1 NAMESPACE AUTH=LOGIN");
508 cprintf(" STARTTLS");
512 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
518 * implements the STARTTLS command (Citadel API version)
521 void imap_starttls(int num_parms, char *parms[])
523 char ok_response[SIZ];
524 char nosup_response[SIZ];
525 char error_response[SIZ];
528 "%s OK begin TLS negotiation now\r\n",
530 sprintf(nosup_response,
531 "%s NO TLS not supported here\r\n",
533 sprintf(error_response,
534 "%s BAD Internal error\r\n",
536 CtdlStartTLS(ok_response, nosup_response, error_response);
542 * implements the SELECT command
544 void imap_select(int num_parms, char *parms[])
547 char augmented_roomname[ROOMNAMELEN];
551 struct ctdlroom QRscratch;
557 /* Convert the supplied folder name to a roomname */
558 i = imap_roomname(towhere, sizeof towhere, parms[2]);
560 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
564 floornum = (i & 0x00ff);
565 roomflags = (i & 0xff00);
567 /* First try a regular match */
568 c = getroom(&QRscratch, towhere);
570 /* Then try a mailbox name match */
572 MailboxName(augmented_roomname, sizeof augmented_roomname,
574 c = getroom(&QRscratch, augmented_roomname);
576 strcpy(towhere, augmented_roomname);
579 /* If the room exists, check security/access */
581 /* See if there is an existing user/room relationship */
582 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
584 /* normal clients have to pass through security */
590 /* Fail here if no such room */
592 cprintf("%s NO ... no such room, or access denied\r\n",
597 /* If we already had some other folder selected, auto-expunge it */
601 * usergoto() formally takes us to the desired room, happily returning
602 * the number of messages and number of new messages.
604 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
605 usergoto(NULL, 0, 0, &msgs, &new);
608 if (!strcasecmp(parms[1], "EXAMINE")) {
616 cprintf("* %d EXISTS\r\n", msgs);
617 cprintf("* %d RECENT\r\n", new);
619 /* Note that \Deleted is a valid flag, but not a permanent flag,
620 * because we don't maintain its state across sessions. Citadel
621 * automatically expunges mailboxes when they are de-selected.
623 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
624 cprintf("* OK [PERMANENTFLAGS (\\Seen \\Answered)] "
625 "permanent flags\r\n");
627 cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
628 cprintf("%s OK [%s] %s completed\r\n",
630 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
636 * does the real work for expunge
638 int imap_do_expunge(void)
641 int num_expunged = 0;
643 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
644 if (IMAP->selected == 0) {
648 if (IMAP->num_msgs > 0)
649 for (i = 0; i < IMAP->num_msgs; ++i) {
650 if (IMAP->flags[i] & IMAP_DELETED) {
651 CtdlDeleteMessages(CC->room.QRname,
652 IMAP->msgids[i], "");
657 if (num_expunged > 0) {
658 imap_rescan_msgids();
661 lprintf(CTDL_DEBUG, "Expunged %d messages.\n", num_expunged);
662 return (num_expunged);
667 * implements the EXPUNGE command syntax
669 void imap_expunge(int num_parms, char *parms[])
671 int num_expunged = 0;
673 num_expunged = imap_do_expunge();
674 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
679 * implements the CLOSE command
681 void imap_close(int num_parms, char *parms[])
684 /* Yes, we always expunge on close. */
685 if (IMAP->selected) {
692 cprintf("%s OK CLOSE completed\r\n", parms[0]);
697 * Implements the NAMESPACE command.
699 void imap_namespace(int num_parms, char *parms[])
706 cprintf("* NAMESPACE ");
708 /* All personal folders are subordinate to INBOX. */
709 cprintf("((\"INBOX/\" \"/\")) ");
711 /* Other users' folders ... coming soon! FIXME */
714 /* Show all floors as shared namespaces. Neato! */
716 for (i = 0; i < MAXFLOORS; ++i) {
718 if (fl->f_flags & F_INUSE) {
719 if (floors > 0) cprintf(" ");
721 sprintf(buf, "%s/", fl->f_name);
729 /* Wind it up with a newline and a completion message. */
731 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
737 * Used by LIST and LSUB to show the floors in the listing
739 void imap_list_floors(char *cmd, char *pattern)
744 for (i = 0; i < MAXFLOORS; ++i) {
746 if (fl->f_flags & F_INUSE) {
747 if (imap_mailbox_matches_pattern
748 (pattern, fl->f_name)) {
749 cprintf("* %s (\\NoSelect) \"/\" ", cmd);
750 imap_strout(fl->f_name);
760 * Back end for imap_lsub()
762 * IMAP "subscribed folder" is equivocated to Citadel "known rooms." This
763 * may or may not be the desired behavior in the future.
765 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data)
771 pattern = (char *) data;
773 /* Only list rooms to which the user has access!! */
774 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
776 imap_mailboxname(buf, sizeof buf, qrbuf);
777 if (imap_mailbox_matches_pattern(pattern, buf)) {
778 cprintf("* LSUB () \"/\" ");
787 * Implements the LSUB command
789 void imap_lsub(int num_parms, char *parms[])
793 cprintf("%s BAD arguments invalid\r\n", parms[0]);
796 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
798 if (strlen(parms[3]) == 0) {
799 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
803 imap_list_floors("LSUB", pattern);
804 ForEachRoom(imap_lsub_listroom, pattern);
807 cprintf("%s OK LSUB completed\r\n", parms[0]);
813 * Back end for imap_list()
815 void imap_list_listroom(struct ctdlroom *qrbuf, void *data)
821 pattern = (char *) data;
823 /* Only list rooms to which the user has access!! */
824 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
826 || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
827 imap_mailboxname(buf, sizeof buf, qrbuf);
828 if (imap_mailbox_matches_pattern(pattern, buf)) {
829 cprintf("* LIST () \"/\" ");
838 * Implements the LIST command
840 void imap_list(int num_parms, char *parms[])
844 cprintf("%s BAD arguments invalid\r\n", parms[0]);
847 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
849 if (strlen(parms[3]) == 0) {
850 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
854 imap_list_floors("LIST", pattern);
855 ForEachRoom(imap_list_listroom, pattern);
858 cprintf("%s OK LIST completed\r\n", parms[0]);
864 * Implements the CREATE command
867 void imap_create(int num_parms, char *parms[])
870 char roomname[ROOMNAMELEN];
876 if (strchr(parms[2], '\\') != NULL) {
877 cprintf("%s NO Invalid character in folder name\r\n",
879 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
883 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
885 cprintf("%s NO Invalid mailbox name or location\r\n",
887 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
890 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
891 flags = (ret & 0xff00); /* upper 8 bits = flags */
893 if (flags & IR_MAILBOX) {
894 if (strncasecmp(parms[2], "INBOX/", 6)) {
895 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
896 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
901 if (flags & IR_MAILBOX) {
902 newroomtype = 4; /* private mailbox */
903 newroomview = VIEW_MAILBOX;
905 newroomtype = 0; /* public folder */
906 newroomview = VIEW_BBS;
909 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
910 roomname, floornum, newroomtype);
912 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
915 ("%s NO Mailbox already exists, or create failed\r\n",
918 cprintf("%s OK CREATE completed\r\n", parms[0]);
920 lprintf(CTDL_DEBUG, "imap_create() completed\n");
925 * Locate a room by its IMAP folder name, and check access to it.
926 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
928 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
931 char augmented_roomname[ROOMNAMELEN];
932 char roomname[ROOMNAMELEN];
934 struct ctdlroom QRscratch;
938 ret = imap_roomname(roomname, sizeof roomname, foldername);
943 /* First try a regular match */
944 c = getroom(&QRscratch, roomname);
946 /* Then try a mailbox name match */
948 MailboxName(augmented_roomname, sizeof augmented_roomname,
949 &CC->user, roomname);
950 c = getroom(&QRscratch, augmented_roomname);
952 strcpy(roomname, augmented_roomname);
955 /* If the room exists, check security/access */
957 /* See if there is an existing user/room relationship */
958 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
960 /* normal clients have to pass through security */
964 if ((zapped_ok) && (ra & UA_ZAPPED)) {
969 /* Fail here if no such room */
971 strcpy(returned_roomname, "");
974 strcpy(returned_roomname, QRscratch.QRname);
981 * Implements the STATUS command (sort of)
984 void imap_status(int num_parms, char *parms[])
987 char roomname[ROOMNAMELEN];
989 char savedroom[ROOMNAMELEN];
992 ret = imap_grabroom(roomname, parms[2], 0);
995 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1001 * usergoto() formally takes us to the desired room, happily returning
1002 * the number of messages and number of new messages. (If another
1003 * folder is selected, save its name so we can return there!!!!!)
1005 if (IMAP->selected) {
1006 strcpy(savedroom, CC->room.QRname);
1008 usergoto(roomname, 0, 0, &msgs, &new);
1011 * Tell the client what it wants to know. In fact, tell it *more* than
1012 * it wants to know. We happily IGnore the supplied status data item
1013 * names and simply spew all possible data items. It's far easier to
1014 * code and probably saves us some processing time too.
1016 imap_mailboxname(buf, sizeof buf, &CC->room);
1017 cprintf("* STATUS ");
1019 cprintf(" (MESSAGES %d ", msgs);
1020 cprintf("RECENT %d ", new); /* Initially, new==recent */
1021 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1022 cprintf("UNSEEN %d)\r\n", new);
1025 * If another folder is selected, go back to that room so we can resume
1026 * our happy day without violent explosions.
1028 if (IMAP->selected) {
1029 usergoto(savedroom, 0, 0, &msgs, &new);
1033 * Oooh, look, we're done!
1035 cprintf("%s OK STATUS completed\r\n", parms[0]);
1041 * Implements the SUBSCRIBE command
1044 void imap_subscribe(int num_parms, char *parms[])
1047 char roomname[ROOMNAMELEN];
1048 char savedroom[ROOMNAMELEN];
1051 ret = imap_grabroom(roomname, parms[2], 1);
1054 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1062 * usergoto() formally takes us to the desired room, which has the side
1063 * effect of marking the room as not-zapped ... exactly the effect
1064 * we're looking for.
1066 if (IMAP->selected) {
1067 strcpy(savedroom, CC->room.QRname);
1069 usergoto(roomname, 0, 0, &msgs, &new);
1072 * If another folder is selected, go back to that room so we can resume
1073 * our happy day without violent explosions.
1075 if (IMAP->selected) {
1076 usergoto(savedroom, 0, 0, &msgs, &new);
1079 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1084 * Implements the UNSUBSCRIBE command
1087 void imap_unsubscribe(int num_parms, char *parms[])
1090 char roomname[ROOMNAMELEN];
1091 char savedroom[ROOMNAMELEN];
1094 ret = imap_grabroom(roomname, parms[2], 0);
1097 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1103 * usergoto() formally takes us to the desired room.
1105 if (IMAP->selected) {
1106 strcpy(savedroom, CC->room.QRname);
1108 usergoto(roomname, 0, 0, &msgs, &new);
1111 * Now make the API call to zap the room
1113 if (CtdlForgetThisRoom() == 0) {
1114 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1117 ("%s NO You may not unsubscribe from this folder.\r\n",
1122 * If another folder is selected, go back to that room so we can resume
1123 * our happy day without violent explosions.
1125 if (IMAP->selected) {
1126 usergoto(savedroom, 0, 0, &msgs, &new);
1133 * Implements the DELETE command
1136 void imap_delete(int num_parms, char *parms[])
1139 char roomname[ROOMNAMELEN];
1140 char savedroom[ROOMNAMELEN];
1143 ret = imap_grabroom(roomname, parms[2], 0);
1145 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1151 * usergoto() formally takes us to the desired room, happily returning
1152 * the number of messages and number of new messages. (If another
1153 * folder is selected, save its name so we can return there!!!!!)
1155 if (IMAP->selected) {
1156 strcpy(savedroom, CC->room.QRname);
1158 usergoto(roomname, 0, 0, &msgs, &new);
1161 * Now delete the room.
1163 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1164 delete_room(&CC->room);
1165 cprintf("%s OK DELETE completed\r\n", parms[0]);
1167 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1171 * If another folder is selected, go back to that room so we can resume
1172 * our happy day without violent explosions.
1174 if (IMAP->selected) {
1175 usergoto(savedroom, 0, 0, &msgs, &new);
1181 * Back end function for imap_rename()
1183 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1185 char foldername[SIZ];
1186 char newfoldername[SIZ];
1187 char newroomname[ROOMNAMELEN];
1189 struct irl *irlp = NULL; /* scratch pointer */
1190 struct irlparms *irlparms;
1192 irlparms = (struct irlparms *) data;
1193 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1195 /* Rename subfolders */
1196 if ((!strncasecmp(foldername, irlparms->oldname,
1197 strlen(irlparms->oldname))
1198 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1200 sprintf(newfoldername, "%s/%s",
1202 &foldername[strlen(irlparms->oldname) + 1]
1205 newfloor = imap_roomname(newroomname,
1207 newfoldername) & 0xFF;
1209 irlp = (struct irl *) malloc(sizeof(struct irl));
1210 strcpy(irlp->irl_newroom, newroomname);
1211 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1212 irlp->irl_newfloor = newfloor;
1213 irlp->next = *(irlparms->irl);
1214 *(irlparms->irl) = irlp;
1220 * Implements the RENAME command
1223 void imap_rename(int num_parms, char *parms[])
1225 char old_room[ROOMNAMELEN];
1226 char new_room[ROOMNAMELEN];
1230 struct irl *irl = NULL; /* the list */
1231 struct irl *irlp = NULL; /* scratch pointer */
1232 struct irlparms irlparms;
1234 if (strchr(parms[3], '\\') != NULL) {
1235 cprintf("%s NO Invalid character in folder name\r\n",
1240 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1241 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1242 new_floor = (newr & 0xFF);
1244 r = CtdlRenameRoom(old_room, new_room, new_floor);
1246 if (r == crr_room_not_found) {
1247 cprintf("%s NO Could not locate this folder\r\n",
1251 if (r == crr_already_exists) {
1252 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1255 if (r == crr_noneditable) {
1256 cprintf("%s This folder is not editable.\r\n", parms[0]);
1259 if (r == crr_invalid_floor) {
1260 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1263 if (r == crr_access_denied) {
1264 cprintf("%s You do not have permission to edit "
1265 "this folder.\r\n", parms[0]);
1269 cprintf("%s NO Rename failed - undefined error %d\r\n",
1275 /* If this is the INBOX, then RFC2060 says we have to just move the
1276 * contents. In a Citadel environment it's easier to rename the room
1277 * (already did that) and create a new inbox.
1279 if (!strcasecmp(parms[2], "INBOX")) {
1280 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1283 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1285 irlparms.oldname = parms[2];
1286 irlparms.newname = parms[3];
1287 irlparms.irl = &irl;
1288 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1290 /* ... and now rename them. */
1291 while (irl != NULL) {
1292 r = CtdlRenameRoom(irl->irl_oldroom,
1296 /* FIXME handle error returns better */
1297 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n",
1306 cprintf("%s OK RENAME completed\r\n", parms[0]);
1313 * Main command loop for IMAP sessions.
1315 void imap_command_loop(void)
1321 CC->lastcmd = time(NULL);
1322 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1324 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1325 lprintf(CTDL_ERR, "IMAP socket is broken. Ending session.\r\n");
1330 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1331 while (strlen(cmdbuf) < 5)
1332 strcat(cmdbuf, " ");
1334 /* strip off l/t whitespace and CRLF */
1335 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1336 cmdbuf[strlen(cmdbuf) - 1] = 0;
1337 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1338 cmdbuf[strlen(cmdbuf) - 1] = 0;
1341 /* If we're in the middle of a multi-line command, handle that */
1342 if (IMAP->authstate == imap_as_expecting_username) {
1343 imap_auth_login_user(cmdbuf);
1346 if (IMAP->authstate == imap_as_expecting_password) {
1347 imap_auth_login_pass(cmdbuf);
1351 /* Ok, at this point we're in normal command mode. The first thing
1352 * we do is print any incoming pages (yeah! we really do!)
1354 imap_print_instant_messages();
1357 * Before processing the command that was just entered... if we happen
1358 * to have a folder selected, we'd like to rescan that folder for new
1359 * messages, and for deletions/changes of existing messages. This
1360 * could probably be optimized somehow, but IMAP sucks...
1362 if (IMAP->selected) {
1363 imap_rescan_msgids();
1366 /* Now for the command set. */
1368 /* Grab the tag, command, and parameters. Check syntax. */
1369 num_parms = imap_parameterize(parms, cmdbuf);
1370 if (num_parms < 2) {
1371 cprintf("BAD syntax error\r\n");
1374 /* The commands below may be executed in any state */
1376 else if ((!strcasecmp(parms[1], "NOOP"))
1377 || (!strcasecmp(parms[1], "CHECK"))) {
1378 cprintf("%s OK This command successfully did nothing.\r\n",
1382 else if (!strcasecmp(parms[1], "LOGOUT")) {
1383 if (IMAP->selected) {
1384 imap_do_expunge(); /* yes, we auto-expunge */
1386 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1387 cprintf("%s OK thank you for using Citadel IMAP\r\n",
1393 else if (!strcasecmp(parms[1], "LOGIN")) {
1394 imap_login(num_parms, parms);
1397 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1398 imap_authenticate(num_parms, parms);
1401 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1402 imap_capability(num_parms, parms);
1405 else if (!strcasecmp(parms[1], "STARTTLS")) {
1406 imap_starttls(num_parms, parms);
1409 else if (!CC->logged_in) {
1410 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1413 /* The commans below require a logged-in state */
1415 else if (!strcasecmp(parms[1], "SELECT")) {
1416 imap_select(num_parms, parms);
1419 else if (!strcasecmp(parms[1], "EXAMINE")) {
1420 imap_select(num_parms, parms);
1423 else if (!strcasecmp(parms[1], "LSUB")) {
1424 imap_lsub(num_parms, parms);
1427 else if (!strcasecmp(parms[1], "LIST")) {
1428 imap_list(num_parms, parms);
1431 else if (!strcasecmp(parms[1], "CREATE")) {
1432 imap_create(num_parms, parms);
1435 else if (!strcasecmp(parms[1], "DELETE")) {
1436 imap_delete(num_parms, parms);
1439 else if (!strcasecmp(parms[1], "RENAME")) {
1440 imap_rename(num_parms, parms);
1443 else if (!strcasecmp(parms[1], "STATUS")) {
1444 imap_status(num_parms, parms);
1447 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1448 imap_subscribe(num_parms, parms);
1451 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1452 imap_unsubscribe(num_parms, parms);
1455 else if (!strcasecmp(parms[1], "APPEND")) {
1456 imap_append(num_parms, parms);
1459 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1460 imap_namespace(num_parms, parms);
1463 else if (IMAP->selected == 0) {
1464 cprintf("%s BAD no folder selected\r\n", parms[0]);
1467 /* The commands below require the SELECT state on a mailbox */
1469 else if (!strcasecmp(parms[1], "FETCH")) {
1470 imap_fetch(num_parms, parms);
1473 else if ((!strcasecmp(parms[1], "UID"))
1474 && (!strcasecmp(parms[2], "FETCH"))) {
1475 imap_uidfetch(num_parms, parms);
1478 else if (!strcasecmp(parms[1], "SEARCH")) {
1479 imap_search(num_parms, parms);
1482 else if ((!strcasecmp(parms[1], "UID"))
1483 && (!strcasecmp(parms[2], "SEARCH"))) {
1484 imap_uidsearch(num_parms, parms);
1487 else if (!strcasecmp(parms[1], "STORE")) {
1488 imap_store(num_parms, parms);
1491 else if ((!strcasecmp(parms[1], "UID"))
1492 && (!strcasecmp(parms[2], "STORE"))) {
1493 imap_uidstore(num_parms, parms);
1496 else if (!strcasecmp(parms[1], "COPY")) {
1497 imap_copy(num_parms, parms);
1500 else if ((!strcasecmp(parms[1], "UID"))
1501 && (!strcasecmp(parms[2], "COPY"))) {
1502 imap_uidcopy(num_parms, parms);
1505 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1506 imap_expunge(num_parms, parms);
1509 else if (!strcasecmp(parms[1], "CLOSE")) {
1510 imap_close(num_parms, parms);
1513 /* End of commands. If we get here, the command is either invalid
1518 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1521 /* If the client transmitted a message we can free it now */
1522 imap_free_transmitted_message();
1528 * This function is called to register the IMAP extension with Citadel.
1530 char *serv_imap_init(void)
1532 CtdlRegisterServiceHook(config.c_imap_port,
1533 NULL, imap_greeting, imap_command_loop, NULL);
1535 CtdlRegisterServiceHook(config.c_imaps_port,
1536 NULL, imaps_greeting, imap_command_loop, NULL);
1538 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);