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 */
247 * Back end for the MSGS command: output message number only.
249 void simple_listing(long msgnum, void *userdata)
251 cprintf("%ld\n", msgnum);
257 * Back end for the MSGS command: output header summary.
259 void headers_listing(long msgnum, void *userdata)
261 struct CtdlMessage *msg;
263 msg = CtdlFetchMessage(msgnum, 0);
265 cprintf("%ld|0|||||\n", msgnum);
269 cprintf("%ld|%s|%s|%s|%s|%s|\n",
271 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
272 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
273 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
274 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
275 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
277 CtdlFreeMessage(msg);
282 /* Determine if a given message matches the fields in a message template.
283 * Return 0 for a successful match.
285 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
288 /* If there aren't any fields in the template, all messages will
291 if (template == NULL) return(0);
293 /* Null messages are bogus. */
294 if (msg == NULL) return(1);
296 for (i='A'; i<='Z'; ++i) {
297 if (template->cm_fields[i] != NULL) {
298 if (msg->cm_fields[i] == NULL) {
301 if (strcasecmp(msg->cm_fields[i],
302 template->cm_fields[i])) return 1;
306 /* All compares succeeded: we have a match! */
313 * Retrieve the "seen" message list for the current room.
315 void CtdlGetSeen(char *buf, int which_set) {
318 /* Learn about the user and room in question */
319 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
321 if (which_set == ctdlsetseen_seen)
322 safestrncpy(buf, vbuf.v_seen, SIZ);
323 if (which_set == ctdlsetseen_answered)
324 safestrncpy(buf, vbuf.v_answered, SIZ);
330 * Manipulate the "seen msgs" string (or other message set strings)
332 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
333 int target_setting, int which_set,
334 struct ctdluser *which_user, struct ctdlroom *which_room) {
335 struct cdbdata *cdbfr;
347 char *is_set; /* actually an array of booleans */
350 char setstr[SIZ], lostr[SIZ], histr[SIZ];
353 /* Don't bother doing *anything* if we were passed a list of zero messages */
354 if (num_target_msgnums < 1) {
358 lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
359 num_target_msgnums, target_msgnums[0],
360 target_setting, which_set);
362 /* Learn about the user and room in question */
363 CtdlGetRelationship(&vbuf,
364 ((which_user != NULL) ? which_user : &CC->user),
365 ((which_room != NULL) ? which_room : &CC->room)
368 /* Load the message list */
369 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
371 msglist = (long *) cdbfr->ptr;
372 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
373 num_msgs = cdbfr->len / sizeof(long);
376 return; /* No messages at all? No further action. */
379 is_set = malloc(num_msgs * sizeof(char));
380 memset(is_set, 0, (num_msgs * sizeof(char)) );
382 /* Decide which message set we're manipulating */
384 case ctdlsetseen_seen:
385 safestrncpy(vset, vbuf.v_seen, sizeof vset);
387 case ctdlsetseen_answered:
388 safestrncpy(vset, vbuf.v_answered, sizeof vset);
392 /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
394 /* Translate the existing sequence set into an array of booleans */
395 num_sets = num_tokens(vset, ',');
396 for (s=0; s<num_sets; ++s) {
397 extract_token(setstr, vset, s, ',', sizeof setstr);
399 extract_token(lostr, setstr, 0, ':', sizeof lostr);
400 if (num_tokens(setstr, ':') >= 2) {
401 extract_token(histr, setstr, 1, ':', sizeof histr);
402 if (!strcmp(histr, "*")) {
403 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
407 strcpy(histr, lostr);
412 for (i = 0; i < num_msgs; ++i) {
413 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
419 /* Now translate the array of booleans back into a sequence set */
424 for (i=0; i<num_msgs; ++i) {
426 is_seen = is_set[i]; /* Default to existing setting */
428 for (k=0; k<num_target_msgnums; ++k) {
429 if (msglist[i] == target_msgnums[k]) {
430 is_seen = target_setting;
435 if (lo < 0L) lo = msglist[i];
439 if ( ((is_seen == 0) && (was_seen == 1))
440 || ((is_seen == 1) && (i == num_msgs-1)) ) {
442 /* begin trim-o-matic code */
445 while ( (strlen(vset) + 20) > sizeof vset) {
446 remove_token(vset, 0, ',');
448 if (j--) break; /* loop no more than 9 times */
450 if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
454 snprintf(lostr, sizeof lostr,
455 "1:%ld,%s", t, vset);
456 safestrncpy(vset, lostr, sizeof vset);
458 /* end trim-o-matic code */
466 snprintf(&vset[tmp], (sizeof vset) - tmp,
470 snprintf(&vset[tmp], (sizeof vset) - tmp,
479 /* Decide which message set we're manipulating */
481 case ctdlsetseen_seen:
482 safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
484 case ctdlsetseen_answered:
485 safestrncpy(vbuf.v_answered, vset,
486 sizeof vbuf.v_answered);
491 /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
493 CtdlSetRelationship(&vbuf,
494 ((which_user != NULL) ? which_user : &CC->user),
495 ((which_room != NULL) ? which_room : &CC->room)
501 * API function to perform an operation for each qualifying message in the
502 * current room. (Returns the number of messages processed.)
504 int CtdlForEachMessage(int mode, long ref, char *search_string,
506 struct CtdlMessage *compare,
507 void (*CallBack) (long, void *),
513 struct cdbdata *cdbfr;
514 long *msglist = NULL;
516 int num_processed = 0;
519 struct CtdlMessage *msg = NULL;
522 int printed_lastold = 0;
523 int num_search_msgs = 0;
524 long *search_msgs = NULL;
526 /* Learn about the user and room in question */
527 getuser(&CC->user, CC->curr_user);
528 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
530 /* Load the message list */
531 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
533 msglist = (long *) cdbfr->ptr;
534 cdbfr->ptr = NULL; /* CtdlForEachMessage() now owns this memory */
535 num_msgs = cdbfr->len / sizeof(long);
538 return 0; /* No messages at all? No further action. */
543 * Now begin the traversal.
545 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
547 /* If the caller is looking for a specific MIME type, filter
548 * out all messages which are not of the type requested.
550 if (content_type != NULL) if (strlen(content_type) > 0) {
552 /* This call to GetMetaData() sits inside this loop
553 * so that we only do the extra database read per msg
554 * if we need to. Doing the extra read all the time
555 * really kills the server. If we ever need to use
556 * metadata for another search criterion, we need to
557 * move the read somewhere else -- but still be smart
558 * enough to only do the read if the caller has
559 * specified something that will need it.
561 GetMetaData(&smi, msglist[a]);
563 if (strcasecmp(smi.meta_content_type, content_type)) {
569 num_msgs = sort_msglist(msglist, num_msgs);
571 /* If a template was supplied, filter out the messages which
572 * don't match. (This could induce some delays!)
575 if (compare != NULL) {
576 for (a = 0; a < num_msgs; ++a) {
577 msg = CtdlFetchMessage(msglist[a], 1);
579 if (CtdlMsgCmp(msg, compare)) {
582 CtdlFreeMessage(msg);
588 /* If a search string was specified, get a message list from
589 * the full text index and remove messages which aren't on both
593 * Since the lists are sorted and strictly ascending, and the
594 * output list is guaranteed to be shorter than or equal to the
595 * input list, we overwrite the bottom of the input list. This
596 * eliminates the need to memmove big chunks of the list over and
599 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
600 ft_search(&num_search_msgs, &search_msgs, search_string);
601 if (num_search_msgs > 0) {
605 orig_num_msgs = num_msgs;
607 for (i=0; i<orig_num_msgs; ++i) {
608 for (j=0; j<num_search_msgs; ++j) {
609 if (msglist[i] == search_msgs[j]) {
610 msglist[num_msgs++] = msglist[i];
616 num_msgs = 0; /* No messages qualify */
618 if (search_msgs != NULL) free(search_msgs);
620 /* Now that we've purged messages which don't contain the search
621 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
628 * Now iterate through the message list, according to the
629 * criteria supplied by the caller.
632 for (a = 0; a < num_msgs; ++a) {
633 thismsg = msglist[a];
634 if (mode == MSGS_ALL) {
638 is_seen = is_msg_in_sequence_set(
639 vbuf.v_seen, thismsg);
640 if (is_seen) lastold = thismsg;
646 || ((mode == MSGS_OLD) && (is_seen))
647 || ((mode == MSGS_NEW) && (!is_seen))
648 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
649 || ((mode == MSGS_FIRST) && (a < ref))
650 || ((mode == MSGS_GT) && (thismsg > ref))
651 || ((mode == MSGS_EQ) && (thismsg == ref))
654 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
656 CallBack(lastold, userdata);
660 if (CallBack) CallBack(thismsg, userdata);
664 free(msglist); /* Clean up */
665 return num_processed;
671 * cmd_msgs() - get list of message #'s in this room
672 * implements the MSGS server command using CtdlForEachMessage()
674 void cmd_msgs(char *cmdbuf)
683 int with_template = 0;
684 struct CtdlMessage *template = NULL;
685 int with_headers = 0;
686 char search_string[1024];
688 extract_token(which, cmdbuf, 0, '|', sizeof which);
689 cm_ref = extract_int(cmdbuf, 1);
690 extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
691 with_template = extract_int(cmdbuf, 2);
692 with_headers = extract_int(cmdbuf, 3);
695 if (!strncasecmp(which, "OLD", 3))
697 else if (!strncasecmp(which, "NEW", 3))
699 else if (!strncasecmp(which, "FIRST", 5))
701 else if (!strncasecmp(which, "LAST", 4))
703 else if (!strncasecmp(which, "GT", 2))
705 else if (!strncasecmp(which, "SEARCH", 6))
710 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
711 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
715 if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
716 cprintf("%d Full text index is not enabled on this server.\n",
717 ERROR + CMD_NOT_SUPPORTED);
723 cprintf("%d Send template then receive message list\n",
725 template = (struct CtdlMessage *)
726 malloc(sizeof(struct CtdlMessage));
727 memset(template, 0, sizeof(struct CtdlMessage));
728 template->cm_magic = CTDLMESSAGE_MAGIC;
729 template->cm_anon_type = MES_NORMAL;
731 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
732 extract_token(tfield, buf, 0, '|', sizeof tfield);
733 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
734 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
735 if (!strcasecmp(tfield, msgkeys[i])) {
736 template->cm_fields[i] =
744 cprintf("%d \n", LISTING_FOLLOWS);
747 CtdlForEachMessage(mode,
748 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
749 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
752 (with_headers ? headers_listing : simple_listing),
755 if (template != NULL) CtdlFreeMessage(template);
763 * help_subst() - support routine for help file viewer
765 void help_subst(char *strbuf, char *source, char *dest)
770 while (p = pattern2(strbuf, source), (p >= 0)) {
771 strcpy(workbuf, &strbuf[p + strlen(source)]);
772 strcpy(&strbuf[p], dest);
773 strcat(strbuf, workbuf);
778 void do_help_subst(char *buffer)
782 help_subst(buffer, "^nodename", config.c_nodename);
783 help_subst(buffer, "^humannode", config.c_humannode);
784 help_subst(buffer, "^fqdn", config.c_fqdn);
785 help_subst(buffer, "^username", CC->user.fullname);
786 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
787 help_subst(buffer, "^usernum", buf2);
788 help_subst(buffer, "^sysadm", config.c_sysadm);
789 help_subst(buffer, "^variantname", CITADEL);
790 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
791 help_subst(buffer, "^maxsessions", buf2);
792 help_subst(buffer, "^bbsdir", ctdl_bbsbase_dir);
798 * memfmout() - Citadel text formatter and paginator.
799 * Although the original purpose of this routine was to format
800 * text to the reader's screen width, all we're really using it
801 * for here is to format text out to 80 columns before sending it
802 * to the client. The client software may reformat it again.
805 char *mptr, /* where are we going to get our text from? */
806 char subst, /* nonzero if we should do substitutions */
807 char *nl) /* string to terminate lines with */
815 static int width = 80;
820 c = 1; /* c is the current pos */
824 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
826 buffer[strlen(buffer) + 1] = 0;
827 buffer[strlen(buffer)] = ch;
830 if (buffer[0] == '^')
831 do_help_subst(buffer);
833 buffer[strlen(buffer) + 1] = 0;
835 strcpy(buffer, &buffer[1]);
843 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
846 if (((old == 13) || (old == 10)) && (isspace(real))) {
851 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
852 cprintf("%s%s", nl, aaa);
861 if ((strlen(aaa) + c) > (width - 5)) {
870 if ((ch == 13) || (ch == 10)) {
871 cprintf("%s%s", aaa, nl);
878 cprintf("%s%s", aaa, nl);
884 * Callback function for mime parser that simply lists the part
886 void list_this_part(char *name, char *filename, char *partnum, char *disp,
887 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
892 ma = (struct ma_info *)cbuserdata;
893 if (ma->is_ma == 0) {
894 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
895 name, filename, partnum, disp, cbtype, (long)length);
900 * Callback function for multipart prefix
902 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
903 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
908 ma = (struct ma_info *)cbuserdata;
909 if (!strcasecmp(cbtype, "multipart/alternative")) {
913 if (ma->is_ma == 0) {
914 cprintf("pref=%s|%s\n", partnum, cbtype);
919 * Callback function for multipart sufffix
921 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
922 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
927 ma = (struct ma_info *)cbuserdata;
928 if (ma->is_ma == 0) {
929 cprintf("suff=%s|%s\n", partnum, cbtype);
931 if (!strcasecmp(cbtype, "multipart/alternative")) {
938 * Callback function for mime parser that opens a section for downloading
940 void mime_download(char *name, char *filename, char *partnum, char *disp,
941 void *content, char *cbtype, char *cbcharset, size_t length,
942 char *encoding, void *cbuserdata)
945 /* Silently go away if there's already a download open... */
946 if (CC->download_fp != NULL)
949 /* ...or if this is not the desired section */
950 if (strcasecmp(CC->download_desired_section, partnum))
953 CC->download_fp = tmpfile();
954 if (CC->download_fp == NULL)
957 fwrite(content, length, 1, CC->download_fp);
958 fflush(CC->download_fp);
959 rewind(CC->download_fp);
961 OpenCmdResult(filename, cbtype);
967 * Callback function for mime parser that outputs a section all at once
969 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
970 void *content, char *cbtype, char *cbcharset, size_t length,
971 char *encoding, void *cbuserdata)
973 int *found_it = (int *)cbuserdata;
975 /* ...or if this is not the desired section */
976 if (strcasecmp(CC->download_desired_section, partnum))
981 cprintf("%d %d\n", BINARY_FOLLOWS, length);
982 client_write(content, length);
988 * Load a message from disk into memory.
989 * This is used by CtdlOutputMsg() and other fetch functions.
991 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
992 * using the CtdlMessageFree() function.
994 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
996 struct cdbdata *dmsgtext;
997 struct CtdlMessage *ret = NULL;
1001 cit_uint8_t field_header;
1003 lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1005 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1006 if (dmsgtext == NULL) {
1009 mptr = dmsgtext->ptr;
1010 upper_bound = mptr + dmsgtext->len;
1012 /* Parse the three bytes that begin EVERY message on disk.
1013 * The first is always 0xFF, the on-disk magic number.
1014 * The second is the anonymous/public type byte.
1015 * The third is the format type byte (vari, fixed, or MIME).
1020 "Message %ld appears to be corrupted.\n",
1025 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1026 memset(ret, 0, sizeof(struct CtdlMessage));
1028 ret->cm_magic = CTDLMESSAGE_MAGIC;
1029 ret->cm_anon_type = *mptr++; /* Anon type byte */
1030 ret->cm_format_type = *mptr++; /* Format type byte */
1033 * The rest is zero or more arbitrary fields. Load them in.
1034 * We're done when we encounter either a zero-length field or
1035 * have just processed the 'M' (message text) field.
1038 if (mptr >= upper_bound) {
1041 field_header = *mptr++;
1042 ret->cm_fields[field_header] = strdup(mptr);
1044 while (*mptr++ != 0); /* advance to next field */
1046 } while ((mptr < upper_bound) && (field_header != 'M'));
1050 /* Always make sure there's something in the msg text field. If
1051 * it's NULL, the message text is most likely stored separately,
1052 * so go ahead and fetch that. Failing that, just set a dummy
1053 * body so other code doesn't barf.
1055 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1056 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1057 if (dmsgtext != NULL) {
1058 ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1062 if (ret->cm_fields['M'] == NULL) {
1063 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1066 /* Perform "before read" hooks (aborting if any return nonzero) */
1067 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1068 CtdlFreeMessage(ret);
1077 * Returns 1 if the supplied pointer points to a valid Citadel message.
1078 * If the pointer is NULL or the magic number check fails, returns 0.
1080 int is_valid_message(struct CtdlMessage *msg) {
1083 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1084 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1092 * 'Destructor' for struct CtdlMessage
1094 void CtdlFreeMessage(struct CtdlMessage *msg)
1098 if (is_valid_message(msg) == 0)
1100 if (msg != NULL) free (msg);
1104 for (i = 0; i < 256; ++i)
1105 if (msg->cm_fields[i] != NULL) {
1106 free(msg->cm_fields[i]);
1109 msg->cm_magic = 0; /* just in case */
1115 * Pre callback function for multipart/alternative
1117 * NOTE: this differs from the standard behavior for a reason. Normally when
1118 * displaying multipart/alternative you want to show the _last_ usable
1119 * format in the message. Here we show the _first_ one, because it's
1120 * usually text/plain. Since this set of functions is designed for text
1121 * output to non-MIME-aware clients, this is the desired behavior.
1124 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1125 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1130 ma = (struct ma_info *)cbuserdata;
1131 lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1132 if (!strcasecmp(cbtype, "multipart/alternative")) {
1136 if (!strcasecmp(cbtype, "message/rfc822")) {
1142 * Post callback function for multipart/alternative
1144 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1145 void *content, char *cbtype, char *cbcharset, size_t length,
1146 char *encoding, void *cbuserdata)
1150 ma = (struct ma_info *)cbuserdata;
1151 lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1152 if (!strcasecmp(cbtype, "multipart/alternative")) {
1156 if (!strcasecmp(cbtype, "message/rfc822")) {
1162 * Inline callback function for mime parser that wants to display text
1164 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1165 void *content, char *cbtype, char *cbcharset, size_t length,
1166 char *encoding, void *cbuserdata)
1173 ma = (struct ma_info *)cbuserdata;
1176 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1177 partnum, filename, cbtype, (long)length);
1180 * If we're in the middle of a multipart/alternative scope and
1181 * we've already printed another section, skip this one.
1183 if ( (ma->is_ma) && (ma->did_print) ) {
1184 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1190 if ( (!strcasecmp(cbtype, "text/plain"))
1191 || (strlen(cbtype)==0) ) {
1194 client_write(wptr, length);
1195 if (wptr[length-1] != '\n') {
1202 if (!strcasecmp(cbtype, "text/html")) {
1203 ptr = html_to_ascii(content, length, 80, 0);
1205 client_write(ptr, wlen);
1206 if (ptr[wlen-1] != '\n') {
1213 if (ma->use_fo_hooks) {
1214 if (PerformFixedOutputHooks(cbtype, content, length)) {
1215 /* above function returns nonzero if it handled the part */
1220 if (strncasecmp(cbtype, "multipart/", 10)) {
1221 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1222 partnum, filename, cbtype, (long)length);
1228 * The client is elegant and sophisticated and wants to be choosy about
1229 * MIME content types, so figure out which multipart/alternative part
1230 * we're going to send.
1232 * We use a system of weights. When we find a part that matches one of the
1233 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1234 * and then set ma->chosen_pref to that MIME type's position in our preference
1235 * list. If we then hit another match, we only replace the first match if
1236 * the preference value is lower.
1238 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1239 void *content, char *cbtype, char *cbcharset, size_t length,
1240 char *encoding, void *cbuserdata)
1246 ma = (struct ma_info *)cbuserdata;
1248 if (ma->is_ma > 0) {
1249 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1250 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1251 lprintf(CTDL_DEBUG, "Is <%s> == <%s> ??\n", buf, cbtype);
1252 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1253 if (i < ma->chosen_pref) {
1254 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1255 ma->chosen_pref = i;
1263 * Now that we've chosen our preferred part, output it.
1265 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1266 void *content, char *cbtype, char *cbcharset, size_t length,
1267 char *encoding, void *cbuserdata)
1271 int add_newline = 0;
1275 ma = (struct ma_info *)cbuserdata;
1277 /* This is not the MIME part you're looking for... */
1278 if (strcasecmp(partnum, ma->chosen_part)) return;
1280 /* If the content-type of this part is in our preferred formats
1281 * list, we can simply output it verbatim.
1283 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1284 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1285 if (!strcasecmp(buf, cbtype)) {
1286 /* Yeah! Go! W00t!! */
1288 text_content = (char *)content;
1289 if (text_content[length-1] != '\n') {
1293 cprintf("Content-type: %s", cbtype);
1294 if (strlen(cbcharset) > 0) {
1295 cprintf("; charset=%s", cbcharset);
1297 cprintf("\nContent-length: %d\n",
1298 (int)(length + add_newline) );
1299 if (strlen(encoding) > 0) {
1300 cprintf("Content-transfer-encoding: %s\n", encoding);
1303 cprintf("Content-transfer-encoding: 7bit\n");
1306 client_write(content, length);
1307 if (add_newline) cprintf("\n");
1312 /* No translations required or possible: output as text/plain */
1313 cprintf("Content-type: text/plain\n\n");
1314 fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1315 length, encoding, cbuserdata);
1320 char desired_section[64];
1327 * Callback function for
1329 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1330 void *content, char *cbtype, char *cbcharset, size_t length,
1331 char *encoding, void *cbuserdata)
1333 struct encapmsg *encap;
1335 encap = (struct encapmsg *)cbuserdata;
1337 /* Only proceed if this is the desired section... */
1338 if (!strcasecmp(encap->desired_section, partnum)) {
1339 encap->msglen = length;
1340 encap->msg = malloc(length + 2);
1341 memcpy(encap->msg, content, length);
1351 * Get a message off disk. (returns om_* values found in msgbase.h)
1354 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1355 int mode, /* how would you like that message? */
1356 int headers_only, /* eschew the message body? */
1357 int do_proto, /* do Citadel protocol responses? */
1358 int crlf, /* Use CRLF newlines instead of LF? */
1359 char *section /* NULL or a message/rfc822 section */
1361 struct CtdlMessage *TheMessage = NULL;
1362 int retcode = om_no_such_msg;
1363 struct encapmsg encap;
1365 lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n",
1367 (section ? section : "<>")
1370 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1371 if (do_proto) cprintf("%d Not logged in.\n",
1372 ERROR + NOT_LOGGED_IN);
1373 return(om_not_logged_in);
1376 /* FIXME: check message id against msglist for this room */
1379 * Fetch the message from disk. If we're in any sort of headers
1380 * only mode, request that we don't even bother loading the body
1383 if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1384 TheMessage = CtdlFetchMessage(msg_num, 0);
1387 TheMessage = CtdlFetchMessage(msg_num, 1);
1390 if (TheMessage == NULL) {
1391 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1392 ERROR + MESSAGE_NOT_FOUND, msg_num);
1393 return(om_no_such_msg);
1396 /* Here is the weird form of this command, to process only an
1397 * encapsulated message/rfc822 section.
1399 if (section) if (strlen(section)>0) if (strcmp(section, "0")) {
1400 memset(&encap, 0, sizeof encap);
1401 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1402 mime_parser(TheMessage->cm_fields['M'],
1404 *extract_encapsulated_message,
1405 NULL, NULL, (void *)&encap, 0
1407 CtdlFreeMessage(TheMessage);
1411 encap.msg[encap.msglen] = 0;
1412 TheMessage = convert_internet_message(encap.msg);
1413 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1415 /* Now we let it fall through to the bottom of this
1416 * function, because TheMessage now contains the
1417 * encapsulated message instead of the top-level
1418 * message. Isn't that neat?
1423 if (do_proto) cprintf("%d msg %ld has no part %s\n",
1424 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1425 retcode = om_no_such_msg;
1430 /* Ok, output the message now */
1431 retcode = CtdlOutputPreLoadedMsg(
1433 headers_only, do_proto, crlf);
1434 CtdlFreeMessage(TheMessage);
1441 * Get a message off disk. (returns om_* values found in msgbase.h)
1444 int CtdlOutputPreLoadedMsg(
1445 struct CtdlMessage *TheMessage,
1446 int mode, /* how would you like that message? */
1447 int headers_only, /* eschew the message body? */
1448 int do_proto, /* do Citadel protocol responses? */
1449 int crlf /* Use CRLF newlines instead of LF? */
1455 char display_name[256];
1457 char *nl; /* newline string */
1459 int subject_found = 0;
1462 /* Buffers needed for RFC822 translation. These are all filled
1463 * using functions that are bounds-checked, and therefore we can
1464 * make them substantially smaller than SIZ.
1472 char datestamp[100];
1474 lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1475 ((TheMessage == NULL) ? "NULL" : "not null"),
1476 mode, headers_only, do_proto, crlf);
1478 strcpy(mid, "unknown");
1479 nl = (crlf ? "\r\n" : "\n");
1481 if (!is_valid_message(TheMessage)) {
1483 "ERROR: invalid preloaded message for output\n");
1484 return(om_no_such_msg);
1487 /* Are we downloading a MIME component? */
1488 if (mode == MT_DOWNLOAD) {
1489 if (TheMessage->cm_format_type != FMT_RFC822) {
1491 cprintf("%d This is not a MIME message.\n",
1492 ERROR + ILLEGAL_VALUE);
1493 } else if (CC->download_fp != NULL) {
1494 if (do_proto) cprintf(
1495 "%d You already have a download open.\n",
1496 ERROR + RESOURCE_BUSY);
1498 /* Parse the message text component */
1499 mptr = TheMessage->cm_fields['M'];
1500 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1501 /* If there's no file open by this time, the requested
1502 * section wasn't found, so print an error
1504 if (CC->download_fp == NULL) {
1505 if (do_proto) cprintf(
1506 "%d Section %s not found.\n",
1507 ERROR + FILE_NOT_FOUND,
1508 CC->download_desired_section);
1511 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1514 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
1515 * in a single server operation instead of opening a download file.
1517 if (mode == MT_SPEW_SECTION) {
1518 if (TheMessage->cm_format_type != FMT_RFC822) {
1520 cprintf("%d This is not a MIME message.\n",
1521 ERROR + ILLEGAL_VALUE);
1523 /* Parse the message text component */
1526 mptr = TheMessage->cm_fields['M'];
1527 mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
1528 /* If section wasn't found, print an error
1531 if (do_proto) cprintf(
1532 "%d Section %s not found.\n",
1533 ERROR + FILE_NOT_FOUND,
1534 CC->download_desired_section);
1537 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1540 /* now for the user-mode message reading loops */
1541 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1543 /* Does the caller want to skip the headers? */
1544 if (headers_only == HEADERS_NONE) goto START_TEXT;
1546 /* Tell the client which format type we're using. */
1547 if ( (mode == MT_CITADEL) && (do_proto) ) {
1548 cprintf("type=%d\n", TheMessage->cm_format_type);
1551 /* nhdr=yes means that we're only displaying headers, no body */
1552 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1553 && (mode == MT_CITADEL)
1556 cprintf("nhdr=yes\n");
1559 /* begin header processing loop for Citadel message format */
1561 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1563 safestrncpy(display_name, "<unknown>", sizeof display_name);
1564 if (TheMessage->cm_fields['A']) {
1565 strcpy(buf, TheMessage->cm_fields['A']);
1566 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1567 safestrncpy(display_name, "****", sizeof display_name);
1569 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1570 safestrncpy(display_name, "anonymous", sizeof display_name);
1573 safestrncpy(display_name, buf, sizeof display_name);
1575 if ((is_room_aide())
1576 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1577 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1578 size_t tmp = strlen(display_name);
1579 snprintf(&display_name[tmp],
1580 sizeof display_name - tmp,
1585 /* Don't show Internet address for users on the
1586 * local Citadel network.
1589 if (TheMessage->cm_fields['N'] != NULL)
1590 if (strlen(TheMessage->cm_fields['N']) > 0)
1591 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1595 /* Now spew the header fields in the order we like them. */
1596 safestrncpy(allkeys, FORDER, sizeof allkeys);
1597 for (i=0; i<strlen(allkeys); ++i) {
1598 k = (int) allkeys[i];
1600 if ( (TheMessage->cm_fields[k] != NULL)
1601 && (msgkeys[k] != NULL) ) {
1603 if (do_proto) cprintf("%s=%s\n",
1607 else if ((k == 'F') && (suppress_f)) {
1610 /* Masquerade display name if needed */
1612 if (do_proto) cprintf("%s=%s\n",
1614 TheMessage->cm_fields[k]
1623 /* begin header processing loop for RFC822 transfer format */
1628 strcpy(snode, NODENAME);
1629 strcpy(lnode, HUMANNODE);
1630 if (mode == MT_RFC822) {
1631 for (i = 0; i < 256; ++i) {
1632 if (TheMessage->cm_fields[i]) {
1633 mptr = TheMessage->cm_fields[i];
1636 safestrncpy(luser, mptr, sizeof luser);
1637 safestrncpy(suser, mptr, sizeof suser);
1639 else if (i == 'Y') {
1640 cprintf("CC: %s%s", mptr, nl);
1642 else if (i == 'P') {
1643 cprintf("Return-Path: %s%s", mptr, nl);
1645 else if (i == 'V') {
1646 cprintf("Envelope-To: %s%s", mptr, nl);
1648 else if (i == 'U') {
1649 cprintf("Subject: %s%s", mptr, nl);
1653 safestrncpy(mid, mptr, sizeof mid);
1655 safestrncpy(lnode, mptr, sizeof lnode);
1657 safestrncpy(fuser, mptr, sizeof fuser);
1658 /* else if (i == 'O')
1659 cprintf("X-Citadel-Room: %s%s",
1662 safestrncpy(snode, mptr, sizeof snode);
1664 cprintf("To: %s%s", mptr, nl);
1665 else if (i == 'T') {
1666 datestring(datestamp, sizeof datestamp,
1667 atol(mptr), DATESTRING_RFC822);
1668 cprintf("Date: %s%s", datestamp, nl);
1672 if (subject_found == 0) {
1673 cprintf("Subject: (no subject)%s", nl);
1677 for (i=0; i<strlen(suser); ++i) {
1678 suser[i] = tolower(suser[i]);
1679 if (!isalnum(suser[i])) suser[i]='_';
1682 if (mode == MT_RFC822) {
1683 if (!strcasecmp(snode, NODENAME)) {
1684 safestrncpy(snode, FQDN, sizeof snode);
1687 /* Construct a fun message id */
1688 cprintf("Message-ID: <%s", mid);
1689 if (strchr(mid, '@')==NULL) {
1690 cprintf("@%s", snode);
1694 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1695 cprintf("From: \"----\" <x@x.org>%s", nl);
1697 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1698 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1700 else if (strlen(fuser) > 0) {
1701 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1704 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1707 cprintf("Organization: %s%s", lnode, nl);
1709 /* Blank line signifying RFC822 end-of-headers */
1710 if (TheMessage->cm_format_type != FMT_RFC822) {
1715 /* end header processing loop ... at this point, we're in the text */
1717 if (headers_only == HEADERS_FAST) goto DONE;
1718 mptr = TheMessage->cm_fields['M'];
1720 /* Tell the client about the MIME parts in this message */
1721 if (TheMessage->cm_format_type == FMT_RFC822) {
1722 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1723 memset(&ma, 0, sizeof(struct ma_info));
1724 mime_parser(mptr, NULL,
1725 (do_proto ? *list_this_part : NULL),
1726 (do_proto ? *list_this_pref : NULL),
1727 (do_proto ? *list_this_suff : NULL),
1730 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1731 char *start_of_text = NULL;
1732 start_of_text = strstr(mptr, "\n\r\n");
1733 if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1734 if (start_of_text == NULL) start_of_text = mptr;
1736 start_of_text = strstr(start_of_text, "\n");
1741 int nllen = strlen(nl);
1742 while (ch=*mptr, ch!=0) {
1748 ((headers_only == HEADERS_NONE) && (mptr >= start_of_text))
1749 || ((headers_only == HEADERS_ONLY) && (mptr < start_of_text))
1750 || ((headers_only != HEADERS_NONE) && (headers_only != HEADERS_ONLY))
1753 sprintf(&outbuf[outlen], "%s", nl);
1757 outbuf[outlen++] = ch;
1762 if (outlen > 1000) {
1763 client_write(outbuf, outlen);
1768 client_write(outbuf, outlen);
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 = NULL;
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 // Add a flag so the Funambol module knows its mail
2561 msg->cm_fields['W'] = strdup(recipient);
2562 MailboxName(actual_rm, sizeof actual_rm,
2563 &userbuf, MAILROOM);
2564 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2565 BumpNewMailCounter(userbuf.usernum);
2566 if (strlen(config.c_funambol_host) > 0) {
2567 /* Generate a instruction message for the Funambol notification
2568 server, in the same style as the SMTP queue */
2569 instr = malloc(SIZ * 2);
2570 snprintf(instr, SIZ * 2,
2571 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2573 SPOOLMIME, newmsgid, (long)time(NULL),
2574 msg->cm_fields['A'], msg->cm_fields['N']
2577 imsg = malloc(sizeof(struct CtdlMessage));
2578 memset(imsg, 0, sizeof(struct CtdlMessage));
2579 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2580 imsg->cm_anon_type = MES_NORMAL;
2581 imsg->cm_format_type = FMT_RFC822;
2582 imsg->cm_fields['A'] = strdup("Citadel");
2583 imsg->cm_fields['J'] = strdup("do not journal");
2584 imsg->cm_fields['M'] = instr;
2585 imsg->cm_fields['W'] = strdup(recipient);
2586 CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM);
2587 CtdlFreeMessage(imsg);
2591 lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2592 CtdlSaveMsgPointerInRoom(config.c_aideroom,
2597 /* Perform "after save" hooks */
2598 lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2599 PerformMessageHooks(msg, EVT_AFTERSAVE);
2601 /* For IGnet mail, we have to save a new copy into the spooler for
2602 * each recipient, with the R and D fields set to the recipient and
2603 * destination-node. This has two ugly side effects: all other
2604 * recipients end up being unlisted in this recipient's copy of the
2605 * message, and it has to deliver multiple messages to the same
2606 * node. We'll revisit this again in a year or so when everyone has
2607 * a network spool receiver that can handle the new style messages.
2610 if (recps->num_ignet > 0)
2611 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2612 extract_token(recipient, recps->recp_ignet, i,
2613 '|', sizeof recipient);
2615 hold_R = msg->cm_fields['R'];
2616 hold_D = msg->cm_fields['D'];
2617 msg->cm_fields['R'] = malloc(SIZ);
2618 msg->cm_fields['D'] = malloc(128);
2619 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2620 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2622 serialize_message(&smr, msg);
2624 snprintf(submit_filename, sizeof submit_filename,
2625 "%s/netmail.%04lx.%04x.%04x",
2627 (long) getpid(), CC->cs_pid, ++seqnum);
2628 network_fp = fopen(submit_filename, "wb+");
2629 if (network_fp != NULL) {
2630 fwrite(smr.ser, smr.len, 1, network_fp);
2636 free(msg->cm_fields['R']);
2637 free(msg->cm_fields['D']);
2638 msg->cm_fields['R'] = hold_R;
2639 msg->cm_fields['D'] = hold_D;
2642 /* Go back to the room we started from */
2643 lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2644 if (strcasecmp(hold_rm, CC->room.QRname))
2645 /* getroom(&CC->room, hold_rm); */
2646 usergoto(hold_rm, 0, 1, NULL, NULL);
2648 /* For internet mail, generate delivery instructions.
2649 * Yes, this is recursive. Deal with it. Infinite recursion does
2650 * not happen because the delivery instructions message does not
2651 * contain a recipient.
2654 if (recps->num_internet > 0) {
2655 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2656 instr = malloc(SIZ * 2);
2657 snprintf(instr, SIZ * 2,
2658 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2660 SPOOLMIME, newmsgid, (long)time(NULL),
2661 msg->cm_fields['A'], msg->cm_fields['N']
2664 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2665 size_t tmp = strlen(instr);
2666 extract_token(recipient, recps->recp_internet,
2667 i, '|', sizeof recipient);
2668 snprintf(&instr[tmp], SIZ * 2 - tmp,
2669 "remote|%s|0||\n", recipient);
2672 imsg = malloc(sizeof(struct CtdlMessage));
2673 memset(imsg, 0, sizeof(struct CtdlMessage));
2674 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2675 imsg->cm_anon_type = MES_NORMAL;
2676 imsg->cm_format_type = FMT_RFC822;
2677 imsg->cm_fields['A'] = strdup("Citadel");
2678 imsg->cm_fields['J'] = strdup("do not journal");
2679 imsg->cm_fields['M'] = instr;
2680 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2681 CtdlFreeMessage(imsg);
2685 * Any addresses to harvest for someone's address book?
2687 if ( (CC->logged_in) && (recps != NULL) ) {
2688 collected_addresses = harvest_collected_addresses(msg);
2691 if (collected_addresses != NULL) {
2692 begin_critical_section(S_ATBF);
2693 aptr = (struct addresses_to_be_filed *)
2694 malloc(sizeof(struct addresses_to_be_filed));
2696 MailboxName(actual_rm, sizeof actual_rm,
2697 &CC->user, USERCONTACTSROOM);
2698 aptr->roomname = strdup(actual_rm);
2699 aptr->collected_addresses = collected_addresses;
2701 end_critical_section(S_ATBF);
2705 * Determine whether this message qualifies for journaling.
2707 if (msg->cm_fields['J'] != NULL) {
2708 qualified_for_journaling = 0;
2711 if (recps == NULL) {
2712 qualified_for_journaling = config.c_journal_pubmsgs;
2714 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2715 qualified_for_journaling = config.c_journal_email;
2718 qualified_for_journaling = config.c_journal_pubmsgs;
2723 * Do we have to perform journaling? If so, hand off the saved
2724 * RFC822 version will be handed off to the journaler for background
2725 * submit. Otherwise, we have to free the memory ourselves.
2727 if (saved_rfc822_version != NULL) {
2728 if (qualified_for_journaling) {
2729 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2732 free(saved_rfc822_version);
2745 * Convenience function for generating small administrative messages.
2747 void quickie_message(char *from, char *fromaddr, char *to, char *room, char *text,
2748 int format_type, char *subject)
2750 struct CtdlMessage *msg;
2751 struct recptypes *recp = NULL;
2753 msg = malloc(sizeof(struct CtdlMessage));
2754 memset(msg, 0, sizeof(struct CtdlMessage));
2755 msg->cm_magic = CTDLMESSAGE_MAGIC;
2756 msg->cm_anon_type = MES_NORMAL;
2757 msg->cm_format_type = format_type;
2760 msg->cm_fields['A'] = strdup(from);
2762 else if (fromaddr != NULL) {
2763 msg->cm_fields['A'] = strdup(fromaddr);
2764 if (strchr(msg->cm_fields['A'], '@')) {
2765 *strchr(msg->cm_fields['A'], '@') = 0;
2769 msg->cm_fields['A'] = strdup("Citadel");
2772 if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
2773 if (room != NULL) msg->cm_fields['O'] = strdup(room);
2774 msg->cm_fields['N'] = strdup(NODENAME);
2776 msg->cm_fields['R'] = strdup(to);
2777 recp = validate_recipients(to);
2779 if (subject != NULL) {
2780 msg->cm_fields['U'] = strdup(subject);
2782 msg->cm_fields['M'] = strdup(text);
2784 CtdlSubmitMsg(msg, recp, room);
2785 CtdlFreeMessage(msg);
2786 if (recp != NULL) free(recp);
2792 * Back end function used by CtdlMakeMessage() and similar functions
2794 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2795 size_t maxlen, /* maximum message length */
2796 char *exist, /* if non-null, append to it;
2797 exist is ALWAYS freed */
2798 int crlf /* CRLF newlines instead of LF */
2802 size_t message_len = 0;
2803 size_t buffer_len = 0;
2810 if (exist == NULL) {
2817 message_len = strlen(exist);
2818 buffer_len = message_len + 4096;
2819 m = realloc(exist, buffer_len);
2826 /* Do we need to change leading ".." to "." for SMTP escaping? */
2827 if (!strcmp(terminator, ".")) {
2831 /* flush the input if we have nowhere to store it */
2836 /* read in the lines of message text one by one */
2838 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2839 if (!strcmp(buf, terminator)) finished = 1;
2841 strcat(buf, "\r\n");
2847 /* Unescape SMTP-style input of two dots at the beginning of the line */
2849 if (!strncmp(buf, "..", 2)) {
2850 strcpy(buf, &buf[1]);
2854 if ( (!flushing) && (!finished) ) {
2855 /* Measure the line */
2856 linelen = strlen(buf);
2858 /* augment the buffer if we have to */
2859 if ((message_len + linelen) >= buffer_len) {
2860 ptr = realloc(m, (buffer_len * 2) );
2861 if (ptr == NULL) { /* flush if can't allocate */
2864 buffer_len = (buffer_len * 2);
2866 lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2870 /* Add the new line to the buffer. NOTE: this loop must avoid
2871 * using functions like strcat() and strlen() because they
2872 * traverse the entire buffer upon every call, and doing that
2873 * for a multi-megabyte message slows it down beyond usability.
2875 strcpy(&m[message_len], buf);
2876 message_len += linelen;
2879 /* if we've hit the max msg length, flush the rest */
2880 if (message_len >= maxlen) flushing = 1;
2882 } while (!finished);
2890 * Build a binary message to be saved on disk.
2891 * (NOTE: if you supply 'preformatted_text', the buffer you give it
2892 * will become part of the message. This means you are no longer
2893 * responsible for managing that memory -- it will be freed along with
2894 * the rest of the fields when CtdlFreeMessage() is called.)
2897 struct CtdlMessage *CtdlMakeMessage(
2898 struct ctdluser *author, /* author's user structure */
2899 char *recipient, /* NULL if it's not mail */
2900 char *recp_cc, /* NULL if it's not mail */
2901 char *room, /* room where it's going */
2902 int type, /* see MES_ types in header file */
2903 int format_type, /* variformat, plain text, MIME... */
2904 char *fake_name, /* who we're masquerading as */
2905 char *subject, /* Subject (optional) */
2906 char *supplied_euid, /* ...or NULL if this is irrelevant */
2907 char *preformatted_text /* ...or NULL to read text from client */
2909 char dest_node[SIZ];
2911 struct CtdlMessage *msg;
2913 msg = malloc(sizeof(struct CtdlMessage));
2914 memset(msg, 0, sizeof(struct CtdlMessage));
2915 msg->cm_magic = CTDLMESSAGE_MAGIC;
2916 msg->cm_anon_type = type;
2917 msg->cm_format_type = format_type;
2919 /* Don't confuse the poor folks if it's not routed mail. */
2920 strcpy(dest_node, "");
2925 snprintf(buf, sizeof buf, "cit%ld", author->usernum); /* Path */
2926 msg->cm_fields['P'] = strdup(buf);
2928 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
2929 msg->cm_fields['T'] = strdup(buf);
2931 if (fake_name[0]) /* author */
2932 msg->cm_fields['A'] = strdup(fake_name);
2934 msg->cm_fields['A'] = strdup(author->fullname);
2936 if (CC->room.QRflags & QR_MAILBOX) { /* room */
2937 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2940 msg->cm_fields['O'] = strdup(CC->room.QRname);
2943 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
2944 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
2946 if (recipient[0] != 0) {
2947 msg->cm_fields['R'] = strdup(recipient);
2949 if (recp_cc[0] != 0) {
2950 msg->cm_fields['Y'] = strdup(recp_cc);
2952 if (dest_node[0] != 0) {
2953 msg->cm_fields['D'] = strdup(dest_node);
2956 if ( (author == &CC->user) && (strlen(CC->cs_inet_email) > 0) ) {
2957 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2960 if (subject != NULL) {
2963 length = strlen(subject);
2969 while ((subject[i] != '\0') &&
2970 (IsAscii = isascii(subject[i]) != 0 ))
2973 msg->cm_fields['U'] = strdup(subject);
2974 else /* ok, we've got utf8 in the string. */
2976 msg->cm_fields['U'] = rfc2047encode(subject, length);
2982 if (supplied_euid != NULL) {
2983 msg->cm_fields['E'] = strdup(supplied_euid);
2986 if (preformatted_text != NULL) {
2987 msg->cm_fields['M'] = preformatted_text;
2990 msg->cm_fields['M'] = CtdlReadMessageBody("000",
2991 config.c_maxmsglen, NULL, 0);
2999 * Check to see whether we have permission to post a message in the current
3000 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
3001 * returns 0 on success.
3003 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
3006 if (!(CC->logged_in)) {
3007 snprintf(errmsgbuf, n, "Not logged in.");
3008 return (ERROR + NOT_LOGGED_IN);
3011 if ((CC->user.axlevel < 2)
3012 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
3013 snprintf(errmsgbuf, n, "Need to be validated to enter "
3014 "(except in %s> to sysop)", MAILROOM);
3015 return (ERROR + HIGHER_ACCESS_REQUIRED);
3018 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3019 if (!(ra & UA_POSTALLOWED)) {
3020 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
3021 return (ERROR + HIGHER_ACCESS_REQUIRED);
3024 strcpy(errmsgbuf, "Ok");
3030 * Check to see if the specified user has Internet mail permission
3031 * (returns nonzero if permission is granted)
3033 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
3035 /* Do not allow twits to send Internet mail */
3036 if (who->axlevel <= 2) return(0);
3038 /* Globally enabled? */
3039 if (config.c_restrict == 0) return(1);
3041 /* User flagged ok? */
3042 if (who->flags & US_INTERNET) return(2);
3044 /* Aide level access? */
3045 if (who->axlevel >= 6) return(3);
3047 /* No mail for you! */
3053 * Validate recipients, count delivery types and errors, and handle aliasing
3054 * FIXME check for dupes!!!!!
3055 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
3056 * were specified, or the number of addresses found invalid.
3057 * caller needs to free the result.
3059 struct recptypes *validate_recipients(char *supplied_recipients) {
3060 struct recptypes *ret;
3061 char recipients[SIZ];
3062 char this_recp[256];
3063 char this_recp_cooked[256];
3069 struct ctdluser tempUS;
3070 struct ctdlroom tempQR;
3074 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
3075 if (ret == NULL) return(NULL);
3076 memset(ret, 0, sizeof(struct recptypes));
3079 ret->num_internet = 0;
3084 if (supplied_recipients == NULL) {
3085 strcpy(recipients, "");
3088 safestrncpy(recipients, supplied_recipients, sizeof recipients);
3091 /* Change all valid separator characters to commas */
3092 for (i=0; i<strlen(recipients); ++i) {
3093 if ((recipients[i] == ';') || (recipients[i] == '|')) {
3094 recipients[i] = ',';
3098 /* Now start extracting recipients... */
3100 while (strlen(recipients) > 0) {
3102 for (i=0; i<=strlen(recipients); ++i) {
3103 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
3104 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
3105 safestrncpy(this_recp, recipients, i+1);
3107 if (recipients[i] == ',') {
3108 strcpy(recipients, &recipients[i+1]);
3111 strcpy(recipients, "");
3118 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
3120 mailtype = alias(this_recp);
3121 mailtype = alias(this_recp);
3122 mailtype = alias(this_recp);
3123 for (j=0; j<=strlen(this_recp); ++j) {
3124 if (this_recp[j]=='_') {
3125 this_recp_cooked[j] = ' ';
3128 this_recp_cooked[j] = this_recp[j];
3134 if (!strcasecmp(this_recp, "sysop")) {
3136 strcpy(this_recp, config.c_aideroom);
3137 if (strlen(ret->recp_room) > 0) {
3138 strcat(ret->recp_room, "|");
3140 strcat(ret->recp_room, this_recp);
3142 else if (getuser(&tempUS, this_recp) == 0) {
3144 strcpy(this_recp, tempUS.fullname);
3145 if (strlen(ret->recp_local) > 0) {
3146 strcat(ret->recp_local, "|");
3148 strcat(ret->recp_local, this_recp);
3150 else if (getuser(&tempUS, this_recp_cooked) == 0) {
3152 strcpy(this_recp, tempUS.fullname);
3153 if (strlen(ret->recp_local) > 0) {
3154 strcat(ret->recp_local, "|");
3156 strcat(ret->recp_local, this_recp);
3158 else if ( (!strncasecmp(this_recp, "room_", 5))
3159 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
3161 if (strlen(ret->recp_room) > 0) {
3162 strcat(ret->recp_room, "|");
3164 strcat(ret->recp_room, &this_recp_cooked[5]);
3172 /* Yes, you're reading this correctly: if the target
3173 * domain points back to the local system or an attached
3174 * Citadel directory, the address is invalid. That's
3175 * because if the address were valid, we would have
3176 * already translated it to a local address by now.
3178 if (IsDirectory(this_recp)) {
3183 ++ret->num_internet;
3184 if (strlen(ret->recp_internet) > 0) {
3185 strcat(ret->recp_internet, "|");
3187 strcat(ret->recp_internet, this_recp);
3192 if (strlen(ret->recp_ignet) > 0) {
3193 strcat(ret->recp_ignet, "|");
3195 strcat(ret->recp_ignet, this_recp);
3203 if (strlen(ret->errormsg) == 0) {
3204 snprintf(append, sizeof append,
3205 "Invalid recipient: %s",
3209 snprintf(append, sizeof append,
3212 if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
3213 strcat(ret->errormsg, append);
3217 if (strlen(ret->display_recp) == 0) {
3218 strcpy(append, this_recp);
3221 snprintf(append, sizeof append, ", %s",
3224 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
3225 strcat(ret->display_recp, append);
3230 if ((ret->num_local + ret->num_internet + ret->num_ignet +
3231 ret->num_room + ret->num_error) == 0) {
3232 ret->num_error = (-1);
3233 strcpy(ret->errormsg, "No recipients specified.");
3236 lprintf(CTDL_DEBUG, "validate_recipients()\n");
3237 lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
3238 lprintf(CTDL_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
3239 lprintf(CTDL_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
3240 lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
3241 lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
3249 * message entry - mode 0 (normal)
3251 void cmd_ent0(char *entargs)
3257 char supplied_euid[128];
3258 char masquerade_as[SIZ];
3260 int format_type = 0;
3261 char newusername[SIZ];
3262 struct CtdlMessage *msg;
3266 struct recptypes *valid = NULL;
3267 struct recptypes *valid_to = NULL;
3268 struct recptypes *valid_cc = NULL;
3269 struct recptypes *valid_bcc = NULL;
3276 post = extract_int(entargs, 0);
3277 extract_token(recp, entargs, 1, '|', sizeof recp);
3278 anon_flag = extract_int(entargs, 2);
3279 format_type = extract_int(entargs, 3);
3280 extract_token(subject, entargs, 4, '|', sizeof subject);
3281 do_confirm = extract_int(entargs, 6);
3282 extract_token(cc, entargs, 7, '|', sizeof cc);
3283 extract_token(bcc, entargs, 8, '|', sizeof bcc);
3284 switch(CC->room.QRdefaultview) {
3287 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3290 supplied_euid[0] = 0;
3294 /* first check to make sure the request is valid. */
3296 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3298 cprintf("%d %s\n", err, errmsg);
3302 /* Check some other permission type things. */
3305 if (CC->user.axlevel < 6) {
3306 cprintf("%d You don't have permission to masquerade.\n",
3307 ERROR + HIGHER_ACCESS_REQUIRED);
3310 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3311 memset(CC->fake_postname, 0, sizeof(CC->fake_postname) );
3312 safestrncpy(CC->fake_postname, newusername,
3313 sizeof(CC->fake_postname) );
3314 cprintf("%d ok\n", CIT_OK);
3317 CC->cs_flags |= CS_POSTING;
3319 /* In the Mail> room we have to behave a little differently --
3320 * make sure the user has specified at least one recipient. Then
3321 * validate the recipient(s).
3323 if ( (CC->room.QRflags & QR_MAILBOX)
3324 && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) ) {
3326 if (CC->user.axlevel < 2) {
3327 strcpy(recp, "sysop");
3332 valid_to = validate_recipients(recp);
3333 if (valid_to->num_error > 0) {
3334 cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3339 valid_cc = validate_recipients(cc);
3340 if (valid_cc->num_error > 0) {
3341 cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3347 valid_bcc = validate_recipients(bcc);
3348 if (valid_bcc->num_error > 0) {
3349 cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3356 /* Recipient required, but none were specified */
3357 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3361 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3365 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3366 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3367 cprintf("%d You do not have permission "
3368 "to send Internet mail.\n",
3369 ERROR + HIGHER_ACCESS_REQUIRED);
3377 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)
3378 && (CC->user.axlevel < 4) ) {
3379 cprintf("%d Higher access required for network mail.\n",
3380 ERROR + HIGHER_ACCESS_REQUIRED);
3387 if ((RESTRICT_INTERNET == 1)
3388 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3389 && ((CC->user.flags & US_INTERNET) == 0)
3390 && (!CC->internal_pgm)) {
3391 cprintf("%d You don't have access to Internet mail.\n",
3392 ERROR + HIGHER_ACCESS_REQUIRED);
3401 /* Is this a room which has anonymous-only or anonymous-option? */
3402 anonymous = MES_NORMAL;
3403 if (CC->room.QRflags & QR_ANONONLY) {
3404 anonymous = MES_ANONONLY;
3406 if (CC->room.QRflags & QR_ANONOPT) {
3407 if (anon_flag == 1) { /* only if the user requested it */
3408 anonymous = MES_ANONOPT;
3412 if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3416 /* If we're only checking the validity of the request, return
3417 * success without creating the message.
3420 cprintf("%d %s\n", CIT_OK,
3421 ((valid_to != NULL) ? valid_to->display_recp : "") );
3428 /* We don't need these anymore because we'll do it differently below */
3433 /* Handle author masquerading */
3434 if (CC->fake_postname[0]) {
3435 strcpy(masquerade_as, CC->fake_postname);
3437 else if (CC->fake_username[0]) {
3438 strcpy(masquerade_as, CC->fake_username);
3441 strcpy(masquerade_as, "");
3444 /* Read in the message from the client. */
3446 cprintf("%d send message\n", START_CHAT_MODE);
3448 cprintf("%d send message\n", SEND_LISTING);
3451 msg = CtdlMakeMessage(&CC->user, recp, cc,
3452 CC->room.QRname, anonymous, format_type,
3453 masquerade_as, subject,
3454 ((strlen(supplied_euid) > 0) ? supplied_euid : NULL),
3457 /* Put together one big recipients struct containing to/cc/bcc all in
3458 * one. This is for the envelope.
3460 char *all_recps = malloc(SIZ * 3);
3461 strcpy(all_recps, recp);
3462 if (strlen(cc) > 0) {
3463 if (strlen(all_recps) > 0) {
3464 strcat(all_recps, ",");
3466 strcat(all_recps, cc);
3468 if (strlen(bcc) > 0) {
3469 if (strlen(all_recps) > 0) {
3470 strcat(all_recps, ",");
3472 strcat(all_recps, bcc);
3474 if (strlen(all_recps) > 0) {
3475 valid = validate_recipients(all_recps);
3483 msgnum = CtdlSubmitMsg(msg, valid, "");
3486 cprintf("%ld\n", msgnum);
3488 cprintf("Message accepted.\n");
3491 cprintf("Internal error.\n");
3493 if (msg->cm_fields['E'] != NULL) {
3494 cprintf("%s\n", msg->cm_fields['E']);
3501 CtdlFreeMessage(msg);
3503 CC->fake_postname[0] = '\0';
3504 if (valid != NULL) {
3513 * API function to delete messages which match a set of criteria
3514 * (returns the actual number of messages deleted)
3516 int CtdlDeleteMessages(char *room_name, /* which room */
3517 long *dmsgnums, /* array of msg numbers to be deleted */
3518 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
3519 char *content_type /* or "" for any */
3523 struct ctdlroom qrbuf;
3524 struct cdbdata *cdbfr;
3525 long *msglist = NULL;
3526 long *dellist = NULL;
3529 int num_deleted = 0;
3531 struct MetaData smi;
3533 lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s)\n",
3534 room_name, num_dmsgnums, content_type);
3536 /* get room record, obtaining a lock... */
3537 if (lgetroom(&qrbuf, room_name) != 0) {
3538 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3540 return (0); /* room not found */
3542 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3544 if (cdbfr != NULL) {
3545 dellist = malloc(cdbfr->len);
3546 msglist = (long *) cdbfr->ptr;
3547 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3548 num_msgs = cdbfr->len / sizeof(long);
3552 for (i = 0; i < num_msgs; ++i) {
3555 /* Set/clear a bit for each criterion */
3557 /* 0 messages in the list or a null list means that we are
3558 * interested in deleting any messages which meet the other criteria.
3560 if ((num_dmsgnums == 0) || (dmsgnums == NULL)) {
3561 delete_this |= 0x01;
3564 for (j=0; j<num_dmsgnums; ++j) {
3565 if (msglist[i] == dmsgnums[j]) {
3566 delete_this |= 0x01;
3571 if (strlen(content_type) == 0) {
3572 delete_this |= 0x02;
3574 GetMetaData(&smi, msglist[i]);
3575 if (!strcasecmp(smi.meta_content_type,
3577 delete_this |= 0x02;
3581 /* Delete message only if all bits are set */
3582 if (delete_this == 0x03) {
3583 dellist[num_deleted++] = msglist[i];
3588 num_msgs = sort_msglist(msglist, num_msgs);
3589 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3590 msglist, (int)(num_msgs * sizeof(long)));
3592 qrbuf.QRhighest = msglist[num_msgs - 1];
3596 /* Go through the messages we pulled out of the index, and decrement
3597 * their reference counts by 1. If this is the only room the message
3598 * was in, the reference count will reach zero and the message will
3599 * automatically be deleted from the database. We do this in a
3600 * separate pass because there might be plug-in hooks getting called,
3601 * and we don't want that happening during an S_ROOMS critical
3604 if (num_deleted) for (i=0; i<num_deleted; ++i) {
3605 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3606 AdjRefCount(dellist[i], -1);
3609 /* Now free the memory we used, and go away. */
3610 if (msglist != NULL) free(msglist);
3611 if (dellist != NULL) free(dellist);
3612 lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3613 return (num_deleted);
3619 * Check whether the current user has permission to delete messages from
3620 * the current room (returns 1 for yes, 0 for no)
3622 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3624 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
3625 if (ra & UA_DELETEALLOWED) return(1);
3633 * Delete message from current room
3635 void cmd_dele(char *args)
3644 extract_token(msgset, args, 0, '|', sizeof msgset);
3645 num_msgs = num_tokens(msgset, ',');
3647 cprintf("%d Nothing to do.\n", CIT_OK);
3651 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3652 cprintf("%d Higher access required.\n",
3653 ERROR + HIGHER_ACCESS_REQUIRED);
3658 * Build our message set to be moved/copied
3660 msgs = malloc(num_msgs * sizeof(long));
3661 for (i=0; i<num_msgs; ++i) {
3662 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3663 msgs[i] = atol(msgtok);
3666 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3670 cprintf("%d %d message%s deleted.\n", CIT_OK,
3671 num_deleted, ((num_deleted != 1) ? "s" : ""));
3673 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
3679 * Back end API function for moves and deletes (multiple messages)
3681 int CtdlCopyMsgsToRoom(long *msgnums, int num_msgs, char *dest) {
3684 err = CtdlSaveMsgPointersInRoom(dest, msgnums, num_msgs, 1, NULL);
3685 if (err != 0) return(err);
3694 * move or copy a message to another room
3696 void cmd_move(char *args)
3703 char targ[ROOMNAMELEN];
3704 struct ctdlroom qtemp;
3711 extract_token(msgset, args, 0, '|', sizeof msgset);
3712 num_msgs = num_tokens(msgset, ',');
3714 cprintf("%d Nothing to do.\n", CIT_OK);
3718 extract_token(targ, args, 1, '|', sizeof targ);
3719 convert_room_name_macros(targ, sizeof targ);
3720 targ[ROOMNAMELEN - 1] = 0;
3721 is_copy = extract_int(args, 2);
3723 if (getroom(&qtemp, targ) != 0) {
3724 cprintf("%d '%s' does not exist.\n",
3725 ERROR + ROOM_NOT_FOUND, targ);
3729 getuser(&CC->user, CC->curr_user);
3730 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3732 /* Check for permission to perform this operation.
3733 * Remember: "CC->room" is source, "qtemp" is target.
3737 /* Aides can move/copy */
3738 if (CC->user.axlevel >= 6) permit = 1;
3740 /* Room aides can move/copy */
3741 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3743 /* Permit move/copy from personal rooms */
3744 if ((CC->room.QRflags & QR_MAILBOX)
3745 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3747 /* Permit only copy from public to personal room */
3749 && (!(CC->room.QRflags & QR_MAILBOX))
3750 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3752 /* User must have access to target room */
3753 if (!(ra & UA_KNOWN)) permit = 0;
3756 cprintf("%d Higher access required.\n",
3757 ERROR + HIGHER_ACCESS_REQUIRED);
3762 * Build our message set to be moved/copied
3764 msgs = malloc(num_msgs * sizeof(long));
3765 for (i=0; i<num_msgs; ++i) {
3766 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3767 msgs[i] = atol(msgtok);
3773 err = CtdlCopyMsgsToRoom(msgs, num_msgs, targ);
3775 cprintf("%d Cannot store message(s) in %s: error %d\n",
3781 /* Now delete the message from the source room,
3782 * if this is a 'move' rather than a 'copy' operation.
3785 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
3789 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3795 * GetMetaData() - Get the supplementary record for a message
3797 void GetMetaData(struct MetaData *smibuf, long msgnum)
3800 struct cdbdata *cdbsmi;
3803 memset(smibuf, 0, sizeof(struct MetaData));
3804 smibuf->meta_msgnum = msgnum;
3805 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3807 /* Use the negative of the message number for its supp record index */
3808 TheIndex = (0L - msgnum);
3810 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3811 if (cdbsmi == NULL) {
3812 return; /* record not found; go with defaults */
3814 memcpy(smibuf, cdbsmi->ptr,
3815 ((cdbsmi->len > sizeof(struct MetaData)) ?
3816 sizeof(struct MetaData) : cdbsmi->len));
3823 * PutMetaData() - (re)write supplementary record for a message
3825 void PutMetaData(struct MetaData *smibuf)
3829 /* Use the negative of the message number for the metadata db index */
3830 TheIndex = (0L - smibuf->meta_msgnum);
3832 cdb_store(CDB_MSGMAIN,
3833 &TheIndex, (int)sizeof(long),
3834 smibuf, (int)sizeof(struct MetaData));
3839 * AdjRefCount - submit an adjustment to the reference count for a message.
3840 * (These are just queued -- we actually process them later.)
3842 void AdjRefCount(long msgnum, int incr)
3844 struct arcq new_arcq;
3846 begin_critical_section(S_SUPPMSGMAIN);
3847 if (arcfp == NULL) {
3848 arcfp = fopen(file_arcq, "ab+");
3850 end_critical_section(S_SUPPMSGMAIN);
3852 /* msgnum < 0 means that we're trying to close the file */
3854 lprintf(CTDL_DEBUG, "Closing the AdjRefCount queue file\n");
3855 begin_critical_section(S_SUPPMSGMAIN);
3856 if (arcfp != NULL) {
3860 end_critical_section(S_SUPPMSGMAIN);
3865 * If we can't open the queue, perform the operation synchronously.
3867 if (arcfp == NULL) {
3868 TDAP_AdjRefCount(msgnum, incr);
3872 new_arcq.arcq_msgnum = msgnum;
3873 new_arcq.arcq_delta = incr;
3874 fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
3882 * TDAP_ProcessAdjRefCountQueue()
3884 * Process the queue of message count adjustments that was created by calls
3885 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
3886 * for each one. This should be an "off hours" operation.
3888 int TDAP_ProcessAdjRefCountQueue(void)
3890 char file_arcq_temp[PATH_MAX];
3893 struct arcq arcq_rec;
3894 int num_records_processed = 0;
3896 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s2", file_arcq);
3898 begin_critical_section(S_SUPPMSGMAIN);
3899 if (arcfp != NULL) {
3904 r = link(file_arcq, file_arcq_temp);
3906 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3907 end_critical_section(S_SUPPMSGMAIN);
3908 return(num_records_processed);
3912 end_critical_section(S_SUPPMSGMAIN);
3914 fp = fopen(file_arcq_temp, "rb");
3916 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3917 return(num_records_processed);
3920 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
3921 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
3922 ++num_records_processed;
3926 r = unlink(file_arcq_temp);
3928 lprintf(CTDL_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
3931 return(num_records_processed);
3937 * TDAP_AdjRefCount - adjust the reference count for a message.
3938 * This one does it "for real" because it's called by
3939 * the autopurger function that processes the queue
3940 * created by AdjRefCount(). If a message's reference
3941 * count becomes zero, we also delete the message from
3942 * disk and de-index it.
3944 void TDAP_AdjRefCount(long msgnum, int incr)
3947 struct MetaData smi;
3950 /* This is a *tight* critical section; please keep it that way, as
3951 * it may get called while nested in other critical sections.
3952 * Complicating this any further will surely cause deadlock!
3954 begin_critical_section(S_SUPPMSGMAIN);
3955 GetMetaData(&smi, msgnum);
3956 smi.meta_refcount += incr;
3958 end_critical_section(S_SUPPMSGMAIN);
3959 lprintf(CTDL_DEBUG, "msg %ld ref count delta %d, is now %d\n",
3960 msgnum, incr, smi.meta_refcount);
3962 /* If the reference count is now zero, delete the message
3963 * (and its supplementary record as well).
3965 if (smi.meta_refcount == 0) {
3966 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
3968 /* Remove from fulltext index */
3969 if (config.c_enable_fulltext) {
3970 ft_index_message(msgnum, 0);
3973 /* Remove from message base */
3975 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3976 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3978 /* Remove metadata record */
3979 delnum = (0L - msgnum);
3980 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3986 * Write a generic object to this room
3988 * Note: this could be much more efficient. Right now we use two temporary
3989 * files, and still pull the message into memory as with all others.
3991 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
3992 char *content_type, /* MIME type of this object */
3993 char *tempfilename, /* Where to fetch it from */
3994 struct ctdluser *is_mailbox, /* Mailbox room? */
3995 int is_binary, /* Is encoding necessary? */
3996 int is_unique, /* Del others of this type? */
3997 unsigned int flags /* Internal save flags */
4002 struct ctdlroom qrbuf;
4003 char roomname[ROOMNAMELEN];
4004 struct CtdlMessage *msg;
4006 char *raw_message = NULL;
4007 char *encoded_message = NULL;
4008 off_t raw_length = 0;
4010 if (is_mailbox != NULL) {
4011 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
4014 safestrncpy(roomname, req_room, sizeof(roomname));
4017 fp = fopen(tempfilename, "rb");
4019 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
4020 tempfilename, strerror(errno));
4023 fseek(fp, 0L, SEEK_END);
4024 raw_length = ftell(fp);
4026 lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
4028 raw_message = malloc((size_t)raw_length + 2);
4029 fread(raw_message, (size_t)raw_length, 1, fp);
4033 encoded_message = malloc((size_t)
4034 (((raw_length * 134) / 100) + 4096 ) );
4037 encoded_message = malloc((size_t)(raw_length + 4096));
4040 sprintf(encoded_message, "Content-type: %s\n", content_type);
4043 sprintf(&encoded_message[strlen(encoded_message)],
4044 "Content-transfer-encoding: base64\n\n"
4048 sprintf(&encoded_message[strlen(encoded_message)],
4049 "Content-transfer-encoding: 7bit\n\n"
4055 &encoded_message[strlen(encoded_message)],
4061 raw_message[raw_length] = 0;
4063 &encoded_message[strlen(encoded_message)],
4071 lprintf(CTDL_DEBUG, "Allocating\n");
4072 msg = malloc(sizeof(struct CtdlMessage));
4073 memset(msg, 0, sizeof(struct CtdlMessage));
4074 msg->cm_magic = CTDLMESSAGE_MAGIC;
4075 msg->cm_anon_type = MES_NORMAL;
4076 msg->cm_format_type = 4;
4077 msg->cm_fields['A'] = strdup(CC->user.fullname);
4078 msg->cm_fields['O'] = strdup(req_room);
4079 msg->cm_fields['N'] = strdup(config.c_nodename);
4080 msg->cm_fields['H'] = strdup(config.c_humannode);
4081 msg->cm_flags = flags;
4083 msg->cm_fields['M'] = encoded_message;
4085 /* Create the requested room if we have to. */
4086 if (getroom(&qrbuf, roomname) != 0) {
4087 create_room(roomname,
4088 ( (is_mailbox != NULL) ? 5 : 3 ),
4089 "", 0, 1, 0, VIEW_BBS);
4091 /* If the caller specified this object as unique, delete all
4092 * other objects of this type that are currently in the room.
4095 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
4096 CtdlDeleteMessages(roomname, NULL, 0, content_type)
4099 /* Now write the data */
4100 CtdlSubmitMsg(msg, NULL, roomname);
4101 CtdlFreeMessage(msg);
4109 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
4110 config_msgnum = msgnum;
4114 char *CtdlGetSysConfig(char *sysconfname) {
4115 char hold_rm[ROOMNAMELEN];
4118 struct CtdlMessage *msg;
4121 strcpy(hold_rm, CC->room.QRname);
4122 if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
4123 getroom(&CC->room, hold_rm);
4128 /* We want the last (and probably only) config in this room */
4129 begin_critical_section(S_CONFIG);
4130 config_msgnum = (-1L);
4131 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
4132 CtdlGetSysConfigBackend, NULL);
4133 msgnum = config_msgnum;
4134 end_critical_section(S_CONFIG);
4140 msg = CtdlFetchMessage(msgnum, 1);
4142 conf = strdup(msg->cm_fields['M']);
4143 CtdlFreeMessage(msg);
4150 getroom(&CC->room, hold_rm);
4152 if (conf != NULL) do {
4153 extract_token(buf, conf, 0, '\n', sizeof buf);
4154 strcpy(conf, &conf[strlen(buf)+1]);
4155 } while ( (strlen(conf)>0) && (strlen(buf)>0) );
4160 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
4161 char temp[PATH_MAX];
4164 CtdlMakeTempFileName(temp, sizeof temp);
4166 fp = fopen(temp, "w");
4167 if (fp == NULL) return;
4168 fprintf(fp, "%s", sysconfdata);
4171 /* this handy API function does all the work for us */
4172 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
4178 * Determine whether a given Internet address belongs to the current user
4180 int CtdlIsMe(char *addr, int addr_buf_len)
4182 struct recptypes *recp;
4185 recp = validate_recipients(addr);
4186 if (recp == NULL) return(0);
4188 if (recp->num_local == 0) {
4193 for (i=0; i<recp->num_local; ++i) {
4194 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
4195 if (!strcasecmp(addr, CC->user.fullname)) {
4207 * Citadel protocol command to do the same
4209 void cmd_isme(char *argbuf) {
4212 if (CtdlAccessCheck(ac_logged_in)) return;
4213 extract_token(addr, argbuf, 0, '|', sizeof addr);
4215 if (CtdlIsMe(addr, sizeof addr)) {
4216 cprintf("%d %s\n", CIT_OK, addr);
4219 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);