4 * IMAP server for the Citadel/UX system
5 * Copyright (C) 2000-2001 by Art Cancro and others.
6 * This code is released under the terms of the GNU General Public License.
8 * WARNING: this is an incomplete implementation, still in progress. Parts of
9 * it work, but it's not really usable yet from a user perspective.
11 * WARNING: Mark Crispin is an idiot. IMAP is the most brain-damaged protocol
12 * you will ever have the profound lack of pleasure to encounter.
24 #include <sys/types.h>
33 #include "sysdep_decls.h"
34 #include "citserver.h"
37 #include "dynloader.h"
44 #include "internet_addressing.h"
45 #include "serv_imap.h"
46 #include "imap_tools.h"
47 #include "imap_fetch.h"
48 #include "imap_search.h"
49 #include "imap_store.h"
50 #include "imap_misc.h"
57 * If there is a message ID map in memory, free it
59 void imap_free_msgids(void) {
60 if (IMAP->msgids != NULL) {
65 if (IMAP->flags != NULL) {
73 * Back end for imap_load_msgids()
75 * FIXME: this should be optimized by figuring out a way to allocate memory
76 * once rather than doing a reallok() for each message.
78 void imap_add_single_msgid(long msgnum, void *userdata) {
80 IMAP->num_msgs = IMAP->num_msgs + 1;
81 if (IMAP->msgids == NULL) {
82 IMAP->msgids = mallok(IMAP->num_msgs * sizeof(long));
85 IMAP->msgids = reallok(IMAP->msgids,
86 IMAP->num_msgs * sizeof(long));
88 if (IMAP->flags == NULL) {
89 IMAP->flags = mallok(IMAP->num_msgs * sizeof(long));
92 IMAP->flags = reallok(IMAP->flags,
93 IMAP->num_msgs * sizeof(long));
95 IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
96 IMAP->flags[IMAP->num_msgs - 1] = 0;
102 * Set up a message ID map for the current room (folder)
104 void imap_load_msgids(void) {
106 if (IMAP->selected == 0) {
107 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
111 imap_free_msgids(); /* If there was already a map, free it */
113 CtdlForEachMessage(MSGS_ALL, 0L, (-63), NULL, NULL,
114 imap_add_single_msgid, NULL);
116 lprintf(9, "imap_load_msgids() mapped %d messages\n", IMAP->num_msgs);
121 * Re-scan the selected room (folder) and see if it's been changed at all
123 void imap_rescan_msgids(void) {
125 int original_num_msgs = 0;
126 long original_highest = 0L;
130 if (IMAP->selected == 0) {
131 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
137 * Check to see if any of the messages we know about have been expunged
139 if (IMAP->num_msgs > 0)
140 for (i=0; i<IMAP->num_msgs; ++i) {
142 count = CtdlForEachMessage(MSGS_EQ, IMAP->msgids[i],
143 (-63), NULL, NULL, NULL, NULL);
146 cprintf("* %d EXPUNGE\r\n", i+1);
148 /* Here's some nice stupid nonsense. When a message
149 * is expunged, we have to slide all the existing
150 * messages up in the message array.
153 memcpy(&IMAP->msgids[i], &IMAP->msgids[i+1],
154 (sizeof(long)*(IMAP->num_msgs-i)) );
155 memcpy(&IMAP->flags[i], &IMAP->flags[i+1],
156 (sizeof(long)*(IMAP->num_msgs-i)) );
164 * Remember how many messages were here before we re-scanned.
166 original_num_msgs = IMAP->num_msgs;
167 if (IMAP->num_msgs > 0) {
168 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
171 original_highest = 0L;
175 * Now peruse the room for *new* messages only.
177 CtdlForEachMessage(MSGS_GT, original_highest, (-63), NULL, NULL,
178 imap_add_single_msgid, NULL);
181 * If new messages have arrived, tell the client about them.
183 if (IMAP->num_msgs > original_num_msgs) {
184 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
196 * This cleanup function blows away the temporary memory and files used by
199 void imap_cleanup_function(void) {
201 /* Don't do this stuff if this is not a IMAP session! */
202 if (CC->h_command_function != imap_command_loop) return;
204 lprintf(9, "Performing IMAP cleanup hook\n");
206 lprintf(9, "Finished IMAP cleanup hook\n");
212 * Here's where our IMAP session begins its happy day.
214 void imap_greeting(void) {
216 strcpy(CC->cs_clientname, "IMAP session");
217 CtdlAllocUserData(SYM_IMAP, sizeof(struct citimap));
218 IMAP->authstate = imap_as_normal;
220 cprintf("* OK %s Citadel/UX IMAP4rev1 server ready\r\n",
226 * implements the LOGIN command (ordinary username/password login)
228 void imap_login(int num_parms, char *parms[]) {
229 if (CtdlLoginExistingUser(parms[2]) == login_ok) {
230 if (CtdlTryPassword(parms[3]) == pass_ok) {
231 cprintf("%s OK login successful\r\n", parms[0]);
236 cprintf("%s BAD Login incorrect\r\n", parms[0]);
241 * Implements the AUTHENTICATE command
243 void imap_authenticate(int num_parms, char *parms[]) {
246 if (num_parms != 3) {
247 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
251 if (!strcasecmp(parms[2], "LOGIN")) {
252 encode_base64(buf, "Username:");
253 cprintf("+ %s\r\n", buf);
254 IMAP->authstate = imap_as_expecting_username;
255 strcpy(IMAP->authseq, parms[0]);
260 cprintf("%s NO AUTHENTICATE %s failed\r\n",
265 void imap_auth_login_user(char *cmd) {
268 decode_base64(buf, cmd);
269 CtdlLoginExistingUser(buf);
270 encode_base64(buf, "Password:");
271 cprintf("+ %s\r\n", buf);
272 IMAP->authstate = imap_as_expecting_password;
276 void imap_auth_login_pass(char *cmd) {
279 decode_base64(buf, cmd);
280 if (CtdlTryPassword(buf) == pass_ok) {
281 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
284 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
286 IMAP->authstate = imap_as_normal;
293 * implements the CAPABILITY command
295 void imap_capability(int num_parms, char *parms[]) {
296 cprintf("* CAPABILITY IMAP4 IMAP4REV1 AUTH=LOGIN\r\n");
297 cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
305 * implements the SELECT command
307 void imap_select(int num_parms, char *parms[]) {
309 char augmented_roomname[ROOMNAMELEN];
313 struct quickroom QRscratch;
319 /* Convert the supplied folder name to a roomname */
320 i = imap_roomname(towhere, sizeof towhere, parms[2]);
322 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
326 floornum = (i & 0x00ff);
327 roomflags = (i & 0xff00);
329 /* First try a regular match */
330 c = getroom(&QRscratch, towhere);
332 /* Then try a mailbox name match */
334 MailboxName(augmented_roomname, &CC->usersupp, towhere);
335 c = getroom(&QRscratch, augmented_roomname);
337 strcpy(towhere, augmented_roomname);
340 /* If the room exists, check security/access */
342 /* See if there is an existing user/room relationship */
343 ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
345 /* normal clients have to pass through security */
351 /* Fail here if no such room */
353 cprintf("%s NO ... no such room, or access denied\r\n",
360 * usergoto() formally takes us to the desired room, happily returning
361 * the number of messages and number of new messages.
363 usergoto(QRscratch.QRname, 0, &msgs, &new);
366 if (!strcasecmp(parms[1], "EXAMINE")) {
375 /* FIXME ... much more info needs to be supplied here */
376 cprintf("* %d EXISTS\r\n", msgs);
377 cprintf("* %d RECENT\r\n", new);
378 cprintf("* FLAGS (\\Deleted)\r\n");
379 cprintf("* OK [PERMANENTFLAGS (\\Deleted)] permanent flags\r\n");
380 cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
381 cprintf("%s OK [%s] %s completed\r\n",
383 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"),
390 * does the real work for expunge
392 int imap_do_expunge(void) {
394 int num_expunged = 0;
396 if (IMAP->num_msgs > 0) for (i=0; i<IMAP->num_msgs; ++i) {
397 if (IMAP->flags[i] & IMAP_DELETED) {
398 CtdlDeleteMessages(CC->quickroom.QRname,
399 IMAP->msgids[i], "");
404 if (num_expunged > 0) {
405 imap_rescan_msgids();
408 return(num_expunged);
413 * implements the EXPUNGE command syntax
415 void imap_expunge(int num_parms, char *parms[]) {
416 int num_expunged = 0;
418 cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
423 * implements the CLOSE command
425 void imap_close(int num_parms, char *parms[]) {
427 /* Yes, we always expunge on close. */
433 cprintf("%s OK CLOSE completed\r\n", parms[0]);
440 * Used by LIST and LSUB to show the floors in the listing
442 void imap_list_floors(char *cmd) {
446 for (i=0; i<MAXFLOORS; ++i) {
448 if (fl->f_flags & F_INUSE) {
449 cprintf("* %s (\\NoSelect) \"|\" ", cmd);
450 imap_strout(fl->f_name);
459 * Back end for imap_lsub()
461 * IMAP "subscribed folder" is equivocated to Citadel "known rooms." This
462 * may or may not be the desired behavior in the future.
464 void imap_lsub_listroom(struct quickroom *qrbuf, void *data) {
469 pattern = (char *)data;
470 lprintf(9, "lsub pattern: <%s>\n", pattern);
472 /* Only list rooms to which the user has access!! */
473 ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
475 imap_mailboxname(buf, sizeof buf, qrbuf);
476 cprintf("* LSUB () \"|\" ");
484 * Implements the LSUB command
486 * FIXME: Handle wildcards, please.
488 void imap_lsub(int num_parms, char *parms[]) {
491 cprintf("%s BAD arguments invalid\r\n", parms[0]);
494 sprintf(pattern, "%s%s", parms[2], parms[3]);
495 imap_list_floors("LSUB");
496 ForEachRoom(imap_lsub_listroom, pattern);
497 cprintf("%s OK LSUB completed\r\n", parms[0]);
503 * Back end for imap_list()
505 void imap_list_listroom(struct quickroom *qrbuf, void *data) {
510 pattern = (char *)data;
511 lprintf(9, "list pattern: <%s>\n", pattern);
513 /* Only list rooms to which the user has access!! */
514 ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
516 || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
517 imap_mailboxname(buf, sizeof buf, qrbuf);
518 cprintf("* LIST () \"|\" ");
526 * Implements the LIST command
528 * FIXME: Handle wildcards, please.
530 void imap_list(int num_parms, char *parms[]) {
533 cprintf("%s BAD arguments invalid\r\n", parms[0]);
536 sprintf(pattern, "%s%s", parms[2], parms[3]);
537 imap_list_floors("LIST");
538 ForEachRoom(imap_list_listroom, pattern);
539 cprintf("%s OK LIST completed\r\n", parms[0]);
545 * Implements the CREATE command
548 void imap_create(int num_parms, char *parms[]) {
550 char roomname[ROOMNAMELEN];
555 ret = imap_roomname(roomname, sizeof roomname, parms[2]);
557 cprintf("%s NO Invalid mailbox name or location\r\n",
561 floornum = ( ret & 0x00ff ); /* lower 8 bits = floor number */
562 flags = ( ret & 0xff00 ); /* upper 8 bits = flags */
564 if (flags & IR_MAILBOX) {
565 newroomtype = 4; /* private mailbox */
568 newroomtype = 0; /* public folder */
571 lprintf(7, "Create new room <%s> on floor <%d> with type <%d>\n",
572 roomname, floornum, newroomtype);
574 ret = create_room(roomname, newroomtype, "", floornum, 1);
576 cprintf("%s NO Mailbox already exists, or create failed\r\n",
580 cprintf("%s OK CREATE completed\r\n", parms[0]);
586 * Locate a room by its IMAP folder name, and check access to it
588 int imap_grabroom(char *returned_roomname, char *foldername) {
590 char augmented_roomname[ROOMNAMELEN];
591 char roomname[ROOMNAMELEN];
593 struct quickroom QRscratch;
597 ret = imap_roomname(roomname, sizeof roomname, foldername);
602 /* First try a regular match */
603 c = getroom(&QRscratch, roomname);
605 /* Then try a mailbox name match */
607 MailboxName(augmented_roomname, &CC->usersupp, roomname);
608 c = getroom(&QRscratch, augmented_roomname);
610 strcpy(roomname, augmented_roomname);
613 /* If the room exists, check security/access */
615 /* See if there is an existing user/room relationship */
616 ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
618 /* normal clients have to pass through security */
624 /* Fail here if no such room */
626 strcpy(returned_roomname, "");
630 strcpy(returned_roomname, QRscratch.QRname);
637 * Implements the STATUS command (sort of)
640 void imap_status(int num_parms, char *parms[]) {
642 char roomname[ROOMNAMELEN];
644 char savedroom[ROOMNAMELEN];
647 ret = imap_grabroom(roomname, parms[2]);
649 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
655 * usergoto() formally takes us to the desired room, happily returning
656 * the number of messages and number of new messages. (If another
657 * folder is selected, save its name so we can return there!!!!!)
659 if (IMAP->selected) {
660 strcpy(savedroom, CC->quickroom.QRname);
662 usergoto(roomname, 0, &msgs, &new);
665 * Tell the client what it wants to know. In fact, tell it *more* than
666 * it wants to know. We happily IGnore the supplied status data item
667 * names and simply spew all possible data items. It's far easier to
668 * code and probably saves us some processing time too.
670 * FIXME we need to implement RECENT and UNSEEN eventually...
673 imap_mailboxname(buf, sizeof buf, &CC->quickroom);
674 cprintf("* STATUS ");
676 cprintf(" (MESSAGES %d RECENT 0 UIDNEXT %ld "
677 "UIDVALIDITY 0 UNSEEN 0)\r\n",
679 CitControl.MMhighest + 1
683 * If another folder is selected, go back to that room so we can resume
684 * our happy day without violent explosions.
686 if (IMAP->selected) {
687 usergoto(savedroom, 0, &msgs, &new);
691 * Oooh, look, we're done!
693 cprintf("%s OK STATUS completed\r\n", parms[0]);
699 * Implements the SUBSCRIBE command
702 void imap_subscribe(int num_parms, char *parms[]) {
704 char roomname[ROOMNAMELEN];
705 char savedroom[ROOMNAMELEN];
708 ret = imap_grabroom(roomname, parms[2]);
710 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
716 * usergoto() formally takes us to the desired room, which has the side
717 * effect of marking the room as not-zapped ... exactly the effect
720 if (IMAP->selected) {
721 strcpy(savedroom, CC->quickroom.QRname);
723 usergoto(roomname, 0, &msgs, &new);
726 * If another folder is selected, go back to that room so we can resume
727 * our happy day without violent explosions.
729 if (IMAP->selected) {
730 usergoto(savedroom, 0, &msgs, &new);
733 cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
738 * Implements the UNSUBSCRIBE command
741 void imap_unsubscribe(int num_parms, char *parms[]) {
743 char roomname[ROOMNAMELEN];
744 char savedroom[ROOMNAMELEN];
747 ret = imap_grabroom(roomname, parms[2]);
749 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
755 * usergoto() formally takes us to the desired room.
757 if (IMAP->selected) {
758 strcpy(savedroom, CC->quickroom.QRname);
760 usergoto(roomname, 0, &msgs, &new);
763 * Now make the API call to zap the room
765 if (CtdlForgetThisRoom() == 0) {
766 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
769 cprintf("%s NO You may not unsubscribe from this folder.\r\n",
774 * If another folder is selected, go back to that room so we can resume
775 * our happy day without violent explosions.
777 if (IMAP->selected) {
778 usergoto(savedroom, 0, &msgs, &new);
785 * Implements the DELETE command
788 void imap_delete(int num_parms, char *parms[]) {
790 char roomname[ROOMNAMELEN];
791 char savedroom[ROOMNAMELEN];
794 ret = imap_grabroom(roomname, parms[2]);
796 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
802 * usergoto() formally takes us to the desired room, happily returning
803 * the number of messages and number of new messages. (If another
804 * folder is selected, save its name so we can return there!!!!!)
806 if (IMAP->selected) {
807 strcpy(savedroom, CC->quickroom.QRname);
809 usergoto(roomname, 0, &msgs, &new);
812 * Now delete the room.
814 if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->quickroom)) {
815 cprintf("%s OK DELETE completed\r\n", parms[0]);
816 delete_room(&CC->quickroom);
819 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
823 * If another folder is selected, go back to that room so we can resume
824 * our happy day without violent explosions.
826 if (IMAP->selected) {
827 usergoto(savedroom, 0, &msgs, &new);
834 * Implements the RENAME command
837 void imap_rename(int num_parms, char *parms[]) {
838 cprintf("%s NO The RENAME command is not yet implemented (FIXME)\r\n",
845 * Main command loop for IMAP sessions.
847 void imap_command_loop(void) {
853 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
854 if (client_gets(cmdbuf) < 1) {
855 lprintf(3, "IMAP socket is broken. Ending session.\r\n");
860 lprintf(5, "citserver[%3d]: %s\r\n", CC->cs_pid, cmdbuf);
861 while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
864 /* strip off l/t whitespace and CRLF */
865 if (cmdbuf[strlen(cmdbuf)-1]=='\n') cmdbuf[strlen(cmdbuf)-1]=0;
866 if (cmdbuf[strlen(cmdbuf)-1]=='\r') cmdbuf[strlen(cmdbuf)-1]=0;
869 /* If we're in the middle of a multi-line command, handle that */
870 if (IMAP->authstate == imap_as_expecting_username) {
871 imap_auth_login_user(cmdbuf);
874 if (IMAP->authstate == imap_as_expecting_password) {
875 imap_auth_login_pass(cmdbuf);
880 /* Ok, at this point we're in normal command mode. The first thing
881 * we do is print any incoming pages (yeah! we really do!)
883 imap_print_express_messages();
886 * Before processing the command that was just entered... if we happen
887 * to have a folder selected, we'd like to rescan that folder for new
888 * messages, and for deletions/changes of existing messages. This
889 * could probably be optimized somehow, but IMAP sucks...
891 if (IMAP->selected) {
892 imap_rescan_msgids();
895 /* Now for the command set. */
897 /* Grab the tag, command, and parameters. Check syntax. */
898 num_parms = imap_parameterize(parms, cmdbuf);
900 cprintf("BAD syntax error\r\n");
903 /* The commands below may be executed in any state */
905 else if ( (!strcasecmp(parms[1], "NOOP"))
906 || (!strcasecmp(parms[1], "CHECK")) ) {
907 cprintf("%s OK This command successfully did nothing.\r\n",
911 else if (!strcasecmp(parms[1], "LOGOUT")) {
912 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
913 cprintf("%s OK thank you for using Citadel IMAP\r\n", parms[0]);
918 else if (!strcasecmp(parms[1], "LOGIN")) {
919 imap_login(num_parms, parms);
922 else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
923 imap_authenticate(num_parms, parms);
926 else if (!strcasecmp(parms[1], "CAPABILITY")) {
927 imap_capability(num_parms, parms);
930 else if (!CC->logged_in) {
931 cprintf("%s BAD Not logged in.\r\n", parms[0]);
934 /* The commans below require a logged-in state */
936 else if (!strcasecmp(parms[1], "SELECT")) {
937 imap_select(num_parms, parms);
940 else if (!strcasecmp(parms[1], "EXAMINE")) {
941 imap_select(num_parms, parms);
944 else if (!strcasecmp(parms[1], "LSUB")) {
945 imap_lsub(num_parms, parms);
948 else if (!strcasecmp(parms[1], "LIST")) {
949 imap_list(num_parms, parms);
952 else if (!strcasecmp(parms[1], "CREATE")) {
953 imap_create(num_parms, parms);
956 else if (!strcasecmp(parms[1], "DELETE")) {
957 imap_delete(num_parms, parms);
960 else if (!strcasecmp(parms[1], "RENAME")) {
961 imap_rename(num_parms, parms);
964 else if (!strcasecmp(parms[1], "STATUS")) {
965 imap_status(num_parms, parms);
968 else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
969 imap_subscribe(num_parms, parms);
972 else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
973 imap_unsubscribe(num_parms, parms);
976 else if (IMAP->selected == 0) {
977 cprintf("%s BAD no folder selected\r\n", parms[0]);
980 /* The commands below require the SELECT state on a mailbox */
982 else if (!strcasecmp(parms[1], "FETCH")) {
983 imap_fetch(num_parms, parms);
986 else if ( (!strcasecmp(parms[1], "UID"))
987 && (!strcasecmp(parms[2], "FETCH")) ) {
988 imap_uidfetch(num_parms, parms);
991 else if (!strcasecmp(parms[1], "SEARCH")) {
992 imap_search(num_parms, parms);
995 else if ( (!strcasecmp(parms[1], "UID"))
996 && (!strcasecmp(parms[2], "SEARCH")) ) {
997 imap_uidsearch(num_parms, parms);
1000 else if (!strcasecmp(parms[1], "STORE")) {
1001 imap_store(num_parms, parms);
1004 else if ( (!strcasecmp(parms[1], "UID"))
1005 && (!strcasecmp(parms[2], "STORE")) ) {
1006 imap_uidstore(num_parms, parms);
1009 else if (!strcasecmp(parms[1], "COPY")) {
1010 imap_copy(num_parms, parms);
1013 else if ( (!strcasecmp(parms[1], "UID"))
1014 && (!strcasecmp(parms[2], "COPY")) ) {
1015 imap_uidcopy(num_parms, parms);
1018 else if (!strcasecmp(parms[1], "EXPUNGE")) {
1019 imap_expunge(num_parms, parms);
1022 else if (!strcasecmp(parms[1], "CLOSE")) {
1023 imap_close(num_parms, parms);
1026 /* End of commands. If we get here, the command is either invalid
1031 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1039 * This function is called by dynloader.c to register the IMAP module
1040 * with the Citadel server.
1042 char *Dynamic_Module_Init(void)
1044 SYM_IMAP = CtdlGetDynamicSymbol();
1045 CtdlRegisterServiceHook(config.c_imap_port,
1049 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);