4 * IMAP server for the Citadel system
5 * Copyright (C) 2000-2009 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.
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35 #include <sys/types.h>
37 #if TIME_WITH_SYS_TIME
38 # include <sys/time.h>
42 # include <sys/time.h>
52 #include <libcitadel.h>
55 #include "citserver.h"
63 #include "internet_addressing.h"
64 #include "serv_imap.h"
65 #include "imap_tools.h"
66 #include "imap_list.h"
67 #include "imap_fetch.h"
68 #include "imap_search.h"
69 #include "imap_store.h"
71 #include "imap_metadata.h"
72 #include "imap_misc.h"
75 #include "ctdl_module.h"
78 /* imap_rename() uses this struct containing list of rooms to rename */
81 char irl_oldroom[ROOMNAMELEN];
82 char irl_newroom[ROOMNAMELEN];
86 /* Data which is passed between imap_rename() and imap_rename_backend() */
95 * If there is a message ID map in memory, free it
97 void imap_free_msgids(void)
99 if (IMAP->msgids != NULL) {
105 if (IMAP->flags != NULL) {
109 IMAP->last_mtime = (-1);
114 * If there is a transmitted message in memory, free it
116 void imap_free_transmitted_message(void)
118 if (IMAP->transmitted_message != NULL) {
119 free(IMAP->transmitted_message);
120 IMAP->transmitted_message = NULL;
121 IMAP->transmitted_length = 0;
127 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
128 * sets stored in the visit record for this user/room. Note that we have
129 * to parse each sequence set manually here, because calling the utility
130 * function is_msg_in_sequence_set() over and over again is too expensive.
132 * first_msg should be set to 0 to rescan the flags for every message in the
133 * room, or some other value if we're only interested in an incremental
136 void imap_set_seen_flags(int first_msg)
142 char setstr[64], lostr[64], histr[64];
145 if (IMAP->num_msgs < 1) return;
146 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
148 for (i = first_msg; i < IMAP->num_msgs; ++i) {
149 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
150 IMAP->flags[i] |= IMAP_RECENT;
151 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
155 * Do the "\Seen" flag.
156 * (Any message not "\Seen" is considered "\Recent".)
158 num_sets = num_tokens(vbuf.v_seen, ',');
159 for (s=0; s<num_sets; ++s) {
160 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
162 extract_token(lostr, setstr, 0, ':', sizeof lostr);
163 if (num_tokens(setstr, ':') >= 2) {
164 extract_token(histr, setstr, 1, ':', sizeof histr);
165 if (!strcmp(histr, "*")) {
166 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
170 strcpy(histr, lostr);
175 for (i = first_msg; i < IMAP->num_msgs; ++i) {
176 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
177 IMAP->flags[i] |= IMAP_SEEN;
178 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
183 /* Do the ANSWERED flag */
184 num_sets = num_tokens(vbuf.v_answered, ',');
185 for (s=0; s<num_sets; ++s) {
186 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
188 extract_token(lostr, setstr, 0, ':', sizeof lostr);
189 if (num_tokens(setstr, ':') >= 2) {
190 extract_token(histr, setstr, 1, ':', sizeof histr);
191 if (!strcmp(histr, "*")) {
192 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
196 strcpy(histr, lostr);
201 for (i = first_msg; i < IMAP->num_msgs; ++i) {
202 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
203 IMAP->flags[i] |= IMAP_ANSWERED;
213 * Back end for imap_load_msgids()
215 * Optimization: instead of calling realloc() to add each message, we
216 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
217 * allows the mapping to proceed much faster.
219 void imap_add_single_msgid(long msgnum, void *userdata)
223 if (IMAP->num_msgs > IMAP->num_alloc) {
224 IMAP->num_alloc += REALLOC_INCREMENT;
225 IMAP->msgids = realloc(IMAP->msgids,
226 (IMAP->num_alloc * sizeof(long)) );
227 IMAP->flags = realloc(IMAP->flags,
228 (IMAP->num_alloc * sizeof(long)) );
230 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
231 IMAP->flags[IMAP->num_msgs - 1] = 0;
237 * Set up a message ID map for the current room (folder)
239 void imap_load_msgids(void)
241 struct cdbdata *cdbfr;
243 if (IMAP->selected == 0) {
244 CtdlLogPrintf(CTDL_ERR,
245 "imap_load_msgids() can't run; no room selected\n");
249 imap_free_msgids(); /* If there was already a map, free it */
251 /* Load the message list */
252 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
254 IMAP->msgids = malloc(cdbfr->len);
255 memcpy(IMAP->msgids, cdbfr->ptr, cdbfr->len);
256 IMAP->num_msgs = cdbfr->len / sizeof(long);
257 IMAP->num_alloc = cdbfr->len / sizeof(long);
261 if (IMAP->num_msgs) {
262 IMAP->flags = malloc(IMAP->num_alloc * sizeof(long));
263 memset(IMAP->flags, 0, (IMAP->num_alloc * sizeof(long)) );
266 imap_set_seen_flags(0);
271 * Re-scan the selected room (folder) and see if it's been changed at all
273 void imap_rescan_msgids(void)
276 int original_num_msgs = 0;
277 long original_highest = 0L;
279 int message_still_exists;
280 struct cdbdata *cdbfr;
281 long *msglist = NULL;
285 if (IMAP->selected == 0) {
286 CtdlLogPrintf(CTDL_ERR,
287 "imap_load_msgids() can't run; no room selected\n");
292 * Check to see if the room's contents have changed.
293 * If not, we can avoid this rescan.
295 getroom(&CC->room, CC->room.QRname);
296 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
300 /* Load the *current* message list from disk, so we can compare it
301 * to what we have in memory.
303 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
305 msglist = malloc(cdbfr->len);
306 if (msglist == NULL) {
307 CtdlLogPrintf(CTDL_CRIT, "malloc() failed\n");
310 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
311 num_msgs = cdbfr->len / sizeof(long);
318 * Check to see if any of the messages we know about have been expunged
320 if (IMAP->num_msgs > 0) {
322 for (i = 0; i < IMAP->num_msgs; ++i) {
324 message_still_exists = 0;
326 for (j = jstart; j < num_msgs; ++j) {
327 if (msglist[j] == IMAP->msgids[i]) {
328 message_still_exists = 1;
335 if (message_still_exists == 0) {
336 cprintf("* %d EXPUNGE\r\n", i + 1);
338 /* Here's some nice stupid nonsense. When a
339 * message is expunged, we have to slide all
340 * the existing messages up in the message
344 memcpy(&IMAP->msgids[i],
345 &IMAP->msgids[i + 1],
347 (IMAP->num_msgs - i)));
348 memcpy(&IMAP->flags[i],
351 (IMAP->num_msgs - i)));
360 * Remember how many messages were here before we re-scanned.
362 original_num_msgs = IMAP->num_msgs;
363 if (IMAP->num_msgs > 0) {
364 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
366 original_highest = 0L;
370 * Now peruse the room for *new* messages only.
373 for (j = 0; j < num_msgs; ++j) {
374 if (msglist[j] > original_highest) {
375 imap_add_single_msgid(msglist[j], NULL);
379 imap_set_seen_flags(original_num_msgs);
382 * If new messages have arrived, tell the client about them.
384 if (IMAP->num_msgs > original_num_msgs) {
386 for (j = 0; j < num_msgs; ++j) {
387 if (IMAP->flags[j] & IMAP_RECENT) {
392 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
393 cprintf("* %d RECENT\r\n", num_recent);
399 IMAP->last_mtime = CC->room.QRmtime;
409 * This cleanup function blows away the temporary memory and files used by
412 void imap_cleanup_function(void)
415 /* Don't do this stuff if this is not a IMAP session! */
416 if (CC->h_command_function != imap_command_loop)
419 /* If there is a mailbox selected, auto-expunge it. */
420 if (IMAP->selected) {
424 CtdlLogPrintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
426 imap_free_transmitted_message();
428 if (IMAP->cached_rfc822_data != NULL) {
429 free(IMAP->cached_rfc822_data);
430 IMAP->cached_rfc822_data = NULL;
431 IMAP->cached_rfc822_msgnum = (-1);
432 IMAP->cached_rfc822_withbody = 0;
435 if (IMAP->cached_body != NULL) {
436 free(IMAP->cached_body);
437 IMAP->cached_body = NULL;
438 IMAP->cached_body_len = 0;
439 IMAP->cached_bodymsgnum = (-1);
443 CtdlLogPrintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
448 * Does the actual work of the CAPABILITY command (because we need to
449 * output this stuff in other places as well)
451 void imap_output_capability_string(void) {
452 cprintf("CAPABILITY IMAP4REV1 NAMESPACE ID AUTH=PLAIN AUTH=LOGIN UIDPLUS");
455 if (!CC->redirect_ssl) cprintf(" STARTTLS");
458 #ifndef DISABLE_IMAP_ACL
462 /* We are building a partial implementation of METADATA for the sole purpose
463 * of interoperating with the ical/vcard version of the Bynari Insight Connector.
464 * It is not a full RFC5464 implementation, but it should refuse non-Bynari
465 * metadata in a compatible and graceful way.
467 cprintf(" METADATA");
470 * LIST-EXTENDED was originally going to be required by the METADATA extension.
471 * It was mercifully removed prior to the finalization of RFC5464. We started
472 * implementing this but stopped when we learned that it would not be needed.
473 * If you uncomment this declaration you are responsible for writing a lot of new
476 * cprintf(" LIST-EXTENDED")
481 * implements the CAPABILITY command
483 void imap_capability(int num_parms, char *parms[])
486 imap_output_capability_string();
488 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
494 * Implements the ID command (specified by RFC2971)
496 * We ignore the client-supplied information, and output a NIL response.
497 * Although this is technically a valid implementation of the extension, it
498 * is quite useless. It exists only so that we may see which clients are
499 * making use of this extension.
502 void imap_id(int num_parms, char *parms[])
504 cprintf("* ID NIL\r\n");
505 cprintf("%s OK ID completed\r\n", parms[0]);
511 * Here's where our IMAP session begins its happy day.
513 void imap_greeting(void)
516 strcpy(CC->cs_clientname, "IMAP session");
517 CC->session_specific_data = malloc(sizeof(struct citimap));
518 memset(IMAP, 0, sizeof(struct citimap));
519 IMAP->authstate = imap_as_normal;
520 IMAP->cached_rfc822_data = NULL;
521 IMAP->cached_rfc822_msgnum = (-1);
522 IMAP->cached_rfc822_withbody = 0;
526 cprintf("* BYE; Server busy, try later\r\n");
531 imap_output_capability_string();
532 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
536 * IMAPS is just like IMAP, except it goes crypto right away.
538 void imaps_greeting(void) {
539 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
541 if (!CC->redirect_ssl) CC->kill_me = 1; /* kill session if no crypto */
548 * implements the LOGIN command (ordinary username/password login)
550 void imap_login(int num_parms, char *parms[])
552 if (num_parms != 4) {
553 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
557 if (CtdlLoginExistingUser(NULL, parms[2]) == login_ok) {
558 if (CtdlTryPassword(parms[3]) == pass_ok) {
559 cprintf("%s OK [", parms[0]);
560 imap_output_capability_string();
561 cprintf("] Hello, %s\r\n", CC->user.fullname);
566 cprintf("%s BAD Login incorrect\r\n", parms[0]);
571 * Implements the AUTHENTICATE command
573 void imap_authenticate(int num_parms, char *parms[])
577 if (num_parms != 3) {
578 cprintf("%s BAD incorrect number of parameters\r\n",
584 cprintf("%s BAD Already logged in.\r\n", parms[0]);
588 if (!strcasecmp(parms[2], "LOGIN")) {
589 CtdlEncodeBase64(buf, "Username:", 9, 0);
590 cprintf("+ %s\r\n", buf);
591 IMAP->authstate = imap_as_expecting_username;
592 strcpy(IMAP->authseq, parms[0]);
596 if (!strcasecmp(parms[2], "PLAIN")) {
597 // CtdlEncodeBase64(buf, "Username:", 9, 0);
598 // cprintf("+ %s\r\n", buf);
600 IMAP->authstate = imap_as_expecting_plainauth;
601 strcpy(IMAP->authseq, parms[0]);
606 cprintf("%s NO AUTHENTICATE %s failed\r\n",
611 void imap_auth_plain(char *cmd)
613 char decoded_authstring[1024];
619 memset(pass, 0, sizeof(pass));
620 CtdlDecodeBase64(decoded_authstring, cmd, strlen(cmd));
621 safestrncpy(ident, decoded_authstring, sizeof ident);
622 safestrncpy(user, &decoded_authstring[strlen(ident) + 1], sizeof user);
623 safestrncpy(pass, &decoded_authstring[strlen(ident) + strlen(user) + 2], sizeof pass);
625 IMAP->authstate = imap_as_normal;
627 if (!IsEmptyStr(ident)) {
628 result = CtdlLoginExistingUser(user, ident);
631 result = CtdlLoginExistingUser(NULL, user);
634 if (result == login_ok) {
635 if (CtdlTryPassword(pass) == pass_ok) {
636 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
640 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
643 void imap_auth_login_user(char *cmd)
647 CtdlDecodeBase64(buf, cmd, SIZ);
648 CtdlLoginExistingUser(NULL, buf);
649 CtdlEncodeBase64(buf, "Password:", 9, 0);
650 cprintf("+ %s\r\n", buf);
651 IMAP->authstate = imap_as_expecting_password;
655 void imap_auth_login_pass(char *cmd)
659 memset(buf, 0, sizeof(buf));
660 CtdlDecodeBase64(buf, cmd, SIZ);
661 if (CtdlTryPassword(buf) == pass_ok) {
662 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
664 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
666 IMAP->authstate = imap_as_normal;
672 * implements the STARTTLS command (Citadel API version)
674 void imap_starttls(int num_parms, char *parms[])
676 char ok_response[SIZ];
677 char nosup_response[SIZ];
678 char error_response[SIZ];
681 "%s OK begin TLS negotiation now\r\n",
683 sprintf(nosup_response,
684 "%s NO TLS not supported here\r\n",
686 sprintf(error_response,
687 "%s BAD Internal error\r\n",
689 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
694 * implements the SELECT command
696 void imap_select(int num_parms, char *parms[])
699 char augmented_roomname[ROOMNAMELEN];
703 struct ctdlroom QRscratch;
709 /* Convert the supplied folder name to a roomname */
710 i = imap_roomname(towhere, sizeof towhere, parms[2]);
712 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
716 floornum = (i & 0x00ff);
717 roomflags = (i & 0xff00);
719 /* First try a regular match */
720 c = getroom(&QRscratch, towhere);
722 /* Then try a mailbox name match */
724 MailboxName(augmented_roomname, sizeof augmented_roomname,
726 c = getroom(&QRscratch, augmented_roomname);
728 strcpy(towhere, augmented_roomname);
731 /* If the room exists, check security/access */
733 /* See if there is an existing user/room relationship */
734 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
736 /* normal clients have to pass through security */
742 /* Fail here if no such room */
744 cprintf("%s NO ... no such room, or access denied\r\n",
749 /* If we already had some other folder selected, auto-expunge it */
753 * usergoto() formally takes us to the desired room, happily returning
754 * the number of messages and number of new messages.
756 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
757 usergoto(NULL, 0, 0, &msgs, &new);
760 if (!strcasecmp(parms[1], "EXAMINE")) {
767 IMAP->last_mtime = CC->room.QRmtime;
769 cprintf("* %d EXISTS\r\n", msgs);
770 cprintf("* %d RECENT\r\n", new);
772 cprintf("* OK [UIDVALIDITY %ld] UID validity status\r\n", GLOBAL_UIDVALIDITY_VALUE);
773 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
775 /* Technically, \Deleted is a valid flag, but not a permanent flag,
776 * because we don't maintain its state across sessions. Citadel
777 * automatically expunges mailboxes when they are de-selected.
779 * Unfortunately, omitting \Deleted as a PERMANENTFLAGS flag causes
780 * some clients (particularly Thunderbird) to misbehave -- they simply
781 * elect not to transmit the flag at all. So we have to advertise
782 * \Deleted as a PERMANENTFLAGS flag, even though it technically isn't.
784 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
785 cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] permanent flags\r\n");
787 cprintf("%s OK [%s] %s completed\r\n",
789 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
795 * Does the real work for expunge.
797 int imap_do_expunge(void)
800 int num_expunged = 0;
801 long *delmsgs = NULL;
804 CtdlLogPrintf(CTDL_DEBUG, "imap_do_expunge() called\n");
805 if (IMAP->selected == 0) {
809 if (IMAP->num_msgs > 0) {
810 delmsgs = malloc(IMAP->num_msgs * sizeof(long));
811 for (i = 0; i < IMAP->num_msgs; ++i) {
812 if (IMAP->flags[i] & IMAP_DELETED) {
813 delmsgs[num_delmsgs++] = IMAP->msgids[i];
816 if (num_delmsgs > 0) {
817 CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
819 num_expunged += num_delmsgs;
823 if (num_expunged > 0) {
824 imap_rescan_msgids();
827 CtdlLogPrintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n",
828 num_expunged, CC->room.QRname);
829 return (num_expunged);
834 * implements the EXPUNGE command syntax
836 void imap_expunge(int num_parms, char *parms[])
838 int num_expunged = 0;
840 num_expunged = imap_do_expunge();
841 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
846 * implements the CLOSE command
848 void imap_close(int num_parms, char *parms[])
851 /* Yes, we always expunge on close. */
852 if (IMAP->selected) {
859 cprintf("%s OK CLOSE completed\r\n", parms[0]);
864 * Implements the NAMESPACE command.
866 void imap_namespace(int num_parms, char *parms[])
873 cprintf("* NAMESPACE ");
875 /* All personal folders are subordinate to INBOX. */
876 cprintf("((\"INBOX/\" \"/\")) ");
878 /* Other users' folders ... coming soon! FIXME */
881 /* Show all floors as shared namespaces. Neato! */
883 for (i = 0; i < MAXFLOORS; ++i) {
885 if (fl->f_flags & F_INUSE) {
886 if (floors > 0) cprintf(" ");
888 sprintf(buf, "%s/", fl->f_name);
896 /* Wind it up with a newline and a completion message. */
898 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
904 * Implements the CREATE command
907 void imap_create(int num_parms, char *parms[])
910 char roomname[ROOMNAMELEN];
915 char *notification_message = NULL;
918 cprintf("%s NO A foder name must be specified\r\n", parms[0]);
922 if (strchr(parms[2], '\\') != NULL) {
923 cprintf("%s NO Invalid character in folder name\r\n", parms[0]);
924 CtdlLogPrintf(CTDL_DEBUG, "invalid character in folder name\n");
928 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
930 cprintf("%s NO Invalid mailbox name or location\r\n",
932 CtdlLogPrintf(CTDL_DEBUG, "invalid mailbox name or location\n");
935 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
936 flags = (ret & 0xff00); /* upper 8 bits = flags */
938 if (flags & IR_MAILBOX) {
939 if (strncasecmp(parms[2], "INBOX/", 6)) {
940 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
941 CtdlLogPrintf(CTDL_DEBUG, "not subordinate to inbox\n");
946 if (flags & IR_MAILBOX) {
947 newroomtype = 4; /* private mailbox */
948 newroomview = VIEW_MAILBOX;
950 newroomtype = 0; /* public folder */
951 newroomview = VIEW_BBS;
954 CtdlLogPrintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
955 roomname, floornum, newroomtype);
957 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
959 /*** DO NOT CHANGE THIS ERROR MESSAGE IN ANY WAY! BYNARI CONNECTOR DEPENDS ON IT! ***/
960 cprintf("%s NO Mailbox already exists, or create failed\r\n", parms[0]);
962 cprintf("%s OK CREATE completed\r\n", parms[0]);
963 /* post a message in Aide> describing the new room */
964 notification_message = malloc(1024);
965 snprintf(notification_message, 1024,
966 "A new room called \"%s\" has been created by %s%s%s%s\n",
969 ((ret & QR_MAILBOX) ? " [personal]" : ""),
970 ((ret & QR_PRIVATE) ? " [private]" : ""),
971 ((ret & QR_GUESSNAME) ? " [hidden]" : "")
973 aide_message(notification_message, "Room Creation Message");
974 free(notification_message);
976 CtdlLogPrintf(CTDL_DEBUG, "imap_create() completed\n");
981 * Locate a room by its IMAP folder name, and check access to it.
982 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
984 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
987 char augmented_roomname[ROOMNAMELEN];
988 char roomname[ROOMNAMELEN];
990 struct ctdlroom QRscratch;
994 ret = imap_roomname(roomname, sizeof roomname, foldername);
999 /* First try a regular match */
1000 c = getroom(&QRscratch, roomname);
1002 /* Then try a mailbox name match */
1004 MailboxName(augmented_roomname, sizeof augmented_roomname,
1005 &CC->user, roomname);
1006 c = getroom(&QRscratch, augmented_roomname);
1008 strcpy(roomname, augmented_roomname);
1011 /* If the room exists, check security/access */
1013 /* See if there is an existing user/room relationship */
1014 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1016 /* normal clients have to pass through security */
1017 if (ra & UA_KNOWN) {
1020 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1025 /* Fail here if no such room */
1027 strcpy(returned_roomname, "");
1030 strcpy(returned_roomname, QRscratch.QRname);
1037 * Implements the STATUS command (sort of)
1040 void imap_status(int num_parms, char *parms[])
1043 char roomname[ROOMNAMELEN];
1045 char savedroom[ROOMNAMELEN];
1048 ret = imap_grabroom(roomname, parms[2], 1);
1051 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1057 * usergoto() formally takes us to the desired room, happily returning
1058 * the number of messages and number of new messages. (If another
1059 * folder is selected, save its name so we can return there!!!!!)
1061 if (IMAP->selected) {
1062 strcpy(savedroom, CC->room.QRname);
1064 usergoto(roomname, 0, 0, &msgs, &new);
1067 * Tell the client what it wants to know. In fact, tell it *more* than
1068 * it wants to know. We happily IGnore the supplied status data item
1069 * names and simply spew all possible data items. It's far easier to
1070 * code and probably saves us some processing time too.
1072 imap_mailboxname(buf, sizeof buf, &CC->room);
1073 cprintf("* STATUS ");
1075 cprintf(" (MESSAGES %d ", msgs);
1076 cprintf("RECENT %d ", new); /* Initially, new==recent */
1077 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1078 cprintf("UNSEEN %d)\r\n", new);
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);
1089 * Oooh, look, we're done!
1091 cprintf("%s OK STATUS completed\r\n", parms[0]);
1097 * Implements the SUBSCRIBE command
1100 void imap_subscribe(int num_parms, char *parms[])
1103 char roomname[ROOMNAMELEN];
1104 char savedroom[ROOMNAMELEN];
1107 ret = imap_grabroom(roomname, parms[2], 1);
1110 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1118 * usergoto() formally takes us to the desired room, which has the side
1119 * effect of marking the room as not-zapped ... exactly the effect
1120 * we're looking for.
1122 if (IMAP->selected) {
1123 strcpy(savedroom, CC->room.QRname);
1125 usergoto(roomname, 0, 0, &msgs, &new);
1128 * If another folder is selected, go back to that room so we can resume
1129 * our happy day without violent explosions.
1131 if (IMAP->selected) {
1132 usergoto(savedroom, 0, 0, &msgs, &new);
1135 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1140 * Implements the UNSUBSCRIBE command
1143 void imap_unsubscribe(int num_parms, char *parms[])
1146 char roomname[ROOMNAMELEN];
1147 char savedroom[ROOMNAMELEN];
1150 ret = imap_grabroom(roomname, parms[2], 1);
1153 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1159 * usergoto() formally takes us to the desired room.
1161 if (IMAP->selected) {
1162 strcpy(savedroom, CC->room.QRname);
1164 usergoto(roomname, 0, 0, &msgs, &new);
1167 * Now make the API call to zap the room
1169 if (CtdlForgetThisRoom() == 0) {
1170 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1173 ("%s NO You may not unsubscribe from this folder.\r\n",
1178 * If another folder is selected, go back to that room so we can resume
1179 * our happy day without violent explosions.
1181 if (IMAP->selected) {
1182 usergoto(savedroom, 0, 0, &msgs, &new);
1189 * Implements the DELETE command
1192 void imap_delete(int num_parms, char *parms[])
1195 char roomname[ROOMNAMELEN];
1196 char savedroom[ROOMNAMELEN];
1199 ret = imap_grabroom(roomname, parms[2], 1);
1201 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1207 * usergoto() formally takes us to the desired room, happily returning
1208 * the number of messages and number of new messages. (If another
1209 * folder is selected, save its name so we can return there!!!!!)
1211 if (IMAP->selected) {
1212 strcpy(savedroom, CC->room.QRname);
1214 usergoto(roomname, 0, 0, &msgs, &new);
1217 * Now delete the room.
1219 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1220 schedule_room_for_deletion(&CC->room);
1221 cprintf("%s OK DELETE completed\r\n", parms[0]);
1223 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1227 * If another folder is selected, go back to that room so we can resume
1228 * our happy day without violent explosions.
1230 if (IMAP->selected) {
1231 usergoto(savedroom, 0, 0, &msgs, &new);
1237 * Back end function for imap_rename()
1239 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1241 char foldername[SIZ];
1242 char newfoldername[SIZ];
1243 char newroomname[ROOMNAMELEN];
1245 struct irl *irlp = NULL; /* scratch pointer */
1246 struct irlparms *irlparms;
1248 irlparms = (struct irlparms *) data;
1249 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1251 /* Rename subfolders */
1252 if ((!strncasecmp(foldername, irlparms->oldname,
1253 strlen(irlparms->oldname))
1254 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1256 sprintf(newfoldername, "%s/%s",
1258 &foldername[strlen(irlparms->oldname) + 1]
1261 newfloor = imap_roomname(newroomname,
1263 newfoldername) & 0xFF;
1265 irlp = (struct irl *) malloc(sizeof(struct irl));
1266 strcpy(irlp->irl_newroom, newroomname);
1267 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1268 irlp->irl_newfloor = newfloor;
1269 irlp->next = *(irlparms->irl);
1270 *(irlparms->irl) = irlp;
1276 * Implements the RENAME command
1279 void imap_rename(int num_parms, char *parms[])
1281 char old_room[ROOMNAMELEN];
1282 char new_room[ROOMNAMELEN];
1286 struct irl *irl = NULL; /* the list */
1287 struct irl *irlp = NULL; /* scratch pointer */
1288 struct irlparms irlparms;
1291 if (strchr(parms[3], '\\') != NULL) {
1292 cprintf("%s NO Invalid character in folder name\r\n",
1297 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1298 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1299 new_floor = (newr & 0xFF);
1301 r = CtdlRenameRoom(old_room, new_room, new_floor);
1303 if (r == crr_room_not_found) {
1304 cprintf("%s NO Could not locate this folder\r\n",
1308 if (r == crr_already_exists) {
1309 cprintf("%s NO '%s' already exists.\r\n", parms[0], parms[2]);
1312 if (r == crr_noneditable) {
1313 cprintf("%s NO This folder is not editable.\r\n", parms[0]);
1316 if (r == crr_invalid_floor) {
1317 cprintf("%s NO Folder root does not exist.\r\n", parms[0]);
1320 if (r == crr_access_denied) {
1321 cprintf("%s NO You do not have permission to edit this folder.\r\n",
1326 cprintf("%s NO Rename failed - undefined error %d\r\n",
1331 /* If this is the INBOX, then RFC2060 says we have to just move the
1332 * contents. In a Citadel environment it's easier to rename the room
1333 * (already did that) and create a new inbox.
1335 if (!strcasecmp(parms[2], "INBOX")) {
1336 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1339 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1341 irlparms.oldname = parms[2];
1342 irlparms.newname = parms[3];
1343 irlparms.irl = &irl;
1344 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1346 /* ... and now rename them. */
1347 while (irl != NULL) {
1348 r = CtdlRenameRoom(irl->irl_oldroom,
1352 /* FIXME handle error returns better */
1353 CtdlLogPrintf(CTDL_ERR, "CtdlRenameRoom() error %d\n", r);
1361 snprintf(buf, sizeof buf, "IMAP folder \"%s\" renamed to \"%s\" by %s\n",
1366 aide_message(buf, "IMAP folder rename");
1368 cprintf("%s OK RENAME completed\r\n", parms[0]);
1375 * Main command loop for IMAP sessions.
1377 void imap_command_loop(void)
1382 struct timeval tv1, tv2;
1383 suseconds_t total_time = 0;
1384 int untagged_ok = 1;
1386 gettimeofday(&tv1, NULL);
1387 CC->lastcmd = time(NULL);
1388 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1390 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1391 CtdlLogPrintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1396 if (IMAP->authstate == imap_as_expecting_password) {
1397 CtdlLogPrintf(CTDL_INFO, "IMAP: <password>\n");
1399 else if (IMAP->authstate == imap_as_expecting_plainauth) {
1400 CtdlLogPrintf(CTDL_INFO, "IMAP: <plain_auth>\n");
1402 else if (bmstrcasestr(cmdbuf, " LOGIN ")) {
1403 CtdlLogPrintf(CTDL_INFO, "IMAP: LOGIN...\n");
1406 CtdlLogPrintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1409 while (strlen(cmdbuf) < 5)
1410 strcat(cmdbuf, " ");
1412 /* strip off l/t whitespace and CRLF */
1413 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1414 cmdbuf[strlen(cmdbuf) - 1] = 0;
1415 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1416 cmdbuf[strlen(cmdbuf) - 1] = 0;
1419 /* If we're in the middle of a multi-line command, handle that */
1420 if (IMAP->authstate == imap_as_expecting_username) {
1421 imap_auth_login_user(cmdbuf);
1424 if (IMAP->authstate == imap_as_expecting_plainauth) {
1425 imap_auth_plain(cmdbuf);
1428 if (IMAP->authstate == imap_as_expecting_password) {
1429 imap_auth_login_pass(cmdbuf);
1434 /* Ok, at this point we're in normal command mode.
1435 * If the command just submitted does not contain a literal, we
1436 * might think about delivering some untagged stuff...
1438 if (cmdbuf[strlen(cmdbuf)-1] == '}') {
1442 /* Grab the tag, command, and parameters. */
1443 num_parms = imap_parameterize(parms, cmdbuf);
1445 /* RFC3501 says that we cannot output untagged data during these commands */
1446 if (num_parms >= 2) {
1447 if ( (!strcasecmp(parms[1], "FETCH"))
1448 || (!strcasecmp(parms[1], "STORE"))
1449 || (!strcasecmp(parms[1], "SEARCH"))
1457 /* we can put any additional untagged stuff right here in the future */
1460 * Before processing the command that was just entered... if we happen
1461 * to have a folder selected, we'd like to rescan that folder for new
1462 * messages, and for deletions/changes of existing messages. This
1463 * could probably be optimized better with some deep thought...
1465 if (IMAP->selected) {
1466 imap_rescan_msgids();
1470 /* Now for the command set. */
1472 if (num_parms < 2) {
1473 cprintf("BAD syntax error\r\n");
1476 /* The commands below may be executed in any state */
1478 else if ((!strcasecmp(parms[1], "NOOP"))
1479 || (!strcasecmp(parms[1], "CHECK"))) {
1480 cprintf("%s OK No operation\r\n",
1484 else if (!strcasecmp(parms[1], "ID")) {
1485 imap_id(num_parms, parms);
1489 else if (!strcasecmp(parms[1], "LOGOUT")) {
1490 if (IMAP->selected) {
1491 imap_do_expunge(); /* yes, we auto-expunge at logout */
1493 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1494 cprintf("%s OK Citadel IMAP session ended.\r\n",
1500 else if (!strcasecmp(parms[1], "LOGIN")) {
1501 imap_login(num_parms, parms);
1504 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1505 imap_authenticate(num_parms, parms);
1508 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1509 imap_capability(num_parms, parms);
1512 else if (!strcasecmp(parms[1], "STARTTLS")) {
1513 imap_starttls(num_parms, parms);
1516 else if (!CC->logged_in) {
1517 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1520 /* The commans below require a logged-in state */
1522 else if (!strcasecmp(parms[1], "SELECT")) {
1523 imap_select(num_parms, parms);
1526 else if (!strcasecmp(parms[1], "EXAMINE")) {
1527 imap_select(num_parms, parms);
1530 else if (!strcasecmp(parms[1], "LSUB")) {
1531 imap_list(num_parms, parms);
1534 else if (!strcasecmp(parms[1], "LIST")) {
1535 imap_list(num_parms, parms);
1538 else if (!strcasecmp(parms[1], "CREATE")) {
1539 imap_create(num_parms, parms);
1542 else if (!strcasecmp(parms[1], "DELETE")) {
1543 imap_delete(num_parms, parms);
1546 else if (!strcasecmp(parms[1], "RENAME")) {
1547 imap_rename(num_parms, parms);
1550 else if (!strcasecmp(parms[1], "STATUS")) {
1551 imap_status(num_parms, parms);
1554 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1555 imap_subscribe(num_parms, parms);
1558 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1559 imap_unsubscribe(num_parms, parms);
1562 else if (!strcasecmp(parms[1], "APPEND")) {
1563 imap_append(num_parms, parms);
1566 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1567 imap_namespace(num_parms, parms);
1570 else if (!strcasecmp(parms[1], "SETACL")) {
1571 imap_setacl(num_parms, parms);
1574 else if (!strcasecmp(parms[1], "DELETEACL")) {
1575 imap_deleteacl(num_parms, parms);
1578 else if (!strcasecmp(parms[1], "GETACL")) {
1579 imap_getacl(num_parms, parms);
1582 else if (!strcasecmp(parms[1], "LISTRIGHTS")) {
1583 imap_listrights(num_parms, parms);
1586 else if (!strcasecmp(parms[1], "MYRIGHTS")) {
1587 imap_myrights(num_parms, parms);
1590 else if (!strcasecmp(parms[1], "GETMETADATA")) {
1591 imap_getmetadata(num_parms, parms);
1594 else if (!strcasecmp(parms[1], "SETMETADATA")) {
1595 imap_setmetadata(num_parms, parms);
1598 else if (IMAP->selected == 0) {
1599 cprintf("%s BAD no folder selected\r\n", parms[0]);
1602 /* The commands below require the SELECT state on a mailbox */
1604 else if (!strcasecmp(parms[1], "FETCH")) {
1605 imap_fetch(num_parms, parms);
1608 else if ((!strcasecmp(parms[1], "UID"))
1609 && (!strcasecmp(parms[2], "FETCH"))) {
1610 imap_uidfetch(num_parms, parms);
1613 else if (!strcasecmp(parms[1], "SEARCH")) {
1614 imap_search(num_parms, parms);
1617 else if ((!strcasecmp(parms[1], "UID"))
1618 && (!strcasecmp(parms[2], "SEARCH"))) {
1619 imap_uidsearch(num_parms, parms);
1622 else if (!strcasecmp(parms[1], "STORE")) {
1623 imap_store(num_parms, parms);
1626 else if ((!strcasecmp(parms[1], "UID"))
1627 && (!strcasecmp(parms[2], "STORE"))) {
1628 imap_uidstore(num_parms, parms);
1631 else if (!strcasecmp(parms[1], "COPY")) {
1632 imap_copy(num_parms, parms);
1635 else if ((!strcasecmp(parms[1], "UID")) && (!strcasecmp(parms[2], "COPY"))) {
1636 imap_uidcopy(num_parms, parms);
1639 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1640 imap_expunge(num_parms, parms);
1643 else if ((!strcasecmp(parms[1], "UID")) && (!strcasecmp(parms[2], "EXPUNGE"))) {
1644 imap_expunge(num_parms, parms);
1647 else if (!strcasecmp(parms[1], "CLOSE")) {
1648 imap_close(num_parms, parms);
1651 /* End of commands. If we get here, the command is either invalid
1656 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1659 /* If the client transmitted a message we can free it now */
1660 imap_free_transmitted_message();
1662 gettimeofday(&tv2, NULL);
1663 total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1664 CtdlLogPrintf(CTDL_INFO, "IMAP: %s\n", cmdbuf); // FIXME FIXME FIXME REMOVE THIS NOW
1665 CtdlLogPrintf(CTDL_DEBUG, "IMAP command completed in %ld.%ld seconds\n",
1666 (total_time / 1000000),
1667 (total_time % 1000000)
1672 const char *CitadelServiceIMAP="IMAP";
1673 const char *CitadelServiceIMAPS="IMAPS";
1676 * This function is called to register the IMAP extension with Citadel.
1678 CTDL_MODULE_INIT(imap)
1682 CtdlRegisterServiceHook(config.c_imap_port,
1683 NULL, imap_greeting, imap_command_loop, NULL, CitadelServiceIMAP);
1685 CtdlRegisterServiceHook(config.c_imaps_port,
1686 NULL, imaps_greeting, imap_command_loop, NULL, CitadelServiceIMAPS);
1688 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1691 /* return our Subversion id for the Log */