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");
2097 return(om_no_such_msg);
2100 /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2101 * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2103 if ( (flags & SUPPRESS_ENV_TO) && (!CM_IsEmpty(TheMessage, eenVelopeTo)) ) {
2104 memset(TheMessage->cm_fields[eenVelopeTo], ' ', TheMessage->cm_lengths[eenVelopeTo]);
2107 /* Are we downloading a MIME component? */
2108 if (mode == MT_DOWNLOAD) {
2109 if (TheMessage->cm_format_type != FMT_RFC822) {
2111 cprintf("%d This is not a MIME message.\n",
2112 ERROR + ILLEGAL_VALUE);
2113 } else if (CC->download_fp != NULL) {
2114 if (do_proto) cprintf(
2115 "%d You already have a download open.\n",
2116 ERROR + RESOURCE_BUSY);
2118 /* Parse the message text component */
2119 mime_parser(CM_RANGE(TheMessage, eMesageText),
2120 *mime_download, NULL, NULL, NULL, 0);
2121 /* If there's no file open by this time, the requested
2122 * section wasn't found, so print an error
2124 if (CC->download_fp == NULL) {
2125 if (do_proto) cprintf(
2126 "%d Section %s not found.\n",
2127 ERROR + FILE_NOT_FOUND,
2128 CC->download_desired_section);
2131 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
2134 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2135 * in a single server operation instead of opening a download file.
2137 if (mode == MT_SPEW_SECTION) {
2138 if (TheMessage->cm_format_type != FMT_RFC822) {
2140 cprintf("%d This is not a MIME message.\n",
2141 ERROR + ILLEGAL_VALUE);
2143 /* Parse the message text component */
2146 mime_parser(CM_RANGE(TheMessage, eMesageText),
2147 *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2148 /* If section wasn't found, print an error
2151 if (do_proto) cprintf(
2152 "%d Section %s not found.\n",
2153 ERROR + FILE_NOT_FOUND,
2154 CC->download_desired_section);
2157 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
2160 /* now for the user-mode message reading loops */
2161 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2163 /* Does the caller want to skip the headers? */
2164 if (headers_only == HEADERS_NONE) goto START_TEXT;
2166 /* Tell the client which format type we're using. */
2167 if ( (mode == MT_CITADEL) && (do_proto) ) {
2168 cprintf("type=%d\n", TheMessage->cm_format_type);
2171 /* nhdr=yes means that we're only displaying headers, no body */
2172 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2173 && ((mode == MT_CITADEL) || (mode == MT_MIME))
2176 cprintf("nhdr=yes\n");
2179 if ((mode == MT_CITADEL) || (mode == MT_MIME))
2180 OutputCtdlMsgHeaders(TheMessage, do_proto);
2183 /* begin header processing loop for RFC822 transfer format */
2187 memcpy(snode, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")) + 1);
2188 if (mode == MT_RFC822)
2189 OutputRFC822MsgHeaders(
2194 suser, sizeof(suser),
2195 luser, sizeof(luser),
2196 fuser, sizeof(fuser),
2197 snode, sizeof(snode)
2201 for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2202 suser[i] = tolower(suser[i]);
2203 if (!isalnum(suser[i])) suser[i]='_';
2206 if (mode == MT_RFC822) {
2207 if (!strcasecmp(snode, NODENAME)) {
2208 safestrncpy(snode, FQDN, sizeof snode);
2211 /* Construct a fun message id */
2212 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
2213 if (strchr(mid, '@')==NULL) {
2214 cprintf("@%s", snode);
2218 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2219 cprintf("From: \"----\" <x@x.org>%s", nl);
2221 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2222 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2224 else if (!IsEmptyStr(fuser)) {
2225 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2228 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2231 /* Blank line signifying RFC822 end-of-headers */
2232 if (TheMessage->cm_format_type != FMT_RFC822) {
2237 /* end header processing loop ... at this point, we're in the text */
2239 if (headers_only == HEADERS_FAST) goto DONE;
2241 /* Tell the client about the MIME parts in this message */
2242 if (TheMessage->cm_format_type == FMT_RFC822) {
2243 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2244 memset(&ma, 0, sizeof(struct ma_info));
2245 mime_parser(CM_RANGE(TheMessage, eMesageText),
2246 (do_proto ? *list_this_part : NULL),
2247 (do_proto ? *list_this_pref : NULL),
2248 (do_proto ? *list_this_suff : NULL),
2251 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
2252 Dump_RFC822HeadersBody(
2261 if (headers_only == HEADERS_ONLY) {
2265 /* signify start of msg text */
2266 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2267 if (do_proto) cprintf("text\n");
2270 if (TheMessage->cm_format_type == FMT_FIXED)
2273 mode, /* how would you like that message? */
2276 /* If the message on disk is format 0 (Citadel vari-format), we
2277 * output using the formatter at 80 columns. This is the final output
2278 * form if the transfer format is RFC822, but if the transfer format
2279 * is Citadel proprietary, it'll still work, because the indentation
2280 * for new paragraphs is correct and the client will reformat the
2281 * message to the reader's screen width.
2283 if (TheMessage->cm_format_type == FMT_CITADEL) {
2284 if (mode == MT_MIME) {
2285 cprintf("Content-type: text/x-citadel-variformat\n\n");
2287 memfmout(TheMessage->cm_fields[eMesageText], nl);
2290 /* If the message on disk is format 4 (MIME), we've gotta hand it
2291 * off to the MIME parser. The client has already been told that
2292 * this message is format 1 (fixed format), so the callback function
2293 * we use will display those parts as-is.
2295 if (TheMessage->cm_format_type == FMT_RFC822) {
2296 memset(&ma, 0, sizeof(struct ma_info));
2298 if (mode == MT_MIME) {
2299 ma.use_fo_hooks = 0;
2300 strcpy(ma.chosen_part, "1");
2301 ma.chosen_pref = 9999;
2302 ma.dont_decode = CC->msg4_dont_decode;
2303 mime_parser(CM_RANGE(TheMessage, eMesageText),
2304 *choose_preferred, *fixed_output_pre,
2305 *fixed_output_post, (void *)&ma, 1);
2306 mime_parser(CM_RANGE(TheMessage, eMesageText),
2307 *output_preferred, NULL, NULL, (void *)&ma, 1);
2310 ma.use_fo_hooks = 1;
2311 mime_parser(CM_RANGE(TheMessage, eMesageText),
2312 *fixed_output, *fixed_output_pre,
2313 *fixed_output_post, (void *)&ma, 0);
2318 DONE: /* now we're done */
2319 if (do_proto) cprintf("000\n");
2324 * Save one or more message pointers into a specified room
2325 * (Returns 0 for success, nonzero for failure)
2326 * roomname may be NULL to use the current room
2328 * Note that the 'supplied_msg' field may be set to NULL, in which case
2329 * the message will be fetched from disk, by number, if we need to perform
2330 * replication checks. This adds an additional database read, so if the
2331 * caller already has the message in memory then it should be supplied. (Obviously
2332 * this mode of operation only works if we're saving a single message.)
2334 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2335 int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2338 char hold_rm[ROOMNAMELEN];
2339 struct cdbdata *cdbfr;
2342 long highest_msg = 0L;
2345 struct CtdlMessage *msg = NULL;
2347 long *msgs_to_be_merged = NULL;
2348 int num_msgs_to_be_merged = 0;
2351 "msgbase: CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)",
2352 roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2355 strcpy(hold_rm, CC->room.QRname);
2358 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2359 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2360 if (num_newmsgs > 1) supplied_msg = NULL;
2362 /* Now the regular stuff */
2363 if (CtdlGetRoomLock(&CC->room,
2364 ((roomname != NULL) ? roomname : CC->room.QRname) )
2366 syslog(LOG_ERR, "msgbase: no such room <%s>", roomname);
2367 return(ERROR + ROOM_NOT_FOUND);
2371 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2372 num_msgs_to_be_merged = 0;
2375 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2376 if (cdbfr == NULL) {
2380 msglist = (long *) cdbfr->ptr;
2381 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2382 num_msgs = cdbfr->len / sizeof(long);
2387 /* Create a list of msgid's which were supplied by the caller, but do
2388 * not already exist in the target room. It is absolutely taboo to
2389 * have more than one reference to the same message in a room.
2391 for (i=0; i<num_newmsgs; ++i) {
2393 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2394 if (msglist[j] == newmsgidlist[i]) {
2399 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2403 syslog(LOG_DEBUG, "msgbase: %d unique messages to be merged", num_msgs_to_be_merged);
2406 * Now merge the new messages
2408 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2409 if (msglist == NULL) {
2410 syslog(LOG_ALERT, "msgbase: ERROR; can't realloc message list!");
2411 free(msgs_to_be_merged);
2412 return (ERROR + INTERNAL_ERROR);
2414 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2415 num_msgs += num_msgs_to_be_merged;
2417 /* Sort the message list, so all the msgid's are in order */
2418 num_msgs = sort_msglist(msglist, num_msgs);
2420 /* Determine the highest message number */
2421 highest_msg = msglist[num_msgs - 1];
2423 /* Write it back to disk. */
2424 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2425 msglist, (int)(num_msgs * sizeof(long)));
2427 /* Free up the memory we used. */
2430 /* Update the highest-message pointer and unlock the room. */
2431 CC->room.QRhighest = highest_msg;
2432 CtdlPutRoomLock(&CC->room);
2434 /* Perform replication checks if necessary */
2435 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2436 syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() doing repl checks");
2438 for (i=0; i<num_msgs_to_be_merged; ++i) {
2439 msgid = msgs_to_be_merged[i];
2441 if (supplied_msg != NULL) {
2445 msg = CtdlFetchMessage(msgid, 0, 1);
2449 ReplicationChecks(msg);
2451 /* If the message has an Exclusive ID, index that... */
2452 if (!CM_IsEmpty(msg, eExclusiveID)) {
2453 index_message_by_euid(msg->cm_fields[eExclusiveID], &CC->room, msgid);
2456 /* Free up the memory we may have allocated */
2457 if (msg != supplied_msg) {
2466 syslog(LOG_DEBUG, "msgbase: CtdlSaveMsgPointerInRoom() skips repl checks");
2469 /* Submit this room for processing by hooks */
2470 PerformRoomHooks(&CC->room);
2472 /* Go back to the room we were in before we wandered here... */
2473 CtdlGetRoom(&CC->room, hold_rm);
2475 /* Bump the reference count for all messages which were merged */
2476 if (!suppress_refcount_adj) {
2477 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
2480 /* Free up memory... */
2481 if (msgs_to_be_merged != NULL) {
2482 free(msgs_to_be_merged);
2485 /* Return success. */
2491 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2494 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2495 int do_repl_check, struct CtdlMessage *supplied_msg)
2497 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
2504 * Message base operation to save a new message to the message store
2505 * (returns new message number)
2507 * This is the back end for CtdlSubmitMsg() and should not be directly
2508 * called by server-side modules.
2511 long CtdlSaveThisMessage(struct CtdlMessage *msg, long msgid, int Reply) {
2519 * If the message is big, set its body aside for storage elsewhere
2520 * and we hide the message body from the serializer
2522 if (!CM_IsEmpty(msg, eMesageText) && msg->cm_lengths[eMesageText] > BIGMSG)
2525 holdM = msg->cm_fields[eMesageText];
2526 msg->cm_fields[eMesageText] = NULL;
2527 holdMLen = msg->cm_lengths[eMesageText];
2528 msg->cm_lengths[eMesageText] = 0;
2531 /* Serialize our data structure for storage in the database */
2532 CtdlSerializeMessage(&smr, msg);
2535 /* put the message body back into the message */
2536 msg->cm_fields[eMesageText] = holdM;
2537 msg->cm_lengths[eMesageText] = holdMLen;
2542 cprintf("%d Unable to serialize message\n",
2543 ERROR + INTERNAL_ERROR);
2546 syslog(LOG_ERR, "msgbase: CtdlSaveMessage() unable to serialize message");
2552 /* Write our little bundle of joy into the message base */
2553 retval = cdb_store(CDB_MSGMAIN, &msgid, (int)sizeof(long),
2556 syslog(LOG_ERR, "msgbase: can't store message %ld: %ld", msgid, retval);
2560 retval = cdb_store(CDB_BIGMSGS,
2567 syslog(LOG_ERR, "msgbase: failed to store message body for msgid %ld: %ld", msgid, retval);
2572 /* Free the memory we used for the serialized message */
2578 long send_message(struct CtdlMessage *msg) {
2584 /* Get a new message number */
2585 newmsgid = get_new_message_number();
2587 /* Generate an ID if we don't have one already */
2588 if (CM_IsEmpty(msg, emessageId)) {
2589 msgidbuflen = snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
2590 (long unsigned int) time(NULL),
2591 (long unsigned int) newmsgid,
2592 CtdlGetConfigStr("c_fqdn")
2595 CM_SetField(msg, emessageId, msgidbuf, msgidbuflen);
2598 retval = CtdlSaveThisMessage(msg, newmsgid, 1);
2604 /* Return the *local* message ID to the caller
2605 * (even if we're storing an incoming network message)
2613 * Serialize a struct CtdlMessage into the format used on disk and network.
2615 * This function loads up a "struct ser_ret" (defined in server.h) which
2616 * contains the length of the serialized message and a pointer to the
2617 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2619 void CtdlSerializeMessage(struct ser_ret *ret, /* return values */
2620 struct CtdlMessage *msg) /* unserialized msg */
2626 * Check for valid message format
2628 if (CM_IsValidMsg(msg) == 0) {
2629 syslog(LOG_ERR, "msgbase: CtdlSerializeMessage() aborting due to invalid message");
2636 for (i=0; i < NDiskFields; ++i)
2637 if (msg->cm_fields[FieldOrder[i]] != NULL)
2638 ret->len += msg->cm_lengths[FieldOrder[i]] + 2;
2640 ret->ser = malloc(ret->len);
2641 if (ret->ser == NULL) {
2642 syslog(LOG_ERR, "msgbase: CtdlSerializeMessage() malloc(%ld) failed: %m", (long)ret->len);
2649 ret->ser[1] = msg->cm_anon_type;
2650 ret->ser[2] = msg->cm_format_type;
2653 for (i=0; i < NDiskFields; ++i)
2654 if (msg->cm_fields[FieldOrder[i]] != NULL)
2656 ret->ser[wlen++] = (char)FieldOrder[i];
2658 memcpy(&ret->ser[wlen],
2659 msg->cm_fields[FieldOrder[i]],
2660 msg->cm_lengths[FieldOrder[i]] + 1);
2662 wlen = wlen + msg->cm_lengths[FieldOrder[i]] + 1;
2665 if (ret->len != wlen) {
2666 syslog(LOG_ERR, "msgbase: ERROR; len=%ld wlen=%ld", (long)ret->len, (long)wlen);
2674 * Check to see if any messages already exist in the current room which
2675 * carry the same Exclusive ID as this one. If any are found, delete them.
2677 void ReplicationChecks(struct CtdlMessage *msg) {
2678 long old_msgnum = (-1L);
2680 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2682 syslog(LOG_DEBUG, "msgbase: performing replication checks in <%s>", CC->room.QRname);
2684 /* No exclusive id? Don't do anything. */
2685 if (msg == NULL) return;
2686 if (CM_IsEmpty(msg, eExclusiveID)) return;
2688 /*syslog(LOG_DEBUG, "msgbase: exclusive ID: <%s> for room <%s>",
2689 msg->cm_fields[eExclusiveID], CC->room.QRname);*/
2691 old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields[eExclusiveID], &CC->room);
2692 if (old_msgnum > 0L) {
2693 syslog(LOG_DEBUG, "msgbase: ReplicationChecks() replacing message %ld", old_msgnum);
2694 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2701 * Save a message to disk and submit it into the delivery system.
2703 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2704 recptypes *recps, /* recipients (if mail) */
2705 const char *force, /* force a particular room? */
2706 int flags /* should the message be exported clean? */
2709 char hold_rm[ROOMNAMELEN];
2710 char actual_rm[ROOMNAMELEN];
2711 char force_room[ROOMNAMELEN];
2712 char content_type[SIZ]; /* We have to learn this */
2713 char recipient[SIZ];
2714 char bounce_to[1024];
2717 const char *mptr = NULL;
2718 struct ctdluser userbuf;
2720 struct MetaData smi;
2721 char *collected_addresses = NULL;
2722 struct addresses_to_be_filed *aptr = NULL;
2723 StrBuf *saved_rfc822_version = NULL;
2724 int qualified_for_journaling = 0;
2726 syslog(LOG_DEBUG, "msgbase: CtdlSubmitMsg() called");
2727 if (CM_IsValidMsg(msg) == 0) return(-1); /* self check */
2729 /* If this message has no timestamp, we take the liberty of
2730 * giving it one, right now.
2732 if (CM_IsEmpty(msg, eTimestamp)) {
2733 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
2736 /* If this message has no path, we generate one.
2738 if (CM_IsEmpty(msg, eMessagePath)) {
2739 if (!CM_IsEmpty(msg, eAuthor)) {
2740 CM_CopyField(msg, eMessagePath, eAuthor);
2741 for (a=0; !IsEmptyStr(&msg->cm_fields[eMessagePath][a]); ++a) {
2742 if (isspace(msg->cm_fields[eMessagePath][a])) {
2743 msg->cm_fields[eMessagePath][a] = ' ';
2748 CM_SetField(msg, eMessagePath, HKEY("unknown"));
2752 if (force == NULL) {
2753 force_room[0] = '\0';
2756 strcpy(force_room, force);
2759 /* Learn about what's inside, because it's what's inside that counts */
2760 if (CM_IsEmpty(msg, eMesageText)) {
2761 syslog(LOG_ERR, "msgbase: ERROR; attempt to save message with NULL body");
2765 switch (msg->cm_format_type) {
2767 strcpy(content_type, "text/x-citadel-variformat");
2770 strcpy(content_type, "text/plain");
2773 strcpy(content_type, "text/plain");
2774 mptr = bmstrcasestr(msg->cm_fields[eMesageText], "Content-type:");
2777 safestrncpy(content_type, &mptr[13], sizeof content_type);
2778 striplt(content_type);
2779 aptr = content_type;
2780 while (!IsEmptyStr(aptr)) {
2792 /* Goto the correct room */
2793 room = (recps) ? CC->room.QRname : SENTITEMS;
2794 syslog(LOG_DEBUG, "msgbase: selected room %s", room);
2795 strcpy(hold_rm, CC->room.QRname);
2796 strcpy(actual_rm, CC->room.QRname);
2797 if (recps != NULL) {
2798 strcpy(actual_rm, SENTITEMS);
2801 /* If the user is a twit, move to the twit room for posting */
2803 if (CC->user.axlevel == AxProbU) {
2804 strcpy(hold_rm, actual_rm);
2805 strcpy(actual_rm, CtdlGetConfigStr("c_twitroom"));
2806 syslog(LOG_DEBUG, "msgbase: diverting to twit room");
2810 /* ...or if this message is destined for Aide> then go there. */
2811 if (!IsEmptyStr(force_room)) {
2812 strcpy(actual_rm, force_room);
2815 syslog(LOG_DEBUG, "msgbase: final selection: %s (%s)", actual_rm, room);
2816 if (strcasecmp(actual_rm, CC->room.QRname)) {
2817 /* CtdlGetRoom(&CC->room, actual_rm); */
2818 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL, NULL, NULL);
2822 * If this message has no O (room) field, generate one.
2824 if (CM_IsEmpty(msg, eOriginalRoom) && !IsEmptyStr(CC->room.QRname)) {
2825 CM_SetField(msg, eOriginalRoom, CC->room.QRname, strlen(CC->room.QRname));
2828 /* Perform "before save" hooks (aborting if any return nonzero) */
2829 syslog(LOG_DEBUG, "msgbase: performing before-save hooks");
2830 if (PerformMessageHooks(msg, recps, EVT_BEFORESAVE) > 0) return(-3);
2833 * If this message has an Exclusive ID, and the room is replication
2834 * checking enabled, then do replication checks.
2836 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2837 ReplicationChecks(msg);
2840 /* Save it to disk */
2841 syslog(LOG_DEBUG, "msgbase: saving to disk");
2842 newmsgid = send_message(msg);
2843 if (newmsgid <= 0L) return(-5);
2845 /* Write a supplemental message info record. This doesn't have to
2846 * be a critical section because nobody else knows about this message
2849 syslog(LOG_DEBUG, "msgbase: creating metadata record");
2850 memset(&smi, 0, sizeof(struct MetaData));
2851 smi.meta_msgnum = newmsgid;
2852 smi.meta_refcount = 0;
2853 safestrncpy(smi.meta_content_type, content_type,
2854 sizeof smi.meta_content_type);
2857 * Measure how big this message will be when rendered as RFC822.
2858 * We do this for two reasons:
2859 * 1. We need the RFC822 length for the new metadata record, so the
2860 * POP and IMAP services don't have to calculate message lengths
2861 * while the user is waiting (multiplied by potentially hundreds
2862 * or thousands of messages).
2863 * 2. If journaling is enabled, we will need an RFC822 version of the
2864 * message to attach to the journalized copy.
2866 if (CC->redirect_buffer != NULL) {
2867 syslog(LOG_ALERT, "msgbase: CC->redirect_buffer is not NULL during message submission!");
2870 CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
2871 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
2872 smi.meta_rfc822_length = StrLength(CC->redirect_buffer);
2873 saved_rfc822_version = CC->redirect_buffer;
2874 CC->redirect_buffer = NULL;
2878 /* Now figure out where to store the pointers */
2879 syslog(LOG_DEBUG, "msgbase: storing pointers");
2881 /* If this is being done by the networker delivering a private
2882 * message, we want to BYPASS saving the sender's copy (because there
2883 * is no local sender; it would otherwise go to the Trashcan).
2885 if ((!CC->internal_pgm) || (recps == NULL)) {
2886 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2887 syslog(LOG_ERR, "msgbase: ERROR saving message pointer!");
2888 CtdlSaveMsgPointerInRoom(CtdlGetConfigStr("c_aideroom"), newmsgid, 0, msg);
2892 /* For internet mail, drop a copy in the outbound queue room */
2893 if ((recps != NULL) && (recps->num_internet > 0)) {
2894 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2897 /* If other rooms are specified, drop them there too. */
2898 if ((recps != NULL) && (recps->num_room > 0))
2899 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2900 extract_token(recipient, recps->recp_room, i,
2901 '|', sizeof recipient);
2902 syslog(LOG_DEBUG, "msgbase: delivering to room <%s>", recipient);
2903 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2906 /* Bump this user's messages posted counter. */
2907 syslog(LOG_DEBUG, "msgbase: updating user");
2908 CtdlLockGetCurrentUser();
2909 CC->user.posted = CC->user.posted + 1;
2910 CtdlPutCurrentUserLock();
2912 /* Decide where bounces need to be delivered */
2913 if ((recps != NULL) && (recps->bounce_to == NULL))
2916 snprintf(bounce_to, sizeof bounce_to, "%s@%s",
2917 CC->user.fullname, CtdlGetConfigStr("c_nodename"));
2919 snprintf(bounce_to, sizeof bounce_to, "%s@%s",
2920 msg->cm_fields[eAuthor], msg->cm_fields[eNodeName]);
2921 recps->bounce_to = bounce_to;
2924 CM_SetFieldLONG(msg, eVltMsgNum, newmsgid);
2927 /* If this is private, local mail, make a copy in the
2928 * recipient's mailbox and bump the reference count.
2930 if ((recps != NULL) && (recps->num_local > 0))
2935 pch = recps->recp_local;
2936 recps->recp_local = recipient;
2937 ntokens = num_tokens(pch, '|');
2938 for (i=0; i<ntokens; ++i)
2940 extract_token(recipient, pch, i, '|', sizeof recipient);
2941 syslog(LOG_DEBUG, "msgbase: delivering private local mail to <%s>", recipient);
2942 if (CtdlGetUser(&userbuf, recipient) == 0) {
2943 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
2944 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2945 CtdlBumpNewMailCounter(userbuf.usernum);
2946 PerformMessageHooks(msg, recps, EVT_AFTERUSRMBOXSAVE);
2949 syslog(LOG_DEBUG, "msgbase: no user <%s>", recipient);
2950 CtdlSaveMsgPointerInRoom(CtdlGetConfigStr("c_aideroom"), newmsgid, 0, msg);
2953 recps->recp_local = pch;
2956 /* Perform "after save" hooks */
2957 syslog(LOG_DEBUG, "msgbase: performing after-save hooks");
2959 PerformMessageHooks(msg, recps, EVT_AFTERSAVE);
2960 CM_FlushField(msg, eVltMsgNum);
2962 /* Go back to the room we started from */
2963 syslog(LOG_DEBUG, "msgbase: returning to original room %s", hold_rm);
2964 if (strcasecmp(hold_rm, CC->room.QRname))
2965 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL, NULL, NULL);
2968 * Any addresses to harvest for someone's address book?
2970 if ( (CC->logged_in) && (recps != NULL) ) {
2971 collected_addresses = harvest_collected_addresses(msg);
2974 if (collected_addresses != NULL) {
2975 aptr = (struct addresses_to_be_filed *)
2976 malloc(sizeof(struct addresses_to_be_filed));
2977 CtdlMailboxName(actual_rm, sizeof actual_rm,
2978 &CC->user, USERCONTACTSROOM);
2979 aptr->roomname = strdup(actual_rm);
2980 aptr->collected_addresses = collected_addresses;
2981 begin_critical_section(S_ATBF);
2984 end_critical_section(S_ATBF);
2988 * Determine whether this message qualifies for journaling.
2990 if (!CM_IsEmpty(msg, eJournal)) {
2991 qualified_for_journaling = 0;
2994 if (recps == NULL) {
2995 qualified_for_journaling = CtdlGetConfigInt("c_journal_pubmsgs");
2997 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2998 qualified_for_journaling = CtdlGetConfigInt("c_journal_email");
3001 qualified_for_journaling = CtdlGetConfigInt("c_journal_pubmsgs");
3006 * Do we have to perform journaling? If so, hand off the saved
3007 * RFC822 version will be handed off to the journaler for background
3008 * submit. Otherwise, we have to free the memory ourselves.
3010 if (saved_rfc822_version != NULL) {
3011 if (qualified_for_journaling) {
3012 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
3015 FreeStrBuf(&saved_rfc822_version);
3019 if ((recps != NULL) && (recps->bounce_to == bounce_to))
3020 recps->bounce_to = NULL;
3028 * Convenience function for generating small administrative messages.
3030 long quickie_message(const char *from,
3031 const char *fromaddr,
3036 const char *subject)
3038 struct CtdlMessage *msg;
3039 recptypes *recp = NULL;
3041 msg = malloc(sizeof(struct CtdlMessage));
3042 memset(msg, 0, sizeof(struct CtdlMessage));
3043 msg->cm_magic = CTDLMESSAGE_MAGIC;
3044 msg->cm_anon_type = MES_NORMAL;
3045 msg->cm_format_type = format_type;
3047 if (!IsEmptyStr(from)) {
3048 CM_SetField(msg, eAuthor, from, strlen(from));
3050 else if (!IsEmptyStr(fromaddr)) {
3052 CM_SetField(msg, eAuthor, fromaddr, strlen(fromaddr));
3053 pAt = strchr(msg->cm_fields[eAuthor], '@');
3055 CM_CutFieldAt(msg, eAuthor, pAt - msg->cm_fields[eAuthor]);
3059 msg->cm_fields[eAuthor] = strdup("Citadel");
3062 if (!IsEmptyStr(fromaddr)) CM_SetField(msg, erFc822Addr, fromaddr, strlen(fromaddr));
3063 if (!IsEmptyStr(room)) CM_SetField(msg, eOriginalRoom, room, strlen(room));
3064 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
3065 if (!IsEmptyStr(to)) {
3066 CM_SetField(msg, eRecipient, to, strlen(to));
3067 recp = validate_recipients(to, NULL, 0);
3069 if (!IsEmptyStr(subject)) {
3070 CM_SetField(msg, eMsgSubject, subject, strlen(subject));
3072 if (!IsEmptyStr(text)) {
3073 CM_SetField(msg, eMesageText, text, strlen(text));
3076 long msgnum = CtdlSubmitMsg(msg, recp, room, 0);
3078 if (recp != NULL) free_recipients(recp);
3084 * Back end function used by CtdlMakeMessage() and similar functions
3086 StrBuf *CtdlReadMessageBodyBuf(char *terminator, /* token signalling EOT */
3088 size_t maxlen, /* maximum message length */
3089 StrBuf *exist, /* if non-null, append to it;
3090 exist is ALWAYS freed */
3091 int crlf /* CRLF newlines instead of LF */
3100 LineBuf = NewStrBufPlain(NULL, SIZ);
3101 if (exist == NULL) {
3102 Message = NewStrBufPlain(NULL, 4 * SIZ);
3105 Message = NewStrBufDup(exist);
3108 /* Do we need to change leading ".." to "." for SMTP escaping? */
3109 if ((tlen == 1) && (*terminator == '.')) {
3113 /* read in the lines of message text one by one */
3115 if (CtdlClientGetLine(LineBuf) < 0) {
3118 if ((StrLength(LineBuf) == tlen) && (!strcmp(ChrPtr(LineBuf), terminator))) {
3121 if ( (!flushing) && (!finished) ) {
3123 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3126 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3129 /* Unescape SMTP-style input of two dots at the beginning of the line */
3131 (StrLength(LineBuf) == 2) &&
3132 (!strcmp(ChrPtr(LineBuf), "..")))
3134 StrBufCutLeft(LineBuf, 1);
3137 StrBufAppendBuf(Message, LineBuf, 0);
3140 /* if we've hit the max msg length, flush the rest */
3141 if (StrLength(Message) >= maxlen) flushing = 1;
3143 } while (!finished);
3144 FreeStrBuf(&LineBuf);
3150 * Back end function used by CtdlMakeMessage() and similar functions
3152 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
3154 size_t maxlen, /* maximum message length */
3155 StrBuf *exist, /* if non-null, append to it;
3156 exist is ALWAYS freed */
3157 int crlf /* CRLF newlines instead of LF */
3162 Message = CtdlReadMessageBodyBuf(terminator,
3168 if (Message == NULL)
3171 return SmashStrBuf(&Message);
3174 struct CtdlMessage *CtdlMakeMessage(
3175 struct ctdluser *author, /* author's user structure */
3176 char *recipient, /* NULL if it's not mail */
3177 char *recp_cc, /* NULL if it's not mail */
3178 char *room, /* room where it's going */
3179 int type, /* see MES_ types in header file */
3180 int format_type, /* variformat, plain text, MIME... */
3181 char *fake_name, /* who we're masquerading as */
3182 char *my_email, /* which of my email addresses to use (empty is ok) */
3183 char *subject, /* Subject (optional) */
3184 char *supplied_euid, /* ...or NULL if this is irrelevant */
3185 char *preformatted_text, /* ...or NULL to read text from client */
3186 char *references /* Thread references */
3189 return CtdlMakeMessageLen(
3190 author, /* author's user structure */
3191 recipient, /* NULL if it's not mail */
3192 (recipient)?strlen(recipient) : 0,
3193 recp_cc, /* NULL if it's not mail */
3194 (recp_cc)?strlen(recp_cc): 0,
3195 room, /* room where it's going */
3196 (room)?strlen(room): 0,
3197 type, /* see MES_ types in header file */
3198 format_type, /* variformat, plain text, MIME... */
3199 fake_name, /* who we're masquerading as */
3200 (fake_name)?strlen(fake_name): 0,
3201 my_email, /* which of my email addresses to use (empty is ok) */
3202 (my_email)?strlen(my_email): 0,
3203 subject, /* Subject (optional) */
3204 (subject)?strlen(subject): 0,
3205 supplied_euid, /* ...or NULL if this is irrelevant */
3206 (supplied_euid)?strlen(supplied_euid):0,
3207 preformatted_text, /* ...or NULL to read text from client */
3208 (preformatted_text)?strlen(preformatted_text) : 0,
3209 references, /* Thread references */
3210 (references)?strlen(references):0);
3215 * Build a binary message to be saved on disk.
3216 * (NOTE: if you supply 'preformatted_text', the buffer you give it
3217 * will become part of the message. This means you are no longer
3218 * responsible for managing that memory -- it will be freed along with
3219 * the rest of the fields when CM_Free() is called.)
3222 struct CtdlMessage *CtdlMakeMessageLen(
3223 struct ctdluser *author, /* author's user structure */
3224 char *recipient, /* NULL if it's not mail */
3226 char *recp_cc, /* NULL if it's not mail */
3228 char *room, /* room where it's going */
3230 int type, /* see MES_ types in header file */
3231 int format_type, /* variformat, plain text, MIME... */
3232 char *fake_name, /* who we're masquerading as */
3234 char *my_email, /* which of my email addresses to use (empty is ok) */
3236 char *subject, /* Subject (optional) */
3238 char *supplied_euid, /* ...or NULL if this is irrelevant */
3240 char *preformatted_text, /* ...or NULL to read text from client */
3242 char *references, /* Thread references */
3246 /* Don't confuse the poor folks if it's not routed mail. * /
3247 char dest_node[256] = "";*/
3250 struct CtdlMessage *msg;
3252 StrBuf *FakeEncAuthor = NULL;
3254 msg = malloc(sizeof(struct CtdlMessage));
3255 memset(msg, 0, sizeof(struct CtdlMessage));
3256 msg->cm_magic = CTDLMESSAGE_MAGIC;
3257 msg->cm_anon_type = type;
3258 msg->cm_format_type = format_type;
3260 if (recipient != NULL) rcplen = striplt(recipient);
3261 if (recp_cc != NULL) cclen = striplt(recp_cc);
3263 /* Path or Return-Path */
3265 CM_SetField(msg, eMessagePath, my_email, myelen);
3267 else if (!IsEmptyStr(author->fullname)) {
3268 CM_SetField(msg, eMessagePath, author->fullname, strlen(author->fullname));
3270 convert_spaces_to_underscores(msg->cm_fields[eMessagePath]);
3272 blen = snprintf(buf, sizeof buf, "%ld", (long)time(NULL));
3273 CM_SetField(msg, eTimestamp, buf, blen);
3276 FakeAuthor = NewStrBufPlain (fake_name, fnlen);
3279 FakeAuthor = NewStrBufPlain (author->fullname, -1);
3281 StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
3282 CM_SetAsFieldSB(msg, eAuthor, &FakeEncAuthor);
3283 FreeStrBuf(&FakeAuthor);
3285 if (!!IsEmptyStr(CC->room.QRname)) {
3286 if (CC->room.QRflags & QR_MAILBOX) { /* room */
3287 CM_SetField(msg, eOriginalRoom, &CC->room.QRname[11], strlen(&CC->room.QRname[11]));
3290 CM_SetField(msg, eOriginalRoom, CC->room.QRname, strlen(CC->room.QRname));
3294 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
3295 CM_SetField(msg, eHumanNode, CtdlGetConfigStr("c_humannode"), strlen(CtdlGetConfigStr("c_humannode")));
3298 CM_SetField(msg, eRecipient, recipient, rcplen);
3301 CM_SetField(msg, eCarbonCopY, recp_cc, cclen);
3305 CM_SetField(msg, erFc822Addr, my_email, myelen);
3307 else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
3308 CM_SetField(msg, erFc822Addr, CC->cs_inet_email, strlen(CC->cs_inet_email));
3311 if (subject != NULL) {
3313 length = striplt(subject);
3319 while ((subject[i] != '\0') &&
3320 (IsAscii = isascii(subject[i]) != 0 ))
3323 CM_SetField(msg, eMsgSubject, subject, subjlen);
3324 else /* ok, we've got utf8 in the string. */
3327 rfc2047Subj = rfc2047encode(subject, length);
3328 CM_SetAsField(msg, eMsgSubject, &rfc2047Subj, strlen(rfc2047Subj));
3335 CM_SetField(msg, eExclusiveID, supplied_euid, euidlen);
3339 CM_SetField(msg, eWeferences, references, reflen);
3342 if (preformatted_text != NULL) {
3343 CM_SetField(msg, eMesageText, preformatted_text, textlen);
3347 MsgBody = CtdlReadMessageBodyBuf(HKEY("000"), CtdlGetConfigLong("c_maxmsglen"), NULL, 0);
3348 if (MsgBody != NULL) {
3349 CM_SetAsFieldSB(msg, eMesageText, &MsgBody);
3360 * API function to delete messages which match a set of criteria
3361 * (returns the actual number of messages deleted)
3363 int CtdlDeleteMessages(const char *room_name, /* which room */
3364 long *dmsgnums, /* array of msg numbers to be deleted */
3365 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
3366 char *content_type /* or "" for any. regular expressions expected. */
3369 struct ctdlroom qrbuf;
3370 struct cdbdata *cdbfr;
3371 long *msglist = NULL;
3372 long *dellist = NULL;
3375 int num_deleted = 0;
3377 struct MetaData smi;
3380 int need_to_free_re = 0;
3382 if (content_type) if (!IsEmptyStr(content_type)) {
3383 regcomp(&re, content_type, 0);
3384 need_to_free_re = 1;
3386 syslog(LOG_DEBUG, "msgbase: CtdlDeleteMessages(%s, %d msgs, %s)", room_name, num_dmsgnums, content_type);
3388 /* get room record, obtaining a lock... */
3389 if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
3390 syslog(LOG_ERR, "msgbase: CtdlDeleteMessages(): Room <%s> not found", room_name);
3391 if (need_to_free_re) regfree(&re);
3392 return(0); /* room not found */
3394 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3396 if (cdbfr != NULL) {
3397 dellist = malloc(cdbfr->len);
3398 msglist = (long *) cdbfr->ptr;
3399 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3400 num_msgs = cdbfr->len / sizeof(long);
3404 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
3405 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
3406 int have_more_del = 1;
3408 num_msgs = sort_msglist(msglist, num_msgs);
3409 if (num_dmsgnums > 1)
3410 num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
3413 StrBuf *dbg = NewStrBuf();
3414 for (i = 0; i < num_dmsgnums; i++)
3415 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
3416 syslog(LOG_DEBUG, "msgbase: Deleting before: %s", ChrPtr(dbg));
3421 while ((i < num_msgs) && (have_more_del)) {
3424 /* Set/clear a bit for each criterion */
3426 /* 0 messages in the list or a null list means that we are
3427 * interested in deleting any messages which meet the other criteria.
3430 delete_this |= 0x01;
3433 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
3438 if (msglist[i] == dmsgnums[j]) {
3439 delete_this |= 0x01;
3442 have_more_del = (j < num_dmsgnums);
3445 if (have_contenttype) {
3446 GetMetaData(&smi, msglist[i]);
3447 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3448 delete_this |= 0x02;
3451 delete_this |= 0x02;
3454 /* Delete message only if all bits are set */
3455 if (delete_this == 0x03) {
3456 dellist[num_deleted++] = msglist[i];
3463 StrBuf *dbg = NewStrBuf();
3464 for (i = 0; i < num_deleted; i++)
3465 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
3466 syslog(LOG_DEBUG, "msgbase: Deleting: %s", ChrPtr(dbg));
3470 num_msgs = sort_msglist(msglist, num_msgs);
3471 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3472 msglist, (int)(num_msgs * sizeof(long)));
3475 qrbuf.QRhighest = msglist[num_msgs - 1];
3477 qrbuf.QRhighest = 0;
3479 CtdlPutRoomLock(&qrbuf);
3481 /* Go through the messages we pulled out of the index, and decrement
3482 * their reference counts by 1. If this is the only room the message
3483 * was in, the reference count will reach zero and the message will
3484 * automatically be deleted from the database. We do this in a
3485 * separate pass because there might be plug-in hooks getting called,
3486 * and we don't want that happening during an S_ROOMS critical
3490 for (i=0; i<num_deleted; ++i) {
3491 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3493 AdjRefCountList(dellist, num_deleted, -1);
3495 /* Now free the memory we used, and go away. */
3496 if (msglist != NULL) free(msglist);
3497 if (dellist != NULL) free(dellist);
3498 syslog(LOG_DEBUG, "msgbase: %d message(s) deleted", num_deleted);
3499 if (need_to_free_re) regfree(&re);
3500 return (num_deleted);
3507 * GetMetaData() - Get the supplementary record for a message
3509 void GetMetaData(struct MetaData *smibuf, long msgnum)
3512 struct cdbdata *cdbsmi;
3515 memset(smibuf, 0, sizeof(struct MetaData));
3516 smibuf->meta_msgnum = msgnum;
3517 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3519 /* Use the negative of the message number for its supp record index */
3520 TheIndex = (0L - msgnum);
3522 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3523 if (cdbsmi == NULL) {
3524 return; /* record not found; go with defaults */
3526 memcpy(smibuf, cdbsmi->ptr,
3527 ((cdbsmi->len > sizeof(struct MetaData)) ?
3528 sizeof(struct MetaData) : cdbsmi->len));
3535 * PutMetaData() - (re)write supplementary record for a message
3537 void PutMetaData(struct MetaData *smibuf)
3541 /* Use the negative of the message number for the metadata db index */
3542 TheIndex = (0L - smibuf->meta_msgnum);
3544 cdb_store(CDB_MSGMAIN,
3545 &TheIndex, (int)sizeof(long),
3546 smibuf, (int)sizeof(struct MetaData));
3551 * AdjRefCount - submit an adjustment to the reference count for a message.
3552 * (These are just queued -- we actually process them later.)
3554 void AdjRefCount(long msgnum, int incr)
3556 struct arcq new_arcq;
3559 syslog(LOG_DEBUG, "msgbase: AdjRefCount() msg %ld ref count delta %+d", msgnum, incr);
3561 begin_critical_section(S_SUPPMSGMAIN);
3562 if (arcfp == NULL) {
3563 arcfp = fopen(file_arcq, "ab+");
3564 chown(file_arcq, CTDLUID, (-1));
3565 chmod(file_arcq, 0600);
3567 end_critical_section(S_SUPPMSGMAIN);
3569 /* msgnum < 0 means that we're trying to close the file */
3571 syslog(LOG_DEBUG, "msgbase: closing the AdjRefCount queue file");
3572 begin_critical_section(S_SUPPMSGMAIN);
3573 if (arcfp != NULL) {
3577 end_critical_section(S_SUPPMSGMAIN);
3582 * If we can't open the queue, perform the operation synchronously.
3584 if (arcfp == NULL) {
3585 TDAP_AdjRefCount(msgnum, incr);
3589 new_arcq.arcq_msgnum = msgnum;
3590 new_arcq.arcq_delta = incr;
3591 rv = fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
3593 syslog(LOG_EMERG, "%s: %m", file_arcq);
3600 void AdjRefCountList(long *msgnum, long nmsg, int incr)
3602 long i, the_size, offset;
3603 struct arcq *new_arcq;
3606 syslog(LOG_DEBUG, "msgbase: AdjRefCountList() msg %ld ref count delta %+d", nmsg, incr);
3608 begin_critical_section(S_SUPPMSGMAIN);
3609 if (arcfp == NULL) {
3610 arcfp = fopen(file_arcq, "ab+");
3611 chown(file_arcq, CTDLUID, (-1));
3612 chmod(file_arcq, 0600);
3614 end_critical_section(S_SUPPMSGMAIN);
3617 * If we can't open the queue, perform the operation synchronously.
3619 if (arcfp == NULL) {
3620 for (i = 0; i < nmsg; i++)
3621 TDAP_AdjRefCount(msgnum[i], incr);
3625 the_size = sizeof(struct arcq) * nmsg;
3626 new_arcq = malloc(the_size);
3627 for (i = 0; i < nmsg; i++) {
3628 new_arcq[i].arcq_msgnum = msgnum[i];
3629 new_arcq[i].arcq_delta = incr;
3633 while ((rv >= 0) && (offset < the_size))
3635 rv = fwrite(new_arcq + offset, 1, the_size - offset, arcfp);
3637 syslog(LOG_ERR, "%s: %m", file_arcq);
3651 * TDAP_ProcessAdjRefCountQueue()
3653 * Process the queue of message count adjustments that was created by calls
3654 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
3655 * for each one. This should be an "off hours" operation.
3657 int TDAP_ProcessAdjRefCountQueue(void)
3659 char file_arcq_temp[PATH_MAX];
3662 struct arcq arcq_rec;
3663 int num_records_processed = 0;
3665 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s.%04x", file_arcq, rand());
3667 begin_critical_section(S_SUPPMSGMAIN);
3668 if (arcfp != NULL) {
3673 r = link(file_arcq, file_arcq_temp);
3675 syslog(LOG_ERR, "%s: %m", file_arcq_temp);
3676 end_critical_section(S_SUPPMSGMAIN);
3677 return(num_records_processed);
3681 end_critical_section(S_SUPPMSGMAIN);
3683 fp = fopen(file_arcq_temp, "rb");
3685 syslog(LOG_ERR, "%s: %m", file_arcq_temp);
3686 return(num_records_processed);
3689 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
3690 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
3691 ++num_records_processed;
3695 r = unlink(file_arcq_temp);
3697 syslog(LOG_ERR, "%s: %m", file_arcq_temp);
3700 return(num_records_processed);
3706 * TDAP_AdjRefCount - adjust the reference count for a message.
3707 * This one does it "for real" because it's called by
3708 * the autopurger function that processes the queue
3709 * created by AdjRefCount(). If a message's reference
3710 * count becomes zero, we also delete the message from
3711 * disk and de-index it.
3713 void TDAP_AdjRefCount(long msgnum, int incr)
3716 struct MetaData smi;
3719 /* This is a *tight* critical section; please keep it that way, as
3720 * it may get called while nested in other critical sections.
3721 * Complicating this any further will surely cause deadlock!
3723 begin_critical_section(S_SUPPMSGMAIN);
3724 GetMetaData(&smi, msgnum);
3725 smi.meta_refcount += incr;
3727 end_critical_section(S_SUPPMSGMAIN);
3728 syslog(LOG_DEBUG, "msgbase: TDAP_AdjRefCount() msg %ld ref count delta %+d, is now %d",
3729 msgnum, incr, smi.meta_refcount
3732 /* If the reference count is now zero, delete the message
3733 * (and its supplementary record as well).
3735 if (smi.meta_refcount == 0) {
3736 syslog(LOG_DEBUG, "msgbase: deleting message <%ld>", msgnum);
3738 /* Call delete hooks with NULL room to show it has gone altogether */
3739 PerformDeleteHooks(NULL, msgnum);
3741 /* Remove from message base */
3743 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3744 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3746 /* Remove metadata record */
3747 delnum = (0L - msgnum);
3748 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3754 * Write a generic object to this room
3756 * Note: this could be much more efficient. Right now we use two temporary
3757 * files, and still pull the message into memory as with all others.
3759 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
3760 char *content_type, /* MIME type of this object */
3761 char *raw_message, /* Data to be written */
3762 off_t raw_length, /* Size of raw_message */
3763 struct ctdluser *is_mailbox, /* Mailbox room? */
3764 int is_binary, /* Is encoding necessary? */
3765 int is_unique, /* Del others of this type? */
3766 unsigned int flags /* Internal save flags */
3769 struct ctdlroom qrbuf;
3770 char roomname[ROOMNAMELEN];
3771 struct CtdlMessage *msg;
3772 StrBuf *encoded_message = NULL;
3774 if (is_mailbox != NULL) {
3775 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3778 safestrncpy(roomname, req_room, sizeof(roomname));
3781 syslog(LOG_DEBUG, "msfbase: raw length is %ld", (long)raw_length);
3784 encoded_message = NewStrBufPlain(NULL, (size_t) (((raw_length * 134) / 100) + 4096 ) );
3787 encoded_message = NewStrBufPlain(NULL, (size_t)(raw_length + 4096));
3790 StrBufAppendBufPlain(encoded_message, HKEY("Content-type: "), 0);
3791 StrBufAppendBufPlain(encoded_message, content_type, -1, 0);
3792 StrBufAppendBufPlain(encoded_message, HKEY("\n"), 0);
3795 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: base64\n\n"), 0);
3798 StrBufAppendBufPlain(encoded_message, HKEY("Content-transfer-encoding: 7bit\n\n"), 0);
3802 StrBufBase64Append(encoded_message, NULL, raw_message, raw_length, 0);
3805 StrBufAppendBufPlain(encoded_message, raw_message, raw_length, 0);
3808 syslog(LOG_DEBUG, "msgbase: allocating");
3809 msg = malloc(sizeof(struct CtdlMessage));
3810 memset(msg, 0, sizeof(struct CtdlMessage));
3811 msg->cm_magic = CTDLMESSAGE_MAGIC;
3812 msg->cm_anon_type = MES_NORMAL;
3813 msg->cm_format_type = 4;
3814 CM_SetField(msg, eAuthor, CC->user.fullname, strlen(CC->user.fullname));
3815 CM_SetField(msg, eOriginalRoom, req_room, strlen(req_room));
3816 CM_SetField(msg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
3817 CM_SetField(msg, eHumanNode, CtdlGetConfigStr("c_humannode"), strlen(CtdlGetConfigStr("c_humannode")));
3818 msg->cm_flags = flags;
3820 CM_SetAsFieldSB(msg, eMesageText, &encoded_message);
3822 /* Create the requested room if we have to. */
3823 if (CtdlGetRoom(&qrbuf, roomname) != 0) {
3824 CtdlCreateRoom(roomname,
3825 ( (is_mailbox != NULL) ? 5 : 3 ),
3826 "", 0, 1, 0, VIEW_BBS);
3828 /* If the caller specified this object as unique, delete all
3829 * other objects of this type that are currently in the room.
3832 syslog(LOG_DEBUG, "msgbase: deleted %d other msgs of this type",
3833 CtdlDeleteMessages(roomname, NULL, 0, content_type)
3836 /* Now write the data */
3837 CtdlSubmitMsg(msg, NULL, roomname, 0);
3843 /*****************************************************************************/
3844 /* MODULE INITIALIZATION STUFF */
3845 /*****************************************************************************/
3847 CTDL_MODULE_INIT(msgbase)
3850 FillMsgKeyLookupTable();
3853 /* return our Subversion id for the Log */