4 * Implements the message store.
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
23 # include <sys/time.h>
39 #include "dynloader.h"
43 #include "sysdep_decls.h"
44 #include "citserver.h"
50 #include "mime_parser.h"
53 #include "internet_addressing.h"
55 #define desired_section ((char *)CtdlGetUserData(SYM_DESIRED_SECTION))
56 #define ma ((struct ma_info *)CtdlGetUserData(SYM_MA_INFO))
57 #define msg_repl ((struct repl *)CtdlGetUserData(SYM_REPL))
59 extern struct config config;
63 * These are the four-character field headers we use when outputting
64 * messages in Citadel format (as opposed to RFC822 format).
67 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
68 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
69 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
70 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
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,
101 * This function is self explanatory.
102 * (What can I say, I'm in a weird mood today...)
104 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
108 for (i = 0; i < strlen(name); ++i) {
109 if (name[i] == '@') {
110 while (isspace(name[i - 1]) && i > 0) {
111 strcpy(&name[i - 1], &name[i]);
114 while (isspace(name[i + 1])) {
115 strcpy(&name[i + 1], &name[i + 2]);
123 * Aliasing for network mail.
124 * (Error messages have been commented out, because this is a server.)
126 int alias(char *name)
127 { /* process alias and routing info for mail */
130 char aaa[SIZ], bbb[SIZ];
131 char *ignetcfg = NULL;
132 char *ignetmap = NULL;
139 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
141 fp = fopen("network/mail.aliases", "r");
143 fp = fopen("/dev/null", "r");
150 while (fgets(aaa, sizeof aaa, fp) != NULL) {
151 while (isspace(name[0]))
152 strcpy(name, &name[1]);
153 aaa[strlen(aaa) - 1] = 0;
155 for (a = 0; a < strlen(aaa); ++a) {
157 strcpy(bbb, &aaa[a + 1]);
161 if (!strcasecmp(name, aaa))
166 /* Hit the Global Address Book */
167 if (CtdlDirectoryLookup(aaa, name) == 0) {
171 lprintf(7, "Mail is being forwarded to %s\n", name);
173 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
174 for (a=0; a<strlen(name); ++a) {
175 if (name[a] == '@') {
176 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
178 lprintf(7, "Changed to <%s>\n", name);
183 /* determine local or remote type, see citadel.h */
184 at = haschar(name, '@');
185 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
186 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
187 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
189 /* figure out the delivery mode */
190 extract_token(node, name, 1, '@');
192 /* If there are one or more dots in the nodename, we assume that it
193 * is an FQDN and will attempt SMTP delivery to the Internet.
195 if (haschar(node, '.') > 0) {
196 return(MES_INTERNET);
199 /* Otherwise we look in the IGnet maps for a valid Citadel node.
200 * Try directly-connected nodes first...
202 ignetcfg = CtdlGetSysConfig(IGNETCFG);
203 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
204 extract_token(buf, ignetcfg, i, '\n');
205 extract_token(testnode, buf, 0, '|');
206 if (!strcasecmp(node, testnode)) {
214 * Then try nodes that are two or more hops away.
216 ignetmap = CtdlGetSysConfig(IGNETMAP);
217 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
218 extract_token(buf, ignetmap, i, '\n');
219 extract_token(testnode, buf, 0, '|');
220 if (!strcasecmp(node, testnode)) {
227 /* If we get to this point it's an invalid node name */
236 fp = fopen("citadel.control", "r");
237 fread((char *) &CitControl, sizeof(struct CitControl), 1, fp);
243 void simple_listing(long msgnum, void *userdata)
245 cprintf("%ld\n", msgnum);
250 /* Determine if a given message matches the fields in a message template.
251 * Return 0 for a successful match.
253 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
256 /* If there aren't any fields in the template, all messages will
259 if (template == NULL) return(0);
261 /* Null messages are bogus. */
262 if (msg == NULL) return(1);
264 for (i='A'; i<='Z'; ++i) {
265 if (template->cm_fields[i] != NULL) {
266 if (msg->cm_fields[i] == NULL) {
269 if (strcasecmp(msg->cm_fields[i],
270 template->cm_fields[i])) return 1;
274 /* All compares succeeded: we have a match! */
280 * Manipulate the "seen msgs" string.
282 void CtdlSetSeen(long target_msgnum, int target_setting) {
284 struct cdbdata *cdbfr;
294 /* Learn about the user and room in question */
296 getuser(&CC->usersupp, CC->curr_user);
297 CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
299 /* Load the message list */
300 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long));
302 msglist = mallok(cdbfr->len);
303 memcpy(msglist, cdbfr->ptr, cdbfr->len);
304 num_msgs = cdbfr->len / sizeof(long);
307 return; /* No messages at all? No further action. */
310 lprintf(9, "before optimize: %s\n", vbuf.v_seen);
313 for (i=0; i<num_msgs; ++i) {
316 if (msglist[i] == target_msgnum) {
317 is_seen = target_setting;
320 if (is_msg_in_mset(vbuf.v_seen, msglist[i])) {
326 if (lo < 0L) lo = msglist[i];
329 if ( ((is_seen == 0) && (was_seen == 1))
330 || ((is_seen == 1) && (i == num_msgs-1)) ) {
331 if ( (strlen(newseen) + 20) > SIZ) {
332 strcpy(newseen, &newseen[20]);
335 if (strlen(newseen) > 0) strcat(newseen, ",");
337 sprintf(&newseen[strlen(newseen)], "%ld", lo);
340 sprintf(&newseen[strlen(newseen)], "%ld:%ld",
349 safestrncpy(vbuf.v_seen, newseen, SIZ);
350 lprintf(9, " after optimize: %s\n", vbuf.v_seen);
352 CtdlSetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
357 * API function to perform an operation for each qualifying message in the
358 * current room. (Returns the number of messages processed.)
360 int CtdlForEachMessage(int mode, long ref,
361 int moderation_level,
363 struct CtdlMessage *compare,
364 void (*CallBack) (long, void *),
370 struct cdbdata *cdbfr;
371 long *msglist = NULL;
373 int num_processed = 0;
376 struct CtdlMessage *msg;
379 int printed_lastold = 0;
381 /* Learn about the user and room in question */
383 getuser(&CC->usersupp, CC->curr_user);
384 CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
386 /* Load the message list */
387 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long));
389 msglist = mallok(cdbfr->len);
390 memcpy(msglist, cdbfr->ptr, cdbfr->len);
391 num_msgs = cdbfr->len / sizeof(long);
394 return 0; /* No messages at all? No further action. */
399 * Now begin the traversal.
401 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
402 GetMetaData(&smi, msglist[a]);
404 /* Filter out messages that are moderated below the level
405 * currently being viewed at.
407 if (smi.meta_mod < moderation_level) {
411 /* If the caller is looking for a specific MIME type, filter
412 * out all messages which are not of the type requested.
414 if (content_type != NULL) if (strlen(content_type) > 0) {
415 if (strcasecmp(smi.meta_content_type, content_type)) {
421 num_msgs = sort_msglist(msglist, num_msgs);
423 /* If a template was supplied, filter out the messages which
424 * don't match. (This could induce some delays!)
427 if (compare != NULL) {
428 for (a = 0; a < num_msgs; ++a) {
429 msg = CtdlFetchMessage(msglist[a]);
431 if (CtdlMsgCmp(msg, compare)) {
434 CtdlFreeMessage(msg);
442 * Now iterate through the message list, according to the
443 * criteria supplied by the caller.
446 for (a = 0; a < num_msgs; ++a) {
447 thismsg = msglist[a];
448 is_seen = is_msg_in_mset(vbuf.v_seen, thismsg);
449 if (is_seen) lastold = thismsg;
454 || ((mode == MSGS_OLD) && (is_seen))
455 || ((mode == MSGS_NEW) && (!is_seen))
456 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
457 || ((mode == MSGS_FIRST) && (a < ref))
458 || ((mode == MSGS_GT) && (thismsg > ref))
459 || ((mode == MSGS_EQ) && (thismsg == ref))
462 if ((mode == MSGS_NEW) && (CC->usersupp.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
464 CallBack(lastold, userdata);
468 if (CallBack) CallBack(thismsg, userdata);
472 phree(msglist); /* Clean up */
473 return num_processed;
479 * cmd_msgs() - get list of message #'s in this room
480 * implements the MSGS server command using CtdlForEachMessage()
482 void cmd_msgs(char *cmdbuf)
491 int with_template = 0;
492 struct CtdlMessage *template = NULL;
494 extract(which, cmdbuf, 0);
495 cm_ref = extract_int(cmdbuf, 1);
496 with_template = extract_int(cmdbuf, 2);
500 if (!strncasecmp(which, "OLD", 3))
502 else if (!strncasecmp(which, "NEW", 3))
504 else if (!strncasecmp(which, "FIRST", 5))
506 else if (!strncasecmp(which, "LAST", 4))
508 else if (!strncasecmp(which, "GT", 2))
511 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
512 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
517 cprintf("%d Send template then receive message list\n",
519 template = (struct CtdlMessage *)
520 mallok(sizeof(struct CtdlMessage));
521 memset(template, 0, sizeof(struct CtdlMessage));
522 while(client_gets(buf), strcmp(buf,"000")) {
523 extract(tfield, buf, 0);
524 extract(tvalue, buf, 1);
525 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
526 if (!strcasecmp(tfield, msgkeys[i])) {
527 template->cm_fields[i] =
534 cprintf("%d Message list...\n", LISTING_FOLLOWS);
537 CtdlForEachMessage(mode, cm_ref,
538 CC->usersupp.moderation_filter,
539 NULL, template, simple_listing, NULL);
540 if (template != NULL) CtdlFreeMessage(template);
548 * help_subst() - support routine for help file viewer
550 void help_subst(char *strbuf, char *source, char *dest)
555 while (p = pattern2(strbuf, source), (p >= 0)) {
556 strcpy(workbuf, &strbuf[p + strlen(source)]);
557 strcpy(&strbuf[p], dest);
558 strcat(strbuf, workbuf);
563 void do_help_subst(char *buffer)
567 help_subst(buffer, "^nodename", config.c_nodename);
568 help_subst(buffer, "^humannode", config.c_humannode);
569 help_subst(buffer, "^fqdn", config.c_fqdn);
570 help_subst(buffer, "^username", CC->usersupp.fullname);
571 sprintf(buf2, "%ld", CC->usersupp.usernum);
572 help_subst(buffer, "^usernum", buf2);
573 help_subst(buffer, "^sysadm", config.c_sysadm);
574 help_subst(buffer, "^variantname", CITADEL);
575 sprintf(buf2, "%d", config.c_maxsessions);
576 help_subst(buffer, "^maxsessions", buf2);
582 * memfmout() - Citadel text formatter and paginator.
583 * Although the original purpose of this routine was to format
584 * text to the reader's screen width, all we're really using it
585 * for here is to format text out to 80 columns before sending it
586 * to the client. The client software may reformat it again.
589 int width, /* screen width to use */
590 char *mptr, /* where are we going to get our text from? */
591 char subst, /* nonzero if we should do substitutions */
592 char *nl) /* string to terminate lines with */
604 c = 1; /* c is the current pos */
608 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
610 buffer[strlen(buffer) + 1] = 0;
611 buffer[strlen(buffer)] = ch;
614 if (buffer[0] == '^')
615 do_help_subst(buffer);
617 buffer[strlen(buffer) + 1] = 0;
619 strcpy(buffer, &buffer[1]);
627 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10))
629 if (((old == 13) || (old == 10)) && (isspace(real))) {
637 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
638 cprintf("%s%s", nl, aaa);
647 if ((strlen(aaa) + c) > (width - 5)) {
656 if ((ch == 13) || (ch == 10)) {
657 cprintf("%s%s", aaa, nl);
664 cprintf("%s%s", aaa, nl);
670 * Callback function for mime parser that simply lists the part
672 void list_this_part(char *name, char *filename, char *partnum, char *disp,
673 void *content, char *cbtype, size_t length, char *encoding,
677 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
678 name, filename, partnum, disp, cbtype, (long)length);
683 * Callback function for mime parser that opens a section for downloading
685 void mime_download(char *name, char *filename, char *partnum, char *disp,
686 void *content, char *cbtype, size_t length, char *encoding,
690 /* Silently go away if there's already a download open... */
691 if (CC->download_fp != NULL)
694 /* ...or if this is not the desired section */
695 if (strcasecmp(desired_section, partnum))
698 CC->download_fp = tmpfile();
699 if (CC->download_fp == NULL)
702 fwrite(content, length, 1, CC->download_fp);
703 fflush(CC->download_fp);
704 rewind(CC->download_fp);
706 OpenCmdResult(filename, cbtype);
712 * Load a message from disk into memory.
713 * This is used by CtdlOutputMsg() and other fetch functions.
715 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
716 * using the CtdlMessageFree() function.
718 struct CtdlMessage *CtdlFetchMessage(long msgnum)
720 struct cdbdata *dmsgtext;
721 struct CtdlMessage *ret = NULL;
724 CIT_UBYTE field_header;
727 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
728 if (dmsgtext == NULL) {
731 mptr = dmsgtext->ptr;
733 /* Parse the three bytes that begin EVERY message on disk.
734 * The first is always 0xFF, the on-disk magic number.
735 * The second is the anonymous/public type byte.
736 * The third is the format type byte (vari, fixed, or MIME).
740 lprintf(5, "Message %ld appears to be corrupted.\n", msgnum);
744 ret = (struct CtdlMessage *) mallok(sizeof(struct CtdlMessage));
745 memset(ret, 0, sizeof(struct CtdlMessage));
747 ret->cm_magic = CTDLMESSAGE_MAGIC;
748 ret->cm_anon_type = *mptr++; /* Anon type byte */
749 ret->cm_format_type = *mptr++; /* Format type byte */
752 * The rest is zero or more arbitrary fields. Load them in.
753 * We're done when we encounter either a zero-length field or
754 * have just processed the 'M' (message text) field.
757 field_length = strlen(mptr);
758 if (field_length == 0)
760 field_header = *mptr++;
761 ret->cm_fields[field_header] = mallok(field_length);
762 strcpy(ret->cm_fields[field_header], mptr);
764 while (*mptr++ != 0); /* advance to next field */
766 } while ((field_length > 0) && (field_header != 'M'));
770 /* Always make sure there's something in the msg text field */
771 if (ret->cm_fields['M'] == NULL)
772 ret->cm_fields['M'] = strdoop("<no text>\n");
774 /* Perform "before read" hooks (aborting if any return nonzero) */
775 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
776 CtdlFreeMessage(ret);
785 * Returns 1 if the supplied pointer points to a valid Citadel message.
786 * If the pointer is NULL or the magic number check fails, returns 0.
788 int is_valid_message(struct CtdlMessage *msg) {
791 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
792 lprintf(3, "is_valid_message() -- self-check failed\n");
800 * 'Destructor' for struct CtdlMessage
802 void CtdlFreeMessage(struct CtdlMessage *msg)
806 if (is_valid_message(msg) == 0) return;
808 for (i = 0; i < 256; ++i)
809 if (msg->cm_fields[i] != NULL) {
810 phree(msg->cm_fields[i]);
813 msg->cm_magic = 0; /* just in case */
819 * Pre callback function for multipart/alternative
821 * NOTE: this differs from the standard behavior for a reason. Normally when
822 * displaying multipart/alternative you want to show the _last_ usable
823 * format in the message. Here we show the _first_ one, because it's
824 * usually text/plain. Since this set of functions is designed for text
825 * output to non-MIME-aware clients, this is the desired behavior.
828 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
829 void *content, char *cbtype, size_t length, char *encoding,
832 lprintf(9, "fixed_output_pre() type=<%s>\n", cbtype);
833 if (!strcasecmp(cbtype, "multipart/alternative")) {
841 * Post callback function for multipart/alternative
843 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
844 void *content, char *cbtype, size_t length, char *encoding,
847 lprintf(9, "fixed_output_post() type=<%s>\n", cbtype);
848 if (!strcasecmp(cbtype, "multipart/alternative")) {
856 * Inline callback function for mime parser that wants to display text
858 void fixed_output(char *name, char *filename, char *partnum, char *disp,
859 void *content, char *cbtype, size_t length, char *encoding,
867 lprintf(9, "fixed_output() type=<%s>\n", cbtype);
870 * If we're in the middle of a multipart/alternative scope and
871 * we've already printed another section, skip this one.
873 if ( (ma->is_ma == 1) && (ma->did_print == 1) ) {
874 lprintf(9, "Skipping part %s (%s)\n", partnum, cbtype);
879 if ( (!strcasecmp(cbtype, "text/plain"))
880 || (strlen(cbtype)==0) ) {
886 if (ch==10) cprintf("\r\n");
887 else cprintf("%c", ch);
891 if (ch != '\n') cprintf("\n");
893 else if (!strcasecmp(cbtype, "text/html")) {
894 ptr = html_to_ascii(content, 80, 0);
899 if (ch==10) cprintf("\r\n");
900 else cprintf("%c", ch);
904 else if (strncasecmp(cbtype, "multipart/", 10)) {
905 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
906 partnum, filename, cbtype, (long)length);
912 * Get a message off disk. (returns om_* values found in msgbase.h)
915 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
916 int mode, /* how would you like that message? */
917 int headers_only, /* eschew the message body? */
918 int do_proto, /* do Citadel protocol responses? */
919 int crlf /* Use CRLF newlines instead of LF? */
921 struct CtdlMessage *TheMessage;
924 lprintf(7, "CtdlOutputMsg() msgnum=%ld, mode=%d\n",
929 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
930 if (do_proto) cprintf("%d Not logged in.\n",
931 ERROR + NOT_LOGGED_IN);
932 return(om_not_logged_in);
935 /* FIXME ... small security issue
936 * We need to check to make sure the requested message is actually
937 * in the current room, and set msg_ok to 1 only if it is. This
938 * functionality is currently missing because I'm in a hurry to replace
939 * broken production code with nonbroken pre-beta code. :( -- ajc
942 if (do_proto) cprintf("%d Message %ld is not in this room.\n",
944 return(om_no_such_msg);
949 * Fetch the message from disk
951 TheMessage = CtdlFetchMessage(msg_num);
952 if (TheMessage == NULL) {
953 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
955 return(om_no_such_msg);
958 retcode = CtdlOutputPreLoadedMsg(
959 TheMessage, msg_num, mode,
960 headers_only, do_proto, crlf);
962 CtdlFreeMessage(TheMessage);
968 * Get a message off disk. (returns om_* values found in msgbase.h)
971 int CtdlOutputPreLoadedMsg(struct CtdlMessage *TheMessage,
973 int mode, /* how would you like that message? */
974 int headers_only, /* eschew the message body? */
975 int do_proto, /* do Citadel protocol responses? */
976 int crlf /* Use CRLF newlines instead of LF? */
982 char display_name[SIZ];
984 char *nl; /* newline string */
987 /* buffers needed for RFC822 translation */
997 sprintf(mid, "%ld", msg_num);
998 nl = (crlf ? "\r\n" : "\n");
1000 if (!is_valid_message(TheMessage)) {
1001 lprintf(1, "ERROR: invalid preloaded message for output\n");
1002 return(om_no_such_msg);
1005 /* Are we downloading a MIME component? */
1006 if (mode == MT_DOWNLOAD) {
1007 if (TheMessage->cm_format_type != FMT_RFC822) {
1009 cprintf("%d This is not a MIME message.\n",
1011 } else if (CC->download_fp != NULL) {
1012 if (do_proto) cprintf(
1013 "%d You already have a download open.\n",
1016 /* Parse the message text component */
1017 mptr = TheMessage->cm_fields['M'];
1018 mime_parser(mptr, NULL,
1019 *mime_download, NULL, NULL,
1021 /* If there's no file open by this time, the requested
1022 * section wasn't found, so print an error
1024 if (CC->download_fp == NULL) {
1025 if (do_proto) cprintf(
1026 "%d Section %s not found.\n",
1027 ERROR + FILE_NOT_FOUND,
1031 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1034 /* now for the user-mode message reading loops */
1035 if (do_proto) cprintf("%d Message %ld:\n", LISTING_FOLLOWS, msg_num);
1037 /* Tell the client which format type we're using. If this is a
1038 * MIME message, *lie* about it and tell the user it's fixed-format.
1040 if (mode == MT_CITADEL) {
1041 if (TheMessage->cm_format_type == FMT_RFC822) {
1042 if (do_proto) cprintf("type=1\n");
1045 if (do_proto) cprintf("type=%d\n",
1046 TheMessage->cm_format_type);
1050 /* nhdr=yes means that we're only displaying headers, no body */
1051 if ((TheMessage->cm_anon_type == MES_ANONONLY) && (mode == MT_CITADEL)) {
1052 if (do_proto) cprintf("nhdr=yes\n");
1055 /* begin header processing loop for Citadel message format */
1057 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1059 strcpy(display_name, "<unknown>");
1060 if (TheMessage->cm_fields['A']) {
1061 strcpy(buf, TheMessage->cm_fields['A']);
1062 PerformUserHooks(buf, (-1L), EVT_OUTPUTMSG);
1063 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1064 strcpy(display_name, "****");
1066 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1067 strcpy(display_name, "anonymous");
1070 strcpy(display_name, buf);
1072 if ((is_room_aide())
1073 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1074 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1075 sprintf(&display_name[strlen(display_name)],
1080 /* Don't show Internet address for users on the
1081 * local Citadel network.
1084 if (TheMessage->cm_fields['N'] != NULL)
1085 if (strlen(TheMessage->cm_fields['N']) > 0)
1086 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1090 /* Now spew the header fields in the order we like them. */
1091 strcpy(allkeys, FORDER);
1092 for (i=0; i<strlen(allkeys); ++i) {
1093 k = (int) allkeys[i];
1095 if ( (TheMessage->cm_fields[k] != NULL)
1096 && (msgkeys[k] != NULL) ) {
1098 if (do_proto) cprintf("%s=%s\n",
1102 else if ((k == 'F') && (suppress_f)) {
1105 /* Masquerade display name if needed */
1107 if (do_proto) cprintf("%s=%s\n",
1109 TheMessage->cm_fields[k]
1118 /* begin header processing loop for RFC822 transfer format */
1123 strcpy(snode, NODENAME);
1124 strcpy(lnode, HUMANNODE);
1125 if (mode == MT_RFC822) {
1126 cprintf("X-UIDL: %ld%s", msg_num, nl);
1127 for (i = 0; i < 256; ++i) {
1128 if (TheMessage->cm_fields[i]) {
1129 mptr = TheMessage->cm_fields[i];
1132 strcpy(luser, mptr);
1133 strcpy(suser, mptr);
1136 "Path:" removed for now because it confuses brain-dead Microsoft shitware
1137 into thinking that mail messages are newsgroup messages instead. When we
1138 add NNTP support back into Citadel we'll have to add code to only output
1139 this field when appropriate.
1140 else if (i == 'P') {
1141 cprintf("Path: %s%s", mptr, nl);
1145 cprintf("Subject: %s%s", mptr, nl);
1147 safestrncpy(mid, mptr, sizeof mid);
1149 safestrncpy(lnode, mptr, sizeof lnode);
1151 safestrncpy(fuser, mptr, sizeof fuser);
1153 cprintf("X-Citadel-Room: %s%s",
1156 safestrncpy(snode, mptr, sizeof snode);
1158 cprintf("To: %s%s", mptr, nl);
1159 else if (i == 'T') {
1160 datestring(datestamp, atol(mptr),
1161 DATESTRING_RFC822 );
1162 cprintf("Date: %s%s", datestamp, nl);
1168 for (i=0; i<strlen(suser); ++i) {
1169 suser[i] = tolower(suser[i]);
1170 if (!isalnum(suser[i])) suser[i]='_';
1173 if (mode == MT_RFC822) {
1174 if (!strcasecmp(snode, NODENAME)) {
1175 strcpy(snode, FQDN);
1178 /* Construct a fun message id */
1179 cprintf("Message-ID: <%s", mid);
1180 if (strchr(mid, '@')==NULL) {
1181 cprintf("@%s", snode);
1185 PerformUserHooks(luser, (-1L), EVT_OUTPUTMSG);
1187 if (strlen(fuser) > 0) {
1188 cprintf("From: %s (%s)%s", fuser, luser, nl);
1191 cprintf("From: %s@%s (%s)%s", suser, snode, luser, nl);
1194 cprintf("Organization: %s%s", lnode, nl);
1197 /* end header processing loop ... at this point, we're in the text */
1199 mptr = TheMessage->cm_fields['M'];
1201 /* Tell the client about the MIME parts in this message */
1202 if (TheMessage->cm_format_type == FMT_RFC822) {
1203 if (mode == MT_CITADEL) {
1204 mime_parser(mptr, NULL,
1205 *list_this_part, NULL, NULL,
1208 else if (mode == MT_MIME) { /* list parts only */
1209 mime_parser(mptr, NULL,
1210 *list_this_part, NULL, NULL,
1212 if (do_proto) cprintf("000\n");
1215 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1216 /* FIXME ... we have to put some code in here to avoid
1217 * printing duplicate header information when both
1218 * Citadel and RFC822 headers exist. Preference should
1219 * probably be given to the RFC822 headers.
1221 while (ch=*(mptr++), ch!=0) {
1223 else if (ch==10) cprintf("%s", nl);
1224 else cprintf("%c", ch);
1226 if (do_proto) cprintf("000\n");
1232 if (do_proto) cprintf("000\n");
1236 /* signify start of msg text */
1237 if (mode == MT_CITADEL)
1238 if (do_proto) cprintf("text\n");
1239 if (mode == MT_RFC822) {
1240 if (TheMessage->cm_fields['U'] == NULL) {
1241 cprintf("Subject: (no subject)%s", nl);
1246 /* If the format type on disk is 1 (fixed-format), then we want
1247 * everything to be output completely literally ... regardless of
1248 * what message transfer format is in use.
1250 if (TheMessage->cm_format_type == FMT_FIXED) {
1252 while (ch = *mptr++, ch > 0) {
1255 if ((ch == 10) || (strlen(buf) > 250)) {
1256 cprintf("%s%s", buf, nl);
1259 buf[strlen(buf) + 1] = 0;
1260 buf[strlen(buf)] = ch;
1263 if (strlen(buf) > 0)
1264 cprintf("%s%s", buf, nl);
1267 /* If the message on disk is format 0 (Citadel vari-format), we
1268 * output using the formatter at 80 columns. This is the final output
1269 * form if the transfer format is RFC822, but if the transfer format
1270 * is Citadel proprietary, it'll still work, because the indentation
1271 * for new paragraphs is correct and the client will reformat the
1272 * message to the reader's screen width.
1274 if (TheMessage->cm_format_type == FMT_CITADEL) {
1275 memfmout(80, mptr, 0, nl);
1278 /* If the message on disk is format 4 (MIME), we've gotta hand it
1279 * off to the MIME parser. The client has already been told that
1280 * this message is format 1 (fixed format), so the callback function
1281 * we use will display those parts as-is.
1283 if (TheMessage->cm_format_type == FMT_RFC822) {
1284 CtdlAllocUserData(SYM_MA_INFO, sizeof(struct ma_info));
1285 memset(ma, 0, sizeof(struct ma_info));
1286 mime_parser(mptr, NULL,
1287 *fixed_output, *fixed_output_pre, *fixed_output_post,
1291 /* now we're done */
1292 if (do_proto) cprintf("000\n");
1299 * display a message (mode 0 - Citadel proprietary)
1301 void cmd_msg0(char *cmdbuf)
1304 int headers_only = 0;
1306 msgid = extract_long(cmdbuf, 0);
1307 headers_only = extract_int(cmdbuf, 1);
1309 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0);
1315 * display a message (mode 2 - RFC822)
1317 void cmd_msg2(char *cmdbuf)
1320 int headers_only = 0;
1322 msgid = extract_long(cmdbuf, 0);
1323 headers_only = extract_int(cmdbuf, 1);
1325 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1);
1331 * display a message (mode 3 - IGnet raw format - internal programs only)
1333 void cmd_msg3(char *cmdbuf)
1336 struct CtdlMessage *msg;
1339 if (CC->internal_pgm == 0) {
1340 cprintf("%d This command is for internal programs only.\n",
1345 msgnum = extract_long(cmdbuf, 0);
1346 msg = CtdlFetchMessage(msgnum);
1348 cprintf("%d Message %ld not found.\n",
1353 serialize_message(&smr, msg);
1354 CtdlFreeMessage(msg);
1357 cprintf("%d Unable to serialize message\n",
1358 ERROR+INTERNAL_ERROR);
1362 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1363 client_write(smr.ser, smr.len);
1370 * display a message (mode 4 - MIME) (FIXME ... still evolving, not complete)
1372 void cmd_msg4(char *cmdbuf)
1376 msgid = extract_long(cmdbuf, 0);
1377 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0);
1381 * Open a component of a MIME message as a download file
1383 void cmd_opna(char *cmdbuf)
1387 CtdlAllocUserData(SYM_DESIRED_SECTION, SIZ);
1389 msgid = extract_long(cmdbuf, 0);
1390 extract(desired_section, cmdbuf, 1);
1392 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1);
1397 * Save a message pointer into a specified room
1398 * (Returns 0 for success, nonzero for failure)
1399 * roomname may be NULL to use the current room
1401 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid, int flags) {
1403 char hold_rm[ROOMNAMELEN];
1404 struct cdbdata *cdbfr;
1407 long highest_msg = 0L;
1408 struct CtdlMessage *msg = NULL;
1410 lprintf(9, "CtdlSaveMsgPointerInRoom(%s, %ld, %d)\n",
1411 roomname, msgid, flags);
1413 strcpy(hold_rm, CC->quickroom.QRname);
1415 /* We may need to check to see if this message is real */
1416 if ( (flags & SM_VERIFY_GOODNESS)
1417 || (flags & SM_DO_REPL_CHECK)
1419 msg = CtdlFetchMessage(msgid);
1420 if (msg == NULL) return(ERROR + ILLEGAL_VALUE);
1423 /* Perform replication checks if necessary */
1424 if ( (flags & SM_DO_REPL_CHECK) && (msg != NULL) ) {
1426 if (getroom(&CC->quickroom,
1427 ((roomname != NULL) ? roomname : CC->quickroom.QRname) )
1429 lprintf(9, "No such room <%s>\n", roomname);
1430 if (msg != NULL) CtdlFreeMessage(msg);
1431 return(ERROR + ROOM_NOT_FOUND);
1434 if (ReplicationChecks(msg) != 0) {
1435 getroom(&CC->quickroom, hold_rm);
1436 if (msg != NULL) CtdlFreeMessage(msg);
1437 lprintf(9, "Did replication, and newer exists\n");
1442 /* Now the regular stuff */
1443 if (lgetroom(&CC->quickroom,
1444 ((roomname != NULL) ? roomname : CC->quickroom.QRname) )
1446 lprintf(9, "No such room <%s>\n", roomname);
1447 if (msg != NULL) CtdlFreeMessage(msg);
1448 return(ERROR + ROOM_NOT_FOUND);
1451 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long));
1452 if (cdbfr == NULL) {
1456 msglist = mallok(cdbfr->len);
1457 if (msglist == NULL)
1458 lprintf(3, "ERROR malloc msglist!\n");
1459 num_msgs = cdbfr->len / sizeof(long);
1460 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1465 /* Make sure the message doesn't already exist in this room. It
1466 * is absolutely taboo to have more than one reference to the same
1467 * message in a room.
1469 if (num_msgs > 0) for (i=0; i<num_msgs; ++i) {
1470 if (msglist[i] == msgid) {
1471 lputroom(&CC->quickroom); /* unlock the room */
1472 getroom(&CC->quickroom, hold_rm);
1473 if (msg != NULL) CtdlFreeMessage(msg);
1474 return(ERROR + ALREADY_EXISTS);
1478 /* Now add the new message */
1480 msglist = reallok(msglist,
1481 (num_msgs * sizeof(long)));
1483 if (msglist == NULL) {
1484 lprintf(3, "ERROR: can't realloc message list!\n");
1486 msglist[num_msgs - 1] = msgid;
1488 /* Sort the message list, so all the msgid's are in order */
1489 num_msgs = sort_msglist(msglist, num_msgs);
1491 /* Determine the highest message number */
1492 highest_msg = msglist[num_msgs - 1];
1494 /* Write it back to disk. */
1495 cdb_store(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long),
1496 msglist, num_msgs * sizeof(long));
1498 /* Free up the memory we used. */
1501 /* Update the highest-message pointer and unlock the room. */
1502 CC->quickroom.QRhighest = highest_msg;
1503 lputroom(&CC->quickroom);
1504 getroom(&CC->quickroom, hold_rm);
1506 /* Bump the reference count for this message. */
1507 if ((flags & SM_DONT_BUMP_REF)==0) {
1508 AdjRefCount(msgid, +1);
1511 /* Return success. */
1512 if (msg != NULL) CtdlFreeMessage(msg);
1519 * Message base operation to send a message to the master file
1520 * (returns new message number)
1522 * This is the back end for CtdlSubmitMsg() and should not be directly
1523 * called by server-side modules.
1526 long send_message(struct CtdlMessage *msg, /* pointer to buffer */
1527 FILE *save_a_copy) /* save a copy to disk? */
1534 /* Get a new message number */
1535 newmsgid = get_new_message_number();
1536 sprintf(msgidbuf, "%ld@%s", newmsgid, config.c_fqdn);
1538 /* Generate an ID if we don't have one already */
1539 if (msg->cm_fields['I']==NULL) {
1540 msg->cm_fields['I'] = strdoop(msgidbuf);
1543 serialize_message(&smr, msg);
1546 cprintf("%d Unable to serialize message\n",
1547 ERROR+INTERNAL_ERROR);
1551 /* Write our little bundle of joy into the message base */
1552 if (cdb_store(CDB_MSGMAIN, &newmsgid, sizeof(long),
1553 smr.ser, smr.len) < 0) {
1554 lprintf(2, "Can't store message\n");
1560 /* If the caller specified that a copy should be saved to a particular
1561 * file handle, do that now too.
1563 if (save_a_copy != NULL) {
1564 fwrite(smr.ser, smr.len, 1, save_a_copy);
1567 /* Free the memory we used for the serialized message */
1570 /* Return the *local* message ID to the caller
1571 * (even if we're storing an incoming network message)
1579 * Serialize a struct CtdlMessage into the format used on disk and network.
1581 * This function loads up a "struct ser_ret" (defined in server.h) which
1582 * contains the length of the serialized message and a pointer to the
1583 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
1585 void serialize_message(struct ser_ret *ret, /* return values */
1586 struct CtdlMessage *msg) /* unserialized msg */
1590 static char *forder = FORDER;
1592 if (is_valid_message(msg) == 0) return; /* self check */
1595 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
1596 ret->len = ret->len +
1597 strlen(msg->cm_fields[(int)forder[i]]) + 2;
1599 lprintf(9, "serialize_message() calling malloc(%ld)\n", (long)ret->len);
1600 ret->ser = mallok(ret->len);
1601 if (ret->ser == NULL) {
1607 ret->ser[1] = msg->cm_anon_type;
1608 ret->ser[2] = msg->cm_format_type;
1611 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
1612 ret->ser[wlen++] = (char)forder[i];
1613 strcpy(&ret->ser[wlen], msg->cm_fields[(int)forder[i]]);
1614 wlen = wlen + strlen(msg->cm_fields[(int)forder[i]]) + 1;
1616 if (ret->len != wlen) lprintf(3, "ERROR: len=%ld wlen=%ld\n",
1617 (long)ret->len, (long)wlen);
1625 * Back end for the ReplicationChecks() function
1627 void check_repl(long msgnum, void *userdata) {
1628 struct CtdlMessage *msg;
1629 time_t timestamp = (-1L);
1631 lprintf(9, "check_repl() found message %ld\n", msgnum);
1632 msg = CtdlFetchMessage(msgnum);
1633 if (msg == NULL) return;
1634 if (msg->cm_fields['T'] != NULL) {
1635 timestamp = atol(msg->cm_fields['T']);
1637 CtdlFreeMessage(msg);
1639 if (timestamp > msg_repl->highest) {
1640 msg_repl->highest = timestamp; /* newer! */
1641 lprintf(9, "newer!\n");
1644 lprintf(9, "older!\n");
1646 /* Existing isn't newer? Then delete the old one(s). */
1647 CtdlDeleteMessages(CC->quickroom.QRname, msgnum, "");
1652 * Check to see if any messages already exist which carry the same Extended ID
1656 * -> With older timestamps: delete them and return 0. Message will be saved.
1657 * -> With newer timestamps: return 1. Message save will be aborted.
1659 int ReplicationChecks(struct CtdlMessage *msg) {
1660 struct CtdlMessage *template;
1663 lprintf(9, "ReplicationChecks() started\n");
1664 /* No extended id? Don't do anything. */
1665 if (msg->cm_fields['E'] == NULL) return 0;
1666 if (strlen(msg->cm_fields['E']) == 0) return 0;
1667 lprintf(9, "Extended ID: <%s>\n", msg->cm_fields['E']);
1669 CtdlAllocUserData(SYM_REPL, sizeof(struct repl));
1670 strcpy(msg_repl->extended_id, msg->cm_fields['E']);
1671 msg_repl->highest = atol(msg->cm_fields['T']);
1673 template = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1674 memset(template, 0, sizeof(struct CtdlMessage));
1675 template->cm_fields['E'] = strdoop(msg->cm_fields['E']);
1677 CtdlForEachMessage(MSGS_ALL, 0L, (-127), NULL, template,
1680 /* If a newer message exists with the same Extended ID, abort
1683 if (msg_repl->highest > atol(msg->cm_fields['T']) ) {
1687 CtdlFreeMessage(template);
1688 lprintf(9, "ReplicationChecks() returning %d\n", abort_this);
1696 * Save a message to disk and submit it into the delivery system.
1698 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
1699 struct recptypes *recps, /* recipients (if mail) */
1700 char *force /* force a particular room? */
1703 char hold_rm[ROOMNAMELEN];
1704 char actual_rm[ROOMNAMELEN];
1705 char force_room[ROOMNAMELEN];
1706 char content_type[SIZ]; /* We have to learn this */
1707 char recipient[SIZ];
1710 struct usersupp userbuf;
1712 struct MetaData smi;
1713 FILE *network_fp = NULL;
1714 static int seqnum = 1;
1715 struct CtdlMessage *imsg = NULL;
1718 char *hold_R, *hold_D;
1720 lprintf(9, "CtdlSubmitMsg() called\n");
1721 if (is_valid_message(msg) == 0) return(-1); /* self check */
1723 /* If this message has no timestamp, we take the liberty of
1724 * giving it one, right now.
1726 if (msg->cm_fields['T'] == NULL) {
1727 lprintf(9, "Generating timestamp\n");
1728 sprintf(aaa, "%ld", (long)time(NULL));
1729 msg->cm_fields['T'] = strdoop(aaa);
1732 /* If this message has no path, we generate one.
1734 if (msg->cm_fields['P'] == NULL) {
1735 lprintf(9, "Generating path\n");
1736 if (msg->cm_fields['A'] != NULL) {
1737 msg->cm_fields['P'] = strdoop(msg->cm_fields['A']);
1738 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
1739 if (isspace(msg->cm_fields['P'][a])) {
1740 msg->cm_fields['P'][a] = ' ';
1745 msg->cm_fields['P'] = strdoop("unknown");
1749 strcpy(force_room, force);
1751 /* Learn about what's inside, because it's what's inside that counts */
1752 lprintf(9, "Learning what's inside\n");
1753 if (msg->cm_fields['M'] == NULL) {
1754 lprintf(1, "ERROR: attempt to save message with NULL body\n");
1757 switch (msg->cm_format_type) {
1759 strcpy(content_type, "text/x-citadel-variformat");
1762 strcpy(content_type, "text/plain");
1765 strcpy(content_type, "text/plain");
1766 /* advance past header fields */
1767 mptr = msg->cm_fields['M'];
1770 if (!strncasecmp(mptr, "Content-type: ", 14)) {
1771 safestrncpy(content_type, mptr,
1772 sizeof(content_type));
1773 strcpy(content_type, &content_type[14]);
1774 for (a = 0; a < strlen(content_type); ++a)
1775 if ((content_type[a] == ';')
1776 || (content_type[a] == ' ')
1777 || (content_type[a] == 13)
1778 || (content_type[a] == 10))
1779 content_type[a] = 0;
1786 /* Goto the correct room */
1787 lprintf(9, "Switching rooms\n");
1788 strcpy(hold_rm, CC->quickroom.QRname);
1789 strcpy(actual_rm, CC->quickroom.QRname);
1790 if (recps != NULL) {
1791 strcpy(actual_rm, SENTITEMS);
1794 /* If the user is a twit, move to the twit room for posting */
1795 lprintf(9, "Handling twit stuff\n");
1797 if (CC->usersupp.axlevel == 2) {
1798 strcpy(hold_rm, actual_rm);
1799 strcpy(actual_rm, config.c_twitroom);
1803 /* ...or if this message is destined for Aide> then go there. */
1804 if (strlen(force_room) > 0) {
1805 strcpy(actual_rm, force_room);
1808 lprintf(9, "Possibly relocating\n");
1809 if (strcasecmp(actual_rm, CC->quickroom.QRname)) {
1810 getroom(&CC->quickroom, actual_rm);
1814 * If this message has no O (room) field, generate one.
1816 if (msg->cm_fields['O'] == NULL) {
1817 msg->cm_fields['O'] = strdoop(CC->quickroom.QRname);
1820 /* Perform "before save" hooks (aborting if any return nonzero) */
1821 lprintf(9, "Performing before-save hooks\n");
1822 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-1);
1824 /* If this message has an Extended ID, perform replication checks */
1825 lprintf(9, "Performing replication checks\n");
1826 if (ReplicationChecks(msg) > 0) return(-1);
1828 /* Save it to disk */
1829 lprintf(9, "Saving to disk\n");
1830 newmsgid = send_message(msg, NULL);
1831 if (newmsgid <= 0L) return(-1);
1833 /* Write a supplemental message info record. This doesn't have to
1834 * be a critical section because nobody else knows about this message
1837 lprintf(9, "Creating MetaData record\n");
1838 memset(&smi, 0, sizeof(struct MetaData));
1839 smi.meta_msgnum = newmsgid;
1840 smi.meta_refcount = 0;
1841 safestrncpy(smi.meta_content_type, content_type, 64);
1844 /* Now figure out where to store the pointers */
1845 lprintf(9, "Storing pointers\n");
1847 /* If this is being done by the networker delivering a private
1848 * message, we want to BYPASS saving the sender's copy (because there
1849 * is no local sender; it would otherwise go to the Trashcan).
1851 if ((!CC->internal_pgm) || (recps == NULL)) {
1852 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0) != 0) {
1853 lprintf(3, "ERROR saving message pointer!\n");
1854 CtdlSaveMsgPointerInRoom(AIDEROOM, newmsgid, 0);
1858 /* For internet mail, drop a copy in the outbound queue room */
1860 if (recps->num_internet > 0) {
1861 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0);
1864 /* If other rooms are specified, drop them there too. */
1866 if (recps->num_room > 0)
1867 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
1868 extract(recipient, recps->recp_room, i);
1869 lprintf(9, "Delivering to local room <%s>\n", recipient);
1870 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0);
1873 /* Bump this user's messages posted counter. */
1874 lprintf(9, "Updating user\n");
1875 lgetuser(&CC->usersupp, CC->curr_user);
1876 CC->usersupp.posted = CC->usersupp.posted + 1;
1877 lputuser(&CC->usersupp);
1879 /* If this is private, local mail, make a copy in the
1880 * recipient's mailbox and bump the reference count.
1883 if (recps->num_local > 0)
1884 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
1885 extract(recipient, recps->recp_local, i);
1886 lprintf(9, "Delivering private local mail to <%s>\n",
1888 if (getuser(&userbuf, recipient) == 0) {
1889 MailboxName(actual_rm, &userbuf, MAILROOM);
1890 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0);
1893 lprintf(9, "No user <%s>\n", recipient);
1894 CtdlSaveMsgPointerInRoom(AIDEROOM, newmsgid, 0);
1898 /* Perform "after save" hooks */
1899 lprintf(9, "Performing after-save hooks\n");
1900 PerformMessageHooks(msg, EVT_AFTERSAVE);
1902 /* For IGnet mail, we have to save a new copy into the spooler for
1903 * each recipient, with the R and D fields set to the recipient and
1904 * destination-node. This has two ugly side effects: all other
1905 * recipients end up being unlisted in this recipient's copy of the
1906 * message, and it has to deliver multiple messages to the same
1907 * node. We'll revisit this again in a year or so when everyone has
1908 * a network spool receiver that can handle the new style messages.
1911 if (recps->num_ignet > 0)
1912 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
1913 extract(recipient, recps->recp_ignet, i);
1915 hold_R = msg->cm_fields['R'];
1916 hold_D = msg->cm_fields['D'];
1917 msg->cm_fields['R'] = mallok(SIZ);
1918 msg->cm_fields['D'] = mallok(SIZ);
1919 extract_token(msg->cm_fields['R'], recipient, 0, '@');
1920 extract_token(msg->cm_fields['D'], recipient, 1, '@');
1922 serialize_message(&smr, msg);
1925 "./network/spoolin/netmail.%04lx.%04x.%04x",
1926 (long) getpid(), CC->cs_pid, ++seqnum);
1927 network_fp = fopen(aaa, "wb+");
1928 if (network_fp != NULL) {
1929 fwrite(smr.ser, smr.len, 1, network_fp);
1935 phree(msg->cm_fields['R']);
1936 phree(msg->cm_fields['D']);
1937 msg->cm_fields['R'] = hold_R;
1938 msg->cm_fields['D'] = hold_D;
1941 /* Go back to the room we started from */
1942 lprintf(9, "Returning to original room\n");
1943 if (strcasecmp(hold_rm, CC->quickroom.QRname))
1944 getroom(&CC->quickroom, hold_rm);
1946 /* For internet mail, generate delivery instructions.
1947 * Yes, this is recursive. Deal with it. Infinite recursion does
1948 * not happen because the delivery instructions message does not
1949 * contain a recipient.
1952 if (recps->num_internet > 0) {
1953 lprintf(9, "Generating delivery instructions\n");
1954 instr = mallok(SIZ * 2);
1956 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
1958 SPOOLMIME, newmsgid, (long)time(NULL),
1959 msg->cm_fields['A'], msg->cm_fields['N']
1962 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
1963 extract(recipient, recps->recp_internet, i);
1964 sprintf(&instr[strlen(instr)],
1965 "remote|%s|0||\n", recipient);
1968 imsg = mallok(sizeof(struct CtdlMessage));
1969 memset(imsg, 0, sizeof(struct CtdlMessage));
1970 imsg->cm_magic = CTDLMESSAGE_MAGIC;
1971 imsg->cm_anon_type = MES_NORMAL;
1972 imsg->cm_format_type = FMT_RFC822;
1973 imsg->cm_fields['A'] = strdoop("Citadel");
1974 imsg->cm_fields['M'] = instr;
1975 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
1976 CtdlFreeMessage(imsg);
1985 * Convenience function for generating small administrative messages.
1987 void quickie_message(char *from, char *to, char *room, char *text)
1989 struct CtdlMessage *msg;
1991 msg = mallok(sizeof(struct CtdlMessage));
1992 memset(msg, 0, sizeof(struct CtdlMessage));
1993 msg->cm_magic = CTDLMESSAGE_MAGIC;
1994 msg->cm_anon_type = MES_NORMAL;
1995 msg->cm_format_type = 0;
1996 msg->cm_fields['A'] = strdoop(from);
1997 msg->cm_fields['O'] = strdoop(room);
1998 msg->cm_fields['N'] = strdoop(NODENAME);
2000 msg->cm_fields['R'] = strdoop(to);
2001 msg->cm_fields['M'] = strdoop(text);
2003 CtdlSubmitMsg(msg, NULL, room);
2004 CtdlFreeMessage(msg);
2005 syslog(LOG_NOTICE, text);
2011 * Back end function used by make_message() and similar functions
2013 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2014 size_t maxlen, /* maximum message length */
2015 char *exist /* if non-null, append to it;
2016 exist is ALWAYS freed */
2020 size_t message_len = 0;
2021 size_t buffer_len = 0;
2025 if (exist == NULL) {
2032 message_len = strlen(exist);
2033 buffer_len = message_len + 4096;
2034 m = reallok(exist, buffer_len);
2041 /* flush the input if we have nowhere to store it */
2043 while ( (client_gets(buf)>0) && strcmp(buf, terminator) ) ;;
2047 /* read in the lines of message text one by one */
2048 while ( (client_gets(buf)>0) && strcmp(buf, terminator) ) {
2050 /* strip trailing newline type stuff */
2051 if (buf[strlen(buf)-1]==10) buf[strlen(buf)-1]=0;
2052 if (buf[strlen(buf)-1]==13) buf[strlen(buf)-1]=0;
2054 linelen = strlen(buf);
2056 /* augment the buffer if we have to */
2057 if ((message_len + linelen + 2) > buffer_len) {
2058 lprintf(9, "realloking\n");
2059 ptr = reallok(m, (buffer_len * 2) );
2060 if (ptr == NULL) { /* flush if can't allocate */
2061 while ( (client_gets(buf)>0) &&
2062 strcmp(buf, terminator)) ;;
2065 buffer_len = (buffer_len * 2);
2067 lprintf(9, "buffer_len is %ld\n", (long)buffer_len);
2071 /* Add the new line to the buffer. NOTE: this loop must avoid
2072 * using functions like strcat() and strlen() because they
2073 * traverse the entire buffer upon every call, and doing that
2074 * for a multi-megabyte message slows it down beyond usability.
2076 strcpy(&m[message_len], buf);
2077 m[message_len + linelen] = '\n';
2078 m[message_len + linelen + 1] = 0;
2079 message_len = message_len + linelen + 1;
2081 /* if we've hit the max msg length, flush the rest */
2082 if (message_len >= maxlen) {
2083 while ( (client_gets(buf)>0)
2084 && strcmp(buf, terminator)) ;;
2095 * Build a binary message to be saved on disk.
2098 static struct CtdlMessage *make_message(
2099 struct usersupp *author, /* author's usersupp structure */
2100 char *recipient, /* NULL if it's not mail */
2101 char *room, /* room where it's going */
2102 int type, /* see MES_ types in header file */
2103 int format_type, /* variformat, plain text, MIME... */
2104 char *fake_name, /* who we're masquerading as */
2105 char *subject /* Subject (optional) */
2107 char dest_node[SIZ];
2109 struct CtdlMessage *msg;
2111 msg = mallok(sizeof(struct CtdlMessage));
2112 memset(msg, 0, sizeof(struct CtdlMessage));
2113 msg->cm_magic = CTDLMESSAGE_MAGIC;
2114 msg->cm_anon_type = type;
2115 msg->cm_format_type = format_type;
2117 /* Don't confuse the poor folks if it's not routed mail. */
2118 strcpy(dest_node, "");
2122 sprintf(buf, "cit%ld", author->usernum); /* Path */
2123 msg->cm_fields['P'] = strdoop(buf);
2125 sprintf(buf, "%ld", (long)time(NULL)); /* timestamp */
2126 msg->cm_fields['T'] = strdoop(buf);
2128 if (fake_name[0]) /* author */
2129 msg->cm_fields['A'] = strdoop(fake_name);
2131 msg->cm_fields['A'] = strdoop(author->fullname);
2133 if (CC->quickroom.QRflags & QR_MAILBOX) { /* room */
2134 msg->cm_fields['O'] = strdoop(&CC->quickroom.QRname[11]);
2137 msg->cm_fields['O'] = strdoop(CC->quickroom.QRname);
2140 msg->cm_fields['N'] = strdoop(NODENAME); /* nodename */
2141 msg->cm_fields['H'] = strdoop(HUMANNODE); /* hnodename */
2143 if (recipient[0] != 0) {
2144 msg->cm_fields['R'] = strdoop(recipient);
2146 if (dest_node[0] != 0) {
2147 msg->cm_fields['D'] = strdoop(dest_node);
2150 if ( (author == &CC->usersupp) && (CC->cs_inet_email != NULL) ) {
2151 msg->cm_fields['F'] = strdoop(CC->cs_inet_email);
2154 if (subject != NULL) {
2156 if (strlen(subject) > 0) {
2157 msg->cm_fields['U'] = strdoop(subject);
2161 msg->cm_fields['M'] = CtdlReadMessageBody("000",
2162 config.c_maxmsglen, NULL);
2169 * Check to see whether we have permission to post a message in the current
2170 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
2171 * returns 0 on success.
2173 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf) {
2175 if (!(CC->logged_in)) {
2176 sprintf(errmsgbuf, "Not logged in.");
2177 return (ERROR + NOT_LOGGED_IN);
2180 if ((CC->usersupp.axlevel < 2)
2181 && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)) {
2182 sprintf(errmsgbuf, "Need to be validated to enter "
2183 "(except in %s> to sysop)", MAILROOM);
2184 return (ERROR + HIGHER_ACCESS_REQUIRED);
2187 if ((CC->usersupp.axlevel < 4)
2188 && (CC->quickroom.QRflags & QR_NETWORK)) {
2189 sprintf(errmsgbuf, "Need net privileges to enter here.");
2190 return (ERROR + HIGHER_ACCESS_REQUIRED);
2193 if ((CC->usersupp.axlevel < 6)
2194 && (CC->quickroom.QRflags & QR_READONLY)) {
2195 sprintf(errmsgbuf, "Sorry, this is a read-only room.");
2196 return (ERROR + HIGHER_ACCESS_REQUIRED);
2199 strcpy(errmsgbuf, "Ok");
2205 * Validate recipients, count delivery types and errors, and handle aliasing
2206 * FIXME check for dupes!!!!!
2208 struct recptypes *validate_recipients(char *recipients) {
2209 struct recptypes *ret;
2210 char this_recp[SIZ];
2211 char this_recp_cooked[SIZ];
2217 struct usersupp tempUS;
2218 struct quickroom tempQR;
2221 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
2222 if (ret == NULL) return(NULL);
2223 memset(ret, 0, sizeof(struct recptypes));
2226 ret->num_internet = 0;
2231 if (recipients == NULL) {
2234 else if (strlen(recipients) == 0) {
2238 /* Change all valid separator characters to commas */
2239 for (i=0; i<strlen(recipients); ++i) {
2240 if ((recipients[i] == ';') || (recipients[i] == '|')) {
2241 recipients[i] = ',';
2246 num_recps = num_tokens(recipients, ',');
2249 if (num_recps > 0) for (i=0; i<num_recps; ++i) {
2250 extract_token(this_recp, recipients, i, ',');
2252 lprintf(9, "Evaluating recipient #%d <%s>\n", i, this_recp);
2253 mailtype = alias(this_recp);
2254 mailtype = alias(this_recp);
2255 mailtype = alias(this_recp);
2256 for (j=0; j<=strlen(this_recp); ++j) {
2257 if (this_recp[j]=='_') {
2258 this_recp_cooked[j] = ' ';
2261 this_recp_cooked[j] = this_recp[j];
2267 if (!strcasecmp(this_recp, "sysop")) {
2269 strcpy(this_recp, AIDEROOM);
2270 if (strlen(ret->recp_room) > 0) {
2271 strcat(ret->recp_room, "|");
2273 strcat(ret->recp_room, this_recp);
2275 else if (getuser(&tempUS, this_recp) == 0) {
2277 strcpy(this_recp, tempUS.fullname);
2278 if (strlen(ret->recp_local) > 0) {
2279 strcat(ret->recp_local, "|");
2281 strcat(ret->recp_local, this_recp);
2283 else if (getuser(&tempUS, this_recp_cooked) == 0) {
2285 strcpy(this_recp, tempUS.fullname);
2286 if (strlen(ret->recp_local) > 0) {
2287 strcat(ret->recp_local, "|");
2289 strcat(ret->recp_local, this_recp);
2291 else if ( (!strncasecmp(this_recp, "room_", 5))
2292 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
2294 if (strlen(ret->recp_room) > 0) {
2295 strcat(ret->recp_room, "|");
2297 strcat(ret->recp_room, &this_recp_cooked[5]);
2305 ++ret->num_internet;
2306 if (strlen(ret->recp_internet) > 0) {
2307 strcat(ret->recp_internet, "|");
2309 strcat(ret->recp_internet, this_recp);
2313 if (strlen(ret->recp_ignet) > 0) {
2314 strcat(ret->recp_ignet, "|");
2316 strcat(ret->recp_ignet, this_recp);
2324 if (strlen(ret->errormsg) == 0) {
2326 "Invalid recipient: %s",
2333 if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
2334 strcat(ret->errormsg, append);
2338 if (strlen(ret->display_recp) == 0) {
2339 strcpy(append, this_recp);
2342 sprintf(append, ", %s", this_recp);
2344 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
2345 strcat(ret->display_recp, append);
2350 if ((ret->num_local + ret->num_internet + ret->num_ignet +
2351 ret->num_room + ret->num_error) == 0) {
2353 strcpy(ret->errormsg, "No recipients specified.");
2356 lprintf(9, "validate_recipients()\n");
2357 lprintf(9, " local: %d <%s>\n", ret->num_local, ret->recp_local);
2358 lprintf(9, " room: %d <%s>\n", ret->num_room, ret->recp_room);
2359 lprintf(9, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
2360 lprintf(9, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
2361 lprintf(9, " error: %d <%s>\n", ret->num_error, ret->errormsg);
2369 * message entry - mode 0 (normal)
2371 void cmd_ent0(char *entargs)
2375 char masquerade_as[SIZ];
2377 int format_type = 0;
2378 char newusername[SIZ];
2379 struct CtdlMessage *msg;
2383 struct recptypes *valid = NULL;
2386 post = extract_int(entargs, 0);
2387 extract(recp, entargs, 1);
2388 anon_flag = extract_int(entargs, 2);
2389 format_type = extract_int(entargs, 3);
2390 extract(subject, entargs, 4);
2392 /* first check to make sure the request is valid. */
2394 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg);
2396 cprintf("%d %s\n", err, errmsg);
2400 /* Check some other permission type things. */
2403 if (CC->usersupp.axlevel < 6) {
2404 cprintf("%d You don't have permission to masquerade.\n",
2405 ERROR + HIGHER_ACCESS_REQUIRED);
2408 extract(newusername, entargs, 4);
2409 memset(CC->fake_postname, 0, sizeof(CC->fake_postname) );
2410 safestrncpy(CC->fake_postname, newusername,
2411 sizeof(CC->fake_postname) );
2412 cprintf("%d ok\n", OK);
2415 CC->cs_flags |= CS_POSTING;
2417 if (CC->quickroom.QRflags & QR_MAILBOX) {
2418 if (CC->usersupp.axlevel < 2) {
2419 strcpy(recp, "sysop");
2422 valid = validate_recipients(recp);
2423 if (valid->num_error > 0) {
2425 ERROR + NO_SUCH_USER, valid->errormsg);
2430 if ( ( (valid->num_internet + valid->num_ignet) > 0)
2431 && (CC->usersupp.axlevel < 4) ) {
2432 cprintf("%d Higher access required for network mail.\n",
2433 ERROR + HIGHER_ACCESS_REQUIRED);
2438 if ((RESTRICT_INTERNET == 1) && (valid->num_internet > 0)
2439 && ((CC->usersupp.flags & US_INTERNET) == 0)
2440 && (!CC->internal_pgm)) {
2441 cprintf("%d You don't have access to Internet mail.\n",
2442 ERROR + HIGHER_ACCESS_REQUIRED);
2449 /* Is this a room which has anonymous-only or anonymous-option? */
2450 anonymous = MES_NORMAL;
2451 if (CC->quickroom.QRflags & QR_ANONONLY) {
2452 anonymous = MES_ANONONLY;
2454 if (CC->quickroom.QRflags & QR_ANONOPT) {
2455 if (anon_flag == 1) { /* only if the user requested it */
2456 anonymous = MES_ANONOPT;
2460 if ((CC->quickroom.QRflags & QR_MAILBOX) == 0) {
2464 /* If we're only checking the validity of the request, return
2465 * success without creating the message.
2468 cprintf("%d %s\n", OK,
2469 ((valid != NULL) ? valid->display_recp : "") );
2474 /* Handle author masquerading */
2475 if (CC->fake_postname[0]) {
2476 strcpy(masquerade_as, CC->fake_postname);
2478 else if (CC->fake_username[0]) {
2479 strcpy(masquerade_as, CC->fake_username);
2482 strcpy(masquerade_as, "");
2485 /* Read in the message from the client. */
2486 cprintf("%d send message\n", SEND_LISTING);
2487 msg = make_message(&CC->usersupp, recp,
2488 CC->quickroom.QRname, anonymous, format_type,
2489 masquerade_as, subject);
2492 CtdlSubmitMsg(msg, valid, "");
2493 CtdlFreeMessage(msg);
2495 CC->fake_postname[0] = '\0';
2503 * API function to delete messages which match a set of criteria
2504 * (returns the actual number of messages deleted)
2506 int CtdlDeleteMessages(char *room_name, /* which room */
2507 long dmsgnum, /* or "0" for any */
2508 char *content_type /* or "" for any */
2512 struct quickroom qrbuf;
2513 struct cdbdata *cdbfr;
2514 long *msglist = NULL;
2515 long *dellist = NULL;
2518 int num_deleted = 0;
2520 struct MetaData smi;
2522 lprintf(9, "CtdlDeleteMessages(%s, %ld, %s)\n",
2523 room_name, dmsgnum, content_type);
2525 /* get room record, obtaining a lock... */
2526 if (lgetroom(&qrbuf, room_name) != 0) {
2527 lprintf(7, "CtdlDeleteMessages(): Room <%s> not found\n",
2529 return (0); /* room not found */
2531 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
2533 if (cdbfr != NULL) {
2534 msglist = mallok(cdbfr->len);
2535 dellist = mallok(cdbfr->len);
2536 memcpy(msglist, cdbfr->ptr, cdbfr->len);
2537 num_msgs = cdbfr->len / sizeof(long);
2541 for (i = 0; i < num_msgs; ++i) {
2544 /* Set/clear a bit for each criterion */
2546 if ((dmsgnum == 0L) || (msglist[i] == dmsgnum)) {
2547 delete_this |= 0x01;
2549 if (strlen(content_type) == 0) {
2550 delete_this |= 0x02;
2552 GetMetaData(&smi, msglist[i]);
2553 if (!strcasecmp(smi.meta_content_type,
2555 delete_this |= 0x02;
2559 /* Delete message only if all bits are set */
2560 if (delete_this == 0x03) {
2561 dellist[num_deleted++] = msglist[i];
2566 num_msgs = sort_msglist(msglist, num_msgs);
2567 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long),
2568 msglist, (num_msgs * sizeof(long)));
2570 qrbuf.QRhighest = msglist[num_msgs - 1];
2574 /* Go through the messages we pulled out of the index, and decrement
2575 * their reference counts by 1. If this is the only room the message
2576 * was in, the reference count will reach zero and the message will
2577 * automatically be deleted from the database. We do this in a
2578 * separate pass because there might be plug-in hooks getting called,
2579 * and we don't want that happening during an S_QUICKROOM critical
2582 if (num_deleted) for (i=0; i<num_deleted; ++i) {
2583 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
2584 AdjRefCount(dellist[i], -1);
2587 /* Now free the memory we used, and go away. */
2588 if (msglist != NULL) phree(msglist);
2589 if (dellist != NULL) phree(dellist);
2590 lprintf(9, "%d message(s) deleted.\n", num_deleted);
2591 return (num_deleted);
2597 * Check whether the current user has permission to delete messages from
2598 * the current room (returns 1 for yes, 0 for no)
2600 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
2601 getuser(&CC->usersupp, CC->curr_user);
2602 if ((CC->usersupp.axlevel < 6)
2603 && (CC->usersupp.usernum != CC->quickroom.QRroomaide)
2604 && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)
2605 && (!(CC->internal_pgm))) {
2614 * Delete message from current room
2616 void cmd_dele(char *delstr)
2621 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
2622 cprintf("%d Higher access required.\n",
2623 ERROR + HIGHER_ACCESS_REQUIRED);
2626 delnum = extract_long(delstr, 0);
2628 num_deleted = CtdlDeleteMessages(CC->quickroom.QRname, delnum, "");
2631 cprintf("%d %d message%s deleted.\n", OK,
2632 num_deleted, ((num_deleted != 1) ? "s" : ""));
2634 cprintf("%d Message %ld not found.\n", ERROR, delnum);
2640 * Back end API function for moves and deletes
2642 int CtdlCopyMsgToRoom(long msgnum, char *dest) {
2645 err = CtdlSaveMsgPointerInRoom(dest, msgnum,
2646 (SM_VERIFY_GOODNESS | SM_DO_REPL_CHECK) );
2647 if (err != 0) return(err);
2655 * move or copy a message to another room
2657 void cmd_move(char *args)
2661 struct quickroom qtemp;
2665 num = extract_long(args, 0);
2666 extract(targ, args, 1);
2667 targ[ROOMNAMELEN - 1] = 0;
2668 is_copy = extract_int(args, 2);
2670 if (getroom(&qtemp, targ) != 0) {
2671 cprintf("%d '%s' does not exist.\n", ERROR, targ);
2675 getuser(&CC->usersupp, CC->curr_user);
2676 /* Aides can move/copy */
2677 if ((CC->usersupp.axlevel < 6)
2678 /* Roomaides can move/copy */
2679 && (CC->usersupp.usernum != CC->quickroom.QRroomaide)
2680 /* Permit move/copy to/from personal rooms */
2681 && (!((CC->quickroom.QRflags & QR_MAILBOX)
2682 && (qtemp.QRflags & QR_MAILBOX)))
2683 /* Permit only copy from public to personal room */
2684 && (!(is_copy && !(CC->quickroom.QRflags & QR_MAILBOX)
2685 && (qtemp.QRflags & QR_MAILBOX)))) {
2686 cprintf("%d Higher access required.\n",
2687 ERROR + HIGHER_ACCESS_REQUIRED);
2691 err = CtdlCopyMsgToRoom(num, targ);
2693 cprintf("%d Cannot store message in %s: error %d\n",
2698 /* Now delete the message from the source room,
2699 * if this is a 'move' rather than a 'copy' operation.
2702 CtdlDeleteMessages(CC->quickroom.QRname, num, "");
2705 cprintf("%d Message %s.\n", OK, (is_copy ? "copied" : "moved") );
2711 * GetMetaData() - Get the supplementary record for a message
2713 void GetMetaData(struct MetaData *smibuf, long msgnum)
2716 struct cdbdata *cdbsmi;
2719 memset(smibuf, 0, sizeof(struct MetaData));
2720 smibuf->meta_msgnum = msgnum;
2721 smibuf->meta_refcount = 1; /* Default reference count is 1 */
2723 /* Use the negative of the message number for its supp record index */
2724 TheIndex = (0L - msgnum);
2726 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
2727 if (cdbsmi == NULL) {
2728 return; /* record not found; go with defaults */
2730 memcpy(smibuf, cdbsmi->ptr,
2731 ((cdbsmi->len > sizeof(struct MetaData)) ?
2732 sizeof(struct MetaData) : cdbsmi->len));
2739 * PutMetaData() - (re)write supplementary record for a message
2741 void PutMetaData(struct MetaData *smibuf)
2745 /* Use the negative of the message number for the metadata db index */
2746 TheIndex = (0L - smibuf->meta_msgnum);
2748 lprintf(9, "PutMetaData(%ld) - ref count is %d\n",
2749 smibuf->meta_msgnum, smibuf->meta_refcount);
2751 cdb_store(CDB_MSGMAIN,
2752 &TheIndex, sizeof(long),
2753 smibuf, sizeof(struct MetaData));
2758 * AdjRefCount - change the reference count for a message;
2759 * delete the message if it reaches zero
2761 void AdjRefCount(long msgnum, int incr)
2764 struct MetaData smi;
2767 /* This is a *tight* critical section; please keep it that way, as
2768 * it may get called while nested in other critical sections.
2769 * Complicating this any further will surely cause deadlock!
2771 begin_critical_section(S_SUPPMSGMAIN);
2772 GetMetaData(&smi, msgnum);
2773 lprintf(9, "Ref count for message <%ld> before write is <%d>\n",
2774 msgnum, smi.meta_refcount);
2775 smi.meta_refcount += incr;
2777 end_critical_section(S_SUPPMSGMAIN);
2778 lprintf(9, "Ref count for message <%ld> after write is <%d>\n",
2779 msgnum, smi.meta_refcount);
2781 /* If the reference count is now zero, delete the message
2782 * (and its supplementary record as well).
2784 if (smi.meta_refcount == 0) {
2785 lprintf(9, "Deleting message <%ld>\n", msgnum);
2787 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
2789 /* We have to delete the metadata record too! */
2790 delnum = (0L - msgnum);
2791 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
2796 * Write a generic object to this room
2798 * Note: this could be much more efficient. Right now we use two temporary
2799 * files, and still pull the message into memory as with all others.
2801 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
2802 char *content_type, /* MIME type of this object */
2803 char *tempfilename, /* Where to fetch it from */
2804 struct usersupp *is_mailbox, /* Mailbox room? */
2805 int is_binary, /* Is encoding necessary? */
2806 int is_unique, /* Del others of this type? */
2807 unsigned int flags /* Internal save flags */
2812 char filename[PATH_MAX];
2815 struct quickroom qrbuf;
2816 char roomname[ROOMNAMELEN];
2817 struct CtdlMessage *msg;
2820 if (is_mailbox != NULL)
2821 MailboxName(roomname, is_mailbox, req_room);
2823 safestrncpy(roomname, req_room, sizeof(roomname));
2824 lprintf(9, "CtdlWriteObject() to <%s> (flags=%d)\n", roomname, flags);
2826 strcpy(filename, tmpnam(NULL));
2827 fp = fopen(filename, "w");
2831 tempfp = fopen(tempfilename, "r");
2832 if (tempfp == NULL) {
2838 fprintf(fp, "Content-type: %s\n", content_type);
2839 lprintf(9, "Content-type: %s\n", content_type);
2841 if (is_binary == 0) {
2842 fprintf(fp, "Content-transfer-encoding: 7bit\n\n");
2843 while (ch = getc(tempfp), ch > 0)
2849 fprintf(fp, "Content-transfer-encoding: base64\n\n");
2852 sprintf(cmdbuf, "./base64 -e <%s >>%s",
2853 tempfilename, filename);
2857 lprintf(9, "Allocating\n");
2858 msg = mallok(sizeof(struct CtdlMessage));
2859 memset(msg, 0, sizeof(struct CtdlMessage));
2860 msg->cm_magic = CTDLMESSAGE_MAGIC;
2861 msg->cm_anon_type = MES_NORMAL;
2862 msg->cm_format_type = 4;
2863 msg->cm_fields['A'] = strdoop(CC->usersupp.fullname);
2864 msg->cm_fields['O'] = strdoop(req_room);
2865 msg->cm_fields['N'] = strdoop(config.c_nodename);
2866 msg->cm_fields['H'] = strdoop(config.c_humannode);
2867 msg->cm_flags = flags;
2869 lprintf(9, "Loading\n");
2870 fp = fopen(filename, "rb");
2871 fseek(fp, 0L, SEEK_END);
2874 msg->cm_fields['M'] = mallok(len);
2875 fread(msg->cm_fields['M'], len, 1, fp);
2879 /* Create the requested room if we have to. */
2880 if (getroom(&qrbuf, roomname) != 0) {
2881 create_room(roomname,
2882 ( (is_mailbox != NULL) ? 5 : 3 ),
2885 /* If the caller specified this object as unique, delete all
2886 * other objects of this type that are currently in the room.
2889 lprintf(9, "Deleted %d other msgs of this type\n",
2890 CtdlDeleteMessages(roomname, 0L, content_type));
2892 /* Now write the data */
2893 CtdlSubmitMsg(msg, NULL, roomname);
2894 CtdlFreeMessage(msg);
2902 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
2903 config_msgnum = msgnum;
2907 char *CtdlGetSysConfig(char *sysconfname) {
2908 char hold_rm[ROOMNAMELEN];
2911 struct CtdlMessage *msg;
2914 strcpy(hold_rm, CC->quickroom.QRname);
2915 if (getroom(&CC->quickroom, SYSCONFIGROOM) != 0) {
2916 getroom(&CC->quickroom, hold_rm);
2921 /* We want the last (and probably only) config in this room */
2922 begin_critical_section(S_CONFIG);
2923 config_msgnum = (-1L);
2924 CtdlForEachMessage(MSGS_LAST, 1, (-127), sysconfname, NULL,
2925 CtdlGetSysConfigBackend, NULL);
2926 msgnum = config_msgnum;
2927 end_critical_section(S_CONFIG);
2933 msg = CtdlFetchMessage(msgnum);
2935 conf = strdoop(msg->cm_fields['M']);
2936 CtdlFreeMessage(msg);
2943 getroom(&CC->quickroom, hold_rm);
2945 if (conf != NULL) do {
2946 extract_token(buf, conf, 0, '\n');
2947 strcpy(conf, &conf[strlen(buf)+1]);
2948 } while ( (strlen(conf)>0) && (strlen(buf)>0) );
2953 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
2954 char temp[PATH_MAX];
2957 strcpy(temp, tmpnam(NULL));
2959 fp = fopen(temp, "w");
2960 if (fp == NULL) return;
2961 fprintf(fp, "%s", sysconfdata);
2964 /* this handy API function does all the work for us */
2965 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);