1 // Implements the message store.
3 // Copyright (c) 1987-2022 by the citadel.org team
5 // This program is open source software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License version 3.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
20 #include <libcitadel.h>
21 #include "ctdl_module.h"
22 #include "citserver.h"
25 #include "clientsocket.h"
29 #include "internet_addressing.h"
30 #include "euidindex.h"
32 #include "journaling.h"
34 struct addresses_to_be_filed *atbf = NULL;
36 // These are the four-character field headers we use when outputting
37 // messages in Citadel format (as opposed to RFC822 format).
39 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
40 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
41 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
42 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
43 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
44 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
45 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
46 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
48 "from", // A -> eAuthor
49 NULL, // B -> eBig_message
50 NULL, // C (formerly used as eRemoteRoom)
51 NULL, // D (formerly used as eDestination)
52 "exti", // E -> eXclusivID
53 "rfca", // F -> erFc822Addr
55 "hnod", // H (formerly used as eHumanNode)
56 "msgn", // I -> emessageId
57 "jrnl", // J -> eJournal
58 "rep2", // K -> eReplyTo
59 "list", // L -> eListID
60 "text", // M -> eMesageText
61 NULL, // N (formerly used as eNodename)
62 "room", // O -> eOriginalRoom
63 "path", // P -> eMessagePath
65 "rcpt", // R -> eRecipient
66 NULL, // S (formerly used as eSpecialField)
67 "time", // T -> eTimestamp
68 "subj", // U -> eMsgSubject
69 "nvto", // V -> eenVelopeTo
70 "wefw", // W -> eWeferences
72 "cccc", // Y -> eCarbonCopY
77 HashList *msgKeyLookup = NULL;
79 int GetFieldFromMnemonic(eMsgField *f, const char* c) {
81 if (GetHash(msgKeyLookup, c, 4, &v)) {
88 void FillMsgKeyLookupTable(void) {
91 msgKeyLookup = NewHash (1, FourHash);
93 for (i=0; i < 91; i++) {
94 if (msgkeys[i] != NULL) {
95 Put(msgKeyLookup, msgkeys[i], 4, (void*)i, reference_free_handler);
101 eMsgField FieldOrder[] = {
102 /* Important fields */
110 /* Semi-important fields */
115 /* G is not used yet */
118 /* Q is not used yet */
120 /* X is not used yet */
121 /* Z is not used yet */
128 /* Message text (MUST be last) */
130 /* Not saved to disk:
135 static const long NDiskFields = sizeof(FieldOrder) / sizeof(eMsgField);
138 int CM_IsEmpty(struct CtdlMessage *Msg, eMsgField which) {
139 return !((Msg->cm_fields[which] != NULL) && (Msg->cm_fields[which][0] != '\0'));
143 void CM_SetField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length) {
144 if (Msg->cm_fields[which] != NULL) {
145 free (Msg->cm_fields[which]);
147 if (length < 0) { // You can set the length to -1 to have CM_SetField measure it for you
148 length = strlen(buf);
150 Msg->cm_fields[which] = malloc(length + 1);
151 memcpy(Msg->cm_fields[which], buf, length);
152 Msg->cm_fields[which][length] = '\0';
153 Msg->cm_lengths[which] = length;
157 void CM_SetFieldLONG(struct CtdlMessage *Msg, eMsgField which, long lvalue) {
160 len = snprintf(buf, sizeof(buf), "%ld", lvalue);
161 CM_SetField(Msg, which, buf, len);
165 void CM_CutFieldAt(struct CtdlMessage *Msg, eMsgField WhichToCut, long maxlen) {
166 if (Msg->cm_fields[WhichToCut] == NULL)
169 if (Msg->cm_lengths[WhichToCut] > maxlen)
171 Msg->cm_fields[WhichToCut][maxlen] = '\0';
172 Msg->cm_lengths[WhichToCut] = maxlen;
177 void CM_FlushField(struct CtdlMessage *Msg, eMsgField which) {
178 if (Msg->cm_fields[which] != NULL)
179 free (Msg->cm_fields[which]);
180 Msg->cm_fields[which] = NULL;
181 Msg->cm_lengths[which] = 0;
185 void CM_Flush(struct CtdlMessage *Msg) {
188 if (CM_IsValidMsg(Msg) == 0) {
192 for (i = 0; i < 256; ++i) {
193 CM_FlushField(Msg, i);
198 void CM_CopyField(struct CtdlMessage *Msg, eMsgField WhichToPutTo, eMsgField WhichtToCopy) {
200 if (Msg->cm_fields[WhichToPutTo] != NULL) {
201 free (Msg->cm_fields[WhichToPutTo]);
204 if (Msg->cm_fields[WhichtToCopy] != NULL) {
205 len = Msg->cm_lengths[WhichtToCopy];
206 Msg->cm_fields[WhichToPutTo] = malloc(len + 1);
207 memcpy(Msg->cm_fields[WhichToPutTo], Msg->cm_fields[WhichtToCopy], len);
208 Msg->cm_fields[WhichToPutTo][len] = '\0';
209 Msg->cm_lengths[WhichToPutTo] = len;
212 Msg->cm_fields[WhichToPutTo] = NULL;
213 Msg->cm_lengths[WhichToPutTo] = 0;
218 void CM_PrependToField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length) {
219 if (Msg->cm_fields[which] != NULL) {
224 oldmsgsize = Msg->cm_lengths[which] + 1;
225 newmsgsize = length + oldmsgsize;
227 new = malloc(newmsgsize);
228 memcpy(new, buf, length);
229 memcpy(new + length, Msg->cm_fields[which], oldmsgsize);
230 free(Msg->cm_fields[which]);
231 Msg->cm_fields[which] = new;
232 Msg->cm_lengths[which] = newmsgsize - 1;
235 Msg->cm_fields[which] = malloc(length + 1);
236 memcpy(Msg->cm_fields[which], buf, length);
237 Msg->cm_fields[which][length] = '\0';
238 Msg->cm_lengths[which] = length;
243 void CM_SetAsField(struct CtdlMessage *Msg, eMsgField which, char **buf, long length) {
244 if (Msg->cm_fields[which] != NULL) {
245 free (Msg->cm_fields[which]);
248 Msg->cm_fields[which] = *buf;
250 if (length < 0) { // You can set the length to -1 to have CM_SetField measure it for you
251 Msg->cm_lengths[which] = strlen(Msg->cm_fields[which]);
254 Msg->cm_lengths[which] = length;
259 void CM_SetAsFieldSB(struct CtdlMessage *Msg, eMsgField which, StrBuf **buf) {
260 if (Msg->cm_fields[which] != NULL) {
261 free (Msg->cm_fields[which]);
264 Msg->cm_lengths[which] = StrLength(*buf);
265 Msg->cm_fields[which] = SmashStrBuf(buf);
269 void CM_GetAsField(struct CtdlMessage *Msg, eMsgField which, char **ret, long *retlen) {
270 if (Msg->cm_fields[which] != NULL) {
271 *retlen = Msg->cm_lengths[which];
272 *ret = Msg->cm_fields[which];
273 Msg->cm_fields[which] = NULL;
274 Msg->cm_lengths[which] = 0;
283 // Returns 1 if the supplied pointer points to a valid Citadel message.
284 // If the pointer is NULL or the magic number check fails, returns 0.
285 int CM_IsValidMsg(struct CtdlMessage *msg) {
289 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
290 syslog(LOG_WARNING, "msgbase: CM_IsValidMsg() self-check failed");
297 void CM_FreeContents(struct CtdlMessage *msg) {
300 for (i = 0; i < 256; ++i)
301 if (msg->cm_fields[i] != NULL) {
302 free(msg->cm_fields[i]);
303 msg->cm_lengths[i] = 0;
306 msg->cm_magic = 0; // just in case
310 // 'Destructor' for struct CtdlMessage
311 void CM_Free(struct CtdlMessage *msg) {
312 if (CM_IsValidMsg(msg) == 0) {
313 if (msg != NULL) free (msg);
316 CM_FreeContents(msg);
321 int CM_DupField(eMsgField i, struct CtdlMessage *OrgMsg, struct CtdlMessage *NewMsg) {
323 len = OrgMsg->cm_lengths[i];
324 NewMsg->cm_fields[i] = malloc(len + 1);
325 if (NewMsg->cm_fields[i] == NULL) {
328 memcpy(NewMsg->cm_fields[i], OrgMsg->cm_fields[i], len);
329 NewMsg->cm_fields[i][len] = '\0';
330 NewMsg->cm_lengths[i] = len;
335 struct CtdlMessage *CM_Duplicate(struct CtdlMessage *OrgMsg) {
337 struct CtdlMessage *NewMsg;
339 if (CM_IsValidMsg(OrgMsg) == 0) {
342 NewMsg = (struct CtdlMessage *)malloc(sizeof(struct CtdlMessage));
343 if (NewMsg == NULL) {
347 memcpy(NewMsg, OrgMsg, sizeof(struct CtdlMessage));
349 memset(&NewMsg->cm_fields, 0, sizeof(char*) * 256);
351 for (i = 0; i < 256; ++i) {
352 if (OrgMsg->cm_fields[i] != NULL) {
353 if (!CM_DupField(i, OrgMsg, NewMsg)) {
364 // Determine if a given message matches the fields in a message template.
365 // Return 0 for a successful match.
366 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
369 // If there aren't any fields in the template, all messages will match.
370 if (template == NULL) return(0);
372 // Null messages are bogus.
373 if (msg == NULL) return(1);
375 for (i='A'; i<='Z'; ++i) {
376 if (template->cm_fields[i] != NULL) {
377 if (msg->cm_fields[i] == NULL) {
378 // Considered equal if temmplate is empty string
379 if (IsEmptyStr(template->cm_fields[i])) continue;
382 if ((template->cm_lengths[i] != msg->cm_lengths[i]) ||
383 (strcasecmp(msg->cm_fields[i], template->cm_fields[i])))
388 // All compares succeeded: we have a match!
393 // Retrieve the "seen" message list for the current room.
394 void CtdlGetSeen(char *buf, int which_set) {
397 // Learn about the user and room in question
398 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
400 if (which_set == ctdlsetseen_seen) {
401 safestrncpy(buf, vbuf.v_seen, SIZ);
403 if (which_set == ctdlsetseen_answered) {
404 safestrncpy(buf, vbuf.v_answered, SIZ);
409 // Manipulate the "seen msgs" string (or other message set strings)
410 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
411 int target_setting, int which_set,
412 struct ctdluser *which_user, struct ctdlroom *which_room) {
413 struct cdbdata *cdbfr;
427 char *is_set; // actually an array of booleans
429 // Don't bother doing *anything* if we were passed a list of zero messages
430 if (num_target_msgnums < 1) {
434 // If no room was specified, we go with the current room.
436 which_room = &CC->room;
439 // If no user was specified, we go with the current user.
441 which_user = &CC->user;
444 syslog(LOG_DEBUG, "msgbase: CtdlSetSeen(%d msgs starting with %ld, %s, %d) in <%s>",
445 num_target_msgnums, target_msgnums[0],
446 (target_setting ? "SET" : "CLEAR"),
450 // Learn about the user and room in question
451 CtdlGetRelationship(&vbuf, which_user, which_room);
453 // Load the message list
454 cdbfr = cdb_fetch(CDB_MSGLISTS, &which_room->QRnumber, sizeof(long));
456 msglist = (long *) cdbfr->ptr;
457 cdbfr->ptr = NULL; // CtdlSetSeen() now owns this memory
458 num_msgs = cdbfr->len / sizeof(long);
462 return; // No messages at all? No further action.
465 is_set = malloc(num_msgs * sizeof(char));
466 memset(is_set, 0, (num_msgs * sizeof(char)) );
468 // Decide which message set we're manipulating
470 case ctdlsetseen_seen:
471 vset = NewStrBufPlain(vbuf.v_seen, -1);
473 case ctdlsetseen_answered:
474 vset = NewStrBufPlain(vbuf.v_answered, -1);
481 #if 0 // This is a special diagnostic section. Do not allow it to run during normal operation.
482 syslog(LOG_DEBUG, "There are %d messages in the room.\n", num_msgs);
483 for (i=0; i<num_msgs; ++i) {
484 if ((i > 0) && (msglist[i] <= msglist[i-1])) abort();
486 syslog(LOG_DEBUG, "We are twiddling %d of them.\n", num_target_msgnums);
487 for (k=0; k<num_target_msgnums; ++k) {
488 if ((k > 0) && (target_msgnums[k] <= target_msgnums[k-1])) abort();
492 // Translate the existing sequence set into an array of booleans
493 setstr = NewStrBuf();
497 while (StrBufExtract_NextToken(setstr, vset, &pvset, ',') >= 0) {
499 StrBufExtract_token(lostr, setstr, 0, ':');
500 if (StrBufNum_tokens(setstr, ':') >= 2) {
501 StrBufExtract_token(histr, setstr, 1, ':');
505 StrBufAppendBuf(histr, lostr, 0);
508 if (!strcmp(ChrPtr(histr), "*")) {
515 for (i = 0; i < num_msgs; ++i) {
516 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
525 // Now translate the array of booleans back into a sequence set
531 for (i=0; i<num_msgs; ++i) {
535 for (k=0; k<num_target_msgnums; ++k) {
536 if (msglist[i] == target_msgnums[k]) {
537 is_seen = target_setting;
541 if ((was_seen == 0) && (is_seen == 1)) {
544 else if ((was_seen == 1) && (is_seen == 0)) {
547 if (StrLength(vset) > 0) {
548 StrBufAppendBufPlain(vset, HKEY(","), 0);
551 StrBufAppendPrintf(vset, "%ld", hi);
554 StrBufAppendPrintf(vset, "%ld:%ld", lo, hi);
558 if ((is_seen) && (i == num_msgs - 1)) {
559 if (StrLength(vset) > 0) {
560 StrBufAppendBufPlain(vset, HKEY(","), 0);
562 if ((i==0) || (was_seen == 0)) {
563 StrBufAppendPrintf(vset, "%ld", msglist[i]);
566 StrBufAppendPrintf(vset, "%ld:%ld", lo, msglist[i]);
573 // We will have to stuff this string back into a 4096 byte buffer, so if it's
574 // larger than that now, truncate it by removing tokens from the beginning.
575 // The limit of 100 iterations is there to prevent an infinite loop in case
576 // something unexpected happens.
577 int number_of_truncations = 0;
578 while ( (StrLength(vset) > SIZ) && (number_of_truncations < 100) ) {
579 StrBufRemove_token(vset, 0, ',');
580 ++number_of_truncations;
583 // If we're truncating the sequence set of messages marked with the 'seen' flag,
584 // we want the earliest messages (the truncated ones) to be marked, not unmarked.
585 // Otherwise messages at the beginning will suddenly appear to be 'unseen'.
586 if ( (which_set == ctdlsetseen_seen) && (number_of_truncations > 0) ) {
588 first_tok = NewStrBuf();
589 StrBufExtract_token(first_tok, vset, 0, ',');
590 StrBufRemove_token(vset, 0, ',');
592 if (StrBufNum_tokens(first_tok, ':') > 1) {
593 StrBufRemove_token(first_tok, 0, ':');
597 new_set = NewStrBuf();
598 StrBufAppendBufPlain(new_set, HKEY("1:"), 0);
599 StrBufAppendBuf(new_set, first_tok, 0);
600 StrBufAppendBufPlain(new_set, HKEY(":"), 0);
601 StrBufAppendBuf(new_set, vset, 0);
604 FreeStrBuf(&first_tok);
608 // Decide which message set we're manipulating
610 case ctdlsetseen_seen:
611 safestrncpy(vbuf.v_seen, ChrPtr(vset), sizeof vbuf.v_seen);
613 case ctdlsetseen_answered:
614 safestrncpy(vbuf.v_answered, ChrPtr(vset), sizeof vbuf.v_answered);
620 CtdlSetRelationship(&vbuf, which_user, which_room);
625 // API function to perform an operation for each qualifying message in the
626 // current room. (Returns the number of messages processed.)
627 int CtdlForEachMessage(int mode, long ref, char *search_string,
629 struct CtdlMessage *compare,
630 ForEachMsgCallback CallBack,
635 struct cdbdata *cdbfr;
636 long *msglist = NULL;
638 int num_processed = 0;
641 struct CtdlMessage *msg = NULL;
644 int printed_lastold = 0;
645 int num_search_msgs = 0;
646 long *search_msgs = NULL;
648 int need_to_free_re = 0;
651 if ((content_type) && (!IsEmptyStr(content_type))) {
652 regcomp(&re, content_type, 0);
656 // Learn about the user and room in question
657 if (server_shutting_down) {
658 if (need_to_free_re) regfree(&re);
661 CtdlGetUser(&CC->user, CC->curr_user);
663 if (server_shutting_down) {
664 if (need_to_free_re) regfree(&re);
667 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
669 if (server_shutting_down) {
670 if (need_to_free_re) regfree(&re);
674 // Load the message list
675 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
677 if (need_to_free_re) regfree(&re);
678 return 0; // No messages at all? No further action.
681 msglist = (long *) cdbfr->ptr;
682 num_msgs = cdbfr->len / sizeof(long);
684 cdbfr->ptr = NULL; // clear this so that cdb_free() doesn't free it
685 cdb_free(cdbfr); // we own this memory now
688 * Now begin the traversal.
690 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
692 /* If the caller is looking for a specific MIME type, filter
693 * out all messages which are not of the type requested.
695 if ((content_type != NULL) && (!IsEmptyStr(content_type))) {
697 /* This call to GetMetaData() sits inside this loop
698 * so that we only do the extra database read per msg
699 * if we need to. Doing the extra read all the time
700 * really kills the server. If we ever need to use
701 * metadata for another search criterion, we need to
702 * move the read somewhere else -- but still be smart
703 * enough to only do the read if the caller has
704 * specified something that will need it.
706 if (server_shutting_down) {
707 if (need_to_free_re) regfree(&re);
711 GetMetaData(&smi, msglist[a]);
713 /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
714 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
720 num_msgs = sort_msglist(msglist, num_msgs);
722 /* If a template was supplied, filter out the messages which
723 * don't match. (This could induce some delays!)
726 if (compare != NULL) {
727 for (a = 0; a < num_msgs; ++a) {
728 if (server_shutting_down) {
729 if (need_to_free_re) regfree(&re);
733 msg = CtdlFetchMessage(msglist[a], 1);
735 if (CtdlMsgCmp(msg, compare)) {
744 /* If a search string was specified, get a message list from
745 * the full text index and remove messages which aren't on both
749 * Since the lists are sorted and strictly ascending, and the
750 * output list is guaranteed to be shorter than or equal to the
751 * input list, we overwrite the bottom of the input list. This
752 * eliminates the need to memmove big chunks of the list over and
755 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
757 /* Call search module via hook mechanism.
758 * NULL means use any search function available.
759 * otherwise replace with a char * to name of search routine
761 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
763 if (num_search_msgs > 0) {
767 orig_num_msgs = num_msgs;
769 for (i=0; i<orig_num_msgs; ++i) {
770 for (j=0; j<num_search_msgs; ++j) {
771 if (msglist[i] == search_msgs[j]) {
772 msglist[num_msgs++] = msglist[i];
778 num_msgs = 0; /* No messages qualify */
780 if (search_msgs != NULL) free(search_msgs);
782 /* Now that we've purged messages which don't contain the search
783 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
790 * Now iterate through the message list, according to the
791 * criteria supplied by the caller.
794 for (a = 0; a < num_msgs; ++a) {
795 if (server_shutting_down) {
796 if (need_to_free_re) regfree(&re);
798 return num_processed;
800 thismsg = msglist[a];
801 if (mode == MSGS_ALL) {
805 is_seen = is_msg_in_sequence_set(vbuf.v_seen, thismsg);
806 if (is_seen) lastold = thismsg;
812 || ((mode == MSGS_OLD) && (is_seen))
813 || ((mode == MSGS_NEW) && (!is_seen))
814 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
815 || ((mode == MSGS_FIRST) && (a < ref))
816 || ((mode == MSGS_GT) && (thismsg > ref))
817 || ((mode == MSGS_LT) && (thismsg < ref))
818 || ((mode == MSGS_EQ) && (thismsg == ref))
821 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
823 CallBack(lastold, userdata);
829 CallBack(thismsg, userdata);
834 if (need_to_free_re) regfree(&re);
837 * We cache the most recent msglist in order to do security checks later
839 if (CC->client_socket > 0) {
840 if (CC->cached_msglist != NULL) {
841 free(CC->cached_msglist);
843 CC->cached_msglist = msglist;
844 CC->cached_num_msgs = num_msgs;
850 return num_processed;
855 * memfmout() - Citadel text formatter and paginator.
856 * Although the original purpose of this routine was to format
857 * text to the reader's screen width, all we're really using it
858 * for here is to format text out to 80 columns before sending it
859 * to the client. The client software may reformat it again.
862 char *mptr, /* where are we going to get our text from? */
863 const char *nl /* string to terminate lines with */
866 unsigned char ch = 0;
873 while (ch=*(mptr++), ch != 0) {
876 if (client_write(outbuf, len) == -1) {
877 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
881 if (client_write(nl, nllen) == -1) {
882 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
887 else if (ch == '\r') {
888 /* Ignore carriage returns. Newlines are always LF or CRLF but never CR. */
890 else if (isspace(ch)) {
891 if (column > 72) { /* Beyond 72 columns, break on the next space */
892 if (client_write(outbuf, len) == -1) {
893 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
897 if (client_write(nl, nllen) == -1) {
898 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
911 if (column > 1000) { /* Beyond 1000 columns, break anywhere */
912 if (client_write(outbuf, len) == -1) {
913 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
917 if (client_write(nl, nllen) == -1) {
918 syslog(LOG_ERR, "msgbase: memfmout(): aborting due to write failure");
926 if (client_write(outbuf, len) == -1) {
927 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
930 client_write(nl, nllen);
937 * Callback function for mime parser that simply lists the part
939 void list_this_part(char *name, char *filename, char *partnum, char *disp,
940 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
941 char *cbid, void *cbuserdata)
945 ma = (struct ma_info *)cbuserdata;
946 if (ma->is_ma == 0) {
947 cprintf("part=%s|%s|%s|%s|%s|%ld|%s|%s\n",
961 * Callback function for multipart prefix
963 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
964 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
965 char *cbid, void *cbuserdata)
969 ma = (struct ma_info *)cbuserdata;
970 if (!strcasecmp(cbtype, "multipart/alternative")) {
974 if (ma->is_ma == 0) {
975 cprintf("pref=%s|%s\n", partnum, cbtype);
981 * Callback function for multipart sufffix
983 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
984 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
985 char *cbid, void *cbuserdata)
989 ma = (struct ma_info *)cbuserdata;
990 if (ma->is_ma == 0) {
991 cprintf("suff=%s|%s\n", partnum, cbtype);
993 if (!strcasecmp(cbtype, "multipart/alternative")) {
1000 * Callback function for mime parser that opens a section for downloading
1001 * we use serv_files function here:
1003 extern void OpenCmdResult(char *filename, const char *mime_type);
1004 void mime_download(char *name, char *filename, char *partnum, char *disp,
1005 void *content, char *cbtype, char *cbcharset, size_t length,
1006 char *encoding, char *cbid, void *cbuserdata)
1010 /* Silently go away if there's already a download open. */
1011 if (CC->download_fp != NULL)
1015 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1016 || (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1018 CC->download_fp = tmpfile();
1019 if (CC->download_fp == NULL) {
1020 syslog(LOG_ERR, "msgbase: mime_download() couldn't write: %m");
1021 cprintf("%d cannot open temporary file: %s\n", ERROR + INTERNAL_ERROR, strerror(errno));
1025 rv = fwrite(content, length, 1, CC->download_fp);
1027 syslog(LOG_ERR, "msgbase: mime_download() Couldn't write: %m");
1028 cprintf("%d unable to write tempfile.\n", ERROR + TOO_BIG);
1029 fclose(CC->download_fp);
1030 CC->download_fp = NULL;
1033 fflush(CC->download_fp);
1034 rewind(CC->download_fp);
1036 OpenCmdResult(filename, cbtype);
1042 * Callback function for mime parser that outputs a section all at once.
1043 * We can specify the desired section by part number *or* content-id.
1045 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
1046 void *content, char *cbtype, char *cbcharset, size_t length,
1047 char *encoding, char *cbid, void *cbuserdata)
1049 int *found_it = (int *)cbuserdata;
1052 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1053 || (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1056 cprintf("%d %d|-1|%s|%s|%s\n",
1063 client_write(content, length);
1068 struct CtdlMessage *CtdlDeserializeMessage(long msgnum, int with_body, const char *Buffer, long Length) {
1069 struct CtdlMessage *ret = NULL;
1071 const char *upper_bound;
1073 cit_uint8_t field_header;
1077 upper_bound = Buffer + Length;
1082 // Parse the three bytes that begin EVERY message on disk.
1083 // The first is always 0xFF, the on-disk magic number.
1084 // The second is the anonymous/public type byte.
1085 // The third is the format type byte (vari, fixed, or MIME).
1089 syslog(LOG_ERR, "msgbase: message %ld appears to be corrupted", msgnum);
1092 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1093 memset(ret, 0, sizeof(struct CtdlMessage));
1095 ret->cm_magic = CTDLMESSAGE_MAGIC;
1096 ret->cm_anon_type = *mptr++; // Anon type byte
1097 ret->cm_format_type = *mptr++; // Format type byte
1099 // The rest is zero or more arbitrary fields. Load them in.
1100 // We're done when we encounter either a zero-length field or
1101 // have just processed the 'M' (message text) field.
1104 field_header = '\0';
1107 while (field_header == '\0') { // work around possibly buggy messages
1108 if (mptr >= upper_bound) {
1111 field_header = *mptr++;
1113 if (mptr >= upper_bound) {
1116 which = field_header;
1119 CM_SetField(ret, which, mptr, len);
1121 mptr += len + 1; // advance to next field
1123 } while ((mptr < upper_bound) && (field_header != 'M'));
1128 // Load a message from disk into memory.
1129 // This is used by CtdlOutputMsg() and other fetch functions.
1131 // NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1132 // using the CM_Free(); function.
1134 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body) {
1135 struct cdbdata *dmsgtext;
1136 struct CtdlMessage *ret = NULL;
1138 syslog(LOG_DEBUG, "msgbase: CtdlFetchMessage(%ld, %d)", msgnum, with_body);
1139 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1140 if (dmsgtext == NULL) {
1141 syslog(LOG_ERR, "msgbase: message #%ld was not found", msgnum);
1145 if (dmsgtext->ptr[dmsgtext->len - 1] != '\0') {
1146 syslog(LOG_ERR, "msgbase: CtdlFetchMessage(%ld, %d) Forcefully terminating message!!", msgnum, with_body);
1147 dmsgtext->ptr[dmsgtext->len - 1] = '\0';
1150 ret = CtdlDeserializeMessage(msgnum, with_body, dmsgtext->ptr, dmsgtext->len);
1158 // Always make sure there's something in the msg text field. If
1159 // it's NULL, the message text is most likely stored separately,
1160 // so go ahead and fetch that. Failing that, just set a dummy
1161 // body so other code doesn't barf.
1163 if ( (CM_IsEmpty(ret, eMesageText)) && (with_body) ) {
1164 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1165 if (dmsgtext != NULL) {
1166 CM_SetAsField(ret, eMesageText, &dmsgtext->ptr, dmsgtext->len - 1);
1170 if (CM_IsEmpty(ret, eMesageText)) {
1171 CM_SetField(ret, eMesageText, HKEY("\r\n\r\n (no text)\r\n"));
1178 // Pre callback function for multipart/alternative
1180 // NOTE: this differs from the standard behavior for a reason. Normally when
1181 // displaying multipart/alternative you want to show the _last_ usable
1182 // format in the message. Here we show the _first_ one, because it's
1183 // usually text/plain. Since this set of functions is designed for text
1184 // output to non-MIME-aware clients, this is the desired behavior.
1186 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1187 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1188 char *cbid, void *cbuserdata)
1192 ma = (struct ma_info *)cbuserdata;
1193 syslog(LOG_DEBUG, "msgbase: fixed_output_pre() type=<%s>", cbtype);
1194 if (!strcasecmp(cbtype, "multipart/alternative")) {
1198 if (!strcasecmp(cbtype, "message/rfc822")) {
1205 // Post callback function for multipart/alternative
1207 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1208 void *content, char *cbtype, char *cbcharset, size_t length,
1209 char *encoding, char *cbid, void *cbuserdata)
1213 ma = (struct ma_info *)cbuserdata;
1214 syslog(LOG_DEBUG, "msgbase: fixed_output_post() type=<%s>", cbtype);
1215 if (!strcasecmp(cbtype, "multipart/alternative")) {
1219 if (!strcasecmp(cbtype, "message/rfc822")) {
1225 // Inline callback function for mime parser that wants to display text
1226 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1227 void *content, char *cbtype, char *cbcharset, size_t length,
1228 char *encoding, char *cbid, void *cbuserdata)
1235 ma = (struct ma_info *)cbuserdata;
1238 "msgbase: fixed_output() part %s: %s (%s) (%ld bytes)",
1239 partnum, filename, cbtype, (long)length
1242 // If we're in the middle of a multipart/alternative scope and
1243 // we've already printed another section, skip this one.
1244 if ( (ma->is_ma) && (ma->did_print) ) {
1245 syslog(LOG_DEBUG, "msgbase: skipping part %s (%s)", partnum, cbtype);
1250 if ( (!strcasecmp(cbtype, "text/plain"))
1251 || (IsEmptyStr(cbtype)) ) {
1254 client_write(wptr, length);
1255 if (wptr[length-1] != '\n') {
1262 if (!strcasecmp(cbtype, "text/html")) {
1263 ptr = html_to_ascii(content, length, 80);
1265 client_write(ptr, wlen);
1266 if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
1273 if (ma->use_fo_hooks) {
1274 if (PerformFixedOutputHooks(cbtype, content, length)) { // returns nonzero if it handled the part
1279 if (strncasecmp(cbtype, "multipart/", 10)) {
1280 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1281 partnum, filename, cbtype, (long)length);
1287 // The client is elegant and sophisticated and wants to be choosy about
1288 // MIME content types, so figure out which multipart/alternative part
1289 // we're going to send.
1291 // We use a system of weights. When we find a part that matches one of the
1292 // MIME types we've declared as preferential, we can store it in ma->chosen_part
1293 // and then set ma->chosen_pref to that MIME type's position in our preference
1294 // list. If we then hit another match, we only replace the first match if
1295 // the preference value is lower.
1296 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1297 void *content, char *cbtype, char *cbcharset, size_t length,
1298 char *encoding, char *cbid, void *cbuserdata)
1304 ma = (struct ma_info *)cbuserdata;
1306 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1307 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1308 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1309 if (i < ma->chosen_pref) {
1310 syslog(LOG_DEBUG, "msgbase: setting chosen part to <%s>", partnum);
1311 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1312 ma->chosen_pref = i;
1319 // Now that we've chosen our preferred part, output it.
1320 void output_preferred(char *name,
1334 int add_newline = 0;
1337 char *decoded = NULL;
1338 size_t bytes_decoded;
1341 ma = (struct ma_info *)cbuserdata;
1343 // This is not the MIME part you're looking for...
1344 if (strcasecmp(partnum, ma->chosen_part)) return;
1346 // If the content-type of this part is in our preferred formats
1347 // list, we can simply output it verbatim.
1348 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1349 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1350 if (!strcasecmp(buf, cbtype)) {
1351 /* Yeah! Go! W00t!! */
1352 if (ma->dont_decode == 0)
1353 rc = mime_decode_now (content,
1359 break; // Give us the chance, maybe theres another one.
1361 if (rc == 0) text_content = (char *)content;
1363 text_content = decoded;
1364 length = bytes_decoded;
1367 if (text_content[length-1] != '\n') {
1370 cprintf("Content-type: %s", cbtype);
1371 if (!IsEmptyStr(cbcharset)) {
1372 cprintf("; charset=%s", cbcharset);
1374 cprintf("\nContent-length: %d\n",
1375 (int)(length + add_newline) );
1376 if (!IsEmptyStr(encoding)) {
1377 cprintf("Content-transfer-encoding: %s\n", encoding);
1380 cprintf("Content-transfer-encoding: 7bit\n");
1382 cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1384 if (client_write(text_content, length) == -1)
1386 syslog(LOG_ERR, "msgbase: output_preferred() aborting due to write failure");
1389 if (add_newline) cprintf("\n");
1390 if (decoded != NULL) free(decoded);
1395 // No translations required or possible: output as text/plain
1396 cprintf("Content-type: text/plain\n\n");
1398 if (ma->dont_decode == 0)
1399 rc = mime_decode_now (content,
1405 return; // Give us the chance, maybe theres another one.
1407 if (rc == 0) text_content = (char *)content;
1409 text_content = decoded;
1410 length = bytes_decoded;
1413 fixed_output(name, filename, partnum, disp, text_content, cbtype, cbcharset, length, encoding, cbid, cbuserdata);
1414 if (decoded != NULL) free(decoded);
1419 char desired_section[64];
1425 // Callback function
1426 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1427 void *content, char *cbtype, char *cbcharset, size_t length,
1428 char *encoding, char *cbid, void *cbuserdata)
1430 struct encapmsg *encap;
1432 encap = (struct encapmsg *)cbuserdata;
1434 // Only proceed if this is the desired section...
1435 if (!strcasecmp(encap->desired_section, partnum)) {
1436 encap->msglen = length;
1437 encap->msg = malloc(length + 2);
1438 memcpy(encap->msg, content, length);
1444 // Determine whether the specified message exists in the cached_msglist
1445 // (This is a security check)
1446 int check_cached_msglist(long msgnum) {
1448 // cases in which we skip the check
1449 if (!CC) return om_ok; // not a session
1450 if (CC->client_socket <= 0) return om_ok; // not a client session
1451 if (CC->cached_msglist == NULL) return om_access_denied; // no msglist fetched
1452 if (CC->cached_num_msgs == 0) return om_access_denied; // nothing to check
1454 // Do a binary search within the cached_msglist for the requested msgnum
1456 int max = (CC->cached_num_msgs - 1);
1458 while (max >= min) {
1459 int middle = min + (max-min) / 2 ;
1460 if (msgnum == CC->cached_msglist[middle]) {
1463 if (msgnum > CC->cached_msglist[middle]) {
1471 return om_access_denied;
1475 // Get a message off disk. (returns om_* values found in msgbase.h)
1476 int CtdlOutputMsg(long msg_num, // message number (local) to fetch
1477 int mode, // how would you like that message?
1478 int headers_only, // eschew the message body?
1479 int do_proto, // do Citadel protocol responses?
1480 int crlf, // Use CRLF newlines instead of LF?
1481 char *section, // NULL or a message/rfc822 section
1482 int flags, // various flags; see msgbase.h
1487 struct CtdlMessage *TheMessage = NULL;
1488 int retcode = CIT_OK;
1489 struct encapmsg encap;
1492 syslog(LOG_DEBUG, "msgbase: CtdlOutputMsg(msgnum=%ld, mode=%d, section=%s)",
1494 (section ? section : "<>")
1497 r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
1500 if (r == om_not_logged_in) {
1501 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1504 cprintf("%d An unknown error has occurred.\n", ERROR);
1511 * Check to make sure the message is actually IN this room
1513 r = check_cached_msglist(msg_num);
1514 if (r == om_access_denied) {
1515 /* Not in the cache? We get ONE shot to check it again. */
1516 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
1517 r = check_cached_msglist(msg_num);
1520 syslog(LOG_DEBUG, "msgbase: security check fail; message %ld is not in %s",
1521 msg_num, CC->room.QRname
1524 if (r == om_access_denied) {
1525 cprintf("%d message %ld was not found in this room\n",
1526 ERROR + HIGHER_ACCESS_REQUIRED,
1535 * Fetch the message from disk. If we're in HEADERS_FAST mode,
1536 * request that we don't even bother loading the body into memory.
1538 if (headers_only == HEADERS_FAST) {
1539 TheMessage = CtdlFetchMessage(msg_num, 0);
1542 TheMessage = CtdlFetchMessage(msg_num, 1);
1545 if (TheMessage == NULL) {
1546 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1547 ERROR + MESSAGE_NOT_FOUND, msg_num);
1548 return(om_no_such_msg);
1551 /* Here is the weird form of this command, to process only an
1552 * encapsulated message/rfc822 section.
1554 if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1555 memset(&encap, 0, sizeof encap);
1556 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1557 mime_parser(CM_RANGE(TheMessage, eMesageText),
1558 *extract_encapsulated_message,
1559 NULL, NULL, (void *)&encap, 0
1562 if ((Author != NULL) && (*Author == NULL))
1565 CM_GetAsField(TheMessage, eAuthor, Author, &len);
1567 if ((Address != NULL) && (*Address == NULL))
1570 CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
1572 if ((MessageID != NULL) && (*MessageID == NULL))
1575 CM_GetAsField(TheMessage, emessageId, MessageID, &len);
1577 CM_Free(TheMessage);
1581 encap.msg[encap.msglen] = 0;
1582 TheMessage = convert_internet_message(encap.msg);
1583 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1585 /* Now we let it fall through to the bottom of this
1586 * function, because TheMessage now contains the
1587 * encapsulated message instead of the top-level
1588 * message. Isn't that neat?
1593 cprintf("%d msg %ld has no part %s\n",
1594 ERROR + MESSAGE_NOT_FOUND,
1598 retcode = om_no_such_msg;
1603 /* Ok, output the message now */
1604 if (retcode == CIT_OK)
1605 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
1606 if ((Author != NULL) && (*Author == NULL))
1609 CM_GetAsField(TheMessage, eAuthor, Author, &len);
1611 if ((Address != NULL) && (*Address == NULL))
1614 CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
1616 if ((MessageID != NULL) && (*MessageID == NULL))
1619 CM_GetAsField(TheMessage, emessageId, MessageID, &len);
1622 CM_Free(TheMessage);
1628 void OutputCtdlMsgHeaders(struct CtdlMessage *TheMessage, int do_proto) {
1631 char display_name[256];
1633 /* begin header processing loop for Citadel message format */
1634 safestrncpy(display_name, "<unknown>", sizeof display_name);
1635 if (!CM_IsEmpty(TheMessage, eAuthor)) {
1636 strcpy(buf, TheMessage->cm_fields[eAuthor]);
1637 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1638 safestrncpy(display_name, "****", sizeof display_name);
1640 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1641 safestrncpy(display_name, "anonymous", sizeof display_name);
1644 safestrncpy(display_name, buf, sizeof display_name);
1646 if ((is_room_aide())
1647 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1648 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1649 size_t tmp = strlen(display_name);
1650 snprintf(&display_name[tmp],
1651 sizeof display_name - tmp,
1656 /* Now spew the header fields in the order we like them. */
1657 for (i=0; i< NDiskFields; ++i) {
1659 Field = FieldOrder[i];
1660 if (Field != eMesageText) {
1661 if ( (!CM_IsEmpty(TheMessage, Field)) && (msgkeys[Field] != NULL) ) {
1662 if ((Field == eenVelopeTo) || (Field == eRecipient) || (Field == eCarbonCopY)) {
1663 sanitize_truncated_recipient(TheMessage->cm_fields[Field]);
1665 if (Field == eAuthor) {
1667 cprintf("%s=%s\n", msgkeys[Field], display_name);
1670 /* Masquerade display name if needed */
1673 cprintf("%s=%s\n", msgkeys[Field], TheMessage->cm_fields[Field]);
1676 /* Give the client a hint about whether the message originated locally */
1677 if (Field == erFc822Addr) {
1678 if (IsDirectory(TheMessage->cm_fields[Field] ,0)) {
1679 cprintf("locl=yes\n"); // message originated locally.
1691 void OutputRFC822MsgHeaders(
1692 struct CtdlMessage *TheMessage,
1693 int flags, /* should the message be exported clean */
1694 const char *nl, int nlen,
1695 char *mid, long sizeof_mid,
1696 char *suser, long sizeof_suser,
1697 char *luser, long sizeof_luser,
1698 char *fuser, long sizeof_fuser,
1699 char *snode, long sizeof_snode)
1701 char datestamp[100];
1702 int subject_found = 0;
1709 for (i = 0; i < NDiskFields; ++i) {
1710 if (TheMessage->cm_fields[FieldOrder[i]]) {
1711 mptr = mpptr = TheMessage->cm_fields[FieldOrder[i]];
1712 switch (FieldOrder[i]) {
1714 safestrncpy(luser, mptr, sizeof_luser);
1715 safestrncpy(suser, mptr, sizeof_suser);
1718 if ((flags & QP_EADDR) != 0) {
1719 mptr = qp_encode_email_addrs(mptr);
1721 sanitize_truncated_recipient(mptr);
1722 cprintf("CC: %s%s", mptr, nl);
1725 cprintf("Return-Path: %s%s", mptr, nl);
1728 cprintf("List-ID: %s%s", mptr, nl);
1731 if ((flags & QP_EADDR) != 0)
1732 mptr = qp_encode_email_addrs(mptr);
1734 while ((*hptr != '\0') && isspace(*hptr))
1736 if (!IsEmptyStr(hptr))
1737 cprintf("Envelope-To: %s%s", hptr, nl);
1740 cprintf("Subject: %s%s", mptr, nl);
1744 safestrncpy(mid, mptr, sizeof_mid);
1747 safestrncpy(fuser, mptr, sizeof_fuser);
1750 if (haschar(mptr, '@') == 0) {
1751 sanitize_truncated_recipient(mptr);
1752 cprintf("To: %s@%s", mptr, CtdlGetConfigStr("c_fqdn"));
1756 if ((flags & QP_EADDR) != 0) {
1757 mptr = qp_encode_email_addrs(mptr);
1759 sanitize_truncated_recipient(mptr);
1760 cprintf("To: %s", mptr);
1765 datestring(datestamp, sizeof datestamp, atol(mptr), DATESTRING_RFC822);
1766 cprintf("Date: %s%s", datestamp, nl);
1769 cprintf("References: ");
1770 k = num_tokens(mptr, '|');
1771 for (j=0; j<k; ++j) {
1772 extract_token(buf, mptr, j, '|', sizeof buf);
1773 cprintf("<%s>", buf);
1784 while ((*hptr != '\0') && isspace(*hptr))
1786 if (!IsEmptyStr(hptr))
1787 cprintf("Reply-To: %s%s", mptr, nl);
1799 /* these don't map to mime message headers. */
1802 if (mptr != mpptr) {
1807 if (subject_found == 0) {
1808 cprintf("Subject: (no subject)%s", nl);
1813 void Dump_RFC822HeadersBody(
1814 struct CtdlMessage *TheMessage,
1815 int headers_only, /* eschew the message body? */
1816 int flags, /* should the bessage be exported clean? */
1817 const char *nl, int nlen)
1819 cit_uint8_t prev_ch;
1821 const char *StartOfText = StrBufNOTNULL;
1824 int nllen = strlen(nl);
1828 mptr = TheMessage->cm_fields[eMesageText];
1831 while (*mptr != '\0') {
1832 if (*mptr == '\r') {
1839 eoh = (*(mptr+1) == '\r') && (*(mptr+2) == '\n');
1841 eoh = *(mptr+1) == '\n';
1845 StartOfText = strchr(StartOfText, '\n');
1846 StartOfText = strchr(StartOfText, '\n');
1849 if (((headers_only == HEADERS_NONE) && (mptr >= StartOfText)) ||
1850 ((headers_only == HEADERS_ONLY) && (mptr < StartOfText)) ||
1851 ((headers_only != HEADERS_NONE) &&
1852 (headers_only != HEADERS_ONLY))
1854 if (*mptr == '\n') {
1855 memcpy(&outbuf[outlen], nl, nllen);
1857 outbuf[outlen] = '\0';
1860 outbuf[outlen++] = *mptr;
1864 if (flags & ESC_DOT) {
1865 if ((prev_ch == '\n') && (*mptr == '.') && ((*(mptr+1) == '\r') || (*(mptr+1) == '\n'))) {
1866 outbuf[outlen++] = '.';
1871 if (outlen > 1000) {
1872 if (client_write(outbuf, outlen) == -1) {
1873 syslog(LOG_ERR, "msgbase: Dump_RFC822HeadersBody() aborting due to write failure");
1876 lfSent = (outbuf[outlen - 1] == '\n');
1881 client_write(outbuf, outlen);
1882 lfSent = (outbuf[outlen - 1] == '\n');
1885 client_write(nl, nlen);
1889 /* If the format type on disk is 1 (fixed-format), then we want
1890 * everything to be output completely literally ... regardless of
1891 * what message transfer format is in use.
1893 void DumpFormatFixed(
1894 struct CtdlMessage *TheMessage,
1895 int mode, /* how would you like that message? */
1896 const char *nl, int nllen)
1904 mptr = TheMessage->cm_fields[eMesageText];
1906 if (mode == MT_MIME) {
1907 cprintf("Content-type: text/plain\n\n");
1911 while (ch = *mptr++, ch > 0) {
1915 if ((buflen > 250) && (!xlline)){
1919 while ((buflen > 0) &&
1920 (!isspace(buf[buflen])))
1926 mptr -= tbuflen - buflen;
1932 /* if we reach the outer bounds of our buffer, abort without respect for what we purge. */
1933 if (xlline && ((isspace(ch)) || (buflen > SIZ - nllen - 2))) {
1938 memcpy (&buf[buflen], nl, nllen);
1942 if (client_write(buf, buflen) == -1) {
1943 syslog(LOG_ERR, "msgbase: DumpFormatFixed() aborting due to write failure");
1955 if (!IsEmptyStr(buf)) {
1956 cprintf("%s%s", buf, nl);
1962 * Get a message off disk. (returns om_* values found in msgbase.h)
1964 int CtdlOutputPreLoadedMsg(
1965 struct CtdlMessage *TheMessage,
1966 int mode, /* how would you like that message? */
1967 int headers_only, /* eschew the message body? */
1968 int do_proto, /* do Citadel protocol responses? */
1969 int crlf, /* Use CRLF newlines instead of LF? */
1970 int flags /* should the bessage be exported clean? */
1973 const char *nl; /* newline string */
1977 /* Buffers needed for RFC822 translation. These are all filled
1978 * using functions that are bounds-checked, and therefore we can
1979 * make them substantially smaller than SIZ.
1987 syslog(LOG_DEBUG, "msgbase: CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d",
1988 ((TheMessage == NULL) ? "NULL" : "not null"),
1989 mode, headers_only, do_proto, crlf
1992 strcpy(mid, "unknown");
1993 nl = (crlf ? "\r\n" : "\n");
1994 nlen = crlf ? 2 : 1;
1996 if (!CM_IsValidMsg(TheMessage)) {
1997 syslog(LOG_ERR, "msgbase: error; invalid preloaded message for output");
1998 return(om_no_such_msg);
2001 /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2002 * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2004 if ( (flags & SUPPRESS_ENV_TO) && (!CM_IsEmpty(TheMessage, eenVelopeTo)) ) {
2005 memset(TheMessage->cm_fields[eenVelopeTo], ' ', TheMessage->cm_lengths[eenVelopeTo]);
2008 /* Are we downloading a MIME component? */
2009 if (mode == MT_DOWNLOAD) {
2010 if (TheMessage->cm_format_type != FMT_RFC822) {
2012 cprintf("%d This is not a MIME message.\n",
2013 ERROR + ILLEGAL_VALUE);
2014 } else if (CC->download_fp != NULL) {
2015 if (do_proto) cprintf(
2016 "%d You already have a download open.\n",
2017 ERROR + RESOURCE_BUSY);
2019 /* Parse the message text component */
2020 mime_parser(CM_RANGE(TheMessage, eMesageText),
2021 *mime_download, NULL, NULL, NULL, 0);
2022 /* If there's no file open by this time, the requested
2023 * section wasn't found, so print an error
2025 if (CC->download_fp == NULL) {
2026 if (do_proto) cprintf(
2027 "%d Section %s not found.\n",
2028 ERROR + FILE_NOT_FOUND,
2029 CC->download_desired_section);
2032 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
2035 // MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2036 // in a single server operation instead of opening a download file.
2037 if (mode == MT_SPEW_SECTION) {
2038 if (TheMessage->cm_format_type != FMT_RFC822) {
2040 cprintf("%d This is not a MIME message.\n",
2041 ERROR + ILLEGAL_VALUE);
2044 // Locate and parse the component specified by the caller
2046 mime_parser(CM_RANGE(TheMessage, eMesageText), *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2048 // If section wasn't found, print an error
2051 cprintf( "%d Section %s not found.\n", ERROR + FILE_NOT_FOUND, CC->download_desired_section);
2055 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
2058 // now for the user-mode message reading loops
2059 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2061 // Does the caller want to skip the headers?
2062 if (headers_only == HEADERS_NONE) goto START_TEXT;
2064 // Tell the client which format type we're using.
2065 if ( (mode == MT_CITADEL) && (do_proto) ) {
2066 cprintf("type=%d\n", TheMessage->cm_format_type); // Tell the client which format type we're using.
2069 // nhdr=yes means that we're only displaying headers, no body
2070 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2071 && ((mode == MT_CITADEL) || (mode == MT_MIME))
2074 cprintf("nhdr=yes\n");
2077 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
2078 OutputCtdlMsgHeaders(TheMessage, do_proto);
2081 // begin header processing loop for RFC822 transfer format
2086 if (mode == MT_RFC822)
2087 OutputRFC822MsgHeaders(
2092 suser, sizeof(suser),
2093 luser, sizeof(luser),
2094 fuser, sizeof(fuser),
2095 snode, sizeof(snode)
2099 for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2100 suser[i] = tolower(suser[i]);
2101 if (!isalnum(suser[i])) suser[i]='_';
2104 if (mode == MT_RFC822) {
2105 /* Construct a fun message id */
2106 cprintf("Message-ID: <%s", mid);
2107 if (strchr(mid, '@')==NULL) {
2108 cprintf("@%s", snode);
2112 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2113 cprintf("From: \"----\" <x@x.org>%s", nl);
2115 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2116 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2118 else if (!IsEmptyStr(fuser)) {
2119 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2122 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2125 /* Blank line signifying RFC822 end-of-headers */
2126 if (TheMessage->cm_format_type != FMT_RFC822) {
2131 // end header processing loop ... at this point, we're in the text
2133 if (headers_only == HEADERS_FAST) goto DONE;
2135 // Tell the client about the MIME parts in this message
2136 if (TheMessage->cm_format_type == FMT_RFC822) {
2137 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2138 memset(&ma, 0, sizeof(struct ma_info));
2139 mime_parser(CM_RANGE(TheMessage, eMesageText),
2140 (do_proto ? *list_this_part : NULL),
2141 (do_proto ? *list_this_pref : NULL),
2142 (do_proto ? *list_this_suff : NULL),
2145 else if (mode == MT_RFC822) { // unparsed RFC822 dump
2146 Dump_RFC822HeadersBody(
2155 if (headers_only == HEADERS_ONLY) {
2159 // signify start of msg text
2160 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2161 if (do_proto) cprintf("text\n");
2164 if (TheMessage->cm_format_type == FMT_FIXED)
2167 mode, // how would you like that message?
2170 // If the message on disk is format 0 (Citadel vari-format), we
2171 // output using the formatter at 80 columns. This is the final output
2172 // form if the transfer format is RFC822, but if the transfer format
2173 // is Citadel proprietary, it'll still work, because the indentation
2174 // for new paragraphs is correct and the client will reformat the
2175 // message to the reader's screen width.
2177 if (TheMessage->cm_format_type == FMT_CITADEL) {
2178 if (mode == MT_MIME) {
2179 cprintf("Content-type: text/x-citadel-variformat\n\n");
2181 memfmout(TheMessage->cm_fields[eMesageText], nl);
2184 // If the message on disk is format 4 (MIME), we've gotta hand it
2185 // off to the MIME parser. The client has already been told that
2186 // this message is format 1 (fixed format), so the callback function
2187 // we use will display those parts as-is.
2189 if (TheMessage->cm_format_type == FMT_RFC822) {
2190 memset(&ma, 0, sizeof(struct ma_info));
2192 if (mode == MT_MIME) {
2193 ma.use_fo_hooks = 0;
2194 strcpy(ma.chosen_part, "1");
2195 ma.chosen_pref = 9999;
2196 ma.dont_decode = CC->msg4_dont_decode;
2197 mime_parser(CM_RANGE(TheMessage, eMesageText),
2198 *choose_preferred, *fixed_output_pre,
2199 *fixed_output_post, (void *)&ma, 1);
2200 mime_parser(CM_RANGE(TheMessage, eMesageText),
2201 *output_preferred, NULL, NULL, (void *)&ma, 1);
2204 ma.use_fo_hooks = 1;
2205 mime_parser(CM_RANGE(TheMessage, eMesageText),
2206 *fixed_output, *fixed_output_pre,
2207 *fixed_output_post, (void *)&ma, 0);
2212 DONE: /* now we're done */
2213 if (do_proto) cprintf("000\n");
2217 // Save one or more message pointers into a specified room
2218 // (Returns 0 for success, nonzero for failure)
2219 // roomname may be NULL to use the current room
2221 // Note that the 'supplied_msg' field may be set to NULL, in which case
2222 // the message will be fetched from disk, by number, if we need to perform
2223 // replication checks. This adds an additional database read, so if the
2224 // caller already has the message in memory then it should be supplied. (Obviously
2225 // this mode of operation only works if we're saving a single message.)
2227 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2228 int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2231 char hold_rm[ROOMNAMELEN];
2232 struct cdbdata *cdbfr;
2235 long highest_msg = 0L;
2238 struct CtdlMessage *msg = NULL;
2240 long *msgs_to_be_merged = NULL;
2241 int num_msgs_to_be_merged = 0;
2244 "msgbase: CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)",
2245 roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2248 strcpy(hold_rm, CC->room.QRname);
2251 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2252 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2253 if (num_newmsgs > 1) supplied_msg = NULL;
2255 /* Now the regular stuff */
2256 if (CtdlGetRoomLock(&CC->room,
2257 ((roomname != NULL) ? roomname : CC->room.QRname) )
2259 syslog(LOG_ERR, "msgbase: no such room <%s>", roomname);
2260 return(ERROR + ROOM_NOT_FOUND);
2264 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2265 num_msgs_to_be_merged = 0;
2268 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2269 if (cdbfr == NULL) {
2273 msglist = (long *) cdbfr->ptr;
2274 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2275 num_msgs = cdbfr->len / sizeof(long);
2280 /* Create a list of msgid's which were supplied by the caller, but do
2281 * not already exist in the target room. It is absolutely taboo to
2282 * have more than one reference to the same message in a room.
2284 for (i=0; i<num_newmsgs; ++i) {
2286 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2287 if (msglist[j] == newmsgidlist[i]) {
2292 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2296 syslog(LOG_DEBUG, "msgbase: %d unique messages to be merged", num_msgs_to_be_merged);
2299 * Now merge the new messages
2301 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2302 if (msglist == NULL) {
2303 syslog(LOG_ALERT, "msgbase: ERROR; can't realloc message list!");
2304 free(msgs_to_be_merged);
2305 return (ERROR + INTERNAL_ERROR);
2307 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2308 num_msgs += num_msgs_to_be_merged;
2310 /* Sort the message list, so all the msgid's are in order */
2311 num_msgs = sort_msglist(msglist, num_msgs);
2313 /* Determine the highest message number */
2314 highest_msg = msglist[num_msgs - 1];
2316 /* Write it back to disk. */
2317 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2318 msglist, (int)(num_msgs * sizeof(long)));
2320 /* Free up the memory we used. */
2323 /* Update the highest-message pointer and unlock the room. */
2324 CC->room.QRhighest = highest_msg;
2325 CtdlPutRoomLock(&CC->room);
2327 /* Perform replication checks if necessary */
2328 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2329 syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() doing repl checks");
2331 for (i=0; i<num_msgs_to_be_merged; ++i) {
2332 msgid = msgs_to_be_merged[i];
2334 if (supplied_msg != NULL) {
2338 msg = CtdlFetchMessage(msgid, 0);
2342 ReplicationChecks(msg);
2344 /* If the message has an Exclusive ID, index that... */
2345 if (!CM_IsEmpty(msg, eExclusiveID)) {
2346 index_message_by_euid(msg->cm_fields[eExclusiveID], &CC->room, msgid);
2349 /* Free up the memory we may have allocated */
2350 if (msg != supplied_msg) {
2359 syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() skips repl checks");
2362 /* Submit this room for processing by hooks */
2363 int total_roomhook_errors = PerformRoomHooks(&CC->room);
2364 if (total_roomhook_errors) {
2365 syslog(LOG_WARNING, "msgbase: room hooks returned %d errors", total_roomhook_errors);
2368 /* Go back to the room we were in before we wandered here... */
2369 CtdlGetRoom(&CC->room, hold_rm);
2371 /* Bump the reference count for all messages which were merged */
2372 if (!suppress_refcount_adj) {
2373 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
2376 /* Free up memory... */
2377 if (msgs_to_be_merged != NULL) {
2378 free(msgs_to_be_merged);
2381 /* Return success. */
2387 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2390 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2391 int do_repl_check, struct CtdlMessage *supplied_msg)
2393 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
2398 * Message base operation to save a new message to the message store
2399 * (returns new message number)
2401 * This is the back end for CtdlSubmitMsg() and should not be directly
2402 * called by server-side modules.
2405 long CtdlSaveThisMessage(struct CtdlMessage *msg, long msgid, int Reply) {
2413 * If the message is big, set its body aside for storage elsewhere
2414 * and we hide the message body from the serializer
2416 if (!CM_IsEmpty(msg, eMesageText) && msg->cm_lengths[eMesageText] > BIGMSG) {
2418 holdM = msg->cm_fields[eMesageText];
2419 msg->cm_fields[eMesageText] = NULL;
2420 holdMLen = msg->cm_lengths[eMesageText];
2421 msg->cm_lengths[eMesageText] = 0;
2424 /* Serialize our data structure for storage in the database */
2425 CtdlSerializeMessage(&smr, msg);
2428 /* put the message body back into the message */
2429 msg->cm_fields[eMesageText] = holdM;
2430 msg->cm_lengths[eMesageText] = holdMLen;
2435 cprintf("%d Unable to serialize message\n",
2436 ERROR + INTERNAL_ERROR);
2439 syslog(LOG_ERR, "msgbase: CtdlSaveMessage() unable to serialize message");
2445 /* Write our little bundle of joy into the message base */
2446 retval = cdb_store(CDB_MSGMAIN, &msgid, (int)sizeof(long), smr.ser, smr.len);
2448 syslog(LOG_ERR, "msgbase: can't store message %ld: %ld", msgid, retval);
2452 retval = cdb_store(CDB_BIGMSGS,
2459 syslog(LOG_ERR, "msgbase: failed to store message body for msgid %ld: %ld", msgid, retval);
2464 /* Free the memory we used for the serialized message */
2471 long send_message(struct CtdlMessage *msg) {
2477 /* Get a new message number */
2478 newmsgid = get_new_message_number();
2480 /* Generate an ID if we don't have one already */
2481 if (CM_IsEmpty(msg, emessageId)) {
2482 msgidbuflen = snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
2483 (long unsigned int) time(NULL),
2484 (long unsigned int) newmsgid,
2485 CtdlGetConfigStr("c_fqdn")
2488 CM_SetField(msg, emessageId, msgidbuf, msgidbuflen);
2491 retval = CtdlSaveThisMessage(msg, newmsgid, 1);
2497 /* Return the *local* message ID to the caller
2498 * (even if we're storing an incoming network message)
2505 * Serialize a struct CtdlMessage into the format used on disk.
2507 * This function loads up a "struct ser_ret" (defined in server.h) which
2508 * contains the length of the serialized message and a pointer to the
2509 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2511 void CtdlSerializeMessage(struct ser_ret *ret, /* return values */
2512 struct CtdlMessage *msg) /* unserialized msg */
2518 * Check for valid message format
2520 if (CM_IsValidMsg(msg) == 0) {
2521 syslog(LOG_ERR, "msgbase: CtdlSerializeMessage() aborting due to invalid message");
2528 for (i=0; i < NDiskFields; ++i)
2529 if (msg->cm_fields[FieldOrder[i]] != NULL)
2530 ret->len += msg->cm_lengths[FieldOrder[i]] + 2;
2532 ret->ser = malloc(ret->len);
2533 if (ret->ser == NULL) {
2534 syslog(LOG_ERR, "msgbase: CtdlSerializeMessage() malloc(%ld) failed: %m", (long)ret->len);
2541 ret->ser[1] = msg->cm_anon_type;
2542 ret->ser[2] = msg->cm_format_type;
2545 for (i=0; i < NDiskFields; ++i) {
2546 if (msg->cm_fields[FieldOrder[i]] != NULL) {
2547 ret->ser[wlen++] = (char)FieldOrder[i];
2549 memcpy(&ret->ser[wlen],
2550 msg->cm_fields[FieldOrder[i]],
2551 msg->cm_lengths[FieldOrder[i]] + 1);
2553 wlen = wlen + msg->cm_lengths[FieldOrder[i]] + 1;
2557 if (ret->len != wlen) {
2558 syslog(LOG_ERR, "msgbase: ERROR; len=%ld wlen=%ld", (long)ret->len, (long)wlen);
2566 * Check to see if any messages already exist in the current room which
2567 * carry the same Exclusive ID as this one. If any are found, delete them.
2569 void ReplicationChecks(struct CtdlMessage *msg) {
2570 long old_msgnum = (-1L);
2572 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2574 syslog(LOG_DEBUG, "msgbase: performing replication checks in <%s>", CC->room.QRname);
2576 /* No exclusive id? Don't do anything. */
2577 if (msg == NULL) return;
2578 if (CM_IsEmpty(msg, eExclusiveID)) return;
2580 /*syslog(LOG_DEBUG, "msgbase: exclusive ID: <%s> for room <%s>",
2581 msg->cm_fields[eExclusiveID], CC->room.QRname);*/
2583 old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields[eExclusiveID], &CC->room);
2584 if (old_msgnum > 0L) {
2585 syslog(LOG_DEBUG, "msgbase: ReplicationChecks() replacing message %ld", old_msgnum);
2586 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2592 * Save a message to disk and submit it into the delivery system.
2594 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2595 struct recptypes *recps, /* recipients (if mail) */
2596 const char *force /* force a particular room? */
2598 char hold_rm[ROOMNAMELEN];
2599 char actual_rm[ROOMNAMELEN];
2600 char force_room[ROOMNAMELEN];
2601 char content_type[SIZ]; /* We have to learn this */
2602 char recipient[SIZ];
2603 char bounce_to[1024];
2606 const char *mptr = NULL;
2607 struct ctdluser userbuf;
2609 struct MetaData smi;
2610 char *collected_addresses = NULL;
2611 struct addresses_to_be_filed *aptr = NULL;
2612 StrBuf *saved_rfc822_version = NULL;
2613 int qualified_for_journaling = 0;
2615 syslog(LOG_DEBUG, "msgbase: CtdlSubmitMsg() called");
2616 if (CM_IsValidMsg(msg) == 0) return(-1); /* self check */
2618 /* If this message has no timestamp, we take the liberty of
2619 * giving it one, right now.
2621 if (CM_IsEmpty(msg, eTimestamp)) {
2622 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
2625 /* If this message has no path, we generate one.
2627 if (CM_IsEmpty(msg, eMessagePath)) {
2628 if (!CM_IsEmpty(msg, eAuthor)) {
2629 CM_CopyField(msg, eMessagePath, eAuthor);
2630 for (a=0; !IsEmptyStr(&msg->cm_fields[eMessagePath][a]); ++a) {
2631 if (isspace(msg->cm_fields[eMessagePath][a])) {
2632 msg->cm_fields[eMessagePath][a] = ' ';
2637 CM_SetField(msg, eMessagePath, HKEY("unknown"));
2641 if (force == NULL) {
2642 force_room[0] = '\0';
2645 strcpy(force_room, force);
2648 /* Learn about what's inside, because it's what's inside that counts */
2649 if (CM_IsEmpty(msg, eMesageText)) {
2650 syslog(LOG_ERR, "msgbase: ERROR; attempt to save message with NULL body");
2654 switch (msg->cm_format_type) {
2656 strcpy(content_type, "text/x-citadel-variformat");
2659 strcpy(content_type, "text/plain");
2662 strcpy(content_type, "text/plain");
2663 mptr = bmstrcasestr(msg->cm_fields[eMesageText], "Content-type:");
2666 safestrncpy(content_type, &mptr[13], sizeof content_type);
2667 striplt(content_type);
2668 aptr = content_type;
2669 while (!IsEmptyStr(aptr)) {
2681 /* Goto the correct room */
2682 room = (recps) ? CC->room.QRname : SENTITEMS;
2683 syslog(LOG_DEBUG, "msgbase: selected room %s", room);
2684 strcpy(hold_rm, CC->room.QRname);
2685 strcpy(actual_rm, CC->room.QRname);
2686 if (recps != NULL) {
2687 strcpy(actual_rm, SENTITEMS);
2690 /* If the user is a twit, move to the twit room for posting */
2692 if (CC->user.axlevel == AxProbU) {
2693 strcpy(hold_rm, actual_rm);
2694 strcpy(actual_rm, CtdlGetConfigStr("c_twitroom"));
2695 syslog(LOG_DEBUG, "msgbase: diverting to twit room");
2699 /* ...or if this message is destined for Aide> then go there. */
2700 if (!IsEmptyStr(force_room)) {
2701 strcpy(actual_rm, force_room);
2704 syslog(LOG_DEBUG, "msgbase: final selection: %s (%s)", actual_rm, room);
2705 if (strcasecmp(actual_rm, CC->room.QRname)) {
2706 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL, NULL, NULL);
2710 * If this message has no O (room) field, generate one.
2712 if (CM_IsEmpty(msg, eOriginalRoom) && !IsEmptyStr(CC->room.QRname)) {
2713 CM_SetField(msg, eOriginalRoom, CC->room.QRname, -1);
2716 /* Perform "before save" hooks (aborting if any return nonzero) */
2717 syslog(LOG_DEBUG, "msgbase: performing before-save hooks");
2718 if (PerformMessageHooks(msg, recps, EVT_BEFORESAVE) > 0) return(-3);
2721 * If this message has an Exclusive ID, and the room is replication
2722 * checking enabled, then do replication checks.
2724 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2725 ReplicationChecks(msg);
2728 /* Save it to disk */
2729 syslog(LOG_DEBUG, "msgbase: saving to disk");
2730 newmsgid = send_message(msg);
2731 if (newmsgid <= 0L) return(-5);
2733 /* Write a supplemental message info record. This doesn't have to
2734 * be a critical section because nobody else knows about this message
2737 syslog(LOG_DEBUG, "msgbase: creating metadata record");
2738 memset(&smi, 0, sizeof(struct MetaData));
2739 smi.meta_msgnum = newmsgid;
2740 smi.meta_refcount = 0;
2741 safestrncpy(smi.meta_content_type, content_type, sizeof smi.meta_content_type);
2744 * Measure how big this message will be when rendered as RFC822.
2745 * We do this for two reasons:
2746 * 1. We need the RFC822 length for the new metadata record, so the
2747 * POP and IMAP services don't have to calculate message lengths
2748 * while the user is waiting (multiplied by potentially hundreds
2749 * or thousands of messages).
2750 * 2. If journaling is enabled, we will need an RFC822 version of the
2751 * message to attach to the journalized copy.
2753 if (CC->redirect_buffer != NULL) {
2754 syslog(LOG_ALERT, "msgbase: CC->redirect_buffer is not NULL during message submission!");
2757 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
2758 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
2759 smi.meta_rfc822_length = StrLength(CC->redirect_buffer);
2760 saved_rfc822_version = CC->redirect_buffer;
2761 CC->redirect_buffer = NULL;
2765 /* Now figure out where to store the pointers */
2766 syslog(LOG_DEBUG, "msgbase: storing pointers");
2768 /* If this is being done by the networker delivering a private
2769 * message, we want to BYPASS saving the sender's copy (because there
2770 * is no local sender; it would otherwise go to the Trashcan).
2772 if ((!CC->internal_pgm) || (recps == NULL)) {
2773 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2774 syslog(LOG_ERR, "msgbase: ERROR saving message pointer %ld in %s", newmsgid, actual_rm);
2775 CtdlSaveMsgPointerInRoom(CtdlGetConfigStr("c_aideroom"), newmsgid, 0, msg);
2779 /* For internet mail, drop a copy in the outbound queue room */
2780 if ((recps != NULL) && (recps->num_internet > 0)) {
2781 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2784 /* If other rooms are specified, drop them there too. */
2785 if ((recps != NULL) && (recps->num_room > 0)) {
2786 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2787 extract_token(recipient, recps->recp_room, i, '|', sizeof recipient);
2788 syslog(LOG_DEBUG, "msgbase: delivering to room <%s>", recipient);
2789 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2793 /* Bump this user's messages posted counter. */
2794 syslog(LOG_DEBUG, "msgbase: updating user");
2795 CtdlLockGetCurrentUser();
2796 CC->user.posted = CC->user.posted + 1;
2797 CtdlPutCurrentUserLock();
2799 /* Decide where bounces need to be delivered */
2800 if ((recps != NULL) && (recps->bounce_to == NULL)) {
2801 if (CC->logged_in) {
2802 strcpy(bounce_to, CC->user.fullname);
2804 else if (!IsEmptyStr(msg->cm_fields[eAuthor])){
2805 strcpy(bounce_to, msg->cm_fields[eAuthor]);
2807 recps->bounce_to = bounce_to;
2810 CM_SetFieldLONG(msg, eVltMsgNum, newmsgid);
2812 /* If this is private, local mail, make a copy in the
2813 * recipient's mailbox and bump the reference count.
2815 if ((recps != NULL) && (recps->num_local > 0)) {
2819 pch = recps->recp_local;
2820 recps->recp_local = recipient;
2821 ntokens = num_tokens(pch, '|');
2822 for (i=0; i<ntokens; ++i) {
2823 extract_token(recipient, pch, i, '|', sizeof recipient);
2824 syslog(LOG_DEBUG, "msgbase: delivering private local mail to <%s>", recipient);
2825 if (CtdlGetUser(&userbuf, recipient) == 0) {
2826 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
2827 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2828 CtdlBumpNewMailCounter(userbuf.usernum);
2829 PerformMessageHooks(msg, recps, EVT_AFTERUSRMBOXSAVE);
2832 syslog(LOG_DEBUG, "msgbase: no user <%s>", recipient);
2833 CtdlSaveMsgPointerInRoom(CtdlGetConfigStr("c_aideroom"), newmsgid, 0, msg);
2836 recps->recp_local = pch;
2839 /* Perform "after save" hooks */
2840 syslog(LOG_DEBUG, "msgbase: performing after-save hooks");
2842 PerformMessageHooks(msg, recps, EVT_AFTERSAVE);
2843 CM_FlushField(msg, eVltMsgNum);
2845 /* Go back to the room we started from */
2846 syslog(LOG_DEBUG, "msgbase: returning to original room %s", hold_rm);
2847 if (strcasecmp(hold_rm, CC->room.QRname)) {
2848 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL, NULL, NULL);
2852 * Any addresses to harvest for someone's address book?
2854 if ( (CC->logged_in) && (recps != NULL) ) {
2855 collected_addresses = harvest_collected_addresses(msg);
2858 if (collected_addresses != NULL) {
2859 aptr = (struct addresses_to_be_filed *) malloc(sizeof(struct addresses_to_be_filed));
2860 CtdlMailboxName(actual_rm, sizeof actual_rm, &CC->user, USERCONTACTSROOM);
2861 aptr->roomname = strdup(actual_rm);
2862 aptr->collected_addresses = collected_addresses;
2863 begin_critical_section(S_ATBF);
2866 end_critical_section(S_ATBF);
2870 * Determine whether this message qualifies for journaling.
2872 if (!CM_IsEmpty(msg, eJournal)) {
2873 qualified_for_journaling = 0;
2876 if (recps == NULL) {
2877 qualified_for_journaling = CtdlGetConfigInt("c_journal_pubmsgs");
2879 else if (recps->num_local + recps->num_internet > 0) {
2880 qualified_for_journaling = CtdlGetConfigInt("c_journal_email");
2883 qualified_for_journaling = CtdlGetConfigInt("c_journal_pubmsgs");
2888 * Do we have to perform journaling? If so, hand off the saved
2889 * RFC822 version will be handed off to the journaler for background
2890 * submit. Otherwise, we have to free the memory ourselves.
2892 if (saved_rfc822_version != NULL) {
2893 if (qualified_for_journaling) {
2894 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2897 FreeStrBuf(&saved_rfc822_version);
2901 if ((recps != NULL) && (recps->bounce_to == bounce_to))
2902 recps->bounce_to = NULL;
2910 * Convenience function for generating small administrative messages.
2912 long quickie_message(char *from,
2920 struct CtdlMessage *msg;
2921 struct recptypes *recp = NULL;
2923 msg = malloc(sizeof(struct CtdlMessage));
2924 memset(msg, 0, sizeof(struct CtdlMessage));
2925 msg->cm_magic = CTDLMESSAGE_MAGIC;
2926 msg->cm_anon_type = MES_NORMAL;
2927 msg->cm_format_type = format_type;
2929 if (!IsEmptyStr(from)) {
2930 CM_SetField(msg, eAuthor, from, -1);
2932 else if (!IsEmptyStr(fromaddr)) {
2934 CM_SetField(msg, eAuthor, fromaddr, -1);
2935 pAt = strchr(msg->cm_fields[eAuthor], '@');
2937 CM_CutFieldAt(msg, eAuthor, pAt - msg->cm_fields[eAuthor]);
2941 msg->cm_fields[eAuthor] = strdup("Citadel");
2944 if (!IsEmptyStr(fromaddr)) CM_SetField(msg, erFc822Addr, fromaddr, -1);
2945 if (!IsEmptyStr(room)) CM_SetField(msg, eOriginalRoom, room, -1);
2946 if (!IsEmptyStr(to)) {
2947 CM_SetField(msg, eRecipient, to, -1);
2948 recp = validate_recipients(to, NULL, 0);
2950 if (!IsEmptyStr(subject)) {
2951 CM_SetField(msg, eMsgSubject, subject, -1);
2953 if (!IsEmptyStr(text)) {
2954 CM_SetField(msg, eMesageText, text, -1);
2957 long msgnum = CtdlSubmitMsg(msg, recp, room);
2959 if (recp != NULL) free_recipients(recp);
2965 * Back end function used by CtdlMakeMessage() and similar functions
2967 StrBuf *CtdlReadMessageBodyBuf(char *terminator, // token signalling EOT
2969 size_t maxlen, // maximum message length
2970 StrBuf *exist, // if non-null, append to it; exist is ALWAYS freed
2971 int crlf // CRLF newlines instead of LF
2979 LineBuf = NewStrBufPlain(NULL, SIZ);
2980 if (exist == NULL) {
2981 Message = NewStrBufPlain(NULL, 4 * SIZ);
2984 Message = NewStrBufDup(exist);
2987 /* Do we need to change leading ".." to "." for SMTP escaping? */
2988 if ((tlen == 1) && (*terminator == '.')) {
2992 /* read in the lines of message text one by one */
2994 if (CtdlClientGetLine(LineBuf) < 0) {
2997 if ((StrLength(LineBuf) == tlen) && (!strcmp(ChrPtr(LineBuf), terminator))) {
3000 if ( (!flushing) && (!finished) ) {
3002 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3005 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3008 /* Unescape SMTP-style input of two dots at the beginning of the line */
3009 if ((dotdot) && (StrLength(LineBuf) > 1) && (ChrPtr(LineBuf)[0] == '.')) {
3010 StrBufCutLeft(LineBuf, 1);
3012 StrBufAppendBuf(Message, LineBuf, 0);
3015 /* if we've hit the max msg length, flush the rest */
3016 if (StrLength(Message) >= maxlen) {
3020 } while (!finished);
3021 FreeStrBuf(&LineBuf);
3024 syslog(LOG_ERR, "msgbase: exceeded maximum message length of %ld - message was truncated", maxlen);
3031 // Back end function used by CtdlMakeMessage() and similar functions
3032 char *CtdlReadMessageBody(char *terminator, // token signalling EOT
3034 size_t maxlen, // maximum message length
3035 StrBuf *exist, // if non-null, append to it; exist is ALWAYS freed
3036 int crlf // CRLF newlines instead of LF
3040 Message = CtdlReadMessageBodyBuf(terminator,
3046 if (Message == NULL) {
3050 return SmashStrBuf(&Message);
3055 struct CtdlMessage *CtdlMakeMessage(
3056 struct ctdluser *author, /* author's user structure */
3057 char *recipient, /* NULL if it's not mail */
3058 char *recp_cc, /* NULL if it's not mail */
3059 char *room, /* room where it's going */
3060 int type, /* see MES_ types in header file */
3061 int format_type, /* variformat, plain text, MIME... */
3062 char *fake_name, /* who we're masquerading as */
3063 char *my_email, /* which of my email addresses to use (empty is ok) */
3064 char *subject, /* Subject (optional) */
3065 char *supplied_euid, /* ...or NULL if this is irrelevant */
3066 char *preformatted_text, /* ...or NULL to read text from client */
3067 char *references /* Thread references */
3069 return CtdlMakeMessageLen(
3070 author, /* author's user structure */
3071 recipient, /* NULL if it's not mail */
3072 (recipient)?strlen(recipient) : 0,
3073 recp_cc, /* NULL if it's not mail */
3074 (recp_cc)?strlen(recp_cc): 0,
3075 room, /* room where it's going */
3076 (room)?strlen(room): 0,
3077 type, /* see MES_ types in header file */
3078 format_type, /* variformat, plain text, MIME... */
3079 fake_name, /* who we're masquerading as */
3080 (fake_name)?strlen(fake_name): 0,
3081 my_email, /* which of my email addresses to use (empty is ok) */
3082 (my_email)?strlen(my_email): 0,
3083 subject, /* Subject (optional) */
3084 (subject)?strlen(subject): 0,
3085 supplied_euid, /* ...or NULL if this is irrelevant */
3086 (supplied_euid)?strlen(supplied_euid):0,
3087 preformatted_text, /* ...or NULL to read text from client */
3088 (preformatted_text)?strlen(preformatted_text) : 0,
3089 references, /* Thread references */
3090 (references)?strlen(references):0);
3096 * Build a binary message to be saved on disk.
3097 * (NOTE: if you supply 'preformatted_text', the buffer you give it
3098 * will become part of the message. This means you are no longer
3099 * responsible for managing that memory -- it will be freed along with
3100 * the rest of the fields when CM_Free() is called.)
3102 struct CtdlMessage *CtdlMakeMessageLen(
3103 struct ctdluser *author, /* author's user structure */
3104 char *recipient, /* NULL if it's not mail */
3106 char *recp_cc, /* NULL if it's not mail */
3108 char *room, /* room where it's going */
3110 int type, /* see MES_ types in header file */
3111 int format_type, /* variformat, plain text, MIME... */
3112 char *fake_name, /* who we're masquerading as */
3114 char *my_email, /* which of my email addresses to use (empty is ok) */
3116 char *subject, /* Subject (optional) */
3118 char *supplied_euid, /* ...or NULL if this is irrelevant */
3120 char *preformatted_text, /* ...or NULL to read text from client */
3122 char *references, /* Thread references */
3127 struct CtdlMessage *msg;
3129 StrBuf *FakeEncAuthor = NULL;
3131 msg = malloc(sizeof(struct CtdlMessage));
3132 memset(msg, 0, sizeof(struct CtdlMessage));
3133 msg->cm_magic = CTDLMESSAGE_MAGIC;
3134 msg->cm_anon_type = type;
3135 msg->cm_format_type = format_type;
3137 if (recipient != NULL) rcplen = striplt(recipient);
3138 if (recp_cc != NULL) cclen = striplt(recp_cc);
3140 /* Path or Return-Path */
3142 CM_SetField(msg, eMessagePath, my_email, myelen);
3144 else if (!IsEmptyStr(author->fullname)) {
3145 CM_SetField(msg, eMessagePath, author->fullname, -1);
3147 convert_spaces_to_underscores(msg->cm_fields[eMessagePath]);
3149 blen = snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
3150 CM_SetField(msg, eTimestamp, buf, blen);
3153 FakeAuthor = NewStrBufPlain (fake_name, fnlen);
3156 FakeAuthor = NewStrBufPlain (author->fullname, -1);
3158 StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
3159 CM_SetAsFieldSB(msg, eAuthor, &FakeEncAuthor);
3160 FreeStrBuf(&FakeAuthor);
3162 if (!!IsEmptyStr(CC->room.QRname)) {
3163 if (CC->room.QRflags & QR_MAILBOX) { /* room */
3164 CM_SetField(msg, eOriginalRoom, &CC->room.QRname[11], -1);
3167 CM_SetField(msg, eOriginalRoom, CC->room.QRname, -1);
3172 CM_SetField(msg, eRecipient, recipient, rcplen);
3175 CM_SetField(msg, eCarbonCopY, recp_cc, cclen);
3179 CM_SetField(msg, erFc822Addr, my_email, myelen);
3181 else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
3182 CM_SetField(msg, erFc822Addr, CC->cs_inet_email, -1);
3185 if (subject != NULL) {
3187 length = striplt(subject);
3193 while ((subject[i] != '\0') &&
3194 (IsAscii = isascii(subject[i]) != 0 ))
3197 CM_SetField(msg, eMsgSubject, subject, subjlen);
3198 else /* ok, we've got utf8 in the string. */
3201 rfc2047Subj = rfc2047encode(subject, length);
3202 CM_SetAsField(msg, eMsgSubject, &rfc2047Subj, strlen(rfc2047Subj));
3209 CM_SetField(msg, eExclusiveID, supplied_euid, euidlen);
3213 CM_SetField(msg, eWeferences, references, reflen);
3216 if (preformatted_text != NULL) {
3217 CM_SetField(msg, eMesageText, preformatted_text, textlen);
3221 MsgBody = CtdlReadMessageBodyBuf(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0);
3222 if (MsgBody != NULL) {
3223 CM_SetAsFieldSB(msg, eMesageText, &MsgBody);
3232 * API function to delete messages which match a set of criteria
3233 * (returns the actual number of messages deleted)
3235 int CtdlDeleteMessages(const char *room_name, // which room
3236 long *dmsgnums, // array of msg numbers to be deleted
3237 int num_dmsgnums, // number of msgs to be deleted, or 0 for "any"
3238 char *content_type // or "" for any. regular expressions expected.
3240 struct ctdlroom qrbuf;
3241 struct cdbdata *cdbfr;
3242 long *msglist = NULL;
3243 long *dellist = NULL;
3246 int num_deleted = 0;
3248 struct MetaData smi;
3251 int need_to_free_re = 0;
3253 if (content_type) if (!IsEmptyStr(content_type)) {
3254 regcomp(&re, content_type, 0);
3255 need_to_free_re = 1;
3257 syslog(LOG_DEBUG, "msgbase: CtdlDeleteMessages(%s, %d msgs, %s)", room_name, num_dmsgnums, content_type);
3259 /* get room record, obtaining a lock... */
3260 if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
3261 syslog(LOG_ERR, "msgbase: CtdlDeleteMessages(): Room <%s> not found", room_name);
3262 if (need_to_free_re) regfree(&re);
3263 return(0); /* room not found */
3265 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3267 if (cdbfr != NULL) {
3268 dellist = malloc(cdbfr->len);
3269 msglist = (long *) cdbfr->ptr;
3270 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3271 num_msgs = cdbfr->len / sizeof(long);
3275 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
3276 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
3277 int have_more_del = 1;
3279 num_msgs = sort_msglist(msglist, num_msgs);
3280 if (num_dmsgnums > 1)
3281 num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
3284 StrBuf *dbg = NewStrBuf();
3285 for (i = 0; i < num_dmsgnums; i++)
3286 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
3287 syslog(LOG_DEBUG, "msgbase: Deleting before: %s", ChrPtr(dbg));
3292 while ((i < num_msgs) && (have_more_del)) {
3295 /* Set/clear a bit for each criterion */
3297 /* 0 messages in the list or a null list means that we are
3298 * interested in deleting any messages which meet the other criteria.
3301 delete_this |= 0x01;
3304 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
3309 if (msglist[i] == dmsgnums[j]) {
3310 delete_this |= 0x01;
3313 have_more_del = (j < num_dmsgnums);
3316 if (have_contenttype) {
3317 GetMetaData(&smi, msglist[i]);
3318 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3319 delete_this |= 0x02;
3322 delete_this |= 0x02;
3325 /* Delete message only if all bits are set */
3326 if (delete_this == 0x03) {
3327 dellist[num_deleted++] = msglist[i];
3334 StrBuf *dbg = NewStrBuf();
3335 for (i = 0; i < num_deleted; i++)
3336 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
3337 syslog(LOG_DEBUG, "msgbase: Deleting: %s", ChrPtr(dbg));
3341 num_msgs = sort_msglist(msglist, num_msgs);
3342 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3343 msglist, (int)(num_msgs * sizeof(long)));
3346 qrbuf.QRhighest = msglist[num_msgs - 1];
3348 qrbuf.QRhighest = 0;
3350 CtdlPutRoomLock(&qrbuf);
3352 /* Go through the messages we pulled out of the index, and decrement
3353 * their reference counts by 1. If this is the only room the message
3354 * was in, the reference count will reach zero and the message will
3355 * automatically be deleted from the database. We do this in a
3356 * separate pass because there might be plug-in hooks getting called,
3357 * and we don't want that happening during an S_ROOMS critical
3361 for (i=0; i<num_deleted; ++i) {
3362 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3364 AdjRefCountList(dellist, num_deleted, -1);
3366 /* Now free the memory we used, and go away. */
3367 if (msglist != NULL) free(msglist);
3368 if (dellist != NULL) free(dellist);
3369 syslog(LOG_DEBUG, "msgbase: %d message(s) deleted", num_deleted);
3370 if (need_to_free_re) regfree(&re);
3371 return (num_deleted);
3376 * GetMetaData() - Get the supplementary record for a message
3378 void GetMetaData(struct MetaData *smibuf, long msgnum)
3380 struct cdbdata *cdbsmi;
3383 memset(smibuf, 0, sizeof(struct MetaData));
3384 smibuf->meta_msgnum = msgnum;
3385 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3387 /* Use the negative of the message number for its supp record index */
3388 TheIndex = (0L - msgnum);
3390 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3391 if (cdbsmi == NULL) {
3392 return; /* record not found; leave it alone */
3394 memcpy(smibuf, cdbsmi->ptr,
3395 ((cdbsmi->len > sizeof(struct MetaData)) ?
3396 sizeof(struct MetaData) : cdbsmi->len)
3404 * PutMetaData() - (re)write supplementary record for a message
3406 void PutMetaData(struct MetaData *smibuf)
3410 /* Use the negative of the message number for the metadata db index */
3411 TheIndex = (0L - smibuf->meta_msgnum);
3413 cdb_store(CDB_MSGMAIN,
3414 &TheIndex, (int)sizeof(long),
3415 smibuf, (int)sizeof(struct MetaData)
3421 * Convenience function to process a big block of AdjRefCount() operations
3423 void AdjRefCountList(long *msgnum, long nmsg, int incr)
3427 for (i = 0; i < nmsg; i++) {
3428 AdjRefCount(msgnum[i], incr);
3434 * AdjRefCount - adjust the reference count for a message. We need to delete from disk any message whose reference count reaches zero.
3436 void AdjRefCount(long msgnum, int incr)
3438 struct MetaData smi;
3441 /* This is a *tight* critical section; please keep it that way, as
3442 * it may get called while nested in other critical sections.
3443 * Complicating this any further will surely cause deadlock!
3445 begin_critical_section(S_SUPPMSGMAIN);
3446 GetMetaData(&smi, msgnum);
3447 smi.meta_refcount += incr;
3449 end_critical_section(S_SUPPMSGMAIN);
3450 syslog(LOG_DEBUG, "msgbase: AdjRefCount() msg %ld ref count delta %+d, is now %d", msgnum, incr, smi.meta_refcount);
3452 /* If the reference count is now zero, delete both the message and its metadata record.
3454 if (smi.meta_refcount == 0) {
3455 syslog(LOG_DEBUG, "msgbase: deleting message <%ld>", msgnum);
3457 /* Call delete hooks with NULL room to show it has gone altogether */
3458 PerformDeleteHooks(NULL, msgnum);
3460 /* Remove from message base */
3462 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3463 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3465 /* Remove metadata record */
3466 delnum = (0L - msgnum);
3467 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3473 * Write a generic object to this room
3475 * Returns the message number of the written object, in case you need it.
3477 long CtdlWriteObject(char *req_room, /* Room to stuff it in */
3478 char *content_type, /* MIME type of this object */
3479 char *raw_message, /* Data to be written */
3480 off_t raw_length, /* Size of raw_message */
3481 struct ctdluser *is_mailbox, /* Mailbox room? */
3482 int is_binary, /* Is encoding necessary? */
3483 unsigned int flags /* Internal save flags */
3485 struct ctdlroom qrbuf;
3486 char roomname[ROOMNAMELEN];
3487 struct CtdlMessage *msg;
3488 StrBuf *encoded_message = NULL;
3490 if (is_mailbox != NULL) {
3491 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3494 safestrncpy(roomname, req_room, sizeof(roomname));
3497 syslog(LOG_DEBUG, "msfbase: raw length is %ld", (long)raw_length);
3500 encoded_message = NewStrBufPlain(NULL, (size_t) (((raw_length * 134) / 100) + 4096 ) );
3503 encoded_message = NewStrBufPlain(NULL, (size_t)(raw_length + 4096));
3506 StrBufAppendBufPlain(encoded_message, HKEY("Content-type: "), 0);
3507 StrBufAppendBufPlain(encoded_message, content_type, -1, 0);
3508 StrBufAppendBufPlain(encoded_message, HKEY("\n"), 0);
3511 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: base64\n\n"), 0);
3514 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: 7bit\n\n"), 0);
3518 StrBufBase64Append(encoded_message, NULL, raw_message, raw_length, 0);
3521 StrBufAppendBufPlain(encoded_message, raw_message, raw_length, 0);
3524 syslog(LOG_DEBUG, "msgbase: allocating");
3525 msg = malloc(sizeof(struct CtdlMessage));
3526 memset(msg, 0, sizeof(struct CtdlMessage));
3527 msg->cm_magic = CTDLMESSAGE_MAGIC;
3528 msg->cm_anon_type = MES_NORMAL;
3529 msg->cm_format_type = 4;
3530 CM_SetField(msg, eAuthor, CC->user.fullname, -1);
3531 CM_SetField(msg, eOriginalRoom, req_room, -1);
3532 msg->cm_flags = flags;
3534 CM_SetAsFieldSB(msg, eMesageText, &encoded_message);
3536 /* Create the requested room if we have to. */
3537 if (CtdlGetRoom(&qrbuf, roomname) != 0) {
3538 CtdlCreateRoom(roomname, ( (is_mailbox != NULL) ? 5 : 3 ), "", 0, 1, 0, VIEW_BBS);
3541 /* Now write the data */
3542 long new_msgnum = CtdlSubmitMsg(msg, NULL, roomname);
3548 /************************************************************************/
3549 /* MODULE INITIALIZATION */
3550 /************************************************************************/
3552 char *ctdl_module_init_msgbase(void) {
3554 FillMsgKeyLookupTable();
3557 /* return our module id for the log */