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>
34 #include <libcitadel.h>
37 #include "serv_extensions.h"
41 #include "sysdep_decls.h"
42 #include "citserver.h"
50 #include "internet_addressing.h"
51 #include "euidindex.h"
52 #include "journaling.h"
53 #include "citadel_dirs.h"
54 #include "clientsocket.h"
55 #include "serv_network.h"
59 struct addresses_to_be_filed *atbf = NULL;
61 /* This temp file holds the queue of operations for AdjRefCount() */
62 static FILE *arcfp = NULL;
65 * This really belongs in serv_network.c, but I don't know how to export
66 * symbols between modules.
68 struct FilterList *filterlist = NULL;
72 * These are the four-character field headers we use when outputting
73 * messages in Citadel format (as opposed to RFC822 format).
76 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
77 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
78 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
79 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
80 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
81 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
82 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
83 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
111 * This function is self explanatory.
112 * (What can I say, I'm in a weird mood today...)
114 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
118 for (i = 0; i < strlen(name); ++i) {
119 if (name[i] == '@') {
120 while (isspace(name[i - 1]) && i > 0) {
121 strcpy(&name[i - 1], &name[i]);
124 while (isspace(name[i + 1])) {
125 strcpy(&name[i + 1], &name[i + 2]);
133 * Aliasing for network mail.
134 * (Error messages have been commented out, because this is a server.)
136 int alias(char *name)
137 { /* process alias and routing info for mail */
140 char aaa[SIZ], bbb[SIZ];
141 char *ignetcfg = NULL;
142 char *ignetmap = NULL;
148 char original_name[256];
149 safestrncpy(original_name, name, sizeof original_name);
152 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
153 stripallbut(name, '<', '>');
155 fp = fopen(file_mail_aliases, "r");
157 fp = fopen("/dev/null", "r");
164 while (fgets(aaa, sizeof aaa, fp) != NULL) {
165 while (isspace(name[0]))
166 strcpy(name, &name[1]);
167 aaa[strlen(aaa) - 1] = 0;
169 for (a = 0; a < strlen(aaa); ++a) {
171 strcpy(bbb, &aaa[a + 1]);
175 if (!strcasecmp(name, aaa))
180 /* Hit the Global Address Book */
181 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
185 if (strcasecmp(original_name, name)) {
186 lprintf(CTDL_INFO, "%s is being forwarded to %s\n", original_name, name);
189 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
190 for (a=0; a<strlen(name); ++a) {
191 if (name[a] == '@') {
192 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
194 lprintf(CTDL_INFO, "Changed to <%s>\n", name);
199 /* determine local or remote type, see citadel.h */
200 at = haschar(name, '@');
201 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
202 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
203 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
205 /* figure out the delivery mode */
206 extract_token(node, name, 1, '@', sizeof node);
208 /* If there are one or more dots in the nodename, we assume that it
209 * is an FQDN and will attempt SMTP delivery to the Internet.
211 if (haschar(node, '.') > 0) {
212 return(MES_INTERNET);
215 /* Otherwise we look in the IGnet maps for a valid Citadel node.
216 * Try directly-connected nodes first...
218 ignetcfg = CtdlGetSysConfig(IGNETCFG);
219 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
220 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
221 extract_token(testnode, buf, 0, '|', sizeof testnode);
222 if (!strcasecmp(node, testnode)) {
230 * Then try nodes that are two or more hops away.
232 ignetmap = CtdlGetSysConfig(IGNETMAP);
233 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
234 extract_token(buf, ignetmap, i, '\n', sizeof buf);
235 extract_token(testnode, buf, 0, '|', sizeof testnode);
236 if (!strcasecmp(node, testnode)) {
243 /* If we get to this point it's an invalid node name */
249 * Back end for the MSGS command: output message number only.
251 void simple_listing(long msgnum, void *userdata)
253 cprintf("%ld\n", msgnum);
259 * Back end for the MSGS command: output header summary.
261 void headers_listing(long msgnum, void *userdata)
263 struct CtdlMessage *msg;
265 msg = CtdlFetchMessage(msgnum, 0);
267 cprintf("%ld|0|||||\n", msgnum);
271 cprintf("%ld|%s|%s|%s|%s|%s|\n",
273 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
274 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
275 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
276 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
277 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
279 CtdlFreeMessage(msg);
284 /* Determine if a given message matches the fields in a message template.
285 * Return 0 for a successful match.
287 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
290 /* If there aren't any fields in the template, all messages will
293 if (template == NULL) return(0);
295 /* Null messages are bogus. */
296 if (msg == NULL) return(1);
298 for (i='A'; i<='Z'; ++i) {
299 if (template->cm_fields[i] != NULL) {
300 if (msg->cm_fields[i] == NULL) {
303 if (strcasecmp(msg->cm_fields[i],
304 template->cm_fields[i])) return 1;
308 /* All compares succeeded: we have a match! */
315 * Retrieve the "seen" message list for the current room.
317 void CtdlGetSeen(char *buf, int which_set) {
320 /* Learn about the user and room in question */
321 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
323 if (which_set == ctdlsetseen_seen)
324 safestrncpy(buf, vbuf.v_seen, SIZ);
325 if (which_set == ctdlsetseen_answered)
326 safestrncpy(buf, vbuf.v_answered, SIZ);
332 * Manipulate the "seen msgs" string (or other message set strings)
334 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
335 int target_setting, int which_set,
336 struct ctdluser *which_user, struct ctdlroom *which_room) {
337 struct cdbdata *cdbfr;
349 char *is_set; /* actually an array of booleans */
352 char setstr[SIZ], lostr[SIZ], histr[SIZ];
355 /* Don't bother doing *anything* if we were passed a list of zero messages */
356 if (num_target_msgnums < 1) {
360 lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
361 num_target_msgnums, target_msgnums[0],
362 target_setting, which_set);
364 /* Learn about the user and room in question */
365 CtdlGetRelationship(&vbuf,
366 ((which_user != NULL) ? which_user : &CC->user),
367 ((which_room != NULL) ? which_room : &CC->room)
370 /* Load the message list */
371 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
373 msglist = (long *) cdbfr->ptr;
374 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
375 num_msgs = cdbfr->len / sizeof(long);
378 return; /* No messages at all? No further action. */
381 is_set = malloc(num_msgs * sizeof(char));
382 memset(is_set, 0, (num_msgs * sizeof(char)) );
384 /* Decide which message set we're manipulating */
386 case ctdlsetseen_seen:
387 safestrncpy(vset, vbuf.v_seen, sizeof vset);
389 case ctdlsetseen_answered:
390 safestrncpy(vset, vbuf.v_answered, sizeof vset);
394 /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
396 /* Translate the existing sequence set into an array of booleans */
397 num_sets = num_tokens(vset, ',');
398 for (s=0; s<num_sets; ++s) {
399 extract_token(setstr, vset, s, ',', sizeof setstr);
401 extract_token(lostr, setstr, 0, ':', sizeof lostr);
402 if (num_tokens(setstr, ':') >= 2) {
403 extract_token(histr, setstr, 1, ':', sizeof histr);
404 if (!strcmp(histr, "*")) {
405 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
409 strcpy(histr, lostr);
414 for (i = 0; i < num_msgs; ++i) {
415 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
421 /* Now translate the array of booleans back into a sequence set */
426 for (i=0; i<num_msgs; ++i) {
428 is_seen = is_set[i]; /* Default to existing setting */
430 for (k=0; k<num_target_msgnums; ++k) {
431 if (msglist[i] == target_msgnums[k]) {
432 is_seen = target_setting;
437 if (lo < 0L) lo = msglist[i];
441 if ( ((is_seen == 0) && (was_seen == 1))
442 || ((is_seen == 1) && (i == num_msgs-1)) ) {
444 /* begin trim-o-matic code */
447 while ( (strlen(vset) + 20) > sizeof vset) {
448 remove_token(vset, 0, ',');
450 if (j--) break; /* loop no more than 9 times */
452 if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
456 snprintf(lostr, sizeof lostr,
457 "1:%ld,%s", t, vset);
458 safestrncpy(vset, lostr, sizeof vset);
460 /* end trim-o-matic code */
468 snprintf(&vset[tmp], (sizeof vset) - tmp,
472 snprintf(&vset[tmp], (sizeof vset) - tmp,
481 /* Decide which message set we're manipulating */
483 case ctdlsetseen_seen:
484 safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
486 case ctdlsetseen_answered:
487 safestrncpy(vbuf.v_answered, vset,
488 sizeof vbuf.v_answered);
493 /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
495 CtdlSetRelationship(&vbuf,
496 ((which_user != NULL) ? which_user : &CC->user),
497 ((which_room != NULL) ? which_room : &CC->room)
503 * API function to perform an operation for each qualifying message in the
504 * current room. (Returns the number of messages processed.)
506 int CtdlForEachMessage(int mode, long ref, char *search_string,
508 struct CtdlMessage *compare,
509 void (*CallBack) (long, void *),
515 struct cdbdata *cdbfr;
516 long *msglist = NULL;
518 int num_processed = 0;
521 struct CtdlMessage *msg = NULL;
524 int printed_lastold = 0;
525 int num_search_msgs = 0;
526 long *search_msgs = NULL;
528 int need_to_free_re = 0;
531 if (content_type) if (!IsEmptyStr(content_type)) {
532 regcomp(&re, content_type, 0);
536 /* Learn about the user and room in question */
537 getuser(&CC->user, CC->curr_user);
538 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
540 /* Load the message list */
541 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
543 msglist = (long *) cdbfr->ptr;
544 num_msgs = cdbfr->len / sizeof(long);
546 if (need_to_free_re) regfree(&re);
547 return 0; /* No messages at all? No further action. */
552 * Now begin the traversal.
554 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
556 /* If the caller is looking for a specific MIME type, filter
557 * out all messages which are not of the type requested.
559 if (content_type != NULL) if (!IsEmptyStr(content_type)) {
561 /* This call to GetMetaData() sits inside this loop
562 * so that we only do the extra database read per msg
563 * if we need to. Doing the extra read all the time
564 * really kills the server. If we ever need to use
565 * metadata for another search criterion, we need to
566 * move the read somewhere else -- but still be smart
567 * enough to only do the read if the caller has
568 * specified something that will need it.
570 GetMetaData(&smi, msglist[a]);
572 /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
573 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
579 num_msgs = sort_msglist(msglist, num_msgs);
581 /* If a template was supplied, filter out the messages which
582 * don't match. (This could induce some delays!)
585 if (compare != NULL) {
586 for (a = 0; a < num_msgs; ++a) {
587 msg = CtdlFetchMessage(msglist[a], 1);
589 if (CtdlMsgCmp(msg, compare)) {
592 CtdlFreeMessage(msg);
598 /* If a search string was specified, get a message list from
599 * the full text index and remove messages which aren't on both
603 * Since the lists are sorted and strictly ascending, and the
604 * output list is guaranteed to be shorter than or equal to the
605 * input list, we overwrite the bottom of the input list. This
606 * eliminates the need to memmove big chunks of the list over and
609 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
611 /* Call search module via hook mechanism.
612 * NULL means use any search function available.
613 * otherwise replace with a char * to name of search routine
615 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
617 if (num_search_msgs > 0) {
621 orig_num_msgs = num_msgs;
623 for (i=0; i<orig_num_msgs; ++i) {
624 for (j=0; j<num_search_msgs; ++j) {
625 if (msglist[i] == search_msgs[j]) {
626 msglist[num_msgs++] = msglist[i];
632 num_msgs = 0; /* No messages qualify */
634 if (search_msgs != NULL) free(search_msgs);
636 /* Now that we've purged messages which don't contain the search
637 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
644 * Now iterate through the message list, according to the
645 * criteria supplied by the caller.
648 for (a = 0; a < num_msgs; ++a) {
649 thismsg = msglist[a];
650 if (mode == MSGS_ALL) {
654 is_seen = is_msg_in_sequence_set(
655 vbuf.v_seen, thismsg);
656 if (is_seen) lastold = thismsg;
662 || ((mode == MSGS_OLD) && (is_seen))
663 || ((mode == MSGS_NEW) && (!is_seen))
664 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
665 || ((mode == MSGS_FIRST) && (a < ref))
666 || ((mode == MSGS_GT) && (thismsg > ref))
667 || ((mode == MSGS_EQ) && (thismsg == ref))
670 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
672 CallBack(lastold, userdata);
676 if (CallBack) CallBack(thismsg, userdata);
680 cdb_free(cdbfr); /* Clean up */
681 if (need_to_free_re) regfree(&re);
682 return num_processed;
688 * cmd_msgs() - get list of message #'s in this room
689 * implements the MSGS server command using CtdlForEachMessage()
691 void cmd_msgs(char *cmdbuf)
700 int with_template = 0;
701 struct CtdlMessage *template = NULL;
702 int with_headers = 0;
703 char search_string[1024];
705 extract_token(which, cmdbuf, 0, '|', sizeof which);
706 cm_ref = extract_int(cmdbuf, 1);
707 extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
708 with_template = extract_int(cmdbuf, 2);
709 with_headers = extract_int(cmdbuf, 3);
712 if (!strncasecmp(which, "OLD", 3))
714 else if (!strncasecmp(which, "NEW", 3))
716 else if (!strncasecmp(which, "FIRST", 5))
718 else if (!strncasecmp(which, "LAST", 4))
720 else if (!strncasecmp(which, "GT", 2))
722 else if (!strncasecmp(which, "SEARCH", 6))
727 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
728 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
732 if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
733 cprintf("%d Full text index is not enabled on this server.\n",
734 ERROR + CMD_NOT_SUPPORTED);
740 cprintf("%d Send template then receive message list\n",
742 template = (struct CtdlMessage *)
743 malloc(sizeof(struct CtdlMessage));
744 memset(template, 0, sizeof(struct CtdlMessage));
745 template->cm_magic = CTDLMESSAGE_MAGIC;
746 template->cm_anon_type = MES_NORMAL;
748 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
749 extract_token(tfield, buf, 0, '|', sizeof tfield);
750 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
751 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
752 if (!strcasecmp(tfield, msgkeys[i])) {
753 template->cm_fields[i] =
761 cprintf("%d \n", LISTING_FOLLOWS);
764 CtdlForEachMessage(mode,
765 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
766 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
769 (with_headers ? headers_listing : simple_listing),
772 if (template != NULL) CtdlFreeMessage(template);
780 * help_subst() - support routine for help file viewer
782 void help_subst(char *strbuf, char *source, char *dest)
787 while (p = pattern2(strbuf, source), (p >= 0)) {
788 strcpy(workbuf, &strbuf[p + strlen(source)]);
789 strcpy(&strbuf[p], dest);
790 strcat(strbuf, workbuf);
795 void do_help_subst(char *buffer)
799 help_subst(buffer, "^nodename", config.c_nodename);
800 help_subst(buffer, "^humannode", config.c_humannode);
801 help_subst(buffer, "^fqdn", config.c_fqdn);
802 help_subst(buffer, "^username", CC->user.fullname);
803 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
804 help_subst(buffer, "^usernum", buf2);
805 help_subst(buffer, "^sysadm", config.c_sysadm);
806 help_subst(buffer, "^variantname", CITADEL);
807 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
808 help_subst(buffer, "^maxsessions", buf2);
809 help_subst(buffer, "^bbsdir", ctdl_message_dir);
815 * memfmout() - Citadel text formatter and paginator.
816 * Although the original purpose of this routine was to format
817 * text to the reader's screen width, all we're really using it
818 * for here is to format text out to 80 columns before sending it
819 * to the client. The client software may reformat it again.
822 char *mptr, /* where are we going to get our text from? */
823 char subst, /* nonzero if we should do substitutions */
824 char *nl) /* string to terminate lines with */
832 static int width = 80;
837 c = 1; /* c is the current pos */
841 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
843 buffer[strlen(buffer) + 1] = 0;
844 buffer[strlen(buffer)] = ch;
847 if (buffer[0] == '^')
848 do_help_subst(buffer);
850 buffer[strlen(buffer) + 1] = 0;
852 strcpy(buffer, &buffer[1]);
860 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
863 if (((old == 13) || (old == 10)) && (isspace(real))) {
868 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
869 cprintf("%s%s", nl, aaa);
878 if ((strlen(aaa) + c) > (width - 5)) {
887 if ((ch == 13) || (ch == 10)) {
888 cprintf("%s%s", aaa, nl);
895 cprintf("%s%s", aaa, nl);
901 * Callback function for mime parser that simply lists the part
903 void list_this_part(char *name, char *filename, char *partnum, char *disp,
904 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
909 ma = (struct ma_info *)cbuserdata;
910 if (ma->is_ma == 0) {
911 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
912 name, filename, partnum, disp, cbtype, (long)length);
917 * Callback function for multipart prefix
919 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
920 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
925 ma = (struct ma_info *)cbuserdata;
926 if (!strcasecmp(cbtype, "multipart/alternative")) {
930 if (ma->is_ma == 0) {
931 cprintf("pref=%s|%s\n", partnum, cbtype);
936 * Callback function for multipart sufffix
938 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
939 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
944 ma = (struct ma_info *)cbuserdata;
945 if (ma->is_ma == 0) {
946 cprintf("suff=%s|%s\n", partnum, cbtype);
948 if (!strcasecmp(cbtype, "multipart/alternative")) {
955 * Callback function for mime parser that opens a section for downloading
957 void mime_download(char *name, char *filename, char *partnum, char *disp,
958 void *content, char *cbtype, char *cbcharset, size_t length,
959 char *encoding, void *cbuserdata)
962 /* Silently go away if there's already a download open... */
963 if (CC->download_fp != NULL)
966 /* ...or if this is not the desired section */
967 if (strcasecmp(CC->download_desired_section, partnum))
970 CC->download_fp = tmpfile();
971 if (CC->download_fp == NULL)
974 fwrite(content, length, 1, CC->download_fp);
975 fflush(CC->download_fp);
976 rewind(CC->download_fp);
978 OpenCmdResult(filename, cbtype);
984 * Callback function for mime parser that outputs a section all at once
986 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
987 void *content, char *cbtype, char *cbcharset, size_t length,
988 char *encoding, void *cbuserdata)
990 int *found_it = (int *)cbuserdata;
992 /* ...or if this is not the desired section */
993 if (strcasecmp(CC->download_desired_section, partnum))
998 cprintf("%d %d\n", BINARY_FOLLOWS, (int)length);
999 client_write(content, length);
1005 * Load a message from disk into memory.
1006 * This is used by CtdlOutputMsg() and other fetch functions.
1008 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1009 * using the CtdlMessageFree() function.
1011 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1013 struct cdbdata *dmsgtext;
1014 struct CtdlMessage *ret = NULL;
1018 cit_uint8_t field_header;
1020 lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1022 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1023 if (dmsgtext == NULL) {
1026 mptr = dmsgtext->ptr;
1027 upper_bound = mptr + dmsgtext->len;
1029 /* Parse the three bytes that begin EVERY message on disk.
1030 * The first is always 0xFF, the on-disk magic number.
1031 * The second is the anonymous/public type byte.
1032 * The third is the format type byte (vari, fixed, or MIME).
1036 lprintf(CTDL_ERR, "Message %ld appears to be corrupted.\n", msgnum);
1040 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1041 memset(ret, 0, sizeof(struct CtdlMessage));
1043 ret->cm_magic = CTDLMESSAGE_MAGIC;
1044 ret->cm_anon_type = *mptr++; /* Anon type byte */
1045 ret->cm_format_type = *mptr++; /* Format type byte */
1048 * The rest is zero or more arbitrary fields. Load them in.
1049 * We're done when we encounter either a zero-length field or
1050 * have just processed the 'M' (message text) field.
1053 if (mptr >= upper_bound) {
1056 field_header = *mptr++;
1057 ret->cm_fields[field_header] = strdup(mptr);
1059 while (*mptr++ != 0); /* advance to next field */
1061 } while ((mptr < upper_bound) && (field_header != 'M'));
1065 /* Always make sure there's something in the msg text field. If
1066 * it's NULL, the message text is most likely stored separately,
1067 * so go ahead and fetch that. Failing that, just set a dummy
1068 * body so other code doesn't barf.
1070 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1071 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1072 if (dmsgtext != NULL) {
1073 ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1077 if (ret->cm_fields['M'] == NULL) {
1078 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1081 /* Perform "before read" hooks (aborting if any return nonzero) */
1082 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1083 CtdlFreeMessage(ret);
1092 * Returns 1 if the supplied pointer points to a valid Citadel message.
1093 * If the pointer is NULL or the magic number check fails, returns 0.
1095 int is_valid_message(struct CtdlMessage *msg) {
1098 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1099 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1107 * 'Destructor' for struct CtdlMessage
1109 void CtdlFreeMessage(struct CtdlMessage *msg)
1113 if (is_valid_message(msg) == 0)
1115 if (msg != NULL) free (msg);
1119 for (i = 0; i < 256; ++i)
1120 if (msg->cm_fields[i] != NULL) {
1121 free(msg->cm_fields[i]);
1124 msg->cm_magic = 0; /* just in case */
1130 * Pre callback function for multipart/alternative
1132 * NOTE: this differs from the standard behavior for a reason. Normally when
1133 * displaying multipart/alternative you want to show the _last_ usable
1134 * format in the message. Here we show the _first_ one, because it's
1135 * usually text/plain. Since this set of functions is designed for text
1136 * output to non-MIME-aware clients, this is the desired behavior.
1139 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1140 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1145 ma = (struct ma_info *)cbuserdata;
1146 lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1147 if (!strcasecmp(cbtype, "multipart/alternative")) {
1151 if (!strcasecmp(cbtype, "message/rfc822")) {
1157 * Post callback function for multipart/alternative
1159 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1160 void *content, char *cbtype, char *cbcharset, size_t length,
1161 char *encoding, void *cbuserdata)
1165 ma = (struct ma_info *)cbuserdata;
1166 lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1167 if (!strcasecmp(cbtype, "multipart/alternative")) {
1171 if (!strcasecmp(cbtype, "message/rfc822")) {
1177 * Inline callback function for mime parser that wants to display text
1179 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1180 void *content, char *cbtype, char *cbcharset, size_t length,
1181 char *encoding, void *cbuserdata)
1188 ma = (struct ma_info *)cbuserdata;
1191 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1192 partnum, filename, cbtype, (long)length);
1195 * If we're in the middle of a multipart/alternative scope and
1196 * we've already printed another section, skip this one.
1198 if ( (ma->is_ma) && (ma->did_print) ) {
1199 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n", partnum, cbtype);
1204 if ( (!strcasecmp(cbtype, "text/plain"))
1205 || (IsEmptyStr(cbtype)) ) {
1208 client_write(wptr, length);
1209 if (wptr[length-1] != '\n') {
1216 if (!strcasecmp(cbtype, "text/html")) {
1217 ptr = html_to_ascii(content, length, 80, 0);
1219 client_write(ptr, wlen);
1220 if (ptr[wlen-1] != '\n') {
1227 if (ma->use_fo_hooks) {
1228 if (PerformFixedOutputHooks(cbtype, content, length)) {
1229 /* above function returns nonzero if it handled the part */
1234 if (strncasecmp(cbtype, "multipart/", 10)) {
1235 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1236 partnum, filename, cbtype, (long)length);
1242 * The client is elegant and sophisticated and wants to be choosy about
1243 * MIME content types, so figure out which multipart/alternative part
1244 * we're going to send.
1246 * We use a system of weights. When we find a part that matches one of the
1247 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1248 * and then set ma->chosen_pref to that MIME type's position in our preference
1249 * list. If we then hit another match, we only replace the first match if
1250 * the preference value is lower.
1252 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1253 void *content, char *cbtype, char *cbcharset, size_t length,
1254 char *encoding, void *cbuserdata)
1260 ma = (struct ma_info *)cbuserdata;
1262 // NOTE: REMOVING THIS CONDITIONAL FIXES BUG 220
1263 // http://bugzilla.citadel.org/show_bug.cgi?id=220
1264 // I don't know if there are any side effects! Please TEST TEST TEST
1265 //if (ma->is_ma > 0) {
1267 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1268 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1269 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1270 if (i < ma->chosen_pref) {
1271 lprintf(CTDL_DEBUG, "Setting chosen part: <%s>\n", partnum);
1272 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1273 ma->chosen_pref = i;
1280 * Now that we've chosen our preferred part, output it.
1282 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1283 void *content, char *cbtype, char *cbcharset, size_t length,
1284 char *encoding, void *cbuserdata)
1288 int add_newline = 0;
1292 ma = (struct ma_info *)cbuserdata;
1294 /* This is not the MIME part you're looking for... */
1295 if (strcasecmp(partnum, ma->chosen_part)) return;
1297 /* If the content-type of this part is in our preferred formats
1298 * list, we can simply output it verbatim.
1300 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1301 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1302 if (!strcasecmp(buf, cbtype)) {
1303 /* Yeah! Go! W00t!! */
1305 text_content = (char *)content;
1306 if (text_content[length-1] != '\n') {
1309 cprintf("Content-type: %s", cbtype);
1310 if (!IsEmptyStr(cbcharset)) {
1311 cprintf("; charset=%s", cbcharset);
1313 cprintf("\nContent-length: %d\n",
1314 (int)(length + add_newline) );
1315 if (!IsEmptyStr(encoding)) {
1316 cprintf("Content-transfer-encoding: %s\n", encoding);
1319 cprintf("Content-transfer-encoding: 7bit\n");
1321 cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1323 client_write(content, length);
1324 if (add_newline) cprintf("\n");
1329 /* No translations required or possible: output as text/plain */
1330 cprintf("Content-type: text/plain\n\n");
1331 fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1332 length, encoding, cbuserdata);
1337 char desired_section[64];
1344 * Callback function for
1346 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1347 void *content, char *cbtype, char *cbcharset, size_t length,
1348 char *encoding, void *cbuserdata)
1350 struct encapmsg *encap;
1352 encap = (struct encapmsg *)cbuserdata;
1354 /* Only proceed if this is the desired section... */
1355 if (!strcasecmp(encap->desired_section, partnum)) {
1356 encap->msglen = length;
1357 encap->msg = malloc(length + 2);
1358 memcpy(encap->msg, content, length);
1368 * Get a message off disk. (returns om_* values found in msgbase.h)
1371 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1372 int mode, /* how would you like that message? */
1373 int headers_only, /* eschew the message body? */
1374 int do_proto, /* do Citadel protocol responses? */
1375 int crlf, /* Use CRLF newlines instead of LF? */
1376 char *section /* NULL or a message/rfc822 section */
1378 struct CtdlMessage *TheMessage = NULL;
1379 int retcode = om_no_such_msg;
1380 struct encapmsg encap;
1382 lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n",
1384 (section ? section : "<>")
1387 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1388 if (do_proto) cprintf("%d Not logged in.\n",
1389 ERROR + NOT_LOGGED_IN);
1390 return(om_not_logged_in);
1393 /* FIXME: check message id against msglist for this room */
1396 * Fetch the message from disk. If we're in any sort of headers
1397 * only mode, request that we don't even bother loading the body
1400 if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1401 TheMessage = CtdlFetchMessage(msg_num, 0);
1404 TheMessage = CtdlFetchMessage(msg_num, 1);
1407 if (TheMessage == NULL) {
1408 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1409 ERROR + MESSAGE_NOT_FOUND, msg_num);
1410 return(om_no_such_msg);
1413 /* Here is the weird form of this command, to process only an
1414 * encapsulated message/rfc822 section.
1416 if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1417 memset(&encap, 0, sizeof encap);
1418 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1419 mime_parser(TheMessage->cm_fields['M'],
1421 *extract_encapsulated_message,
1422 NULL, NULL, (void *)&encap, 0
1424 CtdlFreeMessage(TheMessage);
1428 encap.msg[encap.msglen] = 0;
1429 TheMessage = convert_internet_message(encap.msg);
1430 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1432 /* Now we let it fall through to the bottom of this
1433 * function, because TheMessage now contains the
1434 * encapsulated message instead of the top-level
1435 * message. Isn't that neat?
1440 if (do_proto) cprintf("%d msg %ld has no part %s\n",
1441 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1442 retcode = om_no_such_msg;
1447 /* Ok, output the message now */
1448 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf);
1449 CtdlFreeMessage(TheMessage);
1456 * Get a message off disk. (returns om_* values found in msgbase.h)
1458 int CtdlOutputPreLoadedMsg(
1459 struct CtdlMessage *TheMessage,
1460 int mode, /* how would you like that message? */
1461 int headers_only, /* eschew the message body? */
1462 int do_proto, /* do Citadel protocol responses? */
1463 int crlf /* Use CRLF newlines instead of LF? */
1469 char display_name[256];
1471 char *nl; /* newline string */
1473 int subject_found = 0;
1476 /* Buffers needed for RFC822 translation. These are all filled
1477 * using functions that are bounds-checked, and therefore we can
1478 * make them substantially smaller than SIZ.
1486 char datestamp[100];
1488 lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1489 ((TheMessage == NULL) ? "NULL" : "not null"),
1490 mode, headers_only, do_proto, crlf);
1492 strcpy(mid, "unknown");
1493 nl = (crlf ? "\r\n" : "\n");
1495 if (!is_valid_message(TheMessage)) {
1497 "ERROR: invalid preloaded message for output\n");
1498 return(om_no_such_msg);
1501 /* Are we downloading a MIME component? */
1502 if (mode == MT_DOWNLOAD) {
1503 if (TheMessage->cm_format_type != FMT_RFC822) {
1505 cprintf("%d This is not a MIME message.\n",
1506 ERROR + ILLEGAL_VALUE);
1507 } else if (CC->download_fp != NULL) {
1508 if (do_proto) cprintf(
1509 "%d You already have a download open.\n",
1510 ERROR + RESOURCE_BUSY);
1512 /* Parse the message text component */
1513 mptr = TheMessage->cm_fields['M'];
1514 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1515 /* If there's no file open by this time, the requested
1516 * section wasn't found, so print an error
1518 if (CC->download_fp == NULL) {
1519 if (do_proto) cprintf(
1520 "%d Section %s not found.\n",
1521 ERROR + FILE_NOT_FOUND,
1522 CC->download_desired_section);
1525 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1528 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
1529 * in a single server operation instead of opening a download file.
1531 if (mode == MT_SPEW_SECTION) {
1532 if (TheMessage->cm_format_type != FMT_RFC822) {
1534 cprintf("%d This is not a MIME message.\n",
1535 ERROR + ILLEGAL_VALUE);
1537 /* Parse the message text component */
1540 mptr = TheMessage->cm_fields['M'];
1541 mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
1542 /* If section wasn't found, print an error
1545 if (do_proto) cprintf(
1546 "%d Section %s not found.\n",
1547 ERROR + FILE_NOT_FOUND,
1548 CC->download_desired_section);
1551 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1554 /* now for the user-mode message reading loops */
1555 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1557 /* Does the caller want to skip the headers? */
1558 if (headers_only == HEADERS_NONE) goto START_TEXT;
1560 /* Tell the client which format type we're using. */
1561 if ( (mode == MT_CITADEL) && (do_proto) ) {
1562 cprintf("type=%d\n", TheMessage->cm_format_type);
1565 /* nhdr=yes means that we're only displaying headers, no body */
1566 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1567 && (mode == MT_CITADEL)
1570 cprintf("nhdr=yes\n");
1573 /* begin header processing loop for Citadel message format */
1575 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1577 safestrncpy(display_name, "<unknown>", sizeof display_name);
1578 if (TheMessage->cm_fields['A']) {
1579 strcpy(buf, TheMessage->cm_fields['A']);
1580 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1581 safestrncpy(display_name, "****", sizeof display_name);
1583 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1584 safestrncpy(display_name, "anonymous", sizeof display_name);
1587 safestrncpy(display_name, buf, sizeof display_name);
1589 if ((is_room_aide())
1590 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1591 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1592 size_t tmp = strlen(display_name);
1593 snprintf(&display_name[tmp],
1594 sizeof display_name - tmp,
1599 /* Don't show Internet address for users on the
1600 * local Citadel network.
1603 if (TheMessage->cm_fields['N'] != NULL)
1604 if (!IsEmptyStr(TheMessage->cm_fields['N']))
1605 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1609 /* Now spew the header fields in the order we like them. */
1610 safestrncpy(allkeys, FORDER, sizeof allkeys);
1611 for (i=0; i<strlen(allkeys); ++i) {
1612 k = (int) allkeys[i];
1614 if ( (TheMessage->cm_fields[k] != NULL)
1615 && (msgkeys[k] != NULL) ) {
1617 if (do_proto) cprintf("%s=%s\n",
1621 else if ((k == 'F') && (suppress_f)) {
1624 /* Masquerade display name if needed */
1626 if (do_proto) cprintf("%s=%s\n",
1628 TheMessage->cm_fields[k]
1637 /* begin header processing loop for RFC822 transfer format */
1642 strcpy(snode, NODENAME);
1643 strcpy(lnode, HUMANNODE);
1644 if (mode == MT_RFC822) {
1645 for (i = 0; i < 256; ++i) {
1646 if (TheMessage->cm_fields[i]) {
1647 mptr = TheMessage->cm_fields[i];
1650 safestrncpy(luser, mptr, sizeof luser);
1651 safestrncpy(suser, mptr, sizeof suser);
1653 else if (i == 'Y') {
1654 cprintf("CC: %s%s", mptr, nl);
1656 else if (i == 'P') {
1657 cprintf("Return-Path: %s%s", mptr, nl);
1659 else if (i == 'V') {
1660 cprintf("Envelope-To: %s%s", mptr, nl);
1662 else if (i == 'U') {
1663 cprintf("Subject: %s%s", mptr, nl);
1667 safestrncpy(mid, mptr, sizeof mid);
1669 safestrncpy(lnode, mptr, sizeof lnode);
1671 safestrncpy(fuser, mptr, sizeof fuser);
1672 /* else if (i == 'O')
1673 cprintf("X-Citadel-Room: %s%s",
1676 safestrncpy(snode, mptr, sizeof snode);
1679 if (haschar(mptr, '@') == 0)
1681 cprintf("To: %s@%s%s", mptr, config.c_fqdn, nl);
1685 cprintf("To: %s%s", mptr, nl);
1688 else if (i == 'T') {
1689 datestring(datestamp, sizeof datestamp,
1690 atol(mptr), DATESTRING_RFC822);
1691 cprintf("Date: %s%s", datestamp, nl);
1695 if (subject_found == 0) {
1696 cprintf("Subject: (no subject)%s", nl);
1700 for (i=0; !IsEmptyStr(&suser[i]); ++i) {
1701 suser[i] = tolower(suser[i]);
1702 if (!isalnum(suser[i])) suser[i]='_';
1705 if (mode == MT_RFC822) {
1706 if (!strcasecmp(snode, NODENAME)) {
1707 safestrncpy(snode, FQDN, sizeof snode);
1710 /* Construct a fun message id */
1711 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
1712 if (strchr(mid, '@')==NULL) {
1713 cprintf("@%s", snode);
1717 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1718 cprintf("From: \"----\" <x@x.org>%s", nl);
1720 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1721 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1723 else if (!IsEmptyStr(fuser)) {
1724 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1727 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1730 cprintf("Organization: %s%s", lnode, nl);
1732 /* Blank line signifying RFC822 end-of-headers */
1733 if (TheMessage->cm_format_type != FMT_RFC822) {
1738 /* end header processing loop ... at this point, we're in the text */
1740 if (headers_only == HEADERS_FAST) goto DONE;
1741 mptr = TheMessage->cm_fields['M'];
1743 /* Tell the client about the MIME parts in this message */
1744 if (TheMessage->cm_format_type == FMT_RFC822) {
1745 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1746 memset(&ma, 0, sizeof(struct ma_info));
1747 mime_parser(mptr, NULL,
1748 (do_proto ? *list_this_part : NULL),
1749 (do_proto ? *list_this_pref : NULL),
1750 (do_proto ? *list_this_suff : NULL),
1753 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1754 char *start_of_text = NULL;
1755 start_of_text = strstr(mptr, "\n\r\n");
1756 if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1757 if (start_of_text == NULL) start_of_text = mptr;
1759 start_of_text = strstr(start_of_text, "\n");
1764 int nllen = strlen(nl);
1765 while (ch=*mptr, ch!=0) {
1771 ((headers_only == HEADERS_NONE) && (mptr >= start_of_text))
1772 || ((headers_only == HEADERS_ONLY) && (mptr < start_of_text))
1773 || ((headers_only != HEADERS_NONE) && (headers_only != HEADERS_ONLY))
1776 sprintf(&outbuf[outlen], "%s", nl);
1780 outbuf[outlen++] = ch;
1785 if (outlen > 1000) {
1786 client_write(outbuf, outlen);
1791 client_write(outbuf, outlen);
1799 if (headers_only == HEADERS_ONLY) {
1803 /* signify start of msg text */
1804 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1805 if (do_proto) cprintf("text\n");
1808 /* If the format type on disk is 1 (fixed-format), then we want
1809 * everything to be output completely literally ... regardless of
1810 * what message transfer format is in use.
1812 if (TheMessage->cm_format_type == FMT_FIXED) {
1814 if (mode == MT_MIME) {
1815 cprintf("Content-type: text/plain\n\n");
1819 while (ch = *mptr++, ch > 0) {
1822 if ((ch == 10) || (buflen > 250)) {
1824 cprintf("%s%s", buf, nl);
1833 if (!IsEmptyStr(buf))
1834 cprintf("%s%s", buf, nl);
1837 /* If the message on disk is format 0 (Citadel vari-format), we
1838 * output using the formatter at 80 columns. This is the final output
1839 * form if the transfer format is RFC822, but if the transfer format
1840 * is Citadel proprietary, it'll still work, because the indentation
1841 * for new paragraphs is correct and the client will reformat the
1842 * message to the reader's screen width.
1844 if (TheMessage->cm_format_type == FMT_CITADEL) {
1845 if (mode == MT_MIME) {
1846 cprintf("Content-type: text/x-citadel-variformat\n\n");
1848 memfmout(mptr, 0, nl);
1851 /* If the message on disk is format 4 (MIME), we've gotta hand it
1852 * off to the MIME parser. The client has already been told that
1853 * this message is format 1 (fixed format), so the callback function
1854 * we use will display those parts as-is.
1856 if (TheMessage->cm_format_type == FMT_RFC822) {
1857 memset(&ma, 0, sizeof(struct ma_info));
1859 if (mode == MT_MIME) {
1860 ma.use_fo_hooks = 0;
1861 strcpy(ma.chosen_part, "1");
1862 ma.chosen_pref = 9999;
1863 mime_parser(mptr, NULL,
1864 *choose_preferred, *fixed_output_pre,
1865 *fixed_output_post, (void *)&ma, 0);
1866 mime_parser(mptr, NULL,
1867 *output_preferred, NULL, NULL, (void *)&ma, CC->msg4_dont_decode);
1870 ma.use_fo_hooks = 1;
1871 mime_parser(mptr, NULL,
1872 *fixed_output, *fixed_output_pre,
1873 *fixed_output_post, (void *)&ma, 0);
1878 DONE: /* now we're done */
1879 if (do_proto) cprintf("000\n");
1886 * display a message (mode 0 - Citadel proprietary)
1888 void cmd_msg0(char *cmdbuf)
1891 int headers_only = HEADERS_ALL;
1893 msgid = extract_long(cmdbuf, 0);
1894 headers_only = extract_int(cmdbuf, 1);
1896 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1902 * display a message (mode 2 - RFC822)
1904 void cmd_msg2(char *cmdbuf)
1907 int headers_only = HEADERS_ALL;
1909 msgid = extract_long(cmdbuf, 0);
1910 headers_only = extract_int(cmdbuf, 1);
1912 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1918 * display a message (mode 3 - IGnet raw format - internal programs only)
1920 void cmd_msg3(char *cmdbuf)
1923 struct CtdlMessage *msg = NULL;
1926 if (CC->internal_pgm == 0) {
1927 cprintf("%d This command is for internal programs only.\n",
1928 ERROR + HIGHER_ACCESS_REQUIRED);
1932 msgnum = extract_long(cmdbuf, 0);
1933 msg = CtdlFetchMessage(msgnum, 1);
1935 cprintf("%d Message %ld not found.\n",
1936 ERROR + MESSAGE_NOT_FOUND, msgnum);
1940 serialize_message(&smr, msg);
1941 CtdlFreeMessage(msg);
1944 cprintf("%d Unable to serialize message\n",
1945 ERROR + INTERNAL_ERROR);
1949 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1950 client_write((char *)smr.ser, (int)smr.len);
1957 * Display a message using MIME content types
1959 void cmd_msg4(char *cmdbuf)
1964 msgid = extract_long(cmdbuf, 0);
1965 extract_token(section, cmdbuf, 1, '|', sizeof section);
1966 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1972 * Client tells us its preferred message format(s)
1974 void cmd_msgp(char *cmdbuf)
1976 if (!strcasecmp(cmdbuf, "dont_decode")) {
1977 CC->msg4_dont_decode = 1;
1978 cprintf("%d MSG4 will not pre-decode messages.\n", CIT_OK);
1981 safestrncpy(CC->preferred_formats, cmdbuf, sizeof(CC->preferred_formats));
1982 cprintf("%d Preferred MIME formats have been set.\n", CIT_OK);
1988 * Open a component of a MIME message as a download file
1990 void cmd_opna(char *cmdbuf)
1993 char desired_section[128];
1995 msgid = extract_long(cmdbuf, 0);
1996 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1997 safestrncpy(CC->download_desired_section, desired_section,
1998 sizeof CC->download_desired_section);
1999 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
2004 * Open a component of a MIME message and transmit it all at once
2006 void cmd_dlat(char *cmdbuf)
2009 char desired_section[128];
2011 msgid = extract_long(cmdbuf, 0);
2012 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2013 safestrncpy(CC->download_desired_section, desired_section,
2014 sizeof CC->download_desired_section);
2015 CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL);
2020 * Save one or more message pointers into a specified room
2021 * (Returns 0 for success, nonzero for failure)
2022 * roomname may be NULL to use the current room
2024 * Note that the 'supplied_msg' field may be set to NULL, in which case
2025 * the message will be fetched from disk, by number, if we need to perform
2026 * replication checks. This adds an additional database read, so if the
2027 * caller already has the message in memory then it should be supplied. (Obviously
2028 * this mode of operation only works if we're saving a single message.)
2030 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2031 int do_repl_check, struct CtdlMessage *supplied_msg)
2034 char hold_rm[ROOMNAMELEN];
2035 struct cdbdata *cdbfr;
2038 long highest_msg = 0L;
2041 struct CtdlMessage *msg = NULL;
2043 long *msgs_to_be_merged = NULL;
2044 int num_msgs_to_be_merged = 0;
2047 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d)\n",
2048 roomname, num_newmsgs, do_repl_check);
2050 strcpy(hold_rm, CC->room.QRname);
2053 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2054 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2055 if (num_newmsgs > 1) supplied_msg = NULL;
2057 /* Now the regular stuff */
2058 if (lgetroom(&CC->room,
2059 ((roomname != NULL) ? roomname : CC->room.QRname) )
2061 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
2062 return(ERROR + ROOM_NOT_FOUND);
2066 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2067 num_msgs_to_be_merged = 0;
2070 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2071 if (cdbfr == NULL) {
2075 msglist = (long *) cdbfr->ptr;
2076 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2077 num_msgs = cdbfr->len / sizeof(long);
2082 /* Create a list of msgid's which were supplied by the caller, but do
2083 * not already exist in the target room. It is absolutely taboo to
2084 * have more than one reference to the same message in a room.
2086 for (i=0; i<num_newmsgs; ++i) {
2088 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2089 if (msglist[j] == newmsgidlist[i]) {
2094 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2098 lprintf(9, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2101 * Now merge the new messages
2103 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2104 if (msglist == NULL) {
2105 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
2107 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2108 num_msgs += num_msgs_to_be_merged;
2110 /* Sort the message list, so all the msgid's are in order */
2111 num_msgs = sort_msglist(msglist, num_msgs);
2113 /* Determine the highest message number */
2114 highest_msg = msglist[num_msgs - 1];
2116 /* Write it back to disk. */
2117 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2118 msglist, (int)(num_msgs * sizeof(long)));
2120 /* Free up the memory we used. */
2123 /* Update the highest-message pointer and unlock the room. */
2124 CC->room.QRhighest = highest_msg;
2125 lputroom(&CC->room);
2127 /* Perform replication checks if necessary */
2128 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2129 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2131 for (i=0; i<num_msgs_to_be_merged; ++i) {
2132 msgid = msgs_to_be_merged[i];
2134 if (supplied_msg != NULL) {
2138 msg = CtdlFetchMessage(msgid, 0);
2142 ReplicationChecks(msg);
2144 /* If the message has an Exclusive ID, index that... */
2145 if (msg->cm_fields['E'] != NULL) {
2146 index_message_by_euid(msg->cm_fields['E'], &CC->room, msgid);
2149 /* Free up the memory we may have allocated */
2150 if (msg != supplied_msg) {
2151 CtdlFreeMessage(msg);
2159 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2162 /* Submit this room for processing by hooks */
2163 PerformRoomHooks(&CC->room);
2165 /* Go back to the room we were in before we wandered here... */
2166 getroom(&CC->room, hold_rm);
2168 /* Bump the reference count for all messages which were merged */
2169 for (i=0; i<num_msgs_to_be_merged; ++i) {
2170 AdjRefCount(msgs_to_be_merged[i], +1);
2173 /* Free up memory... */
2174 if (msgs_to_be_merged != NULL) {
2175 free(msgs_to_be_merged);
2178 /* Return success. */
2184 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2187 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2188 int do_repl_check, struct CtdlMessage *supplied_msg)
2190 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg);
2197 * Message base operation to save a new message to the message store
2198 * (returns new message number)
2200 * This is the back end for CtdlSubmitMsg() and should not be directly
2201 * called by server-side modules.
2204 long send_message(struct CtdlMessage *msg) {
2212 /* Get a new message number */
2213 newmsgid = get_new_message_number();
2214 snprintf(msgidbuf, sizeof msgidbuf, "%010ld@%s", newmsgid, config.c_fqdn);
2216 /* Generate an ID if we don't have one already */
2217 if (msg->cm_fields['I']==NULL) {
2218 msg->cm_fields['I'] = strdup(msgidbuf);
2221 /* If the message is big, set its body aside for storage elsewhere */
2222 if (msg->cm_fields['M'] != NULL) {
2223 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2225 holdM = msg->cm_fields['M'];
2226 msg->cm_fields['M'] = NULL;
2230 /* Serialize our data structure for storage in the database */
2231 serialize_message(&smr, msg);
2234 msg->cm_fields['M'] = holdM;
2238 cprintf("%d Unable to serialize message\n",
2239 ERROR + INTERNAL_ERROR);
2243 /* Write our little bundle of joy into the message base */
2244 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2245 smr.ser, smr.len) < 0) {
2246 lprintf(CTDL_ERR, "Can't store message\n");
2250 cdb_store(CDB_BIGMSGS,
2260 /* Free the memory we used for the serialized message */
2263 /* Return the *local* message ID to the caller
2264 * (even if we're storing an incoming network message)
2272 * Serialize a struct CtdlMessage into the format used on disk and network.
2274 * This function loads up a "struct ser_ret" (defined in server.h) which
2275 * contains the length of the serialized message and a pointer to the
2276 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2278 void serialize_message(struct ser_ret *ret, /* return values */
2279 struct CtdlMessage *msg) /* unserialized msg */
2281 size_t wlen, fieldlen;
2283 static char *forder = FORDER;
2286 * Check for valid message format
2288 if (is_valid_message(msg) == 0) {
2289 lprintf(CTDL_ERR, "serialize_message() aborting due to invalid message\n");
2296 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2297 ret->len = ret->len +
2298 strlen(msg->cm_fields[(int)forder[i]]) + 2;
2300 ret->ser = malloc(ret->len);
2301 if (ret->ser == NULL) {
2302 lprintf(CTDL_ERR, "serialize_message() malloc(%ld) failed: %s\n",
2303 (long)ret->len, strerror(errno));
2310 ret->ser[1] = msg->cm_anon_type;
2311 ret->ser[2] = msg->cm_format_type;
2314 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2315 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
2316 ret->ser[wlen++] = (char)forder[i];
2317 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
2318 wlen = wlen + fieldlen + 1;
2320 if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2321 (long)ret->len, (long)wlen);
2328 * Serialize a struct CtdlMessage into the format used on disk and network.
2330 * This function loads up a "struct ser_ret" (defined in server.h) which
2331 * contains the length of the serialized message and a pointer to the
2332 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2334 void dump_message(struct CtdlMessage *msg, /* unserialized msg */
2335 long Siz) /* how many chars ? */
2339 static char *forder = FORDER;
2343 * Check for valid message format
2345 if (is_valid_message(msg) == 0) {
2346 lprintf(CTDL_ERR, "dump_message() aborting due to invalid message\n");
2350 buf = (char*) malloc (Siz + 1);
2354 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2355 snprintf (buf, Siz, " msg[%c] = %s ...\n", (char) forder[i],
2356 msg->cm_fields[(int)forder[i]]);
2357 client_write (buf, strlen(buf));
2366 * Check to see if any messages already exist in the current room which
2367 * carry the same Exclusive ID as this one. If any are found, delete them.
2369 void ReplicationChecks(struct CtdlMessage *msg) {
2370 long old_msgnum = (-1L);
2372 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2374 lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2377 /* No exclusive id? Don't do anything. */
2378 if (msg == NULL) return;
2379 if (msg->cm_fields['E'] == NULL) return;
2380 if (IsEmptyStr(msg->cm_fields['E'])) return;
2381 /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2382 msg->cm_fields['E'], CC->room.QRname);*/
2384 old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2385 if (old_msgnum > 0L) {
2386 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2387 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2394 * Save a message to disk and submit it into the delivery system.
2396 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2397 struct recptypes *recps, /* recipients (if mail) */
2398 char *force /* force a particular room? */
2400 char submit_filename[128];
2401 char generated_timestamp[32];
2402 char hold_rm[ROOMNAMELEN];
2403 char actual_rm[ROOMNAMELEN];
2404 char force_room[ROOMNAMELEN];
2405 char content_type[SIZ]; /* We have to learn this */
2406 char recipient[SIZ];
2409 struct ctdluser userbuf;
2411 struct MetaData smi;
2412 FILE *network_fp = NULL;
2413 static int seqnum = 1;
2414 struct CtdlMessage *imsg = NULL;
2416 size_t instr_alloc = 0;
2418 char *hold_R, *hold_D;
2419 char *collected_addresses = NULL;
2420 struct addresses_to_be_filed *aptr = NULL;
2421 char *saved_rfc822_version = NULL;
2422 int qualified_for_journaling = 0;
2423 struct CitContext *CCC = CC; /* CachedCitContext - performance boost */
2425 lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2426 if (is_valid_message(msg) == 0) return(-1); /* self check */
2428 /* If this message has no timestamp, we take the liberty of
2429 * giving it one, right now.
2431 if (msg->cm_fields['T'] == NULL) {
2432 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2433 msg->cm_fields['T'] = strdup(generated_timestamp);
2436 /* If this message has no path, we generate one.
2438 if (msg->cm_fields['P'] == NULL) {
2439 if (msg->cm_fields['A'] != NULL) {
2440 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2441 for (a=0; !IsEmptyStr(&msg->cm_fields['P'][a]); ++a) {
2442 if (isspace(msg->cm_fields['P'][a])) {
2443 msg->cm_fields['P'][a] = ' ';
2448 msg->cm_fields['P'] = strdup("unknown");
2452 if (force == NULL) {
2453 strcpy(force_room, "");
2456 strcpy(force_room, force);
2459 /* Learn about what's inside, because it's what's inside that counts */
2460 if (msg->cm_fields['M'] == NULL) {
2461 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2465 switch (msg->cm_format_type) {
2467 strcpy(content_type, "text/x-citadel-variformat");
2470 strcpy(content_type, "text/plain");
2473 strcpy(content_type, "text/plain");
2474 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type:");
2477 safestrncpy(content_type, &mptr[13], sizeof content_type);
2478 striplt(content_type);
2479 aptr = content_type;
2480 while (!IsEmptyStr(aptr)) {
2492 /* Goto the correct room */
2493 lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CCC->room.QRname : SENTITEMS);
2494 strcpy(hold_rm, CCC->room.QRname);
2495 strcpy(actual_rm, CCC->room.QRname);
2496 if (recps != NULL) {
2497 strcpy(actual_rm, SENTITEMS);
2500 /* If the user is a twit, move to the twit room for posting */
2502 if (CCC->user.axlevel == 2) {
2503 strcpy(hold_rm, actual_rm);
2504 strcpy(actual_rm, config.c_twitroom);
2505 lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2509 /* ...or if this message is destined for Aide> then go there. */
2510 if (!IsEmptyStr(force_room)) {
2511 strcpy(actual_rm, force_room);
2514 lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2515 if (strcasecmp(actual_rm, CCC->room.QRname)) {
2516 /* getroom(&CCC->room, actual_rm); */
2517 usergoto(actual_rm, 0, 1, NULL, NULL);
2521 * If this message has no O (room) field, generate one.
2523 if (msg->cm_fields['O'] == NULL) {
2524 msg->cm_fields['O'] = strdup(CCC->room.QRname);
2527 /* Perform "before save" hooks (aborting if any return nonzero) */
2528 lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2529 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2532 * If this message has an Exclusive ID, and the room is replication
2533 * checking enabled, then do replication checks.
2535 if (DoesThisRoomNeedEuidIndexing(&CCC->room)) {
2536 ReplicationChecks(msg);
2539 /* Save it to disk */
2540 lprintf(CTDL_DEBUG, "Saving to disk\n");
2541 newmsgid = send_message(msg);
2542 if (newmsgid <= 0L) return(-5);
2544 /* Write a supplemental message info record. This doesn't have to
2545 * be a critical section because nobody else knows about this message
2548 lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2549 memset(&smi, 0, sizeof(struct MetaData));
2550 smi.meta_msgnum = newmsgid;
2551 smi.meta_refcount = 0;
2552 safestrncpy(smi.meta_content_type, content_type,
2553 sizeof smi.meta_content_type);
2556 * Measure how big this message will be when rendered as RFC822.
2557 * We do this for two reasons:
2558 * 1. We need the RFC822 length for the new metadata record, so the
2559 * POP and IMAP services don't have to calculate message lengths
2560 * while the user is waiting (multiplied by potentially hundreds
2561 * or thousands of messages).
2562 * 2. If journaling is enabled, we will need an RFC822 version of the
2563 * message to attach to the journalized copy.
2565 if (CCC->redirect_buffer != NULL) {
2566 lprintf(CTDL_ALERT, "CCC->redirect_buffer is not NULL during message submission!\n");
2569 CCC->redirect_buffer = malloc(SIZ);
2570 CCC->redirect_len = 0;
2571 CCC->redirect_alloc = SIZ;
2572 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2573 smi.meta_rfc822_length = CCC->redirect_len;
2574 saved_rfc822_version = CCC->redirect_buffer;
2575 CCC->redirect_buffer = NULL;
2576 CCC->redirect_len = 0;
2577 CCC->redirect_alloc = 0;
2581 /* Now figure out where to store the pointers */
2582 lprintf(CTDL_DEBUG, "Storing pointers\n");
2584 /* If this is being done by the networker delivering a private
2585 * message, we want to BYPASS saving the sender's copy (because there
2586 * is no local sender; it would otherwise go to the Trashcan).
2588 if ((!CCC->internal_pgm) || (recps == NULL)) {
2589 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2590 lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2591 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2595 /* For internet mail, drop a copy in the outbound queue room */
2597 if (recps->num_internet > 0) {
2598 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2601 /* If other rooms are specified, drop them there too. */
2603 if (recps->num_room > 0)
2604 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2605 extract_token(recipient, recps->recp_room, i,
2606 '|', sizeof recipient);
2607 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2608 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2611 /* Bump this user's messages posted counter. */
2612 lprintf(CTDL_DEBUG, "Updating user\n");
2613 lgetuser(&CCC->user, CCC->curr_user);
2614 CCC->user.posted = CCC->user.posted + 1;
2615 lputuser(&CCC->user);
2617 /* If this is private, local mail, make a copy in the
2618 * recipient's mailbox and bump the reference count.
2621 if (recps->num_local > 0)
2622 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2623 extract_token(recipient, recps->recp_local, i,
2624 '|', sizeof recipient);
2625 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2627 if (getuser(&userbuf, recipient) == 0) {
2628 // Add a flag so the Funambol module knows its mail
2629 msg->cm_fields['W'] = strdup(recipient);
2630 MailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
2631 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2632 BumpNewMailCounter(userbuf.usernum);
2633 if (!IsEmptyStr(config.c_funambol_host) || !IsEmptyStr(config.c_pager_program)) {
2634 /* Generate a instruction message for the Funambol notification
2635 * server, in the same style as the SMTP queue
2638 instr = malloc(instr_alloc);
2639 snprintf(instr, instr_alloc,
2640 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2642 SPOOLMIME, newmsgid, (long)time(NULL),
2643 msg->cm_fields['A'], msg->cm_fields['N']
2646 imsg = malloc(sizeof(struct CtdlMessage));
2647 memset(imsg, 0, sizeof(struct CtdlMessage));
2648 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2649 imsg->cm_anon_type = MES_NORMAL;
2650 imsg->cm_format_type = FMT_RFC822;
2651 imsg->cm_fields['A'] = strdup("Citadel");
2652 imsg->cm_fields['J'] = strdup("do not journal");
2653 imsg->cm_fields['M'] = instr; /* imsg owns this memory now */
2654 imsg->cm_fields['W'] = strdup(recipient);
2655 CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM);
2656 CtdlFreeMessage(imsg);
2660 lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2661 CtdlSaveMsgPointerInRoom(config.c_aideroom,
2666 /* Perform "after save" hooks */
2667 lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2668 PerformMessageHooks(msg, EVT_AFTERSAVE);
2670 /* For IGnet mail, we have to save a new copy into the spooler for
2671 * each recipient, with the R and D fields set to the recipient and
2672 * destination-node. This has two ugly side effects: all other
2673 * recipients end up being unlisted in this recipient's copy of the
2674 * message, and it has to deliver multiple messages to the same
2675 * node. We'll revisit this again in a year or so when everyone has
2676 * a network spool receiver that can handle the new style messages.
2679 if (recps->num_ignet > 0)
2680 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2681 extract_token(recipient, recps->recp_ignet, i,
2682 '|', sizeof recipient);
2684 hold_R = msg->cm_fields['R'];
2685 hold_D = msg->cm_fields['D'];
2686 msg->cm_fields['R'] = malloc(SIZ);
2687 msg->cm_fields['D'] = malloc(128);
2688 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2689 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2691 serialize_message(&smr, msg);
2693 snprintf(submit_filename, sizeof submit_filename,
2694 "%s/netmail.%04lx.%04x.%04x",
2696 (long) getpid(), CCC->cs_pid, ++seqnum);
2697 network_fp = fopen(submit_filename, "wb+");
2698 if (network_fp != NULL) {
2699 fwrite(smr.ser, smr.len, 1, network_fp);
2705 free(msg->cm_fields['R']);
2706 free(msg->cm_fields['D']);
2707 msg->cm_fields['R'] = hold_R;
2708 msg->cm_fields['D'] = hold_D;
2711 /* Go back to the room we started from */
2712 lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2713 if (strcasecmp(hold_rm, CCC->room.QRname))
2714 usergoto(hold_rm, 0, 1, NULL, NULL);
2716 /* For internet mail, generate delivery instructions.
2717 * Yes, this is recursive. Deal with it. Infinite recursion does
2718 * not happen because the delivery instructions message does not
2719 * contain a recipient.
2722 if (recps->num_internet > 0) {
2723 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2725 instr = malloc(instr_alloc);
2726 snprintf(instr, instr_alloc,
2727 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2729 SPOOLMIME, newmsgid, (long)time(NULL),
2730 msg->cm_fields['A'], msg->cm_fields['N']
2733 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2734 size_t tmp = strlen(instr);
2735 extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
2736 if ((tmp + strlen(recipient) + 32) > instr_alloc) {
2737 instr_alloc = instr_alloc * 2;
2738 instr = realloc(instr, instr_alloc);
2740 snprintf(&instr[tmp], instr_alloc - tmp, "remote|%s|0||\n", recipient);
2743 imsg = malloc(sizeof(struct CtdlMessage));
2744 memset(imsg, 0, sizeof(struct CtdlMessage));
2745 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2746 imsg->cm_anon_type = MES_NORMAL;
2747 imsg->cm_format_type = FMT_RFC822;
2748 imsg->cm_fields['A'] = strdup("Citadel");
2749 imsg->cm_fields['J'] = strdup("do not journal");
2750 imsg->cm_fields['M'] = instr; /* imsg owns this memory now */
2751 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2752 CtdlFreeMessage(imsg);
2756 * Any addresses to harvest for someone's address book?
2758 if ( (CCC->logged_in) && (recps != NULL) ) {
2759 collected_addresses = harvest_collected_addresses(msg);
2762 if (collected_addresses != NULL) {
2763 begin_critical_section(S_ATBF);
2764 aptr = (struct addresses_to_be_filed *)
2765 malloc(sizeof(struct addresses_to_be_filed));
2767 MailboxName(actual_rm, sizeof actual_rm,
2768 &CCC->user, USERCONTACTSROOM);
2769 aptr->roomname = strdup(actual_rm);
2770 aptr->collected_addresses = collected_addresses;
2772 end_critical_section(S_ATBF);
2776 * Determine whether this message qualifies for journaling.
2778 if (msg->cm_fields['J'] != NULL) {
2779 qualified_for_journaling = 0;
2782 if (recps == NULL) {
2783 qualified_for_journaling = config.c_journal_pubmsgs;
2785 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2786 qualified_for_journaling = config.c_journal_email;
2789 qualified_for_journaling = config.c_journal_pubmsgs;
2794 * Do we have to perform journaling? If so, hand off the saved
2795 * RFC822 version will be handed off to the journaler for background
2796 * submit. Otherwise, we have to free the memory ourselves.
2798 if (saved_rfc822_version != NULL) {
2799 if (qualified_for_journaling) {
2800 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2803 free(saved_rfc822_version);
2816 * Convenience function for generating small administrative messages.
2818 void quickie_message(char *from, char *fromaddr, char *to, char *room, char *text,
2819 int format_type, char *subject)
2821 struct CtdlMessage *msg;
2822 struct recptypes *recp = NULL;
2824 msg = malloc(sizeof(struct CtdlMessage));
2825 memset(msg, 0, sizeof(struct CtdlMessage));
2826 msg->cm_magic = CTDLMESSAGE_MAGIC;
2827 msg->cm_anon_type = MES_NORMAL;
2828 msg->cm_format_type = format_type;
2831 msg->cm_fields['A'] = strdup(from);
2833 else if (fromaddr != NULL) {
2834 msg->cm_fields['A'] = strdup(fromaddr);
2835 if (strchr(msg->cm_fields['A'], '@')) {
2836 *strchr(msg->cm_fields['A'], '@') = 0;
2840 msg->cm_fields['A'] = strdup("Citadel");
2843 if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
2844 if (room != NULL) msg->cm_fields['O'] = strdup(room);
2845 msg->cm_fields['N'] = strdup(NODENAME);
2847 msg->cm_fields['R'] = strdup(to);
2848 recp = validate_recipients(to, NULL, 0);
2850 if (subject != NULL) {
2851 msg->cm_fields['U'] = strdup(subject);
2853 msg->cm_fields['M'] = strdup(text);
2855 CtdlSubmitMsg(msg, recp, room);
2856 CtdlFreeMessage(msg);
2857 if (recp != NULL) free_recipients(recp);
2863 * Back end function used by CtdlMakeMessage() and similar functions
2865 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2866 size_t maxlen, /* maximum message length */
2867 char *exist, /* if non-null, append to it;
2868 exist is ALWAYS freed */
2869 int crlf, /* CRLF newlines instead of LF */
2870 int sock /* socket handle or 0 for this session's client socket */
2874 size_t message_len = 0;
2875 size_t buffer_len = 0;
2882 if (exist == NULL) {
2889 message_len = strlen(exist);
2890 buffer_len = message_len + 4096;
2891 m = realloc(exist, buffer_len);
2898 /* Do we need to change leading ".." to "." for SMTP escaping? */
2899 if (!strcmp(terminator, ".")) {
2903 /* flush the input if we have nowhere to store it */
2908 /* read in the lines of message text one by one */
2911 if (sock_getln(sock, buf, (sizeof buf - 3)) < 0) finished = 1;
2914 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2916 if (!strcmp(buf, terminator)) finished = 1;
2918 strcat(buf, "\r\n");
2924 /* Unescape SMTP-style input of two dots at the beginning of the line */
2926 if (!strncmp(buf, "..", 2)) {
2927 strcpy(buf, &buf[1]);
2931 if ( (!flushing) && (!finished) ) {
2932 /* Measure the line */
2933 linelen = strlen(buf);
2935 /* augment the buffer if we have to */
2936 if ((message_len + linelen) >= buffer_len) {
2937 ptr = realloc(m, (buffer_len * 2) );
2938 if (ptr == NULL) { /* flush if can't allocate */
2941 buffer_len = (buffer_len * 2);
2943 lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2947 /* Add the new line to the buffer. NOTE: this loop must avoid
2948 * using functions like strcat() and strlen() because they
2949 * traverse the entire buffer upon every call, and doing that
2950 * for a multi-megabyte message slows it down beyond usability.
2952 strcpy(&m[message_len], buf);
2953 message_len += linelen;
2956 /* if we've hit the max msg length, flush the rest */
2957 if (message_len >= maxlen) flushing = 1;
2959 } while (!finished);
2967 * Build a binary message to be saved on disk.
2968 * (NOTE: if you supply 'preformatted_text', the buffer you give it
2969 * will become part of the message. This means you are no longer
2970 * responsible for managing that memory -- it will be freed along with
2971 * the rest of the fields when CtdlFreeMessage() is called.)
2974 struct CtdlMessage *CtdlMakeMessage(
2975 struct ctdluser *author, /* author's user structure */
2976 char *recipient, /* NULL if it's not mail */
2977 char *recp_cc, /* NULL if it's not mail */
2978 char *room, /* room where it's going */
2979 int type, /* see MES_ types in header file */
2980 int format_type, /* variformat, plain text, MIME... */
2981 char *fake_name, /* who we're masquerading as */
2982 char *my_email, /* which of my email addresses to use (empty is ok) */
2983 char *subject, /* Subject (optional) */
2984 char *supplied_euid, /* ...or NULL if this is irrelevant */
2985 char *preformatted_text /* ...or NULL to read text from client */
2987 char dest_node[256];
2989 struct CtdlMessage *msg;
2992 msg = malloc(sizeof(struct CtdlMessage));
2993 memset(msg, 0, sizeof(struct CtdlMessage));
2994 msg->cm_magic = CTDLMESSAGE_MAGIC;
2995 msg->cm_anon_type = type;
2996 msg->cm_format_type = format_type;
2998 /* Don't confuse the poor folks if it's not routed mail. */
2999 strcpy(dest_node, "");
3004 /* Path or Return-Path */
3005 if (my_email == NULL) my_email = "";
3007 if (!IsEmptyStr(my_email)) {
3008 msg->cm_fields['P'] = strdup(my_email);
3011 snprintf(buf, sizeof buf, "%s", author->fullname);
3012 msg->cm_fields['P'] = strdup(buf);
3014 for (i=0; (msg->cm_fields['P'][i]!=0); ++i) {
3015 if (isspace(msg->cm_fields['P'][i])) {
3016 msg->cm_fields['P'][i] = '_';
3020 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
3021 msg->cm_fields['T'] = strdup(buf);
3023 if (fake_name[0]) /* author */
3024 msg->cm_fields['A'] = strdup(fake_name);
3026 msg->cm_fields['A'] = strdup(author->fullname);
3028 if (CC->room.QRflags & QR_MAILBOX) { /* room */
3029 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
3032 msg->cm_fields['O'] = strdup(CC->room.QRname);
3035 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
3036 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
3038 if (recipient[0] != 0) {
3039 msg->cm_fields['R'] = strdup(recipient);
3041 if (recp_cc[0] != 0) {
3042 msg->cm_fields['Y'] = strdup(recp_cc);
3044 if (dest_node[0] != 0) {
3045 msg->cm_fields['D'] = strdup(dest_node);
3048 if (!IsEmptyStr(my_email)) {
3049 msg->cm_fields['F'] = strdup(my_email);
3051 else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
3052 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
3055 if (subject != NULL) {
3058 length = strlen(subject);
3064 while ((subject[i] != '\0') &&
3065 (IsAscii = isascii(subject[i]) != 0 ))
3068 msg->cm_fields['U'] = strdup(subject);
3069 else /* ok, we've got utf8 in the string. */
3071 msg->cm_fields['U'] = rfc2047encode(subject, length);
3077 if (supplied_euid != NULL) {
3078 msg->cm_fields['E'] = strdup(supplied_euid);
3081 if (preformatted_text != NULL) {
3082 msg->cm_fields['M'] = preformatted_text;
3085 msg->cm_fields['M'] = CtdlReadMessageBody("000", config.c_maxmsglen, NULL, 0, 0);
3093 * Check to see whether we have permission to post a message in the current
3094 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
3095 * returns 0 on success.
3097 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf,
3099 const char* RemoteIdentifier,
3103 if (!(CC->logged_in) &&
3104 (PostPublic == POST_LOGGED_IN)) {
3105 snprintf(errmsgbuf, n, "Not logged in.");
3106 return (ERROR + NOT_LOGGED_IN);
3108 else if (PostPublic == CHECK_EXISTANCE) {
3109 return (0); // We're Evaling whether a recipient exists
3111 else if (!(CC->logged_in)) {
3113 if ((CC->room.QRflags & QR_READONLY)) {
3114 snprintf(errmsgbuf, n, "Not logged in.");
3115 return (ERROR + NOT_LOGGED_IN);
3117 if (CC->room.QRflags2 & QR2_MODERATED) {
3118 snprintf(errmsgbuf, n, "Not logged in Moderation feature not yet implemented!");
3119 return (ERROR + NOT_LOGGED_IN);
3121 if ((PostPublic!=POST_LMTP) &&(CC->room.QRflags2 & QR2_SMTP_PUBLIC) == 0) {
3126 if (RemoteIdentifier == NULL)
3128 snprintf(errmsgbuf, n, "Need sender to permit access.");
3129 return (ERROR + USERNAME_REQUIRED);
3132 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
3133 begin_critical_section(S_NETCONFIGS);
3134 if (!read_spoolcontrol_file(&sc, filename))
3136 end_critical_section(S_NETCONFIGS);
3137 snprintf(errmsgbuf, n,
3138 "This mailing list only accepts posts from subscribers.");
3139 return (ERROR + NO_SUCH_USER);
3141 end_critical_section(S_NETCONFIGS);
3142 found = is_recipient (sc, RemoteIdentifier);
3143 free_spoolcontrol_struct(&sc);
3148 snprintf(errmsgbuf, n,
3149 "This mailing list only accepts posts from subscribers.");
3150 return (ERROR + NO_SUCH_USER);
3157 if ((CC->user.axlevel < 2)
3158 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
3159 snprintf(errmsgbuf, n, "Need to be validated to enter "
3160 "(except in %s> to sysop)", MAILROOM);
3161 return (ERROR + HIGHER_ACCESS_REQUIRED);
3164 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3165 if (!(ra & UA_POSTALLOWED)) {
3166 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
3167 return (ERROR + HIGHER_ACCESS_REQUIRED);
3170 strcpy(errmsgbuf, "Ok");
3176 * Check to see if the specified user has Internet mail permission
3177 * (returns nonzero if permission is granted)
3179 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
3181 /* Do not allow twits to send Internet mail */
3182 if (who->axlevel <= 2) return(0);
3184 /* Globally enabled? */
3185 if (config.c_restrict == 0) return(1);
3187 /* User flagged ok? */
3188 if (who->flags & US_INTERNET) return(2);
3190 /* Aide level access? */
3191 if (who->axlevel >= 6) return(3);
3193 /* No mail for you! */
3199 * Validate recipients, count delivery types and errors, and handle aliasing
3200 * FIXME check for dupes!!!!!
3202 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
3203 * were specified, or the number of addresses found invalid.
3205 * Caller needs to free the result using free_recipients()
3207 struct recptypes *validate_recipients(char *supplied_recipients,
3208 const char *RemoteIdentifier,
3210 struct recptypes *ret;
3211 char *recipients = NULL;
3212 char this_recp[256];
3213 char this_recp_cooked[256];
3219 struct ctdluser tempUS;
3220 struct ctdlroom tempQR;
3221 struct ctdlroom tempQR2;
3227 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
3228 if (ret == NULL) return(NULL);
3230 /* Set all strings to null and numeric values to zero */
3231 memset(ret, 0, sizeof(struct recptypes));
3233 if (supplied_recipients == NULL) {
3234 recipients = strdup("");
3237 recipients = strdup(supplied_recipients);
3240 /* Allocate some memory. Yes, this allocates 500% more memory than we will
3241 * actually need, but it's healthier for the heap than doing lots of tiny
3242 * realloc() calls instead.
3245 ret->errormsg = malloc(strlen(recipients) + 1024);
3246 ret->recp_local = malloc(strlen(recipients) + 1024);
3247 ret->recp_internet = malloc(strlen(recipients) + 1024);
3248 ret->recp_ignet = malloc(strlen(recipients) + 1024);
3249 ret->recp_room = malloc(strlen(recipients) + 1024);
3250 ret->display_recp = malloc(strlen(recipients) + 1024);
3252 ret->errormsg[0] = 0;
3253 ret->recp_local[0] = 0;
3254 ret->recp_internet[0] = 0;
3255 ret->recp_ignet[0] = 0;
3256 ret->recp_room[0] = 0;
3257 ret->display_recp[0] = 0;
3259 ret->recptypes_magic = RECPTYPES_MAGIC;
3261 /* Change all valid separator characters to commas */
3262 for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
3263 if ((recipients[i] == ';') || (recipients[i] == '|')) {
3264 recipients[i] = ',';
3268 /* Now start extracting recipients... */
3270 while (!IsEmptyStr(recipients)) {
3272 for (i=0; i<=strlen(recipients); ++i) {
3273 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
3274 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
3275 safestrncpy(this_recp, recipients, i+1);
3277 if (recipients[i] == ',') {
3278 strcpy(recipients, &recipients[i+1]);
3281 strcpy(recipients, "");
3288 if (IsEmptyStr(this_recp))
3290 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
3292 mailtype = alias(this_recp);
3293 mailtype = alias(this_recp);
3294 mailtype = alias(this_recp);
3296 for (j=0; !IsEmptyStr(&this_recp[j]); ++j) {
3297 if (this_recp[j]=='_') {
3298 this_recp_cooked[j] = ' ';
3301 this_recp_cooked[j] = this_recp[j];
3304 this_recp_cooked[j] = '\0';
3309 if (!strcasecmp(this_recp, "sysop")) {
3311 strcpy(this_recp, config.c_aideroom);
3312 if (!IsEmptyStr(ret->recp_room)) {
3313 strcat(ret->recp_room, "|");
3315 strcat(ret->recp_room, this_recp);
3317 else if (getuser(&tempUS, this_recp) == 0) {
3319 strcpy(this_recp, tempUS.fullname);
3320 if (!IsEmptyStr(ret->recp_local)) {
3321 strcat(ret->recp_local, "|");
3323 strcat(ret->recp_local, this_recp);
3325 else if (getuser(&tempUS, this_recp_cooked) == 0) {
3327 strcpy(this_recp, tempUS.fullname);
3328 if (!IsEmptyStr(ret->recp_local)) {
3329 strcat(ret->recp_local, "|");
3331 strcat(ret->recp_local, this_recp);
3333 else if ( (!strncasecmp(this_recp, "room_", 5))
3334 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
3336 /* Save room so we can restore it later */
3340 /* Check permissions to send mail to this room */
3341 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg,
3353 if (!IsEmptyStr(ret->recp_room)) {
3354 strcat(ret->recp_room, "|");
3356 strcat(ret->recp_room, &this_recp_cooked[5]);
3359 /* Restore room in case something needs it */
3369 /* Yes, you're reading this correctly: if the target
3370 * domain points back to the local system or an attached
3371 * Citadel directory, the address is invalid. That's
3372 * because if the address were valid, we would have
3373 * already translated it to a local address by now.
3375 if (IsDirectory(this_recp, 0)) {
3380 ++ret->num_internet;
3381 if (!IsEmptyStr(ret->recp_internet)) {
3382 strcat(ret->recp_internet, "|");
3384 strcat(ret->recp_internet, this_recp);
3389 if (!IsEmptyStr(ret->recp_ignet)) {
3390 strcat(ret->recp_ignet, "|");
3392 strcat(ret->recp_ignet, this_recp);
3400 if (IsEmptyStr(errmsg)) {
3401 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
3404 snprintf(append, sizeof append, "%s", errmsg);
3406 if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
3407 if (!IsEmptyStr(ret->errormsg)) {
3408 strcat(ret->errormsg, "; ");
3410 strcat(ret->errormsg, append);
3414 if (IsEmptyStr(ret->display_recp)) {
3415 strcpy(append, this_recp);
3418 snprintf(append, sizeof append, ", %s", this_recp);
3420 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
3421 strcat(ret->display_recp, append);
3426 if ((ret->num_local + ret->num_internet + ret->num_ignet +
3427 ret->num_room + ret->num_error) == 0) {
3428 ret->num_error = (-1);
3429 strcpy(ret->errormsg, "No recipients specified.");
3432 lprintf(CTDL_DEBUG, "validate_recipients()\n");
3433 lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
3434 lprintf(CTDL_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
3435 lprintf(CTDL_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
3436 lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
3437 lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
3445 * Destructor for struct recptypes
3447 void free_recipients(struct recptypes *valid) {
3449 if (valid == NULL) {
3453 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
3454 lprintf(CTDL_EMERG, "Attempt to call free_recipients() on some other data type!\n");
3458 if (valid->errormsg != NULL) free(valid->errormsg);
3459 if (valid->recp_local != NULL) free(valid->recp_local);
3460 if (valid->recp_internet != NULL) free(valid->recp_internet);
3461 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
3462 if (valid->recp_room != NULL) free(valid->recp_room);
3463 if (valid->display_recp != NULL) free(valid->display_recp);
3470 * message entry - mode 0 (normal)
3472 void cmd_ent0(char *entargs)
3478 char supplied_euid[128];
3480 int format_type = 0;
3481 char newusername[256];
3482 char newuseremail[256];
3483 struct CtdlMessage *msg;
3487 struct recptypes *valid = NULL;
3488 struct recptypes *valid_to = NULL;
3489 struct recptypes *valid_cc = NULL;
3490 struct recptypes *valid_bcc = NULL;
3492 int subject_required = 0;
3497 int newuseremail_ok = 0;
3501 post = extract_int(entargs, 0);
3502 extract_token(recp, entargs, 1, '|', sizeof recp);
3503 anon_flag = extract_int(entargs, 2);
3504 format_type = extract_int(entargs, 3);
3505 extract_token(subject, entargs, 4, '|', sizeof subject);
3506 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3507 do_confirm = extract_int(entargs, 6);
3508 extract_token(cc, entargs, 7, '|', sizeof cc);
3509 extract_token(bcc, entargs, 8, '|', sizeof bcc);
3510 switch(CC->room.QRdefaultview) {
3513 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3516 supplied_euid[0] = 0;
3519 extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
3521 /* first check to make sure the request is valid. */
3523 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg, NULL, POST_LOGGED_IN);
3526 cprintf("%d %s\n", err, errmsg);
3530 /* Check some other permission type things. */
3532 if (IsEmptyStr(newusername)) {
3533 strcpy(newusername, CC->user.fullname);
3535 if ( (CC->user.axlevel < 6)
3536 && (strcasecmp(newusername, CC->user.fullname))
3537 && (strcasecmp(newusername, CC->cs_inet_fn))
3539 cprintf("%d You don't have permission to author messages as '%s'.\n",
3540 ERROR + HIGHER_ACCESS_REQUIRED,
3547 if (IsEmptyStr(newuseremail)) {
3548 newuseremail_ok = 1;
3551 if (!IsEmptyStr(newuseremail)) {
3552 if (!strcasecmp(newuseremail, CC->cs_inet_email)) {
3553 newuseremail_ok = 1;
3555 else if (!IsEmptyStr(CC->cs_inet_other_emails)) {
3556 j = num_tokens(CC->cs_inet_other_emails, '|');
3557 for (i=0; i<j; ++i) {
3558 extract_token(buf, CC->cs_inet_other_emails, i, '|', sizeof buf);
3559 if (!strcasecmp(newuseremail, buf)) {
3560 newuseremail_ok = 1;
3566 if (!newuseremail_ok) {
3567 cprintf("%d You don't have permission to author messages as '%s'.\n",
3568 ERROR + HIGHER_ACCESS_REQUIRED,
3574 CC->cs_flags |= CS_POSTING;
3576 /* In mailbox rooms we have to behave a little differently --
3577 * make sure the user has specified at least one recipient. Then
3578 * validate the recipient(s). We do this for the Mail> room, as
3579 * well as any room which has the "Mailbox" view set.
3582 if ( ( (CC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) )
3583 || ( (CC->room.QRflags & QR_MAILBOX) && (CC->curr_view == VIEW_MAILBOX) )
3585 if (CC->user.axlevel < 2) {
3586 strcpy(recp, "sysop");
3591 valid_to = validate_recipients(recp, NULL, 0);
3592 if (valid_to->num_error > 0) {
3593 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_to->errormsg);
3594 free_recipients(valid_to);
3598 valid_cc = validate_recipients(cc, NULL, 0);
3599 if (valid_cc->num_error > 0) {
3600 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_cc->errormsg);
3601 free_recipients(valid_to);
3602 free_recipients(valid_cc);
3606 valid_bcc = validate_recipients(bcc, NULL, 0);
3607 if (valid_bcc->num_error > 0) {
3608 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_bcc->errormsg);
3609 free_recipients(valid_to);
3610 free_recipients(valid_cc);
3611 free_recipients(valid_bcc);
3615 /* Recipient required, but none were specified */
3616 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3617 free_recipients(valid_to);
3618 free_recipients(valid_cc);
3619 free_recipients(valid_bcc);
3620 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3624 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3625 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3626 cprintf("%d You do not have permission "
3627 "to send Internet mail.\n",
3628 ERROR + HIGHER_ACCESS_REQUIRED);
3629 free_recipients(valid_to);
3630 free_recipients(valid_cc);
3631 free_recipients(valid_bcc);
3636 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)
3637 && (CC->user.axlevel < 4) ) {
3638 cprintf("%d Higher access required for network mail.\n",
3639 ERROR + HIGHER_ACCESS_REQUIRED);
3640 free_recipients(valid_to);
3641 free_recipients(valid_cc);
3642 free_recipients(valid_bcc);
3646 if ((RESTRICT_INTERNET == 1)
3647 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3648 && ((CC->user.flags & US_INTERNET) == 0)
3649 && (!CC->internal_pgm)) {
3650 cprintf("%d You don't have access to Internet mail.\n",
3651 ERROR + HIGHER_ACCESS_REQUIRED);
3652 free_recipients(valid_to);
3653 free_recipients(valid_cc);
3654 free_recipients(valid_bcc);
3660 /* Is this a room which has anonymous-only or anonymous-option? */
3661 anonymous = MES_NORMAL;
3662 if (CC->room.QRflags & QR_ANONONLY) {
3663 anonymous = MES_ANONONLY;
3665 if (CC->room.QRflags & QR_ANONOPT) {
3666 if (anon_flag == 1) { /* only if the user requested it */
3667 anonymous = MES_ANONOPT;
3671 if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3675 /* Recommend to the client that the use of a message subject is
3676 * strongly recommended in this room, if either the SUBJECTREQ flag
3677 * is set, or if there is one or more Internet email recipients.
3679 if (CC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
3680 if (valid_to) if (valid_to->num_internet > 0) subject_required = 1;
3681 if (valid_cc) if (valid_cc->num_internet > 0) subject_required = 1;
3682 if (valid_bcc) if (valid_bcc->num_internet > 0) subject_required = 1;
3684 /* If we're only checking the validity of the request, return
3685 * success without creating the message.
3688 cprintf("%d %s|%d\n", CIT_OK,
3689 ((valid_to != NULL) ? valid_to->display_recp : ""),
3691 free_recipients(valid_to);
3692 free_recipients(valid_cc);
3693 free_recipients(valid_bcc);
3697 /* We don't need these anymore because we'll do it differently below */
3698 free_recipients(valid_to);
3699 free_recipients(valid_cc);
3700 free_recipients(valid_bcc);
3702 /* Read in the message from the client. */
3704 cprintf("%d send message\n", START_CHAT_MODE);
3706 cprintf("%d send message\n", SEND_LISTING);
3709 msg = CtdlMakeMessage(&CC->user, recp, cc,
3710 CC->room.QRname, anonymous, format_type,
3711 newusername, newuseremail, subject,
3712 ((!IsEmptyStr(supplied_euid)) ? supplied_euid : NULL),
3715 /* Put together one big recipients struct containing to/cc/bcc all in
3716 * one. This is for the envelope.
3718 char *all_recps = malloc(SIZ * 3);
3719 strcpy(all_recps, recp);
3720 if (!IsEmptyStr(cc)) {
3721 if (!IsEmptyStr(all_recps)) {
3722 strcat(all_recps, ",");
3724 strcat(all_recps, cc);
3726 if (!IsEmptyStr(bcc)) {
3727 if (!IsEmptyStr(all_recps)) {
3728 strcat(all_recps, ",");
3730 strcat(all_recps, bcc);
3732 if (!IsEmptyStr(all_recps)) {
3733 valid = validate_recipients(all_recps, NULL, 0);
3741 msgnum = CtdlSubmitMsg(msg, valid, "");
3744 cprintf("%ld\n", msgnum);
3746 cprintf("Message accepted.\n");
3749 cprintf("Internal error.\n");
3751 if (msg->cm_fields['E'] != NULL) {
3752 cprintf("%s\n", msg->cm_fields['E']);
3759 CtdlFreeMessage(msg);
3761 if (valid != NULL) {
3762 free_recipients(valid);
3770 * API function to delete messages which match a set of criteria
3771 * (returns the actual number of messages deleted)
3773 int CtdlDeleteMessages(char *room_name, /* which room */
3774 long *dmsgnums, /* array of msg numbers to be deleted */
3775 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
3776 char *content_type /* or "" for any. regular expressions expected. */
3779 struct ctdlroom qrbuf;
3780 struct cdbdata *cdbfr;
3781 long *msglist = NULL;
3782 long *dellist = NULL;
3785 int num_deleted = 0;
3787 struct MetaData smi;
3790 int need_to_free_re = 0;
3792 if (content_type) if (!IsEmptyStr(content_type)) {
3793 regcomp(&re, content_type, 0);
3794 need_to_free_re = 1;
3796 lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
3797 room_name, num_dmsgnums, content_type);
3799 /* get room record, obtaining a lock... */
3800 if (lgetroom(&qrbuf, room_name) != 0) {
3801 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3803 if (need_to_free_re) regfree(&re);
3804 return (0); /* room not found */
3806 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3808 if (cdbfr != NULL) {
3809 dellist = malloc(cdbfr->len);
3810 msglist = (long *) cdbfr->ptr;
3811 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3812 num_msgs = cdbfr->len / sizeof(long);
3816 for (i = 0; i < num_msgs; ++i) {
3819 /* Set/clear a bit for each criterion */
3821 /* 0 messages in the list or a null list means that we are
3822 * interested in deleting any messages which meet the other criteria.
3824 if ((num_dmsgnums == 0) || (dmsgnums == NULL)) {
3825 delete_this |= 0x01;
3828 for (j=0; j<num_dmsgnums; ++j) {
3829 if (msglist[i] == dmsgnums[j]) {
3830 delete_this |= 0x01;
3835 if (IsEmptyStr(content_type)) {
3836 delete_this |= 0x02;
3838 GetMetaData(&smi, msglist[i]);
3839 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
3840 delete_this |= 0x02;
3844 /* Delete message only if all bits are set */
3845 if (delete_this == 0x03) {
3846 dellist[num_deleted++] = msglist[i];
3851 num_msgs = sort_msglist(msglist, num_msgs);
3852 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3853 msglist, (int)(num_msgs * sizeof(long)));
3855 qrbuf.QRhighest = msglist[num_msgs - 1];
3859 /* Go through the messages we pulled out of the index, and decrement
3860 * their reference counts by 1. If this is the only room the message
3861 * was in, the reference count will reach zero and the message will
3862 * automatically be deleted from the database. We do this in a
3863 * separate pass because there might be plug-in hooks getting called,
3864 * and we don't want that happening during an S_ROOMS critical
3867 if (num_deleted) for (i=0; i<num_deleted; ++i) {
3868 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3869 AdjRefCount(dellist[i], -1);
3872 /* Now free the memory we used, and go away. */
3873 if (msglist != NULL) free(msglist);
3874 if (dellist != NULL) free(dellist);
3875 lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3876 if (need_to_free_re) regfree(&re);
3877 return (num_deleted);
3883 * Check whether the current user has permission to delete messages from
3884 * the current room (returns 1 for yes, 0 for no)
3886 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3888 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3889 if (ra & UA_DELETEALLOWED) return(1);
3897 * Delete message from current room
3899 void cmd_dele(char *args)
3908 extract_token(msgset, args, 0, '|', sizeof msgset);
3909 num_msgs = num_tokens(msgset, ',');
3911 cprintf("%d Nothing to do.\n", CIT_OK);
3915 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3916 cprintf("%d Higher access required.\n",
3917 ERROR + HIGHER_ACCESS_REQUIRED);
3922 * Build our message set to be moved/copied
3924 msgs = malloc(num_msgs * sizeof(long));
3925 for (i=0; i<num_msgs; ++i) {
3926 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3927 msgs[i] = atol(msgtok);
3930 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3934 cprintf("%d %d message%s deleted.\n", CIT_OK,
3935 num_deleted, ((num_deleted != 1) ? "s" : ""));
3937 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
3943 * Back end API function for moves and deletes (multiple messages)
3945 int CtdlCopyMsgsToRoom(long *msgnums, int num_msgs, char *dest) {
3948 err = CtdlSaveMsgPointersInRoom(dest, msgnums, num_msgs, 1, NULL);
3949 if (err != 0) return(err);
3958 * move or copy a message to another room
3960 void cmd_move(char *args)
3967 char targ[ROOMNAMELEN];
3968 struct ctdlroom qtemp;
3975 extract_token(msgset, args, 0, '|', sizeof msgset);
3976 num_msgs = num_tokens(msgset, ',');
3978 cprintf("%d Nothing to do.\n", CIT_OK);
3982 extract_token(targ, args, 1, '|', sizeof targ);
3983 convert_room_name_macros(targ, sizeof targ);
3984 targ[ROOMNAMELEN - 1] = 0;
3985 is_copy = extract_int(args, 2);
3987 if (getroom(&qtemp, targ) != 0) {
3988 cprintf("%d '%s' does not exist.\n",
3989 ERROR + ROOM_NOT_FOUND, targ);
3993 getuser(&CC->user, CC->curr_user);
3994 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3996 /* Check for permission to perform this operation.
3997 * Remember: "CC->room" is source, "qtemp" is target.
4001 /* Aides can move/copy */
4002 if (CC->user.axlevel >= 6) permit = 1;
4004 /* Room aides can move/copy */
4005 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
4007 /* Permit move/copy from personal rooms */
4008 if ((CC->room.QRflags & QR_MAILBOX)
4009 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
4011 /* Permit only copy from public to personal room */
4013 && (!(CC->room.QRflags & QR_MAILBOX))
4014 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
4016 /* Permit message removal from collaborative delete rooms */
4017 if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
4019 /* Users allowed to post into the target room may move into it too. */
4020 if ((CC->room.QRflags & QR_MAILBOX) &&
4021 (qtemp.QRflags & UA_POSTALLOWED)) permit = 1;
4023 /* User must have access to target room */
4024 if (!(ra & UA_KNOWN)) permit = 0;
4027 cprintf("%d Higher access required.\n",
4028 ERROR + HIGHER_ACCESS_REQUIRED);
4033 * Build our message set to be moved/copied
4035 msgs = malloc(num_msgs * sizeof(long));
4036 for (i=0; i<num_msgs; ++i) {
4037 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
4038 msgs[i] = atol(msgtok);
4044 err = CtdlCopyMsgsToRoom(msgs, num_msgs, targ);
4046 cprintf("%d Cannot store message(s) in %s: error %d\n",
4052 /* Now delete the message from the source room,
4053 * if this is a 'move' rather than a 'copy' operation.
4056 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
4060 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
4066 * GetMetaData() - Get the supplementary record for a message
4068 void GetMetaData(struct MetaData *smibuf, long msgnum)
4071 struct cdbdata *cdbsmi;
4074 memset(smibuf, 0, sizeof(struct MetaData));
4075 smibuf->meta_msgnum = msgnum;
4076 smibuf->meta_refcount = 1; /* Default reference count is 1 */
4078 /* Use the negative of the message number for its supp record index */
4079 TheIndex = (0L - msgnum);
4081 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
4082 if (cdbsmi == NULL) {
4083 return; /* record not found; go with defaults */
4085 memcpy(smibuf, cdbsmi->ptr,
4086 ((cdbsmi->len > sizeof(struct MetaData)) ?
4087 sizeof(struct MetaData) : cdbsmi->len));
4094 * PutMetaData() - (re)write supplementary record for a message
4096 void PutMetaData(struct MetaData *smibuf)
4100 /* Use the negative of the message number for the metadata db index */
4101 TheIndex = (0L - smibuf->meta_msgnum);
4103 cdb_store(CDB_MSGMAIN,
4104 &TheIndex, (int)sizeof(long),
4105 smibuf, (int)sizeof(struct MetaData));
4110 * AdjRefCount - submit an adjustment to the reference count for a message.
4111 * (These are just queued -- we actually process them later.)
4113 void AdjRefCount(long msgnum, int incr)
4115 struct arcq new_arcq;
4117 begin_critical_section(S_SUPPMSGMAIN);
4118 if (arcfp == NULL) {
4119 arcfp = fopen(file_arcq, "ab+");
4121 end_critical_section(S_SUPPMSGMAIN);
4123 /* msgnum < 0 means that we're trying to close the file */
4125 lprintf(CTDL_DEBUG, "Closing the AdjRefCount queue file\n");
4126 begin_critical_section(S_SUPPMSGMAIN);
4127 if (arcfp != NULL) {
4131 end_critical_section(S_SUPPMSGMAIN);
4136 * If we can't open the queue, perform the operation synchronously.
4138 if (arcfp == NULL) {
4139 TDAP_AdjRefCount(msgnum, incr);
4143 new_arcq.arcq_msgnum = msgnum;
4144 new_arcq.arcq_delta = incr;
4145 fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
4153 * TDAP_ProcessAdjRefCountQueue()
4155 * Process the queue of message count adjustments that was created by calls
4156 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
4157 * for each one. This should be an "off hours" operation.
4159 int TDAP_ProcessAdjRefCountQueue(void)
4161 char file_arcq_temp[PATH_MAX];
4164 struct arcq arcq_rec;
4165 int num_records_processed = 0;
4167 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s2", file_arcq);
4169 begin_critical_section(S_SUPPMSGMAIN);
4170 if (arcfp != NULL) {
4175 r = link(file_arcq, file_arcq_temp);
4177 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4178 end_critical_section(S_SUPPMSGMAIN);
4179 return(num_records_processed);
4183 end_critical_section(S_SUPPMSGMAIN);
4185 fp = fopen(file_arcq_temp, "rb");
4187 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4188 return(num_records_processed);
4191 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
4192 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
4193 ++num_records_processed;
4197 r = unlink(file_arcq_temp);
4199 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
4202 return(num_records_processed);
4208 * TDAP_AdjRefCount - adjust the reference count for a message.
4209 * This one does it "for real" because it's called by
4210 * the autopurger function that processes the queue
4211 * created by AdjRefCount(). If a message's reference
4212 * count becomes zero, we also delete the message from
4213 * disk and de-index it.
4215 void TDAP_AdjRefCount(long msgnum, int incr)
4218 struct MetaData smi;
4221 /* This is a *tight* critical section; please keep it that way, as
4222 * it may get called while nested in other critical sections.
4223 * Complicating this any further will surely cause deadlock!
4225 begin_critical_section(S_SUPPMSGMAIN);
4226 GetMetaData(&smi, msgnum);
4227 smi.meta_refcount += incr;
4229 end_critical_section(S_SUPPMSGMAIN);
4230 lprintf(CTDL_DEBUG, "msg %ld ref count delta %d, is now %d\n",
4231 msgnum, incr, smi.meta_refcount);
4233 /* If the reference count is now zero, delete the message
4234 * (and its supplementary record as well).
4236 if (smi.meta_refcount == 0) {
4237 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
4239 /* Call delete hooks with NULL room to show it has gone altogether */
4240 PerformDeleteHooks(NULL, msgnum);
4242 /* Remove from message base */
4244 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4245 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
4247 /* Remove metadata record */
4248 delnum = (0L - msgnum);
4249 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
4255 * Write a generic object to this room
4257 * Note: this could be much more efficient. Right now we use two temporary
4258 * files, and still pull the message into memory as with all others.
4260 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
4261 char *content_type, /* MIME type of this object */
4262 char *tempfilename, /* Where to fetch it from */
4263 struct ctdluser *is_mailbox, /* Mailbox room? */
4264 int is_binary, /* Is encoding necessary? */
4265 int is_unique, /* Del others of this type? */
4266 unsigned int flags /* Internal save flags */
4271 struct ctdlroom qrbuf;
4272 char roomname[ROOMNAMELEN];
4273 struct CtdlMessage *msg;
4275 char *raw_message = NULL;
4276 char *encoded_message = NULL;
4277 off_t raw_length = 0;
4279 if (is_mailbox != NULL) {
4280 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
4283 safestrncpy(roomname, req_room, sizeof(roomname));
4286 fp = fopen(tempfilename, "rb");
4288 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
4289 tempfilename, strerror(errno));
4292 fseek(fp, 0L, SEEK_END);
4293 raw_length = ftell(fp);
4295 lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
4297 raw_message = malloc((size_t)raw_length + 2);
4298 fread(raw_message, (size_t)raw_length, 1, fp);
4302 encoded_message = malloc((size_t)
4303 (((raw_length * 134) / 100) + 4096 ) );
4306 encoded_message = malloc((size_t)(raw_length + 4096));
4309 sprintf(encoded_message, "Content-type: %s\n", content_type);
4312 sprintf(&encoded_message[strlen(encoded_message)],
4313 "Content-transfer-encoding: base64\n\n"
4317 sprintf(&encoded_message[strlen(encoded_message)],
4318 "Content-transfer-encoding: 7bit\n\n"
4324 &encoded_message[strlen(encoded_message)],
4331 raw_message[raw_length] = 0;
4333 &encoded_message[strlen(encoded_message)],
4341 lprintf(CTDL_DEBUG, "Allocating\n");
4342 msg = malloc(sizeof(struct CtdlMessage));
4343 memset(msg, 0, sizeof(struct CtdlMessage));
4344 msg->cm_magic = CTDLMESSAGE_MAGIC;
4345 msg->cm_anon_type = MES_NORMAL;
4346 msg->cm_format_type = 4;
4347 msg->cm_fields['A'] = strdup(CC->user.fullname);
4348 msg->cm_fields['O'] = strdup(req_room);
4349 msg->cm_fields['N'] = strdup(config.c_nodename);
4350 msg->cm_fields['H'] = strdup(config.c_humannode);
4351 msg->cm_flags = flags;
4353 msg->cm_fields['M'] = encoded_message;
4355 /* Create the requested room if we have to. */
4356 if (getroom(&qrbuf, roomname) != 0) {
4357 create_room(roomname,
4358 ( (is_mailbox != NULL) ? 5 : 3 ),
4359 "", 0, 1, 0, VIEW_BBS);
4361 /* If the caller specified this object as unique, delete all
4362 * other objects of this type that are currently in the room.
4365 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
4366 CtdlDeleteMessages(roomname, NULL, 0, content_type)
4369 /* Now write the data */
4370 CtdlSubmitMsg(msg, NULL, roomname);
4371 CtdlFreeMessage(msg);
4379 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
4380 config_msgnum = msgnum;
4384 char *CtdlGetSysConfig(char *sysconfname) {
4385 char hold_rm[ROOMNAMELEN];
4388 struct CtdlMessage *msg;
4391 strcpy(hold_rm, CC->room.QRname);
4392 if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
4393 getroom(&CC->room, hold_rm);
4398 /* We want the last (and probably only) config in this room */
4399 begin_critical_section(S_CONFIG);
4400 config_msgnum = (-1L);
4401 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
4402 CtdlGetSysConfigBackend, NULL);
4403 msgnum = config_msgnum;
4404 end_critical_section(S_CONFIG);
4410 msg = CtdlFetchMessage(msgnum, 1);
4412 conf = strdup(msg->cm_fields['M']);
4413 CtdlFreeMessage(msg);
4420 getroom(&CC->room, hold_rm);
4422 if (conf != NULL) do {
4423 extract_token(buf, conf, 0, '\n', sizeof buf);
4424 strcpy(conf, &conf[strlen(buf)+1]);
4425 } while ( (!IsEmptyStr(conf)) && (!IsEmptyStr(buf)) );
4430 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
4431 char temp[PATH_MAX];
4434 CtdlMakeTempFileName(temp, sizeof temp);
4436 fp = fopen(temp, "w");
4437 if (fp == NULL) return;
4438 fprintf(fp, "%s", sysconfdata);
4441 /* this handy API function does all the work for us */
4442 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
4448 * Determine whether a given Internet address belongs to the current user
4450 int CtdlIsMe(char *addr, int addr_buf_len)
4452 struct recptypes *recp;
4455 recp = validate_recipients(addr, NULL, 0);
4456 if (recp == NULL) return(0);
4458 if (recp->num_local == 0) {
4459 free_recipients(recp);
4463 for (i=0; i<recp->num_local; ++i) {
4464 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
4465 if (!strcasecmp(addr, CC->user.fullname)) {
4466 free_recipients(recp);
4471 free_recipients(recp);
4477 * Citadel protocol command to do the same
4479 void cmd_isme(char *argbuf) {
4482 if (CtdlAccessCheck(ac_logged_in)) return;
4483 extract_token(addr, argbuf, 0, '|', sizeof addr);
4485 if (CtdlIsMe(addr, sizeof addr)) {
4486 cprintf("%d %s\n", CIT_OK, addr);
4489 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);