]> code.citadel.org Git - citadel.git/blobdiff - citadel/server/msgbase.c
Changed some C89 style comments to C99 style.
[citadel.git] / citadel / server / msgbase.c
index 0da39fc875e87db8a0541258210c2cf0f7e1022d..ae77f36336bb057f3545f5184d533f68662ea105 100644 (file)
@@ -1,6 +1,6 @@
 // Implements the message store.
 //
-// Copyright (c) 1987-2022 by the citadel.org team
+// Copyright (c) 1987-2023 by the citadel.org team
 //
 // This program is open source software; you can redistribute it and/or modify
 // it under the terms of the GNU General Public License version 3.
@@ -24,6 +24,7 @@
 #include "euidindex.h"
 #include "msgbase.h"
 #include "journaling.h"
+#include "modules/fulltext/serv_fulltext.h"
 
 struct addresses_to_be_filed *atbf = NULL;
 
@@ -134,17 +135,12 @@ int CM_IsEmpty(struct CtdlMessage *Msg, eMsgField which) {
 }
 
 
-void CM_SetField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length) {
+void CM_SetField(struct CtdlMessage *Msg, eMsgField which, const char *buf) {
        if (Msg->cm_fields[which] != NULL) {
-               free (Msg->cm_fields[which]);
-       }
-       if (length < 0) {                       // You can set the length to -1 to have CM_SetField measure it for you
-               length = strlen(buf);
+               free(Msg->cm_fields[which]);
        }
-       Msg->cm_fields[which] = malloc(length + 1);
-       memcpy(Msg->cm_fields[which], buf, length);
-       Msg->cm_fields[which][length] = '\0';
-       Msg->cm_lengths[which] = length;
+       Msg->cm_fields[which] = strdup(buf);
+       Msg->cm_lengths[which] = strlen(buf);
 }
 
 
@@ -152,7 +148,7 @@ void CM_SetFieldLONG(struct CtdlMessage *Msg, eMsgField which, long lvalue) {
        char buf[128];
        long len;
        len = snprintf(buf, sizeof(buf), "%ld", lvalue);
-       CM_SetField(Msg, which, buf, len);
+       CM_SetField(Msg, which, buf);
 }
 
 
@@ -234,6 +230,7 @@ void CM_PrependToField(struct CtdlMessage *Msg, eMsgField which, const char *buf
 }
 
 
+// This is like CM_SetField() except the caller is transferring ownership of the supplied memory to the message
 void CM_SetAsField(struct CtdlMessage *Msg, eMsgField which, char **buf, long length) {
        if (Msg->cm_fields[which] != NULL) {
                free (Msg->cm_fields[which]);
@@ -386,7 +383,7 @@ int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
 
 // Retrieve the "seen" message list for the current room.
 void CtdlGetSeen(char *buf, int which_set) {
-       visit vbuf;
+       struct visit vbuf;
 
        // Learn about the user and room in question
        CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
@@ -404,13 +401,12 @@ void CtdlGetSeen(char *buf, int which_set) {
 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
                int target_setting, int which_set,
                struct ctdluser *which_user, struct ctdlroom *which_room) {
-       struct cdbdata *cdbfr;
        int i, k;
        int is_seen = 0;
        int was_seen = 0;
        long lo = (-1L);
        long hi = (-1L);
-       visit vbuf;
+       struct visit vbuf;
        long *msglist;
        int num_msgs = 0;
        StrBuf *vset;
@@ -445,17 +441,12 @@ void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
        CtdlGetRelationship(&vbuf, which_user, which_room);
 
        // Load the message list
-       cdbfr = cdb_fetch(CDB_MSGLISTS, &which_room->QRnumber, sizeof(long));
-       if (cdbfr != NULL) {
-               msglist = (long *) cdbfr->ptr;
-               cdbfr->ptr = NULL;      // CtdlSetSeen() now owns this memory
-               num_msgs = cdbfr->len / sizeof(long);
-               cdb_free(cdbfr);
-       }
-       else {
-               return; // No messages at all?  No further action.
+       num_msgs = CtdlFetchMsgList(which_room->QRnumber, &msglist);
+       if (num_msgs <= 0) {
+               free(msglist);
+               return;
        }
-
+       
        is_set = malloc(num_msgs * sizeof(char));
        memset(is_set, 0, (num_msgs * sizeof(char)) );
 
@@ -471,18 +462,6 @@ void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
                vset = NewStrBuf();
        }
 
-
-#if 0  // This is a special diagnostic section.  Do not allow it to run during normal operation.
-       syslog(LOG_DEBUG, "There are %d messages in the room.\n", num_msgs);
-       for (i=0; i<num_msgs; ++i) {
-               if ((i > 0) && (msglist[i] <= msglist[i-1])) abort();
-       }
-       syslog(LOG_DEBUG, "We are twiddling %d of them.\n", num_target_msgnums);
-       for (k=0; k<num_target_msgnums; ++k) {
-               if ((k > 0) && (target_msgnums[k] <= target_msgnums[k-1])) abort();
-       }
-#endif
-
        // Translate the existing sequence set into an array of booleans
        setstr = NewStrBuf();
        lostr = NewStrBuf();
@@ -599,12 +578,14 @@ void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
                vset = new_set;
        }
 
-       // Decide which message set we're manipulating
+       // Decide which message set we're manipulating.  Zero the buffers so they compress well.
        switch (which_set) {
                case ctdlsetseen_seen:
+                       memset(vbuf.v_seen, 0, sizeof vbuf.v_seen);
                        safestrncpy(vbuf.v_seen, ChrPtr(vset), sizeof vbuf.v_seen);
                        break;
                case ctdlsetseen_answered:
+                       memset(vbuf.v_answered, 0, sizeof vbuf.v_seen);
                        safestrncpy(vbuf.v_answered, ChrPtr(vset), sizeof vbuf.v_answered);
                        break;
        }
@@ -625,8 +606,7 @@ int CtdlForEachMessage(int mode, long ref, char *search_string,
                        void *userdata)
 {
        int a, i, j;
-       visit vbuf;
-       struct cdbdata *cdbfr;
+       struct visit vbuf;
        long *msglist = NULL;
        int num_msgs = 0;
        int num_processed = 0;
@@ -636,11 +616,10 @@ int CtdlForEachMessage(int mode, long ref, char *search_string,
        int is_seen = 0;
        long lastold = 0L;
        int printed_lastold = 0;
-       int num_search_msgs = 0;
-       long *search_msgs = NULL;
        regex_t re;
        int need_to_free_re = 0;
        regmatch_t pm;
+       Array *search = NULL;
 
        if ((content_type) && (!IsEmptyStr(content_type))) {
                regcomp(&re, content_type, 0);
@@ -666,37 +645,28 @@ int CtdlForEachMessage(int mode, long ref, char *search_string,
        }
 
        // Load the message list
-       cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
-       if (cdbfr == NULL) {
+       num_msgs = CtdlFetchMsgList(CC->room.QRnumber, &msglist);
+       if (num_msgs <= 0) {
+               free(msglist);
                if (need_to_free_re) regfree(&re);
                return 0;       // No messages at all?  No further action.
        }
 
-       msglist = (long *) cdbfr->ptr;
-       num_msgs = cdbfr->len / sizeof(long);
-
-       cdbfr->ptr = NULL;      // clear this so that cdb_free() doesn't free it
-       cdb_free(cdbfr);        // we own this memory now
-
-       /*
-        * Now begin the traversal.
-        */
-       if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
+       // Now begin the traversal.
+       if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) if (msglist[a] > 0) {
 
-               /* If the caller is looking for a specific MIME type, filter
-                * out all messages which are not of the type requested.
-                */
+               // If the caller is looking for a specific MIME type, filter
+               // out all messages which are not of the type requested.
                if ((content_type != NULL) && (!IsEmptyStr(content_type))) {
 
-                       /* This call to GetMetaData() sits inside this loop
-                        * so that we only do the extra database read per msg
-                        * if we need to.  Doing the extra read all the time
-                        * really kills the server.  If we ever need to use
-                        * metadata for another search criterion, we need to
-                        * move the read somewhere else -- but still be smart
-                        * enough to only do the read if the caller has
-                        * specified something that will need it.
-                        */
+                       // This call to GetMetaData() sits inside this loop
+                       // so that we only do the extra database read per msg
+                       // if we need to.  Doing the extra read all the time
+                       // really kills the server.  If we ever need to use
+                       // metadata for another search criterion, we need to
+                       // move the read somewhere else -- but still be smart
+                       // enough to only do the read if the caller has
+                       // specified something that will need it.
                        if (server_shutting_down) {
                                if (need_to_free_re) regfree(&re);
                                free(msglist);
@@ -704,7 +674,6 @@ int CtdlForEachMessage(int mode, long ref, char *search_string,
                        }
                        GetMetaData(&smi, msglist[a]);
 
-                       /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
                        if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
                                msglist[a] = 0L;
                        }
@@ -713,9 +682,7 @@ int CtdlForEachMessage(int mode, long ref, char *search_string,
 
        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 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) {
@@ -752,17 +719,19 @@ int CtdlForEachMessage(int mode, long ref, char *search_string,
                 * NULL means use any search function available.
                 * otherwise replace with a char * to name of search routine
                 */
-               CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
+               search = CtdlFullTextSearch(search_string);
 
-               if (num_search_msgs > 0) {
+               if (array_len(search) > 0) {
        
                        int orig_num_msgs;
 
                        orig_num_msgs = num_msgs;
                        num_msgs = 0;
                        for (i=0; i<orig_num_msgs; ++i) {
-                               for (j=0; j<num_search_msgs; ++j) {
-                                       if (msglist[i] == search_msgs[j]) {
+                               for (j=0; j<array_len(search); ++j) {
+                                       long smsgnum;
+                                       memcpy(&smsgnum, array_get_element_at(search, j), sizeof(long));
+                                       if (msglist[i] == smsgnum) {
                                                msglist[num_msgs++] = msglist[i];
                                        }
                                }
@@ -771,7 +740,7 @@ int CtdlForEachMessage(int mode, long ref, char *search_string,
                else {
                        num_msgs = 0;   /* No messages qualify */
                }
-               if (search_msgs != NULL) free(search_msgs);
+               if (search != NULL) array_free(search);
 
                /* Now that we've purged messages which don't contain the search
                 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
@@ -1110,7 +1079,7 @@ struct CtdlMessage *CtdlDeserializeMessage(long msgnum, int with_body, const cha
                which = field_header;
                len = strlen(mptr);
 
-               CM_SetField(ret, which, mptr, len);
+               CM_SetField(ret, which, mptr);
 
                mptr += len + 1;                                // advance to next field
 
@@ -1126,25 +1095,23 @@ struct CtdlMessage *CtdlDeserializeMessage(long msgnum, int with_body, const cha
 //       using the CM_Free(); function.
 //
 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body) {
-       struct cdbdata *dmsgtext;
+       struct cdbdata dmsgtext;
        struct CtdlMessage *ret = NULL;
 
        syslog(LOG_DEBUG, "msgbase: CtdlFetchMessage(%ld, %d)", msgnum, with_body);
        dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
-       if (dmsgtext == NULL) {
+       if (dmsgtext.ptr == NULL) {
                syslog(LOG_ERR, "msgbase: message #%ld was not found", msgnum);
                return NULL;
        }
 
-       if (dmsgtext->ptr[dmsgtext->len - 1] != '\0') {
+       if (dmsgtext.ptr[dmsgtext.len - 1] != '\0') {
+               // FIXME LMDB cannot write to immutable memory
                syslog(LOG_ERR, "msgbase: CtdlFetchMessage(%ld, %d) Forcefully terminating message!!", msgnum, with_body);
-               dmsgtext->ptr[dmsgtext->len - 1] = '\0';
+               dmsgtext.ptr[dmsgtext.len - 1] = '\0';
        }
 
-       ret = CtdlDeserializeMessage(msgnum, with_body, dmsgtext->ptr, dmsgtext->len);
-
-       cdb_free(dmsgtext);
-
+       ret = CtdlDeserializeMessage(msgnum, with_body, dmsgtext.ptr, dmsgtext.len);
        if (ret == NULL) {
                return NULL;
        }
@@ -1156,13 +1123,12 @@ struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body) {
        //
        if ( (CM_IsEmpty(ret, eMesageText)) && (with_body) ) {
                dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
-               if (dmsgtext != NULL) {
-                       CM_SetAsField(ret, eMesageText, &dmsgtext->ptr, dmsgtext->len - 1);
-                       cdb_free(dmsgtext);
+               if (dmsgtext.ptr != NULL) {
+                       CM_SetField(ret, eMesageText, dmsgtext.ptr);
                }
        }
        if (CM_IsEmpty(ret, eMesageText)) {
-               CM_SetField(ret, eMesageText, HKEY("\r\n\r\n (no text)\r\n"));
+               CM_SetField(ret, eMesageText, "\r\n\r\n (no text)\r\n");
        }
 
        return (ret);
@@ -1254,7 +1220,7 @@ void fixed_output(char *name, char *filename, char *partnum, char *disp,
        }
 
        if (!strcasecmp(cbtype, "text/html")) {
-               ptr = html_to_ascii(content, length, 80);
+               ptr = html_to_ascii(content, length, 80, 0);
                wlen = strlen(ptr);
                client_write(ptr, wlen);
                if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
@@ -1501,12 +1467,10 @@ int CtdlOutputMsg(long msg_num,         // message number (local) to fetch
                return(r);
        }
 
-       /*
-        * Check to make sure the message is actually IN this room
-        */
+       // Check to make sure the message is actually IN this room
        r = check_cached_msglist(msg_num);
        if (r == om_access_denied) {
-               /* Not in the cache?  We get ONE shot to check it again. */
+               // Not in the cache?  We get ONE shot to check it again.
                CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
                r = check_cached_msglist(msg_num);
        }
@@ -1525,10 +1489,7 @@ int CtdlOutputMsg(long msg_num,          // message number (local) to fetch
                return(r);
        }
 
-       /*
-        * Fetch the message from disk.  If we're in HEADERS_FAST mode,
-        * request that we don't even bother loading the body into memory.
-        */
+       // Fetch the message from disk.  If we're in HEADERS_FAST mode, request that we don't even bother loading the body into memory.
        if (headers_only == HEADERS_FAST) {
                TheMessage = CtdlFetchMessage(msg_num, 0);
        }
@@ -1542,9 +1503,7 @@ int CtdlOutputMsg(long msg_num,           // message number (local) to fetch
                return(om_no_such_msg);
        }
 
-       /* Here is the weird form of this command, to process only an
-        * encapsulated message/rfc822 section.
-        */
+       // Here is the weird form of this command, to process only an encapsulated message/rfc822 section.
        if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
                memset(&encap, 0, sizeof encap);
                safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
@@ -1553,18 +1512,15 @@ int CtdlOutputMsg(long msg_num,         // message number (local) to fetch
                            NULL, NULL, (void *)&encap, 0
                        );
 
-               if ((Author != NULL) && (*Author == NULL))
-               {
+               if ((Author != NULL) && (*Author == NULL)) {
                        long len;
                        CM_GetAsField(TheMessage, eAuthor, Author, &len);
                }
-               if ((Address != NULL) && (*Address == NULL))
-               {       
+               if ((Address != NULL) && (*Address == NULL)) {  
                        long len;
                        CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
                }
-               if ((MessageID != NULL) && (*MessageID == NULL))
-               {       
+               if ((MessageID != NULL) && (*MessageID == NULL)) {      
                        long len;
                        CM_GetAsField(TheMessage, emessageId, MessageID, &len);
                }
@@ -1574,41 +1530,33 @@ int CtdlOutputMsg(long msg_num,         // message number (local) to fetch
                if (encap.msg) {
                        encap.msg[encap.msglen] = 0;
                        TheMessage = convert_internet_message(encap.msg);
-                       encap.msg = NULL;       /* no free() here, TheMessage owns it now */
+                       encap.msg = NULL;       // no free() here, TheMessage owns it now
 
-                       /* Now we let it fall through to the bottom of this
-                        * function, because TheMessage now contains the
-                        * encapsulated message instead of the top-level
-                        * message.  Isn't that neat?
-                        */
+                       // Now we let it fall through to the bottom of this function, because TheMessage now contains the
+                       // encapsulated message instead of the top-level message.  Isn't that neat?
                }
                else {
                        if (do_proto) {
-                               cprintf("%d msg %ld has no part %s\n",
-                                       ERROR + MESSAGE_NOT_FOUND,
-                                       msg_num,
-                                       section);
+                               cprintf("%d msg %ld has no part %s\n", ERROR + MESSAGE_NOT_FOUND, msg_num, section);
                        }
                        retcode = om_no_such_msg;
                }
 
        }
 
-       /* Ok, output the message now */
-       if (retcode == CIT_OK)
+       // Ok, output the message now
+       if (retcode == CIT_OK) {
                retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
-       if ((Author != NULL) && (*Author == NULL))
-       {
+       }
+       if ((Author != NULL) && (*Author == NULL)) {
                long len;
                CM_GetAsField(TheMessage, eAuthor, Author, &len);
        }
-       if ((Address != NULL) && (*Address == NULL))
-       {       
+       if ((Address != NULL) && (*Address == NULL)) {  
                long len;
                CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
        }
-       if ((MessageID != NULL) && (*MessageID == NULL))
-       {       
+       if ((MessageID != NULL) && (*MessageID == NULL)) {      
                long len;
                CM_GetAsField(TheMessage, emessageId, MessageID, &len);
        }
@@ -1952,26 +1900,23 @@ void DumpFormatFixed(
 }
 
 
-/*
- * Get a message off disk.  (returns om_* values found in msgbase.h)
- */
+// Get a message off disk.  (returns om_* values found in msgbase.h)
 int CtdlOutputPreLoadedMsg(
                struct CtdlMessage *TheMessage,
-               int mode,               /* how would you like that message? */
-               int headers_only,       /* eschew the message body? */
-               int do_proto,           /* do Citadel protocol responses? */
-               int crlf,               /* Use CRLF newlines instead of LF? */
-               int flags               /* should the bessage be exported clean? */
+               int mode,               // how would you like that message?
+               int headers_only,       // eschew the message body?
+               int do_proto,           // do Citadel protocol responses?
+               int crlf,               // Use CRLF newlines instead of LF?
+               int flags               // should the bessage be exported clean?
 ) {
        int i;
-       const char *nl; /* newline string */
+       const char *nl; // newline string
        int nlen;
        struct ma_info ma;
 
-       /* Buffers needed for RFC822 translation.  These are all filled
-        * using functions that are bounds-checked, and therefore we can
-        * make them substantially smaller than SIZ.
-        */
+       // Buffers needed for RFC822 translation.  These are all filled
+       // using functions that are bounds-checked, and therefore we can
+       // make them substantially smaller than SIZ.
        char suser[1024];
        char luser[1024];
        char fuser[1024];
@@ -1992,35 +1937,33 @@ int CtdlOutputPreLoadedMsg(
                return(om_no_such_msg);
        }
 
-       /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
-        * Pad it with spaces in order to avoid changing the RFC822 length of the message.
-        */
+       // Suppress envelope recipients if required to avoid disclosing BCC addresses.
+       // Pad it with spaces in order to avoid changing the RFC822 length of the message.
        if ( (flags & SUPPRESS_ENV_TO) && (!CM_IsEmpty(TheMessage, eenVelopeTo)) ) {
                memset(TheMessage->cm_fields[eenVelopeTo], ' ', TheMessage->cm_lengths[eenVelopeTo]);
        }
                
-       /* Are we downloading a MIME component? */
+       // Are we downloading a MIME component?
        if (mode == MT_DOWNLOAD) {
                if (TheMessage->cm_format_type != FMT_RFC822) {
-                       if (do_proto)
-                               cprintf("%d This is not a MIME message.\n",
-                               ERROR + ILLEGAL_VALUE);
-               } else if (CC->download_fp != NULL) {
-                       if (do_proto) cprintf(
-                               "%d You already have a download open.\n",
-                               ERROR + RESOURCE_BUSY);
-               } else {
-                       /* Parse the message text component */
-                       mime_parser(CM_RANGE(TheMessage, eMesageText),
-                                   *mime_download, NULL, NULL, NULL, 0);
-                       /* If there's no file open by this time, the requested
-                        * section wasn't found, so print an error
-                        */
+                       if (do_proto) {
+                               cprintf("%d This is not a MIME message.\n", ERROR + ILLEGAL_VALUE);
+                       }
+               }
+               else if (CC->download_fp != NULL) {
+                       if (do_proto) {
+                               cprintf( "%d You already have a download open.\n", ERROR + RESOURCE_BUSY);
+                       }
+               }
+               else {
+                       // Parse the message text component
+                       mime_parser(CM_RANGE(TheMessage, eMesageText), *mime_download, NULL, NULL, NULL, 0);
+
+                       // If there's no file open by this time, the requested * section wasn't found, so print an error
                        if (CC->download_fp == NULL) {
-                               if (do_proto) cprintf(
-                                       "%d Section %s not found.\n",
-                                       ERROR + FILE_NOT_FOUND,
-                                       CC->download_desired_section);
+                               if (do_proto) {
+                                       cprintf( "%d Section %s not found.\n", ERROR + FILE_NOT_FOUND, CC->download_desired_section);
+                               }
                        }
                }
                return((CC->download_fp != NULL) ? om_ok : om_mime_error);
@@ -2077,7 +2020,7 @@ int CtdlOutputPreLoadedMsg(
        strcpy(luser, "");
        strcpy(fuser, "");
        strcpy(snode, "");
-       if (mode == MT_RFC822) 
+       if (mode == MT_RFC822) {
                OutputRFC822MsgHeaders(
                        TheMessage,
                        flags,
@@ -2087,8 +2030,8 @@ int CtdlOutputPreLoadedMsg(
                        luser, sizeof(luser),
                        fuser, sizeof(fuser),
                        snode, sizeof(snode)
-                       );
-
+               );
+       }
 
        for (i=0; !IsEmptyStr(&suser[i]); ++i) {
                suser[i] = tolower(suser[i]);
@@ -2096,7 +2039,7 @@ int CtdlOutputPreLoadedMsg(
        }
 
        if (mode == MT_RFC822) {
-               /* Construct a fun message id */
+               // Construct a fun message id
                cprintf("Message-ID: <%s", mid);
                if (strchr(mid, '@')==NULL) {
                        cprintf("@%s", snode);
@@ -2116,7 +2059,7 @@ int CtdlOutputPreLoadedMsg(
                        cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
                }
 
-               /* Blank line signifying RFC822 end-of-headers */
+               // Blank line signifying RFC822 end-of-headers
                if (TheMessage->cm_format_type != FMT_RFC822) {
                        cprintf("%s", nl);
                }
@@ -2203,7 +2146,7 @@ START_TEXT:
 
        }
 
-DONE:  /* now we're done */
+DONE:  // now we're done
        if (do_proto) cprintf("000\n");
        return(om_ok);
 }
@@ -2241,40 +2184,24 @@ int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newms
 
        strcpy(hold_rm, CC->room.QRname);
 
-       /* Sanity checks */
+       // Sanity checks
        if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
        if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
        if (num_newmsgs > 1) supplied_msg = NULL;
 
-       /* Now the regular stuff */
-       if (CtdlGetRoomLock(&CC->room,
-          ((roomname != NULL) ? roomname : CC->room.QRname) )
-          != 0) {
+       // Now the regular stuff
+       if (CtdlGetRoomLock(&CC->room, ((roomname != NULL) ? roomname : CC->room.QRname) ) != 0) {
                syslog(LOG_ERR, "msgbase: no such room <%s>", roomname);
                return(ERROR + ROOM_NOT_FOUND);
        }
 
-
        msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
        num_msgs_to_be_merged = 0;
+       num_msgs = CtdlFetchMsgList(CC->room.QRnumber, &msglist);
 
-
-       cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
-       if (cdbfr == NULL) {
-               msglist = NULL;
-               num_msgs = 0;
-       } else {
-               msglist = (long *) cdbfr->ptr;
-               cdbfr->ptr = NULL;      /* CtdlSaveMsgPointerInRoom() now owns this memory */
-               num_msgs = cdbfr->len / sizeof(long);
-               cdb_free(cdbfr);
-       }
-
-
-       /* Create a list of msgid's which were supplied by the caller, but do
-        * not already exist in the target room.  It is absolutely taboo to
-        * have more than one reference to the same message in a room.
-        */
+       // Create a list of msgid's which were supplied by the caller, but do
+       // not already exist in the target room.  It is absolutely taboo to
+       // have more than one reference to the same message in a room.
        for (i=0; i<num_newmsgs; ++i) {
                unique = 1;
                if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
@@ -2289,36 +2216,34 @@ int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newms
 
        syslog(LOG_DEBUG, "msgbase: %d unique messages to be merged", num_msgs_to_be_merged);
 
-       /*
-        * Now merge the new messages
-        */
+       // Now merge the new messages
        msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
        if (msglist == NULL) {
                syslog(LOG_ALERT, "msgbase: ERROR; can't realloc message list!");
                free(msgs_to_be_merged);
+               abort();                                        // FIXME
                return (ERROR + INTERNAL_ERROR);
        }
        memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
        num_msgs += num_msgs_to_be_merged;
 
-       /* Sort the message list, so all the msgid's are in order */
+       // Sort the message list, so all the msgid's are in order
        num_msgs = sort_msglist(msglist, num_msgs);
 
-       /* Determine the highest message number */
+       // Determine the highest message number
        highest_msg = msglist[num_msgs - 1];
 
-       /* Write it back to disk. */
-       cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
-                 msglist, (int)(num_msgs * sizeof(long)));
+       // Write it back to disk.
+       cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long), msglist, (int)(num_msgs * sizeof(long)));
 
-       /* Free up the memory we used. */
+       // Free up the memory we used.
        free(msglist);
 
-       /* Update the highest-message pointer and unlock the room. */
+       // Update the highest-message pointer and unlock the room.
        CC->room.QRhighest = highest_msg;
        CtdlPutRoomLock(&CC->room);
 
-       /* Perform replication checks if necessary */
+       // Perform replication checks if necessary
        if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
                syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() doing repl checks");
 
@@ -2335,12 +2260,12 @@ int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newms
                        if (msg != NULL) {
                                ReplicationChecks(msg);
                
-                               /* If the message has an Exclusive ID, index that... */
+                               // If the message has an Exclusive ID, index that...
                                if (!CM_IsEmpty(msg, eExclusiveID)) {
                                        index_message_by_euid(msg->cm_fields[eExclusiveID], &CC->room, msgid);
                                }
 
-                               /* Free up the memory we may have allocated */
+                               // Free up the memory we may have allocated
                                if (msg != supplied_msg) {
                                        CM_Free(msg);
                                }
@@ -2353,49 +2278,41 @@ int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newms
                syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() skips repl checks");
        }
 
-       /* Submit this room for processing by hooks */
+       // Submit this room for processing by hooks
        int total_roomhook_errors = PerformRoomHooks(&CC->room);
        if (total_roomhook_errors) {
                syslog(LOG_WARNING, "msgbase: room hooks returned %d errors", total_roomhook_errors);
        }
 
-       /* Go back to the room we were in before we wandered here... */
+       // Go back to the room we were in before we wandered here...
        CtdlGetRoom(&CC->room, hold_rm);
 
-       /* Bump the reference count for all messages which were merged */
+       // Bump the reference count for all messages which were merged
        if (!suppress_refcount_adj) {
                AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
        }
 
-       /* Free up memory... */
+       // Free up memory...
        if (msgs_to_be_merged != NULL) {
                free(msgs_to_be_merged);
        }
 
-       /* Return success. */
+       // Return success.
        return (0);
 }
 
 
-/*
- * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
- * a single message.
- */
-int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
-                            int do_repl_check, struct CtdlMessage *supplied_msg)
-{
+// This is the same as CtdlSaveMsgPointersInRoom() but it only accepts a single message.
+int CtdlSaveMsgPointerInRoom(char *roomname, long msgid, int do_repl_check, struct CtdlMessage *supplied_msg) {
        return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
 }
 
 
-/*
- * Message base operation to save a new message to the message store
- * (returns new message number)
- *
- * This is the back end for CtdlSubmitMsg() and should not be directly
- * called by server-side modules.
- *
- */
+// Message base operation to save a new message to the message store
+// (returns new message number)
+//
+// This is the back end for CtdlSubmitMsg() and should not be directly
+// called by server-side modules.
 long CtdlSaveThisMessage(struct CtdlMessage *msg, long msgid, int Reply) {
        long retval;
        struct ser_ret smr;
@@ -2403,10 +2320,7 @@ long CtdlSaveThisMessage(struct CtdlMessage *msg, long msgid, int Reply) {
        char *holdM = NULL;
        long holdMLen = 0;
 
-       /*
-        * If the message is big, set its body aside for storage elsewhere
-        * and we hide the message body from the serializer
-        */
+       // If the message is big, set its body aside for storage elsewhere and we hide the message body from the serializer
        if (!CM_IsEmpty(msg, eMesageText) && msg->cm_lengths[eMesageText] > BIGMSG) {
                is_bigmsg = 1;
                holdM = msg->cm_fields[eMesageText];
@@ -2415,49 +2329,41 @@ long CtdlSaveThisMessage(struct CtdlMessage *msg, long msgid, int Reply) {
                msg->cm_lengths[eMesageText] = 0;
        }
 
-       /* Serialize our data structure for storage in the database */  
+       // Serialize our data structure for storage in the database
        CtdlSerializeMessage(&smr, msg);
 
        if (is_bigmsg) {
-               /* put the message body back into the message */
+               // put the message body back into the message
                msg->cm_fields[eMesageText] = holdM;
                msg->cm_lengths[eMesageText] = holdMLen;
        }
 
        if (smr.len == 0) {
                if (Reply) {
-                       cprintf("%d Unable to serialize message\n",
-                               ERROR + INTERNAL_ERROR);
+                       cprintf("%d Unable to serialize message\n", ERROR + INTERNAL_ERROR);
                }
                else {
                        syslog(LOG_ERR, "msgbase: CtdlSaveMessage() unable to serialize message");
-
                }
                return (-1L);
        }
 
-       /* Write our little bundle of joy into the message base */
+       // Write our little bundle of joy into the message base
        retval = cdb_store(CDB_MSGMAIN, &msgid, (int)sizeof(long), smr.ser, smr.len);
        if (retval < 0) {
                syslog(LOG_ERR, "msgbase: can't store message %ld: %ld", msgid, retval);
        }
        else {
                if (is_bigmsg) {
-                       retval = cdb_store(CDB_BIGMSGS,
-                                          &msgid,
-                                          (int)sizeof(long),
-                                          holdM,
-                                          (holdMLen + 1)
-                               );
+                       retval = cdb_store(CDB_BIGMSGS, &msgid, (int)sizeof(long), holdM, (holdMLen + 1));
                        if (retval < 0) {
                                syslog(LOG_ERR, "msgbase: failed to store message body for msgid %ld: %ld", msgid, retval);
                        }
                }
        }
 
-       /* Free the memory we used for the serialized message */
+       // Free the memory we used for the serialized message
        free(smr.ser);
-
        return(retval);
 }
 
@@ -2468,18 +2374,17 @@ long send_message(struct CtdlMessage *msg) {
        char msgidbuf[256];
        long msgidbuflen;
 
-       /* Get a new message number */
+       // Get a new message number
        newmsgid = get_new_message_number();
 
-       /* Generate an ID if we don't have one already */
+       // Generate an ID if we don't have one already
        if (CM_IsEmpty(msg, emessageId)) {
                msgidbuflen = snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
-                                      (long unsigned int) time(NULL),
-                                      (long unsigned int) newmsgid,
-                                      CtdlGetConfigStr("c_fqdn")
-                       );
-
-               CM_SetField(msg, emessageId, msgidbuf, msgidbuflen);
+                      (long unsigned int) time(NULL),
+                      (long unsigned int) newmsgid,
+                      CtdlGetConfigStr("c_fqdn")
+               );
+               CM_SetField(msg, emessageId, msgidbuf);
        }
 
        retval = CtdlSaveThisMessage(msg, newmsgid, 1);
@@ -2488,29 +2393,23 @@ long send_message(struct CtdlMessage *msg) {
                retval = newmsgid;
        }
 
-       /* Return the *local* message ID to the caller
-        * (even if we're storing an incoming network message)
-        */
+       // Return the *local* message ID to the caller (even if we're storing a remotely originated message)
        return(retval);
 }
 
 
-/*
- * Serialize a struct CtdlMessage into the format used on disk.
- * 
- * 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 CtdlSerializeMessage(struct ser_ret *ret,         /* return values */
-                         struct CtdlMessage *msg)      /* unserialized msg */
+// Serialize a struct CtdlMessage into the format used on disk.
+// 
+// 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 CtdlSerializeMessage(struct ser_ret *ret,         // return values
+                         struct CtdlMessage *msg)      // unserialized msg
 {
        size_t wlen;
        int i;
 
-       /*
-        * Check for valid message format
-        */
+       // Check for valid message format
        if (CM_IsValidMsg(msg) == 0) {
                syslog(LOG_ERR, "msgbase: CtdlSerializeMessage() aborting due to invalid message");
                ret->len = 0;
@@ -2628,7 +2527,7 @@ long CtdlSubmitMsg(struct CtdlMessage *msg,       /* message to save */
                        }
                }
                else {
-                       CM_SetField(msg, eMessagePath, HKEY("unknown"));
+                       CM_SetField(msg, eMessagePath, "unknown");
                }
        }
 
@@ -2658,7 +2557,7 @@ long CtdlSubmitMsg(struct CtdlMessage *msg,       /* message to save */
                if (mptr != NULL) {
                        char *aptr;
                        safestrncpy(content_type, &mptr[13], sizeof content_type);
-                       striplt(content_type);
+                       string_trim(content_type);
                        aptr = content_type;
                        while (!IsEmptyStr(aptr)) {
                                if ((*aptr == ';')
@@ -2704,7 +2603,7 @@ long CtdlSubmitMsg(struct CtdlMessage *msg,       /* message to save */
         * If this message has no O (room) field, generate one.
         */
        if (CM_IsEmpty(msg, eOriginalRoom) && !IsEmptyStr(CC->room.QRname)) {
-               CM_SetField(msg, eOriginalRoom, CC->room.QRname, -1);
+               CM_SetField(msg, eOriginalRoom, CC->room.QRname);
        }
 
        /* Perform "before save" hooks (aborting if any return nonzero) */
@@ -2746,7 +2645,7 @@ long CtdlSubmitMsg(struct CtdlMessage *msg,       /* message to save */
         */
        if (CC->redirect_buffer != NULL) {
                syslog(LOG_ALERT, "msgbase: CC->redirect_buffer is not NULL during message submission!");
-               abort();
+               exit(CTDLEXIT_REDIRECT);
        }
        CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
        CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
@@ -2784,12 +2683,6 @@ long CtdlSubmitMsg(struct CtdlMessage *msg,      /* message to save */
                }
        }
 
-       /* Bump this user's messages posted counter. */
-       syslog(LOG_DEBUG, "msgbase: updating user");
-       CtdlLockGetCurrentUser();
-       CC->user.posted = CC->user.posted + 1;
-       CtdlPutCurrentUserLock();
-
        /* Decide where bounces need to be delivered */
        if ((recps != NULL) && (recps->bounce_to == NULL)) {
                if (CC->logged_in) {
@@ -2803,9 +2696,7 @@ long CtdlSubmitMsg(struct CtdlMessage *msg,       /* message to save */
                
        CM_SetFieldLONG(msg, eVltMsgNum, newmsgid);
 
-       /* If this is private, local mail, make a copy in the
-        * recipient's mailbox and bump the reference count.
-        */
+       // If this is private, local mail, make a copy in the recipient's mailbox and bump the reference count.
        if ((recps != NULL) && (recps->num_local > 0)) {
                char *pch;
                int ntokens;
@@ -2819,7 +2710,7 @@ long CtdlSubmitMsg(struct CtdlMessage *msg,       /* message to save */
                        if (CtdlGetUser(&userbuf, recipient) == 0) {
                                CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
                                CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
-                               CtdlBumpNewMailCounter(userbuf.usernum);
+                               CtdlBumpNewMailCounter(userbuf.usernum);        // if this user is logged in, tell them they have new mail.
                                PerformMessageHooks(msg, recps, EVT_AFTERUSRMBOXSAVE);
                        }
                        else {
@@ -2921,11 +2812,11 @@ long quickie_message(char *from,
        msg->cm_format_type = format_type;
 
        if (!IsEmptyStr(from)) {
-               CM_SetField(msg, eAuthor, from, -1);
+               CM_SetField(msg, eAuthor, from);
        }
        else if (!IsEmptyStr(fromaddr)) {
                char *pAt;
-               CM_SetField(msg, eAuthor, fromaddr, -1);
+               CM_SetField(msg, eAuthor, fromaddr);
                pAt = strchr(msg->cm_fields[eAuthor], '@');
                if (pAt != NULL) {
                        CM_CutFieldAt(msg, eAuthor, pAt - msg->cm_fields[eAuthor]);
@@ -2935,17 +2826,17 @@ long quickie_message(char *from,
                msg->cm_fields[eAuthor] = strdup("Citadel");
        }
 
-       if (!IsEmptyStr(fromaddr)) CM_SetField(msg, erFc822Addr, fromaddr, -1);
-       if (!IsEmptyStr(room)) CM_SetField(msg, eOriginalRoom, room, -1);
+       if (!IsEmptyStr(fromaddr)) CM_SetField(msg, erFc822Addr, fromaddr);
+       if (!IsEmptyStr(room)) CM_SetField(msg, eOriginalRoom, room);
        if (!IsEmptyStr(to)) {
-               CM_SetField(msg, eRecipient, to, -1);
+               CM_SetField(msg, eRecipient, to);
                recp = validate_recipients(to, NULL, 0);
        }
        if (!IsEmptyStr(subject)) {
-               CM_SetField(msg, eMsgSubject, subject, -1);
+               CM_SetField(msg, eMsgSubject, subject);
        }
        if (!IsEmptyStr(text)) {
-               CM_SetField(msg, eMesageText, text, -1);
+               CM_SetField(msg, eMesageText, text);
        }
 
        long msgnum = CtdlSubmitMsg(msg, recp, room);
@@ -3128,20 +3019,20 @@ struct CtdlMessage *CtdlMakeMessageLen(
        msg->cm_anon_type = type;
        msg->cm_format_type = format_type;
 
-       if (recipient != NULL) rcplen = striplt(recipient);
-       if (recp_cc != NULL) cclen = striplt(recp_cc);
+       if (recipient != NULL) rcplen = string_trim(recipient);
+       if (recp_cc != NULL) cclen = string_trim(recp_cc);
 
        /* Path or Return-Path */
        if (myelen > 0) {
-               CM_SetField(msg, eMessagePath, my_email, myelen);
+               CM_SetField(msg, eMessagePath, my_email);
        }
        else if (!IsEmptyStr(author->fullname)) {
-               CM_SetField(msg, eMessagePath, author->fullname, -1);
+               CM_SetField(msg, eMessagePath, author->fullname);
        }
        convert_spaces_to_underscores(msg->cm_fields[eMessagePath]);
 
        blen = snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
-       CM_SetField(msg, eTimestamp, buf, blen);
+       CM_SetField(msg, eTimestamp, buf);
 
        if (fnlen > 0) {
                FakeAuthor = NewStrBufPlain (fake_name, fnlen);
@@ -3155,30 +3046,30 @@ struct CtdlMessage *CtdlMakeMessageLen(
 
        if (!!IsEmptyStr(CC->room.QRname)) {
                if (CC->room.QRflags & QR_MAILBOX) {            /* room */
-                       CM_SetField(msg, eOriginalRoom, &CC->room.QRname[11], -1);
+                       CM_SetField(msg, eOriginalRoom, &CC->room.QRname[11]);
                }
                else {
-                       CM_SetField(msg, eOriginalRoom, CC->room.QRname, -1);
+                       CM_SetField(msg, eOriginalRoom, CC->room.QRname);
                }
        }
 
        if (rcplen > 0) {
-               CM_SetField(msg, eRecipient, recipient, rcplen);
+               CM_SetField(msg, eRecipient, recipient);
        }
        if (cclen > 0) {
-               CM_SetField(msg, eCarbonCopY, recp_cc, cclen);
+               CM_SetField(msg, eCarbonCopY, recp_cc);
        }
 
        if (myelen > 0) {
-               CM_SetField(msg, erFc822Addr, my_email, myelen);
+               CM_SetField(msg, erFc822Addr, my_email);
        }
        else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
-               CM_SetField(msg, erFc822Addr, CC->cs_inet_email, -1);
+               CM_SetField(msg, erFc822Addr, CC->cs_inet_email);
        }
 
        if (subject != NULL) {
                long length;
-               length = striplt(subject);
+               length = string_trim(subject);
                if (length > 0) {
                        long i;
                        long IsAscii;
@@ -3188,7 +3079,7 @@ struct CtdlMessage *CtdlMakeMessageLen(
                               (IsAscii = isascii(subject[i]) != 0 ))
                                i++;
                        if (IsAscii != 0)
-                               CM_SetField(msg, eMsgSubject, subject, subjlen);
+                               CM_SetField(msg, eMsgSubject, subject);
                        else /* ok, we've got utf8 in the string. */
                        {
                                char *rfc2047Subj;
@@ -3200,15 +3091,15 @@ struct CtdlMessage *CtdlMakeMessageLen(
        }
 
        if (euidlen > 0) {
-               CM_SetField(msg, eExclusiveID, supplied_euid, euidlen);
+               CM_SetField(msg, eExclusiveID, supplied_euid);
        }
 
        if (reflen > 0) {
-               CM_SetField(msg, eWeferences, references, reflen);
+               CM_SetField(msg, eWeferences, references);
        }
 
        if (preformatted_text != NULL) {
-               CM_SetField(msg, eMesageText, preformatted_text, textlen);
+               CM_SetField(msg, eMesageText, preformatted_text);
        }
        else {
                StrBuf *MsgBody;
@@ -3256,33 +3147,20 @@ int CtdlDeleteMessages(const char *room_name,   // which room
                if (need_to_free_re) regfree(&re);
                return(0);      /* room not found */
        }
-       cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
 
-       if (cdbfr != NULL) {
-               dellist = malloc(cdbfr->len);
-               msglist = (long *) cdbfr->ptr;
-               cdbfr->ptr = NULL;      /* CtdlDeleteMessages() now owns this memory */
-               num_msgs = cdbfr->len / sizeof(long);
-               cdb_free(cdbfr);
-       }
+       num_msgs = CtdlFetchMsgList(qrbuf.QRnumber, &msglist);
        if (num_msgs > 0) {
+               dellist = malloc(num_msgs * sizeof(long));
                int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
                int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
                int have_more_del = 1;
 
                num_msgs = sort_msglist(msglist, num_msgs);
-               if (num_dmsgnums > 1)
+               if (num_dmsgnums > 1) {
                        num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
-/*
-               {
-                       StrBuf *dbg = NewStrBuf();
-                       for (i = 0; i < num_dmsgnums; i++)
-                               StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
-                       syslog(LOG_DEBUG, "msgbase: Deleting before: %s", ChrPtr(dbg));
-                       FreeStrBuf(&dbg);
                }
-*/
-               i = 0; j = 0;
+               i = 0;
+               j = 0;
                while ((i < num_msgs) && (have_more_del)) {
                        delete_this = 0x00;
 
@@ -3323,23 +3201,16 @@ int CtdlDeleteMessages(const char *room_name,   // which room
                        }
                        i++;
                }
-/*
-               {
-                       StrBuf *dbg = NewStrBuf();
-                       for (i = 0; i < num_deleted; i++)
-                               StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
-                       syslog(LOG_DEBUG, "msgbase: Deleting: %s", ChrPtr(dbg));
-                       FreeStrBuf(&dbg);
-               }
-*/
+
                num_msgs = sort_msglist(msglist, num_msgs);
-               cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
-                         msglist, (int)(num_msgs * sizeof(long)));
+               cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long), msglist, (int)(num_msgs * sizeof(long)));
 
-               if (num_msgs > 0)
+               if (num_msgs > 0) {
                        qrbuf.QRhighest = msglist[num_msgs - 1];
-               else
+               }
+               else {
                        qrbuf.QRhighest = 0;
+               }
        }
        CtdlPutRoomLock(&qrbuf);
 
@@ -3369,9 +3240,8 @@ int CtdlDeleteMessages(const char *room_name,     // which room
 /*
  * GetMetaData()  -  Get the supplementary record for a message
  */
-void GetMetaData(struct MetaData *smibuf, long msgnum)
-{
-       struct cdbdata *cdbsmi;
+void GetMetaData(struct MetaData *smibuf, long msgnum) {
+       struct cdbdata cdbsmi;
        long TheIndex;
 
        memset(smibuf, 0, sizeof(struct MetaData));
@@ -3382,14 +3252,10 @@ void GetMetaData(struct MetaData *smibuf, long msgnum)
        TheIndex = (0L - msgnum);
 
        cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
-       if (cdbsmi == NULL) {
+       if (cdbsmi.ptr == NULL) {
                return;                 /* record not found; leave it alone */
        }
-       memcpy(smibuf, cdbsmi->ptr,
-              ((cdbsmi->len > sizeof(struct MetaData)) ?
-               sizeof(struct MetaData) : cdbsmi->len)
-       );
-       cdb_free(cdbsmi);
+       memcpy(smibuf, cdbsmi.ptr, ((cdbsmi.len > sizeof(struct MetaData)) ? sizeof(struct MetaData) : cdbsmi.len));
        return;
 }
 
@@ -3411,11 +3277,8 @@ void PutMetaData(struct MetaData *smibuf)
 }
 
 
-/*
- * Convenience function to process a big block of AdjRefCount() operations
- */
-void AdjRefCountList(long *msgnum, long nmsg, int incr)
-{
+// Convenience function to process a big block of AdjRefCount() operations
+void AdjRefCountList(long *msgnum, long nmsg, int incr) {
        long i;
 
        for (i = 0; i < nmsg; i++) {
@@ -3424,18 +3287,15 @@ void AdjRefCountList(long *msgnum, long nmsg, int incr)
 }
 
 
-/*
- * AdjRefCount - adjust the reference count for a message.  We need to delete from disk any message whose reference count reaches zero.
- */
-void AdjRefCount(long msgnum, int incr)
-{
+// AdjRefCount - adjust the reference count for a message.
+// We need to delete from disk any message whose reference count reaches zero.
+void AdjRefCount(long msgnum, int incr) {
        struct MetaData smi;
        long delnum;
 
-       /* This is a *tight* critical section; please keep it that way, as
-        * it may get called while nested in other critical sections.  
-        * Complicating this any further will surely cause deadlock!
-        */
+       // This is a *tight* critical section; please keep it that way, as
+       // it may get called while nested in other critical sections.  
+       // Complicating this any further will surely cause deadlock!
        begin_critical_section(S_SUPPMSGMAIN);
        GetMetaData(&smi, msgnum);
        smi.meta_refcount += incr;
@@ -3443,38 +3303,34 @@ void AdjRefCount(long msgnum, int incr)
        end_critical_section(S_SUPPMSGMAIN);
        syslog(LOG_DEBUG, "msgbase: AdjRefCount() msg %ld ref count delta %+d, is now %d", msgnum, incr, smi.meta_refcount);
 
-       /* If the reference count is now zero, delete both the message and its metadata record.
-        */
+       // If the reference count is now zero, delete both the message and its metadata record.
        if (smi.meta_refcount == 0) {
                syslog(LOG_DEBUG, "msgbase: deleting message <%ld>", msgnum);
                
-               /* Call delete hooks with NULL room to show it has gone altogether */
+               // Call delete hooks with NULL room to show it has gone altogether
                PerformDeleteHooks(NULL, msgnum);
 
-               /* Remove from message base */
+               // Remove from message base
                delnum = msgnum;
                cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
-               cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
+               cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));    // There might not be a bigmsgs.  Not an error.
 
-               /* Remove metadata record */
+               // Remove metadata record
                delnum = (0L - msgnum);
                cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
        }
 }
 
 
-/*
- * Write a generic object to this room
- *
- * Returns the message number of the written object, in case you need it.
- */
-long CtdlWriteObject(char *req_room,                   /* Room to stuff it in */
-                    char *content_type,                /* MIME type of this object */
-                    char *raw_message,                 /* Data to be written */
-                    off_t raw_length,                  /* Size of raw_message */
-                    struct ctdluser *is_mailbox,       /* Mailbox room? */
-                    int is_binary,                     /* Is encoding necessary? */
-                    unsigned int flags                 /* Internal save flags */
+// Write a generic object to this room
+// Returns the message number of the written object, in case you need it.
+long CtdlWriteObject(char *req_room,                   // Room to stuff it in
+                    char *content_type,                // MIME type of this object
+                    char *raw_message,                 // Data to be written
+                    off_t raw_length,                  // Size of raw_message
+                    struct ctdluser *is_mailbox,       // Mailbox room?
+                    int is_binary,                     // Is encoding necessary?
+                    unsigned int flags                 // Internal save flags
 ) {
        struct ctdlroom qrbuf;
        char roomname[ROOMNAMELEN];
@@ -3521,8 +3377,8 @@ long CtdlWriteObject(char *req_room,                      /* Room to stuff it in */
        msg->cm_magic = CTDLMESSAGE_MAGIC;
        msg->cm_anon_type = MES_NORMAL;
        msg->cm_format_type = 4;
-       CM_SetField(msg, eAuthor, CC->user.fullname, -1);
-       CM_SetField(msg, eOriginalRoom, req_room, -1);
+       CM_SetField(msg, eAuthor, CC->user.fullname);
+       CM_SetField(msg, eOriginalRoom, req_room);
        msg->cm_flags = flags;
        
        CM_SetAsFieldSB(msg, eMesageText, &encoded_message);