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;
64 /* This temp file holds the queue of operations for AdjRefCount() */
65 static FILE *arcfp = NULL;
68 * This really belongs in serv_network.c, but I don't know how to export
69 * symbols between modules.
71 struct FilterList *filterlist = NULL;
75 * These are the four-character field headers we use when outputting
76 * messages in Citadel format (as opposed to RFC822 format).
79 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
80 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
81 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
82 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
83 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
84 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
85 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
86 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
114 * This function is self explanatory.
115 * (What can I say, I'm in a weird mood today...)
117 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
121 for (i = 0; i < strlen(name); ++i) {
122 if (name[i] == '@') {
123 while (isspace(name[i - 1]) && i > 0) {
124 strcpy(&name[i - 1], &name[i]);
127 while (isspace(name[i + 1])) {
128 strcpy(&name[i + 1], &name[i + 2]);
136 * Aliasing for network mail.
137 * (Error messages have been commented out, because this is a server.)
139 int alias(char *name)
140 { /* process alias and routing info for mail */
143 char aaa[SIZ], bbb[SIZ];
144 char *ignetcfg = NULL;
145 char *ignetmap = NULL;
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 lprintf(CTDL_INFO, "Mail is being forwarded to %s\n", name);
187 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
188 for (a=0; a<strlen(name); ++a) {
189 if (name[a] == '@') {
190 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
192 lprintf(CTDL_INFO, "Changed to <%s>\n", name);
197 /* determine local or remote type, see citadel.h */
198 at = haschar(name, '@');
199 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
200 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
201 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
203 /* figure out the delivery mode */
204 extract_token(node, name, 1, '@', sizeof node);
206 /* If there are one or more dots in the nodename, we assume that it
207 * is an FQDN and will attempt SMTP delivery to the Internet.
209 if (haschar(node, '.') > 0) {
210 return(MES_INTERNET);
213 /* Otherwise we look in the IGnet maps for a valid Citadel node.
214 * Try directly-connected nodes first...
216 ignetcfg = CtdlGetSysConfig(IGNETCFG);
217 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
218 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
219 extract_token(testnode, buf, 0, '|', sizeof testnode);
220 if (!strcasecmp(node, testnode)) {
228 * Then try nodes that are two or more hops away.
230 ignetmap = CtdlGetSysConfig(IGNETMAP);
231 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
232 extract_token(buf, ignetmap, i, '\n', sizeof buf);
233 extract_token(testnode, buf, 0, '|', sizeof testnode);
234 if (!strcasecmp(node, testnode)) {
241 /* If we get to this point it's an invalid node name */
250 fp = fopen(file_citadel_control, "r");
252 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
253 file_citadel_control,
257 fread((char *) &CitControl, sizeof(struct CitControl), 1, fp);
263 * Back end for the MSGS command: output message number only.
265 void simple_listing(long msgnum, void *userdata)
267 cprintf("%ld\n", msgnum);
273 * Back end for the MSGS command: output header summary.
275 void headers_listing(long msgnum, void *userdata)
277 struct CtdlMessage *msg;
279 msg = CtdlFetchMessage(msgnum, 0);
281 cprintf("%ld|0|||||\n", msgnum);
285 cprintf("%ld|%s|%s|%s|%s|%s|\n",
287 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
288 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
289 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
290 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
291 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
293 CtdlFreeMessage(msg);
298 /* Determine if a given message matches the fields in a message template.
299 * Return 0 for a successful match.
301 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
304 /* If there aren't any fields in the template, all messages will
307 if (template == NULL) return(0);
309 /* Null messages are bogus. */
310 if (msg == NULL) return(1);
312 for (i='A'; i<='Z'; ++i) {
313 if (template->cm_fields[i] != NULL) {
314 if (msg->cm_fields[i] == NULL) {
317 if (strcasecmp(msg->cm_fields[i],
318 template->cm_fields[i])) return 1;
322 /* All compares succeeded: we have a match! */
329 * Retrieve the "seen" message list for the current room.
331 void CtdlGetSeen(char *buf, int which_set) {
334 /* Learn about the user and room in question */
335 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
337 if (which_set == ctdlsetseen_seen)
338 safestrncpy(buf, vbuf.v_seen, SIZ);
339 if (which_set == ctdlsetseen_answered)
340 safestrncpy(buf, vbuf.v_answered, SIZ);
346 * Manipulate the "seen msgs" string (or other message set strings)
348 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
349 int target_setting, int which_set,
350 struct ctdluser *which_user, struct ctdlroom *which_room) {
351 struct cdbdata *cdbfr;
363 char *is_set; /* actually an array of booleans */
366 char setstr[SIZ], lostr[SIZ], histr[SIZ];
369 /* Don't bother doing *anything* if we were passed a list of zero messages */
370 if (num_target_msgnums < 1) {
374 lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
375 num_target_msgnums, target_msgnums[0],
376 target_setting, which_set);
378 /* Learn about the user and room in question */
379 CtdlGetRelationship(&vbuf,
380 ((which_user != NULL) ? which_user : &CC->user),
381 ((which_room != NULL) ? which_room : &CC->room)
384 /* Load the message list */
385 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
387 msglist = (long *) cdbfr->ptr;
388 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
389 num_msgs = cdbfr->len / sizeof(long);
392 return; /* No messages at all? No further action. */
395 is_set = malloc(num_msgs * sizeof(char));
396 memset(is_set, 0, (num_msgs * sizeof(char)) );
398 /* Decide which message set we're manipulating */
400 case ctdlsetseen_seen:
401 safestrncpy(vset, vbuf.v_seen, sizeof vset);
403 case ctdlsetseen_answered:
404 safestrncpy(vset, vbuf.v_answered, sizeof vset);
408 /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
410 /* Translate the existing sequence set into an array of booleans */
411 num_sets = num_tokens(vset, ',');
412 for (s=0; s<num_sets; ++s) {
413 extract_token(setstr, vset, s, ',', sizeof setstr);
415 extract_token(lostr, setstr, 0, ':', sizeof lostr);
416 if (num_tokens(setstr, ':') >= 2) {
417 extract_token(histr, setstr, 1, ':', sizeof histr);
418 if (!strcmp(histr, "*")) {
419 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
423 strcpy(histr, lostr);
428 for (i = 0; i < num_msgs; ++i) {
429 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
435 /* Now translate the array of booleans back into a sequence set */
440 for (i=0; i<num_msgs; ++i) {
442 is_seen = is_set[i]; /* Default to existing setting */
444 for (k=0; k<num_target_msgnums; ++k) {
445 if (msglist[i] == target_msgnums[k]) {
446 is_seen = target_setting;
451 if (lo < 0L) lo = msglist[i];
455 if ( ((is_seen == 0) && (was_seen == 1))
456 || ((is_seen == 1) && (i == num_msgs-1)) ) {
458 /* begin trim-o-matic code */
461 while ( (strlen(vset) + 20) > sizeof vset) {
462 remove_token(vset, 0, ',');
464 if (j--) break; /* loop no more than 9 times */
466 if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
470 snprintf(lostr, sizeof lostr,
471 "1:%ld,%s", t, vset);
472 safestrncpy(vset, lostr, sizeof vset);
474 /* end trim-o-matic code */
482 snprintf(&vset[tmp], (sizeof vset) - tmp,
486 snprintf(&vset[tmp], (sizeof vset) - tmp,
495 /* Decide which message set we're manipulating */
497 case ctdlsetseen_seen:
498 safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
500 case ctdlsetseen_answered:
501 safestrncpy(vbuf.v_answered, vset,
502 sizeof vbuf.v_answered);
507 /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
509 CtdlSetRelationship(&vbuf,
510 ((which_user != NULL) ? which_user : &CC->user),
511 ((which_room != NULL) ? which_room : &CC->room)
517 * API function to perform an operation for each qualifying message in the
518 * current room. (Returns the number of messages processed.)
520 int CtdlForEachMessage(int mode, long ref, char *search_string,
522 struct CtdlMessage *compare,
523 void (*CallBack) (long, void *),
529 struct cdbdata *cdbfr;
530 long *msglist = NULL;
532 int num_processed = 0;
535 struct CtdlMessage *msg;
538 int printed_lastold = 0;
539 int num_search_msgs = 0;
540 long *search_msgs = NULL;
542 /* Learn about the user and room in question */
544 getuser(&CC->user, CC->curr_user);
545 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
547 /* Load the message list */
548 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
550 msglist = (long *) cdbfr->ptr;
551 cdbfr->ptr = NULL; /* CtdlForEachMessage() now owns this memory */
552 num_msgs = cdbfr->len / sizeof(long);
555 return 0; /* No messages at all? No further action. */
560 * Now begin the traversal.
562 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
564 /* If the caller is looking for a specific MIME type, filter
565 * out all messages which are not of the type requested.
567 if (content_type != NULL) if (strlen(content_type) > 0) {
569 /* This call to GetMetaData() sits inside this loop
570 * so that we only do the extra database read per msg
571 * if we need to. Doing the extra read all the time
572 * really kills the server. If we ever need to use
573 * metadata for another search criterion, we need to
574 * move the read somewhere else -- but still be smart
575 * enough to only do the read if the caller has
576 * specified something that will need it.
578 GetMetaData(&smi, msglist[a]);
580 if (strcasecmp(smi.meta_content_type, content_type)) {
586 num_msgs = sort_msglist(msglist, num_msgs);
588 /* If a template was supplied, filter out the messages which
589 * don't match. (This could induce some delays!)
592 if (compare != NULL) {
593 for (a = 0; a < num_msgs; ++a) {
594 msg = CtdlFetchMessage(msglist[a], 1);
596 if (CtdlMsgCmp(msg, compare)) {
599 CtdlFreeMessage(msg);
605 /* If a search string was specified, get a message list from
606 * the full text index and remove messages which aren't on both
610 * Since the lists are sorted and strictly ascending, and the
611 * output list is guaranteed to be shorter than or equal to the
612 * input list, we overwrite the bottom of the input list. This
613 * eliminates the need to memmove big chunks of the list over and
616 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
617 ft_search(&num_search_msgs, &search_msgs, search_string);
618 if (num_search_msgs > 0) {
622 orig_num_msgs = num_msgs;
624 for (i=0; i<orig_num_msgs; ++i) {
625 for (j=0; j<num_search_msgs; ++j) {
626 if (msglist[i] == search_msgs[j]) {
627 msglist[num_msgs++] = msglist[i];
633 num_msgs = 0; /* No messages qualify */
635 if (search_msgs != NULL) free(search_msgs);
637 /* Now that we've purged messages which don't contain the search
638 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
645 * Now iterate through the message list, according to the
646 * criteria supplied by the caller.
649 for (a = 0; a < num_msgs; ++a) {
650 thismsg = msglist[a];
651 if (mode == MSGS_ALL) {
655 is_seen = is_msg_in_sequence_set(
656 vbuf.v_seen, thismsg);
657 if (is_seen) lastold = thismsg;
663 || ((mode == MSGS_OLD) && (is_seen))
664 || ((mode == MSGS_NEW) && (!is_seen))
665 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
666 || ((mode == MSGS_FIRST) && (a < ref))
667 || ((mode == MSGS_GT) && (thismsg > ref))
668 || ((mode == MSGS_EQ) && (thismsg == ref))
671 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
673 CallBack(lastold, userdata);
677 if (CallBack) CallBack(thismsg, userdata);
681 free(msglist); /* Clean up */
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 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
746 extract_token(tfield, buf, 0, '|', sizeof tfield);
747 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
748 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
749 if (!strcasecmp(tfield, msgkeys[i])) {
750 template->cm_fields[i] =
758 cprintf("%d \n", LISTING_FOLLOWS);
761 CtdlForEachMessage(mode,
762 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
763 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
766 (with_headers ? headers_listing : simple_listing),
769 if (template != NULL) CtdlFreeMessage(template);
777 * help_subst() - support routine for help file viewer
779 void help_subst(char *strbuf, char *source, char *dest)
784 while (p = pattern2(strbuf, source), (p >= 0)) {
785 strcpy(workbuf, &strbuf[p + strlen(source)]);
786 strcpy(&strbuf[p], dest);
787 strcat(strbuf, workbuf);
792 void do_help_subst(char *buffer)
796 help_subst(buffer, "^nodename", config.c_nodename);
797 help_subst(buffer, "^humannode", config.c_humannode);
798 help_subst(buffer, "^fqdn", config.c_fqdn);
799 help_subst(buffer, "^username", CC->user.fullname);
800 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
801 help_subst(buffer, "^usernum", buf2);
802 help_subst(buffer, "^sysadm", config.c_sysadm);
803 help_subst(buffer, "^variantname", CITADEL);
804 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
805 help_subst(buffer, "^maxsessions", buf2);
806 help_subst(buffer, "^bbsdir", ctdl_bbsbase_dir);
812 * memfmout() - Citadel text formatter and paginator.
813 * Although the original purpose of this routine was to format
814 * text to the reader's screen width, all we're really using it
815 * for here is to format text out to 80 columns before sending it
816 * to the client. The client software may reformat it again.
819 char *mptr, /* where are we going to get our text from? */
820 char subst, /* nonzero if we should do substitutions */
821 char *nl) /* string to terminate lines with */
829 static int width = 80;
834 c = 1; /* c is the current pos */
838 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
840 buffer[strlen(buffer) + 1] = 0;
841 buffer[strlen(buffer)] = ch;
844 if (buffer[0] == '^')
845 do_help_subst(buffer);
847 buffer[strlen(buffer) + 1] = 0;
849 strcpy(buffer, &buffer[1]);
857 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
860 if (((old == 13) || (old == 10)) && (isspace(real))) {
865 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
866 cprintf("%s%s", nl, aaa);
875 if ((strlen(aaa) + c) > (width - 5)) {
884 if ((ch == 13) || (ch == 10)) {
885 cprintf("%s%s", aaa, nl);
892 cprintf("%s%s", aaa, nl);
898 * Callback function for mime parser that simply lists the part
900 void list_this_part(char *name, char *filename, char *partnum, char *disp,
901 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
906 ma = (struct ma_info *)cbuserdata;
907 if (ma->is_ma == 0) {
908 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
909 name, filename, partnum, disp, cbtype, (long)length);
914 * Callback function for multipart prefix
916 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
917 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
922 ma = (struct ma_info *)cbuserdata;
923 if (!strcasecmp(cbtype, "multipart/alternative")) {
927 if (ma->is_ma == 0) {
928 cprintf("pref=%s|%s\n", partnum, cbtype);
933 * Callback function for multipart sufffix
935 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
936 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
941 ma = (struct ma_info *)cbuserdata;
942 if (ma->is_ma == 0) {
943 cprintf("suff=%s|%s\n", partnum, cbtype);
945 if (!strcasecmp(cbtype, "multipart/alternative")) {
952 * Callback function for mime parser that opens a section for downloading
954 void mime_download(char *name, char *filename, char *partnum, char *disp,
955 void *content, char *cbtype, char *cbcharset, size_t length,
956 char *encoding, void *cbuserdata)
959 /* Silently go away if there's already a download open... */
960 if (CC->download_fp != NULL)
963 /* ...or if this is not the desired section */
964 if (strcasecmp(CC->download_desired_section, partnum))
967 CC->download_fp = tmpfile();
968 if (CC->download_fp == NULL)
971 fwrite(content, length, 1, CC->download_fp);
972 fflush(CC->download_fp);
973 rewind(CC->download_fp);
975 OpenCmdResult(filename, cbtype);
981 * Callback function for mime parser that outputs a section all at once
983 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
984 void *content, char *cbtype, char *cbcharset, size_t length,
985 char *encoding, void *cbuserdata)
987 int *found_it = (int *)cbuserdata;
989 /* ...or if this is not the desired section */
990 if (strcasecmp(CC->download_desired_section, partnum))
995 cprintf("%d %d\n", BINARY_FOLLOWS, length);
996 client_write(content, length);
1002 * Load a message from disk into memory.
1003 * This is used by CtdlOutputMsg() and other fetch functions.
1005 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1006 * using the CtdlMessageFree() function.
1008 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1010 struct cdbdata *dmsgtext;
1011 struct CtdlMessage *ret = NULL;
1015 cit_uint8_t field_header;
1017 lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1019 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1020 if (dmsgtext == NULL) {
1023 mptr = dmsgtext->ptr;
1024 upper_bound = mptr + dmsgtext->len;
1026 /* Parse the three bytes that begin EVERY message on disk.
1027 * The first is always 0xFF, the on-disk magic number.
1028 * The second is the anonymous/public type byte.
1029 * The third is the format type byte (vari, fixed, or MIME).
1034 "Message %ld appears to be corrupted.\n",
1039 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1040 memset(ret, 0, sizeof(struct CtdlMessage));
1042 ret->cm_magic = CTDLMESSAGE_MAGIC;
1043 ret->cm_anon_type = *mptr++; /* Anon type byte */
1044 ret->cm_format_type = *mptr++; /* Format type byte */
1047 * The rest is zero or more arbitrary fields. Load them in.
1048 * We're done when we encounter either a zero-length field or
1049 * have just processed the 'M' (message text) field.
1052 if (mptr >= upper_bound) {
1055 field_header = *mptr++;
1056 ret->cm_fields[field_header] = strdup(mptr);
1058 while (*mptr++ != 0); /* advance to next field */
1060 } while ((mptr < upper_bound) && (field_header != 'M'));
1064 /* Always make sure there's something in the msg text field. If
1065 * it's NULL, the message text is most likely stored separately,
1066 * so go ahead and fetch that. Failing that, just set a dummy
1067 * body so other code doesn't barf.
1069 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1070 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1071 if (dmsgtext != NULL) {
1072 ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1076 if (ret->cm_fields['M'] == NULL) {
1077 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1080 /* Perform "before read" hooks (aborting if any return nonzero) */
1081 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1082 CtdlFreeMessage(ret);
1091 * Returns 1 if the supplied pointer points to a valid Citadel message.
1092 * If the pointer is NULL or the magic number check fails, returns 0.
1094 int is_valid_message(struct CtdlMessage *msg) {
1097 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1098 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1106 * 'Destructor' for struct CtdlMessage
1108 void CtdlFreeMessage(struct CtdlMessage *msg)
1112 if (is_valid_message(msg) == 0) return;
1114 for (i = 0; i < 256; ++i)
1115 if (msg->cm_fields[i] != NULL) {
1116 free(msg->cm_fields[i]);
1119 msg->cm_magic = 0; /* just in case */
1125 * Pre callback function for multipart/alternative
1127 * NOTE: this differs from the standard behavior for a reason. Normally when
1128 * displaying multipart/alternative you want to show the _last_ usable
1129 * format in the message. Here we show the _first_ one, because it's
1130 * usually text/plain. Since this set of functions is designed for text
1131 * output to non-MIME-aware clients, this is the desired behavior.
1134 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1135 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1140 ma = (struct ma_info *)cbuserdata;
1141 lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1142 if (!strcasecmp(cbtype, "multipart/alternative")) {
1146 if (!strcasecmp(cbtype, "message/rfc822")) {
1152 * Post callback function for multipart/alternative
1154 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1155 void *content, char *cbtype, char *cbcharset, size_t length,
1156 char *encoding, void *cbuserdata)
1160 ma = (struct ma_info *)cbuserdata;
1161 lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1162 if (!strcasecmp(cbtype, "multipart/alternative")) {
1166 if (!strcasecmp(cbtype, "message/rfc822")) {
1172 * Inline callback function for mime parser that wants to display text
1174 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1175 void *content, char *cbtype, char *cbcharset, size_t length,
1176 char *encoding, void *cbuserdata)
1183 ma = (struct ma_info *)cbuserdata;
1186 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1187 partnum, filename, cbtype, (long)length);
1190 * If we're in the middle of a multipart/alternative scope and
1191 * we've already printed another section, skip this one.
1193 if ( (ma->is_ma) && (ma->did_print) ) {
1194 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1200 if ( (!strcasecmp(cbtype, "text/plain"))
1201 || (strlen(cbtype)==0) ) {
1204 client_write(wptr, length);
1205 if (wptr[length-1] != '\n') {
1212 if (!strcasecmp(cbtype, "text/html")) {
1213 ptr = html_to_ascii(content, length, 80, 0);
1215 client_write(ptr, wlen);
1216 if (ptr[wlen-1] != '\n') {
1223 if (ma->use_fo_hooks) {
1224 if (PerformFixedOutputHooks(cbtype, content, length)) {
1225 /* above function returns nonzero if it handled the part */
1230 if (strncasecmp(cbtype, "multipart/", 10)) {
1231 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1232 partnum, filename, cbtype, (long)length);
1238 * The client is elegant and sophisticated and wants to be choosy about
1239 * MIME content types, so figure out which multipart/alternative part
1240 * we're going to send.
1242 * We use a system of weights. When we find a part that matches one of the
1243 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1244 * and then set ma->chosen_pref to that MIME type's position in our preference
1245 * list. If we then hit another match, we only replace the first match if
1246 * the preference value is lower.
1248 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1249 void *content, char *cbtype, char *cbcharset, size_t length,
1250 char *encoding, void *cbuserdata)
1256 ma = (struct ma_info *)cbuserdata;
1258 if (ma->is_ma > 0) {
1259 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1260 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1261 lprintf(CTDL_DEBUG, "Is <%s> == <%s> ??\n", buf, cbtype);
1262 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1263 if (i < ma->chosen_pref) {
1264 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1265 ma->chosen_pref = i;
1273 * Now that we've chosen our preferred part, output it.
1275 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1276 void *content, char *cbtype, char *cbcharset, size_t length,
1277 char *encoding, void *cbuserdata)
1281 int add_newline = 0;
1285 ma = (struct ma_info *)cbuserdata;
1287 /* This is not the MIME part you're looking for... */
1288 if (strcasecmp(partnum, ma->chosen_part)) return;
1290 /* If the content-type of this part is in our preferred formats
1291 * list, we can simply output it verbatim.
1293 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1294 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1295 if (!strcasecmp(buf, cbtype)) {
1296 /* Yeah! Go! W00t!! */
1298 text_content = (char *)content;
1299 if (text_content[length-1] != '\n') {
1303 cprintf("Content-type: %s", cbtype);
1304 if (strlen(cbcharset) > 0) {
1305 cprintf("; charset=%s", cbcharset);
1307 cprintf("\nContent-length: %d\n",
1308 (int)(length + add_newline) );
1309 if (strlen(encoding) > 0) {
1310 cprintf("Content-transfer-encoding: %s\n", encoding);
1313 cprintf("Content-transfer-encoding: 7bit\n");
1316 client_write(content, length);
1317 if (add_newline) cprintf("\n");
1322 /* No translations required or possible: output as text/plain */
1323 cprintf("Content-type: text/plain\n\n");
1324 fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1325 length, encoding, cbuserdata);
1330 char desired_section[64];
1337 * Callback function for
1339 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1340 void *content, char *cbtype, char *cbcharset, size_t length,
1341 char *encoding, void *cbuserdata)
1343 struct encapmsg *encap;
1345 encap = (struct encapmsg *)cbuserdata;
1347 /* Only proceed if this is the desired section... */
1348 if (!strcasecmp(encap->desired_section, partnum)) {
1349 encap->msglen = length;
1350 encap->msg = malloc(length + 2);
1351 memcpy(encap->msg, content, length);
1361 * Get a message off disk. (returns om_* values found in msgbase.h)
1364 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1365 int mode, /* how would you like that message? */
1366 int headers_only, /* eschew the message body? */
1367 int do_proto, /* do Citadel protocol responses? */
1368 int crlf, /* Use CRLF newlines instead of LF? */
1369 char *section /* NULL or a message/rfc822 section */
1371 struct CtdlMessage *TheMessage = NULL;
1372 int retcode = om_no_such_msg;
1373 struct encapmsg encap;
1375 lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n",
1377 (section ? section : "<>")
1380 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1381 if (do_proto) cprintf("%d Not logged in.\n",
1382 ERROR + NOT_LOGGED_IN);
1383 return(om_not_logged_in);
1386 /* FIXME: check message id against msglist for this room */
1389 * Fetch the message from disk. If we're in any sort of headers
1390 * only mode, request that we don't even bother loading the body
1393 if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1394 TheMessage = CtdlFetchMessage(msg_num, 0);
1397 TheMessage = CtdlFetchMessage(msg_num, 1);
1400 if (TheMessage == NULL) {
1401 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1402 ERROR + MESSAGE_NOT_FOUND, msg_num);
1403 return(om_no_such_msg);
1406 /* Here is the weird form of this command, to process only an
1407 * encapsulated message/rfc822 section.
1409 if (section) if (strlen(section)>0) if (strcmp(section, "0")) {
1410 memset(&encap, 0, sizeof encap);
1411 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1412 mime_parser(TheMessage->cm_fields['M'],
1414 *extract_encapsulated_message,
1415 NULL, NULL, (void *)&encap, 0
1417 CtdlFreeMessage(TheMessage);
1421 encap.msg[encap.msglen] = 0;
1422 TheMessage = convert_internet_message(encap.msg);
1423 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1425 /* Now we let it fall through to the bottom of this
1426 * function, because TheMessage now contains the
1427 * encapsulated message instead of the top-level
1428 * message. Isn't that neat?
1433 if (do_proto) cprintf("%d msg %ld has no part %s\n",
1434 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1435 retcode = om_no_such_msg;
1440 /* Ok, output the message now */
1441 retcode = CtdlOutputPreLoadedMsg(
1443 headers_only, do_proto, crlf);
1444 CtdlFreeMessage(TheMessage);
1451 * Get a message off disk. (returns om_* values found in msgbase.h)
1454 int CtdlOutputPreLoadedMsg(
1455 struct CtdlMessage *TheMessage,
1456 int mode, /* how would you like that message? */
1457 int headers_only, /* eschew the message body? */
1458 int do_proto, /* do Citadel protocol responses? */
1459 int crlf /* Use CRLF newlines instead of LF? */
1465 char display_name[256];
1467 char *nl; /* newline string */
1469 int subject_found = 0;
1472 /* Buffers needed for RFC822 translation. These are all filled
1473 * using functions that are bounds-checked, and therefore we can
1474 * make them substantially smaller than SIZ.
1482 char datestamp[100];
1484 lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1485 ((TheMessage == NULL) ? "NULL" : "not null"),
1486 mode, headers_only, do_proto, crlf);
1488 strcpy(mid, "unknown");
1489 nl = (crlf ? "\r\n" : "\n");
1491 if (!is_valid_message(TheMessage)) {
1493 "ERROR: invalid preloaded message for output\n");
1494 return(om_no_such_msg);
1497 /* Are we downloading a MIME component? */
1498 if (mode == MT_DOWNLOAD) {
1499 if (TheMessage->cm_format_type != FMT_RFC822) {
1501 cprintf("%d This is not a MIME message.\n",
1502 ERROR + ILLEGAL_VALUE);
1503 } else if (CC->download_fp != NULL) {
1504 if (do_proto) cprintf(
1505 "%d You already have a download open.\n",
1506 ERROR + RESOURCE_BUSY);
1508 /* Parse the message text component */
1509 mptr = TheMessage->cm_fields['M'];
1510 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1511 /* If there's no file open by this time, the requested
1512 * section wasn't found, so print an error
1514 if (CC->download_fp == NULL) {
1515 if (do_proto) cprintf(
1516 "%d Section %s not found.\n",
1517 ERROR + FILE_NOT_FOUND,
1518 CC->download_desired_section);
1521 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1524 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
1525 * in a single server operation instead of opening a download file.
1527 if (mode == MT_SPEW_SECTION) {
1528 if (TheMessage->cm_format_type != FMT_RFC822) {
1530 cprintf("%d This is not a MIME message.\n",
1531 ERROR + ILLEGAL_VALUE);
1533 /* Parse the message text component */
1536 mptr = TheMessage->cm_fields['M'];
1537 mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
1538 /* If section wasn't found, print an error
1541 if (do_proto) cprintf(
1542 "%d Section %s not found.\n",
1543 ERROR + FILE_NOT_FOUND,
1544 CC->download_desired_section);
1547 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1550 /* now for the user-mode message reading loops */
1551 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1553 /* Does the caller want to skip the headers? */
1554 if (headers_only == HEADERS_NONE) goto START_TEXT;
1556 /* Tell the client which format type we're using. */
1557 if ( (mode == MT_CITADEL) && (do_proto) ) {
1558 cprintf("type=%d\n", TheMessage->cm_format_type);
1561 /* nhdr=yes means that we're only displaying headers, no body */
1562 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1563 && (mode == MT_CITADEL)
1566 cprintf("nhdr=yes\n");
1569 /* begin header processing loop for Citadel message format */
1571 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1573 safestrncpy(display_name, "<unknown>", sizeof display_name);
1574 if (TheMessage->cm_fields['A']) {
1575 strcpy(buf, TheMessage->cm_fields['A']);
1576 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1577 safestrncpy(display_name, "****", sizeof display_name);
1579 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1580 safestrncpy(display_name, "anonymous", sizeof display_name);
1583 safestrncpy(display_name, buf, sizeof display_name);
1585 if ((is_room_aide())
1586 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1587 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1588 size_t tmp = strlen(display_name);
1589 snprintf(&display_name[tmp],
1590 sizeof display_name - tmp,
1595 /* Don't show Internet address for users on the
1596 * local Citadel network.
1599 if (TheMessage->cm_fields['N'] != NULL)
1600 if (strlen(TheMessage->cm_fields['N']) > 0)
1601 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1605 /* Now spew the header fields in the order we like them. */
1606 safestrncpy(allkeys, FORDER, sizeof allkeys);
1607 for (i=0; i<strlen(allkeys); ++i) {
1608 k = (int) allkeys[i];
1610 if ( (TheMessage->cm_fields[k] != NULL)
1611 && (msgkeys[k] != NULL) ) {
1613 if (do_proto) cprintf("%s=%s\n",
1617 else if ((k == 'F') && (suppress_f)) {
1620 /* Masquerade display name if needed */
1622 if (do_proto) cprintf("%s=%s\n",
1624 TheMessage->cm_fields[k]
1633 /* begin header processing loop for RFC822 transfer format */
1638 strcpy(snode, NODENAME);
1639 strcpy(lnode, HUMANNODE);
1640 if (mode == MT_RFC822) {
1641 for (i = 0; i < 256; ++i) {
1642 if (TheMessage->cm_fields[i]) {
1643 mptr = TheMessage->cm_fields[i];
1646 safestrncpy(luser, mptr, sizeof luser);
1647 safestrncpy(suser, mptr, sizeof suser);
1649 else if (i == 'Y') {
1650 cprintf("CC: %s%s", mptr, nl);
1652 else if (i == 'P') {
1653 cprintf("Return-Path: %s%s", mptr, nl);
1655 else if (i == 'V') {
1656 cprintf("Envelope-To: %s%s", mptr, nl);
1658 else if (i == 'U') {
1659 cprintf("Subject: %s%s", mptr, nl);
1663 safestrncpy(mid, mptr, sizeof mid);
1665 safestrncpy(lnode, mptr, sizeof lnode);
1667 safestrncpy(fuser, mptr, sizeof fuser);
1668 /* else if (i == 'O')
1669 cprintf("X-Citadel-Room: %s%s",
1672 safestrncpy(snode, mptr, sizeof snode);
1674 cprintf("To: %s%s", mptr, nl);
1675 else if (i == 'T') {
1676 datestring(datestamp, sizeof datestamp,
1677 atol(mptr), DATESTRING_RFC822);
1678 cprintf("Date: %s%s", datestamp, nl);
1682 if (subject_found == 0) {
1683 cprintf("Subject: (no subject)%s", nl);
1687 for (i=0; i<strlen(suser); ++i) {
1688 suser[i] = tolower(suser[i]);
1689 if (!isalnum(suser[i])) suser[i]='_';
1692 if (mode == MT_RFC822) {
1693 if (!strcasecmp(snode, NODENAME)) {
1694 safestrncpy(snode, FQDN, sizeof snode);
1697 /* Construct a fun message id */
1698 cprintf("Message-ID: <%s", mid);
1699 if (strchr(mid, '@')==NULL) {
1700 cprintf("@%s", snode);
1704 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1705 cprintf("From: \"----\" <x@x.org>%s", nl);
1707 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1708 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1710 else if (strlen(fuser) > 0) {
1711 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1714 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1717 cprintf("Organization: %s%s", lnode, nl);
1719 /* Blank line signifying RFC822 end-of-headers */
1720 if (TheMessage->cm_format_type != FMT_RFC822) {
1725 /* end header processing loop ... at this point, we're in the text */
1727 if (headers_only == HEADERS_FAST) goto DONE;
1728 mptr = TheMessage->cm_fields['M'];
1730 /* Tell the client about the MIME parts in this message */
1731 if (TheMessage->cm_format_type == FMT_RFC822) {
1732 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1733 memset(&ma, 0, sizeof(struct ma_info));
1734 mime_parser(mptr, NULL,
1735 (do_proto ? *list_this_part : NULL),
1736 (do_proto ? *list_this_pref : NULL),
1737 (do_proto ? *list_this_suff : NULL),
1740 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1741 char *start_of_text = NULL;
1742 start_of_text = strstr(mptr, "\n\r\n");
1743 if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1744 if (start_of_text == NULL) start_of_text = mptr;
1746 start_of_text = strstr(start_of_text, "\n");
1748 while (ch=*mptr, ch!=0) {
1752 else switch(headers_only) {
1754 if (mptr >= start_of_text) {
1755 if (ch == 10) cprintf("%s", nl);
1756 else cprintf("%c", ch);
1760 if (mptr < start_of_text) {
1761 if (ch == 10) cprintf("%s", nl);
1762 else cprintf("%c", ch);
1766 if (ch == 10) cprintf("%s", nl);
1767 else cprintf("%c", ch);
1776 if (headers_only == HEADERS_ONLY) {
1780 /* signify start of msg text */
1781 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1782 if (do_proto) cprintf("text\n");
1785 /* If the format type on disk is 1 (fixed-format), then we want
1786 * everything to be output completely literally ... regardless of
1787 * what message transfer format is in use.
1789 if (TheMessage->cm_format_type == FMT_FIXED) {
1790 if (mode == MT_MIME) {
1791 cprintf("Content-type: text/plain\n\n");
1794 while (ch = *mptr++, ch > 0) {
1797 if ((ch == 10) || (strlen(buf) > 250)) {
1798 cprintf("%s%s", buf, nl);
1801 buf[strlen(buf) + 1] = 0;
1802 buf[strlen(buf)] = ch;
1805 if (strlen(buf) > 0)
1806 cprintf("%s%s", buf, nl);
1809 /* If the message on disk is format 0 (Citadel vari-format), we
1810 * output using the formatter at 80 columns. This is the final output
1811 * form if the transfer format is RFC822, but if the transfer format
1812 * is Citadel proprietary, it'll still work, because the indentation
1813 * for new paragraphs is correct and the client will reformat the
1814 * message to the reader's screen width.
1816 if (TheMessage->cm_format_type == FMT_CITADEL) {
1817 if (mode == MT_MIME) {
1818 cprintf("Content-type: text/x-citadel-variformat\n\n");
1820 memfmout(mptr, 0, nl);
1823 /* If the message on disk is format 4 (MIME), we've gotta hand it
1824 * off to the MIME parser. The client has already been told that
1825 * this message is format 1 (fixed format), so the callback function
1826 * we use will display those parts as-is.
1828 if (TheMessage->cm_format_type == FMT_RFC822) {
1829 memset(&ma, 0, sizeof(struct ma_info));
1831 if (mode == MT_MIME) {
1832 ma.use_fo_hooks = 0;
1833 strcpy(ma.chosen_part, "1");
1834 ma.chosen_pref = 9999;
1835 mime_parser(mptr, NULL,
1836 *choose_preferred, *fixed_output_pre,
1837 *fixed_output_post, (void *)&ma, 0);
1838 mime_parser(mptr, NULL,
1839 *output_preferred, NULL, NULL, (void *)&ma, 0);
1842 ma.use_fo_hooks = 1;
1843 mime_parser(mptr, NULL,
1844 *fixed_output, *fixed_output_pre,
1845 *fixed_output_post, (void *)&ma, 0);
1850 DONE: /* now we're done */
1851 if (do_proto) cprintf("000\n");
1858 * display a message (mode 0 - Citadel proprietary)
1860 void cmd_msg0(char *cmdbuf)
1863 int headers_only = HEADERS_ALL;
1865 msgid = extract_long(cmdbuf, 0);
1866 headers_only = extract_int(cmdbuf, 1);
1868 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1874 * display a message (mode 2 - RFC822)
1876 void cmd_msg2(char *cmdbuf)
1879 int headers_only = HEADERS_ALL;
1881 msgid = extract_long(cmdbuf, 0);
1882 headers_only = extract_int(cmdbuf, 1);
1884 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1890 * display a message (mode 3 - IGnet raw format - internal programs only)
1892 void cmd_msg3(char *cmdbuf)
1895 struct CtdlMessage *msg;
1898 if (CC->internal_pgm == 0) {
1899 cprintf("%d This command is for internal programs only.\n",
1900 ERROR + HIGHER_ACCESS_REQUIRED);
1904 msgnum = extract_long(cmdbuf, 0);
1905 msg = CtdlFetchMessage(msgnum, 1);
1907 cprintf("%d Message %ld not found.\n",
1908 ERROR + MESSAGE_NOT_FOUND, msgnum);
1912 serialize_message(&smr, msg);
1913 CtdlFreeMessage(msg);
1916 cprintf("%d Unable to serialize message\n",
1917 ERROR + INTERNAL_ERROR);
1921 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1922 client_write((char *)smr.ser, (int)smr.len);
1929 * Display a message using MIME content types
1931 void cmd_msg4(char *cmdbuf)
1936 msgid = extract_long(cmdbuf, 0);
1937 extract_token(section, cmdbuf, 1, '|', sizeof section);
1938 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1944 * Client tells us its preferred message format(s)
1946 void cmd_msgp(char *cmdbuf)
1948 safestrncpy(CC->preferred_formats, cmdbuf,
1949 sizeof(CC->preferred_formats));
1950 cprintf("%d ok\n", CIT_OK);
1955 * Open a component of a MIME message as a download file
1957 void cmd_opna(char *cmdbuf)
1960 char desired_section[128];
1962 msgid = extract_long(cmdbuf, 0);
1963 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1964 safestrncpy(CC->download_desired_section, desired_section,
1965 sizeof CC->download_desired_section);
1966 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
1971 * Open a component of a MIME message and transmit it all at once
1973 void cmd_dlat(char *cmdbuf)
1976 char desired_section[128];
1978 msgid = extract_long(cmdbuf, 0);
1979 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1980 safestrncpy(CC->download_desired_section, desired_section,
1981 sizeof CC->download_desired_section);
1982 CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL);
1987 * Save one or more message pointers into a specified room
1988 * (Returns 0 for success, nonzero for failure)
1989 * roomname may be NULL to use the current room
1991 * Note that the 'supplied_msg' field may be set to NULL, in which case
1992 * the message will be fetched from disk, by number, if we need to perform
1993 * replication checks. This adds an additional database read, so if the
1994 * caller already has the message in memory then it should be supplied. (Obviously
1995 * this mode of operation only works if we're saving a single message.)
1997 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
1998 int do_repl_check, struct CtdlMessage *supplied_msg)
2001 char hold_rm[ROOMNAMELEN];
2002 struct cdbdata *cdbfr;
2005 long highest_msg = 0L;
2008 struct CtdlMessage *msg = NULL;
2010 long *msgs_to_be_merged = NULL;
2011 int num_msgs_to_be_merged = 0;
2014 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d)\n",
2015 roomname, num_newmsgs, do_repl_check);
2017 strcpy(hold_rm, CC->room.QRname);
2020 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2021 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2022 if (num_newmsgs > 1) supplied_msg = NULL;
2024 /* Now the regular stuff */
2025 if (lgetroom(&CC->room,
2026 ((roomname != NULL) ? roomname : CC->room.QRname) )
2028 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
2029 return(ERROR + ROOM_NOT_FOUND);
2033 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2034 num_msgs_to_be_merged = 0;
2037 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2038 if (cdbfr == NULL) {
2042 msglist = (long *) cdbfr->ptr;
2043 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2044 num_msgs = cdbfr->len / sizeof(long);
2049 /* Create a list of msgid's which were supplied by the caller, but do
2050 * not already exist in the target room. It is absolutely taboo to
2051 * have more than one reference to the same message in a room.
2053 for (i=0; i<num_newmsgs; ++i) {
2055 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2056 if (msglist[j] == newmsgidlist[i]) {
2061 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2065 lprintf(9, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2068 * Now merge the new messages
2070 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2071 if (msglist == NULL) {
2072 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
2074 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2075 num_msgs += num_msgs_to_be_merged;
2077 /* Sort the message list, so all the msgid's are in order */
2078 num_msgs = sort_msglist(msglist, num_msgs);
2080 /* Determine the highest message number */
2081 highest_msg = msglist[num_msgs - 1];
2083 /* Write it back to disk. */
2084 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2085 msglist, (int)(num_msgs * sizeof(long)));
2087 /* Free up the memory we used. */
2090 /* Update the highest-message pointer and unlock the room. */
2091 CC->room.QRhighest = highest_msg;
2092 lputroom(&CC->room);
2094 /* Perform replication checks if necessary */
2095 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2096 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2098 for (i=0; i<num_msgs_to_be_merged; ++i) {
2099 msgid = msgs_to_be_merged[i];
2101 if (supplied_msg != NULL) {
2105 msg = CtdlFetchMessage(msgid, 0);
2109 ReplicationChecks(msg);
2111 /* If the message has an Exclusive ID, index that... */
2112 if (msg->cm_fields['E'] != NULL) {
2113 index_message_by_euid(msg->cm_fields['E'], &CC->room, msgid);
2116 /* Free up the memory we may have allocated */
2117 if (msg != supplied_msg) {
2118 CtdlFreeMessage(msg);
2126 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2129 /* Submit this room for net processing */
2130 network_queue_room(&CC->room, NULL);
2132 #ifdef HAVE_LIBSIEVE
2133 /* If this is someone's inbox, submit the room for sieve processing */
2134 if (!strcasecmp(&CC->room.QRname[11], MAILROOM)) {
2135 sieve_queue_room(&CC->room);
2137 #endif /* HAVE_LIBSIEVE */
2139 /* Go back to the room we were in before we wandered here... */
2140 getroom(&CC->room, hold_rm);
2142 /* Bump the reference count for all messages which were merged */
2143 for (i=0; i<num_msgs_to_be_merged; ++i) {
2144 AdjRefCount(msgs_to_be_merged[i], +1);
2147 /* Free up memory... */
2148 if (msgs_to_be_merged != NULL) {
2149 free(msgs_to_be_merged);
2152 /* Return success. */
2158 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2161 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2162 int do_repl_check, struct CtdlMessage *supplied_msg)
2164 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg);
2171 * Message base operation to save a new message to the message store
2172 * (returns new message number)
2174 * This is the back end for CtdlSubmitMsg() and should not be directly
2175 * called by server-side modules.
2178 long send_message(struct CtdlMessage *msg) {
2186 /* Get a new message number */
2187 newmsgid = get_new_message_number();
2188 snprintf(msgidbuf, sizeof msgidbuf, "%010ld@%s", newmsgid, config.c_fqdn);
2190 /* Generate an ID if we don't have one already */
2191 if (msg->cm_fields['I']==NULL) {
2192 msg->cm_fields['I'] = strdup(msgidbuf);
2195 /* If the message is big, set its body aside for storage elsewhere */
2196 if (msg->cm_fields['M'] != NULL) {
2197 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2199 holdM = msg->cm_fields['M'];
2200 msg->cm_fields['M'] = NULL;
2204 /* Serialize our data structure for storage in the database */
2205 serialize_message(&smr, msg);
2208 msg->cm_fields['M'] = holdM;
2212 cprintf("%d Unable to serialize message\n",
2213 ERROR + INTERNAL_ERROR);
2217 /* Write our little bundle of joy into the message base */
2218 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2219 smr.ser, smr.len) < 0) {
2220 lprintf(CTDL_ERR, "Can't store message\n");
2224 cdb_store(CDB_BIGMSGS,
2234 /* Free the memory we used for the serialized message */
2237 /* Return the *local* message ID to the caller
2238 * (even if we're storing an incoming network message)
2246 * Serialize a struct CtdlMessage into the format used on disk and network.
2248 * This function loads up a "struct ser_ret" (defined in server.h) which
2249 * contains the length of the serialized message and a pointer to the
2250 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2252 void serialize_message(struct ser_ret *ret, /* return values */
2253 struct CtdlMessage *msg) /* unserialized msg */
2255 size_t wlen, fieldlen;
2257 static char *forder = FORDER;
2260 * Check for valid message format
2262 if (is_valid_message(msg) == 0) {
2263 lprintf(CTDL_ERR, "serialize_message() aborting due to invalid message\n");
2270 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2271 ret->len = ret->len +
2272 strlen(msg->cm_fields[(int)forder[i]]) + 2;
2274 ret->ser = malloc(ret->len);
2275 if (ret->ser == NULL) {
2276 lprintf(CTDL_ERR, "serialize_message() malloc(%ld) failed: %s\n",
2277 (long)ret->len, strerror(errno));
2284 ret->ser[1] = msg->cm_anon_type;
2285 ret->ser[2] = msg->cm_format_type;
2288 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2289 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
2290 ret->ser[wlen++] = (char)forder[i];
2291 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
2292 wlen = wlen + fieldlen + 1;
2294 if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2295 (long)ret->len, (long)wlen);
2303 * Check to see if any messages already exist in the current room which
2304 * carry the same Exclusive ID as this one. If any are found, delete them.
2306 void ReplicationChecks(struct CtdlMessage *msg) {
2307 long old_msgnum = (-1L);
2309 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2311 lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2314 /* No exclusive id? Don't do anything. */
2315 if (msg == NULL) return;
2316 if (msg->cm_fields['E'] == NULL) return;
2317 if (strlen(msg->cm_fields['E']) == 0) return;
2318 /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2319 msg->cm_fields['E'], CC->room.QRname);*/
2321 old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2322 if (old_msgnum > 0L) {
2323 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2324 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "");
2331 * Save a message to disk and submit it into the delivery system.
2333 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2334 struct recptypes *recps, /* recipients (if mail) */
2335 char *force /* force a particular room? */
2337 char submit_filename[128];
2338 char generated_timestamp[32];
2339 char hold_rm[ROOMNAMELEN];
2340 char actual_rm[ROOMNAMELEN];
2341 char force_room[ROOMNAMELEN];
2342 char content_type[SIZ]; /* We have to learn this */
2343 char recipient[SIZ];
2346 struct ctdluser userbuf;
2348 struct MetaData smi;
2349 FILE *network_fp = NULL;
2350 static int seqnum = 1;
2351 struct CtdlMessage *imsg = NULL;
2354 char *hold_R, *hold_D;
2355 char *collected_addresses = NULL;
2356 struct addresses_to_be_filed *aptr = NULL;
2357 char *saved_rfc822_version = NULL;
2358 int qualified_for_journaling = 0;
2360 lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2361 if (is_valid_message(msg) == 0) return(-1); /* self check */
2363 /* If this message has no timestamp, we take the liberty of
2364 * giving it one, right now.
2366 if (msg->cm_fields['T'] == NULL) {
2367 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2368 msg->cm_fields['T'] = strdup(generated_timestamp);
2371 /* If this message has no path, we generate one.
2373 if (msg->cm_fields['P'] == NULL) {
2374 if (msg->cm_fields['A'] != NULL) {
2375 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2376 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
2377 if (isspace(msg->cm_fields['P'][a])) {
2378 msg->cm_fields['P'][a] = ' ';
2383 msg->cm_fields['P'] = strdup("unknown");
2387 if (force == NULL) {
2388 strcpy(force_room, "");
2391 strcpy(force_room, force);
2394 /* Learn about what's inside, because it's what's inside that counts */
2395 if (msg->cm_fields['M'] == NULL) {
2396 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2400 switch (msg->cm_format_type) {
2402 strcpy(content_type, "text/x-citadel-variformat");
2405 strcpy(content_type, "text/plain");
2408 strcpy(content_type, "text/plain");
2409 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type: ");
2411 safestrncpy(content_type, &mptr[14],
2412 sizeof content_type);
2413 for (a = 0; a < strlen(content_type); ++a) {
2414 if ((content_type[a] == ';')
2415 || (content_type[a] == ' ')
2416 || (content_type[a] == 13)
2417 || (content_type[a] == 10)) {
2418 content_type[a] = 0;
2424 /* Goto the correct room */
2425 lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CC->room.QRname : SENTITEMS);
2426 strcpy(hold_rm, CC->room.QRname);
2427 strcpy(actual_rm, CC->room.QRname);
2428 if (recps != NULL) {
2429 strcpy(actual_rm, SENTITEMS);
2432 /* If the user is a twit, move to the twit room for posting */
2434 if (CC->user.axlevel == 2) {
2435 strcpy(hold_rm, actual_rm);
2436 strcpy(actual_rm, config.c_twitroom);
2437 lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2441 /* ...or if this message is destined for Aide> then go there. */
2442 if (strlen(force_room) > 0) {
2443 strcpy(actual_rm, force_room);
2446 lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2447 if (strcasecmp(actual_rm, CC->room.QRname)) {
2448 /* getroom(&CC->room, actual_rm); */
2449 usergoto(actual_rm, 0, 1, NULL, NULL);
2453 * If this message has no O (room) field, generate one.
2455 if (msg->cm_fields['O'] == NULL) {
2456 msg->cm_fields['O'] = strdup(CC->room.QRname);
2459 /* Perform "before save" hooks (aborting if any return nonzero) */
2460 lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2461 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2464 * If this message has an Exclusive ID, and the room is replication
2465 * checking enabled, then do replication checks.
2467 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2468 ReplicationChecks(msg);
2471 /* Save it to disk */
2472 lprintf(CTDL_DEBUG, "Saving to disk\n");
2473 newmsgid = send_message(msg);
2474 if (newmsgid <= 0L) return(-5);
2476 /* Write a supplemental message info record. This doesn't have to
2477 * be a critical section because nobody else knows about this message
2480 lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2481 memset(&smi, 0, sizeof(struct MetaData));
2482 smi.meta_msgnum = newmsgid;
2483 smi.meta_refcount = 0;
2484 safestrncpy(smi.meta_content_type, content_type,
2485 sizeof smi.meta_content_type);
2488 * Measure how big this message will be when rendered as RFC822.
2489 * We do this for two reasons:
2490 * 1. We need the RFC822 length for the new metadata record, so the
2491 * POP and IMAP services don't have to calculate message lengths
2492 * while the user is waiting (multiplied by potentially hundreds
2493 * or thousands of messages).
2494 * 2. If journaling is enabled, we will need an RFC822 version of the
2495 * message to attach to the journalized copy.
2497 if (CC->redirect_buffer != NULL) {
2498 lprintf(CTDL_ALERT, "CC->redirect_buffer is not NULL during message submission!\n");
2501 CC->redirect_buffer = malloc(SIZ);
2502 CC->redirect_len = 0;
2503 CC->redirect_alloc = SIZ;
2504 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2505 smi.meta_rfc822_length = CC->redirect_len;
2506 saved_rfc822_version = CC->redirect_buffer;
2507 CC->redirect_buffer = NULL;
2508 CC->redirect_len = 0;
2509 CC->redirect_alloc = 0;
2513 /* Now figure out where to store the pointers */
2514 lprintf(CTDL_DEBUG, "Storing pointers\n");
2516 /* If this is being done by the networker delivering a private
2517 * message, we want to BYPASS saving the sender's copy (because there
2518 * is no local sender; it would otherwise go to the Trashcan).
2520 if ((!CC->internal_pgm) || (recps == NULL)) {
2521 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2522 lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2523 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2527 /* For internet mail, drop a copy in the outbound queue room */
2529 if (recps->num_internet > 0) {
2530 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2533 /* If other rooms are specified, drop them there too. */
2535 if (recps->num_room > 0)
2536 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2537 extract_token(recipient, recps->recp_room, i,
2538 '|', sizeof recipient);
2539 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2540 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2543 /* Bump this user's messages posted counter. */
2544 lprintf(CTDL_DEBUG, "Updating user\n");
2545 lgetuser(&CC->user, CC->curr_user);
2546 CC->user.posted = CC->user.posted + 1;
2547 lputuser(&CC->user);
2549 /* If this is private, local mail, make a copy in the
2550 * recipient's mailbox and bump the reference count.
2553 if (recps->num_local > 0)
2554 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2555 extract_token(recipient, recps->recp_local, i,
2556 '|', sizeof recipient);
2557 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2559 if (getuser(&userbuf, recipient) == 0) {
2560 MailboxName(actual_rm, sizeof actual_rm,
2561 &userbuf, MAILROOM);
2562 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2563 BumpNewMailCounter(userbuf.usernum);
2566 lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2567 CtdlSaveMsgPointerInRoom(config.c_aideroom,
2572 /* Perform "after save" hooks */
2573 lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2574 PerformMessageHooks(msg, EVT_AFTERSAVE);
2576 /* For IGnet mail, we have to save a new copy into the spooler for
2577 * each recipient, with the R and D fields set to the recipient and
2578 * destination-node. This has two ugly side effects: all other
2579 * recipients end up being unlisted in this recipient's copy of the
2580 * message, and it has to deliver multiple messages to the same
2581 * node. We'll revisit this again in a year or so when everyone has
2582 * a network spool receiver that can handle the new style messages.
2585 if (recps->num_ignet > 0)
2586 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2587 extract_token(recipient, recps->recp_ignet, i,
2588 '|', sizeof recipient);
2590 hold_R = msg->cm_fields['R'];
2591 hold_D = msg->cm_fields['D'];
2592 msg->cm_fields['R'] = malloc(SIZ);
2593 msg->cm_fields['D'] = malloc(128);
2594 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2595 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2597 serialize_message(&smr, msg);
2599 snprintf(submit_filename, sizeof submit_filename,
2600 "%s/netmail.%04lx.%04x.%04x",
2602 (long) getpid(), CC->cs_pid, ++seqnum);
2603 network_fp = fopen(submit_filename, "wb+");
2604 if (network_fp != NULL) {
2605 fwrite(smr.ser, smr.len, 1, network_fp);
2611 free(msg->cm_fields['R']);
2612 free(msg->cm_fields['D']);
2613 msg->cm_fields['R'] = hold_R;
2614 msg->cm_fields['D'] = hold_D;
2617 /* Go back to the room we started from */
2618 lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2619 if (strcasecmp(hold_rm, CC->room.QRname))
2620 /* getroom(&CC->room, hold_rm); */
2621 usergoto(hold_rm, 0, 1, NULL, NULL);
2623 /* For internet mail, generate delivery instructions.
2624 * Yes, this is recursive. Deal with it. Infinite recursion does
2625 * not happen because the delivery instructions message does not
2626 * contain a recipient.
2629 if (recps->num_internet > 0) {
2630 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2631 instr = malloc(SIZ * 2);
2632 snprintf(instr, SIZ * 2,
2633 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2635 SPOOLMIME, newmsgid, (long)time(NULL),
2636 msg->cm_fields['A'], msg->cm_fields['N']
2639 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2640 size_t tmp = strlen(instr);
2641 extract_token(recipient, recps->recp_internet,
2642 i, '|', sizeof recipient);
2643 snprintf(&instr[tmp], SIZ * 2 - tmp,
2644 "remote|%s|0||\n", recipient);
2647 imsg = malloc(sizeof(struct CtdlMessage));
2648 memset(imsg, 0, sizeof(struct CtdlMessage));
2649 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2650 imsg->cm_anon_type = MES_NORMAL;
2651 imsg->cm_format_type = FMT_RFC822;
2652 imsg->cm_fields['A'] = strdup("Citadel");
2653 imsg->cm_fields['J'] = strdup("do not journal");
2654 imsg->cm_fields['M'] = instr;
2655 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2656 CtdlFreeMessage(imsg);
2660 * Any addresses to harvest for someone's address book?
2662 if ( (CC->logged_in) && (recps != NULL) ) {
2663 collected_addresses = harvest_collected_addresses(msg);
2666 if (collected_addresses != NULL) {
2667 begin_critical_section(S_ATBF);
2668 aptr = (struct addresses_to_be_filed *)
2669 malloc(sizeof(struct addresses_to_be_filed));
2671 MailboxName(actual_rm, sizeof actual_rm,
2672 &CC->user, USERCONTACTSROOM);
2673 aptr->roomname = strdup(actual_rm);
2674 aptr->collected_addresses = collected_addresses;
2676 end_critical_section(S_ATBF);
2680 * Determine whether this message qualifies for journaling.
2682 if (msg->cm_fields['J'] != NULL) {
2683 qualified_for_journaling = 0;
2686 if (recps == NULL) {
2687 qualified_for_journaling = config.c_journal_pubmsgs;
2689 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2690 qualified_for_journaling = config.c_journal_email;
2693 qualified_for_journaling = config.c_journal_pubmsgs;
2698 * Do we have to perform journaling? If so, hand off the saved
2699 * RFC822 version will be handed off to the journaler for background
2700 * submit. Otherwise, we have to free the memory ourselves.
2702 if (saved_rfc822_version != NULL) {
2703 if (qualified_for_journaling) {
2704 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2707 free(saved_rfc822_version);
2720 * Convenience function for generating small administrative messages.
2722 void quickie_message(char *from, char *fromaddr, char *to, char *room, char *text,
2723 int format_type, char *subject)
2725 struct CtdlMessage *msg;
2726 struct recptypes *recp = NULL;
2728 msg = malloc(sizeof(struct CtdlMessage));
2729 memset(msg, 0, sizeof(struct CtdlMessage));
2730 msg->cm_magic = CTDLMESSAGE_MAGIC;
2731 msg->cm_anon_type = MES_NORMAL;
2732 msg->cm_format_type = format_type;
2735 msg->cm_fields['A'] = strdup(from);
2737 else if (fromaddr != NULL) {
2738 msg->cm_fields['A'] = strdup(fromaddr);
2739 if (strchr(msg->cm_fields['A'], '@')) {
2740 *strchr(msg->cm_fields['A'], '@') = 0;
2744 msg->cm_fields['A'] = strdup("Citadel");
2747 if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
2748 if (room != NULL) msg->cm_fields['O'] = strdup(room);
2749 msg->cm_fields['N'] = strdup(NODENAME);
2751 msg->cm_fields['R'] = strdup(to);
2752 recp = validate_recipients(to);
2754 if (subject != NULL) {
2755 msg->cm_fields['U'] = strdup(subject);
2757 msg->cm_fields['M'] = strdup(text);
2759 CtdlSubmitMsg(msg, recp, room);
2760 CtdlFreeMessage(msg);
2761 if (recp != NULL) free(recp);
2767 * Back end function used by CtdlMakeMessage() and similar functions
2769 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2770 size_t maxlen, /* maximum message length */
2771 char *exist, /* if non-null, append to it;
2772 exist is ALWAYS freed */
2773 int crlf /* CRLF newlines instead of LF */
2777 size_t message_len = 0;
2778 size_t buffer_len = 0;
2785 if (exist == NULL) {
2792 message_len = strlen(exist);
2793 buffer_len = message_len + 4096;
2794 m = realloc(exist, buffer_len);
2801 /* Do we need to change leading ".." to "." for SMTP escaping? */
2802 if (!strcmp(terminator, ".")) {
2806 /* flush the input if we have nowhere to store it */
2811 /* read in the lines of message text one by one */
2813 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2814 if (!strcmp(buf, terminator)) finished = 1;
2816 strcat(buf, "\r\n");
2822 /* Unescape SMTP-style input of two dots at the beginning of the line */
2824 if (!strncmp(buf, "..", 2)) {
2825 strcpy(buf, &buf[1]);
2829 if ( (!flushing) && (!finished) ) {
2830 /* Measure the line */
2831 linelen = strlen(buf);
2833 /* augment the buffer if we have to */
2834 if ((message_len + linelen) >= buffer_len) {
2835 ptr = realloc(m, (buffer_len * 2) );
2836 if (ptr == NULL) { /* flush if can't allocate */
2839 buffer_len = (buffer_len * 2);
2841 lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2845 /* Add the new line to the buffer. NOTE: this loop must avoid
2846 * using functions like strcat() and strlen() because they
2847 * traverse the entire buffer upon every call, and doing that
2848 * for a multi-megabyte message slows it down beyond usability.
2850 strcpy(&m[message_len], buf);
2851 message_len += linelen;
2854 /* if we've hit the max msg length, flush the rest */
2855 if (message_len >= maxlen) flushing = 1;
2857 } while (!finished);
2865 * Build a binary message to be saved on disk.
2866 * (NOTE: if you supply 'preformatted_text', the buffer you give it
2867 * will become part of the message. This means you are no longer
2868 * responsible for managing that memory -- it will be freed along with
2869 * the rest of the fields when CtdlFreeMessage() is called.)
2872 struct CtdlMessage *CtdlMakeMessage(
2873 struct ctdluser *author, /* author's user structure */
2874 char *recipient, /* NULL if it's not mail */
2875 char *recp_cc, /* NULL if it's not mail */
2876 char *room, /* room where it's going */
2877 int type, /* see MES_ types in header file */
2878 int format_type, /* variformat, plain text, MIME... */
2879 char *fake_name, /* who we're masquerading as */
2880 char *subject, /* Subject (optional) */
2881 char *supplied_euid, /* ...or NULL if this is irrelevant */
2882 char *preformatted_text /* ...or NULL to read text from client */
2884 char dest_node[SIZ];
2886 struct CtdlMessage *msg;
2888 msg = malloc(sizeof(struct CtdlMessage));
2889 memset(msg, 0, sizeof(struct CtdlMessage));
2890 msg->cm_magic = CTDLMESSAGE_MAGIC;
2891 msg->cm_anon_type = type;
2892 msg->cm_format_type = format_type;
2894 /* Don't confuse the poor folks if it's not routed mail. */
2895 strcpy(dest_node, "");
2900 snprintf(buf, sizeof buf, "cit%ld", author->usernum); /* Path */
2901 msg->cm_fields['P'] = strdup(buf);
2903 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
2904 msg->cm_fields['T'] = strdup(buf);
2906 if (fake_name[0]) /* author */
2907 msg->cm_fields['A'] = strdup(fake_name);
2909 msg->cm_fields['A'] = strdup(author->fullname);
2911 if (CC->room.QRflags & QR_MAILBOX) { /* room */
2912 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2915 msg->cm_fields['O'] = strdup(CC->room.QRname);
2918 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
2919 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
2921 if (recipient[0] != 0) {
2922 msg->cm_fields['R'] = strdup(recipient);
2924 if (recp_cc[0] != 0) {
2925 msg->cm_fields['Y'] = strdup(recp_cc);
2927 if (dest_node[0] != 0) {
2928 msg->cm_fields['D'] = strdup(dest_node);
2931 if ( (author == &CC->user) && (strlen(CC->cs_inet_email) > 0) ) {
2932 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2935 if (subject != NULL) {
2937 if (strlen(subject) > 0) {
2938 msg->cm_fields['U'] = strdup(subject);
2942 if (supplied_euid != NULL) {
2943 msg->cm_fields['E'] = strdup(supplied_euid);
2946 if (preformatted_text != NULL) {
2947 msg->cm_fields['M'] = preformatted_text;
2950 msg->cm_fields['M'] = CtdlReadMessageBody("000",
2951 config.c_maxmsglen, NULL, 0);
2959 * Check to see whether we have permission to post a message in the current
2960 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
2961 * returns 0 on success.
2963 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
2965 if (!(CC->logged_in)) {
2966 snprintf(errmsgbuf, n, "Not logged in.");
2967 return (ERROR + NOT_LOGGED_IN);
2970 if ((CC->user.axlevel < 2)
2971 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
2972 snprintf(errmsgbuf, n, "Need to be validated to enter "
2973 "(except in %s> to sysop)", MAILROOM);
2974 return (ERROR + HIGHER_ACCESS_REQUIRED);
2977 if ((CC->user.axlevel < 4)
2978 && (CC->room.QRflags & QR_NETWORK)) {
2979 snprintf(errmsgbuf, n, "Need net privileges to enter here.");
2980 return (ERROR + HIGHER_ACCESS_REQUIRED);
2983 if ((CC->user.axlevel < 6)
2984 && (CC->room.QRflags & QR_READONLY)) {
2985 snprintf(errmsgbuf, n, "Sorry, this is a read-only room.");
2986 return (ERROR + HIGHER_ACCESS_REQUIRED);
2989 strcpy(errmsgbuf, "Ok");
2995 * Check to see if the specified user has Internet mail permission
2996 * (returns nonzero if permission is granted)
2998 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
3000 /* Do not allow twits to send Internet mail */
3001 if (who->axlevel <= 2) return(0);
3003 /* Globally enabled? */
3004 if (config.c_restrict == 0) return(1);
3006 /* User flagged ok? */
3007 if (who->flags & US_INTERNET) return(2);
3009 /* Aide level access? */
3010 if (who->axlevel >= 6) return(3);
3012 /* No mail for you! */
3018 * Validate recipients, count delivery types and errors, and handle aliasing
3019 * FIXME check for dupes!!!!!
3020 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
3021 * were specified, or the number of addresses found invalid.
3022 * caller needs to free the result.
3024 struct recptypes *validate_recipients(char *supplied_recipients) {
3025 struct recptypes *ret;
3026 char recipients[SIZ];
3027 char this_recp[256];
3028 char this_recp_cooked[256];
3034 struct ctdluser tempUS;
3035 struct ctdlroom tempQR;
3039 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
3040 if (ret == NULL) return(NULL);
3041 memset(ret, 0, sizeof(struct recptypes));
3044 ret->num_internet = 0;
3049 if (supplied_recipients == NULL) {
3050 strcpy(recipients, "");
3053 safestrncpy(recipients, supplied_recipients, sizeof recipients);
3056 /* Change all valid separator characters to commas */
3057 for (i=0; i<strlen(recipients); ++i) {
3058 if ((recipients[i] == ';') || (recipients[i] == '|')) {
3059 recipients[i] = ',';
3063 /* Now start extracting recipients... */
3065 while (strlen(recipients) > 0) {
3067 for (i=0; i<=strlen(recipients); ++i) {
3068 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
3069 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
3070 safestrncpy(this_recp, recipients, i+1);
3072 if (recipients[i] == ',') {
3073 strcpy(recipients, &recipients[i+1]);
3076 strcpy(recipients, "");
3083 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
3085 mailtype = alias(this_recp);
3086 mailtype = alias(this_recp);
3087 mailtype = alias(this_recp);
3088 for (j=0; j<=strlen(this_recp); ++j) {
3089 if (this_recp[j]=='_') {
3090 this_recp_cooked[j] = ' ';
3093 this_recp_cooked[j] = this_recp[j];
3099 if (!strcasecmp(this_recp, "sysop")) {
3101 strcpy(this_recp, config.c_aideroom);
3102 if (strlen(ret->recp_room) > 0) {
3103 strcat(ret->recp_room, "|");
3105 strcat(ret->recp_room, this_recp);
3107 else if (getuser(&tempUS, this_recp) == 0) {
3109 strcpy(this_recp, tempUS.fullname);
3110 if (strlen(ret->recp_local) > 0) {
3111 strcat(ret->recp_local, "|");
3113 strcat(ret->recp_local, this_recp);
3115 else if (getuser(&tempUS, this_recp_cooked) == 0) {
3117 strcpy(this_recp, tempUS.fullname);
3118 if (strlen(ret->recp_local) > 0) {
3119 strcat(ret->recp_local, "|");
3121 strcat(ret->recp_local, this_recp);
3123 else if ( (!strncasecmp(this_recp, "room_", 5))
3124 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
3126 if (strlen(ret->recp_room) > 0) {
3127 strcat(ret->recp_room, "|");
3129 strcat(ret->recp_room, &this_recp_cooked[5]);
3137 /* Yes, you're reading this correctly: if the target
3138 * domain points back to the local system or an attached
3139 * Citadel directory, the address is invalid. That's
3140 * because if the address were valid, we would have
3141 * already translated it to a local address by now.
3143 if (IsDirectory(this_recp)) {
3148 ++ret->num_internet;
3149 if (strlen(ret->recp_internet) > 0) {
3150 strcat(ret->recp_internet, "|");
3152 strcat(ret->recp_internet, this_recp);
3157 if (strlen(ret->recp_ignet) > 0) {
3158 strcat(ret->recp_ignet, "|");
3160 strcat(ret->recp_ignet, this_recp);
3168 if (strlen(ret->errormsg) == 0) {
3169 snprintf(append, sizeof append,
3170 "Invalid recipient: %s",
3174 snprintf(append, sizeof append,
3177 if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
3178 strcat(ret->errormsg, append);
3182 if (strlen(ret->display_recp) == 0) {
3183 strcpy(append, this_recp);
3186 snprintf(append, sizeof append, ", %s",
3189 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
3190 strcat(ret->display_recp, append);
3195 if ((ret->num_local + ret->num_internet + ret->num_ignet +
3196 ret->num_room + ret->num_error) == 0) {
3197 ret->num_error = (-1);
3198 strcpy(ret->errormsg, "No recipients specified.");
3201 lprintf(CTDL_DEBUG, "validate_recipients()\n");
3202 lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
3203 lprintf(CTDL_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
3204 lprintf(CTDL_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
3205 lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
3206 lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
3214 * message entry - mode 0 (normal)
3216 void cmd_ent0(char *entargs)
3222 char supplied_euid[128];
3223 char masquerade_as[SIZ];
3225 int format_type = 0;
3226 char newusername[SIZ];
3227 struct CtdlMessage *msg;
3231 struct recptypes *valid = NULL;
3232 struct recptypes *valid_to = NULL;
3233 struct recptypes *valid_cc = NULL;
3234 struct recptypes *valid_bcc = NULL;
3241 post = extract_int(entargs, 0);
3242 extract_token(recp, entargs, 1, '|', sizeof recp);
3243 anon_flag = extract_int(entargs, 2);
3244 format_type = extract_int(entargs, 3);
3245 extract_token(subject, entargs, 4, '|', sizeof subject);
3246 do_confirm = extract_int(entargs, 6);
3247 extract_token(cc, entargs, 7, '|', sizeof cc);
3248 extract_token(bcc, entargs, 8, '|', sizeof bcc);
3249 switch(CC->room.QRdefaultview) {
3252 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3255 supplied_euid[0] = 0;
3259 /* first check to make sure the request is valid. */
3261 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3263 cprintf("%d %s\n", err, errmsg);
3267 /* Check some other permission type things. */
3270 if (CC->user.axlevel < 6) {
3271 cprintf("%d You don't have permission to masquerade.\n",
3272 ERROR + HIGHER_ACCESS_REQUIRED);
3275 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3276 memset(CC->fake_postname, 0, sizeof(CC->fake_postname) );
3277 safestrncpy(CC->fake_postname, newusername,
3278 sizeof(CC->fake_postname) );
3279 cprintf("%d ok\n", CIT_OK);
3282 CC->cs_flags |= CS_POSTING;
3284 /* In the Mail> room we have to behave a little differently --
3285 * make sure the user has specified at least one recipient. Then
3286 * validate the recipient(s).
3288 if ( (CC->room.QRflags & QR_MAILBOX)
3289 && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) ) {
3291 if (CC->user.axlevel < 2) {
3292 strcpy(recp, "sysop");
3297 valid_to = validate_recipients(recp);
3298 if (valid_to->num_error > 0) {
3299 cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3304 valid_cc = validate_recipients(cc);
3305 if (valid_cc->num_error > 0) {
3306 cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3312 valid_bcc = validate_recipients(bcc);
3313 if (valid_bcc->num_error > 0) {
3314 cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3321 /* Recipient required, but none were specified */
3322 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3326 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3330 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3331 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3332 cprintf("%d You do not have permission "
3333 "to send Internet mail.\n",
3334 ERROR + HIGHER_ACCESS_REQUIRED);
3342 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)
3343 && (CC->user.axlevel < 4) ) {
3344 cprintf("%d Higher access required for network mail.\n",
3345 ERROR + HIGHER_ACCESS_REQUIRED);
3352 if ((RESTRICT_INTERNET == 1)
3353 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3354 && ((CC->user.flags & US_INTERNET) == 0)
3355 && (!CC->internal_pgm)) {
3356 cprintf("%d You don't have access to Internet mail.\n",
3357 ERROR + HIGHER_ACCESS_REQUIRED);
3366 /* Is this a room which has anonymous-only or anonymous-option? */
3367 anonymous = MES_NORMAL;
3368 if (CC->room.QRflags & QR_ANONONLY) {
3369 anonymous = MES_ANONONLY;
3371 if (CC->room.QRflags & QR_ANONOPT) {
3372 if (anon_flag == 1) { /* only if the user requested it */
3373 anonymous = MES_ANONOPT;
3377 if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3381 /* If we're only checking the validity of the request, return
3382 * success without creating the message.
3385 cprintf("%d %s\n", CIT_OK,
3386 ((valid_to != NULL) ? valid_to->display_recp : "") );
3393 /* We don't need these anymore because we'll do it differently below */
3398 /* Handle author masquerading */
3399 if (CC->fake_postname[0]) {
3400 strcpy(masquerade_as, CC->fake_postname);
3402 else if (CC->fake_username[0]) {
3403 strcpy(masquerade_as, CC->fake_username);
3406 strcpy(masquerade_as, "");
3409 /* Read in the message from the client. */
3411 cprintf("%d send message\n", START_CHAT_MODE);
3413 cprintf("%d send message\n", SEND_LISTING);
3416 msg = CtdlMakeMessage(&CC->user, recp, cc,
3417 CC->room.QRname, anonymous, format_type,
3418 masquerade_as, subject,
3419 ((strlen(supplied_euid) > 0) ? supplied_euid : NULL),
3422 /* Put together one big recipients struct containing to/cc/bcc all in
3423 * one. This is for the envelope.
3425 char *all_recps = malloc(SIZ * 3);
3426 strcpy(all_recps, recp);
3427 if (strlen(cc) > 0) {
3428 if (strlen(all_recps) > 0) {
3429 strcat(all_recps, ",");
3431 strcat(all_recps, cc);
3433 if (strlen(bcc) > 0) {
3434 if (strlen(all_recps) > 0) {
3435 strcat(all_recps, ",");
3437 strcat(all_recps, bcc);
3439 if (strlen(all_recps) > 0) {
3440 valid = validate_recipients(all_recps);
3448 msgnum = CtdlSubmitMsg(msg, valid, "");
3451 cprintf("%ld\n", msgnum);
3453 cprintf("Message accepted.\n");
3456 cprintf("Internal error.\n");
3458 if (msg->cm_fields['E'] != NULL) {
3459 cprintf("%s\n", msg->cm_fields['E']);
3466 CtdlFreeMessage(msg);
3468 CC->fake_postname[0] = '\0';
3469 if (valid != NULL) {
3478 * API function to delete messages which match a set of criteria
3479 * (returns the actual number of messages deleted)
3481 int CtdlDeleteMessages(char *room_name, /* which room */
3482 long *dmsgnums, /* array of msg numbers to be deleted */
3483 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
3484 char *content_type /* or "" for any */
3488 struct ctdlroom qrbuf;
3489 struct cdbdata *cdbfr;
3490 long *msglist = NULL;
3491 long *dellist = NULL;
3494 int num_deleted = 0;
3496 struct MetaData smi;
3498 lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
3499 room_name, num_dmsgnums, content_type);
3501 /* get room record, obtaining a lock... */
3502 if (lgetroom(&qrbuf, room_name) != 0) {
3503 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3505 return (0); /* room not found */
3507 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3509 if (cdbfr != NULL) {
3510 dellist = malloc(cdbfr->len);
3511 msglist = (long *) cdbfr->ptr;
3512 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3513 num_msgs = cdbfr->len / sizeof(long);
3517 for (i = 0; i < num_msgs; ++i) {
3520 /* Set/clear a bit for each criterion */
3522 /* 0 messages in the list or a null list means that we are
3523 * interested in deleting any messages which meet the other criteria.
3525 if ((num_dmsgnums == 0) || (dmsgnums == NULL)) {
3526 delete_this |= 0x01;
3529 for (j=0; j<num_dmsgnums; ++j) {
3530 if (msglist[i] == dmsgnums[j]) {
3531 delete_this |= 0x01;
3536 if (strlen(content_type) == 0) {
3537 delete_this |= 0x02;
3539 GetMetaData(&smi, msglist[i]);
3540 if (!strcasecmp(smi.meta_content_type,
3542 delete_this |= 0x02;
3546 /* Delete message only if all bits are set */
3547 if (delete_this == 0x03) {
3548 dellist[num_deleted++] = msglist[i];
3553 num_msgs = sort_msglist(msglist, num_msgs);
3554 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3555 msglist, (int)(num_msgs * sizeof(long)));
3557 qrbuf.QRhighest = msglist[num_msgs - 1];
3561 /* Go through the messages we pulled out of the index, and decrement
3562 * their reference counts by 1. If this is the only room the message
3563 * was in, the reference count will reach zero and the message will
3564 * automatically be deleted from the database. We do this in a
3565 * separate pass because there might be plug-in hooks getting called,
3566 * and we don't want that happening during an S_ROOMS critical
3569 if (num_deleted) for (i=0; i<num_deleted; ++i) {
3570 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3571 AdjRefCount(dellist[i], -1);
3574 /* Now free the memory we used, and go away. */
3575 if (msglist != NULL) free(msglist);
3576 if (dellist != NULL) free(dellist);
3577 lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3578 return (num_deleted);
3584 * Check whether the current user has permission to delete messages from
3585 * the current room (returns 1 for yes, 0 for no)
3587 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3588 getuser(&CC->user, CC->curr_user);
3589 if ((CC->user.axlevel < 6)
3590 && (CC->user.usernum != CC->room.QRroomaide)
3591 && ((CC->room.QRflags & QR_MAILBOX) == 0)
3592 && (!(CC->internal_pgm))) {
3601 * Delete message from current room
3603 void cmd_dele(char *args)
3612 extract_token(msgset, args, 0, '|', sizeof msgset);
3613 num_msgs = num_tokens(msgset, ',');
3615 cprintf("%d Nothing to do.\n", CIT_OK);
3619 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3620 cprintf("%d Higher access required.\n",
3621 ERROR + HIGHER_ACCESS_REQUIRED);
3626 * Build our message set to be moved/copied
3628 msgs = malloc(num_msgs * sizeof(long));
3629 for (i=0; i<num_msgs; ++i) {
3630 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3631 msgs[i] = atol(msgtok);
3634 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3638 cprintf("%d %d message%s deleted.\n", CIT_OK,
3639 num_deleted, ((num_deleted != 1) ? "s" : ""));
3641 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
3647 * Back end API function for moves and deletes (multiple messages)
3649 int CtdlCopyMsgsToRoom(long *msgnums, int num_msgs, char *dest) {
3652 err = CtdlSaveMsgPointersInRoom(dest, msgnums, num_msgs, 1, NULL);
3653 if (err != 0) return(err);
3662 * move or copy a message to another room
3664 void cmd_move(char *args)
3671 char targ[ROOMNAMELEN];
3672 struct ctdlroom qtemp;
3679 extract_token(msgset, args, 0, '|', sizeof msgset);
3680 num_msgs = num_tokens(msgset, ',');
3682 cprintf("%d Nothing to do.\n", CIT_OK);
3686 extract_token(targ, args, 1, '|', sizeof targ);
3687 convert_room_name_macros(targ, sizeof targ);
3688 targ[ROOMNAMELEN - 1] = 0;
3689 is_copy = extract_int(args, 2);
3691 if (getroom(&qtemp, targ) != 0) {
3692 cprintf("%d '%s' does not exist.\n",
3693 ERROR + ROOM_NOT_FOUND, targ);
3697 getuser(&CC->user, CC->curr_user);
3698 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3700 /* Check for permission to perform this operation.
3701 * Remember: "CC->room" is source, "qtemp" is target.
3705 /* Aides can move/copy */
3706 if (CC->user.axlevel >= 6) permit = 1;
3708 /* Room aides can move/copy */
3709 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3711 /* Permit move/copy from personal rooms */
3712 if ((CC->room.QRflags & QR_MAILBOX)
3713 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3715 /* Permit only copy from public to personal room */
3717 && (!(CC->room.QRflags & QR_MAILBOX))
3718 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3720 /* User must have access to target room */
3721 if (!(ra & UA_KNOWN)) permit = 0;
3724 cprintf("%d Higher access required.\n",
3725 ERROR + HIGHER_ACCESS_REQUIRED);
3730 * Build our message set to be moved/copied
3732 msgs = malloc(num_msgs * sizeof(long));
3733 for (i=0; i<num_msgs; ++i) {
3734 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3735 msgs[i] = atol(msgtok);
3741 err = CtdlCopyMsgsToRoom(msgs, num_msgs, targ);
3743 cprintf("%d Cannot store message(s) in %s: error %d\n",
3749 /* Now delete the message from the source room,
3750 * if this is a 'move' rather than a 'copy' operation.
3753 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3757 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3763 * GetMetaData() - Get the supplementary record for a message
3765 void GetMetaData(struct MetaData *smibuf, long msgnum)
3768 struct cdbdata *cdbsmi;
3771 memset(smibuf, 0, sizeof(struct MetaData));
3772 smibuf->meta_msgnum = msgnum;
3773 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3775 /* Use the negative of the message number for its supp record index */
3776 TheIndex = (0L - msgnum);
3778 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3779 if (cdbsmi == NULL) {
3780 return; /* record not found; go with defaults */
3782 memcpy(smibuf, cdbsmi->ptr,
3783 ((cdbsmi->len > sizeof(struct MetaData)) ?
3784 sizeof(struct MetaData) : cdbsmi->len));
3791 * PutMetaData() - (re)write supplementary record for a message
3793 void PutMetaData(struct MetaData *smibuf)
3797 /* Use the negative of the message number for the metadata db index */
3798 TheIndex = (0L - smibuf->meta_msgnum);
3800 lprintf(CTDL_DEBUG, "PutMetaData(%ld) - ref count is %d\n",
3801 smibuf->meta_msgnum, smibuf->meta_refcount);
3803 cdb_store(CDB_MSGMAIN,
3804 &TheIndex, (int)sizeof(long),
3805 smibuf, (int)sizeof(struct MetaData));
3810 * AdjRefCount - submit an adjustment to the reference count for a message.
3811 * (These are just queued -- we actually process them later.)
3813 void AdjRefCount(long msgnum, int incr)
3815 struct arcq new_arcq;
3817 begin_critical_section(S_SUPPMSGMAIN);
3818 if (arcfp == NULL) {
3819 arcfp = fopen(file_arcq, "ab+");
3821 end_critical_section(S_SUPPMSGMAIN);
3823 /* msgnum < 0 means that we're trying to close the file */
3825 lprintf(CTDL_DEBUG, "Closing the AdjRefCount queue file\n");
3826 begin_critical_section(S_SUPPMSGMAIN);
3827 if (arcfp != NULL) {
3831 end_critical_section(S_SUPPMSGMAIN);
3836 * If we can't open the queue, perform the operation synchronously.
3838 if (arcfp == NULL) {
3839 TDAP_AdjRefCount(msgnum, incr);
3843 new_arcq.arcq_msgnum = msgnum;
3844 new_arcq.arcq_delta = incr;
3845 fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
3853 * TDAP_ProcessAdjRefCountQueue()
3855 * Process the queue of message count adjustments that was created by calls
3856 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
3857 * for each one. This should be an "off hours" operation.
3859 int TDAP_ProcessAdjRefCountQueue(void)
3861 char file_arcq_temp[PATH_MAX];
3864 struct arcq arcq_rec;
3865 int num_records_processed = 0;
3867 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s2", file_arcq);
3869 begin_critical_section(S_SUPPMSGMAIN);
3870 if (arcfp != NULL) {
3875 r = link(file_arcq, file_arcq_temp);
3877 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3878 end_critical_section(S_SUPPMSGMAIN);
3879 return(num_records_processed);
3883 end_critical_section(S_SUPPMSGMAIN);
3885 fp = fopen(file_arcq_temp, "rb");
3887 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3888 return(num_records_processed);
3891 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
3892 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
3893 ++num_records_processed;
3897 r = unlink(file_arcq_temp);
3899 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3902 return(num_records_processed);
3908 * TDAP_AdjRefCount - adjust the reference count for a message.
3909 * This one does it "for real" because it's called by
3910 * the autopurger function that processes the queue
3911 * created by AdjRefCount(). If a message's reference
3912 * count becomes zero, we also delete the message from
3913 * disk and de-index it.
3915 void TDAP_AdjRefCount(long msgnum, int incr)
3918 struct MetaData smi;
3921 /* This is a *tight* critical section; please keep it that way, as
3922 * it may get called while nested in other critical sections.
3923 * Complicating this any further will surely cause deadlock!
3925 begin_critical_section(S_SUPPMSGMAIN);
3926 GetMetaData(&smi, msgnum);
3927 smi.meta_refcount += incr;
3929 end_critical_section(S_SUPPMSGMAIN);
3930 lprintf(CTDL_DEBUG, "msg %ld ref count incr %d, is now %d\n",
3931 msgnum, incr, smi.meta_refcount);
3933 /* If the reference count is now zero, delete the message
3934 * (and its supplementary record as well).
3936 if (smi.meta_refcount == 0) {
3937 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
3939 /* Remove from fulltext index */
3940 if (config.c_enable_fulltext) {
3941 ft_index_message(msgnum, 0);
3944 /* Remove from message base */
3946 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3947 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3949 /* Remove metadata record */
3950 delnum = (0L - msgnum);
3951 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3957 * Write a generic object to this room
3959 * Note: this could be much more efficient. Right now we use two temporary
3960 * files, and still pull the message into memory as with all others.
3962 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
3963 char *content_type, /* MIME type of this object */
3964 char *tempfilename, /* Where to fetch it from */
3965 struct ctdluser *is_mailbox, /* Mailbox room? */
3966 int is_binary, /* Is encoding necessary? */
3967 int is_unique, /* Del others of this type? */
3968 unsigned int flags /* Internal save flags */
3973 struct ctdlroom qrbuf;
3974 char roomname[ROOMNAMELEN];
3975 struct CtdlMessage *msg;
3977 char *raw_message = NULL;
3978 char *encoded_message = NULL;
3979 off_t raw_length = 0;
3981 if (is_mailbox != NULL) {
3982 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3985 safestrncpy(roomname, req_room, sizeof(roomname));
3988 fp = fopen(tempfilename, "rb");
3990 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
3991 tempfilename, strerror(errno));
3994 fseek(fp, 0L, SEEK_END);
3995 raw_length = ftell(fp);
3997 lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
3999 raw_message = malloc((size_t)raw_length + 2);
4000 fread(raw_message, (size_t)raw_length, 1, fp);
4004 encoded_message = malloc((size_t)
4005 (((raw_length * 134) / 100) + 4096 ) );
4008 encoded_message = malloc((size_t)(raw_length + 4096));
4011 sprintf(encoded_message, "Content-type: %s\n", content_type);
4014 sprintf(&encoded_message[strlen(encoded_message)],
4015 "Content-transfer-encoding: base64\n\n"
4019 sprintf(&encoded_message[strlen(encoded_message)],
4020 "Content-transfer-encoding: 7bit\n\n"
4026 &encoded_message[strlen(encoded_message)],
4032 raw_message[raw_length] = 0;
4034 &encoded_message[strlen(encoded_message)],
4042 lprintf(CTDL_DEBUG, "Allocating\n");
4043 msg = malloc(sizeof(struct CtdlMessage));
4044 memset(msg, 0, sizeof(struct CtdlMessage));
4045 msg->cm_magic = CTDLMESSAGE_MAGIC;
4046 msg->cm_anon_type = MES_NORMAL;
4047 msg->cm_format_type = 4;
4048 msg->cm_fields['A'] = strdup(CC->user.fullname);
4049 msg->cm_fields['O'] = strdup(req_room);
4050 msg->cm_fields['N'] = strdup(config.c_nodename);
4051 msg->cm_fields['H'] = strdup(config.c_humannode);
4052 msg->cm_flags = flags;
4054 msg->cm_fields['M'] = encoded_message;
4056 /* Create the requested room if we have to. */
4057 if (getroom(&qrbuf, roomname) != 0) {
4058 create_room(roomname,
4059 ( (is_mailbox != NULL) ? 5 : 3 ),
4060 "", 0, 1, 0, VIEW_BBS);
4062 /* If the caller specified this object as unique, delete all
4063 * other objects of this type that are currently in the room.
4066 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
4067 CtdlDeleteMessages(roomname, NULL, 0, content_type)
4070 /* Now write the data */
4071 CtdlSubmitMsg(msg, NULL, roomname);
4072 CtdlFreeMessage(msg);
4080 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
4081 config_msgnum = msgnum;
4085 char *CtdlGetSysConfig(char *sysconfname) {
4086 char hold_rm[ROOMNAMELEN];
4089 struct CtdlMessage *msg;
4092 strcpy(hold_rm, CC->room.QRname);
4093 if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
4094 getroom(&CC->room, hold_rm);
4099 /* We want the last (and probably only) config in this room */
4100 begin_critical_section(S_CONFIG);
4101 config_msgnum = (-1L);
4102 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
4103 CtdlGetSysConfigBackend, NULL);
4104 msgnum = config_msgnum;
4105 end_critical_section(S_CONFIG);
4111 msg = CtdlFetchMessage(msgnum, 1);
4113 conf = strdup(msg->cm_fields['M']);
4114 CtdlFreeMessage(msg);
4121 getroom(&CC->room, hold_rm);
4123 if (conf != NULL) do {
4124 extract_token(buf, conf, 0, '\n', sizeof buf);
4125 strcpy(conf, &conf[strlen(buf)+1]);
4126 } while ( (strlen(conf)>0) && (strlen(buf)>0) );
4131 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
4132 char temp[PATH_MAX];
4135 CtdlMakeTempFileName(temp, sizeof temp);
4137 fp = fopen(temp, "w");
4138 if (fp == NULL) return;
4139 fprintf(fp, "%s", sysconfdata);
4142 /* this handy API function does all the work for us */
4143 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
4149 * Determine whether a given Internet address belongs to the current user
4151 int CtdlIsMe(char *addr, int addr_buf_len)
4153 struct recptypes *recp;
4156 recp = validate_recipients(addr);
4157 if (recp == NULL) return(0);
4159 if (recp->num_local == 0) {
4164 for (i=0; i<recp->num_local; ++i) {
4165 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
4166 if (!strcasecmp(addr, CC->user.fullname)) {
4178 * Citadel protocol command to do the same
4180 void cmd_isme(char *argbuf) {
4183 if (CtdlAccessCheck(ac_logged_in)) return;
4184 extract_token(addr, argbuf, 0, '|', sizeof addr);
4186 if (CtdlIsMe(addr, sizeof addr)) {
4187 cprintf("%d %s\n", CIT_OK, addr);
4190 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);