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) );
3601 if (cdbut != NULL) return;
3602 /* no, this message isn't sent recently; go ahead. */
3603 quickie_message(from,
3614 * Back end function used by CtdlMakeMessage() and similar functions
3616 StrBuf *CtdlReadMessageBodyBuf(char *terminator, /* token signalling EOT */
3618 size_t maxlen, /* maximum message length */
3619 char *exist, /* if non-null, append to it;
3620 exist is ALWAYS freed */
3621 int crlf, /* CRLF newlines instead of LF */
3622 int *sock /* socket handle or 0 for this session's client socket */
3631 LineBuf = NewStrBufPlain(NULL, SIZ);
3632 if (exist == NULL) {
3633 Message = NewStrBufPlain(NULL, 4 * SIZ);
3636 Message = NewStrBufPlain(exist, -1);
3640 /* Do we need to change leading ".." to "." for SMTP escaping? */
3641 if ((tlen == 1) && (*terminator == '.')) {
3645 /* read in the lines of message text one by one */
3648 if ((CtdlSockGetLine(sock, LineBuf, 5) < 0) ||
3653 if (CtdlClientGetLine(LineBuf) < 0) finished = 1;
3655 if ((StrLength(LineBuf) == tlen) &&
3656 (!strcmp(ChrPtr(LineBuf), terminator)))
3659 if ( (!flushing) && (!finished) ) {
3661 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3664 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3667 /* Unescape SMTP-style input of two dots at the beginning of the line */
3669 (StrLength(LineBuf) == 2) &&
3670 (!strcmp(ChrPtr(LineBuf), "..")))
3672 StrBufCutLeft(LineBuf, 1);
3675 StrBufAppendBuf(Message, LineBuf, 0);
3678 /* if we've hit the max msg length, flush the rest */
3679 if (StrLength(Message) >= maxlen) flushing = 1;
3681 } while (!finished);
3682 FreeStrBuf(&LineBuf);
3686 void DeleteAsyncMsg(ReadAsyncMsg **Msg)
3690 FreeStrBuf(&(*Msg)->MsgBuf);
3696 ReadAsyncMsg *NewAsyncMsg(const char *terminator, /* token signalling EOT */
3698 size_t maxlen, /* maximum message length */
3699 size_t expectlen, /* if we expect a message, how long should it be? */
3700 char *exist, /* if non-null, append to it;
3701 exist is ALWAYS freed */
3702 long eLen, /* length of exist */
3703 int crlf /* CRLF newlines instead of LF */
3706 ReadAsyncMsg *NewMsg;
3708 NewMsg = (ReadAsyncMsg *)malloc(sizeof(ReadAsyncMsg));
3709 memset(NewMsg, 0, sizeof(ReadAsyncMsg));
3711 if (exist == NULL) {
3714 if (expectlen == 0) {
3718 len = expectlen + 10;
3720 NewMsg->MsgBuf = NewStrBufPlain(NULL, len);
3723 NewMsg->MsgBuf = NewStrBufPlain(exist, eLen);
3726 /* Do we need to change leading ".." to "." for SMTP escaping? */
3727 if ((tlen == 1) && (*terminator == '.')) {
3731 NewMsg->terminator = terminator;
3732 NewMsg->tlen = tlen;
3734 NewMsg->maxlen = maxlen;
3736 NewMsg->crlf = crlf;
3742 * Back end function used by CtdlMakeMessage() and similar functions
3744 eReadState CtdlReadMessageBodyAsync(AsyncIO *IO)
3746 ReadAsyncMsg *ReadMsg;
3747 int MsgFinished = 0;
3748 eReadState Finished = eMustReadMore;
3753 const char *pch = ChrPtr(IO->SendBuf.Buf);
3754 const char *pchh = IO->SendBuf.ReadWritePointer;
3760 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
3761 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
3762 ((CitContext*)(IO->CitContext))->ServiceName,
3765 fd = fopen(fn, "a+");
3768 ReadMsg = IO->ReadMsg;
3770 /* read in the lines of message text one by one */
3772 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
3775 case eMustReadMore: /// read new from socket...
3777 if (IO->RecvBuf.ReadWritePointer != NULL) {
3778 nbytes = StrLength(IO->RecvBuf.Buf) - (IO->RecvBuf.ReadWritePointer - ChrPtr(IO->RecvBuf.Buf));
3779 fprintf(fd, "Read; Line unfinished: %ld Bytes still in buffer [", nbytes);
3781 fwrite(IO->RecvBuf.ReadWritePointer, nbytes, 1, fd);
3785 fprintf(fd, "BufferEmpty! \n");
3791 case eBufferNotEmpty: /* shouldn't happen... */
3792 case eReadSuccess: /// done for now...
3794 case eReadFail: /// WHUT?
3800 if ((StrLength(IO->IOBuf) == ReadMsg->tlen) &&
3801 (!strcmp(ChrPtr(IO->IOBuf), ReadMsg->terminator))) {
3804 fprintf(fd, "found Terminator; Message Size: %d\n", StrLength(ReadMsg->MsgBuf));
3807 else if (!ReadMsg->flushing) {
3810 fprintf(fd, "Read Line: [%d][%s]\n", StrLength(IO->IOBuf), ChrPtr(IO->IOBuf));
3813 /* Unescape SMTP-style input of two dots at the beginning of the line */
3814 if ((ReadMsg->dodot) &&
3815 (StrLength(IO->IOBuf) == 2) && /* TODO: do we just unescape lines with two dots or any line? */
3816 (!strcmp(ChrPtr(IO->IOBuf), "..")))
3819 fprintf(fd, "UnEscaped!\n");
3821 StrBufCutLeft(IO->IOBuf, 1);
3824 if (ReadMsg->crlf) {
3825 StrBufAppendBufPlain(IO->IOBuf, HKEY("\r\n"), 0);
3828 StrBufAppendBufPlain(IO->IOBuf, HKEY("\n"), 0);
3831 StrBufAppendBuf(ReadMsg->MsgBuf, IO->IOBuf, 0);
3834 /* if we've hit the max msg length, flush the rest */
3835 if (StrLength(ReadMsg->MsgBuf) >= ReadMsg->maxlen) ReadMsg->flushing = 1;
3837 } while (!MsgFinished);
3840 fprintf(fd, "Done with reading; %s.\n, ",
3841 (MsgFinished)?"Message Finished": "FAILED");
3845 return eReadSuccess;
3852 * Back end function used by CtdlMakeMessage() and similar functions
3854 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
3856 size_t maxlen, /* maximum message length */
3857 char *exist, /* if non-null, append to it;
3858 exist is ALWAYS freed */
3859 int crlf, /* CRLF newlines instead of LF */
3860 int *sock /* socket handle or 0 for this session's client socket */
3865 Message = CtdlReadMessageBodyBuf(terminator,
3871 if (Message == NULL)
3874 return SmashStrBuf(&Message);
3879 * Build a binary message to be saved on disk.
3880 * (NOTE: if you supply 'preformatted_text', the buffer you give it
3881 * will become part of the message. This means you are no longer
3882 * responsible for managing that memory -- it will be freed along with
3883 * the rest of the fields when CtdlFreeMessage() is called.)
3886 struct CtdlMessage *CtdlMakeMessage(
3887 struct ctdluser *author, /* author's user structure */
3888 char *recipient, /* NULL if it's not mail */
3889 char *recp_cc, /* NULL if it's not mail */
3890 char *room, /* room where it's going */
3891 int type, /* see MES_ types in header file */
3892 int format_type, /* variformat, plain text, MIME... */
3893 char *fake_name, /* who we're masquerading as */
3894 char *my_email, /* which of my email addresses to use (empty is ok) */
3895 char *subject, /* Subject (optional) */
3896 char *supplied_euid, /* ...or NULL if this is irrelevant */
3897 char *preformatted_text, /* ...or NULL to read text from client */
3898 char *references /* Thread references */
3900 char dest_node[256];
3902 struct CtdlMessage *msg;
3904 StrBuf *FakeEncAuthor = NULL;
3906 msg = malloc(sizeof(struct CtdlMessage));
3907 memset(msg, 0, sizeof(struct CtdlMessage));
3908 msg->cm_magic = CTDLMESSAGE_MAGIC;
3909 msg->cm_anon_type = type;
3910 msg->cm_format_type = format_type;
3912 /* Don't confuse the poor folks if it's not routed mail. */
3913 strcpy(dest_node, "");
3915 if (recipient != NULL) striplt(recipient);
3916 if (recp_cc != NULL) striplt(recp_cc);
3918 /* Path or Return-Path */
3919 if (my_email == NULL) my_email = "";
3921 if (!IsEmptyStr(my_email)) {
3922 msg->cm_fields['P'] = strdup(my_email);
3925 snprintf(buf, sizeof buf, "%s", author->fullname);
3926 msg->cm_fields['P'] = strdup(buf);
3928 convert_spaces_to_underscores(msg->cm_fields['P']);
3930 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
3931 msg->cm_fields['T'] = strdup(buf);
3933 if ((fake_name != NULL) && (fake_name[0])) { /* author */
3934 FakeAuthor = NewStrBufPlain (fake_name, -1);
3937 FakeAuthor = NewStrBufPlain (author->fullname, -1);
3939 StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
3940 msg->cm_fields['A'] = SmashStrBuf(&FakeEncAuthor);
3941 FreeStrBuf(&FakeAuthor);
3943 if (CC->room.QRflags & QR_MAILBOX) { /* room */
3944 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
3947 msg->cm_fields['O'] = strdup(CC->room.QRname);
3950 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
3951 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
3953 if ((recipient != NULL) && (recipient[0] != 0)) {
3954 msg->cm_fields['R'] = strdup(recipient);
3956 if ((recp_cc != NULL) && (recp_cc[0] != 0)) {
3957 msg->cm_fields['Y'] = strdup(recp_cc);
3959 if (dest_node[0] != 0) {
3960 msg->cm_fields['D'] = strdup(dest_node);
3963 if (!IsEmptyStr(my_email)) {
3964 msg->cm_fields['F'] = strdup(my_email);
3966 else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
3967 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
3970 if (subject != NULL) {
3973 length = strlen(subject);
3979 while ((subject[i] != '\0') &&
3980 (IsAscii = isascii(subject[i]) != 0 ))
3983 msg->cm_fields['U'] = strdup(subject);
3984 else /* ok, we've got utf8 in the string. */
3986 msg->cm_fields['U'] = rfc2047encode(subject, length);
3992 if (supplied_euid != NULL) {
3993 msg->cm_fields['E'] = strdup(supplied_euid);
3996 if ((references != NULL) && (!IsEmptyStr(references))) {
3997 if (msg->cm_fields['W'] != NULL)
3998 free(msg->cm_fields['W']);
3999 msg->cm_fields['W'] = strdup(references);
4002 if (preformatted_text != NULL) {
4003 msg->cm_fields['M'] = preformatted_text;
4006 msg->cm_fields['M'] = CtdlReadMessageBody(HKEY("000"), config.c_maxmsglen, NULL, 0, 0);
4012 extern int netconfig_check_roomaccess(
4015 const char* RemoteIdentifier); /* TODO: find a smarter way */
4018 * Check to see whether we have permission to post a message in the current
4019 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
4020 * returns 0 on success.
4022 int CtdlDoIHavePermissionToPostInThisRoom(
4025 const char* RemoteIdentifier,
4031 if (!(CC->logged_in) &&
4032 (PostPublic == POST_LOGGED_IN)) {
4033 snprintf(errmsgbuf, n, "Not logged in.");
4034 return (ERROR + NOT_LOGGED_IN);
4036 else if (PostPublic == CHECK_EXISTANCE) {
4037 return (0); // We're Evaling whether a recipient exists
4039 else if (!(CC->logged_in)) {
4041 if ((CC->room.QRflags & QR_READONLY)) {
4042 snprintf(errmsgbuf, n, "Not logged in.");
4043 return (ERROR + NOT_LOGGED_IN);
4045 if (CC->room.QRflags2 & QR2_MODERATED) {
4046 snprintf(errmsgbuf, n, "Not logged in Moderation feature not yet implemented!");
4047 return (ERROR + NOT_LOGGED_IN);
4049 if ((PostPublic!=POST_LMTP) &&(CC->room.QRflags2 & QR2_SMTP_PUBLIC) == 0) {
4051 return netconfig_check_roomaccess(errmsgbuf, n, RemoteIdentifier);
4057 if ((CC->user.axlevel < AxProbU)
4058 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
4059 snprintf(errmsgbuf, n, "Need to be validated to enter (except in %s> to sysop)", MAILROOM);
4060 return (ERROR + HIGHER_ACCESS_REQUIRED);
4063 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
4065 if (ra & UA_POSTALLOWED) {
4066 strcpy(errmsgbuf, "OK to post or reply here");
4070 if ( (ra & UA_REPLYALLOWED) && (is_reply) ) {
4072 * To be thorough, we ought to check to see if the message they are
4073 * replying to is actually a valid one in this room, but unless this
4074 * actually becomes a problem we'll go with high performance instead.
4076 strcpy(errmsgbuf, "OK to reply here");
4080 if ( (ra & UA_REPLYALLOWED) && (!is_reply) ) {
4081 /* Clarify what happened with a better error message */
4082 snprintf(errmsgbuf, n, "You may only reply to existing messages here.");
4083 return (ERROR + HIGHER_ACCESS_REQUIRED);
4086 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
4087 return (ERROR + HIGHER_ACCESS_REQUIRED);
4093 * Check to see if the specified user has Internet mail permission
4094 * (returns nonzero if permission is granted)
4096 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
4098 /* Do not allow twits to send Internet mail */
4099 if (who->axlevel <= AxProbU) return(0);
4101 /* Globally enabled? */
4102 if (config.c_restrict == 0) return(1);
4104 /* User flagged ok? */
4105 if (who->flags & US_INTERNET) return(2);
4107 /* Admin level access? */
4108 if (who->axlevel >= AxAideU) return(3);
4110 /* No mail for you! */
4116 * Validate recipients, count delivery types and errors, and handle aliasing
4117 * FIXME check for dupes!!!!!
4119 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
4120 * were specified, or the number of addresses found invalid.
4122 * Caller needs to free the result using free_recipients()
4124 struct recptypes *validate_recipients(const char *supplied_recipients,
4125 const char *RemoteIdentifier,
4127 struct CitContext *CCC = CC;
4128 struct recptypes *ret;
4129 char *recipients = NULL;
4131 char this_recp[256];
4132 char this_recp_cooked[256];
4139 struct ctdluser tempUS;
4140 struct ctdlroom tempQR;
4141 struct ctdlroom tempQR2;
4147 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
4148 if (ret == NULL) return(NULL);
4150 /* Set all strings to null and numeric values to zero */
4151 memset(ret, 0, sizeof(struct recptypes));
4153 if (supplied_recipients == NULL) {
4154 recipients = strdup("");
4157 recipients = strdup(supplied_recipients);
4160 /* Allocate some memory. Yes, this allocates 500% more memory than we will
4161 * actually need, but it's healthier for the heap than doing lots of tiny
4162 * realloc() calls instead.
4164 len = strlen(recipients) + 1024;
4165 ret->errormsg = malloc(len);
4166 ret->recp_local = malloc(len);
4167 ret->recp_internet = malloc(len);
4168 ret->recp_ignet = malloc(len);
4169 ret->recp_room = malloc(len);
4170 ret->display_recp = malloc(len);
4171 ret->recp_orgroom = malloc(len);
4172 org_recp = malloc(len);
4174 ret->errormsg[0] = 0;
4175 ret->recp_local[0] = 0;
4176 ret->recp_internet[0] = 0;
4177 ret->recp_ignet[0] = 0;
4178 ret->recp_room[0] = 0;
4179 ret->recp_orgroom[0] = 0;
4180 ret->display_recp[0] = 0;
4182 ret->recptypes_magic = RECPTYPES_MAGIC;
4184 /* Change all valid separator characters to commas */
4185 for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
4186 if ((recipients[i] == ';') || (recipients[i] == '|')) {
4187 recipients[i] = ',';
4191 /* Now start extracting recipients... */
4193 while (!IsEmptyStr(recipients)) {
4194 for (i=0; i<=strlen(recipients); ++i) {
4195 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
4196 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
4197 safestrncpy(this_recp, recipients, i+1);
4199 if (recipients[i] == ',') {
4200 strcpy(recipients, &recipients[i+1]);
4203 strcpy(recipients, "");
4210 if (IsEmptyStr(this_recp))
4212 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
4215 strcpy(org_recp, this_recp);
4218 mailtype = alias(this_recp);
4220 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
4221 if (this_recp[j]=='_') {
4222 this_recp_cooked[j] = ' ';
4225 this_recp_cooked[j] = this_recp[j];
4228 this_recp_cooked[j] = '\0';
4233 if (!strcasecmp(this_recp, "sysop")) {
4235 strcpy(this_recp, config.c_aideroom);
4236 if (!IsEmptyStr(ret->recp_room)) {
4237 strcat(ret->recp_room, "|");
4239 strcat(ret->recp_room, this_recp);
4241 else if ( (!strncasecmp(this_recp, "room_", 5))
4242 && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
4244 /* Save room so we can restore it later */
4245 tempQR2 = CCC->room;
4248 /* Check permissions to send mail to this room */
4249 err = CtdlDoIHavePermissionToPostInThisRoom(
4254 0 /* 0 = not a reply */
4263 if (!IsEmptyStr(ret->recp_room)) {
4264 strcat(ret->recp_room, "|");
4266 strcat(ret->recp_room, &this_recp_cooked[5]);
4268 if (!IsEmptyStr(ret->recp_orgroom)) {
4269 strcat(ret->recp_orgroom, "|");
4271 strcat(ret->recp_orgroom, org_recp);
4275 /* Restore room in case something needs it */
4276 CCC->room = tempQR2;
4279 else if (CtdlGetUser(&tempUS, this_recp) == 0) {
4281 strcpy(this_recp, tempUS.fullname);
4282 if (!IsEmptyStr(ret->recp_local)) {
4283 strcat(ret->recp_local, "|");
4285 strcat(ret->recp_local, this_recp);
4287 else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
4289 strcpy(this_recp, tempUS.fullname);
4290 if (!IsEmptyStr(ret->recp_local)) {
4291 strcat(ret->recp_local, "|");
4293 strcat(ret->recp_local, this_recp);
4301 /* Yes, you're reading this correctly: if the target
4302 * domain points back to the local system or an attached
4303 * Citadel directory, the address is invalid. That's
4304 * because if the address were valid, we would have
4305 * already translated it to a local address by now.
4307 if (IsDirectory(this_recp, 0)) {
4312 ++ret->num_internet;
4313 if (!IsEmptyStr(ret->recp_internet)) {
4314 strcat(ret->recp_internet, "|");
4316 strcat(ret->recp_internet, this_recp);
4321 if (!IsEmptyStr(ret->recp_ignet)) {
4322 strcat(ret->recp_ignet, "|");
4324 strcat(ret->recp_ignet, this_recp);
4332 if (IsEmptyStr(errmsg)) {
4333 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
4336 snprintf(append, sizeof append, "%s", errmsg);
4338 if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
4339 if (!IsEmptyStr(ret->errormsg)) {
4340 strcat(ret->errormsg, "; ");
4342 strcat(ret->errormsg, append);
4346 if (IsEmptyStr(ret->display_recp)) {
4347 strcpy(append, this_recp);
4350 snprintf(append, sizeof append, ", %s", this_recp);
4352 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
4353 strcat(ret->display_recp, append);
4359 if ((ret->num_local + ret->num_internet + ret->num_ignet +
4360 ret->num_room + ret->num_error) == 0) {
4361 ret->num_error = (-1);
4362 strcpy(ret->errormsg, "No recipients specified.");
4365 MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
4366 MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
4367 MSG_syslog(LOG_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
4368 MSG_syslog(LOG_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
4369 MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
4370 MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
4378 * Destructor for struct recptypes
4380 void free_recipients(struct recptypes *valid) {
4382 if (valid == NULL) {
4386 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
4387 struct CitContext *CCC = CC;
4388 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
4392 if (valid->errormsg != NULL) free(valid->errormsg);
4393 if (valid->recp_local != NULL) free(valid->recp_local);
4394 if (valid->recp_internet != NULL) free(valid->recp_internet);
4395 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
4396 if (valid->recp_room != NULL) free(valid->recp_room);
4397 if (valid->recp_orgroom != NULL) free(valid->recp_orgroom);
4398 if (valid->display_recp != NULL) free(valid->display_recp);
4399 if (valid->bounce_to != NULL) free(valid->bounce_to);
4400 if (valid->envelope_from != NULL) free(valid->envelope_from);
4401 if (valid->sending_room != NULL) free(valid->sending_room);
4408 * message entry - mode 0 (normal)
4410 void cmd_ent0(char *entargs)
4412 struct CitContext *CCC = CC;
4417 char supplied_euid[128];
4419 int format_type = 0;
4420 char newusername[256];
4421 char newuseremail[256];
4422 struct CtdlMessage *msg;
4426 struct recptypes *valid = NULL;
4427 struct recptypes *valid_to = NULL;
4428 struct recptypes *valid_cc = NULL;
4429 struct recptypes *valid_bcc = NULL;
4431 int subject_required = 0;
4436 int newuseremail_ok = 0;
4437 char references[SIZ];
4442 post = extract_int(entargs, 0);
4443 extract_token(recp, entargs, 1, '|', sizeof recp);
4444 anon_flag = extract_int(entargs, 2);
4445 format_type = extract_int(entargs, 3);
4446 extract_token(subject, entargs, 4, '|', sizeof subject);
4447 extract_token(newusername, entargs, 5, '|', sizeof newusername);
4448 do_confirm = extract_int(entargs, 6);
4449 extract_token(cc, entargs, 7, '|', sizeof cc);
4450 extract_token(bcc, entargs, 8, '|', sizeof bcc);
4451 switch(CC->room.QRdefaultview) {
4454 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
4457 supplied_euid[0] = 0;
4460 extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
4461 extract_token(references, entargs, 11, '|', sizeof references);
4462 for (ptr=references; *ptr != 0; ++ptr) {
4463 if (*ptr == '!') *ptr = '|';
4466 /* first check to make sure the request is valid. */
4468 err = CtdlDoIHavePermissionToPostInThisRoom(
4473 (!IsEmptyStr(references)) /* is this a reply? or a top-level post? */
4477 cprintf("%d %s\n", err, errmsg);
4481 /* Check some other permission type things. */
4483 if (IsEmptyStr(newusername)) {
4484 strcpy(newusername, CCC->user.fullname);
4486 if ( (CCC->user.axlevel < AxAideU)
4487 && (strcasecmp(newusername, CCC->user.fullname))
4488 && (strcasecmp(newusername, CCC->cs_inet_fn))
4490 cprintf("%d You don't have permission to author messages as '%s'.\n",
4491 ERROR + HIGHER_ACCESS_REQUIRED,
4498 if (IsEmptyStr(newuseremail)) {
4499 newuseremail_ok = 1;
4502 if (!IsEmptyStr(newuseremail)) {
4503 if (!strcasecmp(newuseremail, CCC->cs_inet_email)) {
4504 newuseremail_ok = 1;
4506 else if (!IsEmptyStr(CCC->cs_inet_other_emails)) {
4507 j = num_tokens(CCC->cs_inet_other_emails, '|');
4508 for (i=0; i<j; ++i) {
4509 extract_token(buf, CCC->cs_inet_other_emails, i, '|', sizeof buf);
4510 if (!strcasecmp(newuseremail, buf)) {
4511 newuseremail_ok = 1;
4517 if (!newuseremail_ok) {
4518 cprintf("%d You don't have permission to author messages as '%s'.\n",
4519 ERROR + HIGHER_ACCESS_REQUIRED,
4525 CCC->cs_flags |= CS_POSTING;
4527 /* In mailbox rooms we have to behave a little differently --
4528 * make sure the user has specified at least one recipient. Then
4529 * validate the recipient(s). We do this for the Mail> room, as
4530 * well as any room which has the "Mailbox" view set - unless it
4531 * is the DRAFTS room which does not require recipients
4534 if ( ( ( (CCC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CCC->room.QRname[11], MAILROOM)) )
4535 || ( (CCC->room.QRflags & QR_MAILBOX) && (CCC->curr_view == VIEW_MAILBOX) )
4536 ) && (strcasecmp(&CCC->room.QRname[11], USERDRAFTROOM)) !=0 ) {
4537 if (CCC->user.axlevel < AxProbU) {
4538 strcpy(recp, "sysop");
4543 valid_to = validate_recipients(recp, NULL, 0);
4544 if (valid_to->num_error > 0) {
4545 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_to->errormsg);
4546 free_recipients(valid_to);
4550 valid_cc = validate_recipients(cc, NULL, 0);
4551 if (valid_cc->num_error > 0) {
4552 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_cc->errormsg);
4553 free_recipients(valid_to);
4554 free_recipients(valid_cc);
4558 valid_bcc = validate_recipients(bcc, NULL, 0);
4559 if (valid_bcc->num_error > 0) {
4560 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_bcc->errormsg);
4561 free_recipients(valid_to);
4562 free_recipients(valid_cc);
4563 free_recipients(valid_bcc);
4567 /* Recipient required, but none were specified */
4568 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
4569 free_recipients(valid_to);
4570 free_recipients(valid_cc);
4571 free_recipients(valid_bcc);
4572 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
4576 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
4577 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
4578 cprintf("%d You do not have permission "
4579 "to send Internet mail.\n",
4580 ERROR + HIGHER_ACCESS_REQUIRED);
4581 free_recipients(valid_to);
4582 free_recipients(valid_cc);
4583 free_recipients(valid_bcc);
4588 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)
4589 && (CCC->user.axlevel < AxNetU) ) {
4590 cprintf("%d Higher access required for network mail.\n",
4591 ERROR + HIGHER_ACCESS_REQUIRED);
4592 free_recipients(valid_to);
4593 free_recipients(valid_cc);
4594 free_recipients(valid_bcc);
4598 if ((RESTRICT_INTERNET == 1)
4599 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
4600 && ((CCC->user.flags & US_INTERNET) == 0)
4601 && (!CCC->internal_pgm)) {
4602 cprintf("%d You don't have access to Internet mail.\n",
4603 ERROR + HIGHER_ACCESS_REQUIRED);
4604 free_recipients(valid_to);
4605 free_recipients(valid_cc);
4606 free_recipients(valid_bcc);
4612 /* Is this a room which has anonymous-only or anonymous-option? */
4613 anonymous = MES_NORMAL;
4614 if (CCC->room.QRflags & QR_ANONONLY) {
4615 anonymous = MES_ANONONLY;
4617 if (CCC->room.QRflags & QR_ANONOPT) {
4618 if (anon_flag == 1) { /* only if the user requested it */
4619 anonymous = MES_ANONOPT;
4623 if ((CCC->room.QRflags & QR_MAILBOX) == 0) {
4627 /* Recommend to the client that the use of a message subject is
4628 * strongly recommended in this room, if either the SUBJECTREQ flag
4629 * is set, or if there is one or more Internet email recipients.
4631 if (CCC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
4632 if ((valid_to) && (valid_to->num_internet > 0)) subject_required = 1;
4633 if ((valid_cc) && (valid_cc->num_internet > 0)) subject_required = 1;
4634 if ((valid_bcc) && (valid_bcc->num_internet > 0)) subject_required = 1;
4636 /* If we're only checking the validity of the request, return
4637 * success without creating the message.
4640 cprintf("%d %s|%d\n", CIT_OK,
4641 ((valid_to != NULL) ? valid_to->display_recp : ""),
4643 free_recipients(valid_to);
4644 free_recipients(valid_cc);
4645 free_recipients(valid_bcc);
4649 /* We don't need these anymore because we'll do it differently below */
4650 free_recipients(valid_to);
4651 free_recipients(valid_cc);
4652 free_recipients(valid_bcc);
4654 /* Read in the message from the client. */
4656 cprintf("%d send message\n", START_CHAT_MODE);
4658 cprintf("%d send message\n", SEND_LISTING);
4661 msg = CtdlMakeMessage(&CCC->user, recp, cc,
4662 CCC->room.QRname, anonymous, format_type,
4663 newusername, newuseremail, subject,
4664 ((!IsEmptyStr(supplied_euid)) ? supplied_euid : NULL),
4667 /* Put together one big recipients struct containing to/cc/bcc all in
4668 * one. This is for the envelope.
4670 char *all_recps = malloc(SIZ * 3);
4671 strcpy(all_recps, recp);
4672 if (!IsEmptyStr(cc)) {
4673 if (!IsEmptyStr(all_recps)) {
4674 strcat(all_recps, ",");
4676 strcat(all_recps, cc);
4678 if (!IsEmptyStr(bcc)) {
4679 if (!IsEmptyStr(all_recps)) {
4680 strcat(all_recps, ",");
4682 strcat(all_recps, bcc);
4684 if (!IsEmptyStr(all_recps)) {
4685 valid = validate_recipients(all_recps, NULL, 0);
4692 if ((valid != NULL) && (valid->num_room == 1))
4694 /* posting into an ML room? set the envelope from
4695 * to the actual mail address so others get a valid
4698 msg->cm_fields['V'] = strdup(valid->recp_orgroom);
4702 msgnum = CtdlSubmitMsg(msg, valid, "", QP_EADDR);
4704 cprintf("%ld\n", msgnum);
4706 if (StrLength(CCC->StatusMessage) > 0) {
4707 cprintf("%s\n", ChrPtr(CCC->StatusMessage));
4709 else if (msgnum >= 0L) {
4710 client_write(HKEY("Message accepted.\n"));
4713 client_write(HKEY("Internal error.\n"));
4716 if (msg->cm_fields['E'] != NULL) {
4717 cprintf("%s\n", msg->cm_fields['E']);
4724 CtdlFreeMessage(msg);
4726 if (valid != NULL) {
4727 free_recipients(valid);
4735 * API function to delete messages which match a set of criteria
4736 * (returns the actual number of messages deleted)
4738 int CtdlDeleteMessages(char *room_name, /* which room */
4739 long *dmsgnums, /* array of msg numbers to be deleted */
4740 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
4741 char *content_type /* or "" for any. regular expressions expected. */
4744 struct CitContext *CCC = CC;
4745 struct ctdlroom qrbuf;
4746 struct cdbdata *cdbfr;
4747 long *msglist = NULL;
4748 long *dellist = NULL;
4751 int num_deleted = 0;
4753 struct MetaData smi;
4756 int need_to_free_re = 0;
4758 if (content_type) if (!IsEmptyStr(content_type)) {
4759 regcomp(&re, content_type, 0);
4760 need_to_free_re = 1;
4762 MSG_syslog(LOG_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
4763 room_name, num_dmsgnums, content_type);
4765 /* get room record, obtaining a lock... */
4766 if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
4767 MSG_syslog(LOG_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
4769 if (need_to_free_re) regfree(&re);
4770 return (0); /* room not found */
4772 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
4774 if (cdbfr != NULL) {
4775 dellist = malloc(cdbfr->len);
4776 msglist = (long *) cdbfr->ptr;
4777 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
4778 num_msgs = cdbfr->len / sizeof(long);
4782 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
4783 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
4784 int have_more_del = 1;
4786 num_msgs = sort_msglist(msglist, num_msgs);
4787 if (num_dmsgnums > 1)
4788 num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
4791 StrBuf *dbg = NewStrBuf();
4792 for (i = 0; i < num_dmsgnums; i++)
4793 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
4794 MSG_syslog(LOG_DEBUG, "Deleting before: %s", ChrPtr(dbg));
4799 while ((i < num_msgs) && (have_more_del)) {
4803 /* Set/clear a bit for each criterion */
4805 /* 0 messages in the list or a null list means that we are
4806 * interested in deleting any messages which meet the other criteria.
4809 delete_this |= 0x01;
4812 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
4813 if (msglist[i] == dmsgnums[j]) {
4814 delete_this |= 0x01;
4817 have_more_del = (j < num_dmsgnums);
4820 if (have_contenttype) {
4821 GetMetaData(&smi, msglist[i]);
4822 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
4823 delete_this |= 0x02;
4826 delete_this |= 0x02;
4829 /* Delete message only if all bits are set */
4830 if (delete_this == 0x03) {
4831 dellist[num_deleted++] = msglist[i];
4838 StrBuf *dbg = NewStrBuf();
4839 for (i = 0; i < num_deleted; i++)
4840 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
4841 MSG_syslog(LOG_DEBUG, "Deleting: %s", ChrPtr(dbg));
4845 num_msgs = sort_msglist(msglist, num_msgs);
4846 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
4847 msglist, (int)(num_msgs * sizeof(long)));
4850 qrbuf.QRhighest = msglist[num_msgs - 1];
4852 qrbuf.QRhighest = 0;
4854 CtdlPutRoomLock(&qrbuf);
4856 /* Go through the messages we pulled out of the index, and decrement
4857 * their reference counts by 1. If this is the only room the message
4858 * was in, the reference count will reach zero and the message will
4859 * automatically be deleted from the database. We do this in a
4860 * separate pass because there might be plug-in hooks getting called,
4861 * and we don't want that happening during an S_ROOMS critical
4865 for (i=0; i<num_deleted; ++i) {
4866 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
4868 AdjRefCountList(dellist, num_deleted, -1);
4870 /* Now free the memory we used, and go away. */
4871 if (msglist != NULL) free(msglist);
4872 if (dellist != NULL) free(dellist);
4873 MSG_syslog(LOG_DEBUG, "%d message(s) deleted.\n", num_deleted);
4874 if (need_to_free_re) regfree(&re);
4875 return (num_deleted);
4881 * Check whether the current user has permission to delete messages from
4882 * the current room (returns 1 for yes, 0 for no)
4884 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
4886 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
4887 if (ra & UA_DELETEALLOWED) return(1);
4895 * Delete message from current room
4897 void cmd_dele(char *args)
4906 extract_token(msgset, args, 0, '|', sizeof msgset);
4907 num_msgs = num_tokens(msgset, ',');
4909 cprintf("%d Nothing to do.\n", CIT_OK);
4913 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
4914 cprintf("%d Higher access required.\n",
4915 ERROR + HIGHER_ACCESS_REQUIRED);
4920 * Build our message set to be moved/copied
4922 msgs = malloc(num_msgs * sizeof(long));
4923 for (i=0; i<num_msgs; ++i) {
4924 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
4925 msgs[i] = atol(msgtok);
4928 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
4932 cprintf("%d %d message%s deleted.\n", CIT_OK,
4933 num_deleted, ((num_deleted != 1) ? "s" : ""));
4935 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
4943 * move or copy a message to another room
4945 void cmd_move(char *args)
4952 char targ[ROOMNAMELEN];
4953 struct ctdlroom qtemp;
4960 extract_token(msgset, args, 0, '|', sizeof msgset);
4961 num_msgs = num_tokens(msgset, ',');
4963 cprintf("%d Nothing to do.\n", CIT_OK);
4967 extract_token(targ, args, 1, '|', sizeof targ);
4968 convert_room_name_macros(targ, sizeof targ);
4969 targ[ROOMNAMELEN - 1] = 0;
4970 is_copy = extract_int(args, 2);
4972 if (CtdlGetRoom(&qtemp, targ) != 0) {
4973 cprintf("%d '%s' does not exist.\n", ERROR + ROOM_NOT_FOUND, targ);
4977 if (!strcasecmp(qtemp.QRname, CC->room.QRname)) {
4978 cprintf("%d Source and target rooms are the same.\n", ERROR + ALREADY_EXISTS);
4982 CtdlGetUser(&CC->user, CC->curr_user);
4983 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
4985 /* Check for permission to perform this operation.
4986 * Remember: "CC->room" is source, "qtemp" is target.
4990 /* Admins can move/copy */
4991 if (CC->user.axlevel >= AxAideU) permit = 1;
4993 /* Room aides can move/copy */
4994 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
4996 /* Permit move/copy from personal rooms */
4997 if ((CC->room.QRflags & QR_MAILBOX)
4998 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5000 /* Permit only copy from public to personal room */
5002 && (!(CC->room.QRflags & QR_MAILBOX))
5003 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5005 /* Permit message removal from collaborative delete rooms */
5006 if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
5008 /* Users allowed to post into the target room may move into it too. */
5009 if ((CC->room.QRflags & QR_MAILBOX) &&
5010 (qtemp.QRflags & UA_POSTALLOWED)) permit = 1;
5012 /* User must have access to target room */
5013 if (!(ra & UA_KNOWN)) permit = 0;
5016 cprintf("%d Higher access required.\n",
5017 ERROR + HIGHER_ACCESS_REQUIRED);
5022 * Build our message set to be moved/copied
5024 msgs = malloc(num_msgs * sizeof(long));
5025 for (i=0; i<num_msgs; ++i) {
5026 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
5027 msgs[i] = atol(msgtok);
5033 err = CtdlSaveMsgPointersInRoom(targ, msgs, num_msgs, 1, NULL, 0);
5035 cprintf("%d Cannot store message(s) in %s: error %d\n",
5041 /* Now delete the message from the source room,
5042 * if this is a 'move' rather than a 'copy' operation.
5045 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
5049 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
5055 * GetMetaData() - Get the supplementary record for a message
5057 void GetMetaData(struct MetaData *smibuf, long msgnum)
5060 struct cdbdata *cdbsmi;
5063 memset(smibuf, 0, sizeof(struct MetaData));
5064 smibuf->meta_msgnum = msgnum;
5065 smibuf->meta_refcount = 1; /* Default reference count is 1 */
5067 /* Use the negative of the message number for its supp record index */
5068 TheIndex = (0L - msgnum);
5070 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
5071 if (cdbsmi == NULL) {
5072 return; /* record not found; go with defaults */
5074 memcpy(smibuf, cdbsmi->ptr,
5075 ((cdbsmi->len > sizeof(struct MetaData)) ?
5076 sizeof(struct MetaData) : cdbsmi->len));
5083 * PutMetaData() - (re)write supplementary record for a message
5085 void PutMetaData(struct MetaData *smibuf)
5089 /* Use the negative of the message number for the metadata db index */
5090 TheIndex = (0L - smibuf->meta_msgnum);
5092 cdb_store(CDB_MSGMAIN,
5093 &TheIndex, (int)sizeof(long),
5094 smibuf, (int)sizeof(struct MetaData));
5099 * AdjRefCount - submit an adjustment to the reference count for a message.
5100 * (These are just queued -- we actually process them later.)
5102 void AdjRefCount(long msgnum, int incr)
5104 struct CitContext *CCC = CC;
5105 struct arcq new_arcq;
5108 MSG_syslog(LOG_DEBUG, "AdjRefCount() msg %ld ref count delta %+d\n", msgnum, incr);
5110 begin_critical_section(S_SUPPMSGMAIN);
5111 if (arcfp == NULL) {
5112 arcfp = fopen(file_arcq, "ab+");
5113 chown(file_arcq, CTDLUID, (-1));
5114 chmod(file_arcq, 0600);
5116 end_critical_section(S_SUPPMSGMAIN);
5118 /* msgnum < 0 means that we're trying to close the file */
5120 MSGM_syslog(LOG_DEBUG, "Closing the AdjRefCount queue file\n");
5121 begin_critical_section(S_SUPPMSGMAIN);
5122 if (arcfp != NULL) {
5126 end_critical_section(S_SUPPMSGMAIN);
5131 * If we can't open the queue, perform the operation synchronously.
5133 if (arcfp == NULL) {
5134 TDAP_AdjRefCount(msgnum, incr);
5138 new_arcq.arcq_msgnum = msgnum;
5139 new_arcq.arcq_delta = incr;
5140 rv = fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
5142 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5151 void AdjRefCountList(long *msgnum, long nmsg, int incr)
5153 struct CitContext *CCC = CC;
5154 long i, the_size, offset;
5155 struct arcq *new_arcq;
5158 MSG_syslog(LOG_DEBUG, "AdjRefCountList() msg %ld ref count delta %+d\n", nmsg, incr);
5160 begin_critical_section(S_SUPPMSGMAIN);
5161 if (arcfp == NULL) {
5162 arcfp = fopen(file_arcq, "ab+");
5163 chown(file_arcq, CTDLUID, (-1));
5164 chmod(file_arcq, 0600);
5166 end_critical_section(S_SUPPMSGMAIN);
5169 * If we can't open the queue, perform the operation synchronously.
5171 if (arcfp == NULL) {
5172 for (i = 0; i < nmsg; i++)
5173 TDAP_AdjRefCount(msgnum[i], incr);
5177 the_size = sizeof(struct arcq) * nmsg;
5178 new_arcq = malloc(the_size);
5179 for (i = 0; i < nmsg; i++) {
5180 new_arcq[i].arcq_msgnum = msgnum[i];
5181 new_arcq[i].arcq_delta = incr;
5185 while ((rv >= 0) && (offset < the_size))
5187 rv = fwrite(new_arcq + offset, 1, the_size - offset, arcfp);
5189 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5205 * TDAP_ProcessAdjRefCountQueue()
5207 * Process the queue of message count adjustments that was created by calls
5208 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
5209 * for each one. This should be an "off hours" operation.
5211 int TDAP_ProcessAdjRefCountQueue(void)
5213 struct CitContext *CCC = CC;
5214 char file_arcq_temp[PATH_MAX];
5217 struct arcq arcq_rec;
5218 int num_records_processed = 0;
5220 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s.%04x", file_arcq, rand());
5222 begin_critical_section(S_SUPPMSGMAIN);
5223 if (arcfp != NULL) {
5228 r = link(file_arcq, file_arcq_temp);
5230 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5231 end_critical_section(S_SUPPMSGMAIN);
5232 return(num_records_processed);
5236 end_critical_section(S_SUPPMSGMAIN);
5238 fp = fopen(file_arcq_temp, "rb");
5240 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5241 return(num_records_processed);
5244 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
5245 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
5246 ++num_records_processed;
5250 r = unlink(file_arcq_temp);
5252 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5255 return(num_records_processed);
5261 * TDAP_AdjRefCount - adjust the reference count for a message.
5262 * This one does it "for real" because it's called by
5263 * the autopurger function that processes the queue
5264 * created by AdjRefCount(). If a message's reference
5265 * count becomes zero, we also delete the message from
5266 * disk and de-index it.
5268 void TDAP_AdjRefCount(long msgnum, int incr)
5270 struct CitContext *CCC = CC;
5272 struct MetaData smi;
5275 /* This is a *tight* critical section; please keep it that way, as
5276 * it may get called while nested in other critical sections.
5277 * Complicating this any further will surely cause deadlock!
5279 begin_critical_section(S_SUPPMSGMAIN);
5280 GetMetaData(&smi, msgnum);
5281 smi.meta_refcount += incr;
5283 end_critical_section(S_SUPPMSGMAIN);
5284 MSG_syslog(LOG_DEBUG, "TDAP_AdjRefCount() msg %ld ref count delta %+d, is now %d\n",
5285 msgnum, incr, smi.meta_refcount
5288 /* If the reference count is now zero, delete the message
5289 * (and its supplementary record as well).
5291 if (smi.meta_refcount == 0) {
5292 MSG_syslog(LOG_DEBUG, "Deleting message <%ld>\n", msgnum);
5294 /* Call delete hooks with NULL room to show it has gone altogether */
5295 PerformDeleteHooks(NULL, msgnum);
5297 /* Remove from message base */
5299 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5300 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
5302 /* Remove metadata record */
5303 delnum = (0L - msgnum);
5304 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5310 * Write a generic object to this room
5312 * Note: this could be much more efficient. Right now we use two temporary
5313 * files, and still pull the message into memory as with all others.
5315 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
5316 char *content_type, /* MIME type of this object */
5317 char *raw_message, /* Data to be written */
5318 off_t raw_length, /* Size of raw_message */
5319 struct ctdluser *is_mailbox, /* Mailbox room? */
5320 int is_binary, /* Is encoding necessary? */
5321 int is_unique, /* Del others of this type? */
5322 unsigned int flags /* Internal save flags */
5325 struct CitContext *CCC = CC;
5326 struct ctdlroom qrbuf;
5327 char roomname[ROOMNAMELEN];
5328 struct CtdlMessage *msg;
5329 char *encoded_message = NULL;
5331 if (is_mailbox != NULL) {
5332 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
5335 safestrncpy(roomname, req_room, sizeof(roomname));
5338 MSG_syslog(LOG_DEBUG, "Raw length is %ld\n", (long)raw_length);
5341 encoded_message = malloc((size_t) (((raw_length * 134) / 100) + 4096 ) );
5344 encoded_message = malloc((size_t)(raw_length + 4096));
5347 sprintf(encoded_message, "Content-type: %s\n", content_type);
5350 sprintf(&encoded_message[strlen(encoded_message)],
5351 "Content-transfer-encoding: base64\n\n"
5355 sprintf(&encoded_message[strlen(encoded_message)],
5356 "Content-transfer-encoding: 7bit\n\n"
5362 &encoded_message[strlen(encoded_message)],
5370 &encoded_message[strlen(encoded_message)],
5376 MSGM_syslog(LOG_DEBUG, "Allocating\n");
5377 msg = malloc(sizeof(struct CtdlMessage));
5378 memset(msg, 0, sizeof(struct CtdlMessage));
5379 msg->cm_magic = CTDLMESSAGE_MAGIC;
5380 msg->cm_anon_type = MES_NORMAL;
5381 msg->cm_format_type = 4;
5382 msg->cm_fields['A'] = strdup(CCC->user.fullname);
5383 msg->cm_fields['O'] = strdup(req_room);
5384 msg->cm_fields['N'] = strdup(config.c_nodename);
5385 msg->cm_fields['H'] = strdup(config.c_humannode);
5386 msg->cm_flags = flags;
5388 msg->cm_fields['M'] = encoded_message;
5390 /* Create the requested room if we have to. */
5391 if (CtdlGetRoom(&qrbuf, roomname) != 0) {
5392 CtdlCreateRoom(roomname,
5393 ( (is_mailbox != NULL) ? 5 : 3 ),
5394 "", 0, 1, 0, VIEW_BBS);
5396 /* If the caller specified this object as unique, delete all
5397 * other objects of this type that are currently in the room.
5400 MSG_syslog(LOG_DEBUG, "Deleted %d other msgs of this type\n",
5401 CtdlDeleteMessages(roomname, NULL, 0, content_type)
5404 /* Now write the data */
5405 CtdlSubmitMsg(msg, NULL, roomname, 0);
5406 CtdlFreeMessage(msg);
5414 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
5415 config_msgnum = msgnum;
5419 char *CtdlGetSysConfig(char *sysconfname) {
5420 char hold_rm[ROOMNAMELEN];
5423 struct CtdlMessage *msg;
5426 strcpy(hold_rm, CC->room.QRname);
5427 if (CtdlGetRoom(&CC->room, SYSCONFIGROOM) != 0) {
5428 CtdlGetRoom(&CC->room, hold_rm);
5433 /* We want the last (and probably only) config in this room */
5434 begin_critical_section(S_CONFIG);
5435 config_msgnum = (-1L);
5436 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
5437 CtdlGetSysConfigBackend, NULL);
5438 msgnum = config_msgnum;
5439 end_critical_section(S_CONFIG);
5445 msg = CtdlFetchMessage(msgnum, 1);
5447 conf = strdup(msg->cm_fields['M']);
5448 CtdlFreeMessage(msg);
5455 CtdlGetRoom(&CC->room, hold_rm);
5457 if (conf != NULL) do {
5458 extract_token(buf, conf, 0, '\n', sizeof buf);
5459 strcpy(conf, &conf[strlen(buf)+1]);
5460 } while ( (!IsEmptyStr(conf)) && (!IsEmptyStr(buf)) );
5466 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
5467 CtdlWriteObject(SYSCONFIGROOM, sysconfname, sysconfdata, (strlen(sysconfdata)+1), NULL, 0, 1, 0);
5472 * Determine whether a given Internet address belongs to the current user
5474 int CtdlIsMe(char *addr, int addr_buf_len)
5476 struct recptypes *recp;
5479 recp = validate_recipients(addr, NULL, 0);
5480 if (recp == NULL) return(0);
5482 if (recp->num_local == 0) {
5483 free_recipients(recp);
5487 for (i=0; i<recp->num_local; ++i) {
5488 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
5489 if (!strcasecmp(addr, CC->user.fullname)) {
5490 free_recipients(recp);
5495 free_recipients(recp);
5501 * Citadel protocol command to do the same
5503 void cmd_isme(char *argbuf) {
5506 if (CtdlAccessCheck(ac_logged_in)) return;
5507 extract_token(addr, argbuf, 0, '|', sizeof addr);
5509 if (CtdlIsMe(addr, sizeof addr)) {
5510 cprintf("%d %s\n", CIT_OK, addr);
5513 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);
5519 /*****************************************************************************/
5520 /* MODULE INITIALIZATION STUFF */
5521 /*****************************************************************************/
5522 void SetMessageDebugEnabled(const int n)
5524 MessageDebugEnabled = n;
5526 CTDL_MODULE_INIT(msgbase)
5529 CtdlRegisterDebugFlagHook(HKEY("messages"), SetMessageDebugEnabled, &MessageDebugEnabled);
5531 CtdlRegisterProtoHook(cmd_msgs, "MSGS", "Output a list of messages in the current room");
5532 CtdlRegisterProtoHook(cmd_msg0, "MSG0", "Output a message in plain text format");
5533 CtdlRegisterProtoHook(cmd_msg2, "MSG2", "Output a message in RFC822 format");
5534 CtdlRegisterProtoHook(cmd_msg3, "MSG3", "Output a message in raw format (deprecated)");
5535 CtdlRegisterProtoHook(cmd_msg4, "MSG4", "Output a message in the client's preferred format");
5536 CtdlRegisterProtoHook(cmd_msgp, "MSGP", "Select preferred format for MSG4 output");
5537 CtdlRegisterProtoHook(cmd_opna, "OPNA", "Open an attachment for download");
5538 CtdlRegisterProtoHook(cmd_dlat, "DLAT", "Download an attachment");
5539 CtdlRegisterProtoHook(cmd_ent0, "ENT0", "Enter a message");
5540 CtdlRegisterProtoHook(cmd_dele, "DELE", "Delete a message");
5541 CtdlRegisterProtoHook(cmd_move, "MOVE", "Move or copy a message to another room");
5542 CtdlRegisterProtoHook(cmd_isme, "ISME", "Determine whether an email address belongs to a user");
5545 /* return our Subversion id for the Log */