4 * Implements the message store.
14 #if TIME_WITH_SYS_TIME
15 # include <sys/time.h>
19 # include <sys/time.h>
32 #include <sys/types.h>
36 #include "serv_extensions.h"
40 #include "sysdep_decls.h"
41 #include "citserver.h"
48 #include "mime_parser.h"
51 #include "internet_addressing.h"
52 #include "serv_fulltext.h"
54 #include "euidindex.h"
55 #include "journaling.h"
56 #include "citadel_dirs.h"
57 #include "serv_network.h"
60 # include "serv_sieve.h"
61 #endif /* HAVE_LIBSIEVE */
64 struct addresses_to_be_filed *atbf = NULL;
66 /* This temp file holds the queue of operations for AdjRefCount() */
67 static FILE *arcfp = NULL;
70 * This really belongs in serv_network.c, but I don't know how to export
71 * symbols between modules.
73 struct FilterList *filterlist = NULL;
77 * These are the four-character field headers we use when outputting
78 * messages in Citadel format (as opposed to RFC822 format).
81 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
82 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
83 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
84 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
85 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
86 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
87 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
88 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
116 * This function is self explanatory.
117 * (What can I say, I'm in a weird mood today...)
119 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
123 for (i = 0; i < strlen(name); ++i) {
124 if (name[i] == '@') {
125 while (isspace(name[i - 1]) && i > 0) {
126 strcpy(&name[i - 1], &name[i]);
129 while (isspace(name[i + 1])) {
130 strcpy(&name[i + 1], &name[i + 2]);
138 * Aliasing for network mail.
139 * (Error messages have been commented out, because this is a server.)
141 int alias(char *name)
142 { /* process alias and routing info for mail */
145 char aaa[SIZ], bbb[SIZ];
146 char *ignetcfg = NULL;
147 char *ignetmap = NULL;
154 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
155 stripallbut(name, '<', '>');
157 fp = fopen(file_mail_aliases, "r");
159 fp = fopen("/dev/null", "r");
166 while (fgets(aaa, sizeof aaa, fp) != NULL) {
167 while (isspace(name[0]))
168 strcpy(name, &name[1]);
169 aaa[strlen(aaa) - 1] = 0;
171 for (a = 0; a < strlen(aaa); ++a) {
173 strcpy(bbb, &aaa[a + 1]);
177 if (!strcasecmp(name, aaa))
182 /* Hit the Global Address Book */
183 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
187 lprintf(CTDL_INFO, "Mail is being forwarded to %s\n", 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;
530 if (content_type) if (strlen(content_type) > 0) {
531 regcomp(&re, content_type, 0);
534 /* Learn about the user and room in question */
535 getuser(&CC->user, CC->curr_user);
536 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
538 /* Load the message list */
539 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
541 msglist = (long *) cdbfr->ptr;
542 cdbfr->ptr = NULL; /* CtdlForEachMessage() now owns this memory */
543 num_msgs = cdbfr->len / sizeof(long);
546 return 0; /* No messages at all? No further action. */
551 * Now begin the traversal.
553 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
555 /* If the caller is looking for a specific MIME type, filter
556 * out all messages which are not of the type requested.
558 if (content_type != NULL) if (strlen(content_type) > 0) {
560 /* This call to GetMetaData() sits inside this loop
561 * so that we only do the extra database read per msg
562 * if we need to. Doing the extra read all the time
563 * really kills the server. If we ever need to use
564 * metadata for another search criterion, we need to
565 * move the read somewhere else -- but still be smart
566 * enough to only do the read if the caller has
567 * specified something that will need it.
569 GetMetaData(&smi, msglist[a]);
571 /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
572 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
578 num_msgs = sort_msglist(msglist, num_msgs);
580 /* If a template was supplied, filter out the messages which
581 * don't match. (This could induce some delays!)
584 if (compare != NULL) {
585 for (a = 0; a < num_msgs; ++a) {
586 msg = CtdlFetchMessage(msglist[a], 1);
588 if (CtdlMsgCmp(msg, compare)) {
591 CtdlFreeMessage(msg);
597 /* If a search string was specified, get a message list from
598 * the full text index and remove messages which aren't on both
602 * Since the lists are sorted and strictly ascending, and the
603 * output list is guaranteed to be shorter than or equal to the
604 * input list, we overwrite the bottom of the input list. This
605 * eliminates the need to memmove big chunks of the list over and
608 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
609 ft_search(&num_search_msgs, &search_msgs, search_string);
610 if (num_search_msgs > 0) {
614 orig_num_msgs = num_msgs;
616 for (i=0; i<orig_num_msgs; ++i) {
617 for (j=0; j<num_search_msgs; ++j) {
618 if (msglist[i] == search_msgs[j]) {
619 msglist[num_msgs++] = msglist[i];
625 num_msgs = 0; /* No messages qualify */
627 if (search_msgs != NULL) free(search_msgs);
629 /* Now that we've purged messages which don't contain the search
630 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
637 * Now iterate through the message list, according to the
638 * criteria supplied by the caller.
641 for (a = 0; a < num_msgs; ++a) {
642 thismsg = msglist[a];
643 if (mode == MSGS_ALL) {
647 is_seen = is_msg_in_sequence_set(
648 vbuf.v_seen, thismsg);
649 if (is_seen) lastold = thismsg;
655 || ((mode == MSGS_OLD) && (is_seen))
656 || ((mode == MSGS_NEW) && (!is_seen))
657 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
658 || ((mode == MSGS_FIRST) && (a < ref))
659 || ((mode == MSGS_GT) && (thismsg > ref))
660 || ((mode == MSGS_EQ) && (thismsg == ref))
663 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
665 CallBack(lastold, userdata);
669 if (CallBack) CallBack(thismsg, userdata);
673 free(msglist); /* Clean up */
674 return num_processed;
680 * cmd_msgs() - get list of message #'s in this room
681 * implements the MSGS server command using CtdlForEachMessage()
683 void cmd_msgs(char *cmdbuf)
692 int with_template = 0;
693 struct CtdlMessage *template = NULL;
694 int with_headers = 0;
695 char search_string[1024];
697 extract_token(which, cmdbuf, 0, '|', sizeof which);
698 cm_ref = extract_int(cmdbuf, 1);
699 extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
700 with_template = extract_int(cmdbuf, 2);
701 with_headers = extract_int(cmdbuf, 3);
704 if (!strncasecmp(which, "OLD", 3))
706 else if (!strncasecmp(which, "NEW", 3))
708 else if (!strncasecmp(which, "FIRST", 5))
710 else if (!strncasecmp(which, "LAST", 4))
712 else if (!strncasecmp(which, "GT", 2))
714 else if (!strncasecmp(which, "SEARCH", 6))
719 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
720 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
724 if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
725 cprintf("%d Full text index is not enabled on this server.\n",
726 ERROR + CMD_NOT_SUPPORTED);
732 cprintf("%d Send template then receive message list\n",
734 template = (struct CtdlMessage *)
735 malloc(sizeof(struct CtdlMessage));
736 memset(template, 0, sizeof(struct CtdlMessage));
737 template->cm_magic = CTDLMESSAGE_MAGIC;
738 template->cm_anon_type = MES_NORMAL;
740 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
741 extract_token(tfield, buf, 0, '|', sizeof tfield);
742 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
743 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
744 if (!strcasecmp(tfield, msgkeys[i])) {
745 template->cm_fields[i] =
753 cprintf("%d \n", LISTING_FOLLOWS);
756 CtdlForEachMessage(mode,
757 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
758 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
761 (with_headers ? headers_listing : simple_listing),
764 if (template != NULL) CtdlFreeMessage(template);
772 * help_subst() - support routine for help file viewer
774 void help_subst(char *strbuf, char *source, char *dest)
779 while (p = pattern2(strbuf, source), (p >= 0)) {
780 strcpy(workbuf, &strbuf[p + strlen(source)]);
781 strcpy(&strbuf[p], dest);
782 strcat(strbuf, workbuf);
787 void do_help_subst(char *buffer)
791 help_subst(buffer, "^nodename", config.c_nodename);
792 help_subst(buffer, "^humannode", config.c_humannode);
793 help_subst(buffer, "^fqdn", config.c_fqdn);
794 help_subst(buffer, "^username", CC->user.fullname);
795 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
796 help_subst(buffer, "^usernum", buf2);
797 help_subst(buffer, "^sysadm", config.c_sysadm);
798 help_subst(buffer, "^variantname", CITADEL);
799 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
800 help_subst(buffer, "^maxsessions", buf2);
801 help_subst(buffer, "^bbsdir", ctdl_bbsbase_dir);
807 * memfmout() - Citadel text formatter and paginator.
808 * Although the original purpose of this routine was to format
809 * text to the reader's screen width, all we're really using it
810 * for here is to format text out to 80 columns before sending it
811 * to the client. The client software may reformat it again.
814 char *mptr, /* where are we going to get our text from? */
815 char subst, /* nonzero if we should do substitutions */
816 char *nl) /* string to terminate lines with */
824 static int width = 80;
829 c = 1; /* c is the current pos */
833 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
835 buffer[strlen(buffer) + 1] = 0;
836 buffer[strlen(buffer)] = ch;
839 if (buffer[0] == '^')
840 do_help_subst(buffer);
842 buffer[strlen(buffer) + 1] = 0;
844 strcpy(buffer, &buffer[1]);
852 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
855 if (((old == 13) || (old == 10)) && (isspace(real))) {
860 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
861 cprintf("%s%s", nl, aaa);
870 if ((strlen(aaa) + c) > (width - 5)) {
879 if ((ch == 13) || (ch == 10)) {
880 cprintf("%s%s", aaa, nl);
887 cprintf("%s%s", aaa, nl);
893 * Callback function for mime parser that simply lists the part
895 void list_this_part(char *name, char *filename, char *partnum, char *disp,
896 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
901 ma = (struct ma_info *)cbuserdata;
902 if (ma->is_ma == 0) {
903 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
904 name, filename, partnum, disp, cbtype, (long)length);
909 * Callback function for multipart prefix
911 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
912 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
917 ma = (struct ma_info *)cbuserdata;
918 if (!strcasecmp(cbtype, "multipart/alternative")) {
922 if (ma->is_ma == 0) {
923 cprintf("pref=%s|%s\n", partnum, cbtype);
928 * Callback function for multipart sufffix
930 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
931 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
936 ma = (struct ma_info *)cbuserdata;
937 if (ma->is_ma == 0) {
938 cprintf("suff=%s|%s\n", partnum, cbtype);
940 if (!strcasecmp(cbtype, "multipart/alternative")) {
947 * Callback function for mime parser that opens a section for downloading
949 void mime_download(char *name, char *filename, char *partnum, char *disp,
950 void *content, char *cbtype, char *cbcharset, size_t length,
951 char *encoding, void *cbuserdata)
954 /* Silently go away if there's already a download open... */
955 if (CC->download_fp != NULL)
958 /* ...or if this is not the desired section */
959 if (strcasecmp(CC->download_desired_section, partnum))
962 CC->download_fp = tmpfile();
963 if (CC->download_fp == NULL)
966 fwrite(content, length, 1, CC->download_fp);
967 fflush(CC->download_fp);
968 rewind(CC->download_fp);
970 OpenCmdResult(filename, cbtype);
976 * Callback function for mime parser that outputs a section all at once
978 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
979 void *content, char *cbtype, char *cbcharset, size_t length,
980 char *encoding, void *cbuserdata)
982 int *found_it = (int *)cbuserdata;
984 /* ...or if this is not the desired section */
985 if (strcasecmp(CC->download_desired_section, partnum))
990 cprintf("%d %d\n", BINARY_FOLLOWS, length);
991 client_write(content, length);
997 * Load a message from disk into memory.
998 * This is used by CtdlOutputMsg() and other fetch functions.
1000 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1001 * using the CtdlMessageFree() function.
1003 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1005 struct cdbdata *dmsgtext;
1006 struct CtdlMessage *ret = NULL;
1010 cit_uint8_t field_header;
1012 lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1014 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1015 if (dmsgtext == NULL) {
1018 mptr = dmsgtext->ptr;
1019 upper_bound = mptr + dmsgtext->len;
1021 /* Parse the three bytes that begin EVERY message on disk.
1022 * The first is always 0xFF, the on-disk magic number.
1023 * The second is the anonymous/public type byte.
1024 * The third is the format type byte (vari, fixed, or MIME).
1029 "Message %ld appears to be corrupted.\n",
1034 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1035 memset(ret, 0, sizeof(struct CtdlMessage));
1037 ret->cm_magic = CTDLMESSAGE_MAGIC;
1038 ret->cm_anon_type = *mptr++; /* Anon type byte */
1039 ret->cm_format_type = *mptr++; /* Format type byte */
1042 * The rest is zero or more arbitrary fields. Load them in.
1043 * We're done when we encounter either a zero-length field or
1044 * have just processed the 'M' (message text) field.
1047 if (mptr >= upper_bound) {
1050 field_header = *mptr++;
1051 ret->cm_fields[field_header] = strdup(mptr);
1053 while (*mptr++ != 0); /* advance to next field */
1055 } while ((mptr < upper_bound) && (field_header != 'M'));
1059 /* Always make sure there's something in the msg text field. If
1060 * it's NULL, the message text is most likely stored separately,
1061 * so go ahead and fetch that. Failing that, just set a dummy
1062 * body so other code doesn't barf.
1064 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1065 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1066 if (dmsgtext != NULL) {
1067 ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1071 if (ret->cm_fields['M'] == NULL) {
1072 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1075 /* Perform "before read" hooks (aborting if any return nonzero) */
1076 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1077 CtdlFreeMessage(ret);
1086 * Returns 1 if the supplied pointer points to a valid Citadel message.
1087 * If the pointer is NULL or the magic number check fails, returns 0.
1089 int is_valid_message(struct CtdlMessage *msg) {
1092 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1093 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1101 * 'Destructor' for struct CtdlMessage
1103 void CtdlFreeMessage(struct CtdlMessage *msg)
1107 if (is_valid_message(msg) == 0)
1109 if (msg != NULL) free (msg);
1113 for (i = 0; i < 256; ++i)
1114 if (msg->cm_fields[i] != NULL) {
1115 free(msg->cm_fields[i]);
1118 msg->cm_magic = 0; /* just in case */
1124 * Pre callback function for multipart/alternative
1126 * NOTE: this differs from the standard behavior for a reason. Normally when
1127 * displaying multipart/alternative you want to show the _last_ usable
1128 * format in the message. Here we show the _first_ one, because it's
1129 * usually text/plain. Since this set of functions is designed for text
1130 * output to non-MIME-aware clients, this is the desired behavior.
1133 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1134 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1139 ma = (struct ma_info *)cbuserdata;
1140 lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1141 if (!strcasecmp(cbtype, "multipart/alternative")) {
1145 if (!strcasecmp(cbtype, "message/rfc822")) {
1151 * Post callback function for multipart/alternative
1153 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1154 void *content, char *cbtype, char *cbcharset, size_t length,
1155 char *encoding, void *cbuserdata)
1159 ma = (struct ma_info *)cbuserdata;
1160 lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1161 if (!strcasecmp(cbtype, "multipart/alternative")) {
1165 if (!strcasecmp(cbtype, "message/rfc822")) {
1171 * Inline callback function for mime parser that wants to display text
1173 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1174 void *content, char *cbtype, char *cbcharset, size_t length,
1175 char *encoding, void *cbuserdata)
1182 ma = (struct ma_info *)cbuserdata;
1185 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1186 partnum, filename, cbtype, (long)length);
1189 * If we're in the middle of a multipart/alternative scope and
1190 * we've already printed another section, skip this one.
1192 if ( (ma->is_ma) && (ma->did_print) ) {
1193 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1199 if ( (!strcasecmp(cbtype, "text/plain"))
1200 || (strlen(cbtype)==0) ) {
1203 client_write(wptr, length);
1204 if (wptr[length-1] != '\n') {
1211 if (!strcasecmp(cbtype, "text/html")) {
1212 ptr = html_to_ascii(content, length, 80, 0);
1214 client_write(ptr, wlen);
1215 if (ptr[wlen-1] != '\n') {
1222 if (ma->use_fo_hooks) {
1223 if (PerformFixedOutputHooks(cbtype, content, length)) {
1224 /* above function returns nonzero if it handled the part */
1229 if (strncasecmp(cbtype, "multipart/", 10)) {
1230 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1231 partnum, filename, cbtype, (long)length);
1237 * The client is elegant and sophisticated and wants to be choosy about
1238 * MIME content types, so figure out which multipart/alternative part
1239 * we're going to send.
1241 * We use a system of weights. When we find a part that matches one of the
1242 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1243 * and then set ma->chosen_pref to that MIME type's position in our preference
1244 * list. If we then hit another match, we only replace the first match if
1245 * the preference value is lower.
1247 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1248 void *content, char *cbtype, char *cbcharset, size_t length,
1249 char *encoding, void *cbuserdata)
1255 ma = (struct ma_info *)cbuserdata;
1257 if (ma->is_ma > 0) {
1258 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1259 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1260 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1261 if (i < ma->chosen_pref) {
1262 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1263 ma->chosen_pref = i;
1271 * Now that we've chosen our preferred part, output it.
1273 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1274 void *content, char *cbtype, char *cbcharset, size_t length,
1275 char *encoding, void *cbuserdata)
1279 int add_newline = 0;
1283 ma = (struct ma_info *)cbuserdata;
1285 /* This is not the MIME part you're looking for... */
1286 if (strcasecmp(partnum, ma->chosen_part)) return;
1288 /* If the content-type of this part is in our preferred formats
1289 * list, we can simply output it verbatim.
1291 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1292 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1293 if (!strcasecmp(buf, cbtype)) {
1294 /* Yeah! Go! W00t!! */
1296 text_content = (char *)content;
1297 if (text_content[length-1] != '\n') {
1300 cprintf("Content-type: %s", cbtype);
1301 if (strlen(cbcharset) > 0) {
1302 cprintf("; charset=%s", cbcharset);
1304 cprintf("\nContent-length: %d\n",
1305 (int)(length + add_newline) );
1306 if (strlen(encoding) > 0) {
1307 cprintf("Content-transfer-encoding: %s\n", encoding);
1310 cprintf("Content-transfer-encoding: 7bit\n");
1312 cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1314 client_write(content, length);
1315 if (add_newline) cprintf("\n");
1320 /* No translations required or possible: output as text/plain */
1321 cprintf("Content-type: text/plain\n\n");
1322 fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1323 length, encoding, cbuserdata);
1328 char desired_section[64];
1335 * Callback function for
1337 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1338 void *content, char *cbtype, char *cbcharset, size_t length,
1339 char *encoding, void *cbuserdata)
1341 struct encapmsg *encap;
1343 encap = (struct encapmsg *)cbuserdata;
1345 /* Only proceed if this is the desired section... */
1346 if (!strcasecmp(encap->desired_section, partnum)) {
1347 encap->msglen = length;
1348 encap->msg = malloc(length + 2);
1349 memcpy(encap->msg, content, length);
1359 * Get a message off disk. (returns om_* values found in msgbase.h)
1362 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1363 int mode, /* how would you like that message? */
1364 int headers_only, /* eschew the message body? */
1365 int do_proto, /* do Citadel protocol responses? */
1366 int crlf, /* Use CRLF newlines instead of LF? */
1367 char *section /* NULL or a message/rfc822 section */
1369 struct CtdlMessage *TheMessage = NULL;
1370 int retcode = om_no_such_msg;
1371 struct encapmsg encap;
1373 lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n",
1375 (section ? section : "<>")
1378 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1379 if (do_proto) cprintf("%d Not logged in.\n",
1380 ERROR + NOT_LOGGED_IN);
1381 return(om_not_logged_in);
1384 /* FIXME: check message id against msglist for this room */
1387 * Fetch the message from disk. If we're in any sort of headers
1388 * only mode, request that we don't even bother loading the body
1391 if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1392 TheMessage = CtdlFetchMessage(msg_num, 0);
1395 TheMessage = CtdlFetchMessage(msg_num, 1);
1398 if (TheMessage == NULL) {
1399 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1400 ERROR + MESSAGE_NOT_FOUND, msg_num);
1401 return(om_no_such_msg);
1404 /* Here is the weird form of this command, to process only an
1405 * encapsulated message/rfc822 section.
1407 if (section) if (strlen(section)>0) if (strcmp(section, "0")) {
1408 memset(&encap, 0, sizeof encap);
1409 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1410 mime_parser(TheMessage->cm_fields['M'],
1412 *extract_encapsulated_message,
1413 NULL, NULL, (void *)&encap, 0
1415 CtdlFreeMessage(TheMessage);
1419 encap.msg[encap.msglen] = 0;
1420 TheMessage = convert_internet_message(encap.msg);
1421 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1423 /* Now we let it fall through to the bottom of this
1424 * function, because TheMessage now contains the
1425 * encapsulated message instead of the top-level
1426 * message. Isn't that neat?
1431 if (do_proto) cprintf("%d msg %ld has no part %s\n",
1432 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1433 retcode = om_no_such_msg;
1438 /* Ok, output the message now */
1439 retcode = CtdlOutputPreLoadedMsg(
1441 headers_only, do_proto, crlf);
1442 CtdlFreeMessage(TheMessage);
1449 * Get a message off disk. (returns om_* values found in msgbase.h)
1452 int CtdlOutputPreLoadedMsg(
1453 struct CtdlMessage *TheMessage,
1454 int mode, /* how would you like that message? */
1455 int headers_only, /* eschew the message body? */
1456 int do_proto, /* do Citadel protocol responses? */
1457 int crlf /* Use CRLF newlines instead of LF? */
1463 char display_name[256];
1465 char *nl; /* newline string */
1467 int subject_found = 0;
1470 /* Buffers needed for RFC822 translation. These are all filled
1471 * using functions that are bounds-checked, and therefore we can
1472 * make them substantially smaller than SIZ.
1480 char datestamp[100];
1482 lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1483 ((TheMessage == NULL) ? "NULL" : "not null"),
1484 mode, headers_only, do_proto, crlf);
1486 strcpy(mid, "unknown");
1487 nl = (crlf ? "\r\n" : "\n");
1489 if (!is_valid_message(TheMessage)) {
1491 "ERROR: invalid preloaded message for output\n");
1492 return(om_no_such_msg);
1495 /* Are we downloading a MIME component? */
1496 if (mode == MT_DOWNLOAD) {
1497 if (TheMessage->cm_format_type != FMT_RFC822) {
1499 cprintf("%d This is not a MIME message.\n",
1500 ERROR + ILLEGAL_VALUE);
1501 } else if (CC->download_fp != NULL) {
1502 if (do_proto) cprintf(
1503 "%d You already have a download open.\n",
1504 ERROR + RESOURCE_BUSY);
1506 /* Parse the message text component */
1507 mptr = TheMessage->cm_fields['M'];
1508 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1509 /* If there's no file open by this time, the requested
1510 * section wasn't found, so print an error
1512 if (CC->download_fp == NULL) {
1513 if (do_proto) cprintf(
1514 "%d Section %s not found.\n",
1515 ERROR + FILE_NOT_FOUND,
1516 CC->download_desired_section);
1519 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1522 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
1523 * in a single server operation instead of opening a download file.
1525 if (mode == MT_SPEW_SECTION) {
1526 if (TheMessage->cm_format_type != FMT_RFC822) {
1528 cprintf("%d This is not a MIME message.\n",
1529 ERROR + ILLEGAL_VALUE);
1531 /* Parse the message text component */
1534 mptr = TheMessage->cm_fields['M'];
1535 mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
1536 /* If section wasn't found, print an error
1539 if (do_proto) cprintf(
1540 "%d Section %s not found.\n",
1541 ERROR + FILE_NOT_FOUND,
1542 CC->download_desired_section);
1545 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1548 /* now for the user-mode message reading loops */
1549 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1551 /* Does the caller want to skip the headers? */
1552 if (headers_only == HEADERS_NONE) goto START_TEXT;
1554 /* Tell the client which format type we're using. */
1555 if ( (mode == MT_CITADEL) && (do_proto) ) {
1556 cprintf("type=%d\n", TheMessage->cm_format_type);
1559 /* nhdr=yes means that we're only displaying headers, no body */
1560 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1561 && (mode == MT_CITADEL)
1564 cprintf("nhdr=yes\n");
1567 /* begin header processing loop for Citadel message format */
1569 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1571 safestrncpy(display_name, "<unknown>", sizeof display_name);
1572 if (TheMessage->cm_fields['A']) {
1573 strcpy(buf, TheMessage->cm_fields['A']);
1574 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1575 safestrncpy(display_name, "****", sizeof display_name);
1577 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1578 safestrncpy(display_name, "anonymous", sizeof display_name);
1581 safestrncpy(display_name, buf, sizeof display_name);
1583 if ((is_room_aide())
1584 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1585 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1586 size_t tmp = strlen(display_name);
1587 snprintf(&display_name[tmp],
1588 sizeof display_name - tmp,
1593 /* Don't show Internet address for users on the
1594 * local Citadel network.
1597 if (TheMessage->cm_fields['N'] != NULL)
1598 if (strlen(TheMessage->cm_fields['N']) > 0)
1599 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1603 /* Now spew the header fields in the order we like them. */
1604 safestrncpy(allkeys, FORDER, sizeof allkeys);
1605 for (i=0; i<strlen(allkeys); ++i) {
1606 k = (int) allkeys[i];
1608 if ( (TheMessage->cm_fields[k] != NULL)
1609 && (msgkeys[k] != NULL) ) {
1611 if (do_proto) cprintf("%s=%s\n",
1615 else if ((k == 'F') && (suppress_f)) {
1618 /* Masquerade display name if needed */
1620 if (do_proto) cprintf("%s=%s\n",
1622 TheMessage->cm_fields[k]
1631 /* begin header processing loop for RFC822 transfer format */
1636 strcpy(snode, NODENAME);
1637 strcpy(lnode, HUMANNODE);
1638 if (mode == MT_RFC822) {
1639 for (i = 0; i < 256; ++i) {
1640 if (TheMessage->cm_fields[i]) {
1641 mptr = TheMessage->cm_fields[i];
1644 safestrncpy(luser, mptr, sizeof luser);
1645 safestrncpy(suser, mptr, sizeof suser);
1647 else if (i == 'Y') {
1648 cprintf("CC: %s%s", mptr, nl);
1650 else if (i == 'P') {
1651 cprintf("Return-Path: %s%s", mptr, nl);
1653 else if (i == 'V') {
1654 cprintf("Envelope-To: %s%s", mptr, nl);
1656 else if (i == 'U') {
1657 cprintf("Subject: %s%s", mptr, nl);
1661 safestrncpy(mid, mptr, sizeof mid);
1663 safestrncpy(lnode, mptr, sizeof lnode);
1665 safestrncpy(fuser, mptr, sizeof fuser);
1666 /* else if (i == 'O')
1667 cprintf("X-Citadel-Room: %s%s",
1670 safestrncpy(snode, mptr, sizeof snode);
1672 cprintf("To: %s%s", mptr, nl);
1673 else if (i == 'T') {
1674 datestring(datestamp, sizeof datestamp,
1675 atol(mptr), DATESTRING_RFC822);
1676 cprintf("Date: %s%s", datestamp, nl);
1680 if (subject_found == 0) {
1681 cprintf("Subject: (no subject)%s", nl);
1685 for (i=0; i<strlen(suser); ++i) {
1686 suser[i] = tolower(suser[i]);
1687 if (!isalnum(suser[i])) suser[i]='_';
1690 if (mode == MT_RFC822) {
1691 if (!strcasecmp(snode, NODENAME)) {
1692 safestrncpy(snode, FQDN, sizeof snode);
1695 /* Construct a fun message id */
1696 cprintf("Message-ID: <%s", mid);
1697 if (strchr(mid, '@')==NULL) {
1698 cprintf("@%s", snode);
1702 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1703 cprintf("From: \"----\" <x@x.org>%s", nl);
1705 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1706 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1708 else if (strlen(fuser) > 0) {
1709 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1712 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1715 cprintf("Organization: %s%s", lnode, nl);
1717 /* Blank line signifying RFC822 end-of-headers */
1718 if (TheMessage->cm_format_type != FMT_RFC822) {
1723 /* end header processing loop ... at this point, we're in the text */
1725 if (headers_only == HEADERS_FAST) goto DONE;
1726 mptr = TheMessage->cm_fields['M'];
1728 /* Tell the client about the MIME parts in this message */
1729 if (TheMessage->cm_format_type == FMT_RFC822) {
1730 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1731 memset(&ma, 0, sizeof(struct ma_info));
1732 mime_parser(mptr, NULL,
1733 (do_proto ? *list_this_part : NULL),
1734 (do_proto ? *list_this_pref : NULL),
1735 (do_proto ? *list_this_suff : NULL),
1738 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1739 char *start_of_text = NULL;
1740 start_of_text = strstr(mptr, "\n\r\n");
1741 if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1742 if (start_of_text == NULL) start_of_text = mptr;
1744 start_of_text = strstr(start_of_text, "\n");
1749 int nllen = strlen(nl);
1750 while (ch=*mptr, ch!=0) {
1756 ((headers_only == HEADERS_NONE) && (mptr >= start_of_text))
1757 || ((headers_only == HEADERS_ONLY) && (mptr < start_of_text))
1758 || ((headers_only != HEADERS_NONE) && (headers_only != HEADERS_ONLY))
1761 sprintf(&outbuf[outlen], "%s", nl);
1765 outbuf[outlen++] = ch;
1770 if (outlen > 1000) {
1771 client_write(outbuf, outlen);
1776 client_write(outbuf, outlen);
1784 if (headers_only == HEADERS_ONLY) {
1788 /* signify start of msg text */
1789 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1790 if (do_proto) cprintf("text\n");
1793 /* If the format type on disk is 1 (fixed-format), then we want
1794 * everything to be output completely literally ... regardless of
1795 * what message transfer format is in use.
1797 if (TheMessage->cm_format_type == FMT_FIXED) {
1798 if (mode == MT_MIME) {
1799 cprintf("Content-type: text/plain\n\n");
1802 while (ch = *mptr++, ch > 0) {
1805 if ((ch == 10) || (strlen(buf) > 250)) {
1806 cprintf("%s%s", buf, nl);
1809 buf[strlen(buf) + 1] = 0;
1810 buf[strlen(buf)] = ch;
1813 if (strlen(buf) > 0)
1814 cprintf("%s%s", buf, nl);
1817 /* If the message on disk is format 0 (Citadel vari-format), we
1818 * output using the formatter at 80 columns. This is the final output
1819 * form if the transfer format is RFC822, but if the transfer format
1820 * is Citadel proprietary, it'll still work, because the indentation
1821 * for new paragraphs is correct and the client will reformat the
1822 * message to the reader's screen width.
1824 if (TheMessage->cm_format_type == FMT_CITADEL) {
1825 if (mode == MT_MIME) {
1826 cprintf("Content-type: text/x-citadel-variformat\n\n");
1828 memfmout(mptr, 0, nl);
1831 /* If the message on disk is format 4 (MIME), we've gotta hand it
1832 * off to the MIME parser. The client has already been told that
1833 * this message is format 1 (fixed format), so the callback function
1834 * we use will display those parts as-is.
1836 if (TheMessage->cm_format_type == FMT_RFC822) {
1837 memset(&ma, 0, sizeof(struct ma_info));
1839 if (mode == MT_MIME) {
1840 ma.use_fo_hooks = 0;
1841 strcpy(ma.chosen_part, "1");
1842 ma.chosen_pref = 9999;
1843 mime_parser(mptr, NULL,
1844 *choose_preferred, *fixed_output_pre,
1845 *fixed_output_post, (void *)&ma, 0);
1846 mime_parser(mptr, NULL,
1847 *output_preferred, NULL, NULL, (void *)&ma, 0);
1850 ma.use_fo_hooks = 1;
1851 mime_parser(mptr, NULL,
1852 *fixed_output, *fixed_output_pre,
1853 *fixed_output_post, (void *)&ma, 0);
1858 DONE: /* now we're done */
1859 if (do_proto) cprintf("000\n");
1866 * display a message (mode 0 - Citadel proprietary)
1868 void cmd_msg0(char *cmdbuf)
1871 int headers_only = HEADERS_ALL;
1873 msgid = extract_long(cmdbuf, 0);
1874 headers_only = extract_int(cmdbuf, 1);
1876 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1882 * display a message (mode 2 - RFC822)
1884 void cmd_msg2(char *cmdbuf)
1887 int headers_only = HEADERS_ALL;
1889 msgid = extract_long(cmdbuf, 0);
1890 headers_only = extract_int(cmdbuf, 1);
1892 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1898 * display a message (mode 3 - IGnet raw format - internal programs only)
1900 void cmd_msg3(char *cmdbuf)
1903 struct CtdlMessage *msg = NULL;
1906 if (CC->internal_pgm == 0) {
1907 cprintf("%d This command is for internal programs only.\n",
1908 ERROR + HIGHER_ACCESS_REQUIRED);
1912 msgnum = extract_long(cmdbuf, 0);
1913 msg = CtdlFetchMessage(msgnum, 1);
1915 cprintf("%d Message %ld not found.\n",
1916 ERROR + MESSAGE_NOT_FOUND, msgnum);
1920 serialize_message(&smr, msg);
1921 CtdlFreeMessage(msg);
1924 cprintf("%d Unable to serialize message\n",
1925 ERROR + INTERNAL_ERROR);
1929 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1930 client_write((char *)smr.ser, (int)smr.len);
1937 * Display a message using MIME content types
1939 void cmd_msg4(char *cmdbuf)
1944 msgid = extract_long(cmdbuf, 0);
1945 extract_token(section, cmdbuf, 1, '|', sizeof section);
1946 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1952 * Client tells us its preferred message format(s)
1954 void cmd_msgp(char *cmdbuf)
1956 safestrncpy(CC->preferred_formats, cmdbuf,
1957 sizeof(CC->preferred_formats));
1958 cprintf("%d ok\n", CIT_OK);
1963 * Open a component of a MIME message as a download file
1965 void cmd_opna(char *cmdbuf)
1968 char desired_section[128];
1970 msgid = extract_long(cmdbuf, 0);
1971 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1972 safestrncpy(CC->download_desired_section, desired_section,
1973 sizeof CC->download_desired_section);
1974 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
1979 * Open a component of a MIME message and transmit it all at once
1981 void cmd_dlat(char *cmdbuf)
1984 char desired_section[128];
1986 msgid = extract_long(cmdbuf, 0);
1987 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1988 safestrncpy(CC->download_desired_section, desired_section,
1989 sizeof CC->download_desired_section);
1990 CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL);
1995 * Save one or more message pointers into a specified room
1996 * (Returns 0 for success, nonzero for failure)
1997 * roomname may be NULL to use the current room
1999 * Note that the 'supplied_msg' field may be set to NULL, in which case
2000 * the message will be fetched from disk, by number, if we need to perform
2001 * replication checks. This adds an additional database read, so if the
2002 * caller already has the message in memory then it should be supplied. (Obviously
2003 * this mode of operation only works if we're saving a single message.)
2005 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2006 int do_repl_check, struct CtdlMessage *supplied_msg)
2009 char hold_rm[ROOMNAMELEN];
2010 struct cdbdata *cdbfr;
2013 long highest_msg = 0L;
2016 struct CtdlMessage *msg = NULL;
2018 long *msgs_to_be_merged = NULL;
2019 int num_msgs_to_be_merged = 0;
2022 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d)\n",
2023 roomname, num_newmsgs, do_repl_check);
2025 strcpy(hold_rm, CC->room.QRname);
2028 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2029 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2030 if (num_newmsgs > 1) supplied_msg = NULL;
2032 /* Now the regular stuff */
2033 if (lgetroom(&CC->room,
2034 ((roomname != NULL) ? roomname : CC->room.QRname) )
2036 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
2037 return(ERROR + ROOM_NOT_FOUND);
2041 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2042 num_msgs_to_be_merged = 0;
2045 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2046 if (cdbfr == NULL) {
2050 msglist = (long *) cdbfr->ptr;
2051 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2052 num_msgs = cdbfr->len / sizeof(long);
2057 /* Create a list of msgid's which were supplied by the caller, but do
2058 * not already exist in the target room. It is absolutely taboo to
2059 * have more than one reference to the same message in a room.
2061 for (i=0; i<num_newmsgs; ++i) {
2063 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2064 if (msglist[j] == newmsgidlist[i]) {
2069 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2073 lprintf(9, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2076 * Now merge the new messages
2078 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2079 if (msglist == NULL) {
2080 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
2082 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2083 num_msgs += num_msgs_to_be_merged;
2085 /* Sort the message list, so all the msgid's are in order */
2086 num_msgs = sort_msglist(msglist, num_msgs);
2088 /* Determine the highest message number */
2089 highest_msg = msglist[num_msgs - 1];
2091 /* Write it back to disk. */
2092 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2093 msglist, (int)(num_msgs * sizeof(long)));
2095 /* Free up the memory we used. */
2098 /* Update the highest-message pointer and unlock the room. */
2099 CC->room.QRhighest = highest_msg;
2100 lputroom(&CC->room);
2102 /* Perform replication checks if necessary */
2103 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2104 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2106 for (i=0; i<num_msgs_to_be_merged; ++i) {
2107 msgid = msgs_to_be_merged[i];
2109 if (supplied_msg != NULL) {
2113 msg = CtdlFetchMessage(msgid, 0);
2117 ReplicationChecks(msg);
2119 /* If the message has an Exclusive ID, index that... */
2120 if (msg->cm_fields['E'] != NULL) {
2121 index_message_by_euid(msg->cm_fields['E'], &CC->room, msgid);
2124 /* Free up the memory we may have allocated */
2125 if (msg != supplied_msg) {
2126 CtdlFreeMessage(msg);
2134 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2137 /* Submit this room for net processing */
2138 network_queue_room(&CC->room, NULL);
2140 #ifdef HAVE_LIBSIEVE
2141 /* If this is someone's inbox, submit the room for sieve processing */
2142 if (!strcasecmp(&CC->room.QRname[11], MAILROOM)) {
2143 sieve_queue_room(&CC->room);
2145 #endif /* HAVE_LIBSIEVE */
2147 /* Go back to the room we were in before we wandered here... */
2148 getroom(&CC->room, hold_rm);
2150 /* Bump the reference count for all messages which were merged */
2151 for (i=0; i<num_msgs_to_be_merged; ++i) {
2152 AdjRefCount(msgs_to_be_merged[i], +1);
2155 /* Free up memory... */
2156 if (msgs_to_be_merged != NULL) {
2157 free(msgs_to_be_merged);
2160 /* Return success. */
2166 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2169 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2170 int do_repl_check, struct CtdlMessage *supplied_msg)
2172 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg);
2179 * Message base operation to save a new message to the message store
2180 * (returns new message number)
2182 * This is the back end for CtdlSubmitMsg() and should not be directly
2183 * called by server-side modules.
2186 long send_message(struct CtdlMessage *msg) {
2194 /* Get a new message number */
2195 newmsgid = get_new_message_number();
2196 snprintf(msgidbuf, sizeof msgidbuf, "%010ld@%s", newmsgid, config.c_fqdn);
2198 /* Generate an ID if we don't have one already */
2199 if (msg->cm_fields['I']==NULL) {
2200 msg->cm_fields['I'] = strdup(msgidbuf);
2203 /* If the message is big, set its body aside for storage elsewhere */
2204 if (msg->cm_fields['M'] != NULL) {
2205 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2207 holdM = msg->cm_fields['M'];
2208 msg->cm_fields['M'] = NULL;
2212 /* Serialize our data structure for storage in the database */
2213 serialize_message(&smr, msg);
2216 msg->cm_fields['M'] = holdM;
2220 cprintf("%d Unable to serialize message\n",
2221 ERROR + INTERNAL_ERROR);
2225 /* Write our little bundle of joy into the message base */
2226 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2227 smr.ser, smr.len) < 0) {
2228 lprintf(CTDL_ERR, "Can't store message\n");
2232 cdb_store(CDB_BIGMSGS,
2242 /* Free the memory we used for the serialized message */
2245 /* Return the *local* message ID to the caller
2246 * (even if we're storing an incoming network message)
2254 * Serialize a struct CtdlMessage into the format used on disk and network.
2256 * This function loads up a "struct ser_ret" (defined in server.h) which
2257 * contains the length of the serialized message and a pointer to the
2258 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2260 void serialize_message(struct ser_ret *ret, /* return values */
2261 struct CtdlMessage *msg) /* unserialized msg */
2263 size_t wlen, fieldlen;
2265 static char *forder = FORDER;
2268 * Check for valid message format
2270 if (is_valid_message(msg) == 0) {
2271 lprintf(CTDL_ERR, "serialize_message() aborting due to invalid message\n");
2278 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2279 ret->len = ret->len +
2280 strlen(msg->cm_fields[(int)forder[i]]) + 2;
2282 ret->ser = malloc(ret->len);
2283 if (ret->ser == NULL) {
2284 lprintf(CTDL_ERR, "serialize_message() malloc(%ld) failed: %s\n",
2285 (long)ret->len, strerror(errno));
2292 ret->ser[1] = msg->cm_anon_type;
2293 ret->ser[2] = msg->cm_format_type;
2296 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2297 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
2298 ret->ser[wlen++] = (char)forder[i];
2299 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
2300 wlen = wlen + fieldlen + 1;
2302 if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2303 (long)ret->len, (long)wlen);
2311 * Check to see if any messages already exist in the current room which
2312 * carry the same Exclusive ID as this one. If any are found, delete them.
2314 void ReplicationChecks(struct CtdlMessage *msg) {
2315 long old_msgnum = (-1L);
2317 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2319 lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2322 /* No exclusive id? Don't do anything. */
2323 if (msg == NULL) return;
2324 if (msg->cm_fields['E'] == NULL) return;
2325 if (strlen(msg->cm_fields['E']) == 0) return;
2326 /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2327 msg->cm_fields['E'], CC->room.QRname);*/
2329 old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2330 if (old_msgnum > 0L) {
2331 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2332 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2339 * Save a message to disk and submit it into the delivery system.
2341 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2342 struct recptypes *recps, /* recipients (if mail) */
2343 char *force /* force a particular room? */
2345 char submit_filename[128];
2346 char generated_timestamp[32];
2347 char hold_rm[ROOMNAMELEN];
2348 char actual_rm[ROOMNAMELEN];
2349 char force_room[ROOMNAMELEN];
2350 char content_type[SIZ]; /* We have to learn this */
2351 char recipient[SIZ];
2354 struct ctdluser userbuf;
2356 struct MetaData smi;
2357 FILE *network_fp = NULL;
2358 static int seqnum = 1;
2359 struct CtdlMessage *imsg = NULL;
2362 char *hold_R, *hold_D;
2363 char *collected_addresses = NULL;
2364 struct addresses_to_be_filed *aptr = NULL;
2365 char *saved_rfc822_version = NULL;
2366 int qualified_for_journaling = 0;
2368 lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2369 if (is_valid_message(msg) == 0) return(-1); /* self check */
2371 /* If this message has no timestamp, we take the liberty of
2372 * giving it one, right now.
2374 if (msg->cm_fields['T'] == NULL) {
2375 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2376 msg->cm_fields['T'] = strdup(generated_timestamp);
2379 /* If this message has no path, we generate one.
2381 if (msg->cm_fields['P'] == NULL) {
2382 if (msg->cm_fields['A'] != NULL) {
2383 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2384 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
2385 if (isspace(msg->cm_fields['P'][a])) {
2386 msg->cm_fields['P'][a] = ' ';
2391 msg->cm_fields['P'] = strdup("unknown");
2395 if (force == NULL) {
2396 strcpy(force_room, "");
2399 strcpy(force_room, force);
2402 /* Learn about what's inside, because it's what's inside that counts */
2403 if (msg->cm_fields['M'] == NULL) {
2404 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2408 switch (msg->cm_format_type) {
2410 strcpy(content_type, "text/x-citadel-variformat");
2413 strcpy(content_type, "text/plain");
2416 strcpy(content_type, "text/plain");
2417 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type:");
2419 safestrncpy(content_type, &mptr[13], sizeof content_type);
2420 striplt(content_type);
2421 for (a = 0; a < strlen(content_type); ++a) {
2422 if ((content_type[a] == ';')
2423 || (content_type[a] == ' ')
2424 || (content_type[a] == 13)
2425 || (content_type[a] == 10)) {
2426 content_type[a] = 0;
2432 /* Goto the correct room */
2433 lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CC->room.QRname : SENTITEMS);
2434 strcpy(hold_rm, CC->room.QRname);
2435 strcpy(actual_rm, CC->room.QRname);
2436 if (recps != NULL) {
2437 strcpy(actual_rm, SENTITEMS);
2440 /* If the user is a twit, move to the twit room for posting */
2442 if (CC->user.axlevel == 2) {
2443 strcpy(hold_rm, actual_rm);
2444 strcpy(actual_rm, config.c_twitroom);
2445 lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2449 /* ...or if this message is destined for Aide> then go there. */
2450 if (strlen(force_room) > 0) {
2451 strcpy(actual_rm, force_room);
2454 lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2455 if (strcasecmp(actual_rm, CC->room.QRname)) {
2456 /* getroom(&CC->room, actual_rm); */
2457 usergoto(actual_rm, 0, 1, NULL, NULL);
2461 * If this message has no O (room) field, generate one.
2463 if (msg->cm_fields['O'] == NULL) {
2464 msg->cm_fields['O'] = strdup(CC->room.QRname);
2467 /* Perform "before save" hooks (aborting if any return nonzero) */
2468 lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2469 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2472 * If this message has an Exclusive ID, and the room is replication
2473 * checking enabled, then do replication checks.
2475 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2476 ReplicationChecks(msg);
2479 /* Save it to disk */
2480 lprintf(CTDL_DEBUG, "Saving to disk\n");
2481 newmsgid = send_message(msg);
2482 if (newmsgid <= 0L) return(-5);
2484 /* Write a supplemental message info record. This doesn't have to
2485 * be a critical section because nobody else knows about this message
2488 lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2489 memset(&smi, 0, sizeof(struct MetaData));
2490 smi.meta_msgnum = newmsgid;
2491 smi.meta_refcount = 0;
2492 safestrncpy(smi.meta_content_type, content_type,
2493 sizeof smi.meta_content_type);
2496 * Measure how big this message will be when rendered as RFC822.
2497 * We do this for two reasons:
2498 * 1. We need the RFC822 length for the new metadata record, so the
2499 * POP and IMAP services don't have to calculate message lengths
2500 * while the user is waiting (multiplied by potentially hundreds
2501 * or thousands of messages).
2502 * 2. If journaling is enabled, we will need an RFC822 version of the
2503 * message to attach to the journalized copy.
2505 if (CC->redirect_buffer != NULL) {
2506 lprintf(CTDL_ALERT, "CC->redirect_buffer is not NULL during message submission!\n");
2509 CC->redirect_buffer = malloc(SIZ);
2510 CC->redirect_len = 0;
2511 CC->redirect_alloc = SIZ;
2512 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2513 smi.meta_rfc822_length = CC->redirect_len;
2514 saved_rfc822_version = CC->redirect_buffer;
2515 CC->redirect_buffer = NULL;
2516 CC->redirect_len = 0;
2517 CC->redirect_alloc = 0;
2521 /* Now figure out where to store the pointers */
2522 lprintf(CTDL_DEBUG, "Storing pointers\n");
2524 /* If this is being done by the networker delivering a private
2525 * message, we want to BYPASS saving the sender's copy (because there
2526 * is no local sender; it would otherwise go to the Trashcan).
2528 if ((!CC->internal_pgm) || (recps == NULL)) {
2529 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2530 lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2531 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2535 /* For internet mail, drop a copy in the outbound queue room */
2537 if (recps->num_internet > 0) {
2538 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2541 /* If other rooms are specified, drop them there too. */
2543 if (recps->num_room > 0)
2544 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2545 extract_token(recipient, recps->recp_room, i,
2546 '|', sizeof recipient);
2547 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2548 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2551 /* Bump this user's messages posted counter. */
2552 lprintf(CTDL_DEBUG, "Updating user\n");
2553 lgetuser(&CC->user, CC->curr_user);
2554 CC->user.posted = CC->user.posted + 1;
2555 lputuser(&CC->user);
2557 /* If this is private, local mail, make a copy in the
2558 * recipient's mailbox and bump the reference count.
2561 if (recps->num_local > 0)
2562 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2563 extract_token(recipient, recps->recp_local, i,
2564 '|', sizeof recipient);
2565 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2567 if (getuser(&userbuf, recipient) == 0) {
2568 // Add a flag so the Funambol module knows its mail
2569 msg->cm_fields['W'] = strdup(recipient);
2570 MailboxName(actual_rm, sizeof actual_rm,
2571 &userbuf, MAILROOM);
2572 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2573 BumpNewMailCounter(userbuf.usernum);
2574 if (strlen(config.c_funambol_host) > 0) {
2575 /* Generate a instruction message for the Funambol notification
2576 server, in the same style as the SMTP queue */
2577 instr = malloc(SIZ * 2);
2578 snprintf(instr, SIZ * 2,
2579 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2581 SPOOLMIME, newmsgid, (long)time(NULL),
2582 msg->cm_fields['A'], msg->cm_fields['N']
2585 imsg = malloc(sizeof(struct CtdlMessage));
2586 memset(imsg, 0, sizeof(struct CtdlMessage));
2587 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2588 imsg->cm_anon_type = MES_NORMAL;
2589 imsg->cm_format_type = FMT_RFC822;
2590 imsg->cm_fields['A'] = strdup("Citadel");
2591 imsg->cm_fields['J'] = strdup("do not journal");
2592 imsg->cm_fields['M'] = instr;
2593 imsg->cm_fields['W'] = strdup(recipient);
2594 CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM);
2595 CtdlFreeMessage(imsg);
2599 lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2600 CtdlSaveMsgPointerInRoom(config.c_aideroom,
2605 /* Perform "after save" hooks */
2606 lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2607 PerformMessageHooks(msg, EVT_AFTERSAVE);
2609 /* For IGnet mail, we have to save a new copy into the spooler for
2610 * each recipient, with the R and D fields set to the recipient and
2611 * destination-node. This has two ugly side effects: all other
2612 * recipients end up being unlisted in this recipient's copy of the
2613 * message, and it has to deliver multiple messages to the same
2614 * node. We'll revisit this again in a year or so when everyone has
2615 * a network spool receiver that can handle the new style messages.
2618 if (recps->num_ignet > 0)
2619 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2620 extract_token(recipient, recps->recp_ignet, i,
2621 '|', sizeof recipient);
2623 hold_R = msg->cm_fields['R'];
2624 hold_D = msg->cm_fields['D'];
2625 msg->cm_fields['R'] = malloc(SIZ);
2626 msg->cm_fields['D'] = malloc(128);
2627 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2628 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2630 serialize_message(&smr, msg);
2632 snprintf(submit_filename, sizeof submit_filename,
2633 "%s/netmail.%04lx.%04x.%04x",
2635 (long) getpid(), CC->cs_pid, ++seqnum);
2636 network_fp = fopen(submit_filename, "wb+");
2637 if (network_fp != NULL) {
2638 fwrite(smr.ser, smr.len, 1, network_fp);
2644 free(msg->cm_fields['R']);
2645 free(msg->cm_fields['D']);
2646 msg->cm_fields['R'] = hold_R;
2647 msg->cm_fields['D'] = hold_D;
2650 /* Go back to the room we started from */
2651 lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2652 if (strcasecmp(hold_rm, CC->room.QRname))
2653 /* getroom(&CC->room, hold_rm); */
2654 usergoto(hold_rm, 0, 1, NULL, NULL);
2656 /* For internet mail, generate delivery instructions.
2657 * Yes, this is recursive. Deal with it. Infinite recursion does
2658 * not happen because the delivery instructions message does not
2659 * contain a recipient.
2662 if (recps->num_internet > 0) {
2663 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2664 instr = malloc(SIZ * 2);
2665 snprintf(instr, SIZ * 2,
2666 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2668 SPOOLMIME, newmsgid, (long)time(NULL),
2669 msg->cm_fields['A'], msg->cm_fields['N']
2672 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2673 size_t tmp = strlen(instr);
2674 extract_token(recipient, recps->recp_internet,
2675 i, '|', sizeof recipient);
2676 snprintf(&instr[tmp], SIZ * 2 - tmp,
2677 "remote|%s|0||\n", recipient);
2680 imsg = malloc(sizeof(struct CtdlMessage));
2681 memset(imsg, 0, sizeof(struct CtdlMessage));
2682 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2683 imsg->cm_anon_type = MES_NORMAL;
2684 imsg->cm_format_type = FMT_RFC822;
2685 imsg->cm_fields['A'] = strdup("Citadel");
2686 imsg->cm_fields['J'] = strdup("do not journal");
2687 imsg->cm_fields['M'] = instr;
2688 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2689 CtdlFreeMessage(imsg);
2693 * Any addresses to harvest for someone's address book?
2695 if ( (CC->logged_in) && (recps != NULL) ) {
2696 collected_addresses = harvest_collected_addresses(msg);
2699 if (collected_addresses != NULL) {
2700 begin_critical_section(S_ATBF);
2701 aptr = (struct addresses_to_be_filed *)
2702 malloc(sizeof(struct addresses_to_be_filed));
2704 MailboxName(actual_rm, sizeof actual_rm,
2705 &CC->user, USERCONTACTSROOM);
2706 aptr->roomname = strdup(actual_rm);
2707 aptr->collected_addresses = collected_addresses;
2709 end_critical_section(S_ATBF);
2713 * Determine whether this message qualifies for journaling.
2715 if (msg->cm_fields['J'] != NULL) {
2716 qualified_for_journaling = 0;
2719 if (recps == NULL) {
2720 qualified_for_journaling = config.c_journal_pubmsgs;
2722 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2723 qualified_for_journaling = config.c_journal_email;
2726 qualified_for_journaling = config.c_journal_pubmsgs;
2731 * Do we have to perform journaling? If so, hand off the saved
2732 * RFC822 version will be handed off to the journaler for background
2733 * submit. Otherwise, we have to free the memory ourselves.
2735 if (saved_rfc822_version != NULL) {
2736 if (qualified_for_journaling) {
2737 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2740 free(saved_rfc822_version);
2753 * Convenience function for generating small administrative messages.
2755 void quickie_message(char *from, char *fromaddr, char *to, char *room, char *text,
2756 int format_type, char *subject)
2758 struct CtdlMessage *msg;
2759 struct recptypes *recp = NULL;
2761 msg = malloc(sizeof(struct CtdlMessage));
2762 memset(msg, 0, sizeof(struct CtdlMessage));
2763 msg->cm_magic = CTDLMESSAGE_MAGIC;
2764 msg->cm_anon_type = MES_NORMAL;
2765 msg->cm_format_type = format_type;
2768 msg->cm_fields['A'] = strdup(from);
2770 else if (fromaddr != NULL) {
2771 msg->cm_fields['A'] = strdup(fromaddr);
2772 if (strchr(msg->cm_fields['A'], '@')) {
2773 *strchr(msg->cm_fields['A'], '@') = 0;
2777 msg->cm_fields['A'] = strdup("Citadel");
2780 if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
2781 if (room != NULL) msg->cm_fields['O'] = strdup(room);
2782 msg->cm_fields['N'] = strdup(NODENAME);
2784 msg->cm_fields['R'] = strdup(to);
2785 recp = validate_recipients(to);
2787 if (subject != NULL) {
2788 msg->cm_fields['U'] = strdup(subject);
2790 msg->cm_fields['M'] = strdup(text);
2792 CtdlSubmitMsg(msg, recp, room);
2793 CtdlFreeMessage(msg);
2794 if (recp != NULL) free_recipients(recp);
2800 * Back end function used by CtdlMakeMessage() and similar functions
2802 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2803 size_t maxlen, /* maximum message length */
2804 char *exist, /* if non-null, append to it;
2805 exist is ALWAYS freed */
2806 int crlf /* CRLF newlines instead of LF */
2810 size_t message_len = 0;
2811 size_t buffer_len = 0;
2818 if (exist == NULL) {
2825 message_len = strlen(exist);
2826 buffer_len = message_len + 4096;
2827 m = realloc(exist, buffer_len);
2834 /* Do we need to change leading ".." to "." for SMTP escaping? */
2835 if (!strcmp(terminator, ".")) {
2839 /* flush the input if we have nowhere to store it */
2844 /* read in the lines of message text one by one */
2846 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2847 if (!strcmp(buf, terminator)) finished = 1;
2849 strcat(buf, "\r\n");
2855 /* Unescape SMTP-style input of two dots at the beginning of the line */
2857 if (!strncmp(buf, "..", 2)) {
2858 strcpy(buf, &buf[1]);
2862 if ( (!flushing) && (!finished) ) {
2863 /* Measure the line */
2864 linelen = strlen(buf);
2866 /* augment the buffer if we have to */
2867 if ((message_len + linelen) >= buffer_len) {
2868 ptr = realloc(m, (buffer_len * 2) );
2869 if (ptr == NULL) { /* flush if can't allocate */
2872 buffer_len = (buffer_len * 2);
2874 lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2878 /* Add the new line to the buffer. NOTE: this loop must avoid
2879 * using functions like strcat() and strlen() because they
2880 * traverse the entire buffer upon every call, and doing that
2881 * for a multi-megabyte message slows it down beyond usability.
2883 strcpy(&m[message_len], buf);
2884 message_len += linelen;
2887 /* if we've hit the max msg length, flush the rest */
2888 if (message_len >= maxlen) flushing = 1;
2890 } while (!finished);
2898 * Build a binary message to be saved on disk.
2899 * (NOTE: if you supply 'preformatted_text', the buffer you give it
2900 * will become part of the message. This means you are no longer
2901 * responsible for managing that memory -- it will be freed along with
2902 * the rest of the fields when CtdlFreeMessage() is called.)
2905 struct CtdlMessage *CtdlMakeMessage(
2906 struct ctdluser *author, /* author's user structure */
2907 char *recipient, /* NULL if it's not mail */
2908 char *recp_cc, /* NULL if it's not mail */
2909 char *room, /* room where it's going */
2910 int type, /* see MES_ types in header file */
2911 int format_type, /* variformat, plain text, MIME... */
2912 char *fake_name, /* who we're masquerading as */
2913 char *my_email, /* which of my email addresses to use (empty is ok) */
2914 char *subject, /* Subject (optional) */
2915 char *supplied_euid, /* ...or NULL if this is irrelevant */
2916 char *preformatted_text /* ...or NULL to read text from client */
2918 char dest_node[256];
2920 struct CtdlMessage *msg;
2922 msg = malloc(sizeof(struct CtdlMessage));
2923 memset(msg, 0, sizeof(struct CtdlMessage));
2924 msg->cm_magic = CTDLMESSAGE_MAGIC;
2925 msg->cm_anon_type = type;
2926 msg->cm_format_type = format_type;
2928 /* Don't confuse the poor folks if it's not routed mail. */
2929 strcpy(dest_node, "");
2934 snprintf(buf, sizeof buf, "cit%ld", author->usernum); /* Path */
2935 msg->cm_fields['P'] = strdup(buf);
2937 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
2938 msg->cm_fields['T'] = strdup(buf);
2940 if (fake_name[0]) /* author */
2941 msg->cm_fields['A'] = strdup(fake_name);
2943 msg->cm_fields['A'] = strdup(author->fullname);
2945 if (CC->room.QRflags & QR_MAILBOX) { /* room */
2946 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2949 msg->cm_fields['O'] = strdup(CC->room.QRname);
2952 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
2953 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
2955 if (recipient[0] != 0) {
2956 msg->cm_fields['R'] = strdup(recipient);
2958 if (recp_cc[0] != 0) {
2959 msg->cm_fields['Y'] = strdup(recp_cc);
2961 if (dest_node[0] != 0) {
2962 msg->cm_fields['D'] = strdup(dest_node);
2965 if (strlen(my_email) > 0) {
2966 msg->cm_fields['F'] = strdup(my_email);
2968 else if ( (author == &CC->user) && (strlen(CC->cs_inet_email) > 0) ) {
2969 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2972 if (subject != NULL) {
2975 length = strlen(subject);
2981 while ((subject[i] != '\0') &&
2982 (IsAscii = isascii(subject[i]) != 0 ))
2985 msg->cm_fields['U'] = strdup(subject);
2986 else /* ok, we've got utf8 in the string. */
2988 msg->cm_fields['U'] = rfc2047encode(subject, length);
2994 if (supplied_euid != NULL) {
2995 msg->cm_fields['E'] = strdup(supplied_euid);
2998 if (preformatted_text != NULL) {
2999 msg->cm_fields['M'] = preformatted_text;
3002 msg->cm_fields['M'] = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0);
3010 * Check to see whether we have permission to post a message in the current
3011 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
3012 * returns 0 on success.
3014 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
3017 if (!(CC->logged_in)) {
3018 snprintf(errmsgbuf, n, "Not logged in.");
3019 return (ERROR + NOT_LOGGED_IN);
3022 if ((CC->user.axlevel < 2)
3023 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
3024 snprintf(errmsgbuf, n, "Need to be validated to enter "
3025 "(except in %s> to sysop)", MAILROOM);
3026 return (ERROR + HIGHER_ACCESS_REQUIRED);
3029 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3030 if (!(ra & UA_POSTALLOWED)) {
3031 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
3032 return (ERROR + HIGHER_ACCESS_REQUIRED);
3035 strcpy(errmsgbuf, "Ok");
3041 * Check to see if the specified user has Internet mail permission
3042 * (returns nonzero if permission is granted)
3044 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
3046 /* Do not allow twits to send Internet mail */
3047 if (who->axlevel <= 2) return(0);
3049 /* Globally enabled? */
3050 if (config.c_restrict == 0) return(1);
3052 /* User flagged ok? */
3053 if (who->flags & US_INTERNET) return(2);
3055 /* Aide level access? */
3056 if (who->axlevel >= 6) return(3);
3058 /* No mail for you! */
3064 * Validate recipients, count delivery types and errors, and handle aliasing
3065 * FIXME check for dupes!!!!!
3067 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
3068 * were specified, or the number of addresses found invalid.
3070 * Caller needs to free the result using free_recipients()
3072 struct recptypes *validate_recipients(char *supplied_recipients) {
3073 struct recptypes *ret;
3074 char *recipients = NULL;
3075 char this_recp[256];
3076 char this_recp_cooked[256];
3082 struct ctdluser tempUS;
3083 struct ctdlroom tempQR;
3087 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
3088 if (ret == NULL) return(NULL);
3090 /* Set all strings to null and numeric values to zero */
3091 memset(ret, 0, sizeof(struct recptypes));
3093 if (supplied_recipients == NULL) {
3094 recipients = strdup("");
3097 recipients = strdup(supplied_recipients);
3100 /* Allocate some memory. Yes, this allocates 500% more memory than we will
3101 * actually need, but it's healthier for the heap than doing lots of tiny
3102 * realloc() calls instead.
3105 ret->errormsg = malloc(strlen(recipients) + 1024);
3106 ret->recp_local = malloc(strlen(recipients) + 1024);
3107 ret->recp_internet = malloc(strlen(recipients) + 1024);
3108 ret->recp_ignet = malloc(strlen(recipients) + 1024);
3109 ret->recp_room = malloc(strlen(recipients) + 1024);
3110 ret->display_recp = malloc(strlen(recipients) + 1024);
3112 ret->errormsg[0] = 0;
3113 ret->recp_local[0] = 0;
3114 ret->recp_internet[0] = 0;
3115 ret->recp_ignet[0] = 0;
3116 ret->recp_room[0] = 0;
3117 ret->display_recp[0] = 0;
3119 ret->recptypes_magic = RECPTYPES_MAGIC;
3121 /* Change all valid separator characters to commas */
3122 for (i=0; i<strlen(recipients); ++i) {
3123 if ((recipients[i] == ';') || (recipients[i] == '|')) {
3124 recipients[i] = ',';
3128 /* Now start extracting recipients... */
3130 while (strlen(recipients) > 0) {
3132 for (i=0; i<=strlen(recipients); ++i) {
3133 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
3134 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
3135 safestrncpy(this_recp, recipients, i+1);
3137 if (recipients[i] == ',') {
3138 strcpy(recipients, &recipients[i+1]);
3141 strcpy(recipients, "");
3148 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
3150 mailtype = alias(this_recp);
3151 mailtype = alias(this_recp);
3152 mailtype = alias(this_recp);
3153 for (j=0; j<=strlen(this_recp); ++j) {
3154 if (this_recp[j]=='_') {
3155 this_recp_cooked[j] = ' ';
3158 this_recp_cooked[j] = this_recp[j];
3164 if (!strcasecmp(this_recp, "sysop")) {
3166 strcpy(this_recp, config.c_aideroom);
3167 if (strlen(ret->recp_room) > 0) {
3168 strcat(ret->recp_room, "|");
3170 strcat(ret->recp_room, this_recp);
3172 else if (getuser(&tempUS, this_recp) == 0) {
3174 strcpy(this_recp, tempUS.fullname);
3175 if (strlen(ret->recp_local) > 0) {
3176 strcat(ret->recp_local, "|");
3178 strcat(ret->recp_local, this_recp);
3180 else if (getuser(&tempUS, this_recp_cooked) == 0) {
3182 strcpy(this_recp, tempUS.fullname);
3183 if (strlen(ret->recp_local) > 0) {
3184 strcat(ret->recp_local, "|");
3186 strcat(ret->recp_local, this_recp);
3188 else if ( (!strncasecmp(this_recp, "room_", 5))
3189 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
3191 if (strlen(ret->recp_room) > 0) {
3192 strcat(ret->recp_room, "|");
3194 strcat(ret->recp_room, &this_recp_cooked[5]);
3202 /* Yes, you're reading this correctly: if the target
3203 * domain points back to the local system or an attached
3204 * Citadel directory, the address is invalid. That's
3205 * because if the address were valid, we would have
3206 * already translated it to a local address by now.
3208 if (IsDirectory(this_recp)) {
3213 ++ret->num_internet;
3214 if (strlen(ret->recp_internet) > 0) {
3215 strcat(ret->recp_internet, "|");
3217 strcat(ret->recp_internet, this_recp);
3222 if (strlen(ret->recp_ignet) > 0) {
3223 strcat(ret->recp_ignet, "|");
3225 strcat(ret->recp_ignet, this_recp);
3233 if (strlen(ret->errormsg) == 0) {
3234 snprintf(append, sizeof append,
3235 "Invalid recipient: %s",
3239 snprintf(append, sizeof append, ", %s", this_recp);
3241 if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
3242 strcat(ret->errormsg, append);
3246 if (strlen(ret->display_recp) == 0) {
3247 strcpy(append, this_recp);
3250 snprintf(append, sizeof append, ", %s", this_recp);
3252 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
3253 strcat(ret->display_recp, append);
3258 if ((ret->num_local + ret->num_internet + ret->num_ignet +
3259 ret->num_room + ret->num_error) == 0) {
3260 ret->num_error = (-1);
3261 strcpy(ret->errormsg, "No recipients specified.");
3264 lprintf(CTDL_DEBUG, "validate_recipients()\n");
3265 lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
3266 lprintf(CTDL_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
3267 lprintf(CTDL_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
3268 lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
3269 lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
3277 * Destructor for struct recptypes
3279 void free_recipients(struct recptypes *valid) {
3281 if (valid == NULL) {
3285 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
3286 lprintf(CTDL_EMERG, "Attempt to call free_recipients() on some other data type!\n");
3290 if (valid->errormsg != NULL) free(valid->errormsg);
3291 if (valid->recp_local != NULL) free(valid->recp_local);
3292 if (valid->recp_internet != NULL) free(valid->recp_internet);
3293 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
3294 if (valid->recp_room != NULL) free(valid->recp_room);
3295 if (valid->display_recp != NULL) free(valid->display_recp);
3302 * message entry - mode 0 (normal)
3304 void cmd_ent0(char *entargs)
3310 char supplied_euid[128];
3312 int format_type = 0;
3313 char newusername[256];
3314 char newuseremail[256];
3315 struct CtdlMessage *msg;
3319 struct recptypes *valid = NULL;
3320 struct recptypes *valid_to = NULL;
3321 struct recptypes *valid_cc = NULL;
3322 struct recptypes *valid_bcc = NULL;
3328 int newuseremail_ok = 0;
3332 post = extract_int(entargs, 0);
3333 extract_token(recp, entargs, 1, '|', sizeof recp);
3334 anon_flag = extract_int(entargs, 2);
3335 format_type = extract_int(entargs, 3);
3336 extract_token(subject, entargs, 4, '|', sizeof subject);
3337 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3338 do_confirm = extract_int(entargs, 6);
3339 extract_token(cc, entargs, 7, '|', sizeof cc);
3340 extract_token(bcc, entargs, 8, '|', sizeof bcc);
3341 switch(CC->room.QRdefaultview) {
3344 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3347 supplied_euid[0] = 0;
3350 extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
3352 /* first check to make sure the request is valid. */
3354 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3357 cprintf("%d %s\n", err, errmsg);
3361 /* Check some other permission type things. */
3363 if (strlen(newusername) == 0) {
3364 strcpy(newusername, CC->user.fullname);
3366 if ( (CC->user.axlevel < 6)
3367 && (strcasecmp(newusername, CC->user.fullname))
3368 && (strcasecmp(newusername, CC->cs_inet_fn))
3370 cprintf("%d You don't have permission to author messages as '%s'.\n",
3371 ERROR + HIGHER_ACCESS_REQUIRED,
3378 if (strlen(newuseremail) == 0) {
3379 newuseremail_ok = 1;
3382 if (strlen(newuseremail) > 0) {
3383 if (!strcasecmp(newuseremail, CC->cs_inet_email)) {
3384 newuseremail_ok = 1;
3386 else if (strlen(CC->cs_inet_other_emails) > 0) {
3387 j = num_tokens(CC->cs_inet_other_emails, '|');
3388 for (i=0; i<j; ++i) {
3389 extract_token(buf, CC->cs_inet_other_emails, i, '|', sizeof buf);
3390 if (!strcasecmp(newuseremail, buf)) {
3391 newuseremail_ok = 1;
3397 if (!newuseremail_ok) {
3398 cprintf("%d You don't have permission to author messages as '%s'.\n",
3399 ERROR + HIGHER_ACCESS_REQUIRED,
3405 CC->cs_flags |= CS_POSTING;
3407 /* In the Mail> room we have to behave a little differently --
3408 * make sure the user has specified at least one recipient. Then
3409 * validate the recipient(s).
3411 if ( (CC->room.QRflags & QR_MAILBOX)
3412 && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) ) {
3414 if (CC->user.axlevel < 2) {
3415 strcpy(recp, "sysop");
3420 valid_to = validate_recipients(recp);
3421 if (valid_to->num_error > 0) {
3422 cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3423 free_recipients(valid_to);
3427 valid_cc = validate_recipients(cc);
3428 if (valid_cc->num_error > 0) {
3429 cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3430 free_recipients(valid_to);
3431 free_recipients(valid_cc);
3435 valid_bcc = validate_recipients(bcc);
3436 if (valid_bcc->num_error > 0) {
3437 cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3438 free_recipients(valid_to);
3439 free_recipients(valid_cc);
3440 free_recipients(valid_bcc);
3444 /* Recipient required, but none were specified */
3445 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3446 free_recipients(valid_to);
3447 free_recipients(valid_cc);
3448 free_recipients(valid_bcc);
3449 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3453 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3454 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3455 cprintf("%d You do not have permission "
3456 "to send Internet mail.\n",
3457 ERROR + HIGHER_ACCESS_REQUIRED);
3458 free_recipients(valid_to);
3459 free_recipients(valid_cc);
3460 free_recipients(valid_bcc);
3465 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)
3466 && (CC->user.axlevel < 4) ) {
3467 cprintf("%d Higher access required for network mail.\n",
3468 ERROR + HIGHER_ACCESS_REQUIRED);
3469 free_recipients(valid_to);
3470 free_recipients(valid_cc);
3471 free_recipients(valid_bcc);
3475 if ((RESTRICT_INTERNET == 1)
3476 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3477 && ((CC->user.flags & US_INTERNET) == 0)
3478 && (!CC->internal_pgm)) {
3479 cprintf("%d You don't have access to Internet mail.\n",
3480 ERROR + HIGHER_ACCESS_REQUIRED);
3481 free_recipients(valid_to);
3482 free_recipients(valid_cc);
3483 free_recipients(valid_bcc);
3489 /* Is this a room which has anonymous-only or anonymous-option? */
3490 anonymous = MES_NORMAL;
3491 if (CC->room.QRflags & QR_ANONONLY) {
3492 anonymous = MES_ANONONLY;
3494 if (CC->room.QRflags & QR_ANONOPT) {
3495 if (anon_flag == 1) { /* only if the user requested it */
3496 anonymous = MES_ANONOPT;
3500 if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3504 /* If we're only checking the validity of the request, return
3505 * success without creating the message.
3508 cprintf("%d %s\n", CIT_OK,
3509 ((valid_to != NULL) ? valid_to->display_recp : "") );
3510 free_recipients(valid_to);
3511 free_recipients(valid_cc);
3512 free_recipients(valid_bcc);
3516 /* We don't need these anymore because we'll do it differently below */
3517 free_recipients(valid_to);
3518 free_recipients(valid_cc);
3519 free_recipients(valid_bcc);
3521 /* Read in the message from the client. */
3523 cprintf("%d send message\n", START_CHAT_MODE);
3525 cprintf("%d send message\n", SEND_LISTING);
3528 msg = CtdlMakeMessage(&CC->user, recp, cc,
3529 CC->room.QRname, anonymous, format_type,
3530 newusername, newuseremail, subject,
3531 ((strlen(supplied_euid) > 0) ? supplied_euid : NULL),
3534 /* Put together one big recipients struct containing to/cc/bcc all in
3535 * one. This is for the envelope.
3537 char *all_recps = malloc(SIZ * 3);
3538 strcpy(all_recps, recp);
3539 if (strlen(cc) > 0) {
3540 if (strlen(all_recps) > 0) {
3541 strcat(all_recps, ",");
3543 strcat(all_recps, cc);
3545 if (strlen(bcc) > 0) {
3546 if (strlen(all_recps) > 0) {
3547 strcat(all_recps, ",");
3549 strcat(all_recps, bcc);
3551 if (strlen(all_recps) > 0) {
3552 valid = validate_recipients(all_recps);
3560 msgnum = CtdlSubmitMsg(msg, valid, "");
3563 cprintf("%ld\n", msgnum);
3565 cprintf("Message accepted.\n");
3568 cprintf("Internal error.\n");
3570 if (msg->cm_fields['E'] != NULL) {
3571 cprintf("%s\n", msg->cm_fields['E']);
3578 CtdlFreeMessage(msg);
3580 if (valid != NULL) {
3581 free_recipients(valid);
3589 * API function to delete messages which match a set of criteria
3590 * (returns the actual number of messages deleted)
3592 int CtdlDeleteMessages(char *room_name, /* which room */
3593 long *dmsgnums, /* array of msg numbers to be deleted */
3594 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
3595 char *content_type /* or "" for any. regular expressions expected. */
3598 struct ctdlroom qrbuf;
3599 struct cdbdata *cdbfr;
3600 long *msglist = NULL;
3601 long *dellist = NULL;
3604 int num_deleted = 0;
3606 struct MetaData smi;
3610 if (content_type) if (strlen(content_type) > 0) {
3611 regcomp(&re, content_type, 0);
3613 lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
3614 room_name, num_dmsgnums, content_type);
3616 /* get room record, obtaining a lock... */
3617 if (lgetroom(&qrbuf, room_name) != 0) {
3618 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3620 return (0); /* room not found */
3622 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3624 if (cdbfr != NULL) {
3625 dellist = malloc(cdbfr->len);
3626 msglist = (long *) cdbfr->ptr;
3627 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3628 num_msgs = cdbfr->len / sizeof(long);
3632 for (i = 0; i < num_msgs; ++i) {
3635 /* Set/clear a bit for each criterion */
3637 /* 0 messages in the list or a null list means that we are
3638 * interested in deleting any messages which meet the other criteria.
3640 if ((num_dmsgnums == 0) || (dmsgnums == NULL)) {
3641 delete_this |= 0x01;
3644 for (j=0; j<num_dmsgnums; ++j) {
3645 if (msglist[i] == dmsgnums[j]) {
3646 delete_this |= 0x01;
3651 if (strlen(content_type) == 0) {
3652 delete_this |= 0x02;
3654 GetMetaData(&smi, msglist[i]);
3655 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3656 delete_this |= 0x02;
3660 /* Delete message only if all bits are set */
3661 if (delete_this == 0x03) {
3662 dellist[num_deleted++] = msglist[i];
3667 num_msgs = sort_msglist(msglist, num_msgs);
3668 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3669 msglist, (int)(num_msgs * sizeof(long)));
3671 qrbuf.QRhighest = msglist[num_msgs - 1];
3675 /* Go through the messages we pulled out of the index, and decrement
3676 * their reference counts by 1. If this is the only room the message
3677 * was in, the reference count will reach zero and the message will
3678 * automatically be deleted from the database. We do this in a
3679 * separate pass because there might be plug-in hooks getting called,
3680 * and we don't want that happening during an S_ROOMS critical
3683 if (num_deleted) for (i=0; i<num_deleted; ++i) {
3684 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3685 AdjRefCount(dellist[i], -1);
3688 /* Now free the memory we used, and go away. */
3689 if (msglist != NULL) free(msglist);
3690 if (dellist != NULL) free(dellist);
3691 lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3692 return (num_deleted);
3698 * Check whether the current user has permission to delete messages from
3699 * the current room (returns 1 for yes, 0 for no)
3701 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3703 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3704 if (ra & UA_DELETEALLOWED) return(1);
3712 * Delete message from current room
3714 void cmd_dele(char *args)
3723 extract_token(msgset, args, 0, '|', sizeof msgset);
3724 num_msgs = num_tokens(msgset, ',');
3726 cprintf("%d Nothing to do.\n", CIT_OK);
3730 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3731 cprintf("%d Higher access required.\n",
3732 ERROR + HIGHER_ACCESS_REQUIRED);
3737 * Build our message set to be moved/copied
3739 msgs = malloc(num_msgs * sizeof(long));
3740 for (i=0; i<num_msgs; ++i) {
3741 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3742 msgs[i] = atol(msgtok);
3745 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3749 cprintf("%d %d message%s deleted.\n", CIT_OK,
3750 num_deleted, ((num_deleted != 1) ? "s" : ""));
3752 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
3758 * Back end API function for moves and deletes (multiple messages)
3760 int CtdlCopyMsgsToRoom(long *msgnums, int num_msgs, char *dest) {
3763 err = CtdlSaveMsgPointersInRoom(dest, msgnums, num_msgs, 1, NULL);
3764 if (err != 0) return(err);
3773 * move or copy a message to another room
3775 void cmd_move(char *args)
3782 char targ[ROOMNAMELEN];
3783 struct ctdlroom qtemp;
3790 extract_token(msgset, args, 0, '|', sizeof msgset);
3791 num_msgs = num_tokens(msgset, ',');
3793 cprintf("%d Nothing to do.\n", CIT_OK);
3797 extract_token(targ, args, 1, '|', sizeof targ);
3798 convert_room_name_macros(targ, sizeof targ);
3799 targ[ROOMNAMELEN - 1] = 0;
3800 is_copy = extract_int(args, 2);
3802 if (getroom(&qtemp, targ) != 0) {
3803 cprintf("%d '%s' does not exist.\n",
3804 ERROR + ROOM_NOT_FOUND, targ);
3808 getuser(&CC->user, CC->curr_user);
3809 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3811 /* Check for permission to perform this operation.
3812 * Remember: "CC->room" is source, "qtemp" is target.
3816 /* Aides can move/copy */
3817 if (CC->user.axlevel >= 6) permit = 1;
3819 /* Room aides can move/copy */
3820 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3822 /* Permit move/copy from personal rooms */
3823 if ((CC->room.QRflags & QR_MAILBOX)
3824 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3826 /* Permit only copy from public to personal room */
3828 && (!(CC->room.QRflags & QR_MAILBOX))
3829 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3831 /* Permit message removal from collaborative delete rooms */
3832 if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
3834 /* User must have access to target room */
3835 if (!(ra & UA_KNOWN)) permit = 0;
3838 cprintf("%d Higher access required.\n",
3839 ERROR + HIGHER_ACCESS_REQUIRED);
3844 * Build our message set to be moved/copied
3846 msgs = malloc(num_msgs * sizeof(long));
3847 for (i=0; i<num_msgs; ++i) {
3848 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3849 msgs[i] = atol(msgtok);
3855 err = CtdlCopyMsgsToRoom(msgs, num_msgs, targ);
3857 cprintf("%d Cannot store message(s) in %s: error %d\n",
3863 /* Now delete the message from the source room,
3864 * if this is a 'move' rather than a 'copy' operation.
3867 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3871 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3877 * GetMetaData() - Get the supplementary record for a message
3879 void GetMetaData(struct MetaData *smibuf, long msgnum)
3882 struct cdbdata *cdbsmi;
3885 memset(smibuf, 0, sizeof(struct MetaData));
3886 smibuf->meta_msgnum = msgnum;
3887 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3889 /* Use the negative of the message number for its supp record index */
3890 TheIndex = (0L - msgnum);
3892 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3893 if (cdbsmi == NULL) {
3894 return; /* record not found; go with defaults */
3896 memcpy(smibuf, cdbsmi->ptr,
3897 ((cdbsmi->len > sizeof(struct MetaData)) ?
3898 sizeof(struct MetaData) : cdbsmi->len));
3905 * PutMetaData() - (re)write supplementary record for a message
3907 void PutMetaData(struct MetaData *smibuf)
3911 /* Use the negative of the message number for the metadata db index */
3912 TheIndex = (0L - smibuf->meta_msgnum);
3914 cdb_store(CDB_MSGMAIN,
3915 &TheIndex, (int)sizeof(long),
3916 smibuf, (int)sizeof(struct MetaData));
3921 * AdjRefCount - submit an adjustment to the reference count for a message.
3922 * (These are just queued -- we actually process them later.)
3924 void AdjRefCount(long msgnum, int incr)
3926 struct arcq new_arcq;
3928 begin_critical_section(S_SUPPMSGMAIN);
3929 if (arcfp == NULL) {
3930 arcfp = fopen(file_arcq, "ab+");
3932 end_critical_section(S_SUPPMSGMAIN);
3934 /* msgnum < 0 means that we're trying to close the file */
3936 lprintf(CTDL_DEBUG, "Closing the AdjRefCount queue file\n");
3937 begin_critical_section(S_SUPPMSGMAIN);
3938 if (arcfp != NULL) {
3942 end_critical_section(S_SUPPMSGMAIN);
3947 * If we can't open the queue, perform the operation synchronously.
3949 if (arcfp == NULL) {
3950 TDAP_AdjRefCount(msgnum, incr);
3954 new_arcq.arcq_msgnum = msgnum;
3955 new_arcq.arcq_delta = incr;
3956 fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
3964 * TDAP_ProcessAdjRefCountQueue()
3966 * Process the queue of message count adjustments that was created by calls
3967 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
3968 * for each one. This should be an "off hours" operation.
3970 int TDAP_ProcessAdjRefCountQueue(void)
3972 char file_arcq_temp[PATH_MAX];
3975 struct arcq arcq_rec;
3976 int num_records_processed = 0;
3978 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s2", file_arcq);
3980 begin_critical_section(S_SUPPMSGMAIN);
3981 if (arcfp != NULL) {
3986 r = link(file_arcq, file_arcq_temp);
3988 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3989 end_critical_section(S_SUPPMSGMAIN);
3990 return(num_records_processed);
3994 end_critical_section(S_SUPPMSGMAIN);
3996 fp = fopen(file_arcq_temp, "rb");
3998 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3999 return(num_records_processed);
4002 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
4003 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
4004 ++num_records_processed;
4008 r = unlink(file_arcq_temp);
4010 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4013 return(num_records_processed);
4019 * TDAP_AdjRefCount - adjust the reference count for a message.
4020 * This one does it "for real" because it's called by
4021 * the autopurger function that processes the queue
4022 * created by AdjRefCount(). If a message's reference
4023 * count becomes zero, we also delete the message from
4024 * disk and de-index it.
4026 void TDAP_AdjRefCount(long msgnum, int incr)
4029 struct MetaData smi;
4032 /* This is a *tight* critical section; please keep it that way, as
4033 * it may get called while nested in other critical sections.
4034 * Complicating this any further will surely cause deadlock!
4036 begin_critical_section(S_SUPPMSGMAIN);
4037 GetMetaData(&smi, msgnum);
4038 smi.meta_refcount += incr;
4040 end_critical_section(S_SUPPMSGMAIN);
4041 lprintf(CTDL_DEBUG, "msg %ld ref count delta %d, is now %d\n",
4042 msgnum, incr, smi.meta_refcount);
4044 /* If the reference count is now zero, delete the message
4045 * (and its supplementary record as well).
4047 if (smi.meta_refcount == 0) {
4048 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
4050 /* Remove from fulltext index */
4051 if (config.c_enable_fulltext) {
4052 ft_index_message(msgnum, 0);
4055 /* Remove from message base */
4057 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4058 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
4060 /* Remove metadata record */
4061 delnum = (0L - msgnum);
4062 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4068 * Write a generic object to this room
4070 * Note: this could be much more efficient. Right now we use two temporary
4071 * files, and still pull the message into memory as with all others.
4073 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
4074 char *content_type, /* MIME type of this object */
4075 char *tempfilename, /* Where to fetch it from */
4076 struct ctdluser *is_mailbox, /* Mailbox room? */
4077 int is_binary, /* Is encoding necessary? */
4078 int is_unique, /* Del others of this type? */
4079 unsigned int flags /* Internal save flags */
4084 struct ctdlroom qrbuf;
4085 char roomname[ROOMNAMELEN];
4086 struct CtdlMessage *msg;
4088 char *raw_message = NULL;
4089 char *encoded_message = NULL;
4090 off_t raw_length = 0;
4092 if (is_mailbox != NULL) {
4093 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
4096 safestrncpy(roomname, req_room, sizeof(roomname));
4099 fp = fopen(tempfilename, "rb");
4101 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
4102 tempfilename, strerror(errno));
4105 fseek(fp, 0L, SEEK_END);
4106 raw_length = ftell(fp);
4108 lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
4110 raw_message = malloc((size_t)raw_length + 2);
4111 fread(raw_message, (size_t)raw_length, 1, fp);
4115 encoded_message = malloc((size_t)
4116 (((raw_length * 134) / 100) + 4096 ) );
4119 encoded_message = malloc((size_t)(raw_length + 4096));
4122 sprintf(encoded_message, "Content-type: %s\n", content_type);
4125 sprintf(&encoded_message[strlen(encoded_message)],
4126 "Content-transfer-encoding: base64\n\n"
4130 sprintf(&encoded_message[strlen(encoded_message)],
4131 "Content-transfer-encoding: 7bit\n\n"
4137 &encoded_message[strlen(encoded_message)],
4143 raw_message[raw_length] = 0;
4145 &encoded_message[strlen(encoded_message)],
4153 lprintf(CTDL_DEBUG, "Allocating\n");
4154 msg = malloc(sizeof(struct CtdlMessage));
4155 memset(msg, 0, sizeof(struct CtdlMessage));
4156 msg->cm_magic = CTDLMESSAGE_MAGIC;
4157 msg->cm_anon_type = MES_NORMAL;
4158 msg->cm_format_type = 4;
4159 msg->cm_fields['A'] = strdup(CC->user.fullname);
4160 msg->cm_fields['O'] = strdup(req_room);
4161 msg->cm_fields['N'] = strdup(config.c_nodename);
4162 msg->cm_fields['H'] = strdup(config.c_humannode);
4163 msg->cm_flags = flags;
4165 msg->cm_fields['M'] = encoded_message;
4167 /* Create the requested room if we have to. */
4168 if (getroom(&qrbuf, roomname) != 0) {
4169 create_room(roomname,
4170 ( (is_mailbox != NULL) ? 5 : 3 ),
4171 "", 0, 1, 0, VIEW_BBS);
4173 /* If the caller specified this object as unique, delete all
4174 * other objects of this type that are currently in the room.
4177 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
4178 CtdlDeleteMessages(roomname, NULL, 0, content_type)
4181 /* Now write the data */
4182 CtdlSubmitMsg(msg, NULL, roomname);
4183 CtdlFreeMessage(msg);
4191 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
4192 config_msgnum = msgnum;
4196 char *CtdlGetSysConfig(char *sysconfname) {
4197 char hold_rm[ROOMNAMELEN];
4200 struct CtdlMessage *msg;
4203 strcpy(hold_rm, CC->room.QRname);
4204 if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
4205 getroom(&CC->room, hold_rm);
4210 /* We want the last (and probably only) config in this room */
4211 begin_critical_section(S_CONFIG);
4212 config_msgnum = (-1L);
4213 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
4214 CtdlGetSysConfigBackend, NULL);
4215 msgnum = config_msgnum;
4216 end_critical_section(S_CONFIG);
4222 msg = CtdlFetchMessage(msgnum, 1);
4224 conf = strdup(msg->cm_fields['M']);
4225 CtdlFreeMessage(msg);
4232 getroom(&CC->room, hold_rm);
4234 if (conf != NULL) do {
4235 extract_token(buf, conf, 0, '\n', sizeof buf);
4236 strcpy(conf, &conf[strlen(buf)+1]);
4237 } while ( (strlen(conf)>0) && (strlen(buf)>0) );
4242 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
4243 char temp[PATH_MAX];
4246 CtdlMakeTempFileName(temp, sizeof temp);
4248 fp = fopen(temp, "w");
4249 if (fp == NULL) return;
4250 fprintf(fp, "%s", sysconfdata);
4253 /* this handy API function does all the work for us */
4254 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
4260 * Determine whether a given Internet address belongs to the current user
4262 int CtdlIsMe(char *addr, int addr_buf_len)
4264 struct recptypes *recp;
4267 recp = validate_recipients(addr);
4268 if (recp == NULL) return(0);
4270 if (recp->num_local == 0) {
4271 free_recipients(recp);
4275 for (i=0; i<recp->num_local; ++i) {
4276 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
4277 if (!strcasecmp(addr, CC->user.fullname)) {
4278 free_recipients(recp);
4283 free_recipients(recp);
4289 * Citadel protocol command to do the same
4291 void cmd_isme(char *argbuf) {
4294 if (CtdlAccessCheck(ac_logged_in)) return;
4295 extract_token(addr, argbuf, 0, '|', sizeof addr);
4297 if (CtdlIsMe(addr, sizeof addr)) {
4298 cprintf("%d %s\n", CIT_OK, addr);
4301 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);