4 * IMAP server for the Citadel system
5 * Copyright (C) 2000-2007 by Art Cancro and others.
6 * This code is released under the terms of the GNU General Public License.
8 * WARNING: the IMAP protocol is badly designed. No implementation of it
9 * is perfect. Indeed, with so much gratuitous complexity, *all* IMAP
10 * implementations have bugs.
21 #include <sys/types.h>
23 #if TIME_WITH_SYS_TIME
24 # include <sys/time.h>
28 # include <sys/time.h>
40 #include "sysdep_decls.h"
41 #include "citserver.h"
44 #include "serv_extensions.h"
51 #include "internet_addressing.h"
52 #include "serv_imap.h"
53 #include "imap_tools.h"
54 #include "imap_fetch.h"
55 #include "imap_search.h"
56 #include "imap_store.h"
58 #include "imap_misc.h"
61 #include "serv_crypto.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 ACL AUTH=LOGIN");
440 if (!CC->redirect_ssl) cprintf(" STARTTLS");
445 * implements the CAPABILITY command
447 void imap_capability(int num_parms, char *parms[])
450 imap_output_capability_string();
452 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
458 * Implements the ID command (specified by RFC2971)
460 * We ignore the client-supplied information, and output a NIL response.
461 * Although this is technically a valid implementation of the extension, it
462 * is quite useless. It exists only so that we may see which clients are
463 * making use of this extension.
466 void imap_id(int num_parms, char *parms[])
468 cprintf("* ID NIL\r\n");
469 cprintf("%s OK ID completed\r\n", parms[0]);
475 * Here's where our IMAP session begins its happy day.
477 void imap_greeting(void)
480 strcpy(CC->cs_clientname, "IMAP session");
481 IMAP = malloc(sizeof (struct citimap));
482 memset(IMAP, 0, sizeof(struct citimap));
483 IMAP->authstate = imap_as_normal;
484 IMAP->cached_rfc822_data = NULL;
485 IMAP->cached_rfc822_msgnum = (-1);
486 IMAP->cached_rfc822_withbody = 0;
489 imap_output_capability_string();
490 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
494 * IMAPS is just like IMAP, except it goes crypto right away.
497 void imaps_greeting(void) {
498 CtdlStartTLS(NULL, NULL, NULL);
505 * implements the LOGIN command (ordinary username/password login)
507 void imap_login(int num_parms, char *parms[])
509 if (num_parms != 4) {
510 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
514 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
515 if (CtdlTryPassword(parms[3]) == pass_ok) {
516 cprintf("%s OK [", parms[0]);
517 imap_output_capability_string();
518 cprintf("] Hello, %s\r\n", CC->user.fullname);
523 cprintf("%s BAD Login incorrect\r\n", parms[0]);
528 * Implements the AUTHENTICATE command
530 void imap_authenticate(int num_parms, char *parms[])
534 if (num_parms != 3) {
535 cprintf("%s BAD incorrect number of parameters\r\n",
541 cprintf("%s BAD Already logged in.\r\n", parms[0]);
545 if (!strcasecmp(parms[2], "LOGIN")) {
546 CtdlEncodeBase64(buf, "Username:", 9);
547 cprintf("+ %s\r\n", buf);
548 IMAP->authstate = imap_as_expecting_username;
549 strcpy(IMAP->authseq, parms[0]);
554 cprintf("%s NO AUTHENTICATE %s failed\r\n",
559 void imap_auth_login_user(char *cmd)
563 CtdlDecodeBase64(buf, cmd, SIZ);
564 CtdlLoginExistingUser(buf);
565 CtdlEncodeBase64(buf, "Password:", 9);
566 cprintf("+ %s\r\n", buf);
567 IMAP->authstate = imap_as_expecting_password;
571 void imap_auth_login_pass(char *cmd)
575 CtdlDecodeBase64(buf, cmd, SIZ);
576 if (CtdlTryPassword(buf) == pass_ok) {
577 cprintf("%s OK authentication succeeded\r\n",
580 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
582 IMAP->authstate = imap_as_normal;
588 * implements the STARTTLS command (Citadel API version)
591 void imap_starttls(int num_parms, char *parms[])
593 char ok_response[SIZ];
594 char nosup_response[SIZ];
595 char error_response[SIZ];
598 "%s OK begin TLS negotiation now\r\n",
600 sprintf(nosup_response,
601 "%s NO TLS not supported here\r\n",
603 sprintf(error_response,
604 "%s BAD Internal error\r\n",
606 CtdlStartTLS(ok_response, nosup_response, error_response);
612 * implements the SELECT command
614 void imap_select(int num_parms, char *parms[])
617 char augmented_roomname[ROOMNAMELEN];
621 struct ctdlroom QRscratch;
627 /* Convert the supplied folder name to a roomname */
628 i = imap_roomname(towhere, sizeof towhere, parms[2]);
630 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
634 floornum = (i & 0x00ff);
635 roomflags = (i & 0xff00);
637 /* First try a regular match */
638 c = getroom(&QRscratch, towhere);
640 /* Then try a mailbox name match */
642 MailboxName(augmented_roomname, sizeof augmented_roomname,
644 c = getroom(&QRscratch, augmented_roomname);
646 strcpy(towhere, augmented_roomname);
649 /* If the room exists, check security/access */
651 /* See if there is an existing user/room relationship */
652 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
654 /* normal clients have to pass through security */
660 /* Fail here if no such room */
662 cprintf("%s NO ... no such room, or access denied\r\n",
667 /* If we already had some other folder selected, auto-expunge it */
671 * usergoto() formally takes us to the desired room, happily returning
672 * the number of messages and number of new messages.
674 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
675 usergoto(NULL, 0, 0, &msgs, &new);
678 if (!strcasecmp(parms[1], "EXAMINE")) {
685 IMAP->last_mtime = CC->room.QRmtime;
687 cprintf("* %d EXISTS\r\n", msgs);
688 cprintf("* %d RECENT\r\n", new);
690 cprintf("* OK [UIDVALIDITY 1] UID validity status\r\n");
691 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
693 /* Note that \Deleted is a valid flag, but not a permanent flag,
694 * because we don't maintain its state across sessions. Citadel
695 * automatically expunges mailboxes when they are de-selected.
697 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
698 cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] "
699 "permanent flags\r\n");
701 cprintf("%s OK [%s] %s completed\r\n",
703 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
709 * Does the real work for expunge.
711 int imap_do_expunge(void)
714 int num_expunged = 0;
715 long *delmsgs = NULL;
718 lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
719 if (IMAP->selected == 0) {
723 if (IMAP->num_msgs > 0) {
724 delmsgs = malloc(IMAP->num_msgs * sizeof(long));
725 for (i = 0; i < IMAP->num_msgs; ++i) {
726 if (IMAP->flags[i] & IMAP_DELETED) {
727 delmsgs[num_delmsgs++] = IMAP->msgids[i];
730 if (num_delmsgs > 0) {
731 CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
733 num_expunged += num_delmsgs;
737 if (num_expunged > 0) {
738 imap_rescan_msgids();
741 lprintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n",
742 num_expunged, CC->room.QRname);
743 return (num_expunged);
748 * implements the EXPUNGE command syntax
750 void imap_expunge(int num_parms, char *parms[])
752 int num_expunged = 0;
754 num_expunged = imap_do_expunge();
755 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
760 * implements the CLOSE command
762 void imap_close(int num_parms, char *parms[])
765 /* Yes, we always expunge on close. */
766 if (IMAP->selected) {
773 cprintf("%s OK CLOSE completed\r\n", parms[0]);
778 * Implements the NAMESPACE command.
780 void imap_namespace(int num_parms, char *parms[])
787 cprintf("* NAMESPACE ");
789 /* All personal folders are subordinate to INBOX. */
790 cprintf("((\"INBOX/\" \"/\")) ");
792 /* Other users' folders ... coming soon! FIXME */
795 /* Show all floors as shared namespaces. Neato! */
797 for (i = 0; i < MAXFLOORS; ++i) {
799 if (fl->f_flags & F_INUSE) {
800 if (floors > 0) cprintf(" ");
802 sprintf(buf, "%s/", fl->f_name);
810 /* Wind it up with a newline and a completion message. */
812 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
818 * Used by LIST and LSUB to show the floors in the listing
820 void imap_list_floors(char *cmd, char *pattern)
825 for (i = 0; i < MAXFLOORS; ++i) {
827 if (fl->f_flags & F_INUSE) {
828 if (imap_mailbox_matches_pattern
829 (pattern, fl->f_name)) {
830 cprintf("* %s (\\NoSelect) \"/\" ", cmd);
831 imap_strout(fl->f_name);
841 * Back end for imap_lsub()
843 * IMAP "subscribed folder" is equivocated to Citadel "known rooms." This
844 * may or may not be the desired behavior in the future.
846 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data)
850 char **data_for_callback;
854 data_for_callback = data;
855 pattern = data_for_callback[0];
856 verb = data_for_callback[1];
858 /* Only list rooms to which the user has access!! */
859 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
861 imap_mailboxname(buf, sizeof buf, qrbuf);
862 if (imap_mailbox_matches_pattern(pattern, buf)) {
863 cprintf("* %s () \"/\" ", verb);
872 * Back end for imap_list()
874 void imap_list_listroom(struct ctdlroom *qrbuf, void *data)
878 char **data_for_callback;
882 data_for_callback = data;
883 pattern = data_for_callback[0];
884 verb = data_for_callback[1];
886 /* Only list rooms to which the user has access!! */
887 CtdlRoomAccess(qrbuf, &CC->user, &ra, NULL);
889 || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
890 imap_mailboxname(buf, sizeof buf, qrbuf);
891 if (imap_mailbox_matches_pattern(pattern, buf)) {
892 cprintf("* %s () \"/\" ", verb);
901 * Implements the LIST and LSUB commands
903 void imap_list(int num_parms, char *parms[])
906 int subscribed_rooms_only = 0;
910 char *data_for_callback[3];
913 cprintf("%s BAD arguments invalid\r\n", parms[0]);
917 /* parms[1] is the IMAP verb being used (e.g. LIST or LSUB)
918 * This tells us how to behave, and what verb to return back to the caller
920 safestrncpy(verb, parms[1], sizeof verb);
922 for (i=0; i<j; ++i) {
923 verb[i] = toupper(verb[i]);
926 if (!strcasecmp(verb, "LSUB")) {
927 subscribed_rooms_only = 1;
930 snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
932 data_for_callback[0] = pattern;
933 data_for_callback[1] = verb;
934 data_for_callback[2] = "All your base are belong to us.";
936 if (strlen(parms[3]) == 0) {
937 cprintf("* %s (\\Noselect) \"/\" \"\"\r\n", verb);
941 imap_list_floors(verb, pattern);
943 (subscribed_rooms_only ? imap_lsub_listroom : imap_list_listroom),
948 cprintf("%s OK %s completed\r\n", parms[0], verb);
954 * Implements the CREATE command
957 void imap_create(int num_parms, char *parms[])
960 char roomname[ROOMNAMELEN];
966 if (strchr(parms[2], '\\') != NULL) {
967 cprintf("%s NO Invalid character in folder name\r\n",
969 lprintf(CTDL_DEBUG, "invalid character in folder name\n");
973 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
975 cprintf("%s NO Invalid mailbox name or location\r\n",
977 lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
980 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
981 flags = (ret & 0xff00); /* upper 8 bits = flags */
983 if (flags & IR_MAILBOX) {
984 if (strncasecmp(parms[2], "INBOX/", 6)) {
985 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
986 lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
991 if (flags & IR_MAILBOX) {
992 newroomtype = 4; /* private mailbox */
993 newroomview = VIEW_MAILBOX;
995 newroomtype = 0; /* public folder */
996 newroomview = VIEW_BBS;
999 lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
1000 roomname, floornum, newroomtype);
1002 ret = create_room(roomname, newroomtype, "", floornum, 1, 0, newroomview);
1004 /*** DO NOT CHANGE THIS ERROR MESSAGE IN ANY WAY! BYNARI CONNECTOR DEPENDS ON IT! ***/
1005 cprintf("%s NO Mailbox already exists, or create failed\r\n", parms[0]);
1007 cprintf("%s OK CREATE completed\r\n", parms[0]);
1009 lprintf(CTDL_DEBUG, "imap_create() completed\n");
1014 * Locate a room by its IMAP folder name, and check access to it.
1015 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
1017 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
1020 char augmented_roomname[ROOMNAMELEN];
1021 char roomname[ROOMNAMELEN];
1023 struct ctdlroom QRscratch;
1027 ret = imap_roomname(roomname, sizeof roomname, foldername);
1032 /* First try a regular match */
1033 c = getroom(&QRscratch, roomname);
1035 /* Then try a mailbox name match */
1037 MailboxName(augmented_roomname, sizeof augmented_roomname,
1038 &CC->user, roomname);
1039 c = getroom(&QRscratch, augmented_roomname);
1041 strcpy(roomname, augmented_roomname);
1044 /* If the room exists, check security/access */
1046 /* See if there is an existing user/room relationship */
1047 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1049 /* normal clients have to pass through security */
1050 if (ra & UA_KNOWN) {
1053 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1058 /* Fail here if no such room */
1060 strcpy(returned_roomname, "");
1063 strcpy(returned_roomname, QRscratch.QRname);
1070 * Implements the STATUS command (sort of)
1073 void imap_status(int num_parms, char *parms[])
1076 char roomname[ROOMNAMELEN];
1078 char savedroom[ROOMNAMELEN];
1081 ret = imap_grabroom(roomname, parms[2], 0);
1084 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1090 * usergoto() formally takes us to the desired room, happily returning
1091 * the number of messages and number of new messages. (If another
1092 * folder is selected, save its name so we can return there!!!!!)
1094 if (IMAP->selected) {
1095 strcpy(savedroom, CC->room.QRname);
1097 usergoto(roomname, 0, 0, &msgs, &new);
1100 * Tell the client what it wants to know. In fact, tell it *more* than
1101 * it wants to know. We happily IGnore the supplied status data item
1102 * names and simply spew all possible data items. It's far easier to
1103 * code and probably saves us some processing time too.
1105 imap_mailboxname(buf, sizeof buf, &CC->room);
1106 cprintf("* STATUS ");
1108 cprintf(" (MESSAGES %d ", msgs);
1109 cprintf("RECENT %d ", new); /* Initially, new==recent */
1110 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1111 cprintf("UNSEEN %d)\r\n", new);
1114 * If another folder is selected, go back to that room so we can resume
1115 * our happy day without violent explosions.
1117 if (IMAP->selected) {
1118 usergoto(savedroom, 0, 0, &msgs, &new);
1122 * Oooh, look, we're done!
1124 cprintf("%s OK STATUS completed\r\n", parms[0]);
1130 * Implements the SUBSCRIBE command
1133 void imap_subscribe(int num_parms, char *parms[])
1136 char roomname[ROOMNAMELEN];
1137 char savedroom[ROOMNAMELEN];
1140 ret = imap_grabroom(roomname, parms[2], 1);
1143 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1151 * usergoto() formally takes us to the desired room, which has the side
1152 * effect of marking the room as not-zapped ... exactly the effect
1153 * we're looking for.
1155 if (IMAP->selected) {
1156 strcpy(savedroom, CC->room.QRname);
1158 usergoto(roomname, 0, 0, &msgs, &new);
1161 * If another folder is selected, go back to that room so we can resume
1162 * our happy day without violent explosions.
1164 if (IMAP->selected) {
1165 usergoto(savedroom, 0, 0, &msgs, &new);
1168 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1173 * Implements the UNSUBSCRIBE command
1176 void imap_unsubscribe(int num_parms, char *parms[])
1179 char roomname[ROOMNAMELEN];
1180 char savedroom[ROOMNAMELEN];
1183 ret = imap_grabroom(roomname, parms[2], 0);
1186 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1192 * usergoto() formally takes us to the desired room.
1194 if (IMAP->selected) {
1195 strcpy(savedroom, CC->room.QRname);
1197 usergoto(roomname, 0, 0, &msgs, &new);
1200 * Now make the API call to zap the room
1202 if (CtdlForgetThisRoom() == 0) {
1203 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1206 ("%s NO You may not unsubscribe from this folder.\r\n",
1211 * If another folder is selected, go back to that room so we can resume
1212 * our happy day without violent explosions.
1214 if (IMAP->selected) {
1215 usergoto(savedroom, 0, 0, &msgs, &new);
1222 * Implements the DELETE command
1225 void imap_delete(int num_parms, char *parms[])
1228 char roomname[ROOMNAMELEN];
1229 char savedroom[ROOMNAMELEN];
1232 ret = imap_grabroom(roomname, parms[2], 1);
1234 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1240 * usergoto() formally takes us to the desired room, happily returning
1241 * the number of messages and number of new messages. (If another
1242 * folder is selected, save its name so we can return there!!!!!)
1244 if (IMAP->selected) {
1245 strcpy(savedroom, CC->room.QRname);
1247 usergoto(roomname, 0, 0, &msgs, &new);
1250 * Now delete the room.
1252 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1253 schedule_room_for_deletion(&CC->room);
1254 cprintf("%s OK DELETE completed\r\n", parms[0]);
1256 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1260 * If another folder is selected, go back to that room so we can resume
1261 * our happy day without violent explosions.
1263 if (IMAP->selected) {
1264 usergoto(savedroom, 0, 0, &msgs, &new);
1270 * Back end function for imap_rename()
1272 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1274 char foldername[SIZ];
1275 char newfoldername[SIZ];
1276 char newroomname[ROOMNAMELEN];
1278 struct irl *irlp = NULL; /* scratch pointer */
1279 struct irlparms *irlparms;
1281 irlparms = (struct irlparms *) data;
1282 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1284 /* Rename subfolders */
1285 if ((!strncasecmp(foldername, irlparms->oldname,
1286 strlen(irlparms->oldname))
1287 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1289 sprintf(newfoldername, "%s/%s",
1291 &foldername[strlen(irlparms->oldname) + 1]
1294 newfloor = imap_roomname(newroomname,
1296 newfoldername) & 0xFF;
1298 irlp = (struct irl *) malloc(sizeof(struct irl));
1299 strcpy(irlp->irl_newroom, newroomname);
1300 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1301 irlp->irl_newfloor = newfloor;
1302 irlp->next = *(irlparms->irl);
1303 *(irlparms->irl) = irlp;
1309 * Implements the RENAME command
1312 void imap_rename(int num_parms, char *parms[])
1314 char old_room[ROOMNAMELEN];
1315 char new_room[ROOMNAMELEN];
1319 struct irl *irl = NULL; /* the list */
1320 struct irl *irlp = NULL; /* scratch pointer */
1321 struct irlparms irlparms;
1323 if (strchr(parms[3], '\\') != NULL) {
1324 cprintf("%s NO Invalid character in folder name\r\n",
1329 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1330 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1331 new_floor = (newr & 0xFF);
1333 r = CtdlRenameRoom(old_room, new_room, new_floor);
1335 if (r == crr_room_not_found) {
1336 cprintf("%s NO Could not locate this folder\r\n",
1340 if (r == crr_already_exists) {
1341 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1344 if (r == crr_noneditable) {
1345 cprintf("%s This folder is not editable.\r\n", parms[0]);
1348 if (r == crr_invalid_floor) {
1349 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1352 if (r == crr_access_denied) {
1353 cprintf("%s You do not have permission to edit "
1354 "this folder.\r\n", parms[0]);
1358 cprintf("%s NO Rename failed - undefined error %d\r\n",
1364 /* If this is the INBOX, then RFC2060 says we have to just move the
1365 * contents. In a Citadel environment it's easier to rename the room
1366 * (already did that) and create a new inbox.
1368 if (!strcasecmp(parms[2], "INBOX")) {
1369 create_room(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1372 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1374 irlparms.oldname = parms[2];
1375 irlparms.newname = parms[3];
1376 irlparms.irl = &irl;
1377 ForEachRoom(imap_rename_backend, (void *) &irlparms);
1379 /* ... and now rename them. */
1380 while (irl != NULL) {
1381 r = CtdlRenameRoom(irl->irl_oldroom,
1385 /* FIXME handle error returns better */
1386 lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n", r);
1394 cprintf("%s OK RENAME completed\r\n", parms[0]);
1401 * Main command loop for IMAP sessions.
1403 void imap_command_loop(void)
1408 struct timeval tv1, tv2;
1409 suseconds_t total_time = 0;
1411 gettimeofday(&tv1, NULL);
1412 CC->lastcmd = time(NULL);
1413 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1415 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1416 lprintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1421 if (IMAP->authstate == imap_as_expecting_password) {
1422 lprintf(CTDL_INFO, "IMAP: <password>\n");
1424 else if (bmstrcasestr(cmdbuf, " LOGIN ")) {
1425 lprintf(CTDL_INFO, "IMAP: LOGIN...\n");
1428 lprintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1431 while (strlen(cmdbuf) < 5)
1432 strcat(cmdbuf, " ");
1434 /* strip off l/t whitespace and CRLF */
1435 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1436 cmdbuf[strlen(cmdbuf) - 1] = 0;
1437 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1438 cmdbuf[strlen(cmdbuf) - 1] = 0;
1441 /* If we're in the middle of a multi-line command, handle that */
1442 if (IMAP->authstate == imap_as_expecting_username) {
1443 imap_auth_login_user(cmdbuf);
1446 if (IMAP->authstate == imap_as_expecting_password) {
1447 imap_auth_login_pass(cmdbuf);
1451 /* Ok, at this point we're in normal command mode. The first thing
1452 * we do is print any incoming pages (yeah! we really do!)
1454 imap_print_instant_messages();
1457 * Before processing the command that was just entered... if we happen
1458 * to have a folder selected, we'd like to rescan that folder for new
1459 * messages, and for deletions/changes of existing messages. This
1460 * could probably be optimized somehow, but IMAP sucks...
1462 if (IMAP->selected) {
1463 imap_rescan_msgids();
1466 /* Now for the command set. */
1468 /* Grab the tag, command, and parameters. Check syntax. */
1469 num_parms = imap_parameterize(parms, cmdbuf);
1470 if (num_parms < 2) {
1471 cprintf("BAD syntax error\r\n");
1474 /* The commands below may be executed in any state */
1476 else if ((!strcasecmp(parms[1], "NOOP"))
1477 || (!strcasecmp(parms[1], "CHECK"))) {
1478 cprintf("%s OK No operation\r\n",
1482 else if (!strcasecmp(parms[1], "ID")) {
1483 imap_id(num_parms, parms);
1487 else if (!strcasecmp(parms[1], "LOGOUT")) {
1488 if (IMAP->selected) {
1489 imap_do_expunge(); /* yes, we auto-expunge */
1491 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1492 cprintf("%s OK Citadel IMAP session ended.\r\n",
1498 else if (!strcasecmp(parms[1], "LOGIN")) {
1499 imap_login(num_parms, parms);
1502 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1503 imap_authenticate(num_parms, parms);
1506 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1507 imap_capability(num_parms, parms);
1510 else if (!strcasecmp(parms[1], "STARTTLS")) {
1511 imap_starttls(num_parms, parms);
1514 else if (!CC->logged_in) {
1515 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1518 /* The commans below require a logged-in state */
1520 else if (!strcasecmp(parms[1], "SELECT")) {
1521 imap_select(num_parms, parms);
1524 else if (!strcasecmp(parms[1], "EXAMINE")) {
1525 imap_select(num_parms, parms);
1528 else if (!strcasecmp(parms[1], "LSUB")) {
1529 imap_list(num_parms, parms);
1532 else if (!strcasecmp(parms[1], "LIST")) {
1533 imap_list(num_parms, parms);
1536 else if (!strcasecmp(parms[1], "CREATE")) {
1537 imap_create(num_parms, parms);
1540 else if (!strcasecmp(parms[1], "DELETE")) {
1541 imap_delete(num_parms, parms);
1544 else if (!strcasecmp(parms[1], "RENAME")) {
1545 imap_rename(num_parms, parms);
1548 else if (!strcasecmp(parms[1], "STATUS")) {
1549 imap_status(num_parms, parms);
1552 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1553 imap_subscribe(num_parms, parms);
1556 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1557 imap_unsubscribe(num_parms, parms);
1560 else if (!strcasecmp(parms[1], "APPEND")) {
1561 imap_append(num_parms, parms);
1564 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1565 imap_namespace(num_parms, parms);
1568 else if (!strcasecmp(parms[1], "SETACL")) {
1569 imap_setacl(num_parms, parms);
1572 else if (!strcasecmp(parms[1], "DELETEACL")) {
1573 imap_deleteacl(num_parms, parms);
1576 else if (!strcasecmp(parms[1], "GETACL")) {
1577 imap_getacl(num_parms, parms);
1580 else if (!strcasecmp(parms[1], "LISTRIGHTS")) {
1581 imap_listrights(num_parms, parms);
1584 else if (!strcasecmp(parms[1], "MYRIGHTS")) {
1585 imap_myrights(num_parms, parms);
1588 else if (IMAP->selected == 0) {
1589 cprintf("%s BAD no folder selected\r\n", parms[0]);
1592 /* The commands below require the SELECT state on a mailbox */
1594 else if (!strcasecmp(parms[1], "FETCH")) {
1595 imap_fetch(num_parms, parms);
1598 else if ((!strcasecmp(parms[1], "UID"))
1599 && (!strcasecmp(parms[2], "FETCH"))) {
1600 imap_uidfetch(num_parms, parms);
1603 else if (!strcasecmp(parms[1], "SEARCH")) {
1604 imap_search(num_parms, parms);
1607 else if ((!strcasecmp(parms[1], "UID"))
1608 && (!strcasecmp(parms[2], "SEARCH"))) {
1609 imap_uidsearch(num_parms, parms);
1612 else if (!strcasecmp(parms[1], "STORE")) {
1613 imap_store(num_parms, parms);
1616 else if ((!strcasecmp(parms[1], "UID"))
1617 && (!strcasecmp(parms[2], "STORE"))) {
1618 imap_uidstore(num_parms, parms);
1621 else if (!strcasecmp(parms[1], "COPY")) {
1622 imap_copy(num_parms, parms);
1625 else if ((!strcasecmp(parms[1], "UID"))
1626 && (!strcasecmp(parms[2], "COPY"))) {
1627 imap_uidcopy(num_parms, parms);
1630 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1631 imap_expunge(num_parms, parms);
1634 else if (!strcasecmp(parms[1], "CLOSE")) {
1635 imap_close(num_parms, parms);
1638 /* End of commands. If we get here, the command is either invalid
1643 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1646 /* If the client transmitted a message we can free it now */
1647 imap_free_transmitted_message();
1649 gettimeofday(&tv2, NULL);
1650 total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1651 lprintf(CTDL_DEBUG, "IMAP command completed in %ld.%ld seconds\n",
1652 (total_time / 1000000),
1653 (total_time % 1000000)
1659 * This function is called to register the IMAP extension with Citadel.
1661 char *serv_imap_init(void)
1663 CtdlRegisterServiceHook(config.c_imap_port,
1664 NULL, imap_greeting, imap_command_loop, NULL);
1666 CtdlRegisterServiceHook(config.c_imaps_port,
1667 NULL, imaps_greeting, imap_command_loop, NULL);
1669 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);