2 * Implements the message store.
4 * Copyright (c) 1987-2017 by the citadel.org team
6 * This program is open source software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 3.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
21 #include <libcitadel.h>
23 #include "ctdl_module.h"
24 #include "citserver.h"
27 #include "clientsocket.h"
31 #include "internet_addressing.h"
32 #include "euidindex.h"
34 #include "journaling.h"
36 struct addresses_to_be_filed *atbf = NULL;
38 /* This temp file holds the queue of operations for AdjRefCount() */
39 static FILE *arcfp = NULL;
40 void AdjRefCountList(long *msgnum, long nmsg, int incr);
43 * These are the four-character field headers we use when outputting
44 * messages in Citadel format (as opposed to RFC822 format).
47 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
48 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
49 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
50 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
51 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
52 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
53 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
54 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
56 "from", /* A -> eAuthor */
57 NULL, /* B -> eBig_message */
58 NULL, /* C -> eRemoteRoom */
59 NULL, /* D -> eDestination */
60 "exti", /* E -> eXclusivID */
61 "rfca", /* F -> erFc822Addr */
63 "hnod", /* H -> eHumanNode */
64 "msgn", /* I -> emessageId */
65 "jrnl", /* J -> eJournal */
66 "rep2", /* K -> eReplyTo */
67 "list", /* L -> eListID */
68 "text", /* M -> eMesageText */
69 "node", /* N -> eNodeName */
70 "room", /* O -> eOriginalRoom */
71 "path", /* P -> eMessagePath */
73 "rcpt", /* R -> eRecipient */
74 "spec", /* S -> eSpecialField */
75 "time", /* T -> eTimestamp */
76 "subj", /* U -> eMsgSubject */
77 "nvto", /* V -> eenVelopeTo */
78 "wefw", /* W -> eWeferences */
80 "cccc", /* Y -> eCarbonCopY */
84 HashList *msgKeyLookup = NULL;
86 int GetFieldFromMnemonic(eMsgField *f, const char* c)
89 if (GetHash(msgKeyLookup, c, 4, &v)) {
96 void FillMsgKeyLookupTable(void)
100 msgKeyLookup = NewHash (1, FourHash);
102 for (i=0; i < 91; i++) {
103 if (msgkeys[i] != NULL) {
104 Put(msgKeyLookup, msgkeys[i], 4, (void*)i, reference_free_handler);
109 eMsgField FieldOrder[] = {
110 /* Important fields */
121 /* Semi-important fields */
127 /* G is not used yet, may become virus signature*/
130 /* Q is not used yet */
133 /* X is not used yet */
134 /* Z is not used yet */
141 /* Message text (MUST be last) */
143 /* Not saved to disk:
148 static const long NDiskFields = sizeof(FieldOrder) / sizeof(eMsgField);
150 int CM_IsEmpty(struct CtdlMessage *Msg, eMsgField which)
152 return !((Msg->cm_fields[which] != NULL) &&
153 (Msg->cm_fields[which][0] != '\0'));
156 void CM_SetField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length)
158 if (Msg->cm_fields[which] != NULL)
159 free (Msg->cm_fields[which]);
160 Msg->cm_fields[which] = malloc(length + 1);
161 memcpy(Msg->cm_fields[which], buf, length);
162 Msg->cm_fields[which][length] = '\0';
163 Msg->cm_lengths[which] = length;
166 void CM_SetFieldLONG(struct CtdlMessage *Msg, eMsgField which, long lvalue)
170 len = snprintf(buf, sizeof(buf), "%ld", lvalue);
171 CM_SetField(Msg, which, buf, len);
173 void CM_CutFieldAt(struct CtdlMessage *Msg, eMsgField WhichToCut, long maxlen)
175 if (Msg->cm_fields[WhichToCut] == NULL)
178 if (Msg->cm_lengths[WhichToCut] > maxlen)
180 Msg->cm_fields[WhichToCut][maxlen] = '\0';
181 Msg->cm_lengths[WhichToCut] = maxlen;
185 void CM_FlushField(struct CtdlMessage *Msg, eMsgField which)
187 if (Msg->cm_fields[which] != NULL)
188 free (Msg->cm_fields[which]);
189 Msg->cm_fields[which] = NULL;
190 Msg->cm_lengths[which] = 0;
192 void CM_Flush(struct CtdlMessage *Msg)
196 if (CM_IsValidMsg(Msg) == 0)
199 for (i = 0; i < 256; ++i)
201 CM_FlushField(Msg, i);
205 void CM_CopyField(struct CtdlMessage *Msg, eMsgField WhichToPutTo, eMsgField WhichtToCopy)
208 if (Msg->cm_fields[WhichToPutTo] != NULL)
209 free (Msg->cm_fields[WhichToPutTo]);
211 if (Msg->cm_fields[WhichtToCopy] != NULL)
213 len = Msg->cm_lengths[WhichtToCopy];
214 Msg->cm_fields[WhichToPutTo] = malloc(len + 1);
215 memcpy(Msg->cm_fields[WhichToPutTo], Msg->cm_fields[WhichtToCopy], len);
216 Msg->cm_fields[WhichToPutTo][len] = '\0';
217 Msg->cm_lengths[WhichToPutTo] = len;
221 Msg->cm_fields[WhichToPutTo] = NULL;
222 Msg->cm_lengths[WhichToPutTo] = 0;
227 void CM_PrependToField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length)
229 if (Msg->cm_fields[which] != NULL) {
234 oldmsgsize = Msg->cm_lengths[which] + 1;
235 newmsgsize = length + oldmsgsize;
237 new = malloc(newmsgsize);
238 memcpy(new, buf, length);
239 memcpy(new + length, Msg->cm_fields[which], oldmsgsize);
240 free(Msg->cm_fields[which]);
241 Msg->cm_fields[which] = new;
242 Msg->cm_lengths[which] = newmsgsize - 1;
245 Msg->cm_fields[which] = malloc(length + 1);
246 memcpy(Msg->cm_fields[which], buf, length);
247 Msg->cm_fields[which][length] = '\0';
248 Msg->cm_lengths[which] = length;
252 void CM_SetAsField(struct CtdlMessage *Msg, eMsgField which, char **buf, long length)
254 if (Msg->cm_fields[which] != NULL)
255 free (Msg->cm_fields[which]);
257 Msg->cm_fields[which] = *buf;
259 Msg->cm_lengths[which] = length;
262 void CM_SetAsFieldSB(struct CtdlMessage *Msg, eMsgField which, StrBuf **buf)
264 if (Msg->cm_fields[which] != NULL)
265 free (Msg->cm_fields[which]);
267 Msg->cm_lengths[which] = StrLength(*buf);
268 Msg->cm_fields[which] = SmashStrBuf(buf);
271 void CM_GetAsField(struct CtdlMessage *Msg, eMsgField which, char **ret, long *retlen)
273 if (Msg->cm_fields[which] != NULL)
275 *retlen = Msg->cm_lengths[which];
276 *ret = Msg->cm_fields[which];
277 Msg->cm_fields[which] = NULL;
278 Msg->cm_lengths[which] = 0;
288 * Returns 1 if the supplied pointer points to a valid Citadel message.
289 * If the pointer is NULL or the magic number check fails, returns 0.
291 int CM_IsValidMsg(struct CtdlMessage *msg) {
294 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
295 syslog(LOG_WARNING, "msgbase: CM_IsValidMsg() self-check failed");
301 void CM_FreeContents(struct CtdlMessage *msg)
305 for (i = 0; i < 256; ++i)
306 if (msg->cm_fields[i] != NULL) {
307 free(msg->cm_fields[i]);
308 msg->cm_lengths[i] = 0;
311 msg->cm_magic = 0; /* just in case */
314 * 'Destructor' for struct CtdlMessage
316 void CM_Free(struct CtdlMessage *msg)
318 if (CM_IsValidMsg(msg) == 0)
320 if (msg != NULL) free (msg);
323 CM_FreeContents(msg);
327 int CM_DupField(eMsgField i, struct CtdlMessage *OrgMsg, struct CtdlMessage *NewMsg)
330 len = OrgMsg->cm_lengths[i];
331 NewMsg->cm_fields[i] = malloc(len + 1);
332 if (NewMsg->cm_fields[i] == NULL)
334 memcpy(NewMsg->cm_fields[i], OrgMsg->cm_fields[i], len);
335 NewMsg->cm_fields[i][len] = '\0';
336 NewMsg->cm_lengths[i] = len;
340 struct CtdlMessage * CM_Duplicate(struct CtdlMessage *OrgMsg)
343 struct CtdlMessage *NewMsg;
345 if (CM_IsValidMsg(OrgMsg) == 0)
347 NewMsg = (struct CtdlMessage *)malloc(sizeof(struct CtdlMessage));
351 memcpy(NewMsg, OrgMsg, sizeof(struct CtdlMessage));
353 memset(&NewMsg->cm_fields, 0, sizeof(char*) * 256);
355 for (i = 0; i < 256; ++i)
357 if (OrgMsg->cm_fields[i] != NULL)
359 if (!CM_DupField(i, OrgMsg, NewMsg))
374 /* Determine if a given message matches the fields in a message template.
375 * Return 0 for a successful match.
377 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
380 /* If there aren't any fields in the template, all messages will
383 if (template == NULL) return(0);
385 /* Null messages are bogus. */
386 if (msg == NULL) return(1);
388 for (i='A'; i<='Z'; ++i) {
389 if (template->cm_fields[i] != NULL) {
390 if (msg->cm_fields[i] == NULL) {
391 /* Considered equal if temmplate is empty string */
392 if (IsEmptyStr(template->cm_fields[i])) continue;
395 if ((template->cm_lengths[i] != msg->cm_lengths[i]) ||
396 (strcasecmp(msg->cm_fields[i], template->cm_fields[i])))
401 /* All compares succeeded: we have a match! */
408 * Retrieve the "seen" message list for the current room.
410 void CtdlGetSeen(char *buf, int which_set) {
413 /* Learn about the user and room in question */
414 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
416 if (which_set == ctdlsetseen_seen)
417 safestrncpy(buf, vbuf.v_seen, SIZ);
418 if (which_set == ctdlsetseen_answered)
419 safestrncpy(buf, vbuf.v_answered, SIZ);
425 * Manipulate the "seen msgs" string (or other message set strings)
427 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
428 int target_setting, int which_set,
429 struct ctdluser *which_user, struct ctdlroom *which_room) {
430 struct cdbdata *cdbfr;
435 long hi = (-1L); /// TODO: we just write here. y?
444 char *is_set; /* actually an array of booleans */
446 /* Don't bother doing *anything* if we were passed a list of zero messages */
447 if (num_target_msgnums < 1) {
451 /* If no room was specified, we go with the current room. */
453 which_room = &CC->room;
456 /* If no user was specified, we go with the current user. */
458 which_user = &CC->user;
461 syslog(LOG_DEBUG, "msgbase: CtdlSetSeen(%d msgs starting with %ld, %s, %d) in <%s>",
462 num_target_msgnums, target_msgnums[0],
463 (target_setting ? "SET" : "CLEAR"),
467 /* Learn about the user and room in question */
468 CtdlGetRelationship(&vbuf, which_user, which_room);
470 /* Load the message list */
471 cdbfr = cdb_fetch(CDB_MSGLISTS, &which_room->QRnumber, sizeof(long));
473 msglist = (long *) cdbfr->ptr;
474 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
475 num_msgs = cdbfr->len / sizeof(long);
478 return; /* No messages at all? No further action. */
481 is_set = malloc(num_msgs * sizeof(char));
482 memset(is_set, 0, (num_msgs * sizeof(char)) );
484 /* Decide which message set we're manipulating */
486 case ctdlsetseen_seen:
487 vset = NewStrBufPlain(vbuf.v_seen, -1);
489 case ctdlsetseen_answered:
490 vset = NewStrBufPlain(vbuf.v_answered, -1);
497 #if 0 /* This is a special diagnostic section. Do not allow it to run during normal operation. */
498 syslog(LOG_DEBUG, "There are %d messages in the room.\n", num_msgs);
499 for (i=0; i<num_msgs; ++i) {
500 if ((i > 0) && (msglist[i] <= msglist[i-1])) abort();
502 syslog(LOG_DEBUG, "We are twiddling %d of them.\n", num_target_msgnums);
503 for (k=0; k<num_target_msgnums; ++k) {
504 if ((k > 0) && (target_msgnums[k] <= target_msgnums[k-1])) abort();
508 /* Translate the existing sequence set into an array of booleans */
509 setstr = NewStrBuf();
513 while (StrBufExtract_NextToken(setstr, vset, &pvset, ',') >= 0) {
515 StrBufExtract_token(lostr, setstr, 0, ':');
516 if (StrBufNum_tokens(setstr, ':') >= 2) {
517 StrBufExtract_token(histr, setstr, 1, ':');
521 StrBufAppendBuf(histr, lostr, 0);
524 if (!strcmp(ChrPtr(histr), "*")) {
531 for (i = 0; i < num_msgs; ++i) {
532 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
542 /* Now translate the array of booleans back into a sequence set */
548 for (i=0; i<num_msgs; ++i) {
552 for (k=0; k<num_target_msgnums; ++k) {
553 if (msglist[i] == target_msgnums[k]) {
554 is_seen = target_setting;
558 if ((was_seen == 0) && (is_seen == 1)) {
561 else if ((was_seen == 1) && (is_seen == 0)) {
564 if (StrLength(vset) > 0) {
565 StrBufAppendBufPlain(vset, HKEY(","), 0);
568 StrBufAppendPrintf(vset, "%ld", hi);
571 StrBufAppendPrintf(vset, "%ld:%ld", lo, hi);
575 if ((is_seen) && (i == num_msgs - 1)) {
576 if (StrLength(vset) > 0) {
577 StrBufAppendBufPlain(vset, HKEY(","), 0);
579 if ((i==0) || (was_seen == 0)) {
580 StrBufAppendPrintf(vset, "%ld", msglist[i]);
583 StrBufAppendPrintf(vset, "%ld:%ld", lo, msglist[i]);
591 * We will have to stuff this string back into a 4096 byte buffer, so if it's
592 * larger than that now, truncate it by removing tokens from the beginning.
593 * The limit of 100 iterations is there to prevent an infinite loop in case
594 * something unexpected happens.
596 int number_of_truncations = 0;
597 while ( (StrLength(vset) > SIZ) && (number_of_truncations < 100) ) {
598 StrBufRemove_token(vset, 0, ',');
599 ++number_of_truncations;
603 * If we're truncating the sequence set of messages marked with the 'seen' flag,
604 * we want the earliest messages (the truncated ones) to be marked, not unmarked.
605 * Otherwise messages at the beginning will suddenly appear to be 'unseen'.
607 if ( (which_set == ctdlsetseen_seen) && (number_of_truncations > 0) ) {
609 first_tok = NewStrBuf();
610 StrBufExtract_token(first_tok, vset, 0, ',');
611 StrBufRemove_token(vset, 0, ',');
613 if (StrBufNum_tokens(first_tok, ':') > 1) {
614 StrBufRemove_token(first_tok, 0, ':');
618 new_set = NewStrBuf();
619 StrBufAppendBufPlain(new_set, HKEY("1:"), 0);
620 StrBufAppendBuf(new_set, first_tok, 0);
621 StrBufAppendBufPlain(new_set, HKEY(":"), 0);
622 StrBufAppendBuf(new_set, vset, 0);
625 FreeStrBuf(&first_tok);
629 /* Decide which message set we're manipulating */
631 case ctdlsetseen_seen:
632 safestrncpy(vbuf.v_seen, ChrPtr(vset), sizeof vbuf.v_seen);
634 case ctdlsetseen_answered:
635 safestrncpy(vbuf.v_answered, ChrPtr(vset), sizeof vbuf.v_answered);
641 CtdlSetRelationship(&vbuf, which_user, which_room);
647 * API function to perform an operation for each qualifying message in the
648 * current room. (Returns the number of messages processed.)
650 int CtdlForEachMessage(int mode, long ref, char *search_string,
652 struct CtdlMessage *compare,
653 ForEachMsgCallback CallBack,
658 struct cdbdata *cdbfr;
659 long *msglist = NULL;
661 int num_processed = 0;
664 struct CtdlMessage *msg = NULL;
667 int printed_lastold = 0;
668 int num_search_msgs = 0;
669 long *search_msgs = NULL;
671 int need_to_free_re = 0;
674 if ((content_type) && (!IsEmptyStr(content_type))) {
675 regcomp(&re, content_type, 0);
679 /* Learn about the user and room in question */
680 if (server_shutting_down) {
681 if (need_to_free_re) regfree(&re);
684 CtdlGetUser(&CC->user, CC->curr_user);
686 if (server_shutting_down) {
687 if (need_to_free_re) regfree(&re);
690 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
692 if (server_shutting_down) {
693 if (need_to_free_re) regfree(&re);
697 /* Load the message list */
698 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
700 if (need_to_free_re) regfree(&re);
701 return 0; /* No messages at all? No further action. */
704 msglist = (long *) cdbfr->ptr;
705 num_msgs = cdbfr->len / sizeof(long);
707 cdbfr->ptr = NULL; /* clear this so that cdb_free() doesn't free it */
708 cdb_free(cdbfr); /* we own this memory now */
711 * Now begin the traversal.
713 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
715 /* If the caller is looking for a specific MIME type, filter
716 * out all messages which are not of the type requested.
718 if ((content_type != NULL) && (!IsEmptyStr(content_type))) {
720 /* This call to GetMetaData() sits inside this loop
721 * so that we only do the extra database read per msg
722 * if we need to. Doing the extra read all the time
723 * really kills the server. If we ever need to use
724 * metadata for another search criterion, we need to
725 * move the read somewhere else -- but still be smart
726 * enough to only do the read if the caller has
727 * specified something that will need it.
729 if (server_shutting_down) {
730 if (need_to_free_re) regfree(&re);
734 GetMetaData(&smi, msglist[a]);
736 /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
737 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
743 num_msgs = sort_msglist(msglist, num_msgs);
745 /* If a template was supplied, filter out the messages which
746 * don't match. (This could induce some delays!)
749 if (compare != NULL) {
750 for (a = 0; a < num_msgs; ++a) {
751 if (server_shutting_down) {
752 if (need_to_free_re) regfree(&re);
756 msg = CtdlFetchMessage(msglist[a], 1, 1);
758 if (CtdlMsgCmp(msg, compare)) {
767 /* If a search string was specified, get a message list from
768 * the full text index and remove messages which aren't on both
772 * Since the lists are sorted and strictly ascending, and the
773 * output list is guaranteed to be shorter than or equal to the
774 * input list, we overwrite the bottom of the input list. This
775 * eliminates the need to memmove big chunks of the list over and
778 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
780 /* Call search module via hook mechanism.
781 * NULL means use any search function available.
782 * otherwise replace with a char * to name of search routine
784 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
786 if (num_search_msgs > 0) {
790 orig_num_msgs = num_msgs;
792 for (i=0; i<orig_num_msgs; ++i) {
793 for (j=0; j<num_search_msgs; ++j) {
794 if (msglist[i] == search_msgs[j]) {
795 msglist[num_msgs++] = msglist[i];
801 num_msgs = 0; /* No messages qualify */
803 if (search_msgs != NULL) free(search_msgs);
805 /* Now that we've purged messages which don't contain the search
806 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
813 * Now iterate through the message list, according to the
814 * criteria supplied by the caller.
817 for (a = 0; a < num_msgs; ++a) {
818 if (server_shutting_down) {
819 if (need_to_free_re) regfree(&re);
821 return num_processed;
823 thismsg = msglist[a];
824 if (mode == MSGS_ALL) {
828 is_seen = is_msg_in_sequence_set(
829 vbuf.v_seen, thismsg);
830 if (is_seen) lastold = thismsg;
836 || ((mode == MSGS_OLD) && (is_seen))
837 || ((mode == MSGS_NEW) && (!is_seen))
838 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
839 || ((mode == MSGS_FIRST) && (a < ref))
840 || ((mode == MSGS_GT) && (thismsg > ref))
841 || ((mode == MSGS_LT) && (thismsg < ref))
842 || ((mode == MSGS_EQ) && (thismsg == ref))
845 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
847 CallBack(lastold, userdata);
851 if (CallBack) CallBack(thismsg, userdata);
855 if (need_to_free_re) regfree(&re);
858 * We cache the most recent msglist in order to do security checks later
860 if (CC->client_socket > 0) {
861 if (CC->cached_msglist != NULL) {
862 free(CC->cached_msglist);
864 CC->cached_msglist = msglist;
865 CC->cached_num_msgs = num_msgs;
871 return num_processed;
877 * memfmout() - Citadel text formatter and paginator.
878 * Although the original purpose of this routine was to format
879 * text to the reader's screen width, all we're really using it
880 * for here is to format text out to 80 columns before sending it
881 * to the client. The client software may reformat it again.
884 char *mptr, /* where are we going to get our text from? */
885 const char *nl /* string to terminate lines with */
888 unsigned char ch = 0;
895 while (ch=*(mptr++), ch != 0) {
898 if (client_write(outbuf, len) == -1)
900 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
904 if (client_write(nl, nllen) == -1)
906 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
911 else if (ch == '\r') {
912 /* Ignore carriage returns. Newlines are always LF or CRLF but never CR. */
914 else if (isspace(ch)) {
915 if (column > 72) { /* Beyond 72 columns, break on the next space */
916 if (client_write(outbuf, len) == -1)
918 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
922 if (client_write(nl, nllen) == -1)
924 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
937 if (column > 1000) { /* Beyond 1000 columns, break anywhere */
938 if (client_write(outbuf, len) == -1)
940 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
944 if (client_write(nl, nllen) == -1)
946 syslog(LOG_ERR, "msgbase: memfmout(): aborting due to write failure");
954 if (client_write(outbuf, len) == -1)
956 syslog(LOG_ERR, "msgbase: memfmout() aborting due to write failure");
959 client_write(nl, nllen);
967 * Callback function for mime parser that simply lists the part
969 void list_this_part(char *name, char *filename, char *partnum, char *disp,
970 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
971 char *cbid, void *cbuserdata)
975 ma = (struct ma_info *)cbuserdata;
976 if (ma->is_ma == 0) {
977 cprintf("part=%s|%s|%s|%s|%s|%ld|%s|%s\n",
990 * Callback function for multipart prefix
992 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
993 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
994 char *cbid, void *cbuserdata)
998 ma = (struct ma_info *)cbuserdata;
999 if (!strcasecmp(cbtype, "multipart/alternative")) {
1003 if (ma->is_ma == 0) {
1004 cprintf("pref=%s|%s\n", partnum, cbtype);
1009 * Callback function for multipart sufffix
1011 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
1012 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1013 char *cbid, void *cbuserdata)
1017 ma = (struct ma_info *)cbuserdata;
1018 if (ma->is_ma == 0) {
1019 cprintf("suff=%s|%s\n", partnum, cbtype);
1021 if (!strcasecmp(cbtype, "multipart/alternative")) {
1028 * Callback function for mime parser that opens a section for downloading
1029 * we use serv_files function here:
1031 extern void OpenCmdResult(char *filename, const char *mime_type);
1032 void mime_download(char *name, char *filename, char *partnum, char *disp,
1033 void *content, char *cbtype, char *cbcharset, size_t length,
1034 char *encoding, char *cbid, void *cbuserdata)
1038 /* Silently go away if there's already a download open. */
1039 if (CC->download_fp != NULL)
1043 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1044 || (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1046 CC->download_fp = tmpfile();
1047 if (CC->download_fp == NULL) {
1048 syslog(LOG_EMERG, "msgbase: mime_download() couldn't write: %m");
1049 cprintf("%d cannot open temporary file: %s\n", ERROR + INTERNAL_ERROR, strerror(errno));
1053 rv = fwrite(content, length, 1, CC->download_fp);
1055 syslog(LOG_EMERG, "msgbase: mime_download() Couldn't write: %m");
1056 cprintf("%d unable to write tempfile.\n", ERROR + TOO_BIG);
1057 fclose(CC->download_fp);
1058 CC->download_fp = NULL;
1061 fflush(CC->download_fp);
1062 rewind(CC->download_fp);
1064 OpenCmdResult(filename, cbtype);
1071 * Callback function for mime parser that outputs a section all at once.
1072 * We can specify the desired section by part number *or* content-id.
1074 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
1075 void *content, char *cbtype, char *cbcharset, size_t length,
1076 char *encoding, char *cbid, void *cbuserdata)
1078 int *found_it = (int *)cbuserdata;
1081 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1082 || (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1085 cprintf("%d %d|-1|%s|%s|%s\n",
1092 client_write(content, length);
1096 struct CtdlMessage *CtdlDeserializeMessage(long msgnum, int with_body, const char *Buffer, long Length)
1098 struct CtdlMessage *ret = NULL;
1100 const char *upper_bound;
1102 cit_uint8_t field_header;
1106 upper_bound = Buffer + Length;
1108 /* Parse the three bytes that begin EVERY message on disk.
1109 * The first is always 0xFF, the on-disk magic number.
1110 * The second is the anonymous/public type byte.
1111 * The third is the format type byte (vari, fixed, or MIME).
1115 syslog(LOG_ERR, "msgbase: message %ld appears to be corrupted", msgnum);
1118 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1119 memset(ret, 0, sizeof(struct CtdlMessage));
1121 ret->cm_magic = CTDLMESSAGE_MAGIC;
1122 ret->cm_anon_type = *mptr++; /* Anon type byte */
1123 ret->cm_format_type = *mptr++; /* Format type byte */
1126 * The rest is zero or more arbitrary fields. Load them in.
1127 * We're done when we encounter either a zero-length field or
1128 * have just processed the 'M' (message text) field.
1131 field_header = '\0';
1134 /* work around possibly buggy messages: */
1135 while (field_header == '\0')
1137 if (mptr >= upper_bound) {
1140 field_header = *mptr++;
1142 if (mptr >= upper_bound) {
1145 which = field_header;
1148 CM_SetField(ret, which, mptr, len);
1150 mptr += len + 1; /* advance to next field */
1152 } while ((mptr < upper_bound) && (field_header != 'M'));
1159 * Load a message from disk into memory.
1160 * This is used by CtdlOutputMsg() and other fetch functions.
1162 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1163 * using the CM_Free(); function.
1165 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body, int run_msg_hooks)
1167 struct cdbdata *dmsgtext;
1168 struct CtdlMessage *ret = NULL;
1170 syslog(LOG_DEBUG, "msgbase: CtdlFetchMessage(%ld, %d)", msgnum, with_body);
1171 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1172 if (dmsgtext == NULL) {
1173 syslog(LOG_ERR, "msgbase: CtdlFetchMessage(%ld, %d) Failed!", msgnum, with_body);
1177 if (dmsgtext->ptr[dmsgtext->len - 1] != '\0')
1179 syslog(LOG_ERR, "msgbase: CtdlFetchMessage(%ld, %d) Forcefully terminating message!!", msgnum, with_body);
1180 dmsgtext->ptr[dmsgtext->len - 1] = '\0';
1183 ret = CtdlDeserializeMessage(msgnum, with_body, dmsgtext->ptr, dmsgtext->len);
1191 /* Always make sure there's something in the msg text field. If
1192 * it's NULL, the message text is most likely stored separately,
1193 * so go ahead and fetch that. Failing that, just set a dummy
1194 * body so other code doesn't barf.
1196 if ( (CM_IsEmpty(ret, eMesageText)) && (with_body) ) {
1197 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1198 if (dmsgtext != NULL) {
1199 CM_SetAsField(ret, eMesageText, &dmsgtext->ptr, dmsgtext->len - 1);
1203 if (CM_IsEmpty(ret, eMesageText)) {
1204 CM_SetField(ret, eMesageText, HKEY("\r\n\r\n (no text)\r\n"));
1207 /* Perform "before read" hooks (aborting if any return nonzero) */
1208 if (run_msg_hooks && (PerformMessageHooks(ret, NULL, EVT_BEFOREREAD) > 0)) {
1219 * Pre callback function for multipart/alternative
1221 * NOTE: this differs from the standard behavior for a reason. Normally when
1222 * displaying multipart/alternative you want to show the _last_ usable
1223 * format in the message. Here we show the _first_ one, because it's
1224 * usually text/plain. Since this set of functions is designed for text
1225 * output to non-MIME-aware clients, this is the desired behavior.
1228 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1229 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1230 char *cbid, void *cbuserdata)
1234 ma = (struct ma_info *)cbuserdata;
1235 syslog(LOG_DEBUG, "msgbase: fixed_output_pre() type=<%s>", cbtype);
1236 if (!strcasecmp(cbtype, "multipart/alternative")) {
1240 if (!strcasecmp(cbtype, "message/rfc822")) {
1246 * Post callback function for multipart/alternative
1248 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1249 void *content, char *cbtype, char *cbcharset, size_t length,
1250 char *encoding, char *cbid, void *cbuserdata)
1254 ma = (struct ma_info *)cbuserdata;
1255 syslog(LOG_DEBUG, "msgbase: fixed_output_post() type=<%s>", cbtype);
1256 if (!strcasecmp(cbtype, "multipart/alternative")) {
1260 if (!strcasecmp(cbtype, "message/rfc822")) {
1266 * Inline callback function for mime parser that wants to display text
1268 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1269 void *content, char *cbtype, char *cbcharset, size_t length,
1270 char *encoding, char *cbid, void *cbuserdata)
1277 ma = (struct ma_info *)cbuserdata;
1280 "msgbase: fixed_output() part %s: %s (%s) (%ld bytes)",
1281 partnum, filename, cbtype, (long)length
1285 * If we're in the middle of a multipart/alternative scope and
1286 * we've already printed another section, skip this one.
1288 if ( (ma->is_ma) && (ma->did_print) ) {
1289 syslog(LOG_DEBUG, "msgbase: skipping part %s (%s)", partnum, cbtype);
1294 if ( (!strcasecmp(cbtype, "text/plain"))
1295 || (IsEmptyStr(cbtype)) ) {
1298 client_write(wptr, length);
1299 if (wptr[length-1] != '\n') {
1306 if (!strcasecmp(cbtype, "text/html")) {
1307 ptr = html_to_ascii(content, length, 80, 0);
1309 client_write(ptr, wlen);
1310 if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
1317 if (ma->use_fo_hooks) {
1318 if (PerformFixedOutputHooks(cbtype, content, length)) {
1319 /* above function returns nonzero if it handled the part */
1324 if (strncasecmp(cbtype, "multipart/", 10)) {
1325 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1326 partnum, filename, cbtype, (long)length);
1332 * The client is elegant and sophisticated and wants to be choosy about
1333 * MIME content types, so figure out which multipart/alternative part
1334 * we're going to send.
1336 * We use a system of weights. When we find a part that matches one of the
1337 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1338 * and then set ma->chosen_pref to that MIME type's position in our preference
1339 * list. If we then hit another match, we only replace the first match if
1340 * the preference value is lower.
1342 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1343 void *content, char *cbtype, char *cbcharset, size_t length,
1344 char *encoding, char *cbid, void *cbuserdata)
1350 ma = (struct ma_info *)cbuserdata;
1352 // NOTE: REMOVING THIS CONDITIONAL FIXES BUG 220
1353 // http://bugzilla.citadel.org/show_bug.cgi?id=220
1354 // I don't know if there are any side effects! Please TEST TEST TEST
1355 //if (ma->is_ma > 0) {
1357 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1358 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1359 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1360 if (i < ma->chosen_pref) {
1361 syslog(LOG_DEBUG, "msgbase: setting chosen part to <%s>", partnum);
1362 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1363 ma->chosen_pref = i;
1370 * Now that we've chosen our preferred part, output it.
1372 void output_preferred(char *name,
1386 int add_newline = 0;
1389 char *decoded = NULL;
1390 size_t bytes_decoded;
1393 ma = (struct ma_info *)cbuserdata;
1395 /* This is not the MIME part you're looking for... */
1396 if (strcasecmp(partnum, ma->chosen_part)) return;
1398 /* If the content-type of this part is in our preferred formats
1399 * list, we can simply output it verbatim.
1401 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1402 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1403 if (!strcasecmp(buf, cbtype)) {
1404 /* Yeah! Go! W00t!! */
1405 if (ma->dont_decode == 0)
1406 rc = mime_decode_now (content,
1412 break; /* Give us the chance, maybe theres another one. */
1414 if (rc == 0) text_content = (char *)content;
1416 text_content = decoded;
1417 length = bytes_decoded;
1420 if (text_content[length-1] != '\n') {
1423 cprintf("Content-type: %s", cbtype);
1424 if (!IsEmptyStr(cbcharset)) {
1425 cprintf("; charset=%s", cbcharset);
1427 cprintf("\nContent-length: %d\n",
1428 (int)(length + add_newline) );
1429 if (!IsEmptyStr(encoding)) {
1430 cprintf("Content-transfer-encoding: %s\n", encoding);
1433 cprintf("Content-transfer-encoding: 7bit\n");
1435 cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1437 if (client_write(text_content, length) == -1)
1439 syslog(LOG_ERR, "msgbase: output_preferred() aborting due to write failure");
1442 if (add_newline) cprintf("\n");
1443 if (decoded != NULL) free(decoded);
1448 /* No translations required or possible: output as text/plain */
1449 cprintf("Content-type: text/plain\n\n");
1451 if (ma->dont_decode == 0)
1452 rc = mime_decode_now (content,
1458 return; /* Give us the chance, maybe theres another one. */
1460 if (rc == 0) text_content = (char *)content;
1462 text_content = decoded;
1463 length = bytes_decoded;
1466 fixed_output(name, filename, partnum, disp, text_content, cbtype, cbcharset,
1467 length, encoding, cbid, cbuserdata);
1468 if (decoded != NULL) free(decoded);
1473 char desired_section[64];
1480 * Callback function for
1482 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1483 void *content, char *cbtype, char *cbcharset, size_t length,
1484 char *encoding, char *cbid, void *cbuserdata)
1486 struct encapmsg *encap;
1488 encap = (struct encapmsg *)cbuserdata;
1490 /* Only proceed if this is the desired section... */
1491 if (!strcasecmp(encap->desired_section, partnum)) {
1492 encap->msglen = length;
1493 encap->msg = malloc(length + 2);
1494 memcpy(encap->msg, content, length);
1501 * Determine whether the specified message exists in the cached_msglist
1502 * (This is a security check)
1504 int check_cached_msglist(long msgnum) {
1506 /* cases in which we skip the check */
1507 if (!CC) return om_ok; /* not a session */
1508 if (CC->client_socket <= 0) return om_ok; /* not a client session */
1509 if (CC->cached_msglist == NULL) return om_access_denied; /* no msglist fetched */
1510 if (CC->cached_num_msgs == 0) return om_access_denied; /* nothing to check */
1513 /* Do a binary search within the cached_msglist for the requested msgnum */
1515 int max = (CC->cached_num_msgs - 1);
1517 while (max >= min) {
1518 int middle = min + (max-min) / 2 ;
1519 if (msgnum == CC->cached_msglist[middle]) {
1522 if (msgnum > CC->cached_msglist[middle]) {
1530 return om_access_denied;
1536 * Get a message off disk. (returns om_* values found in msgbase.h)
1539 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1540 int mode, /* how would you like that message? */
1541 int headers_only, /* eschew the message body? */
1542 int do_proto, /* do Citadel protocol responses? */
1543 int crlf, /* Use CRLF newlines instead of LF? */
1544 char *section, /* NULL or a message/rfc822 section */
1545 int flags, /* various flags; see msgbase.h */
1550 struct CtdlMessage *TheMessage = NULL;
1551 int retcode = CIT_OK;
1552 struct encapmsg encap;
1555 syslog(LOG_DEBUG, "msgbase: CtdlOutputMsg(msgnum=%ld, mode=%d, section=%s)",
1557 (section ? section : "<>")
1560 r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
1563 if (r == om_not_logged_in) {
1564 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1567 cprintf("%d An unknown error has occurred.\n", ERROR);
1574 * Check to make sure the message is actually IN this room
1576 r = check_cached_msglist(msg_num);
1577 if (r == om_access_denied) {
1578 /* Not in the cache? We get ONE shot to check it again. */
1579 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
1580 r = check_cached_msglist(msg_num);
1583 syslog(LOG_DEBUG, "msgbase: security check fail; message %ld is not in %s",
1584 msg_num, CC->room.QRname
1587 if (r == om_access_denied) {
1588 cprintf("%d message %ld was not found in this room\n",
1589 ERROR + HIGHER_ACCESS_REQUIRED,
1598 * Fetch the message from disk. If we're in HEADERS_FAST mode,
1599 * request that we don't even bother loading the body into memory.
1601 if (headers_only == HEADERS_FAST) {
1602 TheMessage = CtdlFetchMessage(msg_num, 0, 1);
1605 TheMessage = CtdlFetchMessage(msg_num, 1, 1);
1608 if (TheMessage == NULL) {
1609 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1610 ERROR + MESSAGE_NOT_FOUND, msg_num);
1611 return(om_no_such_msg);
1614 /* Here is the weird form of this command, to process only an
1615 * encapsulated message/rfc822 section.
1617 if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1618 memset(&encap, 0, sizeof encap);
1619 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1620 mime_parser(CM_RANGE(TheMessage, eMesageText),
1621 *extract_encapsulated_message,
1622 NULL, NULL, (void *)&encap, 0
1625 if ((Author != NULL) && (*Author == NULL))
1628 CM_GetAsField(TheMessage, eAuthor, Author, &len);
1630 if ((Address != NULL) && (*Address == NULL))
1633 CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
1635 if ((MessageID != NULL) && (*MessageID == NULL))
1638 CM_GetAsField(TheMessage, emessageId, MessageID, &len);
1640 CM_Free(TheMessage);
1644 encap.msg[encap.msglen] = 0;
1645 TheMessage = convert_internet_message(encap.msg);
1646 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1648 /* Now we let it fall through to the bottom of this
1649 * function, because TheMessage now contains the
1650 * encapsulated message instead of the top-level
1651 * message. Isn't that neat?
1656 cprintf("%d msg %ld has no part %s\n",
1657 ERROR + MESSAGE_NOT_FOUND,
1661 retcode = om_no_such_msg;
1666 /* Ok, output the message now */
1667 if (retcode == CIT_OK)
1668 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
1669 if ((Author != NULL) && (*Author == NULL))
1672 CM_GetAsField(TheMessage, eAuthor, Author, &len);
1674 if ((Address != NULL) && (*Address == NULL))
1677 CM_GetAsField(TheMessage, erFc822Addr, Address, &len);
1679 if ((MessageID != NULL) && (*MessageID == NULL))
1682 CM_GetAsField(TheMessage, emessageId, MessageID, &len);
1685 CM_Free(TheMessage);
1692 void OutputCtdlMsgHeaders(
1693 struct CtdlMessage *TheMessage,
1694 int do_proto) /* do Citadel protocol responses? */
1699 char display_name[256];
1701 /* begin header processing loop for Citadel message format */
1702 safestrncpy(display_name, "<unknown>", sizeof display_name);
1703 if (!CM_IsEmpty(TheMessage, eAuthor)) {
1704 strcpy(buf, TheMessage->cm_fields[eAuthor]);
1705 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1706 safestrncpy(display_name, "****", sizeof display_name);
1708 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1709 safestrncpy(display_name, "anonymous", sizeof display_name);
1712 safestrncpy(display_name, buf, sizeof display_name);
1714 if ((is_room_aide())
1715 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1716 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1717 size_t tmp = strlen(display_name);
1718 snprintf(&display_name[tmp],
1719 sizeof display_name - tmp,
1724 /* Don't show Internet address for users on the
1725 * local Citadel network.
1728 if (!CM_IsEmpty(TheMessage, eNodeName) &&
1729 (haschar(TheMessage->cm_fields[eNodeName], '.') == 0))
1734 /* Now spew the header fields in the order we like them. */
1735 for (i=0; i< NDiskFields; ++i) {
1737 Field = FieldOrder[i];
1738 if (Field != eMesageText) {
1739 if ( (!CM_IsEmpty(TheMessage, Field))
1740 && (msgkeys[Field] != NULL) ) {
1741 if ((Field == eenVelopeTo) ||
1742 (Field == eRecipient) ||
1743 (Field == eCarbonCopY)) {
1744 sanitize_truncated_recipient(TheMessage->cm_fields[Field]);
1746 if (Field == eAuthor) {
1747 if (do_proto) cprintf("%s=%s\n",
1751 else if ((Field == erFc822Addr) && (suppress_f)) {
1754 /* Masquerade display name if needed */
1756 if (do_proto) cprintf("%s=%s\n",
1758 TheMessage->cm_fields[Field]
1767 void OutputRFC822MsgHeaders(
1768 struct CtdlMessage *TheMessage,
1769 int flags, /* should the bessage be exported clean */
1770 const char *nl, int nlen,
1771 char *mid, long sizeof_mid,
1772 char *suser, long sizeof_suser,
1773 char *luser, long sizeof_luser,
1774 char *fuser, long sizeof_fuser,
1775 char *snode, long sizeof_snode)
1777 char datestamp[100];
1778 int subject_found = 0;
1785 for (i = 0; i < NDiskFields; ++i) {
1786 if (TheMessage->cm_fields[FieldOrder[i]]) {
1787 mptr = mpptr = TheMessage->cm_fields[FieldOrder[i]];
1788 switch (FieldOrder[i]) {
1790 safestrncpy(luser, mptr, sizeof_luser);
1791 safestrncpy(suser, mptr, sizeof_suser);
1794 if ((flags & QP_EADDR) != 0) {
1795 mptr = qp_encode_email_addrs(mptr);
1797 sanitize_truncated_recipient(mptr);
1798 cprintf("CC: %s%s", mptr, nl);
1801 cprintf("Return-Path: %s%s", mptr, nl);
1804 cprintf("List-ID: %s%s", mptr, nl);
1807 if ((flags & QP_EADDR) != 0)
1808 mptr = qp_encode_email_addrs(mptr);
1810 while ((*hptr != '\0') && isspace(*hptr))
1812 if (!IsEmptyStr(hptr))
1813 cprintf("Envelope-To: %s%s", hptr, nl);
1816 cprintf("Subject: %s%s", mptr, nl);
1820 safestrncpy(mid, mptr, sizeof_mid); /// TODO: detect @ here and copy @nodename in if not found.
1823 safestrncpy(fuser, mptr, sizeof_fuser);
1824 /* case eOriginalRoom:
1825 cprintf("X-Citadel-Room: %s%s",
1830 safestrncpy(snode, mptr, sizeof_snode);
1833 if (haschar(mptr, '@') == 0)
1835 sanitize_truncated_recipient(mptr);
1836 cprintf("To: %s@%s", mptr, CtdlGetConfigStr("c_fqdn"));
1841 if ((flags & QP_EADDR) != 0) {
1842 mptr = qp_encode_email_addrs(mptr);
1844 sanitize_truncated_recipient(mptr);
1845 cprintf("To: %s", mptr);
1850 datestring(datestamp, sizeof datestamp,
1851 atol(mptr), DATESTRING_RFC822);
1852 cprintf("Date: %s%s", datestamp, nl);
1855 cprintf("References: ");
1856 k = num_tokens(mptr, '|');
1857 for (j=0; j<k; ++j) {
1858 extract_token(buf, mptr, j, '|', sizeof buf);
1859 cprintf("<%s>", buf);
1870 while ((*hptr != '\0') && isspace(*hptr))
1872 if (!IsEmptyStr(hptr))
1873 cprintf("Reply-To: %s%s", mptr, nl);
1889 /* these don't map to mime message headers. */
1897 if (subject_found == 0) {
1898 cprintf("Subject: (no subject)%s", nl);
1903 void Dump_RFC822HeadersBody(
1904 struct CtdlMessage *TheMessage,
1905 int headers_only, /* eschew the message body? */
1906 int flags, /* should the bessage be exported clean? */
1908 const char *nl, int nlen)
1910 cit_uint8_t prev_ch;
1912 const char *StartOfText = StrBufNOTNULL;
1915 int nllen = strlen(nl);
1919 mptr = TheMessage->cm_fields[eMesageText];
1923 while (*mptr != '\0') {
1924 if (*mptr == '\r') {
1931 eoh = (*(mptr+1) == '\r') && (*(mptr+2) == '\n');
1933 eoh = *(mptr+1) == '\n';
1937 StartOfText = strchr(StartOfText, '\n');
1938 StartOfText = strchr(StartOfText, '\n');
1941 if (((headers_only == HEADERS_NONE) && (mptr >= StartOfText)) ||
1942 ((headers_only == HEADERS_ONLY) && (mptr < StartOfText)) ||
1943 ((headers_only != HEADERS_NONE) &&
1944 (headers_only != HEADERS_ONLY))
1946 if (*mptr == '\n') {
1947 memcpy(&outbuf[outlen], nl, nllen);
1949 outbuf[outlen] = '\0';
1952 outbuf[outlen++] = *mptr;
1956 if (flags & ESC_DOT)
1958 if ((prev_ch == '\n') &&
1960 ((*(mptr+1) == '\r') || (*(mptr+1) == '\n')))
1962 outbuf[outlen++] = '.';
1967 if (outlen > 1000) {
1968 if (client_write(outbuf, outlen) == -1)
1970 syslog(LOG_ERR, "msgbase: Dump_RFC822HeadersBody() aborting due to write failure");
1973 lfSent = (outbuf[outlen - 1] == '\n');
1978 client_write(outbuf, outlen);
1979 lfSent = (outbuf[outlen - 1] == '\n');
1982 client_write(nl, nlen);
1987 /* If the format type on disk is 1 (fixed-format), then we want
1988 * everything to be output completely literally ... regardless of
1989 * what message transfer format is in use.
1991 void DumpFormatFixed(
1992 struct CtdlMessage *TheMessage,
1993 int mode, /* how would you like that message? */
1994 const char *nl, int nllen)
2002 mptr = TheMessage->cm_fields[eMesageText];
2004 if (mode == MT_MIME) {
2005 cprintf("Content-type: text/plain\n\n");
2009 while (ch = *mptr++, ch > 0) {
2013 if ((buflen > 250) && (!xlline)){
2017 while ((buflen > 0) &&
2018 (!isspace(buf[buflen])))
2024 mptr -= tbuflen - buflen;
2029 /* if we reach the outer bounds of our buffer,
2030 abort without respect what whe purge. */
2033 (buflen > SIZ - nllen - 2)))
2037 memcpy (&buf[buflen], nl, nllen);
2041 if (client_write(buf, buflen) == -1)
2043 syslog(LOG_ERR, "msgbase: DumpFormatFixed() aborting due to write failure");
2055 if (!IsEmptyStr(buf))
2056 cprintf("%s%s", buf, nl);
2060 * Get a message off disk. (returns om_* values found in msgbase.h)
2062 int CtdlOutputPreLoadedMsg(
2063 struct CtdlMessage *TheMessage,
2064 int mode, /* how would you like that message? */
2065 int headers_only, /* eschew the message body? */
2066 int do_proto, /* do Citadel protocol responses? */
2067 int crlf, /* Use CRLF newlines instead of LF? */
2068 int flags /* should the bessage be exported clean? */
2071 const char *nl; /* newline string */
2075 /* Buffers needed for RFC822 translation. These are all filled
2076 * using functions that are bounds-checked, and therefore we can
2077 * make them substantially smaller than SIZ.
2085 syslog(LOG_DEBUG, "msgbase: CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d",
2086 ((TheMessage == NULL) ? "NULL" : "not null"),
2087 mode, headers_only, do_proto, crlf
2090 strcpy(mid, "unknown");
2091 nl = (crlf ? "\r\n" : "\n");
2092 nlen = crlf ? 2 : 1;
2094 if (!CM_IsValidMsg(TheMessage)) {
2095 syslog(LOG_ERR, "msgbase: error; invalid preloaded message for output");
2096 return(om_no_such_msg);
2099 /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2100 * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2102 if ( (flags & SUPPRESS_ENV_TO) && (!CM_IsEmpty(TheMessage, eenVelopeTo)) ) {
2103 memset(TheMessage->cm_fields[eenVelopeTo], ' ', TheMessage->cm_lengths[eenVelopeTo]);
2106 /* Are we downloading a MIME component? */
2107 if (mode == MT_DOWNLOAD) {
2108 if (TheMessage->cm_format_type != FMT_RFC822) {
2110 cprintf("%d This is not a MIME message.\n",
2111 ERROR + ILLEGAL_VALUE);
2112 } else if (CC->download_fp != NULL) {
2113 if (do_proto) cprintf(
2114 "%d You already have a download open.\n",
2115 ERROR + RESOURCE_BUSY);
2117 /* Parse the message text component */
2118 mime_parser(CM_RANGE(TheMessage, eMesageText),
2119 *mime_download, NULL, NULL, NULL, 0);
2120 /* If there's no file open by this time, the requested
2121 * section wasn't found, so print an error
2123 if (CC->download_fp == NULL) {
2124 if (do_proto) cprintf(
2125 "%d Section %s not found.\n",
2126 ERROR + FILE_NOT_FOUND,
2127 CC->download_desired_section);
2130 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
2133 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2134 * in a single server operation instead of opening a download file.
2136 if (mode == MT_SPEW_SECTION) {
2137 if (TheMessage->cm_format_type != FMT_RFC822) {
2139 cprintf("%d This is not a MIME message.\n",
2140 ERROR + ILLEGAL_VALUE);
2142 /* Parse the message text component */
2145 mime_parser(CM_RANGE(TheMessage, eMesageText),
2146 *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2147 /* If section wasn't found, print an error
2150 if (do_proto) cprintf(
2151 "%d Section %s not found.\n",
2152 ERROR + FILE_NOT_FOUND,
2153 CC->download_desired_section);
2156 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
2159 /* now for the user-mode message reading loops */
2160 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2162 /* Does the caller want to skip the headers? */
2163 if (headers_only == HEADERS_NONE) goto START_TEXT;
2165 /* Tell the client which format type we're using. */
2166 if ( (mode == MT_CITADEL) && (do_proto) ) {
2167 cprintf("type=%d\n", TheMessage->cm_format_type);
2170 /* nhdr=yes means that we're only displaying headers, no body */
2171 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2172 && ((mode == MT_CITADEL) || (mode == MT_MIME))
2175 cprintf("nhdr=yes\n");
2178 if ((mode == MT_CITADEL) || (mode == MT_MIME))
2179 OutputCtdlMsgHeaders(TheMessage, do_proto);
2182 /* begin header processing loop for RFC822 transfer format */
2186 memcpy(snode, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")) + 1);
2187 if (mode == MT_RFC822)
2188 OutputRFC822MsgHeaders(
2193 suser, sizeof(suser),
2194 luser, sizeof(luser),
2195 fuser, sizeof(fuser),
2196 snode, sizeof(snode)
2200 for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2201 suser[i] = tolower(suser[i]);
2202 if (!isalnum(suser[i])) suser[i]='_';
2205 if (mode == MT_RFC822) {
2206 if (!strcasecmp(snode, NODENAME)) {
2207 safestrncpy(snode, FQDN, sizeof snode);
2210 /* Construct a fun message id */
2211 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
2212 if (strchr(mid, '@')==NULL) {
2213 cprintf("@%s", snode);
2217 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2218 cprintf("From: \"----\" <x@x.org>%s", nl);
2220 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2221 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2223 else if (!IsEmptyStr(fuser)) {
2224 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2227 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2230 /* Blank line signifying RFC822 end-of-headers */
2231 if (TheMessage->cm_format_type != FMT_RFC822) {
2236 /* end header processing loop ... at this point, we're in the text */
2238 if (headers_only == HEADERS_FAST) goto DONE;
2240 /* Tell the client about the MIME parts in this message */
2241 if (TheMessage->cm_format_type == FMT_RFC822) {
2242 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2243 memset(&ma, 0, sizeof(struct ma_info));
2244 mime_parser(CM_RANGE(TheMessage, eMesageText),
2245 (do_proto ? *list_this_part : NULL),
2246 (do_proto ? *list_this_pref : NULL),
2247 (do_proto ? *list_this_suff : NULL),
2250 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
2251 Dump_RFC822HeadersBody(
2260 if (headers_only == HEADERS_ONLY) {
2264 /* signify start of msg text */
2265 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2266 if (do_proto) cprintf("text\n");
2269 if (TheMessage->cm_format_type == FMT_FIXED)
2272 mode, /* how would you like that message? */
2275 /* If the message on disk is format 0 (Citadel vari-format), we
2276 * output using the formatter at 80 columns. This is the final output
2277 * form if the transfer format is RFC822, but if the transfer format
2278 * is Citadel proprietary, it'll still work, because the indentation
2279 * for new paragraphs is correct and the client will reformat the
2280 * message to the reader's screen width.
2282 if (TheMessage->cm_format_type == FMT_CITADEL) {
2283 if (mode == MT_MIME) {
2284 cprintf("Content-type: text/x-citadel-variformat\n\n");
2286 memfmout(TheMessage->cm_fields[eMesageText], nl);
2289 /* If the message on disk is format 4 (MIME), we've gotta hand it
2290 * off to the MIME parser. The client has already been told that
2291 * this message is format 1 (fixed format), so the callback function
2292 * we use will display those parts as-is.
2294 if (TheMessage->cm_format_type == FMT_RFC822) {
2295 memset(&ma, 0, sizeof(struct ma_info));
2297 if (mode == MT_MIME) {
2298 ma.use_fo_hooks = 0;
2299 strcpy(ma.chosen_part, "1");
2300 ma.chosen_pref = 9999;
2301 ma.dont_decode = CC->msg4_dont_decode;
2302 mime_parser(CM_RANGE(TheMessage, eMesageText),
2303 *choose_preferred, *fixed_output_pre,
2304 *fixed_output_post, (void *)&ma, 1);
2305 mime_parser(CM_RANGE(TheMessage, eMesageText),
2306 *output_preferred, NULL, NULL, (void *)&ma, 1);
2309 ma.use_fo_hooks = 1;
2310 mime_parser(CM_RANGE(TheMessage, eMesageText),
2311 *fixed_output, *fixed_output_pre,
2312 *fixed_output_post, (void *)&ma, 0);
2317 DONE: /* now we're done */
2318 if (do_proto) cprintf("000\n");
2323 * Save one or more message pointers into a specified room
2324 * (Returns 0 for success, nonzero for failure)
2325 * roomname may be NULL to use the current room
2327 * Note that the 'supplied_msg' field may be set to NULL, in which case
2328 * the message will be fetched from disk, by number, if we need to perform
2329 * replication checks. This adds an additional database read, so if the
2330 * caller already has the message in memory then it should be supplied. (Obviously
2331 * this mode of operation only works if we're saving a single message.)
2333 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2334 int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2337 char hold_rm[ROOMNAMELEN];
2338 struct cdbdata *cdbfr;
2341 long highest_msg = 0L;
2344 struct CtdlMessage *msg = NULL;
2346 long *msgs_to_be_merged = NULL;
2347 int num_msgs_to_be_merged = 0;
2350 "msgbase: CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)",
2351 roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2354 strcpy(hold_rm, CC->room.QRname);
2357 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2358 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2359 if (num_newmsgs > 1) supplied_msg = NULL;
2361 /* Now the regular stuff */
2362 if (CtdlGetRoomLock(&CC->room,
2363 ((roomname != NULL) ? roomname : CC->room.QRname) )
2365 syslog(LOG_ERR, "msgbase: no such room <%s>", roomname);
2366 return(ERROR + ROOM_NOT_FOUND);
2370 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2371 num_msgs_to_be_merged = 0;
2374 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2375 if (cdbfr == NULL) {
2379 msglist = (long *) cdbfr->ptr;
2380 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2381 num_msgs = cdbfr->len / sizeof(long);
2386 /* Create a list of msgid's which were supplied by the caller, but do
2387 * not already exist in the target room. It is absolutely taboo to
2388 * have more than one reference to the same message in a room.
2390 for (i=0; i<num_newmsgs; ++i) {
2392 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2393 if (msglist[j] == newmsgidlist[i]) {
2398 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2402 syslog(LOG_DEBUG, "msgbase: %d unique messages to be merged", num_msgs_to_be_merged);
2405 * Now merge the new messages
2407 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2408 if (msglist == NULL) {
2409 syslog(LOG_ALERT, "msgbase: ERROR; can't realloc message list!");
2410 free(msgs_to_be_merged);
2411 return (ERROR + INTERNAL_ERROR);
2413 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2414 num_msgs += num_msgs_to_be_merged;
2416 /* Sort the message list, so all the msgid's are in order */
2417 num_msgs = sort_msglist(msglist, num_msgs);
2419 /* Determine the highest message number */
2420 highest_msg = msglist[num_msgs - 1];
2422 /* Write it back to disk. */
2423 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2424 msglist, (int)(num_msgs * sizeof(long)));
2426 /* Free up the memory we used. */
2429 /* Update the highest-message pointer and unlock the room. */
2430 CC->room.QRhighest = highest_msg;
2431 CtdlPutRoomLock(&CC->room);
2433 /* Perform replication checks if necessary */
2434 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2435 syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() doing repl checks");
2437 for (i=0; i<num_msgs_to_be_merged; ++i) {
2438 msgid = msgs_to_be_merged[i];
2440 if (supplied_msg != NULL) {
2444 msg = CtdlFetchMessage(msgid, 0, 1);
2448 ReplicationChecks(msg);
2450 /* If the message has an Exclusive ID, index that... */
2451 if (!CM_IsEmpty(msg, eExclusiveID)) {
2452 index_message_by_euid(msg->cm_fields[eExclusiveID], &CC->room, msgid);
2455 /* Free up the memory we may have allocated */
2456 if (msg != supplied_msg) {
2465 syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() skips repl checks");
2468 /* Submit this room for processing by hooks */
2469 PerformRoomHooks(&CC->room);
2471 /* Go back to the room we were in before we wandered here... */
2472 CtdlGetRoom(&CC->room, hold_rm);
2474 /* Bump the reference count for all messages which were merged */
2475 if (!suppress_refcount_adj) {
2476 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
2479 /* Free up memory... */
2480 if (msgs_to_be_merged != NULL) {
2481 free(msgs_to_be_merged);
2484 /* Return success. */
2490 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2493 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2494 int do_repl_check, struct CtdlMessage *supplied_msg)
2496 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
2503 * Message base operation to save a new message to the message store
2504 * (returns new message number)
2506 * This is the back end for CtdlSubmitMsg() and should not be directly
2507 * called by server-side modules.
2510 long CtdlSaveThisMessage(struct CtdlMessage *msg, long msgid, int Reply) {
2518 * If the message is big, set its body aside for storage elsewhere
2519 * and we hide the message body from the serializer
2521 if (!CM_IsEmpty(msg, eMesageText) && msg->cm_lengths[eMesageText] > BIGMSG)
2524 holdM = msg->cm_fields[eMesageText];
2525 msg->cm_fields[eMesageText] = NULL;
2526 holdMLen = msg->cm_lengths[eMesageText];
2527 msg->cm_lengths[eMesageText] = 0;
2530 /* Serialize our data structure for storage in the database */
2531 CtdlSerializeMessage(&smr, msg);
2534 /* put the message body back into the message */
2535 msg->cm_fields[eMesageText] = holdM;
2536 msg->cm_lengths[eMesageText] = holdMLen;
2541 cprintf("%d Unable to serialize message\n",
2542 ERROR + INTERNAL_ERROR);
2545 syslog(LOG_ERR, "msgbase: CtdlSaveMessage() unable to serialize message");
2551 /* Write our little bundle of joy into the message base */
2552 retval = cdb_store(CDB_MSGMAIN, &msgid, (int)sizeof(long),
2555 syslog(LOG_ERR, "msgbase: can't store message %ld: %ld", msgid, retval);
2559 retval = cdb_store(CDB_BIGMSGS,
2566 syslog(LOG_ERR, "msgbase: failed to store message body for msgid %ld: %ld", msgid, retval);
2571 /* Free the memory we used for the serialized message */
2577 long send_message(struct CtdlMessage *msg) {
2583 /* Get a new message number */
2584 newmsgid = get_new_message_number();
2586 /* Generate an ID if we don't have one already */
2587 if (CM_IsEmpty(msg, emessageId)) {
2588 msgidbuflen = snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
2589 (long unsigned int) time(NULL),
2590 (long unsigned int) newmsgid,
2591 CtdlGetConfigStr("c_fqdn")
2594 CM_SetField(msg, emessageId, msgidbuf, msgidbuflen);
2597 retval = CtdlSaveThisMessage(msg, newmsgid, 1);
2603 /* Return the *local* message ID to the caller
2604 * (even if we're storing an incoming network message)
2612 * Serialize a struct CtdlMessage into the format used on disk and network.
2614 * This function loads up a "struct ser_ret" (defined in server.h) which
2615 * contains the length of the serialized message and a pointer to the
2616 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2618 void CtdlSerializeMessage(struct ser_ret *ret, /* return values */
2619 struct CtdlMessage *msg) /* unserialized msg */
2625 * Check for valid message format
2627 if (CM_IsValidMsg(msg) == 0) {
2628 syslog(LOG_ERR, "msgbase: CtdlSerializeMessage() aborting due to invalid message");
2635 for (i=0; i < NDiskFields; ++i)
2636 if (msg->cm_fields[FieldOrder[i]] != NULL)
2637 ret->len += msg->cm_lengths[FieldOrder[i]] + 2;
2639 ret->ser = malloc(ret->len);
2640 if (ret->ser == NULL) {
2641 syslog(LOG_ERR, "msgbase: CtdlSerializeMessage() malloc(%ld) failed: %m", (long)ret->len);
2648 ret->ser[1] = msg->cm_anon_type;
2649 ret->ser[2] = msg->cm_format_type;
2652 for (i=0; i < NDiskFields; ++i)
2653 if (msg->cm_fields[FieldOrder[i]] != NULL)
2655 ret->ser[wlen++] = (char)FieldOrder[i];
2657 memcpy(&ret->ser[wlen],
2658 msg->cm_fields[FieldOrder[i]],
2659 msg->cm_lengths[FieldOrder[i]] + 1);
2661 wlen = wlen + msg->cm_lengths[FieldOrder[i]] + 1;
2664 if (ret->len != wlen) {
2665 syslog(LOG_ERR, "msgbase: ERROR; len=%ld wlen=%ld", (long)ret->len, (long)wlen);
2673 * Check to see if any messages already exist in the current room which
2674 * carry the same Exclusive ID as this one. If any are found, delete them.
2676 void ReplicationChecks(struct CtdlMessage *msg) {
2677 long old_msgnum = (-1L);
2679 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2681 syslog(LOG_DEBUG, "msgbase: performing replication checks in <%s>", CC->room.QRname);
2683 /* No exclusive id? Don't do anything. */
2684 if (msg == NULL) return;
2685 if (CM_IsEmpty(msg, eExclusiveID)) return;
2687 /*syslog(LOG_DEBUG, "msgbase: exclusive ID: <%s> for room <%s>",
2688 msg->cm_fields[eExclusiveID], CC->room.QRname);*/
2690 old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields[eExclusiveID], &CC->room);
2691 if (old_msgnum > 0L) {
2692 syslog(LOG_DEBUG, "msgbase: ReplicationChecks() replacing message %ld", old_msgnum);
2693 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2700 * Save a message to disk and submit it into the delivery system.
2702 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2703 recptypes *recps, /* recipients (if mail) */
2704 const char *force, /* force a particular room? */
2705 int flags /* should the message be exported clean? */
2708 char hold_rm[ROOMNAMELEN];
2709 char actual_rm[ROOMNAMELEN];
2710 char force_room[ROOMNAMELEN];
2711 char content_type[SIZ]; /* We have to learn this */
2712 char recipient[SIZ];
2713 char bounce_to[1024];
2716 const char *mptr = NULL;
2717 struct ctdluser userbuf;
2719 struct MetaData smi;
2720 char *collected_addresses = NULL;
2721 struct addresses_to_be_filed *aptr = NULL;
2722 StrBuf *saved_rfc822_version = NULL;
2723 int qualified_for_journaling = 0;
2725 syslog(LOG_DEBUG, "msgbase: CtdlSubmitMsg() called");
2726 if (CM_IsValidMsg(msg) == 0) return(-1); /* self check */
2728 /* If this message has no timestamp, we take the liberty of
2729 * giving it one, right now.
2731 if (CM_IsEmpty(msg, eTimestamp)) {
2732 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
2735 /* If this message has no path, we generate one.
2737 if (CM_IsEmpty(msg, eMessagePath)) {
2738 if (!CM_IsEmpty(msg, eAuthor)) {
2739 CM_CopyField(msg, eMessagePath, eAuthor);
2740 for (a=0; !IsEmptyStr(&msg->cm_fields[eMessagePath][a]); ++a) {
2741 if (isspace(msg->cm_fields[eMessagePath][a])) {
2742 msg->cm_fields[eMessagePath][a] = ' ';
2747 CM_SetField(msg, eMessagePath, HKEY("unknown"));
2751 if (force == NULL) {
2752 force_room[0] = '\0';
2755 strcpy(force_room, force);
2758 /* Learn about what's inside, because it's what's inside that counts */
2759 if (CM_IsEmpty(msg, eMesageText)) {
2760 syslog(LOG_ERR, "msgbase: ERROR; attempt to save message with NULL body");
2764 switch (msg->cm_format_type) {
2766 strcpy(content_type, "text/x-citadel-variformat");
2769 strcpy(content_type, "text/plain");
2772 strcpy(content_type, "text/plain");
2773 mptr = bmstrcasestr(msg->cm_fields[eMesageText], "Content-type:");
2776 safestrncpy(content_type, &mptr[13], sizeof content_type);
2777 striplt(content_type);
2778 aptr = content_type;
2779 while (!IsEmptyStr(aptr)) {
2791 /* Goto the correct room */
2792 room = (recps) ? CC->room.QRname : SENTITEMS;
2793 syslog(LOG_DEBUG, "msgbase: selected room %s", room);
2794 strcpy(hold_rm, CC->room.QRname);
2795 strcpy(actual_rm, CC->room.QRname);
2796 if (recps != NULL) {
2797 strcpy(actual_rm, SENTITEMS);
2800 /* If the user is a twit, move to the twit room for posting */
2802 if (CC->user.axlevel == AxProbU) {
2803 strcpy(hold_rm, actual_rm);
2804 strcpy(actual_rm, CtdlGetConfigStr("c_twitroom"));
2805 syslog(LOG_DEBUG, "msgbase: diverting to twit room");
2809 /* ...or if this message is destined for Aide> then go there. */
2810 if (!IsEmptyStr(force_room)) {
2811 strcpy(actual_rm, force_room);
2814 syslog(LOG_DEBUG, "msgbase: final selection: %s (%s)", actual_rm, room);
2815 if (strcasecmp(actual_rm, CC->room.QRname)) {
2816 /* CtdlGetRoom(&CC->room, actual_rm); */
2817 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL, NULL, NULL);
2821 * If this message has no O (room) field, generate one.
2823 if (CM_IsEmpty(msg, eOriginalRoom) && !IsEmptyStr(CC->room.QRname)) {
2824 CM_SetField(msg, eOriginalRoom, CC->room.QRname, strlen(CC->room.QRname));
2827 /* Perform "before save" hooks (aborting if any return nonzero) */
2828 syslog(LOG_DEBUG, "msgbase: performing before-save hooks");
2829 if (PerformMessageHooks(msg, recps, EVT_BEFORESAVE) > 0) return(-3);
2832 * If this message has an Exclusive ID, and the room is replication
2833 * checking enabled, then do replication checks.
2835 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2836 ReplicationChecks(msg);
2839 /* Save it to disk */
2840 syslog(LOG_DEBUG, "msgbase: saving to disk");
2841 newmsgid = send_message(msg);
2842 if (newmsgid <= 0L) return(-5);
2844 /* Write a supplemental message info record. This doesn't have to
2845 * be a critical section because nobody else knows about this message
2848 syslog(LOG_DEBUG, "msgbase: creating metadata record");
2849 memset(&smi, 0, sizeof(struct MetaData));
2850 smi.meta_msgnum = newmsgid;
2851 smi.meta_refcount = 0;
2852 safestrncpy(smi.meta_content_type, content_type,
2853 sizeof smi.meta_content_type);
2856 * Measure how big this message will be when rendered as RFC822.
2857 * We do this for two reasons:
2858 * 1. We need the RFC822 length for the new metadata record, so the
2859 * POP and IMAP services don't have to calculate message lengths
2860 * while the user is waiting (multiplied by potentially hundreds
2861 * or thousands of messages).
2862 * 2. If journaling is enabled, we will need an RFC822 version of the
2863 * message to attach to the journalized copy.
2865 if (CC->redirect_buffer != NULL) {
2866 syslog(LOG_ALERT, "msgbase: CC->redirect_buffer is not NULL during message submission!");
2869 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
2870 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
2871 smi.meta_rfc822_length = StrLength(CC->redirect_buffer);
2872 saved_rfc822_version = CC->redirect_buffer;
2873 CC->redirect_buffer = NULL;
2877 /* Now figure out where to store the pointers */
2878 syslog(LOG_DEBUG, "msgbase: storing pointers");
2880 /* If this is being done by the networker delivering a private
2881 * message, we want to BYPASS saving the sender's copy (because there
2882 * is no local sender; it would otherwise go to the Trashcan).
2884 if ((!CC->internal_pgm) || (recps == NULL)) {
2885 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2886 syslog(LOG_ERR, "msgbase: ERROR saving message pointer!");
2887 CtdlSaveMsgPointerInRoom(CtdlGetConfigStr("c_aideroom"), newmsgid, 0, msg);
2891 /* For internet mail, drop a copy in the outbound queue room */
2892 if ((recps != NULL) && (recps->num_internet > 0)) {
2893 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2896 /* If other rooms are specified, drop them there too. */
2897 if ((recps != NULL) && (recps->num_room > 0))
2898 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2899 extract_token(recipient, recps->recp_room, i,
2900 '|', sizeof recipient);
2901 syslog(LOG_DEBUG, "msgbase: delivering to room <%s>", recipient);
2902 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2905 /* Bump this user's messages posted counter. */
2906 syslog(LOG_DEBUG, "msgbase: updating user");
2907 CtdlLockGetCurrentUser();
2908 CC->user.posted = CC->user.posted + 1;
2909 CtdlPutCurrentUserLock();
2911 /* Decide where bounces need to be delivered */
2912 if ((recps != NULL) && (recps->bounce_to == NULL))
2914 if (CC->logged_in) {
2915 snprintf(bounce_to, sizeof bounce_to, "%s@%s", CC->user.fullname, CtdlGetConfigStr("c_nodename"));
2918 snprintf(bounce_to, sizeof bounce_to, "%s@%s", msg->cm_fields[eAuthor], msg->cm_fields[eNodeName]);
2920 recps->bounce_to = bounce_to;
2923 CM_SetFieldLONG(msg, eVltMsgNum, newmsgid);
2926 /* If this is private, local mail, make a copy in the
2927 * recipient's mailbox and bump the reference count.
2929 if ((recps != NULL) && (recps->num_local > 0))
2934 pch = recps->recp_local;
2935 recps->recp_local = recipient;
2936 ntokens = num_tokens(pch, '|');
2937 for (i=0; i<ntokens; ++i)
2939 extract_token(recipient, pch, i, '|', sizeof recipient);
2940 syslog(LOG_DEBUG, "msgbase: delivering private local mail to <%s>", recipient);
2941 if (CtdlGetUser(&userbuf, recipient) == 0) {
2942 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
2943 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2944 CtdlBumpNewMailCounter(userbuf.usernum);
2945 PerformMessageHooks(msg, recps, EVT_AFTERUSRMBOXSAVE);
2948 syslog(LOG_DEBUG, "msgbase: no user <%s>", recipient);
2949 CtdlSaveMsgPointerInRoom(CtdlGetConfigStr("c_aideroom"), newmsgid, 0, msg);
2952 recps->recp_local = pch;
2955 /* Perform "after save" hooks */
2956 syslog(LOG_DEBUG, "msgbase: performing after-save hooks");
2958 PerformMessageHooks(msg, recps, EVT_AFTERSAVE);
2959 CM_FlushField(msg, eVltMsgNum);
2961 /* Go back to the room we started from */
2962 syslog(LOG_DEBUG, "msgbase: returning to original room %s", hold_rm);
2963 if (strcasecmp(hold_rm, CC->room.QRname))
2964 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL, NULL, NULL);
2967 * Any addresses to harvest for someone's address book?
2969 if ( (CC->logged_in) && (recps != NULL) ) {
2970 collected_addresses = harvest_collected_addresses(msg);
2973 if (collected_addresses != NULL) {
2974 aptr = (struct addresses_to_be_filed *)
2975 malloc(sizeof(struct addresses_to_be_filed));
2976 CtdlMailboxName(actual_rm, sizeof actual_rm,
2977 &CC->user, USERCONTACTSROOM);
2978 aptr->roomname = strdup(actual_rm);
2979 aptr->collected_addresses = collected_addresses;
2980 begin_critical_section(S_ATBF);
2983 end_critical_section(S_ATBF);
2987 * Determine whether this message qualifies for journaling.
2989 if (!CM_IsEmpty(msg, eJournal)) {
2990 qualified_for_journaling = 0;
2993 if (recps == NULL) {
2994 qualified_for_journaling = CtdlGetConfigInt("c_journal_pubmsgs");
2996 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2997 qualified_for_journaling = CtdlGetConfigInt("c_journal_email");
3000 qualified_for_journaling = CtdlGetConfigInt("c_journal_pubmsgs");
3005 * Do we have to perform journaling? If so, hand off the saved
3006 * RFC822 version will be handed off to the journaler for background
3007 * submit. Otherwise, we have to free the memory ourselves.
3009 if (saved_rfc822_version != NULL) {
3010 if (qualified_for_journaling) {
3011 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
3014 FreeStrBuf(&saved_rfc822_version);
3018 if ((recps != NULL) && (recps->bounce_to == bounce_to))
3019 recps->bounce_to = NULL;
3027 * Convenience function for generating small administrative messages.
3029 long quickie_message(const char *from,
3030 const char *fromaddr,
3035 const char *subject)
3037 struct CtdlMessage *msg;
3038 recptypes *recp = NULL;
3040 msg = malloc(sizeof(struct CtdlMessage));
3041 memset(msg, 0, sizeof(struct CtdlMessage));
3042 msg->cm_magic = CTDLMESSAGE_MAGIC;
3043 msg->cm_anon_type = MES_NORMAL;
3044 msg->cm_format_type = format_type;
3046 if (!IsEmptyStr(from)) {
3047 CM_SetField(msg, eAuthor, from, strlen(from));
3049 else if (!IsEmptyStr(fromaddr)) {
3051 CM_SetField(msg, eAuthor, fromaddr, strlen(fromaddr));
3052 pAt = strchr(msg->cm_fields[eAuthor], '@');
3054 CM_CutFieldAt(msg, eAuthor, pAt - msg->cm_fields[eAuthor]);
3058 msg->cm_fields[eAuthor] = strdup("Citadel");
3061 if (!IsEmptyStr(fromaddr)) CM_SetField(msg, erFc822Addr, fromaddr, strlen(fromaddr));
3062 if (!IsEmptyStr(room)) CM_SetField(msg, eOriginalRoom, room, strlen(room));
3063 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
3064 if (!IsEmptyStr(to)) {
3065 CM_SetField(msg, eRecipient, to, strlen(to));
3066 recp = validate_recipients(to, NULL, 0);
3068 if (!IsEmptyStr(subject)) {
3069 CM_SetField(msg, eMsgSubject, subject, strlen(subject));
3071 if (!IsEmptyStr(text)) {
3072 CM_SetField(msg, eMesageText, text, strlen(text));
3075 long msgnum = CtdlSubmitMsg(msg, recp, room, 0);
3077 if (recp != NULL) free_recipients(recp);
3083 * Back end function used by CtdlMakeMessage() and similar functions
3085 StrBuf *CtdlReadMessageBodyBuf(char *terminator, /* token signalling EOT */
3087 size_t maxlen, /* maximum message length */
3088 StrBuf *exist, /* if non-null, append to it;
3089 exist is ALWAYS freed */
3090 int crlf /* CRLF newlines instead of LF */
3099 LineBuf = NewStrBufPlain(NULL, SIZ);
3100 if (exist == NULL) {
3101 Message = NewStrBufPlain(NULL, 4 * SIZ);
3104 Message = NewStrBufDup(exist);
3107 /* Do we need to change leading ".." to "." for SMTP escaping? */
3108 if ((tlen == 1) && (*terminator == '.')) {
3112 /* read in the lines of message text one by one */
3114 if (CtdlClientGetLine(LineBuf) < 0) {
3117 if ((StrLength(LineBuf) == tlen) && (!strcmp(ChrPtr(LineBuf), terminator))) {
3120 if ( (!flushing) && (!finished) ) {
3122 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3125 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3128 /* Unescape SMTP-style input of two dots at the beginning of the line */
3130 (StrLength(LineBuf) == 2) &&
3131 (!strcmp(ChrPtr(LineBuf), "..")))
3133 StrBufCutLeft(LineBuf, 1);
3136 StrBufAppendBuf(Message, LineBuf, 0);
3139 /* if we've hit the max msg length, flush the rest */
3140 if (StrLength(Message) >= maxlen) flushing = 1;
3142 } while (!finished);
3143 FreeStrBuf(&LineBuf);
3149 * Back end function used by CtdlMakeMessage() and similar functions
3151 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
3153 size_t maxlen, /* maximum message length */
3154 StrBuf *exist, /* if non-null, append to it;
3155 exist is ALWAYS freed */
3156 int crlf /* CRLF newlines instead of LF */
3161 Message = CtdlReadMessageBodyBuf(terminator,
3167 if (Message == NULL)
3170 return SmashStrBuf(&Message);
3173 struct CtdlMessage *CtdlMakeMessage(
3174 struct ctdluser *author, /* author's user structure */
3175 char *recipient, /* NULL if it's not mail */
3176 char *recp_cc, /* NULL if it's not mail */
3177 char *room, /* room where it's going */
3178 int type, /* see MES_ types in header file */
3179 int format_type, /* variformat, plain text, MIME... */
3180 char *fake_name, /* who we're masquerading as */
3181 char *my_email, /* which of my email addresses to use (empty is ok) */
3182 char *subject, /* Subject (optional) */
3183 char *supplied_euid, /* ...or NULL if this is irrelevant */
3184 char *preformatted_text, /* ...or NULL to read text from client */
3185 char *references /* Thread references */
3188 return CtdlMakeMessageLen(
3189 author, /* author's user structure */
3190 recipient, /* NULL if it's not mail */
3191 (recipient)?strlen(recipient) : 0,
3192 recp_cc, /* NULL if it's not mail */
3193 (recp_cc)?strlen(recp_cc): 0,
3194 room, /* room where it's going */
3195 (room)?strlen(room): 0,
3196 type, /* see MES_ types in header file */
3197 format_type, /* variformat, plain text, MIME... */
3198 fake_name, /* who we're masquerading as */
3199 (fake_name)?strlen(fake_name): 0,
3200 my_email, /* which of my email addresses to use (empty is ok) */
3201 (my_email)?strlen(my_email): 0,
3202 subject, /* Subject (optional) */
3203 (subject)?strlen(subject): 0,
3204 supplied_euid, /* ...or NULL if this is irrelevant */
3205 (supplied_euid)?strlen(supplied_euid):0,
3206 preformatted_text, /* ...or NULL to read text from client */
3207 (preformatted_text)?strlen(preformatted_text) : 0,
3208 references, /* Thread references */
3209 (references)?strlen(references):0);
3214 * Build a binary message to be saved on disk.
3215 * (NOTE: if you supply 'preformatted_text', the buffer you give it
3216 * will become part of the message. This means you are no longer
3217 * responsible for managing that memory -- it will be freed along with
3218 * the rest of the fields when CM_Free() is called.)
3221 struct CtdlMessage *CtdlMakeMessageLen(
3222 struct ctdluser *author, /* author's user structure */
3223 char *recipient, /* NULL if it's not mail */
3225 char *recp_cc, /* NULL if it's not mail */
3227 char *room, /* room where it's going */
3229 int type, /* see MES_ types in header file */
3230 int format_type, /* variformat, plain text, MIME... */
3231 char *fake_name, /* who we're masquerading as */
3233 char *my_email, /* which of my email addresses to use (empty is ok) */
3235 char *subject, /* Subject (optional) */
3237 char *supplied_euid, /* ...or NULL if this is irrelevant */
3239 char *preformatted_text, /* ...or NULL to read text from client */
3241 char *references, /* Thread references */
3245 /* Don't confuse the poor folks if it's not routed mail. * /
3246 char dest_node[256] = "";*/
3249 struct CtdlMessage *msg;
3251 StrBuf *FakeEncAuthor = NULL;
3253 msg = malloc(sizeof(struct CtdlMessage));
3254 memset(msg, 0, sizeof(struct CtdlMessage));
3255 msg->cm_magic = CTDLMESSAGE_MAGIC;
3256 msg->cm_anon_type = type;
3257 msg->cm_format_type = format_type;
3259 if (recipient != NULL) rcplen = striplt(recipient);
3260 if (recp_cc != NULL) cclen = striplt(recp_cc);
3262 /* Path or Return-Path */
3264 CM_SetField(msg, eMessagePath, my_email, myelen);
3266 else if (!IsEmptyStr(author->fullname)) {
3267 CM_SetField(msg, eMessagePath, author->fullname, strlen(author->fullname));
3269 convert_spaces_to_underscores(msg->cm_fields[eMessagePath]);
3271 blen = snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
3272 CM_SetField(msg, eTimestamp, buf, blen);
3275 FakeAuthor = NewStrBufPlain (fake_name, fnlen);
3278 FakeAuthor = NewStrBufPlain (author->fullname, -1);
3280 StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
3281 CM_SetAsFieldSB(msg, eAuthor, &FakeEncAuthor);
3282 FreeStrBuf(&FakeAuthor);
3284 if (!!IsEmptyStr(CC->room.QRname)) {
3285 if (CC->room.QRflags & QR_MAILBOX) { /* room */
3286 CM_SetField(msg, eOriginalRoom, &CC->room.QRname[11], strlen(&CC->room.QRname[11]));
3289 CM_SetField(msg, eOriginalRoom, CC->room.QRname, strlen(CC->room.QRname));
3293 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
3294 CM_SetField(msg, eHumanNode, CtdlGetConfigStr("c_humannode"), strlen(CtdlGetConfigStr("c_humannode")));
3297 CM_SetField(msg, eRecipient, recipient, rcplen);
3300 CM_SetField(msg, eCarbonCopY, recp_cc, cclen);
3304 CM_SetField(msg, erFc822Addr, my_email, myelen);
3306 else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
3307 CM_SetField(msg, erFc822Addr, CC->cs_inet_email, strlen(CC->cs_inet_email));
3310 if (subject != NULL) {
3312 length = striplt(subject);
3318 while ((subject[i] != '\0') &&
3319 (IsAscii = isascii(subject[i]) != 0 ))
3322 CM_SetField(msg, eMsgSubject, subject, subjlen);
3323 else /* ok, we've got utf8 in the string. */
3326 rfc2047Subj = rfc2047encode(subject, length);
3327 CM_SetAsField(msg, eMsgSubject, &rfc2047Subj, strlen(rfc2047Subj));
3334 CM_SetField(msg, eExclusiveID, supplied_euid, euidlen);
3338 CM_SetField(msg, eWeferences, references, reflen);
3341 if (preformatted_text != NULL) {
3342 CM_SetField(msg, eMesageText, preformatted_text, textlen);
3346 MsgBody = CtdlReadMessageBodyBuf(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0);
3347 if (MsgBody != NULL) {
3348 CM_SetAsFieldSB(msg, eMesageText, &MsgBody);
3359 * API function to delete messages which match a set of criteria
3360 * (returns the actual number of messages deleted)
3362 int CtdlDeleteMessages(const char *room_name, /* which room */
3363 long *dmsgnums, /* array of msg numbers to be deleted */
3364 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
3365 char *content_type /* or "" for any. regular expressions expected. */
3368 struct ctdlroom qrbuf;
3369 struct cdbdata *cdbfr;
3370 long *msglist = NULL;
3371 long *dellist = NULL;
3374 int num_deleted = 0;
3376 struct MetaData smi;
3379 int need_to_free_re = 0;
3381 if (content_type) if (!IsEmptyStr(content_type)) {
3382 regcomp(&re, content_type, 0);
3383 need_to_free_re = 1;
3385 syslog(LOG_DEBUG, "msgbase: CtdlDeleteMessages(%s, %d msgs, %s)", room_name, num_dmsgnums, content_type);
3387 /* get room record, obtaining a lock... */
3388 if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
3389 syslog(LOG_ERR, "msgbase: CtdlDeleteMessages(): Room <%s> not found", room_name);
3390 if (need_to_free_re) regfree(&re);
3391 return(0); /* room not found */
3393 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3395 if (cdbfr != NULL) {
3396 dellist = malloc(cdbfr->len);
3397 msglist = (long *) cdbfr->ptr;
3398 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3399 num_msgs = cdbfr->len / sizeof(long);
3403 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
3404 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
3405 int have_more_del = 1;
3407 num_msgs = sort_msglist(msglist, num_msgs);
3408 if (num_dmsgnums > 1)
3409 num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
3412 StrBuf *dbg = NewStrBuf();
3413 for (i = 0; i < num_dmsgnums; i++)
3414 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
3415 syslog(LOG_DEBUG, "msgbase: Deleting before: %s", ChrPtr(dbg));
3420 while ((i < num_msgs) && (have_more_del)) {
3423 /* Set/clear a bit for each criterion */
3425 /* 0 messages in the list or a null list means that we are
3426 * interested in deleting any messages which meet the other criteria.
3429 delete_this |= 0x01;
3432 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
3437 if (msglist[i] == dmsgnums[j]) {
3438 delete_this |= 0x01;
3441 have_more_del = (j < num_dmsgnums);
3444 if (have_contenttype) {
3445 GetMetaData(&smi, msglist[i]);
3446 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3447 delete_this |= 0x02;
3450 delete_this |= 0x02;
3453 /* Delete message only if all bits are set */
3454 if (delete_this == 0x03) {
3455 dellist[num_deleted++] = msglist[i];
3462 StrBuf *dbg = NewStrBuf();
3463 for (i = 0; i < num_deleted; i++)
3464 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
3465 syslog(LOG_DEBUG, "msgbase: Deleting: %s", ChrPtr(dbg));
3469 num_msgs = sort_msglist(msglist, num_msgs);
3470 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3471 msglist, (int)(num_msgs * sizeof(long)));
3474 qrbuf.QRhighest = msglist[num_msgs - 1];
3476 qrbuf.QRhighest = 0;
3478 CtdlPutRoomLock(&qrbuf);
3480 /* Go through the messages we pulled out of the index, and decrement
3481 * their reference counts by 1. If this is the only room the message
3482 * was in, the reference count will reach zero and the message will
3483 * automatically be deleted from the database. We do this in a
3484 * separate pass because there might be plug-in hooks getting called,
3485 * and we don't want that happening during an S_ROOMS critical
3489 for (i=0; i<num_deleted; ++i) {
3490 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3492 AdjRefCountList(dellist, num_deleted, -1);
3494 /* Now free the memory we used, and go away. */
3495 if (msglist != NULL) free(msglist);
3496 if (dellist != NULL) free(dellist);
3497 syslog(LOG_DEBUG, "msgbase: %d message(s) deleted", num_deleted);
3498 if (need_to_free_re) regfree(&re);
3499 return (num_deleted);
3506 * GetMetaData() - Get the supplementary record for a message
3508 void GetMetaData(struct MetaData *smibuf, long msgnum)
3511 struct cdbdata *cdbsmi;
3514 memset(smibuf, 0, sizeof(struct MetaData));
3515 smibuf->meta_msgnum = msgnum;
3516 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3518 /* Use the negative of the message number for its supp record index */
3519 TheIndex = (0L - msgnum);
3521 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3522 if (cdbsmi == NULL) {
3523 return; /* record not found; go with defaults */
3525 memcpy(smibuf, cdbsmi->ptr,
3526 ((cdbsmi->len > sizeof(struct MetaData)) ?
3527 sizeof(struct MetaData) : cdbsmi->len));
3534 * PutMetaData() - (re)write supplementary record for a message
3536 void PutMetaData(struct MetaData *smibuf)
3540 /* Use the negative of the message number for the metadata db index */
3541 TheIndex = (0L - smibuf->meta_msgnum);
3543 cdb_store(CDB_MSGMAIN,
3544 &TheIndex, (int)sizeof(long),
3545 smibuf, (int)sizeof(struct MetaData));
3550 * AdjRefCount - submit an adjustment to the reference count for a message.
3551 * (These are just queued -- we actually process them later.)
3553 void AdjRefCount(long msgnum, int incr)
3555 struct arcq new_arcq;
3558 syslog(LOG_DEBUG, "msgbase: AdjRefCount() msg %ld ref count delta %+d", msgnum, incr);
3560 begin_critical_section(S_SUPPMSGMAIN);
3561 if (arcfp == NULL) {
3562 arcfp = fopen(file_arcq, "ab+");
3563 chown(file_arcq, CTDLUID, (-1));
3564 chmod(file_arcq, 0600);
3566 end_critical_section(S_SUPPMSGMAIN);
3568 /* msgnum < 0 means that we're trying to close the file */
3570 syslog(LOG_DEBUG, "msgbase: closing the AdjRefCount queue file");
3571 begin_critical_section(S_SUPPMSGMAIN);
3572 if (arcfp != NULL) {
3576 end_critical_section(S_SUPPMSGMAIN);
3581 * If we can't open the queue, perform the operation synchronously.
3583 if (arcfp == NULL) {
3584 TDAP_AdjRefCount(msgnum, incr);
3588 new_arcq.arcq_msgnum = msgnum;
3589 new_arcq.arcq_delta = incr;
3590 rv = fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
3592 syslog(LOG_EMERG, "%s: %m", file_arcq);
3599 void AdjRefCountList(long *msgnum, long nmsg, int incr)
3601 long i, the_size, offset;
3602 struct arcq *new_arcq;
3605 syslog(LOG_DEBUG, "msgbase: AdjRefCountList() msg %ld ref count delta %+d", nmsg, incr);
3607 begin_critical_section(S_SUPPMSGMAIN);
3608 if (arcfp == NULL) {
3609 arcfp = fopen(file_arcq, "ab+");
3610 chown(file_arcq, CTDLUID, (-1));
3611 chmod(file_arcq, 0600);
3613 end_critical_section(S_SUPPMSGMAIN);
3616 * If we can't open the queue, perform the operation synchronously.
3618 if (arcfp == NULL) {
3619 for (i = 0; i < nmsg; i++)
3620 TDAP_AdjRefCount(msgnum[i], incr);
3624 the_size = sizeof(struct arcq) * nmsg;
3625 new_arcq = malloc(the_size);
3626 for (i = 0; i < nmsg; i++) {
3627 new_arcq[i].arcq_msgnum = msgnum[i];
3628 new_arcq[i].arcq_delta = incr;
3632 while ((rv >= 0) && (offset < the_size))
3634 rv = fwrite(new_arcq + offset, 1, the_size - offset, arcfp);
3636 syslog(LOG_ERR, "%s: %m", file_arcq);
3650 * TDAP_ProcessAdjRefCountQueue()
3652 * Process the queue of message count adjustments that was created by calls
3653 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
3654 * for each one. This should be an "off hours" operation.
3656 int TDAP_ProcessAdjRefCountQueue(void)
3658 char file_arcq_temp[PATH_MAX];
3661 struct arcq arcq_rec;
3662 int num_records_processed = 0;
3664 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s.%04x", file_arcq, rand());
3666 begin_critical_section(S_SUPPMSGMAIN);
3667 if (arcfp != NULL) {
3672 r = link(file_arcq, file_arcq_temp);
3674 syslog(LOG_ERR, "%s: %m", file_arcq_temp);
3675 end_critical_section(S_SUPPMSGMAIN);
3676 return(num_records_processed);
3680 end_critical_section(S_SUPPMSGMAIN);
3682 fp = fopen(file_arcq_temp, "rb");
3684 syslog(LOG_ERR, "%s: %m", file_arcq_temp);
3685 return(num_records_processed);
3688 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
3689 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
3690 ++num_records_processed;
3694 r = unlink(file_arcq_temp);
3696 syslog(LOG_ERR, "%s: %m", file_arcq_temp);
3699 return(num_records_processed);
3705 * TDAP_AdjRefCount - adjust the reference count for a message.
3706 * This one does it "for real" because it's called by
3707 * the autopurger function that processes the queue
3708 * created by AdjRefCount(). If a message's reference
3709 * count becomes zero, we also delete the message from
3710 * disk and de-index it.
3712 void TDAP_AdjRefCount(long msgnum, int incr)
3715 struct MetaData smi;
3718 /* This is a *tight* critical section; please keep it that way, as
3719 * it may get called while nested in other critical sections.
3720 * Complicating this any further will surely cause deadlock!
3722 begin_critical_section(S_SUPPMSGMAIN);
3723 GetMetaData(&smi, msgnum);
3724 smi.meta_refcount += incr;
3726 end_critical_section(S_SUPPMSGMAIN);
3727 syslog(LOG_DEBUG, "msgbase: TDAP_AdjRefCount() msg %ld ref count delta %+d, is now %d",
3728 msgnum, incr, smi.meta_refcount
3731 /* If the reference count is now zero, delete the message
3732 * (and its supplementary record as well).
3734 if (smi.meta_refcount == 0) {
3735 syslog(LOG_DEBUG, "msgbase: deleting message <%ld>", msgnum);
3737 /* Call delete hooks with NULL room to show it has gone altogether */
3738 PerformDeleteHooks(NULL, msgnum);
3740 /* Remove from message base */
3742 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3743 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3745 /* Remove metadata record */
3746 delnum = (0L - msgnum);
3747 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3753 * Write a generic object to this room
3755 * Note: this could be much more efficient. Right now we use two temporary
3756 * files, and still pull the message into memory as with all others.
3758 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
3759 char *content_type, /* MIME type of this object */
3760 char *raw_message, /* Data to be written */
3761 off_t raw_length, /* Size of raw_message */
3762 struct ctdluser *is_mailbox, /* Mailbox room? */
3763 int is_binary, /* Is encoding necessary? */
3764 int is_unique, /* Del others of this type? */
3765 unsigned int flags /* Internal save flags */
3768 struct ctdlroom qrbuf;
3769 char roomname[ROOMNAMELEN];
3770 struct CtdlMessage *msg;
3771 StrBuf *encoded_message = NULL;
3773 if (is_mailbox != NULL) {
3774 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3777 safestrncpy(roomname, req_room, sizeof(roomname));
3780 syslog(LOG_DEBUG, "msfbase: raw length is %ld", (long)raw_length);
3783 encoded_message = NewStrBufPlain(NULL, (size_t) (((raw_length * 134) / 100) + 4096 ) );
3786 encoded_message = NewStrBufPlain(NULL, (size_t)(raw_length + 4096));
3789 StrBufAppendBufPlain(encoded_message, HKEY("Content-type: "), 0);
3790 StrBufAppendBufPlain(encoded_message, content_type, -1, 0);
3791 StrBufAppendBufPlain(encoded_message, HKEY("\n"), 0);
3794 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: base64\n\n"), 0);
3797 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: 7bit\n\n"), 0);
3801 StrBufBase64Append(encoded_message, NULL, raw_message, raw_length, 0);
3804 StrBufAppendBufPlain(encoded_message, raw_message, raw_length, 0);
3807 syslog(LOG_DEBUG, "msgbase: allocating");
3808 msg = malloc(sizeof(struct CtdlMessage));
3809 memset(msg, 0, sizeof(struct CtdlMessage));
3810 msg->cm_magic = CTDLMESSAGE_MAGIC;
3811 msg->cm_anon_type = MES_NORMAL;
3812 msg->cm_format_type = 4;
3813 CM_SetField(msg, eAuthor, CC->user.fullname, strlen(CC->user.fullname));
3814 CM_SetField(msg, eOriginalRoom, req_room, strlen(req_room));
3815 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
3816 CM_SetField(msg, eHumanNode, CtdlGetConfigStr("c_humannode"), strlen(CtdlGetConfigStr("c_humannode")));
3817 msg->cm_flags = flags;
3819 CM_SetAsFieldSB(msg, eMesageText, &encoded_message);
3821 /* Create the requested room if we have to. */
3822 if (CtdlGetRoom(&qrbuf, roomname) != 0) {
3823 CtdlCreateRoom(roomname,
3824 ( (is_mailbox != NULL) ? 5 : 3 ),
3825 "", 0, 1, 0, VIEW_BBS);
3827 /* If the caller specified this object as unique, delete all
3828 * other objects of this type that are currently in the room.
3831 syslog(LOG_DEBUG, "msgbase: deleted %d other msgs of this type",
3832 CtdlDeleteMessages(roomname, NULL, 0, content_type)
3835 /* Now write the data */
3836 CtdlSubmitMsg(msg, NULL, roomname, 0);
3842 /*****************************************************************************/
3843 /* MODULE INITIALIZATION STUFF */
3844 /*****************************************************************************/
3846 CTDL_MODULE_INIT(msgbase)
3849 FillMsgKeyLookupTable();
3852 /* return our Subversion id for the Log */