2 * Implements the message store.
4 * Copyright (c) 1987-2012 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 #if TIME_WITH_SYS_TIME
22 # include <sys/time.h>
26 # include <sys/time.h>
39 #include <sys/types.h>
44 #include <libcitadel.h>
47 #include "serv_extensions.h"
51 #include "sysdep_decls.h"
52 #include "citserver.h"
59 #include "internet_addressing.h"
60 #include "euidindex.h"
61 #include "journaling.h"
62 #include "citadel_dirs.h"
63 #include "clientsocket.h"
66 #include "ctdl_module.h"
69 struct addresses_to_be_filed *atbf = NULL;
71 /* This temp file holds the queue of operations for AdjRefCount() */
72 static FILE *arcfp = NULL;
73 void AdjRefCountList(long *msgnum, long nmsg, int incr);
75 int MessageDebugEnabled = 0;
78 * These are the four-character field headers we use when outputting
79 * messages in Citadel format (as opposed to RFC822 format).
82 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
83 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
84 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
85 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
86 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
87 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
88 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
89 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
118 * This function is self explanatory.
119 * (What can I say, I'm in a weird mood today...)
121 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
125 for (i = 0; i < strlen(name); ++i) {
126 if (name[i] == '@') {
127 while (isspace(name[i - 1]) && i > 0) {
128 strcpy(&name[i - 1], &name[i]);
131 while (isspace(name[i + 1])) {
132 strcpy(&name[i + 1], &name[i + 2]);
140 * Aliasing for network mail.
141 * (Error messages have been commented out, because this is a server.)
143 int alias(char *name)
144 { /* process alias and routing info for mail */
145 struct CitContext *CCC = CC;
148 char aaa[SIZ], bbb[SIZ];
149 char *ignetcfg = NULL;
150 char *ignetmap = NULL;
156 char original_name[256];
157 safestrncpy(original_name, name, sizeof original_name);
160 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
161 stripallbut(name, '<', '>');
163 fp = fopen(file_mail_aliases, "r");
165 fp = fopen("/dev/null", "r");
172 while (fgets(aaa, sizeof aaa, fp) != NULL) {
173 while (isspace(name[0]))
174 strcpy(name, &name[1]);
175 aaa[strlen(aaa) - 1] = 0;
177 for (a = 0; a < strlen(aaa); ++a) {
179 strcpy(bbb, &aaa[a + 1]);
183 if (!strcasecmp(name, aaa))
188 /* Hit the Global Address Book */
189 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
193 if (strcasecmp(original_name, name)) {
194 MSG_syslog(LOG_INFO, "%s is being forwarded to %s\n", original_name, name);
197 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
198 for (a=0; a<strlen(name); ++a) {
199 if (name[a] == '@') {
200 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
202 MSG_syslog(LOG_INFO, "Changed to <%s>\n", name);
207 /* determine local or remote type, see citadel.h */
208 at = haschar(name, '@');
209 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
210 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
211 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
213 /* figure out the delivery mode */
214 extract_token(node, name, 1, '@', sizeof node);
216 /* If there are one or more dots in the nodename, we assume that it
217 * is an FQDN and will attempt SMTP delivery to the Internet.
219 if (haschar(node, '.') > 0) {
220 return(MES_INTERNET);
223 /* Otherwise we look in the IGnet maps for a valid Citadel node.
224 * Try directly-connected nodes first...
226 ignetcfg = CtdlGetSysConfig(IGNETCFG);
227 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
228 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
229 extract_token(testnode, buf, 0, '|', sizeof testnode);
230 if (!strcasecmp(node, testnode)) {
238 * Then try nodes that are two or more hops away.
240 ignetmap = CtdlGetSysConfig(IGNETMAP);
241 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
242 extract_token(buf, ignetmap, i, '\n', sizeof buf);
243 extract_token(testnode, buf, 0, '|', sizeof testnode);
244 if (!strcasecmp(node, testnode)) {
251 /* If we get to this point it's an invalid node name */
257 * Back end for the MSGS command: output message number only.
259 void simple_listing(long msgnum, void *userdata)
261 cprintf("%ld\n", msgnum);
267 * Back end for the MSGS command: output header summary.
269 void headers_listing(long msgnum, void *userdata)
271 struct CtdlMessage *msg;
273 msg = CtdlFetchMessage(msgnum, 0);
275 cprintf("%ld|0|||||\n", msgnum);
279 cprintf("%ld|%s|%s|%s|%s|%s|\n",
281 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
282 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
283 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
284 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
285 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
287 CtdlFreeMessage(msg);
291 * Back end for the MSGS command: output EUID header.
293 void headers_euid(long msgnum, void *userdata)
295 struct CtdlMessage *msg;
297 msg = CtdlFetchMessage(msgnum, 0);
299 cprintf("%ld||\n", msgnum);
303 cprintf("%ld|%s|%s\n",
305 (msg->cm_fields['E'] ? msg->cm_fields['E'] : ""),
306 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"));
307 CtdlFreeMessage(msg);
314 /* Determine if a given message matches the fields in a message template.
315 * Return 0 for a successful match.
317 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
320 /* If there aren't any fields in the template, all messages will
323 if (template == NULL) return(0);
325 /* Null messages are bogus. */
326 if (msg == NULL) return(1);
328 for (i='A'; i<='Z'; ++i) {
329 if (template->cm_fields[i] != NULL) {
330 if (msg->cm_fields[i] == NULL) {
331 /* Considered equal if temmplate is empty string */
332 if (IsEmptyStr(template->cm_fields[i])) continue;
335 if (strcasecmp(msg->cm_fields[i],
336 template->cm_fields[i])) return 1;
340 /* All compares succeeded: we have a match! */
347 * Retrieve the "seen" message list for the current room.
349 void CtdlGetSeen(char *buf, int which_set) {
350 struct CitContext *CCC = CC;
353 /* Learn about the user and room in question */
354 CtdlGetRelationship(&vbuf, &CCC->user, &CCC->room);
356 if (which_set == ctdlsetseen_seen)
357 safestrncpy(buf, vbuf.v_seen, SIZ);
358 if (which_set == ctdlsetseen_answered)
359 safestrncpy(buf, vbuf.v_answered, SIZ);
365 * Manipulate the "seen msgs" string (or other message set strings)
367 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
368 int target_setting, int which_set,
369 struct ctdluser *which_user, struct ctdlroom *which_room) {
370 struct CitContext *CCC = CC;
371 struct cdbdata *cdbfr;
376 long hi = (-1L); /// TODO: we just write here. y?
385 char *is_set; /* actually an array of booleans */
387 /* Don't bother doing *anything* if we were passed a list of zero messages */
388 if (num_target_msgnums < 1) {
392 /* If no room was specified, we go with the current room. */
394 which_room = &CCC->room;
397 /* If no user was specified, we go with the current user. */
399 which_user = &CCC->user;
402 MSG_syslog(LOG_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %s, %d) in <%s>\n",
403 num_target_msgnums, target_msgnums[0],
404 (target_setting ? "SET" : "CLEAR"),
408 /* Learn about the user and room in question */
409 CtdlGetRelationship(&vbuf, which_user, which_room);
411 /* Load the message list */
412 cdbfr = cdb_fetch(CDB_MSGLISTS, &which_room->QRnumber, sizeof(long));
414 msglist = (long *) cdbfr->ptr;
415 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
416 num_msgs = cdbfr->len / sizeof(long);
419 return; /* No messages at all? No further action. */
422 is_set = malloc(num_msgs * sizeof(char));
423 memset(is_set, 0, (num_msgs * sizeof(char)) );
425 /* Decide which message set we're manipulating */
427 case ctdlsetseen_seen:
428 vset = NewStrBufPlain(vbuf.v_seen, -1);
430 case ctdlsetseen_answered:
431 vset = NewStrBufPlain(vbuf.v_answered, -1);
438 #if 0 /* This is a special diagnostic section. Do not allow it to run during normal operation. */
439 MSG_syslog(LOG_DEBUG, "There are %d messages in the room.\n", num_msgs);
440 for (i=0; i<num_msgs; ++i) {
441 if ((i > 0) && (msglist[i] <= msglist[i-1])) abort();
443 MSG_syslog(LOG_DEBUG, "We are twiddling %d of them.\n", num_target_msgnums);
444 for (k=0; k<num_target_msgnums; ++k) {
445 if ((k > 0) && (target_msgnums[k] <= target_msgnums[k-1])) abort();
449 MSG_syslog(LOG_DEBUG, "before update: %s\n", ChrPtr(vset));
451 /* Translate the existing sequence set into an array of booleans */
452 setstr = NewStrBuf();
456 while (StrBufExtract_NextToken(setstr, vset, &pvset, ',') >= 0) {
458 StrBufExtract_token(lostr, setstr, 0, ':');
459 if (StrBufNum_tokens(setstr, ':') >= 2) {
460 StrBufExtract_token(histr, setstr, 1, ':');
464 StrBufAppendBuf(histr, lostr, 0);
467 if (!strcmp(ChrPtr(histr), "*")) {
474 for (i = 0; i < num_msgs; ++i) {
475 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
485 /* Now translate the array of booleans back into a sequence set */
491 for (i=0; i<num_msgs; ++i) {
495 for (k=0; k<num_target_msgnums; ++k) {
496 if (msglist[i] == target_msgnums[k]) {
497 is_seen = target_setting;
501 if ((was_seen == 0) && (is_seen == 1)) {
504 else if ((was_seen == 1) && (is_seen == 0)) {
507 if (StrLength(vset) > 0) {
508 StrBufAppendBufPlain(vset, HKEY(","), 0);
511 StrBufAppendPrintf(vset, "%ld", hi);
514 StrBufAppendPrintf(vset, "%ld:%ld", lo, hi);
518 if ((is_seen) && (i == num_msgs - 1)) {
519 if (StrLength(vset) > 0) {
520 StrBufAppendBufPlain(vset, HKEY(","), 0);
522 if ((i==0) || (was_seen == 0)) {
523 StrBufAppendPrintf(vset, "%ld", msglist[i]);
526 StrBufAppendPrintf(vset, "%ld:%ld", lo, msglist[i]);
534 * We will have to stuff this string back into a 4096 byte buffer, so if it's
535 * larger than that now, truncate it by removing tokens from the beginning.
536 * The limit of 100 iterations is there to prevent an infinite loop in case
537 * something unexpected happens.
539 int number_of_truncations = 0;
540 while ( (StrLength(vset) > SIZ) && (number_of_truncations < 100) ) {
541 StrBufRemove_token(vset, 0, ',');
542 ++number_of_truncations;
546 * If we're truncating the sequence set of messages marked with the 'seen' flag,
547 * we want the earliest messages (the truncated ones) to be marked, not unmarked.
548 * Otherwise messages at the beginning will suddenly appear to be 'unseen'.
550 if ( (which_set == ctdlsetseen_seen) && (number_of_truncations > 0) ) {
552 first_tok = NewStrBuf();
553 StrBufExtract_token(first_tok, vset, 0, ',');
554 StrBufRemove_token(vset, 0, ',');
556 if (StrBufNum_tokens(first_tok, ':') > 1) {
557 StrBufRemove_token(first_tok, 0, ':');
561 new_set = NewStrBuf();
562 StrBufAppendBufPlain(new_set, HKEY("1:"), 0);
563 StrBufAppendBuf(new_set, first_tok, 0);
564 StrBufAppendBufPlain(new_set, HKEY(":"), 0);
565 StrBufAppendBuf(new_set, vset, 0);
568 FreeStrBuf(&first_tok);
572 MSG_syslog(LOG_DEBUG, " after update: %s\n", ChrPtr(vset));
574 /* Decide which message set we're manipulating */
576 case ctdlsetseen_seen:
577 safestrncpy(vbuf.v_seen, ChrPtr(vset), sizeof vbuf.v_seen);
579 case ctdlsetseen_answered:
580 safestrncpy(vbuf.v_answered, ChrPtr(vset), sizeof vbuf.v_answered);
586 CtdlSetRelationship(&vbuf, which_user, which_room);
592 * API function to perform an operation for each qualifying message in the
593 * current room. (Returns the number of messages processed.)
595 int CtdlForEachMessage(int mode, long ref, char *search_string,
597 struct CtdlMessage *compare,
598 ForEachMsgCallback CallBack,
601 struct CitContext *CCC = CC;
604 struct cdbdata *cdbfr;
605 long *msglist = NULL;
607 int num_processed = 0;
610 struct CtdlMessage *msg = NULL;
613 int printed_lastold = 0;
614 int num_search_msgs = 0;
615 long *search_msgs = NULL;
617 int need_to_free_re = 0;
620 if ((content_type) && (!IsEmptyStr(content_type))) {
621 regcomp(&re, content_type, 0);
625 /* Learn about the user and room in question */
626 if (server_shutting_down) {
627 if (need_to_free_re) regfree(&re);
630 CtdlGetUser(&CCC->user, CCC->curr_user);
632 if (server_shutting_down) {
633 if (need_to_free_re) regfree(&re);
636 CtdlGetRelationship(&vbuf, &CCC->user, &CCC->room);
638 if (server_shutting_down) {
639 if (need_to_free_re) regfree(&re);
643 /* Load the message list */
644 cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
646 if (need_to_free_re) regfree(&re);
647 return 0; /* No messages at all? No further action. */
650 msglist = (long *) cdbfr->ptr;
651 num_msgs = cdbfr->len / sizeof(long);
653 cdbfr->ptr = NULL; /* clear this so that cdb_free() doesn't free it */
654 cdb_free(cdbfr); /* we own this memory now */
657 * Now begin the traversal.
659 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
661 /* If the caller is looking for a specific MIME type, filter
662 * out all messages which are not of the type requested.
664 if ((content_type != NULL) && (!IsEmptyStr(content_type))) {
666 /* This call to GetMetaData() sits inside this loop
667 * so that we only do the extra database read per msg
668 * if we need to. Doing the extra read all the time
669 * really kills the server. If we ever need to use
670 * metadata for another search criterion, we need to
671 * move the read somewhere else -- but still be smart
672 * enough to only do the read if the caller has
673 * specified something that will need it.
675 if (server_shutting_down) {
676 if (need_to_free_re) regfree(&re);
680 GetMetaData(&smi, msglist[a]);
682 /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
683 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
689 num_msgs = sort_msglist(msglist, num_msgs);
691 /* If a template was supplied, filter out the messages which
692 * don't match. (This could induce some delays!)
695 if (compare != NULL) {
696 for (a = 0; a < num_msgs; ++a) {
697 if (server_shutting_down) {
698 if (need_to_free_re) regfree(&re);
702 msg = CtdlFetchMessage(msglist[a], 1);
704 if (CtdlMsgCmp(msg, compare)) {
707 CtdlFreeMessage(msg);
713 /* If a search string was specified, get a message list from
714 * the full text index and remove messages which aren't on both
718 * Since the lists are sorted and strictly ascending, and the
719 * output list is guaranteed to be shorter than or equal to the
720 * input list, we overwrite the bottom of the input list. This
721 * eliminates the need to memmove big chunks of the list over and
724 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
726 /* Call search module via hook mechanism.
727 * NULL means use any search function available.
728 * otherwise replace with a char * to name of search routine
730 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
732 if (num_search_msgs > 0) {
736 orig_num_msgs = num_msgs;
738 for (i=0; i<orig_num_msgs; ++i) {
739 for (j=0; j<num_search_msgs; ++j) {
740 if (msglist[i] == search_msgs[j]) {
741 msglist[num_msgs++] = msglist[i];
747 num_msgs = 0; /* No messages qualify */
749 if (search_msgs != NULL) free(search_msgs);
751 /* Now that we've purged messages which don't contain the search
752 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
759 * Now iterate through the message list, according to the
760 * criteria supplied by the caller.
763 for (a = 0; a < num_msgs; ++a) {
764 if (server_shutting_down) {
765 if (need_to_free_re) regfree(&re);
767 return num_processed;
769 thismsg = msglist[a];
770 if (mode == MSGS_ALL) {
774 is_seen = is_msg_in_sequence_set(
775 vbuf.v_seen, thismsg);
776 if (is_seen) lastold = thismsg;
782 || ((mode == MSGS_OLD) && (is_seen))
783 || ((mode == MSGS_NEW) && (!is_seen))
784 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
785 || ((mode == MSGS_FIRST) && (a < ref))
786 || ((mode == MSGS_GT) && (thismsg > ref))
787 || ((mode == MSGS_LT) && (thismsg < ref))
788 || ((mode == MSGS_EQ) && (thismsg == ref))
791 if ((mode == MSGS_NEW) && (CCC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
793 CallBack(lastold, userdata);
797 if (CallBack) CallBack(thismsg, userdata);
801 if (need_to_free_re) regfree(&re);
804 * We cache the most recent msglist in order to do security checks later
806 if (CCC->client_socket > 0) {
807 if (CCC->cached_msglist != NULL) {
808 free(CCC->cached_msglist);
810 CCC->cached_msglist = msglist;
811 CCC->cached_num_msgs = num_msgs;
817 return num_processed;
823 * cmd_msgs() - get list of message #'s in this room
824 * implements the MSGS server command using CtdlForEachMessage()
826 void cmd_msgs(char *cmdbuf)
835 int with_template = 0;
836 struct CtdlMessage *template = NULL;
837 char search_string[1024];
838 ForEachMsgCallback CallBack;
840 if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
842 extract_token(which, cmdbuf, 0, '|', sizeof which);
843 cm_ref = extract_int(cmdbuf, 1);
844 extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
845 with_template = extract_int(cmdbuf, 2);
846 switch (extract_int(cmdbuf, 3))
850 CallBack = simple_listing;
853 CallBack = headers_listing;
856 CallBack = headers_euid;
861 if (!strncasecmp(which, "OLD", 3))
863 else if (!strncasecmp(which, "NEW", 3))
865 else if (!strncasecmp(which, "FIRST", 5))
867 else if (!strncasecmp(which, "LAST", 4))
869 else if (!strncasecmp(which, "GT", 2))
871 else if (!strncasecmp(which, "LT", 2))
873 else if (!strncasecmp(which, "SEARCH", 6))
878 if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
879 cprintf("%d Full text index is not enabled on this server.\n",
880 ERROR + CMD_NOT_SUPPORTED);
886 cprintf("%d Send template then receive message list\n",
888 template = (struct CtdlMessage *)
889 malloc(sizeof(struct CtdlMessage));
890 memset(template, 0, sizeof(struct CtdlMessage));
891 template->cm_magic = CTDLMESSAGE_MAGIC;
892 template->cm_anon_type = MES_NORMAL;
894 while(client_getln(buf, sizeof buf) >= 0 && strcmp(buf,"000")) {
895 extract_token(tfield, buf, 0, '|', sizeof tfield);
896 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
897 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
898 if (!strcasecmp(tfield, msgkeys[i])) {
899 template->cm_fields[i] =
907 cprintf("%d \n", LISTING_FOLLOWS);
910 CtdlForEachMessage(mode,
911 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
912 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
917 if (template != NULL) CtdlFreeMessage(template);
925 * help_subst() - support routine for help file viewer
927 void help_subst(char *strbuf, char *source, char *dest)
932 while (p = pattern2(strbuf, source), (p >= 0)) {
933 strcpy(workbuf, &strbuf[p + strlen(source)]);
934 strcpy(&strbuf[p], dest);
935 strcat(strbuf, workbuf);
940 void do_help_subst(char *buffer)
944 help_subst(buffer, "^nodename", config.c_nodename);
945 help_subst(buffer, "^humannode", config.c_humannode);
946 help_subst(buffer, "^fqdn", config.c_fqdn);
947 help_subst(buffer, "^username", CC->user.fullname);
948 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
949 help_subst(buffer, "^usernum", buf2);
950 help_subst(buffer, "^sysadm", config.c_sysadm);
951 help_subst(buffer, "^variantname", CITADEL);
952 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
953 help_subst(buffer, "^maxsessions", buf2);
954 help_subst(buffer, "^bbsdir", ctdl_message_dir);
960 * memfmout() - Citadel text formatter and paginator.
961 * Although the original purpose of this routine was to format
962 * text to the reader's screen width, all we're really using it
963 * for here is to format text out to 80 columns before sending it
964 * to the client. The client software may reformat it again.
967 char *mptr, /* where are we going to get our text from? */
968 const char *nl /* string to terminate lines with */
970 struct CitContext *CCC = CC;
972 unsigned char ch = 0;
979 while (ch=*(mptr++), ch != 0) {
982 if (client_write(outbuf, len) == -1)
984 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
988 if (client_write(nl, nllen) == -1)
990 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
995 else if (ch == '\r') {
996 /* Ignore carriage returns. Newlines are always LF or CRLF but never CR. */
998 else if (isspace(ch)) {
999 if (column > 72) { /* Beyond 72 columns, break on the next space */
1000 if (client_write(outbuf, len) == -1)
1002 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1006 if (client_write(nl, nllen) == -1)
1008 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1021 if (column > 1000) { /* Beyond 1000 columns, break anywhere */
1022 if (client_write(outbuf, len) == -1)
1024 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1028 if (client_write(nl, nllen) == -1)
1030 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1038 if (client_write(outbuf, len) == -1)
1040 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1044 client_write(nl, nllen);
1052 * Callback function for mime parser that simply lists the part
1054 void list_this_part(char *name, char *filename, char *partnum, char *disp,
1055 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1056 char *cbid, void *cbuserdata)
1060 ma = (struct ma_info *)cbuserdata;
1061 if (ma->is_ma == 0) {
1062 cprintf("part=%s|%s|%s|%s|%s|%ld|%s|%s\n",
1075 * Callback function for multipart prefix
1077 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
1078 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1079 char *cbid, void *cbuserdata)
1083 ma = (struct ma_info *)cbuserdata;
1084 if (!strcasecmp(cbtype, "multipart/alternative")) {
1088 if (ma->is_ma == 0) {
1089 cprintf("pref=%s|%s\n", partnum, cbtype);
1094 * Callback function for multipart sufffix
1096 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
1097 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1098 char *cbid, void *cbuserdata)
1102 ma = (struct ma_info *)cbuserdata;
1103 if (ma->is_ma == 0) {
1104 cprintf("suff=%s|%s\n", partnum, cbtype);
1106 if (!strcasecmp(cbtype, "multipart/alternative")) {
1113 * Callback function for mime parser that opens a section for downloading
1115 void mime_download(char *name, char *filename, char *partnum, char *disp,
1116 void *content, char *cbtype, char *cbcharset, size_t length,
1117 char *encoding, char *cbid, void *cbuserdata)
1120 CitContext *CCC = MyContext();
1122 /* Silently go away if there's already a download open. */
1123 if (CCC->download_fp != NULL)
1127 (!IsEmptyStr(partnum) && (!strcasecmp(CCC->download_desired_section, partnum)))
1128 || (!IsEmptyStr(cbid) && (!strcasecmp(CCC->download_desired_section, cbid)))
1130 CCC->download_fp = tmpfile();
1131 if (CCC->download_fp == NULL) {
1132 MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1134 cprintf("%d cannot open temporary file: %s\n",
1135 ERROR + INTERNAL_ERROR, strerror(errno));
1139 rv = fwrite(content, length, 1, CC->download_fp);
1141 MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1143 cprintf("%d unable to write tempfile.\n",
1145 fclose(CCC->download_fp);
1146 CCC->download_fp = NULL;
1149 fflush(CCC->download_fp);
1150 rewind(CCC->download_fp);
1152 OpenCmdResult(filename, cbtype);
1159 * Callback function for mime parser that outputs a section all at once.
1160 * We can specify the desired section by part number *or* content-id.
1162 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
1163 void *content, char *cbtype, char *cbcharset, size_t length,
1164 char *encoding, char *cbid, void *cbuserdata)
1166 int *found_it = (int *)cbuserdata;
1169 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1170 || (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1173 cprintf("%d %d|-1|%s|%s|%s\n",
1180 client_write(content, length);
1186 * Load a message from disk into memory.
1187 * This is used by CtdlOutputMsg() and other fetch functions.
1189 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1190 * using the CtdlMessageFree() function.
1192 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1194 struct CitContext *CCC = CC;
1195 struct cdbdata *dmsgtext;
1196 struct CtdlMessage *ret = NULL;
1200 cit_uint8_t field_header;
1202 MSG_syslog(LOG_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1203 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1204 if (dmsgtext == NULL) {
1207 mptr = dmsgtext->ptr;
1208 upper_bound = mptr + dmsgtext->len;
1210 /* Parse the three bytes that begin EVERY message on disk.
1211 * The first is always 0xFF, the on-disk magic number.
1212 * The second is the anonymous/public type byte.
1213 * The third is the format type byte (vari, fixed, or MIME).
1217 MSG_syslog(LOG_ERR, "Message %ld appears to be corrupted.\n", msgnum);
1221 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1222 memset(ret, 0, sizeof(struct CtdlMessage));
1224 ret->cm_magic = CTDLMESSAGE_MAGIC;
1225 ret->cm_anon_type = *mptr++; /* Anon type byte */
1226 ret->cm_format_type = *mptr++; /* Format type byte */
1229 * The rest is zero or more arbitrary fields. Load them in.
1230 * We're done when we encounter either a zero-length field or
1231 * have just processed the 'M' (message text) field.
1234 if (mptr >= upper_bound) {
1237 field_header = *mptr++;
1238 ret->cm_fields[field_header] = strdup(mptr);
1240 while (*mptr++ != 0); /* advance to next field */
1242 } while ((mptr < upper_bound) && (field_header != 'M'));
1246 /* Always make sure there's something in the msg text field. If
1247 * it's NULL, the message text is most likely stored separately,
1248 * so go ahead and fetch that. Failing that, just set a dummy
1249 * body so other code doesn't barf.
1251 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1252 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1253 if (dmsgtext != NULL) {
1254 ret->cm_fields['M'] = dmsgtext->ptr;
1255 dmsgtext->ptr = NULL;
1259 if (ret->cm_fields['M'] == NULL) {
1260 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1263 /* Perform "before read" hooks (aborting if any return nonzero) */
1264 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1265 CtdlFreeMessage(ret);
1274 * Returns 1 if the supplied pointer points to a valid Citadel message.
1275 * If the pointer is NULL or the magic number check fails, returns 0.
1277 int is_valid_message(struct CtdlMessage *msg) {
1280 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1281 struct CitContext *CCC = CC;
1282 MSGM_syslog(LOG_WARNING, "is_valid_message() -- self-check failed\n");
1288 void CtdlFreeMessageContents(struct CtdlMessage *msg)
1292 for (i = 0; i < 256; ++i)
1293 if (msg->cm_fields[i] != NULL) {
1294 free(msg->cm_fields[i]);
1297 msg->cm_magic = 0; /* just in case */
1300 * 'Destructor' for struct CtdlMessage
1302 void CtdlFreeMessage(struct CtdlMessage *msg)
1304 if (is_valid_message(msg) == 0)
1306 if (msg != NULL) free (msg);
1309 CtdlFreeMessageContents(msg);
1315 * Pre callback function for multipart/alternative
1317 * NOTE: this differs from the standard behavior for a reason. Normally when
1318 * displaying multipart/alternative you want to show the _last_ usable
1319 * format in the message. Here we show the _first_ one, because it's
1320 * usually text/plain. Since this set of functions is designed for text
1321 * output to non-MIME-aware clients, this is the desired behavior.
1324 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1325 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1326 char *cbid, void *cbuserdata)
1328 struct CitContext *CCC = CC;
1331 ma = (struct ma_info *)cbuserdata;
1332 MSG_syslog(LOG_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1333 if (!strcasecmp(cbtype, "multipart/alternative")) {
1337 if (!strcasecmp(cbtype, "message/rfc822")) {
1343 * Post callback function for multipart/alternative
1345 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1346 void *content, char *cbtype, char *cbcharset, size_t length,
1347 char *encoding, char *cbid, void *cbuserdata)
1349 struct CitContext *CCC = CC;
1352 ma = (struct ma_info *)cbuserdata;
1353 MSG_syslog(LOG_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1354 if (!strcasecmp(cbtype, "multipart/alternative")) {
1358 if (!strcasecmp(cbtype, "message/rfc822")) {
1364 * Inline callback function for mime parser that wants to display text
1366 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1367 void *content, char *cbtype, char *cbcharset, size_t length,
1368 char *encoding, char *cbid, void *cbuserdata)
1370 struct CitContext *CCC = CC;
1376 ma = (struct ma_info *)cbuserdata;
1378 MSG_syslog(LOG_DEBUG,
1379 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1380 partnum, filename, cbtype, (long)length);
1383 * If we're in the middle of a multipart/alternative scope and
1384 * we've already printed another section, skip this one.
1386 if ( (ma->is_ma) && (ma->did_print) ) {
1387 MSG_syslog(LOG_DEBUG, "Skipping part %s (%s)\n", partnum, cbtype);
1392 if ( (!strcasecmp(cbtype, "text/plain"))
1393 || (IsEmptyStr(cbtype)) ) {
1396 client_write(wptr, length);
1397 if (wptr[length-1] != '\n') {
1404 if (!strcasecmp(cbtype, "text/html")) {
1405 ptr = html_to_ascii(content, length, 80, 0);
1407 client_write(ptr, wlen);
1408 if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
1415 if (ma->use_fo_hooks) {
1416 if (PerformFixedOutputHooks(cbtype, content, length)) {
1417 /* above function returns nonzero if it handled the part */
1422 if (strncasecmp(cbtype, "multipart/", 10)) {
1423 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1424 partnum, filename, cbtype, (long)length);
1430 * The client is elegant and sophisticated and wants to be choosy about
1431 * MIME content types, so figure out which multipart/alternative part
1432 * we're going to send.
1434 * We use a system of weights. When we find a part that matches one of the
1435 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1436 * and then set ma->chosen_pref to that MIME type's position in our preference
1437 * list. If we then hit another match, we only replace the first match if
1438 * the preference value is lower.
1440 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1441 void *content, char *cbtype, char *cbcharset, size_t length,
1442 char *encoding, char *cbid, void *cbuserdata)
1444 struct CitContext *CCC = CC;
1449 ma = (struct ma_info *)cbuserdata;
1451 // NOTE: REMOVING THIS CONDITIONAL FIXES BUG 220
1452 // http://bugzilla.citadel.org/show_bug.cgi?id=220
1453 // I don't know if there are any side effects! Please TEST TEST TEST
1454 //if (ma->is_ma > 0) {
1456 for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1457 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1458 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1459 if (i < ma->chosen_pref) {
1460 MSG_syslog(LOG_DEBUG, "Setting chosen part: <%s>\n", partnum);
1461 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1462 ma->chosen_pref = i;
1469 * Now that we've chosen our preferred part, output it.
1471 void output_preferred(char *name,
1483 struct CitContext *CCC = CC;
1486 int add_newline = 0;
1489 char *decoded = NULL;
1490 size_t bytes_decoded;
1493 ma = (struct ma_info *)cbuserdata;
1495 /* This is not the MIME part you're looking for... */
1496 if (strcasecmp(partnum, ma->chosen_part)) return;
1498 /* If the content-type of this part is in our preferred formats
1499 * list, we can simply output it verbatim.
1501 for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1502 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1503 if (!strcasecmp(buf, cbtype)) {
1504 /* Yeah! Go! W00t!! */
1505 if (ma->dont_decode == 0)
1506 rc = mime_decode_now (content,
1512 break; /* Give us the chance, maybe theres another one. */
1514 if (rc == 0) text_content = (char *)content;
1516 text_content = decoded;
1517 length = bytes_decoded;
1520 if (text_content[length-1] != '\n') {
1523 cprintf("Content-type: %s", cbtype);
1524 if (!IsEmptyStr(cbcharset)) {
1525 cprintf("; charset=%s", cbcharset);
1527 cprintf("\nContent-length: %d\n",
1528 (int)(length + add_newline) );
1529 if (!IsEmptyStr(encoding)) {
1530 cprintf("Content-transfer-encoding: %s\n", encoding);
1533 cprintf("Content-transfer-encoding: 7bit\n");
1535 cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1537 if (client_write(text_content, length) == -1)
1539 MSGM_syslog(LOG_ERR, "output_preferred(): aborting due to write failure.\n");
1542 if (add_newline) cprintf("\n");
1543 if (decoded != NULL) free(decoded);
1548 /* No translations required or possible: output as text/plain */
1549 cprintf("Content-type: text/plain\n\n");
1551 if (ma->dont_decode == 0)
1552 rc = mime_decode_now (content,
1558 return; /* Give us the chance, maybe theres another one. */
1560 if (rc == 0) text_content = (char *)content;
1562 text_content = decoded;
1563 length = bytes_decoded;
1566 fixed_output(name, filename, partnum, disp, text_content, cbtype, cbcharset,
1567 length, encoding, cbid, cbuserdata);
1568 if (decoded != NULL) free(decoded);
1573 char desired_section[64];
1580 * Callback function for
1582 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1583 void *content, char *cbtype, char *cbcharset, size_t length,
1584 char *encoding, char *cbid, void *cbuserdata)
1586 struct encapmsg *encap;
1588 encap = (struct encapmsg *)cbuserdata;
1590 /* Only proceed if this is the desired section... */
1591 if (!strcasecmp(encap->desired_section, partnum)) {
1592 encap->msglen = length;
1593 encap->msg = malloc(length + 2);
1594 memcpy(encap->msg, content, length);
1601 * Determine whether the specified message exists in the cached_msglist
1602 * (This is a security check)
1604 int check_cached_msglist(long msgnum) {
1605 struct CitContext *CCC = CC;
1607 /* cases in which we skip the check */
1608 if (!CCC) return om_ok; /* not a session */
1609 if (CCC->client_socket <= 0) return om_ok; /* not a client session */
1610 if (CCC->cached_msglist == NULL) return om_access_denied; /* no msglist fetched */
1611 if (CCC->cached_num_msgs == 0) return om_access_denied; /* nothing to check */
1614 /* Do a binary search within the cached_msglist for the requested msgnum */
1616 int max = (CC->cached_num_msgs - 1);
1618 while (max >= min) {
1619 int middle = min + (max-min) / 2 ;
1620 if (msgnum == CCC->cached_msglist[middle]) {
1623 if (msgnum > CC->cached_msglist[middle]) {
1631 return om_access_denied;
1636 * Determine whether the currently logged in session has permission to read
1637 * messages in the current room.
1639 int CtdlDoIHavePermissionToReadMessagesInThisRoom(void) {
1640 if ( (!(CC->logged_in))
1641 && (!(CC->internal_pgm))
1642 && (!config.c_guest_logins)
1644 return(om_not_logged_in);
1651 * Get a message off disk. (returns om_* values found in msgbase.h)
1654 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1655 int mode, /* how would you like that message? */
1656 int headers_only, /* eschew the message body? */
1657 int do_proto, /* do Citadel protocol responses? */
1658 int crlf, /* Use CRLF newlines instead of LF? */
1659 char *section, /* NULL or a message/rfc822 section */
1660 int flags, /* various flags; see msgbase.h */
1664 struct CitContext *CCC = CC;
1665 struct CtdlMessage *TheMessage = NULL;
1666 int retcode = CIT_OK;
1667 struct encapmsg encap;
1670 MSG_syslog(LOG_DEBUG, "CtdlOutputMsg(msgnum=%ld, mode=%d, section=%s)\n",
1672 (section ? section : "<>")
1675 r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
1678 if (r == om_not_logged_in) {
1679 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1682 cprintf("%d An unknown error has occurred.\n", ERROR);
1689 * Check to make sure the message is actually IN this room
1691 r = check_cached_msglist(msg_num);
1692 if (r == om_access_denied) {
1693 /* Not in the cache? We get ONE shot to check it again. */
1694 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
1695 r = check_cached_msglist(msg_num);
1698 MSG_syslog(LOG_DEBUG, "Security check fail: message %ld is not in %s\n",
1699 msg_num, CCC->room.QRname
1702 if (r == om_access_denied) {
1703 cprintf("%d message %ld was not found in this room\n",
1704 ERROR + HIGHER_ACCESS_REQUIRED,
1713 * Fetch the message from disk. If we're in HEADERS_FAST mode,
1714 * request that we don't even bother loading the body into memory.
1716 if (headers_only == HEADERS_FAST) {
1717 TheMessage = CtdlFetchMessage(msg_num, 0);
1720 TheMessage = CtdlFetchMessage(msg_num, 1);
1723 if (TheMessage == NULL) {
1724 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1725 ERROR + MESSAGE_NOT_FOUND, msg_num);
1726 return(om_no_such_msg);
1729 /* Here is the weird form of this command, to process only an
1730 * encapsulated message/rfc822 section.
1732 if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1733 memset(&encap, 0, sizeof encap);
1734 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1735 mime_parser(TheMessage->cm_fields['M'],
1737 *extract_encapsulated_message,
1738 NULL, NULL, (void *)&encap, 0
1741 if ((Author != NULL) && (*Author == NULL))
1743 *Author = TheMessage->cm_fields['A'];
1744 TheMessage->cm_fields['A'] = NULL;
1746 if ((Address != NULL) && (*Address == NULL))
1748 *Address = TheMessage->cm_fields['F'];
1749 TheMessage->cm_fields['F'] = NULL;
1751 CtdlFreeMessage(TheMessage);
1755 encap.msg[encap.msglen] = 0;
1756 TheMessage = convert_internet_message(encap.msg);
1757 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1759 /* Now we let it fall through to the bottom of this
1760 * function, because TheMessage now contains the
1761 * encapsulated message instead of the top-level
1762 * message. Isn't that neat?
1768 cprintf("%d msg %ld has no part %s\n",
1769 ERROR + MESSAGE_NOT_FOUND,
1773 retcode = om_no_such_msg;
1778 /* Ok, output the message now */
1779 if (retcode == CIT_OK)
1780 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
1781 if ((Author != NULL) && (*Author == NULL))
1783 *Author = TheMessage->cm_fields['A'];
1784 TheMessage->cm_fields['A'] = NULL;
1786 if ((Address != NULL) && (*Address == NULL))
1788 *Address = TheMessage->cm_fields['F'];
1789 TheMessage->cm_fields['F'] = NULL;
1792 CtdlFreeMessage(TheMessage);
1798 char *qp_encode_email_addrs(char *source)
1800 struct CitContext *CCC = CC;
1801 char *user, *node, *name;
1802 const char headerStr[] = "=?UTF-8?Q?";
1806 int need_to_encode = 0;
1812 long nAddrPtrMax = 50;
1817 if (source == NULL) return source;
1818 if (IsEmptyStr(source)) return source;
1819 if (MessageDebugEnabled != 0) cit_backtrace();
1820 MSG_syslog(LOG_DEBUG, "qp_encode_email_addrs: [%s]\n", source);
1822 AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
1823 AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
1824 memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
1827 while (!IsEmptyStr (&source[i])) {
1828 if (nColons >= nAddrPtrMax){
1831 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1832 memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
1833 free (AddrPtr), AddrPtr = ptr;
1835 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1836 memset(&ptr[nAddrPtrMax], 0,
1837 sizeof (long) * nAddrPtrMax);
1839 memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
1840 free (AddrUtf8), AddrUtf8 = ptr;
1843 if (((unsigned char) source[i] < 32) ||
1844 ((unsigned char) source[i] > 126)) {
1846 AddrUtf8[nColons] = 1;
1848 if (source[i] == '"')
1849 InQuotes = !InQuotes;
1850 if (!InQuotes && source[i] == ',') {
1851 AddrPtr[nColons] = i;
1856 if (need_to_encode == 0) {
1863 EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
1864 Encoded = (char*) malloc (EncodedMaxLen);
1866 for (i = 0; i < nColons; i++)
1867 source[AddrPtr[i]++] = '\0';
1868 /* TODO: if libidn, this might get larger*/
1869 user = malloc(SourceLen + 1);
1870 node = malloc(SourceLen + 1);
1871 name = malloc(SourceLen + 1);
1875 for (i = 0; i < nColons && nPtr != NULL; i++) {
1876 nmax = EncodedMaxLen - (nPtr - Encoded);
1878 process_rfc822_addr(&source[AddrPtr[i]],
1882 /* TODO: libIDN here ! */
1883 if (IsEmptyStr(name)) {
1884 n = snprintf(nPtr, nmax,
1885 (i==0)?"%s@%s" : ",%s@%s",
1889 EncodedName = rfc2047encode(name, strlen(name));
1890 n = snprintf(nPtr, nmax,
1891 (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
1892 EncodedName, user, node);
1897 n = snprintf(nPtr, nmax,
1898 (i==0)?"%s" : ",%s",
1899 &source[AddrPtr[i]]);
1905 ptr = (char*) malloc(EncodedMaxLen * 2);
1906 memcpy(ptr, Encoded, EncodedMaxLen);
1907 nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
1908 free(Encoded), Encoded = ptr;
1910 i--; /* do it once more with properly lengthened buffer */
1913 for (i = 0; i < nColons; i++)
1914 source[--AddrPtr[i]] = ',';
1925 /* If the last item in a list of recipients was truncated to a partial address,
1926 * remove it completely in order to avoid choking libSieve
1928 void sanitize_truncated_recipient(char *str)
1931 if (num_tokens(str, ',') < 2) return;
1933 int len = strlen(str);
1934 if (len < 900) return;
1935 if (len > 998) str[998] = 0;
1937 char *cptr = strrchr(str, ',');
1940 char *lptr = strchr(cptr, '<');
1941 char *rptr = strchr(cptr, '>');
1943 if ( (lptr) && (rptr) && (rptr > lptr) ) return;
1949 void OutputCtdlMsgHeaders(
1950 struct CtdlMessage *TheMessage,
1951 int do_proto) /* do Citadel protocol responses? */
1957 char display_name[256];
1959 /* begin header processing loop for Citadel message format */
1960 safestrncpy(display_name, "<unknown>", sizeof display_name);
1961 if (TheMessage->cm_fields['A']) {
1962 strcpy(buf, TheMessage->cm_fields['A']);
1963 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1964 safestrncpy(display_name, "****", sizeof display_name);
1966 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1967 safestrncpy(display_name, "anonymous", sizeof display_name);
1970 safestrncpy(display_name, buf, sizeof display_name);
1972 if ((is_room_aide())
1973 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1974 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1975 size_t tmp = strlen(display_name);
1976 snprintf(&display_name[tmp],
1977 sizeof display_name - tmp,
1982 /* Don't show Internet address for users on the
1983 * local Citadel network.
1986 if (TheMessage->cm_fields['N'] != NULL)
1987 if (!IsEmptyStr(TheMessage->cm_fields['N']))
1988 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1992 /* Now spew the header fields in the order we like them. */
1993 n = safestrncpy(allkeys, FORDER, sizeof allkeys);
1994 for (i=0; i<n; ++i) {
1995 k = (int) allkeys[i];
1997 if ( (TheMessage->cm_fields[k] != NULL)
1998 && (msgkeys[k] != NULL) ) {
1999 if ((k == 'V') || (k == 'R') || (k == 'Y')) {
2000 sanitize_truncated_recipient(TheMessage->cm_fields[k]);
2003 if (do_proto) cprintf("%s=%s\n",
2007 else if ((k == 'F') && (suppress_f)) {
2010 /* Masquerade display name if needed */
2012 if (do_proto) cprintf("%s=%s\n",
2014 TheMessage->cm_fields[k]
2023 void OutputRFC822MsgHeaders(
2024 struct CtdlMessage *TheMessage,
2025 int flags, /* should the bessage be exported clean */
2027 char *mid, long sizeof_mid,
2028 char *suser, long sizeof_suser,
2029 char *luser, long sizeof_luser,
2030 char *fuser, long sizeof_fuser,
2031 char *snode, long sizeof_snode)
2033 char datestamp[100];
2034 int subject_found = 0;
2041 for (i = 0; i < 256; ++i) {
2042 if (TheMessage->cm_fields[i]) {
2043 mptr = mpptr = TheMessage->cm_fields[i];
2046 safestrncpy(luser, mptr, sizeof_luser);
2047 safestrncpy(suser, mptr, sizeof_suser);
2049 else if (i == 'Y') {
2050 if ((flags & QP_EADDR) != 0) {
2051 mptr = qp_encode_email_addrs(mptr);
2053 sanitize_truncated_recipient(mptr);
2054 cprintf("CC: %s%s", mptr, nl);
2056 else if (i == 'P') {
2057 cprintf("Return-Path: %s%s", mptr, nl);
2059 else if (i == 'L') {
2060 cprintf("List-ID: %s%s", mptr, nl);
2062 else if (i == 'V') {
2063 if ((flags & QP_EADDR) != 0)
2064 mptr = qp_encode_email_addrs(mptr);
2066 while ((*hptr != '\0') && isspace(*hptr))
2068 if (!IsEmptyStr(hptr))
2069 cprintf("Envelope-To: %s%s", hptr, nl);
2071 else if (i == 'U') {
2072 cprintf("Subject: %s%s", mptr, nl);
2076 safestrncpy(mid, mptr, sizeof_mid); /// TODO: detect @ here and copy @nodename in if not found.
2078 safestrncpy(fuser, mptr, sizeof_fuser);
2079 /* else if (i == 'O')
2080 cprintf("X-Citadel-Room: %s%s",
2083 safestrncpy(snode, mptr, sizeof_snode);
2086 if (haschar(mptr, '@') == 0)
2088 sanitize_truncated_recipient(mptr);
2089 cprintf("To: %s@%s", mptr, config.c_fqdn);
2094 if ((flags & QP_EADDR) != 0) {
2095 mptr = qp_encode_email_addrs(mptr);
2097 sanitize_truncated_recipient(mptr);
2098 cprintf("To: %s", mptr);
2102 else if (i == 'T') {
2103 datestring(datestamp, sizeof datestamp,
2104 atol(mptr), DATESTRING_RFC822);
2105 cprintf("Date: %s%s", datestamp, nl);
2107 else if (i == 'W') {
2108 cprintf("References: ");
2109 k = num_tokens(mptr, '|');
2110 for (j=0; j<k; ++j) {
2111 extract_token(buf, mptr, j, '|', sizeof buf);
2112 cprintf("<%s>", buf);
2121 else if (i == 'K') {
2123 while ((*hptr != '\0') && isspace(*hptr))
2125 if (!IsEmptyStr(hptr))
2126 cprintf("Reply-To: %s%s", mptr, nl);
2132 if (subject_found == 0) {
2133 cprintf("Subject: (no subject)%s", nl);
2138 void Dump_RFC822HeadersBody(
2139 struct CtdlMessage *TheMessage,
2140 int headers_only, /* eschew the message body? */
2141 int flags, /* should the bessage be exported clean? */
2145 cit_uint8_t prev_ch;
2147 const char *StartOfText = StrBufNOTNULL;
2150 int nllen = strlen(nl);
2153 mptr = TheMessage->cm_fields['M'];
2157 while (*mptr != '\0') {
2158 if (*mptr == '\r') {
2165 eoh = (*(mptr+1) == '\r') && (*(mptr+2) == '\n');
2167 eoh = *(mptr+1) == '\n';
2171 StartOfText = strchr(StartOfText, '\n');
2172 StartOfText = strchr(StartOfText, '\n');
2175 if (((headers_only == HEADERS_NONE) && (mptr >= StartOfText)) ||
2176 ((headers_only == HEADERS_ONLY) && (mptr < StartOfText)) ||
2177 ((headers_only != HEADERS_NONE) &&
2178 (headers_only != HEADERS_ONLY))
2180 if (*mptr == '\n') {
2181 memcpy(&outbuf[outlen], nl, nllen);
2183 outbuf[outlen] = '\0';
2186 outbuf[outlen++] = *mptr;
2190 if (flags & ESC_DOT)
2192 if ((prev_ch == '\n') &&
2194 ((*(mptr+1) == '\r') || (*(mptr+1) == '\n')))
2196 outbuf[outlen++] = '.';
2201 if (outlen > 1000) {
2202 if (client_write(outbuf, outlen) == -1)
2204 struct CitContext *CCC = CC;
2205 MSGM_syslog(LOG_ERR, "Dump_RFC822HeadersBody(): aborting due to write failure.\n");
2212 client_write(outbuf, outlen);
2218 /* If the format type on disk is 1 (fixed-format), then we want
2219 * everything to be output completely literally ... regardless of
2220 * what message transfer format is in use.
2222 void DumpFormatFixed(
2223 struct CtdlMessage *TheMessage,
2224 int mode, /* how would you like that message? */
2231 int nllen = strlen (nl);
2234 mptr = TheMessage->cm_fields['M'];
2236 if (mode == MT_MIME) {
2237 cprintf("Content-type: text/plain\n\n");
2241 while (ch = *mptr++, ch > 0) {
2245 if ((buflen > 250) && (!xlline)){
2249 while ((buflen > 0) &&
2250 (!isspace(buf[buflen])))
2256 mptr -= tbuflen - buflen;
2261 /* if we reach the outer bounds of our buffer,
2262 abort without respect what whe purge. */
2265 (buflen > SIZ - nllen - 2)))
2269 memcpy (&buf[buflen], nl, nllen);
2273 if (client_write(buf, buflen) == -1)
2275 struct CitContext *CCC = CC;
2276 MSGM_syslog(LOG_ERR, "DumpFormatFixed(): aborting due to write failure.\n");
2288 if (!IsEmptyStr(buf))
2289 cprintf("%s%s", buf, nl);
2293 * Get a message off disk. (returns om_* values found in msgbase.h)
2295 int CtdlOutputPreLoadedMsg(
2296 struct CtdlMessage *TheMessage,
2297 int mode, /* how would you like that message? */
2298 int headers_only, /* eschew the message body? */
2299 int do_proto, /* do Citadel protocol responses? */
2300 int crlf, /* Use CRLF newlines instead of LF? */
2301 int flags /* should the bessage be exported clean? */
2303 struct CitContext *CCC = CC;
2306 const char *nl; /* newline string */
2309 /* Buffers needed for RFC822 translation. These are all filled
2310 * using functions that are bounds-checked, and therefore we can
2311 * make them substantially smaller than SIZ.
2319 MSG_syslog(LOG_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
2320 ((TheMessage == NULL) ? "NULL" : "not null"),
2321 mode, headers_only, do_proto, crlf);
2323 strcpy(mid, "unknown");
2324 nl = (crlf ? "\r\n" : "\n");
2326 if (!is_valid_message(TheMessage)) {
2327 MSGM_syslog(LOG_ERR,
2328 "ERROR: invalid preloaded message for output\n");
2330 return(om_no_such_msg);
2333 /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2334 * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2336 if ( (flags & SUPPRESS_ENV_TO) && (TheMessage->cm_fields['V'] != NULL) ) {
2337 memset(TheMessage->cm_fields['V'], ' ', strlen(TheMessage->cm_fields['V']));
2340 /* Are we downloading a MIME component? */
2341 if (mode == MT_DOWNLOAD) {
2342 if (TheMessage->cm_format_type != FMT_RFC822) {
2344 cprintf("%d This is not a MIME message.\n",
2345 ERROR + ILLEGAL_VALUE);
2346 } else if (CCC->download_fp != NULL) {
2347 if (do_proto) cprintf(
2348 "%d You already have a download open.\n",
2349 ERROR + RESOURCE_BUSY);
2351 /* Parse the message text component */
2352 mptr = TheMessage->cm_fields['M'];
2353 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
2354 /* If there's no file open by this time, the requested
2355 * section wasn't found, so print an error
2357 if (CCC->download_fp == NULL) {
2358 if (do_proto) cprintf(
2359 "%d Section %s not found.\n",
2360 ERROR + FILE_NOT_FOUND,
2361 CCC->download_desired_section);
2364 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2367 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2368 * in a single server operation instead of opening a download file.
2370 if (mode == MT_SPEW_SECTION) {
2371 if (TheMessage->cm_format_type != FMT_RFC822) {
2373 cprintf("%d This is not a MIME message.\n",
2374 ERROR + ILLEGAL_VALUE);
2376 /* Parse the message text component */
2379 mptr = TheMessage->cm_fields['M'];
2380 mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2381 /* If section wasn't found, print an error
2384 if (do_proto) cprintf(
2385 "%d Section %s not found.\n",
2386 ERROR + FILE_NOT_FOUND,
2387 CCC->download_desired_section);
2390 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2393 /* now for the user-mode message reading loops */
2394 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2396 /* Does the caller want to skip the headers? */
2397 if (headers_only == HEADERS_NONE) goto START_TEXT;
2399 /* Tell the client which format type we're using. */
2400 if ( (mode == MT_CITADEL) && (do_proto) ) {
2401 cprintf("type=%d\n", TheMessage->cm_format_type);
2404 /* nhdr=yes means that we're only displaying headers, no body */
2405 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2406 && ((mode == MT_CITADEL) || (mode == MT_MIME))
2409 cprintf("nhdr=yes\n");
2412 if ((mode == MT_CITADEL) || (mode == MT_MIME))
2413 OutputCtdlMsgHeaders(TheMessage, do_proto);
2416 /* begin header processing loop for RFC822 transfer format */
2420 strcpy(snode, NODENAME);
2421 if (mode == MT_RFC822)
2422 OutputRFC822MsgHeaders(
2427 suser, sizeof(suser),
2428 luser, sizeof(luser),
2429 fuser, sizeof(fuser),
2430 snode, sizeof(snode)
2434 for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2435 suser[i] = tolower(suser[i]);
2436 if (!isalnum(suser[i])) suser[i]='_';
2439 if (mode == MT_RFC822) {
2440 if (!strcasecmp(snode, NODENAME)) {
2441 safestrncpy(snode, FQDN, sizeof snode);
2444 /* Construct a fun message id */
2445 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
2446 if (strchr(mid, '@')==NULL) {
2447 cprintf("@%s", snode);
2451 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2452 cprintf("From: \"----\" <x@x.org>%s", nl);
2454 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2455 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2457 else if (!IsEmptyStr(fuser)) {
2458 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2461 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2464 /* Blank line signifying RFC822 end-of-headers */
2465 if (TheMessage->cm_format_type != FMT_RFC822) {
2470 /* end header processing loop ... at this point, we're in the text */
2472 if (headers_only == HEADERS_FAST) goto DONE;
2474 /* Tell the client about the MIME parts in this message */
2475 if (TheMessage->cm_format_type == FMT_RFC822) {
2476 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2477 mptr = TheMessage->cm_fields['M'];
2478 memset(&ma, 0, sizeof(struct ma_info));
2479 mime_parser(mptr, NULL,
2480 (do_proto ? *list_this_part : NULL),
2481 (do_proto ? *list_this_pref : NULL),
2482 (do_proto ? *list_this_suff : NULL),
2485 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
2486 Dump_RFC822HeadersBody(
2495 if (headers_only == HEADERS_ONLY) {
2499 /* signify start of msg text */
2500 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2501 if (do_proto) cprintf("text\n");
2504 if (TheMessage->cm_format_type == FMT_FIXED)
2507 mode, /* how would you like that message? */
2510 /* If the message on disk is format 0 (Citadel vari-format), we
2511 * output using the formatter at 80 columns. This is the final output
2512 * form if the transfer format is RFC822, but if the transfer format
2513 * is Citadel proprietary, it'll still work, because the indentation
2514 * for new paragraphs is correct and the client will reformat the
2515 * message to the reader's screen width.
2517 if (TheMessage->cm_format_type == FMT_CITADEL) {
2518 mptr = TheMessage->cm_fields['M'];
2520 if (mode == MT_MIME) {
2521 cprintf("Content-type: text/x-citadel-variformat\n\n");
2526 /* If the message on disk is format 4 (MIME), we've gotta hand it
2527 * off to the MIME parser. The client has already been told that
2528 * this message is format 1 (fixed format), so the callback function
2529 * we use will display those parts as-is.
2531 if (TheMessage->cm_format_type == FMT_RFC822) {
2532 memset(&ma, 0, sizeof(struct ma_info));
2534 if (mode == MT_MIME) {
2535 ma.use_fo_hooks = 0;
2536 strcpy(ma.chosen_part, "1");
2537 ma.chosen_pref = 9999;
2538 ma.dont_decode = CCC->msg4_dont_decode;
2539 mime_parser(mptr, NULL,
2540 *choose_preferred, *fixed_output_pre,
2541 *fixed_output_post, (void *)&ma, 1);
2542 mime_parser(mptr, NULL,
2543 *output_preferred, NULL, NULL, (void *)&ma, 1);
2546 ma.use_fo_hooks = 1;
2547 mime_parser(mptr, NULL,
2548 *fixed_output, *fixed_output_pre,
2549 *fixed_output_post, (void *)&ma, 0);
2554 DONE: /* now we're done */
2555 if (do_proto) cprintf("000\n");
2561 * display a message (mode 0 - Citadel proprietary)
2563 void cmd_msg0(char *cmdbuf)
2566 int headers_only = HEADERS_ALL;
2568 msgid = extract_long(cmdbuf, 0);
2569 headers_only = extract_int(cmdbuf, 1);
2571 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL, 0, NULL, NULL);
2577 * display a message (mode 2 - RFC822)
2579 void cmd_msg2(char *cmdbuf)
2582 int headers_only = HEADERS_ALL;
2584 msgid = extract_long(cmdbuf, 0);
2585 headers_only = extract_int(cmdbuf, 1);
2587 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL, 0, NULL, NULL);
2593 * display a message (mode 3 - IGnet raw format - internal programs only)
2595 void cmd_msg3(char *cmdbuf)
2598 struct CtdlMessage *msg = NULL;
2601 if (CC->internal_pgm == 0) {
2602 cprintf("%d This command is for internal programs only.\n",
2603 ERROR + HIGHER_ACCESS_REQUIRED);
2607 msgnum = extract_long(cmdbuf, 0);
2608 msg = CtdlFetchMessage(msgnum, 1);
2610 cprintf("%d Message %ld not found.\n",
2611 ERROR + MESSAGE_NOT_FOUND, msgnum);
2615 serialize_message(&smr, msg);
2616 CtdlFreeMessage(msg);
2619 cprintf("%d Unable to serialize message\n",
2620 ERROR + INTERNAL_ERROR);
2624 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
2625 client_write((char *)smr.ser, (int)smr.len);
2632 * Display a message using MIME content types
2634 void cmd_msg4(char *cmdbuf)
2639 msgid = extract_long(cmdbuf, 0);
2640 extract_token(section, cmdbuf, 1, '|', sizeof section);
2641 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) , 0, NULL, NULL);
2647 * Client tells us its preferred message format(s)
2649 void cmd_msgp(char *cmdbuf)
2651 if (!strcasecmp(cmdbuf, "dont_decode")) {
2652 CC->msg4_dont_decode = 1;
2653 cprintf("%d MSG4 will not pre-decode messages.\n", CIT_OK);
2656 safestrncpy(CC->preferred_formats, cmdbuf, sizeof(CC->preferred_formats));
2657 cprintf("%d Preferred MIME formats have been set.\n", CIT_OK);
2663 * Open a component of a MIME message as a download file
2665 void cmd_opna(char *cmdbuf)
2668 char desired_section[128];
2670 msgid = extract_long(cmdbuf, 0);
2671 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2672 safestrncpy(CC->download_desired_section, desired_section,
2673 sizeof CC->download_desired_section);
2674 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL, 0, NULL, NULL);
2679 * Open a component of a MIME message and transmit it all at once
2681 void cmd_dlat(char *cmdbuf)
2684 char desired_section[128];
2686 msgid = extract_long(cmdbuf, 0);
2687 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2688 safestrncpy(CC->download_desired_section, desired_section,
2689 sizeof CC->download_desired_section);
2690 CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL, 0, NULL, NULL);
2695 * Save one or more message pointers into a specified room
2696 * (Returns 0 for success, nonzero for failure)
2697 * roomname may be NULL to use the current room
2699 * Note that the 'supplied_msg' field may be set to NULL, in which case
2700 * the message will be fetched from disk, by number, if we need to perform
2701 * replication checks. This adds an additional database read, so if the
2702 * caller already has the message in memory then it should be supplied. (Obviously
2703 * this mode of operation only works if we're saving a single message.)
2705 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2706 int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2708 struct CitContext *CCC = CC;
2710 char hold_rm[ROOMNAMELEN];
2711 struct cdbdata *cdbfr;
2714 long highest_msg = 0L;
2717 struct CtdlMessage *msg = NULL;
2719 long *msgs_to_be_merged = NULL;
2720 int num_msgs_to_be_merged = 0;
2722 MSG_syslog(LOG_DEBUG,
2723 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)\n",
2724 roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2727 strcpy(hold_rm, CCC->room.QRname);
2730 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2731 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2732 if (num_newmsgs > 1) supplied_msg = NULL;
2734 /* Now the regular stuff */
2735 if (CtdlGetRoomLock(&CCC->room,
2736 ((roomname != NULL) ? roomname : CCC->room.QRname) )
2738 MSG_syslog(LOG_ERR, "No such room <%s>\n", roomname);
2739 return(ERROR + ROOM_NOT_FOUND);
2743 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2744 num_msgs_to_be_merged = 0;
2747 cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
2748 if (cdbfr == NULL) {
2752 msglist = (long *) cdbfr->ptr;
2753 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2754 num_msgs = cdbfr->len / sizeof(long);
2759 /* Create a list of msgid's which were supplied by the caller, but do
2760 * not already exist in the target room. It is absolutely taboo to
2761 * have more than one reference to the same message in a room.
2763 for (i=0; i<num_newmsgs; ++i) {
2765 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2766 if (msglist[j] == newmsgidlist[i]) {
2771 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2775 MSG_syslog(LOG_DEBUG, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2778 * Now merge the new messages
2780 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2781 if (msglist == NULL) {
2782 MSGM_syslog(LOG_ALERT, "ERROR: can't realloc message list!\n");
2783 free(msgs_to_be_merged);
2784 return (ERROR + INTERNAL_ERROR);
2786 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2787 num_msgs += num_msgs_to_be_merged;
2789 /* Sort the message list, so all the msgid's are in order */
2790 num_msgs = sort_msglist(msglist, num_msgs);
2792 /* Determine the highest message number */
2793 highest_msg = msglist[num_msgs - 1];
2795 /* Write it back to disk. */
2796 cdb_store(CDB_MSGLISTS, &CCC->room.QRnumber, (int)sizeof(long),
2797 msglist, (int)(num_msgs * sizeof(long)));
2799 /* Free up the memory we used. */
2802 /* Update the highest-message pointer and unlock the room. */
2803 CCC->room.QRhighest = highest_msg;
2804 CtdlPutRoomLock(&CCC->room);
2806 /* Perform replication checks if necessary */
2807 if ( (DoesThisRoomNeedEuidIndexing(&CCC->room)) && (do_repl_check) ) {
2808 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2810 for (i=0; i<num_msgs_to_be_merged; ++i) {
2811 msgid = msgs_to_be_merged[i];
2813 if (supplied_msg != NULL) {
2817 msg = CtdlFetchMessage(msgid, 0);
2821 ReplicationChecks(msg);
2823 /* If the message has an Exclusive ID, index that... */
2824 if (msg->cm_fields['E'] != NULL) {
2825 index_message_by_euid(msg->cm_fields['E'], &CCC->room, msgid);
2828 /* Free up the memory we may have allocated */
2829 if (msg != supplied_msg) {
2830 CtdlFreeMessage(msg);
2838 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2841 /* Submit this room for processing by hooks */
2842 PerformRoomHooks(&CCC->room);
2844 /* Go back to the room we were in before we wandered here... */
2845 CtdlGetRoom(&CCC->room, hold_rm);
2847 /* Bump the reference count for all messages which were merged */
2848 if (!suppress_refcount_adj) {
2849 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
2852 /* Free up memory... */
2853 if (msgs_to_be_merged != NULL) {
2854 free(msgs_to_be_merged);
2857 /* Return success. */
2863 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2866 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2867 int do_repl_check, struct CtdlMessage *supplied_msg)
2869 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
2876 * Message base operation to save a new message to the message store
2877 * (returns new message number)
2879 * This is the back end for CtdlSubmitMsg() and should not be directly
2880 * called by server-side modules.
2883 long send_message(struct CtdlMessage *msg) {
2884 struct CitContext *CCC = CC;
2892 /* Get a new message number */
2893 newmsgid = get_new_message_number();
2894 snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
2895 (long unsigned int) time(NULL),
2896 (long unsigned int) newmsgid,
2900 /* Generate an ID if we don't have one already */
2901 if (msg->cm_fields['I']==NULL) {
2902 msg->cm_fields['I'] = strdup(msgidbuf);
2905 /* If the message is big, set its body aside for storage elsewhere */
2906 if (msg->cm_fields['M'] != NULL) {
2907 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2909 holdM = msg->cm_fields['M'];
2910 msg->cm_fields['M'] = NULL;
2914 /* Serialize our data structure for storage in the database */
2915 serialize_message(&smr, msg);
2918 msg->cm_fields['M'] = holdM;
2922 cprintf("%d Unable to serialize message\n",
2923 ERROR + INTERNAL_ERROR);
2927 /* Write our little bundle of joy into the message base */
2928 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2929 smr.ser, smr.len) < 0) {
2930 MSGM_syslog(LOG_ERR, "Can't store message\n");
2934 cdb_store(CDB_BIGMSGS,
2944 /* Free the memory we used for the serialized message */
2947 /* Return the *local* message ID to the caller
2948 * (even if we're storing an incoming network message)
2956 * Serialize a struct CtdlMessage into the format used on disk and network.
2958 * This function loads up a "struct ser_ret" (defined in server.h) which
2959 * contains the length of the serialized message and a pointer to the
2960 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2962 void serialize_message(struct ser_ret *ret, /* return values */
2963 struct CtdlMessage *msg) /* unserialized msg */
2965 struct CitContext *CCC = CC;
2966 size_t wlen, fieldlen;
2968 static char *forder = FORDER;
2971 * Check for valid message format
2973 if (is_valid_message(msg) == 0) {
2974 MSGM_syslog(LOG_ERR, "serialize_message() aborting due to invalid message\n");
2981 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2982 ret->len = ret->len +
2983 strlen(msg->cm_fields[(int)forder[i]]) + 2;
2985 ret->ser = malloc(ret->len);
2986 if (ret->ser == NULL) {
2987 MSG_syslog(LOG_ERR, "serialize_message() malloc(%ld) failed: %s\n",
2988 (long)ret->len, strerror(errno));
2995 ret->ser[1] = msg->cm_anon_type;
2996 ret->ser[2] = msg->cm_format_type;
2999 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
3000 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
3001 ret->ser[wlen++] = (char)forder[i];
3002 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
3003 wlen = wlen + fieldlen + 1;
3005 if (ret->len != wlen) {
3006 MSG_syslog(LOG_ERR, "ERROR: len=%ld wlen=%ld\n",
3007 (long)ret->len, (long)wlen);
3015 * Check to see if any messages already exist in the current room which
3016 * carry the same Exclusive ID as this one. If any are found, delete them.
3018 void ReplicationChecks(struct CtdlMessage *msg) {
3019 struct CitContext *CCC = CC;
3020 long old_msgnum = (-1L);
3022 if (DoesThisRoomNeedEuidIndexing(&CCC->room) == 0) return;
3024 MSG_syslog(LOG_DEBUG, "Performing replication checks in <%s>\n",
3027 /* No exclusive id? Don't do anything. */
3028 if (msg == NULL) return;
3029 if (msg->cm_fields['E'] == NULL) return;
3030 if (IsEmptyStr(msg->cm_fields['E'])) return;
3031 /*MSG_syslog(LOG_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
3032 msg->cm_fields['E'], CCC->room.QRname);*/
3034 old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields['E'], &CCC->room);
3035 if (old_msgnum > 0L) {
3036 MSG_syslog(LOG_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
3037 CtdlDeleteMessages(CCC->room.QRname, &old_msgnum, 1, "");
3044 * Save a message to disk and submit it into the delivery system.
3046 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
3047 struct recptypes *recps, /* recipients (if mail) */
3048 const char *force, /* force a particular room? */
3049 int flags /* should the message be exported clean? */
3052 char submit_filename[128];
3053 char generated_timestamp[32];
3054 char hold_rm[ROOMNAMELEN];
3055 char actual_rm[ROOMNAMELEN];
3056 char force_room[ROOMNAMELEN];
3057 char content_type[SIZ]; /* We have to learn this */
3058 char recipient[SIZ];
3061 const char *mptr = NULL;
3062 struct ctdluser userbuf;
3064 struct MetaData smi;
3065 FILE *network_fp = NULL;
3066 static int seqnum = 1;
3067 struct CtdlMessage *imsg = NULL;
3069 size_t instr_alloc = 0;
3071 char *hold_R, *hold_D;
3072 char *collected_addresses = NULL;
3073 struct addresses_to_be_filed *aptr = NULL;
3074 StrBuf *saved_rfc822_version = NULL;
3075 int qualified_for_journaling = 0;
3076 CitContext *CCC = MyContext();
3077 char bounce_to[1024] = "";
3080 MSGM_syslog(LOG_DEBUG, "CtdlSubmitMsg() called\n");
3081 if (is_valid_message(msg) == 0) return(-1); /* self check */
3083 /* If this message has no timestamp, we take the liberty of
3084 * giving it one, right now.
3086 if (msg->cm_fields['T'] == NULL) {
3087 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
3088 msg->cm_fields['T'] = strdup(generated_timestamp);
3091 /* If this message has no path, we generate one.
3093 if (msg->cm_fields['P'] == NULL) {
3094 if (msg->cm_fields['A'] != NULL) {
3095 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
3096 for (a=0; !IsEmptyStr(&msg->cm_fields['P'][a]); ++a) {
3097 if (isspace(msg->cm_fields['P'][a])) {
3098 msg->cm_fields['P'][a] = ' ';
3103 msg->cm_fields['P'] = strdup("unknown");
3107 if (force == NULL) {
3108 strcpy(force_room, "");
3111 strcpy(force_room, force);
3114 /* Learn about what's inside, because it's what's inside that counts */
3115 if (msg->cm_fields['M'] == NULL) {
3116 MSGM_syslog(LOG_ERR, "ERROR: attempt to save message with NULL body\n");
3120 switch (msg->cm_format_type) {
3122 strcpy(content_type, "text/x-citadel-variformat");
3125 strcpy(content_type, "text/plain");
3128 strcpy(content_type, "text/plain");
3129 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type:");
3132 safestrncpy(content_type, &mptr[13], sizeof content_type);
3133 striplt(content_type);
3134 aptr = content_type;
3135 while (!IsEmptyStr(aptr)) {
3147 /* Goto the correct room */
3148 room = (recps) ? CCC->room.QRname : SENTITEMS;
3149 MSG_syslog(LOG_DEBUG, "Selected room %s\n", room);
3150 strcpy(hold_rm, CCC->room.QRname);
3151 strcpy(actual_rm, CCC->room.QRname);
3152 if (recps != NULL) {
3153 strcpy(actual_rm, SENTITEMS);
3156 /* If the user is a twit, move to the twit room for posting */
3158 if (CCC->user.axlevel == AxProbU) {
3159 strcpy(hold_rm, actual_rm);
3160 strcpy(actual_rm, config.c_twitroom);
3161 MSGM_syslog(LOG_DEBUG, "Diverting to twit room\n");
3165 /* ...or if this message is destined for Aide> then go there. */
3166 if (!IsEmptyStr(force_room)) {
3167 strcpy(actual_rm, force_room);
3170 MSG_syslog(LOG_INFO, "Final selection: %s (%s)\n", actual_rm, room);
3171 if (strcasecmp(actual_rm, CCC->room.QRname)) {
3172 /* CtdlGetRoom(&CCC->room, actual_rm); */
3173 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL);
3177 * If this message has no O (room) field, generate one.
3179 if (msg->cm_fields['O'] == NULL) {
3180 msg->cm_fields['O'] = strdup(CCC->room.QRname);
3183 /* Perform "before save" hooks (aborting if any return nonzero) */
3184 MSGM_syslog(LOG_DEBUG, "Performing before-save hooks\n");
3185 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
3188 * If this message has an Exclusive ID, and the room is replication
3189 * checking enabled, then do replication checks.
3191 if (DoesThisRoomNeedEuidIndexing(&CCC->room)) {
3192 ReplicationChecks(msg);
3195 /* Save it to disk */
3196 MSGM_syslog(LOG_DEBUG, "Saving to disk\n");
3197 newmsgid = send_message(msg);
3198 if (newmsgid <= 0L) return(-5);
3200 /* Write a supplemental message info record. This doesn't have to
3201 * be a critical section because nobody else knows about this message
3204 MSGM_syslog(LOG_DEBUG, "Creating MetaData record\n");
3205 memset(&smi, 0, sizeof(struct MetaData));
3206 smi.meta_msgnum = newmsgid;
3207 smi.meta_refcount = 0;
3208 safestrncpy(smi.meta_content_type, content_type,
3209 sizeof smi.meta_content_type);
3212 * Measure how big this message will be when rendered as RFC822.
3213 * We do this for two reasons:
3214 * 1. We need the RFC822 length for the new metadata record, so the
3215 * POP and IMAP services don't have to calculate message lengths
3216 * while the user is waiting (multiplied by potentially hundreds
3217 * or thousands of messages).
3218 * 2. If journaling is enabled, we will need an RFC822 version of the
3219 * message to attach to the journalized copy.
3221 if (CCC->redirect_buffer != NULL) {
3222 MSGM_syslog(LOG_ALERT, "CCC->redirect_buffer is not NULL during message submission!\n");
3225 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
3226 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
3227 smi.meta_rfc822_length = StrLength(CCC->redirect_buffer);
3228 saved_rfc822_version = CCC->redirect_buffer;
3229 CCC->redirect_buffer = NULL;
3233 /* Now figure out where to store the pointers */
3234 MSGM_syslog(LOG_DEBUG, "Storing pointers\n");
3236 /* If this is being done by the networker delivering a private
3237 * message, we want to BYPASS saving the sender's copy (because there
3238 * is no local sender; it would otherwise go to the Trashcan).
3240 if ((!CCC->internal_pgm) || (recps == NULL)) {
3241 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
3242 MSGM_syslog(LOG_ERR, "ERROR saving message pointer!\n");
3243 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3247 /* For internet mail, drop a copy in the outbound queue room */
3248 if ((recps != NULL) && (recps->num_internet > 0)) {
3249 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
3252 /* If other rooms are specified, drop them there too. */
3253 if ((recps != NULL) && (recps->num_room > 0))
3254 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
3255 extract_token(recipient, recps->recp_room, i,
3256 '|', sizeof recipient);
3257 MSG_syslog(LOG_DEBUG, "Delivering to room <%s>\n", recipient);///// xxxx
3258 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
3261 /* Bump this user's messages posted counter. */
3262 MSGM_syslog(LOG_DEBUG, "Updating user\n");
3263 CtdlGetUserLock(&CCC->user, CCC->curr_user);
3264 CCC->user.posted = CCC->user.posted + 1;
3265 CtdlPutUserLock(&CCC->user);
3267 /* Decide where bounces need to be delivered */
3268 if ((recps != NULL) && (recps->bounce_to != NULL)) {
3269 safestrncpy(bounce_to, recps->bounce_to, sizeof bounce_to);
3271 else if (CCC->logged_in) {
3272 snprintf(bounce_to, sizeof bounce_to, "%s@%s", CCC->user.fullname, config.c_nodename);
3275 snprintf(bounce_to, sizeof bounce_to, "%s@%s", msg->cm_fields['A'], msg->cm_fields['N']);
3278 /* If this is private, local mail, make a copy in the
3279 * recipient's mailbox and bump the reference count.
3281 if ((recps != NULL) && (recps->num_local > 0))
3282 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
3283 extract_token(recipient, recps->recp_local, i,
3284 '|', sizeof recipient);
3285 MSG_syslog(LOG_DEBUG, "Delivering private local mail to <%s>\n",
3287 if (CtdlGetUser(&userbuf, recipient) == 0) {
3288 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
3289 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
3290 CtdlBumpNewMailCounter(userbuf.usernum);
3291 if (!IsEmptyStr(config.c_funambol_host) || !IsEmptyStr(config.c_pager_program)) {
3292 /* Generate a instruction message for the Funambol notification
3293 * server, in the same style as the SMTP queue
3296 instr = malloc(instr_alloc);
3297 snprintf(instr, instr_alloc,
3298 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
3300 SPOOLMIME, newmsgid, (long)time(NULL),
3304 imsg = malloc(sizeof(struct CtdlMessage));
3305 memset(imsg, 0, sizeof(struct CtdlMessage));
3306 imsg->cm_magic = CTDLMESSAGE_MAGIC;
3307 imsg->cm_anon_type = MES_NORMAL;
3308 imsg->cm_format_type = FMT_RFC822;
3309 imsg->cm_fields['U'] = strdup("QMSG");
3310 imsg->cm_fields['A'] = strdup("Citadel");
3311 imsg->cm_fields['J'] = strdup("do not journal");
3312 imsg->cm_fields['M'] = instr; /* imsg owns this memory now */
3313 imsg->cm_fields['2'] = strdup(recipient);
3314 CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM, 0);
3315 CtdlFreeMessage(imsg);
3319 MSG_syslog(LOG_DEBUG, "No user <%s>\n", recipient);
3320 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3324 /* Perform "after save" hooks */
3325 MSGM_syslog(LOG_DEBUG, "Performing after-save hooks\n");
3326 if (msg->cm_fields['3'] != NULL) free(msg->cm_fields['3']);
3327 msg->cm_fields['3'] = malloc(20);
3328 snprintf(msg->cm_fields['3'], 20, "%ld", newmsgid);
3329 PerformMessageHooks(msg, EVT_AFTERSAVE);
3330 free(msg->cm_fields['3']);
3331 msg->cm_fields['3'] = NULL;
3333 /* For IGnet mail, we have to save a new copy into the spooler for
3334 * each recipient, with the R and D fields set to the recipient and
3335 * destination-node. This has two ugly side effects: all other
3336 * recipients end up being unlisted in this recipient's copy of the
3337 * message, and it has to deliver multiple messages to the same
3338 * node. We'll revisit this again in a year or so when everyone has
3339 * a network spool receiver that can handle the new style messages.
3341 if ((recps != NULL) && (recps->num_ignet > 0))
3342 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
3343 extract_token(recipient, recps->recp_ignet, i,
3344 '|', sizeof recipient);
3346 hold_R = msg->cm_fields['R'];
3347 hold_D = msg->cm_fields['D'];
3348 msg->cm_fields['R'] = malloc(SIZ);
3349 msg->cm_fields['D'] = malloc(128);
3350 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
3351 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
3353 serialize_message(&smr, msg);
3355 snprintf(submit_filename, sizeof submit_filename,
3356 "%s/netmail.%04lx.%04x.%04x",
3358 (long) getpid(), CCC->cs_pid, ++seqnum);
3359 network_fp = fopen(submit_filename, "wb+");
3360 if (network_fp != NULL) {
3361 rv = fwrite(smr.ser, smr.len, 1, network_fp);
3363 MSG_syslog(LOG_EMERG, "CtdlSubmitMsg(): Couldn't write network spool file: %s\n",
3371 free(msg->cm_fields['R']);
3372 free(msg->cm_fields['D']);
3373 msg->cm_fields['R'] = hold_R;
3374 msg->cm_fields['D'] = hold_D;
3377 /* Go back to the room we started from */
3378 MSG_syslog(LOG_DEBUG, "Returning to original room %s\n", hold_rm);
3379 if (strcasecmp(hold_rm, CCC->room.QRname))
3380 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL);
3382 /* For internet mail, generate delivery instructions.
3383 * Yes, this is recursive. Deal with it. Infinite recursion does
3384 * not happen because the delivery instructions message does not
3385 * contain a recipient.
3387 if ((recps != NULL) && (recps->num_internet > 0)) {
3388 StrBuf *SpoolMsg = NewStrBuf();
3391 MSGM_syslog(LOG_DEBUG, "Generating delivery instructions\n");
3393 StrBufPrintf(SpoolMsg,
3394 "Content-type: "SPOOLMIME"\n"
3403 if (recps->envelope_from != NULL) {
3404 StrBufAppendBufPlain(SpoolMsg, HKEY("envelope_from|"), 0);
3405 StrBufAppendBufPlain(SpoolMsg, recps->envelope_from, -1, 0);
3406 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3408 if (recps->sending_room != NULL) {
3409 StrBufAppendBufPlain(SpoolMsg, HKEY("source_room|"), 0);
3410 StrBufAppendBufPlain(SpoolMsg, recps->sending_room, -1, 0);
3411 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3414 nTokens = num_tokens(recps->recp_internet, '|');
3415 for (i = 0; i < nTokens; i++) {
3417 len = extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
3419 StrBufAppendBufPlain(SpoolMsg, HKEY("remote|"), 0);
3420 StrBufAppendBufPlain(SpoolMsg, recipient, len, 0);
3421 StrBufAppendBufPlain(SpoolMsg, HKEY("|0||\n"), 0);
3425 imsg = malloc(sizeof(struct CtdlMessage));
3426 memset(imsg, 0, sizeof(struct CtdlMessage));
3427 imsg->cm_magic = CTDLMESSAGE_MAGIC;
3428 imsg->cm_anon_type = MES_NORMAL;
3429 imsg->cm_format_type = FMT_RFC822;
3430 imsg->cm_fields['U'] = strdup("QMSG");
3431 imsg->cm_fields['A'] = strdup("Citadel");
3432 imsg->cm_fields['J'] = strdup("do not journal");
3433 imsg->cm_fields['M'] = SmashStrBuf(&SpoolMsg); /* imsg owns this memory now */
3434 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
3435 CtdlFreeMessage(imsg);
3439 * Any addresses to harvest for someone's address book?
3441 if ( (CCC->logged_in) && (recps != NULL) ) {
3442 collected_addresses = harvest_collected_addresses(msg);
3445 if (collected_addresses != NULL) {
3446 aptr = (struct addresses_to_be_filed *)
3447 malloc(sizeof(struct addresses_to_be_filed));
3448 CtdlMailboxName(actual_rm, sizeof actual_rm,
3449 &CCC->user, USERCONTACTSROOM);
3450 aptr->roomname = strdup(actual_rm);
3451 aptr->collected_addresses = collected_addresses;
3452 begin_critical_section(S_ATBF);
3455 end_critical_section(S_ATBF);
3459 * Determine whether this message qualifies for journaling.
3461 if (msg->cm_fields['J'] != NULL) {
3462 qualified_for_journaling = 0;
3465 if (recps == NULL) {
3466 qualified_for_journaling = config.c_journal_pubmsgs;
3468 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
3469 qualified_for_journaling = config.c_journal_email;
3472 qualified_for_journaling = config.c_journal_pubmsgs;
3477 * Do we have to perform journaling? If so, hand off the saved
3478 * RFC822 version will be handed off to the journaler for background
3479 * submit. Otherwise, we have to free the memory ourselves.
3481 if (saved_rfc822_version != NULL) {
3482 if (qualified_for_journaling) {
3483 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
3486 FreeStrBuf(&saved_rfc822_version);
3496 * Convenience function for generating small administrative messages.
3498 void quickie_message(const char *from,
3499 const char *fromaddr,
3504 const char *subject)
3506 struct CtdlMessage *msg;
3507 struct recptypes *recp = NULL;
3509 msg = malloc(sizeof(struct CtdlMessage));
3510 memset(msg, 0, sizeof(struct CtdlMessage));
3511 msg->cm_magic = CTDLMESSAGE_MAGIC;
3512 msg->cm_anon_type = MES_NORMAL;
3513 msg->cm_format_type = format_type;
3516 msg->cm_fields['A'] = strdup(from);
3518 else if (fromaddr != NULL) {
3519 msg->cm_fields['A'] = strdup(fromaddr);
3520 if (strchr(msg->cm_fields['A'], '@')) {
3521 *strchr(msg->cm_fields['A'], '@') = 0;
3525 msg->cm_fields['A'] = strdup("Citadel");
3528 if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
3529 if (room != NULL) msg->cm_fields['O'] = strdup(room);
3530 msg->cm_fields['N'] = strdup(NODENAME);
3532 msg->cm_fields['R'] = strdup(to);
3533 recp = validate_recipients(to, NULL, 0);
3535 if (subject != NULL) {
3536 msg->cm_fields['U'] = strdup(subject);
3538 msg->cm_fields['M'] = strdup(text);
3540 CtdlSubmitMsg(msg, recp, room, 0);
3541 CtdlFreeMessage(msg);
3542 if (recp != NULL) free_recipients(recp);
3545 void flood_protect_quickie_message(const char *from,
3546 const char *fromaddr,
3551 const char *subject,
3553 const char **CritStr,
3558 u_char rawdigest[MD5_DIGEST_LEN];
3559 struct MD5Context md5context;
3561 struct cdbdata *cdbut;
3564 time_t ts = time(NULL);
3565 time_t tsday = ts / (8*60*60); /* just care for a day... */
3567 tslen = snprintf(timestamp, sizeof(timestamp), "%ld", tsday);
3568 MD5Init(&md5context);
3570 for (i = 0; i < nCriterions; i++)
3571 MD5Update(&md5context,
3572 (const unsigned char*)CritStr[i], CritStrLen[i]);
3573 MD5Update(&md5context,
3574 (const unsigned char*)timestamp, tslen);
3575 MD5Final(rawdigest, &md5context);
3577 guid = NewStrBufPlain(NULL,
3578 MD5_DIGEST_LEN * 2 + 12);
3579 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
3580 StrBufAppendBufPlain(guid, HKEY("_fldpt"), 0);
3581 if (StrLength(guid) > 40)
3582 StrBufCutAt(guid, 40, NULL);
3583 /* Find out if we've already sent a similar message */
3584 memcpy(ut.ut_msgid, SKEY(guid));
3585 ut.ut_timestamp = ts;
3587 cdbut = cdb_fetch(CDB_USETABLE, SKEY(guid));
3589 if (cdbut != NULL) {
3590 /* yes, we did. flood protection kicks in. */
3592 "not sending message again\n");
3596 /* rewrite the record anyway, to update the timestamp */
3597 cdb_store(CDB_USETABLE,
3599 &ut, sizeof(struct UseTable) );
3603 if (cdbut != NULL) return;
3604 /* no, this message isn't sent recently; go ahead. */
3605 quickie_message(from,
3616 * Back end function used by CtdlMakeMessage() and similar functions
3618 StrBuf *CtdlReadMessageBodyBuf(char *terminator, /* token signalling EOT */
3620 size_t maxlen, /* maximum message length */
3621 char *exist, /* if non-null, append to it;
3622 exist is ALWAYS freed */
3623 int crlf, /* CRLF newlines instead of LF */
3624 int *sock /* socket handle or 0 for this session's client socket */
3633 LineBuf = NewStrBufPlain(NULL, SIZ);
3634 if (exist == NULL) {
3635 Message = NewStrBufPlain(NULL, 4 * SIZ);
3638 Message = NewStrBufPlain(exist, -1);
3642 /* Do we need to change leading ".." to "." for SMTP escaping? */
3643 if ((tlen == 1) && (*terminator == '.')) {
3647 /* read in the lines of message text one by one */
3650 if ((CtdlSockGetLine(sock, LineBuf, 5) < 0) ||
3655 if (CtdlClientGetLine(LineBuf) < 0) finished = 1;
3657 if ((StrLength(LineBuf) == tlen) &&
3658 (!strcmp(ChrPtr(LineBuf), terminator)))
3661 if ( (!flushing) && (!finished) ) {
3663 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3666 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3669 /* Unescape SMTP-style input of two dots at the beginning of the line */
3671 (StrLength(LineBuf) == 2) &&
3672 (!strcmp(ChrPtr(LineBuf), "..")))
3674 StrBufCutLeft(LineBuf, 1);
3677 StrBufAppendBuf(Message, LineBuf, 0);
3680 /* if we've hit the max msg length, flush the rest */
3681 if (StrLength(Message) >= maxlen) flushing = 1;
3683 } while (!finished);
3684 FreeStrBuf(&LineBuf);
3688 void DeleteAsyncMsg(ReadAsyncMsg **Msg)
3692 FreeStrBuf(&(*Msg)->MsgBuf);
3698 ReadAsyncMsg *NewAsyncMsg(const char *terminator, /* token signalling EOT */
3700 size_t maxlen, /* maximum message length */
3701 size_t expectlen, /* if we expect a message, how long should it be? */
3702 char *exist, /* if non-null, append to it;
3703 exist is ALWAYS freed */
3704 long eLen, /* length of exist */
3705 int crlf /* CRLF newlines instead of LF */
3708 ReadAsyncMsg *NewMsg;
3710 NewMsg = (ReadAsyncMsg *)malloc(sizeof(ReadAsyncMsg));
3711 memset(NewMsg, 0, sizeof(ReadAsyncMsg));
3713 if (exist == NULL) {
3716 if (expectlen == 0) {
3720 len = expectlen + 10;
3722 NewMsg->MsgBuf = NewStrBufPlain(NULL, len);
3725 NewMsg->MsgBuf = NewStrBufPlain(exist, eLen);
3728 /* Do we need to change leading ".." to "." for SMTP escaping? */
3729 if ((tlen == 1) && (*terminator == '.')) {
3733 NewMsg->terminator = terminator;
3734 NewMsg->tlen = tlen;
3736 NewMsg->maxlen = maxlen;
3738 NewMsg->crlf = crlf;
3744 * Back end function used by CtdlMakeMessage() and similar functions
3746 eReadState CtdlReadMessageBodyAsync(AsyncIO *IO)
3748 ReadAsyncMsg *ReadMsg;
3749 int MsgFinished = 0;
3750 eReadState Finished = eMustReadMore;
3755 const char *pch = ChrPtr(IO->SendBuf.Buf);
3756 const char *pchh = IO->SendBuf.ReadWritePointer;
3762 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
3763 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
3764 ((CitContext*)(IO->CitContext))->ServiceName,
3767 fd = fopen(fn, "a+");
3770 ReadMsg = IO->ReadMsg;
3772 /* read in the lines of message text one by one */
3774 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
3777 case eMustReadMore: /// read new from socket...
3779 if (IO->RecvBuf.ReadWritePointer != NULL) {
3780 nbytes = StrLength(IO->RecvBuf.Buf) - (IO->RecvBuf.ReadWritePointer - ChrPtr(IO->RecvBuf.Buf));
3781 fprintf(fd, "Read; Line unfinished: %ld Bytes still in buffer [", nbytes);
3783 fwrite(IO->RecvBuf.ReadWritePointer, nbytes, 1, fd);
3787 fprintf(fd, "BufferEmpty! \n");
3793 case eBufferNotEmpty: /* shouldn't happen... */
3794 case eReadSuccess: /// done for now...
3796 case eReadFail: /// WHUT?
3802 if ((StrLength(IO->IOBuf) == ReadMsg->tlen) &&
3803 (!strcmp(ChrPtr(IO->IOBuf), ReadMsg->terminator))) {
3806 fprintf(fd, "found Terminator; Message Size: %d\n", StrLength(ReadMsg->MsgBuf));
3809 else if (!ReadMsg->flushing) {
3812 fprintf(fd, "Read Line: [%d][%s]\n", StrLength(IO->IOBuf), ChrPtr(IO->IOBuf));
3815 /* Unescape SMTP-style input of two dots at the beginning of the line */
3816 if ((ReadMsg->dodot) &&
3817 (StrLength(IO->IOBuf) == 2) && /* TODO: do we just unescape lines with two dots or any line? */
3818 (!strcmp(ChrPtr(IO->IOBuf), "..")))
3821 fprintf(fd, "UnEscaped!\n");
3823 StrBufCutLeft(IO->IOBuf, 1);
3826 if (ReadMsg->crlf) {
3827 StrBufAppendBufPlain(IO->IOBuf, HKEY("\r\n"), 0);
3830 StrBufAppendBufPlain(IO->IOBuf, HKEY("\n"), 0);
3833 StrBufAppendBuf(ReadMsg->MsgBuf, IO->IOBuf, 0);
3836 /* if we've hit the max msg length, flush the rest */
3837 if (StrLength(ReadMsg->MsgBuf) >= ReadMsg->maxlen) ReadMsg->flushing = 1;
3839 } while (!MsgFinished);
3842 fprintf(fd, "Done with reading; %s.\n, ",
3843 (MsgFinished)?"Message Finished": "FAILED");
3847 return eReadSuccess;
3854 * Back end function used by CtdlMakeMessage() and similar functions
3856 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
3858 size_t maxlen, /* maximum message length */
3859 char *exist, /* if non-null, append to it;
3860 exist is ALWAYS freed */
3861 int crlf, /* CRLF newlines instead of LF */
3862 int *sock /* socket handle or 0 for this session's client socket */
3867 Message = CtdlReadMessageBodyBuf(terminator,
3873 if (Message == NULL)
3876 return SmashStrBuf(&Message);
3881 * Build a binary message to be saved on disk.
3882 * (NOTE: if you supply 'preformatted_text', the buffer you give it
3883 * will become part of the message. This means you are no longer
3884 * responsible for managing that memory -- it will be freed along with
3885 * the rest of the fields when CtdlFreeMessage() is called.)
3888 struct CtdlMessage *CtdlMakeMessage(
3889 struct ctdluser *author, /* author's user structure */
3890 char *recipient, /* NULL if it's not mail */
3891 char *recp_cc, /* NULL if it's not mail */
3892 char *room, /* room where it's going */
3893 int type, /* see MES_ types in header file */
3894 int format_type, /* variformat, plain text, MIME... */
3895 char *fake_name, /* who we're masquerading as */
3896 char *my_email, /* which of my email addresses to use (empty is ok) */
3897 char *subject, /* Subject (optional) */
3898 char *supplied_euid, /* ...or NULL if this is irrelevant */
3899 char *preformatted_text, /* ...or NULL to read text from client */
3900 char *references /* Thread references */
3902 char dest_node[256];
3904 struct CtdlMessage *msg;
3906 StrBuf *FakeEncAuthor = NULL;
3908 msg = malloc(sizeof(struct CtdlMessage));
3909 memset(msg, 0, sizeof(struct CtdlMessage));
3910 msg->cm_magic = CTDLMESSAGE_MAGIC;
3911 msg->cm_anon_type = type;
3912 msg->cm_format_type = format_type;
3914 /* Don't confuse the poor folks if it's not routed mail. */
3915 strcpy(dest_node, "");
3917 if (recipient != NULL) striplt(recipient);
3918 if (recp_cc != NULL) striplt(recp_cc);
3920 /* Path or Return-Path */
3921 if (my_email == NULL) my_email = "";
3923 if (!IsEmptyStr(my_email)) {
3924 msg->cm_fields['P'] = strdup(my_email);
3927 snprintf(buf, sizeof buf, "%s", author->fullname);
3928 msg->cm_fields['P'] = strdup(buf);
3930 convert_spaces_to_underscores(msg->cm_fields['P']);
3932 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
3933 msg->cm_fields['T'] = strdup(buf);
3935 if ((fake_name != NULL) && (fake_name[0])) { /* author */
3936 FakeAuthor = NewStrBufPlain (fake_name, -1);
3939 FakeAuthor = NewStrBufPlain (author->fullname, -1);
3941 StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
3942 msg->cm_fields['A'] = SmashStrBuf(&FakeEncAuthor);
3943 FreeStrBuf(&FakeAuthor);
3945 if (CC->room.QRflags & QR_MAILBOX) { /* room */
3946 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
3949 msg->cm_fields['O'] = strdup(CC->room.QRname);
3952 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
3953 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
3955 if ((recipient != NULL) && (recipient[0] != 0)) {
3956 msg->cm_fields['R'] = strdup(recipient);
3958 if ((recp_cc != NULL) && (recp_cc[0] != 0)) {
3959 msg->cm_fields['Y'] = strdup(recp_cc);
3961 if (dest_node[0] != 0) {
3962 msg->cm_fields['D'] = strdup(dest_node);
3965 if (!IsEmptyStr(my_email)) {
3966 msg->cm_fields['F'] = strdup(my_email);
3968 else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
3969 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
3972 if (subject != NULL) {
3975 length = strlen(subject);
3981 while ((subject[i] != '\0') &&
3982 (IsAscii = isascii(subject[i]) != 0 ))
3985 msg->cm_fields['U'] = strdup(subject);
3986 else /* ok, we've got utf8 in the string. */
3988 msg->cm_fields['U'] = rfc2047encode(subject, length);
3994 if (supplied_euid != NULL) {
3995 msg->cm_fields['E'] = strdup(supplied_euid);
3998 if ((references != NULL) && (!IsEmptyStr(references))) {
3999 if (msg->cm_fields['W'] != NULL)
4000 free(msg->cm_fields['W']);
4001 msg->cm_fields['W'] = strdup(references);
4004 if (preformatted_text != NULL) {
4005 msg->cm_fields['M'] = preformatted_text;
4008 msg->cm_fields['M'] = CtdlReadMessageBody(HKEY("000"), config.c_maxmsglen, NULL, 0, 0);
4014 extern int netconfig_check_roomaccess(
4017 const char* RemoteIdentifier); /* TODO: find a smarter way */
4020 * Check to see whether we have permission to post a message in the current
4021 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
4022 * returns 0 on success.
4024 int CtdlDoIHavePermissionToPostInThisRoom(
4027 const char* RemoteIdentifier,
4033 if (!(CC->logged_in) &&
4034 (PostPublic == POST_LOGGED_IN)) {
4035 snprintf(errmsgbuf, n, "Not logged in.");
4036 return (ERROR + NOT_LOGGED_IN);
4038 else if (PostPublic == CHECK_EXISTANCE) {
4039 return (0); // We're Evaling whether a recipient exists
4041 else if (!(CC->logged_in)) {
4043 if ((CC->room.QRflags & QR_READONLY)) {
4044 snprintf(errmsgbuf, n, "Not logged in.");
4045 return (ERROR + NOT_LOGGED_IN);
4047 if (CC->room.QRflags2 & QR2_MODERATED) {
4048 snprintf(errmsgbuf, n, "Not logged in Moderation feature not yet implemented!");
4049 return (ERROR + NOT_LOGGED_IN);
4051 if ((PostPublic!=POST_LMTP) &&(CC->room.QRflags2 & QR2_SMTP_PUBLIC) == 0) {
4053 return netconfig_check_roomaccess(errmsgbuf, n, RemoteIdentifier);
4059 if ((CC->user.axlevel < AxProbU)
4060 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
4061 snprintf(errmsgbuf, n, "Need to be validated to enter (except in %s> to sysop)", MAILROOM);
4062 return (ERROR + HIGHER_ACCESS_REQUIRED);
4065 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
4067 if (ra & UA_POSTALLOWED) {
4068 strcpy(errmsgbuf, "OK to post or reply here");
4072 if ( (ra & UA_REPLYALLOWED) && (is_reply) ) {
4074 * To be thorough, we ought to check to see if the message they are
4075 * replying to is actually a valid one in this room, but unless this
4076 * actually becomes a problem we'll go with high performance instead.
4078 strcpy(errmsgbuf, "OK to reply here");
4082 if ( (ra & UA_REPLYALLOWED) && (!is_reply) ) {
4083 /* Clarify what happened with a better error message */
4084 snprintf(errmsgbuf, n, "You may only reply to existing messages here.");
4085 return (ERROR + HIGHER_ACCESS_REQUIRED);
4088 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
4089 return (ERROR + HIGHER_ACCESS_REQUIRED);
4095 * Check to see if the specified user has Internet mail permission
4096 * (returns nonzero if permission is granted)
4098 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
4100 /* Do not allow twits to send Internet mail */
4101 if (who->axlevel <= AxProbU) return(0);
4103 /* Globally enabled? */
4104 if (config.c_restrict == 0) return(1);
4106 /* User flagged ok? */
4107 if (who->flags & US_INTERNET) return(2);
4109 /* Admin level access? */
4110 if (who->axlevel >= AxAideU) return(3);
4112 /* No mail for you! */
4118 * Validate recipients, count delivery types and errors, and handle aliasing
4119 * FIXME check for dupes!!!!!
4121 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
4122 * were specified, or the number of addresses found invalid.
4124 * Caller needs to free the result using free_recipients()
4126 struct recptypes *validate_recipients(const char *supplied_recipients,
4127 const char *RemoteIdentifier,
4129 struct CitContext *CCC = CC;
4130 struct recptypes *ret;
4131 char *recipients = NULL;
4133 char this_recp[256];
4134 char this_recp_cooked[256];
4141 struct ctdluser tempUS;
4142 struct ctdlroom tempQR;
4143 struct ctdlroom tempQR2;
4149 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
4150 if (ret == NULL) return(NULL);
4152 /* Set all strings to null and numeric values to zero */
4153 memset(ret, 0, sizeof(struct recptypes));
4155 if (supplied_recipients == NULL) {
4156 recipients = strdup("");
4159 recipients = strdup(supplied_recipients);
4162 /* Allocate some memory. Yes, this allocates 500% more memory than we will
4163 * actually need, but it's healthier for the heap than doing lots of tiny
4164 * realloc() calls instead.
4166 len = strlen(recipients) + 1024;
4167 ret->errormsg = malloc(len);
4168 ret->recp_local = malloc(len);
4169 ret->recp_internet = malloc(len);
4170 ret->recp_ignet = malloc(len);
4171 ret->recp_room = malloc(len);
4172 ret->display_recp = malloc(len);
4173 ret->recp_orgroom = malloc(len);
4174 org_recp = malloc(len);
4176 ret->errormsg[0] = 0;
4177 ret->recp_local[0] = 0;
4178 ret->recp_internet[0] = 0;
4179 ret->recp_ignet[0] = 0;
4180 ret->recp_room[0] = 0;
4181 ret->recp_orgroom[0] = 0;
4182 ret->display_recp[0] = 0;
4184 ret->recptypes_magic = RECPTYPES_MAGIC;
4186 /* Change all valid separator characters to commas */
4187 for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
4188 if ((recipients[i] == ';') || (recipients[i] == '|')) {
4189 recipients[i] = ',';
4193 /* Now start extracting recipients... */
4195 while (!IsEmptyStr(recipients)) {
4196 for (i=0; i<=strlen(recipients); ++i) {
4197 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
4198 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
4199 safestrncpy(this_recp, recipients, i+1);
4201 if (recipients[i] == ',') {
4202 strcpy(recipients, &recipients[i+1]);
4205 strcpy(recipients, "");
4212 if (IsEmptyStr(this_recp))
4214 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
4217 strcpy(org_recp, this_recp);
4220 mailtype = alias(this_recp);
4222 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
4223 if (this_recp[j]=='_') {
4224 this_recp_cooked[j] = ' ';
4227 this_recp_cooked[j] = this_recp[j];
4230 this_recp_cooked[j] = '\0';
4235 if (!strcasecmp(this_recp, "sysop")) {
4237 strcpy(this_recp, config.c_aideroom);
4238 if (!IsEmptyStr(ret->recp_room)) {
4239 strcat(ret->recp_room, "|");
4241 strcat(ret->recp_room, this_recp);
4243 else if ( (!strncasecmp(this_recp, "room_", 5))
4244 && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
4246 /* Save room so we can restore it later */
4247 tempQR2 = CCC->room;
4250 /* Check permissions to send mail to this room */
4251 err = CtdlDoIHavePermissionToPostInThisRoom(
4256 0 /* 0 = not a reply */
4265 if (!IsEmptyStr(ret->recp_room)) {
4266 strcat(ret->recp_room, "|");
4268 strcat(ret->recp_room, &this_recp_cooked[5]);
4270 if (!IsEmptyStr(ret->recp_orgroom)) {
4271 strcat(ret->recp_orgroom, "|");
4273 strcat(ret->recp_orgroom, org_recp);
4277 /* Restore room in case something needs it */
4278 CCC->room = tempQR2;
4281 else if (CtdlGetUser(&tempUS, this_recp) == 0) {
4283 strcpy(this_recp, tempUS.fullname);
4284 if (!IsEmptyStr(ret->recp_local)) {
4285 strcat(ret->recp_local, "|");
4287 strcat(ret->recp_local, this_recp);
4289 else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
4291 strcpy(this_recp, tempUS.fullname);
4292 if (!IsEmptyStr(ret->recp_local)) {
4293 strcat(ret->recp_local, "|");
4295 strcat(ret->recp_local, this_recp);
4303 /* Yes, you're reading this correctly: if the target
4304 * domain points back to the local system or an attached
4305 * Citadel directory, the address is invalid. That's
4306 * because if the address were valid, we would have
4307 * already translated it to a local address by now.
4309 if (IsDirectory(this_recp, 0)) {
4314 ++ret->num_internet;
4315 if (!IsEmptyStr(ret->recp_internet)) {
4316 strcat(ret->recp_internet, "|");
4318 strcat(ret->recp_internet, this_recp);
4323 if (!IsEmptyStr(ret->recp_ignet)) {
4324 strcat(ret->recp_ignet, "|");
4326 strcat(ret->recp_ignet, this_recp);
4334 if (IsEmptyStr(errmsg)) {
4335 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
4338 snprintf(append, sizeof append, "%s", errmsg);
4340 if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
4341 if (!IsEmptyStr(ret->errormsg)) {
4342 strcat(ret->errormsg, "; ");
4344 strcat(ret->errormsg, append);
4348 if (IsEmptyStr(ret->display_recp)) {
4349 strcpy(append, this_recp);
4352 snprintf(append, sizeof append, ", %s", this_recp);
4354 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
4355 strcat(ret->display_recp, append);
4361 if ((ret->num_local + ret->num_internet + ret->num_ignet +
4362 ret->num_room + ret->num_error) == 0) {
4363 ret->num_error = (-1);
4364 strcpy(ret->errormsg, "No recipients specified.");
4367 MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
4368 MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
4369 MSG_syslog(LOG_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
4370 MSG_syslog(LOG_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
4371 MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
4372 MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
4380 * Destructor for struct recptypes
4382 void free_recipients(struct recptypes *valid) {
4384 if (valid == NULL) {
4388 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
4389 struct CitContext *CCC = CC;
4390 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
4394 if (valid->errormsg != NULL) free(valid->errormsg);
4395 if (valid->recp_local != NULL) free(valid->recp_local);
4396 if (valid->recp_internet != NULL) free(valid->recp_internet);
4397 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
4398 if (valid->recp_room != NULL) free(valid->recp_room);
4399 if (valid->recp_orgroom != NULL) free(valid->recp_orgroom);
4400 if (valid->display_recp != NULL) free(valid->display_recp);
4401 if (valid->bounce_to != NULL) free(valid->bounce_to);
4402 if (valid->envelope_from != NULL) free(valid->envelope_from);
4403 if (valid->sending_room != NULL) free(valid->sending_room);
4410 * message entry - mode 0 (normal)
4412 void cmd_ent0(char *entargs)
4414 struct CitContext *CCC = CC;
4419 char supplied_euid[128];
4421 int format_type = 0;
4422 char newusername[256];
4423 char newuseremail[256];
4424 struct CtdlMessage *msg;
4428 struct recptypes *valid = NULL;
4429 struct recptypes *valid_to = NULL;
4430 struct recptypes *valid_cc = NULL;
4431 struct recptypes *valid_bcc = NULL;
4433 int subject_required = 0;
4438 int newuseremail_ok = 0;
4439 char references[SIZ];
4444 post = extract_int(entargs, 0);
4445 extract_token(recp, entargs, 1, '|', sizeof recp);
4446 anon_flag = extract_int(entargs, 2);
4447 format_type = extract_int(entargs, 3);
4448 extract_token(subject, entargs, 4, '|', sizeof subject);
4449 extract_token(newusername, entargs, 5, '|', sizeof newusername);
4450 do_confirm = extract_int(entargs, 6);
4451 extract_token(cc, entargs, 7, '|', sizeof cc);
4452 extract_token(bcc, entargs, 8, '|', sizeof bcc);
4453 switch(CC->room.QRdefaultview) {
4456 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
4459 supplied_euid[0] = 0;
4462 extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
4463 extract_token(references, entargs, 11, '|', sizeof references);
4464 for (ptr=references; *ptr != 0; ++ptr) {
4465 if (*ptr == '!') *ptr = '|';
4468 /* first check to make sure the request is valid. */
4470 err = CtdlDoIHavePermissionToPostInThisRoom(
4475 (!IsEmptyStr(references)) /* is this a reply? or a top-level post? */
4479 cprintf("%d %s\n", err, errmsg);
4483 /* Check some other permission type things. */
4485 if (IsEmptyStr(newusername)) {
4486 strcpy(newusername, CCC->user.fullname);
4488 if ( (CCC->user.axlevel < AxAideU)
4489 && (strcasecmp(newusername, CCC->user.fullname))
4490 && (strcasecmp(newusername, CCC->cs_inet_fn))
4492 cprintf("%d You don't have permission to author messages as '%s'.\n",
4493 ERROR + HIGHER_ACCESS_REQUIRED,
4500 if (IsEmptyStr(newuseremail)) {
4501 newuseremail_ok = 1;
4504 if (!IsEmptyStr(newuseremail)) {
4505 if (!strcasecmp(newuseremail, CCC->cs_inet_email)) {
4506 newuseremail_ok = 1;
4508 else if (!IsEmptyStr(CCC->cs_inet_other_emails)) {
4509 j = num_tokens(CCC->cs_inet_other_emails, '|');
4510 for (i=0; i<j; ++i) {
4511 extract_token(buf, CCC->cs_inet_other_emails, i, '|', sizeof buf);
4512 if (!strcasecmp(newuseremail, buf)) {
4513 newuseremail_ok = 1;
4519 if (!newuseremail_ok) {
4520 cprintf("%d You don't have permission to author messages as '%s'.\n",
4521 ERROR + HIGHER_ACCESS_REQUIRED,
4527 CCC->cs_flags |= CS_POSTING;
4529 /* In mailbox rooms we have to behave a little differently --
4530 * make sure the user has specified at least one recipient. Then
4531 * validate the recipient(s). We do this for the Mail> room, as
4532 * well as any room which has the "Mailbox" view set - unless it
4533 * is the DRAFTS room which does not require recipients
4536 if ( ( ( (CCC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CCC->room.QRname[11], MAILROOM)) )
4537 || ( (CCC->room.QRflags & QR_MAILBOX) && (CCC->curr_view == VIEW_MAILBOX) )
4538 ) && (strcasecmp(&CCC->room.QRname[11], USERDRAFTROOM)) !=0 ) {
4539 if (CCC->user.axlevel < AxProbU) {
4540 strcpy(recp, "sysop");
4545 valid_to = validate_recipients(recp, NULL, 0);
4546 if (valid_to->num_error > 0) {
4547 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_to->errormsg);
4548 free_recipients(valid_to);
4552 valid_cc = validate_recipients(cc, NULL, 0);
4553 if (valid_cc->num_error > 0) {
4554 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_cc->errormsg);
4555 free_recipients(valid_to);
4556 free_recipients(valid_cc);
4560 valid_bcc = validate_recipients(bcc, NULL, 0);
4561 if (valid_bcc->num_error > 0) {
4562 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_bcc->errormsg);
4563 free_recipients(valid_to);
4564 free_recipients(valid_cc);
4565 free_recipients(valid_bcc);
4569 /* Recipient required, but none were specified */
4570 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
4571 free_recipients(valid_to);
4572 free_recipients(valid_cc);
4573 free_recipients(valid_bcc);
4574 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
4578 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
4579 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
4580 cprintf("%d You do not have permission "
4581 "to send Internet mail.\n",
4582 ERROR + HIGHER_ACCESS_REQUIRED);
4583 free_recipients(valid_to);
4584 free_recipients(valid_cc);
4585 free_recipients(valid_bcc);
4590 if ( ( (valid_to->num_internet + valid_to->num_ignet + valid_cc->num_internet + valid_cc->num_ignet + valid_bcc->num_internet + valid_bcc->num_ignet) > 0)
4591 && (CCC->user.axlevel < AxNetU) ) {
4592 cprintf("%d Higher access required for network mail.\n",
4593 ERROR + HIGHER_ACCESS_REQUIRED);
4594 free_recipients(valid_to);
4595 free_recipients(valid_cc);
4596 free_recipients(valid_bcc);
4600 if ((RESTRICT_INTERNET == 1)
4601 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
4602 && ((CCC->user.flags & US_INTERNET) == 0)
4603 && (!CCC->internal_pgm)) {
4604 cprintf("%d You don't have access to Internet mail.\n",
4605 ERROR + HIGHER_ACCESS_REQUIRED);
4606 free_recipients(valid_to);
4607 free_recipients(valid_cc);
4608 free_recipients(valid_bcc);
4614 /* Is this a room which has anonymous-only or anonymous-option? */
4615 anonymous = MES_NORMAL;
4616 if (CCC->room.QRflags & QR_ANONONLY) {
4617 anonymous = MES_ANONONLY;
4619 if (CCC->room.QRflags & QR_ANONOPT) {
4620 if (anon_flag == 1) { /* only if the user requested it */
4621 anonymous = MES_ANONOPT;
4625 if ((CCC->room.QRflags & QR_MAILBOX) == 0) {
4629 /* Recommend to the client that the use of a message subject is
4630 * strongly recommended in this room, if either the SUBJECTREQ flag
4631 * is set, or if there is one or more Internet email recipients.
4633 if (CCC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
4634 if ((valid_to) && (valid_to->num_internet > 0)) subject_required = 1;
4635 if ((valid_cc) && (valid_cc->num_internet > 0)) subject_required = 1;
4636 if ((valid_bcc) && (valid_bcc->num_internet > 0)) subject_required = 1;
4638 /* If we're only checking the validity of the request, return
4639 * success without creating the message.
4642 cprintf("%d %s|%d\n", CIT_OK,
4643 ((valid_to != NULL) ? valid_to->display_recp : ""),
4645 free_recipients(valid_to);
4646 free_recipients(valid_cc);
4647 free_recipients(valid_bcc);
4651 /* We don't need these anymore because we'll do it differently below */
4652 free_recipients(valid_to);
4653 free_recipients(valid_cc);
4654 free_recipients(valid_bcc);
4656 /* Read in the message from the client. */
4658 cprintf("%d send message\n", START_CHAT_MODE);
4660 cprintf("%d send message\n", SEND_LISTING);
4663 msg = CtdlMakeMessage(&CCC->user, recp, cc,
4664 CCC->room.QRname, anonymous, format_type,
4665 newusername, newuseremail, subject,
4666 ((!IsEmptyStr(supplied_euid)) ? supplied_euid : NULL),
4669 /* Put together one big recipients struct containing to/cc/bcc all in
4670 * one. This is for the envelope.
4672 char *all_recps = malloc(SIZ * 3);
4673 strcpy(all_recps, recp);
4674 if (!IsEmptyStr(cc)) {
4675 if (!IsEmptyStr(all_recps)) {
4676 strcat(all_recps, ",");
4678 strcat(all_recps, cc);
4680 if (!IsEmptyStr(bcc)) {
4681 if (!IsEmptyStr(all_recps)) {
4682 strcat(all_recps, ",");
4684 strcat(all_recps, bcc);
4686 if (!IsEmptyStr(all_recps)) {
4687 valid = validate_recipients(all_recps, NULL, 0);
4694 if ((valid != NULL) && (valid->num_room == 1))
4696 /* posting into an ML room? set the envelope from
4697 * to the actual mail address so others get a valid
4700 msg->cm_fields['V'] = strdup(valid->recp_orgroom);
4704 msgnum = CtdlSubmitMsg(msg, valid, "", QP_EADDR);
4706 cprintf("%ld\n", msgnum);
4708 if (StrLength(CCC->StatusMessage) > 0) {
4709 cprintf("%s\n", ChrPtr(CCC->StatusMessage));
4711 else if (msgnum >= 0L) {
4712 client_write(HKEY("Message accepted.\n"));
4715 client_write(HKEY("Internal error.\n"));
4718 if (msg->cm_fields['E'] != NULL) {
4719 cprintf("%s\n", msg->cm_fields['E']);
4726 CtdlFreeMessage(msg);
4728 if (valid != NULL) {
4729 free_recipients(valid);
4737 * API function to delete messages which match a set of criteria
4738 * (returns the actual number of messages deleted)
4740 int CtdlDeleteMessages(char *room_name, /* which room */
4741 long *dmsgnums, /* array of msg numbers to be deleted */
4742 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
4743 char *content_type /* or "" for any. regular expressions expected. */
4746 struct CitContext *CCC = CC;
4747 struct ctdlroom qrbuf;
4748 struct cdbdata *cdbfr;
4749 long *msglist = NULL;
4750 long *dellist = NULL;
4753 int num_deleted = 0;
4755 struct MetaData smi;
4758 int need_to_free_re = 0;
4760 if (content_type) if (!IsEmptyStr(content_type)) {
4761 regcomp(&re, content_type, 0);
4762 need_to_free_re = 1;
4764 MSG_syslog(LOG_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
4765 room_name, num_dmsgnums, content_type);
4767 /* get room record, obtaining a lock... */
4768 if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
4769 MSG_syslog(LOG_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
4771 if (need_to_free_re) regfree(&re);
4772 return (0); /* room not found */
4774 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
4776 if (cdbfr != NULL) {
4777 dellist = malloc(cdbfr->len);
4778 msglist = (long *) cdbfr->ptr;
4779 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
4780 num_msgs = cdbfr->len / sizeof(long);
4784 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
4785 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
4786 int have_more_del = 1;
4788 num_msgs = sort_msglist(msglist, num_msgs);
4789 if (num_dmsgnums > 1)
4790 num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
4793 StrBuf *dbg = NewStrBuf();
4794 for (i = 0; i < num_dmsgnums; i++)
4795 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
4796 MSG_syslog(LOG_DEBUG, "Deleting before: %s", ChrPtr(dbg));
4801 while ((i < num_msgs) && (have_more_del)) {
4805 /* Set/clear a bit for each criterion */
4807 /* 0 messages in the list or a null list means that we are
4808 * interested in deleting any messages which meet the other criteria.
4811 delete_this |= 0x01;
4814 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
4815 if (msglist[i] == dmsgnums[j]) {
4816 delete_this |= 0x01;
4819 have_more_del = (j < num_dmsgnums);
4822 if (have_contenttype) {
4823 GetMetaData(&smi, msglist[i]);
4824 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
4825 delete_this |= 0x02;
4828 delete_this |= 0x02;
4831 /* Delete message only if all bits are set */
4832 if (delete_this == 0x03) {
4833 dellist[num_deleted++] = msglist[i];
4840 StrBuf *dbg = NewStrBuf();
4841 for (i = 0; i < num_deleted; i++)
4842 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
4843 MSG_syslog(LOG_DEBUG, "Deleting: %s", ChrPtr(dbg));
4847 num_msgs = sort_msglist(msglist, num_msgs);
4848 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
4849 msglist, (int)(num_msgs * sizeof(long)));
4852 qrbuf.QRhighest = msglist[num_msgs - 1];
4854 qrbuf.QRhighest = 0;
4856 CtdlPutRoomLock(&qrbuf);
4858 /* Go through the messages we pulled out of the index, and decrement
4859 * their reference counts by 1. If this is the only room the message
4860 * was in, the reference count will reach zero and the message will
4861 * automatically be deleted from the database. We do this in a
4862 * separate pass because there might be plug-in hooks getting called,
4863 * and we don't want that happening during an S_ROOMS critical
4867 for (i=0; i<num_deleted; ++i) {
4868 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
4870 AdjRefCountList(dellist, num_deleted, -1);
4872 /* Now free the memory we used, and go away. */
4873 if (msglist != NULL) free(msglist);
4874 if (dellist != NULL) free(dellist);
4875 MSG_syslog(LOG_DEBUG, "%d message(s) deleted.\n", num_deleted);
4876 if (need_to_free_re) regfree(&re);
4877 return (num_deleted);
4883 * Check whether the current user has permission to delete messages from
4884 * the current room (returns 1 for yes, 0 for no)
4886 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
4888 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
4889 if (ra & UA_DELETEALLOWED) return(1);
4897 * Delete message from current room
4899 void cmd_dele(char *args)
4908 extract_token(msgset, args, 0, '|', sizeof msgset);
4909 num_msgs = num_tokens(msgset, ',');
4911 cprintf("%d Nothing to do.\n", CIT_OK);
4915 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
4916 cprintf("%d Higher access required.\n",
4917 ERROR + HIGHER_ACCESS_REQUIRED);
4922 * Build our message set to be moved/copied
4924 msgs = malloc(num_msgs * sizeof(long));
4925 for (i=0; i<num_msgs; ++i) {
4926 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
4927 msgs[i] = atol(msgtok);
4930 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
4934 cprintf("%d %d message%s deleted.\n", CIT_OK,
4935 num_deleted, ((num_deleted != 1) ? "s" : ""));
4937 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
4945 * move or copy a message to another room
4947 void cmd_move(char *args)
4954 char targ[ROOMNAMELEN];
4955 struct ctdlroom qtemp;
4962 extract_token(msgset, args, 0, '|', sizeof msgset);
4963 num_msgs = num_tokens(msgset, ',');
4965 cprintf("%d Nothing to do.\n", CIT_OK);
4969 extract_token(targ, args, 1, '|', sizeof targ);
4970 convert_room_name_macros(targ, sizeof targ);
4971 targ[ROOMNAMELEN - 1] = 0;
4972 is_copy = extract_int(args, 2);
4974 if (CtdlGetRoom(&qtemp, targ) != 0) {
4975 cprintf("%d '%s' does not exist.\n", ERROR + ROOM_NOT_FOUND, targ);
4979 if (!strcasecmp(qtemp.QRname, CC->room.QRname)) {
4980 cprintf("%d Source and target rooms are the same.\n", ERROR + ALREADY_EXISTS);
4984 CtdlGetUser(&CC->user, CC->curr_user);
4985 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
4987 /* Check for permission to perform this operation.
4988 * Remember: "CC->room" is source, "qtemp" is target.
4992 /* Admins can move/copy */
4993 if (CC->user.axlevel >= AxAideU) permit = 1;
4995 /* Room aides can move/copy */
4996 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
4998 /* Permit move/copy from personal rooms */
4999 if ((CC->room.QRflags & QR_MAILBOX)
5000 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5002 /* Permit only copy from public to personal room */
5004 && (!(CC->room.QRflags & QR_MAILBOX))
5005 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5007 /* Permit message removal from collaborative delete rooms */
5008 if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
5010 /* Users allowed to post into the target room may move into it too. */
5011 if ((CC->room.QRflags & QR_MAILBOX) &&
5012 (qtemp.QRflags & UA_POSTALLOWED)) permit = 1;
5014 /* User must have access to target room */
5015 if (!(ra & UA_KNOWN)) permit = 0;
5018 cprintf("%d Higher access required.\n",
5019 ERROR + HIGHER_ACCESS_REQUIRED);
5024 * Build our message set to be moved/copied
5026 msgs = malloc(num_msgs * sizeof(long));
5027 for (i=0; i<num_msgs; ++i) {
5028 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
5029 msgs[i] = atol(msgtok);
5035 err = CtdlSaveMsgPointersInRoom(targ, msgs, num_msgs, 1, NULL, 0);
5037 cprintf("%d Cannot store message(s) in %s: error %d\n",
5043 /* Now delete the message from the source room,
5044 * if this is a 'move' rather than a 'copy' operation.
5047 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
5051 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
5057 * GetMetaData() - Get the supplementary record for a message
5059 void GetMetaData(struct MetaData *smibuf, long msgnum)
5062 struct cdbdata *cdbsmi;
5065 memset(smibuf, 0, sizeof(struct MetaData));
5066 smibuf->meta_msgnum = msgnum;
5067 smibuf->meta_refcount = 1; /* Default reference count is 1 */
5069 /* Use the negative of the message number for its supp record index */
5070 TheIndex = (0L - msgnum);
5072 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
5073 if (cdbsmi == NULL) {
5074 return; /* record not found; go with defaults */
5076 memcpy(smibuf, cdbsmi->ptr,
5077 ((cdbsmi->len > sizeof(struct MetaData)) ?
5078 sizeof(struct MetaData) : cdbsmi->len));
5085 * PutMetaData() - (re)write supplementary record for a message
5087 void PutMetaData(struct MetaData *smibuf)
5091 /* Use the negative of the message number for the metadata db index */
5092 TheIndex = (0L - smibuf->meta_msgnum);
5094 cdb_store(CDB_MSGMAIN,
5095 &TheIndex, (int)sizeof(long),
5096 smibuf, (int)sizeof(struct MetaData));
5101 * AdjRefCount - submit an adjustment to the reference count for a message.
5102 * (These are just queued -- we actually process them later.)
5104 void AdjRefCount(long msgnum, int incr)
5106 struct CitContext *CCC = CC;
5107 struct arcq new_arcq;
5110 MSG_syslog(LOG_DEBUG, "AdjRefCount() msg %ld ref count delta %+d\n", msgnum, incr);
5112 begin_critical_section(S_SUPPMSGMAIN);
5113 if (arcfp == NULL) {
5114 arcfp = fopen(file_arcq, "ab+");
5115 chown(file_arcq, CTDLUID, (-1));
5116 chmod(file_arcq, 0600);
5118 end_critical_section(S_SUPPMSGMAIN);
5120 /* msgnum < 0 means that we're trying to close the file */
5122 MSGM_syslog(LOG_DEBUG, "Closing the AdjRefCount queue file\n");
5123 begin_critical_section(S_SUPPMSGMAIN);
5124 if (arcfp != NULL) {
5128 end_critical_section(S_SUPPMSGMAIN);
5133 * If we can't open the queue, perform the operation synchronously.
5135 if (arcfp == NULL) {
5136 TDAP_AdjRefCount(msgnum, incr);
5140 new_arcq.arcq_msgnum = msgnum;
5141 new_arcq.arcq_delta = incr;
5142 rv = fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
5144 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5153 void AdjRefCountList(long *msgnum, long nmsg, int incr)
5155 struct CitContext *CCC = CC;
5156 long i, the_size, offset;
5157 struct arcq *new_arcq;
5160 MSG_syslog(LOG_DEBUG, "AdjRefCountList() msg %ld ref count delta %+d\n", nmsg, incr);
5162 begin_critical_section(S_SUPPMSGMAIN);
5163 if (arcfp == NULL) {
5164 arcfp = fopen(file_arcq, "ab+");
5165 chown(file_arcq, CTDLUID, (-1));
5166 chmod(file_arcq, 0600);
5168 end_critical_section(S_SUPPMSGMAIN);
5171 * If we can't open the queue, perform the operation synchronously.
5173 if (arcfp == NULL) {
5174 for (i = 0; i < nmsg; i++)
5175 TDAP_AdjRefCount(msgnum[i], incr);
5179 the_size = sizeof(struct arcq) * nmsg;
5180 new_arcq = malloc(the_size);
5181 for (i = 0; i < nmsg; i++) {
5182 new_arcq[i].arcq_msgnum = msgnum[i];
5183 new_arcq[i].arcq_delta = incr;
5187 while ((rv >= 0) && (offset < the_size))
5189 rv = fwrite(new_arcq + offset, 1, the_size - offset, arcfp);
5191 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5207 * TDAP_ProcessAdjRefCountQueue()
5209 * Process the queue of message count adjustments that was created by calls
5210 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
5211 * for each one. This should be an "off hours" operation.
5213 int TDAP_ProcessAdjRefCountQueue(void)
5215 struct CitContext *CCC = CC;
5216 char file_arcq_temp[PATH_MAX];
5219 struct arcq arcq_rec;
5220 int num_records_processed = 0;
5222 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s.%04x", file_arcq, rand());
5224 begin_critical_section(S_SUPPMSGMAIN);
5225 if (arcfp != NULL) {
5230 r = link(file_arcq, file_arcq_temp);
5232 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5233 end_critical_section(S_SUPPMSGMAIN);
5234 return(num_records_processed);
5238 end_critical_section(S_SUPPMSGMAIN);
5240 fp = fopen(file_arcq_temp, "rb");
5242 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5243 return(num_records_processed);
5246 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
5247 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
5248 ++num_records_processed;
5252 r = unlink(file_arcq_temp);
5254 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5257 return(num_records_processed);
5263 * TDAP_AdjRefCount - adjust the reference count for a message.
5264 * This one does it "for real" because it's called by
5265 * the autopurger function that processes the queue
5266 * created by AdjRefCount(). If a message's reference
5267 * count becomes zero, we also delete the message from
5268 * disk and de-index it.
5270 void TDAP_AdjRefCount(long msgnum, int incr)
5272 struct CitContext *CCC = CC;
5274 struct MetaData smi;
5277 /* This is a *tight* critical section; please keep it that way, as
5278 * it may get called while nested in other critical sections.
5279 * Complicating this any further will surely cause deadlock!
5281 begin_critical_section(S_SUPPMSGMAIN);
5282 GetMetaData(&smi, msgnum);
5283 smi.meta_refcount += incr;
5285 end_critical_section(S_SUPPMSGMAIN);
5286 MSG_syslog(LOG_DEBUG, "TDAP_AdjRefCount() msg %ld ref count delta %+d, is now %d\n",
5287 msgnum, incr, smi.meta_refcount
5290 /* If the reference count is now zero, delete the message
5291 * (and its supplementary record as well).
5293 if (smi.meta_refcount == 0) {
5294 MSG_syslog(LOG_DEBUG, "Deleting message <%ld>\n", msgnum);
5296 /* Call delete hooks with NULL room to show it has gone altogether */
5297 PerformDeleteHooks(NULL, msgnum);
5299 /* Remove from message base */
5301 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5302 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
5304 /* Remove metadata record */
5305 delnum = (0L - msgnum);
5306 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5312 * Write a generic object to this room
5314 * Note: this could be much more efficient. Right now we use two temporary
5315 * files, and still pull the message into memory as with all others.
5317 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
5318 char *content_type, /* MIME type of this object */
5319 char *raw_message, /* Data to be written */
5320 off_t raw_length, /* Size of raw_message */
5321 struct ctdluser *is_mailbox, /* Mailbox room? */
5322 int is_binary, /* Is encoding necessary? */
5323 int is_unique, /* Del others of this type? */
5324 unsigned int flags /* Internal save flags */
5327 struct CitContext *CCC = CC;
5328 struct ctdlroom qrbuf;
5329 char roomname[ROOMNAMELEN];
5330 struct CtdlMessage *msg;
5331 char *encoded_message = NULL;
5333 if (is_mailbox != NULL) {
5334 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
5337 safestrncpy(roomname, req_room, sizeof(roomname));
5340 MSG_syslog(LOG_DEBUG, "Raw length is %ld\n", (long)raw_length);
5343 encoded_message = malloc((size_t) (((raw_length * 134) / 100) + 4096 ) );
5346 encoded_message = malloc((size_t)(raw_length + 4096));
5349 sprintf(encoded_message, "Content-type: %s\n", content_type);
5352 sprintf(&encoded_message[strlen(encoded_message)],
5353 "Content-transfer-encoding: base64\n\n"
5357 sprintf(&encoded_message[strlen(encoded_message)],
5358 "Content-transfer-encoding: 7bit\n\n"
5364 &encoded_message[strlen(encoded_message)],
5372 &encoded_message[strlen(encoded_message)],
5378 MSGM_syslog(LOG_DEBUG, "Allocating\n");
5379 msg = malloc(sizeof(struct CtdlMessage));
5380 memset(msg, 0, sizeof(struct CtdlMessage));
5381 msg->cm_magic = CTDLMESSAGE_MAGIC;
5382 msg->cm_anon_type = MES_NORMAL;
5383 msg->cm_format_type = 4;
5384 msg->cm_fields['A'] = strdup(CCC->user.fullname);
5385 msg->cm_fields['O'] = strdup(req_room);
5386 msg->cm_fields['N'] = strdup(config.c_nodename);
5387 msg->cm_fields['H'] = strdup(config.c_humannode);
5388 msg->cm_flags = flags;
5390 msg->cm_fields['M'] = encoded_message;
5392 /* Create the requested room if we have to. */
5393 if (CtdlGetRoom(&qrbuf, roomname) != 0) {
5394 CtdlCreateRoom(roomname,
5395 ( (is_mailbox != NULL) ? 5 : 3 ),
5396 "", 0, 1, 0, VIEW_BBS);
5398 /* If the caller specified this object as unique, delete all
5399 * other objects of this type that are currently in the room.
5402 MSG_syslog(LOG_DEBUG, "Deleted %d other msgs of this type\n",
5403 CtdlDeleteMessages(roomname, NULL, 0, content_type)
5406 /* Now write the data */
5407 CtdlSubmitMsg(msg, NULL, roomname, 0);
5408 CtdlFreeMessage(msg);
5416 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
5417 config_msgnum = msgnum;
5421 char *CtdlGetSysConfig(char *sysconfname) {
5422 char hold_rm[ROOMNAMELEN];
5425 struct CtdlMessage *msg;
5428 strcpy(hold_rm, CC->room.QRname);
5429 if (CtdlGetRoom(&CC->room, SYSCONFIGROOM) != 0) {
5430 CtdlGetRoom(&CC->room, hold_rm);
5435 /* We want the last (and probably only) config in this room */
5436 begin_critical_section(S_CONFIG);
5437 config_msgnum = (-1L);
5438 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
5439 CtdlGetSysConfigBackend, NULL);
5440 msgnum = config_msgnum;
5441 end_critical_section(S_CONFIG);
5447 msg = CtdlFetchMessage(msgnum, 1);
5449 conf = strdup(msg->cm_fields['M']);
5450 CtdlFreeMessage(msg);
5457 CtdlGetRoom(&CC->room, hold_rm);
5459 if (conf != NULL) do {
5460 extract_token(buf, conf, 0, '\n', sizeof buf);
5461 strcpy(conf, &conf[strlen(buf)+1]);
5462 } while ( (!IsEmptyStr(conf)) && (!IsEmptyStr(buf)) );
5468 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
5469 CtdlWriteObject(SYSCONFIGROOM, sysconfname, sysconfdata, (strlen(sysconfdata)+1), NULL, 0, 1, 0);
5474 * Determine whether a given Internet address belongs to the current user
5476 int CtdlIsMe(char *addr, int addr_buf_len)
5478 struct recptypes *recp;
5481 recp = validate_recipients(addr, NULL, 0);
5482 if (recp == NULL) return(0);
5484 if (recp->num_local == 0) {
5485 free_recipients(recp);
5489 for (i=0; i<recp->num_local; ++i) {
5490 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
5491 if (!strcasecmp(addr, CC->user.fullname)) {
5492 free_recipients(recp);
5497 free_recipients(recp);
5503 * Citadel protocol command to do the same
5505 void cmd_isme(char *argbuf) {
5508 if (CtdlAccessCheck(ac_logged_in)) return;
5509 extract_token(addr, argbuf, 0, '|', sizeof addr);
5511 if (CtdlIsMe(addr, sizeof addr)) {
5512 cprintf("%d %s\n", CIT_OK, addr);
5515 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);
5521 /*****************************************************************************/
5522 /* MODULE INITIALIZATION STUFF */
5523 /*****************************************************************************/
5524 void SetMessageDebugEnabled(const int n)
5526 MessageDebugEnabled = n;
5528 CTDL_MODULE_INIT(msgbase)
5531 CtdlRegisterDebugFlagHook(HKEY("messages"), SetMessageDebugEnabled, &MessageDebugEnabled);
5533 CtdlRegisterProtoHook(cmd_msgs, "MSGS", "Output a list of messages in the current room");
5534 CtdlRegisterProtoHook(cmd_msg0, "MSG0", "Output a message in plain text format");
5535 CtdlRegisterProtoHook(cmd_msg2, "MSG2", "Output a message in RFC822 format");
5536 CtdlRegisterProtoHook(cmd_msg3, "MSG3", "Output a message in raw format (deprecated)");
5537 CtdlRegisterProtoHook(cmd_msg4, "MSG4", "Output a message in the client's preferred format");
5538 CtdlRegisterProtoHook(cmd_msgp, "MSGP", "Select preferred format for MSG4 output");
5539 CtdlRegisterProtoHook(cmd_opna, "OPNA", "Open an attachment for download");
5540 CtdlRegisterProtoHook(cmd_dlat, "DLAT", "Download an attachment");
5541 CtdlRegisterProtoHook(cmd_ent0, "ENT0", "Enter a message");
5542 CtdlRegisterProtoHook(cmd_dele, "DELE", "Delete a message");
5543 CtdlRegisterProtoHook(cmd_move, "MOVE", "Move or copy a message to another room");
5544 CtdlRegisterProtoHook(cmd_isme, "ISME", "Determine whether an email address belongs to a user");
5547 /* return our Subversion id for the Log */