* Got some more parsing in there
[citadel.git] / citadel / msgbase.c
index 849a9cf7568e4c9f2f7ae261095e406f89f2b3bf..61488f1faf6a7fd178874e0f29a88cf302d0d2e4 100644 (file)
@@ -8,9 +8,6 @@
 #include <ctype.h>
 #include <string.h>
 #include <syslog.h>
-#ifdef HAVE_PTHREAD_H
-#include <pthread.h>
-#endif
 #include <limits.h>
 #include "citadel.h"
 #include "server.h"
 #include "dynloader.h"
 #include "tools.h"
 #include "mime_parser.h"
+#include "html.h"
 
 #define desired_section ((char *)CtdlGetUserData(SYM_DESIRED_SECTION))
+#define ma ((struct ma_info *)CtdlGetUserData(SYM_MA_INFO))
+#define msg_repl ((struct repl *)CtdlGetUserData(SYM_REPL))
 
 extern struct config config;
 
+char *msgkeys[] = {
+       "", "", "", "", "", "", "", "", 
+       "", "", "", "", "", "", "", "", 
+       "", "", "", "", "", "", "", "", 
+       "", "", "", "", "", "", "", "", 
+       "", "", "", "", "", "", "", "", 
+       "", "", "", "", "", "", "", "", 
+       "", "", "", "", "", "", "", "", 
+       "", "", "", "", "", "", "", "", 
+       "", 
+       "from",
+       "", "", "",
+       "exti",
+       "", "", 
+       "hnod",
+       "msgn",
+       "", "", "",
+       "text",
+       "node",
+       "room",
+       "path",
+       "",
+       "rcpt",
+       "spec",
+       "time",
+       "subj",
+       "",
+       "",
+       "",
+       "",
+       ""
+};
 
 /*
  * This function is self explanatory.
@@ -66,8 +98,6 @@ int alias(char *name)
        int a, b;
        char aaa[300], bbb[300];
 
-       lprintf(9, "alias() called for <%s>\n", name);
-
        remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
 
        fp = fopen("network/mail.aliases", "r");
@@ -182,12 +212,45 @@ void simple_listing(long msgnum)
 }
 
 
+
+/* Determine if a given message matches the fields in a message template.
+ * Return 0 for a successful match.
+ */
+int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
+       int i;
+
+       /* If there aren't any fields in the template, all messages will
+        * match.
+        */
+       if (template == NULL) return(0);
+
+       /* Null messages are bogus. */
+       if (msg == NULL) return(1);
+
+       for (i='A'; i<='Z'; ++i) {
+               if (template->cm_fields[i] != NULL) {
+                       if (msg->cm_fields[i] == NULL) {
+                               return 1;
+                       }
+                       if (strcasecmp(msg->cm_fields[i],
+                               template->cm_fields[i])) return 1;
+               }
+       }
+
+       /* All compares succeeded: we have a match! */
+       return 0;
+}
+
+
+
+
 /*
  * API function to perform an operation for each qualifying message in the
  * current room.
  */
 void CtdlForEachMessage(int mode, long ref,
                        char *content_type,
+                       struct CtdlMessage *compare,
                        void (*CallBack) (long msgnum))
 {
 
@@ -198,6 +261,7 @@ void CtdlForEachMessage(int mode, long ref,
        int num_msgs = 0;
        long thismsg;
        struct SuppMsgInfo smi;
+       struct CtdlMessage *msg;
 
        /* Learn about the user and room in question */
        get_mm();
@@ -230,6 +294,24 @@ void CtdlForEachMessage(int mode, long ref,
                                }
 
        num_msgs = sort_msglist(msglist, num_msgs);
+
+       /* If a template was supplied, filter out the messages which
+        * don't match.  (This could induce some delays!)
+        */
+       if (num_msgs > 0) {
+               if (compare != NULL) {
+                       for (a = 0; a < num_msgs; ++a) {
+                               msg = CtdlFetchMessage(msglist[a]);
+                               if (msg != NULL) {
+                                       if (CtdlMsgCmp(msg, compare)) {
+                                               msglist[a] = 0L;
+                                       }
+                                       CtdlFreeMessage(msg);
+                               }
+                       }
+               }
+       }
+
        
        /*
         * Now iterate through the message list, according to the
@@ -238,7 +320,6 @@ void CtdlForEachMessage(int mode, long ref,
        if (num_msgs > 0)
                for (a = 0; a < num_msgs; ++a) {
                        thismsg = msglist[a];
-                       lprintf(9, "Iterating through <%ld>\n", thismsg);
                        if ((thismsg > 0)
                            && (
 
@@ -252,7 +333,6 @@ void CtdlForEachMessage(int mode, long ref,
                                || ((mode == MSGS_GT) && (thismsg > ref))
                            )
                            ) {
-                               lprintf(9, "Issuing callback for <%ld>\n", thismsg);
                                CallBack(thismsg);
                        }
                }
@@ -269,10 +349,17 @@ void cmd_msgs(char *cmdbuf)
 {
        int mode = 0;
        char which[256];
+       char buf[256];
+       char tfield[256];
+       char tvalue[256];
        int cm_ref = 0;
+       int i;
+       int with_template = 0;
+       struct CtdlMessage *template = NULL;
 
        extract(which, cmdbuf, 0);
        cm_ref = extract_int(cmdbuf, 1);
+       with_template = extract_int(cmdbuf, 2);
 
        mode = MSGS_ALL;
        strcat(which, "   ");
@@ -291,8 +378,30 @@ void cmd_msgs(char *cmdbuf)
                cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
                return;
        }
-       cprintf("%d Message list...\n", LISTING_FOLLOWS);
-       CtdlForEachMessage(mode, cm_ref, NULL, simple_listing);
+
+       if (with_template) {
+               cprintf("%d Send template then receive message list\n",
+                       START_CHAT_MODE);
+               template = (struct CtdlMessage *)
+                       mallok(sizeof(struct CtdlMessage));
+               memset(template, 0, sizeof(struct CtdlMessage));
+               while(client_gets(buf), strcmp(buf,"000")) {
+                       extract(tfield, buf, 0);
+                       extract(tvalue, buf, 1);
+                       for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
+                               if (!strcasecmp(tfield, msgkeys[i])) {
+                                       template->cm_fields[i] =
+                                               strdoop(tvalue);
+                               }
+                       }
+               }
+       }
+       else {
+               cprintf("%d Message list...\n", LISTING_FOLLOWS);
+       }
+
+       CtdlForEachMessage(mode, cm_ref, NULL, template, simple_listing);
+       if (template != NULL) CtdlFreeMessage(template);
        cprintf("000\n");
 }
 
@@ -357,7 +466,7 @@ void memfmout(int width, char *mptr, char subst)
        strcpy(buffer, "");
        c = 1;                  /* c is the current pos */
 
-      FMTA:if (subst) {
+FMTA:  if (subst) {
                while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
                        ch = *mptr++;
                        buffer[strlen(buffer) + 1] = 0;
@@ -370,8 +479,9 @@ void memfmout(int width, char *mptr, char subst)
                buffer[strlen(buffer) + 1] = 0;
                a = buffer[0];
                strcpy(buffer, &buffer[1]);
-       } else
+       } else {
                ch = *mptr++;
+       }
 
        old = real;
        real = ch;
@@ -416,7 +526,7 @@ void memfmout(int width, char *mptr, char subst)
        }
        goto FMTA;
 
-      FMTEND:cprintf("%s\n", aaa);
+FMTEND:        cprintf("%s\n", aaa);
 }
 
 
@@ -439,10 +549,34 @@ void list_this_part(char *name, char *filename, char *partnum, char *disp,
 void fixed_output(char *name, char *filename, char *partnum, char *disp,
                  void *content, char *cbtype, size_t length)
 {
+       char *ptr;
+
+       if (!strcasecmp(cbtype, "multipart/alternative")) {
+               strcpy(ma->prefix, partnum);
+               strcat(ma->prefix, ".");
+               ma->is_ma = 1;
+               ma->did_print = 0;
+               return;
+       }
+
+       if ( (!strncasecmp(partnum, ma->prefix, strlen(ma->prefix)))
+          && (ma->is_ma == 1) 
+          && (ma->did_print == 1) ) {
+               lprintf(9, "Skipping part %s (%s)\n", partnum, cbtype);
+               return;
+       }
+
+       ma->did_print = 1;
 
        if (!strcasecmp(cbtype, "text/plain")) {
                client_write(content, length);
-       } else {
+       }
+       else if (!strcasecmp(cbtype, "text/html")) {
+               ptr = html_to_ascii(content, 80, 0);
+               client_write(ptr, strlen(ptr));
+               phree(ptr);
+       }
+       else if (strncasecmp(cbtype, "multipart/", 10)) {
                cprintf("Part %s: %s (%s) (%d bytes)\n",
                        partnum, filename, cbtype, length);
        }
@@ -479,7 +613,7 @@ void mime_download(char *name, char *filename, char *partnum, char *disp,
 
 /*
  * Load a message from disk into memory.
- * (This will replace a big piece of output_message() eventually)
+ * This is used by output_message() and other fetch functions.
  *
  * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
  *       using the CtdlMessageFree() function.
@@ -493,10 +627,8 @@ struct CtdlMessage *CtdlFetchMessage(long msgnum)
        CIT_UBYTE field_header;
        size_t field_length;
 
-
        dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
        if (dmsgtext == NULL) {
-               lprintf(9, "CtdlFetchMessage(%ld) failed.\n");
                return NULL;
        }
        mptr = dmsgtext->ptr;
@@ -537,9 +669,36 @@ struct CtdlMessage *CtdlFetchMessage(long msgnum)
        } while ((field_length > 0) && (field_header != 'M'));
 
        cdb_free(dmsgtext);
+
+       /* Always make sure there's something in the msg text field */
+       if (ret->cm_fields['M'] == NULL)
+               ret->cm_fields['M'] = strdoop("<no text>\n");
+
+       /* Perform "before read" hooks (aborting if any return nonzero) */
+       if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
+               CtdlFreeMessage(ret);
+               return NULL;
+       }
+
        return (ret);
 }
 
+
+/*
+ * Returns 1 if the supplied pointer points to a valid Citadel message.
+ * If the pointer is NULL or the magic number check fails, returns 0.
+ */
+int is_valid_message(struct CtdlMessage *msg) {
+       if (msg == NULL)
+               return 0;
+       if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
+               lprintf(3, "is_valid_message() -- self-check failed\n");
+               return 0;
+       }
+       return 1;
+}
+
+
 /*
  * 'Destructor' for struct CtdlMessage
  */
@@ -547,16 +706,13 @@ void CtdlFreeMessage(struct CtdlMessage *msg)
 {
        int i;
 
-       if (msg == NULL)
-               return;
-       if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
-               lprintf(3, "CtdlFreeMessage() -- self-check failed\n");
-               return;
-       }
+       if (is_valid_message(msg) == 0) return;
+
        for (i = 0; i < 256; ++i)
                if (msg->cm_fields[i] != NULL)
                        phree(msg->cm_fields[i]);
 
+       msg->cm_magic = 0;      /* just in case */
        phree(msg);
 }
 
@@ -569,10 +725,12 @@ void CtdlFreeMessage(struct CtdlMessage *msg)
 void output_message(char *msgid, int mode, int headers_only)
 {
        long msg_num;
-       int a, i;
+       int a, i, k;
        char buf[1024];
        time_t xtime;
        CIT_UBYTE ch;
+       char allkeys[256];
+       char display_name[256];
 
        struct CtdlMessage *TheMessage = NULL;
 
@@ -587,11 +745,13 @@ void output_message(char *msgid, int mode, int headers_only)
        /*                                       */
 
        msg_num = atol(msgid);
+       safestrncpy(mid, msgid, sizeof mid);
 
        if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
                cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
                return;
        }
+
        /* FIX ... small security issue
         * We need to check to make sure the requested message is actually
         * in the current room, and set msg_ok to 1 only if it is.  This
@@ -610,7 +770,7 @@ void output_message(char *msgid, int mode, int headers_only)
         */
        TheMessage = CtdlFetchMessage(msg_num);
        if (TheMessage == NULL) {
-               cprintf("%d Can't locate message %ld on disk\n", ERROR, msg_num);
+               cprintf("%d Can't locate msg %ld on disk\n", ERROR, msg_num);
                return;
        }
 
@@ -638,60 +798,69 @@ void output_message(char *msgid, int mode, int headers_only)
                CtdlFreeMessage(TheMessage);
                return;
        }
+
        /* now for the user-mode message reading loops */
        cprintf("%d Message %ld:\n", LISTING_FOLLOWS, msg_num);
 
-       if (mode == MT_CITADEL)
-               cprintf("type=%d\n", TheMessage->cm_format_type);
+       /* Tell the client which format type we're using.  If this is a
+        * MIME message, *lie* about it and tell the user it's fixed-format.
+        */
+       if (mode == MT_CITADEL) {
+               if (TheMessage->cm_format_type == 4)
+                       cprintf("type=1\n");
+               else
+                       cprintf("type=%d\n", TheMessage->cm_format_type);
+       }
 
+       /* nhdr=yes means that we're only displaying headers, no body */
        if ((TheMessage->cm_anon_type == MES_ANON) && (mode == MT_CITADEL)) {
                cprintf("nhdr=yes\n");
        }
+
        /* begin header processing loop for Citadel message format */
 
        if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
 
-               if (TheMessage->cm_fields['P']) {
-                       cprintf("path=%s\n", TheMessage->cm_fields['P']);
-               }
-               if (TheMessage->cm_fields['I']) {
-                       cprintf("msgn=%s\n", TheMessage->cm_fields['I']);
-               }
-               if (TheMessage->cm_fields['T']) {
-                       cprintf("time=%s\n", TheMessage->cm_fields['T']);
-               }
+               strcpy(display_name, "<unknown>");
                if (TheMessage->cm_fields['A']) {
                        strcpy(buf, TheMessage->cm_fields['A']);
                        PerformUserHooks(buf, (-1L), EVT_OUTPUTMSG);
                        if (TheMessage->cm_anon_type == MES_ANON)
-                               cprintf("from=****");
+                               strcpy(display_name, "****");
                        else if (TheMessage->cm_anon_type == MES_AN2)
-                               cprintf("from=anonymous");
+                               strcpy(display_name, "anonymous");
                        else
-                               cprintf("from=%s", buf);
+                               strcpy(display_name, buf);
                        if ((is_room_aide())
                            && ((TheMessage->cm_anon_type == MES_ANON)
                             || (TheMessage->cm_anon_type == MES_AN2))) {
-                               cprintf(" [%s]", buf);
+                               sprintf(&display_name[strlen(display_name)],
+                                       " [%s]", buf);
                        }
-                       cprintf("\n");
-               }
-               if (TheMessage->cm_fields['O']) {
-                       cprintf("room=%s\n", TheMessage->cm_fields['O']);
-               }
-               if (TheMessage->cm_fields['N']) {
-                       cprintf("node=%s\n", TheMessage->cm_fields['N']);
-               }
-               if (TheMessage->cm_fields['H']) {
-                       cprintf("hnod=%s\n", TheMessage->cm_fields['H']);
-               }
-               if (TheMessage->cm_fields['R']) {
-                       cprintf("rcpt=%s\n", TheMessage->cm_fields['R']);
                }
-               if (TheMessage->cm_fields['U']) {
-                       cprintf("subj=%s\n", TheMessage->cm_fields['U']);
+
+               strcpy(allkeys, FORDER);
+               for (i=0; i<strlen(allkeys); ++i) {
+                       k = (int) allkeys[i];
+                       if (k != 'M') {
+                               if (TheMessage->cm_fields[k] != NULL) {
+                                       if (k == 'A') {
+                                               cprintf("%s=%s\n",
+                                                       msgkeys[k],
+                                                       display_name);
+                                       }
+                                       else {
+                                               cprintf("%s=%s\n",
+                                                       msgkeys[k],
+                                                       TheMessage->cm_fields[k]
+                                       );
+                                       }
+                               }
+                       }
                }
+
        }
+
        /* begin header processing loop for RFC822 transfer format */
 
        strcpy(suser, "");
@@ -733,36 +902,40 @@ void output_message(char *msgid, int mode, int headers_only)
                        }
                }
        }
+
        if (mode == MT_RFC822) {
                if (!strcasecmp(snode, NODENAME)) {
                        strcpy(snode, FQDN);
                }
                cprintf("Message-ID: <%s@%s>\n", mid, snode);
                PerformUserHooks(luser, (-1L), EVT_OUTPUTMSG);
-               cprintf("From: %s@%s (%s)\n",
-                       suser, snode, luser);
+               cprintf("From: %s@%s (%s)\n", suser, snode, luser);
                cprintf("Organization: %s\n", lnode);
        }
+
        /* end header processing loop ... at this point, we're in the text */
 
        mptr = TheMessage->cm_fields['M'];
 
-       /* do some sort of MIME output */
-       if (TheMessage->cm_format_type == 4) {
-               if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
+       /* Tell the client about the MIME parts in this message */
+       if (TheMessage->cm_format_type == 4) {  /* legacy textual dump */
+               if (mode == MT_CITADEL) {
                        mime_parser(mptr, NULL, *list_this_part);
                }
-               if (mode == MT_MIME) {  /* If MT_MIME then it's parts only */
+               else if (mode == MT_MIME) {     /* list parts only */
+                       mime_parser(mptr, NULL, *list_this_part);
                        cprintf("000\n");
                        CtdlFreeMessage(TheMessage);
                        return;
                }
        }
+
        if (headers_only) {
                cprintf("000\n");
                CtdlFreeMessage(TheMessage);
                return;
        }
+
        /* signify start of msg text */
        if (mode == MT_CITADEL)
                cprintf("text\n");
@@ -789,6 +962,7 @@ void output_message(char *msgid, int mode, int headers_only)
                if (strlen(buf) > 0)
                        cprintf("%s\n", buf);
        }
+
        /* If the message on disk is format 0 (Citadel vari-format), we
         * output using the formatter at 80 columns.  This is the final output
         * form if the transfer format is RFC822, but if the transfer format
@@ -799,14 +973,18 @@ void output_message(char *msgid, int mode, int headers_only)
        if (TheMessage->cm_format_type == 0) {
                memfmout(80, mptr, 0);
        }
+
        /* If the message on disk is format 4 (MIME), we've gotta hand it
         * off to the MIME parser.  The client has already been told that
         * this message is format 1 (fixed format), so the callback function
         * we use will display those parts as-is.
         */
        if (TheMessage->cm_format_type == 4) {
+               CtdlAllocUserData(SYM_MA_INFO, sizeof(struct ma_info));
+               memset(ma, 0, sizeof(struct ma_info));
                mime_parser(mptr, NULL, *fixed_output);
        }
+
        /* now we're done */
        cprintf("000\n");
        CtdlFreeMessage(TheMessage);
@@ -853,7 +1031,8 @@ void cmd_msg2(char *cmdbuf)
 void cmd_msg3(char *cmdbuf)
 {
        long msgnum;
-       struct cdbdata *dmsgtext;
+       struct CtdlMessage *msg;
+       struct ser_ret smr;
 
        if (CC->internal_pgm == 0) {
                cprintf("%d This command is for internal programs only.\n",
@@ -862,15 +1041,25 @@ void cmd_msg3(char *cmdbuf)
        }
 
        msgnum = extract_long(cmdbuf, 0);
+       msg = CtdlFetchMessage(msgnum);
+       if (msg == NULL) {
+               cprintf("%d Message %ld not found.\n", 
+                       ERROR, msgnum);
+               return;
+       }
 
-       dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
-       if (dmsgtext == NULL) {
-               cprintf("%d Message %ld not found\n", ERROR, msgnum);
+       serialize_message(&smr, msg);
+       CtdlFreeMessage(msg);
+
+       if (smr.len == 0) {
+               cprintf("%d Unable to serialize message\n",
+                       ERROR+INTERNAL_ERROR);
+               return;
        }
 
-       cprintf("%d %ld\n", BINARY_FOLLOWS, dmsgtext->len);
-       client_write(dmsgtext->ptr, dmsgtext->len);
-       cdb_free(dmsgtext);
+       cprintf("%d %ld\n", BINARY_FOLLOWS, smr.len);
+       client_write(smr.ser, smr.len);
+       phree(smr.ser);
 }
 
 
@@ -902,42 +1091,164 @@ void cmd_opna(char *cmdbuf)
        output_message(msgid, MT_DOWNLOAD, 0);
 }                      
 
+
+/*
+ * Save a message pointer into a specified room
+ * (Returns 0 for success, nonzero for failure)
+ * roomname may be NULL to use the current room
+ */
+int CtdlSaveMsgPointerInRoom(char *roomname, long msgid, int flags) {
+       int i;
+       char hold_rm[ROOMNAMELEN];
+        struct cdbdata *cdbfr;
+        int num_msgs;
+        long *msglist;
+        long highest_msg = 0L;
+       struct CtdlMessage *msg = NULL;
+
+       lprintf(9, "CtdlSaveMsgPointerInRoom(%s, %ld, %d)\n",
+               roomname, msgid, flags);
+
+       strcpy(hold_rm, CC->quickroom.QRname);
+
+       /* We may need to check to see if this message is real */
+       if (  (flags & SM_VERIFY_GOODNESS)
+          || (flags & SM_DO_REPL_CHECK)
+          ) {
+               msg = CtdlFetchMessage(msgid);
+               if (msg == NULL) return(ERROR + ILLEGAL_VALUE);
+       }
+
+       /* Perform replication checks if necessary */
+       if ( (flags & SM_DO_REPL_CHECK) && (msg != NULL) ) {
+
+               if (getroom(&CC->quickroom,
+                  ((roomname != NULL) ? roomname : CC->quickroom.QRname) )
+                  != 0) {
+                       lprintf(9, "No such room <%s>\n", roomname);
+                       if (msg != NULL) CtdlFreeMessage(msg);
+                       return(ERROR + ROOM_NOT_FOUND);
+               }
+
+               if (ReplicationChecks(msg) != 0) {
+                       getroom(&CC->quickroom, hold_rm);
+                       if (msg != NULL) CtdlFreeMessage(msg);
+                       lprintf(9, "Did replication, and newer exists\n");
+                       return(0);
+               }
+       }
+
+       /* Now the regular stuff */
+       if (lgetroom(&CC->quickroom,
+          ((roomname != NULL) ? roomname : CC->quickroom.QRname) )
+          != 0) {
+               lprintf(9, "No such room <%s>\n", roomname);
+               if (msg != NULL) CtdlFreeMessage(msg);
+               return(ERROR + ROOM_NOT_FOUND);
+       }
+
+        cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long));
+        if (cdbfr == NULL) {
+                msglist = NULL;
+                num_msgs = 0;
+        } else {
+                msglist = mallok(cdbfr->len);
+                if (msglist == NULL)
+                        lprintf(3, "ERROR malloc msglist!\n");
+                num_msgs = cdbfr->len / sizeof(long);
+                memcpy(msglist, cdbfr->ptr, cdbfr->len);
+                cdb_free(cdbfr);
+        }
+
+
+       /* Make sure the message doesn't already exist in this room.  It
+        * is absolutely taboo to have more than one reference to the same
+        * message in a room.
+        */
+        if (num_msgs > 0) for (i=0; i<num_msgs; ++i) {
+               if (msglist[i] == msgid) {
+                       lputroom(&CC->quickroom);       /* unlock the room */
+                       getroom(&CC->quickroom, hold_rm);
+                       if (msg != NULL) CtdlFreeMessage(msg);
+                       return(ERROR + ALREADY_EXISTS);
+               }
+       }
+
+        /* Now add the new message */
+        ++num_msgs;
+        msglist = reallok(msglist,
+                          (num_msgs * sizeof(long)));
+
+        if (msglist == NULL) {
+                lprintf(3, "ERROR: can't realloc message list!\n");
+        }
+        msglist[num_msgs - 1] = msgid;
+
+        /* Sort the message list, so all the msgid's are in order */
+        num_msgs = sort_msglist(msglist, num_msgs);
+
+        /* Determine the highest message number */
+        highest_msg = msglist[num_msgs - 1];
+
+        /* Write it back to disk. */
+        cdb_store(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long),
+                  msglist, num_msgs * sizeof(long));
+
+        /* Free up the memory we used. */
+        phree(msglist);
+
+       /* Update the highest-message pointer and unlock the room. */
+       CC->quickroom.QRhighest = highest_msg;
+       lputroom(&CC->quickroom);
+       getroom(&CC->quickroom, hold_rm);
+
+       /* Bump the reference count for this message. */
+       AdjRefCount(msgid, +1);
+
+       /* Return success. */
+       if (msg != NULL) CtdlFreeMessage(msg);
+        return (0);
+}
+
+
+
 /*
  * Message base operation to send a message to the master file
  * (returns new message number)
+ *
+ * This is the back end for CtdlSaveMsg() and should not be directly
+ * called by server-side modules.
+ *
  */
-long send_message(char *message_in_memory,
-                                                       /* pointer to buffer */
-                                                  size_t message_length,       /* length of buffer */
-                                                     int generate_id)
-{                              /* 1 to generate an I field */
-
+long send_message(struct CtdlMessage *msg,     /* pointer to buffer */
+               int generate_id,                /* generate 'I' field? */
+               FILE *save_a_copy)              /* save a copy to disk? */
+{
        long newmsgid;
-       char *actual_message;
-       size_t actual_length;
        long retval;
        char msgidbuf[32];
+        struct ser_ret smr;
 
        /* Get a new message number */
        newmsgid = get_new_message_number();
+       sprintf(msgidbuf, "%ld", newmsgid);
 
        if (generate_id) {
-               sprintf(msgidbuf, "I%ld", newmsgid);
-               actual_length = message_length + strlen(msgidbuf) + 1;
-               actual_message = mallok(actual_length);
-               memcpy(actual_message, message_in_memory, 3);
-               memcpy(&actual_message[3], msgidbuf, (strlen(msgidbuf) + 1));
-               memcpy(&actual_message[strlen(msgidbuf) + 4],
-                      &message_in_memory[3], message_length - 3);
-       } else {
-               actual_message = message_in_memory;
-               actual_length = message_length;
+               msg->cm_fields['I'] = strdoop(msgidbuf);
        }
+       
+        serialize_message(&smr, msg);
+
+        if (smr.len == 0) {
+                cprintf("%d Unable to serialize message\n",
+                        ERROR+INTERNAL_ERROR);
+                return (-1L);
+        }
 
        /* Write our little bundle of joy into the message base */
        begin_critical_section(S_MSGMAIN);
        if (cdb_store(CDB_MSGMAIN, &newmsgid, sizeof(long),
-                     actual_message, actual_length) < 0) {
+                     smr.ser, smr.len) < 0) {
                lprintf(2, "Can't store message\n");
                retval = 0L;
        } else {
@@ -945,101 +1256,202 @@ long send_message(char *message_in_memory,
        }
        end_critical_section(S_MSGMAIN);
 
-       if (generate_id) {
-               phree(actual_message);
+       /* If the caller specified that a copy should be saved to a particular
+        * file handle, do that now too.
+        */
+       if (save_a_copy != NULL) {
+               fwrite(smr.ser, smr.len, 1, save_a_copy);
        }
-       /* Finally, return the pointers */
-       return (retval);
+
+       /* Free the memory we used for the serialized message */
+        phree(smr.ser);
+
+       /* Return the *local* message ID to the caller
+        * (even if we're storing an incoming network message)
+        */
+       return(retval);
 }
 
 
 
 /*
- * this is a simple file copy routine.
+ * Serialize a struct CtdlMessage into the format used on disk and network.
+ * 
+ * This function loads up a "struct ser_ret" (defined in server.h) which
+ * contains the length of the serialized message and a pointer to the
+ * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
  */
-void copy_file(char *from, char *to)
+void serialize_message(struct ser_ret *ret,            /* return values */
+                       struct CtdlMessage *msg)        /* unserialized msg */
 {
-       FILE *ffp, *tfp;
-       int a;
+       size_t wlen;
+       int i;
+       static char *forder = FORDER;
 
-       ffp = fopen(from, "r");
-       if (ffp == NULL)
-               return;
-       tfp = fopen(to, "w");
-       if (tfp == NULL) {
-               fclose(ffp);
+       if (is_valid_message(msg) == 0) return;         /* self check */
+
+       ret->len = 3;
+       for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
+               ret->len = ret->len +
+                       strlen(msg->cm_fields[(int)forder[i]]) + 2;
+
+       lprintf(9, "calling malloc\n");
+       ret->ser = mallok(ret->len);
+       if (ret->ser == NULL) {
+               ret->len = 0;
                return;
        }
-       while (a = getc(ffp), a >= 0) {
-               putc(a, tfp);
+
+       ret->ser[0] = 0xFF;
+       ret->ser[1] = msg->cm_anon_type;
+       ret->ser[2] = msg->cm_format_type;
+       wlen = 3;
+
+       for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
+               ret->ser[wlen++] = (char)forder[i];
+               strcpy(&ret->ser[wlen], msg->cm_fields[(int)forder[i]]);
+               wlen = wlen + strlen(msg->cm_fields[(int)forder[i]]) + 1;
        }
-       fclose(ffp);
-       fclose(tfp);
+       if (ret->len != wlen) lprintf(3, "ERROR: len=%d wlen=%d\n",
+               ret->len, wlen);
+
        return;
 }
 
 
 
 /*
- * message base operation to save a message and install its pointers
+ * Back end for the ReplicationChecks() function
+ */
+void check_repl(long msgnum) {
+       struct CtdlMessage *msg;
+       time_t timestamp = (-1L);
+
+       lprintf(9, "check_repl() found message %ld\n", msgnum);
+       msg = CtdlFetchMessage(msgnum);
+       if (msg == NULL) return;
+       if (msg->cm_fields['T'] != NULL) {
+               timestamp = atol(msg->cm_fields['T']);
+       }
+       CtdlFreeMessage(msg);
+
+       if (timestamp > msg_repl->highest) {
+               msg_repl->highest = timestamp;  /* newer! */
+               lprintf(9, "newer!\n");
+               return;
+       }
+       lprintf(9, "older!\n");
+
+       /* Existing isn't newer?  Then delete the old one(s). */
+       CtdlDeleteMessages(CC->quickroom.QRname, msgnum, NULL);
+}
+
+
+/*
+ * Check to see if any messages already exist which carry the same Extended ID
+ * as this one.  
+ *
+ * If any are found:
+ * -> With older timestamps: delete them and return 0.  Message will be saved.
+ * -> With newer timestamps: return 1.  Message save will be aborted.
  */
-void save_message(char *mtmp,  /* file containing proper message */
-                 char *rec,    /* Recipient (if mail) */
-                 char *force,  /* if non-zero length, force a room */
-                 int mailtype, /* local or remote type, see citadel.h */
-                 int generate_id)
-{                              /* set to 1 to generate an 'I' field */
+int ReplicationChecks(struct CtdlMessage *msg) {
+       struct CtdlMessage *template;
+       int abort_this = 0;
+
+       lprintf(9, "ReplicationChecks() started\n");
+       /* No extended id?  Don't do anything. */
+       if (msg->cm_fields['E'] == NULL) return 0;
+       if (strlen(msg->cm_fields['E']) == 0) return 0;
+       lprintf(9, "Extended ID: <%s>\n", msg->cm_fields['E']);
+
+       CtdlAllocUserData(SYM_REPL, sizeof(struct repl));
+       strcpy(msg_repl->extended_id, msg->cm_fields['E']);
+       msg_repl->highest = atol(msg->cm_fields['T']);
+
+       template = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
+       memset(template, 0, sizeof(struct CtdlMessage));
+       template->cm_fields['E'] = strdoop(msg->cm_fields['E']);
+
+       CtdlForEachMessage(MSGS_ALL, 0L, NULL, template, check_repl);
+
+       /* If a newer message exists with the same Extended ID, abort
+        * this save.
+        */
+       if (msg_repl->highest > atol(msg->cm_fields['T']) ) {
+               abort_this = 1;
+               }
+
+       CtdlFreeMessage(template);
+       lprintf(9, "ReplicationChecks() returning %d\n", abort_this);
+       return(abort_this);
+}
+
+
+
+
+/*
+ * Save a message to disk
+ */
+void CtdlSaveMsg(struct CtdlMessage *msg,      /* message to save */
+               char *rec,                      /* Recipient (mail) */
+               char *force,                    /* force a particular room? */
+               int mailtype,                   /* local or remote type */
+               int generate_id)                /* 1 = generate 'I' field */
+{
        char aaa[100];
        char hold_rm[ROOMNAMELEN];
        char actual_rm[ROOMNAMELEN];
        char force_room[ROOMNAMELEN];
-       char content_type[256]; /* We have to learn this */
-       char ch, rch;
+       char content_type[256];                 /* We have to learn this */
        char recipient[256];
        long newmsgid;
-       char *message_in_memory;
        char *mptr;
-       struct stat statbuf;
-       size_t templen;
-       FILE *fp;
        struct usersupp userbuf;
        int a;
-       static int seqnum = 0;
-       int successful_local_recipients = 0;
-       struct quickroom qtemp;
        struct SuppMsgInfo smi;
+       FILE *network_fp = NULL;
+       static int seqnum = 1;
+
+       lprintf(9, "CtdlSaveMsg() called\n");
+       if (is_valid_message(msg) == 0) return;         /* self check */
+
+       /* If this message has no timestamp, we take the liberty of
+        * giving it one, right now.
+        */
+       if (msg->cm_fields['T'] == NULL) {
+               sprintf(aaa, "%ld", time(NULL));
+               msg->cm_fields['T'] = strdoop(aaa);
+       }
 
-       lprintf(9, "save_message(%s,%s,%s,%d,%d)\n",
-               mtmp, rec, force, mailtype, generate_id);
+       lprintf(9, "checkpoint 1      \n");
+       /* If this message has no path, we generate one.
+        */
+       if (msg->cm_fields['A'] == NULL) {
+               msg->cm_fields['A'] = strdoop("unknown user");
+       }
+       if (msg->cm_fields['P'] == NULL) {
+               msg->cm_fields['P'] = strdoop(msg->cm_fields['A']);
+               for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
+                       if (isspace(msg->cm_fields['P'][a])) {
+                               msg->cm_fields['P'][a] = ' ';
+                       }
+               }
+       }
 
        strcpy(force_room, force);
 
+       lprintf(9, "checkpoint 2      \n");
        /* Strip non-printable characters out of the recipient name */
        strcpy(recipient, rec);
        for (a = 0; a < strlen(recipient); ++a)
                if (!isprint(recipient[a]))
                        strcpy(&recipient[a], &recipient[a + 1]);
 
-       /* Measure the message */
-       stat(mtmp, &statbuf);
-       templen = statbuf.st_size;
-
-       /* Now read it into memory */
-       message_in_memory = (char *) mallok(templen);
-       if (message_in_memory == NULL) {
-               lprintf(2, "Can't allocate memory to save message!\n");
-               return;
-       }
-       fp = fopen(mtmp, "rb");
-       fread(message_in_memory, templen, 1, fp);
-       fclose(fp);
-
        /* Learn about what's inside, because it's what's inside that counts */
-       mptr = message_in_memory;
-       ++mptr;                 /* advance past 0xFF header */
-       ++mptr;                 /* advance past anon flag */
-       ch = *mptr++;
-       switch (ch) {
+
+       lprintf(9, "checkpoint 3      \n");
+       switch (msg->cm_format_type) {
        case 0:
                strcpy(content_type, "text/x-citadel-variformat");
                break;
@@ -1049,17 +1461,12 @@ void save_message(char *mtmp,   /* file containing proper message */
        case 4:
                strcpy(content_type, "text/plain");
                /* advance past header fields */
-               while (ch = *mptr++, (ch != 'M' && ch != 0)) {
-                       do {
-                               rch = *mptr++;
-                       } while (rch > 0);
-               }
+               mptr = msg->cm_fields['M'];
                a = strlen(mptr);
                while (--a) {
                        if (!strncasecmp(mptr, "Content-type: ", 14)) {
                                safestrncpy(content_type, mptr,
                                            sizeof(content_type));
-                               lprintf(9, "%s\n", content_type);
                                strcpy(content_type, &content_type[14]);
                                for (a = 0; a < strlen(content_type); ++a)
                                        if ((content_type[a] == ';')
@@ -1072,144 +1479,225 @@ void save_message(char *mtmp, /* file containing proper message */
                        ++mptr;
                }
        }
-       lprintf(9, "Content type is <%s>\n", content_type);
-
-       /* Save it to disk */
-       newmsgid = send_message(message_in_memory, templen, generate_id);
-       phree(message_in_memory);
-       if (newmsgid <= 0L)
-               return;
 
+       lprintf(9, "checkpoint 4      \n");
+       /* Goto the correct room */
+       strcpy(hold_rm, CC->quickroom.QRname);
        strcpy(actual_rm, CC->quickroom.QRname);
-       strcpy(hold_rm, "");
 
-       /* If this is being done by the networker delivering a private
-        * message, we want to BYPASS saving the sender's copy (because there
-        * is no local sender; it would otherwise go to the Trashcan).
-        */
-       if ((!CC->internal_pgm) || (strlen(recipient) == 0)) {
-               /* If the user is a twit, move to the twit room for posting */
-               if (TWITDETECT)
-                       if (CC->usersupp.axlevel == 2) {
-                               strcpy(hold_rm, actual_rm);
-                               strcpy(actual_rm, config.c_twitroom);
-                       }
-               /* ...or if this message is destined for Aide> then go there. */
-               lprintf(9, "actual room forcing loop\n");
-               if (strlen(force_room) > 0) {
+       lprintf(9, "checkpoint 5      \n");
+       /* If the user is a twit, move to the twit room for posting */
+       if ( (CC->logged_in) && (TWITDETECT) ) {
+               if (CC->usersupp.axlevel == 2) {
                        strcpy(hold_rm, actual_rm);
-                       strcpy(actual_rm, force_room);
+                       strcpy(actual_rm, config.c_twitroom);
                }
-               /* This call to usergoto() changes rooms if necessary.  It also
-                  * causes the latest message list to be read into memory.
-                */
-               usergoto(actual_rm, 0);
+       }
 
-               /* read in the quickroom record, obtaining a lock... */
-               lgetroom(&CC->quickroom, actual_rm);
+       lprintf(9, "checkpoint 6      \n");
+       /* ...or if this message is destined for Aide> then go there. */
+       if (strlen(force_room) > 0) {
+               strcpy(actual_rm, force_room);
+       }
 
-               /* Fix an obscure bug */
-               if (!strcasecmp(CC->quickroom.QRname, AIDEROOM)) {
-                       CC->quickroom.QRflags =
-                           CC->quickroom.QRflags & ~QR_MAILBOX;
-               }
-               /* Add the message pointer to the room */
-               CC->quickroom.QRhighest =
-                   AddMessageToRoom(&CC->quickroom, newmsgid);
+       lprintf(9, "checkpoint 7      \n");
+       if (strcasecmp(actual_rm, CC->quickroom.QRname))
+               getroom(&CC->quickroom, actual_rm);
 
-               /* update quickroom */
-               lputroom(&CC->quickroom);
-               ++successful_local_recipients;
-       }
+       lprintf(9, "checkpoint 8      \n");
+       /* Perform "before save" hooks (aborting if any return nonzero) */
+       if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return;
+
+       lprintf(9, "checkpoint 9      \n");
+       /* If this message has an Extended ID, perform replication checks */
+       if (ReplicationChecks(msg) > 0) return;
+
+       lprintf(9, "checkpoint 10     \n");
        /* Network mail - send a copy to the network program. */
        if ((strlen(recipient) > 0) && (mailtype != MES_LOCAL)) {
                sprintf(aaa, "./network/spoolin/netmail.%04lx.%04x.%04x",
                        (long) getpid(), CC->cs_pid, ++seqnum);
-               copy_file(mtmp, aaa);
+               lprintf(9, "Saving a copy to %s\n", aaa);
+               network_fp = fopen(aaa, "ab+");
+               if (network_fp == NULL)
+                       lprintf(2, "ERROR: %s\n", strerror(errno));
+       }
+
+       lprintf(9, "checkpoint 11     \n");
+       /* Save it to disk */
+       newmsgid = send_message(msg, generate_id, network_fp);
+       if (network_fp != NULL) {
+               fclose(network_fp);
                system("exec nohup ./netproc -i >/dev/null 2>&1 &");
        }
+
+       if (newmsgid <= 0L) return;
+
+       lprintf(9, "checkpoint 12     \n");
+       /* Write a supplemental message info record.  This doesn't have to
+        * be a critical section because nobody else knows about this message
+        * yet.
+        */
+       memset(&smi, 0, sizeof(struct SuppMsgInfo));
+       smi.smi_msgnum = newmsgid;
+       smi.smi_refcount = 0;
+       safestrncpy(smi.smi_content_type, content_type, 64);
+       PutSuppMsgInfo(&smi);
+
+       /* Now figure out where to store the pointers */
+
+
+       lprintf(9, "checkpoint 13     \n");
+       /* If this is being done by the networker delivering a private
+        * message, we want to BYPASS saving the sender's copy (because there
+        * is no local sender; it would otherwise go to the Trashcan).
+        */
+       if ((!CC->internal_pgm) || (strlen(recipient) == 0)) {
+               CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0);
+       }
+
+       lprintf(9, "checkpoint 14     \n");
        /* Bump this user's messages posted counter. */
-       lgetuser(&CC->usersupp, CC->curr_user);
-       CC->usersupp.posted = CC->usersupp.posted + 1;
-       lputuser(&CC->usersupp);
+       if (CC->logged_in) {
+               lgetuser(&CC->usersupp, CC->curr_user);
+               CC->usersupp.posted = CC->usersupp.posted + 1;
+               lputuser(&CC->usersupp);
+       }
 
+       lprintf(9, "checkpoint 15     \n");
        /* If this is private, local mail, make a copy in the
         * recipient's mailbox and bump the reference count.
         */
        if ((strlen(recipient) > 0) && (mailtype == MES_LOCAL)) {
                if (getuser(&userbuf, recipient) == 0) {
                        MailboxName(actual_rm, &userbuf, MAILROOM);
-                       lprintf(9, "Targeting mailbox: <%s>\n", actual_rm);
-                       if (lgetroom(&qtemp, actual_rm) == 0) {
-                               qtemp.QRhighest =
-                                   AddMessageToRoom(&qtemp, newmsgid);
-                               lputroom(&qtemp);
-                               ++successful_local_recipients;
-                       }
+                       CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0);
                }
        }
-       /* If we've posted in a room other than the current room, then we
-        * have to now go back to the current room...
-        */
-       if (strlen(hold_rm) > 0) {
-               usergoto(hold_rm, 0);
-       }
-       unlink(mtmp);           /* delete the temporary file */
 
-       /* Write a supplemental message info record.  This doesn't have to
-        * be a critical section because nobody else knows about this message
-        * yet.
-        */
-       memset(&smi, 0, sizeof(struct SuppMsgInfo));
-       smi.smi_msgnum = newmsgid;
-       smi.smi_refcount = successful_local_recipients;
-       safestrncpy(smi.smi_content_type, content_type, 64);
-       PutSuppMsgInfo(&smi);
+       lprintf(9, "checkpoint 16     \n");
+       /* Perform "after save" hooks */
+       PerformMessageHooks(msg, EVT_AFTERSAVE);
+
+       lprintf(9, "checkpoint 17     \n");
+       /* */
+       if (strcasecmp(hold_rm, CC->quickroom.QRname))
+               getroom(&CC->quickroom, hold_rm);
 }
 
 
+
 /*
- * Generate an administrative message and post it in the Aide> room.
+ * Convenience function for generating small administrative messages.
  */
-void aide_message(char *text)
+void quickie_message(char *from, char *to, char *room, char *text)
 {
-       FILE *fp;
-
-       fp = fopen(CC->temp, "wb");
-       fprintf(fp, "%c%c%c", 255, MES_NORMAL, 0);
-       fprintf(fp, "Psysop%c", 0);
-       fprintf(fp, "T%ld%c", (long) time(NULL), 0);
-       fprintf(fp, "ACitadel%c", 0);
-       fprintf(fp, "OAide%c", 0);
-       fprintf(fp, "N%s%c", NODENAME, 0);
-       fprintf(fp, "M%s\n%c", text, 0);
-       fclose(fp);
-       save_message(CC->temp, "", AIDEROOM, MES_LOCAL, 1);
+       struct CtdlMessage *msg;
+
+       msg = mallok(sizeof(struct CtdlMessage));
+       memset(msg, 0, sizeof(struct CtdlMessage));
+       msg->cm_magic = CTDLMESSAGE_MAGIC;
+       msg->cm_anon_type = MES_NORMAL;
+       msg->cm_format_type = 0;
+       msg->cm_fields['A'] = strdoop(from);
+       msg->cm_fields['O'] = strdoop(room);
+       msg->cm_fields['N'] = strdoop(NODENAME);
+       if (to != NULL)
+               msg->cm_fields['R'] = strdoop(to);
+       msg->cm_fields['M'] = strdoop(text);
+
+       CtdlSaveMsg(msg, "", room, MES_LOCAL, 1);
+       CtdlFreeMessage(msg);
        syslog(LOG_NOTICE, text);
-}                              /*
-
-                                * Build a binary message to be saved on disk.
-                                */ void make_message(
-                                                         char *filename,       /* temporary file name */
-                                                struct usersupp *author,       /* author's usersupp structure */
-                                                        char *recipient,       /* NULL if it's not mail */
-                                                            char *room,        /* room where it's going */
-                                                            int type,  /* see MES_ types in header file */
-                                                            int net_type,      /* see MES_ types in header file */
-                                                        int format_type,       /* local or remote (see citadel.h) */
-                                                        char *fake_name)
-{                              /* who we're masquerading as */
+}
+
+
+
+/*
+ * Back end function used by make_message() and similar functions
+ */
+char *CtdlReadMessageBody(char *terminator, size_t maxlen) {
+       char buf[256];
+       size_t message_len = 0;
+       size_t buffer_len = 0;
+       char *ptr, *append;
+       char *m;
+
+       m = mallok(4096);
+       if (m == NULL) {
+               while ( (client_gets(buf)>0) && strcmp(buf, terminator) ) ;;
+               return(NULL);
+       } else {
+               buffer_len = 4096;
+               m[0] = 0;
+               message_len = 0;
+       }
+       /* read in the lines of message text one by one */
+       append = NULL;
+       while ( (client_gets(buf)>0) && strcmp(buf, terminator) ) {
+
+               /* augment the buffer if we have to */
+               if ((message_len + strlen(buf) + 2) > buffer_len) {
+                       lprintf(9, "realloking\n");
+                       ptr = reallok(m, (buffer_len * 2) );
+                       if (ptr == NULL) {      /* flush if can't allocate */
+                               while ( (client_gets(buf)>0) &&
+                                       strcmp(buf, terminator)) ;;
+                               return(m);
+                       } else {
+                               buffer_len = (buffer_len * 2);
+                               m = ptr;
+                               append = NULL;
+                               lprintf(9, "buffer_len is %d\n", buffer_len);
+                       }
+               }
+
+               if (append == NULL) append = m;
+               while (strlen(append) > 0) ++append;
+               strcpy(append, buf);
+               strcat(append, "\n");
+               message_len = message_len + strlen(buf) + 1;
+
+               /* if we've hit the max msg length, flush the rest */
+               if (message_len >= maxlen) {
+                       while ( (client_gets(buf)>0) && strcmp(buf, terminator)) ;;
+                       return(m);
+               }
+       }
+       return(m);
+}
+
+
+
+
+/*
+ * Build a binary message to be saved on disk.
+ */
+
+struct CtdlMessage *make_message(
+       struct usersupp *author,        /* author's usersupp structure */
+       char *recipient,                /* NULL if it's not mail */
+       char *room,                     /* room where it's going */
+       int type,                       /* see MES_ types in header file */
+       int net_type,                   /* see MES_ types in header file */
+       int format_type,                /* local or remote (see citadel.h) */
+       char *fake_name)                /* who we're masquerading as */
+{
 
-       FILE *fp;
        int a;
-       time_t now;
        char dest_node[32];
        char buf[256];
+       struct CtdlMessage *msg;
+
+       msg = mallok(sizeof(struct CtdlMessage));
+       memset(msg, 0, sizeof(struct CtdlMessage));
+       msg->cm_magic = CTDLMESSAGE_MAGIC;
+       msg->cm_anon_type = type;
+       msg->cm_format_type = format_type;
 
        /* Don't confuse the poor folks if it's not routed mail. */
        strcpy(dest_node, "");
 
-
        /* If net_type is MES_BINARY, split out the destination node. */
        if (net_type == MES_BINARY) {
                strcpy(dest_node, NODENAME);
@@ -1220,45 +1708,44 @@ void aide_message(char *text)
                        }
                }
        }
-       /* if net_type is MES_INTERNET, set the dest node to 'internet' */ if (net_type == MES_INTERNET) {
+
+       /* if net_type is MES_INTERNET, set the dest node to 'internet' */
+       if (net_type == MES_INTERNET) {
                strcpy(dest_node, "internet");
        }
+
        while (isspace(recipient[strlen(recipient) - 1]))
                recipient[strlen(recipient) - 1] = 0;
 
-       time(&now);
-       fp = fopen(filename, "w");
-       putc(255, fp);
-       putc(type, fp);         /* Normal or anonymous, see MES_ flags */
-       putc(format_type, fp);  /* Formatted or unformatted */
-       fprintf(fp, "Pcit%ld%c", author->usernum, 0);   /* path */
-       fprintf(fp, "T%ld%c", (long) now, 0);   /* date/time */
-       if (fake_name[0])
-               fprintf(fp, "A%s%c", fake_name, 0);
+       sprintf(buf, "cit%ld", author->usernum);                /* Path */
+       msg->cm_fields['P'] = strdoop(buf);
+
+       sprintf(buf, "%ld", time(NULL));                        /* timestamp */
+       msg->cm_fields['T'] = strdoop(buf);
+
+       if (fake_name[0])                                       /* author */
+               msg->cm_fields['A'] = strdoop(fake_name);
        else
-               fprintf(fp, "A%s%c", author->fullname, 0);      /* author */
+               msg->cm_fields['A'] = strdoop(author->fullname);
 
-       if (CC->quickroom.QRflags & QR_MAILBOX) {       /* room */
-               fprintf(fp, "O%s%c", &CC->quickroom.QRname[11], 0);
-       } else {
-               fprintf(fp, "O%s%c", CC->quickroom.QRname, 0);
-       }
+       if (CC->quickroom.QRflags & QR_MAILBOX)                 /* room */
+               msg->cm_fields['O'] = strdoop(&CC->quickroom.QRname[11]);
+       else
+               msg->cm_fields['O'] = strdoop(CC->quickroom.QRname);
 
-       fprintf(fp, "N%s%c", NODENAME, 0);      /* nodename */
-       fprintf(fp, "H%s%c", HUMANNODE, 0);     /* human nodename */
+       msg->cm_fields['N'] = strdoop(NODENAME);                /* nodename */
+       msg->cm_fields['H'] = strdoop(HUMANNODE);               /* hnodename */
 
        if (recipient[0] != 0)
-               fprintf(fp, "R%s%c", recipient, 0);
+               msg->cm_fields['R'] = strdoop(recipient);
        if (dest_node[0] != 0)
-               fprintf(fp, "D%s%c", dest_node, 0);
+               msg->cm_fields['D'] = strdoop(dest_node);
 
-       putc('M', fp);
 
-       while (client_gets(buf), strcmp(buf, "000")) {
-               fprintf(fp, "%s\n", buf);
-       }
-       putc(0, fp);
-       fclose(fp);
+       msg->cm_fields['M'] = CtdlReadMessageBody("000", config.c_maxmsglen);
+
+
+       return(msg);
 }
 
 
@@ -1266,7 +1753,7 @@ void aide_message(char *text)
 
 
 /*
- * message entry  -  mode 0 (normal) <bc>
+ * message entry  -  mode 0 (normal)
  */
 void cmd_ent0(char *entargs)
 {
@@ -1274,8 +1761,8 @@ void cmd_ent0(char *entargs)
        char recipient[256];
        int anon_flag = 0;
        int format_type = 0;
-       char newusername[256];  /* <bc> */
-
+       char newusername[256];
+       struct CtdlMessage *msg;
        int a, b;
        int e = 0;
        int mtsflag = 0;
@@ -1312,9 +1799,9 @@ void cmd_ent0(char *entargs)
        mtsflag = 0;
 
 
-       if (post == 2) {        /* <bc> */
+       if (post == 2) {
                if (CC->usersupp.axlevel < 6) {
-                       cprintf("%d You don't have permission to do an aide post.\n",
+                       cprintf("%d You don't have permission to masquerade.\n",
                                ERROR + HIGHER_ACCESS_REQUIRED);
                        return;
                }
@@ -1332,9 +1819,7 @@ void cmd_ent0(char *entargs)
                        strcpy(buf, recipient);
                } else
                        strcpy(buf, "sysop");
-               lprintf(9, "calling alias()\n");
                e = alias(buf); /* alias and mail type */
-               lprintf(9, "alias() returned %d\n", e);
                if ((buf[0] == 0) || (e == MES_ERROR)) {
                        cprintf("%d Unknown address - cannot send message.\n",
                                ERROR + NO_SUCH_USER);
@@ -1364,7 +1849,7 @@ void cmd_ent0(char *entargs)
                        return;
                }
                /* Check to make sure the user exists; also get the correct
-                  * upper/lower casing of the name. 
+                * upper/lower casing of the name. 
                 */
                a = getuser(&tempUS, buf);
                if (a != 0) {
@@ -1373,7 +1858,8 @@ void cmd_ent0(char *entargs)
                }
                strcpy(buf, tempUS.fullname);
        }
-      SKFALL:b = MES_NORMAL;
+
+SKFALL:        b = MES_NORMAL;
        if (CC->quickroom.QRflags & QR_ANONONLY)
                b = MES_ANON;
        if (CC->quickroom.QRflags & QR_ANONOPT) {
@@ -1390,14 +1876,25 @@ void cmd_ent0(char *entargs)
                cprintf("%d %s\n", OK, buf);
                return;
        }
+
        cprintf("%d send message\n", SEND_LISTING);
+
+       /* Read in the message from the client. */
        if (CC->fake_postname[0])
-               make_message(CC->temp, &CC->usersupp, buf, CC->quickroom.QRname, b, e, format_type, CC->fake_postname);
+               msg = make_message(&CC->usersupp, buf,
+                       CC->quickroom.QRname, b, e, format_type,
+                       CC->fake_postname);
        else if (CC->fake_username[0])
-               make_message(CC->temp, &CC->usersupp, buf, CC->quickroom.QRname, b, e, format_type, CC->fake_username);
+               msg = make_message(&CC->usersupp, buf,
+                       CC->quickroom.QRname, b, e, format_type,
+                       CC->fake_username);
        else
-               make_message(CC->temp, &CC->usersupp, buf, CC->quickroom.QRname, b, e, format_type, "");
-       save_message(CC->temp, buf, (mtsflag ? AIDEROOM : ""), e, 1);
+               msg = make_message(&CC->usersupp, buf,
+                       CC->quickroom.QRname, b, e, format_type, "");
+
+       if (msg != NULL)
+               CtdlSaveMsg(msg, buf, (mtsflag ? AIDEROOM : ""), e, 1);
+               CtdlFreeMessage(msg);
        CC->fake_postname[0] = '\0';
        return;
 }
@@ -1410,20 +1907,23 @@ void cmd_ent0(char *entargs)
 void cmd_ent3(char *entargs)
 {
        char recp[256];
-       char buf[256];
        int a;
        int e = 0;
+       int valid_msg = 1;
+       unsigned char ch, which_field;
        struct usersupp tempUS;
        long msglen;
-       long bloklen;
-       FILE *fp;
+       struct CtdlMessage *msg;
+       char *tempbuf;
 
        if (CC->internal_pgm == 0) {
                cprintf("%d This command is for internal programs only.\n",
                        ERROR);
                return;
        }
-       /* See if there's a recipient, but make sure it's a real one */ extract(recp, entargs, 1);
+
+       /* See if there's a recipient, but make sure it's a real one */
+       extract(recp, entargs, 1);
        for (a = 0; a < strlen(recp); ++a)
                if (!isprint(recp[a]))
                        strcpy(&recp[a], &recp[a + 1]);
@@ -1449,37 +1949,64 @@ void cmd_ent3(char *entargs)
                        }
                }
        }
+
        /* At this point, message has been approved. */
        if (extract_int(entargs, 0) == 0) {
                cprintf("%d OK to send\n", OK);
                return;
        }
-       /* open a temp file to hold the message */
-       fp = fopen(CC->temp, "wb");
-       if (fp == NULL) {
-               cprintf("%d Cannot open %s: %s\n",
-                       ERROR + INTERNAL_ERROR,
-                       CC->temp, strerror(errno));
+
+       msglen = extract_long(entargs, 2);
+       msg = mallok(sizeof(struct CtdlMessage));
+       if (msg == NULL) {
+               cprintf("%d Out of memory\n", ERROR+INTERNAL_ERROR);
                return;
        }
-       msglen = extract_long(entargs, 2);
-       cprintf("%d %ld\n", SEND_BINARY, msglen);
-       while (msglen > 0L) {
-               bloklen = ((msglen >= 255L) ? 255 : msglen);
-               client_read(buf, (int) bloklen);
-               fwrite(buf, (int) bloklen, 1, fp);
-               msglen = msglen - bloklen;
+
+       memset(msg, 0, sizeof(struct CtdlMessage));
+       tempbuf = mallok(msglen);
+       if (tempbuf == NULL) {
+               cprintf("%d Out of memory\n", ERROR+INTERNAL_ERROR);
+               phree(msg);
+               return;
        }
-       fclose(fp);
 
-       save_message(CC->temp, recp, "", e, 0);
+       cprintf("%d %ld\n", SEND_BINARY, msglen);
+
+       client_read(&ch, 1);                            /* 0xFF magic number */
+       msg->cm_magic = CTDLMESSAGE_MAGIC;
+       client_read(&ch, 1);                            /* anon type */
+       msg->cm_anon_type = ch;
+       client_read(&ch, 1);                            /* format type */
+       msg->cm_format_type = ch;
+       msglen = msglen - 3;
+
+       while (msglen > 0) {
+               client_read(&which_field, 1);
+               if (!isalpha(which_field)) valid_msg = 0;
+               --msglen;
+               tempbuf[0] = 0;
+               do {
+                       client_read(&ch, 1);
+                       --msglen;
+                       a = strlen(tempbuf);
+                       tempbuf[a+1] = 0;
+                       tempbuf[a] = ch;
+               } while ( (ch != 0) && (msglen > 0) );
+               if (valid_msg)
+                       msg->cm_fields[which_field] = strdoop(tempbuf);
+       }
+
+       msg->cm_flags = CM_SKIP_HOOKS;
+       if (valid_msg) CtdlSaveMsg(msg, recp, "", e, 0);
+       CtdlFreeMessage(msg);
+       phree(tempbuf);
 }
 
 
 /*
  * API function to delete messages which match a set of criteria
  * (returns the actual number of messages deleted)
- * FIX ... still need to implement delete by content type
  */
 int CtdlDeleteMessages(char *room_name,                /* which room */
                       long dmsgnum,            /* or "0" for any */
@@ -1507,7 +2034,6 @@ int CtdlDeleteMessages(char *room_name,           /* which room */
        }
        cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
 
-       lprintf(9, "doing mallok/memcpy loop\n");
        if (cdbfr != NULL) {
                msglist = mallok(cdbfr->len);
                memcpy(msglist, cdbfr->ptr, cdbfr->len);
@@ -1566,7 +2092,8 @@ void cmd_dele(char *delstr)
        getuser(&CC->usersupp, CC->curr_user);
        if ((CC->usersupp.axlevel < 6)
            && (CC->usersupp.usernum != CC->quickroom.QRroomaide)
-           && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)) {
+           && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)
+           && (!(CC->internal_pgm))) {
                cprintf("%d Higher access required.\n",
                        ERROR + HIGHER_ACCESS_REQUIRED);
                return;
@@ -1585,17 +2112,20 @@ void cmd_dele(char *delstr)
 
 
 /*
- * move a message to another room
+ * move or copy a message to another room
  */
 void cmd_move(char *args)
 {
        long num;
-       char targ[32];
+       char targ[256];
        struct quickroom qtemp;
-       int foundit;
+       int err;
+       int is_copy = 0;
 
        num = extract_long(args, 0);
        extract(targ, args, 1);
+       targ[ROOMNAMELEN - 1] = 0;
+       is_copy = extract_int(args, 2);
 
        getuser(&CC->usersupp, CC->curr_user);
        if ((CC->usersupp.axlevel < 6)
@@ -1604,28 +2134,26 @@ void cmd_move(char *args)
                        ERROR + HIGHER_ACCESS_REQUIRED);
                return;
        }
+
        if (getroom(&qtemp, targ) != 0) {
                cprintf("%d '%s' does not exist.\n", ERROR, targ);
                return;
        }
-       /* Bump the reference count, otherwise the message will be deleted
-        * from disk when we remove it from the source room.
-        */
-       AdjRefCount(num, 1);
-
-       /* yank the message out of the current room... */
-       foundit = CtdlDeleteMessages(CC->quickroom.QRname, num, NULL);
 
-       if (foundit) {
-               /* put the message into the target room */
-               lgetroom(&qtemp, targ);
-               qtemp.QRhighest = AddMessageToRoom(&qtemp, num);
-               lputroom(&qtemp);
-               cprintf("%d Message moved.\n", OK);
-       } else {
-               AdjRefCount(num, (-1));         /* oops */
-               cprintf("%d msg %ld does not exist.\n", ERROR, num);
+       err = CtdlSaveMsgPointerInRoom(targ, num,
+               (SM_VERIFY_GOODNESS | SM_DO_REPL_CHECK) );
+       if (err != 0) {
+               cprintf("%d Cannot store message in %s: error %d\n",
+                       err, targ, err);
+               return;
        }
+
+       /* Now delete the message from the source room,
+        * if this is a 'move' rather than a 'copy' operation.
+        */
+       if (is_copy == 0) CtdlDeleteMessages(CC->quickroom.QRname, num, NULL);
+
+       cprintf("%d Message %s.\n", OK, (is_copy ? "copied" : "moved") );
 }
 
 
@@ -1675,11 +2203,13 @@ void PutSuppMsgInfo(struct SuppMsgInfo *smibuf)
                  &TheIndex, sizeof(long),
                  smibuf, sizeof(struct SuppMsgInfo));
 
-}                              /*
+}
 
-                                * AdjRefCount  -  change the reference count for a message;
-                                *                 delete the message if it reaches zero
-                                */ void AdjRefCount(long msgnum, int incr)
+/*
+ * AdjRefCount  -  change the reference count for a message;
+ *                 delete the message if it reaches zero
+ */
+void AdjRefCount(long msgnum, int incr)
 {
 
        struct SuppMsgInfo smi;
@@ -1712,13 +2242,17 @@ void PutSuppMsgInfo(struct SuppMsgInfo *smibuf)
 
 /*
  * Write a generic object to this room
+ *
+ * Note: this could be much more efficient.  Right now we use two temporary
+ * files, and still pull the message into memory as with all others.
  */
 void CtdlWriteObject(char *req_room,           /* Room to stuff it in */
                        char *content_type,     /* MIME type of this object */
                        char *tempfilename,     /* Where to fetch it from */
-                       int is_mailbox,         /* Private mailbox room? */
+                       struct usersupp *is_mailbox,    /* Mailbox room? */
                        int is_binary,          /* Is encoding necessary? */
-                       int is_unique   /* Del others of this type? */
+                       int is_unique,          /* Del others of this type? */
+                       unsigned int flags      /* Internal save flags */
                        )
 {
 
@@ -1728,30 +2262,30 @@ void CtdlWriteObject(char *req_room,            /* Room to stuff it in */
        int ch;
        struct quickroom qrbuf;
        char roomname[ROOMNAMELEN];
+       struct CtdlMessage *msg;
+       size_t len;
 
-       if (is_mailbox)
-               MailboxName(roomname, &CC->usersupp, req_room);
+       if (is_mailbox != NULL)
+               MailboxName(roomname, is_mailbox, req_room);
        else
                safestrncpy(roomname, req_room, sizeof(roomname));
+       lprintf(9, "CtdlWriteObject() to <%s> (flags=%d)\n", roomname, flags);
 
        strcpy(filename, tmpnam(NULL));
        fp = fopen(filename, "w");
        if (fp == NULL)
                return;
 
-       fprintf(fp, "%c%c%c", 0xFF, MES_NORMAL, 4);
-       fprintf(fp, "T%ld%c", time(NULL), 0);
-       fprintf(fp, "A%s%c", CC->usersupp.fullname, 0);
-       fprintf(fp, "O%s%c", roomname, 0);
-       fprintf(fp, "N%s%c", config.c_nodename, 0);
-       fprintf(fp, "MContent-type: %s\n", content_type);
-
        tempfp = fopen(tempfilename, "r");
        if (tempfp == NULL) {
                fclose(fp);
                unlink(filename);
                return;
        }
+
+       fprintf(fp, "Content-type: %s\n", content_type);
+       lprintf(9, "Content-type: %s\n", content_type);
+
        if (is_binary == 0) {
                fprintf(fp, "Content-transfer-encoding: 7bit\n\n");
                while (ch = getc(tempfp), ch > 0)
@@ -1768,6 +2302,28 @@ void CtdlWriteObject(char *req_room,             /* Room to stuff it in */
                system(cmdbuf);
        }
 
+       lprintf(9, "Allocating\n");
+       msg = mallok(sizeof(struct CtdlMessage));
+       memset(msg, 0, sizeof(struct CtdlMessage));
+       msg->cm_magic = CTDLMESSAGE_MAGIC;
+       msg->cm_anon_type = MES_NORMAL;
+       msg->cm_format_type = 4;
+       msg->cm_fields['A'] = strdoop(CC->usersupp.fullname);
+       msg->cm_fields['O'] = strdoop(req_room);
+       msg->cm_fields['N'] = strdoop(config.c_nodename);
+       msg->cm_fields['H'] = strdoop(config.c_humannode);
+       msg->cm_flags = flags;
+       
+       lprintf(9, "Loading\n");
+       fp = fopen(filename, "rb");
+       fseek(fp, 0L, SEEK_END);
+       len = ftell(fp);
+       rewind(fp);
+       msg->cm_fields['M'] = mallok(len);
+       fread(msg->cm_fields['M'], len, 1, fp);
+       fclose(fp);
+       unlink(filename);
+
        /* Create the requested room if we have to. */
        if (getroom(&qrbuf, roomname) != 0) {
                create_room(roomname, 4, "", 0);
@@ -1780,5 +2336,6 @@ void CtdlWriteObject(char *req_room,              /* Room to stuff it in */
                        CtdlDeleteMessages(roomname, 0L, content_type));
        }
        /* Now write the data */
-       save_message(filename, "", roomname, MES_LOCAL, 1);
+       CtdlSaveMsg(msg, "", roomname, MES_LOCAL, 1);
+       CtdlFreeMessage(msg);
 }