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)
226 struct cdbdata *cdbfr;
228 if (IMAP->selected == 0) {
230 "imap_load_msgids() can't run; no room selected\n");
234 imap_free_msgids(); /* If there was already a map, free it */
236 /* Load the message list */
237 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
239 IMAP->msgids = malloc(cdbfr->len);
240 memcpy(IMAP->msgids, cdbfr->ptr, cdbfr->len);
241 IMAP->num_msgs = cdbfr->len / sizeof(long);
242 IMAP->num_alloc = cdbfr->len / sizeof(long);
246 if (IMAP->num_msgs) {
247 IMAP->flags = malloc(IMAP->num_alloc * sizeof(long));
248 memset(IMAP->flags, 0, (IMAP->num_alloc * sizeof(long)) );
251 imap_set_seen_flags(0);
256 * Re-scan the selected room (folder) and see if it's been changed at all
258 void imap_rescan_msgids(void)
261 int original_num_msgs = 0;
262 long original_highest = 0L;
264 int message_still_exists;
265 struct cdbdata *cdbfr;
266 long *msglist = NULL;
270 if (IMAP->selected == 0) {
272 "imap_load_msgids() can't run; no room selected\n");
277 * Check to see if the room's contents have changed.
278 * If not, we can avoid this rescan.
280 getroom(&CC->room, CC->room.QRname);
281 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
285 /* Load the *current* message list from disk, so we can compare it
286 * to what we have in memory.
288 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
290 msglist = malloc(cdbfr->len);
291 if (msglist == NULL) {
292 lprintf(CTDL_CRIT, "malloc() failed\n");
295 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
296 num_msgs = cdbfr->len / sizeof(long);
303 * Check to see if any of the messages we know about have been expunged
305 if (IMAP->num_msgs > 0) {
307 for (i = 0; i < IMAP->num_msgs; ++i) {
309 message_still_exists = 0;
311 for (j = jstart; j < num_msgs; ++j) {
312 if (msglist[j] == IMAP->msgids[i]) {
313 message_still_exists = 1;
320 if (message_still_exists == 0) {
321 cprintf("* %d EXPUNGE\r\n", i + 1);
323 /* Here's some nice stupid nonsense. When a
324 * message is expunged, we have to slide all
325 * the existing messages up in the message
329 memcpy(&IMAP->msgids[i],
330 &IMAP->msgids[i + 1],
332 (IMAP->num_msgs - i)));
333 memcpy(&IMAP->flags[i],
336 (IMAP->num_msgs - i)));
345 * Remember how many messages were here before we re-scanned.
347 original_num_msgs = IMAP->num_msgs;
348 if (IMAP->num_msgs > 0) {
349 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
351 original_highest = 0L;
355 * Now peruse the room for *new* messages only.
358 for (j = 0; j < num_msgs; ++j) {
359 if (msglist[j] > original_highest) {
360 imap_add_single_msgid(msglist[j], NULL);
364 imap_set_seen_flags(original_num_msgs);
367 * If new messages have arrived, tell the client about them.
369 if (IMAP->num_msgs > original_num_msgs) {
371 for (j = 0; j < num_msgs; ++j) {
372 if (IMAP->flags[j] & IMAP_RECENT) {
377 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
378 cprintf("* %d RECENT\r\n", num_recent);
384 IMAP->last_mtime = CC->room.QRmtime;
394 * This cleanup function blows away the temporary memory and files used by
397 void imap_cleanup_function(void)
400 /* Don't do this stuff if this is not a IMAP session! */
401 if (CC->h_command_function != imap_command_loop)
404 /* If there is a mailbox selected, auto-expunge it. */
405 if (IMAP->selected) {
409 lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
411 imap_free_transmitted_message();
413 if (IMAP->cached_rfc822_data != NULL) {
414 free(IMAP->cached_rfc822_data);
415 IMAP->cached_rfc822_data = NULL;
416 IMAP->cached_rfc822_msgnum = (-1);
417 IMAP->cached_rfc822_withbody = 0;
420 if (IMAP->cached_body != NULL) {
421 free(IMAP->cached_body);
422 IMAP->cached_body = NULL;
423 IMAP->cached_body_len = 0;
424 IMAP->cached_bodymsgnum = (-1);
428 lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
433 * Does the actual work of the CAPABILITY command (because we need to
434 * output this stuff in other places as well)
436 void imap_output_capability_string(void) {
437 cprintf("CAPABILITY IMAP4REV1 NAMESPACE ID AUTH=LOGIN");
439 if (!CC->redirect_ssl) cprintf(" STARTTLS");
444 * implements the CAPABILITY command
446 void imap_capability(int num_parms, char *parms[])
449 imap_output_capability_string();
451 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
457 * Implements the ID command (specified by RFC2971)
459 * We ignore the client-supplied information, and output a NIL response.
460 * Although this is technically a valid implementation of the extension, it
461 * is quite useless. It exists only so that we may see which clients are
462 * making use of this extension.
465 void imap_id(int num_parms, char *parms[])
467 cprintf("* ID NIL\r\n");
468 cprintf("%s OK ID completed\r\n", parms[0]);
474 * Here's where our IMAP session begins its happy day.
476 void imap_greeting(void)
479 strcpy(CC->cs_clientname, "IMAP session");
480 IMAP = malloc(sizeof (struct citimap));
481 memset(IMAP, 0, sizeof(struct citimap));
482 IMAP->authstate = imap_as_normal;
483 IMAP->cached_rfc822_data = NULL;
484 IMAP->cached_rfc822_msgnum = (-1);
485 IMAP->cached_rfc822_withbody = 0;
488 imap_output_capability_string();
489 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
493 * IMAPS is just like IMAP, except it goes crypto right away.
496 void imaps_greeting(void) {
497 CtdlStartTLS(NULL, NULL, NULL);
504 * implements the LOGIN command (ordinary username/password login)
506 void imap_login(int num_parms, char *parms[])
508 if (num_parms != 4) {
509 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
513 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
514 if (CtdlTryPassword(parms[3]) == pass_ok) {
515 cprintf("%s OK [", parms[0]);
516 imap_output_capability_string();
517 cprintf("] Hello, %s\r\n", CC->user.fullname);
522 cprintf("%s BAD Login incorrect\r\n", parms[0]);
527 * Implements the AUTHENTICATE command
529 void imap_authenticate(int num_parms, char *parms[])
533 if (num_parms != 3) {
534 cprintf("%s BAD incorrect number of parameters\r\n",
540 cprintf("%s BAD Already logged in.\r\n", parms[0]);
544 if (!strcasecmp(parms[2], "LOGIN")) {
545 CtdlEncodeBase64(buf, "Username:", 9);
546 cprintf("+ %s\r\n", buf);
547 IMAP->authstate = imap_as_expecting_username;
548 strcpy(IMAP->authseq, parms[0]);
553 cprintf("%s NO AUTHENTICATE %s failed\r\n",
558 void imap_auth_login_user(char *cmd)
562 CtdlDecodeBase64(buf, cmd, SIZ);
563 CtdlLoginExistingUser(buf);
564 CtdlEncodeBase64(buf, "Password:", 9);
565 cprintf("+ %s\r\n", buf);
566 IMAP->authstate = imap_as_expecting_password;
570 void imap_auth_login_pass(char *cmd)
574 CtdlDecodeBase64(buf, cmd, SIZ);
575 if (CtdlTryPassword(buf) == pass_ok) {
576 cprintf("%s OK authentication succeeded\r\n",
579 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
581 IMAP->authstate = imap_as_normal;
587 * implements the STARTTLS command (Citadel API version)
590 void imap_starttls(int num_parms, char *parms[])
592 char ok_response[SIZ];
593 char nosup_response[SIZ];
594 char error_response[SIZ];
597 "%s OK begin TLS negotiation now\r\n",
599 sprintf(nosup_response,
600 "%s NO TLS not supported here\r\n",
602 sprintf(error_response,
603 "%s BAD Internal error\r\n",
605 CtdlStartTLS(ok_response, nosup_response, error_response);
611 * implements the SELECT command
613 void imap_select(int num_parms, char *parms[])
616 char augmented_roomname[ROOMNAMELEN];
620 struct ctdlroom QRscratch;
626 /* Convert the supplied folder name to a roomname */
627 i = imap_roomname(towhere, sizeof towhere, parms[2]);
629 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
633 floornum = (i & 0x00ff);
634 roomflags = (i & 0xff00);
636 /* First try a regular match */
637 c = getroom(&QRscratch, towhere);
639 /* Then try a mailbox name match */
641 MailboxName(augmented_roomname, sizeof augmented_roomname,
643 c = getroom(&QRscratch, augmented_roomname);
645 strcpy(towhere, augmented_roomname);
648 /* If the room exists, check security/access */
650 /* See if there is an existing user/room relationship */
651 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
653 /* normal clients have to pass through security */
659 /* Fail here if no such room */
661 cprintf("%s NO ... no such room, or access denied\r\n",
666 /* If we already had some other folder selected, auto-expunge it */
670 * usergoto() formally takes us to the desired room, happily returning
671 * the number of messages and number of new messages.
673 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
674 usergoto(NULL, 0, 0, &msgs, &new);
677 if (!strcasecmp(parms[1], "EXAMINE")) {
684 IMAP->last_mtime = CC->room.QRmtime;
686 cprintf("* %d EXISTS\r\n", msgs);
687 cprintf("* %d RECENT\r\n", new);
689 cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
690 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
692 /* Note that \Deleted is a valid flag, but not a permanent flag,
693 * because we don't maintain its state across sessions. Citadel
694 * automatically expunges mailboxes when they are de-selected.
696 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
697 cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] "
698 "permanent flags\r\n");
700 cprintf("%s OK [%s] %s completed\r\n",
702 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
708 * Does the real work for expunge. FIXME do this with the new bulk API
710 int imap_do_expunge(void)
713 int num_expunged = 0;
715 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
716 if (IMAP->selected == 0) {
720 if (IMAP->num_msgs > 0)
721 for (i = 0; i < IMAP->num_msgs; ++i) {
722 if (IMAP->flags[i] & IMAP_DELETED) {
723 CtdlDeleteMessages(CC->room.QRname,
724 IMAP->msgids[i], "", 1);
729 if (num_expunged > 0) {
730 imap_rescan_msgids();
733 lprintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n",
734 num_expunged, CC->room.QRname);
735 return (num_expunged);
740 * implements the EXPUNGE command syntax
742 void imap_expunge(int num_parms, char *parms[])
744 int num_expunged = 0;
746 num_expunged = imap_do_expunge();
747 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
752 * implements the CLOSE command
754 void imap_close(int num_parms, char *parms[])
757 /* Yes, we always expunge on close. */
758 if (IMAP->selected) {
765 cprintf("%s OK CLOSE completed\r\n", parms[0]);
770 * Implements the NAMESPACE command.
772 void imap_namespace(int num_parms, char *parms[])
779 cprintf("* NAMESPACE ");
781 /* All personal folders are subordinate to INBOX. */
782 cprintf("((\"INBOX/\" \"/\")) ");
784 /* Other users' folders ... coming soon! FIXME */
787 /* Show all floors as shared namespaces. Neato! */
789 for (i = 0; i < MAXFLOORS; ++i) {
791 if (fl->f_flags & F_INUSE) {
792 if (floors > 0) cprintf(" ");
794 sprintf(buf, "%s/", fl->f_name);
802 /* Wind it up with a newline and a completion message. */
804 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
810 * Used by LIST and LSUB to show the floors in the listing
812 void imap_list_floors(char *cmd, char *pattern)
817 for (i = 0; i < MAXFLOORS; ++i) {
819 if (fl->f_flags & F_INUSE) {
820 if (imap_mailbox_matches_pattern
821 (pattern, fl->f_name)) {
822 cprintf("* %s (\\NoSelect) \"/\" ", cmd);
823 imap_strout(fl->f_name);
833 * Back end for imap_lsub()
835 * IMAP "subscribed folder" is equivocated to Citadel "known rooms." This
836 * may or may not be the desired behavior in the future.
838 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data)
844 pattern = (char *) data;
846 /* Only list rooms to which the user has access!! */
847 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
849 imap_mailboxname(buf, sizeof buf, qrbuf);
850 if (imap_mailbox_matches_pattern(pattern, buf)) {
851 cprintf("* LSUB () \"/\" ");
860 * Implements the LSUB command
862 void imap_lsub(int num_parms, char *parms[])
866 cprintf("%s BAD arguments invalid\r\n", parms[0]);
869 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
871 if (strlen(parms[3]) == 0) {
872 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
876 imap_list_floors("LSUB", pattern);
877 ForEachRoom(imap_lsub_listroom, pattern);
880 cprintf("%s OK LSUB completed\r\n", parms[0]);
886 * Back end for imap_list()
888 void imap_list_listroom(struct ctdlroom *qrbuf, void *data)
894 pattern = (char *) data;
896 /* Only list rooms to which the user has access!! */
897 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
899 || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
900 imap_mailboxname(buf, sizeof buf, qrbuf);
901 if (imap_mailbox_matches_pattern(pattern, buf)) {
902 cprintf("* LIST () \"/\" ");
911 * Implements the LIST command
913 void imap_list(int num_parms, char *parms[])
917 cprintf("%s BAD arguments invalid\r\n", parms[0]);
920 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
922 if (strlen(parms[3]) == 0) {
923 cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
927 imap_list_floors("LIST", pattern);
928 ForEachRoom(imap_list_listroom, pattern);
931 cprintf("%s OK LIST completed\r\n", parms[0]);
937 * Implements the CREATE command
940 void imap_create(int num_parms, char *parms[])
943 char roomname[ROOMNAMELEN];
949 if (strchr(parms[2], '\\') != NULL) {
950 cprintf("%s NO Invalid character in folder name\r\n",
952 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
956 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
958 cprintf("%s NO Invalid mailbox name or location\r\n",
960 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
963 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
964 flags = (ret & 0xff00); /* upper 8 bits = flags */
966 if (flags & IR_MAILBOX) {
967 if (strncasecmp(parms[2], "INBOX/", 6)) {
968 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
969 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
974 if (flags & IR_MAILBOX) {
975 newroomtype = 4; /* private mailbox */
976 newroomview = VIEW_MAILBOX;
978 newroomtype = 0; /* public folder */
979 newroomview = VIEW_BBS;
982 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
983 roomname, floornum, newroomtype);
985 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
988 ("%s NO Mailbox already exists, or create failed\r\n",
991 cprintf("%s OK CREATE completed\r\n", parms[0]);
993 lprintf(CTDL_DEBUG, "imap_create() completed\n");
998 * Locate a room by its IMAP folder name, and check access to it.
999 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
1001 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
1004 char augmented_roomname[ROOMNAMELEN];
1005 char roomname[ROOMNAMELEN];
1007 struct ctdlroom QRscratch;
1011 ret = imap_roomname(roomname, sizeof roomname, foldername);
1016 /* First try a regular match */
1017 c = getroom(&QRscratch, roomname);
1019 /* Then try a mailbox name match */
1021 MailboxName(augmented_roomname, sizeof augmented_roomname,
1022 &CC->user, roomname);
1023 c = getroom(&QRscratch, augmented_roomname);
1025 strcpy(roomname, augmented_roomname);
1028 /* If the room exists, check security/access */
1030 /* See if there is an existing user/room relationship */
1031 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1033 /* normal clients have to pass through security */
1034 if (ra & UA_KNOWN) {
1037 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1042 /* Fail here if no such room */
1044 strcpy(returned_roomname, "");
1047 strcpy(returned_roomname, QRscratch.QRname);
1054 * Implements the STATUS command (sort of)
1057 void imap_status(int num_parms, char *parms[])
1060 char roomname[ROOMNAMELEN];
1062 char savedroom[ROOMNAMELEN];
1065 ret = imap_grabroom(roomname, parms[2], 0);
1068 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1074 * usergoto() formally takes us to the desired room, happily returning
1075 * the number of messages and number of new messages. (If another
1076 * folder is selected, save its name so we can return there!!!!!)
1078 if (IMAP->selected) {
1079 strcpy(savedroom, CC->room.QRname);
1081 usergoto(roomname, 0, 0, &msgs, &new);
1084 * Tell the client what it wants to know. In fact, tell it *more* than
1085 * it wants to know. We happily IGnore the supplied status data item
1086 * names and simply spew all possible data items. It's far easier to
1087 * code and probably saves us some processing time too.
1089 imap_mailboxname(buf, sizeof buf, &CC->room);
1090 cprintf("* STATUS ");
1092 cprintf(" (MESSAGES %d ", msgs);
1093 cprintf("RECENT %d ", new); /* Initially, new==recent */
1094 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1095 cprintf("UNSEEN %d)\r\n", new);
1098 * If another folder is selected, go back to that room so we can resume
1099 * our happy day without violent explosions.
1101 if (IMAP->selected) {
1102 usergoto(savedroom, 0, 0, &msgs, &new);
1106 * Oooh, look, we're done!
1108 cprintf("%s OK STATUS completed\r\n", parms[0]);
1114 * Implements the SUBSCRIBE command
1117 void imap_subscribe(int num_parms, char *parms[])
1120 char roomname[ROOMNAMELEN];
1121 char savedroom[ROOMNAMELEN];
1124 ret = imap_grabroom(roomname, parms[2], 1);
1127 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1135 * usergoto() formally takes us to the desired room, which has the side
1136 * effect of marking the room as not-zapped ... exactly the effect
1137 * we're looking for.
1139 if (IMAP->selected) {
1140 strcpy(savedroom, CC->room.QRname);
1142 usergoto(roomname, 0, 0, &msgs, &new);
1145 * If another folder is selected, go back to that room so we can resume
1146 * our happy day without violent explosions.
1148 if (IMAP->selected) {
1149 usergoto(savedroom, 0, 0, &msgs, &new);
1152 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1157 * Implements the UNSUBSCRIBE command
1160 void imap_unsubscribe(int num_parms, char *parms[])
1163 char roomname[ROOMNAMELEN];
1164 char savedroom[ROOMNAMELEN];
1167 ret = imap_grabroom(roomname, parms[2], 0);
1170 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1176 * usergoto() formally takes us to the desired room.
1178 if (IMAP->selected) {
1179 strcpy(savedroom, CC->room.QRname);
1181 usergoto(roomname, 0, 0, &msgs, &new);
1184 * Now make the API call to zap the room
1186 if (CtdlForgetThisRoom() == 0) {
1187 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1190 ("%s NO You may not unsubscribe from this folder.\r\n",
1195 * If another folder is selected, go back to that room so we can resume
1196 * our happy day without violent explosions.
1198 if (IMAP->selected) {
1199 usergoto(savedroom, 0, 0, &msgs, &new);
1206 * Implements the DELETE command
1209 void imap_delete(int num_parms, char *parms[])
1212 char roomname[ROOMNAMELEN];
1213 char savedroom[ROOMNAMELEN];
1216 ret = imap_grabroom(roomname, parms[2], 1);
1218 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1224 * usergoto() formally takes us to the desired room, happily returning
1225 * the number of messages and number of new messages. (If another
1226 * folder is selected, save its name so we can return there!!!!!)
1228 if (IMAP->selected) {
1229 strcpy(savedroom, CC->room.QRname);
1231 usergoto(roomname, 0, 0, &msgs, &new);
1234 * Now delete the room.
1236 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1237 schedule_room_for_deletion(&CC->room);
1238 cprintf("%s OK DELETE completed\r\n", parms[0]);
1240 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1244 * If another folder is selected, go back to that room so we can resume
1245 * our happy day without violent explosions.
1247 if (IMAP->selected) {
1248 usergoto(savedroom, 0, 0, &msgs, &new);
1254 * Back end function for imap_rename()
1256 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1258 char foldername[SIZ];
1259 char newfoldername[SIZ];
1260 char newroomname[ROOMNAMELEN];
1262 struct irl *irlp = NULL; /* scratch pointer */
1263 struct irlparms *irlparms;
1265 irlparms = (struct irlparms *) data;
1266 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1268 /* Rename subfolders */
1269 if ((!strncasecmp(foldername, irlparms->oldname,
1270 strlen(irlparms->oldname))
1271 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1273 sprintf(newfoldername, "%s/%s",
1275 &foldername[strlen(irlparms->oldname) + 1]
1278 newfloor = imap_roomname(newroomname,
1280 newfoldername) & 0xFF;
1282 irlp = (struct irl *) malloc(sizeof(struct irl));
1283 strcpy(irlp->irl_newroom, newroomname);
1284 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1285 irlp->irl_newfloor = newfloor;
1286 irlp->next = *(irlparms->irl);
1287 *(irlparms->irl) = irlp;
1293 * Implements the RENAME command
1296 void imap_rename(int num_parms, char *parms[])
1298 char old_room[ROOMNAMELEN];
1299 char new_room[ROOMNAMELEN];
1303 struct irl *irl = NULL; /* the list */
1304 struct irl *irlp = NULL; /* scratch pointer */
1305 struct irlparms irlparms;
1307 if (strchr(parms[3], '\\') != NULL) {
1308 cprintf("%s NO Invalid character in folder name\r\n",
1313 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1314 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1315 new_floor = (newr & 0xFF);
1317 r = CtdlRenameRoom(old_room, new_room, new_floor);
1319 if (r == crr_room_not_found) {
1320 cprintf("%s NO Could not locate this folder\r\n",
1324 if (r == crr_already_exists) {
1325 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1328 if (r == crr_noneditable) {
1329 cprintf("%s This folder is not editable.\r\n", parms[0]);
1332 if (r == crr_invalid_floor) {
1333 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1336 if (r == crr_access_denied) {
1337 cprintf("%s You do not have permission to edit "
1338 "this folder.\r\n", parms[0]);
1342 cprintf("%s NO Rename failed - undefined error %d\r\n",
1348 /* If this is the INBOX, then RFC2060 says we have to just move the
1349 * contents. In a Citadel environment it's easier to rename the room
1350 * (already did that) and create a new inbox.
1352 if (!strcasecmp(parms[2], "INBOX")) {
1353 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1356 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1358 irlparms.oldname = parms[2];
1359 irlparms.newname = parms[3];
1360 irlparms.irl = &irl;
1361 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1363 /* ... and now rename them. */
1364 while (irl != NULL) {
1365 r = CtdlRenameRoom(irl->irl_oldroom,
1369 /* FIXME handle error returns better */
1370 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n",
1379 cprintf("%s OK RENAME completed\r\n", parms[0]);
1386 * Main command loop for IMAP sessions.
1388 void imap_command_loop(void)
1394 CC->lastcmd = time(NULL);
1395 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1397 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1398 lprintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1403 if (IMAP->authstate == imap_as_expecting_password) {
1404 lprintf(CTDL_INFO, "IMAP: <password>\n");
1406 else if (bmstrcasestr(cmdbuf, " LOGIN ")) {
1407 lprintf(CTDL_INFO, "IMAP: LOGIN...\n");
1410 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1413 while (strlen(cmdbuf) < 5)
1414 strcat(cmdbuf, " ");
1416 /* strip off l/t whitespace and CRLF */
1417 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1418 cmdbuf[strlen(cmdbuf) - 1] = 0;
1419 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1420 cmdbuf[strlen(cmdbuf) - 1] = 0;
1423 /* If we're in the middle of a multi-line command, handle that */
1424 if (IMAP->authstate == imap_as_expecting_username) {
1425 imap_auth_login_user(cmdbuf);
1428 if (IMAP->authstate == imap_as_expecting_password) {
1429 imap_auth_login_pass(cmdbuf);
1433 /* Ok, at this point we're in normal command mode. The first thing
1434 * we do is print any incoming pages (yeah! we really do!)
1436 imap_print_instant_messages();
1439 * Before processing the command that was just entered... if we happen
1440 * to have a folder selected, we'd like to rescan that folder for new
1441 * messages, and for deletions/changes of existing messages. This
1442 * could probably be optimized somehow, but IMAP sucks...
1444 if (IMAP->selected) {
1445 imap_rescan_msgids();
1448 /* Now for the command set. */
1450 /* Grab the tag, command, and parameters. Check syntax. */
1451 num_parms = imap_parameterize(parms, cmdbuf);
1452 if (num_parms < 2) {
1453 cprintf("BAD syntax error\r\n");
1456 /* The commands below may be executed in any state */
1458 else if ((!strcasecmp(parms[1], "NOOP"))
1459 || (!strcasecmp(parms[1], "CHECK"))) {
1460 cprintf("%s OK This command successfully did nothing.\r\n",
1464 else if (!strcasecmp(parms[1], "ID")) {
1465 imap_id(num_parms, parms);
1469 else if (!strcasecmp(parms[1], "LOGOUT")) {
1470 if (IMAP->selected) {
1471 imap_do_expunge(); /* yes, we auto-expunge */
1473 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1474 cprintf("%s OK thank you for using Citadel IMAP\r\n",
1480 else if (!strcasecmp(parms[1], "LOGIN")) {
1481 imap_login(num_parms, parms);
1484 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1485 imap_authenticate(num_parms, parms);
1488 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1489 imap_capability(num_parms, parms);
1492 else if (!strcasecmp(parms[1], "STARTTLS")) {
1493 imap_starttls(num_parms, parms);
1496 else if (!CC->logged_in) {
1497 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1500 /* The commans below require a logged-in state */
1502 else if (!strcasecmp(parms[1], "SELECT")) {
1503 imap_select(num_parms, parms);
1506 else if (!strcasecmp(parms[1], "EXAMINE")) {
1507 imap_select(num_parms, parms);
1510 else if (!strcasecmp(parms[1], "LSUB")) {
1511 imap_lsub(num_parms, parms);
1514 else if (!strcasecmp(parms[1], "LIST")) {
1515 imap_list(num_parms, parms);
1518 else if (!strcasecmp(parms[1], "CREATE")) {
1519 imap_create(num_parms, parms);
1522 else if (!strcasecmp(parms[1], "DELETE")) {
1523 imap_delete(num_parms, parms);
1526 else if (!strcasecmp(parms[1], "RENAME")) {
1527 imap_rename(num_parms, parms);
1530 else if (!strcasecmp(parms[1], "STATUS")) {
1531 imap_status(num_parms, parms);
1534 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1535 imap_subscribe(num_parms, parms);
1538 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1539 imap_unsubscribe(num_parms, parms);
1542 else if (!strcasecmp(parms[1], "APPEND")) {
1543 imap_append(num_parms, parms);
1546 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1547 imap_namespace(num_parms, parms);
1550 else if (IMAP->selected == 0) {
1551 cprintf("%s BAD no folder selected\r\n", parms[0]);
1554 /* The commands below require the SELECT state on a mailbox */
1556 else if (!strcasecmp(parms[1], "FETCH")) {
1557 imap_fetch(num_parms, parms);
1560 else if ((!strcasecmp(parms[1], "UID"))
1561 && (!strcasecmp(parms[2], "FETCH"))) {
1562 imap_uidfetch(num_parms, parms);
1565 else if (!strcasecmp(parms[1], "SEARCH")) {
1566 imap_search(num_parms, parms);
1569 else if ((!strcasecmp(parms[1], "UID"))
1570 && (!strcasecmp(parms[2], "SEARCH"))) {
1571 imap_uidsearch(num_parms, parms);
1574 else if (!strcasecmp(parms[1], "STORE")) {
1575 imap_store(num_parms, parms);
1578 else if ((!strcasecmp(parms[1], "UID"))
1579 && (!strcasecmp(parms[2], "STORE"))) {
1580 imap_uidstore(num_parms, parms);
1583 else if (!strcasecmp(parms[1], "COPY")) {
1584 imap_copy(num_parms, parms);
1587 else if ((!strcasecmp(parms[1], "UID"))
1588 && (!strcasecmp(parms[2], "COPY"))) {
1589 imap_uidcopy(num_parms, parms);
1592 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1593 imap_expunge(num_parms, parms);
1596 else if (!strcasecmp(parms[1], "CLOSE")) {
1597 imap_close(num_parms, parms);
1600 /* End of commands. If we get here, the command is either invalid
1605 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1608 /* If the client transmitted a message we can free it now */
1609 imap_free_transmitted_message();
1615 * This function is called to register the IMAP extension with Citadel.
1617 char *serv_imap_init(void)
1619 CtdlRegisterServiceHook(config.c_imap_port,
1620 NULL, imap_greeting, imap_command_loop, NULL);
1622 CtdlRegisterServiceHook(config.c_imaps_port,
1623 NULL, imaps_greeting, imap_command_loop, NULL);
1625 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);