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_metadata.h"
60 #include "imap_misc.h"
63 #include "serv_crypto.h"
66 /* imap_rename() uses this struct containing list of rooms to rename */
69 char irl_oldroom[ROOMNAMELEN];
70 char irl_newroom[ROOMNAMELEN];
74 /* Data which is passed between imap_rename() and imap_rename_backend() */
83 * If there is a message ID map in memory, free it
85 void imap_free_msgids(void)
87 if (IMAP->msgids != NULL) {
93 if (IMAP->flags != NULL) {
97 IMAP->last_mtime = (-1);
102 * If there is a transmitted message in memory, free it
104 void imap_free_transmitted_message(void)
106 if (IMAP->transmitted_message != NULL) {
107 free(IMAP->transmitted_message);
108 IMAP->transmitted_message = NULL;
109 IMAP->transmitted_length = 0;
115 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
116 * sets stored in the visit record for this user/room. Note that we have
117 * to parse each sequence set manually here, because calling the utility
118 * function is_msg_in_sequence_set() over and over again is too expensive.
120 * first_msg should be set to 0 to rescan the flags for every message in the
121 * room, or some other value if we're only interested in an incremental
124 void imap_set_seen_flags(int first_msg)
130 char setstr[64], lostr[64], histr[64];
133 if (IMAP->num_msgs < 1) return;
134 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
136 for (i = first_msg; i < IMAP->num_msgs; ++i) {
137 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
138 IMAP->flags[i] |= IMAP_RECENT;
139 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
143 * Do the "\Seen" flag.
144 * (Any message not "\Seen" is considered "\Recent".)
146 num_sets = num_tokens(vbuf.v_seen, ',');
147 for (s=0; s<num_sets; ++s) {
148 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
150 extract_token(lostr, setstr, 0, ':', sizeof lostr);
151 if (num_tokens(setstr, ':') >= 2) {
152 extract_token(histr, setstr, 1, ':', sizeof histr);
153 if (!strcmp(histr, "*")) {
154 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
158 strcpy(histr, lostr);
163 for (i = first_msg; i < IMAP->num_msgs; ++i) {
164 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
165 IMAP->flags[i] |= IMAP_SEEN;
166 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
171 /* Do the ANSWERED flag */
172 num_sets = num_tokens(vbuf.v_answered, ',');
173 for (s=0; s<num_sets; ++s) {
174 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
176 extract_token(lostr, setstr, 0, ':', sizeof lostr);
177 if (num_tokens(setstr, ':') >= 2) {
178 extract_token(histr, setstr, 1, ':', sizeof histr);
179 if (!strcmp(histr, "*")) {
180 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
184 strcpy(histr, lostr);
189 for (i = first_msg; i < IMAP->num_msgs; ++i) {
190 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
191 IMAP->flags[i] |= IMAP_ANSWERED;
201 * Back end for imap_load_msgids()
203 * Optimization: instead of calling realloc() to add each message, we
204 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
205 * allows the mapping to proceed much faster.
207 void imap_add_single_msgid(long msgnum, void *userdata)
211 if (IMAP->num_msgs > IMAP->num_alloc) {
212 IMAP->num_alloc += REALLOC_INCREMENT;
213 IMAP->msgids = realloc(IMAP->msgids,
214 (IMAP->num_alloc * sizeof(long)) );
215 IMAP->flags = realloc(IMAP->flags,
216 (IMAP->num_alloc * sizeof(long)) );
218 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
219 IMAP->flags[IMAP->num_msgs - 1] = 0;
225 * Set up a message ID map for the current room (folder)
227 void imap_load_msgids(void)
229 struct cdbdata *cdbfr;
231 if (IMAP->selected == 0) {
233 "imap_load_msgids() can't run; no room selected\n");
237 imap_free_msgids(); /* If there was already a map, free it */
239 /* Load the message list */
240 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
242 IMAP->msgids = malloc(cdbfr->len);
243 memcpy(IMAP->msgids, cdbfr->ptr, cdbfr->len);
244 IMAP->num_msgs = cdbfr->len / sizeof(long);
245 IMAP->num_alloc = cdbfr->len / sizeof(long);
249 if (IMAP->num_msgs) {
250 IMAP->flags = malloc(IMAP->num_alloc * sizeof(long));
251 memset(IMAP->flags, 0, (IMAP->num_alloc * sizeof(long)) );
254 imap_set_seen_flags(0);
259 * Re-scan the selected room (folder) and see if it's been changed at all
261 void imap_rescan_msgids(void)
264 int original_num_msgs = 0;
265 long original_highest = 0L;
267 int message_still_exists;
268 struct cdbdata *cdbfr;
269 long *msglist = NULL;
273 if (IMAP->selected == 0) {
275 "imap_load_msgids() can't run; no room selected\n");
280 * Check to see if the room's contents have changed.
281 * If not, we can avoid this rescan.
283 getroom(&CC->room, CC->room.QRname);
284 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
288 /* Load the *current* message list from disk, so we can compare it
289 * to what we have in memory.
291 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
293 msglist = malloc(cdbfr->len);
294 if (msglist == NULL) {
295 lprintf(CTDL_CRIT, "malloc() failed\n");
298 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
299 num_msgs = cdbfr->len / sizeof(long);
306 * Check to see if any of the messages we know about have been expunged
308 if (IMAP->num_msgs > 0) {
310 for (i = 0; i < IMAP->num_msgs; ++i) {
312 message_still_exists = 0;
314 for (j = jstart; j < num_msgs; ++j) {
315 if (msglist[j] == IMAP->msgids[i]) {
316 message_still_exists = 1;
323 if (message_still_exists == 0) {
324 cprintf("* %d EXPUNGE\r\n", i + 1);
326 /* Here's some nice stupid nonsense. When a
327 * message is expunged, we have to slide all
328 * the existing messages up in the message
332 memcpy(&IMAP->msgids[i],
333 &IMAP->msgids[i + 1],
335 (IMAP->num_msgs - i)));
336 memcpy(&IMAP->flags[i],
339 (IMAP->num_msgs - i)));
348 * Remember how many messages were here before we re-scanned.
350 original_num_msgs = IMAP->num_msgs;
351 if (IMAP->num_msgs > 0) {
352 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
354 original_highest = 0L;
358 * Now peruse the room for *new* messages only.
361 for (j = 0; j < num_msgs; ++j) {
362 if (msglist[j] > original_highest) {
363 imap_add_single_msgid(msglist[j], NULL);
367 imap_set_seen_flags(original_num_msgs);
370 * If new messages have arrived, tell the client about them.
372 if (IMAP->num_msgs > original_num_msgs) {
374 for (j = 0; j < num_msgs; ++j) {
375 if (IMAP->flags[j] & IMAP_RECENT) {
380 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
381 cprintf("* %d RECENT\r\n", num_recent);
387 IMAP->last_mtime = CC->room.QRmtime;
397 * This cleanup function blows away the temporary memory and files used by
400 void imap_cleanup_function(void)
403 /* Don't do this stuff if this is not a IMAP session! */
404 if (CC->h_command_function != imap_command_loop)
407 /* If there is a mailbox selected, auto-expunge it. */
408 if (IMAP->selected) {
412 lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
414 imap_free_transmitted_message();
416 if (IMAP->cached_rfc822_data != NULL) {
417 free(IMAP->cached_rfc822_data);
418 IMAP->cached_rfc822_data = NULL;
419 IMAP->cached_rfc822_msgnum = (-1);
420 IMAP->cached_rfc822_withbody = 0;
423 if (IMAP->cached_body != NULL) {
424 free(IMAP->cached_body);
425 IMAP->cached_body = NULL;
426 IMAP->cached_body_len = 0;
427 IMAP->cached_bodymsgnum = (-1);
431 lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
436 * Does the actual work of the CAPABILITY command (because we need to
437 * output this stuff in other places as well)
439 void imap_output_capability_string(void) {
440 cprintf("CAPABILITY IMAP4REV1 NAMESPACE ID ACL AUTH=LOGIN");
443 if (!CC->redirect_ssl) cprintf(" STARTTLS");
446 /* Comment this out if its unfinished state is choking your client */
447 cprintf(" METADATA LIST-EXTENDED");
451 * implements the CAPABILITY command
453 void imap_capability(int num_parms, char *parms[])
456 imap_output_capability_string();
458 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
464 * Implements the ID command (specified by RFC2971)
466 * We ignore the client-supplied information, and output a NIL response.
467 * Although this is technically a valid implementation of the extension, it
468 * is quite useless. It exists only so that we may see which clients are
469 * making use of this extension.
472 void imap_id(int num_parms, char *parms[])
474 cprintf("* ID NIL\r\n");
475 cprintf("%s OK ID completed\r\n", parms[0]);
481 * Here's where our IMAP session begins its happy day.
483 void imap_greeting(void)
486 strcpy(CC->cs_clientname, "IMAP session");
487 IMAP = malloc(sizeof (struct citimap));
488 memset(IMAP, 0, sizeof(struct citimap));
489 IMAP->authstate = imap_as_normal;
490 IMAP->cached_rfc822_data = NULL;
491 IMAP->cached_rfc822_msgnum = (-1);
492 IMAP->cached_rfc822_withbody = 0;
495 imap_output_capability_string();
496 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
500 * IMAPS is just like IMAP, except it goes crypto right away.
503 void imaps_greeting(void) {
504 CtdlStartTLS(NULL, NULL, NULL);
511 * implements the LOGIN command (ordinary username/password login)
513 void imap_login(int num_parms, char *parms[])
515 if (num_parms != 4) {
516 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
520 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
521 if (CtdlTryPassword(parms[3]) == pass_ok) {
522 cprintf("%s OK [", parms[0]);
523 imap_output_capability_string();
524 cprintf("] Hello, %s\r\n", CC->user.fullname);
529 cprintf("%s BAD Login incorrect\r\n", parms[0]);
534 * Implements the AUTHENTICATE command
536 void imap_authenticate(int num_parms, char *parms[])
540 if (num_parms != 3) {
541 cprintf("%s BAD incorrect number of parameters\r\n",
547 cprintf("%s BAD Already logged in.\r\n", parms[0]);
551 if (!strcasecmp(parms[2], "LOGIN")) {
552 CtdlEncodeBase64(buf, "Username:", 9);
553 cprintf("+ %s\r\n", buf);
554 IMAP->authstate = imap_as_expecting_username;
555 strcpy(IMAP->authseq, parms[0]);
560 cprintf("%s NO AUTHENTICATE %s failed\r\n",
565 void imap_auth_login_user(char *cmd)
569 CtdlDecodeBase64(buf, cmd, SIZ);
570 CtdlLoginExistingUser(buf);
571 CtdlEncodeBase64(buf, "Password:", 9);
572 cprintf("+ %s\r\n", buf);
573 IMAP->authstate = imap_as_expecting_password;
577 void imap_auth_login_pass(char *cmd)
581 CtdlDecodeBase64(buf, cmd, SIZ);
582 if (CtdlTryPassword(buf) == pass_ok) {
583 cprintf("%s OK authentication succeeded\r\n",
586 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
588 IMAP->authstate = imap_as_normal;
594 * implements the STARTTLS command (Citadel API version)
597 void imap_starttls(int num_parms, char *parms[])
599 char ok_response[SIZ];
600 char nosup_response[SIZ];
601 char error_response[SIZ];
604 "%s OK begin TLS negotiation now\r\n",
606 sprintf(nosup_response,
607 "%s NO TLS not supported here\r\n",
609 sprintf(error_response,
610 "%s BAD Internal error\r\n",
612 CtdlStartTLS(ok_response, nosup_response, error_response);
618 * implements the SELECT command
620 void imap_select(int num_parms, char *parms[])
623 char augmented_roomname[ROOMNAMELEN];
627 struct ctdlroom QRscratch;
633 /* Convert the supplied folder name to a roomname */
634 i = imap_roomname(towhere, sizeof towhere, parms[2]);
636 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
640 floornum = (i & 0x00ff);
641 roomflags = (i & 0xff00);
643 /* First try a regular match */
644 c = getroom(&QRscratch, towhere);
646 /* Then try a mailbox name match */
648 MailboxName(augmented_roomname, sizeof augmented_roomname,
650 c = getroom(&QRscratch, augmented_roomname);
652 strcpy(towhere, augmented_roomname);
655 /* If the room exists, check security/access */
657 /* See if there is an existing user/room relationship */
658 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
660 /* normal clients have to pass through security */
666 /* Fail here if no such room */
668 cprintf("%s NO ... no such room, or access denied\r\n",
673 /* If we already had some other folder selected, auto-expunge it */
677 * usergoto() formally takes us to the desired room, happily returning
678 * the number of messages and number of new messages.
680 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
681 usergoto(NULL, 0, 0, &msgs, &new);
684 if (!strcasecmp(parms[1], "EXAMINE")) {
691 IMAP->last_mtime = CC->room.QRmtime;
693 cprintf("* %d EXISTS\r\n", msgs);
694 cprintf("* %d RECENT\r\n", new);
696 cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
697 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
699 /* Note that \Deleted is a valid flag, but not a permanent flag,
700 * because we don't maintain its state across sessions. Citadel
701 * automatically expunges mailboxes when they are de-selected.
703 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
704 cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] "
705 "permanent flags\r\n");
707 cprintf("%s OK [%s] %s completed\r\n",
709 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
715 * Does the real work for expunge.
717 int imap_do_expunge(void)
720 int num_expunged = 0;
721 long *delmsgs = NULL;
724 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
725 if (IMAP->selected == 0) {
729 if (IMAP->num_msgs > 0) {
730 delmsgs = malloc(IMAP->num_msgs * sizeof(long));
731 for (i = 0; i < IMAP->num_msgs; ++i) {
732 if (IMAP->flags[i] & IMAP_DELETED) {
733 delmsgs[num_delmsgs++] = IMAP->msgids[i];
736 if (num_delmsgs > 0) {
737 CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
739 num_expunged += num_delmsgs;
743 if (num_expunged > 0) {
744 imap_rescan_msgids();
747 lprintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n",
748 num_expunged, CC->room.QRname);
749 return (num_expunged);
754 * implements the EXPUNGE command syntax
756 void imap_expunge(int num_parms, char *parms[])
758 int num_expunged = 0;
760 num_expunged = imap_do_expunge();
761 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
766 * implements the CLOSE command
768 void imap_close(int num_parms, char *parms[])
771 /* Yes, we always expunge on close. */
772 if (IMAP->selected) {
779 cprintf("%s OK CLOSE completed\r\n", parms[0]);
784 * Implements the NAMESPACE command.
786 void imap_namespace(int num_parms, char *parms[])
793 cprintf("* NAMESPACE ");
795 /* All personal folders are subordinate to INBOX. */
796 cprintf("((\"INBOX/\" \"/\")) ");
798 /* Other users' folders ... coming soon! FIXME */
801 /* Show all floors as shared namespaces. Neato! */
803 for (i = 0; i < MAXFLOORS; ++i) {
805 if (fl->f_flags & F_INUSE) {
806 if (floors > 0) cprintf(" ");
808 sprintf(buf, "%s/", fl->f_name);
816 /* Wind it up with a newline and a completion message. */
818 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
824 * Implements the CREATE command
827 void imap_create(int num_parms, char *parms[])
830 char roomname[ROOMNAMELEN];
836 if (strchr(parms[2], '\\') != NULL) {
837 cprintf("%s NO Invalid character in folder name\r\n",
839 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
843 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
845 cprintf("%s NO Invalid mailbox name or location\r\n",
847 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
850 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
851 flags = (ret & 0xff00); /* upper 8 bits = flags */
853 if (flags & IR_MAILBOX) {
854 if (strncasecmp(parms[2], "INBOX/", 6)) {
855 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
856 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
861 if (flags & IR_MAILBOX) {
862 newroomtype = 4; /* private mailbox */
863 newroomview = VIEW_MAILBOX;
865 newroomtype = 0; /* public folder */
866 newroomview = VIEW_BBS;
869 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
870 roomname, floornum, newroomtype);
872 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
874 /*** DO NOT CHANGE THIS ERROR MESSAGE IN ANY WAY! BYNARI CONNECTOR DEPENDS ON IT! ***/
875 cprintf("%s NO Mailbox already exists, or create failed\r\n", parms[0]);
877 cprintf("%s OK CREATE completed\r\n", parms[0]);
879 lprintf(CTDL_DEBUG, "imap_create() completed\n");
884 * Locate a room by its IMAP folder name, and check access to it.
885 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
887 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
890 char augmented_roomname[ROOMNAMELEN];
891 char roomname[ROOMNAMELEN];
893 struct ctdlroom QRscratch;
897 ret = imap_roomname(roomname, sizeof roomname, foldername);
902 /* First try a regular match */
903 c = getroom(&QRscratch, roomname);
905 /* Then try a mailbox name match */
907 MailboxName(augmented_roomname, sizeof augmented_roomname,
908 &CC->user, roomname);
909 c = getroom(&QRscratch, augmented_roomname);
911 strcpy(roomname, augmented_roomname);
914 /* If the room exists, check security/access */
916 /* See if there is an existing user/room relationship */
917 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
919 /* normal clients have to pass through security */
923 if ((zapped_ok) && (ra & UA_ZAPPED)) {
928 /* Fail here if no such room */
930 strcpy(returned_roomname, "");
933 strcpy(returned_roomname, QRscratch.QRname);
940 * Implements the STATUS command (sort of)
943 void imap_status(int num_parms, char *parms[])
946 char roomname[ROOMNAMELEN];
948 char savedroom[ROOMNAMELEN];
951 ret = imap_grabroom(roomname, parms[2], 0);
954 ("%s NO Invalid mailbox name or location, or access denied\r\n",
960 * usergoto() formally takes us to the desired room, happily returning
961 * the number of messages and number of new messages. (If another
962 * folder is selected, save its name so we can return there!!!!!)
964 if (IMAP->selected) {
965 strcpy(savedroom, CC->room.QRname);
967 usergoto(roomname, 0, 0, &msgs, &new);
970 * Tell the client what it wants to know. In fact, tell it *more* than
971 * it wants to know. We happily IGnore the supplied status data item
972 * names and simply spew all possible data items. It's far easier to
973 * code and probably saves us some processing time too.
975 imap_mailboxname(buf, sizeof buf, &CC->room);
976 cprintf("* STATUS ");
978 cprintf(" (MESSAGES %d ", msgs);
979 cprintf("RECENT %d ", new); /* Initially, new==recent */
980 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
981 cprintf("UNSEEN %d)\r\n", new);
984 * If another folder is selected, go back to that room so we can resume
985 * our happy day without violent explosions.
987 if (IMAP->selected) {
988 usergoto(savedroom, 0, 0, &msgs, &new);
992 * Oooh, look, we're done!
994 cprintf("%s OK STATUS completed\r\n", parms[0]);
1000 * Implements the SUBSCRIBE command
1003 void imap_subscribe(int num_parms, char *parms[])
1006 char roomname[ROOMNAMELEN];
1007 char savedroom[ROOMNAMELEN];
1010 ret = imap_grabroom(roomname, parms[2], 1);
1013 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1021 * usergoto() formally takes us to the desired room, which has the side
1022 * effect of marking the room as not-zapped ... exactly the effect
1023 * we're looking for.
1025 if (IMAP->selected) {
1026 strcpy(savedroom, CC->room.QRname);
1028 usergoto(roomname, 0, 0, &msgs, &new);
1031 * If another folder is selected, go back to that room so we can resume
1032 * our happy day without violent explosions.
1034 if (IMAP->selected) {
1035 usergoto(savedroom, 0, 0, &msgs, &new);
1038 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1043 * Implements the UNSUBSCRIBE command
1046 void imap_unsubscribe(int num_parms, char *parms[])
1049 char roomname[ROOMNAMELEN];
1050 char savedroom[ROOMNAMELEN];
1053 ret = imap_grabroom(roomname, parms[2], 0);
1056 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1062 * usergoto() formally takes us to the desired room.
1064 if (IMAP->selected) {
1065 strcpy(savedroom, CC->room.QRname);
1067 usergoto(roomname, 0, 0, &msgs, &new);
1070 * Now make the API call to zap the room
1072 if (CtdlForgetThisRoom() == 0) {
1073 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1076 ("%s NO You may not unsubscribe from this folder.\r\n",
1081 * If another folder is selected, go back to that room so we can resume
1082 * our happy day without violent explosions.
1084 if (IMAP->selected) {
1085 usergoto(savedroom, 0, 0, &msgs, &new);
1092 * Implements the DELETE command
1095 void imap_delete(int num_parms, char *parms[])
1098 char roomname[ROOMNAMELEN];
1099 char savedroom[ROOMNAMELEN];
1102 ret = imap_grabroom(roomname, parms[2], 1);
1104 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1110 * usergoto() formally takes us to the desired room, happily returning
1111 * the number of messages and number of new messages. (If another
1112 * folder is selected, save its name so we can return there!!!!!)
1114 if (IMAP->selected) {
1115 strcpy(savedroom, CC->room.QRname);
1117 usergoto(roomname, 0, 0, &msgs, &new);
1120 * Now delete the room.
1122 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1123 schedule_room_for_deletion(&CC->room);
1124 cprintf("%s OK DELETE completed\r\n", parms[0]);
1126 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1130 * If another folder is selected, go back to that room so we can resume
1131 * our happy day without violent explosions.
1133 if (IMAP->selected) {
1134 usergoto(savedroom, 0, 0, &msgs, &new);
1140 * Back end function for imap_rename()
1142 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1144 char foldername[SIZ];
1145 char newfoldername[SIZ];
1146 char newroomname[ROOMNAMELEN];
1148 struct irl *irlp = NULL; /* scratch pointer */
1149 struct irlparms *irlparms;
1151 irlparms = (struct irlparms *) data;
1152 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1154 /* Rename subfolders */
1155 if ((!strncasecmp(foldername, irlparms->oldname,
1156 strlen(irlparms->oldname))
1157 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1159 sprintf(newfoldername, "%s/%s",
1161 &foldername[strlen(irlparms->oldname) + 1]
1164 newfloor = imap_roomname(newroomname,
1166 newfoldername) & 0xFF;
1168 irlp = (struct irl *) malloc(sizeof(struct irl));
1169 strcpy(irlp->irl_newroom, newroomname);
1170 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1171 irlp->irl_newfloor = newfloor;
1172 irlp->next = *(irlparms->irl);
1173 *(irlparms->irl) = irlp;
1179 * Implements the RENAME command
1182 void imap_rename(int num_parms, char *parms[])
1184 char old_room[ROOMNAMELEN];
1185 char new_room[ROOMNAMELEN];
1189 struct irl *irl = NULL; /* the list */
1190 struct irl *irlp = NULL; /* scratch pointer */
1191 struct irlparms irlparms;
1193 if (strchr(parms[3], '\\') != NULL) {
1194 cprintf("%s NO Invalid character in folder name\r\n",
1199 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1200 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1201 new_floor = (newr & 0xFF);
1203 r = CtdlRenameRoom(old_room, new_room, new_floor);
1205 if (r == crr_room_not_found) {
1206 cprintf("%s NO Could not locate this folder\r\n",
1210 if (r == crr_already_exists) {
1211 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1214 if (r == crr_noneditable) {
1215 cprintf("%s This folder is not editable.\r\n", parms[0]);
1218 if (r == crr_invalid_floor) {
1219 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1222 if (r == crr_access_denied) {
1223 cprintf("%s You do not have permission to edit "
1224 "this folder.\r\n", parms[0]);
1228 cprintf("%s NO Rename failed - undefined error %d\r\n",
1234 /* If this is the INBOX, then RFC2060 says we have to just move the
1235 * contents. In a Citadel environment it's easier to rename the room
1236 * (already did that) and create a new inbox.
1238 if (!strcasecmp(parms[2], "INBOX")) {
1239 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1242 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1244 irlparms.oldname = parms[2];
1245 irlparms.newname = parms[3];
1246 irlparms.irl = &irl;
1247 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1249 /* ... and now rename them. */
1250 while (irl != NULL) {
1251 r = CtdlRenameRoom(irl->irl_oldroom,
1255 /* FIXME handle error returns better */
1256 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n", r);
1264 cprintf("%s OK RENAME completed\r\n", parms[0]);
1271 * Main command loop for IMAP sessions.
1273 void imap_command_loop(void)
1278 struct timeval tv1, tv2;
1279 suseconds_t total_time = 0;
1281 gettimeofday(&tv1, NULL);
1282 CC->lastcmd = time(NULL);
1283 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1285 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1286 lprintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1291 if (IMAP->authstate == imap_as_expecting_password) {
1292 lprintf(CTDL_INFO, "IMAP: <password>\n");
1294 else if (bmstrcasestr(cmdbuf, " LOGIN ")) {
1295 lprintf(CTDL_INFO, "IMAP: LOGIN...\n");
1298 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1301 while (strlen(cmdbuf) < 5)
1302 strcat(cmdbuf, " ");
1304 /* strip off l/t whitespace and CRLF */
1305 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1306 cmdbuf[strlen(cmdbuf) - 1] = 0;
1307 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1308 cmdbuf[strlen(cmdbuf) - 1] = 0;
1311 /* If we're in the middle of a multi-line command, handle that */
1312 if (IMAP->authstate == imap_as_expecting_username) {
1313 imap_auth_login_user(cmdbuf);
1316 if (IMAP->authstate == imap_as_expecting_password) {
1317 imap_auth_login_pass(cmdbuf);
1321 /* Ok, at this point we're in normal command mode. The first thing
1322 * we do is print any incoming pages (yeah! we really do!)
1324 imap_print_instant_messages();
1327 * Before processing the command that was just entered... if we happen
1328 * to have a folder selected, we'd like to rescan that folder for new
1329 * messages, and for deletions/changes of existing messages. This
1330 * could probably be optimized somehow, but IMAP sucks...
1332 if (IMAP->selected) {
1333 imap_rescan_msgids();
1336 /* Now for the command set. */
1338 /* Grab the tag, command, and parameters. Check syntax. */
1339 num_parms = imap_parameterize(parms, cmdbuf);
1340 if (num_parms < 2) {
1341 cprintf("BAD syntax error\r\n");
1344 /* The commands below may be executed in any state */
1346 else if ((!strcasecmp(parms[1], "NOOP"))
1347 || (!strcasecmp(parms[1], "CHECK"))) {
1348 cprintf("%s OK No operation\r\n",
1352 else if (!strcasecmp(parms[1], "ID")) {
1353 imap_id(num_parms, parms);
1357 else if (!strcasecmp(parms[1], "LOGOUT")) {
1358 if (IMAP->selected) {
1359 imap_do_expunge(); /* yes, we auto-expunge */
1361 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1362 cprintf("%s OK Citadel IMAP session ended.\r\n",
1368 else if (!strcasecmp(parms[1], "LOGIN")) {
1369 imap_login(num_parms, parms);
1372 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1373 imap_authenticate(num_parms, parms);
1376 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1377 imap_capability(num_parms, parms);
1380 else if (!strcasecmp(parms[1], "STARTTLS")) {
1381 imap_starttls(num_parms, parms);
1384 else if (!CC->logged_in) {
1385 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1388 /* The commans below require a logged-in state */
1390 else if (!strcasecmp(parms[1], "SELECT")) {
1391 imap_select(num_parms, parms);
1394 else if (!strcasecmp(parms[1], "EXAMINE")) {
1395 imap_select(num_parms, parms);
1398 else if (!strcasecmp(parms[1], "LSUB")) {
1399 imap_list(num_parms, parms);
1402 else if (!strcasecmp(parms[1], "LIST")) {
1403 imap_list(num_parms, parms);
1406 else if (!strcasecmp(parms[1], "CREATE")) {
1407 imap_create(num_parms, parms);
1410 else if (!strcasecmp(parms[1], "DELETE")) {
1411 imap_delete(num_parms, parms);
1414 else if (!strcasecmp(parms[1], "RENAME")) {
1415 imap_rename(num_parms, parms);
1418 else if (!strcasecmp(parms[1], "STATUS")) {
1419 imap_status(num_parms, parms);
1422 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1423 imap_subscribe(num_parms, parms);
1426 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1427 imap_unsubscribe(num_parms, parms);
1430 else if (!strcasecmp(parms[1], "APPEND")) {
1431 imap_append(num_parms, parms);
1434 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1435 imap_namespace(num_parms, parms);
1438 else if (!strcasecmp(parms[1], "SETACL")) {
1439 imap_setacl(num_parms, parms);
1442 else if (!strcasecmp(parms[1], "DELETEACL")) {
1443 imap_deleteacl(num_parms, parms);
1446 else if (!strcasecmp(parms[1], "GETACL")) {
1447 imap_getacl(num_parms, parms);
1450 else if (!strcasecmp(parms[1], "LISTRIGHTS")) {
1451 imap_listrights(num_parms, parms);
1454 else if (!strcasecmp(parms[1], "MYRIGHTS")) {
1455 imap_myrights(num_parms, parms);
1458 else if (!strcasecmp(parms[1], "GETMETADATA")) {
1459 imap_getmetadata(num_parms, parms);
1462 else if (!strcasecmp(parms[1], "SETMETADATA")) {
1463 imap_setmetadata(num_parms, parms);
1466 else if (IMAP->selected == 0) {
1467 cprintf("%s BAD no folder selected\r\n", parms[0]);
1470 /* The commands below require the SELECT state on a mailbox */
1472 else if (!strcasecmp(parms[1], "FETCH")) {
1473 imap_fetch(num_parms, parms);
1476 else if ((!strcasecmp(parms[1], "UID"))
1477 && (!strcasecmp(parms[2], "FETCH"))) {
1478 imap_uidfetch(num_parms, parms);
1481 else if (!strcasecmp(parms[1], "SEARCH")) {
1482 imap_search(num_parms, parms);
1485 else if ((!strcasecmp(parms[1], "UID"))
1486 && (!strcasecmp(parms[2], "SEARCH"))) {
1487 imap_uidsearch(num_parms, parms);
1490 else if (!strcasecmp(parms[1], "STORE")) {
1491 imap_store(num_parms, parms);
1494 else if ((!strcasecmp(parms[1], "UID"))
1495 && (!strcasecmp(parms[2], "STORE"))) {
1496 imap_uidstore(num_parms, parms);
1499 else if (!strcasecmp(parms[1], "COPY")) {
1500 imap_copy(num_parms, parms);
1503 else if ((!strcasecmp(parms[1], "UID"))
1504 && (!strcasecmp(parms[2], "COPY"))) {
1505 imap_uidcopy(num_parms, parms);
1508 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1509 imap_expunge(num_parms, parms);
1512 else if (!strcasecmp(parms[1], "CLOSE")) {
1513 imap_close(num_parms, parms);
1516 /* End of commands. If we get here, the command is either invalid
1521 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1524 /* If the client transmitted a message we can free it now */
1525 imap_free_transmitted_message();
1527 gettimeofday(&tv2, NULL);
1528 total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1529 lprintf(CTDL_DEBUG, "IMAP command completed in %ld.%ld seconds\n",
1530 (total_time / 1000000),
1531 (total_time % 1000000)
1537 * This function is called to register the IMAP extension with Citadel.
1539 char *serv_imap_init(void)
1541 CtdlRegisterServiceHook(config.c_imap_port,
1542 NULL, imap_greeting, imap_command_loop, NULL);
1544 CtdlRegisterServiceHook(config.c_imaps_port,
1545 NULL, imaps_greeting, imap_command_loop, NULL);
1547 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);