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 "ctdl_module.h"
64 /* imap_rename() uses this struct containing list of rooms to rename */
67 char irl_oldroom[ROOMNAMELEN];
68 char irl_newroom[ROOMNAMELEN];
72 /* Data which is passed between imap_rename() and imap_rename_backend() */
81 * If there is a message ID map in memory, free it
83 void imap_free_msgids(void)
85 if (IMAP->msgids != NULL) {
91 if (IMAP->flags != NULL) {
95 IMAP->last_mtime = (-1);
100 * If there is a transmitted message in memory, free it
102 void imap_free_transmitted_message(void)
104 if (IMAP->transmitted_message != NULL) {
105 free(IMAP->transmitted_message);
106 IMAP->transmitted_message = NULL;
107 IMAP->transmitted_length = 0;
113 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
114 * sets stored in the visit record for this user/room. Note that we have
115 * to parse each sequence set manually here, because calling the utility
116 * function is_msg_in_sequence_set() over and over again is too expensive.
118 * first_msg should be set to 0 to rescan the flags for every message in the
119 * room, or some other value if we're only interested in an incremental
122 void imap_set_seen_flags(int first_msg)
128 char setstr[64], lostr[64], histr[64];
131 if (IMAP->num_msgs < 1) return;
132 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
134 for (i = first_msg; i < IMAP->num_msgs; ++i) {
135 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
136 IMAP->flags[i] |= IMAP_RECENT;
137 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
141 * Do the "\Seen" flag.
142 * (Any message not "\Seen" is considered "\Recent".)
144 num_sets = num_tokens(vbuf.v_seen, ',');
145 for (s=0; s<num_sets; ++s) {
146 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
148 extract_token(lostr, setstr, 0, ':', sizeof lostr);
149 if (num_tokens(setstr, ':') >= 2) {
150 extract_token(histr, setstr, 1, ':', sizeof histr);
151 if (!strcmp(histr, "*")) {
152 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
156 strcpy(histr, lostr);
161 for (i = first_msg; i < IMAP->num_msgs; ++i) {
162 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
163 IMAP->flags[i] |= IMAP_SEEN;
164 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
169 /* Do the ANSWERED flag */
170 num_sets = num_tokens(vbuf.v_answered, ',');
171 for (s=0; s<num_sets; ++s) {
172 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
174 extract_token(lostr, setstr, 0, ':', sizeof lostr);
175 if (num_tokens(setstr, ':') >= 2) {
176 extract_token(histr, setstr, 1, ':', sizeof histr);
177 if (!strcmp(histr, "*")) {
178 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
182 strcpy(histr, lostr);
187 for (i = first_msg; i < IMAP->num_msgs; ++i) {
188 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
189 IMAP->flags[i] |= IMAP_ANSWERED;
199 * Back end for imap_load_msgids()
201 * Optimization: instead of calling realloc() to add each message, we
202 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
203 * allows the mapping to proceed much faster.
205 void imap_add_single_msgid(long msgnum, void *userdata)
209 if (IMAP->num_msgs > IMAP->num_alloc) {
210 IMAP->num_alloc += REALLOC_INCREMENT;
211 IMAP->msgids = realloc(IMAP->msgids,
212 (IMAP->num_alloc * sizeof(long)) );
213 IMAP->flags = realloc(IMAP->flags,
214 (IMAP->num_alloc * sizeof(long)) );
216 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
217 IMAP->flags[IMAP->num_msgs - 1] = 0;
223 * Set up a message ID map for the current room (folder)
225 void imap_load_msgids(void)
227 struct cdbdata *cdbfr;
229 if (IMAP->selected == 0) {
231 "imap_load_msgids() can't run; no room selected\n");
235 imap_free_msgids(); /* If there was already a map, free it */
237 /* Load the message list */
238 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
240 IMAP->msgids = malloc(cdbfr->len);
241 memcpy(IMAP->msgids, cdbfr->ptr, cdbfr->len);
242 IMAP->num_msgs = cdbfr->len / sizeof(long);
243 IMAP->num_alloc = cdbfr->len / sizeof(long);
247 if (IMAP->num_msgs) {
248 IMAP->flags = malloc(IMAP->num_alloc * sizeof(long));
249 memset(IMAP->flags, 0, (IMAP->num_alloc * sizeof(long)) );
252 imap_set_seen_flags(0);
257 * Re-scan the selected room (folder) and see if it's been changed at all
259 void imap_rescan_msgids(void)
262 int original_num_msgs = 0;
263 long original_highest = 0L;
265 int message_still_exists;
266 struct cdbdata *cdbfr;
267 long *msglist = NULL;
271 if (IMAP->selected == 0) {
273 "imap_load_msgids() can't run; no room selected\n");
278 * Check to see if the room's contents have changed.
279 * If not, we can avoid this rescan.
281 getroom(&CC->room, CC->room.QRname);
282 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
286 /* Load the *current* message list from disk, so we can compare it
287 * to what we have in memory.
289 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
291 msglist = malloc(cdbfr->len);
292 if (msglist == NULL) {
293 lprintf(CTDL_CRIT, "malloc() failed\n");
296 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
297 num_msgs = cdbfr->len / sizeof(long);
304 * Check to see if any of the messages we know about have been expunged
306 if (IMAP->num_msgs > 0) {
308 for (i = 0; i < IMAP->num_msgs; ++i) {
310 message_still_exists = 0;
312 for (j = jstart; j < num_msgs; ++j) {
313 if (msglist[j] == IMAP->msgids[i]) {
314 message_still_exists = 1;
321 if (message_still_exists == 0) {
322 cprintf("* %d EXPUNGE\r\n", i + 1);
324 /* Here's some nice stupid nonsense. When a
325 * message is expunged, we have to slide all
326 * the existing messages up in the message
330 memcpy(&IMAP->msgids[i],
331 &IMAP->msgids[i + 1],
333 (IMAP->num_msgs - i)));
334 memcpy(&IMAP->flags[i],
337 (IMAP->num_msgs - i)));
346 * Remember how many messages were here before we re-scanned.
348 original_num_msgs = IMAP->num_msgs;
349 if (IMAP->num_msgs > 0) {
350 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
352 original_highest = 0L;
356 * Now peruse the room for *new* messages only.
359 for (j = 0; j < num_msgs; ++j) {
360 if (msglist[j] > original_highest) {
361 imap_add_single_msgid(msglist[j], NULL);
365 imap_set_seen_flags(original_num_msgs);
368 * If new messages have arrived, tell the client about them.
370 if (IMAP->num_msgs > original_num_msgs) {
372 for (j = 0; j < num_msgs; ++j) {
373 if (IMAP->flags[j] & IMAP_RECENT) {
378 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
379 cprintf("* %d RECENT\r\n", num_recent);
385 IMAP->last_mtime = CC->room.QRmtime;
395 * This cleanup function blows away the temporary memory and files used by
398 void imap_cleanup_function(void)
401 /* Don't do this stuff if this is not a IMAP session! */
402 if (CC->h_command_function != imap_command_loop)
405 /* If there is a mailbox selected, auto-expunge it. */
406 if (IMAP->selected) {
410 lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
412 imap_free_transmitted_message();
414 if (IMAP->cached_rfc822_data != NULL) {
415 free(IMAP->cached_rfc822_data);
416 IMAP->cached_rfc822_data = NULL;
417 IMAP->cached_rfc822_msgnum = (-1);
418 IMAP->cached_rfc822_withbody = 0;
421 if (IMAP->cached_body != NULL) {
422 free(IMAP->cached_body);
423 IMAP->cached_body = NULL;
424 IMAP->cached_body_len = 0;
425 IMAP->cached_bodymsgnum = (-1);
429 lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
434 * Does the actual work of the CAPABILITY command (because we need to
435 * output this stuff in other places as well)
437 void imap_output_capability_string(void) {
438 cprintf("CAPABILITY IMAP4REV1 NAMESPACE ID AUTH=PLAIN AUTH=LOGIN");
441 if (!CC->redirect_ssl) cprintf(" STARTTLS");
444 #ifndef DISABLE_IMAP_ACL
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.
509 void imaps_greeting(void) {
510 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
511 if (!CC->redirect_ssl) CC->kill_me = 1; /* kill session if no crypto */
517 * implements the LOGIN command (ordinary username/password login)
519 void imap_login(int num_parms, char *parms[])
521 if (num_parms != 4) {
522 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
526 if (CtdlLoginExistingUser(NULL, parms[2]) == login_ok) {
527 if (CtdlTryPassword(parms[3]) == pass_ok) {
528 cprintf("%s OK [", parms[0]);
529 imap_output_capability_string();
530 cprintf("] Hello, %s\r\n", CC->user.fullname);
535 cprintf("%s BAD Login incorrect\r\n", parms[0]);
540 * Implements the AUTHENTICATE command
542 void imap_authenticate(int num_parms, char *parms[])
546 if (num_parms != 3) {
547 cprintf("%s BAD incorrect number of parameters\r\n",
553 cprintf("%s BAD Already logged in.\r\n", parms[0]);
557 if (!strcasecmp(parms[2], "LOGIN")) {
558 CtdlEncodeBase64(buf, "Username:", 9);
559 cprintf("+ %s\r\n", buf);
560 IMAP->authstate = imap_as_expecting_username;
561 strcpy(IMAP->authseq, parms[0]);
565 if (!strcasecmp(parms[2], "PLAIN")) {
566 // CtdlEncodeBase64(buf, "Username:", 9);
567 // cprintf("+ %s\r\n", buf);
569 IMAP->authstate = imap_as_expecting_plainauth;
570 strcpy(IMAP->authseq, parms[0]);
575 cprintf("%s NO AUTHENTICATE %s failed\r\n",
580 void imap_auth_plain(char *cmd)
582 char decoded_authstring[1024];
588 CtdlDecodeBase64(decoded_authstring, cmd, strlen(cmd));
589 safestrncpy(ident, decoded_authstring, sizeof ident);
590 safestrncpy(user, &decoded_authstring[strlen(ident) + 1], sizeof user);
591 safestrncpy(pass, &decoded_authstring[strlen(ident) + strlen(user) + 2], sizeof pass);
593 IMAP->authstate = imap_as_normal;
595 if (!IsEmptyStr(ident)) {
596 result = CtdlLoginExistingUser(user, ident);
599 result = CtdlLoginExistingUser(NULL, user);
602 if (result == login_ok) {
603 if (CtdlTryPassword(pass) == pass_ok) {
604 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
608 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
611 void imap_auth_login_user(char *cmd)
615 CtdlDecodeBase64(buf, cmd, SIZ);
616 CtdlLoginExistingUser(NULL, buf);
617 CtdlEncodeBase64(buf, "Password:", 9);
618 cprintf("+ %s\r\n", buf);
619 IMAP->authstate = imap_as_expecting_password;
623 void imap_auth_login_pass(char *cmd)
627 CtdlDecodeBase64(buf, cmd, SIZ);
628 if (CtdlTryPassword(buf) == pass_ok) {
629 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
631 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
633 IMAP->authstate = imap_as_normal;
639 * implements the STARTTLS command (Citadel API version)
641 void imap_starttls(int num_parms, char *parms[])
643 char ok_response[SIZ];
644 char nosup_response[SIZ];
645 char error_response[SIZ];
648 "%s OK begin TLS negotiation now\r\n",
650 sprintf(nosup_response,
651 "%s NO TLS not supported here\r\n",
653 sprintf(error_response,
654 "%s BAD Internal error\r\n",
656 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
661 * implements the SELECT command
663 void imap_select(int num_parms, char *parms[])
666 char augmented_roomname[ROOMNAMELEN];
670 struct ctdlroom QRscratch;
676 /* Convert the supplied folder name to a roomname */
677 i = imap_roomname(towhere, sizeof towhere, parms[2]);
679 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
683 floornum = (i & 0x00ff);
684 roomflags = (i & 0xff00);
686 /* First try a regular match */
687 c = getroom(&QRscratch, towhere);
689 /* Then try a mailbox name match */
691 MailboxName(augmented_roomname, sizeof augmented_roomname,
693 c = getroom(&QRscratch, augmented_roomname);
695 strcpy(towhere, augmented_roomname);
698 /* If the room exists, check security/access */
700 /* See if there is an existing user/room relationship */
701 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
703 /* normal clients have to pass through security */
709 /* Fail here if no such room */
711 cprintf("%s NO ... no such room, or access denied\r\n",
716 /* If we already had some other folder selected, auto-expunge it */
720 * usergoto() formally takes us to the desired room, happily returning
721 * the number of messages and number of new messages.
723 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
724 usergoto(NULL, 0, 0, &msgs, &new);
727 if (!strcasecmp(parms[1], "EXAMINE")) {
734 IMAP->last_mtime = CC->room.QRmtime;
736 cprintf("* %d EXISTS\r\n", msgs);
737 cprintf("* %d RECENT\r\n", new);
739 cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
740 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
742 /* Note that \Deleted is a valid flag, but not a permanent flag,
743 * because we don't maintain its state across sessions. Citadel
744 * automatically expunges mailboxes when they are de-selected.
746 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
747 cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] "
748 "permanent flags\r\n");
750 cprintf("%s OK [%s] %s completed\r\n",
752 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
758 * Does the real work for expunge.
760 int imap_do_expunge(void)
763 int num_expunged = 0;
764 long *delmsgs = NULL;
767 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
768 if (IMAP->selected == 0) {
772 if (IMAP->num_msgs > 0) {
773 delmsgs = malloc(IMAP->num_msgs * sizeof(long));
774 for (i = 0; i < IMAP->num_msgs; ++i) {
775 if (IMAP->flags[i] & IMAP_DELETED) {
776 delmsgs[num_delmsgs++] = IMAP->msgids[i];
779 if (num_delmsgs > 0) {
780 CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
782 num_expunged += num_delmsgs;
786 if (num_expunged > 0) {
787 imap_rescan_msgids();
790 lprintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n",
791 num_expunged, CC->room.QRname);
792 return (num_expunged);
797 * implements the EXPUNGE command syntax
799 void imap_expunge(int num_parms, char *parms[])
801 int num_expunged = 0;
803 num_expunged = imap_do_expunge();
804 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
809 * implements the CLOSE command
811 void imap_close(int num_parms, char *parms[])
814 /* Yes, we always expunge on close. */
815 if (IMAP->selected) {
822 cprintf("%s OK CLOSE completed\r\n", parms[0]);
827 * Implements the NAMESPACE command.
829 void imap_namespace(int num_parms, char *parms[])
836 cprintf("* NAMESPACE ");
838 /* All personal folders are subordinate to INBOX. */
839 cprintf("((\"INBOX/\" \"/\")) ");
841 /* Other users' folders ... coming soon! FIXME */
844 /* Show all floors as shared namespaces. Neato! */
846 for (i = 0; i < MAXFLOORS; ++i) {
848 if (fl->f_flags & F_INUSE) {
849 if (floors > 0) cprintf(" ");
851 sprintf(buf, "%s/", fl->f_name);
859 /* Wind it up with a newline and a completion message. */
861 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
867 * Implements the CREATE command
870 void imap_create(int num_parms, char *parms[])
873 char roomname[ROOMNAMELEN];
879 if (strchr(parms[2], '\\') != NULL) {
880 cprintf("%s NO Invalid character in folder name\r\n",
882 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
886 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
888 cprintf("%s NO Invalid mailbox name or location\r\n",
890 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
893 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
894 flags = (ret & 0xff00); /* upper 8 bits = flags */
896 if (flags & IR_MAILBOX) {
897 if (strncasecmp(parms[2], "INBOX/", 6)) {
898 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
899 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
904 if (flags & IR_MAILBOX) {
905 newroomtype = 4; /* private mailbox */
906 newroomview = VIEW_MAILBOX;
908 newroomtype = 0; /* public folder */
909 newroomview = VIEW_BBS;
912 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
913 roomname, floornum, newroomtype);
915 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
917 /*** DO NOT CHANGE THIS ERROR MESSAGE IN ANY WAY! BYNARI CONNECTOR DEPENDS ON IT! ***/
918 cprintf("%s NO Mailbox already exists, or create failed\r\n", parms[0]);
920 cprintf("%s OK CREATE completed\r\n", parms[0]);
922 lprintf(CTDL_DEBUG, "imap_create() completed\n");
927 * Locate a room by its IMAP folder name, and check access to it.
928 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
930 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
933 char augmented_roomname[ROOMNAMELEN];
934 char roomname[ROOMNAMELEN];
936 struct ctdlroom QRscratch;
940 ret = imap_roomname(roomname, sizeof roomname, foldername);
945 /* First try a regular match */
946 c = getroom(&QRscratch, roomname);
948 /* Then try a mailbox name match */
950 MailboxName(augmented_roomname, sizeof augmented_roomname,
951 &CC->user, roomname);
952 c = getroom(&QRscratch, augmented_roomname);
954 strcpy(roomname, augmented_roomname);
957 /* If the room exists, check security/access */
959 /* See if there is an existing user/room relationship */
960 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
962 /* normal clients have to pass through security */
966 if ((zapped_ok) && (ra & UA_ZAPPED)) {
971 /* Fail here if no such room */
973 strcpy(returned_roomname, "");
976 strcpy(returned_roomname, QRscratch.QRname);
983 * Implements the STATUS command (sort of)
986 void imap_status(int num_parms, char *parms[])
989 char roomname[ROOMNAMELEN];
991 char savedroom[ROOMNAMELEN];
994 ret = imap_grabroom(roomname, parms[2], 0);
997 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1003 * usergoto() formally takes us to the desired room, happily returning
1004 * the number of messages and number of new messages. (If another
1005 * folder is selected, save its name so we can return there!!!!!)
1007 if (IMAP->selected) {
1008 strcpy(savedroom, CC->room.QRname);
1010 usergoto(roomname, 0, 0, &msgs, &new);
1013 * Tell the client what it wants to know. In fact, tell it *more* than
1014 * it wants to know. We happily IGnore the supplied status data item
1015 * names and simply spew all possible data items. It's far easier to
1016 * code and probably saves us some processing time too.
1018 imap_mailboxname(buf, sizeof buf, &CC->room);
1019 cprintf("* STATUS ");
1021 cprintf(" (MESSAGES %d ", msgs);
1022 cprintf("RECENT %d ", new); /* Initially, new==recent */
1023 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1024 cprintf("UNSEEN %d)\r\n", new);
1027 * If another folder is selected, go back to that room so we can resume
1028 * our happy day without violent explosions.
1030 if (IMAP->selected) {
1031 usergoto(savedroom, 0, 0, &msgs, &new);
1035 * Oooh, look, we're done!
1037 cprintf("%s OK STATUS completed\r\n", parms[0]);
1043 * Implements the SUBSCRIBE command
1046 void imap_subscribe(int num_parms, char *parms[])
1049 char roomname[ROOMNAMELEN];
1050 char savedroom[ROOMNAMELEN];
1053 ret = imap_grabroom(roomname, parms[2], 1);
1056 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1064 * usergoto() formally takes us to the desired room, which has the side
1065 * effect of marking the room as not-zapped ... exactly the effect
1066 * we're looking for.
1068 if (IMAP->selected) {
1069 strcpy(savedroom, CC->room.QRname);
1071 usergoto(roomname, 0, 0, &msgs, &new);
1074 * If another folder is selected, go back to that room so we can resume
1075 * our happy day without violent explosions.
1077 if (IMAP->selected) {
1078 usergoto(savedroom, 0, 0, &msgs, &new);
1081 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1086 * Implements the UNSUBSCRIBE command
1089 void imap_unsubscribe(int num_parms, char *parms[])
1092 char roomname[ROOMNAMELEN];
1093 char savedroom[ROOMNAMELEN];
1096 ret = imap_grabroom(roomname, parms[2], 0);
1099 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1105 * usergoto() formally takes us to the desired room.
1107 if (IMAP->selected) {
1108 strcpy(savedroom, CC->room.QRname);
1110 usergoto(roomname, 0, 0, &msgs, &new);
1113 * Now make the API call to zap the room
1115 if (CtdlForgetThisRoom() == 0) {
1116 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1119 ("%s NO You may not unsubscribe from this folder.\r\n",
1124 * If another folder is selected, go back to that room so we can resume
1125 * our happy day without violent explosions.
1127 if (IMAP->selected) {
1128 usergoto(savedroom, 0, 0, &msgs, &new);
1135 * Implements the DELETE command
1138 void imap_delete(int num_parms, char *parms[])
1141 char roomname[ROOMNAMELEN];
1142 char savedroom[ROOMNAMELEN];
1145 ret = imap_grabroom(roomname, parms[2], 1);
1147 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1153 * usergoto() formally takes us to the desired room, happily returning
1154 * the number of messages and number of new messages. (If another
1155 * folder is selected, save its name so we can return there!!!!!)
1157 if (IMAP->selected) {
1158 strcpy(savedroom, CC->room.QRname);
1160 usergoto(roomname, 0, 0, &msgs, &new);
1163 * Now delete the room.
1165 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1166 schedule_room_for_deletion(&CC->room);
1167 cprintf("%s OK DELETE completed\r\n", parms[0]);
1169 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1173 * If another folder is selected, go back to that room so we can resume
1174 * our happy day without violent explosions.
1176 if (IMAP->selected) {
1177 usergoto(savedroom, 0, 0, &msgs, &new);
1183 * Back end function for imap_rename()
1185 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1187 char foldername[SIZ];
1188 char newfoldername[SIZ];
1189 char newroomname[ROOMNAMELEN];
1191 struct irl *irlp = NULL; /* scratch pointer */
1192 struct irlparms *irlparms;
1194 irlparms = (struct irlparms *) data;
1195 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1197 /* Rename subfolders */
1198 if ((!strncasecmp(foldername, irlparms->oldname,
1199 strlen(irlparms->oldname))
1200 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1202 sprintf(newfoldername, "%s/%s",
1204 &foldername[strlen(irlparms->oldname) + 1]
1207 newfloor = imap_roomname(newroomname,
1209 newfoldername) & 0xFF;
1211 irlp = (struct irl *) malloc(sizeof(struct irl));
1212 strcpy(irlp->irl_newroom, newroomname);
1213 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1214 irlp->irl_newfloor = newfloor;
1215 irlp->next = *(irlparms->irl);
1216 *(irlparms->irl) = irlp;
1222 * Implements the RENAME command
1225 void imap_rename(int num_parms, char *parms[])
1227 char old_room[ROOMNAMELEN];
1228 char new_room[ROOMNAMELEN];
1232 struct irl *irl = NULL; /* the list */
1233 struct irl *irlp = NULL; /* scratch pointer */
1234 struct irlparms irlparms;
1236 if (strchr(parms[3], '\\') != NULL) {
1237 cprintf("%s NO Invalid character in folder name\r\n",
1242 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1243 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1244 new_floor = (newr & 0xFF);
1246 r = CtdlRenameRoom(old_room, new_room, new_floor);
1248 if (r == crr_room_not_found) {
1249 cprintf("%s NO Could not locate this folder\r\n",
1253 if (r == crr_already_exists) {
1254 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1257 if (r == crr_noneditable) {
1258 cprintf("%s This folder is not editable.\r\n", parms[0]);
1261 if (r == crr_invalid_floor) {
1262 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1265 if (r == crr_access_denied) {
1266 cprintf("%s You do not have permission to edit "
1267 "this folder.\r\n", parms[0]);
1271 cprintf("%s NO Rename failed - undefined error %d\r\n",
1277 /* If this is the INBOX, then RFC2060 says we have to just move the
1278 * contents. In a Citadel environment it's easier to rename the room
1279 * (already did that) and create a new inbox.
1281 if (!strcasecmp(parms[2], "INBOX")) {
1282 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1285 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1287 irlparms.oldname = parms[2];
1288 irlparms.newname = parms[3];
1289 irlparms.irl = &irl;
1290 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1292 /* ... and now rename them. */
1293 while (irl != NULL) {
1294 r = CtdlRenameRoom(irl->irl_oldroom,
1298 /* FIXME handle error returns better */
1299 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n", r);
1307 cprintf("%s OK RENAME completed\r\n", parms[0]);
1314 * Main command loop for IMAP sessions.
1316 void imap_command_loop(void)
1321 struct timeval tv1, tv2;
1322 suseconds_t total_time = 0;
1324 gettimeofday(&tv1, NULL);
1325 CC->lastcmd = time(NULL);
1326 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1328 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1329 lprintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1334 if (IMAP->authstate == imap_as_expecting_password) {
1335 lprintf(CTDL_INFO, "IMAP: <password>\n");
1337 else if (IMAP->authstate == imap_as_expecting_plainauth) {
1338 lprintf(CTDL_INFO, "IMAP: <plain_auth>\n");
1340 else if (bmstrcasestr(cmdbuf, " LOGIN ")) {
1341 lprintf(CTDL_INFO, "IMAP: LOGIN...\n");
1344 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1347 while (strlen(cmdbuf) < 5)
1348 strcat(cmdbuf, " ");
1350 /* strip off l/t whitespace and CRLF */
1351 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1352 cmdbuf[strlen(cmdbuf) - 1] = 0;
1353 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1354 cmdbuf[strlen(cmdbuf) - 1] = 0;
1357 /* If we're in the middle of a multi-line command, handle that */
1358 if (IMAP->authstate == imap_as_expecting_username) {
1359 imap_auth_login_user(cmdbuf);
1362 if (IMAP->authstate == imap_as_expecting_plainauth) {
1363 imap_auth_plain(cmdbuf);
1366 if (IMAP->authstate == imap_as_expecting_password) {
1367 imap_auth_login_pass(cmdbuf);
1371 /* Ok, at this point we're in normal command mode. The first thing
1372 * we do is print any incoming pages (yeah! we really do!)
1374 imap_print_instant_messages();
1377 * Before processing the command that was just entered... if we happen
1378 * to have a folder selected, we'd like to rescan that folder for new
1379 * messages, and for deletions/changes of existing messages. This
1380 * could probably be optimized somehow, but IMAP sucks...
1382 if (IMAP->selected) {
1383 imap_rescan_msgids();
1386 /* Now for the command set. */
1388 /* Grab the tag, command, and parameters. Check syntax. */
1389 num_parms = imap_parameterize(parms, cmdbuf);
1390 if (num_parms < 2) {
1391 cprintf("BAD syntax error\r\n");
1394 /* The commands below may be executed in any state */
1396 else if ((!strcasecmp(parms[1], "NOOP"))
1397 || (!strcasecmp(parms[1], "CHECK"))) {
1398 cprintf("%s OK No operation\r\n",
1402 else if (!strcasecmp(parms[1], "ID")) {
1403 imap_id(num_parms, parms);
1407 else if (!strcasecmp(parms[1], "LOGOUT")) {
1408 if (IMAP->selected) {
1409 imap_do_expunge(); /* yes, we auto-expunge */
1411 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1412 cprintf("%s OK Citadel IMAP session ended.\r\n",
1418 else if (!strcasecmp(parms[1], "LOGIN")) {
1419 imap_login(num_parms, parms);
1422 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1423 imap_authenticate(num_parms, parms);
1426 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1427 imap_capability(num_parms, parms);
1430 else if (!strcasecmp(parms[1], "STARTTLS")) {
1431 imap_starttls(num_parms, parms);
1434 else if (!CC->logged_in) {
1435 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1438 /* The commans below require a logged-in state */
1440 else if (!strcasecmp(parms[1], "SELECT")) {
1441 imap_select(num_parms, parms);
1444 else if (!strcasecmp(parms[1], "EXAMINE")) {
1445 imap_select(num_parms, parms);
1448 else if (!strcasecmp(parms[1], "LSUB")) {
1449 imap_list(num_parms, parms);
1452 else if (!strcasecmp(parms[1], "LIST")) {
1453 imap_list(num_parms, parms);
1456 else if (!strcasecmp(parms[1], "CREATE")) {
1457 imap_create(num_parms, parms);
1460 else if (!strcasecmp(parms[1], "DELETE")) {
1461 imap_delete(num_parms, parms);
1464 else if (!strcasecmp(parms[1], "RENAME")) {
1465 imap_rename(num_parms, parms);
1468 else if (!strcasecmp(parms[1], "STATUS")) {
1469 imap_status(num_parms, parms);
1472 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1473 imap_subscribe(num_parms, parms);
1476 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1477 imap_unsubscribe(num_parms, parms);
1480 else if (!strcasecmp(parms[1], "APPEND")) {
1481 imap_append(num_parms, parms);
1484 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1485 imap_namespace(num_parms, parms);
1488 else if (!strcasecmp(parms[1], "SETACL")) {
1489 imap_setacl(num_parms, parms);
1492 else if (!strcasecmp(parms[1], "DELETEACL")) {
1493 imap_deleteacl(num_parms, parms);
1496 else if (!strcasecmp(parms[1], "GETACL")) {
1497 imap_getacl(num_parms, parms);
1500 else if (!strcasecmp(parms[1], "LISTRIGHTS")) {
1501 imap_listrights(num_parms, parms);
1504 else if (!strcasecmp(parms[1], "MYRIGHTS")) {
1505 imap_myrights(num_parms, parms);
1508 else if (!strcasecmp(parms[1], "GETMETADATA")) {
1509 imap_getmetadata(num_parms, parms);
1512 else if (!strcasecmp(parms[1], "SETMETADATA")) {
1513 imap_setmetadata(num_parms, parms);
1516 else if (IMAP->selected == 0) {
1517 cprintf("%s BAD no folder selected\r\n", parms[0]);
1520 /* The commands below require the SELECT state on a mailbox */
1522 else if (!strcasecmp(parms[1], "FETCH")) {
1523 imap_fetch(num_parms, parms);
1526 else if ((!strcasecmp(parms[1], "UID"))
1527 && (!strcasecmp(parms[2], "FETCH"))) {
1528 imap_uidfetch(num_parms, parms);
1531 else if (!strcasecmp(parms[1], "SEARCH")) {
1532 imap_search(num_parms, parms);
1535 else if ((!strcasecmp(parms[1], "UID"))
1536 && (!strcasecmp(parms[2], "SEARCH"))) {
1537 imap_uidsearch(num_parms, parms);
1540 else if (!strcasecmp(parms[1], "STORE")) {
1541 imap_store(num_parms, parms);
1544 else if ((!strcasecmp(parms[1], "UID"))
1545 && (!strcasecmp(parms[2], "STORE"))) {
1546 imap_uidstore(num_parms, parms);
1549 else if (!strcasecmp(parms[1], "COPY")) {
1550 imap_copy(num_parms, parms);
1553 else if ((!strcasecmp(parms[1], "UID"))
1554 && (!strcasecmp(parms[2], "COPY"))) {
1555 imap_uidcopy(num_parms, parms);
1558 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1559 imap_expunge(num_parms, parms);
1562 else if (!strcasecmp(parms[1], "CLOSE")) {
1563 imap_close(num_parms, parms);
1566 /* End of commands. If we get here, the command is either invalid
1571 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1574 /* If the client transmitted a message we can free it now */
1575 imap_free_transmitted_message();
1577 gettimeofday(&tv2, NULL);
1578 total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1579 lprintf(CTDL_DEBUG, "IMAP command completed in %ld.%ld seconds\n",
1580 (total_time / 1000000),
1581 (total_time % 1000000)
1586 const char *CitadelServiceIMAP="IMAP";
1587 const char *CitadelServiceIMAPS="IMAPS";
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, CitadelServiceIMAP);
1597 CtdlRegisterServiceHook(config.c_imaps_port,
1598 NULL, imaps_greeting, imap_command_loop, NULL, CitadelServiceIMAPS);
1600 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1602 /* return our Subversion id for the Log */