4 * Implements the message store.
14 #if TIME_WITH_SYS_TIME
15 # include <sys/time.h>
19 # include <sys/time.h>
32 #include <sys/types.h>
36 #include "serv_extensions.h"
40 #include "sysdep_decls.h"
41 #include "citserver.h"
48 #include "mime_parser.h"
51 #include "internet_addressing.h"
52 #include "serv_fulltext.h"
54 #include "euidindex.h"
55 #include "journaling.h"
56 #include "citadel_dirs.h"
57 #include "serv_network.h"
61 struct addresses_to_be_filed *atbf = NULL;
63 /* This temp file holds the queue of operations for AdjRefCount() */
64 static FILE *arcfp = NULL;
67 * This really belongs in serv_network.c, but I don't know how to export
68 * symbols between modules.
70 struct FilterList *filterlist = NULL;
74 * These are the four-character field headers we use when outputting
75 * messages in Citadel format (as opposed to RFC822 format).
78 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
79 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
80 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
81 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
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,
113 * This function is self explanatory.
114 * (What can I say, I'm in a weird mood today...)
116 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
120 for (i = 0; i < strlen(name); ++i) {
121 if (name[i] == '@') {
122 while (isspace(name[i - 1]) && i > 0) {
123 strcpy(&name[i - 1], &name[i]);
126 while (isspace(name[i + 1])) {
127 strcpy(&name[i + 1], &name[i + 2]);
135 * Aliasing for network mail.
136 * (Error messages have been commented out, because this is a server.)
138 int alias(char *name)
139 { /* process alias and routing info for mail */
142 char aaa[SIZ], bbb[SIZ];
143 char *ignetcfg = NULL;
144 char *ignetmap = NULL;
150 char original_name[256];
151 safestrncpy(original_name, name, sizeof original_name);
154 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
155 stripallbut(name, '<', '>');
157 fp = fopen(file_mail_aliases, "r");
159 fp = fopen("/dev/null", "r");
166 while (fgets(aaa, sizeof aaa, fp) != NULL) {
167 while (isspace(name[0]))
168 strcpy(name, &name[1]);
169 aaa[strlen(aaa) - 1] = 0;
171 for (a = 0; a < strlen(aaa); ++a) {
173 strcpy(bbb, &aaa[a + 1]);
177 if (!strcasecmp(name, aaa))
182 /* Hit the Global Address Book */
183 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
187 if (strcasecmp(original_name, name)) {
188 lprintf(CTDL_INFO, "%s is being forwarded to %s\n", original_name, name);
191 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
192 for (a=0; a<strlen(name); ++a) {
193 if (name[a] == '@') {
194 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
196 lprintf(CTDL_INFO, "Changed to <%s>\n", name);
201 /* determine local or remote type, see citadel.h */
202 at = haschar(name, '@');
203 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
204 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
205 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
207 /* figure out the delivery mode */
208 extract_token(node, name, 1, '@', sizeof node);
210 /* If there are one or more dots in the nodename, we assume that it
211 * is an FQDN and will attempt SMTP delivery to the Internet.
213 if (haschar(node, '.') > 0) {
214 return(MES_INTERNET);
217 /* Otherwise we look in the IGnet maps for a valid Citadel node.
218 * Try directly-connected nodes first...
220 ignetcfg = CtdlGetSysConfig(IGNETCFG);
221 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
222 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
223 extract_token(testnode, buf, 0, '|', sizeof testnode);
224 if (!strcasecmp(node, testnode)) {
232 * Then try nodes that are two or more hops away.
234 ignetmap = CtdlGetSysConfig(IGNETMAP);
235 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
236 extract_token(buf, ignetmap, i, '\n', sizeof buf);
237 extract_token(testnode, buf, 0, '|', sizeof testnode);
238 if (!strcasecmp(node, testnode)) {
245 /* If we get to this point it's an invalid node name */
251 * Back end for the MSGS command: output message number only.
253 void simple_listing(long msgnum, void *userdata)
255 cprintf("%ld\n", msgnum);
261 * Back end for the MSGS command: output header summary.
263 void headers_listing(long msgnum, void *userdata)
265 struct CtdlMessage *msg;
267 msg = CtdlFetchMessage(msgnum, 0);
269 cprintf("%ld|0|||||\n", msgnum);
273 cprintf("%ld|%s|%s|%s|%s|%s|\n",
275 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
276 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
277 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
278 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
279 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
281 CtdlFreeMessage(msg);
286 /* Determine if a given message matches the fields in a message template.
287 * Return 0 for a successful match.
289 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
292 /* If there aren't any fields in the template, all messages will
295 if (template == NULL) return(0);
297 /* Null messages are bogus. */
298 if (msg == NULL) return(1);
300 for (i='A'; i<='Z'; ++i) {
301 if (template->cm_fields[i] != NULL) {
302 if (msg->cm_fields[i] == NULL) {
305 if (strcasecmp(msg->cm_fields[i],
306 template->cm_fields[i])) return 1;
310 /* All compares succeeded: we have a match! */
317 * Retrieve the "seen" message list for the current room.
319 void CtdlGetSeen(char *buf, int which_set) {
322 /* Learn about the user and room in question */
323 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
325 if (which_set == ctdlsetseen_seen)
326 safestrncpy(buf, vbuf.v_seen, SIZ);
327 if (which_set == ctdlsetseen_answered)
328 safestrncpy(buf, vbuf.v_answered, SIZ);
334 * Manipulate the "seen msgs" string (or other message set strings)
336 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
337 int target_setting, int which_set,
338 struct ctdluser *which_user, struct ctdlroom *which_room) {
339 struct cdbdata *cdbfr;
351 char *is_set; /* actually an array of booleans */
354 char setstr[SIZ], lostr[SIZ], histr[SIZ];
357 /* Don't bother doing *anything* if we were passed a list of zero messages */
358 if (num_target_msgnums < 1) {
362 lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
363 num_target_msgnums, target_msgnums[0],
364 target_setting, which_set);
366 /* Learn about the user and room in question */
367 CtdlGetRelationship(&vbuf,
368 ((which_user != NULL) ? which_user : &CC->user),
369 ((which_room != NULL) ? which_room : &CC->room)
372 /* Load the message list */
373 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
375 msglist = (long *) cdbfr->ptr;
376 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
377 num_msgs = cdbfr->len / sizeof(long);
380 return; /* No messages at all? No further action. */
383 is_set = malloc(num_msgs * sizeof(char));
384 memset(is_set, 0, (num_msgs * sizeof(char)) );
386 /* Decide which message set we're manipulating */
388 case ctdlsetseen_seen:
389 safestrncpy(vset, vbuf.v_seen, sizeof vset);
391 case ctdlsetseen_answered:
392 safestrncpy(vset, vbuf.v_answered, sizeof vset);
396 /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
398 /* Translate the existing sequence set into an array of booleans */
399 num_sets = num_tokens(vset, ',');
400 for (s=0; s<num_sets; ++s) {
401 extract_token(setstr, vset, s, ',', sizeof setstr);
403 extract_token(lostr, setstr, 0, ':', sizeof lostr);
404 if (num_tokens(setstr, ':') >= 2) {
405 extract_token(histr, setstr, 1, ':', sizeof histr);
406 if (!strcmp(histr, "*")) {
407 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
411 strcpy(histr, lostr);
416 for (i = 0; i < num_msgs; ++i) {
417 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
423 /* Now translate the array of booleans back into a sequence set */
428 for (i=0; i<num_msgs; ++i) {
430 is_seen = is_set[i]; /* Default to existing setting */
432 for (k=0; k<num_target_msgnums; ++k) {
433 if (msglist[i] == target_msgnums[k]) {
434 is_seen = target_setting;
439 if (lo < 0L) lo = msglist[i];
443 if ( ((is_seen == 0) && (was_seen == 1))
444 || ((is_seen == 1) && (i == num_msgs-1)) ) {
446 /* begin trim-o-matic code */
449 while ( (strlen(vset) + 20) > sizeof vset) {
450 remove_token(vset, 0, ',');
452 if (j--) break; /* loop no more than 9 times */
454 if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
458 snprintf(lostr, sizeof lostr,
459 "1:%ld,%s", t, vset);
460 safestrncpy(vset, lostr, sizeof vset);
462 /* end trim-o-matic code */
470 snprintf(&vset[tmp], (sizeof vset) - tmp,
474 snprintf(&vset[tmp], (sizeof vset) - tmp,
483 /* Decide which message set we're manipulating */
485 case ctdlsetseen_seen:
486 safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
488 case ctdlsetseen_answered:
489 safestrncpy(vbuf.v_answered, vset,
490 sizeof vbuf.v_answered);
495 /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
497 CtdlSetRelationship(&vbuf,
498 ((which_user != NULL) ? which_user : &CC->user),
499 ((which_room != NULL) ? which_room : &CC->room)
505 * API function to perform an operation for each qualifying message in the
506 * current room. (Returns the number of messages processed.)
508 int CtdlForEachMessage(int mode, long ref, char *search_string,
510 struct CtdlMessage *compare,
511 void (*CallBack) (long, void *),
517 struct cdbdata *cdbfr;
518 long *msglist = NULL;
520 int num_processed = 0;
523 struct CtdlMessage *msg = NULL;
526 int printed_lastold = 0;
527 int num_search_msgs = 0;
528 long *search_msgs = NULL;
530 int need_to_free_re = 0;
533 if (content_type) if (strlen(content_type) > 0) {
534 regcomp(&re, content_type, 0);
538 /* Learn about the user and room in question */
539 getuser(&CC->user, CC->curr_user);
540 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
542 /* Load the message list */
543 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
545 msglist = (long *) cdbfr->ptr;
546 cdbfr->ptr = NULL; /* CtdlForEachMessage() now owns this memory */
547 num_msgs = cdbfr->len / sizeof(long);
550 if (need_to_free_re) regfree(&re);
551 return 0; /* No messages at all? No further action. */
556 * Now begin the traversal.
558 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
560 /* If the caller is looking for a specific MIME type, filter
561 * out all messages which are not of the type requested.
563 if (content_type != NULL) if (strlen(content_type) > 0) {
565 /* This call to GetMetaData() sits inside this loop
566 * so that we only do the extra database read per msg
567 * if we need to. Doing the extra read all the time
568 * really kills the server. If we ever need to use
569 * metadata for another search criterion, we need to
570 * move the read somewhere else -- but still be smart
571 * enough to only do the read if the caller has
572 * specified something that will need it.
574 GetMetaData(&smi, msglist[a]);
576 /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
577 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
583 num_msgs = sort_msglist(msglist, num_msgs);
585 /* If a template was supplied, filter out the messages which
586 * don't match. (This could induce some delays!)
589 if (compare != NULL) {
590 for (a = 0; a < num_msgs; ++a) {
591 msg = CtdlFetchMessage(msglist[a], 1);
593 if (CtdlMsgCmp(msg, compare)) {
596 CtdlFreeMessage(msg);
602 /* If a search string was specified, get a message list from
603 * the full text index and remove messages which aren't on both
607 * Since the lists are sorted and strictly ascending, and the
608 * output list is guaranteed to be shorter than or equal to the
609 * input list, we overwrite the bottom of the input list. This
610 * eliminates the need to memmove big chunks of the list over and
613 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
614 ft_search(&num_search_msgs, &search_msgs, search_string);
615 if (num_search_msgs > 0) {
619 orig_num_msgs = num_msgs;
621 for (i=0; i<orig_num_msgs; ++i) {
622 for (j=0; j<num_search_msgs; ++j) {
623 if (msglist[i] == search_msgs[j]) {
624 msglist[num_msgs++] = msglist[i];
630 num_msgs = 0; /* No messages qualify */
632 if (search_msgs != NULL) free(search_msgs);
634 /* Now that we've purged messages which don't contain the search
635 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
642 * Now iterate through the message list, according to the
643 * criteria supplied by the caller.
646 for (a = 0; a < num_msgs; ++a) {
647 thismsg = msglist[a];
648 if (mode == MSGS_ALL) {
652 is_seen = is_msg_in_sequence_set(
653 vbuf.v_seen, thismsg);
654 if (is_seen) lastold = thismsg;
660 || ((mode == MSGS_OLD) && (is_seen))
661 || ((mode == MSGS_NEW) && (!is_seen))
662 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
663 || ((mode == MSGS_FIRST) && (a < ref))
664 || ((mode == MSGS_GT) && (thismsg > ref))
665 || ((mode == MSGS_EQ) && (thismsg == ref))
668 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
670 CallBack(lastold, userdata);
674 if (CallBack) CallBack(thismsg, userdata);
678 free(msglist); /* Clean up */
679 if (need_to_free_re) regfree(&re);
680 return num_processed;
686 * cmd_msgs() - get list of message #'s in this room
687 * implements the MSGS server command using CtdlForEachMessage()
689 void cmd_msgs(char *cmdbuf)
698 int with_template = 0;
699 struct CtdlMessage *template = NULL;
700 int with_headers = 0;
701 char search_string[1024];
703 extract_token(which, cmdbuf, 0, '|', sizeof which);
704 cm_ref = extract_int(cmdbuf, 1);
705 extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
706 with_template = extract_int(cmdbuf, 2);
707 with_headers = extract_int(cmdbuf, 3);
710 if (!strncasecmp(which, "OLD", 3))
712 else if (!strncasecmp(which, "NEW", 3))
714 else if (!strncasecmp(which, "FIRST", 5))
716 else if (!strncasecmp(which, "LAST", 4))
718 else if (!strncasecmp(which, "GT", 2))
720 else if (!strncasecmp(which, "SEARCH", 6))
725 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
726 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
730 if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
731 cprintf("%d Full text index is not enabled on this server.\n",
732 ERROR + CMD_NOT_SUPPORTED);
738 cprintf("%d Send template then receive message list\n",
740 template = (struct CtdlMessage *)
741 malloc(sizeof(struct CtdlMessage));
742 memset(template, 0, sizeof(struct CtdlMessage));
743 template->cm_magic = CTDLMESSAGE_MAGIC;
744 template->cm_anon_type = MES_NORMAL;
746 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
747 extract_token(tfield, buf, 0, '|', sizeof tfield);
748 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
749 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
750 if (!strcasecmp(tfield, msgkeys[i])) {
751 template->cm_fields[i] =
759 cprintf("%d \n", LISTING_FOLLOWS);
762 CtdlForEachMessage(mode,
763 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
764 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
767 (with_headers ? headers_listing : simple_listing),
770 if (template != NULL) CtdlFreeMessage(template);
778 * help_subst() - support routine for help file viewer
780 void help_subst(char *strbuf, char *source, char *dest)
785 while (p = pattern2(strbuf, source), (p >= 0)) {
786 strcpy(workbuf, &strbuf[p + strlen(source)]);
787 strcpy(&strbuf[p], dest);
788 strcat(strbuf, workbuf);
793 void do_help_subst(char *buffer)
797 help_subst(buffer, "^nodename", config.c_nodename);
798 help_subst(buffer, "^humannode", config.c_humannode);
799 help_subst(buffer, "^fqdn", config.c_fqdn);
800 help_subst(buffer, "^username", CC->user.fullname);
801 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
802 help_subst(buffer, "^usernum", buf2);
803 help_subst(buffer, "^sysadm", config.c_sysadm);
804 help_subst(buffer, "^variantname", CITADEL);
805 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
806 help_subst(buffer, "^maxsessions", buf2);
807 help_subst(buffer, "^bbsdir", ctdl_bbsbase_dir);
813 * memfmout() - Citadel text formatter and paginator.
814 * Although the original purpose of this routine was to format
815 * text to the reader's screen width, all we're really using it
816 * for here is to format text out to 80 columns before sending it
817 * to the client. The client software may reformat it again.
820 char *mptr, /* where are we going to get our text from? */
821 char subst, /* nonzero if we should do substitutions */
822 char *nl) /* string to terminate lines with */
830 static int width = 80;
835 c = 1; /* c is the current pos */
839 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
841 buffer[strlen(buffer) + 1] = 0;
842 buffer[strlen(buffer)] = ch;
845 if (buffer[0] == '^')
846 do_help_subst(buffer);
848 buffer[strlen(buffer) + 1] = 0;
850 strcpy(buffer, &buffer[1]);
858 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
861 if (((old == 13) || (old == 10)) && (isspace(real))) {
866 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
867 cprintf("%s%s", nl, aaa);
876 if ((strlen(aaa) + c) > (width - 5)) {
885 if ((ch == 13) || (ch == 10)) {
886 cprintf("%s%s", aaa, nl);
893 cprintf("%s%s", aaa, nl);
899 * Callback function for mime parser that simply lists the part
901 void list_this_part(char *name, char *filename, char *partnum, char *disp,
902 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
907 ma = (struct ma_info *)cbuserdata;
908 if (ma->is_ma == 0) {
909 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
910 name, filename, partnum, disp, cbtype, (long)length);
915 * Callback function for multipart prefix
917 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
918 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
923 ma = (struct ma_info *)cbuserdata;
924 if (!strcasecmp(cbtype, "multipart/alternative")) {
928 if (ma->is_ma == 0) {
929 cprintf("pref=%s|%s\n", partnum, cbtype);
934 * Callback function for multipart sufffix
936 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
937 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
942 ma = (struct ma_info *)cbuserdata;
943 if (ma->is_ma == 0) {
944 cprintf("suff=%s|%s\n", partnum, cbtype);
946 if (!strcasecmp(cbtype, "multipart/alternative")) {
953 * Callback function for mime parser that opens a section for downloading
955 void mime_download(char *name, char *filename, char *partnum, char *disp,
956 void *content, char *cbtype, char *cbcharset, size_t length,
957 char *encoding, void *cbuserdata)
960 /* Silently go away if there's already a download open... */
961 if (CC->download_fp != NULL)
964 /* ...or if this is not the desired section */
965 if (strcasecmp(CC->download_desired_section, partnum))
968 CC->download_fp = tmpfile();
969 if (CC->download_fp == NULL)
972 fwrite(content, length, 1, CC->download_fp);
973 fflush(CC->download_fp);
974 rewind(CC->download_fp);
976 OpenCmdResult(filename, cbtype);
982 * Callback function for mime parser that outputs a section all at once
984 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
985 void *content, char *cbtype, char *cbcharset, size_t length,
986 char *encoding, void *cbuserdata)
988 int *found_it = (int *)cbuserdata;
990 /* ...or if this is not the desired section */
991 if (strcasecmp(CC->download_desired_section, partnum))
996 cprintf("%d %d\n", BINARY_FOLLOWS, (int)length);
997 client_write(content, length);
1003 * Load a message from disk into memory.
1004 * This is used by CtdlOutputMsg() and other fetch functions.
1006 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1007 * using the CtdlMessageFree() function.
1009 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1011 struct cdbdata *dmsgtext;
1012 struct CtdlMessage *ret = NULL;
1016 cit_uint8_t field_header;
1018 lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1020 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1021 if (dmsgtext == NULL) {
1024 mptr = dmsgtext->ptr;
1025 upper_bound = mptr + dmsgtext->len;
1027 /* Parse the three bytes that begin EVERY message on disk.
1028 * The first is always 0xFF, the on-disk magic number.
1029 * The second is the anonymous/public type byte.
1030 * The third is the format type byte (vari, fixed, or MIME).
1035 "Message %ld appears to be corrupted.\n",
1040 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1041 memset(ret, 0, sizeof(struct CtdlMessage));
1043 ret->cm_magic = CTDLMESSAGE_MAGIC;
1044 ret->cm_anon_type = *mptr++; /* Anon type byte */
1045 ret->cm_format_type = *mptr++; /* Format type byte */
1048 * The rest is zero or more arbitrary fields. Load them in.
1049 * We're done when we encounter either a zero-length field or
1050 * have just processed the 'M' (message text) field.
1053 if (mptr >= upper_bound) {
1056 field_header = *mptr++;
1057 ret->cm_fields[field_header] = strdup(mptr);
1059 while (*mptr++ != 0); /* advance to next field */
1061 } while ((mptr < upper_bound) && (field_header != 'M'));
1065 /* Always make sure there's something in the msg text field. If
1066 * it's NULL, the message text is most likely stored separately,
1067 * so go ahead and fetch that. Failing that, just set a dummy
1068 * body so other code doesn't barf.
1070 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1071 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1072 if (dmsgtext != NULL) {
1073 ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1077 if (ret->cm_fields['M'] == NULL) {
1078 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1081 /* Perform "before read" hooks (aborting if any return nonzero) */
1082 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1083 CtdlFreeMessage(ret);
1092 * Returns 1 if the supplied pointer points to a valid Citadel message.
1093 * If the pointer is NULL or the magic number check fails, returns 0.
1095 int is_valid_message(struct CtdlMessage *msg) {
1098 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1099 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1107 * 'Destructor' for struct CtdlMessage
1109 void CtdlFreeMessage(struct CtdlMessage *msg)
1113 if (is_valid_message(msg) == 0)
1115 if (msg != NULL) free (msg);
1119 for (i = 0; i < 256; ++i)
1120 if (msg->cm_fields[i] != NULL) {
1121 free(msg->cm_fields[i]);
1124 msg->cm_magic = 0; /* just in case */
1130 * Pre callback function for multipart/alternative
1132 * NOTE: this differs from the standard behavior for a reason. Normally when
1133 * displaying multipart/alternative you want to show the _last_ usable
1134 * format in the message. Here we show the _first_ one, because it's
1135 * usually text/plain. Since this set of functions is designed for text
1136 * output to non-MIME-aware clients, this is the desired behavior.
1139 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1140 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1145 ma = (struct ma_info *)cbuserdata;
1146 lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1147 if (!strcasecmp(cbtype, "multipart/alternative")) {
1151 if (!strcasecmp(cbtype, "message/rfc822")) {
1157 * Post callback function for multipart/alternative
1159 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1160 void *content, char *cbtype, char *cbcharset, size_t length,
1161 char *encoding, void *cbuserdata)
1165 ma = (struct ma_info *)cbuserdata;
1166 lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1167 if (!strcasecmp(cbtype, "multipart/alternative")) {
1171 if (!strcasecmp(cbtype, "message/rfc822")) {
1177 * Inline callback function for mime parser that wants to display text
1179 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1180 void *content, char *cbtype, char *cbcharset, size_t length,
1181 char *encoding, void *cbuserdata)
1188 ma = (struct ma_info *)cbuserdata;
1191 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1192 partnum, filename, cbtype, (long)length);
1195 * If we're in the middle of a multipart/alternative scope and
1196 * we've already printed another section, skip this one.
1198 if ( (ma->is_ma) && (ma->did_print) ) {
1199 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1205 if ( (!strcasecmp(cbtype, "text/plain"))
1206 || (strlen(cbtype)==0) ) {
1209 client_write(wptr, length);
1210 if (wptr[length-1] != '\n') {
1217 if (!strcasecmp(cbtype, "text/html")) {
1218 ptr = html_to_ascii(content, length, 80, 0);
1220 client_write(ptr, wlen);
1221 if (ptr[wlen-1] != '\n') {
1228 if (ma->use_fo_hooks) {
1229 if (PerformFixedOutputHooks(cbtype, content, length)) {
1230 /* above function returns nonzero if it handled the part */
1235 if (strncasecmp(cbtype, "multipart/", 10)) {
1236 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1237 partnum, filename, cbtype, (long)length);
1243 * The client is elegant and sophisticated and wants to be choosy about
1244 * MIME content types, so figure out which multipart/alternative part
1245 * we're going to send.
1247 * We use a system of weights. When we find a part that matches one of the
1248 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1249 * and then set ma->chosen_pref to that MIME type's position in our preference
1250 * list. If we then hit another match, we only replace the first match if
1251 * the preference value is lower.
1253 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1254 void *content, char *cbtype, char *cbcharset, size_t length,
1255 char *encoding, void *cbuserdata)
1261 ma = (struct ma_info *)cbuserdata;
1263 if (ma->is_ma > 0) {
1264 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1265 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1266 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1267 if (i < ma->chosen_pref) {
1268 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1269 ma->chosen_pref = i;
1277 * Now that we've chosen our preferred part, output it.
1279 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1280 void *content, char *cbtype, char *cbcharset, size_t length,
1281 char *encoding, void *cbuserdata)
1285 int add_newline = 0;
1289 ma = (struct ma_info *)cbuserdata;
1291 /* This is not the MIME part you're looking for... */
1292 if (strcasecmp(partnum, ma->chosen_part)) return;
1294 /* If the content-type of this part is in our preferred formats
1295 * list, we can simply output it verbatim.
1297 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1298 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1299 if (!strcasecmp(buf, cbtype)) {
1300 /* Yeah! Go! W00t!! */
1302 text_content = (char *)content;
1303 if (text_content[length-1] != '\n') {
1306 cprintf("Content-type: %s", cbtype);
1307 if (strlen(cbcharset) > 0) {
1308 cprintf("; charset=%s", cbcharset);
1310 cprintf("\nContent-length: %d\n",
1311 (int)(length + add_newline) );
1312 if (strlen(encoding) > 0) {
1313 cprintf("Content-transfer-encoding: %s\n", encoding);
1316 cprintf("Content-transfer-encoding: 7bit\n");
1318 cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1320 client_write(content, length);
1321 if (add_newline) cprintf("\n");
1326 /* No translations required or possible: output as text/plain */
1327 cprintf("Content-type: text/plain\n\n");
1328 fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1329 length, encoding, cbuserdata);
1334 char desired_section[64];
1341 * Callback function for
1343 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1344 void *content, char *cbtype, char *cbcharset, size_t length,
1345 char *encoding, void *cbuserdata)
1347 struct encapmsg *encap;
1349 encap = (struct encapmsg *)cbuserdata;
1351 /* Only proceed if this is the desired section... */
1352 if (!strcasecmp(encap->desired_section, partnum)) {
1353 encap->msglen = length;
1354 encap->msg = malloc(length + 2);
1355 memcpy(encap->msg, content, length);
1365 * Get a message off disk. (returns om_* values found in msgbase.h)
1368 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1369 int mode, /* how would you like that message? */
1370 int headers_only, /* eschew the message body? */
1371 int do_proto, /* do Citadel protocol responses? */
1372 int crlf, /* Use CRLF newlines instead of LF? */
1373 char *section /* NULL or a message/rfc822 section */
1375 struct CtdlMessage *TheMessage = NULL;
1376 int retcode = om_no_such_msg;
1377 struct encapmsg encap;
1379 lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n",
1381 (section ? section : "<>")
1384 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1385 if (do_proto) cprintf("%d Not logged in.\n",
1386 ERROR + NOT_LOGGED_IN);
1387 return(om_not_logged_in);
1390 /* FIXME: check message id against msglist for this room */
1393 * Fetch the message from disk. If we're in any sort of headers
1394 * only mode, request that we don't even bother loading the body
1397 if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1398 TheMessage = CtdlFetchMessage(msg_num, 0);
1401 TheMessage = CtdlFetchMessage(msg_num, 1);
1404 if (TheMessage == NULL) {
1405 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1406 ERROR + MESSAGE_NOT_FOUND, msg_num);
1407 return(om_no_such_msg);
1410 /* Here is the weird form of this command, to process only an
1411 * encapsulated message/rfc822 section.
1413 if (section) if (strlen(section)>0) if (strcmp(section, "0")) {
1414 memset(&encap, 0, sizeof encap);
1415 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1416 mime_parser(TheMessage->cm_fields['M'],
1418 *extract_encapsulated_message,
1419 NULL, NULL, (void *)&encap, 0
1421 CtdlFreeMessage(TheMessage);
1425 encap.msg[encap.msglen] = 0;
1426 TheMessage = convert_internet_message(encap.msg);
1427 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1429 /* Now we let it fall through to the bottom of this
1430 * function, because TheMessage now contains the
1431 * encapsulated message instead of the top-level
1432 * message. Isn't that neat?
1437 if (do_proto) cprintf("%d msg %ld has no part %s\n",
1438 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1439 retcode = om_no_such_msg;
1444 /* Ok, output the message now */
1445 retcode = CtdlOutputPreLoadedMsg(
1447 headers_only, do_proto, crlf);
1448 CtdlFreeMessage(TheMessage);
1455 * Get a message off disk. (returns om_* values found in msgbase.h)
1458 int CtdlOutputPreLoadedMsg(
1459 struct CtdlMessage *TheMessage,
1460 int mode, /* how would you like that message? */
1461 int headers_only, /* eschew the message body? */
1462 int do_proto, /* do Citadel protocol responses? */
1463 int crlf /* Use CRLF newlines instead of LF? */
1469 char display_name[256];
1471 char *nl; /* newline string */
1473 int subject_found = 0;
1476 /* Buffers needed for RFC822 translation. These are all filled
1477 * using functions that are bounds-checked, and therefore we can
1478 * make them substantially smaller than SIZ.
1486 char datestamp[100];
1488 lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1489 ((TheMessage == NULL) ? "NULL" : "not null"),
1490 mode, headers_only, do_proto, crlf);
1492 strcpy(mid, "unknown");
1493 nl = (crlf ? "\r\n" : "\n");
1495 if (!is_valid_message(TheMessage)) {
1497 "ERROR: invalid preloaded message for output\n");
1498 return(om_no_such_msg);
1501 /* Are we downloading a MIME component? */
1502 if (mode == MT_DOWNLOAD) {
1503 if (TheMessage->cm_format_type != FMT_RFC822) {
1505 cprintf("%d This is not a MIME message.\n",
1506 ERROR + ILLEGAL_VALUE);
1507 } else if (CC->download_fp != NULL) {
1508 if (do_proto) cprintf(
1509 "%d You already have a download open.\n",
1510 ERROR + RESOURCE_BUSY);
1512 /* Parse the message text component */
1513 mptr = TheMessage->cm_fields['M'];
1514 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1515 /* If there's no file open by this time, the requested
1516 * section wasn't found, so print an error
1518 if (CC->download_fp == NULL) {
1519 if (do_proto) cprintf(
1520 "%d Section %s not found.\n",
1521 ERROR + FILE_NOT_FOUND,
1522 CC->download_desired_section);
1525 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1528 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
1529 * in a single server operation instead of opening a download file.
1531 if (mode == MT_SPEW_SECTION) {
1532 if (TheMessage->cm_format_type != FMT_RFC822) {
1534 cprintf("%d This is not a MIME message.\n",
1535 ERROR + ILLEGAL_VALUE);
1537 /* Parse the message text component */
1540 mptr = TheMessage->cm_fields['M'];
1541 mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
1542 /* If section wasn't found, print an error
1545 if (do_proto) cprintf(
1546 "%d Section %s not found.\n",
1547 ERROR + FILE_NOT_FOUND,
1548 CC->download_desired_section);
1551 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1554 /* now for the user-mode message reading loops */
1555 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1557 /* Does the caller want to skip the headers? */
1558 if (headers_only == HEADERS_NONE) goto START_TEXT;
1560 /* Tell the client which format type we're using. */
1561 if ( (mode == MT_CITADEL) && (do_proto) ) {
1562 cprintf("type=%d\n", TheMessage->cm_format_type);
1565 /* nhdr=yes means that we're only displaying headers, no body */
1566 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1567 && (mode == MT_CITADEL)
1570 cprintf("nhdr=yes\n");
1573 /* begin header processing loop for Citadel message format */
1575 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1577 safestrncpy(display_name, "<unknown>", sizeof display_name);
1578 if (TheMessage->cm_fields['A']) {
1579 strcpy(buf, TheMessage->cm_fields['A']);
1580 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1581 safestrncpy(display_name, "****", sizeof display_name);
1583 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1584 safestrncpy(display_name, "anonymous", sizeof display_name);
1587 safestrncpy(display_name, buf, sizeof display_name);
1589 if ((is_room_aide())
1590 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1591 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1592 size_t tmp = strlen(display_name);
1593 snprintf(&display_name[tmp],
1594 sizeof display_name - tmp,
1599 /* Don't show Internet address for users on the
1600 * local Citadel network.
1603 if (TheMessage->cm_fields['N'] != NULL)
1604 if (strlen(TheMessage->cm_fields['N']) > 0)
1605 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1609 /* Now spew the header fields in the order we like them. */
1610 safestrncpy(allkeys, FORDER, sizeof allkeys);
1611 for (i=0; i<strlen(allkeys); ++i) {
1612 k = (int) allkeys[i];
1614 if ( (TheMessage->cm_fields[k] != NULL)
1615 && (msgkeys[k] != NULL) ) {
1617 if (do_proto) cprintf("%s=%s\n",
1621 else if ((k == 'F') && (suppress_f)) {
1624 /* Masquerade display name if needed */
1626 if (do_proto) cprintf("%s=%s\n",
1628 TheMessage->cm_fields[k]
1637 /* begin header processing loop for RFC822 transfer format */
1642 strcpy(snode, NODENAME);
1643 strcpy(lnode, HUMANNODE);
1644 if (mode == MT_RFC822) {
1645 for (i = 0; i < 256; ++i) {
1646 if (TheMessage->cm_fields[i]) {
1647 mptr = TheMessage->cm_fields[i];
1650 safestrncpy(luser, mptr, sizeof luser);
1651 safestrncpy(suser, mptr, sizeof suser);
1653 else if (i == 'Y') {
1654 cprintf("CC: %s%s", mptr, nl);
1656 else if (i == 'P') {
1657 cprintf("Return-Path: %s%s", mptr, nl);
1659 else if (i == 'V') {
1660 cprintf("Envelope-To: %s%s", mptr, nl);
1662 else if (i == 'U') {
1663 cprintf("Subject: %s%s", mptr, nl);
1667 safestrncpy(mid, mptr, sizeof mid);
1669 safestrncpy(lnode, mptr, sizeof lnode);
1671 safestrncpy(fuser, mptr, sizeof fuser);
1672 /* else if (i == 'O')
1673 cprintf("X-Citadel-Room: %s%s",
1676 safestrncpy(snode, mptr, sizeof snode);
1678 cprintf("To: %s%s", mptr, nl);
1679 else if (i == 'T') {
1680 datestring(datestamp, sizeof datestamp,
1681 atol(mptr), DATESTRING_RFC822);
1682 cprintf("Date: %s%s", datestamp, nl);
1686 if (subject_found == 0) {
1687 cprintf("Subject: (no subject)%s", nl);
1691 for (i=0; i<strlen(suser); ++i) {
1692 suser[i] = tolower(suser[i]);
1693 if (!isalnum(suser[i])) suser[i]='_';
1696 if (mode == MT_RFC822) {
1697 if (!strcasecmp(snode, NODENAME)) {
1698 safestrncpy(snode, FQDN, sizeof snode);
1701 /* Construct a fun message id */
1702 cprintf("Message-ID: <%s", mid);
1703 if (strchr(mid, '@')==NULL) {
1704 cprintf("@%s", snode);
1708 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1709 cprintf("From: \"----\" <x@x.org>%s", nl);
1711 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1712 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1714 else if (strlen(fuser) > 0) {
1715 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1718 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1721 cprintf("Organization: %s%s", lnode, nl);
1723 /* Blank line signifying RFC822 end-of-headers */
1724 if (TheMessage->cm_format_type != FMT_RFC822) {
1729 /* end header processing loop ... at this point, we're in the text */
1731 if (headers_only == HEADERS_FAST) goto DONE;
1732 mptr = TheMessage->cm_fields['M'];
1734 /* Tell the client about the MIME parts in this message */
1735 if (TheMessage->cm_format_type == FMT_RFC822) {
1736 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1737 memset(&ma, 0, sizeof(struct ma_info));
1738 mime_parser(mptr, NULL,
1739 (do_proto ? *list_this_part : NULL),
1740 (do_proto ? *list_this_pref : NULL),
1741 (do_proto ? *list_this_suff : NULL),
1744 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1745 char *start_of_text = NULL;
1746 start_of_text = strstr(mptr, "\n\r\n");
1747 if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1748 if (start_of_text == NULL) start_of_text = mptr;
1750 start_of_text = strstr(start_of_text, "\n");
1755 int nllen = strlen(nl);
1756 while (ch=*mptr, ch!=0) {
1762 ((headers_only == HEADERS_NONE) && (mptr >= start_of_text))
1763 || ((headers_only == HEADERS_ONLY) && (mptr < start_of_text))
1764 || ((headers_only != HEADERS_NONE) && (headers_only != HEADERS_ONLY))
1767 sprintf(&outbuf[outlen], "%s", nl);
1771 outbuf[outlen++] = ch;
1776 if (outlen > 1000) {
1777 client_write(outbuf, outlen);
1782 client_write(outbuf, outlen);
1790 if (headers_only == HEADERS_ONLY) {
1794 /* signify start of msg text */
1795 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1796 if (do_proto) cprintf("text\n");
1799 /* If the format type on disk is 1 (fixed-format), then we want
1800 * everything to be output completely literally ... regardless of
1801 * what message transfer format is in use.
1803 if (TheMessage->cm_format_type == FMT_FIXED) {
1804 if (mode == MT_MIME) {
1805 cprintf("Content-type: text/plain\n\n");
1808 while (ch = *mptr++, ch > 0) {
1811 if ((ch == 10) || (strlen(buf) > 250)) {
1812 cprintf("%s%s", buf, nl);
1815 buf[strlen(buf) + 1] = 0;
1816 buf[strlen(buf)] = ch;
1819 if (strlen(buf) > 0)
1820 cprintf("%s%s", buf, nl);
1823 /* If the message on disk is format 0 (Citadel vari-format), we
1824 * output using the formatter at 80 columns. This is the final output
1825 * form if the transfer format is RFC822, but if the transfer format
1826 * is Citadel proprietary, it'll still work, because the indentation
1827 * for new paragraphs is correct and the client will reformat the
1828 * message to the reader's screen width.
1830 if (TheMessage->cm_format_type == FMT_CITADEL) {
1831 if (mode == MT_MIME) {
1832 cprintf("Content-type: text/x-citadel-variformat\n\n");
1834 memfmout(mptr, 0, nl);
1837 /* If the message on disk is format 4 (MIME), we've gotta hand it
1838 * off to the MIME parser. The client has already been told that
1839 * this message is format 1 (fixed format), so the callback function
1840 * we use will display those parts as-is.
1842 if (TheMessage->cm_format_type == FMT_RFC822) {
1843 memset(&ma, 0, sizeof(struct ma_info));
1845 if (mode == MT_MIME) {
1846 ma.use_fo_hooks = 0;
1847 strcpy(ma.chosen_part, "1");
1848 ma.chosen_pref = 9999;
1849 mime_parser(mptr, NULL,
1850 *choose_preferred, *fixed_output_pre,
1851 *fixed_output_post, (void *)&ma, 0);
1852 mime_parser(mptr, NULL,
1853 *output_preferred, NULL, NULL, (void *)&ma, 0);
1856 ma.use_fo_hooks = 1;
1857 mime_parser(mptr, NULL,
1858 *fixed_output, *fixed_output_pre,
1859 *fixed_output_post, (void *)&ma, 0);
1864 DONE: /* now we're done */
1865 if (do_proto) cprintf("000\n");
1872 * display a message (mode 0 - Citadel proprietary)
1874 void cmd_msg0(char *cmdbuf)
1877 int headers_only = HEADERS_ALL;
1879 msgid = extract_long(cmdbuf, 0);
1880 headers_only = extract_int(cmdbuf, 1);
1882 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1888 * display a message (mode 2 - RFC822)
1890 void cmd_msg2(char *cmdbuf)
1893 int headers_only = HEADERS_ALL;
1895 msgid = extract_long(cmdbuf, 0);
1896 headers_only = extract_int(cmdbuf, 1);
1898 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1904 * display a message (mode 3 - IGnet raw format - internal programs only)
1906 void cmd_msg3(char *cmdbuf)
1909 struct CtdlMessage *msg = NULL;
1912 if (CC->internal_pgm == 0) {
1913 cprintf("%d This command is for internal programs only.\n",
1914 ERROR + HIGHER_ACCESS_REQUIRED);
1918 msgnum = extract_long(cmdbuf, 0);
1919 msg = CtdlFetchMessage(msgnum, 1);
1921 cprintf("%d Message %ld not found.\n",
1922 ERROR + MESSAGE_NOT_FOUND, msgnum);
1926 serialize_message(&smr, msg);
1927 CtdlFreeMessage(msg);
1930 cprintf("%d Unable to serialize message\n",
1931 ERROR + INTERNAL_ERROR);
1935 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1936 client_write((char *)smr.ser, (int)smr.len);
1943 * Display a message using MIME content types
1945 void cmd_msg4(char *cmdbuf)
1950 msgid = extract_long(cmdbuf, 0);
1951 extract_token(section, cmdbuf, 1, '|', sizeof section);
1952 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1958 * Client tells us its preferred message format(s)
1960 void cmd_msgp(char *cmdbuf)
1962 safestrncpy(CC->preferred_formats, cmdbuf,
1963 sizeof(CC->preferred_formats));
1964 cprintf("%d ok\n", CIT_OK);
1969 * Open a component of a MIME message as a download file
1971 void cmd_opna(char *cmdbuf)
1974 char desired_section[128];
1976 msgid = extract_long(cmdbuf, 0);
1977 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1978 safestrncpy(CC->download_desired_section, desired_section,
1979 sizeof CC->download_desired_section);
1980 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
1985 * Open a component of a MIME message and transmit it all at once
1987 void cmd_dlat(char *cmdbuf)
1990 char desired_section[128];
1992 msgid = extract_long(cmdbuf, 0);
1993 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1994 safestrncpy(CC->download_desired_section, desired_section,
1995 sizeof CC->download_desired_section);
1996 CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL);
2001 * Save one or more message pointers into a specified room
2002 * (Returns 0 for success, nonzero for failure)
2003 * roomname may be NULL to use the current room
2005 * Note that the 'supplied_msg' field may be set to NULL, in which case
2006 * the message will be fetched from disk, by number, if we need to perform
2007 * replication checks. This adds an additional database read, so if the
2008 * caller already has the message in memory then it should be supplied. (Obviously
2009 * this mode of operation only works if we're saving a single message.)
2011 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2012 int do_repl_check, struct CtdlMessage *supplied_msg)
2015 char hold_rm[ROOMNAMELEN];
2016 struct cdbdata *cdbfr;
2019 long highest_msg = 0L;
2022 struct CtdlMessage *msg = NULL;
2024 long *msgs_to_be_merged = NULL;
2025 int num_msgs_to_be_merged = 0;
2028 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d)\n",
2029 roomname, num_newmsgs, do_repl_check);
2031 strcpy(hold_rm, CC->room.QRname);
2034 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2035 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2036 if (num_newmsgs > 1) supplied_msg = NULL;
2038 /* Now the regular stuff */
2039 if (lgetroom(&CC->room,
2040 ((roomname != NULL) ? roomname : CC->room.QRname) )
2042 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
2043 return(ERROR + ROOM_NOT_FOUND);
2047 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2048 num_msgs_to_be_merged = 0;
2051 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2052 if (cdbfr == NULL) {
2056 msglist = (long *) cdbfr->ptr;
2057 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2058 num_msgs = cdbfr->len / sizeof(long);
2063 /* Create a list of msgid's which were supplied by the caller, but do
2064 * not already exist in the target room. It is absolutely taboo to
2065 * have more than one reference to the same message in a room.
2067 for (i=0; i<num_newmsgs; ++i) {
2069 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2070 if (msglist[j] == newmsgidlist[i]) {
2075 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2079 lprintf(9, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2082 * Now merge the new messages
2084 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2085 if (msglist == NULL) {
2086 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
2088 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2089 num_msgs += num_msgs_to_be_merged;
2091 /* Sort the message list, so all the msgid's are in order */
2092 num_msgs = sort_msglist(msglist, num_msgs);
2094 /* Determine the highest message number */
2095 highest_msg = msglist[num_msgs - 1];
2097 /* Write it back to disk. */
2098 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2099 msglist, (int)(num_msgs * sizeof(long)));
2101 /* Free up the memory we used. */
2104 /* Update the highest-message pointer and unlock the room. */
2105 CC->room.QRhighest = highest_msg;
2106 lputroom(&CC->room);
2108 /* Perform replication checks if necessary */
2109 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2110 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2112 for (i=0; i<num_msgs_to_be_merged; ++i) {
2113 msgid = msgs_to_be_merged[i];
2115 if (supplied_msg != NULL) {
2119 msg = CtdlFetchMessage(msgid, 0);
2123 ReplicationChecks(msg);
2125 /* If the message has an Exclusive ID, index that... */
2126 if (msg->cm_fields['E'] != NULL) {
2127 index_message_by_euid(msg->cm_fields['E'], &CC->room, msgid);
2130 /* Free up the memory we may have allocated */
2131 if (msg != supplied_msg) {
2132 CtdlFreeMessage(msg);
2140 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2143 /* Submit this room for processing by hooks */
2144 PerformRoomHooks(&CC->room);
2146 /* Go back to the room we were in before we wandered here... */
2147 getroom(&CC->room, hold_rm);
2149 /* Bump the reference count for all messages which were merged */
2150 for (i=0; i<num_msgs_to_be_merged; ++i) {
2151 AdjRefCount(msgs_to_be_merged[i], +1);
2154 /* Free up memory... */
2155 if (msgs_to_be_merged != NULL) {
2156 free(msgs_to_be_merged);
2159 /* Return success. */
2165 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2168 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2169 int do_repl_check, struct CtdlMessage *supplied_msg)
2171 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg);
2178 * Message base operation to save a new message to the message store
2179 * (returns new message number)
2181 * This is the back end for CtdlSubmitMsg() and should not be directly
2182 * called by server-side modules.
2185 long send_message(struct CtdlMessage *msg) {
2193 /* Get a new message number */
2194 newmsgid = get_new_message_number();
2195 snprintf(msgidbuf, sizeof msgidbuf, "%010ld@%s", newmsgid, config.c_fqdn);
2197 /* Generate an ID if we don't have one already */
2198 if (msg->cm_fields['I']==NULL) {
2199 msg->cm_fields['I'] = strdup(msgidbuf);
2202 /* If the message is big, set its body aside for storage elsewhere */
2203 if (msg->cm_fields['M'] != NULL) {
2204 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2206 holdM = msg->cm_fields['M'];
2207 msg->cm_fields['M'] = NULL;
2211 /* Serialize our data structure for storage in the database */
2212 serialize_message(&smr, msg);
2215 msg->cm_fields['M'] = holdM;
2219 cprintf("%d Unable to serialize message\n",
2220 ERROR + INTERNAL_ERROR);
2224 /* Write our little bundle of joy into the message base */
2225 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2226 smr.ser, smr.len) < 0) {
2227 lprintf(CTDL_ERR, "Can't store message\n");
2231 cdb_store(CDB_BIGMSGS,
2241 /* Free the memory we used for the serialized message */
2244 /* Return the *local* message ID to the caller
2245 * (even if we're storing an incoming network message)
2253 * Serialize a struct CtdlMessage into the format used on disk and network.
2255 * This function loads up a "struct ser_ret" (defined in server.h) which
2256 * contains the length of the serialized message and a pointer to the
2257 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2259 void serialize_message(struct ser_ret *ret, /* return values */
2260 struct CtdlMessage *msg) /* unserialized msg */
2262 size_t wlen, fieldlen;
2264 static char *forder = FORDER;
2267 * Check for valid message format
2269 if (is_valid_message(msg) == 0) {
2270 lprintf(CTDL_ERR, "serialize_message() aborting due to invalid message\n");
2277 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2278 ret->len = ret->len +
2279 strlen(msg->cm_fields[(int)forder[i]]) + 2;
2281 ret->ser = malloc(ret->len);
2282 if (ret->ser == NULL) {
2283 lprintf(CTDL_ERR, "serialize_message() malloc(%ld) failed: %s\n",
2284 (long)ret->len, strerror(errno));
2291 ret->ser[1] = msg->cm_anon_type;
2292 ret->ser[2] = msg->cm_format_type;
2295 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2296 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
2297 ret->ser[wlen++] = (char)forder[i];
2298 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
2299 wlen = wlen + fieldlen + 1;
2301 if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2302 (long)ret->len, (long)wlen);
2310 * Check to see if any messages already exist in the current room which
2311 * carry the same Exclusive ID as this one. If any are found, delete them.
2313 void ReplicationChecks(struct CtdlMessage *msg) {
2314 long old_msgnum = (-1L);
2316 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2318 lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2321 /* No exclusive id? Don't do anything. */
2322 if (msg == NULL) return;
2323 if (msg->cm_fields['E'] == NULL) return;
2324 if (strlen(msg->cm_fields['E']) == 0) return;
2325 /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2326 msg->cm_fields['E'], CC->room.QRname);*/
2328 old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2329 if (old_msgnum > 0L) {
2330 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2331 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2338 * Save a message to disk and submit it into the delivery system.
2340 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2341 struct recptypes *recps, /* recipients (if mail) */
2342 char *force /* force a particular room? */
2344 char submit_filename[128];
2345 char generated_timestamp[32];
2346 char hold_rm[ROOMNAMELEN];
2347 char actual_rm[ROOMNAMELEN];
2348 char force_room[ROOMNAMELEN];
2349 char content_type[SIZ]; /* We have to learn this */
2350 char recipient[SIZ];
2353 struct ctdluser userbuf;
2355 struct MetaData smi;
2356 FILE *network_fp = NULL;
2357 static int seqnum = 1;
2358 struct CtdlMessage *imsg = NULL;
2360 size_t instr_alloc = 0;
2362 char *hold_R, *hold_D;
2363 char *collected_addresses = NULL;
2364 struct addresses_to_be_filed *aptr = NULL;
2365 char *saved_rfc822_version = NULL;
2366 int qualified_for_journaling = 0;
2368 lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2369 if (is_valid_message(msg) == 0) return(-1); /* self check */
2371 /* If this message has no timestamp, we take the liberty of
2372 * giving it one, right now.
2374 if (msg->cm_fields['T'] == NULL) {
2375 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2376 msg->cm_fields['T'] = strdup(generated_timestamp);
2379 /* If this message has no path, we generate one.
2381 if (msg->cm_fields['P'] == NULL) {
2382 if (msg->cm_fields['A'] != NULL) {
2383 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2384 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
2385 if (isspace(msg->cm_fields['P'][a])) {
2386 msg->cm_fields['P'][a] = ' ';
2391 msg->cm_fields['P'] = strdup("unknown");
2395 if (force == NULL) {
2396 strcpy(force_room, "");
2399 strcpy(force_room, force);
2402 /* Learn about what's inside, because it's what's inside that counts */
2403 if (msg->cm_fields['M'] == NULL) {
2404 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2408 switch (msg->cm_format_type) {
2410 strcpy(content_type, "text/x-citadel-variformat");
2413 strcpy(content_type, "text/plain");
2416 strcpy(content_type, "text/plain");
2417 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type:");
2419 safestrncpy(content_type, &mptr[13], sizeof content_type);
2420 striplt(content_type);
2421 for (a = 0; a < strlen(content_type); ++a) {
2422 if ((content_type[a] == ';')
2423 || (content_type[a] == ' ')
2424 || (content_type[a] == 13)
2425 || (content_type[a] == 10)) {
2426 content_type[a] = 0;
2432 /* Goto the correct room */
2433 lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CC->room.QRname : SENTITEMS);
2434 strcpy(hold_rm, CC->room.QRname);
2435 strcpy(actual_rm, CC->room.QRname);
2436 if (recps != NULL) {
2437 strcpy(actual_rm, SENTITEMS);
2440 /* If the user is a twit, move to the twit room for posting */
2442 if (CC->user.axlevel == 2) {
2443 strcpy(hold_rm, actual_rm);
2444 strcpy(actual_rm, config.c_twitroom);
2445 lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2449 /* ...or if this message is destined for Aide> then go there. */
2450 if (strlen(force_room) > 0) {
2451 strcpy(actual_rm, force_room);
2454 lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2455 if (strcasecmp(actual_rm, CC->room.QRname)) {
2456 /* getroom(&CC->room, actual_rm); */
2457 usergoto(actual_rm, 0, 1, NULL, NULL);
2461 * If this message has no O (room) field, generate one.
2463 if (msg->cm_fields['O'] == NULL) {
2464 msg->cm_fields['O'] = strdup(CC->room.QRname);
2467 /* Perform "before save" hooks (aborting if any return nonzero) */
2468 lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2469 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2472 * If this message has an Exclusive ID, and the room is replication
2473 * checking enabled, then do replication checks.
2475 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2476 ReplicationChecks(msg);
2479 /* Save it to disk */
2480 lprintf(CTDL_DEBUG, "Saving to disk\n");
2481 newmsgid = send_message(msg);
2482 if (newmsgid <= 0L) return(-5);
2484 /* Write a supplemental message info record. This doesn't have to
2485 * be a critical section because nobody else knows about this message
2488 lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2489 memset(&smi, 0, sizeof(struct MetaData));
2490 smi.meta_msgnum = newmsgid;
2491 smi.meta_refcount = 0;
2492 safestrncpy(smi.meta_content_type, content_type,
2493 sizeof smi.meta_content_type);
2496 * Measure how big this message will be when rendered as RFC822.
2497 * We do this for two reasons:
2498 * 1. We need the RFC822 length for the new metadata record, so the
2499 * POP and IMAP services don't have to calculate message lengths
2500 * while the user is waiting (multiplied by potentially hundreds
2501 * or thousands of messages).
2502 * 2. If journaling is enabled, we will need an RFC822 version of the
2503 * message to attach to the journalized copy.
2505 if (CC->redirect_buffer != NULL) {
2506 lprintf(CTDL_ALERT, "CC->redirect_buffer is not NULL during message submission!\n");
2509 CC->redirect_buffer = malloc(SIZ);
2510 CC->redirect_len = 0;
2511 CC->redirect_alloc = SIZ;
2512 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2513 smi.meta_rfc822_length = CC->redirect_len;
2514 saved_rfc822_version = CC->redirect_buffer;
2515 CC->redirect_buffer = NULL;
2516 CC->redirect_len = 0;
2517 CC->redirect_alloc = 0;
2521 /* Now figure out where to store the pointers */
2522 lprintf(CTDL_DEBUG, "Storing pointers\n");
2524 /* If this is being done by the networker delivering a private
2525 * message, we want to BYPASS saving the sender's copy (because there
2526 * is no local sender; it would otherwise go to the Trashcan).
2528 if ((!CC->internal_pgm) || (recps == NULL)) {
2529 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2530 lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2531 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2535 /* For internet mail, drop a copy in the outbound queue room */
2537 if (recps->num_internet > 0) {
2538 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2541 /* If other rooms are specified, drop them there too. */
2543 if (recps->num_room > 0)
2544 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2545 extract_token(recipient, recps->recp_room, i,
2546 '|', sizeof recipient);
2547 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2548 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2551 /* Bump this user's messages posted counter. */
2552 lprintf(CTDL_DEBUG, "Updating user\n");
2553 lgetuser(&CC->user, CC->curr_user);
2554 CC->user.posted = CC->user.posted + 1;
2555 lputuser(&CC->user);
2557 /* If this is private, local mail, make a copy in the
2558 * recipient's mailbox and bump the reference count.
2561 if (recps->num_local > 0)
2562 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2563 extract_token(recipient, recps->recp_local, i,
2564 '|', sizeof recipient);
2565 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2567 if (getuser(&userbuf, recipient) == 0) {
2568 // Add a flag so the Funambol module knows its mail
2569 msg->cm_fields['W'] = strdup(recipient);
2570 MailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
2571 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2572 BumpNewMailCounter(userbuf.usernum);
2573 if (strlen(config.c_funambol_host) > 0) {
2574 /* Generate a instruction message for the Funambol notification
2575 * server, in the same style as the SMTP queue
2578 instr = malloc(instr_alloc);
2579 snprintf(instr, instr_alloc,
2580 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2582 SPOOLMIME, newmsgid, (long)time(NULL),
2583 msg->cm_fields['A'], msg->cm_fields['N']
2586 imsg = malloc(sizeof(struct CtdlMessage));
2587 memset(imsg, 0, sizeof(struct CtdlMessage));
2588 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2589 imsg->cm_anon_type = MES_NORMAL;
2590 imsg->cm_format_type = FMT_RFC822;
2591 imsg->cm_fields['A'] = strdup("Citadel");
2592 imsg->cm_fields['J'] = strdup("do not journal");
2593 imsg->cm_fields['M'] = instr; /* imsg owns this memory now */
2594 imsg->cm_fields['W'] = strdup(recipient);
2595 CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM);
2596 CtdlFreeMessage(imsg);
2600 lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2601 CtdlSaveMsgPointerInRoom(config.c_aideroom,
2606 /* Perform "after save" hooks */
2607 lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2608 PerformMessageHooks(msg, EVT_AFTERSAVE);
2610 /* For IGnet mail, we have to save a new copy into the spooler for
2611 * each recipient, with the R and D fields set to the recipient and
2612 * destination-node. This has two ugly side effects: all other
2613 * recipients end up being unlisted in this recipient's copy of the
2614 * message, and it has to deliver multiple messages to the same
2615 * node. We'll revisit this again in a year or so when everyone has
2616 * a network spool receiver that can handle the new style messages.
2619 if (recps->num_ignet > 0)
2620 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2621 extract_token(recipient, recps->recp_ignet, i,
2622 '|', sizeof recipient);
2624 hold_R = msg->cm_fields['R'];
2625 hold_D = msg->cm_fields['D'];
2626 msg->cm_fields['R'] = malloc(SIZ);
2627 msg->cm_fields['D'] = malloc(128);
2628 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2629 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2631 serialize_message(&smr, msg);
2633 snprintf(submit_filename, sizeof submit_filename,
2634 "%s/netmail.%04lx.%04x.%04x",
2636 (long) getpid(), CC->cs_pid, ++seqnum);
2637 network_fp = fopen(submit_filename, "wb+");
2638 if (network_fp != NULL) {
2639 fwrite(smr.ser, smr.len, 1, network_fp);
2645 free(msg->cm_fields['R']);
2646 free(msg->cm_fields['D']);
2647 msg->cm_fields['R'] = hold_R;
2648 msg->cm_fields['D'] = hold_D;
2651 /* Go back to the room we started from */
2652 lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2653 if (strcasecmp(hold_rm, CC->room.QRname))
2654 usergoto(hold_rm, 0, 1, NULL, NULL);
2656 /* For internet mail, generate delivery instructions.
2657 * Yes, this is recursive. Deal with it. Infinite recursion does
2658 * not happen because the delivery instructions message does not
2659 * contain a recipient.
2662 if (recps->num_internet > 0) {
2663 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2665 instr = malloc(instr_alloc);
2666 snprintf(instr, instr_alloc,
2667 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2669 SPOOLMIME, newmsgid, (long)time(NULL),
2670 msg->cm_fields['A'], msg->cm_fields['N']
2673 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2674 size_t tmp = strlen(instr);
2675 extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
2676 if ((tmp + strlen(recipient) + 32) > instr_alloc) {
2677 instr_alloc = instr_alloc * 2;
2678 instr = realloc(instr, instr_alloc);
2680 snprintf(&instr[tmp], instr_alloc - tmp, "remote|%s|0||\n", recipient);
2683 imsg = malloc(sizeof(struct CtdlMessage));
2684 memset(imsg, 0, sizeof(struct CtdlMessage));
2685 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2686 imsg->cm_anon_type = MES_NORMAL;
2687 imsg->cm_format_type = FMT_RFC822;
2688 imsg->cm_fields['A'] = strdup("Citadel");
2689 imsg->cm_fields['J'] = strdup("do not journal");
2690 imsg->cm_fields['M'] = instr; /* imsg owns this memory now */
2691 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2692 CtdlFreeMessage(imsg);
2696 * Any addresses to harvest for someone's address book?
2698 if ( (CC->logged_in) && (recps != NULL) ) {
2699 collected_addresses = harvest_collected_addresses(msg);
2702 if (collected_addresses != NULL) {
2703 begin_critical_section(S_ATBF);
2704 aptr = (struct addresses_to_be_filed *)
2705 malloc(sizeof(struct addresses_to_be_filed));
2707 MailboxName(actual_rm, sizeof actual_rm,
2708 &CC->user, USERCONTACTSROOM);
2709 aptr->roomname = strdup(actual_rm);
2710 aptr->collected_addresses = collected_addresses;
2712 end_critical_section(S_ATBF);
2716 * Determine whether this message qualifies for journaling.
2718 if (msg->cm_fields['J'] != NULL) {
2719 qualified_for_journaling = 0;
2722 if (recps == NULL) {
2723 qualified_for_journaling = config.c_journal_pubmsgs;
2725 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2726 qualified_for_journaling = config.c_journal_email;
2729 qualified_for_journaling = config.c_journal_pubmsgs;
2734 * Do we have to perform journaling? If so, hand off the saved
2735 * RFC822 version will be handed off to the journaler for background
2736 * submit. Otherwise, we have to free the memory ourselves.
2738 if (saved_rfc822_version != NULL) {
2739 if (qualified_for_journaling) {
2740 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2743 free(saved_rfc822_version);
2756 * Convenience function for generating small administrative messages.
2758 void quickie_message(char *from, char *fromaddr, char *to, char *room, char *text,
2759 int format_type, char *subject)
2761 struct CtdlMessage *msg;
2762 struct recptypes *recp = NULL;
2764 msg = malloc(sizeof(struct CtdlMessage));
2765 memset(msg, 0, sizeof(struct CtdlMessage));
2766 msg->cm_magic = CTDLMESSAGE_MAGIC;
2767 msg->cm_anon_type = MES_NORMAL;
2768 msg->cm_format_type = format_type;
2771 msg->cm_fields['A'] = strdup(from);
2773 else if (fromaddr != NULL) {
2774 msg->cm_fields['A'] = strdup(fromaddr);
2775 if (strchr(msg->cm_fields['A'], '@')) {
2776 *strchr(msg->cm_fields['A'], '@') = 0;
2780 msg->cm_fields['A'] = strdup("Citadel");
2783 if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
2784 if (room != NULL) msg->cm_fields['O'] = strdup(room);
2785 msg->cm_fields['N'] = strdup(NODENAME);
2787 msg->cm_fields['R'] = strdup(to);
2788 recp = validate_recipients(to);
2790 if (subject != NULL) {
2791 msg->cm_fields['U'] = strdup(subject);
2793 msg->cm_fields['M'] = strdup(text);
2795 CtdlSubmitMsg(msg, recp, room);
2796 CtdlFreeMessage(msg);
2797 if (recp != NULL) free_recipients(recp);
2803 * Back end function used by CtdlMakeMessage() and similar functions
2805 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2806 size_t maxlen, /* maximum message length */
2807 char *exist, /* if non-null, append to it;
2808 exist is ALWAYS freed */
2809 int crlf /* CRLF newlines instead of LF */
2813 size_t message_len = 0;
2814 size_t buffer_len = 0;
2821 if (exist == NULL) {
2828 message_len = strlen(exist);
2829 buffer_len = message_len + 4096;
2830 m = realloc(exist, buffer_len);
2837 /* Do we need to change leading ".." to "." for SMTP escaping? */
2838 if (!strcmp(terminator, ".")) {
2842 /* flush the input if we have nowhere to store it */
2847 /* read in the lines of message text one by one */
2849 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2850 if (!strcmp(buf, terminator)) finished = 1;
2852 strcat(buf, "\r\n");
2858 /* Unescape SMTP-style input of two dots at the beginning of the line */
2860 if (!strncmp(buf, "..", 2)) {
2861 strcpy(buf, &buf[1]);
2865 if ( (!flushing) && (!finished) ) {
2866 /* Measure the line */
2867 linelen = strlen(buf);
2869 /* augment the buffer if we have to */
2870 if ((message_len + linelen) >= buffer_len) {
2871 ptr = realloc(m, (buffer_len * 2) );
2872 if (ptr == NULL) { /* flush if can't allocate */
2875 buffer_len = (buffer_len * 2);
2877 lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2881 /* Add the new line to the buffer. NOTE: this loop must avoid
2882 * using functions like strcat() and strlen() because they
2883 * traverse the entire buffer upon every call, and doing that
2884 * for a multi-megabyte message slows it down beyond usability.
2886 strcpy(&m[message_len], buf);
2887 message_len += linelen;
2890 /* if we've hit the max msg length, flush the rest */
2891 if (message_len >= maxlen) flushing = 1;
2893 } while (!finished);
2901 * Build a binary message to be saved on disk.
2902 * (NOTE: if you supply 'preformatted_text', the buffer you give it
2903 * will become part of the message. This means you are no longer
2904 * responsible for managing that memory -- it will be freed along with
2905 * the rest of the fields when CtdlFreeMessage() is called.)
2908 struct CtdlMessage *CtdlMakeMessage(
2909 struct ctdluser *author, /* author's user structure */
2910 char *recipient, /* NULL if it's not mail */
2911 char *recp_cc, /* NULL if it's not mail */
2912 char *room, /* room where it's going */
2913 int type, /* see MES_ types in header file */
2914 int format_type, /* variformat, plain text, MIME... */
2915 char *fake_name, /* who we're masquerading as */
2916 char *my_email, /* which of my email addresses to use (empty is ok) */
2917 char *subject, /* Subject (optional) */
2918 char *supplied_euid, /* ...or NULL if this is irrelevant */
2919 char *preformatted_text /* ...or NULL to read text from client */
2921 char dest_node[256];
2923 struct CtdlMessage *msg;
2926 msg = malloc(sizeof(struct CtdlMessage));
2927 memset(msg, 0, sizeof(struct CtdlMessage));
2928 msg->cm_magic = CTDLMESSAGE_MAGIC;
2929 msg->cm_anon_type = type;
2930 msg->cm_format_type = format_type;
2932 /* Don't confuse the poor folks if it's not routed mail. */
2933 strcpy(dest_node, "");
2938 /* Path or Return-Path */
2939 if (my_email == NULL) my_email = "";
2941 if (strlen(my_email) > 0) {
2942 msg->cm_fields['P'] = strdup(my_email);
2945 snprintf(buf, sizeof buf, "%s", author->fullname);
2946 msg->cm_fields['P'] = strdup(buf);
2948 for (i=0; (msg->cm_fields['P'][i]!=0); ++i) {
2949 if (isspace(msg->cm_fields['P'][i])) {
2950 msg->cm_fields['P'][i] = '_';
2954 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
2955 msg->cm_fields['T'] = strdup(buf);
2957 if (fake_name[0]) /* author */
2958 msg->cm_fields['A'] = strdup(fake_name);
2960 msg->cm_fields['A'] = strdup(author->fullname);
2962 if (CC->room.QRflags & QR_MAILBOX) { /* room */
2963 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2966 msg->cm_fields['O'] = strdup(CC->room.QRname);
2969 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
2970 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
2972 if (recipient[0] != 0) {
2973 msg->cm_fields['R'] = strdup(recipient);
2975 if (recp_cc[0] != 0) {
2976 msg->cm_fields['Y'] = strdup(recp_cc);
2978 if (dest_node[0] != 0) {
2979 msg->cm_fields['D'] = strdup(dest_node);
2982 if (strlen(my_email) > 0) {
2983 msg->cm_fields['F'] = strdup(my_email);
2985 else if ( (author == &CC->user) && (strlen(CC->cs_inet_email) > 0) ) {
2986 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2989 if (subject != NULL) {
2992 length = strlen(subject);
2998 while ((subject[i] != '\0') &&
2999 (IsAscii = isascii(subject[i]) != 0 ))
3002 msg->cm_fields['U'] = strdup(subject);
3003 else /* ok, we've got utf8 in the string. */
3005 msg->cm_fields['U'] = rfc2047encode(subject, length);
3011 if (supplied_euid != NULL) {
3012 msg->cm_fields['E'] = strdup(supplied_euid);
3015 if (preformatted_text != NULL) {
3016 msg->cm_fields['M'] = preformatted_text;
3019 msg->cm_fields['M'] = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
3027 * Check to see whether we have permission to post a message in the current
3028 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
3029 * returns 0 on success.
3031 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
3034 if (!(CC->logged_in)) {
3035 snprintf(errmsgbuf, n, "Not logged in.");
3036 return (ERROR + NOT_LOGGED_IN);
3039 if ((CC->user.axlevel < 2)
3040 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
3041 snprintf(errmsgbuf, n, "Need to be validated to enter "
3042 "(except in %s> to sysop)", MAILROOM);
3043 return (ERROR + HIGHER_ACCESS_REQUIRED);
3046 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3047 if (!(ra & UA_POSTALLOWED)) {
3048 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
3049 return (ERROR + HIGHER_ACCESS_REQUIRED);
3052 strcpy(errmsgbuf, "Ok");
3058 * Check to see if the specified user has Internet mail permission
3059 * (returns nonzero if permission is granted)
3061 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
3063 /* Do not allow twits to send Internet mail */
3064 if (who->axlevel <= 2) return(0);
3066 /* Globally enabled? */
3067 if (config.c_restrict == 0) return(1);
3069 /* User flagged ok? */
3070 if (who->flags & US_INTERNET) return(2);
3072 /* Aide level access? */
3073 if (who->axlevel >= 6) return(3);
3075 /* No mail for you! */
3081 * Validate recipients, count delivery types and errors, and handle aliasing
3082 * FIXME check for dupes!!!!!
3084 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
3085 * were specified, or the number of addresses found invalid.
3087 * Caller needs to free the result using free_recipients()
3089 struct recptypes *validate_recipients(char *supplied_recipients) {
3090 struct recptypes *ret;
3091 char *recipients = NULL;
3092 char this_recp[256];
3093 char this_recp_cooked[256];
3099 struct ctdluser tempUS;
3100 struct ctdlroom tempQR;
3104 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
3105 if (ret == NULL) return(NULL);
3107 /* Set all strings to null and numeric values to zero */
3108 memset(ret, 0, sizeof(struct recptypes));
3110 if (supplied_recipients == NULL) {
3111 recipients = strdup("");
3114 recipients = strdup(supplied_recipients);
3117 /* Allocate some memory. Yes, this allocates 500% more memory than we will
3118 * actually need, but it's healthier for the heap than doing lots of tiny
3119 * realloc() calls instead.
3122 ret->errormsg = malloc(strlen(recipients) + 1024);
3123 ret->recp_local = malloc(strlen(recipients) + 1024);
3124 ret->recp_internet = malloc(strlen(recipients) + 1024);
3125 ret->recp_ignet = malloc(strlen(recipients) + 1024);
3126 ret->recp_room = malloc(strlen(recipients) + 1024);
3127 ret->display_recp = malloc(strlen(recipients) + 1024);
3129 ret->errormsg[0] = 0;
3130 ret->recp_local[0] = 0;
3131 ret->recp_internet[0] = 0;
3132 ret->recp_ignet[0] = 0;
3133 ret->recp_room[0] = 0;
3134 ret->display_recp[0] = 0;
3136 ret->recptypes_magic = RECPTYPES_MAGIC;
3138 /* Change all valid separator characters to commas */
3139 for (i=0; i<strlen(recipients); ++i) {
3140 if ((recipients[i] == ';') || (recipients[i] == '|')) {
3141 recipients[i] = ',';
3145 /* Now start extracting recipients... */
3147 while (strlen(recipients) > 0) {
3149 for (i=0; i<=strlen(recipients); ++i) {
3150 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
3151 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
3152 safestrncpy(this_recp, recipients, i+1);
3154 if (recipients[i] == ',') {
3155 strcpy(recipients, &recipients[i+1]);
3158 strcpy(recipients, "");
3165 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
3167 mailtype = alias(this_recp);
3168 mailtype = alias(this_recp);
3169 mailtype = alias(this_recp);
3170 for (j=0; j<=strlen(this_recp); ++j) {
3171 if (this_recp[j]=='_') {
3172 this_recp_cooked[j] = ' ';
3175 this_recp_cooked[j] = this_recp[j];
3181 if (!strcasecmp(this_recp, "sysop")) {
3183 strcpy(this_recp, config.c_aideroom);
3184 if (strlen(ret->recp_room) > 0) {
3185 strcat(ret->recp_room, "|");
3187 strcat(ret->recp_room, this_recp);
3189 else if (getuser(&tempUS, this_recp) == 0) {
3191 strcpy(this_recp, tempUS.fullname);
3192 if (strlen(ret->recp_local) > 0) {
3193 strcat(ret->recp_local, "|");
3195 strcat(ret->recp_local, this_recp);
3197 else if (getuser(&tempUS, this_recp_cooked) == 0) {
3199 strcpy(this_recp, tempUS.fullname);
3200 if (strlen(ret->recp_local) > 0) {
3201 strcat(ret->recp_local, "|");
3203 strcat(ret->recp_local, this_recp);
3205 else if ( (!strncasecmp(this_recp, "room_", 5))
3206 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
3208 if (strlen(ret->recp_room) > 0) {
3209 strcat(ret->recp_room, "|");
3211 strcat(ret->recp_room, &this_recp_cooked[5]);
3219 /* Yes, you're reading this correctly: if the target
3220 * domain points back to the local system or an attached
3221 * Citadel directory, the address is invalid. That's
3222 * because if the address were valid, we would have
3223 * already translated it to a local address by now.
3225 if (IsDirectory(this_recp, 0)) {
3230 ++ret->num_internet;
3231 if (strlen(ret->recp_internet) > 0) {
3232 strcat(ret->recp_internet, "|");
3234 strcat(ret->recp_internet, this_recp);
3239 if (strlen(ret->recp_ignet) > 0) {
3240 strcat(ret->recp_ignet, "|");
3242 strcat(ret->recp_ignet, this_recp);
3250 if (strlen(ret->errormsg) == 0) {
3251 snprintf(append, sizeof append,
3252 "Invalid recipient: %s",
3256 snprintf(append, sizeof append, ", %s", this_recp);
3258 if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
3259 strcat(ret->errormsg, append);
3263 if (strlen(ret->display_recp) == 0) {
3264 strcpy(append, this_recp);
3267 snprintf(append, sizeof append, ", %s", this_recp);
3269 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
3270 strcat(ret->display_recp, append);
3275 if ((ret->num_local + ret->num_internet + ret->num_ignet +
3276 ret->num_room + ret->num_error) == 0) {
3277 ret->num_error = (-1);
3278 strcpy(ret->errormsg, "No recipients specified.");
3281 lprintf(CTDL_DEBUG, "validate_recipients()\n");
3282 lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
3283 lprintf(CTDL_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
3284 lprintf(CTDL_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
3285 lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
3286 lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
3294 * Destructor for struct recptypes
3296 void free_recipients(struct recptypes *valid) {
3298 if (valid == NULL) {
3302 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
3303 lprintf(CTDL_EMERG, "Attempt to call free_recipients() on some other data type!\n");
3307 if (valid->errormsg != NULL) free(valid->errormsg);
3308 if (valid->recp_local != NULL) free(valid->recp_local);
3309 if (valid->recp_internet != NULL) free(valid->recp_internet);
3310 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
3311 if (valid->recp_room != NULL) free(valid->recp_room);
3312 if (valid->display_recp != NULL) free(valid->display_recp);
3319 * message entry - mode 0 (normal)
3321 void cmd_ent0(char *entargs)
3327 char supplied_euid[128];
3329 int format_type = 0;
3330 char newusername[256];
3331 char newuseremail[256];
3332 struct CtdlMessage *msg;
3336 struct recptypes *valid = NULL;
3337 struct recptypes *valid_to = NULL;
3338 struct recptypes *valid_cc = NULL;
3339 struct recptypes *valid_bcc = NULL;
3341 int subject_required = 0;
3346 int newuseremail_ok = 0;
3350 post = extract_int(entargs, 0);
3351 extract_token(recp, entargs, 1, '|', sizeof recp);
3352 anon_flag = extract_int(entargs, 2);
3353 format_type = extract_int(entargs, 3);
3354 extract_token(subject, entargs, 4, '|', sizeof subject);
3355 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3356 do_confirm = extract_int(entargs, 6);
3357 extract_token(cc, entargs, 7, '|', sizeof cc);
3358 extract_token(bcc, entargs, 8, '|', sizeof bcc);
3359 switch(CC->room.QRdefaultview) {
3362 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3365 supplied_euid[0] = 0;
3368 extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
3370 /* first check to make sure the request is valid. */
3372 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3375 cprintf("%d %s\n", err, errmsg);
3379 /* Check some other permission type things. */
3381 if (strlen(newusername) == 0) {
3382 strcpy(newusername, CC->user.fullname);
3384 if ( (CC->user.axlevel < 6)
3385 && (strcasecmp(newusername, CC->user.fullname))
3386 && (strcasecmp(newusername, CC->cs_inet_fn))
3388 cprintf("%d You don't have permission to author messages as '%s'.\n",
3389 ERROR + HIGHER_ACCESS_REQUIRED,
3396 if (strlen(newuseremail) == 0) {
3397 newuseremail_ok = 1;
3400 if (strlen(newuseremail) > 0) {
3401 if (!strcasecmp(newuseremail, CC->cs_inet_email)) {
3402 newuseremail_ok = 1;
3404 else if (strlen(CC->cs_inet_other_emails) > 0) {
3405 j = num_tokens(CC->cs_inet_other_emails, '|');
3406 for (i=0; i<j; ++i) {
3407 extract_token(buf, CC->cs_inet_other_emails, i, '|', sizeof buf);
3408 if (!strcasecmp(newuseremail, buf)) {
3409 newuseremail_ok = 1;
3415 if (!newuseremail_ok) {
3416 cprintf("%d You don't have permission to author messages as '%s'.\n",
3417 ERROR + HIGHER_ACCESS_REQUIRED,
3423 CC->cs_flags |= CS_POSTING;
3425 /* In mailbox rooms we have to behave a little differently --
3426 * make sure the user has specified at least one recipient. Then
3427 * validate the recipient(s). We do this for the Mail> room, as
3428 * well as any room which has the "Mailbox" view set.
3431 if ( ( (CC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) )
3432 || ( (CC->room.QRflags & QR_MAILBOX) && (CC->curr_view == VIEW_MAILBOX) )
3434 if (CC->user.axlevel < 2) {
3435 strcpy(recp, "sysop");
3440 valid_to = validate_recipients(recp);
3441 if (valid_to->num_error > 0) {
3442 cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3443 free_recipients(valid_to);
3447 valid_cc = validate_recipients(cc);
3448 if (valid_cc->num_error > 0) {
3449 cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3450 free_recipients(valid_to);
3451 free_recipients(valid_cc);
3455 valid_bcc = validate_recipients(bcc);
3456 if (valid_bcc->num_error > 0) {
3457 cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3458 free_recipients(valid_to);
3459 free_recipients(valid_cc);
3460 free_recipients(valid_bcc);
3464 /* Recipient required, but none were specified */
3465 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3466 free_recipients(valid_to);
3467 free_recipients(valid_cc);
3468 free_recipients(valid_bcc);
3469 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3473 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3474 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3475 cprintf("%d You do not have permission "
3476 "to send Internet mail.\n",
3477 ERROR + HIGHER_ACCESS_REQUIRED);
3478 free_recipients(valid_to);
3479 free_recipients(valid_cc);
3480 free_recipients(valid_bcc);
3485 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)
3486 && (CC->user.axlevel < 4) ) {
3487 cprintf("%d Higher access required for network mail.\n",
3488 ERROR + HIGHER_ACCESS_REQUIRED);
3489 free_recipients(valid_to);
3490 free_recipients(valid_cc);
3491 free_recipients(valid_bcc);
3495 if ((RESTRICT_INTERNET == 1)
3496 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3497 && ((CC->user.flags & US_INTERNET) == 0)
3498 && (!CC->internal_pgm)) {
3499 cprintf("%d You don't have access to Internet mail.\n",
3500 ERROR + HIGHER_ACCESS_REQUIRED);
3501 free_recipients(valid_to);
3502 free_recipients(valid_cc);
3503 free_recipients(valid_bcc);
3509 /* Is this a room which has anonymous-only or anonymous-option? */
3510 anonymous = MES_NORMAL;
3511 if (CC->room.QRflags & QR_ANONONLY) {
3512 anonymous = MES_ANONONLY;
3514 if (CC->room.QRflags & QR_ANONOPT) {
3515 if (anon_flag == 1) { /* only if the user requested it */
3516 anonymous = MES_ANONOPT;
3520 if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3524 /* Recommend to the client that the use of a message subject is
3525 * strongly recommended in this room, if either the SUBJECTREQ flag
3526 * is set, or if there is one or more Internet email recipients.
3528 if (CC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
3529 if (valid_to) if (valid_to->num_internet > 0) subject_required = 1;
3530 if (valid_cc) if (valid_cc->num_internet > 0) subject_required = 1;
3531 if (valid_bcc) if (valid_bcc->num_internet > 0) subject_required = 1;
3533 /* If we're only checking the validity of the request, return
3534 * success without creating the message.
3537 cprintf("%d %s|%d\n", CIT_OK,
3538 ((valid_to != NULL) ? valid_to->display_recp : ""),
3540 free_recipients(valid_to);
3541 free_recipients(valid_cc);
3542 free_recipients(valid_bcc);
3546 /* We don't need these anymore because we'll do it differently below */
3547 free_recipients(valid_to);
3548 free_recipients(valid_cc);
3549 free_recipients(valid_bcc);
3551 /* Read in the message from the client. */
3553 cprintf("%d send message\n", START_CHAT_MODE);
3555 cprintf("%d send message\n", SEND_LISTING);
3558 msg = CtdlMakeMessage(&CC->user, recp, cc,
3559 CC->room.QRname, anonymous, format_type,
3560 newusername, newuseremail, subject,
3561 ((strlen(supplied_euid) > 0) ? supplied_euid : NULL),
3564 /* Put together one big recipients struct containing to/cc/bcc all in
3565 * one. This is for the envelope.
3567 char *all_recps = malloc(SIZ * 3);
3568 strcpy(all_recps, recp);
3569 if (strlen(cc) > 0) {
3570 if (strlen(all_recps) > 0) {
3571 strcat(all_recps, ",");
3573 strcat(all_recps, cc);
3575 if (strlen(bcc) > 0) {
3576 if (strlen(all_recps) > 0) {
3577 strcat(all_recps, ",");
3579 strcat(all_recps, bcc);
3581 if (strlen(all_recps) > 0) {
3582 valid = validate_recipients(all_recps);
3590 msgnum = CtdlSubmitMsg(msg, valid, "");
3593 cprintf("%ld\n", msgnum);
3595 cprintf("Message accepted.\n");
3598 cprintf("Internal error.\n");
3600 if (msg->cm_fields['E'] != NULL) {
3601 cprintf("%s\n", msg->cm_fields['E']);
3608 CtdlFreeMessage(msg);
3610 if (valid != NULL) {
3611 free_recipients(valid);
3619 * API function to delete messages which match a set of criteria
3620 * (returns the actual number of messages deleted)
3622 int CtdlDeleteMessages(char *room_name, /* which room */
3623 long *dmsgnums, /* array of msg numbers to be deleted */
3624 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
3625 char *content_type /* or "" for any. regular expressions expected. */
3628 struct ctdlroom qrbuf;
3629 struct cdbdata *cdbfr;
3630 long *msglist = NULL;
3631 long *dellist = NULL;
3634 int num_deleted = 0;
3636 struct MetaData smi;
3639 int need_to_free_re = 0;
3641 if (content_type) if (strlen(content_type) > 0) {
3642 regcomp(&re, content_type, 0);
3643 need_to_free_re = 1;
3645 lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
3646 room_name, num_dmsgnums, content_type);
3648 /* get room record, obtaining a lock... */
3649 if (lgetroom(&qrbuf, room_name) != 0) {
3650 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3652 if (need_to_free_re) regfree(&re);
3653 return (0); /* room not found */
3655 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3657 if (cdbfr != NULL) {
3658 dellist = malloc(cdbfr->len);
3659 msglist = (long *) cdbfr->ptr;
3660 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3661 num_msgs = cdbfr->len / sizeof(long);
3665 for (i = 0; i < num_msgs; ++i) {
3668 /* Set/clear a bit for each criterion */
3670 /* 0 messages in the list or a null list means that we are
3671 * interested in deleting any messages which meet the other criteria.
3673 if ((num_dmsgnums == 0) || (dmsgnums == NULL)) {
3674 delete_this |= 0x01;
3677 for (j=0; j<num_dmsgnums; ++j) {
3678 if (msglist[i] == dmsgnums[j]) {
3679 delete_this |= 0x01;
3684 if (strlen(content_type) == 0) {
3685 delete_this |= 0x02;
3687 GetMetaData(&smi, msglist[i]);
3688 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3689 delete_this |= 0x02;
3693 /* Delete message only if all bits are set */
3694 if (delete_this == 0x03) {
3695 dellist[num_deleted++] = msglist[i];
3700 num_msgs = sort_msglist(msglist, num_msgs);
3701 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3702 msglist, (int)(num_msgs * sizeof(long)));
3704 qrbuf.QRhighest = msglist[num_msgs - 1];
3708 /* Go through the messages we pulled out of the index, and decrement
3709 * their reference counts by 1. If this is the only room the message
3710 * was in, the reference count will reach zero and the message will
3711 * automatically be deleted from the database. We do this in a
3712 * separate pass because there might be plug-in hooks getting called,
3713 * and we don't want that happening during an S_ROOMS critical
3716 if (num_deleted) for (i=0; i<num_deleted; ++i) {
3717 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3718 AdjRefCount(dellist[i], -1);
3721 /* Now free the memory we used, and go away. */
3722 if (msglist != NULL) free(msglist);
3723 if (dellist != NULL) free(dellist);
3724 lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3725 if (need_to_free_re) regfree(&re);
3726 return (num_deleted);
3732 * Check whether the current user has permission to delete messages from
3733 * the current room (returns 1 for yes, 0 for no)
3735 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3737 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3738 if (ra & UA_DELETEALLOWED) return(1);
3746 * Delete message from current room
3748 void cmd_dele(char *args)
3757 extract_token(msgset, args, 0, '|', sizeof msgset);
3758 num_msgs = num_tokens(msgset, ',');
3760 cprintf("%d Nothing to do.\n", CIT_OK);
3764 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3765 cprintf("%d Higher access required.\n",
3766 ERROR + HIGHER_ACCESS_REQUIRED);
3771 * Build our message set to be moved/copied
3773 msgs = malloc(num_msgs * sizeof(long));
3774 for (i=0; i<num_msgs; ++i) {
3775 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3776 msgs[i] = atol(msgtok);
3779 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3783 cprintf("%d %d message%s deleted.\n", CIT_OK,
3784 num_deleted, ((num_deleted != 1) ? "s" : ""));
3786 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
3792 * Back end API function for moves and deletes (multiple messages)
3794 int CtdlCopyMsgsToRoom(long *msgnums, int num_msgs, char *dest) {
3797 err = CtdlSaveMsgPointersInRoom(dest, msgnums, num_msgs, 1, NULL);
3798 if (err != 0) return(err);
3807 * move or copy a message to another room
3809 void cmd_move(char *args)
3816 char targ[ROOMNAMELEN];
3817 struct ctdlroom qtemp;
3824 extract_token(msgset, args, 0, '|', sizeof msgset);
3825 num_msgs = num_tokens(msgset, ',');
3827 cprintf("%d Nothing to do.\n", CIT_OK);
3831 extract_token(targ, args, 1, '|', sizeof targ);
3832 convert_room_name_macros(targ, sizeof targ);
3833 targ[ROOMNAMELEN - 1] = 0;
3834 is_copy = extract_int(args, 2);
3836 if (getroom(&qtemp, targ) != 0) {
3837 cprintf("%d '%s' does not exist.\n",
3838 ERROR + ROOM_NOT_FOUND, targ);
3842 getuser(&CC->user, CC->curr_user);
3843 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3845 /* Check for permission to perform this operation.
3846 * Remember: "CC->room" is source, "qtemp" is target.
3850 /* Aides can move/copy */
3851 if (CC->user.axlevel >= 6) permit = 1;
3853 /* Room aides can move/copy */
3854 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3856 /* Permit move/copy from personal rooms */
3857 if ((CC->room.QRflags & QR_MAILBOX)
3858 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3860 /* Permit only copy from public to personal room */
3862 && (!(CC->room.QRflags & QR_MAILBOX))
3863 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3865 /* Permit message removal from collaborative delete rooms */
3866 if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
3868 /* User must have access to target room */
3869 if (!(ra & UA_KNOWN)) permit = 0;
3872 cprintf("%d Higher access required.\n",
3873 ERROR + HIGHER_ACCESS_REQUIRED);
3878 * Build our message set to be moved/copied
3880 msgs = malloc(num_msgs * sizeof(long));
3881 for (i=0; i<num_msgs; ++i) {
3882 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3883 msgs[i] = atol(msgtok);
3889 err = CtdlCopyMsgsToRoom(msgs, num_msgs, targ);
3891 cprintf("%d Cannot store message(s) in %s: error %d\n",
3897 /* Now delete the message from the source room,
3898 * if this is a 'move' rather than a 'copy' operation.
3901 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3905 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3911 * GetMetaData() - Get the supplementary record for a message
3913 void GetMetaData(struct MetaData *smibuf, long msgnum)
3916 struct cdbdata *cdbsmi;
3919 memset(smibuf, 0, sizeof(struct MetaData));
3920 smibuf->meta_msgnum = msgnum;
3921 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3923 /* Use the negative of the message number for its supp record index */
3924 TheIndex = (0L - msgnum);
3926 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3927 if (cdbsmi == NULL) {
3928 return; /* record not found; go with defaults */
3930 memcpy(smibuf, cdbsmi->ptr,
3931 ((cdbsmi->len > sizeof(struct MetaData)) ?
3932 sizeof(struct MetaData) : cdbsmi->len));
3939 * PutMetaData() - (re)write supplementary record for a message
3941 void PutMetaData(struct MetaData *smibuf)
3945 /* Use the negative of the message number for the metadata db index */
3946 TheIndex = (0L - smibuf->meta_msgnum);
3948 cdb_store(CDB_MSGMAIN,
3949 &TheIndex, (int)sizeof(long),
3950 smibuf, (int)sizeof(struct MetaData));
3955 * AdjRefCount - submit an adjustment to the reference count for a message.
3956 * (These are just queued -- we actually process them later.)
3958 void AdjRefCount(long msgnum, int incr)
3960 struct arcq new_arcq;
3962 begin_critical_section(S_SUPPMSGMAIN);
3963 if (arcfp == NULL) {
3964 arcfp = fopen(file_arcq, "ab+");
3966 end_critical_section(S_SUPPMSGMAIN);
3968 /* msgnum < 0 means that we're trying to close the file */
3970 lprintf(CTDL_DEBUG, "Closing the AdjRefCount queue file\n");
3971 begin_critical_section(S_SUPPMSGMAIN);
3972 if (arcfp != NULL) {
3976 end_critical_section(S_SUPPMSGMAIN);
3981 * If we can't open the queue, perform the operation synchronously.
3983 if (arcfp == NULL) {
3984 TDAP_AdjRefCount(msgnum, incr);
3988 new_arcq.arcq_msgnum = msgnum;
3989 new_arcq.arcq_delta = incr;
3990 fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
3998 * TDAP_ProcessAdjRefCountQueue()
4000 * Process the queue of message count adjustments that was created by calls
4001 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
4002 * for each one. This should be an "off hours" operation.
4004 int TDAP_ProcessAdjRefCountQueue(void)
4006 char file_arcq_temp[PATH_MAX];
4009 struct arcq arcq_rec;
4010 int num_records_processed = 0;
4012 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s2", file_arcq);
4014 begin_critical_section(S_SUPPMSGMAIN);
4015 if (arcfp != NULL) {
4020 r = link(file_arcq, file_arcq_temp);
4022 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4023 end_critical_section(S_SUPPMSGMAIN);
4024 return(num_records_processed);
4028 end_critical_section(S_SUPPMSGMAIN);
4030 fp = fopen(file_arcq_temp, "rb");
4032 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4033 return(num_records_processed);
4036 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
4037 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
4038 ++num_records_processed;
4042 r = unlink(file_arcq_temp);
4044 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4047 return(num_records_processed);
4053 * TDAP_AdjRefCount - adjust the reference count for a message.
4054 * This one does it "for real" because it's called by
4055 * the autopurger function that processes the queue
4056 * created by AdjRefCount(). If a message's reference
4057 * count becomes zero, we also delete the message from
4058 * disk and de-index it.
4060 void TDAP_AdjRefCount(long msgnum, int incr)
4063 struct MetaData smi;
4066 /* This is a *tight* critical section; please keep it that way, as
4067 * it may get called while nested in other critical sections.
4068 * Complicating this any further will surely cause deadlock!
4070 begin_critical_section(S_SUPPMSGMAIN);
4071 GetMetaData(&smi, msgnum);
4072 smi.meta_refcount += incr;
4074 end_critical_section(S_SUPPMSGMAIN);
4075 lprintf(CTDL_DEBUG, "msg %ld ref count delta %d, is now %d\n",
4076 msgnum, incr, smi.meta_refcount);
4078 /* If the reference count is now zero, delete the message
4079 * (and its supplementary record as well).
4081 if (smi.meta_refcount == 0) {
4082 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
4084 /* Remove from fulltext index */
4085 if (config.c_enable_fulltext) {
4086 ft_index_message(msgnum, 0);
4089 /* Remove from message base */
4091 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4092 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
4094 /* Remove metadata record */
4095 delnum = (0L - msgnum);
4096 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4102 * Write a generic object to this room
4104 * Note: this could be much more efficient. Right now we use two temporary
4105 * files, and still pull the message into memory as with all others.
4107 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
4108 char *content_type, /* MIME type of this object */
4109 char *tempfilename, /* Where to fetch it from */
4110 struct ctdluser *is_mailbox, /* Mailbox room? */
4111 int is_binary, /* Is encoding necessary? */
4112 int is_unique, /* Del others of this type? */
4113 unsigned int flags /* Internal save flags */
4118 struct ctdlroom qrbuf;
4119 char roomname[ROOMNAMELEN];
4120 struct CtdlMessage *msg;
4122 char *raw_message = NULL;
4123 char *encoded_message = NULL;
4124 off_t raw_length = 0;
4126 if (is_mailbox != NULL) {
4127 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
4130 safestrncpy(roomname, req_room, sizeof(roomname));
4133 fp = fopen(tempfilename, "rb");
4135 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
4136 tempfilename, strerror(errno));
4139 fseek(fp, 0L, SEEK_END);
4140 raw_length = ftell(fp);
4142 lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
4144 raw_message = malloc((size_t)raw_length + 2);
4145 fread(raw_message, (size_t)raw_length, 1, fp);
4149 encoded_message = malloc((size_t)
4150 (((raw_length * 134) / 100) + 4096 ) );
4153 encoded_message = malloc((size_t)(raw_length + 4096));
4156 sprintf(encoded_message, "Content-type: %s\n", content_type);
4159 sprintf(&encoded_message[strlen(encoded_message)],
4160 "Content-transfer-encoding: base64\n\n"
4164 sprintf(&encoded_message[strlen(encoded_message)],
4165 "Content-transfer-encoding: 7bit\n\n"
4171 &encoded_message[strlen(encoded_message)],
4177 raw_message[raw_length] = 0;
4179 &encoded_message[strlen(encoded_message)],
4187 lprintf(CTDL_DEBUG, "Allocating\n");
4188 msg = malloc(sizeof(struct CtdlMessage));
4189 memset(msg, 0, sizeof(struct CtdlMessage));
4190 msg->cm_magic = CTDLMESSAGE_MAGIC;
4191 msg->cm_anon_type = MES_NORMAL;
4192 msg->cm_format_type = 4;
4193 msg->cm_fields['A'] = strdup(CC->user.fullname);
4194 msg->cm_fields['O'] = strdup(req_room);
4195 msg->cm_fields['N'] = strdup(config.c_nodename);
4196 msg->cm_fields['H'] = strdup(config.c_humannode);
4197 msg->cm_flags = flags;
4199 msg->cm_fields['M'] = encoded_message;
4201 /* Create the requested room if we have to. */
4202 if (getroom(&qrbuf, roomname) != 0) {
4203 create_room(roomname,
4204 ( (is_mailbox != NULL) ? 5 : 3 ),
4205 "", 0, 1, 0, VIEW_BBS);
4207 /* If the caller specified this object as unique, delete all
4208 * other objects of this type that are currently in the room.
4211 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
4212 CtdlDeleteMessages(roomname, NULL, 0, content_type)
4215 /* Now write the data */
4216 CtdlSubmitMsg(msg, NULL, roomname);
4217 CtdlFreeMessage(msg);
4225 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
4226 config_msgnum = msgnum;
4230 char *CtdlGetSysConfig(char *sysconfname) {
4231 char hold_rm[ROOMNAMELEN];
4234 struct CtdlMessage *msg;
4237 strcpy(hold_rm, CC->room.QRname);
4238 if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
4239 getroom(&CC->room, hold_rm);
4244 /* We want the last (and probably only) config in this room */
4245 begin_critical_section(S_CONFIG);
4246 config_msgnum = (-1L);
4247 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
4248 CtdlGetSysConfigBackend, NULL);
4249 msgnum = config_msgnum;
4250 end_critical_section(S_CONFIG);
4256 msg = CtdlFetchMessage(msgnum, 1);
4258 conf = strdup(msg->cm_fields['M']);
4259 CtdlFreeMessage(msg);
4266 getroom(&CC->room, hold_rm);
4268 if (conf != NULL) do {
4269 extract_token(buf, conf, 0, '\n', sizeof buf);
4270 strcpy(conf, &conf[strlen(buf)+1]);
4271 } while ( (strlen(conf)>0) && (strlen(buf)>0) );
4276 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
4277 char temp[PATH_MAX];
4280 CtdlMakeTempFileName(temp, sizeof temp);
4282 fp = fopen(temp, "w");
4283 if (fp == NULL) return;
4284 fprintf(fp, "%s", sysconfdata);
4287 /* this handy API function does all the work for us */
4288 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
4294 * Determine whether a given Internet address belongs to the current user
4296 int CtdlIsMe(char *addr, int addr_buf_len)
4298 struct recptypes *recp;
4301 recp = validate_recipients(addr);
4302 if (recp == NULL) return(0);
4304 if (recp->num_local == 0) {
4305 free_recipients(recp);
4309 for (i=0; i<recp->num_local; ++i) {
4310 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
4311 if (!strcasecmp(addr, CC->user.fullname)) {
4312 free_recipients(recp);
4317 free_recipients(recp);
4323 * Citadel protocol command to do the same
4325 void cmd_isme(char *argbuf) {
4328 if (CtdlAccessCheck(ac_logged_in)) return;
4329 extract_token(addr, argbuf, 0, '|', sizeof addr);
4331 if (CtdlIsMe(addr, sizeof addr)) {
4332 cprintf("%d %s\n", CIT_OK, addr);
4335 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);