4 * IMAP server for the Citadel system
5 * Copyright (C) 2000-2007 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_list.h"
55 #include "imap_fetch.h"
56 #include "imap_search.h"
57 #include "imap_store.h"
59 #include "imap_misc.h"
62 #include "serv_crypto.h"
65 /* imap_rename() uses this struct containing list of rooms to rename */
68 char irl_oldroom[ROOMNAMELEN];
69 char irl_newroom[ROOMNAMELEN];
73 /* Data which is passed between imap_rename() and imap_rename_backend() */
82 * If there is a message ID map in memory, free it
84 void imap_free_msgids(void)
86 if (IMAP->msgids != NULL) {
92 if (IMAP->flags != NULL) {
96 IMAP->last_mtime = (-1);
101 * If there is a transmitted message in memory, free it
103 void imap_free_transmitted_message(void)
105 if (IMAP->transmitted_message != NULL) {
106 free(IMAP->transmitted_message);
107 IMAP->transmitted_message = NULL;
108 IMAP->transmitted_length = 0;
114 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
115 * sets stored in the visit record for this user/room. Note that we have
116 * to parse each sequence set manually here, because calling the utility
117 * function is_msg_in_sequence_set() over and over again is too expensive.
119 * first_msg should be set to 0 to rescan the flags for every message in the
120 * room, or some other value if we're only interested in an incremental
123 void imap_set_seen_flags(int first_msg)
129 char setstr[64], lostr[64], histr[64];
132 if (IMAP->num_msgs < 1) return;
133 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
135 for (i = first_msg; i < IMAP->num_msgs; ++i) {
136 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
137 IMAP->flags[i] |= IMAP_RECENT;
138 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
142 * Do the "\Seen" flag.
143 * (Any message not "\Seen" is considered "\Recent".)
145 num_sets = num_tokens(vbuf.v_seen, ',');
146 for (s=0; s<num_sets; ++s) {
147 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
149 extract_token(lostr, setstr, 0, ':', sizeof lostr);
150 if (num_tokens(setstr, ':') >= 2) {
151 extract_token(histr, setstr, 1, ':', sizeof histr);
152 if (!strcmp(histr, "*")) {
153 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
157 strcpy(histr, lostr);
162 for (i = first_msg; i < IMAP->num_msgs; ++i) {
163 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
164 IMAP->flags[i] |= IMAP_SEEN;
165 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
170 /* Do the ANSWERED flag */
171 num_sets = num_tokens(vbuf.v_answered, ',');
172 for (s=0; s<num_sets; ++s) {
173 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
175 extract_token(lostr, setstr, 0, ':', sizeof lostr);
176 if (num_tokens(setstr, ':') >= 2) {
177 extract_token(histr, setstr, 1, ':', sizeof histr);
178 if (!strcmp(histr, "*")) {
179 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
183 strcpy(histr, lostr);
188 for (i = first_msg; i < IMAP->num_msgs; ++i) {
189 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
190 IMAP->flags[i] |= IMAP_ANSWERED;
200 * Back end for imap_load_msgids()
202 * Optimization: instead of calling realloc() to add each message, we
203 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
204 * allows the mapping to proceed much faster.
206 void imap_add_single_msgid(long msgnum, void *userdata)
210 if (IMAP->num_msgs > IMAP->num_alloc) {
211 IMAP->num_alloc += REALLOC_INCREMENT;
212 IMAP->msgids = realloc(IMAP->msgids,
213 (IMAP->num_alloc * sizeof(long)) );
214 IMAP->flags = realloc(IMAP->flags,
215 (IMAP->num_alloc * sizeof(long)) );
217 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
218 IMAP->flags[IMAP->num_msgs - 1] = 0;
224 * Set up a message ID map for the current room (folder)
226 void imap_load_msgids(void)
228 struct cdbdata *cdbfr;
230 if (IMAP->selected == 0) {
232 "imap_load_msgids() can't run; no room selected\n");
236 imap_free_msgids(); /* If there was already a map, free it */
238 /* Load the message list */
239 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
241 IMAP->msgids = malloc(cdbfr->len);
242 memcpy(IMAP->msgids, cdbfr->ptr, cdbfr->len);
243 IMAP->num_msgs = cdbfr->len / sizeof(long);
244 IMAP->num_alloc = cdbfr->len / sizeof(long);
248 if (IMAP->num_msgs) {
249 IMAP->flags = malloc(IMAP->num_alloc * sizeof(long));
250 memset(IMAP->flags, 0, (IMAP->num_alloc * sizeof(long)) );
253 imap_set_seen_flags(0);
258 * Re-scan the selected room (folder) and see if it's been changed at all
260 void imap_rescan_msgids(void)
263 int original_num_msgs = 0;
264 long original_highest = 0L;
266 int message_still_exists;
267 struct cdbdata *cdbfr;
268 long *msglist = NULL;
272 if (IMAP->selected == 0) {
274 "imap_load_msgids() can't run; no room selected\n");
279 * Check to see if the room's contents have changed.
280 * If not, we can avoid this rescan.
282 getroom(&CC->room, CC->room.QRname);
283 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
287 /* Load the *current* message list from disk, so we can compare it
288 * to what we have in memory.
290 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
292 msglist = malloc(cdbfr->len);
293 if (msglist == NULL) {
294 lprintf(CTDL_CRIT, "malloc() failed\n");
297 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
298 num_msgs = cdbfr->len / sizeof(long);
305 * Check to see if any of the messages we know about have been expunged
307 if (IMAP->num_msgs > 0) {
309 for (i = 0; i < IMAP->num_msgs; ++i) {
311 message_still_exists = 0;
313 for (j = jstart; j < num_msgs; ++j) {
314 if (msglist[j] == IMAP->msgids[i]) {
315 message_still_exists = 1;
322 if (message_still_exists == 0) {
323 cprintf("* %d EXPUNGE\r\n", i + 1);
325 /* Here's some nice stupid nonsense. When a
326 * message is expunged, we have to slide all
327 * the existing messages up in the message
331 memcpy(&IMAP->msgids[i],
332 &IMAP->msgids[i + 1],
334 (IMAP->num_msgs - i)));
335 memcpy(&IMAP->flags[i],
338 (IMAP->num_msgs - i)));
347 * Remember how many messages were here before we re-scanned.
349 original_num_msgs = IMAP->num_msgs;
350 if (IMAP->num_msgs > 0) {
351 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
353 original_highest = 0L;
357 * Now peruse the room for *new* messages only.
360 for (j = 0; j < num_msgs; ++j) {
361 if (msglist[j] > original_highest) {
362 imap_add_single_msgid(msglist[j], NULL);
366 imap_set_seen_flags(original_num_msgs);
369 * If new messages have arrived, tell the client about them.
371 if (IMAP->num_msgs > original_num_msgs) {
373 for (j = 0; j < num_msgs; ++j) {
374 if (IMAP->flags[j] & IMAP_RECENT) {
379 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
380 cprintf("* %d RECENT\r\n", num_recent);
386 IMAP->last_mtime = CC->room.QRmtime;
396 * This cleanup function blows away the temporary memory and files used by
399 void imap_cleanup_function(void)
402 /* Don't do this stuff if this is not a IMAP session! */
403 if (CC->h_command_function != imap_command_loop)
406 /* If there is a mailbox selected, auto-expunge it. */
407 if (IMAP->selected) {
411 lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
413 imap_free_transmitted_message();
415 if (IMAP->cached_rfc822_data != NULL) {
416 free(IMAP->cached_rfc822_data);
417 IMAP->cached_rfc822_data = NULL;
418 IMAP->cached_rfc822_msgnum = (-1);
419 IMAP->cached_rfc822_withbody = 0;
422 if (IMAP->cached_body != NULL) {
423 free(IMAP->cached_body);
424 IMAP->cached_body = NULL;
425 IMAP->cached_body_len = 0;
426 IMAP->cached_bodymsgnum = (-1);
430 lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
435 * Does the actual work of the CAPABILITY command (because we need to
436 * output this stuff in other places as well)
438 void imap_output_capability_string(void) {
439 cprintf("CAPABILITY IMAP4REV1 NAMESPACE ID ACL AUTH=LOGIN");
441 if (!CC->redirect_ssl) cprintf(" STARTTLS");
446 * implements the CAPABILITY command
448 void imap_capability(int num_parms, char *parms[])
451 imap_output_capability_string();
453 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
459 * Implements the ID command (specified by RFC2971)
461 * We ignore the client-supplied information, and output a NIL response.
462 * Although this is technically a valid implementation of the extension, it
463 * is quite useless. It exists only so that we may see which clients are
464 * making use of this extension.
467 void imap_id(int num_parms, char *parms[])
469 cprintf("* ID NIL\r\n");
470 cprintf("%s OK ID completed\r\n", parms[0]);
476 * Here's where our IMAP session begins its happy day.
478 void imap_greeting(void)
481 strcpy(CC->cs_clientname, "IMAP session");
482 IMAP = malloc(sizeof (struct citimap));
483 memset(IMAP, 0, sizeof(struct citimap));
484 IMAP->authstate = imap_as_normal;
485 IMAP->cached_rfc822_data = NULL;
486 IMAP->cached_rfc822_msgnum = (-1);
487 IMAP->cached_rfc822_withbody = 0;
490 imap_output_capability_string();
491 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
495 * IMAPS is just like IMAP, except it goes crypto right away.
498 void imaps_greeting(void) {
499 CtdlStartTLS(NULL, NULL, NULL);
506 * implements the LOGIN command (ordinary username/password login)
508 void imap_login(int num_parms, char *parms[])
510 if (num_parms != 4) {
511 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
515 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
516 if (CtdlTryPassword(parms[3]) == pass_ok) {
517 cprintf("%s OK [", parms[0]);
518 imap_output_capability_string();
519 cprintf("] Hello, %s\r\n", CC->user.fullname);
524 cprintf("%s BAD Login incorrect\r\n", parms[0]);
529 * Implements the AUTHENTICATE command
531 void imap_authenticate(int num_parms, char *parms[])
535 if (num_parms != 3) {
536 cprintf("%s BAD incorrect number of parameters\r\n",
542 cprintf("%s BAD Already logged in.\r\n", parms[0]);
546 if (!strcasecmp(parms[2], "LOGIN")) {
547 CtdlEncodeBase64(buf, "Username:", 9);
548 cprintf("+ %s\r\n", buf);
549 IMAP->authstate = imap_as_expecting_username;
550 strcpy(IMAP->authseq, parms[0]);
555 cprintf("%s NO AUTHENTICATE %s failed\r\n",
560 void imap_auth_login_user(char *cmd)
564 CtdlDecodeBase64(buf, cmd, SIZ);
565 CtdlLoginExistingUser(buf);
566 CtdlEncodeBase64(buf, "Password:", 9);
567 cprintf("+ %s\r\n", buf);
568 IMAP->authstate = imap_as_expecting_password;
572 void imap_auth_login_pass(char *cmd)
576 CtdlDecodeBase64(buf, cmd, SIZ);
577 if (CtdlTryPassword(buf) == pass_ok) {
578 cprintf("%s OK authentication succeeded\r\n",
581 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
583 IMAP->authstate = imap_as_normal;
589 * implements the STARTTLS command (Citadel API version)
592 void imap_starttls(int num_parms, char *parms[])
594 char ok_response[SIZ];
595 char nosup_response[SIZ];
596 char error_response[SIZ];
599 "%s OK begin TLS negotiation now\r\n",
601 sprintf(nosup_response,
602 "%s NO TLS not supported here\r\n",
604 sprintf(error_response,
605 "%s BAD Internal error\r\n",
607 CtdlStartTLS(ok_response, nosup_response, error_response);
613 * implements the SELECT command
615 void imap_select(int num_parms, char *parms[])
618 char augmented_roomname[ROOMNAMELEN];
622 struct ctdlroom QRscratch;
628 /* Convert the supplied folder name to a roomname */
629 i = imap_roomname(towhere, sizeof towhere, parms[2]);
631 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
635 floornum = (i & 0x00ff);
636 roomflags = (i & 0xff00);
638 /* First try a regular match */
639 c = getroom(&QRscratch, towhere);
641 /* Then try a mailbox name match */
643 MailboxName(augmented_roomname, sizeof augmented_roomname,
645 c = getroom(&QRscratch, augmented_roomname);
647 strcpy(towhere, augmented_roomname);
650 /* If the room exists, check security/access */
652 /* See if there is an existing user/room relationship */
653 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
655 /* normal clients have to pass through security */
661 /* Fail here if no such room */
663 cprintf("%s NO ... no such room, or access denied\r\n",
668 /* If we already had some other folder selected, auto-expunge it */
672 * usergoto() formally takes us to the desired room, happily returning
673 * the number of messages and number of new messages.
675 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
676 usergoto(NULL, 0, 0, &msgs, &new);
679 if (!strcasecmp(parms[1], "EXAMINE")) {
686 IMAP->last_mtime = CC->room.QRmtime;
688 cprintf("* %d EXISTS\r\n", msgs);
689 cprintf("* %d RECENT\r\n", new);
691 cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
692 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
694 /* Note that \Deleted is a valid flag, but not a permanent flag,
695 * because we don't maintain its state across sessions. Citadel
696 * automatically expunges mailboxes when they are de-selected.
698 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
699 cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] "
700 "permanent flags\r\n");
702 cprintf("%s OK [%s] %s completed\r\n",
704 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
710 * Does the real work for expunge.
712 int imap_do_expunge(void)
715 int num_expunged = 0;
716 long *delmsgs = NULL;
719 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
720 if (IMAP->selected == 0) {
724 if (IMAP->num_msgs > 0) {
725 delmsgs = malloc(IMAP->num_msgs * sizeof(long));
726 for (i = 0; i < IMAP->num_msgs; ++i) {
727 if (IMAP->flags[i] & IMAP_DELETED) {
728 delmsgs[num_delmsgs++] = IMAP->msgids[i];
731 if (num_delmsgs > 0) {
732 CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
734 num_expunged += num_delmsgs;
738 if (num_expunged > 0) {
739 imap_rescan_msgids();
742 lprintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n",
743 num_expunged, CC->room.QRname);
744 return (num_expunged);
749 * implements the EXPUNGE command syntax
751 void imap_expunge(int num_parms, char *parms[])
753 int num_expunged = 0;
755 num_expunged = imap_do_expunge();
756 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
761 * implements the CLOSE command
763 void imap_close(int num_parms, char *parms[])
766 /* Yes, we always expunge on close. */
767 if (IMAP->selected) {
774 cprintf("%s OK CLOSE completed\r\n", parms[0]);
779 * Implements the NAMESPACE command.
781 void imap_namespace(int num_parms, char *parms[])
788 cprintf("* NAMESPACE ");
790 /* All personal folders are subordinate to INBOX. */
791 cprintf("((\"INBOX/\" \"/\")) ");
793 /* Other users' folders ... coming soon! FIXME */
796 /* Show all floors as shared namespaces. Neato! */
798 for (i = 0; i < MAXFLOORS; ++i) {
800 if (fl->f_flags & F_INUSE) {
801 if (floors > 0) cprintf(" ");
803 sprintf(buf, "%s/", fl->f_name);
811 /* Wind it up with a newline and a completion message. */
813 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
819 * Implements the CREATE command
822 void imap_create(int num_parms, char *parms[])
825 char roomname[ROOMNAMELEN];
831 if (strchr(parms[2], '\\') != NULL) {
832 cprintf("%s NO Invalid character in folder name\r\n",
834 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
838 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
840 cprintf("%s NO Invalid mailbox name or location\r\n",
842 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
845 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
846 flags = (ret & 0xff00); /* upper 8 bits = flags */
848 if (flags & IR_MAILBOX) {
849 if (strncasecmp(parms[2], "INBOX/", 6)) {
850 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
851 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
856 if (flags & IR_MAILBOX) {
857 newroomtype = 4; /* private mailbox */
858 newroomview = VIEW_MAILBOX;
860 newroomtype = 0; /* public folder */
861 newroomview = VIEW_BBS;
864 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
865 roomname, floornum, newroomtype);
867 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
869 /*** DO NOT CHANGE THIS ERROR MESSAGE IN ANY WAY! BYNARI CONNECTOR DEPENDS ON IT! ***/
870 cprintf("%s NO Mailbox already exists, or create failed\r\n", parms[0]);
872 cprintf("%s OK CREATE completed\r\n", parms[0]);
874 lprintf(CTDL_DEBUG, "imap_create() completed\n");
879 * Locate a room by its IMAP folder name, and check access to it.
880 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
882 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
885 char augmented_roomname[ROOMNAMELEN];
886 char roomname[ROOMNAMELEN];
888 struct ctdlroom QRscratch;
892 ret = imap_roomname(roomname, sizeof roomname, foldername);
897 /* First try a regular match */
898 c = getroom(&QRscratch, roomname);
900 /* Then try a mailbox name match */
902 MailboxName(augmented_roomname, sizeof augmented_roomname,
903 &CC->user, roomname);
904 c = getroom(&QRscratch, augmented_roomname);
906 strcpy(roomname, augmented_roomname);
909 /* If the room exists, check security/access */
911 /* See if there is an existing user/room relationship */
912 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
914 /* normal clients have to pass through security */
918 if ((zapped_ok) && (ra & UA_ZAPPED)) {
923 /* Fail here if no such room */
925 strcpy(returned_roomname, "");
928 strcpy(returned_roomname, QRscratch.QRname);
935 * Implements the STATUS command (sort of)
938 void imap_status(int num_parms, char *parms[])
941 char roomname[ROOMNAMELEN];
943 char savedroom[ROOMNAMELEN];
946 ret = imap_grabroom(roomname, parms[2], 0);
949 ("%s NO Invalid mailbox name or location, or access denied\r\n",
955 * usergoto() formally takes us to the desired room, happily returning
956 * the number of messages and number of new messages. (If another
957 * folder is selected, save its name so we can return there!!!!!)
959 if (IMAP->selected) {
960 strcpy(savedroom, CC->room.QRname);
962 usergoto(roomname, 0, 0, &msgs, &new);
965 * Tell the client what it wants to know. In fact, tell it *more* than
966 * it wants to know. We happily IGnore the supplied status data item
967 * names and simply spew all possible data items. It's far easier to
968 * code and probably saves us some processing time too.
970 imap_mailboxname(buf, sizeof buf, &CC->room);
971 cprintf("* STATUS ");
973 cprintf(" (MESSAGES %d ", msgs);
974 cprintf("RECENT %d ", new); /* Initially, new==recent */
975 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
976 cprintf("UNSEEN %d)\r\n", new);
979 * If another folder is selected, go back to that room so we can resume
980 * our happy day without violent explosions.
982 if (IMAP->selected) {
983 usergoto(savedroom, 0, 0, &msgs, &new);
987 * Oooh, look, we're done!
989 cprintf("%s OK STATUS completed\r\n", parms[0]);
995 * Implements the SUBSCRIBE command
998 void imap_subscribe(int num_parms, char *parms[])
1001 char roomname[ROOMNAMELEN];
1002 char savedroom[ROOMNAMELEN];
1005 ret = imap_grabroom(roomname, parms[2], 1);
1008 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1016 * usergoto() formally takes us to the desired room, which has the side
1017 * effect of marking the room as not-zapped ... exactly the effect
1018 * we're looking for.
1020 if (IMAP->selected) {
1021 strcpy(savedroom, CC->room.QRname);
1023 usergoto(roomname, 0, 0, &msgs, &new);
1026 * If another folder is selected, go back to that room so we can resume
1027 * our happy day without violent explosions.
1029 if (IMAP->selected) {
1030 usergoto(savedroom, 0, 0, &msgs, &new);
1033 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1038 * Implements the UNSUBSCRIBE command
1041 void imap_unsubscribe(int num_parms, char *parms[])
1044 char roomname[ROOMNAMELEN];
1045 char savedroom[ROOMNAMELEN];
1048 ret = imap_grabroom(roomname, parms[2], 0);
1051 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1057 * usergoto() formally takes us to the desired room.
1059 if (IMAP->selected) {
1060 strcpy(savedroom, CC->room.QRname);
1062 usergoto(roomname, 0, 0, &msgs, &new);
1065 * Now make the API call to zap the room
1067 if (CtdlForgetThisRoom() == 0) {
1068 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1071 ("%s NO You may not unsubscribe from this folder.\r\n",
1076 * If another folder is selected, go back to that room so we can resume
1077 * our happy day without violent explosions.
1079 if (IMAP->selected) {
1080 usergoto(savedroom, 0, 0, &msgs, &new);
1087 * Implements the DELETE command
1090 void imap_delete(int num_parms, char *parms[])
1093 char roomname[ROOMNAMELEN];
1094 char savedroom[ROOMNAMELEN];
1097 ret = imap_grabroom(roomname, parms[2], 1);
1099 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1105 * usergoto() formally takes us to the desired room, happily returning
1106 * the number of messages and number of new messages. (If another
1107 * folder is selected, save its name so we can return there!!!!!)
1109 if (IMAP->selected) {
1110 strcpy(savedroom, CC->room.QRname);
1112 usergoto(roomname, 0, 0, &msgs, &new);
1115 * Now delete the room.
1117 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1118 schedule_room_for_deletion(&CC->room);
1119 cprintf("%s OK DELETE completed\r\n", parms[0]);
1121 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1125 * If another folder is selected, go back to that room so we can resume
1126 * our happy day without violent explosions.
1128 if (IMAP->selected) {
1129 usergoto(savedroom, 0, 0, &msgs, &new);
1135 * Back end function for imap_rename()
1137 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1139 char foldername[SIZ];
1140 char newfoldername[SIZ];
1141 char newroomname[ROOMNAMELEN];
1143 struct irl *irlp = NULL; /* scratch pointer */
1144 struct irlparms *irlparms;
1146 irlparms = (struct irlparms *) data;
1147 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1149 /* Rename subfolders */
1150 if ((!strncasecmp(foldername, irlparms->oldname,
1151 strlen(irlparms->oldname))
1152 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1154 sprintf(newfoldername, "%s/%s",
1156 &foldername[strlen(irlparms->oldname) + 1]
1159 newfloor = imap_roomname(newroomname,
1161 newfoldername) & 0xFF;
1163 irlp = (struct irl *) malloc(sizeof(struct irl));
1164 strcpy(irlp->irl_newroom, newroomname);
1165 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1166 irlp->irl_newfloor = newfloor;
1167 irlp->next = *(irlparms->irl);
1168 *(irlparms->irl) = irlp;
1174 * Implements the RENAME command
1177 void imap_rename(int num_parms, char *parms[])
1179 char old_room[ROOMNAMELEN];
1180 char new_room[ROOMNAMELEN];
1184 struct irl *irl = NULL; /* the list */
1185 struct irl *irlp = NULL; /* scratch pointer */
1186 struct irlparms irlparms;
1188 if (strchr(parms[3], '\\') != NULL) {
1189 cprintf("%s NO Invalid character in folder name\r\n",
1194 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1195 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1196 new_floor = (newr & 0xFF);
1198 r = CtdlRenameRoom(old_room, new_room, new_floor);
1200 if (r == crr_room_not_found) {
1201 cprintf("%s NO Could not locate this folder\r\n",
1205 if (r == crr_already_exists) {
1206 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1209 if (r == crr_noneditable) {
1210 cprintf("%s This folder is not editable.\r\n", parms[0]);
1213 if (r == crr_invalid_floor) {
1214 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1217 if (r == crr_access_denied) {
1218 cprintf("%s You do not have permission to edit "
1219 "this folder.\r\n", parms[0]);
1223 cprintf("%s NO Rename failed - undefined error %d\r\n",
1229 /* If this is the INBOX, then RFC2060 says we have to just move the
1230 * contents. In a Citadel environment it's easier to rename the room
1231 * (already did that) and create a new inbox.
1233 if (!strcasecmp(parms[2], "INBOX")) {
1234 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1237 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1239 irlparms.oldname = parms[2];
1240 irlparms.newname = parms[3];
1241 irlparms.irl = &irl;
1242 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1244 /* ... and now rename them. */
1245 while (irl != NULL) {
1246 r = CtdlRenameRoom(irl->irl_oldroom,
1250 /* FIXME handle error returns better */
1251 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n", r);
1259 cprintf("%s OK RENAME completed\r\n", parms[0]);
1266 * Main command loop for IMAP sessions.
1268 void imap_command_loop(void)
1273 struct timeval tv1, tv2;
1274 suseconds_t total_time = 0;
1276 gettimeofday(&tv1, NULL);
1277 CC->lastcmd = time(NULL);
1278 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1280 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1281 lprintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1286 if (IMAP->authstate == imap_as_expecting_password) {
1287 lprintf(CTDL_INFO, "IMAP: <password>\n");
1289 else if (bmstrcasestr(cmdbuf, " LOGIN ")) {
1290 lprintf(CTDL_INFO, "IMAP: LOGIN...\n");
1293 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1296 while (strlen(cmdbuf) < 5)
1297 strcat(cmdbuf, " ");
1299 /* strip off l/t whitespace and CRLF */
1300 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1301 cmdbuf[strlen(cmdbuf) - 1] = 0;
1302 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1303 cmdbuf[strlen(cmdbuf) - 1] = 0;
1306 /* If we're in the middle of a multi-line command, handle that */
1307 if (IMAP->authstate == imap_as_expecting_username) {
1308 imap_auth_login_user(cmdbuf);
1311 if (IMAP->authstate == imap_as_expecting_password) {
1312 imap_auth_login_pass(cmdbuf);
1316 /* Ok, at this point we're in normal command mode. The first thing
1317 * we do is print any incoming pages (yeah! we really do!)
1319 imap_print_instant_messages();
1322 * Before processing the command that was just entered... if we happen
1323 * to have a folder selected, we'd like to rescan that folder for new
1324 * messages, and for deletions/changes of existing messages. This
1325 * could probably be optimized somehow, but IMAP sucks...
1327 if (IMAP->selected) {
1328 imap_rescan_msgids();
1331 /* Now for the command set. */
1333 /* Grab the tag, command, and parameters. Check syntax. */
1334 num_parms = imap_parameterize(parms, cmdbuf);
1335 if (num_parms < 2) {
1336 cprintf("BAD syntax error\r\n");
1339 /* The commands below may be executed in any state */
1341 else if ((!strcasecmp(parms[1], "NOOP"))
1342 || (!strcasecmp(parms[1], "CHECK"))) {
1343 cprintf("%s OK No operation\r\n",
1347 else if (!strcasecmp(parms[1], "ID")) {
1348 imap_id(num_parms, parms);
1352 else if (!strcasecmp(parms[1], "LOGOUT")) {
1353 if (IMAP->selected) {
1354 imap_do_expunge(); /* yes, we auto-expunge */
1356 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1357 cprintf("%s OK Citadel IMAP session ended.\r\n",
1363 else if (!strcasecmp(parms[1], "LOGIN")) {
1364 imap_login(num_parms, parms);
1367 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1368 imap_authenticate(num_parms, parms);
1371 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1372 imap_capability(num_parms, parms);
1375 else if (!strcasecmp(parms[1], "STARTTLS")) {
1376 imap_starttls(num_parms, parms);
1379 else if (!CC->logged_in) {
1380 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1383 /* The commans below require a logged-in state */
1385 else if (!strcasecmp(parms[1], "SELECT")) {
1386 imap_select(num_parms, parms);
1389 else if (!strcasecmp(parms[1], "EXAMINE")) {
1390 imap_select(num_parms, parms);
1393 else if (!strcasecmp(parms[1], "LSUB")) {
1394 imap_list(num_parms, parms);
1397 else if (!strcasecmp(parms[1], "LIST")) {
1398 imap_list(num_parms, parms);
1401 else if (!strcasecmp(parms[1], "CREATE")) {
1402 imap_create(num_parms, parms);
1405 else if (!strcasecmp(parms[1], "DELETE")) {
1406 imap_delete(num_parms, parms);
1409 else if (!strcasecmp(parms[1], "RENAME")) {
1410 imap_rename(num_parms, parms);
1413 else if (!strcasecmp(parms[1], "STATUS")) {
1414 imap_status(num_parms, parms);
1417 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1418 imap_subscribe(num_parms, parms);
1421 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1422 imap_unsubscribe(num_parms, parms);
1425 else if (!strcasecmp(parms[1], "APPEND")) {
1426 imap_append(num_parms, parms);
1429 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1430 imap_namespace(num_parms, parms);
1433 else if (!strcasecmp(parms[1], "SETACL")) {
1434 imap_setacl(num_parms, parms);
1437 else if (!strcasecmp(parms[1], "DELETEACL")) {
1438 imap_deleteacl(num_parms, parms);
1441 else if (!strcasecmp(parms[1], "GETACL")) {
1442 imap_getacl(num_parms, parms);
1445 else if (!strcasecmp(parms[1], "LISTRIGHTS")) {
1446 imap_listrights(num_parms, parms);
1449 else if (!strcasecmp(parms[1], "MYRIGHTS")) {
1450 imap_myrights(num_parms, parms);
1453 else if (IMAP->selected == 0) {
1454 cprintf("%s BAD no folder selected\r\n", parms[0]);
1457 /* The commands below require the SELECT state on a mailbox */
1459 else if (!strcasecmp(parms[1], "FETCH")) {
1460 imap_fetch(num_parms, parms);
1463 else if ((!strcasecmp(parms[1], "UID"))
1464 && (!strcasecmp(parms[2], "FETCH"))) {
1465 imap_uidfetch(num_parms, parms);
1468 else if (!strcasecmp(parms[1], "SEARCH")) {
1469 imap_search(num_parms, parms);
1472 else if ((!strcasecmp(parms[1], "UID"))
1473 && (!strcasecmp(parms[2], "SEARCH"))) {
1474 imap_uidsearch(num_parms, parms);
1477 else if (!strcasecmp(parms[1], "STORE")) {
1478 imap_store(num_parms, parms);
1481 else if ((!strcasecmp(parms[1], "UID"))
1482 && (!strcasecmp(parms[2], "STORE"))) {
1483 imap_uidstore(num_parms, parms);
1486 else if (!strcasecmp(parms[1], "COPY")) {
1487 imap_copy(num_parms, parms);
1490 else if ((!strcasecmp(parms[1], "UID"))
1491 && (!strcasecmp(parms[2], "COPY"))) {
1492 imap_uidcopy(num_parms, parms);
1495 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1496 imap_expunge(num_parms, parms);
1499 else if (!strcasecmp(parms[1], "CLOSE")) {
1500 imap_close(num_parms, parms);
1503 /* End of commands. If we get here, the command is either invalid
1508 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1511 /* If the client transmitted a message we can free it now */
1512 imap_free_transmitted_message();
1514 gettimeofday(&tv2, NULL);
1515 total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1516 lprintf(CTDL_DEBUG, "IMAP command completed in %ld.%ld seconds\n",
1517 (total_time / 1000000),
1518 (total_time % 1000000)
1524 * This function is called to register the IMAP extension with Citadel.
1526 char *serv_imap_init(void)
1528 CtdlRegisterServiceHook(config.c_imap_port,
1529 NULL, imap_greeting, imap_command_loop, NULL);
1531 CtdlRegisterServiceHook(config.c_imaps_port,
1532 NULL, imaps_greeting, imap_command_loop, NULL);
1534 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);