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,
120 * This function is self explanatory.
121 * (What can I say, I'm in a weird mood today...)
123 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
127 for (i = 0; i < strlen(name); ++i) {
128 if (name[i] == '@') {
129 while (isspace(name[i - 1]) && i > 0) {
130 strcpy(&name[i - 1], &name[i]);
133 while (isspace(name[i + 1])) {
134 strcpy(&name[i + 1], &name[i + 2]);
142 * Aliasing for network mail.
143 * (Error messages have been commented out, because this is a server.)
145 int alias(char *name)
146 { /* process alias and routing info for mail */
147 struct CitContext *CCC = CC;
150 char aaa[SIZ], bbb[SIZ];
151 char *ignetcfg = NULL;
152 char *ignetmap = NULL;
158 char original_name[256];
159 safestrncpy(original_name, name, sizeof original_name);
162 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
163 stripallbut(name, '<', '>');
165 fp = fopen(file_mail_aliases, "r");
167 fp = fopen("/dev/null", "r");
174 while (fgets(aaa, sizeof aaa, fp) != NULL) {
175 while (isspace(name[0]))
176 strcpy(name, &name[1]);
177 aaa[strlen(aaa) - 1] = 0;
179 for (a = 0; a < strlen(aaa); ++a) {
181 strcpy(bbb, &aaa[a + 1]);
185 if (!strcasecmp(name, aaa))
190 /* Hit the Global Address Book */
191 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
195 if (strcasecmp(original_name, name)) {
196 MSG_syslog(LOG_INFO, "%s is being forwarded to %s\n", original_name, name);
199 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
200 for (a=0; a<strlen(name); ++a) {
201 if (name[a] == '@') {
202 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
204 MSG_syslog(LOG_INFO, "Changed to <%s>\n", name);
209 /* determine local or remote type, see citadel.h */
210 at = haschar(name, '@');
211 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
212 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
213 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
215 /* figure out the delivery mode */
216 extract_token(node, name, 1, '@', sizeof node);
218 /* If there are one or more dots in the nodename, we assume that it
219 * is an FQDN and will attempt SMTP delivery to the Internet.
221 if (haschar(node, '.') > 0) {
222 return(MES_INTERNET);
225 /* Otherwise we look in the IGnet maps for a valid Citadel node.
226 * Try directly-connected nodes first...
228 ignetcfg = CtdlGetSysConfig(IGNETCFG);
229 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
230 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
231 extract_token(testnode, buf, 0, '|', sizeof testnode);
232 if (!strcasecmp(node, testnode)) {
240 * Then try nodes that are two or more hops away.
242 ignetmap = CtdlGetSysConfig(IGNETMAP);
243 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
244 extract_token(buf, ignetmap, i, '\n', sizeof buf);
245 extract_token(testnode, buf, 0, '|', sizeof testnode);
246 if (!strcasecmp(node, testnode)) {
253 /* If we get to this point it's an invalid node name */
259 * Back end for the MSGS command: output message number only.
261 void simple_listing(long msgnum, void *userdata)
263 cprintf("%ld\n", msgnum);
269 * Back end for the MSGS command: output header summary.
271 void headers_listing(long msgnum, void *userdata)
273 struct CtdlMessage *msg;
275 msg = CtdlFetchMessage(msgnum, 0);
277 cprintf("%ld|0|||||\n", msgnum);
281 cprintf("%ld|%s|%s|%s|%s|%s|\n",
283 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
284 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
285 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
286 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
287 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
289 CtdlFreeMessage(msg);
293 * Back end for the MSGS command: output EUID header.
295 void headers_euid(long msgnum, void *userdata)
297 struct CtdlMessage *msg;
299 msg = CtdlFetchMessage(msgnum, 0);
301 cprintf("%ld||\n", msgnum);
305 cprintf("%ld|%s|%s\n",
307 (msg->cm_fields['E'] ? msg->cm_fields['E'] : ""),
308 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"));
309 CtdlFreeMessage(msg);
316 /* Determine if a given message matches the fields in a message template.
317 * Return 0 for a successful match.
319 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
322 /* If there aren't any fields in the template, all messages will
325 if (template == NULL) return(0);
327 /* Null messages are bogus. */
328 if (msg == NULL) return(1);
330 for (i='A'; i<='Z'; ++i) {
331 if (template->cm_fields[i] != NULL) {
332 if (msg->cm_fields[i] == NULL) {
333 /* Considered equal if temmplate is empty string */
334 if (IsEmptyStr(template->cm_fields[i])) continue;
337 if (strcasecmp(msg->cm_fields[i],
338 template->cm_fields[i])) return 1;
342 /* All compares succeeded: we have a match! */
349 * Retrieve the "seen" message list for the current room.
351 void CtdlGetSeen(char *buf, int which_set) {
352 struct CitContext *CCC = CC;
355 /* Learn about the user and room in question */
356 CtdlGetRelationship(&vbuf, &CCC->user, &CCC->room);
358 if (which_set == ctdlsetseen_seen)
359 safestrncpy(buf, vbuf.v_seen, SIZ);
360 if (which_set == ctdlsetseen_answered)
361 safestrncpy(buf, vbuf.v_answered, SIZ);
367 * Manipulate the "seen msgs" string (or other message set strings)
369 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
370 int target_setting, int which_set,
371 struct ctdluser *which_user, struct ctdlroom *which_room) {
372 struct CitContext *CCC = CC;
373 struct cdbdata *cdbfr;
378 long hi = (-1L); /// TODO: we just write here. y?
387 char *is_set; /* actually an array of booleans */
389 /* Don't bother doing *anything* if we were passed a list of zero messages */
390 if (num_target_msgnums < 1) {
394 /* If no room was specified, we go with the current room. */
396 which_room = &CCC->room;
399 /* If no user was specified, we go with the current user. */
401 which_user = &CCC->user;
404 MSG_syslog(LOG_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %s, %d) in <%s>\n",
405 num_target_msgnums, target_msgnums[0],
406 (target_setting ? "SET" : "CLEAR"),
410 /* Learn about the user and room in question */
411 CtdlGetRelationship(&vbuf, which_user, which_room);
413 /* Load the message list */
414 cdbfr = cdb_fetch(CDB_MSGLISTS, &which_room->QRnumber, sizeof(long));
416 msglist = (long *) cdbfr->ptr;
417 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
418 num_msgs = cdbfr->len / sizeof(long);
421 return; /* No messages at all? No further action. */
424 is_set = malloc(num_msgs * sizeof(char));
425 memset(is_set, 0, (num_msgs * sizeof(char)) );
427 /* Decide which message set we're manipulating */
429 case ctdlsetseen_seen:
430 vset = NewStrBufPlain(vbuf.v_seen, -1);
432 case ctdlsetseen_answered:
433 vset = NewStrBufPlain(vbuf.v_answered, -1);
440 #if 0 /* This is a special diagnostic section. Do not allow it to run during normal operation. */
441 MSG_syslog(LOG_DEBUG, "There are %d messages in the room.\n", num_msgs);
442 for (i=0; i<num_msgs; ++i) {
443 if ((i > 0) && (msglist[i] <= msglist[i-1])) abort();
445 MSG_syslog(LOG_DEBUG, "We are twiddling %d of them.\n", num_target_msgnums);
446 for (k=0; k<num_target_msgnums; ++k) {
447 if ((k > 0) && (target_msgnums[k] <= target_msgnums[k-1])) abort();
451 MSG_syslog(LOG_DEBUG, "before update: %s\n", ChrPtr(vset));
453 /* Translate the existing sequence set into an array of booleans */
454 setstr = NewStrBuf();
458 while (StrBufExtract_NextToken(setstr, vset, &pvset, ',') >= 0) {
460 StrBufExtract_token(lostr, setstr, 0, ':');
461 if (StrBufNum_tokens(setstr, ':') >= 2) {
462 StrBufExtract_token(histr, setstr, 1, ':');
466 StrBufAppendBuf(histr, lostr, 0);
469 if (!strcmp(ChrPtr(histr), "*")) {
476 for (i = 0; i < num_msgs; ++i) {
477 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
487 /* Now translate the array of booleans back into a sequence set */
493 for (i=0; i<num_msgs; ++i) {
497 for (k=0; k<num_target_msgnums; ++k) {
498 if (msglist[i] == target_msgnums[k]) {
499 is_seen = target_setting;
503 if ((was_seen == 0) && (is_seen == 1)) {
506 else if ((was_seen == 1) && (is_seen == 0)) {
509 if (StrLength(vset) > 0) {
510 StrBufAppendBufPlain(vset, HKEY(","), 0);
513 StrBufAppendPrintf(vset, "%ld", hi);
516 StrBufAppendPrintf(vset, "%ld:%ld", lo, hi);
520 if ((is_seen) && (i == num_msgs - 1)) {
521 if (StrLength(vset) > 0) {
522 StrBufAppendBufPlain(vset, HKEY(","), 0);
524 if ((i==0) || (was_seen == 0)) {
525 StrBufAppendPrintf(vset, "%ld", msglist[i]);
528 StrBufAppendPrintf(vset, "%ld:%ld", lo, msglist[i]);
536 * We will have to stuff this string back into a 4096 byte buffer, so if it's
537 * larger than that now, truncate it by removing tokens from the beginning.
538 * The limit of 100 iterations is there to prevent an infinite loop in case
539 * something unexpected happens.
541 int number_of_truncations = 0;
542 while ( (StrLength(vset) > SIZ) && (number_of_truncations < 100) ) {
543 StrBufRemove_token(vset, 0, ',');
544 ++number_of_truncations;
548 * If we're truncating the sequence set of messages marked with the 'seen' flag,
549 * we want the earliest messages (the truncated ones) to be marked, not unmarked.
550 * Otherwise messages at the beginning will suddenly appear to be 'unseen'.
552 if ( (which_set == ctdlsetseen_seen) && (number_of_truncations > 0) ) {
554 first_tok = NewStrBuf();
555 StrBufExtract_token(first_tok, vset, 0, ',');
556 StrBufRemove_token(vset, 0, ',');
558 if (StrBufNum_tokens(first_tok, ':') > 1) {
559 StrBufRemove_token(first_tok, 0, ':');
563 new_set = NewStrBuf();
564 StrBufAppendBufPlain(new_set, HKEY("1:"), 0);
565 StrBufAppendBuf(new_set, first_tok, 0);
566 StrBufAppendBufPlain(new_set, HKEY(":"), 0);
567 StrBufAppendBuf(new_set, vset, 0);
570 FreeStrBuf(&first_tok);
574 MSG_syslog(LOG_DEBUG, " after update: %s\n", ChrPtr(vset));
576 /* Decide which message set we're manipulating */
578 case ctdlsetseen_seen:
579 safestrncpy(vbuf.v_seen, ChrPtr(vset), sizeof vbuf.v_seen);
581 case ctdlsetseen_answered:
582 safestrncpy(vbuf.v_answered, ChrPtr(vset), sizeof vbuf.v_answered);
588 CtdlSetRelationship(&vbuf, which_user, which_room);
594 * API function to perform an operation for each qualifying message in the
595 * current room. (Returns the number of messages processed.)
597 int CtdlForEachMessage(int mode, long ref, char *search_string,
599 struct CtdlMessage *compare,
600 ForEachMsgCallback CallBack,
603 struct CitContext *CCC = CC;
606 struct cdbdata *cdbfr;
607 long *msglist = NULL;
609 int num_processed = 0;
612 struct CtdlMessage *msg = NULL;
615 int printed_lastold = 0;
616 int num_search_msgs = 0;
617 long *search_msgs = NULL;
619 int need_to_free_re = 0;
622 if ((content_type) && (!IsEmptyStr(content_type))) {
623 regcomp(&re, content_type, 0);
627 /* Learn about the user and room in question */
628 if (server_shutting_down) {
629 if (need_to_free_re) regfree(&re);
632 CtdlGetUser(&CCC->user, CCC->curr_user);
634 if (server_shutting_down) {
635 if (need_to_free_re) regfree(&re);
638 CtdlGetRelationship(&vbuf, &CCC->user, &CCC->room);
640 if (server_shutting_down) {
641 if (need_to_free_re) regfree(&re);
645 /* Load the message list */
646 cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
648 if (need_to_free_re) regfree(&re);
649 return 0; /* No messages at all? No further action. */
652 msglist = (long *) cdbfr->ptr;
653 num_msgs = cdbfr->len / sizeof(long);
655 cdbfr->ptr = NULL; /* clear this so that cdb_free() doesn't free it */
656 cdb_free(cdbfr); /* we own this memory now */
659 * Now begin the traversal.
661 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
663 /* If the caller is looking for a specific MIME type, filter
664 * out all messages which are not of the type requested.
666 if ((content_type != NULL) && (!IsEmptyStr(content_type))) {
668 /* This call to GetMetaData() sits inside this loop
669 * so that we only do the extra database read per msg
670 * if we need to. Doing the extra read all the time
671 * really kills the server. If we ever need to use
672 * metadata for another search criterion, we need to
673 * move the read somewhere else -- but still be smart
674 * enough to only do the read if the caller has
675 * specified something that will need it.
677 if (server_shutting_down) {
678 if (need_to_free_re) regfree(&re);
682 GetMetaData(&smi, msglist[a]);
684 /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
685 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
691 num_msgs = sort_msglist(msglist, num_msgs);
693 /* If a template was supplied, filter out the messages which
694 * don't match. (This could induce some delays!)
697 if (compare != NULL) {
698 for (a = 0; a < num_msgs; ++a) {
699 if (server_shutting_down) {
700 if (need_to_free_re) regfree(&re);
704 msg = CtdlFetchMessage(msglist[a], 1);
706 if (CtdlMsgCmp(msg, compare)) {
709 CtdlFreeMessage(msg);
715 /* If a search string was specified, get a message list from
716 * the full text index and remove messages which aren't on both
720 * Since the lists are sorted and strictly ascending, and the
721 * output list is guaranteed to be shorter than or equal to the
722 * input list, we overwrite the bottom of the input list. This
723 * eliminates the need to memmove big chunks of the list over and
726 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
728 /* Call search module via hook mechanism.
729 * NULL means use any search function available.
730 * otherwise replace with a char * to name of search routine
732 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
734 if (num_search_msgs > 0) {
738 orig_num_msgs = num_msgs;
740 for (i=0; i<orig_num_msgs; ++i) {
741 for (j=0; j<num_search_msgs; ++j) {
742 if (msglist[i] == search_msgs[j]) {
743 msglist[num_msgs++] = msglist[i];
749 num_msgs = 0; /* No messages qualify */
751 if (search_msgs != NULL) free(search_msgs);
753 /* Now that we've purged messages which don't contain the search
754 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
761 * Now iterate through the message list, according to the
762 * criteria supplied by the caller.
765 for (a = 0; a < num_msgs; ++a) {
766 if (server_shutting_down) {
767 if (need_to_free_re) regfree(&re);
769 return num_processed;
771 thismsg = msglist[a];
772 if (mode == MSGS_ALL) {
776 is_seen = is_msg_in_sequence_set(
777 vbuf.v_seen, thismsg);
778 if (is_seen) lastold = thismsg;
784 || ((mode == MSGS_OLD) && (is_seen))
785 || ((mode == MSGS_NEW) && (!is_seen))
786 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
787 || ((mode == MSGS_FIRST) && (a < ref))
788 || ((mode == MSGS_GT) && (thismsg > ref))
789 || ((mode == MSGS_LT) && (thismsg < ref))
790 || ((mode == MSGS_EQ) && (thismsg == ref))
793 if ((mode == MSGS_NEW) && (CCC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
795 CallBack(lastold, userdata);
799 if (CallBack) CallBack(thismsg, userdata);
803 if (need_to_free_re) regfree(&re);
806 * We cache the most recent msglist in order to do security checks later
808 if (CCC->client_socket > 0) {
809 if (CCC->cached_msglist != NULL) {
810 free(CCC->cached_msglist);
812 CCC->cached_msglist = msglist;
813 CCC->cached_num_msgs = num_msgs;
819 return num_processed;
825 * cmd_msgs() - get list of message #'s in this room
826 * implements the MSGS server command using CtdlForEachMessage()
828 void cmd_msgs(char *cmdbuf)
837 int with_template = 0;
838 struct CtdlMessage *template = NULL;
839 char search_string[1024];
840 ForEachMsgCallback CallBack;
842 if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
844 extract_token(which, cmdbuf, 0, '|', sizeof which);
845 cm_ref = extract_int(cmdbuf, 1);
846 extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
847 with_template = extract_int(cmdbuf, 2);
848 switch (extract_int(cmdbuf, 3))
852 CallBack = simple_listing;
855 CallBack = headers_listing;
858 CallBack = headers_euid;
863 if (!strncasecmp(which, "OLD", 3))
865 else if (!strncasecmp(which, "NEW", 3))
867 else if (!strncasecmp(which, "FIRST", 5))
869 else if (!strncasecmp(which, "LAST", 4))
871 else if (!strncasecmp(which, "GT", 2))
873 else if (!strncasecmp(which, "LT", 2))
875 else if (!strncasecmp(which, "SEARCH", 6))
880 if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
881 cprintf("%d Full text index is not enabled on this server.\n",
882 ERROR + CMD_NOT_SUPPORTED);
888 cprintf("%d Send template then receive message list\n",
890 template = (struct CtdlMessage *)
891 malloc(sizeof(struct CtdlMessage));
892 memset(template, 0, sizeof(struct CtdlMessage));
893 template->cm_magic = CTDLMESSAGE_MAGIC;
894 template->cm_anon_type = MES_NORMAL;
896 while(client_getln(buf, sizeof buf) >= 0 && strcmp(buf,"000")) {
897 extract_token(tfield, buf, 0, '|', sizeof tfield);
898 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
899 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
900 if (!strcasecmp(tfield, msgkeys[i])) {
901 template->cm_fields[i] =
909 cprintf("%d \n", LISTING_FOLLOWS);
912 CtdlForEachMessage(mode,
913 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
914 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
919 if (template != NULL) CtdlFreeMessage(template);
927 * help_subst() - support routine for help file viewer
929 void help_subst(char *strbuf, char *source, char *dest)
934 while (p = pattern2(strbuf, source), (p >= 0)) {
935 strcpy(workbuf, &strbuf[p + strlen(source)]);
936 strcpy(&strbuf[p], dest);
937 strcat(strbuf, workbuf);
942 void do_help_subst(char *buffer)
946 help_subst(buffer, "^nodename", config.c_nodename);
947 help_subst(buffer, "^humannode", config.c_humannode);
948 help_subst(buffer, "^fqdn", config.c_fqdn);
949 help_subst(buffer, "^username", CC->user.fullname);
950 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
951 help_subst(buffer, "^usernum", buf2);
952 help_subst(buffer, "^sysadm", config.c_sysadm);
953 help_subst(buffer, "^variantname", CITADEL);
954 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
955 help_subst(buffer, "^maxsessions", buf2);
956 help_subst(buffer, "^bbsdir", ctdl_message_dir);
962 * memfmout() - Citadel text formatter and paginator.
963 * Although the original purpose of this routine was to format
964 * text to the reader's screen width, all we're really using it
965 * for here is to format text out to 80 columns before sending it
966 * to the client. The client software may reformat it again.
969 char *mptr, /* where are we going to get our text from? */
970 const char *nl /* string to terminate lines with */
972 struct CitContext *CCC = CC;
974 unsigned char ch = 0;
981 while (ch=*(mptr++), ch != 0) {
984 if (client_write(outbuf, len) == -1)
986 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
990 if (client_write(nl, nllen) == -1)
992 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
997 else if (ch == '\r') {
998 /* Ignore carriage returns. Newlines are always LF or CRLF but never CR. */
1000 else if (isspace(ch)) {
1001 if (column > 72) { /* Beyond 72 columns, break on the next space */
1002 if (client_write(outbuf, len) == -1)
1004 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1008 if (client_write(nl, nllen) == -1)
1010 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1023 if (column > 1000) { /* Beyond 1000 columns, break anywhere */
1024 if (client_write(outbuf, len) == -1)
1026 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1030 if (client_write(nl, nllen) == -1)
1032 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1040 if (client_write(outbuf, len) == -1)
1042 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1046 client_write(nl, nllen);
1054 * Callback function for mime parser that simply lists the part
1056 void list_this_part(char *name, char *filename, char *partnum, char *disp,
1057 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1058 char *cbid, void *cbuserdata)
1062 ma = (struct ma_info *)cbuserdata;
1063 if (ma->is_ma == 0) {
1064 cprintf("part=%s|%s|%s|%s|%s|%ld|%s|%s\n",
1077 * Callback function for multipart prefix
1079 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
1080 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1081 char *cbid, void *cbuserdata)
1085 ma = (struct ma_info *)cbuserdata;
1086 if (!strcasecmp(cbtype, "multipart/alternative")) {
1090 if (ma->is_ma == 0) {
1091 cprintf("pref=%s|%s\n", partnum, cbtype);
1096 * Callback function for multipart sufffix
1098 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
1099 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1100 char *cbid, void *cbuserdata)
1104 ma = (struct ma_info *)cbuserdata;
1105 if (ma->is_ma == 0) {
1106 cprintf("suff=%s|%s\n", partnum, cbtype);
1108 if (!strcasecmp(cbtype, "multipart/alternative")) {
1115 * Callback function for mime parser that opens a section for downloading
1117 void mime_download(char *name, char *filename, char *partnum, char *disp,
1118 void *content, char *cbtype, char *cbcharset, size_t length,
1119 char *encoding, char *cbid, void *cbuserdata)
1122 CitContext *CCC = MyContext();
1124 /* Silently go away if there's already a download open. */
1125 if (CCC->download_fp != NULL)
1129 (!IsEmptyStr(partnum) && (!strcasecmp(CCC->download_desired_section, partnum)))
1130 || (!IsEmptyStr(cbid) && (!strcasecmp(CCC->download_desired_section, cbid)))
1132 CCC->download_fp = tmpfile();
1133 if (CCC->download_fp == NULL) {
1134 MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1136 cprintf("%d cannot open temporary file: %s\n",
1137 ERROR + INTERNAL_ERROR, strerror(errno));
1141 rv = fwrite(content, length, 1, CC->download_fp);
1143 MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1145 cprintf("%d unable to write tempfile.\n",
1147 fclose(CCC->download_fp);
1148 CCC->download_fp = NULL;
1151 fflush(CCC->download_fp);
1152 rewind(CCC->download_fp);
1154 OpenCmdResult(filename, cbtype);
1161 * Callback function for mime parser that outputs a section all at once.
1162 * We can specify the desired section by part number *or* content-id.
1164 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
1165 void *content, char *cbtype, char *cbcharset, size_t length,
1166 char *encoding, char *cbid, void *cbuserdata)
1168 int *found_it = (int *)cbuserdata;
1171 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1172 || (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1175 cprintf("%d %d|-1|%s|%s|%s\n",
1182 client_write(content, length);
1188 * Load a message from disk into memory.
1189 * This is used by CtdlOutputMsg() and other fetch functions.
1191 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1192 * using the CtdlMessageFree() function.
1194 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1196 struct CitContext *CCC = CC;
1197 struct cdbdata *dmsgtext;
1198 struct CtdlMessage *ret = NULL;
1202 cit_uint8_t field_header;
1204 MSG_syslog(LOG_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1205 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1206 if (dmsgtext == NULL) {
1209 mptr = dmsgtext->ptr;
1210 upper_bound = mptr + dmsgtext->len;
1212 /* Parse the three bytes that begin EVERY message on disk.
1213 * The first is always 0xFF, the on-disk magic number.
1214 * The second is the anonymous/public type byte.
1215 * The third is the format type byte (vari, fixed, or MIME).
1219 MSG_syslog(LOG_ERR, "Message %ld appears to be corrupted.\n", msgnum);
1223 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1224 memset(ret, 0, sizeof(struct CtdlMessage));
1226 ret->cm_magic = CTDLMESSAGE_MAGIC;
1227 ret->cm_anon_type = *mptr++; /* Anon type byte */
1228 ret->cm_format_type = *mptr++; /* Format type byte */
1231 * The rest is zero or more arbitrary fields. Load them in.
1232 * We're done when we encounter either a zero-length field or
1233 * have just processed the 'M' (message text) field.
1236 if (mptr >= upper_bound) {
1239 field_header = *mptr++;
1240 ret->cm_fields[field_header] = strdup(mptr);
1242 while (*mptr++ != 0); /* advance to next field */
1244 } while ((mptr < upper_bound) && (field_header != 'M'));
1248 /* Always make sure there's something in the msg text field. If
1249 * it's NULL, the message text is most likely stored separately,
1250 * so go ahead and fetch that. Failing that, just set a dummy
1251 * body so other code doesn't barf.
1253 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1254 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1255 if (dmsgtext != NULL) {
1256 ret->cm_fields['M'] = dmsgtext->ptr;
1257 dmsgtext->ptr = NULL;
1261 if (ret->cm_fields['M'] == NULL) {
1262 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1265 /* Perform "before read" hooks (aborting if any return nonzero) */
1266 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1267 CtdlFreeMessage(ret);
1276 * Returns 1 if the supplied pointer points to a valid Citadel message.
1277 * If the pointer is NULL or the magic number check fails, returns 0.
1279 int is_valid_message(struct CtdlMessage *msg) {
1282 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1283 struct CitContext *CCC = CC;
1284 MSGM_syslog(LOG_WARNING, "is_valid_message() -- self-check failed\n");
1290 void CtdlFreeMessageContents(struct CtdlMessage *msg)
1294 for (i = 0; i < 256; ++i)
1295 if (msg->cm_fields[i] != NULL) {
1296 free(msg->cm_fields[i]);
1299 msg->cm_magic = 0; /* just in case */
1302 * 'Destructor' for struct CtdlMessage
1304 void CtdlFreeMessage(struct CtdlMessage *msg)
1306 if (is_valid_message(msg) == 0)
1308 if (msg != NULL) free (msg);
1311 CtdlFreeMessageContents(msg);
1315 int DupCMField(int i, struct CtdlMessage *OrgMsg, struct CtdlMessage *NewMsg)
1318 len = strlen(OrgMsg->cm_fields[i]);
1319 NewMsg->cm_fields[i] = malloc(len + 1);
1320 if (NewMsg->cm_fields[i] == NULL)
1322 memcpy(NewMsg->cm_fields[i], OrgMsg->cm_fields[i], len);
1326 struct CtdlMessage * CtdlDuplicateMessage(struct CtdlMessage *OrgMsg)
1329 struct CtdlMessage *NewMsg;
1331 if (is_valid_message(OrgMsg) == 0)
1333 NewMsg = (struct CtdlMessage *)malloc(sizeof(struct CtdlMessage *));
1337 memcpy(NewMsg, OrgMsg, sizeof(struct CtdlMessage *));
1339 memset(NewMsg->cm_fields, 0, sizeof(NewMsg->cm_fields));
1341 for (i = 0; i < 256; ++i)
1343 if (OrgMsg->cm_fields[i] != NULL)
1345 if (!DupCMField(i, OrgMsg, NewMsg))
1347 CtdlFreeMessage(NewMsg);
1359 * Pre callback function for multipart/alternative
1361 * NOTE: this differs from the standard behavior for a reason. Normally when
1362 * displaying multipart/alternative you want to show the _last_ usable
1363 * format in the message. Here we show the _first_ one, because it's
1364 * usually text/plain. Since this set of functions is designed for text
1365 * output to non-MIME-aware clients, this is the desired behavior.
1368 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1369 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1370 char *cbid, void *cbuserdata)
1372 struct CitContext *CCC = CC;
1375 ma = (struct ma_info *)cbuserdata;
1376 MSG_syslog(LOG_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1377 if (!strcasecmp(cbtype, "multipart/alternative")) {
1381 if (!strcasecmp(cbtype, "message/rfc822")) {
1387 * Post callback function for multipart/alternative
1389 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1390 void *content, char *cbtype, char *cbcharset, size_t length,
1391 char *encoding, char *cbid, void *cbuserdata)
1393 struct CitContext *CCC = CC;
1396 ma = (struct ma_info *)cbuserdata;
1397 MSG_syslog(LOG_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1398 if (!strcasecmp(cbtype, "multipart/alternative")) {
1402 if (!strcasecmp(cbtype, "message/rfc822")) {
1408 * Inline callback function for mime parser that wants to display text
1410 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1411 void *content, char *cbtype, char *cbcharset, size_t length,
1412 char *encoding, char *cbid, void *cbuserdata)
1414 struct CitContext *CCC = CC;
1420 ma = (struct ma_info *)cbuserdata;
1422 MSG_syslog(LOG_DEBUG,
1423 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1424 partnum, filename, cbtype, (long)length);
1427 * If we're in the middle of a multipart/alternative scope and
1428 * we've already printed another section, skip this one.
1430 if ( (ma->is_ma) && (ma->did_print) ) {
1431 MSG_syslog(LOG_DEBUG, "Skipping part %s (%s)\n", partnum, cbtype);
1436 if ( (!strcasecmp(cbtype, "text/plain"))
1437 || (IsEmptyStr(cbtype)) ) {
1440 client_write(wptr, length);
1441 if (wptr[length-1] != '\n') {
1448 if (!strcasecmp(cbtype, "text/html")) {
1449 ptr = html_to_ascii(content, length, 80, 0);
1451 client_write(ptr, wlen);
1452 if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
1459 if (ma->use_fo_hooks) {
1460 if (PerformFixedOutputHooks(cbtype, content, length)) {
1461 /* above function returns nonzero if it handled the part */
1466 if (strncasecmp(cbtype, "multipart/", 10)) {
1467 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1468 partnum, filename, cbtype, (long)length);
1474 * The client is elegant and sophisticated and wants to be choosy about
1475 * MIME content types, so figure out which multipart/alternative part
1476 * we're going to send.
1478 * We use a system of weights. When we find a part that matches one of the
1479 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1480 * and then set ma->chosen_pref to that MIME type's position in our preference
1481 * list. If we then hit another match, we only replace the first match if
1482 * the preference value is lower.
1484 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1485 void *content, char *cbtype, char *cbcharset, size_t length,
1486 char *encoding, char *cbid, void *cbuserdata)
1488 struct CitContext *CCC = CC;
1493 ma = (struct ma_info *)cbuserdata;
1495 // NOTE: REMOVING THIS CONDITIONAL FIXES BUG 220
1496 // http://bugzilla.citadel.org/show_bug.cgi?id=220
1497 // I don't know if there are any side effects! Please TEST TEST TEST
1498 //if (ma->is_ma > 0) {
1500 for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1501 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1502 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1503 if (i < ma->chosen_pref) {
1504 MSG_syslog(LOG_DEBUG, "Setting chosen part: <%s>\n", partnum);
1505 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1506 ma->chosen_pref = i;
1513 * Now that we've chosen our preferred part, output it.
1515 void output_preferred(char *name,
1527 struct CitContext *CCC = CC;
1530 int add_newline = 0;
1533 char *decoded = NULL;
1534 size_t bytes_decoded;
1537 ma = (struct ma_info *)cbuserdata;
1539 /* This is not the MIME part you're looking for... */
1540 if (strcasecmp(partnum, ma->chosen_part)) return;
1542 /* If the content-type of this part is in our preferred formats
1543 * list, we can simply output it verbatim.
1545 for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1546 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1547 if (!strcasecmp(buf, cbtype)) {
1548 /* Yeah! Go! W00t!! */
1549 if (ma->dont_decode == 0)
1550 rc = mime_decode_now (content,
1556 break; /* Give us the chance, maybe theres another one. */
1558 if (rc == 0) text_content = (char *)content;
1560 text_content = decoded;
1561 length = bytes_decoded;
1564 if (text_content[length-1] != '\n') {
1567 cprintf("Content-type: %s", cbtype);
1568 if (!IsEmptyStr(cbcharset)) {
1569 cprintf("; charset=%s", cbcharset);
1571 cprintf("\nContent-length: %d\n",
1572 (int)(length + add_newline) );
1573 if (!IsEmptyStr(encoding)) {
1574 cprintf("Content-transfer-encoding: %s\n", encoding);
1577 cprintf("Content-transfer-encoding: 7bit\n");
1579 cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1581 if (client_write(text_content, length) == -1)
1583 MSGM_syslog(LOG_ERR, "output_preferred(): aborting due to write failure.\n");
1586 if (add_newline) cprintf("\n");
1587 if (decoded != NULL) free(decoded);
1592 /* No translations required or possible: output as text/plain */
1593 cprintf("Content-type: text/plain\n\n");
1595 if (ma->dont_decode == 0)
1596 rc = mime_decode_now (content,
1602 return; /* Give us the chance, maybe theres another one. */
1604 if (rc == 0) text_content = (char *)content;
1606 text_content = decoded;
1607 length = bytes_decoded;
1610 fixed_output(name, filename, partnum, disp, text_content, cbtype, cbcharset,
1611 length, encoding, cbid, cbuserdata);
1612 if (decoded != NULL) free(decoded);
1617 char desired_section[64];
1624 * Callback function for
1626 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1627 void *content, char *cbtype, char *cbcharset, size_t length,
1628 char *encoding, char *cbid, void *cbuserdata)
1630 struct encapmsg *encap;
1632 encap = (struct encapmsg *)cbuserdata;
1634 /* Only proceed if this is the desired section... */
1635 if (!strcasecmp(encap->desired_section, partnum)) {
1636 encap->msglen = length;
1637 encap->msg = malloc(length + 2);
1638 memcpy(encap->msg, content, length);
1645 * Determine whether the specified message exists in the cached_msglist
1646 * (This is a security check)
1648 int check_cached_msglist(long msgnum) {
1649 struct CitContext *CCC = CC;
1651 /* cases in which we skip the check */
1652 if (!CCC) return om_ok; /* not a session */
1653 if (CCC->client_socket <= 0) return om_ok; /* not a client session */
1654 if (CCC->cached_msglist == NULL) return om_access_denied; /* no msglist fetched */
1655 if (CCC->cached_num_msgs == 0) return om_access_denied; /* nothing to check */
1658 /* Do a binary search within the cached_msglist for the requested msgnum */
1660 int max = (CC->cached_num_msgs - 1);
1662 while (max >= min) {
1663 int middle = min + (max-min) / 2 ;
1664 if (msgnum == CCC->cached_msglist[middle]) {
1667 if (msgnum > CC->cached_msglist[middle]) {
1675 return om_access_denied;
1680 * Determine whether the currently logged in session has permission to read
1681 * messages in the current room.
1683 int CtdlDoIHavePermissionToReadMessagesInThisRoom(void) {
1684 if ( (!(CC->logged_in))
1685 && (!(CC->internal_pgm))
1686 && (!config.c_guest_logins)
1688 return(om_not_logged_in);
1695 * Get a message off disk. (returns om_* values found in msgbase.h)
1698 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1699 int mode, /* how would you like that message? */
1700 int headers_only, /* eschew the message body? */
1701 int do_proto, /* do Citadel protocol responses? */
1702 int crlf, /* Use CRLF newlines instead of LF? */
1703 char *section, /* NULL or a message/rfc822 section */
1704 int flags, /* various flags; see msgbase.h */
1708 struct CitContext *CCC = CC;
1709 struct CtdlMessage *TheMessage = NULL;
1710 int retcode = CIT_OK;
1711 struct encapmsg encap;
1714 MSG_syslog(LOG_DEBUG, "CtdlOutputMsg(msgnum=%ld, mode=%d, section=%s)\n",
1716 (section ? section : "<>")
1719 r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
1722 if (r == om_not_logged_in) {
1723 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1726 cprintf("%d An unknown error has occurred.\n", ERROR);
1733 * Check to make sure the message is actually IN this room
1735 r = check_cached_msglist(msg_num);
1736 if (r == om_access_denied) {
1737 /* Not in the cache? We get ONE shot to check it again. */
1738 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
1739 r = check_cached_msglist(msg_num);
1742 MSG_syslog(LOG_DEBUG, "Security check fail: message %ld is not in %s\n",
1743 msg_num, CCC->room.QRname
1746 if (r == om_access_denied) {
1747 cprintf("%d message %ld was not found in this room\n",
1748 ERROR + HIGHER_ACCESS_REQUIRED,
1757 * Fetch the message from disk. If we're in HEADERS_FAST mode,
1758 * request that we don't even bother loading the body into memory.
1760 if (headers_only == HEADERS_FAST) {
1761 TheMessage = CtdlFetchMessage(msg_num, 0);
1764 TheMessage = CtdlFetchMessage(msg_num, 1);
1767 if (TheMessage == NULL) {
1768 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1769 ERROR + MESSAGE_NOT_FOUND, msg_num);
1770 return(om_no_such_msg);
1773 /* Here is the weird form of this command, to process only an
1774 * encapsulated message/rfc822 section.
1776 if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1777 memset(&encap, 0, sizeof encap);
1778 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1779 mime_parser(TheMessage->cm_fields['M'],
1781 *extract_encapsulated_message,
1782 NULL, NULL, (void *)&encap, 0
1785 if ((Author != NULL) && (*Author == NULL))
1787 *Author = TheMessage->cm_fields['A'];
1788 TheMessage->cm_fields['A'] = NULL;
1790 if ((Address != NULL) && (*Address == NULL))
1792 *Address = TheMessage->cm_fields['F'];
1793 TheMessage->cm_fields['F'] = NULL;
1795 CtdlFreeMessage(TheMessage);
1799 encap.msg[encap.msglen] = 0;
1800 TheMessage = convert_internet_message(encap.msg);
1801 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1803 /* Now we let it fall through to the bottom of this
1804 * function, because TheMessage now contains the
1805 * encapsulated message instead of the top-level
1806 * message. Isn't that neat?
1812 cprintf("%d msg %ld has no part %s\n",
1813 ERROR + MESSAGE_NOT_FOUND,
1817 retcode = om_no_such_msg;
1822 /* Ok, output the message now */
1823 if (retcode == CIT_OK)
1824 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
1825 if ((Author != NULL) && (*Author == NULL))
1827 *Author = TheMessage->cm_fields['A'];
1828 TheMessage->cm_fields['A'] = NULL;
1830 if ((Address != NULL) && (*Address == NULL))
1832 *Address = TheMessage->cm_fields['F'];
1833 TheMessage->cm_fields['F'] = NULL;
1836 CtdlFreeMessage(TheMessage);
1842 char *qp_encode_email_addrs(char *source)
1844 struct CitContext *CCC = CC;
1845 char *user, *node, *name;
1846 const char headerStr[] = "=?UTF-8?Q?";
1850 int need_to_encode = 0;
1856 long nAddrPtrMax = 50;
1861 if (source == NULL) return source;
1862 if (IsEmptyStr(source)) return source;
1863 if (MessageDebugEnabled != 0) cit_backtrace();
1864 MSG_syslog(LOG_DEBUG, "qp_encode_email_addrs: [%s]\n", source);
1866 AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
1867 AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
1868 memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
1871 while (!IsEmptyStr (&source[i])) {
1872 if (nColons >= nAddrPtrMax){
1875 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1876 memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
1877 free (AddrPtr), AddrPtr = ptr;
1879 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1880 memset(&ptr[nAddrPtrMax], 0,
1881 sizeof (long) * nAddrPtrMax);
1883 memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
1884 free (AddrUtf8), AddrUtf8 = ptr;
1887 if (((unsigned char) source[i] < 32) ||
1888 ((unsigned char) source[i] > 126)) {
1890 AddrUtf8[nColons] = 1;
1892 if (source[i] == '"')
1893 InQuotes = !InQuotes;
1894 if (!InQuotes && source[i] == ',') {
1895 AddrPtr[nColons] = i;
1900 if (need_to_encode == 0) {
1907 EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
1908 Encoded = (char*) malloc (EncodedMaxLen);
1910 for (i = 0; i < nColons; i++)
1911 source[AddrPtr[i]++] = '\0';
1912 /* TODO: if libidn, this might get larger*/
1913 user = malloc(SourceLen + 1);
1914 node = malloc(SourceLen + 1);
1915 name = malloc(SourceLen + 1);
1919 for (i = 0; i < nColons && nPtr != NULL; i++) {
1920 nmax = EncodedMaxLen - (nPtr - Encoded);
1922 process_rfc822_addr(&source[AddrPtr[i]],
1926 /* TODO: libIDN here ! */
1927 if (IsEmptyStr(name)) {
1928 n = snprintf(nPtr, nmax,
1929 (i==0)?"%s@%s" : ",%s@%s",
1933 EncodedName = rfc2047encode(name, strlen(name));
1934 n = snprintf(nPtr, nmax,
1935 (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
1936 EncodedName, user, node);
1941 n = snprintf(nPtr, nmax,
1942 (i==0)?"%s" : ",%s",
1943 &source[AddrPtr[i]]);
1949 ptr = (char*) malloc(EncodedMaxLen * 2);
1950 memcpy(ptr, Encoded, EncodedMaxLen);
1951 nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
1952 free(Encoded), Encoded = ptr;
1954 i--; /* do it once more with properly lengthened buffer */
1957 for (i = 0; i < nColons; i++)
1958 source[--AddrPtr[i]] = ',';
1969 /* If the last item in a list of recipients was truncated to a partial address,
1970 * remove it completely in order to avoid choking libSieve
1972 void sanitize_truncated_recipient(char *str)
1975 if (num_tokens(str, ',') < 2) return;
1977 int len = strlen(str);
1978 if (len < 900) return;
1979 if (len > 998) str[998] = 0;
1981 char *cptr = strrchr(str, ',');
1984 char *lptr = strchr(cptr, '<');
1985 char *rptr = strchr(cptr, '>');
1987 if ( (lptr) && (rptr) && (rptr > lptr) ) return;
1993 void OutputCtdlMsgHeaders(
1994 struct CtdlMessage *TheMessage,
1995 int do_proto) /* do Citadel protocol responses? */
2001 char display_name[256];
2003 /* begin header processing loop for Citadel message format */
2004 safestrncpy(display_name, "<unknown>", sizeof display_name);
2005 if (TheMessage->cm_fields['A']) {
2006 strcpy(buf, TheMessage->cm_fields['A']);
2007 if (TheMessage->cm_anon_type == MES_ANONONLY) {
2008 safestrncpy(display_name, "****", sizeof display_name);
2010 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
2011 safestrncpy(display_name, "anonymous", sizeof display_name);
2014 safestrncpy(display_name, buf, sizeof display_name);
2016 if ((is_room_aide())
2017 && ((TheMessage->cm_anon_type == MES_ANONONLY)
2018 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
2019 size_t tmp = strlen(display_name);
2020 snprintf(&display_name[tmp],
2021 sizeof display_name - tmp,
2026 /* Don't show Internet address for users on the
2027 * local Citadel network.
2030 if (TheMessage->cm_fields['N'] != NULL)
2031 if (!IsEmptyStr(TheMessage->cm_fields['N']))
2032 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
2036 /* Now spew the header fields in the order we like them. */
2037 n = safestrncpy(allkeys, FORDER, sizeof allkeys);
2038 for (i=0; i<n; ++i) {
2039 k = (int) allkeys[i];
2041 if ( (TheMessage->cm_fields[k] != NULL)
2042 && (msgkeys[k] != NULL) ) {
2043 if ((k == 'V') || (k == 'R') || (k == 'Y')) {
2044 sanitize_truncated_recipient(TheMessage->cm_fields[k]);
2047 if (do_proto) cprintf("%s=%s\n",
2051 else if ((k == 'F') && (suppress_f)) {
2054 /* Masquerade display name if needed */
2056 if (do_proto) cprintf("%s=%s\n",
2058 TheMessage->cm_fields[k]
2067 void OutputRFC822MsgHeaders(
2068 struct CtdlMessage *TheMessage,
2069 int flags, /* should the bessage be exported clean */
2071 char *mid, long sizeof_mid,
2072 char *suser, long sizeof_suser,
2073 char *luser, long sizeof_luser,
2074 char *fuser, long sizeof_fuser,
2075 char *snode, long sizeof_snode)
2077 char datestamp[100];
2078 int subject_found = 0;
2085 for (i = 0; i < 256; ++i) {
2086 if (TheMessage->cm_fields[i]) {
2087 mptr = mpptr = TheMessage->cm_fields[i];
2090 safestrncpy(luser, mptr, sizeof_luser);
2091 safestrncpy(suser, mptr, sizeof_suser);
2093 else if (i == 'Y') {
2094 if ((flags & QP_EADDR) != 0) {
2095 mptr = qp_encode_email_addrs(mptr);
2097 sanitize_truncated_recipient(mptr);
2098 cprintf("CC: %s%s", mptr, nl);
2100 else if (i == 'P') {
2101 cprintf("Return-Path: %s%s", mptr, nl);
2103 else if (i == 'L') {
2104 cprintf("List-ID: %s%s", mptr, nl);
2106 else if (i == 'V') {
2107 if ((flags & QP_EADDR) != 0)
2108 mptr = qp_encode_email_addrs(mptr);
2110 while ((*hptr != '\0') && isspace(*hptr))
2112 if (!IsEmptyStr(hptr))
2113 cprintf("Envelope-To: %s%s", hptr, nl);
2115 else if (i == 'U') {
2116 cprintf("Subject: %s%s", mptr, nl);
2120 safestrncpy(mid, mptr, sizeof_mid); /// TODO: detect @ here and copy @nodename in if not found.
2122 safestrncpy(fuser, mptr, sizeof_fuser);
2123 /* else if (i == 'O')
2124 cprintf("X-Citadel-Room: %s%s",
2127 safestrncpy(snode, mptr, sizeof_snode);
2130 if (haschar(mptr, '@') == 0)
2132 sanitize_truncated_recipient(mptr);
2133 cprintf("To: %s@%s", mptr, config.c_fqdn);
2138 if ((flags & QP_EADDR) != 0) {
2139 mptr = qp_encode_email_addrs(mptr);
2141 sanitize_truncated_recipient(mptr);
2142 cprintf("To: %s", mptr);
2146 else if (i == 'T') {
2147 datestring(datestamp, sizeof datestamp,
2148 atol(mptr), DATESTRING_RFC822);
2149 cprintf("Date: %s%s", datestamp, nl);
2151 else if (i == 'W') {
2152 cprintf("References: ");
2153 k = num_tokens(mptr, '|');
2154 for (j=0; j<k; ++j) {
2155 extract_token(buf, mptr, j, '|', sizeof buf);
2156 cprintf("<%s>", buf);
2165 else if (i == 'K') {
2167 while ((*hptr != '\0') && isspace(*hptr))
2169 if (!IsEmptyStr(hptr))
2170 cprintf("Reply-To: %s%s", mptr, nl);
2176 if (subject_found == 0) {
2177 cprintf("Subject: (no subject)%s", nl);
2182 void Dump_RFC822HeadersBody(
2183 struct CtdlMessage *TheMessage,
2184 int headers_only, /* eschew the message body? */
2185 int flags, /* should the bessage be exported clean? */
2189 cit_uint8_t prev_ch;
2191 const char *StartOfText = StrBufNOTNULL;
2194 int nllen = strlen(nl);
2197 mptr = TheMessage->cm_fields['M'];
2201 while (*mptr != '\0') {
2202 if (*mptr == '\r') {
2209 eoh = (*(mptr+1) == '\r') && (*(mptr+2) == '\n');
2211 eoh = *(mptr+1) == '\n';
2215 StartOfText = strchr(StartOfText, '\n');
2216 StartOfText = strchr(StartOfText, '\n');
2219 if (((headers_only == HEADERS_NONE) && (mptr >= StartOfText)) ||
2220 ((headers_only == HEADERS_ONLY) && (mptr < StartOfText)) ||
2221 ((headers_only != HEADERS_NONE) &&
2222 (headers_only != HEADERS_ONLY))
2224 if (*mptr == '\n') {
2225 memcpy(&outbuf[outlen], nl, nllen);
2227 outbuf[outlen] = '\0';
2230 outbuf[outlen++] = *mptr;
2234 if (flags & ESC_DOT)
2236 if ((prev_ch == '\n') &&
2238 ((*(mptr+1) == '\r') || (*(mptr+1) == '\n')))
2240 outbuf[outlen++] = '.';
2245 if (outlen > 1000) {
2246 if (client_write(outbuf, outlen) == -1)
2248 struct CitContext *CCC = CC;
2249 MSGM_syslog(LOG_ERR, "Dump_RFC822HeadersBody(): aborting due to write failure.\n");
2256 client_write(outbuf, outlen);
2262 /* If the format type on disk is 1 (fixed-format), then we want
2263 * everything to be output completely literally ... regardless of
2264 * what message transfer format is in use.
2266 void DumpFormatFixed(
2267 struct CtdlMessage *TheMessage,
2268 int mode, /* how would you like that message? */
2275 int nllen = strlen (nl);
2278 mptr = TheMessage->cm_fields['M'];
2280 if (mode == MT_MIME) {
2281 cprintf("Content-type: text/plain\n\n");
2285 while (ch = *mptr++, ch > 0) {
2289 if ((buflen > 250) && (!xlline)){
2293 while ((buflen > 0) &&
2294 (!isspace(buf[buflen])))
2300 mptr -= tbuflen - buflen;
2305 /* if we reach the outer bounds of our buffer,
2306 abort without respect what whe purge. */
2309 (buflen > SIZ - nllen - 2)))
2313 memcpy (&buf[buflen], nl, nllen);
2317 if (client_write(buf, buflen) == -1)
2319 struct CitContext *CCC = CC;
2320 MSGM_syslog(LOG_ERR, "DumpFormatFixed(): aborting due to write failure.\n");
2332 if (!IsEmptyStr(buf))
2333 cprintf("%s%s", buf, nl);
2337 * Get a message off disk. (returns om_* values found in msgbase.h)
2339 int CtdlOutputPreLoadedMsg(
2340 struct CtdlMessage *TheMessage,
2341 int mode, /* how would you like that message? */
2342 int headers_only, /* eschew the message body? */
2343 int do_proto, /* do Citadel protocol responses? */
2344 int crlf, /* Use CRLF newlines instead of LF? */
2345 int flags /* should the bessage be exported clean? */
2347 struct CitContext *CCC = CC;
2350 const char *nl; /* newline string */
2353 /* Buffers needed for RFC822 translation. These are all filled
2354 * using functions that are bounds-checked, and therefore we can
2355 * make them substantially smaller than SIZ.
2363 MSG_syslog(LOG_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
2364 ((TheMessage == NULL) ? "NULL" : "not null"),
2365 mode, headers_only, do_proto, crlf);
2367 strcpy(mid, "unknown");
2368 nl = (crlf ? "\r\n" : "\n");
2370 if (!is_valid_message(TheMessage)) {
2371 MSGM_syslog(LOG_ERR,
2372 "ERROR: invalid preloaded message for output\n");
2374 return(om_no_such_msg);
2377 /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2378 * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2380 if ( (flags & SUPPRESS_ENV_TO) && (TheMessage->cm_fields['V'] != NULL) ) {
2381 memset(TheMessage->cm_fields['V'], ' ', strlen(TheMessage->cm_fields['V']));
2384 /* Are we downloading a MIME component? */
2385 if (mode == MT_DOWNLOAD) {
2386 if (TheMessage->cm_format_type != FMT_RFC822) {
2388 cprintf("%d This is not a MIME message.\n",
2389 ERROR + ILLEGAL_VALUE);
2390 } else if (CCC->download_fp != NULL) {
2391 if (do_proto) cprintf(
2392 "%d You already have a download open.\n",
2393 ERROR + RESOURCE_BUSY);
2395 /* Parse the message text component */
2396 mptr = TheMessage->cm_fields['M'];
2397 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
2398 /* If there's no file open by this time, the requested
2399 * section wasn't found, so print an error
2401 if (CCC->download_fp == NULL) {
2402 if (do_proto) cprintf(
2403 "%d Section %s not found.\n",
2404 ERROR + FILE_NOT_FOUND,
2405 CCC->download_desired_section);
2408 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2411 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2412 * in a single server operation instead of opening a download file.
2414 if (mode == MT_SPEW_SECTION) {
2415 if (TheMessage->cm_format_type != FMT_RFC822) {
2417 cprintf("%d This is not a MIME message.\n",
2418 ERROR + ILLEGAL_VALUE);
2420 /* Parse the message text component */
2423 mptr = TheMessage->cm_fields['M'];
2424 mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2425 /* If section wasn't found, print an error
2428 if (do_proto) cprintf(
2429 "%d Section %s not found.\n",
2430 ERROR + FILE_NOT_FOUND,
2431 CCC->download_desired_section);
2434 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2437 /* now for the user-mode message reading loops */
2438 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2440 /* Does the caller want to skip the headers? */
2441 if (headers_only == HEADERS_NONE) goto START_TEXT;
2443 /* Tell the client which format type we're using. */
2444 if ( (mode == MT_CITADEL) && (do_proto) ) {
2445 cprintf("type=%d\n", TheMessage->cm_format_type);
2448 /* nhdr=yes means that we're only displaying headers, no body */
2449 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2450 && ((mode == MT_CITADEL) || (mode == MT_MIME))
2453 cprintf("nhdr=yes\n");
2456 if ((mode == MT_CITADEL) || (mode == MT_MIME))
2457 OutputCtdlMsgHeaders(TheMessage, do_proto);
2460 /* begin header processing loop for RFC822 transfer format */
2464 strcpy(snode, NODENAME);
2465 if (mode == MT_RFC822)
2466 OutputRFC822MsgHeaders(
2471 suser, sizeof(suser),
2472 luser, sizeof(luser),
2473 fuser, sizeof(fuser),
2474 snode, sizeof(snode)
2478 for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2479 suser[i] = tolower(suser[i]);
2480 if (!isalnum(suser[i])) suser[i]='_';
2483 if (mode == MT_RFC822) {
2484 if (!strcasecmp(snode, NODENAME)) {
2485 safestrncpy(snode, FQDN, sizeof snode);
2488 /* Construct a fun message id */
2489 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
2490 if (strchr(mid, '@')==NULL) {
2491 cprintf("@%s", snode);
2495 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2496 cprintf("From: \"----\" <x@x.org>%s", nl);
2498 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2499 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2501 else if (!IsEmptyStr(fuser)) {
2502 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2505 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2508 /* Blank line signifying RFC822 end-of-headers */
2509 if (TheMessage->cm_format_type != FMT_RFC822) {
2514 /* end header processing loop ... at this point, we're in the text */
2516 if (headers_only == HEADERS_FAST) goto DONE;
2518 /* Tell the client about the MIME parts in this message */
2519 if (TheMessage->cm_format_type == FMT_RFC822) {
2520 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2521 mptr = TheMessage->cm_fields['M'];
2522 memset(&ma, 0, sizeof(struct ma_info));
2523 mime_parser(mptr, NULL,
2524 (do_proto ? *list_this_part : NULL),
2525 (do_proto ? *list_this_pref : NULL),
2526 (do_proto ? *list_this_suff : NULL),
2529 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
2530 Dump_RFC822HeadersBody(
2539 if (headers_only == HEADERS_ONLY) {
2543 /* signify start of msg text */
2544 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2545 if (do_proto) cprintf("text\n");
2548 if (TheMessage->cm_format_type == FMT_FIXED)
2551 mode, /* how would you like that message? */
2554 /* If the message on disk is format 0 (Citadel vari-format), we
2555 * output using the formatter at 80 columns. This is the final output
2556 * form if the transfer format is RFC822, but if the transfer format
2557 * is Citadel proprietary, it'll still work, because the indentation
2558 * for new paragraphs is correct and the client will reformat the
2559 * message to the reader's screen width.
2561 if (TheMessage->cm_format_type == FMT_CITADEL) {
2562 mptr = TheMessage->cm_fields['M'];
2564 if (mode == MT_MIME) {
2565 cprintf("Content-type: text/x-citadel-variformat\n\n");
2570 /* If the message on disk is format 4 (MIME), we've gotta hand it
2571 * off to the MIME parser. The client has already been told that
2572 * this message is format 1 (fixed format), so the callback function
2573 * we use will display those parts as-is.
2575 if (TheMessage->cm_format_type == FMT_RFC822) {
2576 memset(&ma, 0, sizeof(struct ma_info));
2578 if (mode == MT_MIME) {
2579 ma.use_fo_hooks = 0;
2580 strcpy(ma.chosen_part, "1");
2581 ma.chosen_pref = 9999;
2582 ma.dont_decode = CCC->msg4_dont_decode;
2583 mime_parser(mptr, NULL,
2584 *choose_preferred, *fixed_output_pre,
2585 *fixed_output_post, (void *)&ma, 1);
2586 mime_parser(mptr, NULL,
2587 *output_preferred, NULL, NULL, (void *)&ma, 1);
2590 ma.use_fo_hooks = 1;
2591 mime_parser(mptr, NULL,
2592 *fixed_output, *fixed_output_pre,
2593 *fixed_output_post, (void *)&ma, 0);
2598 DONE: /* now we're done */
2599 if (do_proto) cprintf("000\n");
2605 * display a message (mode 0 - Citadel proprietary)
2607 void cmd_msg0(char *cmdbuf)
2610 int headers_only = HEADERS_ALL;
2612 msgid = extract_long(cmdbuf, 0);
2613 headers_only = extract_int(cmdbuf, 1);
2615 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL, 0, NULL, NULL);
2621 * display a message (mode 2 - RFC822)
2623 void cmd_msg2(char *cmdbuf)
2626 int headers_only = HEADERS_ALL;
2628 msgid = extract_long(cmdbuf, 0);
2629 headers_only = extract_int(cmdbuf, 1);
2631 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL, 0, NULL, NULL);
2637 * display a message (mode 3 - IGnet raw format - internal programs only)
2639 void cmd_msg3(char *cmdbuf)
2642 struct CtdlMessage *msg = NULL;
2645 if (CC->internal_pgm == 0) {
2646 cprintf("%d This command is for internal programs only.\n",
2647 ERROR + HIGHER_ACCESS_REQUIRED);
2651 msgnum = extract_long(cmdbuf, 0);
2652 msg = CtdlFetchMessage(msgnum, 1);
2654 cprintf("%d Message %ld not found.\n",
2655 ERROR + MESSAGE_NOT_FOUND, msgnum);
2659 serialize_message(&smr, msg);
2660 CtdlFreeMessage(msg);
2663 cprintf("%d Unable to serialize message\n",
2664 ERROR + INTERNAL_ERROR);
2668 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
2669 client_write((char *)smr.ser, (int)smr.len);
2676 * Display a message using MIME content types
2678 void cmd_msg4(char *cmdbuf)
2683 msgid = extract_long(cmdbuf, 0);
2684 extract_token(section, cmdbuf, 1, '|', sizeof section);
2685 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) , 0, NULL, NULL);
2691 * Client tells us its preferred message format(s)
2693 void cmd_msgp(char *cmdbuf)
2695 if (!strcasecmp(cmdbuf, "dont_decode")) {
2696 CC->msg4_dont_decode = 1;
2697 cprintf("%d MSG4 will not pre-decode messages.\n", CIT_OK);
2700 safestrncpy(CC->preferred_formats, cmdbuf, sizeof(CC->preferred_formats));
2701 cprintf("%d Preferred MIME formats have been set.\n", CIT_OK);
2707 * Open a component of a MIME message as a download file
2709 void cmd_opna(char *cmdbuf)
2712 char desired_section[128];
2714 msgid = extract_long(cmdbuf, 0);
2715 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2716 safestrncpy(CC->download_desired_section, desired_section,
2717 sizeof CC->download_desired_section);
2718 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL, 0, NULL, NULL);
2723 * Open a component of a MIME message and transmit it all at once
2725 void cmd_dlat(char *cmdbuf)
2728 char desired_section[128];
2730 msgid = extract_long(cmdbuf, 0);
2731 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2732 safestrncpy(CC->download_desired_section, desired_section,
2733 sizeof CC->download_desired_section);
2734 CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL, 0, NULL, NULL);
2739 * Save one or more message pointers into a specified room
2740 * (Returns 0 for success, nonzero for failure)
2741 * roomname may be NULL to use the current room
2743 * Note that the 'supplied_msg' field may be set to NULL, in which case
2744 * the message will be fetched from disk, by number, if we need to perform
2745 * replication checks. This adds an additional database read, so if the
2746 * caller already has the message in memory then it should be supplied. (Obviously
2747 * this mode of operation only works if we're saving a single message.)
2749 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2750 int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2752 struct CitContext *CCC = CC;
2754 char hold_rm[ROOMNAMELEN];
2755 struct cdbdata *cdbfr;
2758 long highest_msg = 0L;
2761 struct CtdlMessage *msg = NULL;
2763 long *msgs_to_be_merged = NULL;
2764 int num_msgs_to_be_merged = 0;
2766 MSG_syslog(LOG_DEBUG,
2767 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)\n",
2768 roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2771 strcpy(hold_rm, CCC->room.QRname);
2774 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2775 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2776 if (num_newmsgs > 1) supplied_msg = NULL;
2778 /* Now the regular stuff */
2779 if (CtdlGetRoomLock(&CCC->room,
2780 ((roomname != NULL) ? roomname : CCC->room.QRname) )
2782 MSG_syslog(LOG_ERR, "No such room <%s>\n", roomname);
2783 return(ERROR + ROOM_NOT_FOUND);
2787 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2788 num_msgs_to_be_merged = 0;
2791 cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
2792 if (cdbfr == NULL) {
2796 msglist = (long *) cdbfr->ptr;
2797 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2798 num_msgs = cdbfr->len / sizeof(long);
2803 /* Create a list of msgid's which were supplied by the caller, but do
2804 * not already exist in the target room. It is absolutely taboo to
2805 * have more than one reference to the same message in a room.
2807 for (i=0; i<num_newmsgs; ++i) {
2809 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2810 if (msglist[j] == newmsgidlist[i]) {
2815 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2819 MSG_syslog(LOG_DEBUG, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2822 * Now merge the new messages
2824 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2825 if (msglist == NULL) {
2826 MSGM_syslog(LOG_ALERT, "ERROR: can't realloc message list!\n");
2827 free(msgs_to_be_merged);
2828 return (ERROR + INTERNAL_ERROR);
2830 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2831 num_msgs += num_msgs_to_be_merged;
2833 /* Sort the message list, so all the msgid's are in order */
2834 num_msgs = sort_msglist(msglist, num_msgs);
2836 /* Determine the highest message number */
2837 highest_msg = msglist[num_msgs - 1];
2839 /* Write it back to disk. */
2840 cdb_store(CDB_MSGLISTS, &CCC->room.QRnumber, (int)sizeof(long),
2841 msglist, (int)(num_msgs * sizeof(long)));
2843 /* Free up the memory we used. */
2846 /* Update the highest-message pointer and unlock the room. */
2847 CCC->room.QRhighest = highest_msg;
2848 CtdlPutRoomLock(&CCC->room);
2850 /* Perform replication checks if necessary */
2851 if ( (DoesThisRoomNeedEuidIndexing(&CCC->room)) && (do_repl_check) ) {
2852 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2854 for (i=0; i<num_msgs_to_be_merged; ++i) {
2855 msgid = msgs_to_be_merged[i];
2857 if (supplied_msg != NULL) {
2861 msg = CtdlFetchMessage(msgid, 0);
2865 ReplicationChecks(msg);
2867 /* If the message has an Exclusive ID, index that... */
2868 if (msg->cm_fields['E'] != NULL) {
2869 index_message_by_euid(msg->cm_fields['E'], &CCC->room, msgid);
2872 /* Free up the memory we may have allocated */
2873 if (msg != supplied_msg) {
2874 CtdlFreeMessage(msg);
2882 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2885 /* Submit this room for processing by hooks */
2886 PerformRoomHooks(&CCC->room);
2888 /* Go back to the room we were in before we wandered here... */
2889 CtdlGetRoom(&CCC->room, hold_rm);
2891 /* Bump the reference count for all messages which were merged */
2892 if (!suppress_refcount_adj) {
2893 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
2896 /* Free up memory... */
2897 if (msgs_to_be_merged != NULL) {
2898 free(msgs_to_be_merged);
2901 /* Return success. */
2907 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2910 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2911 int do_repl_check, struct CtdlMessage *supplied_msg)
2913 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
2920 * Message base operation to save a new message to the message store
2921 * (returns new message number)
2923 * This is the back end for CtdlSubmitMsg() and should not be directly
2924 * called by server-side modules.
2927 long send_message(struct CtdlMessage *msg) {
2928 struct CitContext *CCC = CC;
2936 /* Get a new message number */
2937 newmsgid = get_new_message_number();
2938 snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
2939 (long unsigned int) time(NULL),
2940 (long unsigned int) newmsgid,
2944 /* Generate an ID if we don't have one already */
2945 if (msg->cm_fields['I']==NULL) {
2946 msg->cm_fields['I'] = strdup(msgidbuf);
2949 /* If the message is big, set its body aside for storage elsewhere */
2950 if (msg->cm_fields['M'] != NULL) {
2951 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2953 holdM = msg->cm_fields['M'];
2954 msg->cm_fields['M'] = NULL;
2958 /* Serialize our data structure for storage in the database */
2959 serialize_message(&smr, msg);
2962 msg->cm_fields['M'] = holdM;
2966 cprintf("%d Unable to serialize message\n",
2967 ERROR + INTERNAL_ERROR);
2971 /* Write our little bundle of joy into the message base */
2972 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2973 smr.ser, smr.len) < 0) {
2974 MSGM_syslog(LOG_ERR, "Can't store message\n");
2978 cdb_store(CDB_BIGMSGS,
2988 /* Free the memory we used for the serialized message */
2991 /* Return the *local* message ID to the caller
2992 * (even if we're storing an incoming network message)
3000 * Serialize a struct CtdlMessage into the format used on disk and network.
3002 * This function loads up a "struct ser_ret" (defined in server.h) which
3003 * contains the length of the serialized message and a pointer to the
3004 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
3006 void serialize_message(struct ser_ret *ret, /* return values */
3007 struct CtdlMessage *msg) /* unserialized msg */
3009 struct CitContext *CCC = CC;
3010 size_t wlen, fieldlen;
3012 static char *forder = FORDER;
3015 * Check for valid message format
3017 if (is_valid_message(msg) == 0) {
3018 MSGM_syslog(LOG_ERR, "serialize_message() aborting due to invalid message\n");
3025 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
3026 ret->len = ret->len +
3027 strlen(msg->cm_fields[(int)forder[i]]) + 2;
3029 ret->ser = malloc(ret->len);
3030 if (ret->ser == NULL) {
3031 MSG_syslog(LOG_ERR, "serialize_message() malloc(%ld) failed: %s\n",
3032 (long)ret->len, strerror(errno));
3039 ret->ser[1] = msg->cm_anon_type;
3040 ret->ser[2] = msg->cm_format_type;
3043 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
3044 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
3045 ret->ser[wlen++] = (char)forder[i];
3046 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
3047 wlen = wlen + fieldlen + 1;
3049 if (ret->len != wlen) {
3050 MSG_syslog(LOG_ERR, "ERROR: len=%ld wlen=%ld\n",
3051 (long)ret->len, (long)wlen);
3059 * Check to see if any messages already exist in the current room which
3060 * carry the same Exclusive ID as this one. If any are found, delete them.
3062 void ReplicationChecks(struct CtdlMessage *msg) {
3063 struct CitContext *CCC = CC;
3064 long old_msgnum = (-1L);
3066 if (DoesThisRoomNeedEuidIndexing(&CCC->room) == 0) return;
3068 MSG_syslog(LOG_DEBUG, "Performing replication checks in <%s>\n",
3071 /* No exclusive id? Don't do anything. */
3072 if (msg == NULL) return;
3073 if (msg->cm_fields['E'] == NULL) return;
3074 if (IsEmptyStr(msg->cm_fields['E'])) return;
3075 /*MSG_syslog(LOG_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
3076 msg->cm_fields['E'], CCC->room.QRname);*/
3078 old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields['E'], &CCC->room);
3079 if (old_msgnum > 0L) {
3080 MSG_syslog(LOG_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
3081 CtdlDeleteMessages(CCC->room.QRname, &old_msgnum, 1, "");
3088 * Save a message to disk and submit it into the delivery system.
3090 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
3091 struct recptypes *recps, /* recipients (if mail) */
3092 const char *force, /* force a particular room? */
3093 int flags /* should the message be exported clean? */
3096 char submit_filename[128];
3097 char generated_timestamp[32];
3098 char hold_rm[ROOMNAMELEN];
3099 char actual_rm[ROOMNAMELEN];
3100 char force_room[ROOMNAMELEN];
3101 char content_type[SIZ]; /* We have to learn this */
3102 char recipient[SIZ];
3105 const char *mptr = NULL;
3106 struct ctdluser userbuf;
3108 struct MetaData smi;
3109 FILE *network_fp = NULL;
3110 static int seqnum = 1;
3111 struct CtdlMessage *imsg = NULL;
3113 size_t instr_alloc = 0;
3115 char *hold_R, *hold_D;
3116 char *collected_addresses = NULL;
3117 struct addresses_to_be_filed *aptr = NULL;
3118 StrBuf *saved_rfc822_version = NULL;
3119 int qualified_for_journaling = 0;
3120 CitContext *CCC = MyContext();
3121 char bounce_to[1024] = "";
3124 MSGM_syslog(LOG_DEBUG, "CtdlSubmitMsg() called\n");
3125 if (is_valid_message(msg) == 0) return(-1); /* self check */
3127 /* If this message has no timestamp, we take the liberty of
3128 * giving it one, right now.
3130 if (msg->cm_fields['T'] == NULL) {
3131 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
3132 msg->cm_fields['T'] = strdup(generated_timestamp);
3135 /* If this message has no path, we generate one.
3137 if (msg->cm_fields['P'] == NULL) {
3138 if (msg->cm_fields['A'] != NULL) {
3139 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
3140 for (a=0; !IsEmptyStr(&msg->cm_fields['P'][a]); ++a) {
3141 if (isspace(msg->cm_fields['P'][a])) {
3142 msg->cm_fields['P'][a] = ' ';
3147 msg->cm_fields['P'] = strdup("unknown");
3151 if (force == NULL) {
3152 strcpy(force_room, "");
3155 strcpy(force_room, force);
3158 /* Learn about what's inside, because it's what's inside that counts */
3159 if (msg->cm_fields['M'] == NULL) {
3160 MSGM_syslog(LOG_ERR, "ERROR: attempt to save message with NULL body\n");
3164 switch (msg->cm_format_type) {
3166 strcpy(content_type, "text/x-citadel-variformat");
3169 strcpy(content_type, "text/plain");
3172 strcpy(content_type, "text/plain");
3173 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type:");
3176 safestrncpy(content_type, &mptr[13], sizeof content_type);
3177 striplt(content_type);
3178 aptr = content_type;
3179 while (!IsEmptyStr(aptr)) {
3191 /* Goto the correct room */
3192 room = (recps) ? CCC->room.QRname : SENTITEMS;
3193 MSG_syslog(LOG_DEBUG, "Selected room %s\n", room);
3194 strcpy(hold_rm, CCC->room.QRname);
3195 strcpy(actual_rm, CCC->room.QRname);
3196 if (recps != NULL) {
3197 strcpy(actual_rm, SENTITEMS);
3200 /* If the user is a twit, move to the twit room for posting */
3202 if (CCC->user.axlevel == AxProbU) {
3203 strcpy(hold_rm, actual_rm);
3204 strcpy(actual_rm, config.c_twitroom);
3205 MSGM_syslog(LOG_DEBUG, "Diverting to twit room\n");
3209 /* ...or if this message is destined for Aide> then go there. */
3210 if (!IsEmptyStr(force_room)) {
3211 strcpy(actual_rm, force_room);
3214 MSG_syslog(LOG_INFO, "Final selection: %s (%s)\n", actual_rm, room);
3215 if (strcasecmp(actual_rm, CCC->room.QRname)) {
3216 /* CtdlGetRoom(&CCC->room, actual_rm); */
3217 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL);
3221 * If this message has no O (room) field, generate one.
3223 if (msg->cm_fields['O'] == NULL) {
3224 msg->cm_fields['O'] = strdup(CCC->room.QRname);
3227 /* Perform "before save" hooks (aborting if any return nonzero) */
3228 MSGM_syslog(LOG_DEBUG, "Performing before-save hooks\n");
3229 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
3232 * If this message has an Exclusive ID, and the room is replication
3233 * checking enabled, then do replication checks.
3235 if (DoesThisRoomNeedEuidIndexing(&CCC->room)) {
3236 ReplicationChecks(msg);
3239 /* Save it to disk */
3240 MSGM_syslog(LOG_DEBUG, "Saving to disk\n");
3241 newmsgid = send_message(msg);
3242 if (newmsgid <= 0L) return(-5);
3244 /* Write a supplemental message info record. This doesn't have to
3245 * be a critical section because nobody else knows about this message
3248 MSGM_syslog(LOG_DEBUG, "Creating MetaData record\n");
3249 memset(&smi, 0, sizeof(struct MetaData));
3250 smi.meta_msgnum = newmsgid;
3251 smi.meta_refcount = 0;
3252 safestrncpy(smi.meta_content_type, content_type,
3253 sizeof smi.meta_content_type);
3256 * Measure how big this message will be when rendered as RFC822.
3257 * We do this for two reasons:
3258 * 1. We need the RFC822 length for the new metadata record, so the
3259 * POP and IMAP services don't have to calculate message lengths
3260 * while the user is waiting (multiplied by potentially hundreds
3261 * or thousands of messages).
3262 * 2. If journaling is enabled, we will need an RFC822 version of the
3263 * message to attach to the journalized copy.
3265 if (CCC->redirect_buffer != NULL) {
3266 MSGM_syslog(LOG_ALERT, "CCC->redirect_buffer is not NULL during message submission!\n");
3269 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
3270 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
3271 smi.meta_rfc822_length = StrLength(CCC->redirect_buffer);
3272 saved_rfc822_version = CCC->redirect_buffer;
3273 CCC->redirect_buffer = NULL;
3277 /* Now figure out where to store the pointers */
3278 MSGM_syslog(LOG_DEBUG, "Storing pointers\n");
3280 /* If this is being done by the networker delivering a private
3281 * message, we want to BYPASS saving the sender's copy (because there
3282 * is no local sender; it would otherwise go to the Trashcan).
3284 if ((!CCC->internal_pgm) || (recps == NULL)) {
3285 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
3286 MSGM_syslog(LOG_ERR, "ERROR saving message pointer!\n");
3287 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3291 /* For internet mail, drop a copy in the outbound queue room */
3292 if ((recps != NULL) && (recps->num_internet > 0)) {
3293 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
3296 /* If other rooms are specified, drop them there too. */
3297 if ((recps != NULL) && (recps->num_room > 0))
3298 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
3299 extract_token(recipient, recps->recp_room, i,
3300 '|', sizeof recipient);
3301 MSG_syslog(LOG_DEBUG, "Delivering to room <%s>\n", recipient);///// xxxx
3302 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
3305 /* Bump this user's messages posted counter. */
3306 MSGM_syslog(LOG_DEBUG, "Updating user\n");
3307 CtdlGetUserLock(&CCC->user, CCC->curr_user);
3308 CCC->user.posted = CCC->user.posted + 1;
3309 CtdlPutUserLock(&CCC->user);
3311 /* Decide where bounces need to be delivered */
3312 if ((recps != NULL) && (recps->bounce_to != NULL)) {
3313 safestrncpy(bounce_to, recps->bounce_to, sizeof bounce_to);
3315 else if (CCC->logged_in) {
3316 snprintf(bounce_to, sizeof bounce_to, "%s@%s", CCC->user.fullname, config.c_nodename);
3319 snprintf(bounce_to, sizeof bounce_to, "%s@%s", msg->cm_fields['A'], msg->cm_fields['N']);
3322 /* If this is private, local mail, make a copy in the
3323 * recipient's mailbox and bump the reference count.
3325 if ((recps != NULL) && (recps->num_local > 0))
3326 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
3327 extract_token(recipient, recps->recp_local, i,
3328 '|', sizeof recipient);
3329 MSG_syslog(LOG_DEBUG, "Delivering private local mail to <%s>\n",
3331 if (CtdlGetUser(&userbuf, recipient) == 0) {
3332 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
3333 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
3334 CtdlBumpNewMailCounter(userbuf.usernum);
3335 if (!IsEmptyStr(config.c_funambol_host) || !IsEmptyStr(config.c_pager_program)) {
3336 /* Generate a instruction message for the Funambol notification
3337 * server, in the same style as the SMTP queue
3340 instr = malloc(instr_alloc);
3341 snprintf(instr, instr_alloc,
3342 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
3344 SPOOLMIME, newmsgid, (long)time(NULL),
3348 imsg = malloc(sizeof(struct CtdlMessage));
3349 memset(imsg, 0, sizeof(struct CtdlMessage));
3350 imsg->cm_magic = CTDLMESSAGE_MAGIC;
3351 imsg->cm_anon_type = MES_NORMAL;
3352 imsg->cm_format_type = FMT_RFC822;
3353 imsg->cm_fields['U'] = strdup("QMSG");
3354 imsg->cm_fields['A'] = strdup("Citadel");
3355 imsg->cm_fields['J'] = strdup("do not journal");
3356 imsg->cm_fields['M'] = instr; /* imsg owns this memory now */
3357 imsg->cm_fields['2'] = strdup(recipient);
3358 CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM, 0);
3359 CtdlFreeMessage(imsg);
3363 MSG_syslog(LOG_DEBUG, "No user <%s>\n", recipient);
3364 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3368 /* Perform "after save" hooks */
3369 MSGM_syslog(LOG_DEBUG, "Performing after-save hooks\n");
3370 if (msg->cm_fields['3'] != NULL) free(msg->cm_fields['3']);
3371 msg->cm_fields['3'] = malloc(20);
3372 snprintf(msg->cm_fields['3'], 20, "%ld", newmsgid);
3373 PerformMessageHooks(msg, EVT_AFTERSAVE);
3374 free(msg->cm_fields['3']);
3375 msg->cm_fields['3'] = NULL;
3377 /* For IGnet mail, we have to save a new copy into the spooler for
3378 * each recipient, with the R and D fields set to the recipient and
3379 * destination-node. This has two ugly side effects: all other
3380 * recipients end up being unlisted in this recipient's copy of the
3381 * message, and it has to deliver multiple messages to the same
3382 * node. We'll revisit this again in a year or so when everyone has
3383 * a network spool receiver that can handle the new style messages.
3385 if ((recps != NULL) && (recps->num_ignet > 0))
3386 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
3387 extract_token(recipient, recps->recp_ignet, i,
3388 '|', sizeof recipient);
3390 hold_R = msg->cm_fields['R'];
3391 hold_D = msg->cm_fields['D'];
3392 msg->cm_fields['R'] = malloc(SIZ);
3393 msg->cm_fields['D'] = malloc(128);
3394 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
3395 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
3397 serialize_message(&smr, msg);
3399 snprintf(submit_filename, sizeof submit_filename,
3400 "%s/netmail.%04lx.%04x.%04x",
3402 (long) getpid(), CCC->cs_pid, ++seqnum);
3403 network_fp = fopen(submit_filename, "wb+");
3404 if (network_fp != NULL) {
3405 rv = fwrite(smr.ser, smr.len, 1, network_fp);
3407 MSG_syslog(LOG_EMERG, "CtdlSubmitMsg(): Couldn't write network spool file: %s\n",
3415 free(msg->cm_fields['R']);
3416 free(msg->cm_fields['D']);
3417 msg->cm_fields['R'] = hold_R;
3418 msg->cm_fields['D'] = hold_D;
3421 /* Go back to the room we started from */
3422 MSG_syslog(LOG_DEBUG, "Returning to original room %s\n", hold_rm);
3423 if (strcasecmp(hold_rm, CCC->room.QRname))
3424 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL);
3426 /* For internet mail, generate delivery instructions.
3427 * Yes, this is recursive. Deal with it. Infinite recursion does
3428 * not happen because the delivery instructions message does not
3429 * contain a recipient.
3431 if ((recps != NULL) && (recps->num_internet > 0)) {
3432 StrBuf *SpoolMsg = NewStrBuf();
3435 MSGM_syslog(LOG_DEBUG, "Generating delivery instructions\n");
3437 StrBufPrintf(SpoolMsg,
3438 "Content-type: "SPOOLMIME"\n"
3447 if (recps->envelope_from != NULL) {
3448 StrBufAppendBufPlain(SpoolMsg, HKEY("envelope_from|"), 0);
3449 StrBufAppendBufPlain(SpoolMsg, recps->envelope_from, -1, 0);
3450 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3452 if (recps->sending_room != NULL) {
3453 StrBufAppendBufPlain(SpoolMsg, HKEY("source_room|"), 0);
3454 StrBufAppendBufPlain(SpoolMsg, recps->sending_room, -1, 0);
3455 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3458 nTokens = num_tokens(recps->recp_internet, '|');
3459 for (i = 0; i < nTokens; i++) {
3461 len = extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
3463 StrBufAppendBufPlain(SpoolMsg, HKEY("remote|"), 0);
3464 StrBufAppendBufPlain(SpoolMsg, recipient, len, 0);
3465 StrBufAppendBufPlain(SpoolMsg, HKEY("|0||\n"), 0);
3469 imsg = malloc(sizeof(struct CtdlMessage));
3470 memset(imsg, 0, sizeof(struct CtdlMessage));
3471 imsg->cm_magic = CTDLMESSAGE_MAGIC;
3472 imsg->cm_anon_type = MES_NORMAL;
3473 imsg->cm_format_type = FMT_RFC822;
3474 imsg->cm_fields['U'] = strdup("QMSG");
3475 imsg->cm_fields['A'] = strdup("Citadel");
3476 imsg->cm_fields['J'] = strdup("do not journal");
3477 imsg->cm_fields['M'] = SmashStrBuf(&SpoolMsg); /* imsg owns this memory now */
3478 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
3479 CtdlFreeMessage(imsg);
3483 * Any addresses to harvest for someone's address book?
3485 if ( (CCC->logged_in) && (recps != NULL) ) {
3486 collected_addresses = harvest_collected_addresses(msg);
3489 if (collected_addresses != NULL) {
3490 aptr = (struct addresses_to_be_filed *)
3491 malloc(sizeof(struct addresses_to_be_filed));
3492 CtdlMailboxName(actual_rm, sizeof actual_rm,
3493 &CCC->user, USERCONTACTSROOM);
3494 aptr->roomname = strdup(actual_rm);
3495 aptr->collected_addresses = collected_addresses;
3496 begin_critical_section(S_ATBF);
3499 end_critical_section(S_ATBF);
3503 * Determine whether this message qualifies for journaling.
3505 if (msg->cm_fields['J'] != NULL) {
3506 qualified_for_journaling = 0;
3509 if (recps == NULL) {
3510 qualified_for_journaling = config.c_journal_pubmsgs;
3512 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
3513 qualified_for_journaling = config.c_journal_email;
3516 qualified_for_journaling = config.c_journal_pubmsgs;
3521 * Do we have to perform journaling? If so, hand off the saved
3522 * RFC822 version will be handed off to the journaler for background
3523 * submit. Otherwise, we have to free the memory ourselves.
3525 if (saved_rfc822_version != NULL) {
3526 if (qualified_for_journaling) {
3527 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
3530 FreeStrBuf(&saved_rfc822_version);
3540 * Convenience function for generating small administrative messages.
3542 void quickie_message(const char *from,
3543 const char *fromaddr,
3548 const char *subject)
3550 struct CtdlMessage *msg;
3551 struct recptypes *recp = NULL;
3553 msg = malloc(sizeof(struct CtdlMessage));
3554 memset(msg, 0, sizeof(struct CtdlMessage));
3555 msg->cm_magic = CTDLMESSAGE_MAGIC;
3556 msg->cm_anon_type = MES_NORMAL;
3557 msg->cm_format_type = format_type;
3560 msg->cm_fields['A'] = strdup(from);
3562 else if (fromaddr != NULL) {
3563 msg->cm_fields['A'] = strdup(fromaddr);
3564 if (strchr(msg->cm_fields['A'], '@')) {
3565 *strchr(msg->cm_fields['A'], '@') = 0;
3569 msg->cm_fields['A'] = strdup("Citadel");
3572 if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
3573 if (room != NULL) msg->cm_fields['O'] = strdup(room);
3574 msg->cm_fields['N'] = strdup(NODENAME);
3576 msg->cm_fields['R'] = strdup(to);
3577 recp = validate_recipients(to, NULL, 0);
3579 if (subject != NULL) {
3580 msg->cm_fields['U'] = strdup(subject);
3582 msg->cm_fields['M'] = strdup(text);
3584 CtdlSubmitMsg(msg, recp, room, 0);
3585 CtdlFreeMessage(msg);
3586 if (recp != NULL) free_recipients(recp);
3589 void flood_protect_quickie_message(const char *from,
3590 const char *fromaddr,
3595 const char *subject,
3597 const char **CritStr,
3602 u_char rawdigest[MD5_DIGEST_LEN];
3603 struct MD5Context md5context;
3605 struct cdbdata *cdbut;
3608 time_t ts = time(NULL);
3609 time_t tsday = ts / (8*60*60); /* just care for a day... */
3611 tslen = snprintf(timestamp, sizeof(timestamp), "%ld", tsday);
3612 MD5Init(&md5context);
3614 for (i = 0; i < nCriterions; i++)
3615 MD5Update(&md5context,
3616 (const unsigned char*)CritStr[i], CritStrLen[i]);
3617 MD5Update(&md5context,
3618 (const unsigned char*)timestamp, tslen);
3619 MD5Final(rawdigest, &md5context);
3621 guid = NewStrBufPlain(NULL,
3622 MD5_DIGEST_LEN * 2 + 12);
3623 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
3624 StrBufAppendBufPlain(guid, HKEY("_fldpt"), 0);
3625 if (StrLength(guid) > 40)
3626 StrBufCutAt(guid, 40, NULL);
3627 /* Find out if we've already sent a similar message */
3628 memcpy(ut.ut_msgid, SKEY(guid));
3629 ut.ut_timestamp = ts;
3631 cdbut = cdb_fetch(CDB_USETABLE, SKEY(guid));
3633 if (cdbut != NULL) {
3634 /* yes, we did. flood protection kicks in. */
3636 "not sending message again\n");
3640 /* rewrite the record anyway, to update the timestamp */
3641 cdb_store(CDB_USETABLE,
3643 &ut, sizeof(struct UseTable) );
3647 if (cdbut != NULL) return;
3648 /* no, this message isn't sent recently; go ahead. */
3649 quickie_message(from,
3660 * Back end function used by CtdlMakeMessage() and similar functions
3662 StrBuf *CtdlReadMessageBodyBuf(char *terminator, /* token signalling EOT */
3664 size_t maxlen, /* maximum message length */
3665 StrBuf *exist, /* if non-null, append to it;
3666 exist is ALWAYS freed */
3667 int crlf, /* CRLF newlines instead of LF */
3668 int *sock /* socket handle or 0 for this session's client socket */
3677 LineBuf = NewStrBufPlain(NULL, SIZ);
3678 if (exist == NULL) {
3679 Message = NewStrBufPlain(NULL, 4 * SIZ);
3682 Message = NewStrBufDup(exist);
3685 /* Do we need to change leading ".." to "." for SMTP escaping? */
3686 if ((tlen == 1) && (*terminator == '.')) {
3690 /* read in the lines of message text one by one */
3693 if ((CtdlSockGetLine(sock, LineBuf, 5) < 0) ||
3698 if (CtdlClientGetLine(LineBuf) < 0) finished = 1;
3700 if ((StrLength(LineBuf) == tlen) &&
3701 (!strcmp(ChrPtr(LineBuf), terminator)))
3704 if ( (!flushing) && (!finished) ) {
3706 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3709 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3712 /* Unescape SMTP-style input of two dots at the beginning of the line */
3714 (StrLength(LineBuf) == 2) &&
3715 (!strcmp(ChrPtr(LineBuf), "..")))
3717 StrBufCutLeft(LineBuf, 1);
3720 StrBufAppendBuf(Message, LineBuf, 0);
3723 /* if we've hit the max msg length, flush the rest */
3724 if (StrLength(Message) >= maxlen) flushing = 1;
3726 } while (!finished);
3727 FreeStrBuf(&LineBuf);
3731 void DeleteAsyncMsg(ReadAsyncMsg **Msg)
3735 FreeStrBuf(&(*Msg)->MsgBuf);
3741 ReadAsyncMsg *NewAsyncMsg(const char *terminator, /* token signalling EOT */
3743 size_t maxlen, /* maximum message length */
3744 size_t expectlen, /* if we expect a message, how long should it be? */
3745 StrBuf *exist, /* if non-null, append to it;
3746 exist is ALWAYS freed */
3747 long eLen, /* length of exist */
3748 int crlf /* CRLF newlines instead of LF */
3751 ReadAsyncMsg *NewMsg;
3753 NewMsg = (ReadAsyncMsg *)malloc(sizeof(ReadAsyncMsg));
3754 memset(NewMsg, 0, sizeof(ReadAsyncMsg));
3756 if (exist == NULL) {
3759 if (expectlen == 0) {
3763 len = expectlen + 10;
3765 NewMsg->MsgBuf = NewStrBufPlain(NULL, len);
3768 NewMsg->MsgBuf = NewStrBufDup(exist);
3770 /* Do we need to change leading ".." to "." for SMTP escaping? */
3771 if ((tlen == 1) && (*terminator == '.')) {
3775 NewMsg->terminator = terminator;
3776 NewMsg->tlen = tlen;
3778 NewMsg->maxlen = maxlen;
3780 NewMsg->crlf = crlf;
3786 * Back end function used by CtdlMakeMessage() and similar functions
3788 eReadState CtdlReadMessageBodyAsync(AsyncIO *IO)
3790 ReadAsyncMsg *ReadMsg;
3791 int MsgFinished = 0;
3792 eReadState Finished = eMustReadMore;
3797 const char *pch = ChrPtr(IO->SendBuf.Buf);
3798 const char *pchh = IO->SendBuf.ReadWritePointer;
3804 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
3805 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
3806 ((CitContext*)(IO->CitContext))->ServiceName,
3809 fd = fopen(fn, "a+");
3812 ReadMsg = IO->ReadMsg;
3814 /* read in the lines of message text one by one */
3816 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
3819 case eMustReadMore: /// read new from socket...
3821 if (IO->RecvBuf.ReadWritePointer != NULL) {
3822 nbytes = StrLength(IO->RecvBuf.Buf) - (IO->RecvBuf.ReadWritePointer - ChrPtr(IO->RecvBuf.Buf));
3823 fprintf(fd, "Read; Line unfinished: %ld Bytes still in buffer [", nbytes);
3825 fwrite(IO->RecvBuf.ReadWritePointer, nbytes, 1, fd);
3829 fprintf(fd, "BufferEmpty! \n");
3835 case eBufferNotEmpty: /* shouldn't happen... */
3836 case eReadSuccess: /// done for now...
3838 case eReadFail: /// WHUT?
3844 if ((StrLength(IO->IOBuf) == ReadMsg->tlen) &&
3845 (!strcmp(ChrPtr(IO->IOBuf), ReadMsg->terminator))) {
3848 fprintf(fd, "found Terminator; Message Size: %d\n", StrLength(ReadMsg->MsgBuf));
3851 else if (!ReadMsg->flushing) {
3854 fprintf(fd, "Read Line: [%d][%s]\n", StrLength(IO->IOBuf), ChrPtr(IO->IOBuf));
3857 /* Unescape SMTP-style input of two dots at the beginning of the line */
3858 if ((ReadMsg->dodot) &&
3859 (StrLength(IO->IOBuf) == 2) && /* TODO: do we just unescape lines with two dots or any line? */
3860 (!strcmp(ChrPtr(IO->IOBuf), "..")))
3863 fprintf(fd, "UnEscaped!\n");
3865 StrBufCutLeft(IO->IOBuf, 1);
3868 if (ReadMsg->crlf) {
3869 StrBufAppendBufPlain(IO->IOBuf, HKEY("\r\n"), 0);
3872 StrBufAppendBufPlain(IO->IOBuf, HKEY("\n"), 0);
3875 StrBufAppendBuf(ReadMsg->MsgBuf, IO->IOBuf, 0);
3878 /* if we've hit the max msg length, flush the rest */
3879 if (StrLength(ReadMsg->MsgBuf) >= ReadMsg->maxlen) ReadMsg->flushing = 1;
3881 } while (!MsgFinished);
3884 fprintf(fd, "Done with reading; %s.\n, ",
3885 (MsgFinished)?"Message Finished": "FAILED");
3889 return eReadSuccess;
3896 * Back end function used by CtdlMakeMessage() and similar functions
3898 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
3900 size_t maxlen, /* maximum message length */
3901 StrBuf *exist, /* if non-null, append to it;
3902 exist is ALWAYS freed */
3903 int crlf, /* CRLF newlines instead of LF */
3904 int *sock /* socket handle or 0 for this session's client socket */
3909 Message = CtdlReadMessageBodyBuf(terminator,
3915 if (Message == NULL)
3918 return SmashStrBuf(&Message);
3923 * Build a binary message to be saved on disk.
3924 * (NOTE: if you supply 'preformatted_text', the buffer you give it
3925 * will become part of the message. This means you are no longer
3926 * responsible for managing that memory -- it will be freed along with
3927 * the rest of the fields when CtdlFreeMessage() is called.)
3930 struct CtdlMessage *CtdlMakeMessage(
3931 struct ctdluser *author, /* author's user structure */
3932 char *recipient, /* NULL if it's not mail */
3933 char *recp_cc, /* NULL if it's not mail */
3934 char *room, /* room where it's going */
3935 int type, /* see MES_ types in header file */
3936 int format_type, /* variformat, plain text, MIME... */
3937 char *fake_name, /* who we're masquerading as */
3938 char *my_email, /* which of my email addresses to use (empty is ok) */
3939 char *subject, /* Subject (optional) */
3940 char *supplied_euid, /* ...or NULL if this is irrelevant */
3941 char *preformatted_text, /* ...or NULL to read text from client */
3942 char *references /* Thread references */
3944 char dest_node[256];
3946 struct CtdlMessage *msg;
3948 StrBuf *FakeEncAuthor = NULL;
3950 msg = malloc(sizeof(struct CtdlMessage));
3951 memset(msg, 0, sizeof(struct CtdlMessage));
3952 msg->cm_magic = CTDLMESSAGE_MAGIC;
3953 msg->cm_anon_type = type;
3954 msg->cm_format_type = format_type;
3956 /* Don't confuse the poor folks if it's not routed mail. */
3957 strcpy(dest_node, "");
3959 if (recipient != NULL) striplt(recipient);
3960 if (recp_cc != NULL) striplt(recp_cc);
3962 /* Path or Return-Path */
3963 if (my_email == NULL) my_email = "";
3965 if (!IsEmptyStr(my_email)) {
3966 msg->cm_fields['P'] = strdup(my_email);
3969 snprintf(buf, sizeof buf, "%s", author->fullname);
3970 msg->cm_fields['P'] = strdup(buf);
3972 convert_spaces_to_underscores(msg->cm_fields['P']);
3974 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
3975 msg->cm_fields['T'] = strdup(buf);
3977 if ((fake_name != NULL) && (fake_name[0])) { /* author */
3978 FakeAuthor = NewStrBufPlain (fake_name, -1);
3981 FakeAuthor = NewStrBufPlain (author->fullname, -1);
3983 StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
3984 msg->cm_fields['A'] = SmashStrBuf(&FakeEncAuthor);
3985 FreeStrBuf(&FakeAuthor);
3987 if (CC->room.QRflags & QR_MAILBOX) { /* room */
3988 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
3991 msg->cm_fields['O'] = strdup(CC->room.QRname);
3994 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
3995 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
3997 if ((recipient != NULL) && (recipient[0] != 0)) {
3998 msg->cm_fields['R'] = strdup(recipient);
4000 if ((recp_cc != NULL) && (recp_cc[0] != 0)) {
4001 msg->cm_fields['Y'] = strdup(recp_cc);
4003 if (dest_node[0] != 0) {
4004 msg->cm_fields['D'] = strdup(dest_node);
4007 if (!IsEmptyStr(my_email)) {
4008 msg->cm_fields['F'] = strdup(my_email);
4010 else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
4011 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
4014 if (subject != NULL) {
4017 length = strlen(subject);
4023 while ((subject[i] != '\0') &&
4024 (IsAscii = isascii(subject[i]) != 0 ))
4027 msg->cm_fields['U'] = strdup(subject);
4028 else /* ok, we've got utf8 in the string. */
4030 msg->cm_fields['U'] = rfc2047encode(subject, length);
4036 if (supplied_euid != NULL) {
4037 msg->cm_fields['E'] = strdup(supplied_euid);
4040 if ((references != NULL) && (!IsEmptyStr(references))) {
4041 if (msg->cm_fields['W'] != NULL)
4042 free(msg->cm_fields['W']);
4043 msg->cm_fields['W'] = strdup(references);
4046 if (preformatted_text != NULL) {
4047 msg->cm_fields['M'] = preformatted_text;
4050 msg->cm_fields['M'] = CtdlReadMessageBody(HKEY("000"), config.c_maxmsglen, NULL, 0, 0);
4057 * Check to see whether we have permission to post a message in the current
4058 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
4059 * returns 0 on success.
4061 int CtdlDoIHavePermissionToPostInThisRoom(
4064 const char* RemoteIdentifier,
4070 if (!(CC->logged_in) &&
4071 (PostPublic == POST_LOGGED_IN)) {
4072 snprintf(errmsgbuf, n, "Not logged in.");
4073 return (ERROR + NOT_LOGGED_IN);
4075 else if (PostPublic == CHECK_EXISTANCE) {
4076 return (0); // We're Evaling whether a recipient exists
4078 else if (!(CC->logged_in)) {
4080 if ((CC->room.QRflags & QR_READONLY)) {
4081 snprintf(errmsgbuf, n, "Not logged in.");
4082 return (ERROR + NOT_LOGGED_IN);
4084 if (CC->room.QRflags2 & QR2_MODERATED) {
4085 snprintf(errmsgbuf, n, "Not logged in Moderation feature not yet implemented!");
4086 return (ERROR + NOT_LOGGED_IN);
4088 if ((PostPublic!=POST_LMTP) &&(CC->room.QRflags2 & QR2_SMTP_PUBLIC) == 0) {
4090 return CtdlNetconfigCheckRoomaccess(errmsgbuf, n, RemoteIdentifier);
4096 if ((CC->user.axlevel < AxProbU)
4097 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
4098 snprintf(errmsgbuf, n, "Need to be validated to enter (except in %s> to sysop)", MAILROOM);
4099 return (ERROR + HIGHER_ACCESS_REQUIRED);
4102 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
4104 if (ra & UA_POSTALLOWED) {
4105 strcpy(errmsgbuf, "OK to post or reply here");
4109 if ( (ra & UA_REPLYALLOWED) && (is_reply) ) {
4111 * To be thorough, we ought to check to see if the message they are
4112 * replying to is actually a valid one in this room, but unless this
4113 * actually becomes a problem we'll go with high performance instead.
4115 strcpy(errmsgbuf, "OK to reply here");
4119 if ( (ra & UA_REPLYALLOWED) && (!is_reply) ) {
4120 /* Clarify what happened with a better error message */
4121 snprintf(errmsgbuf, n, "You may only reply to existing messages here.");
4122 return (ERROR + HIGHER_ACCESS_REQUIRED);
4125 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
4126 return (ERROR + HIGHER_ACCESS_REQUIRED);
4132 * Check to see if the specified user has Internet mail permission
4133 * (returns nonzero if permission is granted)
4135 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
4137 /* Do not allow twits to send Internet mail */
4138 if (who->axlevel <= AxProbU) return(0);
4140 /* Globally enabled? */
4141 if (config.c_restrict == 0) return(1);
4143 /* User flagged ok? */
4144 if (who->flags & US_INTERNET) return(2);
4146 /* Admin level access? */
4147 if (who->axlevel >= AxAideU) return(3);
4149 /* No mail for you! */
4155 * Validate recipients, count delivery types and errors, and handle aliasing
4156 * FIXME check for dupes!!!!!
4158 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
4159 * were specified, or the number of addresses found invalid.
4161 * Caller needs to free the result using free_recipients()
4163 struct recptypes *validate_recipients(const char *supplied_recipients,
4164 const char *RemoteIdentifier,
4166 struct CitContext *CCC = CC;
4167 struct recptypes *ret;
4168 char *recipients = NULL;
4170 char this_recp[256];
4171 char this_recp_cooked[256];
4178 struct ctdluser tempUS;
4179 struct ctdlroom tempQR;
4180 struct ctdlroom tempQR2;
4186 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
4187 if (ret == NULL) return(NULL);
4189 /* Set all strings to null and numeric values to zero */
4190 memset(ret, 0, sizeof(struct recptypes));
4192 if (supplied_recipients == NULL) {
4193 recipients = strdup("");
4196 recipients = strdup(supplied_recipients);
4199 /* Allocate some memory. Yes, this allocates 500% more memory than we will
4200 * actually need, but it's healthier for the heap than doing lots of tiny
4201 * realloc() calls instead.
4203 len = strlen(recipients) + 1024;
4204 ret->errormsg = malloc(len);
4205 ret->recp_local = malloc(len);
4206 ret->recp_internet = malloc(len);
4207 ret->recp_ignet = malloc(len);
4208 ret->recp_room = malloc(len);
4209 ret->display_recp = malloc(len);
4210 ret->recp_orgroom = malloc(len);
4211 org_recp = malloc(len);
4213 ret->errormsg[0] = 0;
4214 ret->recp_local[0] = 0;
4215 ret->recp_internet[0] = 0;
4216 ret->recp_ignet[0] = 0;
4217 ret->recp_room[0] = 0;
4218 ret->recp_orgroom[0] = 0;
4219 ret->display_recp[0] = 0;
4221 ret->recptypes_magic = RECPTYPES_MAGIC;
4223 /* Change all valid separator characters to commas */
4224 for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
4225 if ((recipients[i] == ';') || (recipients[i] == '|')) {
4226 recipients[i] = ',';
4230 /* Now start extracting recipients... */
4232 while (!IsEmptyStr(recipients)) {
4233 for (i=0; i<=strlen(recipients); ++i) {
4234 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
4235 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
4236 safestrncpy(this_recp, recipients, i+1);
4238 if (recipients[i] == ',') {
4239 strcpy(recipients, &recipients[i+1]);
4242 strcpy(recipients, "");
4249 if (IsEmptyStr(this_recp))
4251 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
4254 strcpy(org_recp, this_recp);
4257 mailtype = alias(this_recp);
4259 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
4260 if (this_recp[j]=='_') {
4261 this_recp_cooked[j] = ' ';
4264 this_recp_cooked[j] = this_recp[j];
4267 this_recp_cooked[j] = '\0';
4272 if (!strcasecmp(this_recp, "sysop")) {
4274 strcpy(this_recp, config.c_aideroom);
4275 if (!IsEmptyStr(ret->recp_room)) {
4276 strcat(ret->recp_room, "|");
4278 strcat(ret->recp_room, this_recp);
4280 else if ( (!strncasecmp(this_recp, "room_", 5))
4281 && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
4283 /* Save room so we can restore it later */
4284 tempQR2 = CCC->room;
4287 /* Check permissions to send mail to this room */
4288 err = CtdlDoIHavePermissionToPostInThisRoom(
4293 0 /* 0 = not a reply */
4302 if (!IsEmptyStr(ret->recp_room)) {
4303 strcat(ret->recp_room, "|");
4305 strcat(ret->recp_room, &this_recp_cooked[5]);
4307 if (!IsEmptyStr(ret->recp_orgroom)) {
4308 strcat(ret->recp_orgroom, "|");
4310 strcat(ret->recp_orgroom, org_recp);
4314 /* Restore room in case something needs it */
4315 CCC->room = tempQR2;
4318 else if (CtdlGetUser(&tempUS, this_recp) == 0) {
4320 strcpy(this_recp, tempUS.fullname);
4321 if (!IsEmptyStr(ret->recp_local)) {
4322 strcat(ret->recp_local, "|");
4324 strcat(ret->recp_local, this_recp);
4326 else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
4328 strcpy(this_recp, tempUS.fullname);
4329 if (!IsEmptyStr(ret->recp_local)) {
4330 strcat(ret->recp_local, "|");
4332 strcat(ret->recp_local, this_recp);
4340 /* Yes, you're reading this correctly: if the target
4341 * domain points back to the local system or an attached
4342 * Citadel directory, the address is invalid. That's
4343 * because if the address were valid, we would have
4344 * already translated it to a local address by now.
4346 if (IsDirectory(this_recp, 0)) {
4351 ++ret->num_internet;
4352 if (!IsEmptyStr(ret->recp_internet)) {
4353 strcat(ret->recp_internet, "|");
4355 strcat(ret->recp_internet, this_recp);
4360 if (!IsEmptyStr(ret->recp_ignet)) {
4361 strcat(ret->recp_ignet, "|");
4363 strcat(ret->recp_ignet, this_recp);
4371 if (IsEmptyStr(errmsg)) {
4372 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
4375 snprintf(append, sizeof append, "%s", errmsg);
4377 if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
4378 if (!IsEmptyStr(ret->errormsg)) {
4379 strcat(ret->errormsg, "; ");
4381 strcat(ret->errormsg, append);
4385 if (IsEmptyStr(ret->display_recp)) {
4386 strcpy(append, this_recp);
4389 snprintf(append, sizeof append, ", %s", this_recp);
4391 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
4392 strcat(ret->display_recp, append);
4398 if ((ret->num_local + ret->num_internet + ret->num_ignet +
4399 ret->num_room + ret->num_error) == 0) {
4400 ret->num_error = (-1);
4401 strcpy(ret->errormsg, "No recipients specified.");
4404 MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
4405 MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
4406 MSG_syslog(LOG_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
4407 MSG_syslog(LOG_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
4408 MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
4409 MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
4417 * Destructor for struct recptypes
4419 void free_recipients(struct recptypes *valid) {
4421 if (valid == NULL) {
4425 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
4426 struct CitContext *CCC = CC;
4427 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
4431 if (valid->errormsg != NULL) free(valid->errormsg);
4432 if (valid->recp_local != NULL) free(valid->recp_local);
4433 if (valid->recp_internet != NULL) free(valid->recp_internet);
4434 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
4435 if (valid->recp_room != NULL) free(valid->recp_room);
4436 if (valid->recp_orgroom != NULL) free(valid->recp_orgroom);
4437 if (valid->display_recp != NULL) free(valid->display_recp);
4438 if (valid->bounce_to != NULL) free(valid->bounce_to);
4439 if (valid->envelope_from != NULL) free(valid->envelope_from);
4440 if (valid->sending_room != NULL) free(valid->sending_room);
4447 * message entry - mode 0 (normal)
4449 void cmd_ent0(char *entargs)
4451 struct CitContext *CCC = CC;
4456 char supplied_euid[128];
4458 int format_type = 0;
4459 char newusername[256];
4460 char newuseremail[256];
4461 struct CtdlMessage *msg;
4465 struct recptypes *valid = NULL;
4466 struct recptypes *valid_to = NULL;
4467 struct recptypes *valid_cc = NULL;
4468 struct recptypes *valid_bcc = NULL;
4470 int subject_required = 0;
4475 int newuseremail_ok = 0;
4476 char references[SIZ];
4481 post = extract_int(entargs, 0);
4482 extract_token(recp, entargs, 1, '|', sizeof recp);
4483 anon_flag = extract_int(entargs, 2);
4484 format_type = extract_int(entargs, 3);
4485 extract_token(subject, entargs, 4, '|', sizeof subject);
4486 extract_token(newusername, entargs, 5, '|', sizeof newusername);
4487 do_confirm = extract_int(entargs, 6);
4488 extract_token(cc, entargs, 7, '|', sizeof cc);
4489 extract_token(bcc, entargs, 8, '|', sizeof bcc);
4490 switch(CC->room.QRdefaultview) {
4493 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
4496 supplied_euid[0] = 0;
4499 extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
4500 extract_token(references, entargs, 11, '|', sizeof references);
4501 for (ptr=references; *ptr != 0; ++ptr) {
4502 if (*ptr == '!') *ptr = '|';
4505 /* first check to make sure the request is valid. */
4507 err = CtdlDoIHavePermissionToPostInThisRoom(
4512 (!IsEmptyStr(references)) /* is this a reply? or a top-level post? */
4516 cprintf("%d %s\n", err, errmsg);
4520 /* Check some other permission type things. */
4522 if (IsEmptyStr(newusername)) {
4523 strcpy(newusername, CCC->user.fullname);
4525 if ( (CCC->user.axlevel < AxAideU)
4526 && (strcasecmp(newusername, CCC->user.fullname))
4527 && (strcasecmp(newusername, CCC->cs_inet_fn))
4529 cprintf("%d You don't have permission to author messages as '%s'.\n",
4530 ERROR + HIGHER_ACCESS_REQUIRED,
4537 if (IsEmptyStr(newuseremail)) {
4538 newuseremail_ok = 1;
4541 if (!IsEmptyStr(newuseremail)) {
4542 if (!strcasecmp(newuseremail, CCC->cs_inet_email)) {
4543 newuseremail_ok = 1;
4545 else if (!IsEmptyStr(CCC->cs_inet_other_emails)) {
4546 j = num_tokens(CCC->cs_inet_other_emails, '|');
4547 for (i=0; i<j; ++i) {
4548 extract_token(buf, CCC->cs_inet_other_emails, i, '|', sizeof buf);
4549 if (!strcasecmp(newuseremail, buf)) {
4550 newuseremail_ok = 1;
4556 if (!newuseremail_ok) {
4557 cprintf("%d You don't have permission to author messages as '%s'.\n",
4558 ERROR + HIGHER_ACCESS_REQUIRED,
4564 CCC->cs_flags |= CS_POSTING;
4566 /* In mailbox rooms we have to behave a little differently --
4567 * make sure the user has specified at least one recipient. Then
4568 * validate the recipient(s). We do this for the Mail> room, as
4569 * well as any room which has the "Mailbox" view set - unless it
4570 * is the DRAFTS room which does not require recipients
4573 if ( ( ( (CCC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CCC->room.QRname[11], MAILROOM)) )
4574 || ( (CCC->room.QRflags & QR_MAILBOX) && (CCC->curr_view == VIEW_MAILBOX) )
4575 ) && (strcasecmp(&CCC->room.QRname[11], USERDRAFTROOM)) !=0 ) {
4576 if (CCC->user.axlevel < AxProbU) {
4577 strcpy(recp, "sysop");
4582 valid_to = validate_recipients(recp, NULL, 0);
4583 if (valid_to->num_error > 0) {
4584 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_to->errormsg);
4585 free_recipients(valid_to);
4589 valid_cc = validate_recipients(cc, NULL, 0);
4590 if (valid_cc->num_error > 0) {
4591 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_cc->errormsg);
4592 free_recipients(valid_to);
4593 free_recipients(valid_cc);
4597 valid_bcc = validate_recipients(bcc, NULL, 0);
4598 if (valid_bcc->num_error > 0) {
4599 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_bcc->errormsg);
4600 free_recipients(valid_to);
4601 free_recipients(valid_cc);
4602 free_recipients(valid_bcc);
4606 /* Recipient required, but none were specified */
4607 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
4608 free_recipients(valid_to);
4609 free_recipients(valid_cc);
4610 free_recipients(valid_bcc);
4611 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
4615 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
4616 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
4617 cprintf("%d You do not have permission "
4618 "to send Internet mail.\n",
4619 ERROR + HIGHER_ACCESS_REQUIRED);
4620 free_recipients(valid_to);
4621 free_recipients(valid_cc);
4622 free_recipients(valid_bcc);
4627 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)
4628 && (CCC->user.axlevel < AxNetU) ) {
4629 cprintf("%d Higher access required for network mail.\n",
4630 ERROR + HIGHER_ACCESS_REQUIRED);
4631 free_recipients(valid_to);
4632 free_recipients(valid_cc);
4633 free_recipients(valid_bcc);
4637 if ((RESTRICT_INTERNET == 1)
4638 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
4639 && ((CCC->user.flags & US_INTERNET) == 0)
4640 && (!CCC->internal_pgm)) {
4641 cprintf("%d You don't have access to Internet mail.\n",
4642 ERROR + HIGHER_ACCESS_REQUIRED);
4643 free_recipients(valid_to);
4644 free_recipients(valid_cc);
4645 free_recipients(valid_bcc);
4651 /* Is this a room which has anonymous-only or anonymous-option? */
4652 anonymous = MES_NORMAL;
4653 if (CCC->room.QRflags & QR_ANONONLY) {
4654 anonymous = MES_ANONONLY;
4656 if (CCC->room.QRflags & QR_ANONOPT) {
4657 if (anon_flag == 1) { /* only if the user requested it */
4658 anonymous = MES_ANONOPT;
4662 if ((CCC->room.QRflags & QR_MAILBOX) == 0) {
4666 /* Recommend to the client that the use of a message subject is
4667 * strongly recommended in this room, if either the SUBJECTREQ flag
4668 * is set, or if there is one or more Internet email recipients.
4670 if (CCC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
4671 if ((valid_to) && (valid_to->num_internet > 0)) subject_required = 1;
4672 if ((valid_cc) && (valid_cc->num_internet > 0)) subject_required = 1;
4673 if ((valid_bcc) && (valid_bcc->num_internet > 0)) subject_required = 1;
4675 /* If we're only checking the validity of the request, return
4676 * success without creating the message.
4679 cprintf("%d %s|%d\n", CIT_OK,
4680 ((valid_to != NULL) ? valid_to->display_recp : ""),
4682 free_recipients(valid_to);
4683 free_recipients(valid_cc);
4684 free_recipients(valid_bcc);
4688 /* We don't need these anymore because we'll do it differently below */
4689 free_recipients(valid_to);
4690 free_recipients(valid_cc);
4691 free_recipients(valid_bcc);
4693 /* Read in the message from the client. */
4695 cprintf("%d send message\n", START_CHAT_MODE);
4697 cprintf("%d send message\n", SEND_LISTING);
4700 msg = CtdlMakeMessage(&CCC->user, recp, cc,
4701 CCC->room.QRname, anonymous, format_type,
4702 newusername, newuseremail, subject,
4703 ((!IsEmptyStr(supplied_euid)) ? supplied_euid : NULL),
4706 /* Put together one big recipients struct containing to/cc/bcc all in
4707 * one. This is for the envelope.
4709 char *all_recps = malloc(SIZ * 3);
4710 strcpy(all_recps, recp);
4711 if (!IsEmptyStr(cc)) {
4712 if (!IsEmptyStr(all_recps)) {
4713 strcat(all_recps, ",");
4715 strcat(all_recps, cc);
4717 if (!IsEmptyStr(bcc)) {
4718 if (!IsEmptyStr(all_recps)) {
4719 strcat(all_recps, ",");
4721 strcat(all_recps, bcc);
4723 if (!IsEmptyStr(all_recps)) {
4724 valid = validate_recipients(all_recps, NULL, 0);
4731 if ((valid != NULL) && (valid->num_room == 1))
4733 /* posting into an ML room? set the envelope from
4734 * to the actual mail address so others get a valid
4737 msg->cm_fields['V'] = strdup(valid->recp_orgroom);
4741 msgnum = CtdlSubmitMsg(msg, valid, "", QP_EADDR);
4743 cprintf("%ld\n", msgnum);
4745 if (StrLength(CCC->StatusMessage) > 0) {
4746 cprintf("%s\n", ChrPtr(CCC->StatusMessage));
4748 else if (msgnum >= 0L) {
4749 client_write(HKEY("Message accepted.\n"));
4752 client_write(HKEY("Internal error.\n"));
4755 if (msg->cm_fields['E'] != NULL) {
4756 cprintf("%s\n", msg->cm_fields['E']);
4763 CtdlFreeMessage(msg);
4765 if (valid != NULL) {
4766 free_recipients(valid);
4774 * API function to delete messages which match a set of criteria
4775 * (returns the actual number of messages deleted)
4777 int CtdlDeleteMessages(char *room_name, /* which room */
4778 long *dmsgnums, /* array of msg numbers to be deleted */
4779 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
4780 char *content_type /* or "" for any. regular expressions expected. */
4783 struct CitContext *CCC = CC;
4784 struct ctdlroom qrbuf;
4785 struct cdbdata *cdbfr;
4786 long *msglist = NULL;
4787 long *dellist = NULL;
4790 int num_deleted = 0;
4792 struct MetaData smi;
4795 int need_to_free_re = 0;
4797 if (content_type) if (!IsEmptyStr(content_type)) {
4798 regcomp(&re, content_type, 0);
4799 need_to_free_re = 1;
4801 MSG_syslog(LOG_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
4802 room_name, num_dmsgnums, content_type);
4804 /* get room record, obtaining a lock... */
4805 if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
4806 MSG_syslog(LOG_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
4808 if (need_to_free_re) regfree(&re);
4809 return (0); /* room not found */
4811 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
4813 if (cdbfr != NULL) {
4814 dellist = malloc(cdbfr->len);
4815 msglist = (long *) cdbfr->ptr;
4816 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
4817 num_msgs = cdbfr->len / sizeof(long);
4821 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
4822 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
4823 int have_more_del = 1;
4825 num_msgs = sort_msglist(msglist, num_msgs);
4826 if (num_dmsgnums > 1)
4827 num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
4830 StrBuf *dbg = NewStrBuf();
4831 for (i = 0; i < num_dmsgnums; i++)
4832 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
4833 MSG_syslog(LOG_DEBUG, "Deleting before: %s", ChrPtr(dbg));
4838 while ((i < num_msgs) && (have_more_del)) {
4842 /* Set/clear a bit for each criterion */
4844 /* 0 messages in the list or a null list means that we are
4845 * interested in deleting any messages which meet the other criteria.
4848 delete_this |= 0x01;
4851 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
4852 if (msglist[i] == dmsgnums[j]) {
4853 delete_this |= 0x01;
4856 have_more_del = (j < num_dmsgnums);
4859 if (have_contenttype) {
4860 GetMetaData(&smi, msglist[i]);
4861 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
4862 delete_this |= 0x02;
4865 delete_this |= 0x02;
4868 /* Delete message only if all bits are set */
4869 if (delete_this == 0x03) {
4870 dellist[num_deleted++] = msglist[i];
4877 StrBuf *dbg = NewStrBuf();
4878 for (i = 0; i < num_deleted; i++)
4879 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
4880 MSG_syslog(LOG_DEBUG, "Deleting: %s", ChrPtr(dbg));
4884 num_msgs = sort_msglist(msglist, num_msgs);
4885 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
4886 msglist, (int)(num_msgs * sizeof(long)));
4889 qrbuf.QRhighest = msglist[num_msgs - 1];
4891 qrbuf.QRhighest = 0;
4893 CtdlPutRoomLock(&qrbuf);
4895 /* Go through the messages we pulled out of the index, and decrement
4896 * their reference counts by 1. If this is the only room the message
4897 * was in, the reference count will reach zero and the message will
4898 * automatically be deleted from the database. We do this in a
4899 * separate pass because there might be plug-in hooks getting called,
4900 * and we don't want that happening during an S_ROOMS critical
4904 for (i=0; i<num_deleted; ++i) {
4905 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
4907 AdjRefCountList(dellist, num_deleted, -1);
4909 /* Now free the memory we used, and go away. */
4910 if (msglist != NULL) free(msglist);
4911 if (dellist != NULL) free(dellist);
4912 MSG_syslog(LOG_DEBUG, "%d message(s) deleted.\n", num_deleted);
4913 if (need_to_free_re) regfree(&re);
4914 return (num_deleted);
4920 * Check whether the current user has permission to delete messages from
4921 * the current room (returns 1 for yes, 0 for no)
4923 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
4925 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
4926 if (ra & UA_DELETEALLOWED) return(1);
4934 * Delete message from current room
4936 void cmd_dele(char *args)
4945 extract_token(msgset, args, 0, '|', sizeof msgset);
4946 num_msgs = num_tokens(msgset, ',');
4948 cprintf("%d Nothing to do.\n", CIT_OK);
4952 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
4953 cprintf("%d Higher access required.\n",
4954 ERROR + HIGHER_ACCESS_REQUIRED);
4959 * Build our message set to be moved/copied
4961 msgs = malloc(num_msgs * sizeof(long));
4962 for (i=0; i<num_msgs; ++i) {
4963 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
4964 msgs[i] = atol(msgtok);
4967 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
4971 cprintf("%d %d message%s deleted.\n", CIT_OK,
4972 num_deleted, ((num_deleted != 1) ? "s" : ""));
4974 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
4982 * move or copy a message to another room
4984 void cmd_move(char *args)
4991 char targ[ROOMNAMELEN];
4992 struct ctdlroom qtemp;
4999 extract_token(msgset, args, 0, '|', sizeof msgset);
5000 num_msgs = num_tokens(msgset, ',');
5002 cprintf("%d Nothing to do.\n", CIT_OK);
5006 extract_token(targ, args, 1, '|', sizeof targ);
5007 convert_room_name_macros(targ, sizeof targ);
5008 targ[ROOMNAMELEN - 1] = 0;
5009 is_copy = extract_int(args, 2);
5011 if (CtdlGetRoom(&qtemp, targ) != 0) {
5012 cprintf("%d '%s' does not exist.\n", ERROR + ROOM_NOT_FOUND, targ);
5016 if (!strcasecmp(qtemp.QRname, CC->room.QRname)) {
5017 cprintf("%d Source and target rooms are the same.\n", ERROR + ALREADY_EXISTS);
5021 CtdlGetUser(&CC->user, CC->curr_user);
5022 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
5024 /* Check for permission to perform this operation.
5025 * Remember: "CC->room" is source, "qtemp" is target.
5029 /* Admins can move/copy */
5030 if (CC->user.axlevel >= AxAideU) permit = 1;
5032 /* Room aides can move/copy */
5033 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
5035 /* Permit move/copy from personal rooms */
5036 if ((CC->room.QRflags & QR_MAILBOX)
5037 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5039 /* Permit only copy from public to personal room */
5041 && (!(CC->room.QRflags & QR_MAILBOX))
5042 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5044 /* Permit message removal from collaborative delete rooms */
5045 if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
5047 /* Users allowed to post into the target room may move into it too. */
5048 if ((CC->room.QRflags & QR_MAILBOX) &&
5049 (qtemp.QRflags & UA_POSTALLOWED)) permit = 1;
5051 /* User must have access to target room */
5052 if (!(ra & UA_KNOWN)) permit = 0;
5055 cprintf("%d Higher access required.\n",
5056 ERROR + HIGHER_ACCESS_REQUIRED);
5061 * Build our message set to be moved/copied
5063 msgs = malloc(num_msgs * sizeof(long));
5064 for (i=0; i<num_msgs; ++i) {
5065 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
5066 msgs[i] = atol(msgtok);
5072 err = CtdlSaveMsgPointersInRoom(targ, msgs, num_msgs, 1, NULL, 0);
5074 cprintf("%d Cannot store message(s) in %s: error %d\n",
5080 /* Now delete the message from the source room,
5081 * if this is a 'move' rather than a 'copy' operation.
5084 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
5088 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
5094 * GetMetaData() - Get the supplementary record for a message
5096 void GetMetaData(struct MetaData *smibuf, long msgnum)
5099 struct cdbdata *cdbsmi;
5102 memset(smibuf, 0, sizeof(struct MetaData));
5103 smibuf->meta_msgnum = msgnum;
5104 smibuf->meta_refcount = 1; /* Default reference count is 1 */
5106 /* Use the negative of the message number for its supp record index */
5107 TheIndex = (0L - msgnum);
5109 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
5110 if (cdbsmi == NULL) {
5111 return; /* record not found; go with defaults */
5113 memcpy(smibuf, cdbsmi->ptr,
5114 ((cdbsmi->len > sizeof(struct MetaData)) ?
5115 sizeof(struct MetaData) : cdbsmi->len));
5122 * PutMetaData() - (re)write supplementary record for a message
5124 void PutMetaData(struct MetaData *smibuf)
5128 /* Use the negative of the message number for the metadata db index */
5129 TheIndex = (0L - smibuf->meta_msgnum);
5131 cdb_store(CDB_MSGMAIN,
5132 &TheIndex, (int)sizeof(long),
5133 smibuf, (int)sizeof(struct MetaData));
5138 * AdjRefCount - submit an adjustment to the reference count for a message.
5139 * (These are just queued -- we actually process them later.)
5141 void AdjRefCount(long msgnum, int incr)
5143 struct CitContext *CCC = CC;
5144 struct arcq new_arcq;
5147 MSG_syslog(LOG_DEBUG, "AdjRefCount() msg %ld ref count delta %+d\n", msgnum, incr);
5149 begin_critical_section(S_SUPPMSGMAIN);
5150 if (arcfp == NULL) {
5151 arcfp = fopen(file_arcq, "ab+");
5152 chown(file_arcq, CTDLUID, (-1));
5153 chmod(file_arcq, 0600);
5155 end_critical_section(S_SUPPMSGMAIN);
5157 /* msgnum < 0 means that we're trying to close the file */
5159 MSGM_syslog(LOG_DEBUG, "Closing the AdjRefCount queue file\n");
5160 begin_critical_section(S_SUPPMSGMAIN);
5161 if (arcfp != NULL) {
5165 end_critical_section(S_SUPPMSGMAIN);
5170 * If we can't open the queue, perform the operation synchronously.
5172 if (arcfp == NULL) {
5173 TDAP_AdjRefCount(msgnum, incr);
5177 new_arcq.arcq_msgnum = msgnum;
5178 new_arcq.arcq_delta = incr;
5179 rv = fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
5181 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5190 void AdjRefCountList(long *msgnum, long nmsg, int incr)
5192 struct CitContext *CCC = CC;
5193 long i, the_size, offset;
5194 struct arcq *new_arcq;
5197 MSG_syslog(LOG_DEBUG, "AdjRefCountList() msg %ld ref count delta %+d\n", nmsg, incr);
5199 begin_critical_section(S_SUPPMSGMAIN);
5200 if (arcfp == NULL) {
5201 arcfp = fopen(file_arcq, "ab+");
5202 chown(file_arcq, CTDLUID, (-1));
5203 chmod(file_arcq, 0600);
5205 end_critical_section(S_SUPPMSGMAIN);
5208 * If we can't open the queue, perform the operation synchronously.
5210 if (arcfp == NULL) {
5211 for (i = 0; i < nmsg; i++)
5212 TDAP_AdjRefCount(msgnum[i], incr);
5216 the_size = sizeof(struct arcq) * nmsg;
5217 new_arcq = malloc(the_size);
5218 for (i = 0; i < nmsg; i++) {
5219 new_arcq[i].arcq_msgnum = msgnum[i];
5220 new_arcq[i].arcq_delta = incr;
5224 while ((rv >= 0) && (offset < the_size))
5226 rv = fwrite(new_arcq + offset, 1, the_size - offset, arcfp);
5228 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5244 * TDAP_ProcessAdjRefCountQueue()
5246 * Process the queue of message count adjustments that was created by calls
5247 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
5248 * for each one. This should be an "off hours" operation.
5250 int TDAP_ProcessAdjRefCountQueue(void)
5252 struct CitContext *CCC = CC;
5253 char file_arcq_temp[PATH_MAX];
5256 struct arcq arcq_rec;
5257 int num_records_processed = 0;
5259 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s.%04x", file_arcq, rand());
5261 begin_critical_section(S_SUPPMSGMAIN);
5262 if (arcfp != NULL) {
5267 r = link(file_arcq, file_arcq_temp);
5269 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5270 end_critical_section(S_SUPPMSGMAIN);
5271 return(num_records_processed);
5275 end_critical_section(S_SUPPMSGMAIN);
5277 fp = fopen(file_arcq_temp, "rb");
5279 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5280 return(num_records_processed);
5283 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
5284 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
5285 ++num_records_processed;
5289 r = unlink(file_arcq_temp);
5291 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5294 return(num_records_processed);
5300 * TDAP_AdjRefCount - adjust the reference count for a message.
5301 * This one does it "for real" because it's called by
5302 * the autopurger function that processes the queue
5303 * created by AdjRefCount(). If a message's reference
5304 * count becomes zero, we also delete the message from
5305 * disk and de-index it.
5307 void TDAP_AdjRefCount(long msgnum, int incr)
5309 struct CitContext *CCC = CC;
5311 struct MetaData smi;
5314 /* This is a *tight* critical section; please keep it that way, as
5315 * it may get called while nested in other critical sections.
5316 * Complicating this any further will surely cause deadlock!
5318 begin_critical_section(S_SUPPMSGMAIN);
5319 GetMetaData(&smi, msgnum);
5320 smi.meta_refcount += incr;
5322 end_critical_section(S_SUPPMSGMAIN);
5323 MSG_syslog(LOG_DEBUG, "TDAP_AdjRefCount() msg %ld ref count delta %+d, is now %d\n",
5324 msgnum, incr, smi.meta_refcount
5327 /* If the reference count is now zero, delete the message
5328 * (and its supplementary record as well).
5330 if (smi.meta_refcount == 0) {
5331 MSG_syslog(LOG_DEBUG, "Deleting message <%ld>\n", msgnum);
5333 /* Call delete hooks with NULL room to show it has gone altogether */
5334 PerformDeleteHooks(NULL, msgnum);
5336 /* Remove from message base */
5338 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5339 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
5341 /* Remove metadata record */
5342 delnum = (0L - msgnum);
5343 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5349 * Write a generic object to this room
5351 * Note: this could be much more efficient. Right now we use two temporary
5352 * files, and still pull the message into memory as with all others.
5354 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
5355 char *content_type, /* MIME type of this object */
5356 char *raw_message, /* Data to be written */
5357 off_t raw_length, /* Size of raw_message */
5358 struct ctdluser *is_mailbox, /* Mailbox room? */
5359 int is_binary, /* Is encoding necessary? */
5360 int is_unique, /* Del others of this type? */
5361 unsigned int flags /* Internal save flags */
5364 struct CitContext *CCC = CC;
5365 struct ctdlroom qrbuf;
5366 char roomname[ROOMNAMELEN];
5367 struct CtdlMessage *msg;
5368 char *encoded_message = NULL;
5370 if (is_mailbox != NULL) {
5371 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
5374 safestrncpy(roomname, req_room, sizeof(roomname));
5377 MSG_syslog(LOG_DEBUG, "Raw length is %ld\n", (long)raw_length);
5380 encoded_message = malloc((size_t) (((raw_length * 134) / 100) + 4096 ) );
5383 encoded_message = malloc((size_t)(raw_length + 4096));
5386 sprintf(encoded_message, "Content-type: %s\n", content_type);
5389 sprintf(&encoded_message[strlen(encoded_message)],
5390 "Content-transfer-encoding: base64\n\n"
5394 sprintf(&encoded_message[strlen(encoded_message)],
5395 "Content-transfer-encoding: 7bit\n\n"
5401 &encoded_message[strlen(encoded_message)],
5409 &encoded_message[strlen(encoded_message)],
5415 MSGM_syslog(LOG_DEBUG, "Allocating\n");
5416 msg = malloc(sizeof(struct CtdlMessage));
5417 memset(msg, 0, sizeof(struct CtdlMessage));
5418 msg->cm_magic = CTDLMESSAGE_MAGIC;
5419 msg->cm_anon_type = MES_NORMAL;
5420 msg->cm_format_type = 4;
5421 msg->cm_fields['A'] = strdup(CCC->user.fullname);
5422 msg->cm_fields['O'] = strdup(req_room);
5423 msg->cm_fields['N'] = strdup(config.c_nodename);
5424 msg->cm_fields['H'] = strdup(config.c_humannode);
5425 msg->cm_flags = flags;
5427 msg->cm_fields['M'] = encoded_message;
5429 /* Create the requested room if we have to. */
5430 if (CtdlGetRoom(&qrbuf, roomname) != 0) {
5431 CtdlCreateRoom(roomname,
5432 ( (is_mailbox != NULL) ? 5 : 3 ),
5433 "", 0, 1, 0, VIEW_BBS);
5435 /* If the caller specified this object as unique, delete all
5436 * other objects of this type that are currently in the room.
5439 MSG_syslog(LOG_DEBUG, "Deleted %d other msgs of this type\n",
5440 CtdlDeleteMessages(roomname, NULL, 0, content_type)
5443 /* Now write the data */
5444 CtdlSubmitMsg(msg, NULL, roomname, 0);
5445 CtdlFreeMessage(msg);
5453 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
5454 config_msgnum = msgnum;
5458 char *CtdlGetSysConfig(char *sysconfname) {
5459 char hold_rm[ROOMNAMELEN];
5462 struct CtdlMessage *msg;
5465 strcpy(hold_rm, CC->room.QRname);
5466 if (CtdlGetRoom(&CC->room, SYSCONFIGROOM) != 0) {
5467 CtdlGetRoom(&CC->room, hold_rm);
5472 /* We want the last (and probably only) config in this room */
5473 begin_critical_section(S_CONFIG);
5474 config_msgnum = (-1L);
5475 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
5476 CtdlGetSysConfigBackend, NULL);
5477 msgnum = config_msgnum;
5478 end_critical_section(S_CONFIG);
5484 msg = CtdlFetchMessage(msgnum, 1);
5486 conf = strdup(msg->cm_fields['M']);
5487 CtdlFreeMessage(msg);
5494 CtdlGetRoom(&CC->room, hold_rm);
5496 if (conf != NULL) do {
5497 extract_token(buf, conf, 0, '\n', sizeof buf);
5498 strcpy(conf, &conf[strlen(buf)+1]);
5499 } while ( (!IsEmptyStr(conf)) && (!IsEmptyStr(buf)) );
5505 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
5506 CtdlWriteObject(SYSCONFIGROOM, sysconfname, sysconfdata, (strlen(sysconfdata)+1), NULL, 0, 1, 0);
5511 * Determine whether a given Internet address belongs to the current user
5513 int CtdlIsMe(char *addr, int addr_buf_len)
5515 struct recptypes *recp;
5518 recp = validate_recipients(addr, NULL, 0);
5519 if (recp == NULL) return(0);
5521 if (recp->num_local == 0) {
5522 free_recipients(recp);
5526 for (i=0; i<recp->num_local; ++i) {
5527 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
5528 if (!strcasecmp(addr, CC->user.fullname)) {
5529 free_recipients(recp);
5534 free_recipients(recp);
5540 * Citadel protocol command to do the same
5542 void cmd_isme(char *argbuf) {
5545 if (CtdlAccessCheck(ac_logged_in)) return;
5546 extract_token(addr, argbuf, 0, '|', sizeof addr);
5548 if (CtdlIsMe(addr, sizeof addr)) {
5549 cprintf("%d %s\n", CIT_OK, addr);
5552 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);
5558 /*****************************************************************************/
5559 /* MODULE INITIALIZATION STUFF */
5560 /*****************************************************************************/
5561 void SetMessageDebugEnabled(const int n)
5563 MessageDebugEnabled = n;
5565 CTDL_MODULE_INIT(msgbase)
5568 CtdlRegisterDebugFlagHook(HKEY("messages"), SetMessageDebugEnabled, &MessageDebugEnabled);
5570 CtdlRegisterProtoHook(cmd_msgs, "MSGS", "Output a list of messages in the current room");
5571 CtdlRegisterProtoHook(cmd_msg0, "MSG0", "Output a message in plain text format");
5572 CtdlRegisterProtoHook(cmd_msg2, "MSG2", "Output a message in RFC822 format");
5573 CtdlRegisterProtoHook(cmd_msg3, "MSG3", "Output a message in raw format (deprecated)");
5574 CtdlRegisterProtoHook(cmd_msg4, "MSG4", "Output a message in the client's preferred format");
5575 CtdlRegisterProtoHook(cmd_msgp, "MSGP", "Select preferred format for MSG4 output");
5576 CtdlRegisterProtoHook(cmd_opna, "OPNA", "Open an attachment for download");
5577 CtdlRegisterProtoHook(cmd_dlat, "DLAT", "Download an attachment");
5578 CtdlRegisterProtoHook(cmd_ent0, "ENT0", "Enter a message");
5579 CtdlRegisterProtoHook(cmd_dele, "DELE", "Delete a message");
5580 CtdlRegisterProtoHook(cmd_move, "MOVE", "Move or copy a message to another room");
5581 CtdlRegisterProtoHook(cmd_isme, "ISME", "Determine whether an email address belongs to a user");
5584 /* return our Subversion id for the Log */