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"
57 struct addresses_to_be_filed *atbf = NULL;
60 * This really belongs in serv_network.c, but I don't know how to export
61 * symbols between modules.
63 struct FilterList *filterlist = NULL;
67 * These are the four-character field headers we use when outputting
68 * messages in Citadel format (as opposed to RFC822 format).
71 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
72 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
73 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
74 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
75 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
76 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
77 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
78 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
106 * This function is self explanatory.
107 * (What can I say, I'm in a weird mood today...)
109 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
113 for (i = 0; i < strlen(name); ++i) {
114 if (name[i] == '@') {
115 while (isspace(name[i - 1]) && i > 0) {
116 strcpy(&name[i - 1], &name[i]);
119 while (isspace(name[i + 1])) {
120 strcpy(&name[i + 1], &name[i + 2]);
128 * Aliasing for network mail.
129 * (Error messages have been commented out, because this is a server.)
131 int alias(char *name)
132 { /* process alias and routing info for mail */
135 char aaa[SIZ], bbb[SIZ];
136 char *ignetcfg = NULL;
137 char *ignetmap = NULL;
144 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
145 stripallbut(name, '<', '>');
147 fp = fopen(file_mail_aliases, "r");
149 fp = fopen("/dev/null", "r");
156 while (fgets(aaa, sizeof aaa, fp) != NULL) {
157 while (isspace(name[0]))
158 strcpy(name, &name[1]);
159 aaa[strlen(aaa) - 1] = 0;
161 for (a = 0; a < strlen(aaa); ++a) {
163 strcpy(bbb, &aaa[a + 1]);
167 if (!strcasecmp(name, aaa))
172 /* Hit the Global Address Book */
173 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
177 lprintf(CTDL_INFO, "Mail is being forwarded to %s\n", name);
179 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
180 for (a=0; a<strlen(name); ++a) {
181 if (name[a] == '@') {
182 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
184 lprintf(CTDL_INFO, "Changed to <%s>\n", name);
189 /* determine local or remote type, see citadel.h */
190 at = haschar(name, '@');
191 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
192 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
193 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
195 /* figure out the delivery mode */
196 extract_token(node, name, 1, '@', sizeof node);
198 /* If there are one or more dots in the nodename, we assume that it
199 * is an FQDN and will attempt SMTP delivery to the Internet.
201 if (haschar(node, '.') > 0) {
202 return(MES_INTERNET);
205 /* Otherwise we look in the IGnet maps for a valid Citadel node.
206 * Try directly-connected nodes first...
208 ignetcfg = CtdlGetSysConfig(IGNETCFG);
209 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
210 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
211 extract_token(testnode, buf, 0, '|', sizeof testnode);
212 if (!strcasecmp(node, testnode)) {
220 * Then try nodes that are two or more hops away.
222 ignetmap = CtdlGetSysConfig(IGNETMAP);
223 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
224 extract_token(buf, ignetmap, i, '\n', sizeof buf);
225 extract_token(testnode, buf, 0, '|', sizeof testnode);
226 if (!strcasecmp(node, testnode)) {
233 /* If we get to this point it's an invalid node name */
242 fp = fopen(file_citadel_control, "r");
244 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
245 file_citadel_control,
249 fread((char *) &CitControl, sizeof(struct CitControl), 1, fp);
255 * Back end for the MSGS command: output message number only.
257 void simple_listing(long msgnum, void *userdata)
259 cprintf("%ld\n", msgnum);
265 * Back end for the MSGS command: output header summary.
267 void headers_listing(long msgnum, void *userdata)
269 struct CtdlMessage *msg;
271 msg = CtdlFetchMessage(msgnum, 0);
273 cprintf("%ld|0|||||\n", msgnum);
277 cprintf("%ld|%s|%s|%s|%s|%s|\n",
279 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
280 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
281 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
282 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
283 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
285 CtdlFreeMessage(msg);
290 /* Determine if a given message matches the fields in a message template.
291 * Return 0 for a successful match.
293 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
296 /* If there aren't any fields in the template, all messages will
299 if (template == NULL) return(0);
301 /* Null messages are bogus. */
302 if (msg == NULL) return(1);
304 for (i='A'; i<='Z'; ++i) {
305 if (template->cm_fields[i] != NULL) {
306 if (msg->cm_fields[i] == NULL) {
309 if (strcasecmp(msg->cm_fields[i],
310 template->cm_fields[i])) return 1;
314 /* All compares succeeded: we have a match! */
321 * Retrieve the "seen" message list for the current room.
323 void CtdlGetSeen(char *buf, int which_set) {
326 /* Learn about the user and room in question */
327 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
329 if (which_set == ctdlsetseen_seen)
330 safestrncpy(buf, vbuf.v_seen, SIZ);
331 if (which_set == ctdlsetseen_answered)
332 safestrncpy(buf, vbuf.v_answered, SIZ);
338 * Manipulate the "seen msgs" string (or other message set strings)
340 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
341 int target_setting, int which_set,
342 struct ctdluser *which_user, struct ctdlroom *which_room) {
343 struct cdbdata *cdbfr;
355 char *is_set; /* actually an array of booleans */
358 char setstr[SIZ], lostr[SIZ], histr[SIZ];
361 lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
362 num_target_msgnums, target_msgnums[0],
363 target_setting, which_set);
365 /* Learn about the user and room in question */
366 CtdlGetRelationship(&vbuf,
367 ((which_user != NULL) ? which_user : &CC->user),
368 ((which_room != NULL) ? which_room : &CC->room)
371 /* Load the message list */
372 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
374 msglist = (long *) cdbfr->ptr;
375 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
376 num_msgs = cdbfr->len / sizeof(long);
379 return; /* No messages at all? No further action. */
382 is_set = malloc(num_msgs * sizeof(char));
383 memset(is_set, 0, (num_msgs * sizeof(char)) );
385 /* Decide which message set we're manipulating */
387 case ctdlsetseen_seen:
388 safestrncpy(vset, vbuf.v_seen, sizeof vset);
390 case ctdlsetseen_answered:
391 safestrncpy(vset, vbuf.v_answered, sizeof vset);
395 /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
397 /* Translate the existing sequence set into an array of booleans */
398 num_sets = num_tokens(vset, ',');
399 for (s=0; s<num_sets; ++s) {
400 extract_token(setstr, vset, s, ',', sizeof setstr);
402 extract_token(lostr, setstr, 0, ':', sizeof lostr);
403 if (num_tokens(setstr, ':') >= 2) {
404 extract_token(histr, setstr, 1, ':', sizeof histr);
405 if (!strcmp(histr, "*")) {
406 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
410 strcpy(histr, lostr);
415 for (i = 0; i < num_msgs; ++i) {
416 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
422 /* Now translate the array of booleans back into a sequence set */
427 for (i=0; i<num_msgs; ++i) {
429 is_seen = is_set[i]; /* Default to existing setting */
431 for (k=0; k<num_target_msgnums; ++k) {
432 if (msglist[i] == target_msgnums[k]) {
433 is_seen = target_setting;
438 if (lo < 0L) lo = msglist[i];
442 if ( ((is_seen == 0) && (was_seen == 1))
443 || ((is_seen == 1) && (i == num_msgs-1)) ) {
445 /* begin trim-o-matic code */
448 while ( (strlen(vset) + 20) > sizeof vset) {
449 remove_token(vset, 0, ',');
451 if (j--) break; /* loop no more than 9 times */
453 if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
457 snprintf(lostr, sizeof lostr,
458 "1:%ld,%s", t, vset);
459 safestrncpy(vset, lostr, sizeof vset);
461 /* end trim-o-matic code */
469 snprintf(&vset[tmp], (sizeof vset) - tmp,
473 snprintf(&vset[tmp], (sizeof vset) - tmp,
482 /* Decide which message set we're manipulating */
484 case ctdlsetseen_seen:
485 safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
487 case ctdlsetseen_answered:
488 safestrncpy(vbuf.v_answered, vset,
489 sizeof vbuf.v_answered);
494 /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
496 CtdlSetRelationship(&vbuf,
497 ((which_user != NULL) ? which_user : &CC->user),
498 ((which_room != NULL) ? which_room : &CC->room)
504 * API function to perform an operation for each qualifying message in the
505 * current room. (Returns the number of messages processed.)
507 int CtdlForEachMessage(int mode, long ref,
509 struct CtdlMessage *compare,
510 void (*CallBack) (long, void *),
516 struct cdbdata *cdbfr;
517 long *msglist = NULL;
519 int num_processed = 0;
522 struct CtdlMessage *msg;
525 int printed_lastold = 0;
527 /* Learn about the user and room in question */
529 getuser(&CC->user, CC->curr_user);
530 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
532 /* Load the message list */
533 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
535 msglist = (long *) cdbfr->ptr;
536 cdbfr->ptr = NULL; /* CtdlForEachMessage() now owns this memory */
537 num_msgs = cdbfr->len / sizeof(long);
540 return 0; /* No messages at all? No further action. */
545 * Now begin the traversal.
547 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
549 /* If the caller is looking for a specific MIME type, filter
550 * out all messages which are not of the type requested.
552 if (content_type != NULL) if (strlen(content_type) > 0) {
554 /* This call to GetMetaData() sits inside this loop
555 * so that we only do the extra database read per msg
556 * if we need to. Doing the extra read all the time
557 * really kills the server. If we ever need to use
558 * metadata for another search criterion, we need to
559 * move the read somewhere else -- but still be smart
560 * enough to only do the read if the caller has
561 * specified something that will need it.
563 GetMetaData(&smi, msglist[a]);
565 if (strcasecmp(smi.meta_content_type, content_type)) {
571 num_msgs = sort_msglist(msglist, num_msgs);
573 /* If a template was supplied, filter out the messages which
574 * don't match. (This could induce some delays!)
577 if (compare != NULL) {
578 for (a = 0; a < num_msgs; ++a) {
579 msg = CtdlFetchMessage(msglist[a], 1);
581 if (CtdlMsgCmp(msg, compare)) {
584 CtdlFreeMessage(msg);
592 * Now iterate through the message list, according to the
593 * criteria supplied by the caller.
596 for (a = 0; a < num_msgs; ++a) {
597 thismsg = msglist[a];
598 if (mode == MSGS_ALL) {
602 is_seen = is_msg_in_sequence_set(
603 vbuf.v_seen, thismsg);
604 if (is_seen) lastold = thismsg;
610 || ((mode == MSGS_OLD) && (is_seen))
611 || ((mode == MSGS_NEW) && (!is_seen))
612 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
613 || ((mode == MSGS_FIRST) && (a < ref))
614 || ((mode == MSGS_GT) && (thismsg > ref))
615 || ((mode == MSGS_EQ) && (thismsg == ref))
618 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
620 CallBack(lastold, userdata);
624 if (CallBack) CallBack(thismsg, userdata);
628 free(msglist); /* Clean up */
629 return num_processed;
635 * cmd_msgs() - get list of message #'s in this room
636 * implements the MSGS server command using CtdlForEachMessage()
638 void cmd_msgs(char *cmdbuf)
647 int with_template = 0;
648 struct CtdlMessage *template = NULL;
649 int with_headers = 0;
651 extract_token(which, cmdbuf, 0, '|', sizeof which);
652 cm_ref = extract_int(cmdbuf, 1);
653 with_template = extract_int(cmdbuf, 2);
654 with_headers = extract_int(cmdbuf, 3);
658 if (!strncasecmp(which, "OLD", 3))
660 else if (!strncasecmp(which, "NEW", 3))
662 else if (!strncasecmp(which, "FIRST", 5))
664 else if (!strncasecmp(which, "LAST", 4))
666 else if (!strncasecmp(which, "GT", 2))
669 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
670 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
676 cprintf("%d Send template then receive message list\n",
678 template = (struct CtdlMessage *)
679 malloc(sizeof(struct CtdlMessage));
680 memset(template, 0, sizeof(struct CtdlMessage));
681 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
682 extract_token(tfield, buf, 0, '|', sizeof tfield);
683 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
684 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
685 if (!strcasecmp(tfield, msgkeys[i])) {
686 template->cm_fields[i] =
694 cprintf("%d \n", LISTING_FOLLOWS);
697 CtdlForEachMessage(mode,
701 (with_headers ? headers_listing : simple_listing),
704 if (template != NULL) CtdlFreeMessage(template);
712 * help_subst() - support routine for help file viewer
714 void help_subst(char *strbuf, char *source, char *dest)
719 while (p = pattern2(strbuf, source), (p >= 0)) {
720 strcpy(workbuf, &strbuf[p + strlen(source)]);
721 strcpy(&strbuf[p], dest);
722 strcat(strbuf, workbuf);
727 void do_help_subst(char *buffer)
731 help_subst(buffer, "^nodename", config.c_nodename);
732 help_subst(buffer, "^humannode", config.c_humannode);
733 help_subst(buffer, "^fqdn", config.c_fqdn);
734 help_subst(buffer, "^username", CC->user.fullname);
735 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
736 help_subst(buffer, "^usernum", buf2);
737 help_subst(buffer, "^sysadm", config.c_sysadm);
738 help_subst(buffer, "^variantname", CITADEL);
739 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
740 help_subst(buffer, "^maxsessions", buf2);
741 help_subst(buffer, "^bbsdir", ctdl_bbsbase_dir);
747 * memfmout() - Citadel text formatter and paginator.
748 * Although the original purpose of this routine was to format
749 * text to the reader's screen width, all we're really using it
750 * for here is to format text out to 80 columns before sending it
751 * to the client. The client software may reformat it again.
754 char *mptr, /* where are we going to get our text from? */
755 char subst, /* nonzero if we should do substitutions */
756 char *nl) /* string to terminate lines with */
764 static int width = 80;
769 c = 1; /* c is the current pos */
773 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
775 buffer[strlen(buffer) + 1] = 0;
776 buffer[strlen(buffer)] = ch;
779 if (buffer[0] == '^')
780 do_help_subst(buffer);
782 buffer[strlen(buffer) + 1] = 0;
784 strcpy(buffer, &buffer[1]);
792 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
795 if (((old == 13) || (old == 10)) && (isspace(real))) {
800 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
801 cprintf("%s%s", nl, aaa);
810 if ((strlen(aaa) + c) > (width - 5)) {
819 if ((ch == 13) || (ch == 10)) {
820 cprintf("%s%s", aaa, nl);
827 cprintf("%s%s", aaa, nl);
833 * Callback function for mime parser that simply lists the part
835 void list_this_part(char *name, char *filename, char *partnum, char *disp,
836 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
841 ma = (struct ma_info *)cbuserdata;
842 if (ma->is_ma == 0) {
843 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
844 name, filename, partnum, disp, cbtype, (long)length);
849 * Callback function for multipart prefix
851 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
852 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
857 ma = (struct ma_info *)cbuserdata;
858 if (!strcasecmp(cbtype, "multipart/alternative")) {
862 if (ma->is_ma == 0) {
863 cprintf("pref=%s|%s\n", partnum, cbtype);
868 * Callback function for multipart sufffix
870 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
871 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
876 ma = (struct ma_info *)cbuserdata;
877 if (ma->is_ma == 0) {
878 cprintf("suff=%s|%s\n", partnum, cbtype);
880 if (!strcasecmp(cbtype, "multipart/alternative")) {
887 * Callback function for mime parser that opens a section for downloading
889 void mime_download(char *name, char *filename, char *partnum, char *disp,
890 void *content, char *cbtype, char *cbcharset, size_t length,
891 char *encoding, void *cbuserdata)
894 /* Silently go away if there's already a download open... */
895 if (CC->download_fp != NULL)
898 /* ...or if this is not the desired section */
899 if (strcasecmp(CC->download_desired_section, partnum))
902 CC->download_fp = tmpfile();
903 if (CC->download_fp == NULL)
906 fwrite(content, length, 1, CC->download_fp);
907 fflush(CC->download_fp);
908 rewind(CC->download_fp);
910 OpenCmdResult(filename, cbtype);
916 * Load a message from disk into memory.
917 * This is used by CtdlOutputMsg() and other fetch functions.
919 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
920 * using the CtdlMessageFree() function.
922 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
924 struct cdbdata *dmsgtext;
925 struct CtdlMessage *ret = NULL;
929 cit_uint8_t field_header;
931 lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
933 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
934 if (dmsgtext == NULL) {
937 mptr = dmsgtext->ptr;
938 upper_bound = mptr + dmsgtext->len;
940 /* Parse the three bytes that begin EVERY message on disk.
941 * The first is always 0xFF, the on-disk magic number.
942 * The second is the anonymous/public type byte.
943 * The third is the format type byte (vari, fixed, or MIME).
948 "Message %ld appears to be corrupted.\n",
953 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
954 memset(ret, 0, sizeof(struct CtdlMessage));
956 ret->cm_magic = CTDLMESSAGE_MAGIC;
957 ret->cm_anon_type = *mptr++; /* Anon type byte */
958 ret->cm_format_type = *mptr++; /* Format type byte */
961 * The rest is zero or more arbitrary fields. Load them in.
962 * We're done when we encounter either a zero-length field or
963 * have just processed the 'M' (message text) field.
966 if (mptr >= upper_bound) {
969 field_header = *mptr++;
970 ret->cm_fields[field_header] = strdup(mptr);
972 while (*mptr++ != 0); /* advance to next field */
974 } while ((mptr < upper_bound) && (field_header != 'M'));
978 /* Always make sure there's something in the msg text field. If
979 * it's NULL, the message text is most likely stored separately,
980 * so go ahead and fetch that. Failing that, just set a dummy
981 * body so other code doesn't barf.
983 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
984 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
985 if (dmsgtext != NULL) {
986 ret->cm_fields['M'] = strdup(dmsgtext->ptr);
990 if (ret->cm_fields['M'] == NULL) {
991 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
994 /* Perform "before read" hooks (aborting if any return nonzero) */
995 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
996 CtdlFreeMessage(ret);
1005 * Returns 1 if the supplied pointer points to a valid Citadel message.
1006 * If the pointer is NULL or the magic number check fails, returns 0.
1008 int is_valid_message(struct CtdlMessage *msg) {
1011 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1012 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1020 * 'Destructor' for struct CtdlMessage
1022 void CtdlFreeMessage(struct CtdlMessage *msg)
1026 if (is_valid_message(msg) == 0) return;
1028 for (i = 0; i < 256; ++i)
1029 if (msg->cm_fields[i] != NULL) {
1030 free(msg->cm_fields[i]);
1033 msg->cm_magic = 0; /* just in case */
1039 * Pre callback function for multipart/alternative
1041 * NOTE: this differs from the standard behavior for a reason. Normally when
1042 * displaying multipart/alternative you want to show the _last_ usable
1043 * format in the message. Here we show the _first_ one, because it's
1044 * usually text/plain. Since this set of functions is designed for text
1045 * output to non-MIME-aware clients, this is the desired behavior.
1048 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1049 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1054 ma = (struct ma_info *)cbuserdata;
1055 lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1056 if (!strcasecmp(cbtype, "multipart/alternative")) {
1060 if (!strcasecmp(cbtype, "message/rfc822")) {
1066 * Post callback function for multipart/alternative
1068 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1069 void *content, char *cbtype, char *cbcharset, size_t length,
1070 char *encoding, void *cbuserdata)
1074 ma = (struct ma_info *)cbuserdata;
1075 lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1076 if (!strcasecmp(cbtype, "multipart/alternative")) {
1080 if (!strcasecmp(cbtype, "message/rfc822")) {
1086 * Inline callback function for mime parser that wants to display text
1088 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1089 void *content, char *cbtype, char *cbcharset, size_t length,
1090 char *encoding, void *cbuserdata)
1097 ma = (struct ma_info *)cbuserdata;
1100 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1101 partnum, filename, cbtype, (long)length);
1104 * If we're in the middle of a multipart/alternative scope and
1105 * we've already printed another section, skip this one.
1107 if ( (ma->is_ma) && (ma->did_print) ) {
1108 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1114 if ( (!strcasecmp(cbtype, "text/plain"))
1115 || (strlen(cbtype)==0) ) {
1118 client_write(wptr, length);
1119 if (wptr[length-1] != '\n') {
1126 if (!strcasecmp(cbtype, "text/html")) {
1127 ptr = html_to_ascii(content, length, 80, 0);
1129 client_write(ptr, wlen);
1130 if (ptr[wlen-1] != '\n') {
1137 if (ma->use_fo_hooks) {
1138 if (PerformFixedOutputHooks(cbtype, content, length)) {
1139 /* above function returns nonzero if it handled the part */
1144 if (strncasecmp(cbtype, "multipart/", 10)) {
1145 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1146 partnum, filename, cbtype, (long)length);
1152 * The client is elegant and sophisticated and wants to be choosy about
1153 * MIME content types, so figure out which multipart/alternative part
1154 * we're going to send.
1156 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1157 void *content, char *cbtype, char *cbcharset, size_t length,
1158 char *encoding, void *cbuserdata)
1164 ma = (struct ma_info *)cbuserdata;
1166 if (ma->is_ma > 0) {
1167 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1168 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1169 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1170 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1177 * Now that we've chosen our preferred part, output it.
1179 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1180 void *content, char *cbtype, char *cbcharset, size_t length,
1181 char *encoding, void *cbuserdata)
1185 int add_newline = 0;
1189 ma = (struct ma_info *)cbuserdata;
1191 /* This is not the MIME part you're looking for... */
1192 if (strcasecmp(partnum, ma->chosen_part)) return;
1194 /* If the content-type of this part is in our preferred formats
1195 * list, we can simply output it verbatim.
1197 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1198 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1199 if (!strcasecmp(buf, cbtype)) {
1200 /* Yeah! Go! W00t!! */
1202 text_content = (char *)content;
1203 if (text_content[length-1] != '\n') {
1207 cprintf("Content-type: %s", cbtype);
1208 if (strlen(cbcharset) > 0) {
1209 cprintf("; charset=%s", cbcharset);
1211 cprintf("\nContent-length: %d\n",
1212 (int)(length + add_newline) );
1213 if (strlen(encoding) > 0) {
1214 cprintf("Content-transfer-encoding: %s\n", encoding);
1217 cprintf("Content-transfer-encoding: 7bit\n");
1220 client_write(content, length);
1221 if (add_newline) cprintf("\n");
1226 /* No translations required or possible: output as text/plain */
1227 cprintf("Content-type: text/plain\n\n");
1228 fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1229 length, encoding, cbuserdata);
1234 char desired_section[64];
1241 * Callback function for
1243 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1244 void *content, char *cbtype, char *cbcharset, size_t length,
1245 char *encoding, void *cbuserdata)
1247 struct encapmsg *encap;
1249 encap = (struct encapmsg *)cbuserdata;
1251 /* Only proceed if this is the desired section... */
1252 if (!strcasecmp(encap->desired_section, partnum)) {
1253 encap->msglen = length;
1254 encap->msg = malloc(length + 2);
1255 memcpy(encap->msg, content, length);
1265 * Get a message off disk. (returns om_* values found in msgbase.h)
1268 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1269 int mode, /* how would you like that message? */
1270 int headers_only, /* eschew the message body? */
1271 int do_proto, /* do Citadel protocol responses? */
1272 int crlf, /* Use CRLF newlines instead of LF? */
1273 char *section /* NULL or a message/rfc822 section */
1275 struct CtdlMessage *TheMessage = NULL;
1276 int retcode = om_no_such_msg;
1277 struct encapmsg encap;
1279 lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n",
1281 (section ? section : "<>")
1284 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1285 if (do_proto) cprintf("%d Not logged in.\n",
1286 ERROR + NOT_LOGGED_IN);
1287 return(om_not_logged_in);
1290 /* FIXME: check message id against msglist for this room */
1293 * Fetch the message from disk. If we're in any sort of headers
1294 * only mode, request that we don't even bother loading the body
1297 if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1298 TheMessage = CtdlFetchMessage(msg_num, 0);
1301 TheMessage = CtdlFetchMessage(msg_num, 1);
1304 if (TheMessage == NULL) {
1305 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1306 ERROR + MESSAGE_NOT_FOUND, msg_num);
1307 return(om_no_such_msg);
1310 /* Here is the weird form of this command, to process only an
1311 * encapsulated message/rfc822 section.
1313 if (section) if (strlen(section)>0) if (strcmp(section, "0")) {
1314 memset(&encap, 0, sizeof encap);
1315 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1316 mime_parser(TheMessage->cm_fields['M'],
1318 *extract_encapsulated_message,
1319 NULL, NULL, (void *)&encap, 0
1321 CtdlFreeMessage(TheMessage);
1325 encap.msg[encap.msglen] = 0;
1326 TheMessage = convert_internet_message(encap.msg);
1327 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1329 /* Now we let it fall through to the bottom of this
1330 * function, because TheMessage now contains the
1331 * encapsulated message instead of the top-level
1332 * message. Isn't that neat?
1337 if (do_proto) cprintf("%d msg %ld has no part %s\n",
1338 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1339 retcode = om_no_such_msg;
1344 /* Ok, output the message now */
1345 retcode = CtdlOutputPreLoadedMsg(
1347 headers_only, do_proto, crlf);
1348 CtdlFreeMessage(TheMessage);
1355 * Get a message off disk. (returns om_* values found in msgbase.h)
1358 int CtdlOutputPreLoadedMsg(
1359 struct CtdlMessage *TheMessage,
1360 int mode, /* how would you like that message? */
1361 int headers_only, /* eschew the message body? */
1362 int do_proto, /* do Citadel protocol responses? */
1363 int crlf /* Use CRLF newlines instead of LF? */
1369 char display_name[256];
1371 char *nl; /* newline string */
1373 int subject_found = 0;
1376 /* Buffers needed for RFC822 translation. These are all filled
1377 * using functions that are bounds-checked, and therefore we can
1378 * make them substantially smaller than SIZ.
1386 char datestamp[100];
1388 lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1389 ((TheMessage == NULL) ? "NULL" : "not null"),
1390 mode, headers_only, do_proto, crlf);
1392 strcpy(mid, "unknown");
1393 nl = (crlf ? "\r\n" : "\n");
1395 if (!is_valid_message(TheMessage)) {
1397 "ERROR: invalid preloaded message for output\n");
1398 return(om_no_such_msg);
1401 /* Are we downloading a MIME component? */
1402 if (mode == MT_DOWNLOAD) {
1403 if (TheMessage->cm_format_type != FMT_RFC822) {
1405 cprintf("%d This is not a MIME message.\n",
1406 ERROR + ILLEGAL_VALUE);
1407 } else if (CC->download_fp != NULL) {
1408 if (do_proto) cprintf(
1409 "%d You already have a download open.\n",
1410 ERROR + RESOURCE_BUSY);
1412 /* Parse the message text component */
1413 mptr = TheMessage->cm_fields['M'];
1414 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1415 /* If there's no file open by this time, the requested
1416 * section wasn't found, so print an error
1418 if (CC->download_fp == NULL) {
1419 if (do_proto) cprintf(
1420 "%d Section %s not found.\n",
1421 ERROR + FILE_NOT_FOUND,
1422 CC->download_desired_section);
1425 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1428 /* now for the user-mode message reading loops */
1429 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1431 /* Does the caller want to skip the headers? */
1432 if (headers_only == HEADERS_NONE) goto START_TEXT;
1434 /* Tell the client which format type we're using. */
1435 if ( (mode == MT_CITADEL) && (do_proto) ) {
1436 cprintf("type=%d\n", TheMessage->cm_format_type);
1439 /* nhdr=yes means that we're only displaying headers, no body */
1440 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1441 && (mode == MT_CITADEL)
1444 cprintf("nhdr=yes\n");
1447 /* begin header processing loop for Citadel message format */
1449 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1451 safestrncpy(display_name, "<unknown>", sizeof display_name);
1452 if (TheMessage->cm_fields['A']) {
1453 strcpy(buf, TheMessage->cm_fields['A']);
1454 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1455 safestrncpy(display_name, "****", sizeof display_name);
1457 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1458 safestrncpy(display_name, "anonymous", sizeof display_name);
1461 safestrncpy(display_name, buf, sizeof display_name);
1463 if ((is_room_aide())
1464 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1465 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1466 size_t tmp = strlen(display_name);
1467 snprintf(&display_name[tmp],
1468 sizeof display_name - tmp,
1473 /* Don't show Internet address for users on the
1474 * local Citadel network.
1477 if (TheMessage->cm_fields['N'] != NULL)
1478 if (strlen(TheMessage->cm_fields['N']) > 0)
1479 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1483 /* Now spew the header fields in the order we like them. */
1484 safestrncpy(allkeys, FORDER, sizeof allkeys);
1485 for (i=0; i<strlen(allkeys); ++i) {
1486 k = (int) allkeys[i];
1488 if ( (TheMessage->cm_fields[k] != NULL)
1489 && (msgkeys[k] != NULL) ) {
1491 if (do_proto) cprintf("%s=%s\n",
1495 else if ((k == 'F') && (suppress_f)) {
1498 /* Masquerade display name if needed */
1500 if (do_proto) cprintf("%s=%s\n",
1502 TheMessage->cm_fields[k]
1511 /* begin header processing loop for RFC822 transfer format */
1516 strcpy(snode, NODENAME);
1517 strcpy(lnode, HUMANNODE);
1518 if (mode == MT_RFC822) {
1519 for (i = 0; i < 256; ++i) {
1520 if (TheMessage->cm_fields[i]) {
1521 mptr = TheMessage->cm_fields[i];
1524 safestrncpy(luser, mptr, sizeof luser);
1525 safestrncpy(suser, mptr, sizeof suser);
1527 else if (i == 'Y') {
1528 cprintf("CC: %s%s", mptr, nl);
1530 else if (i == 'U') {
1531 cprintf("Subject: %s%s", mptr, nl);
1535 safestrncpy(mid, mptr, sizeof mid);
1537 safestrncpy(lnode, mptr, sizeof lnode);
1539 safestrncpy(fuser, mptr, sizeof fuser);
1540 /* else if (i == 'O')
1541 cprintf("X-Citadel-Room: %s%s",
1544 safestrncpy(snode, mptr, sizeof snode);
1546 cprintf("To: %s%s", mptr, nl);
1547 else if (i == 'T') {
1548 datestring(datestamp, sizeof datestamp,
1549 atol(mptr), DATESTRING_RFC822);
1550 cprintf("Date: %s%s", datestamp, nl);
1554 if (subject_found == 0) {
1555 cprintf("Subject: (no subject)%s", nl);
1559 for (i=0; i<strlen(suser); ++i) {
1560 suser[i] = tolower(suser[i]);
1561 if (!isalnum(suser[i])) suser[i]='_';
1564 if (mode == MT_RFC822) {
1565 if (!strcasecmp(snode, NODENAME)) {
1566 safestrncpy(snode, FQDN, sizeof snode);
1569 /* Construct a fun message id */
1570 cprintf("Message-ID: <%s", mid);
1571 if (strchr(mid, '@')==NULL) {
1572 cprintf("@%s", snode);
1576 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1577 cprintf("From: \"----\" <x@x.org>%s", nl);
1579 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1580 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1582 else if (strlen(fuser) > 0) {
1583 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1586 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1589 cprintf("Organization: %s%s", lnode, nl);
1591 /* Blank line signifying RFC822 end-of-headers */
1592 if (TheMessage->cm_format_type != FMT_RFC822) {
1597 /* end header processing loop ... at this point, we're in the text */
1599 if (headers_only == HEADERS_FAST) goto DONE;
1600 mptr = TheMessage->cm_fields['M'];
1602 /* Tell the client about the MIME parts in this message */
1603 if (TheMessage->cm_format_type == FMT_RFC822) {
1604 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1605 memset(&ma, 0, sizeof(struct ma_info));
1606 mime_parser(mptr, NULL,
1607 (do_proto ? *list_this_part : NULL),
1608 (do_proto ? *list_this_pref : NULL),
1609 (do_proto ? *list_this_suff : NULL),
1612 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1613 char *start_of_text = NULL;
1614 start_of_text = strstr(mptr, "\n\r\n");
1615 if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1616 if (start_of_text == NULL) start_of_text = mptr;
1618 start_of_text = strstr(start_of_text, "\n");
1620 while (ch=*mptr, ch!=0) {
1624 else switch(headers_only) {
1626 if (mptr >= start_of_text) {
1627 if (ch == 10) cprintf("%s", nl);
1628 else cprintf("%c", ch);
1632 if (mptr < start_of_text) {
1633 if (ch == 10) cprintf("%s", nl);
1634 else cprintf("%c", ch);
1638 if (ch == 10) cprintf("%s", nl);
1639 else cprintf("%c", ch);
1648 if (headers_only == HEADERS_ONLY) {
1652 /* signify start of msg text */
1653 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1654 if (do_proto) cprintf("text\n");
1657 /* If the format type on disk is 1 (fixed-format), then we want
1658 * everything to be output completely literally ... regardless of
1659 * what message transfer format is in use.
1661 if (TheMessage->cm_format_type == FMT_FIXED) {
1662 if (mode == MT_MIME) {
1663 cprintf("Content-type: text/plain\n\n");
1666 while (ch = *mptr++, ch > 0) {
1669 if ((ch == 10) || (strlen(buf) > 250)) {
1670 cprintf("%s%s", buf, nl);
1673 buf[strlen(buf) + 1] = 0;
1674 buf[strlen(buf)] = ch;
1677 if (strlen(buf) > 0)
1678 cprintf("%s%s", buf, nl);
1681 /* If the message on disk is format 0 (Citadel vari-format), we
1682 * output using the formatter at 80 columns. This is the final output
1683 * form if the transfer format is RFC822, but if the transfer format
1684 * is Citadel proprietary, it'll still work, because the indentation
1685 * for new paragraphs is correct and the client will reformat the
1686 * message to the reader's screen width.
1688 if (TheMessage->cm_format_type == FMT_CITADEL) {
1689 if (mode == MT_MIME) {
1690 cprintf("Content-type: text/x-citadel-variformat\n\n");
1692 memfmout(mptr, 0, nl);
1695 /* If the message on disk is format 4 (MIME), we've gotta hand it
1696 * off to the MIME parser. The client has already been told that
1697 * this message is format 1 (fixed format), so the callback function
1698 * we use will display those parts as-is.
1700 if (TheMessage->cm_format_type == FMT_RFC822) {
1701 memset(&ma, 0, sizeof(struct ma_info));
1703 if (mode == MT_MIME) {
1704 ma.use_fo_hooks = 0;
1705 strcpy(ma.chosen_part, "1");
1706 mime_parser(mptr, NULL,
1707 *choose_preferred, *fixed_output_pre,
1708 *fixed_output_post, (void *)&ma, 0);
1709 mime_parser(mptr, NULL,
1710 *output_preferred, NULL, NULL, (void *)&ma, 0);
1713 ma.use_fo_hooks = 1;
1714 mime_parser(mptr, NULL,
1715 *fixed_output, *fixed_output_pre,
1716 *fixed_output_post, (void *)&ma, 0);
1721 DONE: /* now we're done */
1722 if (do_proto) cprintf("000\n");
1729 * display a message (mode 0 - Citadel proprietary)
1731 void cmd_msg0(char *cmdbuf)
1734 int headers_only = HEADERS_ALL;
1736 msgid = extract_long(cmdbuf, 0);
1737 headers_only = extract_int(cmdbuf, 1);
1739 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1745 * display a message (mode 2 - RFC822)
1747 void cmd_msg2(char *cmdbuf)
1750 int headers_only = HEADERS_ALL;
1752 msgid = extract_long(cmdbuf, 0);
1753 headers_only = extract_int(cmdbuf, 1);
1755 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1761 * display a message (mode 3 - IGnet raw format - internal programs only)
1763 void cmd_msg3(char *cmdbuf)
1766 struct CtdlMessage *msg;
1769 if (CC->internal_pgm == 0) {
1770 cprintf("%d This command is for internal programs only.\n",
1771 ERROR + HIGHER_ACCESS_REQUIRED);
1775 msgnum = extract_long(cmdbuf, 0);
1776 msg = CtdlFetchMessage(msgnum, 1);
1778 cprintf("%d Message %ld not found.\n",
1779 ERROR + MESSAGE_NOT_FOUND, msgnum);
1783 serialize_message(&smr, msg);
1784 CtdlFreeMessage(msg);
1787 cprintf("%d Unable to serialize message\n",
1788 ERROR + INTERNAL_ERROR);
1792 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1793 client_write((char *)smr.ser, (int)smr.len);
1800 * Display a message using MIME content types
1802 void cmd_msg4(char *cmdbuf)
1807 msgid = extract_long(cmdbuf, 0);
1808 extract_token(section, cmdbuf, 1, '|', sizeof section);
1809 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1815 * Client tells us its preferred message format(s)
1817 void cmd_msgp(char *cmdbuf)
1819 safestrncpy(CC->preferred_formats, cmdbuf,
1820 sizeof(CC->preferred_formats));
1821 cprintf("%d ok\n", CIT_OK);
1826 * Open a component of a MIME message as a download file
1828 void cmd_opna(char *cmdbuf)
1831 char desired_section[128];
1833 msgid = extract_long(cmdbuf, 0);
1834 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1835 safestrncpy(CC->download_desired_section, desired_section,
1836 sizeof CC->download_desired_section);
1837 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
1842 * Save a message pointer into a specified room
1843 * (Returns 0 for success, nonzero for failure)
1844 * roomname may be NULL to use the current room
1846 * Note that the 'supplied_msg' field may be set to NULL, in which case
1847 * the message will be fetched from disk, by number, if we need to perform
1848 * replication checks. This adds an additional database read, so if the
1849 * caller already has the message in memory then it should be supplied.
1851 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid, int do_repl_check,
1852 struct CtdlMessage *supplied_msg) {
1854 char hold_rm[ROOMNAMELEN];
1855 struct cdbdata *cdbfr;
1858 long highest_msg = 0L;
1859 struct CtdlMessage *msg = NULL;
1861 /*lprintf(CTDL_DEBUG,
1862 "CtdlSaveMsgPointerInRoom(room=%s, msgid=%ld, repl=%d)\n",
1863 roomname, msgid, do_repl_check);*/
1865 strcpy(hold_rm, CC->room.QRname);
1867 /* Now the regular stuff */
1868 if (lgetroom(&CC->room,
1869 ((roomname != NULL) ? roomname : CC->room.QRname) )
1871 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
1872 return(ERROR + ROOM_NOT_FOUND);
1875 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
1876 if (cdbfr == NULL) {
1880 msglist = (long *) cdbfr->ptr;
1881 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
1882 num_msgs = cdbfr->len / sizeof(long);
1886 /* Make sure the message doesn't already exist in this room. It
1887 * is absolutely taboo to have more than one reference to the same
1888 * message in a room.
1890 if (num_msgs > 0) for (i=0; i<num_msgs; ++i) {
1891 if (msglist[i] == msgid) {
1892 lputroom(&CC->room); /* unlock the room */
1893 getroom(&CC->room, hold_rm);
1895 return(ERROR + ALREADY_EXISTS);
1899 /* Now add the new message */
1901 msglist = realloc(msglist, (num_msgs * sizeof(long)));
1903 if (msglist == NULL) {
1904 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
1906 msglist[num_msgs - 1] = msgid;
1908 /* Sort the message list, so all the msgid's are in order */
1909 num_msgs = sort_msglist(msglist, num_msgs);
1911 /* Determine the highest message number */
1912 highest_msg = msglist[num_msgs - 1];
1914 /* Write it back to disk. */
1915 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
1916 msglist, (int)(num_msgs * sizeof(long)));
1918 /* Free up the memory we used. */
1921 /* Update the highest-message pointer and unlock the room. */
1922 CC->room.QRhighest = highest_msg;
1923 lputroom(&CC->room);
1925 /* Perform replication checks if necessary */
1926 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
1927 if (supplied_msg != NULL) {
1931 msg = CtdlFetchMessage(msgid, 0);
1935 ReplicationChecks(msg);
1940 /* If the message has an Exclusive ID, index that... */
1942 if (msg->cm_fields['E'] != NULL) {
1943 index_message_by_euid(msg->cm_fields['E'],
1948 /* Free up the memory we may have allocated */
1949 if ( (msg != NULL) && (msg != supplied_msg) ) {
1950 CtdlFreeMessage(msg);
1953 /* Go back to the room we were in before we wandered here... */
1954 getroom(&CC->room, hold_rm);
1956 /* Bump the reference count for this message. */
1957 AdjRefCount(msgid, +1);
1959 /* Return success. */
1966 * Message base operation to save a new message to the message store
1967 * (returns new message number)
1969 * This is the back end for CtdlSubmitMsg() and should not be directly
1970 * called by server-side modules.
1973 long send_message(struct CtdlMessage *msg) {
1981 /* Get a new message number */
1982 newmsgid = get_new_message_number();
1983 snprintf(msgidbuf, sizeof msgidbuf, "%ld@%s", newmsgid, config.c_fqdn);
1985 /* Generate an ID if we don't have one already */
1986 if (msg->cm_fields['I']==NULL) {
1987 msg->cm_fields['I'] = strdup(msgidbuf);
1990 /* If the message is big, set its body aside for storage elsewhere */
1991 if (msg->cm_fields['M'] != NULL) {
1992 if (strlen(msg->cm_fields['M']) > BIGMSG) {
1994 holdM = msg->cm_fields['M'];
1995 msg->cm_fields['M'] = NULL;
1999 /* Serialize our data structure for storage in the database */
2000 serialize_message(&smr, msg);
2003 msg->cm_fields['M'] = holdM;
2007 cprintf("%d Unable to serialize message\n",
2008 ERROR + INTERNAL_ERROR);
2012 /* Write our little bundle of joy into the message base */
2013 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2014 smr.ser, smr.len) < 0) {
2015 lprintf(CTDL_ERR, "Can't store message\n");
2019 cdb_store(CDB_BIGMSGS,
2029 /* Free the memory we used for the serialized message */
2032 /* Return the *local* message ID to the caller
2033 * (even if we're storing an incoming network message)
2041 * Serialize a struct CtdlMessage into the format used on disk and network.
2043 * This function loads up a "struct ser_ret" (defined in server.h) which
2044 * contains the length of the serialized message and a pointer to the
2045 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2047 void serialize_message(struct ser_ret *ret, /* return values */
2048 struct CtdlMessage *msg) /* unserialized msg */
2052 static char *forder = FORDER;
2054 if (is_valid_message(msg) == 0) return; /* self check */
2057 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2058 ret->len = ret->len +
2059 strlen(msg->cm_fields[(int)forder[i]]) + 2;
2061 lprintf(CTDL_DEBUG, "serialize_message() calling malloc(%ld)\n", (long)ret->len);
2062 ret->ser = malloc(ret->len);
2063 if (ret->ser == NULL) {
2069 ret->ser[1] = msg->cm_anon_type;
2070 ret->ser[2] = msg->cm_format_type;
2073 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2074 ret->ser[wlen++] = (char)forder[i];
2075 strcpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]]);
2076 wlen = wlen + strlen(msg->cm_fields[(int)forder[i]]) + 1;
2078 if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2079 (long)ret->len, (long)wlen);
2087 * Check to see if any messages already exist in the current room which
2088 * carry the same Exclusive ID as this one. If any are found, delete them.
2090 void ReplicationChecks(struct CtdlMessage *msg) {
2091 long old_msgnum = (-1L);
2093 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2095 lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2098 /* No exclusive id? Don't do anything. */
2099 if (msg == NULL) return;
2100 if (msg->cm_fields['E'] == NULL) return;
2101 if (strlen(msg->cm_fields['E']) == 0) return;
2102 /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2103 msg->cm_fields['E'], CC->room.QRname);*/
2105 old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2106 if (old_msgnum > 0L) {
2107 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2108 CtdlDeleteMessages(CC->room.QRname, old_msgnum, "", 0);
2115 * Save a message to disk and submit it into the delivery system.
2117 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2118 struct recptypes *recps, /* recipients (if mail) */
2119 char *force /* force a particular room? */
2121 char submit_filename[128];
2122 char generated_timestamp[32];
2123 char hold_rm[ROOMNAMELEN];
2124 char actual_rm[ROOMNAMELEN];
2125 char force_room[ROOMNAMELEN];
2126 char content_type[SIZ]; /* We have to learn this */
2127 char recipient[SIZ];
2130 struct ctdluser userbuf;
2132 struct MetaData smi;
2133 FILE *network_fp = NULL;
2134 static int seqnum = 1;
2135 struct CtdlMessage *imsg = NULL;
2138 char *hold_R, *hold_D;
2139 char *collected_addresses = NULL;
2140 struct addresses_to_be_filed *aptr = NULL;
2141 char *saved_rfc822_version = NULL;
2142 int qualified_for_journaling = 0;
2144 lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2145 if (is_valid_message(msg) == 0) return(-1); /* self check */
2147 /* If this message has no timestamp, we take the liberty of
2148 * giving it one, right now.
2150 if (msg->cm_fields['T'] == NULL) {
2151 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2152 msg->cm_fields['T'] = strdup(generated_timestamp);
2155 /* If this message has no path, we generate one.
2157 if (msg->cm_fields['P'] == NULL) {
2158 if (msg->cm_fields['A'] != NULL) {
2159 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2160 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
2161 if (isspace(msg->cm_fields['P'][a])) {
2162 msg->cm_fields['P'][a] = ' ';
2167 msg->cm_fields['P'] = strdup("unknown");
2171 if (force == NULL) {
2172 strcpy(force_room, "");
2175 strcpy(force_room, force);
2178 /* Learn about what's inside, because it's what's inside that counts */
2179 if (msg->cm_fields['M'] == NULL) {
2180 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2184 switch (msg->cm_format_type) {
2186 strcpy(content_type, "text/x-citadel-variformat");
2189 strcpy(content_type, "text/plain");
2192 strcpy(content_type, "text/plain");
2193 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type: ");
2195 safestrncpy(content_type, &mptr[14],
2196 sizeof content_type);
2197 for (a = 0; a < strlen(content_type); ++a) {
2198 if ((content_type[a] == ';')
2199 || (content_type[a] == ' ')
2200 || (content_type[a] == 13)
2201 || (content_type[a] == 10)) {
2202 content_type[a] = 0;
2208 /* Goto the correct room */
2209 lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CC->room.QRname : SENTITEMS);
2210 strcpy(hold_rm, CC->room.QRname);
2211 strcpy(actual_rm, CC->room.QRname);
2212 if (recps != NULL) {
2213 strcpy(actual_rm, SENTITEMS);
2216 /* If the user is a twit, move to the twit room for posting */
2218 if (CC->user.axlevel == 2) {
2219 strcpy(hold_rm, actual_rm);
2220 strcpy(actual_rm, config.c_twitroom);
2221 lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2225 /* ...or if this message is destined for Aide> then go there. */
2226 if (strlen(force_room) > 0) {
2227 strcpy(actual_rm, force_room);
2230 lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2231 if (strcasecmp(actual_rm, CC->room.QRname)) {
2232 /* getroom(&CC->room, actual_rm); */
2233 usergoto(actual_rm, 0, 1, NULL, NULL);
2237 * If this message has no O (room) field, generate one.
2239 if (msg->cm_fields['O'] == NULL) {
2240 msg->cm_fields['O'] = strdup(CC->room.QRname);
2243 /* Perform "before save" hooks (aborting if any return nonzero) */
2244 lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2245 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2248 * If this message has an Exclusive ID, and the room is replication
2249 * checking enabled, then do replication checks.
2251 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2252 ReplicationChecks(msg);
2255 /* Save it to disk */
2256 lprintf(CTDL_DEBUG, "Saving to disk\n");
2257 newmsgid = send_message(msg);
2258 if (newmsgid <= 0L) return(-5);
2260 /* Write a supplemental message info record. This doesn't have to
2261 * be a critical section because nobody else knows about this message
2264 lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2265 memset(&smi, 0, sizeof(struct MetaData));
2266 smi.meta_msgnum = newmsgid;
2267 smi.meta_refcount = 0;
2268 safestrncpy(smi.meta_content_type, content_type,
2269 sizeof smi.meta_content_type);
2272 * Measure how big this message will be when rendered as RFC822.
2273 * We do this for two reasons:
2274 * 1. We need the RFC822 length for the new metadata record, so the
2275 * POP and IMAP services don't have to calculate message lengths
2276 * while the user is waiting (multiplied by potentially hundreds
2277 * or thousands of messages).
2278 * 2. If journaling is enabled, we will need an RFC822 version of the
2279 * message to attach to the journalized copy.
2281 if (CC->redirect_buffer != NULL) {
2282 lprintf(CTDL_ALERT, "CC->redirect_buffer is not NULL during message submission!\n");
2285 CC->redirect_buffer = malloc(SIZ);
2286 CC->redirect_len = 0;
2287 CC->redirect_alloc = SIZ;
2288 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2289 smi.meta_rfc822_length = CC->redirect_len;
2290 saved_rfc822_version = CC->redirect_buffer;
2291 CC->redirect_buffer = NULL;
2292 CC->redirect_len = 0;
2293 CC->redirect_alloc = 0;
2297 /* Now figure out where to store the pointers */
2298 lprintf(CTDL_DEBUG, "Storing pointers\n");
2300 /* If this is being done by the networker delivering a private
2301 * message, we want to BYPASS saving the sender's copy (because there
2302 * is no local sender; it would otherwise go to the Trashcan).
2304 if ((!CC->internal_pgm) || (recps == NULL)) {
2305 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2306 lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2307 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2311 /* For internet mail, drop a copy in the outbound queue room */
2313 if (recps->num_internet > 0) {
2314 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2317 /* If other rooms are specified, drop them there too. */
2319 if (recps->num_room > 0)
2320 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2321 extract_token(recipient, recps->recp_room, i,
2322 '|', sizeof recipient);
2323 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2324 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2327 /* Bump this user's messages posted counter. */
2328 lprintf(CTDL_DEBUG, "Updating user\n");
2329 lgetuser(&CC->user, CC->curr_user);
2330 CC->user.posted = CC->user.posted + 1;
2331 lputuser(&CC->user);
2333 /* If this is private, local mail, make a copy in the
2334 * recipient's mailbox and bump the reference count.
2337 if (recps->num_local > 0)
2338 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2339 extract_token(recipient, recps->recp_local, i,
2340 '|', sizeof recipient);
2341 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2343 if (getuser(&userbuf, recipient) == 0) {
2344 MailboxName(actual_rm, sizeof actual_rm,
2345 &userbuf, MAILROOM);
2346 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2347 BumpNewMailCounter(userbuf.usernum);
2350 lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2351 CtdlSaveMsgPointerInRoom(config.c_aideroom,
2356 /* Perform "after save" hooks */
2357 lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2358 PerformMessageHooks(msg, EVT_AFTERSAVE);
2360 /* For IGnet mail, we have to save a new copy into the spooler for
2361 * each recipient, with the R and D fields set to the recipient and
2362 * destination-node. This has two ugly side effects: all other
2363 * recipients end up being unlisted in this recipient's copy of the
2364 * message, and it has to deliver multiple messages to the same
2365 * node. We'll revisit this again in a year or so when everyone has
2366 * a network spool receiver that can handle the new style messages.
2369 if (recps->num_ignet > 0)
2370 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2371 extract_token(recipient, recps->recp_ignet, i,
2372 '|', sizeof recipient);
2374 hold_R = msg->cm_fields['R'];
2375 hold_D = msg->cm_fields['D'];
2376 msg->cm_fields['R'] = malloc(SIZ);
2377 msg->cm_fields['D'] = malloc(128);
2378 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2379 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2381 serialize_message(&smr, msg);
2383 snprintf(submit_filename, sizeof submit_filename,
2384 "%s/netmail.%04lx.%04x.%04x",
2386 (long) getpid(), CC->cs_pid, ++seqnum);
2387 network_fp = fopen(submit_filename, "wb+");
2388 if (network_fp != NULL) {
2389 fwrite(smr.ser, smr.len, 1, network_fp);
2395 free(msg->cm_fields['R']);
2396 free(msg->cm_fields['D']);
2397 msg->cm_fields['R'] = hold_R;
2398 msg->cm_fields['D'] = hold_D;
2401 /* Go back to the room we started from */
2402 lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2403 if (strcasecmp(hold_rm, CC->room.QRname))
2404 /* getroom(&CC->room, hold_rm); */
2405 usergoto(hold_rm, 0, 1, NULL, NULL);
2407 /* For internet mail, generate delivery instructions.
2408 * Yes, this is recursive. Deal with it. Infinite recursion does
2409 * not happen because the delivery instructions message does not
2410 * contain a recipient.
2413 if (recps->num_internet > 0) {
2414 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2415 instr = malloc(SIZ * 2);
2416 snprintf(instr, SIZ * 2,
2417 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2419 SPOOLMIME, newmsgid, (long)time(NULL),
2420 msg->cm_fields['A'], msg->cm_fields['N']
2423 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2424 size_t tmp = strlen(instr);
2425 extract_token(recipient, recps->recp_internet,
2426 i, '|', sizeof recipient);
2427 snprintf(&instr[tmp], SIZ * 2 - tmp,
2428 "remote|%s|0||\n", recipient);
2431 imsg = malloc(sizeof(struct CtdlMessage));
2432 memset(imsg, 0, sizeof(struct CtdlMessage));
2433 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2434 imsg->cm_anon_type = MES_NORMAL;
2435 imsg->cm_format_type = FMT_RFC822;
2436 imsg->cm_fields['A'] = strdup("Citadel");
2437 imsg->cm_fields['J'] = strdup("do not journal");
2438 imsg->cm_fields['M'] = instr;
2439 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2440 CtdlFreeMessage(imsg);
2444 * Any addresses to harvest for someone's address book?
2446 if ( (CC->logged_in) && (recps != NULL) ) {
2447 collected_addresses = harvest_collected_addresses(msg);
2450 if (collected_addresses != NULL) {
2451 begin_critical_section(S_ATBF);
2452 aptr = (struct addresses_to_be_filed *)
2453 malloc(sizeof(struct addresses_to_be_filed));
2455 MailboxName(actual_rm, sizeof actual_rm,
2456 &CC->user, USERCONTACTSROOM);
2457 aptr->roomname = strdup(actual_rm);
2458 aptr->collected_addresses = collected_addresses;
2460 end_critical_section(S_ATBF);
2464 * Determine whether this message qualifies for journaling.
2466 if (msg->cm_fields['J'] != NULL) {
2467 qualified_for_journaling = 0;
2470 if (recps == NULL) {
2471 qualified_for_journaling = config.c_journal_pubmsgs;
2473 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2474 qualified_for_journaling = config.c_journal_email;
2477 qualified_for_journaling = config.c_journal_pubmsgs;
2482 * Do we have to perform journaling? If so, hand off the saved
2483 * RFC822 version will be handed off to the journaler for background
2484 * submit. Otherwise, we have to free the memory ourselves.
2486 if (saved_rfc822_version != NULL) {
2487 if (qualified_for_journaling) {
2488 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2491 free(saved_rfc822_version);
2504 * Convenience function for generating small administrative messages.
2506 void quickie_message(char *from, char *to, char *room, char *text,
2507 int format_type, char *subject)
2509 struct CtdlMessage *msg;
2510 struct recptypes *recp = NULL;
2512 msg = malloc(sizeof(struct CtdlMessage));
2513 memset(msg, 0, sizeof(struct CtdlMessage));
2514 msg->cm_magic = CTDLMESSAGE_MAGIC;
2515 msg->cm_anon_type = MES_NORMAL;
2516 msg->cm_format_type = format_type;
2517 msg->cm_fields['A'] = strdup(from);
2518 if (room != NULL) msg->cm_fields['O'] = strdup(room);
2519 msg->cm_fields['N'] = strdup(NODENAME);
2521 msg->cm_fields['R'] = strdup(to);
2522 recp = validate_recipients(to);
2524 if (subject != NULL) {
2525 msg->cm_fields['U'] = strdup(subject);
2527 msg->cm_fields['M'] = strdup(text);
2529 CtdlSubmitMsg(msg, recp, room);
2530 CtdlFreeMessage(msg);
2531 if (recp != NULL) free(recp);
2537 * Back end function used by CtdlMakeMessage() and similar functions
2539 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2540 size_t maxlen, /* maximum message length */
2541 char *exist, /* if non-null, append to it;
2542 exist is ALWAYS freed */
2543 int crlf /* CRLF newlines instead of LF */
2547 size_t message_len = 0;
2548 size_t buffer_len = 0;
2554 if (exist == NULL) {
2561 message_len = strlen(exist);
2562 buffer_len = message_len + 4096;
2563 m = realloc(exist, buffer_len);
2570 /* flush the input if we have nowhere to store it */
2575 /* read in the lines of message text one by one */
2577 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2578 if (!strcmp(buf, terminator)) finished = 1;
2580 strcat(buf, "\r\n");
2586 if ( (!flushing) && (!finished) ) {
2587 /* Measure the line */
2588 linelen = strlen(buf);
2590 /* augment the buffer if we have to */
2591 if ((message_len + linelen) >= buffer_len) {
2592 ptr = realloc(m, (buffer_len * 2) );
2593 if (ptr == NULL) { /* flush if can't allocate */
2596 buffer_len = (buffer_len * 2);
2598 lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2602 /* Add the new line to the buffer. NOTE: this loop must avoid
2603 * using functions like strcat() and strlen() because they
2604 * traverse the entire buffer upon every call, and doing that
2605 * for a multi-megabyte message slows it down beyond usability.
2607 strcpy(&m[message_len], buf);
2608 message_len += linelen;
2611 /* if we've hit the max msg length, flush the rest */
2612 if (message_len >= maxlen) flushing = 1;
2614 } while (!finished);
2622 * Build a binary message to be saved on disk.
2623 * (NOTE: if you supply 'preformatted_text', the buffer you give it
2624 * will become part of the message. This means you are no longer
2625 * responsible for managing that memory -- it will be freed along with
2626 * the rest of the fields when CtdlFreeMessage() is called.)
2629 struct CtdlMessage *CtdlMakeMessage(
2630 struct ctdluser *author, /* author's user structure */
2631 char *recipient, /* NULL if it's not mail */
2632 char *recp_cc, /* NULL if it's not mail */
2633 char *room, /* room where it's going */
2634 int type, /* see MES_ types in header file */
2635 int format_type, /* variformat, plain text, MIME... */
2636 char *fake_name, /* who we're masquerading as */
2637 char *subject, /* Subject (optional) */
2638 char *supplied_euid, /* ...or NULL if this is irrelevant */
2639 char *preformatted_text /* ...or NULL to read text from client */
2641 char dest_node[SIZ];
2643 struct CtdlMessage *msg;
2645 msg = malloc(sizeof(struct CtdlMessage));
2646 memset(msg, 0, sizeof(struct CtdlMessage));
2647 msg->cm_magic = CTDLMESSAGE_MAGIC;
2648 msg->cm_anon_type = type;
2649 msg->cm_format_type = format_type;
2651 /* Don't confuse the poor folks if it's not routed mail. */
2652 strcpy(dest_node, "");
2657 snprintf(buf, sizeof buf, "cit%ld", author->usernum); /* Path */
2658 msg->cm_fields['P'] = strdup(buf);
2660 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
2661 msg->cm_fields['T'] = strdup(buf);
2663 if (fake_name[0]) /* author */
2664 msg->cm_fields['A'] = strdup(fake_name);
2666 msg->cm_fields['A'] = strdup(author->fullname);
2668 if (CC->room.QRflags & QR_MAILBOX) { /* room */
2669 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2672 msg->cm_fields['O'] = strdup(CC->room.QRname);
2675 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
2676 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
2678 if (recipient[0] != 0) {
2679 msg->cm_fields['R'] = strdup(recipient);
2681 if (recp_cc[0] != 0) {
2682 msg->cm_fields['Y'] = strdup(recp_cc);
2684 if (dest_node[0] != 0) {
2685 msg->cm_fields['D'] = strdup(dest_node);
2688 if ( (author == &CC->user) && (strlen(CC->cs_inet_email) > 0) ) {
2689 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2692 if (subject != NULL) {
2694 if (strlen(subject) > 0) {
2695 msg->cm_fields['U'] = strdup(subject);
2699 if (supplied_euid != NULL) {
2700 msg->cm_fields['E'] = strdup(supplied_euid);
2703 if (preformatted_text != NULL) {
2704 msg->cm_fields['M'] = preformatted_text;
2707 msg->cm_fields['M'] = CtdlReadMessageBody("000",
2708 config.c_maxmsglen, NULL, 0);
2716 * Check to see whether we have permission to post a message in the current
2717 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
2718 * returns 0 on success.
2720 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
2722 if (!(CC->logged_in)) {
2723 snprintf(errmsgbuf, n, "Not logged in.");
2724 return (ERROR + NOT_LOGGED_IN);
2727 if ((CC->user.axlevel < 2)
2728 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
2729 snprintf(errmsgbuf, n, "Need to be validated to enter "
2730 "(except in %s> to sysop)", MAILROOM);
2731 return (ERROR + HIGHER_ACCESS_REQUIRED);
2734 if ((CC->user.axlevel < 4)
2735 && (CC->room.QRflags & QR_NETWORK)) {
2736 snprintf(errmsgbuf, n, "Need net privileges to enter here.");
2737 return (ERROR + HIGHER_ACCESS_REQUIRED);
2740 if ((CC->user.axlevel < 6)
2741 && (CC->room.QRflags & QR_READONLY)) {
2742 snprintf(errmsgbuf, n, "Sorry, this is a read-only room.");
2743 return (ERROR + HIGHER_ACCESS_REQUIRED);
2746 strcpy(errmsgbuf, "Ok");
2752 * Check to see if the specified user has Internet mail permission
2753 * (returns nonzero if permission is granted)
2755 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
2757 /* Do not allow twits to send Internet mail */
2758 if (who->axlevel <= 2) return(0);
2760 /* Globally enabled? */
2761 if (config.c_restrict == 0) return(1);
2763 /* User flagged ok? */
2764 if (who->flags & US_INTERNET) return(2);
2766 /* Aide level access? */
2767 if (who->axlevel >= 6) return(3);
2769 /* No mail for you! */
2775 * Validate recipients, count delivery types and errors, and handle aliasing
2776 * FIXME check for dupes!!!!!
2777 * Returns 0 if all addresses are ok, -1 if no addresses were specified,
2778 * or the number of addresses found invalid.
2780 struct recptypes *validate_recipients(char *supplied_recipients) {
2781 struct recptypes *ret;
2782 char recipients[SIZ];
2783 char this_recp[256];
2784 char this_recp_cooked[256];
2790 struct ctdluser tempUS;
2791 struct ctdlroom tempQR;
2795 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
2796 if (ret == NULL) return(NULL);
2797 memset(ret, 0, sizeof(struct recptypes));
2800 ret->num_internet = 0;
2805 if (supplied_recipients == NULL) {
2806 strcpy(recipients, "");
2809 safestrncpy(recipients, supplied_recipients, sizeof recipients);
2812 /* Change all valid separator characters to commas */
2813 for (i=0; i<strlen(recipients); ++i) {
2814 if ((recipients[i] == ';') || (recipients[i] == '|')) {
2815 recipients[i] = ',';
2819 /* Now start extracting recipients... */
2821 while (strlen(recipients) > 0) {
2823 for (i=0; i<=strlen(recipients); ++i) {
2824 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
2825 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
2826 safestrncpy(this_recp, recipients, i+1);
2828 if (recipients[i] == ',') {
2829 strcpy(recipients, &recipients[i+1]);
2832 strcpy(recipients, "");
2839 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
2841 mailtype = alias(this_recp);
2842 mailtype = alias(this_recp);
2843 mailtype = alias(this_recp);
2844 for (j=0; j<=strlen(this_recp); ++j) {
2845 if (this_recp[j]=='_') {
2846 this_recp_cooked[j] = ' ';
2849 this_recp_cooked[j] = this_recp[j];
2855 if (!strcasecmp(this_recp, "sysop")) {
2857 strcpy(this_recp, config.c_aideroom);
2858 if (strlen(ret->recp_room) > 0) {
2859 strcat(ret->recp_room, "|");
2861 strcat(ret->recp_room, this_recp);
2863 else if (getuser(&tempUS, this_recp) == 0) {
2865 strcpy(this_recp, tempUS.fullname);
2866 if (strlen(ret->recp_local) > 0) {
2867 strcat(ret->recp_local, "|");
2869 strcat(ret->recp_local, this_recp);
2871 else if (getuser(&tempUS, this_recp_cooked) == 0) {
2873 strcpy(this_recp, tempUS.fullname);
2874 if (strlen(ret->recp_local) > 0) {
2875 strcat(ret->recp_local, "|");
2877 strcat(ret->recp_local, this_recp);
2879 else if ( (!strncasecmp(this_recp, "room_", 5))
2880 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
2882 if (strlen(ret->recp_room) > 0) {
2883 strcat(ret->recp_room, "|");
2885 strcat(ret->recp_room, &this_recp_cooked[5]);
2893 /* Yes, you're reading this correctly: if the target
2894 * domain points back to the local system or an attached
2895 * Citadel directory, the address is invalid. That's
2896 * because if the address were valid, we would have
2897 * already translated it to a local address by now.
2899 if (IsDirectory(this_recp)) {
2904 ++ret->num_internet;
2905 if (strlen(ret->recp_internet) > 0) {
2906 strcat(ret->recp_internet, "|");
2908 strcat(ret->recp_internet, this_recp);
2913 if (strlen(ret->recp_ignet) > 0) {
2914 strcat(ret->recp_ignet, "|");
2916 strcat(ret->recp_ignet, this_recp);
2924 if (strlen(ret->errormsg) == 0) {
2925 snprintf(append, sizeof append,
2926 "Invalid recipient: %s",
2930 snprintf(append, sizeof append,
2933 if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
2934 strcat(ret->errormsg, append);
2938 if (strlen(ret->display_recp) == 0) {
2939 strcpy(append, this_recp);
2942 snprintf(append, sizeof append, ", %s",
2945 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
2946 strcat(ret->display_recp, append);
2951 if ((ret->num_local + ret->num_internet + ret->num_ignet +
2952 ret->num_room + ret->num_error) == 0) {
2953 ret->num_error = (-1);
2954 strcpy(ret->errormsg, "No recipients specified.");
2957 lprintf(CTDL_DEBUG, "validate_recipients()\n");
2958 lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
2959 lprintf(CTDL_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
2960 lprintf(CTDL_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
2961 lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
2962 lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
2970 * message entry - mode 0 (normal)
2972 void cmd_ent0(char *entargs)
2978 char supplied_euid[128];
2979 char masquerade_as[SIZ];
2981 int format_type = 0;
2982 char newusername[SIZ];
2983 struct CtdlMessage *msg;
2987 struct recptypes *valid = NULL;
2988 struct recptypes *valid_to = NULL;
2989 struct recptypes *valid_cc = NULL;
2990 struct recptypes *valid_bcc = NULL;
2997 post = extract_int(entargs, 0);
2998 extract_token(recp, entargs, 1, '|', sizeof recp);
2999 anon_flag = extract_int(entargs, 2);
3000 format_type = extract_int(entargs, 3);
3001 extract_token(subject, entargs, 4, '|', sizeof subject);
3002 do_confirm = extract_int(entargs, 6);
3003 extract_token(cc, entargs, 7, '|', sizeof cc);
3004 extract_token(bcc, entargs, 8, '|', sizeof bcc);
3005 switch(CC->room.QRdefaultview) {
3008 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3011 supplied_euid[0] = 0;
3015 /* first check to make sure the request is valid. */
3017 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3019 cprintf("%d %s\n", err, errmsg);
3023 /* Check some other permission type things. */
3026 if (CC->user.axlevel < 6) {
3027 cprintf("%d You don't have permission to masquerade.\n",
3028 ERROR + HIGHER_ACCESS_REQUIRED);
3031 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3032 memset(CC->fake_postname, 0, sizeof(CC->fake_postname) );
3033 safestrncpy(CC->fake_postname, newusername,
3034 sizeof(CC->fake_postname) );
3035 cprintf("%d ok\n", CIT_OK);
3038 CC->cs_flags |= CS_POSTING;
3040 /* In the Mail> room we have to behave a little differently --
3041 * make sure the user has specified at least one recipient. Then
3042 * validate the recipient(s).
3044 if ( (CC->room.QRflags & QR_MAILBOX)
3045 && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) ) {
3047 if (CC->user.axlevel < 2) {
3048 strcpy(recp, "sysop");
3053 valid_to = validate_recipients(recp);
3054 if (valid_to->num_error > 0) {
3055 cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3060 valid_cc = validate_recipients(cc);
3061 if (valid_cc->num_error > 0) {
3062 cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3068 valid_bcc = validate_recipients(bcc);
3069 if (valid_bcc->num_error > 0) {
3070 cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3077 /* Recipient required, but none were specified */
3078 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3082 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3086 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3087 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3088 cprintf("%d You do not have permission "
3089 "to send Internet mail.\n",
3090 ERROR + HIGHER_ACCESS_REQUIRED);
3098 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)
3099 && (CC->user.axlevel < 4) ) {
3100 cprintf("%d Higher access required for network mail.\n",
3101 ERROR + HIGHER_ACCESS_REQUIRED);
3108 if ((RESTRICT_INTERNET == 1)
3109 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3110 && ((CC->user.flags & US_INTERNET) == 0)
3111 && (!CC->internal_pgm)) {
3112 cprintf("%d You don't have access to Internet mail.\n",
3113 ERROR + HIGHER_ACCESS_REQUIRED);
3122 /* Is this a room which has anonymous-only or anonymous-option? */
3123 anonymous = MES_NORMAL;
3124 if (CC->room.QRflags & QR_ANONONLY) {
3125 anonymous = MES_ANONONLY;
3127 if (CC->room.QRflags & QR_ANONOPT) {
3128 if (anon_flag == 1) { /* only if the user requested it */
3129 anonymous = MES_ANONOPT;
3133 if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3137 /* If we're only checking the validity of the request, return
3138 * success without creating the message.
3141 cprintf("%d %s\n", CIT_OK,
3142 ((valid_to != NULL) ? valid_to->display_recp : "") );
3149 /* We don't need these anymore because we'll do it differently below */
3154 /* Handle author masquerading */
3155 if (CC->fake_postname[0]) {
3156 strcpy(masquerade_as, CC->fake_postname);
3158 else if (CC->fake_username[0]) {
3159 strcpy(masquerade_as, CC->fake_username);
3162 strcpy(masquerade_as, "");
3165 /* Read in the message from the client. */
3167 cprintf("%d send message\n", START_CHAT_MODE);
3169 cprintf("%d send message\n", SEND_LISTING);
3172 msg = CtdlMakeMessage(&CC->user, recp, cc,
3173 CC->room.QRname, anonymous, format_type,
3174 masquerade_as, subject,
3175 ((strlen(supplied_euid) > 0) ? supplied_euid : NULL),
3178 /* Put together one big recipients struct containing to/cc/bcc all in
3179 * one. This is for the envelope.
3181 char *all_recps = malloc(SIZ * 3);
3182 strcpy(all_recps, recp);
3183 if (strlen(cc) > 0) {
3184 if (strlen(all_recps) > 0) {
3185 strcat(all_recps, ",");
3187 strcat(all_recps, cc);
3189 if (strlen(bcc) > 0) {
3190 if (strlen(all_recps) > 0) {
3191 strcat(all_recps, ",");
3193 strcat(all_recps, bcc);
3195 if (strlen(all_recps) > 0) {
3196 valid = validate_recipients(all_recps);
3204 msgnum = CtdlSubmitMsg(msg, valid, "");
3207 cprintf("%ld\n", msgnum);
3209 cprintf("Message accepted.\n");
3212 cprintf("Internal error.\n");
3214 if (msg->cm_fields['E'] != NULL) {
3215 cprintf("%s\n", msg->cm_fields['E']);
3222 CtdlFreeMessage(msg);
3224 CC->fake_postname[0] = '\0';
3225 if (valid != NULL) {
3234 * API function to delete messages which match a set of criteria
3235 * (returns the actual number of messages deleted)
3237 int CtdlDeleteMessages(char *room_name, /* which room */
3238 long dmsgnum, /* or "0" for any */
3239 char *content_type, /* or "" for any */
3240 int deferred /* let TDAP sweep it later */
3244 struct ctdlroom qrbuf;
3245 struct cdbdata *cdbfr;
3246 long *msglist = NULL;
3247 long *dellist = NULL;
3250 int num_deleted = 0;
3252 struct MetaData smi;
3254 lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %ld, %s, %d)\n",
3255 room_name, dmsgnum, content_type, deferred);
3257 /* get room record, obtaining a lock... */
3258 if (lgetroom(&qrbuf, room_name) != 0) {
3259 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3261 return (0); /* room not found */
3263 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3265 if (cdbfr != NULL) {
3266 dellist = malloc(cdbfr->len);
3267 msglist = (long *) cdbfr->ptr;
3268 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3269 num_msgs = cdbfr->len / sizeof(long);
3273 for (i = 0; i < num_msgs; ++i) {
3276 /* Set/clear a bit for each criterion */
3278 if ((dmsgnum == 0L) || (msglist[i] == dmsgnum)) {
3279 delete_this |= 0x01;
3281 if (strlen(content_type) == 0) {
3282 delete_this |= 0x02;
3284 GetMetaData(&smi, msglist[i]);
3285 if (!strcasecmp(smi.meta_content_type,
3287 delete_this |= 0x02;
3291 /* Delete message only if all bits are set */
3292 if (delete_this == 0x03) {
3293 dellist[num_deleted++] = msglist[i];
3298 num_msgs = sort_msglist(msglist, num_msgs);
3299 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3300 msglist, (int)(num_msgs * sizeof(long)));
3302 qrbuf.QRhighest = msglist[num_msgs - 1];
3307 * If the delete operation is "deferred" (and technically, any delete
3308 * operation not performed by THE DREADED AUTO-PURGER ought to be
3309 * a deferred delete) then we save a pointer to the message in the
3310 * DELETED_MSGS_ROOM. This will cause the reference count to remain
3311 * at least 1, which will save the user from having to synchronously
3312 * wait for various disk-intensive operations to complete.
3314 if ( (deferred) && (num_deleted) ) {
3315 for (i=0; i<num_deleted; ++i) {
3316 CtdlCopyMsgToRoom(dellist[i], DELETED_MSGS_ROOM);
3320 /* Go through the messages we pulled out of the index, and decrement
3321 * their reference counts by 1. If this is the only room the message
3322 * was in, the reference count will reach zero and the message will
3323 * automatically be deleted from the database. We do this in a
3324 * separate pass because there might be plug-in hooks getting called,
3325 * and we don't want that happening during an S_ROOMS critical
3328 if (num_deleted) for (i=0; i<num_deleted; ++i) {
3329 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3330 AdjRefCount(dellist[i], -1);
3333 /* Now free the memory we used, and go away. */
3334 if (msglist != NULL) free(msglist);
3335 if (dellist != NULL) free(dellist);
3336 lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3337 return (num_deleted);
3343 * Check whether the current user has permission to delete messages from
3344 * the current room (returns 1 for yes, 0 for no)
3346 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3347 getuser(&CC->user, CC->curr_user);
3348 if ((CC->user.axlevel < 6)
3349 && (CC->user.usernum != CC->room.QRroomaide)
3350 && ((CC->room.QRflags & QR_MAILBOX) == 0)
3351 && (!(CC->internal_pgm))) {
3360 * Delete message from current room
3362 void cmd_dele(char *delstr)
3367 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3368 cprintf("%d Higher access required.\n",
3369 ERROR + HIGHER_ACCESS_REQUIRED);
3372 delnum = extract_long(delstr, 0);
3374 num_deleted = CtdlDeleteMessages(CC->room.QRname, delnum, "", 1);
3377 cprintf("%d %d message%s deleted.\n", CIT_OK,
3378 num_deleted, ((num_deleted != 1) ? "s" : ""));
3380 cprintf("%d Message %ld not found.\n", ERROR + MESSAGE_NOT_FOUND, delnum);
3386 * Back end API function for moves and deletes
3388 int CtdlCopyMsgToRoom(long msgnum, char *dest) {
3391 err = CtdlSaveMsgPointerInRoom(dest, msgnum, 1, NULL);
3392 if (err != 0) return(err);
3400 * move or copy a message to another room
3402 void cmd_move(char *args)
3405 char targ[ROOMNAMELEN];
3406 struct ctdlroom qtemp;
3412 num = extract_long(args, 0);
3413 extract_token(targ, args, 1, '|', sizeof targ);
3414 convert_room_name_macros(targ, sizeof targ);
3415 targ[ROOMNAMELEN - 1] = 0;
3416 is_copy = extract_int(args, 2);
3418 if (getroom(&qtemp, targ) != 0) {
3419 cprintf("%d '%s' does not exist.\n",
3420 ERROR + ROOM_NOT_FOUND, targ);
3424 getuser(&CC->user, CC->curr_user);
3425 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3427 /* Check for permission to perform this operation.
3428 * Remember: "CC->room" is source, "qtemp" is target.
3432 /* Aides can move/copy */
3433 if (CC->user.axlevel >= 6) permit = 1;
3435 /* Room aides can move/copy */
3436 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3438 /* Permit move/copy from personal rooms */
3439 if ((CC->room.QRflags & QR_MAILBOX)
3440 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3442 /* Permit only copy from public to personal room */
3444 && (!(CC->room.QRflags & QR_MAILBOX))
3445 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3447 /* User must have access to target room */
3448 if (!(ra & UA_KNOWN)) permit = 0;
3451 cprintf("%d Higher access required.\n",
3452 ERROR + HIGHER_ACCESS_REQUIRED);
3456 err = CtdlCopyMsgToRoom(num, targ);
3458 cprintf("%d Cannot store message in %s: error %d\n",
3463 /* Now delete the message from the source room,
3464 * if this is a 'move' rather than a 'copy' operation.
3467 CtdlDeleteMessages(CC->room.QRname, num, "", 0);
3470 cprintf("%d Message %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3476 * GetMetaData() - Get the supplementary record for a message
3478 void GetMetaData(struct MetaData *smibuf, long msgnum)
3481 struct cdbdata *cdbsmi;
3484 memset(smibuf, 0, sizeof(struct MetaData));
3485 smibuf->meta_msgnum = msgnum;
3486 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3488 /* Use the negative of the message number for its supp record index */
3489 TheIndex = (0L - msgnum);
3491 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3492 if (cdbsmi == NULL) {
3493 return; /* record not found; go with defaults */
3495 memcpy(smibuf, cdbsmi->ptr,
3496 ((cdbsmi->len > sizeof(struct MetaData)) ?
3497 sizeof(struct MetaData) : cdbsmi->len));
3504 * PutMetaData() - (re)write supplementary record for a message
3506 void PutMetaData(struct MetaData *smibuf)
3510 /* Use the negative of the message number for the metadata db index */
3511 TheIndex = (0L - smibuf->meta_msgnum);
3513 lprintf(CTDL_DEBUG, "PutMetaData(%ld) - ref count is %d\n",
3514 smibuf->meta_msgnum, smibuf->meta_refcount);
3516 cdb_store(CDB_MSGMAIN,
3517 &TheIndex, (int)sizeof(long),
3518 smibuf, (int)sizeof(struct MetaData));
3523 * AdjRefCount - change the reference count for a message;
3524 * delete the message if it reaches zero
3526 void AdjRefCount(long msgnum, int incr)
3529 struct MetaData smi;
3532 /* This is a *tight* critical section; please keep it that way, as
3533 * it may get called while nested in other critical sections.
3534 * Complicating this any further will surely cause deadlock!
3536 begin_critical_section(S_SUPPMSGMAIN);
3537 GetMetaData(&smi, msgnum);
3538 smi.meta_refcount += incr;
3540 end_critical_section(S_SUPPMSGMAIN);
3541 lprintf(CTDL_DEBUG, "msg %ld ref count incr %d, is now %d\n",
3542 msgnum, incr, smi.meta_refcount);
3544 /* If the reference count is now zero, delete the message
3545 * (and its supplementary record as well).
3547 if (smi.meta_refcount == 0) {
3548 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
3550 /* Remove from fulltext index */
3551 if (config.c_enable_fulltext) {
3552 ft_index_message(msgnum, 0);
3555 /* Remove from message base */
3557 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3558 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3560 /* Remove metadata record */
3561 delnum = (0L - msgnum);
3562 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3567 * Write a generic object to this room
3569 * Note: this could be much more efficient. Right now we use two temporary
3570 * files, and still pull the message into memory as with all others.
3572 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
3573 char *content_type, /* MIME type of this object */
3574 char *tempfilename, /* Where to fetch it from */
3575 struct ctdluser *is_mailbox, /* Mailbox room? */
3576 int is_binary, /* Is encoding necessary? */
3577 int is_unique, /* Del others of this type? */
3578 unsigned int flags /* Internal save flags */
3583 struct ctdlroom qrbuf;
3584 char roomname[ROOMNAMELEN];
3585 struct CtdlMessage *msg;
3587 char *raw_message = NULL;
3588 char *encoded_message = NULL;
3589 off_t raw_length = 0;
3591 if (is_mailbox != NULL) {
3592 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3595 safestrncpy(roomname, req_room, sizeof(roomname));
3598 fp = fopen(tempfilename, "rb");
3600 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
3601 tempfilename, strerror(errno));
3604 fseek(fp, 0L, SEEK_END);
3605 raw_length = ftell(fp);
3607 lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
3609 raw_message = malloc((size_t)raw_length + 2);
3610 fread(raw_message, (size_t)raw_length, 1, fp);
3614 encoded_message = malloc((size_t)
3615 (((raw_length * 134) / 100) + 4096 ) );
3618 encoded_message = malloc((size_t)(raw_length + 4096));
3621 sprintf(encoded_message, "Content-type: %s\n", content_type);
3624 sprintf(&encoded_message[strlen(encoded_message)],
3625 "Content-transfer-encoding: base64\n\n"
3629 sprintf(&encoded_message[strlen(encoded_message)],
3630 "Content-transfer-encoding: 7bit\n\n"
3636 &encoded_message[strlen(encoded_message)],
3642 raw_message[raw_length] = 0;
3644 &encoded_message[strlen(encoded_message)],
3652 lprintf(CTDL_DEBUG, "Allocating\n");
3653 msg = malloc(sizeof(struct CtdlMessage));
3654 memset(msg, 0, sizeof(struct CtdlMessage));
3655 msg->cm_magic = CTDLMESSAGE_MAGIC;
3656 msg->cm_anon_type = MES_NORMAL;
3657 msg->cm_format_type = 4;
3658 msg->cm_fields['A'] = strdup(CC->user.fullname);
3659 msg->cm_fields['O'] = strdup(req_room);
3660 msg->cm_fields['N'] = strdup(config.c_nodename);
3661 msg->cm_fields['H'] = strdup(config.c_humannode);
3662 msg->cm_flags = flags;
3664 msg->cm_fields['M'] = encoded_message;
3666 /* Create the requested room if we have to. */
3667 if (getroom(&qrbuf, roomname) != 0) {
3668 create_room(roomname,
3669 ( (is_mailbox != NULL) ? 5 : 3 ),
3670 "", 0, 1, 0, VIEW_BBS);
3672 /* If the caller specified this object as unique, delete all
3673 * other objects of this type that are currently in the room.
3676 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
3677 CtdlDeleteMessages(roomname, 0L, content_type, 0)
3680 /* Now write the data */
3681 CtdlSubmitMsg(msg, NULL, roomname);
3682 CtdlFreeMessage(msg);
3690 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
3691 config_msgnum = msgnum;
3695 char *CtdlGetSysConfig(char *sysconfname) {
3696 char hold_rm[ROOMNAMELEN];
3699 struct CtdlMessage *msg;
3702 strcpy(hold_rm, CC->room.QRname);
3703 if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
3704 getroom(&CC->room, hold_rm);
3709 /* We want the last (and probably only) config in this room */
3710 begin_critical_section(S_CONFIG);
3711 config_msgnum = (-1L);
3712 CtdlForEachMessage(MSGS_LAST, 1, sysconfname, NULL,
3713 CtdlGetSysConfigBackend, NULL);
3714 msgnum = config_msgnum;
3715 end_critical_section(S_CONFIG);
3721 msg = CtdlFetchMessage(msgnum, 1);
3723 conf = strdup(msg->cm_fields['M']);
3724 CtdlFreeMessage(msg);
3731 getroom(&CC->room, hold_rm);
3733 if (conf != NULL) do {
3734 extract_token(buf, conf, 0, '\n', sizeof buf);
3735 strcpy(conf, &conf[strlen(buf)+1]);
3736 } while ( (strlen(conf)>0) && (strlen(buf)>0) );
3741 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
3742 char temp[PATH_MAX];
3745 CtdlMakeTempFileName(temp, sizeof temp);
3747 fp = fopen(temp, "w");
3748 if (fp == NULL) return;
3749 fprintf(fp, "%s", sysconfdata);
3752 /* this handy API function does all the work for us */
3753 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
3759 * Determine whether a given Internet address belongs to the current user
3761 int CtdlIsMe(char *addr, int addr_buf_len)
3763 struct recptypes *recp;
3766 recp = validate_recipients(addr);
3767 if (recp == NULL) return(0);
3769 if (recp->num_local == 0) {
3774 for (i=0; i<recp->num_local; ++i) {
3775 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
3776 if (!strcasecmp(addr, CC->user.fullname)) {
3788 * Citadel protocol command to do the same
3790 void cmd_isme(char *argbuf) {
3793 if (CtdlAccessCheck(ac_logged_in)) return;
3794 extract_token(addr, argbuf, 0, '|', sizeof addr);
3796 if (CtdlIsMe(addr, sizeof addr)) {
3797 cprintf("%d %s\n", CIT_OK, addr);
3800 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);