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 "citserver.h"
49 #include "internet_addressing.h"
50 #include "serv_imap.h"
51 #include "imap_tools.h"
52 #include "imap_list.h"
53 #include "imap_fetch.h"
54 #include "imap_search.h"
55 #include "imap_store.h"
57 #include "imap_metadata.h"
58 #include "imap_misc.h"
61 #include "serv_crypto.h"
65 #include "ctdl_module.h"
68 /* imap_rename() uses this struct containing list of rooms to rename */
71 char irl_oldroom[ROOMNAMELEN];
72 char irl_newroom[ROOMNAMELEN];
76 /* Data which is passed between imap_rename() and imap_rename_backend() */
85 * If there is a message ID map in memory, free it
87 void imap_free_msgids(void)
89 if (IMAP->msgids != NULL) {
95 if (IMAP->flags != NULL) {
99 IMAP->last_mtime = (-1);
104 * If there is a transmitted message in memory, free it
106 void imap_free_transmitted_message(void)
108 if (IMAP->transmitted_message != NULL) {
109 free(IMAP->transmitted_message);
110 IMAP->transmitted_message = NULL;
111 IMAP->transmitted_length = 0;
117 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
118 * sets stored in the visit record for this user/room. Note that we have
119 * to parse each sequence set manually here, because calling the utility
120 * function is_msg_in_sequence_set() over and over again is too expensive.
122 * first_msg should be set to 0 to rescan the flags for every message in the
123 * room, or some other value if we're only interested in an incremental
126 void imap_set_seen_flags(int first_msg)
132 char setstr[64], lostr[64], histr[64];
135 if (IMAP->num_msgs < 1) return;
136 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
138 for (i = first_msg; i < IMAP->num_msgs; ++i) {
139 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
140 IMAP->flags[i] |= IMAP_RECENT;
141 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
145 * Do the "\Seen" flag.
146 * (Any message not "\Seen" is considered "\Recent".)
148 num_sets = num_tokens(vbuf.v_seen, ',');
149 for (s=0; s<num_sets; ++s) {
150 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
152 extract_token(lostr, setstr, 0, ':', sizeof lostr);
153 if (num_tokens(setstr, ':') >= 2) {
154 extract_token(histr, setstr, 1, ':', sizeof histr);
155 if (!strcmp(histr, "*")) {
156 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
160 strcpy(histr, lostr);
165 for (i = first_msg; i < IMAP->num_msgs; ++i) {
166 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
167 IMAP->flags[i] |= IMAP_SEEN;
168 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
173 /* Do the ANSWERED flag */
174 num_sets = num_tokens(vbuf.v_answered, ',');
175 for (s=0; s<num_sets; ++s) {
176 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
178 extract_token(lostr, setstr, 0, ':', sizeof lostr);
179 if (num_tokens(setstr, ':') >= 2) {
180 extract_token(histr, setstr, 1, ':', sizeof histr);
181 if (!strcmp(histr, "*")) {
182 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
186 strcpy(histr, lostr);
191 for (i = first_msg; i < IMAP->num_msgs; ++i) {
192 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
193 IMAP->flags[i] |= IMAP_ANSWERED;
203 * Back end for imap_load_msgids()
205 * Optimization: instead of calling realloc() to add each message, we
206 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
207 * allows the mapping to proceed much faster.
209 void imap_add_single_msgid(long msgnum, void *userdata)
213 if (IMAP->num_msgs > IMAP->num_alloc) {
214 IMAP->num_alloc += REALLOC_INCREMENT;
215 IMAP->msgids = realloc(IMAP->msgids,
216 (IMAP->num_alloc * sizeof(long)) );
217 IMAP->flags = realloc(IMAP->flags,
218 (IMAP->num_alloc * sizeof(long)) );
220 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
221 IMAP->flags[IMAP->num_msgs - 1] = 0;
227 * Set up a message ID map for the current room (folder)
229 void imap_load_msgids(void)
231 struct cdbdata *cdbfr;
233 if (IMAP->selected == 0) {
235 "imap_load_msgids() can't run; no room selected\n");
239 imap_free_msgids(); /* If there was already a map, free it */
241 /* Load the message list */
242 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
244 IMAP->msgids = malloc(cdbfr->len);
245 memcpy(IMAP->msgids, cdbfr->ptr, cdbfr->len);
246 IMAP->num_msgs = cdbfr->len / sizeof(long);
247 IMAP->num_alloc = cdbfr->len / sizeof(long);
251 if (IMAP->num_msgs) {
252 IMAP->flags = malloc(IMAP->num_alloc * sizeof(long));
253 memset(IMAP->flags, 0, (IMAP->num_alloc * sizeof(long)) );
256 imap_set_seen_flags(0);
261 * Re-scan the selected room (folder) and see if it's been changed at all
263 void imap_rescan_msgids(void)
266 int original_num_msgs = 0;
267 long original_highest = 0L;
269 int message_still_exists;
270 struct cdbdata *cdbfr;
271 long *msglist = NULL;
275 if (IMAP->selected == 0) {
277 "imap_load_msgids() can't run; no room selected\n");
282 * Check to see if the room's contents have changed.
283 * If not, we can avoid this rescan.
285 getroom(&CC->room, CC->room.QRname);
286 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
290 /* Load the *current* message list from disk, so we can compare it
291 * to what we have in memory.
293 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
295 msglist = malloc(cdbfr->len);
296 if (msglist == NULL) {
297 lprintf(CTDL_CRIT, "malloc() failed\n");
300 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
301 num_msgs = cdbfr->len / sizeof(long);
308 * Check to see if any of the messages we know about have been expunged
310 if (IMAP->num_msgs > 0) {
312 for (i = 0; i < IMAP->num_msgs; ++i) {
314 message_still_exists = 0;
316 for (j = jstart; j < num_msgs; ++j) {
317 if (msglist[j] == IMAP->msgids[i]) {
318 message_still_exists = 1;
325 if (message_still_exists == 0) {
326 cprintf("* %d EXPUNGE\r\n", i + 1);
328 /* Here's some nice stupid nonsense. When a
329 * message is expunged, we have to slide all
330 * the existing messages up in the message
334 memcpy(&IMAP->msgids[i],
335 &IMAP->msgids[i + 1],
337 (IMAP->num_msgs - i)));
338 memcpy(&IMAP->flags[i],
341 (IMAP->num_msgs - i)));
350 * Remember how many messages were here before we re-scanned.
352 original_num_msgs = IMAP->num_msgs;
353 if (IMAP->num_msgs > 0) {
354 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
356 original_highest = 0L;
360 * Now peruse the room for *new* messages only.
363 for (j = 0; j < num_msgs; ++j) {
364 if (msglist[j] > original_highest) {
365 imap_add_single_msgid(msglist[j], NULL);
369 imap_set_seen_flags(original_num_msgs);
372 * If new messages have arrived, tell the client about them.
374 if (IMAP->num_msgs > original_num_msgs) {
376 for (j = 0; j < num_msgs; ++j) {
377 if (IMAP->flags[j] & IMAP_RECENT) {
382 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
383 cprintf("* %d RECENT\r\n", num_recent);
389 IMAP->last_mtime = CC->room.QRmtime;
399 * This cleanup function blows away the temporary memory and files used by
402 void imap_cleanup_function(void)
405 /* Don't do this stuff if this is not a IMAP session! */
406 if (CC->h_command_function != imap_command_loop)
409 /* If there is a mailbox selected, auto-expunge it. */
410 if (IMAP->selected) {
414 lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
416 imap_free_transmitted_message();
418 if (IMAP->cached_rfc822_data != NULL) {
419 free(IMAP->cached_rfc822_data);
420 IMAP->cached_rfc822_data = NULL;
421 IMAP->cached_rfc822_msgnum = (-1);
422 IMAP->cached_rfc822_withbody = 0;
425 if (IMAP->cached_body != NULL) {
426 free(IMAP->cached_body);
427 IMAP->cached_body = NULL;
428 IMAP->cached_body_len = 0;
429 IMAP->cached_bodymsgnum = (-1);
433 lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
438 * Does the actual work of the CAPABILITY command (because we need to
439 * output this stuff in other places as well)
441 void imap_output_capability_string(void) {
442 cprintf("CAPABILITY IMAP4REV1 NAMESPACE ID ACL AUTH=PLAIN AUTH=LOGIN");
445 if (!CC->redirect_ssl) cprintf(" STARTTLS");
448 /* We are building a partial implementation of METADATA for the sole purpose
449 * of interoperating with the ical/vcard version of the Bynari Insight Connector.
450 * If you were expecting something else, comment out one or both of these
451 * extension advertisements.
453 cprintf(" METADATA");
454 /* cprintf(" LIST-EXTENDED"); */
458 * implements the CAPABILITY command
460 void imap_capability(int num_parms, char *parms[])
463 imap_output_capability_string();
465 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
471 * Implements the ID command (specified by RFC2971)
473 * We ignore the client-supplied information, and output a NIL response.
474 * Although this is technically a valid implementation of the extension, it
475 * is quite useless. It exists only so that we may see which clients are
476 * making use of this extension.
479 void imap_id(int num_parms, char *parms[])
481 cprintf("* ID NIL\r\n");
482 cprintf("%s OK ID completed\r\n", parms[0]);
488 * Here's where our IMAP session begins its happy day.
490 void imap_greeting(void)
493 strcpy(CC->cs_clientname, "IMAP session");
494 IMAP = malloc(sizeof (struct citimap));
495 memset(IMAP, 0, sizeof(struct citimap));
496 IMAP->authstate = imap_as_normal;
497 IMAP->cached_rfc822_data = NULL;
498 IMAP->cached_rfc822_msgnum = (-1);
499 IMAP->cached_rfc822_withbody = 0;
502 imap_output_capability_string();
503 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
507 * IMAPS is just like IMAP, except it goes crypto right away.
510 void imaps_greeting(void) {
511 CtdlStartTLS(NULL, NULL, NULL);
518 * implements the LOGIN command (ordinary username/password login)
520 void imap_login(int num_parms, char *parms[])
522 if (num_parms != 4) {
523 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
527 if (CtdlLoginExistingUser(NULL, parms[2]) == login_ok) {
528 if (CtdlTryPassword(parms[3]) == pass_ok) {
529 cprintf("%s OK [", parms[0]);
530 imap_output_capability_string();
531 cprintf("] Hello, %s\r\n", CC->user.fullname);
536 cprintf("%s BAD Login incorrect\r\n", parms[0]);
541 * Implements the AUTHENTICATE command
543 void imap_authenticate(int num_parms, char *parms[])
547 if (num_parms != 3) {
548 cprintf("%s BAD incorrect number of parameters\r\n",
554 cprintf("%s BAD Already logged in.\r\n", parms[0]);
558 if (!strcasecmp(parms[2], "LOGIN")) {
559 CtdlEncodeBase64(buf, "Username:", 9);
560 cprintf("+ %s\r\n", buf);
561 IMAP->authstate = imap_as_expecting_username;
562 strcpy(IMAP->authseq, parms[0]);
566 if (!strcasecmp(parms[2], "PLAIN")) {
567 // CtdlEncodeBase64(buf, "Username:", 9);
568 // cprintf("+ %s\r\n", buf);
570 IMAP->authstate = imap_as_expecting_plainauth;
571 strcpy(IMAP->authseq, parms[0]);
576 cprintf("%s NO AUTHENTICATE %s failed\r\n",
581 void imap_auth_plain(char *cmd)
583 char decoded_authstring[1024];
589 CtdlDecodeBase64(decoded_authstring, cmd, strlen(cmd));
590 safestrncpy(ident, decoded_authstring, sizeof ident);
591 safestrncpy(user, &decoded_authstring[strlen(ident) + 1], sizeof user);
592 safestrncpy(pass, &decoded_authstring[strlen(ident) + strlen(user) + 2], sizeof pass);
594 IMAP->authstate = imap_as_normal;
596 if (strlen(ident) > 0) {
597 result = CtdlLoginExistingUser(user, ident);
600 result = CtdlLoginExistingUser(NULL, user);
603 if (result == login_ok) {
604 if (CtdlTryPassword(pass) == pass_ok) {
605 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
609 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
612 void imap_auth_login_user(char *cmd)
616 CtdlDecodeBase64(buf, cmd, SIZ);
617 CtdlLoginExistingUser(NULL, buf);
618 CtdlEncodeBase64(buf, "Password:", 9);
619 cprintf("+ %s\r\n", buf);
620 IMAP->authstate = imap_as_expecting_password;
624 void imap_auth_login_pass(char *cmd)
628 CtdlDecodeBase64(buf, cmd, SIZ);
629 if (CtdlTryPassword(buf) == pass_ok) {
630 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
632 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
634 IMAP->authstate = imap_as_normal;
640 * implements the STARTTLS command (Citadel API version)
643 void imap_starttls(int num_parms, char *parms[])
645 char ok_response[SIZ];
646 char nosup_response[SIZ];
647 char error_response[SIZ];
650 "%s OK begin TLS negotiation now\r\n",
652 sprintf(nosup_response,
653 "%s NO TLS not supported here\r\n",
655 sprintf(error_response,
656 "%s BAD Internal error\r\n",
658 CtdlStartTLS(ok_response, nosup_response, error_response);
664 * implements the SELECT command
666 void imap_select(int num_parms, char *parms[])
669 char augmented_roomname[ROOMNAMELEN];
673 struct ctdlroom QRscratch;
679 /* Convert the supplied folder name to a roomname */
680 i = imap_roomname(towhere, sizeof towhere, parms[2]);
682 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
686 floornum = (i & 0x00ff);
687 roomflags = (i & 0xff00);
689 /* First try a regular match */
690 c = getroom(&QRscratch, towhere);
692 /* Then try a mailbox name match */
694 MailboxName(augmented_roomname, sizeof augmented_roomname,
696 c = getroom(&QRscratch, augmented_roomname);
698 strcpy(towhere, augmented_roomname);
701 /* If the room exists, check security/access */
703 /* See if there is an existing user/room relationship */
704 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
706 /* normal clients have to pass through security */
712 /* Fail here if no such room */
714 cprintf("%s NO ... no such room, or access denied\r\n",
719 /* If we already had some other folder selected, auto-expunge it */
723 * usergoto() formally takes us to the desired room, happily returning
724 * the number of messages and number of new messages.
726 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
727 usergoto(NULL, 0, 0, &msgs, &new);
730 if (!strcasecmp(parms[1], "EXAMINE")) {
737 IMAP->last_mtime = CC->room.QRmtime;
739 cprintf("* %d EXISTS\r\n", msgs);
740 cprintf("* %d RECENT\r\n", new);
742 cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
743 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
745 /* Note that \Deleted is a valid flag, but not a permanent flag,
746 * because we don't maintain its state across sessions. Citadel
747 * automatically expunges mailboxes when they are de-selected.
749 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
750 cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] "
751 "permanent flags\r\n");
753 cprintf("%s OK [%s] %s completed\r\n",
755 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
761 * Does the real work for expunge.
763 int imap_do_expunge(void)
766 int num_expunged = 0;
767 long *delmsgs = NULL;
770 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
771 if (IMAP->selected == 0) {
775 if (IMAP->num_msgs > 0) {
776 delmsgs = malloc(IMAP->num_msgs * sizeof(long));
777 for (i = 0; i < IMAP->num_msgs; ++i) {
778 if (IMAP->flags[i] & IMAP_DELETED) {
779 delmsgs[num_delmsgs++] = IMAP->msgids[i];
782 if (num_delmsgs > 0) {
783 CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
785 num_expunged += num_delmsgs;
789 if (num_expunged > 0) {
790 imap_rescan_msgids();
793 lprintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n",
794 num_expunged, CC->room.QRname);
795 return (num_expunged);
800 * implements the EXPUNGE command syntax
802 void imap_expunge(int num_parms, char *parms[])
804 int num_expunged = 0;
806 num_expunged = imap_do_expunge();
807 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
812 * implements the CLOSE command
814 void imap_close(int num_parms, char *parms[])
817 /* Yes, we always expunge on close. */
818 if (IMAP->selected) {
825 cprintf("%s OK CLOSE completed\r\n", parms[0]);
830 * Implements the NAMESPACE command.
832 void imap_namespace(int num_parms, char *parms[])
839 cprintf("* NAMESPACE ");
841 /* All personal folders are subordinate to INBOX. */
842 cprintf("((\"INBOX/\" \"/\")) ");
844 /* Other users' folders ... coming soon! FIXME */
847 /* Show all floors as shared namespaces. Neato! */
849 for (i = 0; i < MAXFLOORS; ++i) {
851 if (fl->f_flags & F_INUSE) {
852 if (floors > 0) cprintf(" ");
854 sprintf(buf, "%s/", fl->f_name);
862 /* Wind it up with a newline and a completion message. */
864 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
870 * Implements the CREATE command
873 void imap_create(int num_parms, char *parms[])
876 char roomname[ROOMNAMELEN];
882 if (strchr(parms[2], '\\') != NULL) {
883 cprintf("%s NO Invalid character in folder name\r\n",
885 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
889 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
891 cprintf("%s NO Invalid mailbox name or location\r\n",
893 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
896 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
897 flags = (ret & 0xff00); /* upper 8 bits = flags */
899 if (flags & IR_MAILBOX) {
900 if (strncasecmp(parms[2], "INBOX/", 6)) {
901 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
902 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
907 if (flags & IR_MAILBOX) {
908 newroomtype = 4; /* private mailbox */
909 newroomview = VIEW_MAILBOX;
911 newroomtype = 0; /* public folder */
912 newroomview = VIEW_BBS;
915 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
916 roomname, floornum, newroomtype);
918 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
920 /*** DO NOT CHANGE THIS ERROR MESSAGE IN ANY WAY! BYNARI CONNECTOR DEPENDS ON IT! ***/
921 cprintf("%s NO Mailbox already exists, or create failed\r\n", parms[0]);
923 cprintf("%s OK CREATE completed\r\n", parms[0]);
925 lprintf(CTDL_DEBUG, "imap_create() completed\n");
930 * Locate a room by its IMAP folder name, and check access to it.
931 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
933 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
936 char augmented_roomname[ROOMNAMELEN];
937 char roomname[ROOMNAMELEN];
939 struct ctdlroom QRscratch;
943 ret = imap_roomname(roomname, sizeof roomname, foldername);
948 /* First try a regular match */
949 c = getroom(&QRscratch, roomname);
951 /* Then try a mailbox name match */
953 MailboxName(augmented_roomname, sizeof augmented_roomname,
954 &CC->user, roomname);
955 c = getroom(&QRscratch, augmented_roomname);
957 strcpy(roomname, augmented_roomname);
960 /* If the room exists, check security/access */
962 /* See if there is an existing user/room relationship */
963 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
965 /* normal clients have to pass through security */
969 if ((zapped_ok) && (ra & UA_ZAPPED)) {
974 /* Fail here if no such room */
976 strcpy(returned_roomname, "");
979 strcpy(returned_roomname, QRscratch.QRname);
986 * Implements the STATUS command (sort of)
989 void imap_status(int num_parms, char *parms[])
992 char roomname[ROOMNAMELEN];
994 char savedroom[ROOMNAMELEN];
997 ret = imap_grabroom(roomname, parms[2], 0);
1000 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1006 * usergoto() formally takes us to the desired room, happily returning
1007 * the number of messages and number of new messages. (If another
1008 * folder is selected, save its name so we can return there!!!!!)
1010 if (IMAP->selected) {
1011 strcpy(savedroom, CC->room.QRname);
1013 usergoto(roomname, 0, 0, &msgs, &new);
1016 * Tell the client what it wants to know. In fact, tell it *more* than
1017 * it wants to know. We happily IGnore the supplied status data item
1018 * names and simply spew all possible data items. It's far easier to
1019 * code and probably saves us some processing time too.
1021 imap_mailboxname(buf, sizeof buf, &CC->room);
1022 cprintf("* STATUS ");
1024 cprintf(" (MESSAGES %d ", msgs);
1025 cprintf("RECENT %d ", new); /* Initially, new==recent */
1026 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1027 cprintf("UNSEEN %d)\r\n", new);
1030 * If another folder is selected, go back to that room so we can resume
1031 * our happy day without violent explosions.
1033 if (IMAP->selected) {
1034 usergoto(savedroom, 0, 0, &msgs, &new);
1038 * Oooh, look, we're done!
1040 cprintf("%s OK STATUS completed\r\n", parms[0]);
1046 * Implements the SUBSCRIBE command
1049 void imap_subscribe(int num_parms, char *parms[])
1052 char roomname[ROOMNAMELEN];
1053 char savedroom[ROOMNAMELEN];
1056 ret = imap_grabroom(roomname, parms[2], 1);
1059 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1067 * usergoto() formally takes us to the desired room, which has the side
1068 * effect of marking the room as not-zapped ... exactly the effect
1069 * we're looking for.
1071 if (IMAP->selected) {
1072 strcpy(savedroom, CC->room.QRname);
1074 usergoto(roomname, 0, 0, &msgs, &new);
1077 * If another folder is selected, go back to that room so we can resume
1078 * our happy day without violent explosions.
1080 if (IMAP->selected) {
1081 usergoto(savedroom, 0, 0, &msgs, &new);
1084 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1089 * Implements the UNSUBSCRIBE command
1092 void imap_unsubscribe(int num_parms, char *parms[])
1095 char roomname[ROOMNAMELEN];
1096 char savedroom[ROOMNAMELEN];
1099 ret = imap_grabroom(roomname, parms[2], 0);
1102 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1108 * usergoto() formally takes us to the desired room.
1110 if (IMAP->selected) {
1111 strcpy(savedroom, CC->room.QRname);
1113 usergoto(roomname, 0, 0, &msgs, &new);
1116 * Now make the API call to zap the room
1118 if (CtdlForgetThisRoom() == 0) {
1119 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1122 ("%s NO You may not unsubscribe from this folder.\r\n",
1127 * If another folder is selected, go back to that room so we can resume
1128 * our happy day without violent explosions.
1130 if (IMAP->selected) {
1131 usergoto(savedroom, 0, 0, &msgs, &new);
1138 * Implements the DELETE command
1141 void imap_delete(int num_parms, char *parms[])
1144 char roomname[ROOMNAMELEN];
1145 char savedroom[ROOMNAMELEN];
1148 ret = imap_grabroom(roomname, parms[2], 1);
1150 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1156 * usergoto() formally takes us to the desired room, happily returning
1157 * the number of messages and number of new messages. (If another
1158 * folder is selected, save its name so we can return there!!!!!)
1160 if (IMAP->selected) {
1161 strcpy(savedroom, CC->room.QRname);
1163 usergoto(roomname, 0, 0, &msgs, &new);
1166 * Now delete the room.
1168 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1169 schedule_room_for_deletion(&CC->room);
1170 cprintf("%s OK DELETE completed\r\n", parms[0]);
1172 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1176 * If another folder is selected, go back to that room so we can resume
1177 * our happy day without violent explosions.
1179 if (IMAP->selected) {
1180 usergoto(savedroom, 0, 0, &msgs, &new);
1186 * Back end function for imap_rename()
1188 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1190 char foldername[SIZ];
1191 char newfoldername[SIZ];
1192 char newroomname[ROOMNAMELEN];
1194 struct irl *irlp = NULL; /* scratch pointer */
1195 struct irlparms *irlparms;
1197 irlparms = (struct irlparms *) data;
1198 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1200 /* Rename subfolders */
1201 if ((!strncasecmp(foldername, irlparms->oldname,
1202 strlen(irlparms->oldname))
1203 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1205 sprintf(newfoldername, "%s/%s",
1207 &foldername[strlen(irlparms->oldname) + 1]
1210 newfloor = imap_roomname(newroomname,
1212 newfoldername) & 0xFF;
1214 irlp = (struct irl *) malloc(sizeof(struct irl));
1215 strcpy(irlp->irl_newroom, newroomname);
1216 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1217 irlp->irl_newfloor = newfloor;
1218 irlp->next = *(irlparms->irl);
1219 *(irlparms->irl) = irlp;
1225 * Implements the RENAME command
1228 void imap_rename(int num_parms, char *parms[])
1230 char old_room[ROOMNAMELEN];
1231 char new_room[ROOMNAMELEN];
1235 struct irl *irl = NULL; /* the list */
1236 struct irl *irlp = NULL; /* scratch pointer */
1237 struct irlparms irlparms;
1239 if (strchr(parms[3], '\\') != NULL) {
1240 cprintf("%s NO Invalid character in folder name\r\n",
1245 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1246 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1247 new_floor = (newr & 0xFF);
1249 r = CtdlRenameRoom(old_room, new_room, new_floor);
1251 if (r == crr_room_not_found) {
1252 cprintf("%s NO Could not locate this folder\r\n",
1256 if (r == crr_already_exists) {
1257 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1260 if (r == crr_noneditable) {
1261 cprintf("%s This folder is not editable.\r\n", parms[0]);
1264 if (r == crr_invalid_floor) {
1265 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1268 if (r == crr_access_denied) {
1269 cprintf("%s You do not have permission to edit "
1270 "this folder.\r\n", parms[0]);
1274 cprintf("%s NO Rename failed - undefined error %d\r\n",
1280 /* If this is the INBOX, then RFC2060 says we have to just move the
1281 * contents. In a Citadel environment it's easier to rename the room
1282 * (already did that) and create a new inbox.
1284 if (!strcasecmp(parms[2], "INBOX")) {
1285 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1288 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1290 irlparms.oldname = parms[2];
1291 irlparms.newname = parms[3];
1292 irlparms.irl = &irl;
1293 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1295 /* ... and now rename them. */
1296 while (irl != NULL) {
1297 r = CtdlRenameRoom(irl->irl_oldroom,
1301 /* FIXME handle error returns better */
1302 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n", r);
1310 cprintf("%s OK RENAME completed\r\n", parms[0]);
1317 * Main command loop for IMAP sessions.
1319 void imap_command_loop(void)
1324 struct timeval tv1, tv2;
1325 suseconds_t total_time = 0;
1327 gettimeofday(&tv1, NULL);
1328 CC->lastcmd = time(NULL);
1329 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1331 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1332 lprintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1337 if (IMAP->authstate == imap_as_expecting_password) {
1338 lprintf(CTDL_INFO, "IMAP: <password>\n");
1340 else if (IMAP->authstate == imap_as_expecting_plainauth) {
1341 lprintf(CTDL_INFO, "IMAP: <plain_auth>\n");
1343 else if (bmstrcasestr(cmdbuf, " LOGIN ")) {
1344 lprintf(CTDL_INFO, "IMAP: LOGIN...\n");
1347 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1350 while (strlen(cmdbuf) < 5)
1351 strcat(cmdbuf, " ");
1353 /* strip off l/t whitespace and CRLF */
1354 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1355 cmdbuf[strlen(cmdbuf) - 1] = 0;
1356 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1357 cmdbuf[strlen(cmdbuf) - 1] = 0;
1360 /* If we're in the middle of a multi-line command, handle that */
1361 if (IMAP->authstate == imap_as_expecting_username) {
1362 imap_auth_login_user(cmdbuf);
1365 if (IMAP->authstate == imap_as_expecting_plainauth) {
1366 imap_auth_plain(cmdbuf);
1369 if (IMAP->authstate == imap_as_expecting_password) {
1370 imap_auth_login_pass(cmdbuf);
1374 /* Ok, at this point we're in normal command mode. The first thing
1375 * we do is print any incoming pages (yeah! we really do!)
1377 imap_print_instant_messages();
1380 * Before processing the command that was just entered... if we happen
1381 * to have a folder selected, we'd like to rescan that folder for new
1382 * messages, and for deletions/changes of existing messages. This
1383 * could probably be optimized somehow, but IMAP sucks...
1385 if (IMAP->selected) {
1386 imap_rescan_msgids();
1389 /* Now for the command set. */
1391 /* Grab the tag, command, and parameters. Check syntax. */
1392 num_parms = imap_parameterize(parms, cmdbuf);
1393 if (num_parms < 2) {
1394 cprintf("BAD syntax error\r\n");
1397 /* The commands below may be executed in any state */
1399 else if ((!strcasecmp(parms[1], "NOOP"))
1400 || (!strcasecmp(parms[1], "CHECK"))) {
1401 cprintf("%s OK No operation\r\n",
1405 else if (!strcasecmp(parms[1], "ID")) {
1406 imap_id(num_parms, parms);
1410 else if (!strcasecmp(parms[1], "LOGOUT")) {
1411 if (IMAP->selected) {
1412 imap_do_expunge(); /* yes, we auto-expunge */
1414 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1415 cprintf("%s OK Citadel IMAP session ended.\r\n",
1421 else if (!strcasecmp(parms[1], "LOGIN")) {
1422 imap_login(num_parms, parms);
1425 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1426 imap_authenticate(num_parms, parms);
1429 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1430 imap_capability(num_parms, parms);
1433 else if (!strcasecmp(parms[1], "STARTTLS")) {
1434 imap_starttls(num_parms, parms);
1437 else if (!CC->logged_in) {
1438 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1441 /* The commans below require a logged-in state */
1443 else if (!strcasecmp(parms[1], "SELECT")) {
1444 imap_select(num_parms, parms);
1447 else if (!strcasecmp(parms[1], "EXAMINE")) {
1448 imap_select(num_parms, parms);
1451 else if (!strcasecmp(parms[1], "LSUB")) {
1452 imap_list(num_parms, parms);
1455 else if (!strcasecmp(parms[1], "LIST")) {
1456 imap_list(num_parms, parms);
1459 else if (!strcasecmp(parms[1], "CREATE")) {
1460 imap_create(num_parms, parms);
1463 else if (!strcasecmp(parms[1], "DELETE")) {
1464 imap_delete(num_parms, parms);
1467 else if (!strcasecmp(parms[1], "RENAME")) {
1468 imap_rename(num_parms, parms);
1471 else if (!strcasecmp(parms[1], "STATUS")) {
1472 imap_status(num_parms, parms);
1475 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1476 imap_subscribe(num_parms, parms);
1479 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1480 imap_unsubscribe(num_parms, parms);
1483 else if (!strcasecmp(parms[1], "APPEND")) {
1484 imap_append(num_parms, parms);
1487 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1488 imap_namespace(num_parms, parms);
1491 else if (!strcasecmp(parms[1], "SETACL")) {
1492 imap_setacl(num_parms, parms);
1495 else if (!strcasecmp(parms[1], "DELETEACL")) {
1496 imap_deleteacl(num_parms, parms);
1499 else if (!strcasecmp(parms[1], "GETACL")) {
1500 imap_getacl(num_parms, parms);
1503 else if (!strcasecmp(parms[1], "LISTRIGHTS")) {
1504 imap_listrights(num_parms, parms);
1507 else if (!strcasecmp(parms[1], "MYRIGHTS")) {
1508 imap_myrights(num_parms, parms);
1511 else if (!strcasecmp(parms[1], "GETMETADATA")) {
1512 imap_getmetadata(num_parms, parms);
1515 else if (!strcasecmp(parms[1], "SETMETADATA")) {
1516 imap_setmetadata(num_parms, parms);
1519 else if (IMAP->selected == 0) {
1520 cprintf("%s BAD no folder selected\r\n", parms[0]);
1523 /* The commands below require the SELECT state on a mailbox */
1525 else if (!strcasecmp(parms[1], "FETCH")) {
1526 imap_fetch(num_parms, parms);
1529 else if ((!strcasecmp(parms[1], "UID"))
1530 && (!strcasecmp(parms[2], "FETCH"))) {
1531 imap_uidfetch(num_parms, parms);
1534 else if (!strcasecmp(parms[1], "SEARCH")) {
1535 imap_search(num_parms, parms);
1538 else if ((!strcasecmp(parms[1], "UID"))
1539 && (!strcasecmp(parms[2], "SEARCH"))) {
1540 imap_uidsearch(num_parms, parms);
1543 else if (!strcasecmp(parms[1], "STORE")) {
1544 imap_store(num_parms, parms);
1547 else if ((!strcasecmp(parms[1], "UID"))
1548 && (!strcasecmp(parms[2], "STORE"))) {
1549 imap_uidstore(num_parms, parms);
1552 else if (!strcasecmp(parms[1], "COPY")) {
1553 imap_copy(num_parms, parms);
1556 else if ((!strcasecmp(parms[1], "UID"))
1557 && (!strcasecmp(parms[2], "COPY"))) {
1558 imap_uidcopy(num_parms, parms);
1561 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1562 imap_expunge(num_parms, parms);
1565 else if (!strcasecmp(parms[1], "CLOSE")) {
1566 imap_close(num_parms, parms);
1569 /* End of commands. If we get here, the command is either invalid
1574 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1577 /* If the client transmitted a message we can free it now */
1578 imap_free_transmitted_message();
1580 gettimeofday(&tv2, NULL);
1581 total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1582 lprintf(CTDL_DEBUG, "IMAP command completed in %ld.%ld seconds\n",
1583 (total_time / 1000000),
1584 (total_time % 1000000)
1590 * This function is called to register the IMAP extension with Citadel.
1592 CTDL_MODULE_INIT(imap)
1594 CtdlRegisterServiceHook(config.c_imap_port,
1595 NULL, imap_greeting, imap_command_loop, NULL);
1597 CtdlRegisterServiceHook(config.c_imaps_port,
1598 NULL, imaps_greeting, imap_command_loop, NULL);
1600 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1602 /* return our Subversion id for the Log */