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"
53 #include "euidindex.h"
54 #include "journaling.h"
55 #include "citadel_dirs.h"
59 struct addresses_to_be_filed *atbf = NULL;
61 /* This temp file holds the queue of operations for AdjRefCount() */
62 static FILE *arcfp = NULL;
65 * This really belongs in serv_network.c, but I don't know how to export
66 * symbols between modules.
68 struct FilterList *filterlist = NULL;
72 * These are the four-character field headers we use when outputting
73 * messages in Citadel format (as opposed to RFC822 format).
76 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
77 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
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,
111 * This function is self explanatory.
112 * (What can I say, I'm in a weird mood today...)
114 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
118 for (i = 0; i < strlen(name); ++i) {
119 if (name[i] == '@') {
120 while (isspace(name[i - 1]) && i > 0) {
121 strcpy(&name[i - 1], &name[i]);
124 while (isspace(name[i + 1])) {
125 strcpy(&name[i + 1], &name[i + 2]);
133 * Aliasing for network mail.
134 * (Error messages have been commented out, because this is a server.)
136 int alias(char *name)
137 { /* process alias and routing info for mail */
140 char aaa[SIZ], bbb[SIZ];
141 char *ignetcfg = NULL;
142 char *ignetmap = NULL;
148 char original_name[256];
149 safestrncpy(original_name, name, sizeof original_name);
152 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
153 stripallbut(name, '<', '>');
155 fp = fopen(file_mail_aliases, "r");
157 fp = fopen("/dev/null", "r");
164 while (fgets(aaa, sizeof aaa, fp) != NULL) {
165 while (isspace(name[0]))
166 strcpy(name, &name[1]);
167 aaa[strlen(aaa) - 1] = 0;
169 for (a = 0; a < strlen(aaa); ++a) {
171 strcpy(bbb, &aaa[a + 1]);
175 if (!strcasecmp(name, aaa))
180 /* Hit the Global Address Book */
181 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
185 if (strcasecmp(original_name, name)) {
186 lprintf(CTDL_INFO, "%s is being forwarded to %s\n", original_name, name);
189 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
190 for (a=0; a<strlen(name); ++a) {
191 if (name[a] == '@') {
192 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
194 lprintf(CTDL_INFO, "Changed to <%s>\n", name);
199 /* determine local or remote type, see citadel.h */
200 at = haschar(name, '@');
201 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
202 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
203 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
205 /* figure out the delivery mode */
206 extract_token(node, name, 1, '@', sizeof node);
208 /* If there are one or more dots in the nodename, we assume that it
209 * is an FQDN and will attempt SMTP delivery to the Internet.
211 if (haschar(node, '.') > 0) {
212 return(MES_INTERNET);
215 /* Otherwise we look in the IGnet maps for a valid Citadel node.
216 * Try directly-connected nodes first...
218 ignetcfg = CtdlGetSysConfig(IGNETCFG);
219 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
220 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
221 extract_token(testnode, buf, 0, '|', sizeof testnode);
222 if (!strcasecmp(node, testnode)) {
230 * Then try nodes that are two or more hops away.
232 ignetmap = CtdlGetSysConfig(IGNETMAP);
233 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
234 extract_token(buf, ignetmap, i, '\n', sizeof buf);
235 extract_token(testnode, buf, 0, '|', sizeof testnode);
236 if (!strcasecmp(node, testnode)) {
243 /* If we get to this point it's an invalid node name */
249 * Back end for the MSGS command: output message number only.
251 void simple_listing(long msgnum, void *userdata)
253 cprintf("%ld\n", msgnum);
259 * Back end for the MSGS command: output header summary.
261 void headers_listing(long msgnum, void *userdata)
263 struct CtdlMessage *msg;
265 msg = CtdlFetchMessage(msgnum, 0);
267 cprintf("%ld|0|||||\n", msgnum);
271 cprintf("%ld|%s|%s|%s|%s|%s|\n",
273 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
274 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
275 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
276 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
277 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
279 CtdlFreeMessage(msg);
284 /* Determine if a given message matches the fields in a message template.
285 * Return 0 for a successful match.
287 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
290 /* If there aren't any fields in the template, all messages will
293 if (template == NULL) return(0);
295 /* Null messages are bogus. */
296 if (msg == NULL) return(1);
298 for (i='A'; i<='Z'; ++i) {
299 if (template->cm_fields[i] != NULL) {
300 if (msg->cm_fields[i] == NULL) {
303 if (strcasecmp(msg->cm_fields[i],
304 template->cm_fields[i])) return 1;
308 /* All compares succeeded: we have a match! */
315 * Retrieve the "seen" message list for the current room.
317 void CtdlGetSeen(char *buf, int which_set) {
320 /* Learn about the user and room in question */
321 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
323 if (which_set == ctdlsetseen_seen)
324 safestrncpy(buf, vbuf.v_seen, SIZ);
325 if (which_set == ctdlsetseen_answered)
326 safestrncpy(buf, vbuf.v_answered, SIZ);
332 * Manipulate the "seen msgs" string (or other message set strings)
334 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
335 int target_setting, int which_set,
336 struct ctdluser *which_user, struct ctdlroom *which_room) {
337 struct cdbdata *cdbfr;
349 char *is_set; /* actually an array of booleans */
352 char setstr[SIZ], lostr[SIZ], histr[SIZ];
355 /* Don't bother doing *anything* if we were passed a list of zero messages */
356 if (num_target_msgnums < 1) {
360 lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
361 num_target_msgnums, target_msgnums[0],
362 target_setting, which_set);
364 /* Learn about the user and room in question */
365 CtdlGetRelationship(&vbuf,
366 ((which_user != NULL) ? which_user : &CC->user),
367 ((which_room != NULL) ? which_room : &CC->room)
370 /* Load the message list */
371 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
373 msglist = (long *) cdbfr->ptr;
374 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
375 num_msgs = cdbfr->len / sizeof(long);
378 return; /* No messages at all? No further action. */
381 is_set = malloc(num_msgs * sizeof(char));
382 memset(is_set, 0, (num_msgs * sizeof(char)) );
384 /* Decide which message set we're manipulating */
386 case ctdlsetseen_seen:
387 safestrncpy(vset, vbuf.v_seen, sizeof vset);
389 case ctdlsetseen_answered:
390 safestrncpy(vset, vbuf.v_answered, sizeof vset);
394 /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
396 /* Translate the existing sequence set into an array of booleans */
397 num_sets = num_tokens(vset, ',');
398 for (s=0; s<num_sets; ++s) {
399 extract_token(setstr, vset, s, ',', sizeof setstr);
401 extract_token(lostr, setstr, 0, ':', sizeof lostr);
402 if (num_tokens(setstr, ':') >= 2) {
403 extract_token(histr, setstr, 1, ':', sizeof histr);
404 if (!strcmp(histr, "*")) {
405 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
409 strcpy(histr, lostr);
414 for (i = 0; i < num_msgs; ++i) {
415 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
421 /* Now translate the array of booleans back into a sequence set */
426 for (i=0; i<num_msgs; ++i) {
428 is_seen = is_set[i]; /* Default to existing setting */
430 for (k=0; k<num_target_msgnums; ++k) {
431 if (msglist[i] == target_msgnums[k]) {
432 is_seen = target_setting;
437 if (lo < 0L) lo = msglist[i];
441 if ( ((is_seen == 0) && (was_seen == 1))
442 || ((is_seen == 1) && (i == num_msgs-1)) ) {
444 /* begin trim-o-matic code */
447 while ( (strlen(vset) + 20) > sizeof vset) {
448 remove_token(vset, 0, ',');
450 if (j--) break; /* loop no more than 9 times */
452 if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
456 snprintf(lostr, sizeof lostr,
457 "1:%ld,%s", t, vset);
458 safestrncpy(vset, lostr, sizeof vset);
460 /* end trim-o-matic code */
468 snprintf(&vset[tmp], (sizeof vset) - tmp,
472 snprintf(&vset[tmp], (sizeof vset) - tmp,
481 /* Decide which message set we're manipulating */
483 case ctdlsetseen_seen:
484 safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
486 case ctdlsetseen_answered:
487 safestrncpy(vbuf.v_answered, vset,
488 sizeof vbuf.v_answered);
493 /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
495 CtdlSetRelationship(&vbuf,
496 ((which_user != NULL) ? which_user : &CC->user),
497 ((which_room != NULL) ? which_room : &CC->room)
503 * API function to perform an operation for each qualifying message in the
504 * current room. (Returns the number of messages processed.)
506 int CtdlForEachMessage(int mode, long ref, char *search_string,
508 struct CtdlMessage *compare,
509 void (*CallBack) (long, void *),
515 struct cdbdata *cdbfr;
516 long *msglist = NULL;
518 int num_processed = 0;
521 struct CtdlMessage *msg = NULL;
524 int printed_lastold = 0;
525 int num_search_msgs = 0;
526 long *search_msgs = NULL;
528 int need_to_free_re = 0;
531 if (content_type) if (strlen(content_type) > 0) {
532 regcomp(&re, content_type, 0);
536 /* Learn about the user and room in question */
537 getuser(&CC->user, CC->curr_user);
538 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
540 /* Load the message list */
541 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
543 msglist = (long *) cdbfr->ptr;
544 cdbfr->ptr = NULL; /* CtdlForEachMessage() now owns this memory */
545 num_msgs = cdbfr->len / sizeof(long);
548 if (need_to_free_re) regfree(&re);
549 return 0; /* No messages at all? No further action. */
554 * Now begin the traversal.
556 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
558 /* If the caller is looking for a specific MIME type, filter
559 * out all messages which are not of the type requested.
561 if (content_type != NULL) if (strlen(content_type) > 0) {
563 /* This call to GetMetaData() sits inside this loop
564 * so that we only do the extra database read per msg
565 * if we need to. Doing the extra read all the time
566 * really kills the server. If we ever need to use
567 * metadata for another search criterion, we need to
568 * move the read somewhere else -- but still be smart
569 * enough to only do the read if the caller has
570 * specified something that will need it.
572 GetMetaData(&smi, msglist[a]);
574 /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
575 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
581 num_msgs = sort_msglist(msglist, num_msgs);
583 /* If a template was supplied, filter out the messages which
584 * don't match. (This could induce some delays!)
587 if (compare != NULL) {
588 for (a = 0; a < num_msgs; ++a) {
589 msg = CtdlFetchMessage(msglist[a], 1);
591 if (CtdlMsgCmp(msg, compare)) {
594 CtdlFreeMessage(msg);
600 /* If a search string was specified, get a message list from
601 * the full text index and remove messages which aren't on both
605 * Since the lists are sorted and strictly ascending, and the
606 * output list is guaranteed to be shorter than or equal to the
607 * input list, we overwrite the bottom of the input list. This
608 * eliminates the need to memmove big chunks of the list over and
611 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
613 /* Call search module via hook mechanism.
614 * NULL means use any search function available.
615 * otherwise replace with a char * to name of search routine
617 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
619 if (num_search_msgs > 0) {
623 orig_num_msgs = num_msgs;
625 for (i=0; i<orig_num_msgs; ++i) {
626 for (j=0; j<num_search_msgs; ++j) {
627 if (msglist[i] == search_msgs[j]) {
628 msglist[num_msgs++] = msglist[i];
634 num_msgs = 0; /* No messages qualify */
636 if (search_msgs != NULL) free(search_msgs);
638 /* Now that we've purged messages which don't contain the search
639 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
646 * Now iterate through the message list, according to the
647 * criteria supplied by the caller.
650 for (a = 0; a < num_msgs; ++a) {
651 thismsg = msglist[a];
652 if (mode == MSGS_ALL) {
656 is_seen = is_msg_in_sequence_set(
657 vbuf.v_seen, thismsg);
658 if (is_seen) lastold = thismsg;
664 || ((mode == MSGS_OLD) && (is_seen))
665 || ((mode == MSGS_NEW) && (!is_seen))
666 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
667 || ((mode == MSGS_FIRST) && (a < ref))
668 || ((mode == MSGS_GT) && (thismsg > ref))
669 || ((mode == MSGS_EQ) && (thismsg == ref))
672 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
674 CallBack(lastold, userdata);
678 if (CallBack) CallBack(thismsg, userdata);
682 free(msglist); /* Clean up */
683 if (need_to_free_re) regfree(&re);
684 return num_processed;
690 * cmd_msgs() - get list of message #'s in this room
691 * implements the MSGS server command using CtdlForEachMessage()
693 void cmd_msgs(char *cmdbuf)
702 int with_template = 0;
703 struct CtdlMessage *template = NULL;
704 int with_headers = 0;
705 char search_string[1024];
707 extract_token(which, cmdbuf, 0, '|', sizeof which);
708 cm_ref = extract_int(cmdbuf, 1);
709 extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
710 with_template = extract_int(cmdbuf, 2);
711 with_headers = extract_int(cmdbuf, 3);
714 if (!strncasecmp(which, "OLD", 3))
716 else if (!strncasecmp(which, "NEW", 3))
718 else if (!strncasecmp(which, "FIRST", 5))
720 else if (!strncasecmp(which, "LAST", 4))
722 else if (!strncasecmp(which, "GT", 2))
724 else if (!strncasecmp(which, "SEARCH", 6))
729 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
730 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
734 if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
735 cprintf("%d Full text index is not enabled on this server.\n",
736 ERROR + CMD_NOT_SUPPORTED);
742 cprintf("%d Send template then receive message list\n",
744 template = (struct CtdlMessage *)
745 malloc(sizeof(struct CtdlMessage));
746 memset(template, 0, sizeof(struct CtdlMessage));
747 template->cm_magic = CTDLMESSAGE_MAGIC;
748 template->cm_anon_type = MES_NORMAL;
750 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
751 extract_token(tfield, buf, 0, '|', sizeof tfield);
752 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
753 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
754 if (!strcasecmp(tfield, msgkeys[i])) {
755 template->cm_fields[i] =
763 cprintf("%d \n", LISTING_FOLLOWS);
766 CtdlForEachMessage(mode,
767 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
768 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
771 (with_headers ? headers_listing : simple_listing),
774 if (template != NULL) CtdlFreeMessage(template);
782 * help_subst() - support routine for help file viewer
784 void help_subst(char *strbuf, char *source, char *dest)
789 while (p = pattern2(strbuf, source), (p >= 0)) {
790 strcpy(workbuf, &strbuf[p + strlen(source)]);
791 strcpy(&strbuf[p], dest);
792 strcat(strbuf, workbuf);
797 void do_help_subst(char *buffer)
801 help_subst(buffer, "^nodename", config.c_nodename);
802 help_subst(buffer, "^humannode", config.c_humannode);
803 help_subst(buffer, "^fqdn", config.c_fqdn);
804 help_subst(buffer, "^username", CC->user.fullname);
805 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
806 help_subst(buffer, "^usernum", buf2);
807 help_subst(buffer, "^sysadm", config.c_sysadm);
808 help_subst(buffer, "^variantname", CITADEL);
809 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
810 help_subst(buffer, "^maxsessions", buf2);
811 help_subst(buffer, "^bbsdir", ctdl_bbsbase_dir);
817 * memfmout() - Citadel text formatter and paginator.
818 * Although the original purpose of this routine was to format
819 * text to the reader's screen width, all we're really using it
820 * for here is to format text out to 80 columns before sending it
821 * to the client. The client software may reformat it again.
824 char *mptr, /* where are we going to get our text from? */
825 char subst, /* nonzero if we should do substitutions */
826 char *nl) /* string to terminate lines with */
834 static int width = 80;
839 c = 1; /* c is the current pos */
843 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
845 buffer[strlen(buffer) + 1] = 0;
846 buffer[strlen(buffer)] = ch;
849 if (buffer[0] == '^')
850 do_help_subst(buffer);
852 buffer[strlen(buffer) + 1] = 0;
854 strcpy(buffer, &buffer[1]);
862 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
865 if (((old == 13) || (old == 10)) && (isspace(real))) {
870 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
871 cprintf("%s%s", nl, aaa);
880 if ((strlen(aaa) + c) > (width - 5)) {
889 if ((ch == 13) || (ch == 10)) {
890 cprintf("%s%s", aaa, nl);
897 cprintf("%s%s", aaa, nl);
903 * Callback function for mime parser that simply lists the part
905 void list_this_part(char *name, char *filename, char *partnum, char *disp,
906 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
911 ma = (struct ma_info *)cbuserdata;
912 if (ma->is_ma == 0) {
913 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
914 name, filename, partnum, disp, cbtype, (long)length);
919 * Callback function for multipart prefix
921 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
922 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
927 ma = (struct ma_info *)cbuserdata;
928 if (!strcasecmp(cbtype, "multipart/alternative")) {
932 if (ma->is_ma == 0) {
933 cprintf("pref=%s|%s\n", partnum, cbtype);
938 * Callback function for multipart sufffix
940 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
941 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
946 ma = (struct ma_info *)cbuserdata;
947 if (ma->is_ma == 0) {
948 cprintf("suff=%s|%s\n", partnum, cbtype);
950 if (!strcasecmp(cbtype, "multipart/alternative")) {
957 * Callback function for mime parser that opens a section for downloading
959 void mime_download(char *name, char *filename, char *partnum, char *disp,
960 void *content, char *cbtype, char *cbcharset, size_t length,
961 char *encoding, void *cbuserdata)
964 /* Silently go away if there's already a download open... */
965 if (CC->download_fp != NULL)
968 /* ...or if this is not the desired section */
969 if (strcasecmp(CC->download_desired_section, partnum))
972 CC->download_fp = tmpfile();
973 if (CC->download_fp == NULL)
976 fwrite(content, length, 1, CC->download_fp);
977 fflush(CC->download_fp);
978 rewind(CC->download_fp);
980 OpenCmdResult(filename, cbtype);
986 * Callback function for mime parser that outputs a section all at once
988 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
989 void *content, char *cbtype, char *cbcharset, size_t length,
990 char *encoding, void *cbuserdata)
992 int *found_it = (int *)cbuserdata;
994 /* ...or if this is not the desired section */
995 if (strcasecmp(CC->download_desired_section, partnum))
1000 cprintf("%d %d\n", BINARY_FOLLOWS, (int)length);
1001 client_write(content, length);
1007 * Load a message from disk into memory.
1008 * This is used by CtdlOutputMsg() and other fetch functions.
1010 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1011 * using the CtdlMessageFree() function.
1013 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1015 struct cdbdata *dmsgtext;
1016 struct CtdlMessage *ret = NULL;
1020 cit_uint8_t field_header;
1022 lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1024 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1025 if (dmsgtext == NULL) {
1028 mptr = dmsgtext->ptr;
1029 upper_bound = mptr + dmsgtext->len;
1031 /* Parse the three bytes that begin EVERY message on disk.
1032 * The first is always 0xFF, the on-disk magic number.
1033 * The second is the anonymous/public type byte.
1034 * The third is the format type byte (vari, fixed, or MIME).
1039 "Message %ld appears to be corrupted.\n",
1044 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1045 memset(ret, 0, sizeof(struct CtdlMessage));
1047 ret->cm_magic = CTDLMESSAGE_MAGIC;
1048 ret->cm_anon_type = *mptr++; /* Anon type byte */
1049 ret->cm_format_type = *mptr++; /* Format type byte */
1052 * The rest is zero or more arbitrary fields. Load them in.
1053 * We're done when we encounter either a zero-length field or
1054 * have just processed the 'M' (message text) field.
1057 if (mptr >= upper_bound) {
1060 field_header = *mptr++;
1061 ret->cm_fields[field_header] = strdup(mptr);
1063 while (*mptr++ != 0); /* advance to next field */
1065 } while ((mptr < upper_bound) && (field_header != 'M'));
1069 /* Always make sure there's something in the msg text field. If
1070 * it's NULL, the message text is most likely stored separately,
1071 * so go ahead and fetch that. Failing that, just set a dummy
1072 * body so other code doesn't barf.
1074 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1075 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1076 if (dmsgtext != NULL) {
1077 ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1081 if (ret->cm_fields['M'] == NULL) {
1082 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1085 /* Perform "before read" hooks (aborting if any return nonzero) */
1086 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1087 CtdlFreeMessage(ret);
1096 * Returns 1 if the supplied pointer points to a valid Citadel message.
1097 * If the pointer is NULL or the magic number check fails, returns 0.
1099 int is_valid_message(struct CtdlMessage *msg) {
1102 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1103 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1111 * 'Destructor' for struct CtdlMessage
1113 void CtdlFreeMessage(struct CtdlMessage *msg)
1117 if (is_valid_message(msg) == 0)
1119 if (msg != NULL) free (msg);
1123 for (i = 0; i < 256; ++i)
1124 if (msg->cm_fields[i] != NULL) {
1125 free(msg->cm_fields[i]);
1128 msg->cm_magic = 0; /* just in case */
1134 * Pre callback function for multipart/alternative
1136 * NOTE: this differs from the standard behavior for a reason. Normally when
1137 * displaying multipart/alternative you want to show the _last_ usable
1138 * format in the message. Here we show the _first_ one, because it's
1139 * usually text/plain. Since this set of functions is designed for text
1140 * output to non-MIME-aware clients, this is the desired behavior.
1143 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1144 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1149 ma = (struct ma_info *)cbuserdata;
1150 lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1151 if (!strcasecmp(cbtype, "multipart/alternative")) {
1155 if (!strcasecmp(cbtype, "message/rfc822")) {
1161 * Post callback function for multipart/alternative
1163 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1164 void *content, char *cbtype, char *cbcharset, size_t length,
1165 char *encoding, void *cbuserdata)
1169 ma = (struct ma_info *)cbuserdata;
1170 lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1171 if (!strcasecmp(cbtype, "multipart/alternative")) {
1175 if (!strcasecmp(cbtype, "message/rfc822")) {
1181 * Inline callback function for mime parser that wants to display text
1183 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1184 void *content, char *cbtype, char *cbcharset, size_t length,
1185 char *encoding, void *cbuserdata)
1192 ma = (struct ma_info *)cbuserdata;
1195 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1196 partnum, filename, cbtype, (long)length);
1199 * If we're in the middle of a multipart/alternative scope and
1200 * we've already printed another section, skip this one.
1202 if ( (ma->is_ma) && (ma->did_print) ) {
1203 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1209 if ( (!strcasecmp(cbtype, "text/plain"))
1210 || (strlen(cbtype)==0) ) {
1213 client_write(wptr, length);
1214 if (wptr[length-1] != '\n') {
1221 if (!strcasecmp(cbtype, "text/html")) {
1222 ptr = html_to_ascii(content, length, 80, 0);
1224 client_write(ptr, wlen);
1225 if (ptr[wlen-1] != '\n') {
1232 if (ma->use_fo_hooks) {
1233 if (PerformFixedOutputHooks(cbtype, content, length)) {
1234 /* above function returns nonzero if it handled the part */
1239 if (strncasecmp(cbtype, "multipart/", 10)) {
1240 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1241 partnum, filename, cbtype, (long)length);
1247 * The client is elegant and sophisticated and wants to be choosy about
1248 * MIME content types, so figure out which multipart/alternative part
1249 * we're going to send.
1251 * We use a system of weights. When we find a part that matches one of the
1252 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1253 * and then set ma->chosen_pref to that MIME type's position in our preference
1254 * list. If we then hit another match, we only replace the first match if
1255 * the preference value is lower.
1257 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1258 void *content, char *cbtype, char *cbcharset, size_t length,
1259 char *encoding, void *cbuserdata)
1265 ma = (struct ma_info *)cbuserdata;
1267 if (ma->is_ma > 0) {
1268 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1269 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1270 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1271 if (i < ma->chosen_pref) {
1272 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1273 ma->chosen_pref = i;
1281 * Now that we've chosen our preferred part, output it.
1283 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1284 void *content, char *cbtype, char *cbcharset, size_t length,
1285 char *encoding, void *cbuserdata)
1289 int add_newline = 0;
1293 ma = (struct ma_info *)cbuserdata;
1295 /* This is not the MIME part you're looking for... */
1296 if (strcasecmp(partnum, ma->chosen_part)) return;
1298 /* If the content-type of this part is in our preferred formats
1299 * list, we can simply output it verbatim.
1301 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1302 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1303 if (!strcasecmp(buf, cbtype)) {
1304 /* Yeah! Go! W00t!! */
1306 text_content = (char *)content;
1307 if (text_content[length-1] != '\n') {
1310 cprintf("Content-type: %s", cbtype);
1311 if (strlen(cbcharset) > 0) {
1312 cprintf("; charset=%s", cbcharset);
1314 cprintf("\nContent-length: %d\n",
1315 (int)(length + add_newline) );
1316 if (strlen(encoding) > 0) {
1317 cprintf("Content-transfer-encoding: %s\n", encoding);
1320 cprintf("Content-transfer-encoding: 7bit\n");
1322 cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1324 client_write(content, length);
1325 if (add_newline) cprintf("\n");
1330 /* No translations required or possible: output as text/plain */
1331 cprintf("Content-type: text/plain\n\n");
1332 fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1333 length, encoding, cbuserdata);
1338 char desired_section[64];
1345 * Callback function for
1347 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1348 void *content, char *cbtype, char *cbcharset, size_t length,
1349 char *encoding, void *cbuserdata)
1351 struct encapmsg *encap;
1353 encap = (struct encapmsg *)cbuserdata;
1355 /* Only proceed if this is the desired section... */
1356 if (!strcasecmp(encap->desired_section, partnum)) {
1357 encap->msglen = length;
1358 encap->msg = malloc(length + 2);
1359 memcpy(encap->msg, content, length);
1369 * Get a message off disk. (returns om_* values found in msgbase.h)
1372 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1373 int mode, /* how would you like that message? */
1374 int headers_only, /* eschew the message body? */
1375 int do_proto, /* do Citadel protocol responses? */
1376 int crlf, /* Use CRLF newlines instead of LF? */
1377 char *section /* NULL or a message/rfc822 section */
1379 struct CtdlMessage *TheMessage = NULL;
1380 int retcode = om_no_such_msg;
1381 struct encapmsg encap;
1383 lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n",
1385 (section ? section : "<>")
1388 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1389 if (do_proto) cprintf("%d Not logged in.\n",
1390 ERROR + NOT_LOGGED_IN);
1391 return(om_not_logged_in);
1394 /* FIXME: check message id against msglist for this room */
1397 * Fetch the message from disk. If we're in any sort of headers
1398 * only mode, request that we don't even bother loading the body
1401 if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1402 TheMessage = CtdlFetchMessage(msg_num, 0);
1405 TheMessage = CtdlFetchMessage(msg_num, 1);
1408 if (TheMessage == NULL) {
1409 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1410 ERROR + MESSAGE_NOT_FOUND, msg_num);
1411 return(om_no_such_msg);
1414 /* Here is the weird form of this command, to process only an
1415 * encapsulated message/rfc822 section.
1417 if (section) if (strlen(section)>0) if (strcmp(section, "0")) {
1418 memset(&encap, 0, sizeof encap);
1419 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1420 mime_parser(TheMessage->cm_fields['M'],
1422 *extract_encapsulated_message,
1423 NULL, NULL, (void *)&encap, 0
1425 CtdlFreeMessage(TheMessage);
1429 encap.msg[encap.msglen] = 0;
1430 TheMessage = convert_internet_message(encap.msg);
1431 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1433 /* Now we let it fall through to the bottom of this
1434 * function, because TheMessage now contains the
1435 * encapsulated message instead of the top-level
1436 * message. Isn't that neat?
1441 if (do_proto) cprintf("%d msg %ld has no part %s\n",
1442 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1443 retcode = om_no_such_msg;
1448 /* Ok, output the message now */
1449 retcode = CtdlOutputPreLoadedMsg(
1451 headers_only, do_proto, crlf);
1452 CtdlFreeMessage(TheMessage);
1459 * Get a message off disk. (returns om_* values found in msgbase.h)
1462 int CtdlOutputPreLoadedMsg(
1463 struct CtdlMessage *TheMessage,
1464 int mode, /* how would you like that message? */
1465 int headers_only, /* eschew the message body? */
1466 int do_proto, /* do Citadel protocol responses? */
1467 int crlf /* Use CRLF newlines instead of LF? */
1473 char display_name[256];
1475 char *nl; /* newline string */
1477 int subject_found = 0;
1480 /* Buffers needed for RFC822 translation. These are all filled
1481 * using functions that are bounds-checked, and therefore we can
1482 * make them substantially smaller than SIZ.
1490 char datestamp[100];
1492 lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1493 ((TheMessage == NULL) ? "NULL" : "not null"),
1494 mode, headers_only, do_proto, crlf);
1496 strcpy(mid, "unknown");
1497 nl = (crlf ? "\r\n" : "\n");
1499 if (!is_valid_message(TheMessage)) {
1501 "ERROR: invalid preloaded message for output\n");
1502 return(om_no_such_msg);
1505 /* Are we downloading a MIME component? */
1506 if (mode == MT_DOWNLOAD) {
1507 if (TheMessage->cm_format_type != FMT_RFC822) {
1509 cprintf("%d This is not a MIME message.\n",
1510 ERROR + ILLEGAL_VALUE);
1511 } else if (CC->download_fp != NULL) {
1512 if (do_proto) cprintf(
1513 "%d You already have a download open.\n",
1514 ERROR + RESOURCE_BUSY);
1516 /* Parse the message text component */
1517 mptr = TheMessage->cm_fields['M'];
1518 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1519 /* If there's no file open by this time, the requested
1520 * section wasn't found, so print an error
1522 if (CC->download_fp == NULL) {
1523 if (do_proto) cprintf(
1524 "%d Section %s not found.\n",
1525 ERROR + FILE_NOT_FOUND,
1526 CC->download_desired_section);
1529 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1532 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
1533 * in a single server operation instead of opening a download file.
1535 if (mode == MT_SPEW_SECTION) {
1536 if (TheMessage->cm_format_type != FMT_RFC822) {
1538 cprintf("%d This is not a MIME message.\n",
1539 ERROR + ILLEGAL_VALUE);
1541 /* Parse the message text component */
1544 mptr = TheMessage->cm_fields['M'];
1545 mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
1546 /* If section wasn't found, print an error
1549 if (do_proto) cprintf(
1550 "%d Section %s not found.\n",
1551 ERROR + FILE_NOT_FOUND,
1552 CC->download_desired_section);
1555 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1558 /* now for the user-mode message reading loops */
1559 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1561 /* Does the caller want to skip the headers? */
1562 if (headers_only == HEADERS_NONE) goto START_TEXT;
1564 /* Tell the client which format type we're using. */
1565 if ( (mode == MT_CITADEL) && (do_proto) ) {
1566 cprintf("type=%d\n", TheMessage->cm_format_type);
1569 /* nhdr=yes means that we're only displaying headers, no body */
1570 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1571 && (mode == MT_CITADEL)
1574 cprintf("nhdr=yes\n");
1577 /* begin header processing loop for Citadel message format */
1579 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1581 safestrncpy(display_name, "<unknown>", sizeof display_name);
1582 if (TheMessage->cm_fields['A']) {
1583 strcpy(buf, TheMessage->cm_fields['A']);
1584 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1585 safestrncpy(display_name, "****", sizeof display_name);
1587 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1588 safestrncpy(display_name, "anonymous", sizeof display_name);
1591 safestrncpy(display_name, buf, sizeof display_name);
1593 if ((is_room_aide())
1594 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1595 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1596 size_t tmp = strlen(display_name);
1597 snprintf(&display_name[tmp],
1598 sizeof display_name - tmp,
1603 /* Don't show Internet address for users on the
1604 * local Citadel network.
1607 if (TheMessage->cm_fields['N'] != NULL)
1608 if (strlen(TheMessage->cm_fields['N']) > 0)
1609 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1613 /* Now spew the header fields in the order we like them. */
1614 safestrncpy(allkeys, FORDER, sizeof allkeys);
1615 for (i=0; i<strlen(allkeys); ++i) {
1616 k = (int) allkeys[i];
1618 if ( (TheMessage->cm_fields[k] != NULL)
1619 && (msgkeys[k] != NULL) ) {
1621 if (do_proto) cprintf("%s=%s\n",
1625 else if ((k == 'F') && (suppress_f)) {
1628 /* Masquerade display name if needed */
1630 if (do_proto) cprintf("%s=%s\n",
1632 TheMessage->cm_fields[k]
1641 /* begin header processing loop for RFC822 transfer format */
1646 strcpy(snode, NODENAME);
1647 strcpy(lnode, HUMANNODE);
1648 if (mode == MT_RFC822) {
1649 for (i = 0; i < 256; ++i) {
1650 if (TheMessage->cm_fields[i]) {
1651 mptr = TheMessage->cm_fields[i];
1654 safestrncpy(luser, mptr, sizeof luser);
1655 safestrncpy(suser, mptr, sizeof suser);
1657 else if (i == 'Y') {
1658 cprintf("CC: %s%s", mptr, nl);
1660 else if (i == 'P') {
1661 cprintf("Return-Path: %s%s", mptr, nl);
1663 else if (i == 'V') {
1664 cprintf("Envelope-To: %s%s", mptr, nl);
1666 else if (i == 'U') {
1667 cprintf("Subject: %s%s", mptr, nl);
1671 safestrncpy(mid, mptr, sizeof mid);
1673 safestrncpy(lnode, mptr, sizeof lnode);
1675 safestrncpy(fuser, mptr, sizeof fuser);
1676 /* else if (i == 'O')
1677 cprintf("X-Citadel-Room: %s%s",
1680 safestrncpy(snode, mptr, sizeof snode);
1682 cprintf("To: %s%s", mptr, nl);
1683 else if (i == 'T') {
1684 datestring(datestamp, sizeof datestamp,
1685 atol(mptr), DATESTRING_RFC822);
1686 cprintf("Date: %s%s", datestamp, nl);
1690 if (subject_found == 0) {
1691 cprintf("Subject: (no subject)%s", nl);
1695 for (i=0; i<strlen(suser); ++i) {
1696 suser[i] = tolower(suser[i]);
1697 if (!isalnum(suser[i])) suser[i]='_';
1700 if (mode == MT_RFC822) {
1701 if (!strcasecmp(snode, NODENAME)) {
1702 safestrncpy(snode, FQDN, sizeof snode);
1705 /* Construct a fun message id */
1706 cprintf("Message-ID: <%s", mid);
1707 if (strchr(mid, '@')==NULL) {
1708 cprintf("@%s", snode);
1712 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1713 cprintf("From: \"----\" <x@x.org>%s", nl);
1715 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1716 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1718 else if (strlen(fuser) > 0) {
1719 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1722 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1725 cprintf("Organization: %s%s", lnode, nl);
1727 /* Blank line signifying RFC822 end-of-headers */
1728 if (TheMessage->cm_format_type != FMT_RFC822) {
1733 /* end header processing loop ... at this point, we're in the text */
1735 if (headers_only == HEADERS_FAST) goto DONE;
1736 mptr = TheMessage->cm_fields['M'];
1738 /* Tell the client about the MIME parts in this message */
1739 if (TheMessage->cm_format_type == FMT_RFC822) {
1740 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1741 memset(&ma, 0, sizeof(struct ma_info));
1742 mime_parser(mptr, NULL,
1743 (do_proto ? *list_this_part : NULL),
1744 (do_proto ? *list_this_pref : NULL),
1745 (do_proto ? *list_this_suff : NULL),
1748 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1749 char *start_of_text = NULL;
1750 start_of_text = strstr(mptr, "\n\r\n");
1751 if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1752 if (start_of_text == NULL) start_of_text = mptr;
1754 start_of_text = strstr(start_of_text, "\n");
1759 int nllen = strlen(nl);
1760 while (ch=*mptr, ch!=0) {
1766 ((headers_only == HEADERS_NONE) && (mptr >= start_of_text))
1767 || ((headers_only == HEADERS_ONLY) && (mptr < start_of_text))
1768 || ((headers_only != HEADERS_NONE) && (headers_only != HEADERS_ONLY))
1771 sprintf(&outbuf[outlen], "%s", nl);
1775 outbuf[outlen++] = ch;
1780 if (outlen > 1000) {
1781 client_write(outbuf, outlen);
1786 client_write(outbuf, outlen);
1794 if (headers_only == HEADERS_ONLY) {
1798 /* signify start of msg text */
1799 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1800 if (do_proto) cprintf("text\n");
1803 /* If the format type on disk is 1 (fixed-format), then we want
1804 * everything to be output completely literally ... regardless of
1805 * what message transfer format is in use.
1807 if (TheMessage->cm_format_type == FMT_FIXED) {
1808 if (mode == MT_MIME) {
1809 cprintf("Content-type: text/plain\n\n");
1812 while (ch = *mptr++, ch > 0) {
1815 if ((ch == 10) || (strlen(buf) > 250)) {
1816 cprintf("%s%s", buf, nl);
1819 buf[strlen(buf) + 1] = 0;
1820 buf[strlen(buf)] = ch;
1823 if (strlen(buf) > 0)
1824 cprintf("%s%s", buf, nl);
1827 /* If the message on disk is format 0 (Citadel vari-format), we
1828 * output using the formatter at 80 columns. This is the final output
1829 * form if the transfer format is RFC822, but if the transfer format
1830 * is Citadel proprietary, it'll still work, because the indentation
1831 * for new paragraphs is correct and the client will reformat the
1832 * message to the reader's screen width.
1834 if (TheMessage->cm_format_type == FMT_CITADEL) {
1835 if (mode == MT_MIME) {
1836 cprintf("Content-type: text/x-citadel-variformat\n\n");
1838 memfmout(mptr, 0, nl);
1841 /* If the message on disk is format 4 (MIME), we've gotta hand it
1842 * off to the MIME parser. The client has already been told that
1843 * this message is format 1 (fixed format), so the callback function
1844 * we use will display those parts as-is.
1846 if (TheMessage->cm_format_type == FMT_RFC822) {
1847 memset(&ma, 0, sizeof(struct ma_info));
1849 if (mode == MT_MIME) {
1850 ma.use_fo_hooks = 0;
1851 strcpy(ma.chosen_part, "1");
1852 ma.chosen_pref = 9999;
1853 mime_parser(mptr, NULL,
1854 *choose_preferred, *fixed_output_pre,
1855 *fixed_output_post, (void *)&ma, 0);
1856 mime_parser(mptr, NULL,
1857 *output_preferred, NULL, NULL, (void *)&ma, 0);
1860 ma.use_fo_hooks = 1;
1861 mime_parser(mptr, NULL,
1862 *fixed_output, *fixed_output_pre,
1863 *fixed_output_post, (void *)&ma, 0);
1868 DONE: /* now we're done */
1869 if (do_proto) cprintf("000\n");
1876 * display a message (mode 0 - Citadel proprietary)
1878 void cmd_msg0(char *cmdbuf)
1881 int headers_only = HEADERS_ALL;
1883 msgid = extract_long(cmdbuf, 0);
1884 headers_only = extract_int(cmdbuf, 1);
1886 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1892 * display a message (mode 2 - RFC822)
1894 void cmd_msg2(char *cmdbuf)
1897 int headers_only = HEADERS_ALL;
1899 msgid = extract_long(cmdbuf, 0);
1900 headers_only = extract_int(cmdbuf, 1);
1902 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1908 * display a message (mode 3 - IGnet raw format - internal programs only)
1910 void cmd_msg3(char *cmdbuf)
1913 struct CtdlMessage *msg = NULL;
1916 if (CC->internal_pgm == 0) {
1917 cprintf("%d This command is for internal programs only.\n",
1918 ERROR + HIGHER_ACCESS_REQUIRED);
1922 msgnum = extract_long(cmdbuf, 0);
1923 msg = CtdlFetchMessage(msgnum, 1);
1925 cprintf("%d Message %ld not found.\n",
1926 ERROR + MESSAGE_NOT_FOUND, msgnum);
1930 serialize_message(&smr, msg);
1931 CtdlFreeMessage(msg);
1934 cprintf("%d Unable to serialize message\n",
1935 ERROR + INTERNAL_ERROR);
1939 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1940 client_write((char *)smr.ser, (int)smr.len);
1947 * Display a message using MIME content types
1949 void cmd_msg4(char *cmdbuf)
1954 msgid = extract_long(cmdbuf, 0);
1955 extract_token(section, cmdbuf, 1, '|', sizeof section);
1956 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1962 * Client tells us its preferred message format(s)
1964 void cmd_msgp(char *cmdbuf)
1966 safestrncpy(CC->preferred_formats, cmdbuf,
1967 sizeof(CC->preferred_formats));
1968 cprintf("%d ok\n", CIT_OK);
1973 * Open a component of a MIME message as a download file
1975 void cmd_opna(char *cmdbuf)
1978 char desired_section[128];
1980 msgid = extract_long(cmdbuf, 0);
1981 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1982 safestrncpy(CC->download_desired_section, desired_section,
1983 sizeof CC->download_desired_section);
1984 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
1989 * Open a component of a MIME message and transmit it all at once
1991 void cmd_dlat(char *cmdbuf)
1994 char desired_section[128];
1996 msgid = extract_long(cmdbuf, 0);
1997 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1998 safestrncpy(CC->download_desired_section, desired_section,
1999 sizeof CC->download_desired_section);
2000 CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL);
2005 * Save one or more message pointers into a specified room
2006 * (Returns 0 for success, nonzero for failure)
2007 * roomname may be NULL to use the current room
2009 * Note that the 'supplied_msg' field may be set to NULL, in which case
2010 * the message will be fetched from disk, by number, if we need to perform
2011 * replication checks. This adds an additional database read, so if the
2012 * caller already has the message in memory then it should be supplied. (Obviously
2013 * this mode of operation only works if we're saving a single message.)
2015 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2016 int do_repl_check, struct CtdlMessage *supplied_msg)
2019 char hold_rm[ROOMNAMELEN];
2020 struct cdbdata *cdbfr;
2023 long highest_msg = 0L;
2026 struct CtdlMessage *msg = NULL;
2028 long *msgs_to_be_merged = NULL;
2029 int num_msgs_to_be_merged = 0;
2032 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d)\n",
2033 roomname, num_newmsgs, do_repl_check);
2035 strcpy(hold_rm, CC->room.QRname);
2038 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2039 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2040 if (num_newmsgs > 1) supplied_msg = NULL;
2042 /* Now the regular stuff */
2043 if (lgetroom(&CC->room,
2044 ((roomname != NULL) ? roomname : CC->room.QRname) )
2046 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
2047 return(ERROR + ROOM_NOT_FOUND);
2051 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2052 num_msgs_to_be_merged = 0;
2055 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2056 if (cdbfr == NULL) {
2060 msglist = (long *) cdbfr->ptr;
2061 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2062 num_msgs = cdbfr->len / sizeof(long);
2067 /* Create a list of msgid's which were supplied by the caller, but do
2068 * not already exist in the target room. It is absolutely taboo to
2069 * have more than one reference to the same message in a room.
2071 for (i=0; i<num_newmsgs; ++i) {
2073 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2074 if (msglist[j] == newmsgidlist[i]) {
2079 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2083 lprintf(9, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2086 * Now merge the new messages
2088 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2089 if (msglist == NULL) {
2090 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
2092 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2093 num_msgs += num_msgs_to_be_merged;
2095 /* Sort the message list, so all the msgid's are in order */
2096 num_msgs = sort_msglist(msglist, num_msgs);
2098 /* Determine the highest message number */
2099 highest_msg = msglist[num_msgs - 1];
2101 /* Write it back to disk. */
2102 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2103 msglist, (int)(num_msgs * sizeof(long)));
2105 /* Free up the memory we used. */
2108 /* Update the highest-message pointer and unlock the room. */
2109 CC->room.QRhighest = highest_msg;
2110 lputroom(&CC->room);
2112 /* Perform replication checks if necessary */
2113 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2114 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2116 for (i=0; i<num_msgs_to_be_merged; ++i) {
2117 msgid = msgs_to_be_merged[i];
2119 if (supplied_msg != NULL) {
2123 msg = CtdlFetchMessage(msgid, 0);
2127 ReplicationChecks(msg);
2129 /* If the message has an Exclusive ID, index that... */
2130 if (msg->cm_fields['E'] != NULL) {
2131 index_message_by_euid(msg->cm_fields['E'], &CC->room, msgid);
2134 /* Free up the memory we may have allocated */
2135 if (msg != supplied_msg) {
2136 CtdlFreeMessage(msg);
2144 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2147 /* Submit this room for processing by hooks */
2148 PerformRoomHooks(&CC->room);
2150 /* Go back to the room we were in before we wandered here... */
2151 getroom(&CC->room, hold_rm);
2153 /* Bump the reference count for all messages which were merged */
2154 for (i=0; i<num_msgs_to_be_merged; ++i) {
2155 AdjRefCount(msgs_to_be_merged[i], +1);
2158 /* Free up memory... */
2159 if (msgs_to_be_merged != NULL) {
2160 free(msgs_to_be_merged);
2163 /* Return success. */
2169 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2172 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2173 int do_repl_check, struct CtdlMessage *supplied_msg)
2175 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg);
2182 * Message base operation to save a new message to the message store
2183 * (returns new message number)
2185 * This is the back end for CtdlSubmitMsg() and should not be directly
2186 * called by server-side modules.
2189 long send_message(struct CtdlMessage *msg) {
2197 /* Get a new message number */
2198 newmsgid = get_new_message_number();
2199 snprintf(msgidbuf, sizeof msgidbuf, "%010ld@%s", newmsgid, config.c_fqdn);
2201 /* Generate an ID if we don't have one already */
2202 if (msg->cm_fields['I']==NULL) {
2203 msg->cm_fields['I'] = strdup(msgidbuf);
2206 /* If the message is big, set its body aside for storage elsewhere */
2207 if (msg->cm_fields['M'] != NULL) {
2208 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2210 holdM = msg->cm_fields['M'];
2211 msg->cm_fields['M'] = NULL;
2215 /* Serialize our data structure for storage in the database */
2216 serialize_message(&smr, msg);
2219 msg->cm_fields['M'] = holdM;
2223 cprintf("%d Unable to serialize message\n",
2224 ERROR + INTERNAL_ERROR);
2228 /* Write our little bundle of joy into the message base */
2229 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2230 smr.ser, smr.len) < 0) {
2231 lprintf(CTDL_ERR, "Can't store message\n");
2235 cdb_store(CDB_BIGMSGS,
2245 /* Free the memory we used for the serialized message */
2248 /* Return the *local* message ID to the caller
2249 * (even if we're storing an incoming network message)
2257 * Serialize a struct CtdlMessage into the format used on disk and network.
2259 * This function loads up a "struct ser_ret" (defined in server.h) which
2260 * contains the length of the serialized message and a pointer to the
2261 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2263 void serialize_message(struct ser_ret *ret, /* return values */
2264 struct CtdlMessage *msg) /* unserialized msg */
2266 size_t wlen, fieldlen;
2268 static char *forder = FORDER;
2271 * Check for valid message format
2273 if (is_valid_message(msg) == 0) {
2274 lprintf(CTDL_ERR, "serialize_message() aborting due to invalid message\n");
2281 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2282 ret->len = ret->len +
2283 strlen(msg->cm_fields[(int)forder[i]]) + 2;
2285 ret->ser = malloc(ret->len);
2286 if (ret->ser == NULL) {
2287 lprintf(CTDL_ERR, "serialize_message() malloc(%ld) failed: %s\n",
2288 (long)ret->len, strerror(errno));
2295 ret->ser[1] = msg->cm_anon_type;
2296 ret->ser[2] = msg->cm_format_type;
2299 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2300 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
2301 ret->ser[wlen++] = (char)forder[i];
2302 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
2303 wlen = wlen + fieldlen + 1;
2305 if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2306 (long)ret->len, (long)wlen);
2314 * Check to see if any messages already exist in the current room which
2315 * carry the same Exclusive ID as this one. If any are found, delete them.
2317 void ReplicationChecks(struct CtdlMessage *msg) {
2318 long old_msgnum = (-1L);
2320 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2322 lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2325 /* No exclusive id? Don't do anything. */
2326 if (msg == NULL) return;
2327 if (msg->cm_fields['E'] == NULL) return;
2328 if (strlen(msg->cm_fields['E']) == 0) return;
2329 /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2330 msg->cm_fields['E'], CC->room.QRname);*/
2332 old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2333 if (old_msgnum > 0L) {
2334 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2335 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2342 * Save a message to disk and submit it into the delivery system.
2344 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2345 struct recptypes *recps, /* recipients (if mail) */
2346 char *force /* force a particular room? */
2348 char submit_filename[128];
2349 char generated_timestamp[32];
2350 char hold_rm[ROOMNAMELEN];
2351 char actual_rm[ROOMNAMELEN];
2352 char force_room[ROOMNAMELEN];
2353 char content_type[SIZ]; /* We have to learn this */
2354 char recipient[SIZ];
2357 struct ctdluser userbuf;
2359 struct MetaData smi;
2360 FILE *network_fp = NULL;
2361 static int seqnum = 1;
2362 struct CtdlMessage *imsg = NULL;
2364 size_t instr_alloc = 0;
2366 char *hold_R, *hold_D;
2367 char *collected_addresses = NULL;
2368 struct addresses_to_be_filed *aptr = NULL;
2369 char *saved_rfc822_version = NULL;
2370 int qualified_for_journaling = 0;
2372 lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2373 if (is_valid_message(msg) == 0) return(-1); /* self check */
2375 /* If this message has no timestamp, we take the liberty of
2376 * giving it one, right now.
2378 if (msg->cm_fields['T'] == NULL) {
2379 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2380 msg->cm_fields['T'] = strdup(generated_timestamp);
2383 /* If this message has no path, we generate one.
2385 if (msg->cm_fields['P'] == NULL) {
2386 if (msg->cm_fields['A'] != NULL) {
2387 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2388 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
2389 if (isspace(msg->cm_fields['P'][a])) {
2390 msg->cm_fields['P'][a] = ' ';
2395 msg->cm_fields['P'] = strdup("unknown");
2399 if (force == NULL) {
2400 strcpy(force_room, "");
2403 strcpy(force_room, force);
2406 /* Learn about what's inside, because it's what's inside that counts */
2407 if (msg->cm_fields['M'] == NULL) {
2408 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2412 switch (msg->cm_format_type) {
2414 strcpy(content_type, "text/x-citadel-variformat");
2417 strcpy(content_type, "text/plain");
2420 strcpy(content_type, "text/plain");
2421 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type:");
2423 safestrncpy(content_type, &mptr[13], sizeof content_type);
2424 striplt(content_type);
2425 for (a = 0; a < strlen(content_type); ++a) {
2426 if ((content_type[a] == ';')
2427 || (content_type[a] == ' ')
2428 || (content_type[a] == 13)
2429 || (content_type[a] == 10)) {
2430 content_type[a] = 0;
2436 /* Goto the correct room */
2437 lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CC->room.QRname : SENTITEMS);
2438 strcpy(hold_rm, CC->room.QRname);
2439 strcpy(actual_rm, CC->room.QRname);
2440 if (recps != NULL) {
2441 strcpy(actual_rm, SENTITEMS);
2444 /* If the user is a twit, move to the twit room for posting */
2446 if (CC->user.axlevel == 2) {
2447 strcpy(hold_rm, actual_rm);
2448 strcpy(actual_rm, config.c_twitroom);
2449 lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2453 /* ...or if this message is destined for Aide> then go there. */
2454 if (strlen(force_room) > 0) {
2455 strcpy(actual_rm, force_room);
2458 lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2459 if (strcasecmp(actual_rm, CC->room.QRname)) {
2460 /* getroom(&CC->room, actual_rm); */
2461 usergoto(actual_rm, 0, 1, NULL, NULL);
2465 * If this message has no O (room) field, generate one.
2467 if (msg->cm_fields['O'] == NULL) {
2468 msg->cm_fields['O'] = strdup(CC->room.QRname);
2471 /* Perform "before save" hooks (aborting if any return nonzero) */
2472 lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2473 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2476 * If this message has an Exclusive ID, and the room is replication
2477 * checking enabled, then do replication checks.
2479 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2480 ReplicationChecks(msg);
2483 /* Save it to disk */
2484 lprintf(CTDL_DEBUG, "Saving to disk\n");
2485 newmsgid = send_message(msg);
2486 if (newmsgid <= 0L) return(-5);
2488 /* Write a supplemental message info record. This doesn't have to
2489 * be a critical section because nobody else knows about this message
2492 lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2493 memset(&smi, 0, sizeof(struct MetaData));
2494 smi.meta_msgnum = newmsgid;
2495 smi.meta_refcount = 0;
2496 safestrncpy(smi.meta_content_type, content_type,
2497 sizeof smi.meta_content_type);
2500 * Measure how big this message will be when rendered as RFC822.
2501 * We do this for two reasons:
2502 * 1. We need the RFC822 length for the new metadata record, so the
2503 * POP and IMAP services don't have to calculate message lengths
2504 * while the user is waiting (multiplied by potentially hundreds
2505 * or thousands of messages).
2506 * 2. If journaling is enabled, we will need an RFC822 version of the
2507 * message to attach to the journalized copy.
2509 if (CC->redirect_buffer != NULL) {
2510 lprintf(CTDL_ALERT, "CC->redirect_buffer is not NULL during message submission!\n");
2513 CC->redirect_buffer = malloc(SIZ);
2514 CC->redirect_len = 0;
2515 CC->redirect_alloc = SIZ;
2516 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2517 smi.meta_rfc822_length = CC->redirect_len;
2518 saved_rfc822_version = CC->redirect_buffer;
2519 CC->redirect_buffer = NULL;
2520 CC->redirect_len = 0;
2521 CC->redirect_alloc = 0;
2525 /* Now figure out where to store the pointers */
2526 lprintf(CTDL_DEBUG, "Storing pointers\n");
2528 /* If this is being done by the networker delivering a private
2529 * message, we want to BYPASS saving the sender's copy (because there
2530 * is no local sender; it would otherwise go to the Trashcan).
2532 if ((!CC->internal_pgm) || (recps == NULL)) {
2533 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2534 lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2535 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2539 /* For internet mail, drop a copy in the outbound queue room */
2541 if (recps->num_internet > 0) {
2542 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2545 /* If other rooms are specified, drop them there too. */
2547 if (recps->num_room > 0)
2548 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2549 extract_token(recipient, recps->recp_room, i,
2550 '|', sizeof recipient);
2551 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2552 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2555 /* Bump this user's messages posted counter. */
2556 lprintf(CTDL_DEBUG, "Updating user\n");
2557 lgetuser(&CC->user, CC->curr_user);
2558 CC->user.posted = CC->user.posted + 1;
2559 lputuser(&CC->user);
2561 /* If this is private, local mail, make a copy in the
2562 * recipient's mailbox and bump the reference count.
2565 if (recps->num_local > 0)
2566 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2567 extract_token(recipient, recps->recp_local, i,
2568 '|', sizeof recipient);
2569 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2571 if (getuser(&userbuf, recipient) == 0) {
2572 // Add a flag so the Funambol module knows its mail
2573 msg->cm_fields['W'] = strdup(recipient);
2574 MailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
2575 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2576 BumpNewMailCounter(userbuf.usernum);
2577 if (strlen(config.c_funambol_host) > 0) {
2578 /* Generate a instruction message for the Funambol notification
2579 * server, in the same style as the SMTP queue
2582 instr = malloc(instr_alloc);
2583 snprintf(instr, instr_alloc,
2584 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2586 SPOOLMIME, newmsgid, (long)time(NULL),
2587 msg->cm_fields['A'], msg->cm_fields['N']
2590 imsg = malloc(sizeof(struct CtdlMessage));
2591 memset(imsg, 0, sizeof(struct CtdlMessage));
2592 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2593 imsg->cm_anon_type = MES_NORMAL;
2594 imsg->cm_format_type = FMT_RFC822;
2595 imsg->cm_fields['A'] = strdup("Citadel");
2596 imsg->cm_fields['J'] = strdup("do not journal");
2597 imsg->cm_fields['M'] = instr; /* imsg owns this memory now */
2598 imsg->cm_fields['W'] = strdup(recipient);
2599 CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM);
2600 CtdlFreeMessage(imsg);
2604 lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2605 CtdlSaveMsgPointerInRoom(config.c_aideroom,
2610 /* Perform "after save" hooks */
2611 lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2612 PerformMessageHooks(msg, EVT_AFTERSAVE);
2614 /* For IGnet mail, we have to save a new copy into the spooler for
2615 * each recipient, with the R and D fields set to the recipient and
2616 * destination-node. This has two ugly side effects: all other
2617 * recipients end up being unlisted in this recipient's copy of the
2618 * message, and it has to deliver multiple messages to the same
2619 * node. We'll revisit this again in a year or so when everyone has
2620 * a network spool receiver that can handle the new style messages.
2623 if (recps->num_ignet > 0)
2624 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2625 extract_token(recipient, recps->recp_ignet, i,
2626 '|', sizeof recipient);
2628 hold_R = msg->cm_fields['R'];
2629 hold_D = msg->cm_fields['D'];
2630 msg->cm_fields['R'] = malloc(SIZ);
2631 msg->cm_fields['D'] = malloc(128);
2632 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2633 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2635 serialize_message(&smr, msg);
2637 snprintf(submit_filename, sizeof submit_filename,
2638 "%s/netmail.%04lx.%04x.%04x",
2640 (long) getpid(), CC->cs_pid, ++seqnum);
2641 network_fp = fopen(submit_filename, "wb+");
2642 if (network_fp != NULL) {
2643 fwrite(smr.ser, smr.len, 1, network_fp);
2649 free(msg->cm_fields['R']);
2650 free(msg->cm_fields['D']);
2651 msg->cm_fields['R'] = hold_R;
2652 msg->cm_fields['D'] = hold_D;
2655 /* Go back to the room we started from */
2656 lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2657 if (strcasecmp(hold_rm, CC->room.QRname))
2658 usergoto(hold_rm, 0, 1, NULL, NULL);
2660 /* For internet mail, generate delivery instructions.
2661 * Yes, this is recursive. Deal with it. Infinite recursion does
2662 * not happen because the delivery instructions message does not
2663 * contain a recipient.
2666 if (recps->num_internet > 0) {
2667 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2669 instr = malloc(instr_alloc);
2670 snprintf(instr, instr_alloc,
2671 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2673 SPOOLMIME, newmsgid, (long)time(NULL),
2674 msg->cm_fields['A'], msg->cm_fields['N']
2677 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2678 size_t tmp = strlen(instr);
2679 extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
2680 if ((tmp + strlen(recipient) + 32) > instr_alloc) {
2681 instr_alloc = instr_alloc * 2;
2682 instr = realloc(instr, instr_alloc);
2684 snprintf(&instr[tmp], instr_alloc - tmp, "remote|%s|0||\n", recipient);
2687 imsg = malloc(sizeof(struct CtdlMessage));
2688 memset(imsg, 0, sizeof(struct CtdlMessage));
2689 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2690 imsg->cm_anon_type = MES_NORMAL;
2691 imsg->cm_format_type = FMT_RFC822;
2692 imsg->cm_fields['A'] = strdup("Citadel");
2693 imsg->cm_fields['J'] = strdup("do not journal");
2694 imsg->cm_fields['M'] = instr; /* imsg owns this memory now */
2695 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2696 CtdlFreeMessage(imsg);
2700 * Any addresses to harvest for someone's address book?
2702 if ( (CC->logged_in) && (recps != NULL) ) {
2703 collected_addresses = harvest_collected_addresses(msg);
2706 if (collected_addresses != NULL) {
2707 begin_critical_section(S_ATBF);
2708 aptr = (struct addresses_to_be_filed *)
2709 malloc(sizeof(struct addresses_to_be_filed));
2711 MailboxName(actual_rm, sizeof actual_rm,
2712 &CC->user, USERCONTACTSROOM);
2713 aptr->roomname = strdup(actual_rm);
2714 aptr->collected_addresses = collected_addresses;
2716 end_critical_section(S_ATBF);
2720 * Determine whether this message qualifies for journaling.
2722 if (msg->cm_fields['J'] != NULL) {
2723 qualified_for_journaling = 0;
2726 if (recps == NULL) {
2727 qualified_for_journaling = config.c_journal_pubmsgs;
2729 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2730 qualified_for_journaling = config.c_journal_email;
2733 qualified_for_journaling = config.c_journal_pubmsgs;
2738 * Do we have to perform journaling? If so, hand off the saved
2739 * RFC822 version will be handed off to the journaler for background
2740 * submit. Otherwise, we have to free the memory ourselves.
2742 if (saved_rfc822_version != NULL) {
2743 if (qualified_for_journaling) {
2744 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2747 free(saved_rfc822_version);
2760 * Convenience function for generating small administrative messages.
2762 void quickie_message(char *from, char *fromaddr, char *to, char *room, char *text,
2763 int format_type, char *subject)
2765 struct CtdlMessage *msg;
2766 struct recptypes *recp = NULL;
2768 msg = malloc(sizeof(struct CtdlMessage));
2769 memset(msg, 0, sizeof(struct CtdlMessage));
2770 msg->cm_magic = CTDLMESSAGE_MAGIC;
2771 msg->cm_anon_type = MES_NORMAL;
2772 msg->cm_format_type = format_type;
2775 msg->cm_fields['A'] = strdup(from);
2777 else if (fromaddr != NULL) {
2778 msg->cm_fields['A'] = strdup(fromaddr);
2779 if (strchr(msg->cm_fields['A'], '@')) {
2780 *strchr(msg->cm_fields['A'], '@') = 0;
2784 msg->cm_fields['A'] = strdup("Citadel");
2787 if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
2788 if (room != NULL) msg->cm_fields['O'] = strdup(room);
2789 msg->cm_fields['N'] = strdup(NODENAME);
2791 msg->cm_fields['R'] = strdup(to);
2792 recp = validate_recipients(to);
2794 if (subject != NULL) {
2795 msg->cm_fields['U'] = strdup(subject);
2797 msg->cm_fields['M'] = strdup(text);
2799 CtdlSubmitMsg(msg, recp, room);
2800 CtdlFreeMessage(msg);
2801 if (recp != NULL) free_recipients(recp);
2807 * Back end function used by CtdlMakeMessage() and similar functions
2809 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2810 size_t maxlen, /* maximum message length */
2811 char *exist, /* if non-null, append to it;
2812 exist is ALWAYS freed */
2813 int crlf /* CRLF newlines instead of LF */
2817 size_t message_len = 0;
2818 size_t buffer_len = 0;
2825 if (exist == NULL) {
2832 message_len = strlen(exist);
2833 buffer_len = message_len + 4096;
2834 m = realloc(exist, buffer_len);
2841 /* Do we need to change leading ".." to "." for SMTP escaping? */
2842 if (!strcmp(terminator, ".")) {
2846 /* flush the input if we have nowhere to store it */
2851 /* read in the lines of message text one by one */
2853 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2854 if (!strcmp(buf, terminator)) finished = 1;
2856 strcat(buf, "\r\n");
2862 /* Unescape SMTP-style input of two dots at the beginning of the line */
2864 if (!strncmp(buf, "..", 2)) {
2865 strcpy(buf, &buf[1]);
2869 if ( (!flushing) && (!finished) ) {
2870 /* Measure the line */
2871 linelen = strlen(buf);
2873 /* augment the buffer if we have to */
2874 if ((message_len + linelen) >= buffer_len) {
2875 ptr = realloc(m, (buffer_len * 2) );
2876 if (ptr == NULL) { /* flush if can't allocate */
2879 buffer_len = (buffer_len * 2);
2881 lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2885 /* Add the new line to the buffer. NOTE: this loop must avoid
2886 * using functions like strcat() and strlen() because they
2887 * traverse the entire buffer upon every call, and doing that
2888 * for a multi-megabyte message slows it down beyond usability.
2890 strcpy(&m[message_len], buf);
2891 message_len += linelen;
2894 /* if we've hit the max msg length, flush the rest */
2895 if (message_len >= maxlen) flushing = 1;
2897 } while (!finished);
2905 * Build a binary message to be saved on disk.
2906 * (NOTE: if you supply 'preformatted_text', the buffer you give it
2907 * will become part of the message. This means you are no longer
2908 * responsible for managing that memory -- it will be freed along with
2909 * the rest of the fields when CtdlFreeMessage() is called.)
2912 struct CtdlMessage *CtdlMakeMessage(
2913 struct ctdluser *author, /* author's user structure */
2914 char *recipient, /* NULL if it's not mail */
2915 char *recp_cc, /* NULL if it's not mail */
2916 char *room, /* room where it's going */
2917 int type, /* see MES_ types in header file */
2918 int format_type, /* variformat, plain text, MIME... */
2919 char *fake_name, /* who we're masquerading as */
2920 char *my_email, /* which of my email addresses to use (empty is ok) */
2921 char *subject, /* Subject (optional) */
2922 char *supplied_euid, /* ...or NULL if this is irrelevant */
2923 char *preformatted_text /* ...or NULL to read text from client */
2925 char dest_node[256];
2927 struct CtdlMessage *msg;
2930 msg = malloc(sizeof(struct CtdlMessage));
2931 memset(msg, 0, sizeof(struct CtdlMessage));
2932 msg->cm_magic = CTDLMESSAGE_MAGIC;
2933 msg->cm_anon_type = type;
2934 msg->cm_format_type = format_type;
2936 /* Don't confuse the poor folks if it's not routed mail. */
2937 strcpy(dest_node, "");
2942 /* Path or Return-Path */
2943 if (my_email == NULL) my_email = "";
2945 if (strlen(my_email) > 0) {
2946 msg->cm_fields['P'] = strdup(my_email);
2949 snprintf(buf, sizeof buf, "%s", author->fullname);
2950 msg->cm_fields['P'] = strdup(buf);
2952 for (i=0; (msg->cm_fields['P'][i]!=0); ++i) {
2953 if (isspace(msg->cm_fields['P'][i])) {
2954 msg->cm_fields['P'][i] = '_';
2958 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
2959 msg->cm_fields['T'] = strdup(buf);
2961 if (fake_name[0]) /* author */
2962 msg->cm_fields['A'] = strdup(fake_name);
2964 msg->cm_fields['A'] = strdup(author->fullname);
2966 if (CC->room.QRflags & QR_MAILBOX) { /* room */
2967 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2970 msg->cm_fields['O'] = strdup(CC->room.QRname);
2973 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
2974 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
2976 if (recipient[0] != 0) {
2977 msg->cm_fields['R'] = strdup(recipient);
2979 if (recp_cc[0] != 0) {
2980 msg->cm_fields['Y'] = strdup(recp_cc);
2982 if (dest_node[0] != 0) {
2983 msg->cm_fields['D'] = strdup(dest_node);
2986 if (strlen(my_email) > 0) {
2987 msg->cm_fields['F'] = strdup(my_email);
2989 else if ( (author == &CC->user) && (strlen(CC->cs_inet_email) > 0) ) {
2990 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2993 if (subject != NULL) {
2996 length = strlen(subject);
3002 while ((subject[i] != '\0') &&
3003 (IsAscii = isascii(subject[i]) != 0 ))
3006 msg->cm_fields['U'] = strdup(subject);
3007 else /* ok, we've got utf8 in the string. */
3009 msg->cm_fields['U'] = rfc2047encode(subject, length);
3015 if (supplied_euid != NULL) {
3016 msg->cm_fields['E'] = strdup(supplied_euid);
3019 if (preformatted_text != NULL) {
3020 msg->cm_fields['M'] = preformatted_text;
3023 msg->cm_fields['M'] = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
3031 * Check to see whether we have permission to post a message in the current
3032 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
3033 * returns 0 on success.
3035 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
3038 if (!(CC->logged_in)) {
3039 snprintf(errmsgbuf, n, "Not logged in.");
3040 return (ERROR + NOT_LOGGED_IN);
3043 if ((CC->user.axlevel < 2)
3044 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
3045 snprintf(errmsgbuf, n, "Need to be validated to enter "
3046 "(except in %s> to sysop)", MAILROOM);
3047 return (ERROR + HIGHER_ACCESS_REQUIRED);
3050 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3051 if (!(ra & UA_POSTALLOWED)) {
3052 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
3053 return (ERROR + HIGHER_ACCESS_REQUIRED);
3056 strcpy(errmsgbuf, "Ok");
3062 * Check to see if the specified user has Internet mail permission
3063 * (returns nonzero if permission is granted)
3065 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
3067 /* Do not allow twits to send Internet mail */
3068 if (who->axlevel <= 2) return(0);
3070 /* Globally enabled? */
3071 if (config.c_restrict == 0) return(1);
3073 /* User flagged ok? */
3074 if (who->flags & US_INTERNET) return(2);
3076 /* Aide level access? */
3077 if (who->axlevel >= 6) return(3);
3079 /* No mail for you! */
3085 * Validate recipients, count delivery types and errors, and handle aliasing
3086 * FIXME check for dupes!!!!!
3088 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
3089 * were specified, or the number of addresses found invalid.
3091 * Caller needs to free the result using free_recipients()
3093 struct recptypes *validate_recipients(char *supplied_recipients) {
3094 struct recptypes *ret;
3095 char *recipients = NULL;
3096 char this_recp[256];
3097 char this_recp_cooked[256];
3103 struct ctdluser tempUS;
3104 struct ctdlroom tempQR;
3108 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
3109 if (ret == NULL) return(NULL);
3111 /* Set all strings to null and numeric values to zero */
3112 memset(ret, 0, sizeof(struct recptypes));
3114 if (supplied_recipients == NULL) {
3115 recipients = strdup("");
3118 recipients = strdup(supplied_recipients);
3121 /* Allocate some memory. Yes, this allocates 500% more memory than we will
3122 * actually need, but it's healthier for the heap than doing lots of tiny
3123 * realloc() calls instead.
3126 ret->errormsg = malloc(strlen(recipients) + 1024);
3127 ret->recp_local = malloc(strlen(recipients) + 1024);
3128 ret->recp_internet = malloc(strlen(recipients) + 1024);
3129 ret->recp_ignet = malloc(strlen(recipients) + 1024);
3130 ret->recp_room = malloc(strlen(recipients) + 1024);
3131 ret->display_recp = malloc(strlen(recipients) + 1024);
3133 ret->errormsg[0] = 0;
3134 ret->recp_local[0] = 0;
3135 ret->recp_internet[0] = 0;
3136 ret->recp_ignet[0] = 0;
3137 ret->recp_room[0] = 0;
3138 ret->display_recp[0] = 0;
3140 ret->recptypes_magic = RECPTYPES_MAGIC;
3142 /* Change all valid separator characters to commas */
3143 for (i=0; i<strlen(recipients); ++i) {
3144 if ((recipients[i] == ';') || (recipients[i] == '|')) {
3145 recipients[i] = ',';
3149 /* Now start extracting recipients... */
3151 while (strlen(recipients) > 0) {
3153 for (i=0; i<=strlen(recipients); ++i) {
3154 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
3155 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
3156 safestrncpy(this_recp, recipients, i+1);
3158 if (recipients[i] == ',') {
3159 strcpy(recipients, &recipients[i+1]);
3162 strcpy(recipients, "");
3169 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
3171 mailtype = alias(this_recp);
3172 mailtype = alias(this_recp);
3173 mailtype = alias(this_recp);
3174 for (j=0; j<=strlen(this_recp); ++j) {
3175 if (this_recp[j]=='_') {
3176 this_recp_cooked[j] = ' ';
3179 this_recp_cooked[j] = this_recp[j];
3185 if (!strcasecmp(this_recp, "sysop")) {
3187 strcpy(this_recp, config.c_aideroom);
3188 if (strlen(ret->recp_room) > 0) {
3189 strcat(ret->recp_room, "|");
3191 strcat(ret->recp_room, this_recp);
3193 else if (getuser(&tempUS, this_recp) == 0) {
3195 strcpy(this_recp, tempUS.fullname);
3196 if (strlen(ret->recp_local) > 0) {
3197 strcat(ret->recp_local, "|");
3199 strcat(ret->recp_local, this_recp);
3201 else if (getuser(&tempUS, this_recp_cooked) == 0) {
3203 strcpy(this_recp, tempUS.fullname);
3204 if (strlen(ret->recp_local) > 0) {
3205 strcat(ret->recp_local, "|");
3207 strcat(ret->recp_local, this_recp);
3209 else if ( (!strncasecmp(this_recp, "room_", 5))
3210 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
3212 if (strlen(ret->recp_room) > 0) {
3213 strcat(ret->recp_room, "|");
3215 strcat(ret->recp_room, &this_recp_cooked[5]);
3223 /* Yes, you're reading this correctly: if the target
3224 * domain points back to the local system or an attached
3225 * Citadel directory, the address is invalid. That's
3226 * because if the address were valid, we would have
3227 * already translated it to a local address by now.
3229 if (IsDirectory(this_recp, 0)) {
3234 ++ret->num_internet;
3235 if (strlen(ret->recp_internet) > 0) {
3236 strcat(ret->recp_internet, "|");
3238 strcat(ret->recp_internet, this_recp);
3243 if (strlen(ret->recp_ignet) > 0) {
3244 strcat(ret->recp_ignet, "|");
3246 strcat(ret->recp_ignet, this_recp);
3254 if (strlen(ret->errormsg) == 0) {
3255 snprintf(append, sizeof append,
3256 "Invalid recipient: %s",
3260 snprintf(append, sizeof append, ", %s", this_recp);
3262 if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
3263 strcat(ret->errormsg, append);
3267 if (strlen(ret->display_recp) == 0) {
3268 strcpy(append, this_recp);
3271 snprintf(append, sizeof append, ", %s", this_recp);
3273 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
3274 strcat(ret->display_recp, append);
3279 if ((ret->num_local + ret->num_internet + ret->num_ignet +
3280 ret->num_room + ret->num_error) == 0) {
3281 ret->num_error = (-1);
3282 strcpy(ret->errormsg, "No recipients specified.");
3285 lprintf(CTDL_DEBUG, "validate_recipients()\n");
3286 lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
3287 lprintf(CTDL_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
3288 lprintf(CTDL_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
3289 lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
3290 lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
3298 * Destructor for struct recptypes
3300 void free_recipients(struct recptypes *valid) {
3302 if (valid == NULL) {
3306 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
3307 lprintf(CTDL_EMERG, "Attempt to call free_recipients() on some other data type!\n");
3311 if (valid->errormsg != NULL) free(valid->errormsg);
3312 if (valid->recp_local != NULL) free(valid->recp_local);
3313 if (valid->recp_internet != NULL) free(valid->recp_internet);
3314 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
3315 if (valid->recp_room != NULL) free(valid->recp_room);
3316 if (valid->display_recp != NULL) free(valid->display_recp);
3323 * message entry - mode 0 (normal)
3325 void cmd_ent0(char *entargs)
3331 char supplied_euid[128];
3333 int format_type = 0;
3334 char newusername[256];
3335 char newuseremail[256];
3336 struct CtdlMessage *msg;
3340 struct recptypes *valid = NULL;
3341 struct recptypes *valid_to = NULL;
3342 struct recptypes *valid_cc = NULL;
3343 struct recptypes *valid_bcc = NULL;
3345 int subject_required = 0;
3350 int newuseremail_ok = 0;
3354 post = extract_int(entargs, 0);
3355 extract_token(recp, entargs, 1, '|', sizeof recp);
3356 anon_flag = extract_int(entargs, 2);
3357 format_type = extract_int(entargs, 3);
3358 extract_token(subject, entargs, 4, '|', sizeof subject);
3359 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3360 do_confirm = extract_int(entargs, 6);
3361 extract_token(cc, entargs, 7, '|', sizeof cc);
3362 extract_token(bcc, entargs, 8, '|', sizeof bcc);
3363 switch(CC->room.QRdefaultview) {
3366 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3369 supplied_euid[0] = 0;
3372 extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
3374 /* first check to make sure the request is valid. */
3376 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3379 cprintf("%d %s\n", err, errmsg);
3383 /* Check some other permission type things. */
3385 if (strlen(newusername) == 0) {
3386 strcpy(newusername, CC->user.fullname);
3388 if ( (CC->user.axlevel < 6)
3389 && (strcasecmp(newusername, CC->user.fullname))
3390 && (strcasecmp(newusername, CC->cs_inet_fn))
3392 cprintf("%d You don't have permission to author messages as '%s'.\n",
3393 ERROR + HIGHER_ACCESS_REQUIRED,
3400 if (strlen(newuseremail) == 0) {
3401 newuseremail_ok = 1;
3404 if (strlen(newuseremail) > 0) {
3405 if (!strcasecmp(newuseremail, CC->cs_inet_email)) {
3406 newuseremail_ok = 1;
3408 else if (strlen(CC->cs_inet_other_emails) > 0) {
3409 j = num_tokens(CC->cs_inet_other_emails, '|');
3410 for (i=0; i<j; ++i) {
3411 extract_token(buf, CC->cs_inet_other_emails, i, '|', sizeof buf);
3412 if (!strcasecmp(newuseremail, buf)) {
3413 newuseremail_ok = 1;
3419 if (!newuseremail_ok) {
3420 cprintf("%d You don't have permission to author messages as '%s'.\n",
3421 ERROR + HIGHER_ACCESS_REQUIRED,
3427 CC->cs_flags |= CS_POSTING;
3429 /* In mailbox rooms we have to behave a little differently --
3430 * make sure the user has specified at least one recipient. Then
3431 * validate the recipient(s). We do this for the Mail> room, as
3432 * well as any room which has the "Mailbox" view set.
3435 if ( ( (CC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) )
3436 || ( (CC->room.QRflags & QR_MAILBOX) && (CC->curr_view == VIEW_MAILBOX) )
3438 if (CC->user.axlevel < 2) {
3439 strcpy(recp, "sysop");
3444 valid_to = validate_recipients(recp);
3445 if (valid_to->num_error > 0) {
3446 cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3447 free_recipients(valid_to);
3451 valid_cc = validate_recipients(cc);
3452 if (valid_cc->num_error > 0) {
3453 cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3454 free_recipients(valid_to);
3455 free_recipients(valid_cc);
3459 valid_bcc = validate_recipients(bcc);
3460 if (valid_bcc->num_error > 0) {
3461 cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3462 free_recipients(valid_to);
3463 free_recipients(valid_cc);
3464 free_recipients(valid_bcc);
3468 /* Recipient required, but none were specified */
3469 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3470 free_recipients(valid_to);
3471 free_recipients(valid_cc);
3472 free_recipients(valid_bcc);
3473 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3477 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3478 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3479 cprintf("%d You do not have permission "
3480 "to send Internet mail.\n",
3481 ERROR + HIGHER_ACCESS_REQUIRED);
3482 free_recipients(valid_to);
3483 free_recipients(valid_cc);
3484 free_recipients(valid_bcc);
3489 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)
3490 && (CC->user.axlevel < 4) ) {
3491 cprintf("%d Higher access required for network mail.\n",
3492 ERROR + HIGHER_ACCESS_REQUIRED);
3493 free_recipients(valid_to);
3494 free_recipients(valid_cc);
3495 free_recipients(valid_bcc);
3499 if ((RESTRICT_INTERNET == 1)
3500 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3501 && ((CC->user.flags & US_INTERNET) == 0)
3502 && (!CC->internal_pgm)) {
3503 cprintf("%d You don't have access to Internet mail.\n",
3504 ERROR + HIGHER_ACCESS_REQUIRED);
3505 free_recipients(valid_to);
3506 free_recipients(valid_cc);
3507 free_recipients(valid_bcc);
3513 /* Is this a room which has anonymous-only or anonymous-option? */
3514 anonymous = MES_NORMAL;
3515 if (CC->room.QRflags & QR_ANONONLY) {
3516 anonymous = MES_ANONONLY;
3518 if (CC->room.QRflags & QR_ANONOPT) {
3519 if (anon_flag == 1) { /* only if the user requested it */
3520 anonymous = MES_ANONOPT;
3524 if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3528 /* Recommend to the client that the use of a message subject is
3529 * strongly recommended in this room, if either the SUBJECTREQ flag
3530 * is set, or if there is one or more Internet email recipients.
3532 if (CC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
3533 if (valid_to) if (valid_to->num_internet > 0) subject_required = 1;
3534 if (valid_cc) if (valid_cc->num_internet > 0) subject_required = 1;
3535 if (valid_bcc) if (valid_bcc->num_internet > 0) subject_required = 1;
3537 /* If we're only checking the validity of the request, return
3538 * success without creating the message.
3541 cprintf("%d %s|%d\n", CIT_OK,
3542 ((valid_to != NULL) ? valid_to->display_recp : ""),
3544 free_recipients(valid_to);
3545 free_recipients(valid_cc);
3546 free_recipients(valid_bcc);
3550 /* We don't need these anymore because we'll do it differently below */
3551 free_recipients(valid_to);
3552 free_recipients(valid_cc);
3553 free_recipients(valid_bcc);
3555 /* Read in the message from the client. */
3557 cprintf("%d send message\n", START_CHAT_MODE);
3559 cprintf("%d send message\n", SEND_LISTING);
3562 msg = CtdlMakeMessage(&CC->user, recp, cc,
3563 CC->room.QRname, anonymous, format_type,
3564 newusername, newuseremail, subject,
3565 ((strlen(supplied_euid) > 0) ? supplied_euid : NULL),
3568 /* Put together one big recipients struct containing to/cc/bcc all in
3569 * one. This is for the envelope.
3571 char *all_recps = malloc(SIZ * 3);
3572 strcpy(all_recps, recp);
3573 if (strlen(cc) > 0) {
3574 if (strlen(all_recps) > 0) {
3575 strcat(all_recps, ",");
3577 strcat(all_recps, cc);
3579 if (strlen(bcc) > 0) {
3580 if (strlen(all_recps) > 0) {
3581 strcat(all_recps, ",");
3583 strcat(all_recps, bcc);
3585 if (strlen(all_recps) > 0) {
3586 valid = validate_recipients(all_recps);
3594 msgnum = CtdlSubmitMsg(msg, valid, "");
3597 cprintf("%ld\n", msgnum);
3599 cprintf("Message accepted.\n");
3602 cprintf("Internal error.\n");
3604 if (msg->cm_fields['E'] != NULL) {
3605 cprintf("%s\n", msg->cm_fields['E']);
3612 CtdlFreeMessage(msg);
3614 if (valid != NULL) {
3615 free_recipients(valid);
3623 * API function to delete messages which match a set of criteria
3624 * (returns the actual number of messages deleted)
3626 int CtdlDeleteMessages(char *room_name, /* which room */
3627 long *dmsgnums, /* array of msg numbers to be deleted */
3628 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
3629 char *content_type /* or "" for any. regular expressions expected. */
3632 struct ctdlroom qrbuf;
3633 struct cdbdata *cdbfr;
3634 long *msglist = NULL;
3635 long *dellist = NULL;
3638 int num_deleted = 0;
3640 struct MetaData smi;
3643 int need_to_free_re = 0;
3645 if (content_type) if (strlen(content_type) > 0) {
3646 regcomp(&re, content_type, 0);
3647 need_to_free_re = 1;
3649 lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
3650 room_name, num_dmsgnums, content_type);
3652 /* get room record, obtaining a lock... */
3653 if (lgetroom(&qrbuf, room_name) != 0) {
3654 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3656 if (need_to_free_re) regfree(&re);
3657 return (0); /* room not found */
3659 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3661 if (cdbfr != NULL) {
3662 dellist = malloc(cdbfr->len);
3663 msglist = (long *) cdbfr->ptr;
3664 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3665 num_msgs = cdbfr->len / sizeof(long);
3669 for (i = 0; i < num_msgs; ++i) {
3672 /* Set/clear a bit for each criterion */
3674 /* 0 messages in the list or a null list means that we are
3675 * interested in deleting any messages which meet the other criteria.
3677 if ((num_dmsgnums == 0) || (dmsgnums == NULL)) {
3678 delete_this |= 0x01;
3681 for (j=0; j<num_dmsgnums; ++j) {
3682 if (msglist[i] == dmsgnums[j]) {
3683 delete_this |= 0x01;
3688 if (strlen(content_type) == 0) {
3689 delete_this |= 0x02;
3691 GetMetaData(&smi, msglist[i]);
3692 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3693 delete_this |= 0x02;
3697 /* Delete message only if all bits are set */
3698 if (delete_this == 0x03) {
3699 dellist[num_deleted++] = msglist[i];
3704 num_msgs = sort_msglist(msglist, num_msgs);
3705 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3706 msglist, (int)(num_msgs * sizeof(long)));
3708 qrbuf.QRhighest = msglist[num_msgs - 1];
3712 /* Go through the messages we pulled out of the index, and decrement
3713 * their reference counts by 1. If this is the only room the message
3714 * was in, the reference count will reach zero and the message will
3715 * automatically be deleted from the database. We do this in a
3716 * separate pass because there might be plug-in hooks getting called,
3717 * and we don't want that happening during an S_ROOMS critical
3720 if (num_deleted) for (i=0; i<num_deleted; ++i) {
3721 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3722 AdjRefCount(dellist[i], -1);
3725 /* Now free the memory we used, and go away. */
3726 if (msglist != NULL) free(msglist);
3727 if (dellist != NULL) free(dellist);
3728 lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3729 if (need_to_free_re) regfree(&re);
3730 return (num_deleted);
3736 * Check whether the current user has permission to delete messages from
3737 * the current room (returns 1 for yes, 0 for no)
3739 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3741 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3742 if (ra & UA_DELETEALLOWED) return(1);
3750 * Delete message from current room
3752 void cmd_dele(char *args)
3761 extract_token(msgset, args, 0, '|', sizeof msgset);
3762 num_msgs = num_tokens(msgset, ',');
3764 cprintf("%d Nothing to do.\n", CIT_OK);
3768 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3769 cprintf("%d Higher access required.\n",
3770 ERROR + HIGHER_ACCESS_REQUIRED);
3775 * Build our message set to be moved/copied
3777 msgs = malloc(num_msgs * sizeof(long));
3778 for (i=0; i<num_msgs; ++i) {
3779 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3780 msgs[i] = atol(msgtok);
3783 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3787 cprintf("%d %d message%s deleted.\n", CIT_OK,
3788 num_deleted, ((num_deleted != 1) ? "s" : ""));
3790 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
3796 * Back end API function for moves and deletes (multiple messages)
3798 int CtdlCopyMsgsToRoom(long *msgnums, int num_msgs, char *dest) {
3801 err = CtdlSaveMsgPointersInRoom(dest, msgnums, num_msgs, 1, NULL);
3802 if (err != 0) return(err);
3811 * move or copy a message to another room
3813 void cmd_move(char *args)
3820 char targ[ROOMNAMELEN];
3821 struct ctdlroom qtemp;
3828 extract_token(msgset, args, 0, '|', sizeof msgset);
3829 num_msgs = num_tokens(msgset, ',');
3831 cprintf("%d Nothing to do.\n", CIT_OK);
3835 extract_token(targ, args, 1, '|', sizeof targ);
3836 convert_room_name_macros(targ, sizeof targ);
3837 targ[ROOMNAMELEN - 1] = 0;
3838 is_copy = extract_int(args, 2);
3840 if (getroom(&qtemp, targ) != 0) {
3841 cprintf("%d '%s' does not exist.\n",
3842 ERROR + ROOM_NOT_FOUND, targ);
3846 getuser(&CC->user, CC->curr_user);
3847 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3849 /* Check for permission to perform this operation.
3850 * Remember: "CC->room" is source, "qtemp" is target.
3854 /* Aides can move/copy */
3855 if (CC->user.axlevel >= 6) permit = 1;
3857 /* Room aides can move/copy */
3858 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3860 /* Permit move/copy from personal rooms */
3861 if ((CC->room.QRflags & QR_MAILBOX)
3862 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3864 /* Permit only copy from public to personal room */
3866 && (!(CC->room.QRflags & QR_MAILBOX))
3867 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3869 /* Permit message removal from collaborative delete rooms */
3870 if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
3872 /* User must have access to target room */
3873 if (!(ra & UA_KNOWN)) permit = 0;
3876 cprintf("%d Higher access required.\n",
3877 ERROR + HIGHER_ACCESS_REQUIRED);
3882 * Build our message set to be moved/copied
3884 msgs = malloc(num_msgs * sizeof(long));
3885 for (i=0; i<num_msgs; ++i) {
3886 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3887 msgs[i] = atol(msgtok);
3893 err = CtdlCopyMsgsToRoom(msgs, num_msgs, targ);
3895 cprintf("%d Cannot store message(s) in %s: error %d\n",
3901 /* Now delete the message from the source room,
3902 * if this is a 'move' rather than a 'copy' operation.
3905 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3909 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3915 * GetMetaData() - Get the supplementary record for a message
3917 void GetMetaData(struct MetaData *smibuf, long msgnum)
3920 struct cdbdata *cdbsmi;
3923 memset(smibuf, 0, sizeof(struct MetaData));
3924 smibuf->meta_msgnum = msgnum;
3925 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3927 /* Use the negative of the message number for its supp record index */
3928 TheIndex = (0L - msgnum);
3930 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3931 if (cdbsmi == NULL) {
3932 return; /* record not found; go with defaults */
3934 memcpy(smibuf, cdbsmi->ptr,
3935 ((cdbsmi->len > sizeof(struct MetaData)) ?
3936 sizeof(struct MetaData) : cdbsmi->len));
3943 * PutMetaData() - (re)write supplementary record for a message
3945 void PutMetaData(struct MetaData *smibuf)
3949 /* Use the negative of the message number for the metadata db index */
3950 TheIndex = (0L - smibuf->meta_msgnum);
3952 cdb_store(CDB_MSGMAIN,
3953 &TheIndex, (int)sizeof(long),
3954 smibuf, (int)sizeof(struct MetaData));
3959 * AdjRefCount - submit an adjustment to the reference count for a message.
3960 * (These are just queued -- we actually process them later.)
3962 void AdjRefCount(long msgnum, int incr)
3964 struct arcq new_arcq;
3966 begin_critical_section(S_SUPPMSGMAIN);
3967 if (arcfp == NULL) {
3968 arcfp = fopen(file_arcq, "ab+");
3970 end_critical_section(S_SUPPMSGMAIN);
3972 /* msgnum < 0 means that we're trying to close the file */
3974 lprintf(CTDL_DEBUG, "Closing the AdjRefCount queue file\n");
3975 begin_critical_section(S_SUPPMSGMAIN);
3976 if (arcfp != NULL) {
3980 end_critical_section(S_SUPPMSGMAIN);
3985 * If we can't open the queue, perform the operation synchronously.
3987 if (arcfp == NULL) {
3988 TDAP_AdjRefCount(msgnum, incr);
3992 new_arcq.arcq_msgnum = msgnum;
3993 new_arcq.arcq_delta = incr;
3994 fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
4002 * TDAP_ProcessAdjRefCountQueue()
4004 * Process the queue of message count adjustments that was created by calls
4005 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
4006 * for each one. This should be an "off hours" operation.
4008 int TDAP_ProcessAdjRefCountQueue(void)
4010 char file_arcq_temp[PATH_MAX];
4013 struct arcq arcq_rec;
4014 int num_records_processed = 0;
4016 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s2", file_arcq);
4018 begin_critical_section(S_SUPPMSGMAIN);
4019 if (arcfp != NULL) {
4024 r = link(file_arcq, file_arcq_temp);
4026 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4027 end_critical_section(S_SUPPMSGMAIN);
4028 return(num_records_processed);
4032 end_critical_section(S_SUPPMSGMAIN);
4034 fp = fopen(file_arcq_temp, "rb");
4036 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4037 return(num_records_processed);
4040 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
4041 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
4042 ++num_records_processed;
4046 r = unlink(file_arcq_temp);
4048 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4051 return(num_records_processed);
4057 * TDAP_AdjRefCount - adjust the reference count for a message.
4058 * This one does it "for real" because it's called by
4059 * the autopurger function that processes the queue
4060 * created by AdjRefCount(). If a message's reference
4061 * count becomes zero, we also delete the message from
4062 * disk and de-index it.
4064 void TDAP_AdjRefCount(long msgnum, int incr)
4067 struct MetaData smi;
4070 /* This is a *tight* critical section; please keep it that way, as
4071 * it may get called while nested in other critical sections.
4072 * Complicating this any further will surely cause deadlock!
4074 begin_critical_section(S_SUPPMSGMAIN);
4075 GetMetaData(&smi, msgnum);
4076 smi.meta_refcount += incr;
4078 end_critical_section(S_SUPPMSGMAIN);
4079 lprintf(CTDL_DEBUG, "msg %ld ref count delta %d, is now %d\n",
4080 msgnum, incr, smi.meta_refcount);
4082 /* If the reference count is now zero, delete the message
4083 * (and its supplementary record as well).
4085 if (smi.meta_refcount == 0) {
4086 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
4088 /* Call delete hooks with NULL room to show it has gone altogether */
4089 PerformDeleteHooks(NULL, msgnum);
4091 /* Remove from message base */
4093 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4094 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
4096 /* Remove metadata record */
4097 delnum = (0L - msgnum);
4098 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4104 * Write a generic object to this room
4106 * Note: this could be much more efficient. Right now we use two temporary
4107 * files, and still pull the message into memory as with all others.
4109 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
4110 char *content_type, /* MIME type of this object */
4111 char *tempfilename, /* Where to fetch it from */
4112 struct ctdluser *is_mailbox, /* Mailbox room? */
4113 int is_binary, /* Is encoding necessary? */
4114 int is_unique, /* Del others of this type? */
4115 unsigned int flags /* Internal save flags */
4120 struct ctdlroom qrbuf;
4121 char roomname[ROOMNAMELEN];
4122 struct CtdlMessage *msg;
4124 char *raw_message = NULL;
4125 char *encoded_message = NULL;
4126 off_t raw_length = 0;
4128 if (is_mailbox != NULL) {
4129 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
4132 safestrncpy(roomname, req_room, sizeof(roomname));
4135 fp = fopen(tempfilename, "rb");
4137 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
4138 tempfilename, strerror(errno));
4141 fseek(fp, 0L, SEEK_END);
4142 raw_length = ftell(fp);
4144 lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
4146 raw_message = malloc((size_t)raw_length + 2);
4147 fread(raw_message, (size_t)raw_length, 1, fp);
4151 encoded_message = malloc((size_t)
4152 (((raw_length * 134) / 100) + 4096 ) );
4155 encoded_message = malloc((size_t)(raw_length + 4096));
4158 sprintf(encoded_message, "Content-type: %s\n", content_type);
4161 sprintf(&encoded_message[strlen(encoded_message)],
4162 "Content-transfer-encoding: base64\n\n"
4166 sprintf(&encoded_message[strlen(encoded_message)],
4167 "Content-transfer-encoding: 7bit\n\n"
4173 &encoded_message[strlen(encoded_message)],
4179 raw_message[raw_length] = 0;
4181 &encoded_message[strlen(encoded_message)],
4189 lprintf(CTDL_DEBUG, "Allocating\n");
4190 msg = malloc(sizeof(struct CtdlMessage));
4191 memset(msg, 0, sizeof(struct CtdlMessage));
4192 msg->cm_magic = CTDLMESSAGE_MAGIC;
4193 msg->cm_anon_type = MES_NORMAL;
4194 msg->cm_format_type = 4;
4195 msg->cm_fields['A'] = strdup(CC->user.fullname);
4196 msg->cm_fields['O'] = strdup(req_room);
4197 msg->cm_fields['N'] = strdup(config.c_nodename);
4198 msg->cm_fields['H'] = strdup(config.c_humannode);
4199 msg->cm_flags = flags;
4201 msg->cm_fields['M'] = encoded_message;
4203 /* Create the requested room if we have to. */
4204 if (getroom(&qrbuf, roomname) != 0) {
4205 create_room(roomname,
4206 ( (is_mailbox != NULL) ? 5 : 3 ),
4207 "", 0, 1, 0, VIEW_BBS);
4209 /* If the caller specified this object as unique, delete all
4210 * other objects of this type that are currently in the room.
4213 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
4214 CtdlDeleteMessages(roomname, NULL, 0, content_type)
4217 /* Now write the data */
4218 CtdlSubmitMsg(msg, NULL, roomname);
4219 CtdlFreeMessage(msg);
4227 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
4228 config_msgnum = msgnum;
4232 char *CtdlGetSysConfig(char *sysconfname) {
4233 char hold_rm[ROOMNAMELEN];
4236 struct CtdlMessage *msg;
4239 strcpy(hold_rm, CC->room.QRname);
4240 if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
4241 getroom(&CC->room, hold_rm);
4246 /* We want the last (and probably only) config in this room */
4247 begin_critical_section(S_CONFIG);
4248 config_msgnum = (-1L);
4249 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
4250 CtdlGetSysConfigBackend, NULL);
4251 msgnum = config_msgnum;
4252 end_critical_section(S_CONFIG);
4258 msg = CtdlFetchMessage(msgnum, 1);
4260 conf = strdup(msg->cm_fields['M']);
4261 CtdlFreeMessage(msg);
4268 getroom(&CC->room, hold_rm);
4270 if (conf != NULL) do {
4271 extract_token(buf, conf, 0, '\n', sizeof buf);
4272 strcpy(conf, &conf[strlen(buf)+1]);
4273 } while ( (strlen(conf)>0) && (strlen(buf)>0) );
4278 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
4279 char temp[PATH_MAX];
4282 CtdlMakeTempFileName(temp, sizeof temp);
4284 fp = fopen(temp, "w");
4285 if (fp == NULL) return;
4286 fprintf(fp, "%s", sysconfdata);
4289 /* this handy API function does all the work for us */
4290 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
4296 * Determine whether a given Internet address belongs to the current user
4298 int CtdlIsMe(char *addr, int addr_buf_len)
4300 struct recptypes *recp;
4303 recp = validate_recipients(addr);
4304 if (recp == NULL) return(0);
4306 if (recp->num_local == 0) {
4307 free_recipients(recp);
4311 for (i=0; i<recp->num_local; ++i) {
4312 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
4313 if (!strcasecmp(addr, CC->user.fullname)) {
4314 free_recipients(recp);
4319 free_recipients(recp);
4325 * Citadel protocol command to do the same
4327 void cmd_isme(char *argbuf) {
4330 if (CtdlAccessCheck(ac_logged_in)) return;
4331 extract_token(addr, argbuf, 0, '|', sizeof addr);
4333 if (CtdlIsMe(addr, sizeof addr)) {
4334 cprintf("%d %s\n", CIT_OK, addr);
4337 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);