]> code.citadel.org Git - citadel.git/blobdiff - citadel/serv_imap.c
* Replaced all "Citadel/UX" references with "Citadel"
[citadel.git] / citadel / serv_imap.c
index af668a48ee4bf575992d3e4c236c2e79884236f8..e456f925ff790cac60e17e62a799cbb5777814ca 100644 (file)
@@ -1,16 +1,12 @@
 /*
  * $Id$ 
  *
- * IMAP server for the Citadel/UX system
- * Copyright (C) 2000-2001 by Art Cancro and others.
+ * IMAP server for the Citadel system
+ * Copyright (C) 2000-2002 by Art Cancro and others.
  * This code is released under the terms of the GNU General Public License.
  *
- * WARNING: this is an incomplete implementation, still in progress.  Parts of
- * it work, but it's not really usable yet from a user perspective.
- *
  * WARNING: Mark Crispin is an idiot.  IMAP is the most brain-damaged protocol
  * you will ever have the profound lack of pleasure to encounter.
- * 
  */
 
 #include "sysdep.h"
 #include <pwd.h>
 #include <errno.h>
 #include <sys/types.h>
-#include <sys/time.h>
+
+#if TIME_WITH_SYS_TIME
+# include <sys/time.h>
+# include <time.h>
+#else
+# if HAVE_SYS_TIME_H
+#  include <sys/time.h>
+# else
+#  include <time.h>
+# endif
+#endif
+
 #include <sys/wait.h>
 #include <ctype.h>
 #include <string.h>
 #include <limits.h>
 #include "citadel.h"
 #include "server.h"
-#include <time.h>
 #include "sysdep_decls.h"
 #include "citserver.h"
 #include "support.h"
 #include "config.h"
-#include "dynloader.h"
+#include "serv_extensions.h"
 #include "room_ops.h"
 #include "user_ops.h"
 #include "policy.h"
 #include "imap_store.h"
 #include "imap_misc.h"
 
+#ifdef HAVE_OPENSSL
+#include "serv_crypto.h"
+#endif
 
-long SYM_IMAP;
+/* imap_rename() uses this struct containing list of rooms to rename */
+struct irl {
+       struct irl *next;
+       char irl_oldroom[ROOMNAMELEN];
+       char irl_newroom[ROOMNAMELEN];
+       int irl_newfloor;
+};
+
+/* Data which is passed between imap_rename() and imap_rename_backend() */
+struct irlparms {
+       char *oldname;
+       char *newname;
+       struct irl **irl;
+};
 
 
 /*
  * If there is a message ID map in memory, free it
  */
-void imap_free_msgids(void) {
+void imap_free_msgids(void)
+{
        if (IMAP->msgids != NULL) {
-               phree(IMAP->msgids);
+               free(IMAP->msgids);
                IMAP->msgids = NULL;
                IMAP->num_msgs = 0;
        }
        if (IMAP->flags != NULL) {
-               phree(IMAP->flags);
+               free(IMAP->flags);
                IMAP->flags = NULL;
        }
 }
 
 
+/*
+ * If there is a transmitted message in memory, free it
+ */
+void imap_free_transmitted_message(void)
+{
+       if (IMAP->transmitted_message != NULL) {
+               free(IMAP->transmitted_message);
+               IMAP->transmitted_message = NULL;
+               IMAP->transmitted_length = 0;
+       }
+}
+
+
+/*
+ * Set the \\Seen flag for messages which aren't new
+ */
+void imap_set_seen_flags(void)
+{
+       struct visit vbuf;
+       int i;
+
+       CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
+       if (IMAP->num_msgs > 0) {
+               for (i = 0; i < IMAP->num_msgs; ++i) {
+                       if (is_msg_in_mset(vbuf.v_seen, IMAP->msgids[i])) {
+                               IMAP->flags[i] |= IMAP_SEEN;
+                       }
+                       if (is_msg_in_mset
+                           (vbuf.v_answered, IMAP->msgids[i])) {
+                               IMAP->flags[i] |= IMAP_ANSWERED;
+                       }
+               }
+       }
+}
+
+
+
+
 /*
  * Back end for imap_load_msgids()
  *
- * FIXME: this should be optimized by figuring out a way to allocate memory
- * once rather than doing a reallok() for each message.
+ * Optimization: instead of calling realloc() to add each message, we
+ * allocate space in the list for REALLOC_INCREMENT messages at a time.  This
+ * allows the mapping to proceed much faster.
  */
-void imap_add_single_msgid(long msgnum, void *userdata) {
-       
+void imap_add_single_msgid(long msgnum, void *userdata)
+{
+
        IMAP->num_msgs = IMAP->num_msgs + 1;
        if (IMAP->msgids == NULL) {
-               IMAP->msgids = mallok(IMAP->num_msgs * sizeof(long));
-       }
-       else {
-               IMAP->msgids = reallok(IMAP->msgids,
-                       IMAP->num_msgs * sizeof(long));
+               IMAP->msgids = malloc(IMAP->num_msgs * sizeof(long)
+                                     * REALLOC_INCREMENT);
+       } else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
+               IMAP->msgids = realloc(IMAP->msgids,
+                                      (IMAP->num_msgs +
+                                       REALLOC_INCREMENT) * sizeof(long));
        }
        if (IMAP->flags == NULL) {
-               IMAP->flags = mallok(IMAP->num_msgs * sizeof(long));
-       }
-       else {
-               IMAP->flags = reallok(IMAP->flags,
-                       IMAP->num_msgs * sizeof(long));
+               IMAP->flags = malloc(IMAP->num_msgs * sizeof(long)
+                                    * REALLOC_INCREMENT);
+       } else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
+               IMAP->flags = realloc(IMAP->flags,
+                                     (IMAP->num_msgs +
+                                      REALLOC_INCREMENT) * sizeof(long));
        }
        IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
        IMAP->flags[IMAP->num_msgs - 1] = 0;
@@ -101,81 +166,116 @@ void imap_add_single_msgid(long msgnum, void *userdata) {
 /*
  * Set up a message ID map for the current room (folder)
  */
-void imap_load_msgids(void) {
-        
+void imap_load_msgids(void)
+{
+
        if (IMAP->selected == 0) {
-               lprintf(5, "imap_load_msgids() can't run; no room selected\n");
+               lprintf(CTDL_ERR,
+                       "imap_load_msgids() can't run; no room selected\n");
                return;
        }
 
        imap_free_msgids();     /* If there was already a map, free it */
 
-       CtdlForEachMessage(MSGS_ALL, 0L, (-63), NULL, NULL,
-               imap_add_single_msgid, NULL);
+       CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
+                          imap_add_single_msgid, NULL);
 
-       lprintf(9, "imap_load_msgids() mapped %d messages\n", IMAP->num_msgs);
+       imap_set_seen_flags();
+       lprintf(CTDL_DEBUG, "imap_load_msgids() mapped %d messages\n",
+               IMAP->num_msgs);
 }
 
 
 /*
  * Re-scan the selected room (folder) and see if it's been changed at all
  */
-void imap_rescan_msgids(void) {
+void imap_rescan_msgids(void)
+{
 
        int original_num_msgs = 0;
        long original_highest = 0L;
-       int i;
-       int count;
+       int i, j;
+       int message_still_exists;
+       struct cdbdata *cdbfr;
+       long *msglist = NULL;
+       int num_msgs = 0;
+
 
        if (IMAP->selected == 0) {
-               lprintf(5, "imap_load_msgids() can't run; no room selected\n");
+               lprintf(CTDL_ERR,
+                       "imap_load_msgids() can't run; no room selected\n");
                return;
        }
 
+       /* Load the *current* message list from disk, so we can compare it
+        * to what we have in memory.
+        */
+       cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
+       if (cdbfr != NULL) {
+               msglist = malloc(cdbfr->len);
+               memcpy(msglist, cdbfr->ptr, cdbfr->len);
+               num_msgs = cdbfr->len / sizeof(long);
+               cdb_free(cdbfr);
+       } else {
+               num_msgs = 0;
+       }
 
        /*
         * Check to see if any of the messages we know about have been expunged
         */
        if (IMAP->num_msgs > 0)
-        for (i=0; i<IMAP->num_msgs; ++i) {
+               for (i = 0; i < IMAP->num_msgs; ++i) {
+
+                       message_still_exists = 0;
+                       if (num_msgs > 0)
+                               for (j = 0; j < num_msgs; ++j) {
+                                       if (msglist[j] == IMAP->msgids[i]) {
+                                               message_still_exists = 1;
+                                       }
+                               }
+
+                       if (message_still_exists == 0) {
+                               cprintf("* %d EXPUNGE\r\n", i + 1);
+
+                               /* Here's some nice stupid nonsense.  When a message
+                                * is expunged, we have to slide all the existing
+                                * messages up in the message array.
+                                */
+                               --IMAP->num_msgs;
+                               memcpy(&IMAP->msgids[i],
+                                      &IMAP->msgids[i + 1],
+                                      (sizeof(long) *
+                                       (IMAP->num_msgs - i)));
+                               memcpy(&IMAP->flags[i],
+                                      &IMAP->flags[i + 1],
+                                      (sizeof(long) *
+                                       (IMAP->num_msgs - i)));
+
+                               --i;
+                       }
 
-               count = CtdlForEachMessage(MSGS_EQ, IMAP->msgids[i],
-                       (-63), NULL, NULL, NULL, NULL);
-
-               if (count == 0) {
-                       cprintf("* %d EXPUNGE\r\n", i+1);
-
-                       /* Here's some nice stupid nonsense.  When a message
-                        * is expunged, we have to slide all the existing
-                        * messages up in the message array.
-                        */
-                       --IMAP->num_msgs;
-                       memcpy(&IMAP->msgids[i], &IMAP->msgids[i+1],
-                               (sizeof(long)*(IMAP->num_msgs-i)) );
-                       memcpy(&IMAP->flags[i], &IMAP->flags[i+1],
-                               (sizeof(long)*(IMAP->num_msgs-i)) );
-
-                       --i;
                }
 
-       }
-
        /*
         * Remember how many messages were here before we re-scanned.
         */
        original_num_msgs = IMAP->num_msgs;
        if (IMAP->num_msgs > 0) {
                original_highest = IMAP->msgids[IMAP->num_msgs - 1];
-       }
-       else {
+       } else {
                original_highest = 0L;
        }
 
        /*
         * Now peruse the room for *new* messages only.
         */
-       CtdlForEachMessage(MSGS_GT, original_highest, (-63), NULL, NULL,
-               imap_add_single_msgid, NULL);
+       if (num_msgs > 0)
+               for (j = 0; j < num_msgs; ++j) {
+                       if (msglist[j] > original_highest) {
+                               imap_add_single_msgid(msglist[j], NULL);
+                       }
+               }
+       imap_set_seen_flags();
 
        /*
         * If new messages have arrived, tell the client about them.
@@ -184,6 +284,8 @@ void imap_rescan_msgids(void) {
                cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
        }
 
+       if (num_msgs != 0)
+               free(msglist);
 }
 
 
@@ -196,14 +298,35 @@ void imap_rescan_msgids(void) {
  * This cleanup function blows away the temporary memory and files used by
  * the IMAP server.
  */
-void imap_cleanup_function(void) {
+void imap_cleanup_function(void)
+{
 
        /* Don't do this stuff if this is not a IMAP session! */
-       if (CC->h_command_function != imap_command_loop) return;
+       if (CC->h_command_function != imap_command_loop)
+               return;
 
-       lprintf(9, "Performing IMAP cleanup hook\n");
+       /* If there is a mailbox selected, auto-expunge it. */
+       if (IMAP->selected) {
+               imap_do_expunge();
+       }
+
+       lprintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
        imap_free_msgids();
-       lprintf(9, "Finished IMAP cleanup hook\n");
+       imap_free_transmitted_message();
+
+       if (IMAP->cached_fetch != NULL) {
+               fclose(IMAP->cached_fetch);
+               IMAP->cached_fetch = NULL;
+               IMAP->cached_msgnum = (-1);
+       }
+
+       if (IMAP->cached_body != NULL) {
+               fclose(IMAP->cached_body);
+               IMAP->cached_body = NULL;
+               IMAP->cached_bodymsgnum = (-1);
+       }
+
+       lprintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
 }
 
 
@@ -211,13 +334,16 @@ void imap_cleanup_function(void) {
 /*
  * Here's where our IMAP session begins its happy day.
  */
-void imap_greeting(void) {
+void imap_greeting(void)
+{
 
        strcpy(CC->cs_clientname, "IMAP session");
        CtdlAllocUserData(SYM_IMAP, sizeof(struct citimap));
        IMAP->authstate = imap_as_normal;
+       IMAP->cached_fetch = NULL;
+       IMAP->cached_msgnum = (-1);
 
-       cprintf("* OK %s Citadel/UX IMAP4rev1 server ready\r\n",
+       cprintf("* OK %s Citadel IMAP4rev1 server ready\r\n",
                config.c_fqdn);
 }
 
@@ -225,13 +351,14 @@ void imap_greeting(void) {
 /*
  * implements the LOGIN command (ordinary username/password login)
  */
-void imap_login(int num_parms, char *parms[]) {
+void imap_login(int num_parms, char *parms[])
+{
        if (CtdlLoginExistingUser(parms[2]) == login_ok) {
                if (CtdlTryPassword(parms[3]) == pass_ok) {
                        cprintf("%s OK login successful\r\n", parms[0]);
                        return;
                }
-        }
+       }
 
        cprintf("%s BAD Login incorrect\r\n", parms[0]);
 }
@@ -240,16 +367,23 @@ void imap_login(int num_parms, char *parms[]) {
 /*
  * Implements the AUTHENTICATE command
  */
-void imap_authenticate(int num_parms, char *parms[]) {
+void imap_authenticate(int num_parms, char *parms[])
+{
        char buf[SIZ];
 
        if (num_parms != 3) {
-               cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
+               cprintf("%s BAD incorrect number of parameters\r\n",
+                       parms[0]);
+               return;
+       }
+
+       if (CC->logged_in) {
+               cprintf("%s BAD Already logged in.\r\n", parms[0]);
                return;
        }
 
        if (!strcasecmp(parms[2], "LOGIN")) {
-               encode_base64(buf, "Username:");
+               CtdlEncodeBase64(buf, "Username:", 9);
                cprintf("+ %s\r\n", buf);
                IMAP->authstate = imap_as_expecting_username;
                strcpy(IMAP->authseq, parms[0]);
@@ -262,25 +396,27 @@ void imap_authenticate(int num_parms, char *parms[]) {
        }
 }
 
-void imap_auth_login_user(char *cmd) {
+void imap_auth_login_user(char *cmd)
+{
        char buf[SIZ];
 
-       decode_base64(buf, cmd);
+       CtdlDecodeBase64(buf, cmd, SIZ);
        CtdlLoginExistingUser(buf);
-       encode_base64(buf, "Password:");
+       CtdlEncodeBase64(buf, "Password:", 9);
        cprintf("+ %s\r\n", buf);
        IMAP->authstate = imap_as_expecting_password;
        return;
 }
 
-void imap_auth_login_pass(char *cmd) {
+void imap_auth_login_pass(char *cmd)
+{
        char buf[SIZ];
 
-       decode_base64(buf, cmd);
+       CtdlDecodeBase64(buf, cmd, SIZ);
        if (CtdlTryPassword(buf) == pass_ok) {
-               cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
-       }
-       else {
+               cprintf("%s OK authentication succeeded\r\n",
+                       IMAP->authseq);
+       else {
                cprintf("%s NO authentication failed\r\n", IMAP->authseq);
        }
        IMAP->authstate = imap_as_normal;
@@ -288,29 +424,58 @@ void imap_auth_login_pass(char *cmd) {
 }
 
 
-
 /*
  * implements the CAPABILITY command
  */
-void imap_capability(int num_parms, char *parms[]) {
-       cprintf("* CAPABILITY IMAP4 IMAP4REV1 AUTH=LOGIN\r\n");
+void imap_capability(int num_parms, char *parms[])
+{
+       cprintf("* CAPABILITY IMAP4 IMAP4REV1 NAMESPACE AUTH=LOGIN");
+
+#ifdef HAVE_OPENSSL
+       cprintf(" STARTTLS");
+#endif
+
+       cprintf("\r\n");
        cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
 }
 
 
 
+/*
+ * implements the STARTTLS command (Citadel API version)
+ */
+#ifdef HAVE_OPENSSL
+void imap_starttls(int num_parms, char *parms[])
+{
+       char ok_response[SIZ];
+       char nosup_response[SIZ];
+       char error_response[SIZ];
+
+       sprintf(ok_response,
+               "%s OK begin TLS negotiation now\r\n",
+               parms[0]);
+       sprintf(nosup_response,
+               "%s NO TLS not supported here\r\n",
+               parms[0]);
+       sprintf(error_response,
+               "%s BAD Internal error\r\n",
+               parms[0]);
+       CtdlStartTLS(ok_response, nosup_response, error_response);
+}
+#endif
 
 
 /*
  * implements the SELECT command
  */
-void imap_select(int num_parms, char *parms[]) {
+void imap_select(int num_parms, char *parms[])
+{
        char towhere[SIZ];
        char augmented_roomname[ROOMNAMELEN];
        int c = 0;
        int ok = 0;
        int ra = 0;
-       struct quickroom QRscratch;
+       struct ctdlroom QRscratch;
        int msgs, new;
        int floornum;
        int roomflags;
@@ -326,25 +491,26 @@ void imap_select(int num_parms, char *parms[]) {
        floornum = (i & 0x00ff);
        roomflags = (i & 0xff00);
 
-        /* First try a regular match */
-        c = getroom(&QRscratch, towhere);
+       /* First try a regular match */
+       c = getroom(&QRscratch, towhere);
 
-        /* Then try a mailbox name match */
-        if (c != 0) {
-                MailboxName(augmented_roomname, &CC->usersupp, towhere);
-                c = getroom(&QRscratch, augmented_roomname);
-                if (c == 0)
-                        strcpy(towhere, augmented_roomname);
-        }
+       /* Then try a mailbox name match */
+       if (c != 0) {
+               MailboxName(augmented_roomname, sizeof augmented_roomname,
+                           &CC->user, towhere);
+               c = getroom(&QRscratch, augmented_roomname);
+               if (c == 0)
+                       strcpy(towhere, augmented_roomname);
+       }
 
        /* If the room exists, check security/access */
-        if (c == 0) {
-                /* See if there is an existing user/room relationship */
-                ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
+       if (c == 0) {
+               /* See if there is an existing user/room relationship */
+               ra = CtdlRoomAccess(&QRscratch, &CC->user);
 
-                /* normal clients have to pass through security */
-                if (ra & UA_KNOWN) {
-                        ok = 1;
+               /* normal clients have to pass through security */
+               if (ra & UA_KNOWN) {
+                       ok = 1;
                }
        }
 
@@ -352,42 +518,101 @@ void imap_select(int num_parms, char *parms[]) {
        if (!ok) {
                cprintf("%s NO ... no such room, or access denied\r\n",
                        parms[0]);
-               IMAP->selected = 0;
                return;
        }
 
+       /* If we already had some other folder selected, auto-expunge it */
+       imap_do_expunge();
+
        /*
         * usergoto() formally takes us to the desired room, happily returning
         * the number of messages and number of new messages.
         */
-       usergoto(QRscratch.QRname, 0, &msgs, &new);
+       memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
+       usergoto(NULL, 0, 0, &msgs, &new);
        IMAP->selected = 1;
 
        if (!strcasecmp(parms[1], "EXAMINE")) {
                IMAP->readonly = 1;
-       }
-       else {
+       } else {
                IMAP->readonly = 0;
        }
 
        imap_load_msgids();
 
-       /* FIXME ... much more info needs to be supplied here */
        cprintf("* %d EXISTS\r\n", msgs);
        cprintf("* %d RECENT\r\n", new);
+
+       /* Note that \Deleted is a valid flag, but not a permanent flag,
+        * because we don't maintain its state across sessions.  Citadel
+        * automatically expunges mailboxes when they are de-selected.
+        */
+       cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
+       cprintf("* OK [PERMANENTFLAGS (\\Seen \\Answered)] "
+               "permanent flags\r\n");
+
        cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
        cprintf("%s OK [%s] %s completed\r\n",
                parms[0],
-               (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"),
-               parms[1]);
+               (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]);
+}
+
+
+
+/*
+ * does the real work for expunge
+ */
+int imap_do_expunge(void)
+{
+       int i;
+       int num_expunged = 0;
+
+       lprintf(CTDL_DEBUG, "imap_do_expunge() called\n");
+       if (IMAP->selected == 0) {
+               return (0);
+       }
+
+       if (IMAP->num_msgs > 0)
+               for (i = 0; i < IMAP->num_msgs; ++i) {
+                       if (IMAP->flags[i] & IMAP_DELETED) {
+                               CtdlDeleteMessages(CC->room.QRname,
+                                                  IMAP->msgids[i], "");
+                               ++num_expunged;
+                       }
+               }
+
+       if (num_expunged > 0) {
+               imap_rescan_msgids();
+       }
+
+       lprintf(9, "Expunged %d messages.\n", num_expunged);
+       return (num_expunged);
 }
 
 
+/*
+ * implements the EXPUNGE command syntax
+ */
+void imap_expunge(int num_parms, char *parms[])
+{
+       int num_expunged = 0;
+
+       num_expunged = imap_do_expunge();
+       cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
+}
+
 
 /*
  * implements the CLOSE command
  */
-void imap_close(int num_parms, char *parms[]) {
+void imap_close(int num_parms, char *parms[])
+{
+
+       /* Yes, we always expunge on close. */
+       if (IMAP->selected) {
+               imap_do_expunge();
+       }
+
        IMAP->selected = 0;
        IMAP->readonly = 0;
        imap_free_msgids();
@@ -395,21 +620,63 @@ void imap_close(int num_parms, char *parms[]) {
 }
 
 
+/*
+ * Implements the NAMESPACE command.
+ */
+void imap_namespace(int num_parms, char *parms[])
+{
+       int i;
+       struct floor *fl;
+       int floors = 0;
+       char buf[SIZ];
+
+       cprintf("* NAMESPACE ");
+
+       /* All personal folders are subordinate to INBOX. */
+       cprintf("((\"INBOX/\" \"/\")) ");
+
+       /* Other users' folders ... coming soon! FIXME */
+       cprintf("NIL ");
+
+       /* Show all floors as shared namespaces.  Neato! */
+       cprintf("(");
+       for (i = 0; i < MAXFLOORS; ++i) {
+               fl = cgetfloor(i);
+               if (fl->f_flags & F_INUSE) {
+                       if (floors > 0) cprintf(" ");
+                       cprintf("(");
+                       sprintf(buf, "%s/", fl->f_name);
+                       imap_strout(buf);
+                       cprintf(" \"/\")");
+                       ++floors;
+               }
+       }
+       cprintf(")");
+
+       /* Wind it up with a newline and a completion message. */
+       cprintf("\r\n");
+       cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
+}
+
 
 
 /*
  * Used by LIST and LSUB to show the floors in the listing
  */
-void imap_list_floors(char *cmd) {
+void imap_list_floors(char *cmd, char *pattern)
+{
        int i;
        struct floor *fl;
 
-       for (i=0; i<MAXFLOORS; ++i) {
+       for (i = 0; i < MAXFLOORS; ++i) {
                fl = cgetfloor(i);
                if (fl->f_flags & F_INUSE) {
-                       cprintf("* %s (\\NoSelect) \"|\" ", cmd);
-                       imap_strout(fl->f_name);
-                       cprintf("\r\n");
+                       if (imap_mailbox_matches_pattern
+                           (pattern, fl->f_name)) {
+                               cprintf("* %s (\\NoSelect) \"/\" ", cmd);
+                               imap_strout(fl->f_name);
+                               cprintf("\r\n");
+                       }
                }
        }
 }
@@ -422,29 +689,48 @@ void imap_list_floors(char *cmd) {
  * IMAP "subscribed folder" is equivocated to Citadel "known rooms."  This
  * may or may not be the desired behavior in the future.
  */
-void imap_lsub_listroom(struct quickroom *qrbuf, void *data) {
+void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data)
+{
        char buf[SIZ];
        int ra;
+       char *pattern;
+
+       pattern = (char *) data;
 
        /* Only list rooms to which the user has access!! */
-       ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
+       ra = CtdlRoomAccess(qrbuf, &CC->user);
        if (ra & UA_KNOWN) {
                imap_mailboxname(buf, sizeof buf, qrbuf);
-               cprintf("* LSUB () \"|\" ");
-               imap_strout(buf);
-               cprintf("\r\n");
+               if (imap_mailbox_matches_pattern(pattern, buf)) {
+                       cprintf("* LSUB () \"/\" ");
+                       imap_strout(buf);
+                       cprintf("\r\n");
+               }
        }
 }
 
 
 /*
  * Implements the LSUB command
- *
- * FIXME: Handle wildcards, please.
  */
-void imap_lsub(int num_parms, char *parms[]) {
-       imap_list_floors("LSUB");
-       ForEachRoom(imap_lsub_listroom, NULL);
+void imap_lsub(int num_parms, char *parms[])
+{
+       char pattern[SIZ];
+       if (num_parms < 4) {
+               cprintf("%s BAD arguments invalid\r\n", parms[0]);
+               return;
+       }
+       snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
+
+       if (strlen(parms[3]) == 0) {
+               cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
+       }
+
+       else {
+               imap_list_floors("LSUB", pattern);
+               ForEachRoom(imap_lsub_listroom, pattern);
+       }
+
        cprintf("%s OK LSUB completed\r\n", parms[0]);
 }
 
@@ -453,30 +739,49 @@ void imap_lsub(int num_parms, char *parms[]) {
 /*
  * Back end for imap_list()
  */
-void imap_list_listroom(struct quickroom *qrbuf, void *data) {
+void imap_list_listroom(struct ctdlroom *qrbuf, void *data)
+{
        char buf[SIZ];
        int ra;
+       char *pattern;
+
+       pattern = (char *) data;
 
        /* Only list rooms to which the user has access!! */
-       ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
-       if ( (ra & UA_KNOWN) 
-         || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
+       ra = CtdlRoomAccess(qrbuf, &CC->user);
+       if ((ra & UA_KNOWN)
+           || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
                imap_mailboxname(buf, sizeof buf, qrbuf);
-               cprintf("* LIST () \"|\" ");
-               imap_strout(buf);
-               cprintf("\r\n");
+               if (imap_mailbox_matches_pattern(pattern, buf)) {
+                       cprintf("* LIST () \"/\" ");
+                       imap_strout(buf);
+                       cprintf("\r\n");
+               }
        }
 }
 
 
 /*
  * Implements the LIST command
- *
- * FIXME: Handle wildcards, please.
  */
-void imap_list(int num_parms, char *parms[]) {
-       imap_list_floors("LIST");
-       ForEachRoom(imap_list_listroom, NULL);
+void imap_list(int num_parms, char *parms[])
+{
+       char pattern[SIZ];
+       if (num_parms < 4) {
+               cprintf("%s BAD arguments invalid\r\n", parms[0]);
+               return;
+       }
+       snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
+
+       if (strlen(parms[3]) == 0) {
+               cprintf("* LIST (\\Noselect) \"/\" \"\"\r\n");
+       }
+
+       else {
+               imap_list_floors("LIST", pattern);
+               ForEachRoom(imap_list_listroom, pattern);
+       }
+
        cprintf("%s OK LIST completed\r\n", parms[0]);
 }
 
@@ -486,90 +791,108 @@ void imap_list(int num_parms, char *parms[]) {
  * Implements the CREATE command
  *
  */
-void imap_create(int num_parms, char *parms[]) {
+void imap_create(int num_parms, char *parms[])
+{
        int ret;
        char roomname[ROOMNAMELEN];
        int floornum;
        int flags;
        int newroomtype;
 
+       if (strchr(parms[2], '\\') != NULL) {
+               cprintf("%s NO Invalid character in folder name\r\n",
+                       parms[0]);
+               lprintf(CTDL_DEBUG, "invalid character in folder name\n");
+               return;
+       }
+
        ret = imap_roomname(roomname, sizeof roomname, parms[2]);
        if (ret < 0) {
                cprintf("%s NO Invalid mailbox name or location\r\n",
                        parms[0]);
+               lprintf(CTDL_DEBUG, "invalid mailbox name or location\n");
                return;
        }
-       floornum = ( ret & 0x00ff );    /* lower 8 bits = floor number */
-       flags =    ( ret & 0xff00 );    /* upper 8 bits = flags        */
+       floornum = (ret & 0x00ff);      /* lower 8 bits = floor number */
+       flags = (ret & 0xff00); /* upper 8 bits = flags        */
 
        if (flags & IR_MAILBOX) {
-               newroomtype = 4;        /* private mailbox */
+               if (strncasecmp(parms[2], "INBOX/", 6)) {
+                       cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
+                       lprintf(CTDL_DEBUG, "not subordinate to inbox\n");
+                       return;
+               }
        }
-       else {
+
+       if (flags & IR_MAILBOX) {
+               newroomtype = 4;        /* private mailbox */
+       } else {
                newroomtype = 0;        /* public folder */
        }
 
-       lprintf(7, "Create new room <%s> on floor <%d> with type <%d>\n",
+       lprintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
                roomname, floornum, newroomtype);
 
-       ret = create_room(roomname, newroomtype, "", floornum, 1);
+       ret = create_room(roomname, newroomtype, "", floornum, 1, 0);
        if (ret == 0) {
-               cprintf("%s NO Mailbox already exists, or create failed\r\n",
-                       parms[0]);
-       }
-       else {
+               cprintf
+                   ("%s NO Mailbox already exists, or create failed\r\n",
+                    parms[0]);
+       else {
                cprintf("%s OK CREATE completed\r\n", parms[0]);
        }
+       lprintf(CTDL_DEBUG, "imap_create() completed\n");
 }
 
 
 /*
  * Locate a room by its IMAP folder name, and check access to it
  */
-int imap_grabroom(char *returned_roomname, char *foldername) {
+int imap_grabroom(char *returned_roomname, char *foldername)
+{
        int ret;
        char augmented_roomname[ROOMNAMELEN];
        char roomname[ROOMNAMELEN];
        int c;
-       struct quickroom QRscratch;
+       struct ctdlroom QRscratch;
        int ra;
        int ok = 0;
 
        ret = imap_roomname(roomname, sizeof roomname, foldername);
        if (ret < 0) {
-               return(1);
+               return (1);
        }
 
-        /* First try a regular match */
-        c = getroom(&QRscratch, roomname);
+       /* First try a regular match */
+       c = getroom(&QRscratch, roomname);
 
-        /* Then try a mailbox name match */
-        if (c != 0) {
-                MailboxName(augmented_roomname, &CC->usersupp, roomname);
-                c = getroom(&QRscratch, augmented_roomname);
-                if (c == 0)
-                        strcpy(roomname, augmented_roomname);
-        }
+       /* Then try a mailbox name match */
+       if (c != 0) {
+               MailboxName(augmented_roomname, sizeof augmented_roomname,
+                           &CC->user, roomname);
+               c = getroom(&QRscratch, augmented_roomname);
+               if (c == 0)
+                       strcpy(roomname, augmented_roomname);
+       }
 
        /* If the room exists, check security/access */
-        if (c == 0) {
-                /* See if there is an existing user/room relationship */
-                ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
+       if (c == 0) {
+               /* See if there is an existing user/room relationship */
+               ra = CtdlRoomAccess(&QRscratch, &CC->user);
 
-                /* normal clients have to pass through security */
-                if (ra & UA_KNOWN) {
-                        ok = 1;
+               /* normal clients have to pass through security */
+               if (ra & UA_KNOWN) {
+                       ok = 1;
                }
        }
 
        /* Fail here if no such room */
        if (!ok) {
                strcpy(returned_roomname, "");
-               return(1);
-       }
-       else {
+               return (2);
+       } else {
                strcpy(returned_roomname, QRscratch.QRname);
-               return(0);
+               return (0);
        }
 }
 
@@ -578,18 +901,19 @@ int imap_grabroom(char *returned_roomname, char *foldername) {
  * Implements the STATUS command (sort of)
  *
  */
-void imap_status(int num_parms, char *parms[]) {
+void imap_status(int num_parms, char *parms[])
+{
        int ret;
        char roomname[ROOMNAMELEN];
        char buf[SIZ];
-       struct quickroom QRscratch;
        char savedroom[ROOMNAMELEN];
        int msgs, new;
 
        ret = imap_grabroom(roomname, parms[2]);
        if (ret != 0) {
-               cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
-                       parms[0]);
+               cprintf
+                   ("%s NO Invalid mailbox name or location, or access denied\r\n",
+                    parms[0]);
                return;
        }
 
@@ -599,34 +923,30 @@ void imap_status(int num_parms, char *parms[]) {
         * folder is selected, save its name so we can return there!!!!!)
         */
        if (IMAP->selected) {
-               strcpy(savedroom, CC->quickroom.QRname);
+               strcpy(savedroom, CC->room.QRname);
        }
-       usergoto(roomname, 0, &msgs, &new);
+       usergoto(roomname, 0, 0, &msgs, &new);
 
        /*
         * Tell the client what it wants to know.  In fact, tell it *more* than
         * it wants to know.  We happily IGnore the supplied status data item
         * names and simply spew all possible data items.  It's far easier to
         * code and probably saves us some processing time too.
-        *
-        * FIXME we need to implement RECENT and UNSEEN eventually...
         */
-
-       imap_mailboxname(buf, sizeof buf, &QRscratch);
+       imap_mailboxname(buf, sizeof buf, &CC->room);
        cprintf("* STATUS ");
        imap_strout(buf);
-       cprintf(" (MESSAGES %d RECENT 0 UIDNEXT %ld "
-               "UIDVALIDITY 0 UNSEEN 0)\r\n",
-               msgs,
-               CitControl.MMhighest + 1
-       );
+       cprintf(" (MESSAGES %d ", msgs);
+       cprintf("RECENT 0 ");   /* FIXME we need to implement this */
+       cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
+       cprintf("UNSEEN %d)\r\n", new);
 
        /*
         * If another folder is selected, go back to that room so we can resume
         * our happy day without violent explosions.
         */
        if (IMAP->selected) {
-               usergoto(savedroom, 0, &msgs, &new);
+               usergoto(savedroom, 0, 0, &msgs, &new);
        }
 
        /*
@@ -637,30 +957,303 @@ void imap_status(int num_parms, char *parms[]) {
 
 
 
+/*
+ * Implements the SUBSCRIBE command
+ *
+ */
+void imap_subscribe(int num_parms, char *parms[])
+{
+       int ret;
+       char roomname[ROOMNAMELEN];
+       char savedroom[ROOMNAMELEN];
+       int msgs, new;
+
+       ret = imap_grabroom(roomname, parms[2]);
+       if (ret != 0) {
+               cprintf
+                   ("%s NO Invalid mailbox name or location, or access denied\r\n",
+                    parms[0]);
+               return;
+       }
+
+       /*
+        * usergoto() formally takes us to the desired room, which has the side
+        * effect of marking the room as not-zapped ... exactly the effect
+        * we're looking for.
+        */
+       if (IMAP->selected) {
+               strcpy(savedroom, CC->room.QRname);
+       }
+       usergoto(roomname, 0, 0, &msgs, &new);
+
+       /*
+        * If another folder is selected, go back to that room so we can resume
+        * our happy day without violent explosions.
+        */
+       if (IMAP->selected) {
+               usergoto(savedroom, 0, 0, &msgs, &new);
+       }
+
+       cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
+}
+
+
+/*
+ * Implements the UNSUBSCRIBE command
+ *
+ */
+void imap_unsubscribe(int num_parms, char *parms[])
+{
+       int ret;
+       char roomname[ROOMNAMELEN];
+       char savedroom[ROOMNAMELEN];
+       int msgs, new;
+
+       ret = imap_grabroom(roomname, parms[2]);
+       if (ret != 0) {
+               cprintf
+                   ("%s NO Invalid mailbox name or location, or access denied\r\n",
+                    parms[0]);
+               return;
+       }
+
+       /*
+        * usergoto() formally takes us to the desired room.
+        */
+       if (IMAP->selected) {
+               strcpy(savedroom, CC->room.QRname);
+       }
+       usergoto(roomname, 0, 0, &msgs, &new);
+
+       /* 
+        * Now make the API call to zap the room
+        */
+       if (CtdlForgetThisRoom() == 0) {
+               cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
+       } else {
+               cprintf
+                   ("%s NO You may not unsubscribe from this folder.\r\n",
+                    parms[0]);
+       }
+
+       /*
+        * If another folder is selected, go back to that room so we can resume
+        * our happy day without violent explosions.
+        */
+       if (IMAP->selected) {
+               usergoto(savedroom, 0, 0, &msgs, &new);
+       }
+}
+
+
+
+/*
+ * Implements the DELETE command
+ *
+ */
+void imap_delete(int num_parms, char *parms[])
+{
+       int ret;
+       char roomname[ROOMNAMELEN];
+       char savedroom[ROOMNAMELEN];
+       int msgs, new;
+
+       ret = imap_grabroom(roomname, parms[2]);
+       if (ret != 0) {
+               cprintf("%s NO Invalid mailbox name, or access denied\r\n",
+                       parms[0]);
+               return;
+       }
+
+       /*
+        * usergoto() formally takes us to the desired room, happily returning
+        * the number of messages and number of new messages.  (If another
+        * folder is selected, save its name so we can return there!!!!!)
+        */
+       if (IMAP->selected) {
+               strcpy(savedroom, CC->room.QRname);
+       }
+       usergoto(roomname, 0, 0, &msgs, &new);
+
+       /*
+        * Now delete the room.
+        */
+       if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
+               cprintf("%s OK DELETE completed\r\n", parms[0]);
+               delete_room(&CC->room);
+       } else {
+               cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
+       }
+
+       /*
+        * If another folder is selected, go back to that room so we can resume
+        * our happy day without violent explosions.
+        */
+       if (IMAP->selected) {
+               usergoto(savedroom, 0, 0, &msgs, &new);
+       }
+}
+
+
+/*
+ * Back end function for imap_rename()
+ */
+void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
+{
+       char foldername[SIZ];
+       char newfoldername[SIZ];
+       char newroomname[ROOMNAMELEN];
+       int newfloor = 0;
+       struct irl *irlp = NULL;        /* scratch pointer */
+       struct irlparms *irlparms;
+
+       irlparms = (struct irlparms *) data;
+       imap_mailboxname(foldername, sizeof foldername, qrbuf);
+
+       /* Rename subfolders */
+       if ((!strncasecmp(foldername, irlparms->oldname,
+                         strlen(irlparms->oldname))
+            && (foldername[strlen(irlparms->oldname)] == '/'))) {
+
+               sprintf(newfoldername, "%s/%s",
+                       irlparms->newname,
+                       &foldername[strlen(irlparms->oldname) + 1]
+                   );
+
+               newfloor = imap_roomname(newroomname,
+                                        sizeof newroomname,
+                                        newfoldername) & 0xFF;
+
+               irlp = (struct irl *) malloc(sizeof(struct irl));
+               strcpy(irlp->irl_newroom, newroomname);
+               strcpy(irlp->irl_oldroom, qrbuf->QRname);
+               irlp->irl_newfloor = newfloor;
+               irlp->next = *(irlparms->irl);
+               *(irlparms->irl) = irlp;
+       }
+}
+
+
+/*
+ * Implements the RENAME command
+ *
+ */
+void imap_rename(int num_parms, char *parms[])
+{
+       char old_room[ROOMNAMELEN];
+       char new_room[ROOMNAMELEN];
+       int oldr, newr;
+       int new_floor;
+       int r;
+       struct irl *irl = NULL; /* the list */
+       struct irl *irlp = NULL;        /* scratch pointer */
+       struct irlparms irlparms;
+
+       if (strchr(parms[3], '\\') != NULL) {
+               cprintf("%s NO Invalid character in folder name\r\n",
+                       parms[0]);
+               return;
+       }
+
+       oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
+       newr = imap_roomname(new_room, sizeof new_room, parms[3]);
+       new_floor = (newr & 0xFF);
+
+       r = CtdlRenameRoom(old_room, new_room, new_floor);
+
+       if (r == crr_room_not_found) {
+               cprintf("%s NO Could not locate this folder\r\n",
+                       parms[0]);
+               return;
+       }
+       if (r == crr_already_exists) {
+               cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
+               return;
+       }
+       if (r == crr_noneditable) {
+               cprintf("%s This folder is not editable.\r\n", parms[0]);
+               return;
+       }
+       if (r == crr_invalid_floor) {
+               cprintf("%s Folder root does not exist.\r\n", parms[0]);
+               return;
+       }
+       if (r == crr_access_denied) {
+               cprintf("%s You do not have permission to edit "
+                       "this folder.\r\n", parms[0]);
+               return;
+       }
+       if (r != crr_ok) {
+               cprintf("%s NO Rename failed - undefined error %d\r\n",
+                       parms[0], r);
+               return;
+       }
+
+
+       /* If this is the INBOX, then RFC2060 says we have to just move the
+        * contents.  In a Citadel environment it's easier to rename the room
+        * (already did that) and create a new inbox.
+        */
+       if (!strcasecmp(parms[2], "INBOX")) {
+               create_room(MAILROOM, 4, "", 0, 1, 0);
+       }
+
+       /* Otherwise, do the subfolders.  Build a list of rooms to rename... */
+       else {
+               irlparms.oldname = parms[2];
+               irlparms.newname = parms[3];
+               irlparms.irl = &irl;
+               ForEachRoom(imap_rename_backend, (void *) &irlparms);
+
+               /* ... and now rename them. */
+               while (irl != NULL) {
+                       r = CtdlRenameRoom(irl->irl_oldroom,
+                                          irl->irl_newroom,
+                                          irl->irl_newfloor);
+                       if (r != crr_ok) {
+                               /* FIXME handle error returns better */
+                               lprintf(CTDL_ERR, "CtdlRenameRoom() error %d\n",
+                                       r);
+                       }
+                       irlp = irl;
+                       irl = irl->next;
+                       free(irlp);
+               }
+       }
+
+       cprintf("%s OK RENAME completed\r\n", parms[0]);
+}
+
+
+
 
 /* 
  * Main command loop for IMAP sessions.
  */
-void imap_command_loop(void) {
+void imap_command_loop(void)
+{
        char cmdbuf[SIZ];
        char *parms[SIZ];
        int num_parms;
 
        time(&CC->lastcmd);
-       memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
+       memset(cmdbuf, 0, sizeof cmdbuf);       /* Clear it, just in case */
        if (client_gets(cmdbuf) < 1) {
-               lprintf(3, "IMAP socket is broken.  Ending session.\r\n");
+               lprintf(CTDL_ERR, "IMAP socket is broken.  Ending session.\r\n");
                CC->kill_me = 1;
                return;
        }
 
-       lprintf(5, "citserver[%3d]: %s\r\n", CC->cs_pid, cmdbuf);
-       while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
+       lprintf(CTDL_INFO, "IMAP: %s\r\n", cmdbuf);
+       while (strlen(cmdbuf) < 5)
+               strcat(cmdbuf, " ");
 
 
        /* strip off l/t whitespace and CRLF */
-       if (cmdbuf[strlen(cmdbuf)-1]=='\n') cmdbuf[strlen(cmdbuf)-1]=0;
-       if (cmdbuf[strlen(cmdbuf)-1]=='\r') cmdbuf[strlen(cmdbuf)-1]=0;
+       if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
+               cmdbuf[strlen(cmdbuf) - 1] = 0;
+       if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
+               cmdbuf[strlen(cmdbuf) - 1] = 0;
        striplt(cmdbuf);
 
        /* If we're in the middle of a multi-line command, handle that */
@@ -674,7 +1267,10 @@ void imap_command_loop(void) {
        }
 
 
-       /* Ok, at this point we're in normal command mode */
+       /* Ok, at this point we're in normal command mode.  The first thing
+        * we do is print any incoming pages (yeah! we really do!)
+        */
+       imap_print_instant_messages();
 
        /*
         * Before processing the command that was just entered... if we happen
@@ -696,15 +1292,19 @@ void imap_command_loop(void) {
 
        /* The commands below may be executed in any state */
 
-       else if ( (!strcasecmp(parms[1], "NOOP"))
-          || (!strcasecmp(parms[1], "CHECK")) ) {
+       else if ((!strcasecmp(parms[1], "NOOP"))
+                || (!strcasecmp(parms[1], "CHECK"))) {
                cprintf("%s OK This command successfully did nothing.\r\n",
                        parms[0]);
        }
 
        else if (!strcasecmp(parms[1], "LOGOUT")) {
+               if (IMAP->selected) {
+                       imap_do_expunge();      /* yes, we auto-expunge */
+               }
                cprintf("* BYE %s logging out\r\n", config.c_fqdn);
-               cprintf("%s OK thank you for using Citadel IMAP\r\n", parms[0]);
+               cprintf("%s OK thank you for using Citadel IMAP\r\n",
+                       parms[0]);
                CC->kill_me = 1;
                return;
        }
@@ -720,7 +1320,11 @@ void imap_command_loop(void) {
        else if (!strcasecmp(parms[1], "CAPABILITY")) {
                imap_capability(num_parms, parms);
        }
-
+#ifdef HAVE_OPENSSL
+       else if (!strcasecmp(parms[1], "STARTTLS")) {
+               imap_starttls(num_parms, parms);
+       }
+#endif
        else if (!CC->logged_in) {
                cprintf("%s BAD Not logged in.\r\n", parms[0]);
        }
@@ -747,10 +1351,34 @@ void imap_command_loop(void) {
                imap_create(num_parms, parms);
        }
 
+       else if (!strcasecmp(parms[1], "DELETE")) {
+               imap_delete(num_parms, parms);
+       }
+
+       else if (!strcasecmp(parms[1], "RENAME")) {
+               imap_rename(num_parms, parms);
+       }
+
        else if (!strcasecmp(parms[1], "STATUS")) {
                imap_status(num_parms, parms);
        }
 
+       else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
+               imap_subscribe(num_parms, parms);
+       }
+
+       else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
+               imap_unsubscribe(num_parms, parms);
+       }
+
+       else if (!strcasecmp(parms[1], "APPEND")) {
+               imap_append(num_parms, parms);
+       }
+
+       else if (!strcasecmp(parms[1], "NAMESPACE")) {
+               imap_namespace(num_parms, parms);
+       }
+
        else if (IMAP->selected == 0) {
                cprintf("%s BAD no folder selected\r\n", parms[0]);
        }
@@ -761,8 +1389,8 @@ void imap_command_loop(void) {
                imap_fetch(num_parms, parms);
        }
 
-       else if ( (!strcasecmp(parms[1], "UID"))
-               && (!strcasecmp(parms[2], "FETCH")) ) {
+       else if ((!strcasecmp(parms[1], "UID"))
+                && (!strcasecmp(parms[2], "FETCH"))) {
                imap_uidfetch(num_parms, parms);
        }
 
@@ -770,8 +1398,8 @@ void imap_command_loop(void) {
                imap_search(num_parms, parms);
        }
 
-       else if ( (!strcasecmp(parms[1], "UID"))
-               && (!strcasecmp(parms[2], "SEARCH")) ) {
+       else if ((!strcasecmp(parms[1], "UID"))
+                && (!strcasecmp(parms[2], "SEARCH"))) {
                imap_uidsearch(num_parms, parms);
        }
 
@@ -779,8 +1407,8 @@ void imap_command_loop(void) {
                imap_store(num_parms, parms);
        }
 
-       else if ( (!strcasecmp(parms[1], "UID"))
-               && (!strcasecmp(parms[2], "STORE")) ) {
+       else if ((!strcasecmp(parms[1], "UID"))
+                && (!strcasecmp(parms[2], "STORE"))) {
                imap_uidstore(num_parms, parms);
        }
 
@@ -788,11 +1416,15 @@ void imap_command_loop(void) {
                imap_copy(num_parms, parms);
        }
 
-       else if ( (!strcasecmp(parms[1], "UID"))
-               && (!strcasecmp(parms[2], "COPY")) ) {
+       else if ((!strcasecmp(parms[1], "UID"))
+                && (!strcasecmp(parms[2], "COPY"))) {
                imap_uidcopy(num_parms, parms);
        }
 
+       else if (!strcasecmp(parms[1], "EXPUNGE")) {
+               imap_expunge(num_parms, parms);
+       }
+
        else if (!strcasecmp(parms[1], "CLOSE")) {
                imap_close(num_parms, parms);
        }
@@ -805,21 +1437,19 @@ void imap_command_loop(void) {
                cprintf("%s BAD command unrecognized\r\n", parms[0]);
        }
 
+       /* If the client transmitted a message we can free it now */
+       imap_free_transmitted_message();
 }
 
 
 
 /*
- * This function is called by dynloader.c to register the IMAP module
- * with the Citadel server.
+ * This function is called to register the IMAP extension with Citadel.
  */
-char *Dynamic_Module_Init(void)
+char *serv_imap_init(void)
 {
-       SYM_IMAP = CtdlGetDynamicSymbol();
        CtdlRegisterServiceHook(config.c_imap_port,
-                               NULL,
-                               imap_greeting,
-                               imap_command_loop);
+                               NULL, imap_greeting, imap_command_loop, NULL);
        CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
        return "$Id$";
 }