4 * Implements the message store.
14 #if TIME_WITH_SYS_TIME
15 # include <sys/time.h>
19 # include <sys/time.h>
34 #include "serv_extensions.h"
38 #include "sysdep_decls.h"
39 #include "citserver.h"
46 #include "mime_parser.h"
49 #include "internet_addressing.h"
50 #include "serv_fulltext.h"
52 #include "euidindex.h"
53 #include "journaling.h"
54 #include "citadel_dirs.h"
55 #include "serv_network.h"
58 # include "serv_sieve.h"
59 #endif /* HAVE_LIBSIEVE */
62 struct addresses_to_be_filed *atbf = 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;
149 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
150 stripallbut(name, '<', '>');
152 fp = fopen(file_mail_aliases, "r");
154 fp = fopen("/dev/null", "r");
161 while (fgets(aaa, sizeof aaa, fp) != NULL) {
162 while (isspace(name[0]))
163 strcpy(name, &name[1]);
164 aaa[strlen(aaa) - 1] = 0;
166 for (a = 0; a < strlen(aaa); ++a) {
168 strcpy(bbb, &aaa[a + 1]);
172 if (!strcasecmp(name, aaa))
177 /* Hit the Global Address Book */
178 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
182 lprintf(CTDL_INFO, "Mail is being forwarded to %s\n", name);
184 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
185 for (a=0; a<strlen(name); ++a) {
186 if (name[a] == '@') {
187 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
189 lprintf(CTDL_INFO, "Changed to <%s>\n", name);
194 /* determine local or remote type, see citadel.h */
195 at = haschar(name, '@');
196 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
197 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
198 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
200 /* figure out the delivery mode */
201 extract_token(node, name, 1, '@', sizeof node);
203 /* If there are one or more dots in the nodename, we assume that it
204 * is an FQDN and will attempt SMTP delivery to the Internet.
206 if (haschar(node, '.') > 0) {
207 return(MES_INTERNET);
210 /* Otherwise we look in the IGnet maps for a valid Citadel node.
211 * Try directly-connected nodes first...
213 ignetcfg = CtdlGetSysConfig(IGNETCFG);
214 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
215 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
216 extract_token(testnode, buf, 0, '|', sizeof testnode);
217 if (!strcasecmp(node, testnode)) {
225 * Then try nodes that are two or more hops away.
227 ignetmap = CtdlGetSysConfig(IGNETMAP);
228 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
229 extract_token(buf, ignetmap, i, '\n', sizeof buf);
230 extract_token(testnode, buf, 0, '|', sizeof testnode);
231 if (!strcasecmp(node, testnode)) {
238 /* If we get to this point it's an invalid node name */
247 fp = fopen(file_citadel_control, "r");
249 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
250 file_citadel_control,
254 fread((char *) &CitControl, sizeof(struct CitControl), 1, fp);
260 * Back end for the MSGS command: output message number only.
262 void simple_listing(long msgnum, void *userdata)
264 cprintf("%ld\n", msgnum);
270 * Back end for the MSGS command: output header summary.
272 void headers_listing(long msgnum, void *userdata)
274 struct CtdlMessage *msg;
276 msg = CtdlFetchMessage(msgnum, 0);
278 cprintf("%ld|0|||||\n", msgnum);
282 cprintf("%ld|%s|%s|%s|%s|%s|\n",
284 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
285 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
286 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
287 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
288 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
290 CtdlFreeMessage(msg);
295 /* Determine if a given message matches the fields in a message template.
296 * Return 0 for a successful match.
298 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
301 /* If there aren't any fields in the template, all messages will
304 if (template == NULL) return(0);
306 /* Null messages are bogus. */
307 if (msg == NULL) return(1);
309 for (i='A'; i<='Z'; ++i) {
310 if (template->cm_fields[i] != NULL) {
311 if (msg->cm_fields[i] == NULL) {
314 if (strcasecmp(msg->cm_fields[i],
315 template->cm_fields[i])) return 1;
319 /* All compares succeeded: we have a match! */
326 * Retrieve the "seen" message list for the current room.
328 void CtdlGetSeen(char *buf, int which_set) {
331 /* Learn about the user and room in question */
332 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
334 if (which_set == ctdlsetseen_seen)
335 safestrncpy(buf, vbuf.v_seen, SIZ);
336 if (which_set == ctdlsetseen_answered)
337 safestrncpy(buf, vbuf.v_answered, SIZ);
343 * Manipulate the "seen msgs" string (or other message set strings)
345 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
346 int target_setting, int which_set,
347 struct ctdluser *which_user, struct ctdlroom *which_room) {
348 struct cdbdata *cdbfr;
360 char *is_set; /* actually an array of booleans */
363 char setstr[SIZ], lostr[SIZ], histr[SIZ];
366 lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
367 num_target_msgnums, target_msgnums[0],
368 target_setting, which_set);
370 /* Learn about the user and room in question */
371 CtdlGetRelationship(&vbuf,
372 ((which_user != NULL) ? which_user : &CC->user),
373 ((which_room != NULL) ? which_room : &CC->room)
376 /* Load the message list */
377 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
379 msglist = (long *) cdbfr->ptr;
380 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
381 num_msgs = cdbfr->len / sizeof(long);
384 return; /* No messages at all? No further action. */
387 is_set = malloc(num_msgs * sizeof(char));
388 memset(is_set, 0, (num_msgs * sizeof(char)) );
390 /* Decide which message set we're manipulating */
392 case ctdlsetseen_seen:
393 safestrncpy(vset, vbuf.v_seen, sizeof vset);
395 case ctdlsetseen_answered:
396 safestrncpy(vset, vbuf.v_answered, sizeof vset);
400 /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
402 /* Translate the existing sequence set into an array of booleans */
403 num_sets = num_tokens(vset, ',');
404 for (s=0; s<num_sets; ++s) {
405 extract_token(setstr, vset, s, ',', sizeof setstr);
407 extract_token(lostr, setstr, 0, ':', sizeof lostr);
408 if (num_tokens(setstr, ':') >= 2) {
409 extract_token(histr, setstr, 1, ':', sizeof histr);
410 if (!strcmp(histr, "*")) {
411 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
415 strcpy(histr, lostr);
420 for (i = 0; i < num_msgs; ++i) {
421 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
427 /* Now translate the array of booleans back into a sequence set */
432 for (i=0; i<num_msgs; ++i) {
434 is_seen = is_set[i]; /* Default to existing setting */
436 for (k=0; k<num_target_msgnums; ++k) {
437 if (msglist[i] == target_msgnums[k]) {
438 is_seen = target_setting;
443 if (lo < 0L) lo = msglist[i];
447 if ( ((is_seen == 0) && (was_seen == 1))
448 || ((is_seen == 1) && (i == num_msgs-1)) ) {
450 /* begin trim-o-matic code */
453 while ( (strlen(vset) + 20) > sizeof vset) {
454 remove_token(vset, 0, ',');
456 if (j--) break; /* loop no more than 9 times */
458 if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
462 snprintf(lostr, sizeof lostr,
463 "1:%ld,%s", t, vset);
464 safestrncpy(vset, lostr, sizeof vset);
466 /* end trim-o-matic code */
474 snprintf(&vset[tmp], (sizeof vset) - tmp,
478 snprintf(&vset[tmp], (sizeof vset) - tmp,
487 /* Decide which message set we're manipulating */
489 case ctdlsetseen_seen:
490 safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
492 case ctdlsetseen_answered:
493 safestrncpy(vbuf.v_answered, vset,
494 sizeof vbuf.v_answered);
499 /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
501 CtdlSetRelationship(&vbuf,
502 ((which_user != NULL) ? which_user : &CC->user),
503 ((which_room != NULL) ? which_room : &CC->room)
509 * API function to perform an operation for each qualifying message in the
510 * current room. (Returns the number of messages processed.)
512 int CtdlForEachMessage(int mode, long ref, char *search_string,
514 struct CtdlMessage *compare,
515 void (*CallBack) (long, void *),
521 struct cdbdata *cdbfr;
522 long *msglist = NULL;
524 int num_processed = 0;
527 struct CtdlMessage *msg;
530 int printed_lastold = 0;
531 int num_search_msgs = 0;
532 long *search_msgs = NULL;
534 /* Learn about the user and room in question */
536 getuser(&CC->user, CC->curr_user);
537 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
539 /* Load the message list */
540 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
542 msglist = (long *) cdbfr->ptr;
543 cdbfr->ptr = NULL; /* CtdlForEachMessage() now owns this memory */
544 num_msgs = cdbfr->len / sizeof(long);
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 (strlen(content_type) > 0) {
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)) {
578 num_msgs = sort_msglist(msglist, num_msgs);
580 /* If a template was supplied, filter out the messages which
581 * don't match. (This could induce some delays!)
584 if (compare != NULL) {
585 for (a = 0; a < num_msgs; ++a) {
586 msg = CtdlFetchMessage(msglist[a], 1);
588 if (CtdlMsgCmp(msg, compare)) {
591 CtdlFreeMessage(msg);
597 /* If a search string was specified, get a message list from
598 * the full text index and remove messages which aren't on both
602 * Since the lists are sorted and strictly ascending, and the
603 * output list is guaranteed to be shorter than or equal to the
604 * input list, we overwrite the bottom of the input list. This
605 * eliminates the need to memmove big chunks of the list over and
608 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
609 ft_search(&num_search_msgs, &search_msgs, search_string);
610 if (num_search_msgs > 0) {
614 orig_num_msgs = num_msgs;
616 for (i=0; i<orig_num_msgs; ++i) {
617 for (j=0; j<num_search_msgs; ++j) {
618 if (msglist[i] == search_msgs[j]) {
619 msglist[num_msgs++] = msglist[i];
625 num_msgs = 0; /* No messages qualify */
627 if (search_msgs != NULL) free(search_msgs);
629 /* Now that we've purged messages which don't contain the search
630 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
637 * Now iterate through the message list, according to the
638 * criteria supplied by the caller.
641 for (a = 0; a < num_msgs; ++a) {
642 thismsg = msglist[a];
643 if (mode == MSGS_ALL) {
647 is_seen = is_msg_in_sequence_set(
648 vbuf.v_seen, thismsg);
649 if (is_seen) lastold = thismsg;
655 || ((mode == MSGS_OLD) && (is_seen))
656 || ((mode == MSGS_NEW) && (!is_seen))
657 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
658 || ((mode == MSGS_FIRST) && (a < ref))
659 || ((mode == MSGS_GT) && (thismsg > ref))
660 || ((mode == MSGS_EQ) && (thismsg == ref))
663 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
665 CallBack(lastold, userdata);
669 if (CallBack) CallBack(thismsg, userdata);
673 free(msglist); /* Clean up */
674 return num_processed;
680 * cmd_msgs() - get list of message #'s in this room
681 * implements the MSGS server command using CtdlForEachMessage()
683 void cmd_msgs(char *cmdbuf)
692 int with_template = 0;
693 struct CtdlMessage *template = NULL;
694 int with_headers = 0;
695 char search_string[1024];
697 extract_token(which, cmdbuf, 0, '|', sizeof which);
698 cm_ref = extract_int(cmdbuf, 1);
699 extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
700 with_template = extract_int(cmdbuf, 2);
701 with_headers = extract_int(cmdbuf, 3);
704 if (!strncasecmp(which, "OLD", 3))
706 else if (!strncasecmp(which, "NEW", 3))
708 else if (!strncasecmp(which, "FIRST", 5))
710 else if (!strncasecmp(which, "LAST", 4))
712 else if (!strncasecmp(which, "GT", 2))
714 else if (!strncasecmp(which, "SEARCH", 6))
719 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
720 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
724 if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
725 cprintf("%d Full text index is not enabled on this server.\n",
726 ERROR + CMD_NOT_SUPPORTED);
732 cprintf("%d Send template then receive message list\n",
734 template = (struct CtdlMessage *)
735 malloc(sizeof(struct CtdlMessage));
736 memset(template, 0, sizeof(struct CtdlMessage));
737 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
738 extract_token(tfield, buf, 0, '|', sizeof tfield);
739 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
740 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
741 if (!strcasecmp(tfield, msgkeys[i])) {
742 template->cm_fields[i] =
750 cprintf("%d \n", LISTING_FOLLOWS);
753 CtdlForEachMessage(mode,
754 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
755 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
758 (with_headers ? headers_listing : simple_listing),
761 if (template != NULL) CtdlFreeMessage(template);
769 * help_subst() - support routine for help file viewer
771 void help_subst(char *strbuf, char *source, char *dest)
776 while (p = pattern2(strbuf, source), (p >= 0)) {
777 strcpy(workbuf, &strbuf[p + strlen(source)]);
778 strcpy(&strbuf[p], dest);
779 strcat(strbuf, workbuf);
784 void do_help_subst(char *buffer)
788 help_subst(buffer, "^nodename", config.c_nodename);
789 help_subst(buffer, "^humannode", config.c_humannode);
790 help_subst(buffer, "^fqdn", config.c_fqdn);
791 help_subst(buffer, "^username", CC->user.fullname);
792 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
793 help_subst(buffer, "^usernum", buf2);
794 help_subst(buffer, "^sysadm", config.c_sysadm);
795 help_subst(buffer, "^variantname", CITADEL);
796 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
797 help_subst(buffer, "^maxsessions", buf2);
798 help_subst(buffer, "^bbsdir", ctdl_bbsbase_dir);
804 * memfmout() - Citadel text formatter and paginator.
805 * Although the original purpose of this routine was to format
806 * text to the reader's screen width, all we're really using it
807 * for here is to format text out to 80 columns before sending it
808 * to the client. The client software may reformat it again.
811 char *mptr, /* where are we going to get our text from? */
812 char subst, /* nonzero if we should do substitutions */
813 char *nl) /* string to terminate lines with */
821 static int width = 80;
826 c = 1; /* c is the current pos */
830 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
832 buffer[strlen(buffer) + 1] = 0;
833 buffer[strlen(buffer)] = ch;
836 if (buffer[0] == '^')
837 do_help_subst(buffer);
839 buffer[strlen(buffer) + 1] = 0;
841 strcpy(buffer, &buffer[1]);
849 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
852 if (((old == 13) || (old == 10)) && (isspace(real))) {
857 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
858 cprintf("%s%s", nl, aaa);
867 if ((strlen(aaa) + c) > (width - 5)) {
876 if ((ch == 13) || (ch == 10)) {
877 cprintf("%s%s", aaa, nl);
884 cprintf("%s%s", aaa, nl);
890 * Callback function for mime parser that simply lists the part
892 void list_this_part(char *name, char *filename, char *partnum, char *disp,
893 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
898 ma = (struct ma_info *)cbuserdata;
899 if (ma->is_ma == 0) {
900 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
901 name, filename, partnum, disp, cbtype, (long)length);
906 * Callback function for multipart prefix
908 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
909 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
914 ma = (struct ma_info *)cbuserdata;
915 if (!strcasecmp(cbtype, "multipart/alternative")) {
919 if (ma->is_ma == 0) {
920 cprintf("pref=%s|%s\n", partnum, cbtype);
925 * Callback function for multipart sufffix
927 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
928 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
933 ma = (struct ma_info *)cbuserdata;
934 if (ma->is_ma == 0) {
935 cprintf("suff=%s|%s\n", partnum, cbtype);
937 if (!strcasecmp(cbtype, "multipart/alternative")) {
944 * Callback function for mime parser that opens a section for downloading
946 void mime_download(char *name, char *filename, char *partnum, char *disp,
947 void *content, char *cbtype, char *cbcharset, size_t length,
948 char *encoding, void *cbuserdata)
951 /* Silently go away if there's already a download open... */
952 if (CC->download_fp != NULL)
955 /* ...or if this is not the desired section */
956 if (strcasecmp(CC->download_desired_section, partnum))
959 CC->download_fp = tmpfile();
960 if (CC->download_fp == NULL)
963 fwrite(content, length, 1, CC->download_fp);
964 fflush(CC->download_fp);
965 rewind(CC->download_fp);
967 OpenCmdResult(filename, cbtype);
973 * Load a message from disk into memory.
974 * This is used by CtdlOutputMsg() and other fetch functions.
976 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
977 * using the CtdlMessageFree() function.
979 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
981 struct cdbdata *dmsgtext;
982 struct CtdlMessage *ret = NULL;
986 cit_uint8_t field_header;
988 lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
990 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
991 if (dmsgtext == NULL) {
994 mptr = dmsgtext->ptr;
995 upper_bound = mptr + dmsgtext->len;
997 /* Parse the three bytes that begin EVERY message on disk.
998 * The first is always 0xFF, the on-disk magic number.
999 * The second is the anonymous/public type byte.
1000 * The third is the format type byte (vari, fixed, or MIME).
1005 "Message %ld appears to be corrupted.\n",
1010 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1011 memset(ret, 0, sizeof(struct CtdlMessage));
1013 ret->cm_magic = CTDLMESSAGE_MAGIC;
1014 ret->cm_anon_type = *mptr++; /* Anon type byte */
1015 ret->cm_format_type = *mptr++; /* Format type byte */
1018 * The rest is zero or more arbitrary fields. Load them in.
1019 * We're done when we encounter either a zero-length field or
1020 * have just processed the 'M' (message text) field.
1023 if (mptr >= upper_bound) {
1026 field_header = *mptr++;
1027 ret->cm_fields[field_header] = strdup(mptr);
1029 while (*mptr++ != 0); /* advance to next field */
1031 } while ((mptr < upper_bound) && (field_header != 'M'));
1035 /* Always make sure there's something in the msg text field. If
1036 * it's NULL, the message text is most likely stored separately,
1037 * so go ahead and fetch that. Failing that, just set a dummy
1038 * body so other code doesn't barf.
1040 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1041 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1042 if (dmsgtext != NULL) {
1043 ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1047 if (ret->cm_fields['M'] == NULL) {
1048 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1051 /* Perform "before read" hooks (aborting if any return nonzero) */
1052 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1053 CtdlFreeMessage(ret);
1062 * Returns 1 if the supplied pointer points to a valid Citadel message.
1063 * If the pointer is NULL or the magic number check fails, returns 0.
1065 int is_valid_message(struct CtdlMessage *msg) {
1068 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1069 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1077 * 'Destructor' for struct CtdlMessage
1079 void CtdlFreeMessage(struct CtdlMessage *msg)
1083 if (is_valid_message(msg) == 0) return;
1085 for (i = 0; i < 256; ++i)
1086 if (msg->cm_fields[i] != NULL) {
1087 free(msg->cm_fields[i]);
1090 msg->cm_magic = 0; /* just in case */
1096 * Pre callback function for multipart/alternative
1098 * NOTE: this differs from the standard behavior for a reason. Normally when
1099 * displaying multipart/alternative you want to show the _last_ usable
1100 * format in the message. Here we show the _first_ one, because it's
1101 * usually text/plain. Since this set of functions is designed for text
1102 * output to non-MIME-aware clients, this is the desired behavior.
1105 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1106 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1111 ma = (struct ma_info *)cbuserdata;
1112 lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1113 if (!strcasecmp(cbtype, "multipart/alternative")) {
1117 if (!strcasecmp(cbtype, "message/rfc822")) {
1123 * Post callback function for multipart/alternative
1125 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1126 void *content, char *cbtype, char *cbcharset, size_t length,
1127 char *encoding, void *cbuserdata)
1131 ma = (struct ma_info *)cbuserdata;
1132 lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1133 if (!strcasecmp(cbtype, "multipart/alternative")) {
1137 if (!strcasecmp(cbtype, "message/rfc822")) {
1143 * Inline callback function for mime parser that wants to display text
1145 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1146 void *content, char *cbtype, char *cbcharset, size_t length,
1147 char *encoding, void *cbuserdata)
1154 ma = (struct ma_info *)cbuserdata;
1157 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1158 partnum, filename, cbtype, (long)length);
1161 * If we're in the middle of a multipart/alternative scope and
1162 * we've already printed another section, skip this one.
1164 if ( (ma->is_ma) && (ma->did_print) ) {
1165 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1171 if ( (!strcasecmp(cbtype, "text/plain"))
1172 || (strlen(cbtype)==0) ) {
1175 client_write(wptr, length);
1176 if (wptr[length-1] != '\n') {
1183 if (!strcasecmp(cbtype, "text/html")) {
1184 ptr = html_to_ascii(content, length, 80, 0);
1186 client_write(ptr, wlen);
1187 if (ptr[wlen-1] != '\n') {
1194 if (ma->use_fo_hooks) {
1195 if (PerformFixedOutputHooks(cbtype, content, length)) {
1196 /* above function returns nonzero if it handled the part */
1201 if (strncasecmp(cbtype, "multipart/", 10)) {
1202 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1203 partnum, filename, cbtype, (long)length);
1209 * The client is elegant and sophisticated and wants to be choosy about
1210 * MIME content types, so figure out which multipart/alternative part
1211 * we're going to send.
1213 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1214 void *content, char *cbtype, char *cbcharset, size_t length,
1215 char *encoding, void *cbuserdata)
1221 ma = (struct ma_info *)cbuserdata;
1223 if (ma->is_ma > 0) {
1224 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1225 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1226 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1227 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1234 * Now that we've chosen our preferred part, output it.
1236 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1237 void *content, char *cbtype, char *cbcharset, size_t length,
1238 char *encoding, void *cbuserdata)
1242 int add_newline = 0;
1246 ma = (struct ma_info *)cbuserdata;
1248 /* This is not the MIME part you're looking for... */
1249 if (strcasecmp(partnum, ma->chosen_part)) return;
1251 /* If the content-type of this part is in our preferred formats
1252 * list, we can simply output it verbatim.
1254 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1255 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1256 if (!strcasecmp(buf, cbtype)) {
1257 /* Yeah! Go! W00t!! */
1259 text_content = (char *)content;
1260 if (text_content[length-1] != '\n') {
1264 cprintf("Content-type: %s", cbtype);
1265 if (strlen(cbcharset) > 0) {
1266 cprintf("; charset=%s", cbcharset);
1268 cprintf("\nContent-length: %d\n",
1269 (int)(length + add_newline) );
1270 if (strlen(encoding) > 0) {
1271 cprintf("Content-transfer-encoding: %s\n", encoding);
1274 cprintf("Content-transfer-encoding: 7bit\n");
1277 client_write(content, length);
1278 if (add_newline) cprintf("\n");
1283 /* No translations required or possible: output as text/plain */
1284 cprintf("Content-type: text/plain\n\n");
1285 fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1286 length, encoding, cbuserdata);
1291 char desired_section[64];
1298 * Callback function for
1300 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1301 void *content, char *cbtype, char *cbcharset, size_t length,
1302 char *encoding, void *cbuserdata)
1304 struct encapmsg *encap;
1306 encap = (struct encapmsg *)cbuserdata;
1308 /* Only proceed if this is the desired section... */
1309 if (!strcasecmp(encap->desired_section, partnum)) {
1310 encap->msglen = length;
1311 encap->msg = malloc(length + 2);
1312 memcpy(encap->msg, content, length);
1322 * Get a message off disk. (returns om_* values found in msgbase.h)
1325 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1326 int mode, /* how would you like that message? */
1327 int headers_only, /* eschew the message body? */
1328 int do_proto, /* do Citadel protocol responses? */
1329 int crlf, /* Use CRLF newlines instead of LF? */
1330 char *section /* NULL or a message/rfc822 section */
1332 struct CtdlMessage *TheMessage = NULL;
1333 int retcode = om_no_such_msg;
1334 struct encapmsg encap;
1336 lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n",
1338 (section ? section : "<>")
1341 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1342 if (do_proto) cprintf("%d Not logged in.\n",
1343 ERROR + NOT_LOGGED_IN);
1344 return(om_not_logged_in);
1347 /* FIXME: check message id against msglist for this room */
1350 * Fetch the message from disk. If we're in any sort of headers
1351 * only mode, request that we don't even bother loading the body
1354 if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1355 TheMessage = CtdlFetchMessage(msg_num, 0);
1358 TheMessage = CtdlFetchMessage(msg_num, 1);
1361 if (TheMessage == NULL) {
1362 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1363 ERROR + MESSAGE_NOT_FOUND, msg_num);
1364 return(om_no_such_msg);
1367 /* Here is the weird form of this command, to process only an
1368 * encapsulated message/rfc822 section.
1370 if (section) if (strlen(section)>0) if (strcmp(section, "0")) {
1371 memset(&encap, 0, sizeof encap);
1372 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1373 mime_parser(TheMessage->cm_fields['M'],
1375 *extract_encapsulated_message,
1376 NULL, NULL, (void *)&encap, 0
1378 CtdlFreeMessage(TheMessage);
1382 encap.msg[encap.msglen] = 0;
1383 TheMessage = convert_internet_message(encap.msg);
1384 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1386 /* Now we let it fall through to the bottom of this
1387 * function, because TheMessage now contains the
1388 * encapsulated message instead of the top-level
1389 * message. Isn't that neat?
1394 if (do_proto) cprintf("%d msg %ld has no part %s\n",
1395 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1396 retcode = om_no_such_msg;
1401 /* Ok, output the message now */
1402 retcode = CtdlOutputPreLoadedMsg(
1404 headers_only, do_proto, crlf);
1405 CtdlFreeMessage(TheMessage);
1412 * Get a message off disk. (returns om_* values found in msgbase.h)
1415 int CtdlOutputPreLoadedMsg(
1416 struct CtdlMessage *TheMessage,
1417 int mode, /* how would you like that message? */
1418 int headers_only, /* eschew the message body? */
1419 int do_proto, /* do Citadel protocol responses? */
1420 int crlf /* Use CRLF newlines instead of LF? */
1426 char display_name[256];
1428 char *nl; /* newline string */
1430 int subject_found = 0;
1433 /* Buffers needed for RFC822 translation. These are all filled
1434 * using functions that are bounds-checked, and therefore we can
1435 * make them substantially smaller than SIZ.
1443 char datestamp[100];
1445 lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1446 ((TheMessage == NULL) ? "NULL" : "not null"),
1447 mode, headers_only, do_proto, crlf);
1449 strcpy(mid, "unknown");
1450 nl = (crlf ? "\r\n" : "\n");
1452 if (!is_valid_message(TheMessage)) {
1454 "ERROR: invalid preloaded message for output\n");
1455 return(om_no_such_msg);
1458 /* Are we downloading a MIME component? */
1459 if (mode == MT_DOWNLOAD) {
1460 if (TheMessage->cm_format_type != FMT_RFC822) {
1462 cprintf("%d This is not a MIME message.\n",
1463 ERROR + ILLEGAL_VALUE);
1464 } else if (CC->download_fp != NULL) {
1465 if (do_proto) cprintf(
1466 "%d You already have a download open.\n",
1467 ERROR + RESOURCE_BUSY);
1469 /* Parse the message text component */
1470 mptr = TheMessage->cm_fields['M'];
1471 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1472 /* If there's no file open by this time, the requested
1473 * section wasn't found, so print an error
1475 if (CC->download_fp == NULL) {
1476 if (do_proto) cprintf(
1477 "%d Section %s not found.\n",
1478 ERROR + FILE_NOT_FOUND,
1479 CC->download_desired_section);
1482 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1485 /* now for the user-mode message reading loops */
1486 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1488 /* Does the caller want to skip the headers? */
1489 if (headers_only == HEADERS_NONE) goto START_TEXT;
1491 /* Tell the client which format type we're using. */
1492 if ( (mode == MT_CITADEL) && (do_proto) ) {
1493 cprintf("type=%d\n", TheMessage->cm_format_type);
1496 /* nhdr=yes means that we're only displaying headers, no body */
1497 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1498 && (mode == MT_CITADEL)
1501 cprintf("nhdr=yes\n");
1504 /* begin header processing loop for Citadel message format */
1506 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1508 safestrncpy(display_name, "<unknown>", sizeof display_name);
1509 if (TheMessage->cm_fields['A']) {
1510 strcpy(buf, TheMessage->cm_fields['A']);
1511 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1512 safestrncpy(display_name, "****", sizeof display_name);
1514 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1515 safestrncpy(display_name, "anonymous", sizeof display_name);
1518 safestrncpy(display_name, buf, sizeof display_name);
1520 if ((is_room_aide())
1521 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1522 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1523 size_t tmp = strlen(display_name);
1524 snprintf(&display_name[tmp],
1525 sizeof display_name - tmp,
1530 /* Don't show Internet address for users on the
1531 * local Citadel network.
1534 if (TheMessage->cm_fields['N'] != NULL)
1535 if (strlen(TheMessage->cm_fields['N']) > 0)
1536 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1540 /* Now spew the header fields in the order we like them. */
1541 safestrncpy(allkeys, FORDER, sizeof allkeys);
1542 for (i=0; i<strlen(allkeys); ++i) {
1543 k = (int) allkeys[i];
1545 if ( (TheMessage->cm_fields[k] != NULL)
1546 && (msgkeys[k] != NULL) ) {
1548 if (do_proto) cprintf("%s=%s\n",
1552 else if ((k == 'F') && (suppress_f)) {
1555 /* Masquerade display name if needed */
1557 if (do_proto) cprintf("%s=%s\n",
1559 TheMessage->cm_fields[k]
1568 /* begin header processing loop for RFC822 transfer format */
1573 strcpy(snode, NODENAME);
1574 strcpy(lnode, HUMANNODE);
1575 if (mode == MT_RFC822) {
1576 for (i = 0; i < 256; ++i) {
1577 if (TheMessage->cm_fields[i]) {
1578 mptr = TheMessage->cm_fields[i];
1581 safestrncpy(luser, mptr, sizeof luser);
1582 safestrncpy(suser, mptr, sizeof suser);
1584 else if (i == 'Y') {
1585 cprintf("CC: %s%s", mptr, nl);
1587 else if (i == 'U') {
1588 cprintf("Subject: %s%s", mptr, nl);
1592 safestrncpy(mid, mptr, sizeof mid);
1594 safestrncpy(lnode, mptr, sizeof lnode);
1596 safestrncpy(fuser, mptr, sizeof fuser);
1597 /* else if (i == 'O')
1598 cprintf("X-Citadel-Room: %s%s",
1601 safestrncpy(snode, mptr, sizeof snode);
1603 cprintf("To: %s%s", mptr, nl);
1604 else if (i == 'T') {
1605 datestring(datestamp, sizeof datestamp,
1606 atol(mptr), DATESTRING_RFC822);
1607 cprintf("Date: %s%s", datestamp, nl);
1611 if (subject_found == 0) {
1612 cprintf("Subject: (no subject)%s", nl);
1616 for (i=0; i<strlen(suser); ++i) {
1617 suser[i] = tolower(suser[i]);
1618 if (!isalnum(suser[i])) suser[i]='_';
1621 if (mode == MT_RFC822) {
1622 if (!strcasecmp(snode, NODENAME)) {
1623 safestrncpy(snode, FQDN, sizeof snode);
1626 /* Construct a fun message id */
1627 cprintf("Message-ID: <%s", mid);
1628 if (strchr(mid, '@')==NULL) {
1629 cprintf("@%s", snode);
1633 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1634 cprintf("From: \"----\" <x@x.org>%s", nl);
1636 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1637 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1639 else if (strlen(fuser) > 0) {
1640 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1643 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1646 cprintf("Organization: %s%s", lnode, nl);
1648 /* Blank line signifying RFC822 end-of-headers */
1649 if (TheMessage->cm_format_type != FMT_RFC822) {
1654 /* end header processing loop ... at this point, we're in the text */
1656 if (headers_only == HEADERS_FAST) goto DONE;
1657 mptr = TheMessage->cm_fields['M'];
1659 /* Tell the client about the MIME parts in this message */
1660 if (TheMessage->cm_format_type == FMT_RFC822) {
1661 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1662 memset(&ma, 0, sizeof(struct ma_info));
1663 mime_parser(mptr, NULL,
1664 (do_proto ? *list_this_part : NULL),
1665 (do_proto ? *list_this_pref : NULL),
1666 (do_proto ? *list_this_suff : NULL),
1669 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1670 char *start_of_text = NULL;
1671 start_of_text = strstr(mptr, "\n\r\n");
1672 if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1673 if (start_of_text == NULL) start_of_text = mptr;
1675 start_of_text = strstr(start_of_text, "\n");
1677 while (ch=*mptr, ch!=0) {
1681 else switch(headers_only) {
1683 if (mptr >= start_of_text) {
1684 if (ch == 10) cprintf("%s", nl);
1685 else cprintf("%c", ch);
1689 if (mptr < start_of_text) {
1690 if (ch == 10) cprintf("%s", nl);
1691 else cprintf("%c", ch);
1695 if (ch == 10) cprintf("%s", nl);
1696 else cprintf("%c", ch);
1705 if (headers_only == HEADERS_ONLY) {
1709 /* signify start of msg text */
1710 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1711 if (do_proto) cprintf("text\n");
1714 /* If the format type on disk is 1 (fixed-format), then we want
1715 * everything to be output completely literally ... regardless of
1716 * what message transfer format is in use.
1718 if (TheMessage->cm_format_type == FMT_FIXED) {
1719 if (mode == MT_MIME) {
1720 cprintf("Content-type: text/plain\n\n");
1723 while (ch = *mptr++, ch > 0) {
1726 if ((ch == 10) || (strlen(buf) > 250)) {
1727 cprintf("%s%s", buf, nl);
1730 buf[strlen(buf) + 1] = 0;
1731 buf[strlen(buf)] = ch;
1734 if (strlen(buf) > 0)
1735 cprintf("%s%s", buf, nl);
1738 /* If the message on disk is format 0 (Citadel vari-format), we
1739 * output using the formatter at 80 columns. This is the final output
1740 * form if the transfer format is RFC822, but if the transfer format
1741 * is Citadel proprietary, it'll still work, because the indentation
1742 * for new paragraphs is correct and the client will reformat the
1743 * message to the reader's screen width.
1745 if (TheMessage->cm_format_type == FMT_CITADEL) {
1746 if (mode == MT_MIME) {
1747 cprintf("Content-type: text/x-citadel-variformat\n\n");
1749 memfmout(mptr, 0, nl);
1752 /* If the message on disk is format 4 (MIME), we've gotta hand it
1753 * off to the MIME parser. The client has already been told that
1754 * this message is format 1 (fixed format), so the callback function
1755 * we use will display those parts as-is.
1757 if (TheMessage->cm_format_type == FMT_RFC822) {
1758 memset(&ma, 0, sizeof(struct ma_info));
1760 if (mode == MT_MIME) {
1761 ma.use_fo_hooks = 0;
1762 strcpy(ma.chosen_part, "1");
1763 mime_parser(mptr, NULL,
1764 *choose_preferred, *fixed_output_pre,
1765 *fixed_output_post, (void *)&ma, 0);
1766 mime_parser(mptr, NULL,
1767 *output_preferred, NULL, NULL, (void *)&ma, 0);
1770 ma.use_fo_hooks = 1;
1771 mime_parser(mptr, NULL,
1772 *fixed_output, *fixed_output_pre,
1773 *fixed_output_post, (void *)&ma, 0);
1778 DONE: /* now we're done */
1779 if (do_proto) cprintf("000\n");
1786 * display a message (mode 0 - Citadel proprietary)
1788 void cmd_msg0(char *cmdbuf)
1791 int headers_only = HEADERS_ALL;
1793 msgid = extract_long(cmdbuf, 0);
1794 headers_only = extract_int(cmdbuf, 1);
1796 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1802 * display a message (mode 2 - RFC822)
1804 void cmd_msg2(char *cmdbuf)
1807 int headers_only = HEADERS_ALL;
1809 msgid = extract_long(cmdbuf, 0);
1810 headers_only = extract_int(cmdbuf, 1);
1812 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1818 * display a message (mode 3 - IGnet raw format - internal programs only)
1820 void cmd_msg3(char *cmdbuf)
1823 struct CtdlMessage *msg;
1826 if (CC->internal_pgm == 0) {
1827 cprintf("%d This command is for internal programs only.\n",
1828 ERROR + HIGHER_ACCESS_REQUIRED);
1832 msgnum = extract_long(cmdbuf, 0);
1833 msg = CtdlFetchMessage(msgnum, 1);
1835 cprintf("%d Message %ld not found.\n",
1836 ERROR + MESSAGE_NOT_FOUND, msgnum);
1840 serialize_message(&smr, msg);
1841 CtdlFreeMessage(msg);
1844 cprintf("%d Unable to serialize message\n",
1845 ERROR + INTERNAL_ERROR);
1849 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1850 client_write((char *)smr.ser, (int)smr.len);
1857 * Display a message using MIME content types
1859 void cmd_msg4(char *cmdbuf)
1864 msgid = extract_long(cmdbuf, 0);
1865 extract_token(section, cmdbuf, 1, '|', sizeof section);
1866 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1872 * Client tells us its preferred message format(s)
1874 void cmd_msgp(char *cmdbuf)
1876 safestrncpy(CC->preferred_formats, cmdbuf,
1877 sizeof(CC->preferred_formats));
1878 cprintf("%d ok\n", CIT_OK);
1883 * Open a component of a MIME message as a download file
1885 void cmd_opna(char *cmdbuf)
1888 char desired_section[128];
1890 msgid = extract_long(cmdbuf, 0);
1891 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1892 safestrncpy(CC->download_desired_section, desired_section,
1893 sizeof CC->download_desired_section);
1894 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
1898 * Save one or more message pointers into a specified room
1899 * (Returns 0 for success, nonzero for failure)
1900 * roomname may be NULL to use the current room
1902 * Note that the 'supplied_msg' field may be set to NULL, in which case
1903 * the message will be fetched from disk, by number, if we need to perform
1904 * replication checks. This adds an additional database read, so if the
1905 * caller already has the message in memory then it should be supplied. (Obviously
1906 * this mode of operation only works if we're saving a single message.)
1908 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
1909 int do_repl_check, struct CtdlMessage *supplied_msg)
1912 char hold_rm[ROOMNAMELEN];
1913 struct cdbdata *cdbfr;
1916 long highest_msg = 0L;
1919 struct CtdlMessage *msg = NULL;
1921 long *msgs_to_be_merged = NULL;
1922 int num_msgs_to_be_merged = 0;
1925 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d)\n",
1926 roomname, num_newmsgs, do_repl_check);
1928 strcpy(hold_rm, CC->room.QRname);
1931 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
1932 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
1933 if (num_newmsgs > 1) supplied_msg = NULL;
1935 /* Now the regular stuff */
1936 if (lgetroom(&CC->room,
1937 ((roomname != NULL) ? roomname : CC->room.QRname) )
1939 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
1940 return(ERROR + ROOM_NOT_FOUND);
1944 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
1945 num_msgs_to_be_merged = 0;
1948 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
1949 if (cdbfr == NULL) {
1953 msglist = (long *) cdbfr->ptr;
1954 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
1955 num_msgs = cdbfr->len / sizeof(long);
1960 /* Create a list of msgid's which were supplied by the caller, but do
1961 * not already exist in the target room. It is absolutely taboo to
1962 * have more than one reference to the same message in a room.
1964 for (i=0; i<num_newmsgs; ++i) {
1966 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
1967 if (msglist[j] == newmsgidlist[i]) {
1972 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
1976 lprintf(9, "%d unique messages to be merged\n", num_msgs_to_be_merged);
1979 * Now merge the new messages
1981 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
1982 if (msglist == NULL) {
1983 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
1985 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
1986 num_msgs += num_msgs_to_be_merged;
1988 /* Sort the message list, so all the msgid's are in order */
1989 num_msgs = sort_msglist(msglist, num_msgs);
1991 /* Determine the highest message number */
1992 highest_msg = msglist[num_msgs - 1];
1994 /* Write it back to disk. */
1995 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
1996 msglist, (int)(num_msgs * sizeof(long)));
1998 /* Free up the memory we used. */
2001 /* Update the highest-message pointer and unlock the room. */
2002 CC->room.QRhighest = highest_msg;
2003 lputroom(&CC->room);
2005 /* Perform replication checks if necessary */
2006 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2007 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2009 for (i=0; i<num_msgs_to_be_merged; ++i) {
2010 msgid = msgs_to_be_merged[i];
2012 if (supplied_msg != NULL) {
2016 msg = CtdlFetchMessage(msgid, 0);
2020 ReplicationChecks(msg);
2022 /* If the message has an Exclusive ID, index that... */
2023 if (msg->cm_fields['E'] != NULL) {
2024 index_message_by_euid(msg->cm_fields['E'], &CC->room, msgid);
2027 /* Free up the memory we may have allocated */
2028 if (msg != supplied_msg) {
2029 CtdlFreeMessage(msg);
2037 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2040 /* Submit this room for net processing */
2041 network_queue_room(&CC->room, NULL);
2043 #ifdef HAVE_LIBSIEVE
2044 /* If this is someone's inbox, submit the room for sieve processing */
2045 if (!strcasecmp(&CC->room.QRname[11], MAILROOM)) {
2046 sieve_queue_room(&CC->room);
2048 #endif /* HAVE_LIBSIEVE */
2050 /* Go back to the room we were in before we wandered here... */
2051 getroom(&CC->room, hold_rm);
2053 /* Bump the reference count for all messages which were merged */
2054 for (i=0; i<num_msgs_to_be_merged; ++i) {
2055 AdjRefCount(msgs_to_be_merged[i], +1);
2058 /* Free up memory... */
2059 if (msgs_to_be_merged != NULL) {
2060 free(msgs_to_be_merged);
2063 /* Return success. */
2069 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2072 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2073 int do_repl_check, struct CtdlMessage *supplied_msg)
2075 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg);
2082 * Message base operation to save a new message to the message store
2083 * (returns new message number)
2085 * This is the back end for CtdlSubmitMsg() and should not be directly
2086 * called by server-side modules.
2089 long send_message(struct CtdlMessage *msg) {
2097 /* Get a new message number */
2098 newmsgid = get_new_message_number();
2099 snprintf(msgidbuf, sizeof msgidbuf, "%010ld@%s", newmsgid, config.c_fqdn);
2101 /* Generate an ID if we don't have one already */
2102 if (msg->cm_fields['I']==NULL) {
2103 msg->cm_fields['I'] = strdup(msgidbuf);
2106 /* If the message is big, set its body aside for storage elsewhere */
2107 if (msg->cm_fields['M'] != NULL) {
2108 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2110 holdM = msg->cm_fields['M'];
2111 msg->cm_fields['M'] = NULL;
2115 /* Serialize our data structure for storage in the database */
2116 serialize_message(&smr, msg);
2119 msg->cm_fields['M'] = holdM;
2123 cprintf("%d Unable to serialize message\n",
2124 ERROR + INTERNAL_ERROR);
2128 /* Write our little bundle of joy into the message base */
2129 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2130 smr.ser, smr.len) < 0) {
2131 lprintf(CTDL_ERR, "Can't store message\n");
2135 cdb_store(CDB_BIGMSGS,
2145 /* Free the memory we used for the serialized message */
2148 /* Return the *local* message ID to the caller
2149 * (even if we're storing an incoming network message)
2157 * Serialize a struct CtdlMessage into the format used on disk and network.
2159 * This function loads up a "struct ser_ret" (defined in server.h) which
2160 * contains the length of the serialized message and a pointer to the
2161 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2163 void serialize_message(struct ser_ret *ret, /* return values */
2164 struct CtdlMessage *msg) /* unserialized msg */
2166 size_t wlen, fieldlen;
2168 static char *forder = FORDER;
2171 * Check for valid message format
2173 if (is_valid_message(msg) == 0) {
2174 lprintf(CTDL_ERR, "serialize_message() aborting due to invalid message\n");
2181 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2182 ret->len = ret->len +
2183 strlen(msg->cm_fields[(int)forder[i]]) + 2;
2185 ret->ser = malloc(ret->len);
2186 if (ret->ser == NULL) {
2187 lprintf(CTDL_ERR, "serialize_message() malloc(%ld) failed: %s\n",
2188 (long)ret->len, strerror(errno));
2195 ret->ser[1] = msg->cm_anon_type;
2196 ret->ser[2] = msg->cm_format_type;
2199 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2200 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
2201 ret->ser[wlen++] = (char)forder[i];
2202 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
2203 wlen = wlen + fieldlen + 1;
2205 if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2206 (long)ret->len, (long)wlen);
2214 * Check to see if any messages already exist in the current room which
2215 * carry the same Exclusive ID as this one. If any are found, delete them.
2217 void ReplicationChecks(struct CtdlMessage *msg) {
2218 long old_msgnum = (-1L);
2220 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2222 lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2225 /* No exclusive id? Don't do anything. */
2226 if (msg == NULL) return;
2227 if (msg->cm_fields['E'] == NULL) return;
2228 if (strlen(msg->cm_fields['E']) == 0) return;
2229 /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2230 msg->cm_fields['E'], CC->room.QRname);*/
2232 old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2233 if (old_msgnum > 0L) {
2234 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2235 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "", 0);
2242 * Save a message to disk and submit it into the delivery system.
2244 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2245 struct recptypes *recps, /* recipients (if mail) */
2246 char *force /* force a particular room? */
2248 char submit_filename[128];
2249 char generated_timestamp[32];
2250 char hold_rm[ROOMNAMELEN];
2251 char actual_rm[ROOMNAMELEN];
2252 char force_room[ROOMNAMELEN];
2253 char content_type[SIZ]; /* We have to learn this */
2254 char recipient[SIZ];
2257 struct ctdluser userbuf;
2259 struct MetaData smi;
2260 FILE *network_fp = NULL;
2261 static int seqnum = 1;
2262 struct CtdlMessage *imsg = NULL;
2265 char *hold_R, *hold_D;
2266 char *collected_addresses = NULL;
2267 struct addresses_to_be_filed *aptr = NULL;
2268 char *saved_rfc822_version = NULL;
2269 int qualified_for_journaling = 0;
2271 lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2272 if (is_valid_message(msg) == 0) return(-1); /* self check */
2274 /* If this message has no timestamp, we take the liberty of
2275 * giving it one, right now.
2277 if (msg->cm_fields['T'] == NULL) {
2278 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2279 msg->cm_fields['T'] = strdup(generated_timestamp);
2282 /* If this message has no path, we generate one.
2284 if (msg->cm_fields['P'] == NULL) {
2285 if (msg->cm_fields['A'] != NULL) {
2286 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2287 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
2288 if (isspace(msg->cm_fields['P'][a])) {
2289 msg->cm_fields['P'][a] = ' ';
2294 msg->cm_fields['P'] = strdup("unknown");
2298 if (force == NULL) {
2299 strcpy(force_room, "");
2302 strcpy(force_room, force);
2305 /* Learn about what's inside, because it's what's inside that counts */
2306 if (msg->cm_fields['M'] == NULL) {
2307 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2311 switch (msg->cm_format_type) {
2313 strcpy(content_type, "text/x-citadel-variformat");
2316 strcpy(content_type, "text/plain");
2319 strcpy(content_type, "text/plain");
2320 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type: ");
2322 safestrncpy(content_type, &mptr[14],
2323 sizeof content_type);
2324 for (a = 0; a < strlen(content_type); ++a) {
2325 if ((content_type[a] == ';')
2326 || (content_type[a] == ' ')
2327 || (content_type[a] == 13)
2328 || (content_type[a] == 10)) {
2329 content_type[a] = 0;
2335 /* Goto the correct room */
2336 lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CC->room.QRname : SENTITEMS);
2337 strcpy(hold_rm, CC->room.QRname);
2338 strcpy(actual_rm, CC->room.QRname);
2339 if (recps != NULL) {
2340 strcpy(actual_rm, SENTITEMS);
2343 /* If the user is a twit, move to the twit room for posting */
2345 if (CC->user.axlevel == 2) {
2346 strcpy(hold_rm, actual_rm);
2347 strcpy(actual_rm, config.c_twitroom);
2348 lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2352 /* ...or if this message is destined for Aide> then go there. */
2353 if (strlen(force_room) > 0) {
2354 strcpy(actual_rm, force_room);
2357 lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2358 if (strcasecmp(actual_rm, CC->room.QRname)) {
2359 /* getroom(&CC->room, actual_rm); */
2360 usergoto(actual_rm, 0, 1, NULL, NULL);
2364 * If this message has no O (room) field, generate one.
2366 if (msg->cm_fields['O'] == NULL) {
2367 msg->cm_fields['O'] = strdup(CC->room.QRname);
2370 /* Perform "before save" hooks (aborting if any return nonzero) */
2371 lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2372 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2375 * If this message has an Exclusive ID, and the room is replication
2376 * checking enabled, then do replication checks.
2378 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2379 ReplicationChecks(msg);
2382 /* Save it to disk */
2383 lprintf(CTDL_DEBUG, "Saving to disk\n");
2384 newmsgid = send_message(msg);
2385 if (newmsgid <= 0L) return(-5);
2387 /* Write a supplemental message info record. This doesn't have to
2388 * be a critical section because nobody else knows about this message
2391 lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2392 memset(&smi, 0, sizeof(struct MetaData));
2393 smi.meta_msgnum = newmsgid;
2394 smi.meta_refcount = 0;
2395 safestrncpy(smi.meta_content_type, content_type,
2396 sizeof smi.meta_content_type);
2399 * Measure how big this message will be when rendered as RFC822.
2400 * We do this for two reasons:
2401 * 1. We need the RFC822 length for the new metadata record, so the
2402 * POP and IMAP services don't have to calculate message lengths
2403 * while the user is waiting (multiplied by potentially hundreds
2404 * or thousands of messages).
2405 * 2. If journaling is enabled, we will need an RFC822 version of the
2406 * message to attach to the journalized copy.
2408 if (CC->redirect_buffer != NULL) {
2409 lprintf(CTDL_ALERT, "CC->redirect_buffer is not NULL during message submission!\n");
2412 CC->redirect_buffer = malloc(SIZ);
2413 CC->redirect_len = 0;
2414 CC->redirect_alloc = SIZ;
2415 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2416 smi.meta_rfc822_length = CC->redirect_len;
2417 saved_rfc822_version = CC->redirect_buffer;
2418 CC->redirect_buffer = NULL;
2419 CC->redirect_len = 0;
2420 CC->redirect_alloc = 0;
2424 /* Now figure out where to store the pointers */
2425 lprintf(CTDL_DEBUG, "Storing pointers\n");
2427 /* If this is being done by the networker delivering a private
2428 * message, we want to BYPASS saving the sender's copy (because there
2429 * is no local sender; it would otherwise go to the Trashcan).
2431 if ((!CC->internal_pgm) || (recps == NULL)) {
2432 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2433 lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2434 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2438 /* For internet mail, drop a copy in the outbound queue room */
2440 if (recps->num_internet > 0) {
2441 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2444 /* If other rooms are specified, drop them there too. */
2446 if (recps->num_room > 0)
2447 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2448 extract_token(recipient, recps->recp_room, i,
2449 '|', sizeof recipient);
2450 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2451 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2454 /* Bump this user's messages posted counter. */
2455 lprintf(CTDL_DEBUG, "Updating user\n");
2456 lgetuser(&CC->user, CC->curr_user);
2457 CC->user.posted = CC->user.posted + 1;
2458 lputuser(&CC->user);
2460 /* If this is private, local mail, make a copy in the
2461 * recipient's mailbox and bump the reference count.
2464 if (recps->num_local > 0)
2465 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2466 extract_token(recipient, recps->recp_local, i,
2467 '|', sizeof recipient);
2468 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2470 if (getuser(&userbuf, recipient) == 0) {
2471 MailboxName(actual_rm, sizeof actual_rm,
2472 &userbuf, MAILROOM);
2473 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2474 BumpNewMailCounter(userbuf.usernum);
2477 lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2478 CtdlSaveMsgPointerInRoom(config.c_aideroom,
2483 /* Perform "after save" hooks */
2484 lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2485 PerformMessageHooks(msg, EVT_AFTERSAVE);
2487 /* For IGnet mail, we have to save a new copy into the spooler for
2488 * each recipient, with the R and D fields set to the recipient and
2489 * destination-node. This has two ugly side effects: all other
2490 * recipients end up being unlisted in this recipient's copy of the
2491 * message, and it has to deliver multiple messages to the same
2492 * node. We'll revisit this again in a year or so when everyone has
2493 * a network spool receiver that can handle the new style messages.
2496 if (recps->num_ignet > 0)
2497 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2498 extract_token(recipient, recps->recp_ignet, i,
2499 '|', sizeof recipient);
2501 hold_R = msg->cm_fields['R'];
2502 hold_D = msg->cm_fields['D'];
2503 msg->cm_fields['R'] = malloc(SIZ);
2504 msg->cm_fields['D'] = malloc(128);
2505 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2506 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2508 serialize_message(&smr, msg);
2510 snprintf(submit_filename, sizeof submit_filename,
2511 "%s/netmail.%04lx.%04x.%04x",
2513 (long) getpid(), CC->cs_pid, ++seqnum);
2514 network_fp = fopen(submit_filename, "wb+");
2515 if (network_fp != NULL) {
2516 fwrite(smr.ser, smr.len, 1, network_fp);
2522 free(msg->cm_fields['R']);
2523 free(msg->cm_fields['D']);
2524 msg->cm_fields['R'] = hold_R;
2525 msg->cm_fields['D'] = hold_D;
2528 /* Go back to the room we started from */
2529 lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2530 if (strcasecmp(hold_rm, CC->room.QRname))
2531 /* getroom(&CC->room, hold_rm); */
2532 usergoto(hold_rm, 0, 1, NULL, NULL);
2534 /* For internet mail, generate delivery instructions.
2535 * Yes, this is recursive. Deal with it. Infinite recursion does
2536 * not happen because the delivery instructions message does not
2537 * contain a recipient.
2540 if (recps->num_internet > 0) {
2541 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2542 instr = malloc(SIZ * 2);
2543 snprintf(instr, SIZ * 2,
2544 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2546 SPOOLMIME, newmsgid, (long)time(NULL),
2547 msg->cm_fields['A'], msg->cm_fields['N']
2550 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2551 size_t tmp = strlen(instr);
2552 extract_token(recipient, recps->recp_internet,
2553 i, '|', sizeof recipient);
2554 snprintf(&instr[tmp], SIZ * 2 - tmp,
2555 "remote|%s|0||\n", recipient);
2558 imsg = malloc(sizeof(struct CtdlMessage));
2559 memset(imsg, 0, sizeof(struct CtdlMessage));
2560 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2561 imsg->cm_anon_type = MES_NORMAL;
2562 imsg->cm_format_type = FMT_RFC822;
2563 imsg->cm_fields['A'] = strdup("Citadel");
2564 imsg->cm_fields['J'] = strdup("do not journal");
2565 imsg->cm_fields['M'] = instr;
2566 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2567 CtdlFreeMessage(imsg);
2571 * Any addresses to harvest for someone's address book?
2573 if ( (CC->logged_in) && (recps != NULL) ) {
2574 collected_addresses = harvest_collected_addresses(msg);
2577 if (collected_addresses != NULL) {
2578 begin_critical_section(S_ATBF);
2579 aptr = (struct addresses_to_be_filed *)
2580 malloc(sizeof(struct addresses_to_be_filed));
2582 MailboxName(actual_rm, sizeof actual_rm,
2583 &CC->user, USERCONTACTSROOM);
2584 aptr->roomname = strdup(actual_rm);
2585 aptr->collected_addresses = collected_addresses;
2587 end_critical_section(S_ATBF);
2591 * Determine whether this message qualifies for journaling.
2593 if (msg->cm_fields['J'] != NULL) {
2594 qualified_for_journaling = 0;
2597 if (recps == NULL) {
2598 qualified_for_journaling = config.c_journal_pubmsgs;
2600 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2601 qualified_for_journaling = config.c_journal_email;
2604 qualified_for_journaling = config.c_journal_pubmsgs;
2609 * Do we have to perform journaling? If so, hand off the saved
2610 * RFC822 version will be handed off to the journaler for background
2611 * submit. Otherwise, we have to free the memory ourselves.
2613 if (saved_rfc822_version != NULL) {
2614 if (qualified_for_journaling) {
2615 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2618 free(saved_rfc822_version);
2631 * Convenience function for generating small administrative messages.
2633 void quickie_message(char *from, char *to, char *room, char *text,
2634 int format_type, char *subject)
2636 struct CtdlMessage *msg;
2637 struct recptypes *recp = NULL;
2639 msg = malloc(sizeof(struct CtdlMessage));
2640 memset(msg, 0, sizeof(struct CtdlMessage));
2641 msg->cm_magic = CTDLMESSAGE_MAGIC;
2642 msg->cm_anon_type = MES_NORMAL;
2643 msg->cm_format_type = format_type;
2644 msg->cm_fields['A'] = strdup(from);
2645 if (room != NULL) msg->cm_fields['O'] = strdup(room);
2646 msg->cm_fields['N'] = strdup(NODENAME);
2648 msg->cm_fields['R'] = strdup(to);
2649 recp = validate_recipients(to);
2651 if (subject != NULL) {
2652 msg->cm_fields['U'] = strdup(subject);
2654 msg->cm_fields['M'] = strdup(text);
2656 CtdlSubmitMsg(msg, recp, room);
2657 CtdlFreeMessage(msg);
2658 if (recp != NULL) free(recp);
2664 * Back end function used by CtdlMakeMessage() and similar functions
2666 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2667 size_t maxlen, /* maximum message length */
2668 char *exist, /* if non-null, append to it;
2669 exist is ALWAYS freed */
2670 int crlf /* CRLF newlines instead of LF */
2674 size_t message_len = 0;
2675 size_t buffer_len = 0;
2682 if (exist == NULL) {
2689 message_len = strlen(exist);
2690 buffer_len = message_len + 4096;
2691 m = realloc(exist, buffer_len);
2698 /* Do we need to change leading ".." to "." for SMTP escaping? */
2699 if (!strcmp(terminator, ".")) {
2703 /* flush the input if we have nowhere to store it */
2708 /* read in the lines of message text one by one */
2710 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2711 if (!strcmp(buf, terminator)) finished = 1;
2713 strcat(buf, "\r\n");
2719 /* Unescape SMTP-style input of two dots at the beginning of the line */
2721 if (!strncmp(buf, "..", 2)) {
2722 strcpy(buf, &buf[1]);
2726 if ( (!flushing) && (!finished) ) {
2727 /* Measure the line */
2728 linelen = strlen(buf);
2730 /* augment the buffer if we have to */
2731 if ((message_len + linelen) >= buffer_len) {
2732 ptr = realloc(m, (buffer_len * 2) );
2733 if (ptr == NULL) { /* flush if can't allocate */
2736 buffer_len = (buffer_len * 2);
2738 lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2742 /* Add the new line to the buffer. NOTE: this loop must avoid
2743 * using functions like strcat() and strlen() because they
2744 * traverse the entire buffer upon every call, and doing that
2745 * for a multi-megabyte message slows it down beyond usability.
2747 strcpy(&m[message_len], buf);
2748 message_len += linelen;
2751 /* if we've hit the max msg length, flush the rest */
2752 if (message_len >= maxlen) flushing = 1;
2754 } while (!finished);
2762 * Build a binary message to be saved on disk.
2763 * (NOTE: if you supply 'preformatted_text', the buffer you give it
2764 * will become part of the message. This means you are no longer
2765 * responsible for managing that memory -- it will be freed along with
2766 * the rest of the fields when CtdlFreeMessage() is called.)
2769 struct CtdlMessage *CtdlMakeMessage(
2770 struct ctdluser *author, /* author's user structure */
2771 char *recipient, /* NULL if it's not mail */
2772 char *recp_cc, /* NULL if it's not mail */
2773 char *room, /* room where it's going */
2774 int type, /* see MES_ types in header file */
2775 int format_type, /* variformat, plain text, MIME... */
2776 char *fake_name, /* who we're masquerading as */
2777 char *subject, /* Subject (optional) */
2778 char *supplied_euid, /* ...or NULL if this is irrelevant */
2779 char *preformatted_text /* ...or NULL to read text from client */
2781 char dest_node[SIZ];
2783 struct CtdlMessage *msg;
2785 msg = malloc(sizeof(struct CtdlMessage));
2786 memset(msg, 0, sizeof(struct CtdlMessage));
2787 msg->cm_magic = CTDLMESSAGE_MAGIC;
2788 msg->cm_anon_type = type;
2789 msg->cm_format_type = format_type;
2791 /* Don't confuse the poor folks if it's not routed mail. */
2792 strcpy(dest_node, "");
2797 snprintf(buf, sizeof buf, "cit%ld", author->usernum); /* Path */
2798 msg->cm_fields['P'] = strdup(buf);
2800 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
2801 msg->cm_fields['T'] = strdup(buf);
2803 if (fake_name[0]) /* author */
2804 msg->cm_fields['A'] = strdup(fake_name);
2806 msg->cm_fields['A'] = strdup(author->fullname);
2808 if (CC->room.QRflags & QR_MAILBOX) { /* room */
2809 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2812 msg->cm_fields['O'] = strdup(CC->room.QRname);
2815 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
2816 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
2818 if (recipient[0] != 0) {
2819 msg->cm_fields['R'] = strdup(recipient);
2821 if (recp_cc[0] != 0) {
2822 msg->cm_fields['Y'] = strdup(recp_cc);
2824 if (dest_node[0] != 0) {
2825 msg->cm_fields['D'] = strdup(dest_node);
2828 if ( (author == &CC->user) && (strlen(CC->cs_inet_email) > 0) ) {
2829 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2832 if (subject != NULL) {
2834 if (strlen(subject) > 0) {
2835 msg->cm_fields['U'] = strdup(subject);
2839 if (supplied_euid != NULL) {
2840 msg->cm_fields['E'] = strdup(supplied_euid);
2843 if (preformatted_text != NULL) {
2844 msg->cm_fields['M'] = preformatted_text;
2847 msg->cm_fields['M'] = CtdlReadMessageBody("000",
2848 config.c_maxmsglen, NULL, 0);
2856 * Check to see whether we have permission to post a message in the current
2857 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
2858 * returns 0 on success.
2860 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
2862 if (!(CC->logged_in)) {
2863 snprintf(errmsgbuf, n, "Not logged in.");
2864 return (ERROR + NOT_LOGGED_IN);
2867 if ((CC->user.axlevel < 2)
2868 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
2869 snprintf(errmsgbuf, n, "Need to be validated to enter "
2870 "(except in %s> to sysop)", MAILROOM);
2871 return (ERROR + HIGHER_ACCESS_REQUIRED);
2874 if ((CC->user.axlevel < 4)
2875 && (CC->room.QRflags & QR_NETWORK)) {
2876 snprintf(errmsgbuf, n, "Need net privileges to enter here.");
2877 return (ERROR + HIGHER_ACCESS_REQUIRED);
2880 if ((CC->user.axlevel < 6)
2881 && (CC->room.QRflags & QR_READONLY)) {
2882 snprintf(errmsgbuf, n, "Sorry, this is a read-only room.");
2883 return (ERROR + HIGHER_ACCESS_REQUIRED);
2886 strcpy(errmsgbuf, "Ok");
2892 * Check to see if the specified user has Internet mail permission
2893 * (returns nonzero if permission is granted)
2895 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
2897 /* Do not allow twits to send Internet mail */
2898 if (who->axlevel <= 2) return(0);
2900 /* Globally enabled? */
2901 if (config.c_restrict == 0) return(1);
2903 /* User flagged ok? */
2904 if (who->flags & US_INTERNET) return(2);
2906 /* Aide level access? */
2907 if (who->axlevel >= 6) return(3);
2909 /* No mail for you! */
2915 * Validate recipients, count delivery types and errors, and handle aliasing
2916 * FIXME check for dupes!!!!!
2917 * Returns 0 if all addresses are ok, -1 if no addresses were specified,
2918 * or the number of addresses found invalid.
2920 struct recptypes *validate_recipients(char *supplied_recipients) {
2921 struct recptypes *ret;
2922 char recipients[SIZ];
2923 char this_recp[256];
2924 char this_recp_cooked[256];
2930 struct ctdluser tempUS;
2931 struct ctdlroom tempQR;
2935 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
2936 if (ret == NULL) return(NULL);
2937 memset(ret, 0, sizeof(struct recptypes));
2940 ret->num_internet = 0;
2945 if (supplied_recipients == NULL) {
2946 strcpy(recipients, "");
2949 safestrncpy(recipients, supplied_recipients, sizeof recipients);
2952 /* Change all valid separator characters to commas */
2953 for (i=0; i<strlen(recipients); ++i) {
2954 if ((recipients[i] == ';') || (recipients[i] == '|')) {
2955 recipients[i] = ',';
2959 /* Now start extracting recipients... */
2961 while (strlen(recipients) > 0) {
2963 for (i=0; i<=strlen(recipients); ++i) {
2964 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
2965 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
2966 safestrncpy(this_recp, recipients, i+1);
2968 if (recipients[i] == ',') {
2969 strcpy(recipients, &recipients[i+1]);
2972 strcpy(recipients, "");
2979 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
2981 mailtype = alias(this_recp);
2982 mailtype = alias(this_recp);
2983 mailtype = alias(this_recp);
2984 for (j=0; j<=strlen(this_recp); ++j) {
2985 if (this_recp[j]=='_') {
2986 this_recp_cooked[j] = ' ';
2989 this_recp_cooked[j] = this_recp[j];
2995 if (!strcasecmp(this_recp, "sysop")) {
2997 strcpy(this_recp, config.c_aideroom);
2998 if (strlen(ret->recp_room) > 0) {
2999 strcat(ret->recp_room, "|");
3001 strcat(ret->recp_room, this_recp);
3003 else if (getuser(&tempUS, this_recp) == 0) {
3005 strcpy(this_recp, tempUS.fullname);
3006 if (strlen(ret->recp_local) > 0) {
3007 strcat(ret->recp_local, "|");
3009 strcat(ret->recp_local, this_recp);
3011 else if (getuser(&tempUS, this_recp_cooked) == 0) {
3013 strcpy(this_recp, tempUS.fullname);
3014 if (strlen(ret->recp_local) > 0) {
3015 strcat(ret->recp_local, "|");
3017 strcat(ret->recp_local, this_recp);
3019 else if ( (!strncasecmp(this_recp, "room_", 5))
3020 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
3022 if (strlen(ret->recp_room) > 0) {
3023 strcat(ret->recp_room, "|");
3025 strcat(ret->recp_room, &this_recp_cooked[5]);
3033 /* Yes, you're reading this correctly: if the target
3034 * domain points back to the local system or an attached
3035 * Citadel directory, the address is invalid. That's
3036 * because if the address were valid, we would have
3037 * already translated it to a local address by now.
3039 if (IsDirectory(this_recp)) {
3044 ++ret->num_internet;
3045 if (strlen(ret->recp_internet) > 0) {
3046 strcat(ret->recp_internet, "|");
3048 strcat(ret->recp_internet, this_recp);
3053 if (strlen(ret->recp_ignet) > 0) {
3054 strcat(ret->recp_ignet, "|");
3056 strcat(ret->recp_ignet, this_recp);
3064 if (strlen(ret->errormsg) == 0) {
3065 snprintf(append, sizeof append,
3066 "Invalid recipient: %s",
3070 snprintf(append, sizeof append,
3073 if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
3074 strcat(ret->errormsg, append);
3078 if (strlen(ret->display_recp) == 0) {
3079 strcpy(append, this_recp);
3082 snprintf(append, sizeof append, ", %s",
3085 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
3086 strcat(ret->display_recp, append);
3091 if ((ret->num_local + ret->num_internet + ret->num_ignet +
3092 ret->num_room + ret->num_error) == 0) {
3093 ret->num_error = (-1);
3094 strcpy(ret->errormsg, "No recipients specified.");
3097 lprintf(CTDL_DEBUG, "validate_recipients()\n");
3098 lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
3099 lprintf(CTDL_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
3100 lprintf(CTDL_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
3101 lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
3102 lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
3110 * message entry - mode 0 (normal)
3112 void cmd_ent0(char *entargs)
3118 char supplied_euid[128];
3119 char masquerade_as[SIZ];
3121 int format_type = 0;
3122 char newusername[SIZ];
3123 struct CtdlMessage *msg;
3127 struct recptypes *valid = NULL;
3128 struct recptypes *valid_to = NULL;
3129 struct recptypes *valid_cc = NULL;
3130 struct recptypes *valid_bcc = NULL;
3137 post = extract_int(entargs, 0);
3138 extract_token(recp, entargs, 1, '|', sizeof recp);
3139 anon_flag = extract_int(entargs, 2);
3140 format_type = extract_int(entargs, 3);
3141 extract_token(subject, entargs, 4, '|', sizeof subject);
3142 do_confirm = extract_int(entargs, 6);
3143 extract_token(cc, entargs, 7, '|', sizeof cc);
3144 extract_token(bcc, entargs, 8, '|', sizeof bcc);
3145 switch(CC->room.QRdefaultview) {
3148 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3151 supplied_euid[0] = 0;
3155 /* first check to make sure the request is valid. */
3157 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3159 cprintf("%d %s\n", err, errmsg);
3163 /* Check some other permission type things. */
3166 if (CC->user.axlevel < 6) {
3167 cprintf("%d You don't have permission to masquerade.\n",
3168 ERROR + HIGHER_ACCESS_REQUIRED);
3171 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3172 memset(CC->fake_postname, 0, sizeof(CC->fake_postname) );
3173 safestrncpy(CC->fake_postname, newusername,
3174 sizeof(CC->fake_postname) );
3175 cprintf("%d ok\n", CIT_OK);
3178 CC->cs_flags |= CS_POSTING;
3180 /* In the Mail> room we have to behave a little differently --
3181 * make sure the user has specified at least one recipient. Then
3182 * validate the recipient(s).
3184 if ( (CC->room.QRflags & QR_MAILBOX)
3185 && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) ) {
3187 if (CC->user.axlevel < 2) {
3188 strcpy(recp, "sysop");
3193 valid_to = validate_recipients(recp);
3194 if (valid_to->num_error > 0) {
3195 cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3200 valid_cc = validate_recipients(cc);
3201 if (valid_cc->num_error > 0) {
3202 cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3208 valid_bcc = validate_recipients(bcc);
3209 if (valid_bcc->num_error > 0) {
3210 cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3217 /* Recipient required, but none were specified */
3218 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3222 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3226 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3227 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3228 cprintf("%d You do not have permission "
3229 "to send Internet mail.\n",
3230 ERROR + HIGHER_ACCESS_REQUIRED);
3238 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)
3239 && (CC->user.axlevel < 4) ) {
3240 cprintf("%d Higher access required for network mail.\n",
3241 ERROR + HIGHER_ACCESS_REQUIRED);
3248 if ((RESTRICT_INTERNET == 1)
3249 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3250 && ((CC->user.flags & US_INTERNET) == 0)
3251 && (!CC->internal_pgm)) {
3252 cprintf("%d You don't have access to Internet mail.\n",
3253 ERROR + HIGHER_ACCESS_REQUIRED);
3262 /* Is this a room which has anonymous-only or anonymous-option? */
3263 anonymous = MES_NORMAL;
3264 if (CC->room.QRflags & QR_ANONONLY) {
3265 anonymous = MES_ANONONLY;
3267 if (CC->room.QRflags & QR_ANONOPT) {
3268 if (anon_flag == 1) { /* only if the user requested it */
3269 anonymous = MES_ANONOPT;
3273 if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3277 /* If we're only checking the validity of the request, return
3278 * success without creating the message.
3281 cprintf("%d %s\n", CIT_OK,
3282 ((valid_to != NULL) ? valid_to->display_recp : "") );
3289 /* We don't need these anymore because we'll do it differently below */
3294 /* Handle author masquerading */
3295 if (CC->fake_postname[0]) {
3296 strcpy(masquerade_as, CC->fake_postname);
3298 else if (CC->fake_username[0]) {
3299 strcpy(masquerade_as, CC->fake_username);
3302 strcpy(masquerade_as, "");
3305 /* Read in the message from the client. */
3307 cprintf("%d send message\n", START_CHAT_MODE);
3309 cprintf("%d send message\n", SEND_LISTING);
3312 msg = CtdlMakeMessage(&CC->user, recp, cc,
3313 CC->room.QRname, anonymous, format_type,
3314 masquerade_as, subject,
3315 ((strlen(supplied_euid) > 0) ? supplied_euid : NULL),
3318 /* Put together one big recipients struct containing to/cc/bcc all in
3319 * one. This is for the envelope.
3321 char *all_recps = malloc(SIZ * 3);
3322 strcpy(all_recps, recp);
3323 if (strlen(cc) > 0) {
3324 if (strlen(all_recps) > 0) {
3325 strcat(all_recps, ",");
3327 strcat(all_recps, cc);
3329 if (strlen(bcc) > 0) {
3330 if (strlen(all_recps) > 0) {
3331 strcat(all_recps, ",");
3333 strcat(all_recps, bcc);
3335 if (strlen(all_recps) > 0) {
3336 valid = validate_recipients(all_recps);
3344 msgnum = CtdlSubmitMsg(msg, valid, "");
3347 cprintf("%ld\n", msgnum);
3349 cprintf("Message accepted.\n");
3352 cprintf("Internal error.\n");
3354 if (msg->cm_fields['E'] != NULL) {
3355 cprintf("%s\n", msg->cm_fields['E']);
3362 CtdlFreeMessage(msg);
3364 CC->fake_postname[0] = '\0';
3365 if (valid != NULL) {
3374 * API function to delete messages which match a set of criteria
3375 * (returns the actual number of messages deleted)
3377 int CtdlDeleteMessages(char *room_name, /* which room */
3378 long *dmsgnums, /* array of msg numbers to be deleted */
3379 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
3380 char *content_type, /* or "" for any */
3381 int deferred /* let TDAP sweep it later */
3385 struct ctdlroom qrbuf;
3386 struct cdbdata *cdbfr;
3387 long *msglist = NULL;
3388 long *dellist = NULL;
3391 int num_deleted = 0;
3393 struct MetaData smi;
3395 lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s, %d)\n",
3396 room_name, num_dmsgnums, content_type, deferred);
3398 /* get room record, obtaining a lock... */
3399 if (lgetroom(&qrbuf, room_name) != 0) {
3400 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3402 return (0); /* room not found */
3404 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3406 if (cdbfr != NULL) {
3407 dellist = malloc(cdbfr->len);
3408 msglist = (long *) cdbfr->ptr;
3409 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3410 num_msgs = cdbfr->len / sizeof(long);
3414 for (i = 0; i < num_msgs; ++i) {
3417 /* Set/clear a bit for each criterion */
3419 /* 0 messages in the list or a null list means that we are
3420 * interested in deleting any messages which meet the other criteria.
3422 if ((num_dmsgnums == 0) || (dmsgnums == NULL)) {
3423 delete_this |= 0x01;
3426 for (j=0; j<num_dmsgnums; ++j) {
3427 if (msglist[i] == dmsgnums[j]) {
3428 delete_this |= 0x01;
3433 if (strlen(content_type) == 0) {
3434 delete_this |= 0x02;
3436 GetMetaData(&smi, msglist[i]);
3437 if (!strcasecmp(smi.meta_content_type,
3439 delete_this |= 0x02;
3443 /* Delete message only if all bits are set */
3444 if (delete_this == 0x03) {
3445 dellist[num_deleted++] = msglist[i];
3450 num_msgs = sort_msglist(msglist, num_msgs);
3451 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3452 msglist, (int)(num_msgs * sizeof(long)));
3454 qrbuf.QRhighest = msglist[num_msgs - 1];
3459 * If the delete operation is "deferred" (and technically, any delete
3460 * operation not performed by THE DREADED AUTO-PURGER ought to be
3461 * a deferred delete) then we save a pointer to the message in the
3462 * DELETED_MSGS_ROOM. This will cause the reference count to remain
3463 * at least 1, which will save the user from having to synchronously
3464 * wait for various disk-intensive operations to complete.
3466 * Slick -- we now use the new bulk API for moving messages.
3468 if ( (deferred) && (num_deleted) ) {
3469 CtdlCopyMsgsToRoom(dellist, num_deleted, DELETED_MSGS_ROOM);
3472 /* Go through the messages we pulled out of the index, and decrement
3473 * their reference counts by 1. If this is the only room the message
3474 * was in, the reference count will reach zero and the message will
3475 * automatically be deleted from the database. We do this in a
3476 * separate pass because there might be plug-in hooks getting called,
3477 * and we don't want that happening during an S_ROOMS critical
3480 if (num_deleted) for (i=0; i<num_deleted; ++i) {
3481 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3482 AdjRefCount(dellist[i], -1);
3485 /* Now free the memory we used, and go away. */
3486 if (msglist != NULL) free(msglist);
3487 if (dellist != NULL) free(dellist);
3488 lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3489 return (num_deleted);
3495 * Check whether the current user has permission to delete messages from
3496 * the current room (returns 1 for yes, 0 for no)
3498 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3499 getuser(&CC->user, CC->curr_user);
3500 if ((CC->user.axlevel < 6)
3501 && (CC->user.usernum != CC->room.QRroomaide)
3502 && ((CC->room.QRflags & QR_MAILBOX) == 0)
3503 && (!(CC->internal_pgm))) {
3512 * Delete message from current room
3514 void cmd_dele(char *args)
3523 extract_token(msgset, args, 0, '|', sizeof msgset);
3524 num_msgs = num_tokens(msgset, ',');
3526 cprintf("%d Nothing to do.\n", CIT_OK);
3530 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3531 cprintf("%d Higher access required.\n",
3532 ERROR + HIGHER_ACCESS_REQUIRED);
3537 * Build our message set to be moved/copied
3539 msgs = malloc(num_msgs * sizeof(long));
3540 for (i=0; i<num_msgs; ++i) {
3541 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3542 msgs[i] = atol(msgtok);
3545 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "", 1);
3549 cprintf("%d %d message%s deleted.\n", CIT_OK,
3550 num_deleted, ((num_deleted != 1) ? "s" : ""));
3552 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
3558 * Back end API function for moves and deletes (multiple messages)
3560 int CtdlCopyMsgsToRoom(long *msgnums, int num_msgs, char *dest) {
3563 err = CtdlSaveMsgPointersInRoom(dest, msgnums, num_msgs, 1, NULL);
3564 if (err != 0) return(err);
3573 * move or copy a message to another room
3575 void cmd_move(char *args)
3582 char targ[ROOMNAMELEN];
3583 struct ctdlroom qtemp;
3590 extract_token(msgset, args, 0, '|', sizeof msgset);
3591 num_msgs = num_tokens(msgset, ',');
3593 cprintf("%d Nothing to do.\n", CIT_OK);
3597 extract_token(targ, args, 1, '|', sizeof targ);
3598 convert_room_name_macros(targ, sizeof targ);
3599 targ[ROOMNAMELEN - 1] = 0;
3600 is_copy = extract_int(args, 2);
3602 if (getroom(&qtemp, targ) != 0) {
3603 cprintf("%d '%s' does not exist.\n",
3604 ERROR + ROOM_NOT_FOUND, targ);
3608 getuser(&CC->user, CC->curr_user);
3609 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3611 /* Check for permission to perform this operation.
3612 * Remember: "CC->room" is source, "qtemp" is target.
3616 /* Aides can move/copy */
3617 if (CC->user.axlevel >= 6) permit = 1;
3619 /* Room aides can move/copy */
3620 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3622 /* Permit move/copy from personal rooms */
3623 if ((CC->room.QRflags & QR_MAILBOX)
3624 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3626 /* Permit only copy from public to personal room */
3628 && (!(CC->room.QRflags & QR_MAILBOX))
3629 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3631 /* User must have access to target room */
3632 if (!(ra & UA_KNOWN)) permit = 0;
3635 cprintf("%d Higher access required.\n",
3636 ERROR + HIGHER_ACCESS_REQUIRED);
3641 * Build our message set to be moved/copied
3643 msgs = malloc(num_msgs * sizeof(long));
3644 for (i=0; i<num_msgs; ++i) {
3645 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3646 msgs[i] = atol(msgtok);
3652 err = CtdlCopyMsgsToRoom(msgs, num_msgs, targ);
3654 cprintf("%d Cannot store message(s) in %s: error %d\n",
3660 /* Now delete the message from the source room,
3661 * if this is a 'move' rather than a 'copy' operation.
3664 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "", 0);
3668 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3674 * GetMetaData() - Get the supplementary record for a message
3676 void GetMetaData(struct MetaData *smibuf, long msgnum)
3679 struct cdbdata *cdbsmi;
3682 memset(smibuf, 0, sizeof(struct MetaData));
3683 smibuf->meta_msgnum = msgnum;
3684 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3686 /* Use the negative of the message number for its supp record index */
3687 TheIndex = (0L - msgnum);
3689 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3690 if (cdbsmi == NULL) {
3691 return; /* record not found; go with defaults */
3693 memcpy(smibuf, cdbsmi->ptr,
3694 ((cdbsmi->len > sizeof(struct MetaData)) ?
3695 sizeof(struct MetaData) : cdbsmi->len));
3702 * PutMetaData() - (re)write supplementary record for a message
3704 void PutMetaData(struct MetaData *smibuf)
3708 /* Use the negative of the message number for the metadata db index */
3709 TheIndex = (0L - smibuf->meta_msgnum);
3711 lprintf(CTDL_DEBUG, "PutMetaData(%ld) - ref count is %d\n",
3712 smibuf->meta_msgnum, smibuf->meta_refcount);
3714 cdb_store(CDB_MSGMAIN,
3715 &TheIndex, (int)sizeof(long),
3716 smibuf, (int)sizeof(struct MetaData));
3721 * AdjRefCount - change the reference count for a message;
3722 * delete the message if it reaches zero
3724 void AdjRefCount(long msgnum, int incr)
3727 struct MetaData smi;
3730 /* This is a *tight* critical section; please keep it that way, as
3731 * it may get called while nested in other critical sections.
3732 * Complicating this any further will surely cause deadlock!
3734 begin_critical_section(S_SUPPMSGMAIN);
3735 GetMetaData(&smi, msgnum);
3736 smi.meta_refcount += incr;
3738 end_critical_section(S_SUPPMSGMAIN);
3739 lprintf(CTDL_DEBUG, "msg %ld ref count incr %d, is now %d\n",
3740 msgnum, incr, smi.meta_refcount);
3742 /* If the reference count is now zero, delete the message
3743 * (and its supplementary record as well).
3745 if (smi.meta_refcount == 0) {
3746 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
3748 /* Remove from fulltext index */
3749 if (config.c_enable_fulltext) {
3750 ft_index_message(msgnum, 0);
3753 /* Remove from message base */
3755 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3756 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3758 /* Remove metadata record */
3759 delnum = (0L - msgnum);
3760 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3765 * Write a generic object to this room
3767 * Note: this could be much more efficient. Right now we use two temporary
3768 * files, and still pull the message into memory as with all others.
3770 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
3771 char *content_type, /* MIME type of this object */
3772 char *tempfilename, /* Where to fetch it from */
3773 struct ctdluser *is_mailbox, /* Mailbox room? */
3774 int is_binary, /* Is encoding necessary? */
3775 int is_unique, /* Del others of this type? */
3776 unsigned int flags /* Internal save flags */
3781 struct ctdlroom qrbuf;
3782 char roomname[ROOMNAMELEN];
3783 struct CtdlMessage *msg;
3785 char *raw_message = NULL;
3786 char *encoded_message = NULL;
3787 off_t raw_length = 0;
3789 if (is_mailbox != NULL) {
3790 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3793 safestrncpy(roomname, req_room, sizeof(roomname));
3796 fp = fopen(tempfilename, "rb");
3798 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
3799 tempfilename, strerror(errno));
3802 fseek(fp, 0L, SEEK_END);
3803 raw_length = ftell(fp);
3805 lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
3807 raw_message = malloc((size_t)raw_length + 2);
3808 fread(raw_message, (size_t)raw_length, 1, fp);
3812 encoded_message = malloc((size_t)
3813 (((raw_length * 134) / 100) + 4096 ) );
3816 encoded_message = malloc((size_t)(raw_length + 4096));
3819 sprintf(encoded_message, "Content-type: %s\n", content_type);
3822 sprintf(&encoded_message[strlen(encoded_message)],
3823 "Content-transfer-encoding: base64\n\n"
3827 sprintf(&encoded_message[strlen(encoded_message)],
3828 "Content-transfer-encoding: 7bit\n\n"
3834 &encoded_message[strlen(encoded_message)],
3840 raw_message[raw_length] = 0;
3842 &encoded_message[strlen(encoded_message)],
3850 lprintf(CTDL_DEBUG, "Allocating\n");
3851 msg = malloc(sizeof(struct CtdlMessage));
3852 memset(msg, 0, sizeof(struct CtdlMessage));
3853 msg->cm_magic = CTDLMESSAGE_MAGIC;
3854 msg->cm_anon_type = MES_NORMAL;
3855 msg->cm_format_type = 4;
3856 msg->cm_fields['A'] = strdup(CC->user.fullname);
3857 msg->cm_fields['O'] = strdup(req_room);
3858 msg->cm_fields['N'] = strdup(config.c_nodename);
3859 msg->cm_fields['H'] = strdup(config.c_humannode);
3860 msg->cm_flags = flags;
3862 msg->cm_fields['M'] = encoded_message;
3864 /* Create the requested room if we have to. */
3865 if (getroom(&qrbuf, roomname) != 0) {
3866 create_room(roomname,
3867 ( (is_mailbox != NULL) ? 5 : 3 ),
3868 "", 0, 1, 0, VIEW_BBS);
3870 /* If the caller specified this object as unique, delete all
3871 * other objects of this type that are currently in the room.
3874 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
3875 CtdlDeleteMessages(roomname, NULL, 0, content_type, 0)
3878 /* Now write the data */
3879 CtdlSubmitMsg(msg, NULL, roomname);
3880 CtdlFreeMessage(msg);
3888 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
3889 config_msgnum = msgnum;
3893 char *CtdlGetSysConfig(char *sysconfname) {
3894 char hold_rm[ROOMNAMELEN];
3897 struct CtdlMessage *msg;
3900 strcpy(hold_rm, CC->room.QRname);
3901 if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
3902 getroom(&CC->room, hold_rm);
3907 /* We want the last (and probably only) config in this room */
3908 begin_critical_section(S_CONFIG);
3909 config_msgnum = (-1L);
3910 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
3911 CtdlGetSysConfigBackend, NULL);
3912 msgnum = config_msgnum;
3913 end_critical_section(S_CONFIG);
3919 msg = CtdlFetchMessage(msgnum, 1);
3921 conf = strdup(msg->cm_fields['M']);
3922 CtdlFreeMessage(msg);
3929 getroom(&CC->room, hold_rm);
3931 if (conf != NULL) do {
3932 extract_token(buf, conf, 0, '\n', sizeof buf);
3933 strcpy(conf, &conf[strlen(buf)+1]);
3934 } while ( (strlen(conf)>0) && (strlen(buf)>0) );
3939 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
3940 char temp[PATH_MAX];
3943 CtdlMakeTempFileName(temp, sizeof temp);
3945 fp = fopen(temp, "w");
3946 if (fp == NULL) return;
3947 fprintf(fp, "%s", sysconfdata);
3950 /* this handy API function does all the work for us */
3951 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
3957 * Determine whether a given Internet address belongs to the current user
3959 int CtdlIsMe(char *addr, int addr_buf_len)
3961 struct recptypes *recp;
3964 recp = validate_recipients(addr);
3965 if (recp == NULL) return(0);
3967 if (recp->num_local == 0) {
3972 for (i=0; i<recp->num_local; ++i) {
3973 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
3974 if (!strcasecmp(addr, CC->user.fullname)) {
3986 * Citadel protocol command to do the same
3988 void cmd_isme(char *argbuf) {
3991 if (CtdlAccessCheck(ac_logged_in)) return;
3992 extract_token(addr, argbuf, 0, '|', sizeof addr);
3994 if (CtdlIsMe(addr, sizeof addr)) {
3995 cprintf("%d %s\n", CIT_OK, addr);
3998 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);