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"
62 #include "internet_addressing.h"
63 #include "serv_imap.h"
64 #include "imap_tools.h"
65 #include "imap_list.h"
66 #include "imap_fetch.h"
67 #include "imap_search.h"
68 #include "imap_store.h"
70 #include "imap_metadata.h"
71 #include "imap_misc.h"
73 #include "ctdl_module.h"
76 /* imap_rename() uses this struct containing list of rooms to rename */
79 char irl_oldroom[ROOMNAMELEN];
80 char irl_newroom[ROOMNAMELEN];
84 /* Data which is passed between imap_rename() and imap_rename_backend() */
93 * If there is a message ID map in memory, free it
95 void imap_free_msgids(void)
97 if (IMAP->msgids != NULL) {
103 if (IMAP->flags != NULL) {
107 IMAP->last_mtime = (-1);
112 * If there is a transmitted message in memory, free it
114 void imap_free_transmitted_message(void)
116 if (IMAP->transmitted_message != NULL) {
117 free(IMAP->transmitted_message);
118 IMAP->transmitted_message = NULL;
119 IMAP->transmitted_length = 0;
125 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
126 * sets stored in the visit record for this user/room. Note that we have
127 * to parse each sequence set manually here, because calling the utility
128 * function is_msg_in_sequence_set() over and over again is too expensive.
130 * first_msg should be set to 0 to rescan the flags for every message in the
131 * room, or some other value if we're only interested in an incremental
134 void imap_set_seen_flags(int first_msg)
140 char setstr[64], lostr[64], histr[64];
143 if (IMAP->num_msgs < 1) return;
144 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
146 for (i = first_msg; i < IMAP->num_msgs; ++i) {
147 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
148 IMAP->flags[i] |= IMAP_RECENT;
149 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
153 * Do the "\Seen" flag.
154 * (Any message not "\Seen" is considered "\Recent".)
156 num_sets = num_tokens(vbuf.v_seen, ',');
157 for (s=0; s<num_sets; ++s) {
158 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
160 extract_token(lostr, setstr, 0, ':', sizeof lostr);
161 if (num_tokens(setstr, ':') >= 2) {
162 extract_token(histr, setstr, 1, ':', sizeof histr);
163 if (!strcmp(histr, "*")) {
164 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
168 strcpy(histr, lostr);
173 for (i = first_msg; i < IMAP->num_msgs; ++i) {
174 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
175 IMAP->flags[i] |= IMAP_SEEN;
176 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
181 /* Do the ANSWERED flag */
182 num_sets = num_tokens(vbuf.v_answered, ',');
183 for (s=0; s<num_sets; ++s) {
184 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
186 extract_token(lostr, setstr, 0, ':', sizeof lostr);
187 if (num_tokens(setstr, ':') >= 2) {
188 extract_token(histr, setstr, 1, ':', sizeof histr);
189 if (!strcmp(histr, "*")) {
190 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
194 strcpy(histr, lostr);
199 for (i = first_msg; i < IMAP->num_msgs; ++i) {
200 if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
201 IMAP->flags[i] |= IMAP_ANSWERED;
211 * Back end for imap_load_msgids()
213 * Optimization: instead of calling realloc() to add each message, we
214 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
215 * allows the mapping to proceed much faster.
217 void imap_add_single_msgid(long msgnum, void *userdata)
221 if (IMAP->num_msgs > IMAP->num_alloc) {
222 IMAP->num_alloc += REALLOC_INCREMENT;
223 IMAP->msgids = realloc(IMAP->msgids, (IMAP->num_alloc * sizeof(long)) );
224 IMAP->flags = realloc(IMAP->flags, (IMAP->num_alloc * sizeof(long)) );
226 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
227 IMAP->flags[IMAP->num_msgs - 1] = 0;
233 * Set up a message ID map for the current room (folder)
235 void imap_load_msgids(void)
237 struct cdbdata *cdbfr;
239 if (IMAP->selected == 0) {
240 CtdlLogPrintf(CTDL_ERR,
241 "imap_load_msgids() can't run; no room selected\n");
245 imap_free_msgids(); /* If there was already a map, free it */
247 /* Load the message list */
248 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
250 IMAP->msgids = malloc(cdbfr->len);
251 memcpy(IMAP->msgids, cdbfr->ptr, cdbfr->len);
252 IMAP->num_msgs = cdbfr->len / sizeof(long);
253 IMAP->num_alloc = cdbfr->len / sizeof(long);
257 if (IMAP->num_msgs) {
258 IMAP->flags = malloc(IMAP->num_alloc * sizeof(long));
259 memset(IMAP->flags, 0, (IMAP->num_alloc * sizeof(long)) );
262 imap_set_seen_flags(0);
267 * Re-scan the selected room (folder) and see if it's been changed at all
269 void imap_rescan_msgids(void)
272 int original_num_msgs = 0;
273 long original_highest = 0L;
275 int message_still_exists;
276 struct cdbdata *cdbfr;
277 long *msglist = NULL;
281 if (IMAP->selected == 0) {
282 CtdlLogPrintf(CTDL_ERR, "imap_load_msgids() can't run; no room selected\n");
287 * Check to see if the room's contents have changed.
288 * If not, we can avoid this rescan.
290 CtdlGetRoom(&CC->room, CC->room.QRname);
291 if (IMAP->last_mtime == CC->room.QRmtime) { /* No changes! */
295 /* Load the *current* message list from disk, so we can compare it
296 * to what we have in memory.
298 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
300 msglist = malloc(cdbfr->len);
301 if (msglist == NULL) {
302 CtdlLogPrintf(CTDL_CRIT, "malloc() failed\n");
305 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
306 num_msgs = cdbfr->len / sizeof(long);
313 * Check to see if any of the messages we know about have been expunged
315 if (IMAP->num_msgs > 0) {
317 for (i = 0; i < IMAP->num_msgs; ++i) {
319 message_still_exists = 0;
321 for (j = jstart; j < num_msgs; ++j) {
322 if (msglist[j] == IMAP->msgids[i]) {
323 message_still_exists = 1;
330 if (message_still_exists == 0) {
331 cprintf("* %d EXPUNGE\r\n", i + 1);
333 /* Here's some nice stupid nonsense. When a
334 * message is expunged, we have to slide all
335 * the existing messages up in the message
339 memcpy(&IMAP->msgids[i],
340 &IMAP->msgids[i + 1],
342 (IMAP->num_msgs - i)));
343 memcpy(&IMAP->flags[i],
346 (IMAP->num_msgs - i)));
355 * Remember how many messages were here before we re-scanned.
357 original_num_msgs = IMAP->num_msgs;
358 if (IMAP->num_msgs > 0) {
359 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
361 original_highest = 0L;
365 * Now peruse the room for *new* messages only.
366 * This logic is probably the cause of Bug # 368
367 * [ http://bugzilla.citadel.org/show_bug.cgi?id=368 ]
370 for (j = 0; j < num_msgs; ++j) {
371 if (msglist[j] > original_highest) {
372 imap_add_single_msgid(msglist[j], NULL);
376 imap_set_seen_flags(original_num_msgs);
379 * If new messages have arrived, tell the client about them.
381 if (IMAP->num_msgs > original_num_msgs) {
383 for (j = 0; j < num_msgs; ++j) {
384 if (IMAP->flags[j] & IMAP_RECENT) {
389 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
390 cprintf("* %d RECENT\r\n", num_recent);
396 IMAP->last_mtime = CC->room.QRmtime;
401 * This cleanup function blows away the temporary memory and files used by
404 void imap_cleanup_function(void)
407 /* Don't do this stuff if this is not a IMAP session! */
408 if (CC->h_command_function != imap_command_loop)
411 /* If there is a mailbox selected, auto-expunge it. */
412 if (IMAP->selected) {
416 CtdlLogPrintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
418 imap_free_transmitted_message();
420 if (IMAP->cached_rfc822_data != NULL) {
421 free(IMAP->cached_rfc822_data);
422 IMAP->cached_rfc822_data = NULL;
423 IMAP->cached_rfc822_msgnum = (-1);
424 IMAP->cached_rfc822_withbody = 0;
427 if (IMAP->cached_body != NULL) {
428 free(IMAP->cached_body);
429 IMAP->cached_body = NULL;
430 IMAP->cached_body_len = 0;
431 IMAP->cached_bodymsgnum = (-1);
435 CtdlLogPrintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
440 * Does the actual work of the CAPABILITY command (because we need to
441 * output this stuff in other places as well)
443 void imap_output_capability_string(void) {
444 cprintf("CAPABILITY IMAP4REV1 NAMESPACE ID AUTH=PLAIN AUTH=LOGIN UIDPLUS");
447 if (!CC->redirect_ssl) cprintf(" STARTTLS");
450 #ifndef DISABLE_IMAP_ACL
454 /* We are building a partial implementation of METADATA for the sole purpose
455 * of interoperating with the ical/vcard version of the Bynari Insight Connector.
456 * It is not a full RFC5464 implementation, but it should refuse non-Bynari
457 * metadata in a compatible and graceful way.
459 cprintf(" METADATA");
462 * LIST-EXTENDED was originally going to be required by the METADATA extension.
463 * It was mercifully removed prior to the finalization of RFC5464. We started
464 * implementing this but stopped when we learned that it would not be needed.
465 * If you uncomment this declaration you are responsible for writing a lot of new
468 * cprintf(" LIST-EXTENDED")
474 * implements the CAPABILITY command
476 void imap_capability(int num_parms, char *parms[])
479 imap_output_capability_string();
481 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
486 * Implements the ID command (specified by RFC2971)
488 * We ignore the client-supplied information, and output a NIL response.
489 * Although this is technically a valid implementation of the extension, it
490 * is quite useless. It exists only so that we may see which clients are
491 * making use of this extension.
494 void imap_id(int num_parms, char *parms[])
496 cprintf("* ID NIL\r\n");
497 cprintf("%s OK ID completed\r\n", parms[0]);
502 * Here's where our IMAP session begins its happy day.
504 void imap_greeting(void)
507 strcpy(CC->cs_clientname, "IMAP session");
508 CC->session_specific_data = malloc(sizeof(struct citimap));
509 memset(IMAP, 0, sizeof(struct citimap));
510 IMAP->authstate = imap_as_normal;
511 IMAP->cached_rfc822_data = NULL;
512 IMAP->cached_rfc822_msgnum = (-1);
513 IMAP->cached_rfc822_withbody = 0;
517 cprintf("* BYE; Server busy, try later\r\n");
522 imap_output_capability_string();
523 cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
528 * IMAPS is just like IMAP, except it goes crypto right away.
530 void imaps_greeting(void) {
531 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
533 if (!CC->redirect_ssl) CC->kill_me = 1; /* kill session if no crypto */
540 * implements the LOGIN command (ordinary username/password login)
542 void imap_login(int num_parms, char *parms[])
547 if (parms[2][0] == '{') {
548 cprintf("+ go ahead\r\n");
549 IMAP->authstate = imap_as_expecting_multilineusername;
550 strcpy(IMAP->authseq, parms[0]);
554 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
558 if (CtdlLoginExistingUser(NULL, parms[2]) == login_ok) {
559 if (CtdlTryPassword(parms[3]) == pass_ok) {
560 cprintf("%s OK [", parms[0]);
561 imap_output_capability_string();
562 cprintf("] Hello, %s\r\n", CC->user.fullname);
567 cprintf("%s BAD Login incorrect\r\n", parms[0]);
569 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
577 * Implements the AUTHENTICATE command
579 void imap_authenticate(int num_parms, char *parms[])
583 if (num_parms != 3) {
584 cprintf("%s BAD incorrect number of parameters\r\n",
590 cprintf("%s BAD Already logged in.\r\n", parms[0]);
594 if (!strcasecmp(parms[2], "LOGIN")) {
595 CtdlEncodeBase64(buf, "Username:", 9, 0);
596 cprintf("+ %s\r\n", buf);
597 IMAP->authstate = imap_as_expecting_username;
598 strcpy(IMAP->authseq, parms[0]);
602 if (!strcasecmp(parms[2], "PLAIN")) {
603 // CtdlEncodeBase64(buf, "Username:", 9, 0);
604 // cprintf("+ %s\r\n", buf);
606 IMAP->authstate = imap_as_expecting_plainauth;
607 strcpy(IMAP->authseq, parms[0]);
612 cprintf("%s NO AUTHENTICATE %s failed\r\n",
618 void imap_auth_plain(char *cmd)
620 char decoded_authstring[1024];
626 memset(pass, 0, sizeof(pass));
627 CtdlDecodeBase64(decoded_authstring, cmd, strlen(cmd));
628 safestrncpy(ident, decoded_authstring, sizeof ident);
629 safestrncpy(user, &decoded_authstring[strlen(ident) + 1], sizeof user);
630 safestrncpy(pass, &decoded_authstring[strlen(ident) + strlen(user) + 2], sizeof pass);
632 IMAP->authstate = imap_as_normal;
634 if (!IsEmptyStr(ident)) {
635 result = CtdlLoginExistingUser(user, ident);
638 result = CtdlLoginExistingUser(NULL, user);
641 if (result == login_ok) {
642 if (CtdlTryPassword(pass) == pass_ok) {
643 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
647 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
651 void imap_auth_login_user(char *cmd, long state)
656 case imap_as_expecting_username:
657 CtdlDecodeBase64(buf, cmd, SIZ);
658 CtdlLoginExistingUser(NULL, buf);
659 CtdlEncodeBase64(buf, "Password:", 9, 0);
660 cprintf("+ %s\r\n", buf);
662 IMAP->authstate = imap_as_expecting_password;
664 case imap_as_expecting_multilineusername:
665 extract_token(buf, cmd, 1, ' ', sizeof(buf));
666 CtdlLoginExistingUser(NULL, cmd);
667 cprintf("+ go ahead\r\n");
668 IMAP->authstate = imap_as_expecting_multilinepassword;
674 void imap_auth_login_pass(char *cmd, long state)
681 case imap_as_expecting_password:
682 memset(buf, 0, sizeof(buf));
683 CtdlDecodeBase64(buf, cmd, SIZ);
686 case imap_as_expecting_multilinepassword:
690 if (CtdlTryPassword(pass) == pass_ok) {
691 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
693 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
695 IMAP->authstate = imap_as_normal;
701 * implements the STARTTLS command (Citadel API version)
703 void imap_starttls(int num_parms, char *parms[])
705 char ok_response[SIZ];
706 char nosup_response[SIZ];
707 char error_response[SIZ];
709 sprintf(ok_response, "%s OK begin TLS negotiation now\r\n", parms[0]);
710 sprintf(nosup_response, "%s NO TLS not supported here\r\n", parms[0]);
711 sprintf(error_response, "%s BAD Internal error\r\n", parms[0]);
712 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
717 * implements the SELECT command
719 void imap_select(int num_parms, char *parms[])
722 char augmented_roomname[ROOMNAMELEN];
726 struct ctdlroom QRscratch;
732 /* Convert the supplied folder name to a roomname */
733 i = imap_roomname(towhere, sizeof towhere, parms[2]);
735 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
739 floornum = (i & 0x00ff);
740 roomflags = (i & 0xff00);
742 /* First try a regular match */
743 c = CtdlGetRoom(&QRscratch, towhere);
745 /* Then try a mailbox name match */
747 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, towhere);
748 c = CtdlGetRoom(&QRscratch, augmented_roomname);
750 strcpy(towhere, augmented_roomname);
754 /* If the room exists, check security/access */
756 /* See if there is an existing user/room relationship */
757 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
759 /* normal clients have to pass through security */
765 /* Fail here if no such room */
767 cprintf("%s NO ... no such room, or access denied\r\n", parms[0]);
771 /* If we already had some other folder selected, auto-expunge it */
775 * CtdlUserGoto() formally takes us to the desired room, happily returning
776 * the number of messages and number of new messages.
778 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
779 CtdlUserGoto(NULL, 0, 0, &msgs, &new);
782 if (!strcasecmp(parms[1], "EXAMINE")) {
789 IMAP->last_mtime = CC->room.QRmtime;
791 cprintf("* %d EXISTS\r\n", msgs);
792 cprintf("* %d RECENT\r\n", new);
794 cprintf("* OK [UIDVALIDITY %ld] UID validity status\r\n", GLOBAL_UIDVALIDITY_VALUE);
795 cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
797 /* Technically, \Deleted is a valid flag, but not a permanent flag,
798 * because we don't maintain its state across sessions. Citadel
799 * automatically expunges mailboxes when they are de-selected.
801 * Unfortunately, omitting \Deleted as a PERMANENTFLAGS flag causes
802 * some clients (particularly Thunderbird) to misbehave -- they simply
803 * elect not to transmit the flag at all. So we have to advertise
804 * \Deleted as a PERMANENTFLAGS flag, even though it technically isn't.
806 cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
807 cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] permanent flags\r\n");
809 cprintf("%s OK [%s] %s completed\r\n",
811 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]
817 * Does the real work for expunge.
819 int imap_do_expunge(void)
822 int num_expunged = 0;
823 long *delmsgs = NULL;
826 CtdlLogPrintf(CTDL_DEBUG, "imap_do_expunge() called\n");
827 if (IMAP->selected == 0) {
831 if (IMAP->num_msgs > 0) {
832 delmsgs = malloc(IMAP->num_msgs * sizeof(long));
833 for (i = 0; i < IMAP->num_msgs; ++i) {
834 if (IMAP->flags[i] & IMAP_DELETED) {
835 delmsgs[num_delmsgs++] = IMAP->msgids[i];
838 if (num_delmsgs > 0) {
839 CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
841 num_expunged += num_delmsgs;
845 if (num_expunged > 0) {
846 imap_rescan_msgids();
849 CtdlLogPrintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n", num_expunged, CC->room.QRname);
850 return (num_expunged);
855 * implements the EXPUNGE command syntax
857 void imap_expunge(int num_parms, char *parms[])
859 int num_expunged = 0;
861 num_expunged = imap_do_expunge();
862 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
867 * implements the CLOSE command
869 void imap_close(int num_parms, char *parms[])
872 /* Yes, we always expunge on close. */
873 if (IMAP->selected) {
880 cprintf("%s OK CLOSE completed\r\n", parms[0]);
885 * Implements the NAMESPACE command.
887 void imap_namespace(int num_parms, char *parms[])
894 cprintf("* NAMESPACE ");
896 /* All personal folders are subordinate to INBOX. */
897 cprintf("((\"INBOX/\" \"/\")) ");
899 /* Other users' folders ... coming soon! FIXME */
902 /* Show all floors as shared namespaces. Neato! */
904 for (i = 0; i < MAXFLOORS; ++i) {
905 fl = CtdlGetCachedFloor(i);
906 if (fl->f_flags & F_INUSE) {
907 if (floors > 0) cprintf(" ");
909 sprintf(buf, "%s/", fl->f_name);
917 /* Wind it up with a newline and a completion message. */
919 cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
924 * Implements the CREATE command
927 void imap_create(int num_parms, char *parms[])
930 char roomname[ROOMNAMELEN];
935 char *notification_message = NULL;
938 cprintf("%s NO A foder name must be specified\r\n", parms[0]);
942 if (strchr(parms[2], '\\') != NULL) {
943 cprintf("%s NO Invalid character in folder name\r\n", parms[0]);
944 CtdlLogPrintf(CTDL_DEBUG, "invalid character in folder name\n");
948 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
950 cprintf("%s NO Invalid mailbox name or location\r\n",
952 CtdlLogPrintf(CTDL_DEBUG, "invalid mailbox name or location\n");
955 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
956 flags = (ret & 0xff00); /* upper 8 bits = flags */
958 if (flags & IR_MAILBOX) {
959 if (strncasecmp(parms[2], "INBOX/", 6)) {
960 cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
961 CtdlLogPrintf(CTDL_DEBUG, "not subordinate to inbox\n");
966 if (flags & IR_MAILBOX) {
967 newroomtype = 4; /* private mailbox */
968 newroomview = VIEW_MAILBOX;
970 newroomtype = 0; /* public folder */
971 newroomview = VIEW_BBS;
974 CtdlLogPrintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
975 roomname, floornum, newroomtype);
977 ret = CtdlCreateRoom(roomname, newroomtype, "", floornum, 1, 0, newroomview);
979 /*** DO NOT CHANGE THIS ERROR MESSAGE IN ANY WAY! BYNARI CONNECTOR DEPENDS ON IT! ***/
980 cprintf("%s NO Mailbox already exists, or create failed\r\n", parms[0]);
982 cprintf("%s OK CREATE completed\r\n", parms[0]);
983 /* post a message in Aide> describing the new room */
984 notification_message = malloc(1024);
985 snprintf(notification_message, 1024,
986 "A new room called \"%s\" has been created by %s%s%s%s\n",
989 ((ret & QR_MAILBOX) ? " [personal]" : ""),
990 ((ret & QR_PRIVATE) ? " [private]" : ""),
991 ((ret & QR_GUESSNAME) ? " [hidden]" : "")
993 CtdlAideMessage(notification_message, "Room Creation Message");
994 free(notification_message);
996 CtdlLogPrintf(CTDL_DEBUG, "imap_create() completed\n");
1001 * Locate a room by its IMAP folder name, and check access to it.
1002 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
1004 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
1007 char augmented_roomname[ROOMNAMELEN];
1008 char roomname[ROOMNAMELEN];
1010 struct ctdlroom QRscratch;
1014 ret = imap_roomname(roomname, sizeof roomname, foldername);
1019 /* First try a regular match */
1020 c = CtdlGetRoom(&QRscratch, roomname);
1022 /* Then try a mailbox name match */
1024 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname,
1025 &CC->user, roomname);
1026 c = CtdlGetRoom(&QRscratch, augmented_roomname);
1028 strcpy(roomname, augmented_roomname);
1031 /* If the room exists, check security/access */
1033 /* See if there is an existing user/room relationship */
1034 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1036 /* normal clients have to pass through security */
1037 if (ra & UA_KNOWN) {
1040 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1045 /* Fail here if no such room */
1047 strcpy(returned_roomname, "");
1050 strcpy(returned_roomname, QRscratch.QRname);
1057 * Implements the STATUS command (sort of)
1060 void imap_status(int num_parms, char *parms[])
1063 char roomname[ROOMNAMELEN];
1065 char savedroom[ROOMNAMELEN];
1068 ret = imap_grabroom(roomname, parms[2], 1);
1071 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1077 * CtdlUserGoto() formally takes us to the desired room, happily returning
1078 * the number of messages and number of new messages. (If another
1079 * folder is selected, save its name so we can return there!!!!!)
1081 if (IMAP->selected) {
1082 strcpy(savedroom, CC->room.QRname);
1084 CtdlUserGoto(roomname, 0, 0, &msgs, &new);
1087 * Tell the client what it wants to know. In fact, tell it *more* than
1088 * it wants to know. We happily IGnore the supplied status data item
1089 * names and simply spew all possible data items. It's far easier to
1090 * code and probably saves us some processing time too.
1092 imap_mailboxname(buf, sizeof buf, &CC->room);
1093 cprintf("* STATUS ");
1095 cprintf(" (MESSAGES %d ", msgs);
1096 cprintf("RECENT %d ", new); /* Initially, new==recent */
1097 cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1098 cprintf("UNSEEN %d)\r\n", new);
1101 * If another folder is selected, go back to that room so we can resume
1102 * our happy day without violent explosions.
1104 if (IMAP->selected) {
1105 CtdlUserGoto(savedroom, 0, 0, &msgs, &new);
1109 * Oooh, look, we're done!
1111 cprintf("%s OK STATUS completed\r\n", parms[0]);
1116 * Implements the SUBSCRIBE command
1119 void imap_subscribe(int num_parms, char *parms[])
1122 char roomname[ROOMNAMELEN];
1123 char savedroom[ROOMNAMELEN];
1126 ret = imap_grabroom(roomname, parms[2], 1);
1129 "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1137 * CtdlUserGoto() formally takes us to the desired room, which has the side
1138 * effect of marking the room as not-zapped ... exactly the effect
1139 * we're looking for.
1141 if (IMAP->selected) {
1142 strcpy(savedroom, CC->room.QRname);
1144 CtdlUserGoto(roomname, 0, 0, &msgs, &new);
1147 * If another folder is selected, go back to that room so we can resume
1148 * our happy day without violent explosions.
1150 if (IMAP->selected) {
1151 CtdlUserGoto(savedroom, 0, 0, &msgs, &new);
1154 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1159 * Implements the UNSUBSCRIBE command
1162 void imap_unsubscribe(int num_parms, char *parms[])
1165 char roomname[ROOMNAMELEN];
1166 char savedroom[ROOMNAMELEN];
1169 ret = imap_grabroom(roomname, parms[2], 1);
1172 ("%s NO Invalid mailbox name or location, or access denied\r\n",
1178 * CtdlUserGoto() formally takes us to the desired room.
1180 if (IMAP->selected) {
1181 strcpy(savedroom, CC->room.QRname);
1183 CtdlUserGoto(roomname, 0, 0, &msgs, &new);
1186 * Now make the API call to zap the room
1188 if (CtdlForgetThisRoom() == 0) {
1189 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1192 ("%s NO You may not unsubscribe from this folder.\r\n",
1197 * If another folder is selected, go back to that room so we can resume
1198 * our happy day without violent explosions.
1200 if (IMAP->selected) {
1201 CtdlUserGoto(savedroom, 0, 0, &msgs, &new);
1207 * Implements the DELETE command
1210 void imap_delete(int num_parms, char *parms[])
1213 char roomname[ROOMNAMELEN];
1214 char savedroom[ROOMNAMELEN];
1217 ret = imap_grabroom(roomname, parms[2], 1);
1219 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1225 * CtdlUserGoto() formally takes us to the desired room, happily returning
1226 * the number of messages and number of new messages. (If another
1227 * folder is selected, save its name so we can return there!!!!!)
1229 if (IMAP->selected) {
1230 strcpy(savedroom, CC->room.QRname);
1232 CtdlUserGoto(roomname, 0, 0, &msgs, &new);
1235 * Now delete the room.
1237 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1238 CtdlScheduleRoomForDeletion(&CC->room);
1239 cprintf("%s OK DELETE completed\r\n", parms[0]);
1241 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1245 * If another folder is selected, go back to that room so we can resume
1246 * our happy day without violent explosions.
1248 if (IMAP->selected) {
1249 CtdlUserGoto(savedroom, 0, 0, &msgs, &new);
1255 * Back end function for imap_rename()
1257 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1259 char foldername[SIZ];
1260 char newfoldername[SIZ];
1261 char newroomname[ROOMNAMELEN];
1263 struct irl *irlp = NULL; /* scratch pointer */
1264 struct irlparms *irlparms;
1266 irlparms = (struct irlparms *) data;
1267 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1269 /* Rename subfolders */
1270 if ((!strncasecmp(foldername, irlparms->oldname,
1271 strlen(irlparms->oldname))
1272 && (foldername[strlen(irlparms->oldname)] == '/'))) {
1274 sprintf(newfoldername, "%s/%s",
1276 &foldername[strlen(irlparms->oldname) + 1]
1279 newfloor = imap_roomname(newroomname,
1281 newfoldername) & 0xFF;
1283 irlp = (struct irl *) malloc(sizeof(struct irl));
1284 strcpy(irlp->irl_newroom, newroomname);
1285 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1286 irlp->irl_newfloor = newfloor;
1287 irlp->next = *(irlparms->irl);
1288 *(irlparms->irl) = irlp;
1294 * Implements the RENAME command
1297 void imap_rename(int num_parms, char *parms[])
1299 char old_room[ROOMNAMELEN];
1300 char new_room[ROOMNAMELEN];
1304 struct irl *irl = NULL; /* the list */
1305 struct irl *irlp = NULL; /* scratch pointer */
1306 struct irlparms irlparms;
1309 if (strchr(parms[3], '\\') != NULL) {
1310 cprintf("%s NO Invalid character in folder name\r\n",
1315 oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1316 newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1317 new_floor = (newr & 0xFF);
1319 r = CtdlRenameRoom(old_room, new_room, new_floor);
1321 if (r == crr_room_not_found) {
1322 cprintf("%s NO Could not locate this folder\r\n",
1326 if (r == crr_already_exists) {
1327 cprintf("%s NO '%s' already exists.\r\n", parms[0], parms[2]);
1330 if (r == crr_noneditable) {
1331 cprintf("%s NO This folder is not editable.\r\n", parms[0]);
1334 if (r == crr_invalid_floor) {
1335 cprintf("%s NO Folder root does not exist.\r\n", parms[0]);
1338 if (r == crr_access_denied) {
1339 cprintf("%s NO You do not have permission to edit this folder.\r\n",
1344 cprintf("%s NO Rename failed - undefined error %d\r\n",
1349 /* If this is the INBOX, then RFC2060 says we have to just move the
1350 * contents. In a Citadel environment it's easier to rename the room
1351 * (already did that) and create a new inbox.
1353 if (!strcasecmp(parms[2], "INBOX")) {
1354 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1357 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1359 irlparms.oldname = parms[2];
1360 irlparms.newname = parms[3];
1361 irlparms.irl = &irl;
1362 CtdlForEachRoom(imap_rename_backend, (void *) &irlparms);
1364 /* ... and now rename them. */
1365 while (irl != NULL) {
1366 r = CtdlRenameRoom(irl->irl_oldroom,
1370 /* FIXME handle error returns better */
1371 CtdlLogPrintf(CTDL_ERR, "CtdlRenameRoom() error %d\n", r);
1379 snprintf(buf, sizeof buf, "IMAP folder \"%s\" renamed to \"%s\" by %s\n",
1384 CtdlAideMessage(buf, "IMAP folder rename");
1386 cprintf("%s OK RENAME completed\r\n", parms[0]);
1391 * Main command loop for IMAP sessions.
1393 void imap_command_loop(void)
1398 struct timeval tv1, tv2;
1399 suseconds_t total_time = 0;
1400 int untagged_ok = 1;
1402 gettimeofday(&tv1, NULL);
1403 CC->lastcmd = time(NULL);
1404 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1406 if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1407 CtdlLogPrintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1412 if (IMAP->authstate == imap_as_expecting_password) {
1413 CtdlLogPrintf(CTDL_INFO, "IMAP: <password>\n");
1415 else if (IMAP->authstate == imap_as_expecting_plainauth) {
1416 CtdlLogPrintf(CTDL_INFO, "IMAP: <plain_auth>\n");
1418 else if ((IMAP->authstate == imap_as_expecting_multilineusername) ||
1419 bmstrcasestr(cmdbuf, " LOGIN ")) {
1420 CtdlLogPrintf(CTDL_INFO, "IMAP: LOGIN...\n");
1423 CtdlLogPrintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1426 while (strlen(cmdbuf) < 5)
1427 strcat(cmdbuf, " ");
1429 /* strip off l/t whitespace and CRLF */
1430 if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1431 cmdbuf[strlen(cmdbuf) - 1] = 0;
1432 if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1433 cmdbuf[strlen(cmdbuf) - 1] = 0;
1436 /* If we're in the middle of a multi-line command, handle that */
1437 if (IMAP->authstate == imap_as_expecting_username) {
1438 imap_auth_login_user(cmdbuf, imap_as_expecting_username);
1441 if (IMAP->authstate == imap_as_expecting_multilineusername) {
1442 imap_auth_login_user(cmdbuf, imap_as_expecting_multilineusername);
1445 if (IMAP->authstate == imap_as_expecting_plainauth) {
1446 imap_auth_plain(cmdbuf);
1449 if (IMAP->authstate == imap_as_expecting_password) {
1450 imap_auth_login_pass(cmdbuf, imap_as_expecting_password);
1453 if (IMAP->authstate == imap_as_expecting_multilinepassword) {
1454 imap_auth_login_pass(cmdbuf, imap_as_expecting_multilinepassword);
1459 /* Ok, at this point we're in normal command mode.
1460 * If the command just submitted does not contain a literal, we
1461 * might think about delivering some untagged stuff...
1463 if (cmdbuf[strlen(cmdbuf)-1] == '}') {
1467 /* Grab the tag, command, and parameters. */
1468 num_parms = imap_parameterize(parms, cmdbuf);
1470 /* RFC3501 says that we cannot output untagged data during these commands */
1471 if (num_parms >= 2) {
1472 if ( (!strcasecmp(parms[1], "FETCH"))
1473 || (!strcasecmp(parms[1], "STORE"))
1474 || (!strcasecmp(parms[1], "SEARCH"))
1482 /* we can put any additional untagged stuff right here in the future */
1485 * Before processing the command that was just entered... if we happen
1486 * to have a folder selected, we'd like to rescan that folder for new
1487 * messages, and for deletions/changes of existing messages. This
1488 * could probably be optimized better with some deep thought...
1490 if (IMAP->selected) {
1491 imap_rescan_msgids();
1495 /* Now for the command set. */
1497 if (num_parms < 2) {
1498 cprintf("BAD syntax error\r\n");
1501 /* The commands below may be executed in any state */
1503 else if ((!strcasecmp(parms[1], "NOOP"))
1504 || (!strcasecmp(parms[1], "CHECK"))) {
1505 cprintf("%s OK No operation\r\n",
1509 else if (!strcasecmp(parms[1], "ID")) {
1510 imap_id(num_parms, parms);
1514 else if (!strcasecmp(parms[1], "LOGOUT")) {
1515 if (IMAP->selected) {
1516 imap_do_expunge(); /* yes, we auto-expunge at logout */
1518 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1519 cprintf("%s OK Citadel IMAP session ended.\r\n",
1525 else if (!strcasecmp(parms[1], "LOGIN")) {
1526 imap_login(num_parms, parms);
1529 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1530 imap_authenticate(num_parms, parms);
1533 else if (!strcasecmp(parms[1], "CAPABILITY")) {
1534 imap_capability(num_parms, parms);
1537 else if (!strcasecmp(parms[1], "STARTTLS")) {
1538 imap_starttls(num_parms, parms);
1541 else if (!CC->logged_in) {
1542 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1545 /* The commans below require a logged-in state */
1547 else if (!strcasecmp(parms[1], "SELECT")) {
1548 imap_select(num_parms, parms);
1551 else if (!strcasecmp(parms[1], "EXAMINE")) {
1552 imap_select(num_parms, parms);
1555 else if (!strcasecmp(parms[1], "LSUB")) {
1556 imap_list(num_parms, parms);
1559 else if (!strcasecmp(parms[1], "LIST")) {
1560 imap_list(num_parms, parms);
1563 else if (!strcasecmp(parms[1], "CREATE")) {
1564 imap_create(num_parms, parms);
1567 else if (!strcasecmp(parms[1], "DELETE")) {
1568 imap_delete(num_parms, parms);
1571 else if (!strcasecmp(parms[1], "RENAME")) {
1572 imap_rename(num_parms, parms);
1575 else if (!strcasecmp(parms[1], "STATUS")) {
1576 imap_status(num_parms, parms);
1579 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1580 imap_subscribe(num_parms, parms);
1583 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1584 imap_unsubscribe(num_parms, parms);
1587 else if (!strcasecmp(parms[1], "APPEND")) {
1588 imap_append(num_parms, parms);
1591 else if (!strcasecmp(parms[1], "NAMESPACE")) {
1592 imap_namespace(num_parms, parms);
1595 else if (!strcasecmp(parms[1], "SETACL")) {
1596 imap_setacl(num_parms, parms);
1599 else if (!strcasecmp(parms[1], "DELETEACL")) {
1600 imap_deleteacl(num_parms, parms);
1603 else if (!strcasecmp(parms[1], "GETACL")) {
1604 imap_getacl(num_parms, parms);
1607 else if (!strcasecmp(parms[1], "LISTRIGHTS")) {
1608 imap_listrights(num_parms, parms);
1611 else if (!strcasecmp(parms[1], "MYRIGHTS")) {
1612 imap_myrights(num_parms, parms);
1615 else if (!strcasecmp(parms[1], "GETMETADATA")) {
1616 imap_getmetadata(num_parms, parms);
1619 else if (!strcasecmp(parms[1], "SETMETADATA")) {
1620 imap_setmetadata(num_parms, parms);
1623 else if (IMAP->selected == 0) {
1624 cprintf("%s BAD no folder selected\r\n", parms[0]);
1627 /* The commands below require the SELECT state on a mailbox */
1629 else if (!strcasecmp(parms[1], "FETCH")) {
1630 imap_fetch(num_parms, parms);
1633 else if ((!strcasecmp(parms[1], "UID"))
1634 && (!strcasecmp(parms[2], "FETCH"))) {
1635 imap_uidfetch(num_parms, parms);
1638 else if (!strcasecmp(parms[1], "SEARCH")) {
1639 imap_search(num_parms, parms);
1642 else if ((!strcasecmp(parms[1], "UID"))
1643 && (!strcasecmp(parms[2], "SEARCH"))) {
1644 imap_uidsearch(num_parms, parms);
1647 else if (!strcasecmp(parms[1], "STORE")) {
1648 imap_store(num_parms, parms);
1651 else if ((!strcasecmp(parms[1], "UID"))
1652 && (!strcasecmp(parms[2], "STORE"))) {
1653 imap_uidstore(num_parms, parms);
1656 else if (!strcasecmp(parms[1], "COPY")) {
1657 imap_copy(num_parms, parms);
1660 else if ((!strcasecmp(parms[1], "UID")) && (!strcasecmp(parms[2], "COPY"))) {
1661 imap_uidcopy(num_parms, parms);
1664 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1665 imap_expunge(num_parms, parms);
1668 else if ((!strcasecmp(parms[1], "UID")) && (!strcasecmp(parms[2], "EXPUNGE"))) {
1669 imap_expunge(num_parms, parms);
1672 else if (!strcasecmp(parms[1], "CLOSE")) {
1673 imap_close(num_parms, parms);
1676 /* End of commands. If we get here, the command is either invalid
1681 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1684 /* If the client transmitted a message we can free it now */
1685 imap_free_transmitted_message();
1687 gettimeofday(&tv2, NULL);
1688 total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1689 CtdlLogPrintf(CTDL_DEBUG, "IMAP command completed in %ld.%ld seconds\n",
1690 (total_time / 1000000),
1691 (total_time % 1000000)
1696 const char *CitadelServiceIMAP="IMAP";
1697 const char *CitadelServiceIMAPS="IMAPS";
1700 * This function is called to register the IMAP extension with Citadel.
1702 CTDL_MODULE_INIT(imap)
1706 CtdlRegisterServiceHook(config.c_imap_port,
1707 NULL, imap_greeting, imap_command_loop, NULL, CitadelServiceIMAP);
1709 CtdlRegisterServiceHook(config.c_imaps_port,
1710 NULL, imaps_greeting, imap_command_loop, NULL, CitadelServiceIMAPS);
1712 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1715 /* return our Subversion id for the Log */