1 // IMAP server for the Citadel system
3 // Copyright (c) 1987-2023 by the citadel.org team
5 // This program is open source software. Use, duplication, or disclosure
6 // is subject to the terms of the GNU General Public License, version 3.
8 #include "../../sysdep.h"
16 #include <sys/types.h>
23 #include <libcitadel.h>
24 #include "../../citadel_defs.h"
25 #include "../../server.h"
26 #include "../../citserver.h"
27 #include "../../support.h"
28 #include "../../config.h"
29 #include "../../user_ops.h"
30 #include "../../room_ops.h"
31 #include "../../database.h"
32 #include "../../msgbase.h"
33 #include "../../internet_addressing.h"
34 #include "serv_imap.h"
35 #include "imap_tools.h"
36 #include "imap_list.h"
37 #include "imap_fetch.h"
38 #include "imap_search.h"
39 #include "imap_store.h"
41 #include "imap_metadata.h"
42 #include "imap_misc.h"
44 #include "../../ctdl_module.h"
45 HashList *ImapCmds = NULL;
46 void registerImapCMD(const char *First, long FLen, const char *Second, long SLen, imap_handler H, int Flags) {
49 h = (imap_handler_hook*) malloc(sizeof(imap_handler_hook));
50 memset(h, 0, sizeof(imap_handler_hook));
55 Put(ImapCmds, First, FLen, h, NULL);
59 memcpy(CMD, First, FLen);
60 memcpy(CMD+FLen, Second, SLen);
61 CMD[FLen+SLen] = '\0';
62 Put(ImapCmds, CMD, FLen + SLen, h, NULL);
67 const imap_handler_hook *imap_lookup(int num_parms, ConstStr *Params) {
74 /* we abuse the Reply-buffer for uppercasing... */
75 StrBufPlain(Imap->Reply, CKEY(Params[1]));
76 StrBufUpCase(Imap->Reply);
78 syslog(LOG_DEBUG, "---- Looking up [%s] -----", ChrPtr(Imap->Reply));
79 if (GetHash(ImapCmds, SKEY(Imap->Reply), &v)) {
80 syslog(LOG_DEBUG, "Found.");
81 FlushStrBuf(Imap->Reply);
82 return (imap_handler_hook *) v;
86 syslog(LOG_DEBUG, "NOT Found.");
87 FlushStrBuf(Imap->Reply);
91 syslog(LOG_DEBUG, "---- Looking up [%s] -----", ChrPtr(Imap->Reply));
92 StrBufAppendBufPlain(Imap->Reply, CKEY(Params[2]), 0);
93 StrBufUpCase(Imap->Reply);
94 if (GetHash(ImapCmds, SKEY(Imap->Reply), &v)) {
95 syslog(LOG_DEBUG, "Found.");
96 FlushStrBuf(Imap->Reply);
97 return (imap_handler_hook *) v;
99 syslog(LOG_DEBUG, "NOT Found.");
100 FlushStrBuf(Imap->Reply);
105 /* imap_rename() uses this struct containing list of rooms to rename */
108 char irl_oldroom[ROOMNAMELEN];
109 char irl_newroom[ROOMNAMELEN];
114 /* Data which is passed between imap_rename() and imap_rename_backend() */
115 typedef struct __irlparms {
125 * If there is a message ID map in memory, free it
127 void imap_free_msgids(void) {
128 citimap *Imap = IMAP;
129 if (Imap->msgids != NULL) {
135 if (Imap->flags != NULL) {
139 Imap->last_mtime = (-1);
144 * If there is a transmitted message in memory, free it
146 void imap_free_transmitted_message(void) {
147 FreeStrBuf(&IMAP->TransmittedMessage);
152 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
153 * sets stored in the visit record for this user/room. Note that we have
154 * to parse each sequence set manually here, because calling the utility
155 * function is_msg_in_sequence_set() over and over again is too expensive.
157 * first_msg should be set to 0 to rescan the flags for every message in the
158 * room, or some other value if we're only interested in an incremental
161 void imap_set_seen_flags(int first_msg) {
162 citimap *Imap = IMAP;
167 char setstr[64], lostr[64], histr[64];
170 if (Imap->num_msgs < 0) return;
171 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
173 for (i = first_msg; i < Imap->num_msgs; ++i) {
174 Imap->flags[i] = Imap->flags[i] & ~IMAP_SEEN;
175 Imap->flags[i] |= IMAP_RECENT;
176 Imap->flags[i] = Imap->flags[i] & ~IMAP_ANSWERED;
180 * Do the "\Seen" flag.
181 * (Any message not "\Seen" is considered "\Recent".)
183 num_sets = num_tokens(vbuf.v_seen, ',');
184 for (s=0; s<num_sets; ++s) {
185 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
187 extract_token(lostr, setstr, 0, ':', sizeof lostr);
188 if (num_tokens(setstr, ':') >= 2) {
189 extract_token(histr, setstr, 1, ':', sizeof histr);
190 if (!strcmp(histr, "*")) {
191 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
195 strcpy(histr, lostr);
200 for (i = first_msg; i < Imap->num_msgs; ++i) {
201 if ((Imap->msgids[i] >= lo) && (Imap->msgids[i] <= hi)){
202 Imap->flags[i] |= IMAP_SEEN;
203 Imap->flags[i] = Imap->flags[i] & ~IMAP_RECENT;
208 /* Do the ANSWERED flag */
209 num_sets = num_tokens(vbuf.v_answered, ',');
210 for (s=0; s<num_sets; ++s) {
211 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
213 extract_token(lostr, setstr, 0, ':', sizeof lostr);
214 if (num_tokens(setstr, ':') >= 2) {
215 extract_token(histr, setstr, 1, ':', sizeof histr);
216 if (!strcmp(histr, "*")) {
217 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
221 strcpy(histr, lostr);
226 for (i = first_msg; i < Imap->num_msgs; ++i) {
227 if ((Imap->msgids[i] >= lo) && (Imap->msgids[i] <= hi)){
228 Imap->flags[i] |= IMAP_ANSWERED;
237 * Back end for imap_load_msgids()
239 * Optimization: instead of calling realloc() to add each message, we
240 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
241 * allows the mapping to proceed much faster.
243 void imap_add_single_msgid(long msgnum, void *userdata) {
244 citimap *Imap = IMAP;
247 if (Imap->num_msgs > Imap->num_alloc) {
248 Imap->num_alloc += REALLOC_INCREMENT;
249 Imap->msgids = realloc(Imap->msgids, (Imap->num_alloc * sizeof(long)) );
250 Imap->flags = realloc(Imap->flags, (Imap->num_alloc * sizeof(unsigned int)) );
252 Imap->msgids[Imap->num_msgs - 1] = msgnum;
253 Imap->flags[Imap->num_msgs - 1] = 0;
258 * Set up a message ID map for the current room (folder)
260 void imap_load_msgids(void) {
261 citimap *Imap = IMAP;
263 if (Imap->selected == 0) {
264 syslog(LOG_ERR, "imap_load_msgids() can't run; no room selected");
268 imap_free_msgids(); /* If there was already a map, free it */
270 /* Load the message list */
271 Imap->num_msgs = CtdlFetchMsgList(CC->room.QRnumber, &Imap->msgids);
272 Imap->num_alloc = Imap->num_msgs;
274 if (Imap->num_msgs) {
275 Imap->flags = malloc(Imap->num_alloc * sizeof(unsigned int));
276 memset(Imap->flags, 0, (Imap->num_alloc * sizeof(unsigned int)) );
278 imap_set_seen_flags(0);
283 * Re-scan the selected room (folder) and see if it's been changed at all
285 void imap_rescan_msgids(void) {
286 citimap *Imap = IMAP;
287 int original_num_msgs = 0;
288 long original_highest = 0L;
290 int message_still_exists;
291 long *msglist = NULL;
295 if (Imap->selected == 0) {
296 syslog(LOG_ERR, "imap_load_msgids() can't run; no room selected");
301 * Check to see if the room's contents have changed.
302 * If not, we can avoid this rescan.
304 CtdlGetRoom(&CC->room, CC->room.QRname);
305 if (Imap->last_mtime == CC->room.QRmtime) { /* No changes! */
309 /* Load the *current* message list from disk, so we can compare it
310 * to what we have in memory.
312 num_msgs = CtdlFetchMsgList(CC->room.QRnumber, &msglist);
315 * Check to see if any of the messages we know about have been expunged
317 if (Imap->num_msgs > 0) {
319 for (i = 0; i < Imap->num_msgs; ++i) {
321 message_still_exists = 0;
323 for (j = jstart; j < num_msgs; ++j) {
324 if (msglist[j] == Imap->msgids[i]) {
325 message_still_exists = 1;
332 if (message_still_exists == 0) {
333 IAPrintf("* %d EXPUNGE\r\n", i + 1);
335 // When a message is expunged, we have to slide all the existing messages up in the message array.
337 memmove(&Imap->msgids[i], &Imap->msgids[i + 1], (sizeof(long) * (Imap->num_msgs - i)));
338 memmove(&Imap->flags[i], &Imap->flags[i + 1], (sizeof(unsigned int) * (Imap->num_msgs - i)));
345 // Remember how many messages were here before we re-scanned.
346 original_num_msgs = Imap->num_msgs;
347 if (Imap->num_msgs > 0) {
348 original_highest = Imap->msgids[Imap->num_msgs - 1];
351 original_highest = 0L;
354 // Now peruse the room for *new* messages only.
355 // This logic is probably the cause of Bug # 368
356 // [ http://bugzilla.citadel.org/show_bug.cgi?id=368 ]
358 for (j = 0; j < num_msgs; ++j) {
359 if (msglist[j] > original_highest) {
360 imap_add_single_msgid(msglist[j], NULL);
364 imap_set_seen_flags(original_num_msgs);
367 * If new messages have arrived, tell the client about them.
369 if (Imap->num_msgs > original_num_msgs) {
371 for (j = 0; j < num_msgs; ++j) {
372 if (Imap->flags[j] & IMAP_RECENT) {
377 IAPrintf("* %d EXISTS\r\n", Imap->num_msgs);
378 IAPrintf("* %d RECENT\r\n", num_recent);
382 Imap->last_mtime = CC->room.QRmtime;
387 * This cleanup function blows away the temporary memory and files used by
390 void imap_cleanup_function(void) {
391 citimap *Imap = IMAP;
393 /* Don't do this stuff if this is not a Imap session! */
394 if (CC->h_command_function != imap_command_loop)
397 /* If there is a mailbox selected, auto-expunge it. */
398 if (Imap->selected) {
402 syslog(LOG_DEBUG, "Performing IMAP cleanup hook");
404 imap_free_transmitted_message();
406 if (Imap->cached_rfc822 != NULL) {
407 FreeStrBuf(&Imap->cached_rfc822);
408 Imap->cached_rfc822_msgnum = (-1);
409 Imap->cached_rfc822_withbody = 0;
412 if (Imap->cached_body != NULL) {
413 free(Imap->cached_body);
414 Imap->cached_body = NULL;
415 Imap->cached_body_len = 0;
416 Imap->cached_bodymsgnum = (-1);
418 FreeStrBuf(&Imap->Cmd.CmdBuf);
419 FreeStrBuf(&Imap->Reply);
420 if (Imap->Cmd.Params != NULL) free(Imap->Cmd.Params);
422 syslog(LOG_DEBUG, "Finished IMAP cleanup hook");
427 * Does the actual work of the CAPABILITY command (because we need to output this stuff in other places as well)
429 void imap_output_capability_string(void) {
430 IAPuts("CAPABILITY IMAP4REV1 NAMESPACE ID AUTH=PLAIN AUTH=LOGIN UIDPLUS");
432 if (!CC->redirect_ssl) IAPuts(" STARTTLS");
434 #ifndef DISABLE_IMAP_ACL
438 /* We are building a partial implementation of METADATA for the sole purpose
439 * of interoperating with the ical/vcard version of the Bynari Insight Connector.
440 * It is not a full RFC5464 implementation, but it should refuse non-Bynari
441 * metadata in a compatible and graceful way.
446 * LIST-EXTENDED was originally going to be required by the METADATA extension.
447 * It was mercifully removed prior to the finalization of RFC5464. We started
448 * implementing this but stopped when we learned that it would not be needed.
449 * If you uncomment this declaration you are responsible for writing a lot of new
452 * IAPuts(" LIST-EXTENDED")
458 * implements the CAPABILITY command
460 void imap_capability(int num_parms, ConstStr *Params) {
462 imap_output_capability_string();
464 IReply("OK CAPABILITY completed");
469 * Implements the ID command (specified by RFC2971)
471 * We ignore the client-supplied information, and output a NIL response.
472 * Although this is technically a valid implementation of the extension, it
473 * is quite useless. It exists only so that we may see which clients are
474 * making use of this extension.
477 void imap_id(int num_parms, ConstStr *Params) {
478 IAPuts("* ID NIL\r\n");
479 IReply("OK ID completed");
484 * Here's where our IMAP session begins its happy day.
486 void imap_greeting(void) {
489 strcpy(CC->cs_clientname, "IMAP session");
490 CC->session_specific_data = malloc(sizeof(citimap));
491 Imap = (citimap *)CC->session_specific_data;
492 memset(Imap, 0, sizeof(citimap));
493 Imap->authstate = imap_as_normal;
494 Imap->cached_rfc822_msgnum = (-1);
495 Imap->cached_rfc822_withbody = 0;
496 Imap->Reply = NewStrBufPlain(NULL, SIZ * 10); /* 40k */
499 IAPuts("* BYE; Server busy, try later\r\n");
500 CC->kill_me = KILLME_NOLOGIN;
506 imap_output_capability_string();
507 IAPrintf("] %s IMAP4rev1 %s ready\r\n", CtdlGetConfigStr("c_fqdn"), CITADEL);
513 * IMAPS is just like IMAP, except it goes crypto right away.
515 void imaps_greeting(void) {
516 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
517 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
523 * implements the LOGIN command (ordinary username/password login)
525 void imap_login(int num_parms, ConstStr *Params) {
529 if (Params[2].len && (Params[2].Key[0] == '{')) {
530 IAPuts("+ go ahead\r\n");
531 IMAP->authstate = imap_as_expecting_multilineusername;
532 strcpy(IMAP->authseq, Params[0].Key);
536 IReply("BAD incorrect number of parameters");
540 if (CtdlLoginExistingUser(Params[2].Key) == login_ok) {
541 if (CtdlTryPassword(Params[3].Key, Params[3].len) == pass_ok) {
542 /* hm, thats not doable by IReply :-( */
543 IAPrintf("%s OK [", Params[0].Key);
544 imap_output_capability_string();
545 IAPrintf("] Hello, %s\r\n", CC->user.fullname);
549 IReplyPrintf("NO AUTHENTICATE %s failed", Params[3].Key);
554 IReply("BAD Login incorrect");
557 IReply("BAD incorrect number of parameters");
565 * Implements the AUTHENTICATE command
567 void imap_authenticate(int num_parms, ConstStr *Params) {
570 if (num_parms != 3) {
571 IReply("BAD incorrect number of parameters");
576 IReply("BAD Already logged in.");
580 if (!strcasecmp(Params[2].Key, "LOGIN")) {
581 size_t len = CtdlEncodeBase64(UsrBuf, "Username:", 9, BASE64_NO_LINEBREAKS);
582 if (UsrBuf[len - 1] == '\n') {
583 UsrBuf[len - 1] = '\0';
586 IAPrintf("+ %s\r\n", UsrBuf);
587 IMAP->authstate = imap_as_expecting_username;
588 strcpy(IMAP->authseq, Params[0].Key);
592 if (!strcasecmp(Params[2].Key, "PLAIN")) {
593 // size_t len = CtdlEncodeBase64(UsrBuf, "Username:", 9, BASE64_NO_LINEBREAKS);
594 // if (UsrBuf[len - 1] == '\n') {
595 // UsrBuf[len - 1] = '\0';
597 // IAPuts("+ %s\r\n", UsrBuf);
599 IMAP->authstate = imap_as_expecting_plainauth;
600 strcpy(IMAP->authseq, Params[0].Key);
605 IReplyPrintf("NO AUTHENTICATE %s failed",
611 void imap_auth_plain(void) {
612 citimap *Imap = IMAP;
613 const char *decoded_authstring;
614 char ident[256] = "";
622 memset(pass, 0, sizeof(pass));
623 decoded_len = StrBufDecodeBase64(Imap->Cmd.CmdBuf);
625 if (decoded_len > 0) {
626 decoded_authstring = ChrPtr(Imap->Cmd.CmdBuf);
628 len = safestrncpy(ident, decoded_authstring, sizeof ident);
630 decoded_len -= len - 1;
631 decoded_authstring += len + 1;
633 if (decoded_len > 0) {
634 len = safestrncpy(user, decoded_authstring, sizeof user);
636 decoded_authstring += len + 1;
637 decoded_len -= len - 1;
640 if (decoded_len > 0) {
641 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
644 plen = sizeof(pass) - 1;
647 Imap->authstate = imap_as_normal;
649 if (!IsEmptyStr(ident)) {
650 result = CtdlLoginExistingUser(ident);
653 result = CtdlLoginExistingUser(user);
656 if (result == login_ok) {
657 if (CtdlTryPassword(pass, plen) == pass_ok) {
658 IAPrintf("%s OK authentication succeeded\r\n", Imap->authseq);
662 IAPrintf("%s NO authentication failed\r\n", Imap->authseq);
666 void imap_auth_login_user(long state) {
668 citimap *Imap = IMAP;
671 case imap_as_expecting_username:
672 StrBufDecodeBase64(Imap->Cmd.CmdBuf);
673 CtdlLoginExistingUser(ChrPtr(Imap->Cmd.CmdBuf));
674 size_t len = CtdlEncodeBase64(PWBuf, "Password:", 9, BASE64_NO_LINEBREAKS);
675 if (PWBuf[len - 1] == '\n') {
676 PWBuf[len - 1] = '\0';
679 IAPrintf("+ %s\r\n", PWBuf);
681 Imap->authstate = imap_as_expecting_password;
683 case imap_as_expecting_multilineusername:
684 extract_token(PWBuf, ChrPtr(Imap->Cmd.CmdBuf), 1, ' ', sizeof(PWBuf));
685 CtdlLoginExistingUser(ChrPtr(Imap->Cmd.CmdBuf));
686 IAPuts("+ go ahead\r\n");
687 Imap->authstate = imap_as_expecting_multilinepassword;
693 void imap_auth_login_pass(long state) {
694 citimap *Imap = IMAP;
695 const char *pass = NULL;
700 case imap_as_expecting_password:
701 StrBufDecodeBase64(Imap->Cmd.CmdBuf);
702 pass = ChrPtr(Imap->Cmd.CmdBuf);
703 len = StrLength(Imap->Cmd.CmdBuf);
705 case imap_as_expecting_multilinepassword:
706 pass = ChrPtr(Imap->Cmd.CmdBuf);
707 len = StrLength(Imap->Cmd.CmdBuf);
710 if (len > USERNAME_SIZE)
711 StrBufCutAt(Imap->Cmd.CmdBuf, USERNAME_SIZE, NULL);
713 if (CtdlTryPassword(pass, len) == pass_ok) {
714 IAPrintf("%s OK authentication succeeded\r\n", Imap->authseq);
717 IAPrintf("%s NO authentication failed\r\n", Imap->authseq);
719 Imap->authstate = imap_as_normal;
725 * implements the STARTTLS command (Citadel API version)
727 void imap_starttls(int num_parms, ConstStr *Params) {
728 char ok_response[SIZ];
729 char nosup_response[SIZ];
730 char error_response[SIZ];
732 snprintf(ok_response, SIZ, "%s OK begin TLS negotiation now\r\n", Params[0].Key);
733 snprintf(nosup_response, SIZ, "%s NO TLS not supported here\r\n", Params[0].Key);
734 snprintf(error_response, SIZ, "%s BAD Internal error\r\n", Params[0].Key);
735 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
740 * implements the SELECT command
742 void imap_select(int num_parms, ConstStr *Params) {
743 citimap *Imap = IMAP;
744 char towhere[ROOMNAMELEN];
745 char augmented_roomname[ROOMNAMELEN];
749 struct ctdlroom QRscratch;
753 /* Convert the supplied folder name to a roomname */
754 i = imap_roomname(towhere, sizeof towhere, Params[2].Key);
756 IReply("NO Invalid mailbox name.");
761 /* First try a regular match */
762 c = CtdlGetRoom(&QRscratch, towhere);
764 /* Then try a mailbox name match */
766 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, towhere);
767 c = CtdlGetRoom(&QRscratch, augmented_roomname);
769 safestrncpy(towhere, augmented_roomname, sizeof(towhere));
773 /* If the room exists, check security/access */
775 /* See if there is an existing user/room relationship */
776 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
778 /* normal clients have to pass through security */
784 /* Fail here if no such room */
786 IReply("NO ... no such room, or access denied");
790 /* If we already had some other folder selected, auto-expunge it */
794 * CtdlUserGoto() formally takes us to the desired room, happily returning
795 * the number of messages and number of new messages.
797 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
798 CtdlUserGoto(NULL, 0, 0, &msgs, &new, NULL, NULL);
801 if (!strcasecmp(Params[1].Key, "EXAMINE")) {
809 Imap->last_mtime = CC->room.QRmtime;
811 IAPrintf("* %d EXISTS\r\n", msgs);
812 IAPrintf("* %d RECENT\r\n", new);
814 IAPrintf("* OK [UIDVALIDITY %ld] UID validity status\r\n", GLOBAL_UIDVALIDITY_VALUE);
815 IAPrintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CtdlGetConfigLong("MMhighest") + 1);
817 /* Technically, \Deleted is a valid flag, but not a permanent flag,
818 * because we don't maintain its state across sessions. Citadel
819 * automatically expunges mailboxes when they are de-selected.
821 * Unfortunately, omitting \Deleted as a PERMANENTFLAGS flag causes
822 * some clients (particularly Thunderbird) to misbehave -- they simply
823 * elect not to transmit the flag at all. So we have to advertise
824 * \Deleted as a PERMANENTFLAGS flag, even though it technically isn't.
826 IAPuts("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
827 IAPuts("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] permanent flags\r\n");
828 IReplyPrintf("OK [%s] %s completed", (Imap->readonly ? "READ-ONLY" : "READ-WRITE"), Params[1].Key);
833 * Does the real work for expunge.
835 int imap_do_expunge(void) {
836 citimap *Imap = IMAP;
838 int num_expunged = 0;
839 long *delmsgs = NULL;
842 syslog(LOG_DEBUG, "imap_do_expunge() called");
843 if (Imap->selected == 0) {
847 if (Imap->num_msgs > 0) {
848 delmsgs = malloc(Imap->num_msgs * sizeof(long));
849 for (i = 0; i < Imap->num_msgs; ++i) {
850 if (Imap->flags[i] & IMAP_DELETED) {
851 delmsgs[num_delmsgs++] = Imap->msgids[i];
854 if (num_delmsgs > 0) {
855 CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
857 num_expunged += num_delmsgs;
861 if (num_expunged > 0) {
862 imap_rescan_msgids();
865 syslog(LOG_DEBUG, "Expunged %d messages from <%s>", num_expunged, CC->room.QRname);
866 return (num_expunged);
871 * implements the EXPUNGE command syntax
873 void imap_expunge(int num_parms, ConstStr *Params) {
874 int num_expunged = 0;
876 num_expunged = imap_do_expunge();
877 IReplyPrintf("OK expunged %d messages.", num_expunged);
882 * implements the CLOSE command
884 void imap_close(int num_parms, ConstStr *Params) {
886 /* Yes, we always expunge on close. */
887 if (IMAP->selected) {
894 IReply("OK CLOSE completed");
899 * Implements the NAMESPACE command.
901 void imap_namespace(int num_parms, ConstStr *Params) {
908 IAPuts("* NAMESPACE ");
910 /* All personal folders are subordinate to INBOX. */
911 IAPuts("((\"INBOX/\" \"/\")) ");
913 /* Other users' folders ... eventually? FIXME */
916 /* Show all floors as shared namespaces. Neato! */
918 for (i = 0; i < MAXFLOORS; ++i) {
919 fl = CtdlGetCachedFloor(i);
920 if (fl->f_flags & F_INUSE) {
921 /* if (floors > 0) IAPuts(" "); samjam says this confuses javamail */
923 len = snprintf(Namespace, sizeof(Namespace), "%s/", fl->f_name);
924 IPutStr(Namespace, len);
931 /* Wind it up with a newline and a completion message. */
933 IReply("OK NAMESPACE completed");
938 * Implements the CREATE command
941 void imap_create(int num_parms, ConstStr *Params) {
943 char roomname[ROOMNAMELEN];
948 char *notification_message = NULL;
951 IReply("NO A foder name must be specified");
955 if (strchr(Params[2].Key, '\\') != NULL) {
956 IReply("NO Invalid character in folder name");
957 syslog(LOG_ERR, "invalid character in folder name");
961 ret = imap_roomname(roomname, sizeof roomname, Params[2].Key);
963 IReply("NO Invalid mailbox name or location");
964 syslog(LOG_ERR, "invalid mailbox name or location");
967 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
968 flags = (ret & 0xff00); /* upper 8 bits = flags */
970 if (flags & IR_MAILBOX) {
971 if (strncasecmp(Params[2].Key, "INBOX/", 6)) {
972 IReply("NO Personal folders must be created under INBOX");
973 syslog(LOG_ERR, "not subordinate to inbox");
978 if (flags & IR_MAILBOX) {
979 newroomtype = 4; /* private mailbox */
980 newroomview = VIEW_MAILBOX;
983 newroomtype = 0; /* public folder */
984 newroomview = VIEW_BBS;
987 syslog(LOG_INFO, "Create new room <%s> on floor <%d> with type <%d>",
988 roomname, floornum, newroomtype);
990 ret = CtdlCreateRoom(roomname, newroomtype, "", floornum, 1, 0, newroomview);
992 IReply("NO Mailbox already exists, or create failed");
995 IReply("OK CREATE completed");
996 // post a message in Aide> describing the new room
997 notification_message = malloc(1024);
998 snprintf(notification_message, 1024,
999 "A new room called \"%s\" has been created by %s%s%s%s\n",
1002 ((ret & QR_MAILBOX) ? " [personal]" : ""),
1003 ((ret & QR_PRIVATE) ? " [private]" : ""),
1004 ((ret & QR_GUESSNAME) ? " [hidden]" : "")
1006 CtdlAideMessage(notification_message, "Room Creation Message");
1007 free(notification_message);
1009 syslog(LOG_DEBUG, "imap_create() completed");
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, const char *foldername, int zapped_ok) {
1019 char augmented_roomname[ROOMNAMELEN];
1020 char roomname[ROOMNAMELEN];
1022 struct ctdlroom QRscratch;
1026 ret = imap_roomname(roomname, sizeof roomname, foldername);
1031 /* First try a regular match */
1032 c = CtdlGetRoom(&QRscratch, roomname);
1034 /* Then try a mailbox name match */
1036 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, roomname);
1037 c = CtdlGetRoom(&QRscratch, augmented_roomname);
1039 safestrncpy(roomname, augmented_roomname, sizeof(roomname));
1042 /* If the room exists, check security/access */
1044 /* See if there is an existing user/room relationship */
1045 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1047 /* normal clients have to pass through security */
1048 if (ra & UA_KNOWN) {
1051 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1056 /* Fail here if no such room */
1058 strcpy(returned_roomname, "");
1062 safestrncpy(returned_roomname, QRscratch.QRname, ROOMNAMELEN);
1069 * Implements the STATUS command (sort of)
1072 void imap_status(int num_parms, ConstStr *Params) {
1075 char roomname[ROOMNAMELEN];
1076 char imaproomname[SIZ];
1077 char savedroom[ROOMNAMELEN];
1080 ret = imap_grabroom(roomname, Params[2].Key, 1);
1082 IReply("NO Invalid mailbox name or location, or access denied");
1087 * CtdlUserGoto() formally takes us to the desired room, happily returning
1088 * the number of messages and number of new messages. (If another
1089 * folder is selected, save its name so we can return there!!!!!)
1091 if (IMAP->selected) {
1092 strcpy(savedroom, CC->room.QRname);
1094 CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1097 * Tell the client what it wants to know. In fact, tell it *more* than
1098 * it wants to know. We happily IGnore the supplied status data item
1099 * names and simply spew all possible data items. It's far easier to
1100 * code and probably saves us some processing time too.
1102 len = imap_mailboxname(imaproomname, sizeof imaproomname, &CC->room);
1103 IAPuts("* STATUS ");
1104 IPutStr(imaproomname, len);
1105 IAPrintf(" (MESSAGES %d ", msgs);
1106 IAPrintf("RECENT %d ", new); /* Initially, new==recent */
1107 IAPrintf("UIDNEXT %ld ", CtdlGetConfigLong("MMhighest") + 1);
1108 IAPrintf("UNSEEN %d)\r\n", new);
1111 * If another folder is selected, go back to that room so we can resume
1112 * our happy day without violent explosions.
1114 if (IMAP->selected) {
1115 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1119 * Oooh, look, we're done!
1121 IReply("OK STATUS completed");
1126 * Implements the SUBSCRIBE command
1129 void imap_subscribe(int num_parms, ConstStr *Params) {
1131 char roomname[ROOMNAMELEN];
1132 char savedroom[ROOMNAMELEN];
1135 ret = imap_grabroom(roomname, Params[2].Key, 1);
1138 "NO Error %d: invalid mailbox name or location, or access denied",
1145 * CtdlUserGoto() formally takes us to the desired room, which has the side
1146 * effect of marking the room as not-zapped ... exactly the effect
1147 * we're looking for.
1149 if (IMAP->selected) {
1150 strcpy(savedroom, CC->room.QRname);
1152 CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1155 * If another folder is selected, go back to that room so we can resume
1156 * our happy day without violent explosions.
1158 if (IMAP->selected) {
1159 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1162 IReply("OK SUBSCRIBE completed");
1167 * Implements the UNSUBSCRIBE command
1170 void imap_unsubscribe(int num_parms, ConstStr *Params) {
1172 char roomname[ROOMNAMELEN];
1173 char savedroom[ROOMNAMELEN];
1176 ret = imap_grabroom(roomname, Params[2].Key, 1);
1178 IReply("NO Invalid mailbox name or location, or access denied");
1183 * CtdlUserGoto() formally takes us to the desired room.
1185 if (IMAP->selected) {
1186 strcpy(savedroom, CC->room.QRname);
1188 CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1191 * Now make the API call to zap the room
1193 if (CtdlForgetThisRoom() == 0) {
1194 IReply("OK UNSUBSCRIBE completed");
1197 IReply("NO You may not unsubscribe from this folder.");
1201 * If another folder is selected, go back to that room so we can resume
1202 * our happy day without violent explosions.
1204 if (IMAP->selected) {
1205 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1211 * Implements the DELETE command
1214 void imap_delete(int num_parms, ConstStr *Params) {
1216 char roomname[ROOMNAMELEN];
1217 char savedroom[ROOMNAMELEN];
1220 ret = imap_grabroom(roomname, Params[2].Key, 1);
1222 IReply("NO Invalid mailbox name, or access denied");
1227 * CtdlUserGoto() formally takes us to the desired room, happily returning
1228 * the number of messages and number of new messages. (If another
1229 * folder is selected, save its name so we can return there!!!!!)
1231 if (IMAP->selected) {
1232 strcpy(savedroom, CC->room.QRname);
1234 CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1237 * Now delete the room.
1239 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1240 CtdlScheduleRoomForDeletion(&CC->room);
1241 IReply("OK DELETE completed");
1244 IReply("NO Can't delete this folder.");
1248 * If another folder is selected, go back to that room so we can resume
1249 * our happy day without violent explosions.
1251 if (IMAP->selected) {
1252 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1258 * Back end function for imap_rename()
1260 void imap_rename_backend(struct ctdlroom *qrbuf, void *data) {
1261 char foldername[SIZ];
1262 char newfoldername[SIZ];
1263 char newroomname[ROOMNAMELEN];
1265 struct irl *irlp = NULL; /* scratch pointer */
1266 irlparms *myirlparms;
1268 myirlparms = (irlparms *) data;
1269 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1271 /* Rename subfolders */
1272 if ((!strncasecmp(foldername, myirlparms->oldname, myirlparms->oldnamelen) && (foldername[myirlparms->oldnamelen] == '/'))) {
1273 snprintf(newfoldername, sizeof newfoldername, "%s/%s", myirlparms->newname, &foldername[myirlparms->oldnamelen + 1]);
1274 newfloor = imap_roomname(newroomname, sizeof newroomname, newfoldername) & 0xFF;
1275 irlp = (struct irl *) malloc(sizeof(struct irl));
1276 strcpy(irlp->irl_newroom, newroomname);
1277 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1278 irlp->irl_newfloor = newfloor;
1279 irlp->next = *(myirlparms->irl);
1280 *(myirlparms->irl) = irlp;
1286 * Implements the RENAME command
1289 void imap_rename(int num_parms, ConstStr *Params) {
1290 char old_room[ROOMNAMELEN];
1291 char new_room[ROOMNAMELEN];
1295 struct irl *irl = NULL; /* the list */
1296 struct irl *irlp = NULL; /* scratch pointer */
1300 if (strchr(Params[3].Key, '\\') != NULL) {
1301 IReply("NO Invalid character in folder name");
1305 imap_roomname(old_room, sizeof old_room, Params[2].Key);
1306 newr = imap_roomname(new_room, sizeof new_room, Params[3].Key);
1307 new_floor = (newr & 0xFF);
1309 r = CtdlRenameRoom(old_room, new_room, new_floor);
1311 if (r == crr_room_not_found) {
1312 IReply("NO Could not locate this folder");
1315 if (r == crr_already_exists) {
1316 IReplyPrintf("NO '%s' already exists.");
1319 if (r == crr_noneditable) {
1320 IReply("NO This folder is not editable.");
1323 if (r == crr_invalid_floor) {
1324 IReply("NO Folder root does not exist.");
1327 if (r == crr_access_denied) {
1328 IReply("NO You do not have permission to edit this folder.");
1332 IReplyPrintf("NO Rename failed - undefined error %d", r);
1336 /* If this is the INBOX, then RFC2060 says we have to just move the
1337 * contents. In a Citadel environment it's easier to rename the room
1338 * (already did that) and create a new inbox.
1340 if (!strcasecmp(Params[2].Key, "INBOX")) {
1341 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1344 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1346 irlparms.oldname = Params[2].Key;
1347 irlparms.oldnamelen = Params[2].len;
1348 irlparms.newname = Params[3].Key;
1349 irlparms.newnamelen = Params[3].len;
1350 irlparms.irl = &irl;
1351 CtdlForEachRoom(imap_rename_backend, (void *) &irlparms);
1353 /* ... and now rename them. */
1354 while (irl != NULL) {
1355 r = CtdlRenameRoom(irl->irl_oldroom, irl->irl_newroom, irl->irl_newfloor);
1357 /* FIXME handle error returns better */
1358 syslog(LOG_ERR, "CtdlRenameRoom() error %d", r);
1366 snprintf(aidemsg, sizeof aidemsg, "IMAP folder \"%s\" renamed to \"%s\" by %s\n",
1371 CtdlAideMessage(aidemsg, "IMAP folder rename");
1373 IReply("OK RENAME completed");
1378 * Main command loop for IMAP sessions.
1380 void imap_command_loop(void) {
1381 struct timeval tv1, tv2;
1382 suseconds_t total_time = 0;
1384 const char *pchs, *pche;
1385 const imap_handler_hook *h;
1387 gettimeofday(&tv1, NULL);
1388 CC->lastcmd = time(NULL);
1392 if (Imap->Cmd.CmdBuf == NULL)
1393 Imap->Cmd.CmdBuf = NewStrBufPlain(NULL, SIZ);
1395 FlushStrBuf(Imap->Cmd.CmdBuf);
1397 if (CtdlClientGetLine(Imap->Cmd.CmdBuf) < 1) {
1398 syslog(LOG_ERR, "client disconnected: ending session.");
1399 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1403 if (Imap->authstate == imap_as_expecting_password) {
1404 syslog(LOG_INFO, "<password>");
1406 else if (Imap->authstate == imap_as_expecting_plainauth) {
1407 syslog(LOG_INFO, "<plain_auth>");
1409 else if ((Imap->authstate == imap_as_expecting_multilineusername) || cbmstrcasestr(ChrPtr(Imap->Cmd.CmdBuf), " LOGIN ")) {
1410 syslog(LOG_INFO, "LOGIN...");
1413 syslog(LOG_DEBUG, "%s", ChrPtr(Imap->Cmd.CmdBuf));
1416 pchs = ChrPtr(Imap->Cmd.CmdBuf);
1417 pche = pchs + StrLength(Imap->Cmd.CmdBuf);
1419 while ((pche > pchs) && ((*pche == '\n') || (*pche == '\r'))) {
1421 StrBufCutRight(Imap->Cmd.CmdBuf, 1);
1423 StrBufTrim(Imap->Cmd.CmdBuf);
1425 /* If we're in the middle of a multi-line command, handle that */
1426 switch (Imap->authstate){
1427 case imap_as_expecting_username:
1428 imap_auth_login_user(imap_as_expecting_username);
1431 case imap_as_expecting_multilineusername:
1432 imap_auth_login_user(imap_as_expecting_multilineusername);
1435 case imap_as_expecting_plainauth:
1439 case imap_as_expecting_password:
1440 imap_auth_login_pass(imap_as_expecting_password);
1443 case imap_as_expecting_multilinepassword:
1444 imap_auth_login_pass(imap_as_expecting_multilinepassword);
1451 /* Ok, at this point we're in normal command mode.
1452 * If the command just submitted does not contain a literal, we
1453 * might think about delivering some untagged stuff...
1456 /* Grab the tag, command, and parameters. */
1457 imap_parameterize(&Imap->Cmd);
1459 /* Now for the command set. */
1460 h = imap_lookup(Imap->Cmd.num_parms, Imap->Cmd.Params);
1463 IReply("BAD command unrecognized");
1467 /* RFC3501 says that we cannot output untagged data during these commands */
1468 if ((h->Flags & I_FLAG_UNTAGGED) == 0) {
1470 // we can put any additional untagged stuff right here in the future
1472 // Before processing the command that was just entered... if we happen
1473 // to have a folder selected, we'd like to rescan that folder for new
1474 // messages, and for deletions/changes of existing messages. This
1475 // could probably be optimized better with some deep thought...
1476 if (Imap->selected) {
1477 imap_rescan_msgids();
1481 /* does our command require a logged-in state */
1482 if ((!CC->logged_in) && ((h->Flags & I_FLAG_LOGGED_IN) != 0)) {
1483 IReply("BAD Not logged in.");
1487 /* does our command require the SELECT state on a mailbox */
1488 if ((Imap->selected == 0) && ((h->Flags & I_FLAG_SELECT) != 0)){
1489 IReply("BAD no folder selected");
1492 h->h(Imap->Cmd.num_parms, Imap->Cmd.Params);
1494 /* If the client transmitted a message we can free it now */
1499 imap_free_transmitted_message();
1501 gettimeofday(&tv2, NULL);
1502 total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1503 syslog(LOG_DEBUG, "IMAP command completed in %ld.%ld seconds",
1504 (total_time / 1000000),
1505 (total_time % 1000000)
1510 void imap_noop(int num_parms, ConstStr *Params) {
1511 IReply("OK No operation");
1515 void imap_logout(int num_parms, ConstStr *Params) {
1516 if (IMAP->selected) {
1517 imap_do_expunge(); /* yes, we auto-expunge at logout */
1519 IAPrintf("* BYE %s logging out\r\n", CtdlGetConfigStr("c_fqdn"));
1520 IReply("OK Citadel IMAP session ended.");
1521 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1526 const char *CitadelServiceIMAP="IMAP";
1527 const char *CitadelServiceIMAPS="IMAPS";
1530 // Initialization function, called from modules_init.c
1531 char *ctdl_module_init_imap(void) {
1532 if (ImapCmds == NULL) {
1533 ImapCmds = NewHash(1, NULL);
1536 RegisterImapCMD("NOOP", "", imap_noop, I_FLAG_NONE);
1537 RegisterImapCMD("CHECK", "", imap_noop, I_FLAG_NONE);
1538 RegisterImapCMD("ID", "", imap_id, I_FLAG_NONE);
1539 RegisterImapCMD("LOGOUT", "", imap_logout, I_FLAG_NONE);
1540 RegisterImapCMD("LOGIN", "", imap_login, I_FLAG_NONE);
1541 RegisterImapCMD("AUTHENTICATE", "", imap_authenticate, I_FLAG_NONE);
1542 RegisterImapCMD("CAPABILITY", "", imap_capability, I_FLAG_NONE);
1543 RegisterImapCMD("STARTTLS", "", imap_starttls, I_FLAG_NONE);
1545 /* The commans below require a logged-in state */
1546 RegisterImapCMD("SELECT", "", imap_select, I_FLAG_LOGGED_IN);
1547 RegisterImapCMD("EXAMINE", "", imap_select, I_FLAG_LOGGED_IN);
1548 RegisterImapCMD("LSUB", "", imap_list, I_FLAG_LOGGED_IN);
1549 RegisterImapCMD("LIST", "", imap_list, I_FLAG_LOGGED_IN);
1550 RegisterImapCMD("CREATE", "", imap_create, I_FLAG_LOGGED_IN);
1551 RegisterImapCMD("DELETE", "", imap_delete, I_FLAG_LOGGED_IN);
1552 RegisterImapCMD("RENAME", "", imap_rename, I_FLAG_LOGGED_IN);
1553 RegisterImapCMD("STATUS", "", imap_status, I_FLAG_LOGGED_IN);
1554 RegisterImapCMD("SUBSCRIBE", "", imap_subscribe, I_FLAG_LOGGED_IN);
1555 RegisterImapCMD("UNSUBSCRIBE", "", imap_unsubscribe, I_FLAG_LOGGED_IN);
1556 RegisterImapCMD("APPEND", "", imap_append, I_FLAG_LOGGED_IN);
1557 RegisterImapCMD("NAMESPACE", "", imap_namespace, I_FLAG_LOGGED_IN);
1558 RegisterImapCMD("SETACL", "", imap_setacl, I_FLAG_LOGGED_IN);
1559 RegisterImapCMD("DELETEACL", "", imap_deleteacl, I_FLAG_LOGGED_IN);
1560 RegisterImapCMD("GETACL", "", imap_getacl, I_FLAG_LOGGED_IN);
1561 RegisterImapCMD("LISTRIGHTS", "", imap_listrights, I_FLAG_LOGGED_IN);
1562 RegisterImapCMD("MYRIGHTS", "", imap_myrights, I_FLAG_LOGGED_IN);
1563 RegisterImapCMD("GETMETADATA", "", imap_getmetadata, I_FLAG_LOGGED_IN);
1564 RegisterImapCMD("SETMETADATA", "", imap_setmetadata, I_FLAG_LOGGED_IN);
1566 /* The commands below require the SELECT state on a mailbox */
1567 RegisterImapCMD("FETCH", "", imap_fetch, I_FLAG_LOGGED_IN | I_FLAG_SELECT | I_FLAG_UNTAGGED);
1568 RegisterImapCMD("UID", "FETCH", imap_uidfetch, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1569 RegisterImapCMD("SEARCH", "", imap_search, I_FLAG_LOGGED_IN | I_FLAG_SELECT | I_FLAG_UNTAGGED);
1570 RegisterImapCMD("UID", "SEARCH", imap_uidsearch, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1571 RegisterImapCMD("STORE", "", imap_store, I_FLAG_LOGGED_IN | I_FLAG_SELECT | I_FLAG_UNTAGGED);
1572 RegisterImapCMD("UID", "STORE", imap_uidstore, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1573 RegisterImapCMD("COPY", "", imap_copy, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1574 RegisterImapCMD("UID", "COPY", imap_uidcopy, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1575 RegisterImapCMD("EXPUNGE", "", imap_expunge, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1576 RegisterImapCMD("UID", "EXPUNGE", imap_expunge, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1577 RegisterImapCMD("CLOSE", "", imap_close, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1580 CtdlRegisterServiceHook(CtdlGetConfigInt("c_imap_port"), NULL, imap_greeting, imap_command_loop, NULL, CitadelServiceIMAP);
1581 CtdlRegisterServiceHook(CtdlGetConfigInt("c_imaps_port"), NULL, imaps_greeting, imap_command_loop, NULL, CitadelServiceIMAPS);
1582 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP, PRIO_STOP + 30);
1585 // return our module name for the log