1 // IMAP server for the Citadel system
3 // Copyright (C) 2000-2022 by Art Cancro and others.
4 // This code is released under the terms of the GNU General Public License.
6 // WARNING: the IMAP protocol is badly designed. No implementation of it
7 // is perfect. Indeed, with so much gratuitous complexity, *all* IMAP
8 // implementations have bugs.
10 // This program is open source software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 3 of the License, or
13 // (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
20 #include "../../sysdep.h"
28 #include <sys/types.h>
34 #include <libcitadel.h>
35 #include "../../citadel.h"
36 #include "../../server.h"
37 #include "../../citserver.h"
38 #include "../../support.h"
39 #include "../../config.h"
40 #include "../../user_ops.h"
41 #include "../../database.h"
42 #include "../../msgbase.h"
43 #include "../../internet_addressing.h"
44 #include "serv_imap.h"
45 #include "imap_tools.h"
46 #include "imap_list.h"
47 #include "imap_fetch.h"
48 #include "imap_search.h"
49 #include "imap_store.h"
51 #include "imap_metadata.h"
52 #include "imap_misc.h"
54 #include "../../ctdl_module.h"
55 HashList *ImapCmds = NULL;
56 void registerImapCMD(const char *First, long FLen,
57 const char *Second, long SLen,
63 h = (imap_handler_hook*) malloc(sizeof(imap_handler_hook));
64 memset(h, 0, sizeof(imap_handler_hook));
69 Put(ImapCmds, First, FLen, h, NULL);
73 memcpy(CMD, First, FLen);
74 memcpy(CMD+FLen, Second, SLen);
75 CMD[FLen+SLen] = '\0';
76 Put(ImapCmds, CMD, FLen + SLen, h, NULL);
81 const imap_handler_hook *imap_lookup(int num_parms, ConstStr *Params)
83 struct CitContext *CCC = CC;
85 citimap *Imap = CCCIMAP;
90 /* we abuse the Reply-buffer for uppercasing... */
91 StrBufPlain(Imap->Reply, CKEY(Params[1]));
92 StrBufUpCase(Imap->Reply);
94 syslog(LOG_DEBUG, "---- Looking up [%s] -----", ChrPtr(Imap->Reply));
95 if (GetHash(ImapCmds, SKEY(Imap->Reply), &v))
97 syslog(LOG_DEBUG, "Found.");
98 FlushStrBuf(Imap->Reply);
99 return (imap_handler_hook *) v;
104 syslog(LOG_DEBUG, "NOT Found.");
105 FlushStrBuf(Imap->Reply);
109 syslog(LOG_DEBUG, "---- Looking up [%s] -----", ChrPtr(Imap->Reply));
110 StrBufAppendBufPlain(Imap->Reply, CKEY(Params[2]), 0);
111 StrBufUpCase(Imap->Reply);
112 if (GetHash(ImapCmds, SKEY(Imap->Reply), &v))
114 syslog(LOG_DEBUG, "Found.");
115 FlushStrBuf(Imap->Reply);
116 return (imap_handler_hook *) v;
118 syslog(LOG_DEBUG, "NOT Found.");
119 FlushStrBuf(Imap->Reply);
123 /* imap_rename() uses this struct containing list of rooms to rename */
126 char irl_oldroom[ROOMNAMELEN];
127 char irl_newroom[ROOMNAMELEN];
131 /* Data which is passed between imap_rename() and imap_rename_backend() */
132 typedef struct __irlparms {
142 * If there is a message ID map in memory, free it
144 void imap_free_msgids(void)
146 citimap *Imap = IMAP;
147 if (Imap->msgids != NULL) {
153 if (Imap->flags != NULL) {
157 Imap->last_mtime = (-1);
162 * If there is a transmitted message in memory, free it
164 void imap_free_transmitted_message(void) {
165 FreeStrBuf(&IMAP->TransmittedMessage);
170 * Set the \Seen, \Recent. and \Answered flags, based on the sequence
171 * sets stored in the visit record for this user/room. Note that we have
172 * to parse each sequence set manually here, because calling the utility
173 * function is_msg_in_sequence_set() over and over again is too expensive.
175 * first_msg should be set to 0 to rescan the flags for every message in the
176 * room, or some other value if we're only interested in an incremental
179 void imap_set_seen_flags(int first_msg) {
180 citimap *Imap = IMAP;
185 char setstr[64], lostr[64], histr[64];
188 if (Imap->num_msgs < 1) return;
189 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
191 for (i = first_msg; i < Imap->num_msgs; ++i) {
192 Imap->flags[i] = Imap->flags[i] & ~IMAP_SEEN;
193 Imap->flags[i] |= IMAP_RECENT;
194 Imap->flags[i] = Imap->flags[i] & ~IMAP_ANSWERED;
198 * Do the "\Seen" flag.
199 * (Any message not "\Seen" is considered "\Recent".)
201 num_sets = num_tokens(vbuf.v_seen, ',');
202 for (s=0; s<num_sets; ++s) {
203 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
205 extract_token(lostr, setstr, 0, ':', sizeof lostr);
206 if (num_tokens(setstr, ':') >= 2) {
207 extract_token(histr, setstr, 1, ':', sizeof histr);
208 if (!strcmp(histr, "*")) {
209 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
213 strcpy(histr, lostr);
218 for (i = first_msg; i < Imap->num_msgs; ++i) {
219 if ((Imap->msgids[i] >= lo) && (Imap->msgids[i] <= hi)){
220 Imap->flags[i] |= IMAP_SEEN;
221 Imap->flags[i] = Imap->flags[i] & ~IMAP_RECENT;
226 /* Do the ANSWERED flag */
227 num_sets = num_tokens(vbuf.v_answered, ',');
228 for (s=0; s<num_sets; ++s) {
229 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
231 extract_token(lostr, setstr, 0, ':', sizeof lostr);
232 if (num_tokens(setstr, ':') >= 2) {
233 extract_token(histr, setstr, 1, ':', sizeof histr);
234 if (!strcmp(histr, "*")) {
235 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
239 strcpy(histr, lostr);
244 for (i = first_msg; i < Imap->num_msgs; ++i) {
245 if ((Imap->msgids[i] >= lo) && (Imap->msgids[i] <= hi)){
246 Imap->flags[i] |= IMAP_ANSWERED;
256 * Back end for imap_load_msgids()
258 * Optimization: instead of calling realloc() to add each message, we
259 * allocate space in the list for REALLOC_INCREMENT messages at a time. This
260 * allows the mapping to proceed much faster.
262 void imap_add_single_msgid(long msgnum, void *userdata) {
263 citimap *Imap = IMAP;
266 if (Imap->num_msgs > Imap->num_alloc) {
267 Imap->num_alloc += REALLOC_INCREMENT;
268 Imap->msgids = realloc(Imap->msgids, (Imap->num_alloc * sizeof(long)) );
269 Imap->flags = realloc(Imap->flags, (Imap->num_alloc * sizeof(unsigned int)) );
271 Imap->msgids[Imap->num_msgs - 1] = msgnum;
272 Imap->flags[Imap->num_msgs - 1] = 0;
278 * Set up a message ID map for the current room (folder)
280 void imap_load_msgids(void) {
281 struct CitContext *CCC = CC;
282 struct cdbdata *cdbfr;
283 citimap *Imap = CCCIMAP;
285 if (Imap->selected == 0) {
286 syslog(LOG_ERR, "imap_load_msgids() can't run; no room selected");
290 imap_free_msgids(); /* If there was already a map, free it */
292 /* Load the message list */
293 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
295 Imap->msgids = (long*)cdbfr->ptr;
296 Imap->num_msgs = cdbfr->len / sizeof(long);
297 Imap->num_alloc = cdbfr->len / sizeof(long);
303 if (Imap->num_msgs) {
304 Imap->flags = malloc(Imap->num_alloc * sizeof(unsigned int));
305 memset(Imap->flags, 0, (Imap->num_alloc * sizeof(unsigned int)) );
308 imap_set_seen_flags(0);
313 * Re-scan the selected room (folder) and see if it's been changed at all
315 void imap_rescan_msgids(void) {
316 struct CitContext *CCC = CC;
317 citimap *Imap = CCCIMAP;
318 int original_num_msgs = 0;
319 long original_highest = 0L;
321 int message_still_exists;
322 struct cdbdata *cdbfr;
323 long *msglist = NULL;
327 if (Imap->selected == 0) {
328 syslog(LOG_ERR, "imap_load_msgids() can't run; no room selected");
333 * Check to see if the room's contents have changed.
334 * If not, we can avoid this rescan.
336 CtdlGetRoom(&CC->room, CC->room.QRname);
337 if (Imap->last_mtime == CC->room.QRmtime) { /* No changes! */
341 /* Load the *current* message list from disk, so we can compare it
342 * to what we have in memory.
344 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
346 msglist = (long*)cdbfr->ptr;
348 num_msgs = cdbfr->len / sizeof(long);
356 * Check to see if any of the messages we know about have been expunged
358 if (Imap->num_msgs > 0) {
360 for (i = 0; i < Imap->num_msgs; ++i) {
362 message_still_exists = 0;
364 for (j = jstart; j < num_msgs; ++j) {
365 if (msglist[j] == Imap->msgids[i]) {
366 message_still_exists = 1;
373 if (message_still_exists == 0) {
374 IAPrintf("* %d EXPUNGE\r\n", i + 1);
376 // When a message is expunged, we have to slide all the existing messages up in the message array.
378 memmove(&Imap->msgids[i], &Imap->msgids[i + 1], (sizeof(long) * (Imap->num_msgs - i)));
379 memmove(&Imap->flags[i], &Imap->flags[i + 1], (sizeof(unsigned int) * (Imap->num_msgs - i)));
386 // Remember how many messages were here before we re-scanned.
387 original_num_msgs = Imap->num_msgs;
388 if (Imap->num_msgs > 0) {
389 original_highest = Imap->msgids[Imap->num_msgs - 1];
392 original_highest = 0L;
395 // Now peruse the room for *new* messages only.
396 // This logic is probably the cause of Bug # 368
397 // [ http://bugzilla.citadel.org/show_bug.cgi?id=368 ]
399 for (j = 0; j < num_msgs; ++j) {
400 if (msglist[j] > original_highest) {
401 imap_add_single_msgid(msglist[j], NULL);
405 imap_set_seen_flags(original_num_msgs);
408 * If new messages have arrived, tell the client about them.
410 if (Imap->num_msgs > original_num_msgs) {
412 for (j = 0; j < num_msgs; ++j) {
413 if (Imap->flags[j] & IMAP_RECENT) {
418 IAPrintf("* %d EXISTS\r\n", Imap->num_msgs);
419 IAPrintf("* %d RECENT\r\n", num_recent);
422 if (msglist != NULL) {
425 Imap->last_mtime = CC->room.QRmtime;
430 * This cleanup function blows away the temporary memory and files used by
433 void imap_cleanup_function(void) {
434 struct CitContext *CCC = CC;
435 citimap *Imap = CCCIMAP;
437 /* Don't do this stuff if this is not a Imap session! */
438 if (CC->h_command_function != imap_command_loop)
441 /* If there is a mailbox selected, auto-expunge it. */
442 if (Imap->selected) {
446 syslog(LOG_DEBUG, "Performing IMAP cleanup hook");
448 imap_free_transmitted_message();
450 if (Imap->cached_rfc822 != NULL) {
451 FreeStrBuf(&Imap->cached_rfc822);
452 Imap->cached_rfc822_msgnum = (-1);
453 Imap->cached_rfc822_withbody = 0;
456 if (Imap->cached_body != NULL) {
457 free(Imap->cached_body);
458 Imap->cached_body = NULL;
459 Imap->cached_body_len = 0;
460 Imap->cached_bodymsgnum = (-1);
462 FreeStrBuf(&Imap->Cmd.CmdBuf);
463 FreeStrBuf(&Imap->Reply);
464 if (Imap->Cmd.Params != NULL) free(Imap->Cmd.Params);
466 syslog(LOG_DEBUG, "Finished IMAP cleanup hook");
471 * Does the actual work of the CAPABILITY command (because we need to
472 * output this stuff in other places as well)
474 void imap_output_capability_string(void) {
475 IAPuts("CAPABILITY IMAP4REV1 NAMESPACE ID AUTH=PLAIN AUTH=LOGIN UIDPLUS");
478 if (!CC->redirect_ssl) IAPuts(" STARTTLS");
481 #ifndef DISABLE_IMAP_ACL
485 /* We are building a partial implementation of METADATA for the sole purpose
486 * of interoperating with the ical/vcard version of the Bynari Insight Connector.
487 * It is not a full RFC5464 implementation, but it should refuse non-Bynari
488 * metadata in a compatible and graceful way.
493 * LIST-EXTENDED was originally going to be required by the METADATA extension.
494 * It was mercifully removed prior to the finalization of RFC5464. We started
495 * implementing this but stopped when we learned that it would not be needed.
496 * If you uncomment this declaration you are responsible for writing a lot of new
499 * IAPuts(" LIST-EXTENDED")
505 * implements the CAPABILITY command
507 void imap_capability(int num_parms, ConstStr *Params) {
509 imap_output_capability_string();
511 IReply("OK CAPABILITY completed");
516 * Implements the ID command (specified by RFC2971)
518 * We ignore the client-supplied information, and output a NIL response.
519 * Although this is technically a valid implementation of the extension, it
520 * is quite useless. It exists only so that we may see which clients are
521 * making use of this extension.
524 void imap_id(int num_parms, ConstStr *Params) {
525 IAPuts("* ID NIL\r\n");
526 IReply("OK ID completed");
531 * Here's where our IMAP session begins its happy day.
533 void imap_greeting(void) {
535 CitContext *CCC = CC;
537 strcpy(CCC->cs_clientname, "IMAP session");
538 CCC->session_specific_data = malloc(sizeof(citimap));
539 Imap = (citimap *)CCC->session_specific_data;
540 memset(Imap, 0, sizeof(citimap));
541 Imap->authstate = imap_as_normal;
542 Imap->cached_rfc822_msgnum = (-1);
543 Imap->cached_rfc822_withbody = 0;
544 Imap->Reply = NewStrBufPlain(NULL, SIZ * 10); /* 40k */
547 IAPuts("* BYE; Server busy, try later\r\n");
548 CCC->kill_me = KILLME_NOLOGIN;
554 imap_output_capability_string();
555 IAPrintf("] %s IMAP4rev1 %s ready\r\n", CtdlGetConfigStr("c_fqdn"), CITADEL);
561 * IMAPS is just like IMAP, except it goes crypto right away.
563 void imaps_greeting(void) {
564 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
566 if (!CC->redirect_ssl) CC->kill_me = KILLME_NO_CRYPTO; /* kill session if no crypto */
573 * implements the LOGIN command (ordinary username/password login)
575 void imap_login(int num_parms, ConstStr *Params) {
579 if (Params[2].Key[0] == '{') {
580 IAPuts("+ go ahead\r\n");
581 IMAP->authstate = imap_as_expecting_multilineusername;
582 strcpy(IMAP->authseq, Params[0].Key);
586 IReply("BAD incorrect number of parameters");
590 if (CtdlLoginExistingUser(Params[2].Key) == login_ok) {
591 if (CtdlTryPassword(Params[3].Key, Params[3].len) == pass_ok) {
592 /* hm, thats not doable by IReply :-( */
593 IAPrintf("%s OK [", Params[0].Key);
594 imap_output_capability_string();
595 IAPrintf("] Hello, %s\r\n", CC->user.fullname);
600 IReplyPrintf("NO AUTHENTICATE %s failed", Params[3].Key);
605 IReply("BAD Login incorrect");
608 IReply("BAD incorrect number of parameters");
616 * Implements the AUTHENTICATE command
618 void imap_authenticate(int num_parms, ConstStr *Params) {
621 if (num_parms != 3) {
622 IReply("BAD incorrect number of parameters");
627 IReply("BAD Already logged in.");
631 if (!strcasecmp(Params[2].Key, "LOGIN")) {
632 size_t len = CtdlEncodeBase64(UsrBuf, "Username:", 9, 0);
633 if (UsrBuf[len - 1] == '\n') {
634 UsrBuf[len - 1] = '\0';
637 IAPrintf("+ %s\r\n", UsrBuf);
638 IMAP->authstate = imap_as_expecting_username;
639 strcpy(IMAP->authseq, Params[0].Key);
643 if (!strcasecmp(Params[2].Key, "PLAIN")) {
644 // size_t len = CtdlEncodeBase64(UsrBuf, "Username:", 9, 0);
645 // if (UsrBuf[len - 1] == '\n') {
646 // UsrBuf[len - 1] = '\0';
648 // IAPuts("+ %s\r\n", UsrBuf);
650 IMAP->authstate = imap_as_expecting_plainauth;
651 strcpy(IMAP->authseq, Params[0].Key);
656 IReplyPrintf("NO AUTHENTICATE %s failed",
662 void imap_auth_plain(void) {
663 citimap *Imap = IMAP;
664 const char *decoded_authstring;
665 char ident[256] = "";
673 memset(pass, 0, sizeof(pass));
674 decoded_len = StrBufDecodeBase64(Imap->Cmd.CmdBuf);
676 if (decoded_len > 0) {
677 decoded_authstring = ChrPtr(Imap->Cmd.CmdBuf);
679 len = safestrncpy(ident, decoded_authstring, sizeof ident);
681 decoded_len -= len - 1;
682 decoded_authstring += len + 1;
684 if (decoded_len > 0) {
685 len = safestrncpy(user, decoded_authstring, sizeof user);
687 decoded_authstring += len + 1;
688 decoded_len -= len - 1;
691 if (decoded_len > 0) {
692 plen = safestrncpy(pass, decoded_authstring, sizeof pass);
695 plen = sizeof(pass) - 1;
698 Imap->authstate = imap_as_normal;
700 if (!IsEmptyStr(ident)) {
701 result = CtdlLoginExistingUser(ident);
704 result = CtdlLoginExistingUser(user);
707 if (result == login_ok) {
708 if (CtdlTryPassword(pass, plen) == pass_ok) {
709 IAPrintf("%s OK authentication succeeded\r\n", Imap->authseq);
713 IAPrintf("%s NO authentication failed\r\n", Imap->authseq);
717 void imap_auth_login_user(long state) {
719 citimap *Imap = IMAP;
722 case imap_as_expecting_username:
723 StrBufDecodeBase64(Imap->Cmd.CmdBuf);
724 CtdlLoginExistingUser(ChrPtr(Imap->Cmd.CmdBuf));
725 size_t len = CtdlEncodeBase64(PWBuf, "Password:", 9, 0);
726 if (PWBuf[len - 1] == '\n') {
727 PWBuf[len - 1] = '\0';
730 IAPrintf("+ %s\r\n", PWBuf);
732 Imap->authstate = imap_as_expecting_password;
734 case imap_as_expecting_multilineusername:
735 extract_token(PWBuf, ChrPtr(Imap->Cmd.CmdBuf), 1, ' ', sizeof(PWBuf));
736 CtdlLoginExistingUser(ChrPtr(Imap->Cmd.CmdBuf));
737 IAPuts("+ go ahead\r\n");
738 Imap->authstate = imap_as_expecting_multilinepassword;
744 void imap_auth_login_pass(long state) {
745 citimap *Imap = IMAP;
746 const char *pass = NULL;
751 case imap_as_expecting_password:
752 StrBufDecodeBase64(Imap->Cmd.CmdBuf);
753 pass = ChrPtr(Imap->Cmd.CmdBuf);
754 len = StrLength(Imap->Cmd.CmdBuf);
756 case imap_as_expecting_multilinepassword:
757 pass = ChrPtr(Imap->Cmd.CmdBuf);
758 len = StrLength(Imap->Cmd.CmdBuf);
761 if (len > USERNAME_SIZE)
762 StrBufCutAt(Imap->Cmd.CmdBuf, USERNAME_SIZE, NULL);
764 if (CtdlTryPassword(pass, len) == pass_ok) {
765 IAPrintf("%s OK authentication succeeded\r\n", Imap->authseq);
768 IAPrintf("%s NO authentication failed\r\n", Imap->authseq);
770 Imap->authstate = imap_as_normal;
776 * implements the STARTTLS command (Citadel API version)
778 void imap_starttls(int num_parms, ConstStr *Params) {
779 char ok_response[SIZ];
780 char nosup_response[SIZ];
781 char error_response[SIZ];
783 snprintf(ok_response, SIZ, "%s OK begin TLS negotiation now\r\n", Params[0].Key);
784 snprintf(nosup_response, SIZ, "%s NO TLS not supported here\r\n", Params[0].Key);
785 snprintf(error_response, SIZ, "%s BAD Internal error\r\n", Params[0].Key);
786 CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
791 * implements the SELECT command
793 void imap_select(int num_parms, ConstStr *Params) {
794 citimap *Imap = IMAP;
795 char towhere[ROOMNAMELEN];
796 char augmented_roomname[ROOMNAMELEN];
800 struct ctdlroom QRscratch;
804 /* Convert the supplied folder name to a roomname */
805 i = imap_roomname(towhere, sizeof towhere, Params[2].Key);
807 IReply("NO Invalid mailbox name.");
812 /* First try a regular match */
813 c = CtdlGetRoom(&QRscratch, towhere);
815 /* Then try a mailbox name match */
817 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, towhere);
818 c = CtdlGetRoom(&QRscratch, augmented_roomname);
820 safestrncpy(towhere, augmented_roomname, sizeof(towhere));
824 /* If the room exists, check security/access */
826 /* See if there is an existing user/room relationship */
827 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
829 /* normal clients have to pass through security */
835 /* Fail here if no such room */
837 IReply("NO ... no such room, or access denied");
841 /* If we already had some other folder selected, auto-expunge it */
845 * CtdlUserGoto() formally takes us to the desired room, happily returning
846 * the number of messages and number of new messages.
848 memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
849 CtdlUserGoto(NULL, 0, 0, &msgs, &new, NULL, NULL);
852 if (!strcasecmp(Params[1].Key, "EXAMINE")) {
860 Imap->last_mtime = CC->room.QRmtime;
862 IAPrintf("* %d EXISTS\r\n", msgs);
863 IAPrintf("* %d RECENT\r\n", new);
865 IAPrintf("* OK [UIDVALIDITY %ld] UID validity status\r\n", GLOBAL_UIDVALIDITY_VALUE);
866 IAPrintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CtdlGetConfigLong("MMhighest") + 1);
868 /* Technically, \Deleted is a valid flag, but not a permanent flag,
869 * because we don't maintain its state across sessions. Citadel
870 * automatically expunges mailboxes when they are de-selected.
872 * Unfortunately, omitting \Deleted as a PERMANENTFLAGS flag causes
873 * some clients (particularly Thunderbird) to misbehave -- they simply
874 * elect not to transmit the flag at all. So we have to advertise
875 * \Deleted as a PERMANENTFLAGS flag, even though it technically isn't.
877 IAPuts("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
878 IAPuts("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] permanent flags\r\n");
880 IReplyPrintf("OK [%s] %s completed",
881 (Imap->readonly ? "READ-ONLY" : "READ-WRITE"), Params[1].Key
887 * Does the real work for expunge.
889 int imap_do_expunge(void) {
890 struct CitContext *CCC = CC;
891 citimap *Imap = CCCIMAP;
893 int num_expunged = 0;
894 long *delmsgs = NULL;
897 syslog(LOG_DEBUG, "imap_do_expunge() called");
898 if (Imap->selected == 0) {
902 if (Imap->num_msgs > 0) {
903 delmsgs = malloc(Imap->num_msgs * sizeof(long));
904 for (i = 0; i < Imap->num_msgs; ++i) {
905 if (Imap->flags[i] & IMAP_DELETED) {
906 delmsgs[num_delmsgs++] = Imap->msgids[i];
909 if (num_delmsgs > 0) {
910 CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
912 num_expunged += num_delmsgs;
916 if (num_expunged > 0) {
917 imap_rescan_msgids();
920 syslog(LOG_DEBUG, "Expunged %d messages from <%s>", num_expunged, CC->room.QRname);
921 return (num_expunged);
926 * implements the EXPUNGE command syntax
928 void imap_expunge(int num_parms, ConstStr *Params) {
929 int num_expunged = 0;
931 num_expunged = imap_do_expunge();
932 IReplyPrintf("OK expunged %d messages.", num_expunged);
937 * implements the CLOSE command
939 void imap_close(int num_parms, ConstStr *Params) {
941 /* Yes, we always expunge on close. */
942 if (IMAP->selected) {
949 IReply("OK CLOSE completed");
954 * Implements the NAMESPACE command.
956 void imap_namespace(int num_parms, ConstStr *Params) {
963 IAPuts("* NAMESPACE ");
965 /* All personal folders are subordinate to INBOX. */
966 IAPuts("((\"INBOX/\" \"/\")) ");
968 /* Other users' folders ... eventually? FIXME */
971 /* Show all floors as shared namespaces. Neato! */
973 for (i = 0; i < MAXFLOORS; ++i) {
974 fl = CtdlGetCachedFloor(i);
975 if (fl->f_flags & F_INUSE) {
976 /* if (floors > 0) IAPuts(" "); samjam says this confuses javamail */
978 len = snprintf(Namespace, sizeof(Namespace), "%s/", fl->f_name);
979 IPutStr(Namespace, len);
986 /* Wind it up with a newline and a completion message. */
988 IReply("OK NAMESPACE completed");
993 * Implements the CREATE command
996 void imap_create(int num_parms, ConstStr *Params) {
998 char roomname[ROOMNAMELEN];
1001 int newroomtype = 0;
1002 int newroomview = 0;
1003 char *notification_message = NULL;
1005 if (num_parms < 3) {
1006 IReply("NO A foder name must be specified");
1010 if (strchr(Params[2].Key, '\\') != NULL) {
1011 IReply("NO Invalid character in folder name");
1012 syslog(LOG_ERR, "invalid character in folder name");
1016 ret = imap_roomname(roomname, sizeof roomname, Params[2].Key);
1018 IReply("NO Invalid mailbox name or location");
1019 syslog(LOG_ERR, "invalid mailbox name or location");
1022 floornum = (ret & 0x00ff); /* lower 8 bits = floor number */
1023 flags = (ret & 0xff00); /* upper 8 bits = flags */
1025 if (flags & IR_MAILBOX) {
1026 if (strncasecmp(Params[2].Key, "INBOX/", 6)) {
1027 IReply("NO Personal folders must be created under INBOX");
1028 syslog(LOG_ERR, "not subordinate to inbox");
1033 if (flags & IR_MAILBOX) {
1034 newroomtype = 4; /* private mailbox */
1035 newroomview = VIEW_MAILBOX;
1038 newroomtype = 0; /* public folder */
1039 newroomview = VIEW_BBS;
1042 syslog(LOG_INFO, "Create new room <%s> on floor <%d> with type <%d>",
1043 roomname, floornum, newroomtype);
1045 ret = CtdlCreateRoom(roomname, newroomtype, "", floornum, 1, 0, newroomview);
1047 IReply("NO Mailbox already exists, or create failed");
1050 IReply("OK CREATE completed");
1051 // post a message in Aide> describing the new room
1052 notification_message = malloc(1024);
1053 snprintf(notification_message, 1024,
1054 "A new room called \"%s\" has been created by %s%s%s%s\n",
1057 ((ret & QR_MAILBOX) ? " [personal]" : ""),
1058 ((ret & QR_PRIVATE) ? " [private]" : ""),
1059 ((ret & QR_GUESSNAME) ? " [hidden]" : "")
1061 CtdlAideMessage(notification_message, "Room Creation Message");
1062 free(notification_message);
1064 syslog(LOG_DEBUG, "imap_create() completed");
1069 * Locate a room by its IMAP folder name, and check access to it.
1070 * If zapped_ok is nonzero, we can also look for the room in the zapped list.
1072 int imap_grabroom(char *returned_roomname, const char *foldername, int zapped_ok) {
1074 char augmented_roomname[ROOMNAMELEN];
1075 char roomname[ROOMNAMELEN];
1077 struct ctdlroom QRscratch;
1081 ret = imap_roomname(roomname, sizeof roomname, foldername);
1086 /* First try a regular match */
1087 c = CtdlGetRoom(&QRscratch, roomname);
1089 /* Then try a mailbox name match */
1091 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname,
1092 &CC->user, roomname);
1093 c = CtdlGetRoom(&QRscratch, augmented_roomname);
1095 safestrncpy(roomname, augmented_roomname, sizeof(roomname));
1098 /* If the room exists, check security/access */
1100 /* See if there is an existing user/room relationship */
1101 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1103 /* normal clients have to pass through security */
1104 if (ra & UA_KNOWN) {
1107 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1112 /* Fail here if no such room */
1114 strcpy(returned_roomname, "");
1117 safestrncpy(returned_roomname, QRscratch.QRname, ROOMNAMELEN);
1124 * Implements the STATUS command (sort of)
1127 void imap_status(int num_parms, ConstStr *Params) {
1130 char roomname[ROOMNAMELEN];
1131 char imaproomname[SIZ];
1132 char savedroom[ROOMNAMELEN];
1135 ret = imap_grabroom(roomname, Params[2].Key, 1);
1137 IReply("NO Invalid mailbox name or location, or access denied");
1142 * CtdlUserGoto() formally takes us to the desired room, happily returning
1143 * the number of messages and number of new messages. (If another
1144 * folder is selected, save its name so we can return there!!!!!)
1146 if (IMAP->selected) {
1147 strcpy(savedroom, CC->room.QRname);
1149 CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1152 * Tell the client what it wants to know. In fact, tell it *more* than
1153 * it wants to know. We happily IGnore the supplied status data item
1154 * names and simply spew all possible data items. It's far easier to
1155 * code and probably saves us some processing time too.
1157 len = imap_mailboxname(imaproomname, sizeof imaproomname, &CC->room);
1158 IAPuts("* STATUS ");
1159 IPutStr(imaproomname, len);
1160 IAPrintf(" (MESSAGES %d ", msgs);
1161 IAPrintf("RECENT %d ", new); /* Initially, new==recent */
1162 IAPrintf("UIDNEXT %ld ", CtdlGetConfigLong("MMhighest") + 1);
1163 IAPrintf("UNSEEN %d)\r\n", new);
1166 * If another folder is selected, go back to that room so we can resume
1167 * our happy day without violent explosions.
1169 if (IMAP->selected) {
1170 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1174 * Oooh, look, we're done!
1176 IReply("OK STATUS completed");
1181 * Implements the SUBSCRIBE command
1184 void imap_subscribe(int num_parms, ConstStr *Params) {
1186 char roomname[ROOMNAMELEN];
1187 char savedroom[ROOMNAMELEN];
1190 ret = imap_grabroom(roomname, Params[2].Key, 1);
1193 "NO Error %d: invalid mailbox name or location, or access denied",
1200 * CtdlUserGoto() formally takes us to the desired room, which has the side
1201 * effect of marking the room as not-zapped ... exactly the effect
1202 * we're looking for.
1204 if (IMAP->selected) {
1205 strcpy(savedroom, CC->room.QRname);
1207 CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1210 * If another folder is selected, go back to that room so we can resume
1211 * our happy day without violent explosions.
1213 if (IMAP->selected) {
1214 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1217 IReply("OK SUBSCRIBE completed");
1222 * Implements the UNSUBSCRIBE command
1225 void imap_unsubscribe(int num_parms, ConstStr *Params) {
1227 char roomname[ROOMNAMELEN];
1228 char savedroom[ROOMNAMELEN];
1231 ret = imap_grabroom(roomname, Params[2].Key, 1);
1233 IReply("NO Invalid mailbox name or location, or access denied");
1238 * CtdlUserGoto() formally takes us to the desired room.
1240 if (IMAP->selected) {
1241 strcpy(savedroom, CC->room.QRname);
1243 CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1246 * Now make the API call to zap the room
1248 if (CtdlForgetThisRoom() == 0) {
1249 IReply("OK UNSUBSCRIBE completed");
1251 IReply("NO You may not unsubscribe from this folder.");
1255 * If another folder is selected, go back to that room so we can resume
1256 * our happy day without violent explosions.
1258 if (IMAP->selected) {
1259 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1265 * Implements the DELETE command
1268 void imap_delete(int num_parms, ConstStr *Params) {
1270 char roomname[ROOMNAMELEN];
1271 char savedroom[ROOMNAMELEN];
1274 ret = imap_grabroom(roomname, Params[2].Key, 1);
1276 IReply("NO Invalid mailbox name, or access denied");
1281 * CtdlUserGoto() formally takes us to the desired room, happily returning
1282 * the number of messages and number of new messages. (If another
1283 * folder is selected, save its name so we can return there!!!!!)
1285 if (IMAP->selected) {
1286 strcpy(savedroom, CC->room.QRname);
1288 CtdlUserGoto(roomname, 0, 0, &msgs, &new, NULL, NULL);
1291 * Now delete the room.
1293 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1294 CtdlScheduleRoomForDeletion(&CC->room);
1295 IReply("OK DELETE completed");
1297 IReply("NO Can't delete this folder.");
1301 * If another folder is selected, go back to that room so we can resume
1302 * our happy day without violent explosions.
1304 if (IMAP->selected) {
1305 CtdlUserGoto(savedroom, 0, 0, &msgs, &new, NULL, NULL);
1311 * Back end function for imap_rename()
1313 void imap_rename_backend(struct ctdlroom *qrbuf, void *data) {
1314 char foldername[SIZ];
1315 char newfoldername[SIZ];
1316 char newroomname[ROOMNAMELEN];
1318 struct irl *irlp = NULL; /* scratch pointer */
1319 irlparms *myirlparms;
1321 myirlparms = (irlparms *) data;
1322 imap_mailboxname(foldername, sizeof foldername, qrbuf);
1324 /* Rename subfolders */
1325 if ((!strncasecmp(foldername, myirlparms->oldname, myirlparms->oldnamelen) && (foldername[myirlparms->oldnamelen] == '/'))) {
1326 snprintf(newfoldername, sizeof newfoldername, "%s/%s", myirlparms->newname, &foldername[myirlparms->oldnamelen + 1]);
1327 newfloor = imap_roomname(newroomname, sizeof newroomname, newfoldername) & 0xFF;
1328 irlp = (struct irl *) malloc(sizeof(struct irl));
1329 strcpy(irlp->irl_newroom, newroomname);
1330 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1331 irlp->irl_newfloor = newfloor;
1332 irlp->next = *(myirlparms->irl);
1333 *(myirlparms->irl) = irlp;
1339 * Implements the RENAME command
1342 void imap_rename(int num_parms, ConstStr *Params) {
1343 char old_room[ROOMNAMELEN];
1344 char new_room[ROOMNAMELEN];
1348 struct irl *irl = NULL; /* the list */
1349 struct irl *irlp = NULL; /* scratch pointer */
1353 if (strchr(Params[3].Key, '\\') != NULL) {
1354 IReply("NO Invalid character in folder name");
1358 imap_roomname(old_room, sizeof old_room, Params[2].Key);
1359 newr = imap_roomname(new_room, sizeof new_room, Params[3].Key);
1360 new_floor = (newr & 0xFF);
1362 r = CtdlRenameRoom(old_room, new_room, new_floor);
1364 if (r == crr_room_not_found) {
1365 IReply("NO Could not locate this folder");
1368 if (r == crr_already_exists) {
1369 IReplyPrintf("NO '%s' already exists.");
1372 if (r == crr_noneditable) {
1373 IReply("NO This folder is not editable.");
1376 if (r == crr_invalid_floor) {
1377 IReply("NO Folder root does not exist.");
1380 if (r == crr_access_denied) {
1381 IReply("NO You do not have permission to edit this folder.");
1385 IReplyPrintf("NO Rename failed - undefined error %d", r);
1389 /* If this is the INBOX, then RFC2060 says we have to just move the
1390 * contents. In a Citadel environment it's easier to rename the room
1391 * (already did that) and create a new inbox.
1393 if (!strcasecmp(Params[2].Key, "INBOX")) {
1394 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1397 /* Otherwise, do the subfolders. Build a list of rooms to rename... */
1399 irlparms.oldname = Params[2].Key;
1400 irlparms.oldnamelen = Params[2].len;
1401 irlparms.newname = Params[3].Key;
1402 irlparms.newnamelen = Params[3].len;
1403 irlparms.irl = &irl;
1404 CtdlForEachRoom(imap_rename_backend, (void *) &irlparms);
1406 /* ... and now rename them. */
1407 while (irl != NULL) {
1408 r = CtdlRenameRoom(irl->irl_oldroom,
1412 /* FIXME handle error returns better */
1413 syslog(LOG_ERR, "CtdlRenameRoom() error %d", r);
1421 snprintf(aidemsg, sizeof aidemsg, "IMAP folder \"%s\" renamed to \"%s\" by %s\n",
1426 CtdlAideMessage(aidemsg, "IMAP folder rename");
1428 IReply("OK RENAME completed");
1433 * Main command loop for IMAP sessions.
1435 void imap_command_loop(void) {
1436 struct CitContext *CCC = CC;
1437 struct timeval tv1, tv2;
1438 suseconds_t total_time = 0;
1440 const char *pchs, *pche;
1441 const imap_handler_hook *h;
1443 gettimeofday(&tv1, NULL);
1444 CCC->lastcmd = time(NULL);
1448 if (Imap->Cmd.CmdBuf == NULL)
1449 Imap->Cmd.CmdBuf = NewStrBufPlain(NULL, SIZ);
1451 FlushStrBuf(Imap->Cmd.CmdBuf);
1453 if (CtdlClientGetLine(Imap->Cmd.CmdBuf) < 1) {
1454 syslog(LOG_ERR, "client disconnected: ending session.");
1455 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1459 if (Imap->authstate == imap_as_expecting_password) {
1460 syslog(LOG_INFO, "<password>");
1462 else if (Imap->authstate == imap_as_expecting_plainauth) {
1463 syslog(LOG_INFO, "<plain_auth>");
1465 else if ((Imap->authstate == imap_as_expecting_multilineusername) ||
1466 cbmstrcasestr(ChrPtr(Imap->Cmd.CmdBuf), " LOGIN ")) {
1467 syslog(LOG_INFO, "LOGIN...");
1470 syslog(LOG_DEBUG, "%s", ChrPtr(Imap->Cmd.CmdBuf));
1473 pchs = ChrPtr(Imap->Cmd.CmdBuf);
1474 pche = pchs + StrLength(Imap->Cmd.CmdBuf);
1476 while ((pche > pchs) && ((*pche == '\n') || (*pche == '\r'))) {
1478 StrBufCutRight(Imap->Cmd.CmdBuf, 1);
1480 StrBufTrim(Imap->Cmd.CmdBuf);
1482 /* If we're in the middle of a multi-line command, handle that */
1483 switch (Imap->authstate){
1484 case imap_as_expecting_username:
1485 imap_auth_login_user(imap_as_expecting_username);
1488 case imap_as_expecting_multilineusername:
1489 imap_auth_login_user(imap_as_expecting_multilineusername);
1492 case imap_as_expecting_plainauth:
1496 case imap_as_expecting_password:
1497 imap_auth_login_pass(imap_as_expecting_password);
1500 case imap_as_expecting_multilinepassword:
1501 imap_auth_login_pass(imap_as_expecting_multilinepassword);
1508 /* Ok, at this point we're in normal command mode.
1509 * If the command just submitted does not contain a literal, we
1510 * might think about delivering some untagged stuff...
1513 /* Grab the tag, command, and parameters. */
1514 imap_parameterize(&Imap->Cmd);
1516 /* Now for the command set. */
1517 h = imap_lookup(Imap->Cmd.num_parms, Imap->Cmd.Params);
1520 IReply("BAD command unrecognized");
1524 /* RFC3501 says that we cannot output untagged data during these commands */
1525 if ((h->Flags & I_FLAG_UNTAGGED) == 0) {
1527 // we can put any additional untagged stuff right here in the future
1529 // Before processing the command that was just entered... if we happen
1530 // to have a folder selected, we'd like to rescan that folder for new
1531 // messages, and for deletions/changes of existing messages. This
1532 // could probably be optimized better with some deep thought...
1533 if (Imap->selected) {
1534 imap_rescan_msgids();
1538 /* does our command require a logged-in state */
1539 if ((!CC->logged_in) && ((h->Flags & I_FLAG_LOGGED_IN) != 0)) {
1540 IReply("BAD Not logged in.");
1544 /* does our command require the SELECT state on a mailbox */
1545 if ((Imap->selected == 0) && ((h->Flags & I_FLAG_SELECT) != 0)){
1546 IReply("BAD no folder selected");
1549 h->h(Imap->Cmd.num_parms, Imap->Cmd.Params);
1551 /* If the client transmitted a message we can free it now */
1556 imap_free_transmitted_message();
1558 gettimeofday(&tv2, NULL);
1559 total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1560 syslog(LOG_DEBUG, "IMAP command completed in %ld.%ld seconds",
1561 (total_time / 1000000),
1562 (total_time % 1000000)
1567 void imap_noop(int num_parms, ConstStr *Params) {
1568 IReply("OK No operation");
1572 void imap_logout(int num_parms, ConstStr *Params) {
1573 if (IMAP->selected) {
1574 imap_do_expunge(); /* yes, we auto-expunge at logout */
1576 IAPrintf("* BYE %s logging out\r\n", CtdlGetConfigStr("c_fqdn"));
1577 IReply("OK Citadel IMAP session ended.");
1578 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1583 const char *CitadelServiceIMAP="IMAP";
1584 const char *CitadelServiceIMAPS="IMAPS";
1587 // Initialization function, called from modules_init.c
1588 char *ctdl_module_init_imap(void) {
1589 if (ImapCmds == NULL) {
1590 ImapCmds = NewHash(1, NULL);
1593 RegisterImapCMD("NOOP", "", imap_noop, I_FLAG_NONE);
1594 RegisterImapCMD("CHECK", "", imap_noop, I_FLAG_NONE);
1595 RegisterImapCMD("ID", "", imap_id, I_FLAG_NONE);
1596 RegisterImapCMD("LOGOUT", "", imap_logout, I_FLAG_NONE);
1597 RegisterImapCMD("LOGIN", "", imap_login, I_FLAG_NONE);
1598 RegisterImapCMD("AUTHENTICATE", "", imap_authenticate, I_FLAG_NONE);
1599 RegisterImapCMD("CAPABILITY", "", imap_capability, I_FLAG_NONE);
1601 RegisterImapCMD("STARTTLS", "", imap_starttls, I_FLAG_NONE);
1604 /* The commans below require a logged-in state */
1605 RegisterImapCMD("SELECT", "", imap_select, I_FLAG_LOGGED_IN);
1606 RegisterImapCMD("EXAMINE", "", imap_select, I_FLAG_LOGGED_IN);
1607 RegisterImapCMD("LSUB", "", imap_list, I_FLAG_LOGGED_IN);
1608 RegisterImapCMD("LIST", "", imap_list, I_FLAG_LOGGED_IN);
1609 RegisterImapCMD("CREATE", "", imap_create, I_FLAG_LOGGED_IN);
1610 RegisterImapCMD("DELETE", "", imap_delete, I_FLAG_LOGGED_IN);
1611 RegisterImapCMD("RENAME", "", imap_rename, I_FLAG_LOGGED_IN);
1612 RegisterImapCMD("STATUS", "", imap_status, I_FLAG_LOGGED_IN);
1613 RegisterImapCMD("SUBSCRIBE", "", imap_subscribe, I_FLAG_LOGGED_IN);
1614 RegisterImapCMD("UNSUBSCRIBE", "", imap_unsubscribe, I_FLAG_LOGGED_IN);
1615 RegisterImapCMD("APPEND", "", imap_append, I_FLAG_LOGGED_IN);
1616 RegisterImapCMD("NAMESPACE", "", imap_namespace, I_FLAG_LOGGED_IN);
1617 RegisterImapCMD("SETACL", "", imap_setacl, I_FLAG_LOGGED_IN);
1618 RegisterImapCMD("DELETEACL", "", imap_deleteacl, I_FLAG_LOGGED_IN);
1619 RegisterImapCMD("GETACL", "", imap_getacl, I_FLAG_LOGGED_IN);
1620 RegisterImapCMD("LISTRIGHTS", "", imap_listrights, I_FLAG_LOGGED_IN);
1621 RegisterImapCMD("MYRIGHTS", "", imap_myrights, I_FLAG_LOGGED_IN);
1622 RegisterImapCMD("GETMETADATA", "", imap_getmetadata, I_FLAG_LOGGED_IN);
1623 RegisterImapCMD("SETMETADATA", "", imap_setmetadata, I_FLAG_LOGGED_IN);
1625 /* The commands below require the SELECT state on a mailbox */
1626 RegisterImapCMD("FETCH", "", imap_fetch, I_FLAG_LOGGED_IN | I_FLAG_SELECT | I_FLAG_UNTAGGED);
1627 RegisterImapCMD("UID", "FETCH", imap_uidfetch, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1628 RegisterImapCMD("SEARCH", "", imap_search, I_FLAG_LOGGED_IN | I_FLAG_SELECT | I_FLAG_UNTAGGED);
1629 RegisterImapCMD("UID", "SEARCH", imap_uidsearch, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1630 RegisterImapCMD("STORE", "", imap_store, I_FLAG_LOGGED_IN | I_FLAG_SELECT | I_FLAG_UNTAGGED);
1631 RegisterImapCMD("UID", "STORE", imap_uidstore, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1632 RegisterImapCMD("COPY", "", imap_copy, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1633 RegisterImapCMD("UID", "COPY", imap_uidcopy, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1634 RegisterImapCMD("EXPUNGE", "", imap_expunge, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1635 RegisterImapCMD("UID", "EXPUNGE", imap_expunge, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1636 RegisterImapCMD("CLOSE", "", imap_close, I_FLAG_LOGGED_IN | I_FLAG_SELECT);
1639 CtdlRegisterServiceHook(CtdlGetConfigInt("c_imap_port"), NULL, imap_greeting, imap_command_loop, NULL, CitadelServiceIMAP);
1641 CtdlRegisterServiceHook(CtdlGetConfigInt("c_imaps_port"), NULL, imaps_greeting, imap_command_loop, NULL, CitadelServiceIMAPS);
1643 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP, PRIO_STOP + 30);
1646 // return our module name for the log