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"
56 struct addresses_to_be_filed *atbf = NULL;
59 * This really belongs in serv_network.c, but I don't know how to export
60 * symbols between modules.
62 struct FilterList *filterlist = NULL;
66 * These are the four-character field headers we use when outputting
67 * messages in Citadel format (as opposed to RFC822 format).
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,
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,
105 * This function is self explanatory.
106 * (What can I say, I'm in a weird mood today...)
108 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
112 for (i = 0; i < strlen(name); ++i) {
113 if (name[i] == '@') {
114 while (isspace(name[i - 1]) && i > 0) {
115 strcpy(&name[i - 1], &name[i]);
118 while (isspace(name[i + 1])) {
119 strcpy(&name[i + 1], &name[i + 2]);
127 * Aliasing for network mail.
128 * (Error messages have been commented out, because this is a server.)
130 int alias(char *name)
131 { /* process alias and routing info for mail */
134 char aaa[SIZ], bbb[SIZ];
135 char *ignetcfg = NULL;
136 char *ignetmap = NULL;
144 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
145 stripallbut(name, '<', '>');
148 * DIRTY HACK FOLLOWS! due to configs in the network dir in the
149 * legacy installations, we need to calculate ifdeffed here.
160 fp = fopen(filename, "r");
162 fp = fopen("/dev/null", "r");
169 while (fgets(aaa, sizeof aaa, fp) != NULL) {
170 while (isspace(name[0]))
171 strcpy(name, &name[1]);
172 aaa[strlen(aaa) - 1] = 0;
174 for (a = 0; a < strlen(aaa); ++a) {
176 strcpy(bbb, &aaa[a + 1]);
180 if (!strcasecmp(name, aaa))
185 /* Hit the Global Address Book */
186 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
190 lprintf(CTDL_INFO, "Mail is being forwarded to %s\n", name);
192 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
193 for (a=0; a<strlen(name); ++a) {
194 if (name[a] == '@') {
195 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
197 lprintf(CTDL_INFO, "Changed to <%s>\n", name);
202 /* determine local or remote type, see citadel.h */
203 at = haschar(name, '@');
204 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
205 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
206 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
208 /* figure out the delivery mode */
209 extract_token(node, name, 1, '@', sizeof node);
211 /* If there are one or more dots in the nodename, we assume that it
212 * is an FQDN and will attempt SMTP delivery to the Internet.
214 if (haschar(node, '.') > 0) {
215 return(MES_INTERNET);
218 /* Otherwise we look in the IGnet maps for a valid Citadel node.
219 * Try directly-connected nodes first...
221 ignetcfg = CtdlGetSysConfig(IGNETCFG);
222 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
223 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
224 extract_token(testnode, buf, 0, '|', sizeof testnode);
225 if (!strcasecmp(node, testnode)) {
233 * Then try nodes that are two or more hops away.
235 ignetmap = CtdlGetSysConfig(IGNETMAP);
236 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
237 extract_token(buf, ignetmap, i, '\n', sizeof buf);
238 extract_token(testnode, buf, 0, '|', sizeof testnode);
239 if (!strcasecmp(node, testnode)) {
246 /* If we get to this point it's an invalid node name */
258 "%s/citadel.control",
262 fp = fopen(filename, "r");
264 lprintf(CTDL_CRIT, "Cannot open citadel.control: %s\n",
268 fread((char *) &CitControl, sizeof(struct CitControl), 1, fp);
274 * Back end for the MSGS command: output message number only.
276 void simple_listing(long msgnum, void *userdata)
278 cprintf("%ld\n", msgnum);
284 * Back end for the MSGS command: output header summary.
286 void headers_listing(long msgnum, void *userdata)
288 struct CtdlMessage *msg;
290 msg = CtdlFetchMessage(msgnum, 0);
292 cprintf("%ld|0|||||\n", msgnum);
296 cprintf("%ld|%s|%s|%s|%s|%s|\n",
298 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
299 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
300 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
301 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
302 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
304 CtdlFreeMessage(msg);
309 /* Determine if a given message matches the fields in a message template.
310 * Return 0 for a successful match.
312 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
315 /* If there aren't any fields in the template, all messages will
318 if (template == NULL) return(0);
320 /* Null messages are bogus. */
321 if (msg == NULL) return(1);
323 for (i='A'; i<='Z'; ++i) {
324 if (template->cm_fields[i] != NULL) {
325 if (msg->cm_fields[i] == NULL) {
328 if (strcasecmp(msg->cm_fields[i],
329 template->cm_fields[i])) return 1;
333 /* All compares succeeded: we have a match! */
340 * Retrieve the "seen" message list for the current room.
342 void CtdlGetSeen(char *buf, int which_set) {
345 /* Learn about the user and room in question */
346 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
348 if (which_set == ctdlsetseen_seen)
349 safestrncpy(buf, vbuf.v_seen, SIZ);
350 if (which_set == ctdlsetseen_answered)
351 safestrncpy(buf, vbuf.v_answered, SIZ);
357 * Manipulate the "seen msgs" string (or other message set strings)
359 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
360 int target_setting, int which_set,
361 struct ctdluser *which_user, struct ctdlroom *which_room) {
362 struct cdbdata *cdbfr;
374 char *is_set; /* actually an array of booleans */
377 char setstr[SIZ], lostr[SIZ], histr[SIZ];
380 lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
381 num_target_msgnums, target_msgnums[0],
382 target_setting, which_set);
384 /* Learn about the user and room in question */
385 CtdlGetRelationship(&vbuf,
386 ((which_user != NULL) ? which_user : &CC->user),
387 ((which_room != NULL) ? which_room : &CC->room)
390 /* Load the message list */
391 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
393 msglist = (long *) cdbfr->ptr;
394 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
395 num_msgs = cdbfr->len / sizeof(long);
398 return; /* No messages at all? No further action. */
401 is_set = malloc(num_msgs * sizeof(char));
402 memset(is_set, 0, (num_msgs * sizeof(char)) );
404 /* Decide which message set we're manipulating */
406 case ctdlsetseen_seen:
407 safestrncpy(vset, vbuf.v_seen, sizeof vset);
409 case ctdlsetseen_answered:
410 safestrncpy(vset, vbuf.v_answered, sizeof vset);
414 /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
416 /* Translate the existing sequence set into an array of booleans */
417 num_sets = num_tokens(vset, ',');
418 for (s=0; s<num_sets; ++s) {
419 extract_token(setstr, vset, s, ',', sizeof setstr);
421 extract_token(lostr, setstr, 0, ':', sizeof lostr);
422 if (num_tokens(setstr, ':') >= 2) {
423 extract_token(histr, setstr, 1, ':', sizeof histr);
424 if (!strcmp(histr, "*")) {
425 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
429 strcpy(histr, lostr);
434 for (i = 0; i < num_msgs; ++i) {
435 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
441 /* Now translate the array of booleans back into a sequence set */
446 for (i=0; i<num_msgs; ++i) {
448 is_seen = is_set[i]; /* Default to existing setting */
450 for (k=0; k<num_target_msgnums; ++k) {
451 if (msglist[i] == target_msgnums[k]) {
452 is_seen = target_setting;
457 if (lo < 0L) lo = msglist[i];
461 if ( ((is_seen == 0) && (was_seen == 1))
462 || ((is_seen == 1) && (i == num_msgs-1)) ) {
464 /* begin trim-o-matic code */
467 while ( (strlen(vset) + 20) > sizeof vset) {
468 remove_token(vset, 0, ',');
470 if (j--) break; /* loop no more than 9 times */
472 if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
476 snprintf(lostr, sizeof lostr,
477 "1:%ld,%s", t, vset);
478 safestrncpy(vset, lostr, sizeof vset);
480 /* end trim-o-matic code */
488 snprintf(&vset[tmp], (sizeof vset) - tmp,
492 snprintf(&vset[tmp], (sizeof vset) - tmp,
501 /* Decide which message set we're manipulating */
503 case ctdlsetseen_seen:
504 safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
506 case ctdlsetseen_answered:
507 safestrncpy(vbuf.v_answered, vset,
508 sizeof vbuf.v_answered);
513 /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
515 CtdlSetRelationship(&vbuf,
516 ((which_user != NULL) ? which_user : &CC->user),
517 ((which_room != NULL) ? which_room : &CC->room)
523 * API function to perform an operation for each qualifying message in the
524 * current room. (Returns the number of messages processed.)
526 int CtdlForEachMessage(int mode, long ref,
528 struct CtdlMessage *compare,
529 void (*CallBack) (long, void *),
535 struct cdbdata *cdbfr;
536 long *msglist = NULL;
538 int num_processed = 0;
541 struct CtdlMessage *msg;
544 int printed_lastold = 0;
546 /* Learn about the user and room in question */
548 getuser(&CC->user, CC->curr_user);
549 CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
551 /* Load the message list */
552 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
554 msglist = (long *) cdbfr->ptr;
555 cdbfr->ptr = NULL; /* CtdlForEachMessage() now owns this memory */
556 num_msgs = cdbfr->len / sizeof(long);
559 return 0; /* No messages at all? No further action. */
564 * Now begin the traversal.
566 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
568 /* If the caller is looking for a specific MIME type, filter
569 * out all messages which are not of the type requested.
571 if (content_type != NULL) if (strlen(content_type) > 0) {
573 /* This call to GetMetaData() sits inside this loop
574 * so that we only do the extra database read per msg
575 * if we need to. Doing the extra read all the time
576 * really kills the server. If we ever need to use
577 * metadata for another search criterion, we need to
578 * move the read somewhere else -- but still be smart
579 * enough to only do the read if the caller has
580 * specified something that will need it.
582 GetMetaData(&smi, msglist[a]);
584 if (strcasecmp(smi.meta_content_type, content_type)) {
590 num_msgs = sort_msglist(msglist, num_msgs);
592 /* If a template was supplied, filter out the messages which
593 * don't match. (This could induce some delays!)
596 if (compare != NULL) {
597 for (a = 0; a < num_msgs; ++a) {
598 msg = CtdlFetchMessage(msglist[a], 1);
600 if (CtdlMsgCmp(msg, compare)) {
603 CtdlFreeMessage(msg);
611 * Now iterate through the message list, according to the
612 * criteria supplied by the caller.
615 for (a = 0; a < num_msgs; ++a) {
616 thismsg = msglist[a];
617 if (mode == MSGS_ALL) {
621 is_seen = is_msg_in_sequence_set(
622 vbuf.v_seen, thismsg);
623 if (is_seen) lastold = thismsg;
629 || ((mode == MSGS_OLD) && (is_seen))
630 || ((mode == MSGS_NEW) && (!is_seen))
631 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
632 || ((mode == MSGS_FIRST) && (a < ref))
633 || ((mode == MSGS_GT) && (thismsg > ref))
634 || ((mode == MSGS_EQ) && (thismsg == ref))
637 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
639 CallBack(lastold, userdata);
643 if (CallBack) CallBack(thismsg, userdata);
647 free(msglist); /* Clean up */
648 return num_processed;
654 * cmd_msgs() - get list of message #'s in this room
655 * implements the MSGS server command using CtdlForEachMessage()
657 void cmd_msgs(char *cmdbuf)
666 int with_template = 0;
667 struct CtdlMessage *template = NULL;
668 int with_headers = 0;
670 extract_token(which, cmdbuf, 0, '|', sizeof which);
671 cm_ref = extract_int(cmdbuf, 1);
672 with_template = extract_int(cmdbuf, 2);
673 with_headers = extract_int(cmdbuf, 3);
677 if (!strncasecmp(which, "OLD", 3))
679 else if (!strncasecmp(which, "NEW", 3))
681 else if (!strncasecmp(which, "FIRST", 5))
683 else if (!strncasecmp(which, "LAST", 4))
685 else if (!strncasecmp(which, "GT", 2))
688 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
689 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
695 cprintf("%d Send template then receive message list\n",
697 template = (struct CtdlMessage *)
698 malloc(sizeof(struct CtdlMessage));
699 memset(template, 0, sizeof(struct CtdlMessage));
700 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
701 extract_token(tfield, buf, 0, '|', sizeof tfield);
702 extract_token(tvalue, buf, 1, '|', sizeof tvalue);
703 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
704 if (!strcasecmp(tfield, msgkeys[i])) {
705 template->cm_fields[i] =
713 cprintf("%d \n", LISTING_FOLLOWS);
716 CtdlForEachMessage(mode,
720 (with_headers ? headers_listing : simple_listing),
723 if (template != NULL) CtdlFreeMessage(template);
731 * help_subst() - support routine for help file viewer
733 void help_subst(char *strbuf, char *source, char *dest)
738 while (p = pattern2(strbuf, source), (p >= 0)) {
739 strcpy(workbuf, &strbuf[p + strlen(source)]);
740 strcpy(&strbuf[p], dest);
741 strcat(strbuf, workbuf);
746 void do_help_subst(char *buffer)
750 help_subst(buffer, "^nodename", config.c_nodename);
751 help_subst(buffer, "^humannode", config.c_humannode);
752 help_subst(buffer, "^fqdn", config.c_fqdn);
753 help_subst(buffer, "^username", CC->user.fullname);
754 snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
755 help_subst(buffer, "^usernum", buf2);
756 help_subst(buffer, "^sysadm", config.c_sysadm);
757 help_subst(buffer, "^variantname", CITADEL);
758 snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
759 help_subst(buffer, "^maxsessions", buf2);
760 help_subst(buffer, "^bbsdir", CTDLDIR);
766 * memfmout() - Citadel text formatter and paginator.
767 * Although the original purpose of this routine was to format
768 * text to the reader's screen width, all we're really using it
769 * for here is to format text out to 80 columns before sending it
770 * to the client. The client software may reformat it again.
773 int width, /* screen width to use */
774 char *mptr, /* where are we going to get our text from? */
775 char subst, /* nonzero if we should do substitutions */
776 char *nl) /* string to terminate lines with */
788 c = 1; /* c is the current pos */
792 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
794 buffer[strlen(buffer) + 1] = 0;
795 buffer[strlen(buffer)] = ch;
798 if (buffer[0] == '^')
799 do_help_subst(buffer);
801 buffer[strlen(buffer) + 1] = 0;
803 strcpy(buffer, &buffer[1]);
811 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10))
813 if (((old == 13) || (old == 10)) && (isspace(real))) {
821 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
822 cprintf("%s%s", nl, aaa);
831 if ((strlen(aaa) + c) > (width - 5)) {
840 if ((ch == 13) || (ch == 10)) {
841 cprintf("%s%s", aaa, nl);
848 cprintf("%s%s", aaa, nl);
854 * Callback function for mime parser that simply lists the part
856 void list_this_part(char *name, char *filename, char *partnum, char *disp,
857 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
862 ma = (struct ma_info *)cbuserdata;
863 if (ma->is_ma == 0) {
864 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
865 name, filename, partnum, disp, cbtype, (long)length);
870 * Callback function for multipart prefix
872 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
873 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
878 ma = (struct ma_info *)cbuserdata;
879 if (!strcasecmp(cbtype, "multipart/alternative")) {
883 if (ma->is_ma == 0) {
884 cprintf("pref=%s|%s\n", partnum, cbtype);
889 * Callback function for multipart sufffix
891 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
892 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
897 ma = (struct ma_info *)cbuserdata;
898 if (ma->is_ma == 0) {
899 cprintf("suff=%s|%s\n", partnum, cbtype);
901 if (!strcasecmp(cbtype, "multipart/alternative")) {
908 * Callback function for mime parser that opens a section for downloading
910 void mime_download(char *name, char *filename, char *partnum, char *disp,
911 void *content, char *cbtype, char *cbcharset, size_t length,
912 char *encoding, void *cbuserdata)
915 /* Silently go away if there's already a download open... */
916 if (CC->download_fp != NULL)
919 /* ...or if this is not the desired section */
920 if (strcasecmp(CC->download_desired_section, partnum))
923 CC->download_fp = tmpfile();
924 if (CC->download_fp == NULL)
927 fwrite(content, length, 1, CC->download_fp);
928 fflush(CC->download_fp);
929 rewind(CC->download_fp);
931 OpenCmdResult(filename, cbtype);
937 * Load a message from disk into memory.
938 * This is used by CtdlOutputMsg() and other fetch functions.
940 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
941 * using the CtdlMessageFree() function.
943 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
945 struct cdbdata *dmsgtext;
946 struct CtdlMessage *ret = NULL;
950 cit_uint8_t field_header;
952 lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
954 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
955 if (dmsgtext == NULL) {
958 mptr = dmsgtext->ptr;
959 upper_bound = mptr + dmsgtext->len;
961 /* Parse the three bytes that begin EVERY message on disk.
962 * The first is always 0xFF, the on-disk magic number.
963 * The second is the anonymous/public type byte.
964 * The third is the format type byte (vari, fixed, or MIME).
969 "Message %ld appears to be corrupted.\n",
974 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
975 memset(ret, 0, sizeof(struct CtdlMessage));
977 ret->cm_magic = CTDLMESSAGE_MAGIC;
978 ret->cm_anon_type = *mptr++; /* Anon type byte */
979 ret->cm_format_type = *mptr++; /* Format type byte */
982 * The rest is zero or more arbitrary fields. Load them in.
983 * We're done when we encounter either a zero-length field or
984 * have just processed the 'M' (message text) field.
987 if (mptr >= upper_bound) {
990 field_header = *mptr++;
991 ret->cm_fields[field_header] = strdup(mptr);
993 while (*mptr++ != 0); /* advance to next field */
995 } while ((mptr < upper_bound) && (field_header != 'M'));
999 /* Always make sure there's something in the msg text field. If
1000 * it's NULL, the message text is most likely stored separately,
1001 * so go ahead and fetch that. Failing that, just set a dummy
1002 * body so other code doesn't barf.
1004 if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1005 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1006 if (dmsgtext != NULL) {
1007 ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1011 if (ret->cm_fields['M'] == NULL) {
1012 ret->cm_fields['M'] = strdup("<no text>\n");
1015 /* Perform "before read" hooks (aborting if any return nonzero) */
1016 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1017 CtdlFreeMessage(ret);
1026 * Returns 1 if the supplied pointer points to a valid Citadel message.
1027 * If the pointer is NULL or the magic number check fails, returns 0.
1029 int is_valid_message(struct CtdlMessage *msg) {
1032 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1033 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1041 * 'Destructor' for struct CtdlMessage
1043 void CtdlFreeMessage(struct CtdlMessage *msg)
1047 if (is_valid_message(msg) == 0) return;
1049 for (i = 0; i < 256; ++i)
1050 if (msg->cm_fields[i] != NULL) {
1051 free(msg->cm_fields[i]);
1054 msg->cm_magic = 0; /* just in case */
1060 * Pre callback function for multipart/alternative
1062 * NOTE: this differs from the standard behavior for a reason. Normally when
1063 * displaying multipart/alternative you want to show the _last_ usable
1064 * format in the message. Here we show the _first_ one, because it's
1065 * usually text/plain. Since this set of functions is designed for text
1066 * output to non-MIME-aware clients, this is the desired behavior.
1069 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1070 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1075 ma = (struct ma_info *)cbuserdata;
1076 lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1077 if (!strcasecmp(cbtype, "multipart/alternative")) {
1081 if (!strcasecmp(cbtype, "message/rfc822")) {
1087 * Post callback function for multipart/alternative
1089 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1090 void *content, char *cbtype, char *cbcharset, size_t length,
1091 char *encoding, void *cbuserdata)
1095 ma = (struct ma_info *)cbuserdata;
1096 lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1097 if (!strcasecmp(cbtype, "multipart/alternative")) {
1101 if (!strcasecmp(cbtype, "message/rfc822")) {
1107 * Inline callback function for mime parser that wants to display text
1109 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1110 void *content, char *cbtype, char *cbcharset, size_t length,
1111 char *encoding, void *cbuserdata)
1118 ma = (struct ma_info *)cbuserdata;
1121 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1122 partnum, filename, cbtype, (long)length);
1125 * If we're in the middle of a multipart/alternative scope and
1126 * we've already printed another section, skip this one.
1128 if ( (ma->is_ma) && (ma->did_print) ) {
1129 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1135 if ( (!strcasecmp(cbtype, "text/plain"))
1136 || (strlen(cbtype)==0) ) {
1139 client_write(wptr, length);
1140 if (wptr[length-1] != '\n') {
1145 else if (!strcasecmp(cbtype, "text/html")) {
1146 ptr = html_to_ascii(content, length, 80, 0);
1148 client_write(ptr, wlen);
1149 if (ptr[wlen-1] != '\n') {
1154 else if (PerformFixedOutputHooks(cbtype, content, length)) {
1155 /* above function returns nonzero if it handled the part */
1157 else if (strncasecmp(cbtype, "multipart/", 10)) {
1158 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1159 partnum, filename, cbtype, (long)length);
1164 * The client is elegant and sophisticated and wants to be choosy about
1165 * MIME content types, so figure out which multipart/alternative part
1166 * we're going to send.
1168 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1169 void *content, char *cbtype, char *cbcharset, size_t length,
1170 char *encoding, void *cbuserdata)
1176 ma = (struct ma_info *)cbuserdata;
1178 if (ma->is_ma > 0) {
1179 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1180 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1181 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1182 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1189 * Now that we've chosen our preferred part, output it.
1191 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1192 void *content, char *cbtype, char *cbcharset, size_t length,
1193 char *encoding, void *cbuserdata)
1197 int add_newline = 0;
1201 ma = (struct ma_info *)cbuserdata;
1203 /* This is not the MIME part you're looking for... */
1204 if (strcasecmp(partnum, ma->chosen_part)) return;
1206 /* If the content-type of this part is in our preferred formats
1207 * list, we can simply output it verbatim.
1209 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1210 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1211 if (!strcasecmp(buf, cbtype)) {
1212 /* Yeah! Go! W00t!! */
1214 text_content = (char *)content;
1215 if (text_content[length-1] != '\n') {
1219 cprintf("Content-type: %s", cbtype);
1220 if (strlen(cbcharset) > 0) {
1221 cprintf("; charset=%s", cbcharset);
1223 cprintf("\nContent-length: %d\n",
1224 (int)(length + add_newline) );
1225 if (strlen(encoding) > 0) {
1226 cprintf("Content-transfer-encoding: %s\n", encoding);
1229 cprintf("Content-transfer-encoding: 7bit\n");
1232 client_write(content, length);
1233 if (add_newline) cprintf("\n");
1238 /* No translations required or possible: output as text/plain */
1239 cprintf("Content-type: text/plain\n\n");
1240 fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1241 length, encoding, cbuserdata);
1246 char desired_section[64];
1253 * Callback function for
1255 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1256 void *content, char *cbtype, char *cbcharset, size_t length,
1257 char *encoding, void *cbuserdata)
1259 struct encapmsg *encap;
1261 encap = (struct encapmsg *)cbuserdata;
1263 /* Only proceed if this is the desired section... */
1264 if (!strcasecmp(encap->desired_section, partnum)) {
1265 encap->msglen = length;
1266 encap->msg = malloc(length + 2);
1267 memcpy(encap->msg, content, length);
1277 * Get a message off disk. (returns om_* values found in msgbase.h)
1280 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1281 int mode, /* how would you like that message? */
1282 int headers_only, /* eschew the message body? */
1283 int do_proto, /* do Citadel protocol responses? */
1284 int crlf, /* Use CRLF newlines instead of LF? */
1285 char *section /* NULL or a message/rfc822 section */
1287 struct CtdlMessage *TheMessage = NULL;
1288 int retcode = om_no_such_msg;
1289 struct encapmsg encap;
1291 lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n",
1293 (section ? section : "<>")
1296 if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1297 if (do_proto) cprintf("%d Not logged in.\n",
1298 ERROR + NOT_LOGGED_IN);
1299 return(om_not_logged_in);
1302 /* FIXME: check message id against msglist for this room */
1305 * Fetch the message from disk. If we're in any sort of headers
1306 * only mode, request that we don't even bother loading the body
1309 if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1310 TheMessage = CtdlFetchMessage(msg_num, 0);
1313 TheMessage = CtdlFetchMessage(msg_num, 1);
1316 if (TheMessage == NULL) {
1317 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1318 ERROR + MESSAGE_NOT_FOUND, msg_num);
1319 return(om_no_such_msg);
1322 /* Here is the weird form of this command, to process only an
1323 * encapsulated message/rfc822 section.
1325 if (section) if (strlen(section)>0) if (strcmp(section, "0")) {
1326 memset(&encap, 0, sizeof encap);
1327 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1328 mime_parser(TheMessage->cm_fields['M'],
1330 *extract_encapsulated_message,
1331 NULL, NULL, (void *)&encap, 0
1333 CtdlFreeMessage(TheMessage);
1337 encap.msg[encap.msglen] = 0;
1338 TheMessage = convert_internet_message(encap.msg);
1339 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1341 /* Now we let it fall through to the bottom of this
1342 * function, because TheMessage now contains the
1343 * encapsulated message instead of the top-level
1344 * message. Isn't that neat?
1349 if (do_proto) cprintf("%d msg %ld has no part %s\n",
1350 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1351 retcode = om_no_such_msg;
1356 /* Ok, output the message now */
1357 retcode = CtdlOutputPreLoadedMsg(
1359 headers_only, do_proto, crlf);
1360 CtdlFreeMessage(TheMessage);
1367 * Get a message off disk. (returns om_* values found in msgbase.h)
1370 int CtdlOutputPreLoadedMsg(
1371 struct CtdlMessage *TheMessage,
1372 int mode, /* how would you like that message? */
1373 int headers_only, /* eschew the message body? */
1374 int do_proto, /* do Citadel protocol responses? */
1375 int crlf /* Use CRLF newlines instead of LF? */
1381 char display_name[256];
1383 char *nl; /* newline string */
1385 int subject_found = 0;
1388 /* Buffers needed for RFC822 translation. These are all filled
1389 * using functions that are bounds-checked, and therefore we can
1390 * make them substantially smaller than SIZ.
1398 char datestamp[100];
1400 lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1401 ((TheMessage == NULL) ? "NULL" : "not null"),
1402 mode, headers_only, do_proto, crlf);
1404 strcpy(mid, "unknown");
1405 nl = (crlf ? "\r\n" : "\n");
1407 if (!is_valid_message(TheMessage)) {
1409 "ERROR: invalid preloaded message for output\n");
1410 return(om_no_such_msg);
1413 /* Are we downloading a MIME component? */
1414 if (mode == MT_DOWNLOAD) {
1415 if (TheMessage->cm_format_type != FMT_RFC822) {
1417 cprintf("%d This is not a MIME message.\n",
1418 ERROR + ILLEGAL_VALUE);
1419 } else if (CC->download_fp != NULL) {
1420 if (do_proto) cprintf(
1421 "%d You already have a download open.\n",
1422 ERROR + RESOURCE_BUSY);
1424 /* Parse the message text component */
1425 mptr = TheMessage->cm_fields['M'];
1426 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1427 /* If there's no file open by this time, the requested
1428 * section wasn't found, so print an error
1430 if (CC->download_fp == NULL) {
1431 if (do_proto) cprintf(
1432 "%d Section %s not found.\n",
1433 ERROR + FILE_NOT_FOUND,
1434 CC->download_desired_section);
1437 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1440 /* now for the user-mode message reading loops */
1441 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1443 /* Does the caller want to skip the headers? */
1444 if (headers_only == HEADERS_NONE) goto START_TEXT;
1446 /* Tell the client which format type we're using. */
1447 if ( (mode == MT_CITADEL) && (do_proto) ) {
1448 cprintf("type=%d\n", TheMessage->cm_format_type);
1451 /* nhdr=yes means that we're only displaying headers, no body */
1452 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1453 && (mode == MT_CITADEL)
1456 cprintf("nhdr=yes\n");
1459 /* begin header processing loop for Citadel message format */
1461 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1463 safestrncpy(display_name, "<unknown>", sizeof display_name);
1464 if (TheMessage->cm_fields['A']) {
1465 strcpy(buf, TheMessage->cm_fields['A']);
1466 if (TheMessage->cm_anon_type == MES_ANONONLY) {
1467 safestrncpy(display_name, "****", sizeof display_name);
1469 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1470 safestrncpy(display_name, "anonymous", sizeof display_name);
1473 safestrncpy(display_name, buf, sizeof display_name);
1475 if ((is_room_aide())
1476 && ((TheMessage->cm_anon_type == MES_ANONONLY)
1477 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1478 size_t tmp = strlen(display_name);
1479 snprintf(&display_name[tmp],
1480 sizeof display_name - tmp,
1485 /* Don't show Internet address for users on the
1486 * local Citadel network.
1489 if (TheMessage->cm_fields['N'] != NULL)
1490 if (strlen(TheMessage->cm_fields['N']) > 0)
1491 if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1495 /* Now spew the header fields in the order we like them. */
1496 safestrncpy(allkeys, FORDER, sizeof allkeys);
1497 for (i=0; i<strlen(allkeys); ++i) {
1498 k = (int) allkeys[i];
1500 if ( (TheMessage->cm_fields[k] != NULL)
1501 && (msgkeys[k] != NULL) ) {
1503 if (do_proto) cprintf("%s=%s\n",
1507 else if ((k == 'F') && (suppress_f)) {
1510 /* Masquerade display name if needed */
1512 if (do_proto) cprintf("%s=%s\n",
1514 TheMessage->cm_fields[k]
1523 /* begin header processing loop for RFC822 transfer format */
1528 strcpy(snode, NODENAME);
1529 strcpy(lnode, HUMANNODE);
1530 if (mode == MT_RFC822) {
1531 for (i = 0; i < 256; ++i) {
1532 if (TheMessage->cm_fields[i]) {
1533 mptr = TheMessage->cm_fields[i];
1536 safestrncpy(luser, mptr, sizeof luser);
1537 safestrncpy(suser, mptr, sizeof suser);
1539 else if (i == 'Y') {
1540 cprintf("CC: %s%s", mptr, nl);
1542 else if (i == 'U') {
1543 cprintf("Subject: %s%s", mptr, nl);
1547 safestrncpy(mid, mptr, sizeof mid);
1549 safestrncpy(lnode, mptr, sizeof lnode);
1551 safestrncpy(fuser, mptr, sizeof fuser);
1552 /* else if (i == 'O')
1553 cprintf("X-Citadel-Room: %s%s",
1556 safestrncpy(snode, mptr, sizeof snode);
1558 cprintf("To: %s%s", mptr, nl);
1559 else if (i == 'T') {
1560 datestring(datestamp, sizeof datestamp,
1561 atol(mptr), DATESTRING_RFC822);
1562 cprintf("Date: %s%s", datestamp, nl);
1566 if (subject_found == 0) {
1567 cprintf("Subject: (no subject)%s", nl);
1571 for (i=0; i<strlen(suser); ++i) {
1572 suser[i] = tolower(suser[i]);
1573 if (!isalnum(suser[i])) suser[i]='_';
1576 if (mode == MT_RFC822) {
1577 if (!strcasecmp(snode, NODENAME)) {
1578 safestrncpy(snode, FQDN, sizeof snode);
1581 /* Construct a fun message id */
1582 cprintf("Message-ID: <%s", mid);
1583 if (strchr(mid, '@')==NULL) {
1584 cprintf("@%s", snode);
1588 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1589 cprintf("From: \"----\" <x@x.org>%s", nl);
1591 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1592 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1594 else if (strlen(fuser) > 0) {
1595 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1598 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1601 cprintf("Organization: %s%s", lnode, nl);
1603 /* Blank line signifying RFC822 end-of-headers */
1604 if (TheMessage->cm_format_type != FMT_RFC822) {
1609 /* end header processing loop ... at this point, we're in the text */
1611 if (headers_only == HEADERS_FAST) goto DONE;
1612 mptr = TheMessage->cm_fields['M'];
1614 /* Tell the client about the MIME parts in this message */
1615 if (TheMessage->cm_format_type == FMT_RFC822) {
1616 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1617 memset(&ma, 0, sizeof(struct ma_info));
1618 mime_parser(mptr, NULL,
1619 (do_proto ? *list_this_part : NULL),
1620 (do_proto ? *list_this_pref : NULL),
1621 (do_proto ? *list_this_suff : NULL),
1624 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
1625 char *start_of_text = NULL;
1626 start_of_text = strstr(mptr, "\n\r\n");
1627 if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1628 if (start_of_text == NULL) start_of_text = mptr;
1630 start_of_text = strstr(start_of_text, "\n");
1632 while (ch=*mptr, ch!=0) {
1636 else switch(headers_only) {
1638 if (mptr >= start_of_text) {
1639 if (ch == 10) cprintf("%s", nl);
1640 else cprintf("%c", ch);
1644 if (mptr < start_of_text) {
1645 if (ch == 10) cprintf("%s", nl);
1646 else cprintf("%c", ch);
1650 if (ch == 10) cprintf("%s", nl);
1651 else cprintf("%c", ch);
1660 if (headers_only == HEADERS_ONLY) {
1664 /* signify start of msg text */
1665 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1666 if (do_proto) cprintf("text\n");
1669 /* If the format type on disk is 1 (fixed-format), then we want
1670 * everything to be output completely literally ... regardless of
1671 * what message transfer format is in use.
1673 if (TheMessage->cm_format_type == FMT_FIXED) {
1674 if (mode == MT_MIME) {
1675 cprintf("Content-type: text/plain\n\n");
1678 while (ch = *mptr++, ch > 0) {
1681 if ((ch == 10) || (strlen(buf) > 250)) {
1682 cprintf("%s%s", buf, nl);
1685 buf[strlen(buf) + 1] = 0;
1686 buf[strlen(buf)] = ch;
1689 if (strlen(buf) > 0)
1690 cprintf("%s%s", buf, nl);
1693 /* If the message on disk is format 0 (Citadel vari-format), we
1694 * output using the formatter at 80 columns. This is the final output
1695 * form if the transfer format is RFC822, but if the transfer format
1696 * is Citadel proprietary, it'll still work, because the indentation
1697 * for new paragraphs is correct and the client will reformat the
1698 * message to the reader's screen width.
1700 if (TheMessage->cm_format_type == FMT_CITADEL) {
1701 if (mode == MT_MIME) {
1702 cprintf("Content-type: text/x-citadel-variformat\n\n");
1704 memfmout(80, mptr, 0, nl);
1707 /* If the message on disk is format 4 (MIME), we've gotta hand it
1708 * off to the MIME parser. The client has already been told that
1709 * this message is format 1 (fixed format), so the callback function
1710 * we use will display those parts as-is.
1712 if (TheMessage->cm_format_type == FMT_RFC822) {
1713 memset(&ma, 0, sizeof(struct ma_info));
1715 if (mode == MT_MIME) {
1716 strcpy(ma.chosen_part, "1");
1717 mime_parser(mptr, NULL,
1718 *choose_preferred, *fixed_output_pre,
1719 *fixed_output_post, (void *)&ma, 0);
1720 mime_parser(mptr, NULL,
1721 *output_preferred, NULL, NULL, (void *)&ma, 0);
1724 mime_parser(mptr, NULL,
1725 *fixed_output, *fixed_output_pre,
1726 *fixed_output_post, (void *)&ma, 0);
1731 DONE: /* now we're done */
1732 if (do_proto) cprintf("000\n");
1739 * display a message (mode 0 - Citadel proprietary)
1741 void cmd_msg0(char *cmdbuf)
1744 int headers_only = HEADERS_ALL;
1746 msgid = extract_long(cmdbuf, 0);
1747 headers_only = extract_int(cmdbuf, 1);
1749 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1755 * display a message (mode 2 - RFC822)
1757 void cmd_msg2(char *cmdbuf)
1760 int headers_only = HEADERS_ALL;
1762 msgid = extract_long(cmdbuf, 0);
1763 headers_only = extract_int(cmdbuf, 1);
1765 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1771 * display a message (mode 3 - IGnet raw format - internal programs only)
1773 void cmd_msg3(char *cmdbuf)
1776 struct CtdlMessage *msg;
1779 if (CC->internal_pgm == 0) {
1780 cprintf("%d This command is for internal programs only.\n",
1781 ERROR + HIGHER_ACCESS_REQUIRED);
1785 msgnum = extract_long(cmdbuf, 0);
1786 msg = CtdlFetchMessage(msgnum, 1);
1788 cprintf("%d Message %ld not found.\n",
1789 ERROR + MESSAGE_NOT_FOUND, msgnum);
1793 serialize_message(&smr, msg);
1794 CtdlFreeMessage(msg);
1797 cprintf("%d Unable to serialize message\n",
1798 ERROR + INTERNAL_ERROR);
1802 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1803 client_write((char *)smr.ser, (int)smr.len);
1810 * Display a message using MIME content types
1812 void cmd_msg4(char *cmdbuf)
1817 msgid = extract_long(cmdbuf, 0);
1818 extract_token(section, cmdbuf, 1, '|', sizeof section);
1819 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1825 * Client tells us its preferred message format(s)
1827 void cmd_msgp(char *cmdbuf)
1829 safestrncpy(CC->preferred_formats, cmdbuf,
1830 sizeof(CC->preferred_formats));
1831 cprintf("%d ok\n", CIT_OK);
1836 * Open a component of a MIME message as a download file
1838 void cmd_opna(char *cmdbuf)
1841 char desired_section[128];
1843 msgid = extract_long(cmdbuf, 0);
1844 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1845 safestrncpy(CC->download_desired_section, desired_section,
1846 sizeof CC->download_desired_section);
1847 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
1852 * Save a message pointer into a specified room
1853 * (Returns 0 for success, nonzero for failure)
1854 * roomname may be NULL to use the current room
1856 * Note that the 'supplied_msg' field may be set to NULL, in which case
1857 * the message will be fetched from disk, by number, if we need to perform
1858 * replication checks. This adds an additional database read, so if the
1859 * caller already has the message in memory then it should be supplied.
1861 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid, int do_repl_check,
1862 struct CtdlMessage *supplied_msg) {
1864 char hold_rm[ROOMNAMELEN];
1865 struct cdbdata *cdbfr;
1868 long highest_msg = 0L;
1869 struct CtdlMessage *msg = NULL;
1871 /*lprintf(CTDL_DEBUG,
1872 "CtdlSaveMsgPointerInRoom(room=%s, msgid=%ld, repl=%d)\n",
1873 roomname, msgid, do_repl_check);*/
1875 strcpy(hold_rm, CC->room.QRname);
1877 /* Now the regular stuff */
1878 if (lgetroom(&CC->room,
1879 ((roomname != NULL) ? roomname : CC->room.QRname) )
1881 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
1882 return(ERROR + ROOM_NOT_FOUND);
1885 cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
1886 if (cdbfr == NULL) {
1890 msglist = (long *) cdbfr->ptr;
1891 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
1892 num_msgs = cdbfr->len / sizeof(long);
1896 /* Make sure the message doesn't already exist in this room. It
1897 * is absolutely taboo to have more than one reference to the same
1898 * message in a room.
1900 if (num_msgs > 0) for (i=0; i<num_msgs; ++i) {
1901 if (msglist[i] == msgid) {
1902 lputroom(&CC->room); /* unlock the room */
1903 getroom(&CC->room, hold_rm);
1905 return(ERROR + ALREADY_EXISTS);
1909 /* Now add the new message */
1911 msglist = realloc(msglist, (num_msgs * sizeof(long)));
1913 if (msglist == NULL) {
1914 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
1916 msglist[num_msgs - 1] = msgid;
1918 /* Sort the message list, so all the msgid's are in order */
1919 num_msgs = sort_msglist(msglist, num_msgs);
1921 /* Determine the highest message number */
1922 highest_msg = msglist[num_msgs - 1];
1924 /* Write it back to disk. */
1925 cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
1926 msglist, (int)(num_msgs * sizeof(long)));
1928 /* Free up the memory we used. */
1931 /* Update the highest-message pointer and unlock the room. */
1932 CC->room.QRhighest = highest_msg;
1933 lputroom(&CC->room);
1935 /* Perform replication checks if necessary */
1936 if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
1937 if (supplied_msg != NULL) {
1941 msg = CtdlFetchMessage(msgid, 0);
1945 ReplicationChecks(msg);
1950 /* If the message has an Exclusive ID, index that... */
1952 if (msg->cm_fields['E'] != NULL) {
1953 index_message_by_euid(msg->cm_fields['E'],
1958 /* Free up the memory we may have allocated */
1959 if ( (msg != NULL) && (msg != supplied_msg) ) {
1960 CtdlFreeMessage(msg);
1963 /* Go back to the room we were in before we wandered here... */
1964 getroom(&CC->room, hold_rm);
1966 /* Bump the reference count for this message. */
1967 AdjRefCount(msgid, +1);
1969 /* Return success. */
1976 * Message base operation to save a new message to the message store
1977 * (returns new message number)
1979 * This is the back end for CtdlSubmitMsg() and should not be directly
1980 * called by server-side modules.
1983 long send_message(struct CtdlMessage *msg) {
1991 /* Get a new message number */
1992 newmsgid = get_new_message_number();
1993 snprintf(msgidbuf, sizeof msgidbuf, "%ld@%s", newmsgid, config.c_fqdn);
1995 /* Generate an ID if we don't have one already */
1996 if (msg->cm_fields['I']==NULL) {
1997 msg->cm_fields['I'] = strdup(msgidbuf);
2000 /* If the message is big, set its body aside for storage elsewhere */
2001 if (msg->cm_fields['M'] != NULL) {
2002 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2004 holdM = msg->cm_fields['M'];
2005 msg->cm_fields['M'] = NULL;
2009 /* Serialize our data structure for storage in the database */
2010 serialize_message(&smr, msg);
2013 msg->cm_fields['M'] = holdM;
2017 cprintf("%d Unable to serialize message\n",
2018 ERROR + INTERNAL_ERROR);
2022 /* Write our little bundle of joy into the message base */
2023 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2024 smr.ser, smr.len) < 0) {
2025 lprintf(CTDL_ERR, "Can't store message\n");
2029 cdb_store(CDB_BIGMSGS,
2039 /* Free the memory we used for the serialized message */
2042 /* Return the *local* message ID to the caller
2043 * (even if we're storing an incoming network message)
2051 * Serialize a struct CtdlMessage into the format used on disk and network.
2053 * This function loads up a "struct ser_ret" (defined in server.h) which
2054 * contains the length of the serialized message and a pointer to the
2055 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
2057 void serialize_message(struct ser_ret *ret, /* return values */
2058 struct CtdlMessage *msg) /* unserialized msg */
2062 static char *forder = FORDER;
2064 if (is_valid_message(msg) == 0) return; /* self check */
2067 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2068 ret->len = ret->len +
2069 strlen(msg->cm_fields[(int)forder[i]]) + 2;
2071 lprintf(CTDL_DEBUG, "serialize_message() calling malloc(%ld)\n", (long)ret->len);
2072 ret->ser = malloc(ret->len);
2073 if (ret->ser == NULL) {
2079 ret->ser[1] = msg->cm_anon_type;
2080 ret->ser[2] = msg->cm_format_type;
2083 for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2084 ret->ser[wlen++] = (char)forder[i];
2085 strcpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]]);
2086 wlen = wlen + strlen(msg->cm_fields[(int)forder[i]]) + 1;
2088 if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2089 (long)ret->len, (long)wlen);
2097 * Check to see if any messages already exist in the current room which
2098 * carry the same Exclusive ID as this one. If any are found, delete them.
2100 void ReplicationChecks(struct CtdlMessage *msg) {
2101 long old_msgnum = (-1L);
2103 if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2105 lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2108 /* No exclusive id? Don't do anything. */
2109 if (msg == NULL) return;
2110 if (msg->cm_fields['E'] == NULL) return;
2111 if (strlen(msg->cm_fields['E']) == 0) return;
2112 /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2113 msg->cm_fields['E'], CC->room.QRname);*/
2115 old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2116 if (old_msgnum > 0L) {
2117 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2118 CtdlDeleteMessages(CC->room.QRname, old_msgnum, "", 0);
2125 * Save a message to disk and submit it into the delivery system.
2127 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
2128 struct recptypes *recps, /* recipients (if mail) */
2129 char *force /* force a particular room? */
2131 char submit_filename[128];
2132 char generated_timestamp[32];
2133 char hold_rm[ROOMNAMELEN];
2134 char actual_rm[ROOMNAMELEN];
2135 char force_room[ROOMNAMELEN];
2136 char content_type[SIZ]; /* We have to learn this */
2137 char recipient[SIZ];
2140 struct ctdluser userbuf;
2142 struct MetaData smi;
2143 FILE *network_fp = NULL;
2144 static int seqnum = 1;
2145 struct CtdlMessage *imsg = NULL;
2148 char *hold_R, *hold_D;
2149 char *collected_addresses = NULL;
2150 struct addresses_to_be_filed *aptr = NULL;
2151 char *saved_rfc822_version = NULL;
2152 int qualified_for_journaling = 0;
2154 lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2155 if (is_valid_message(msg) == 0) return(-1); /* self check */
2157 /* If this message has no timestamp, we take the liberty of
2158 * giving it one, right now.
2160 if (msg->cm_fields['T'] == NULL) {
2161 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2162 msg->cm_fields['T'] = strdup(generated_timestamp);
2165 /* If this message has no path, we generate one.
2167 if (msg->cm_fields['P'] == NULL) {
2168 if (msg->cm_fields['A'] != NULL) {
2169 msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2170 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
2171 if (isspace(msg->cm_fields['P'][a])) {
2172 msg->cm_fields['P'][a] = ' ';
2177 msg->cm_fields['P'] = strdup("unknown");
2181 if (force == NULL) {
2182 strcpy(force_room, "");
2185 strcpy(force_room, force);
2188 /* Learn about what's inside, because it's what's inside that counts */
2189 if (msg->cm_fields['M'] == NULL) {
2190 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2194 switch (msg->cm_format_type) {
2196 strcpy(content_type, "text/x-citadel-variformat");
2199 strcpy(content_type, "text/plain");
2202 strcpy(content_type, "text/plain");
2203 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type: ");
2205 safestrncpy(content_type, &mptr[14],
2206 sizeof content_type);
2207 for (a = 0; a < strlen(content_type); ++a) {
2208 if ((content_type[a] == ';')
2209 || (content_type[a] == ' ')
2210 || (content_type[a] == 13)
2211 || (content_type[a] == 10)) {
2212 content_type[a] = 0;
2218 /* Goto the correct room */
2219 lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CC->room.QRname : SENTITEMS);
2220 strcpy(hold_rm, CC->room.QRname);
2221 strcpy(actual_rm, CC->room.QRname);
2222 if (recps != NULL) {
2223 strcpy(actual_rm, SENTITEMS);
2226 /* If the user is a twit, move to the twit room for posting */
2228 if (CC->user.axlevel == 2) {
2229 strcpy(hold_rm, actual_rm);
2230 strcpy(actual_rm, config.c_twitroom);
2231 lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2235 /* ...or if this message is destined for Aide> then go there. */
2236 if (strlen(force_room) > 0) {
2237 strcpy(actual_rm, force_room);
2240 lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2241 if (strcasecmp(actual_rm, CC->room.QRname)) {
2242 /* getroom(&CC->room, actual_rm); */
2243 usergoto(actual_rm, 0, 1, NULL, NULL);
2247 * If this message has no O (room) field, generate one.
2249 if (msg->cm_fields['O'] == NULL) {
2250 msg->cm_fields['O'] = strdup(CC->room.QRname);
2253 /* Perform "before save" hooks (aborting if any return nonzero) */
2254 lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2255 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2258 * If this message has an Exclusive ID, and the room is replication
2259 * checking enabled, then do replication checks.
2261 if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2262 ReplicationChecks(msg);
2265 /* Save it to disk */
2266 lprintf(CTDL_DEBUG, "Saving to disk\n");
2267 newmsgid = send_message(msg);
2268 if (newmsgid <= 0L) return(-5);
2270 /* Write a supplemental message info record. This doesn't have to
2271 * be a critical section because nobody else knows about this message
2274 lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2275 memset(&smi, 0, sizeof(struct MetaData));
2276 smi.meta_msgnum = newmsgid;
2277 smi.meta_refcount = 0;
2278 safestrncpy(smi.meta_content_type, content_type,
2279 sizeof smi.meta_content_type);
2282 * Measure how big this message will be when rendered as RFC822.
2283 * We do this for two reasons:
2284 * 1. We need the RFC822 length for the new metadata record, so the
2285 * POP and IMAP services don't have to calculate message lengths
2286 * while the user is waiting (multiplied by potentially hundreds
2287 * or thousands of messages).
2288 * 2. If journaling is enabled, we will need an RFC822 version of the
2289 * message to attach to the journalized copy.
2291 if (CC->redirect_buffer != NULL) {
2292 lprintf(CTDL_ALERT, "CC->redirect_buffer is not NULL during message submission!\n");
2295 CC->redirect_buffer = malloc(SIZ);
2296 CC->redirect_len = 0;
2297 CC->redirect_alloc = SIZ;
2298 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2299 smi.meta_rfc822_length = CC->redirect_len;
2300 saved_rfc822_version = CC->redirect_buffer;
2301 CC->redirect_buffer = NULL;
2302 CC->redirect_len = 0;
2303 CC->redirect_alloc = 0;
2307 /* Now figure out where to store the pointers */
2308 lprintf(CTDL_DEBUG, "Storing pointers\n");
2310 /* If this is being done by the networker delivering a private
2311 * message, we want to BYPASS saving the sender's copy (because there
2312 * is no local sender; it would otherwise go to the Trashcan).
2314 if ((!CC->internal_pgm) || (recps == NULL)) {
2315 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2316 lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2317 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2321 /* For internet mail, drop a copy in the outbound queue room */
2323 if (recps->num_internet > 0) {
2324 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2327 /* If other rooms are specified, drop them there too. */
2329 if (recps->num_room > 0)
2330 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2331 extract_token(recipient, recps->recp_room, i,
2332 '|', sizeof recipient);
2333 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2334 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2337 /* Bump this user's messages posted counter. */
2338 lprintf(CTDL_DEBUG, "Updating user\n");
2339 lgetuser(&CC->user, CC->curr_user);
2340 CC->user.posted = CC->user.posted + 1;
2341 lputuser(&CC->user);
2343 /* If this is private, local mail, make a copy in the
2344 * recipient's mailbox and bump the reference count.
2347 if (recps->num_local > 0)
2348 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2349 extract_token(recipient, recps->recp_local, i,
2350 '|', sizeof recipient);
2351 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2353 if (getuser(&userbuf, recipient) == 0) {
2354 MailboxName(actual_rm, sizeof actual_rm,
2355 &userbuf, MAILROOM);
2356 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2357 BumpNewMailCounter(userbuf.usernum);
2360 lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2361 CtdlSaveMsgPointerInRoom(config.c_aideroom,
2366 /* Perform "after save" hooks */
2367 lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2368 PerformMessageHooks(msg, EVT_AFTERSAVE);
2370 /* For IGnet mail, we have to save a new copy into the spooler for
2371 * each recipient, with the R and D fields set to the recipient and
2372 * destination-node. This has two ugly side effects: all other
2373 * recipients end up being unlisted in this recipient's copy of the
2374 * message, and it has to deliver multiple messages to the same
2375 * node. We'll revisit this again in a year or so when everyone has
2376 * a network spool receiver that can handle the new style messages.
2379 if (recps->num_ignet > 0)
2380 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2381 extract_token(recipient, recps->recp_ignet, i,
2382 '|', sizeof recipient);
2384 hold_R = msg->cm_fields['R'];
2385 hold_D = msg->cm_fields['D'];
2386 msg->cm_fields['R'] = malloc(SIZ);
2387 msg->cm_fields['D'] = malloc(128);
2388 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2389 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2391 serialize_message(&smr, msg);
2393 snprintf(submit_filename, sizeof submit_filename,
2394 "%s/netmail.%04lx.%04x.%04x",
2396 (long) getpid(), CC->cs_pid, ++seqnum);
2397 network_fp = fopen(submit_filename, "wb+");
2398 if (network_fp != NULL) {
2399 fwrite(smr.ser, smr.len, 1, network_fp);
2405 free(msg->cm_fields['R']);
2406 free(msg->cm_fields['D']);
2407 msg->cm_fields['R'] = hold_R;
2408 msg->cm_fields['D'] = hold_D;
2411 /* Go back to the room we started from */
2412 lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2413 if (strcasecmp(hold_rm, CC->room.QRname))
2414 /* getroom(&CC->room, hold_rm); */
2415 usergoto(hold_rm, 0, 1, NULL, NULL);
2417 /* For internet mail, generate delivery instructions.
2418 * Yes, this is recursive. Deal with it. Infinite recursion does
2419 * not happen because the delivery instructions message does not
2420 * contain a recipient.
2423 if (recps->num_internet > 0) {
2424 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2425 instr = malloc(SIZ * 2);
2426 snprintf(instr, SIZ * 2,
2427 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2429 SPOOLMIME, newmsgid, (long)time(NULL),
2430 msg->cm_fields['A'], msg->cm_fields['N']
2433 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2434 size_t tmp = strlen(instr);
2435 extract_token(recipient, recps->recp_internet,
2436 i, '|', sizeof recipient);
2437 snprintf(&instr[tmp], SIZ * 2 - tmp,
2438 "remote|%s|0||\n", recipient);
2441 imsg = malloc(sizeof(struct CtdlMessage));
2442 memset(imsg, 0, sizeof(struct CtdlMessage));
2443 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2444 imsg->cm_anon_type = MES_NORMAL;
2445 imsg->cm_format_type = FMT_RFC822;
2446 imsg->cm_fields['A'] = strdup("Citadel");
2447 imsg->cm_fields['J'] = strdup("do not journal");
2448 imsg->cm_fields['M'] = instr;
2449 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2450 CtdlFreeMessage(imsg);
2454 * Any addresses to harvest for someone's address book?
2456 if ( (CC->logged_in) && (recps != NULL) ) {
2457 collected_addresses = harvest_collected_addresses(msg);
2460 if (collected_addresses != NULL) {
2461 begin_critical_section(S_ATBF);
2462 aptr = (struct addresses_to_be_filed *)
2463 malloc(sizeof(struct addresses_to_be_filed));
2465 MailboxName(actual_rm, sizeof actual_rm,
2466 &CC->user, USERCONTACTSROOM);
2467 aptr->roomname = strdup(actual_rm);
2468 aptr->collected_addresses = collected_addresses;
2470 end_critical_section(S_ATBF);
2474 * Determine whether this message qualifies for journaling.
2476 if (msg->cm_fields['J'] != NULL) {
2477 qualified_for_journaling = 0;
2480 if (recps == NULL) {
2481 qualified_for_journaling = config.c_journal_pubmsgs;
2483 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2484 qualified_for_journaling = config.c_journal_email;
2487 qualified_for_journaling = config.c_journal_pubmsgs;
2492 * Do we have to perform journaling? If so, hand off the saved
2493 * RFC822 version will be handed off to the journaler for background
2494 * submit. Otherwise, we have to free the memory ourselves.
2496 if (saved_rfc822_version != NULL) {
2497 if (qualified_for_journaling) {
2498 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2501 free(saved_rfc822_version);
2514 * Convenience function for generating small administrative messages.
2516 void quickie_message(char *from, char *to, char *room, char *text,
2517 int format_type, char *subject)
2519 struct CtdlMessage *msg;
2520 struct recptypes *recp = NULL;
2522 msg = malloc(sizeof(struct CtdlMessage));
2523 memset(msg, 0, sizeof(struct CtdlMessage));
2524 msg->cm_magic = CTDLMESSAGE_MAGIC;
2525 msg->cm_anon_type = MES_NORMAL;
2526 msg->cm_format_type = format_type;
2527 msg->cm_fields['A'] = strdup(from);
2528 if (room != NULL) msg->cm_fields['O'] = strdup(room);
2529 msg->cm_fields['N'] = strdup(NODENAME);
2531 msg->cm_fields['R'] = strdup(to);
2532 recp = validate_recipients(to);
2534 if (subject != NULL) {
2535 msg->cm_fields['U'] = strdup(subject);
2537 msg->cm_fields['M'] = strdup(text);
2539 CtdlSubmitMsg(msg, recp, room);
2540 CtdlFreeMessage(msg);
2541 if (recp != NULL) free(recp);
2547 * Back end function used by CtdlMakeMessage() and similar functions
2549 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
2550 size_t maxlen, /* maximum message length */
2551 char *exist, /* if non-null, append to it;
2552 exist is ALWAYS freed */
2553 int crlf /* CRLF newlines instead of LF */
2557 size_t message_len = 0;
2558 size_t buffer_len = 0;
2564 if (exist == NULL) {
2571 message_len = strlen(exist);
2572 buffer_len = message_len + 4096;
2573 m = realloc(exist, buffer_len);
2580 /* flush the input if we have nowhere to store it */
2585 /* read in the lines of message text one by one */
2587 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2588 if (!strcmp(buf, terminator)) finished = 1;
2590 strcat(buf, "\r\n");
2596 if ( (!flushing) && (!finished) ) {
2597 /* Measure the line */
2598 linelen = strlen(buf);
2600 /* augment the buffer if we have to */
2601 if ((message_len + linelen) >= buffer_len) {
2602 ptr = realloc(m, (buffer_len * 2) );
2603 if (ptr == NULL) { /* flush if can't allocate */
2606 buffer_len = (buffer_len * 2);
2608 lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2612 /* Add the new line to the buffer. NOTE: this loop must avoid
2613 * using functions like strcat() and strlen() because they
2614 * traverse the entire buffer upon every call, and doing that
2615 * for a multi-megabyte message slows it down beyond usability.
2617 strcpy(&m[message_len], buf);
2618 message_len += linelen;
2621 /* if we've hit the max msg length, flush the rest */
2622 if (message_len >= maxlen) flushing = 1;
2624 } while (!finished);
2632 * Build a binary message to be saved on disk.
2633 * (NOTE: if you supply 'preformatted_text', the buffer you give it
2634 * will become part of the message. This means you are no longer
2635 * responsible for managing that memory -- it will be freed along with
2636 * the rest of the fields when CtdlFreeMessage() is called.)
2639 struct CtdlMessage *CtdlMakeMessage(
2640 struct ctdluser *author, /* author's user structure */
2641 char *recipient, /* NULL if it's not mail */
2642 char *recp_cc, /* NULL if it's not mail */
2643 char *room, /* room where it's going */
2644 int type, /* see MES_ types in header file */
2645 int format_type, /* variformat, plain text, MIME... */
2646 char *fake_name, /* who we're masquerading as */
2647 char *subject, /* Subject (optional) */
2648 char *preformatted_text /* ...or NULL to read text from client */
2650 char dest_node[SIZ];
2652 struct CtdlMessage *msg;
2654 msg = malloc(sizeof(struct CtdlMessage));
2655 memset(msg, 0, sizeof(struct CtdlMessage));
2656 msg->cm_magic = CTDLMESSAGE_MAGIC;
2657 msg->cm_anon_type = type;
2658 msg->cm_format_type = format_type;
2660 /* Don't confuse the poor folks if it's not routed mail. */
2661 strcpy(dest_node, "");
2666 snprintf(buf, sizeof buf, "cit%ld", author->usernum); /* Path */
2667 msg->cm_fields['P'] = strdup(buf);
2669 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
2670 msg->cm_fields['T'] = strdup(buf);
2672 if (fake_name[0]) /* author */
2673 msg->cm_fields['A'] = strdup(fake_name);
2675 msg->cm_fields['A'] = strdup(author->fullname);
2677 if (CC->room.QRflags & QR_MAILBOX) { /* room */
2678 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2681 msg->cm_fields['O'] = strdup(CC->room.QRname);
2684 msg->cm_fields['N'] = strdup(NODENAME); /* nodename */
2685 msg->cm_fields['H'] = strdup(HUMANNODE); /* hnodename */
2687 if (recipient[0] != 0) {
2688 msg->cm_fields['R'] = strdup(recipient);
2690 if (recp_cc[0] != 0) {
2691 msg->cm_fields['Y'] = strdup(recp_cc);
2693 if (dest_node[0] != 0) {
2694 msg->cm_fields['D'] = strdup(dest_node);
2697 if ( (author == &CC->user) && (strlen(CC->cs_inet_email) > 0) ) {
2698 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2701 if (subject != NULL) {
2703 if (strlen(subject) > 0) {
2704 msg->cm_fields['U'] = strdup(subject);
2708 if (preformatted_text != NULL) {
2709 msg->cm_fields['M'] = preformatted_text;
2712 msg->cm_fields['M'] = CtdlReadMessageBody("000",
2713 config.c_maxmsglen, NULL, 0);
2721 * Check to see whether we have permission to post a message in the current
2722 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
2723 * returns 0 on success.
2725 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
2727 if (!(CC->logged_in)) {
2728 snprintf(errmsgbuf, n, "Not logged in.");
2729 return (ERROR + NOT_LOGGED_IN);
2732 if ((CC->user.axlevel < 2)
2733 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
2734 snprintf(errmsgbuf, n, "Need to be validated to enter "
2735 "(except in %s> to sysop)", MAILROOM);
2736 return (ERROR + HIGHER_ACCESS_REQUIRED);
2739 if ((CC->user.axlevel < 4)
2740 && (CC->room.QRflags & QR_NETWORK)) {
2741 snprintf(errmsgbuf, n, "Need net privileges to enter here.");
2742 return (ERROR + HIGHER_ACCESS_REQUIRED);
2745 if ((CC->user.axlevel < 6)
2746 && (CC->room.QRflags & QR_READONLY)) {
2747 snprintf(errmsgbuf, n, "Sorry, this is a read-only room.");
2748 return (ERROR + HIGHER_ACCESS_REQUIRED);
2751 strcpy(errmsgbuf, "Ok");
2757 * Check to see if the specified user has Internet mail permission
2758 * (returns nonzero if permission is granted)
2760 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
2762 /* Do not allow twits to send Internet mail */
2763 if (who->axlevel <= 2) return(0);
2765 /* Globally enabled? */
2766 if (config.c_restrict == 0) return(1);
2768 /* User flagged ok? */
2769 if (who->flags & US_INTERNET) return(2);
2771 /* Aide level access? */
2772 if (who->axlevel >= 6) return(3);
2774 /* No mail for you! */
2780 * Validate recipients, count delivery types and errors, and handle aliasing
2781 * FIXME check for dupes!!!!!
2782 * Returns 0 if all addresses are ok, -1 if no addresses were specified,
2783 * or the number of addresses found invalid.
2785 struct recptypes *validate_recipients(char *supplied_recipients) {
2786 struct recptypes *ret;
2787 char recipients[SIZ];
2788 char this_recp[256];
2789 char this_recp_cooked[256];
2795 struct ctdluser tempUS;
2796 struct ctdlroom tempQR;
2800 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
2801 if (ret == NULL) return(NULL);
2802 memset(ret, 0, sizeof(struct recptypes));
2805 ret->num_internet = 0;
2810 if (supplied_recipients == NULL) {
2811 strcpy(recipients, "");
2814 safestrncpy(recipients, supplied_recipients, sizeof recipients);
2817 /* Change all valid separator characters to commas */
2818 for (i=0; i<strlen(recipients); ++i) {
2819 if ((recipients[i] == ';') || (recipients[i] == '|')) {
2820 recipients[i] = ',';
2824 /* Now start extracting recipients... */
2826 while (strlen(recipients) > 0) {
2828 for (i=0; i<=strlen(recipients); ++i) {
2829 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
2830 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
2831 safestrncpy(this_recp, recipients, i+1);
2833 if (recipients[i] == ',') {
2834 strcpy(recipients, &recipients[i+1]);
2837 strcpy(recipients, "");
2844 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
2846 mailtype = alias(this_recp);
2847 mailtype = alias(this_recp);
2848 mailtype = alias(this_recp);
2849 for (j=0; j<=strlen(this_recp); ++j) {
2850 if (this_recp[j]=='_') {
2851 this_recp_cooked[j] = ' ';
2854 this_recp_cooked[j] = this_recp[j];
2860 if (!strcasecmp(this_recp, "sysop")) {
2862 strcpy(this_recp, config.c_aideroom);
2863 if (strlen(ret->recp_room) > 0) {
2864 strcat(ret->recp_room, "|");
2866 strcat(ret->recp_room, this_recp);
2868 else if (getuser(&tempUS, this_recp) == 0) {
2870 strcpy(this_recp, tempUS.fullname);
2871 if (strlen(ret->recp_local) > 0) {
2872 strcat(ret->recp_local, "|");
2874 strcat(ret->recp_local, this_recp);
2876 else if (getuser(&tempUS, this_recp_cooked) == 0) {
2878 strcpy(this_recp, tempUS.fullname);
2879 if (strlen(ret->recp_local) > 0) {
2880 strcat(ret->recp_local, "|");
2882 strcat(ret->recp_local, this_recp);
2884 else if ( (!strncasecmp(this_recp, "room_", 5))
2885 && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
2887 if (strlen(ret->recp_room) > 0) {
2888 strcat(ret->recp_room, "|");
2890 strcat(ret->recp_room, &this_recp_cooked[5]);
2898 /* Yes, you're reading this correctly: if the target
2899 * domain points back to the local system or an attached
2900 * Citadel directory, the address is invalid. That's
2901 * because if the address were valid, we would have
2902 * already translated it to a local address by now.
2904 if (IsDirectory(this_recp)) {
2909 ++ret->num_internet;
2910 if (strlen(ret->recp_internet) > 0) {
2911 strcat(ret->recp_internet, "|");
2913 strcat(ret->recp_internet, this_recp);
2918 if (strlen(ret->recp_ignet) > 0) {
2919 strcat(ret->recp_ignet, "|");
2921 strcat(ret->recp_ignet, this_recp);
2929 if (strlen(ret->errormsg) == 0) {
2930 snprintf(append, sizeof append,
2931 "Invalid recipient: %s",
2935 snprintf(append, sizeof append,
2938 if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
2939 strcat(ret->errormsg, append);
2943 if (strlen(ret->display_recp) == 0) {
2944 strcpy(append, this_recp);
2947 snprintf(append, sizeof append, ", %s",
2950 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
2951 strcat(ret->display_recp, append);
2956 if ((ret->num_local + ret->num_internet + ret->num_ignet +
2957 ret->num_room + ret->num_error) == 0) {
2958 ret->num_error = (-1);
2959 strcpy(ret->errormsg, "No recipients specified.");
2962 lprintf(CTDL_DEBUG, "validate_recipients()\n");
2963 lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
2964 lprintf(CTDL_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
2965 lprintf(CTDL_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
2966 lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
2967 lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
2975 * message entry - mode 0 (normal)
2977 void cmd_ent0(char *entargs)
2983 char masquerade_as[SIZ];
2985 int format_type = 0;
2986 char newusername[SIZ];
2987 struct CtdlMessage *msg;
2991 struct recptypes *valid = NULL;
2992 struct recptypes *valid_to = NULL;
2993 struct recptypes *valid_cc = NULL;
2994 struct recptypes *valid_bcc = NULL;
3001 post = extract_int(entargs, 0);
3002 extract_token(recp, entargs, 1, '|', sizeof recp);
3003 anon_flag = extract_int(entargs, 2);
3004 format_type = extract_int(entargs, 3);
3005 extract_token(subject, entargs, 4, '|', sizeof subject);
3006 do_confirm = extract_int(entargs, 6);
3007 extract_token(cc, entargs, 7, '|', sizeof cc);
3008 extract_token(bcc, entargs, 8, '|', sizeof bcc);
3010 /* first check to make sure the request is valid. */
3012 err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3014 cprintf("%d %s\n", err, errmsg);
3018 /* Check some other permission type things. */
3021 if (CC->user.axlevel < 6) {
3022 cprintf("%d You don't have permission to masquerade.\n",
3023 ERROR + HIGHER_ACCESS_REQUIRED);
3026 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3027 memset(CC->fake_postname, 0, sizeof(CC->fake_postname) );
3028 safestrncpy(CC->fake_postname, newusername,
3029 sizeof(CC->fake_postname) );
3030 cprintf("%d ok\n", CIT_OK);
3033 CC->cs_flags |= CS_POSTING;
3035 /* In the Mail> room we have to behave a little differently --
3036 * make sure the user has specified at least one recipient. Then
3037 * validate the recipient(s).
3039 if ( (CC->room.QRflags & QR_MAILBOX)
3040 && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) ) {
3042 if (CC->user.axlevel < 2) {
3043 strcpy(recp, "sysop");
3048 valid_to = validate_recipients(recp);
3049 if (valid_to->num_error > 0) {
3050 cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3055 valid_cc = validate_recipients(cc);
3056 if (valid_cc->num_error > 0) {
3057 cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3063 valid_bcc = validate_recipients(bcc);
3064 if (valid_bcc->num_error > 0) {
3065 cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3072 /* Recipient required, but none were specified */
3073 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3077 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3081 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3082 if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3083 cprintf("%d You do not have permission "
3084 "to send Internet mail.\n",
3085 ERROR + HIGHER_ACCESS_REQUIRED);
3093 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)
3094 && (CC->user.axlevel < 4) ) {
3095 cprintf("%d Higher access required for network mail.\n",
3096 ERROR + HIGHER_ACCESS_REQUIRED);
3103 if ((RESTRICT_INTERNET == 1)
3104 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3105 && ((CC->user.flags & US_INTERNET) == 0)
3106 && (!CC->internal_pgm)) {
3107 cprintf("%d You don't have access to Internet mail.\n",
3108 ERROR + HIGHER_ACCESS_REQUIRED);
3117 /* Is this a room which has anonymous-only or anonymous-option? */
3118 anonymous = MES_NORMAL;
3119 if (CC->room.QRflags & QR_ANONONLY) {
3120 anonymous = MES_ANONONLY;
3122 if (CC->room.QRflags & QR_ANONOPT) {
3123 if (anon_flag == 1) { /* only if the user requested it */
3124 anonymous = MES_ANONOPT;
3128 if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3132 /* If we're only checking the validity of the request, return
3133 * success without creating the message.
3136 cprintf("%d %s\n", CIT_OK,
3137 ((valid_to != NULL) ? valid_to->display_recp : "") );
3144 /* We don't need these anymore because we'll do it differently below */
3149 /* Handle author masquerading */
3150 if (CC->fake_postname[0]) {
3151 strcpy(masquerade_as, CC->fake_postname);
3153 else if (CC->fake_username[0]) {
3154 strcpy(masquerade_as, CC->fake_username);
3157 strcpy(masquerade_as, "");
3160 /* Read in the message from the client. */
3162 cprintf("%d send message\n", START_CHAT_MODE);
3164 cprintf("%d send message\n", SEND_LISTING);
3167 msg = CtdlMakeMessage(&CC->user, recp, cc,
3168 CC->room.QRname, anonymous, format_type,
3169 masquerade_as, subject, NULL);
3171 /* Put together one big recipients struct containing to/cc/bcc all in
3172 * one. This is for the envelope.
3174 char *all_recps = malloc(SIZ * 3);
3175 strcpy(all_recps, recp);
3176 if (strlen(cc) > 0) {
3177 if (strlen(all_recps) > 0) {
3178 strcat(all_recps, ",");
3180 strcat(all_recps, cc);
3182 if (strlen(bcc) > 0) {
3183 if (strlen(all_recps) > 0) {
3184 strcat(all_recps, ",");
3186 strcat(all_recps, bcc);
3188 if (strlen(all_recps) > 0) {
3189 valid = validate_recipients(all_recps);
3197 msgnum = CtdlSubmitMsg(msg, valid, "");
3200 cprintf("%ld\n", msgnum);
3202 cprintf("Message accepted.\n");
3205 cprintf("Internal error.\n");
3207 if (msg->cm_fields['E'] != NULL) {
3208 cprintf("%s\n", msg->cm_fields['E']);
3215 CtdlFreeMessage(msg);
3217 CC->fake_postname[0] = '\0';
3218 if (valid != NULL) {
3227 * API function to delete messages which match a set of criteria
3228 * (returns the actual number of messages deleted)
3230 int CtdlDeleteMessages(char *room_name, /* which room */
3231 long dmsgnum, /* or "0" for any */
3232 char *content_type, /* or "" for any */
3233 int deferred /* let TDAP sweep it later */
3237 struct ctdlroom qrbuf;
3238 struct cdbdata *cdbfr;
3239 long *msglist = NULL;
3240 long *dellist = NULL;
3243 int num_deleted = 0;
3245 struct MetaData smi;
3247 lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %ld, %s, %d)\n",
3248 room_name, dmsgnum, content_type, deferred);
3250 /* get room record, obtaining a lock... */
3251 if (lgetroom(&qrbuf, room_name) != 0) {
3252 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3254 return (0); /* room not found */
3256 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3258 if (cdbfr != NULL) {
3259 dellist = malloc(cdbfr->len);
3260 msglist = (long *) cdbfr->ptr;
3261 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
3262 num_msgs = cdbfr->len / sizeof(long);
3266 for (i = 0; i < num_msgs; ++i) {
3269 /* Set/clear a bit for each criterion */
3271 if ((dmsgnum == 0L) || (msglist[i] == dmsgnum)) {
3272 delete_this |= 0x01;
3274 if (strlen(content_type) == 0) {
3275 delete_this |= 0x02;
3277 GetMetaData(&smi, msglist[i]);
3278 if (!strcasecmp(smi.meta_content_type,
3280 delete_this |= 0x02;
3284 /* Delete message only if all bits are set */
3285 if (delete_this == 0x03) {
3286 dellist[num_deleted++] = msglist[i];
3291 num_msgs = sort_msglist(msglist, num_msgs);
3292 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3293 msglist, (int)(num_msgs * sizeof(long)));
3295 qrbuf.QRhighest = msglist[num_msgs - 1];
3300 * If the delete operation is "deferred" (and technically, any delete
3301 * operation not performed by THE DREADED AUTO-PURGER ought to be
3302 * a deferred delete) then we save a pointer to the message in the
3303 * DELETED_MSGS_ROOM. This will cause the reference count to remain
3304 * at least 1, which will save the user from having to synchronously
3305 * wait for various disk-intensive operations to complete.
3307 if ( (deferred) && (num_deleted) ) {
3308 for (i=0; i<num_deleted; ++i) {
3309 CtdlCopyMsgToRoom(dellist[i], DELETED_MSGS_ROOM);
3313 /* Go through the messages we pulled out of the index, and decrement
3314 * their reference counts by 1. If this is the only room the message
3315 * was in, the reference count will reach zero and the message will
3316 * automatically be deleted from the database. We do this in a
3317 * separate pass because there might be plug-in hooks getting called,
3318 * and we don't want that happening during an S_ROOMS critical
3321 if (num_deleted) for (i=0; i<num_deleted; ++i) {
3322 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3323 AdjRefCount(dellist[i], -1);
3326 /* Now free the memory we used, and go away. */
3327 if (msglist != NULL) free(msglist);
3328 if (dellist != NULL) free(dellist);
3329 lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3330 return (num_deleted);
3336 * Check whether the current user has permission to delete messages from
3337 * the current room (returns 1 for yes, 0 for no)
3339 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3340 getuser(&CC->user, CC->curr_user);
3341 if ((CC->user.axlevel < 6)
3342 && (CC->user.usernum != CC->room.QRroomaide)
3343 && ((CC->room.QRflags & QR_MAILBOX) == 0)
3344 && (!(CC->internal_pgm))) {
3353 * Delete message from current room
3355 void cmd_dele(char *delstr)
3360 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3361 cprintf("%d Higher access required.\n",
3362 ERROR + HIGHER_ACCESS_REQUIRED);
3365 delnum = extract_long(delstr, 0);
3367 num_deleted = CtdlDeleteMessages(CC->room.QRname, delnum, "", 1);
3370 cprintf("%d %d message%s deleted.\n", CIT_OK,
3371 num_deleted, ((num_deleted != 1) ? "s" : ""));
3373 cprintf("%d Message %ld not found.\n", ERROR + MESSAGE_NOT_FOUND, delnum);
3379 * Back end API function for moves and deletes
3381 int CtdlCopyMsgToRoom(long msgnum, char *dest) {
3384 err = CtdlSaveMsgPointerInRoom(dest, msgnum, 1, NULL);
3385 if (err != 0) return(err);
3393 * move or copy a message to another room
3395 void cmd_move(char *args)
3398 char targ[ROOMNAMELEN];
3399 struct ctdlroom qtemp;
3405 num = extract_long(args, 0);
3406 extract_token(targ, args, 1, '|', sizeof targ);
3407 convert_room_name_macros(targ, sizeof targ);
3408 targ[ROOMNAMELEN - 1] = 0;
3409 is_copy = extract_int(args, 2);
3411 if (getroom(&qtemp, targ) != 0) {
3412 cprintf("%d '%s' does not exist.\n",
3413 ERROR + ROOM_NOT_FOUND, targ);
3417 getuser(&CC->user, CC->curr_user);
3418 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3420 /* Check for permission to perform this operation.
3421 * Remember: "CC->room" is source, "qtemp" is target.
3425 /* Aides can move/copy */
3426 if (CC->user.axlevel >= 6) permit = 1;
3428 /* Room aides can move/copy */
3429 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3431 /* Permit move/copy from personal rooms */
3432 if ((CC->room.QRflags & QR_MAILBOX)
3433 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3435 /* Permit only copy from public to personal room */
3437 && (!(CC->room.QRflags & QR_MAILBOX))
3438 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3440 /* User must have access to target room */
3441 if (!(ra & UA_KNOWN)) permit = 0;
3444 cprintf("%d Higher access required.\n",
3445 ERROR + HIGHER_ACCESS_REQUIRED);
3449 err = CtdlCopyMsgToRoom(num, targ);
3451 cprintf("%d Cannot store message in %s: error %d\n",
3456 /* Now delete the message from the source room,
3457 * if this is a 'move' rather than a 'copy' operation.
3460 CtdlDeleteMessages(CC->room.QRname, num, "", 0);
3463 cprintf("%d Message %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3469 * GetMetaData() - Get the supplementary record for a message
3471 void GetMetaData(struct MetaData *smibuf, long msgnum)
3474 struct cdbdata *cdbsmi;
3477 memset(smibuf, 0, sizeof(struct MetaData));
3478 smibuf->meta_msgnum = msgnum;
3479 smibuf->meta_refcount = 1; /* Default reference count is 1 */
3481 /* Use the negative of the message number for its supp record index */
3482 TheIndex = (0L - msgnum);
3484 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3485 if (cdbsmi == NULL) {
3486 return; /* record not found; go with defaults */
3488 memcpy(smibuf, cdbsmi->ptr,
3489 ((cdbsmi->len > sizeof(struct MetaData)) ?
3490 sizeof(struct MetaData) : cdbsmi->len));
3497 * PutMetaData() - (re)write supplementary record for a message
3499 void PutMetaData(struct MetaData *smibuf)
3503 /* Use the negative of the message number for the metadata db index */
3504 TheIndex = (0L - smibuf->meta_msgnum);
3506 lprintf(CTDL_DEBUG, "PutMetaData(%ld) - ref count is %d\n",
3507 smibuf->meta_msgnum, smibuf->meta_refcount);
3509 cdb_store(CDB_MSGMAIN,
3510 &TheIndex, (int)sizeof(long),
3511 smibuf, (int)sizeof(struct MetaData));
3516 * AdjRefCount - change the reference count for a message;
3517 * delete the message if it reaches zero
3519 void AdjRefCount(long msgnum, int incr)
3522 struct MetaData smi;
3525 /* This is a *tight* critical section; please keep it that way, as
3526 * it may get called while nested in other critical sections.
3527 * Complicating this any further will surely cause deadlock!
3529 begin_critical_section(S_SUPPMSGMAIN);
3530 GetMetaData(&smi, msgnum);
3531 smi.meta_refcount += incr;
3533 end_critical_section(S_SUPPMSGMAIN);
3534 lprintf(CTDL_DEBUG, "msg %ld ref count incr %d, is now %d\n",
3535 msgnum, incr, smi.meta_refcount);
3537 /* If the reference count is now zero, delete the message
3538 * (and its supplementary record as well).
3540 if (smi.meta_refcount == 0) {
3541 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
3543 /* Remove from fulltext index */
3544 if (config.c_enable_fulltext) {
3545 ft_index_message(msgnum, 0);
3548 /* Remove from message base */
3550 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3551 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3553 /* Remove metadata record */
3554 delnum = (0L - msgnum);
3555 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3560 * Write a generic object to this room
3562 * Note: this could be much more efficient. Right now we use two temporary
3563 * files, and still pull the message into memory as with all others.
3565 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
3566 char *content_type, /* MIME type of this object */
3567 char *tempfilename, /* Where to fetch it from */
3568 struct ctdluser *is_mailbox, /* Mailbox room? */
3569 int is_binary, /* Is encoding necessary? */
3570 int is_unique, /* Del others of this type? */
3571 unsigned int flags /* Internal save flags */
3576 struct ctdlroom qrbuf;
3577 char roomname[ROOMNAMELEN];
3578 struct CtdlMessage *msg;
3580 char *raw_message = NULL;
3581 char *encoded_message = NULL;
3582 off_t raw_length = 0;
3584 if (is_mailbox != NULL) {
3585 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3588 safestrncpy(roomname, req_room, sizeof(roomname));
3591 fp = fopen(tempfilename, "rb");
3593 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
3594 tempfilename, strerror(errno));
3597 fseek(fp, 0L, SEEK_END);
3598 raw_length = ftell(fp);
3600 lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
3602 raw_message = malloc((size_t)raw_length + 2);
3603 fread(raw_message, (size_t)raw_length, 1, fp);
3607 encoded_message = malloc((size_t)
3608 (((raw_length * 134) / 100) + 4096 ) );
3611 encoded_message = malloc((size_t)(raw_length + 4096));
3614 sprintf(encoded_message, "Content-type: %s\n", content_type);
3617 sprintf(&encoded_message[strlen(encoded_message)],
3618 "Content-transfer-encoding: base64\n\n"
3622 sprintf(&encoded_message[strlen(encoded_message)],
3623 "Content-transfer-encoding: 7bit\n\n"
3629 &encoded_message[strlen(encoded_message)],
3635 raw_message[raw_length] = 0;
3637 &encoded_message[strlen(encoded_message)],
3645 lprintf(CTDL_DEBUG, "Allocating\n");
3646 msg = malloc(sizeof(struct CtdlMessage));
3647 memset(msg, 0, sizeof(struct CtdlMessage));
3648 msg->cm_magic = CTDLMESSAGE_MAGIC;
3649 msg->cm_anon_type = MES_NORMAL;
3650 msg->cm_format_type = 4;
3651 msg->cm_fields['A'] = strdup(CC->user.fullname);
3652 msg->cm_fields['O'] = strdup(req_room);
3653 msg->cm_fields['N'] = strdup(config.c_nodename);
3654 msg->cm_fields['H'] = strdup(config.c_humannode);
3655 msg->cm_flags = flags;
3657 msg->cm_fields['M'] = encoded_message;
3659 /* Create the requested room if we have to. */
3660 if (getroom(&qrbuf, roomname) != 0) {
3661 create_room(roomname,
3662 ( (is_mailbox != NULL) ? 5 : 3 ),
3663 "", 0, 1, 0, VIEW_BBS);
3665 /* If the caller specified this object as unique, delete all
3666 * other objects of this type that are currently in the room.
3669 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
3670 CtdlDeleteMessages(roomname, 0L, content_type, 0)
3673 /* Now write the data */
3674 CtdlSubmitMsg(msg, NULL, roomname);
3675 CtdlFreeMessage(msg);
3683 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
3684 config_msgnum = msgnum;
3688 char *CtdlGetSysConfig(char *sysconfname) {
3689 char hold_rm[ROOMNAMELEN];
3692 struct CtdlMessage *msg;
3695 strcpy(hold_rm, CC->room.QRname);
3696 if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
3697 getroom(&CC->room, hold_rm);
3702 /* We want the last (and probably only) config in this room */
3703 begin_critical_section(S_CONFIG);
3704 config_msgnum = (-1L);
3705 CtdlForEachMessage(MSGS_LAST, 1, sysconfname, NULL,
3706 CtdlGetSysConfigBackend, NULL);
3707 msgnum = config_msgnum;
3708 end_critical_section(S_CONFIG);
3714 msg = CtdlFetchMessage(msgnum, 1);
3716 conf = strdup(msg->cm_fields['M']);
3717 CtdlFreeMessage(msg);
3724 getroom(&CC->room, hold_rm);
3726 if (conf != NULL) do {
3727 extract_token(buf, conf, 0, '\n', sizeof buf);
3728 strcpy(conf, &conf[strlen(buf)+1]);
3729 } while ( (strlen(conf)>0) && (strlen(buf)>0) );
3734 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
3735 char temp[PATH_MAX];
3738 CtdlMakeTempFileName(temp, sizeof temp);
3740 fp = fopen(temp, "w");
3741 if (fp == NULL) return;
3742 fprintf(fp, "%s", sysconfdata);
3745 /* this handy API function does all the work for us */
3746 CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
3752 * Determine whether a given Internet address belongs to the current user
3754 int CtdlIsMe(char *addr, int addr_buf_len)
3756 struct recptypes *recp;
3759 recp = validate_recipients(addr);
3760 if (recp == NULL) return(0);
3762 if (recp->num_local == 0) {
3767 for (i=0; i<recp->num_local; ++i) {
3768 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
3769 if (!strcasecmp(addr, CC->user.fullname)) {
3781 * Citadel protocol command to do the same
3783 void cmd_isme(char *argbuf) {
3786 if (CtdlAccessCheck(ac_logged_in)) return;
3787 extract_token(addr, argbuf, 0, '|', sizeof addr);
3789 if (CtdlIsMe(addr, sizeof addr)) {
3790 cprintf("%d %s\n", CIT_OK, addr);
3793 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);