2 * Implements the message store.
4 * Copyright (c) 1987-2012 by the citadel.org team
6 * This program is open source software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License version 3.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
21 #if TIME_WITH_SYS_TIME
22 # include <sys/time.h>
26 # include <sys/time.h>
39 #include <sys/types.h>
44 #include <libcitadel.h>
47 #include "serv_extensions.h"
51 #include "sysdep_decls.h"
52 #include "citserver.h"
59 #include "internet_addressing.h"
60 #include "euidindex.h"
61 #include "journaling.h"
62 #include "citadel_dirs.h"
63 #include "clientsocket.h"
66 #include "ctdl_module.h"
69 struct addresses_to_be_filed *atbf = NULL;
71 /* This temp file holds the queue of operations for AdjRefCount() */
72 static FILE *arcfp = NULL;
73 void AdjRefCountList(long *msgnum, long nmsg, int incr);
75 int MessageDebugEnabled = 0;
78 * These are the four-character field headers we use when outputting
79 * messages in Citadel format (as opposed to RFC822 format).
82 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
83 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
84 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
85 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
86 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
87 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
88 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
89 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
119 eMsgField FieldOrder[] = {
120 /* Important fields */
131 /* Semi-important fields */
137 /* G is not used yet, may become virus signature*/
140 /* Q is not used yet */
143 /* X is not used yet */
144 /* Z is not used yet */
151 /* Message text (MUST be last) */
153 /* Not saved to disk:
158 static const long NDiskFields = sizeof(FieldOrder) / sizeof(eMsgField);
160 int CM_IsEmpty(struct CtdlMessage *Msg, eMsgField which)
162 return !((Msg->cm_fields[which] != NULL) &&
163 (Msg->cm_fields[which][0] != '\0'));
166 void CM_SetField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length)
168 if (Msg->cm_fields[which] != NULL)
169 free (Msg->cm_fields[which]);
170 Msg->cm_fields[which] = malloc(length + 1);
171 memcpy(Msg->cm_fields[which], buf, length);
172 Msg->cm_fields[which][length] = '\0';
175 void CM_SetFieldLONG(struct CtdlMessage *Msg, eMsgField which, long lvalue)
179 len = snprintf(buf, sizeof(buf), "%ld", lvalue);
180 CM_SetField(Msg, which, buf, len);
182 void CM_CutFieldAt(struct CtdlMessage *Msg, eMsgField WhichToCut, long maxlen)
184 if (Msg->cm_fields[WhichToCut] == NULL)
187 if (strlen(Msg->cm_fields[WhichToCut]) > maxlen)
188 Msg->cm_fields[WhichToCut][maxlen] = '\0';
191 void CM_FlushField(struct CtdlMessage *Msg, eMsgField which)
193 if (Msg->cm_fields[which] != NULL)
194 free (Msg->cm_fields[which]);
195 Msg->cm_fields[which] = NULL;
198 void CM_CopyField(struct CtdlMessage *Msg, eMsgField WhichToPutTo, eMsgField WhichtToCopy)
201 if (Msg->cm_fields[WhichToPutTo] != NULL)
202 free (Msg->cm_fields[WhichToPutTo]);
204 if (Msg->cm_fields[WhichtToCopy] != NULL)
206 len = strlen(Msg->cm_fields[WhichtToCopy]);
207 Msg->cm_fields[WhichToPutTo] = malloc(len + 1);
208 memcpy(Msg->cm_fields[WhichToPutTo], Msg->cm_fields[WhichToPutTo], len);
209 Msg->cm_fields[WhichToPutTo][len] = '\0';
212 Msg->cm_fields[WhichToPutTo] = NULL;
216 void CM_PrependToField(struct CtdlMessage *Msg, eMsgField which, const char *buf, long length)
218 if (Msg->cm_fields[which] != NULL) {
223 oldmsgsize = strlen(Msg->cm_fields[which]) + 1;
224 newmsgsize = length + oldmsgsize;
226 new = malloc(newmsgsize);
227 memcpy(new, buf, length);
228 memcpy(new + length, Msg->cm_fields[which], oldmsgsize);
229 free(Msg->cm_fields[which]);
230 Msg->cm_fields[which] = new;
233 Msg->cm_fields[which] = malloc(length + 1);
234 memcpy(Msg->cm_fields[which], buf, length);
235 Msg->cm_fields[which][length] = '\0';
239 void CM_SetAsField(struct CtdlMessage *Msg, eMsgField which, char **buf, long length)
241 if (Msg->cm_fields[which] != NULL)
242 free (Msg->cm_fields[which]);
244 Msg->cm_fields[which] = *buf;
248 void CM_SetAsFieldSB(struct CtdlMessage *Msg, eMsgField which, StrBuf **buf)
250 if (Msg->cm_fields[which] != NULL)
251 free (Msg->cm_fields[which]);
253 Msg->cm_fields[which] = SmashStrBuf(buf);
256 void CM_GetAsField(struct CtdlMessage *Msg, eMsgField which, char **ret, long *retlen)
258 if (Msg->cm_fields[which] != NULL)
260 *retlen = strlen(Msg->cm_fields[which]);
261 *ret = Msg->cm_fields[which];
262 Msg->cm_fields[which] = NULL;
272 * Returns 1 if the supplied pointer points to a valid Citadel message.
273 * If the pointer is NULL or the magic number check fails, returns 0.
275 int CM_IsValidMsg(struct CtdlMessage *msg) {
278 if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
279 struct CitContext *CCC = CC;
280 MSGM_syslog(LOG_WARNING, "CM_IsValidMsg() -- self-check failed\n");
286 void CM_FreeContents(struct CtdlMessage *msg)
290 for (i = 0; i < 256; ++i)
291 if (msg->cm_fields[i] != NULL) {
292 free(msg->cm_fields[i]);
295 msg->cm_magic = 0; /* just in case */
298 * 'Destructor' for struct CtdlMessage
300 void CM_Free(struct CtdlMessage *msg)
302 if (CM_IsValidMsg(msg) == 0)
304 if (msg != NULL) free (msg);
307 CM_FreeContents(msg);
311 int CM_DupField(eMsgField i, struct CtdlMessage *OrgMsg, struct CtdlMessage *NewMsg)
314 len = strlen(OrgMsg->cm_fields[i]);
315 NewMsg->cm_fields[i] = malloc(len + 1);
316 if (NewMsg->cm_fields[i] == NULL)
318 memcpy(NewMsg->cm_fields[i], OrgMsg->cm_fields[i], len);
319 NewMsg->cm_fields[i][len] = '\0';
323 struct CtdlMessage * CM_Duplicate(struct CtdlMessage *OrgMsg)
326 struct CtdlMessage *NewMsg;
328 if (CM_IsValidMsg(OrgMsg) == 0)
330 NewMsg = (struct CtdlMessage *)malloc(sizeof(struct CtdlMessage));
334 memcpy(NewMsg, OrgMsg, sizeof(struct CtdlMessage));
336 memset(&NewMsg->cm_fields, 0, sizeof(char*) * 256);
338 for (i = 0; i < 256; ++i)
340 if (OrgMsg->cm_fields[i] != NULL)
342 if (!CM_DupField(i, OrgMsg, NewMsg))
356 * This function is self explanatory.
357 * (What can I say, I'm in a weird mood today...)
359 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
363 for (i = 0; i < strlen(name); ++i) {
364 if (name[i] == '@') {
365 while (isspace(name[i - 1]) && i > 0) {
366 strcpy(&name[i - 1], &name[i]);
369 while (isspace(name[i + 1])) {
370 strcpy(&name[i + 1], &name[i + 2]);
378 * Aliasing for network mail.
379 * (Error messages have been commented out, because this is a server.)
381 int alias(char *name)
382 { /* process alias and routing info for mail */
383 struct CitContext *CCC = CC;
386 char aaa[SIZ], bbb[SIZ];
387 char *ignetcfg = NULL;
388 char *ignetmap = NULL;
394 char original_name[256];
395 safestrncpy(original_name, name, sizeof original_name);
398 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
399 stripallbut(name, '<', '>');
401 fp = fopen(file_mail_aliases, "r");
403 fp = fopen("/dev/null", "r");
410 while (fgets(aaa, sizeof aaa, fp) != NULL) {
411 while (isspace(name[0]))
412 strcpy(name, &name[1]);
413 aaa[strlen(aaa) - 1] = 0;
415 for (a = 0; a < strlen(aaa); ++a) {
417 strcpy(bbb, &aaa[a + 1]);
421 if (!strcasecmp(name, aaa))
426 /* Hit the Global Address Book */
427 if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
431 if (strcasecmp(original_name, name)) {
432 MSG_syslog(LOG_INFO, "%s is being forwarded to %s\n", original_name, name);
435 /* Change "user @ xxx" to "user" if xxx is an alias for this host */
436 for (a=0; a<strlen(name); ++a) {
437 if (name[a] == '@') {
438 if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
440 MSG_syslog(LOG_INFO, "Changed to <%s>\n", name);
445 /* determine local or remote type, see citadel.h */
446 at = haschar(name, '@');
447 if (at == 0) return(MES_LOCAL); /* no @'s - local address */
448 if (at > 1) return(MES_ERROR); /* >1 @'s - invalid address */
449 remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
451 /* figure out the delivery mode */
452 extract_token(node, name, 1, '@', sizeof node);
454 /* If there are one or more dots in the nodename, we assume that it
455 * is an FQDN and will attempt SMTP delivery to the Internet.
457 if (haschar(node, '.') > 0) {
458 return(MES_INTERNET);
461 /* Otherwise we look in the IGnet maps for a valid Citadel node.
462 * Try directly-connected nodes first...
464 ignetcfg = CtdlGetSysConfig(IGNETCFG);
465 for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
466 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
467 extract_token(testnode, buf, 0, '|', sizeof testnode);
468 if (!strcasecmp(node, testnode)) {
476 * Then try nodes that are two or more hops away.
478 ignetmap = CtdlGetSysConfig(IGNETMAP);
479 for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
480 extract_token(buf, ignetmap, i, '\n', sizeof buf);
481 extract_token(testnode, buf, 0, '|', sizeof testnode);
482 if (!strcasecmp(node, testnode)) {
489 /* If we get to this point it's an invalid node name */
495 * Back end for the MSGS command: output message number only.
497 void simple_listing(long msgnum, void *userdata)
499 cprintf("%ld\n", msgnum);
505 * Back end for the MSGS command: output header summary.
507 void headers_listing(long msgnum, void *userdata)
509 struct CtdlMessage *msg;
511 msg = CtdlFetchMessage(msgnum, 0);
513 cprintf("%ld|0|||||\n", msgnum);
517 cprintf("%ld|%s|%s|%s|%s|%s|\n",
519 (!CM_IsEmpty(msg, eTimestamp) ? msg->cm_fields[eTimestamp] : "0"),
520 (!CM_IsEmpty(msg, eAuthor) ? msg->cm_fields[eAuthor] : ""),
521 (!CM_IsEmpty(msg, eNodeName) ? msg->cm_fields[eNodeName] : ""),
522 (!CM_IsEmpty(msg, erFc822Addr) ? msg->cm_fields[erFc822Addr] : ""),
523 (!CM_IsEmpty(msg, eMsgSubject) ? msg->cm_fields[eMsgSubject] : "")
529 * Back end for the MSGS command: output EUID header.
531 void headers_euid(long msgnum, void *userdata)
533 struct CtdlMessage *msg;
535 msg = CtdlFetchMessage(msgnum, 0);
537 cprintf("%ld||\n", msgnum);
541 cprintf("%ld|%s|%s\n",
543 (!CM_IsEmpty(msg, eExclusiveID) ? msg->cm_fields[eExclusiveID] : ""),
544 (!CM_IsEmpty(msg, eTimestamp) ? msg->cm_fields[eTimestamp] : "0"));
552 /* Determine if a given message matches the fields in a message template.
553 * Return 0 for a successful match.
555 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
558 /* If there aren't any fields in the template, all messages will
561 if (template == NULL) return(0);
563 /* Null messages are bogus. */
564 if (msg == NULL) return(1);
566 for (i='A'; i<='Z'; ++i) {
567 if (template->cm_fields[i] != NULL) {
568 if (msg->cm_fields[i] == NULL) {
569 /* Considered equal if temmplate is empty string */
570 if (IsEmptyStr(template->cm_fields[i])) continue;
573 if (strcasecmp(msg->cm_fields[i],
574 template->cm_fields[i])) return 1;
578 /* All compares succeeded: we have a match! */
585 * Retrieve the "seen" message list for the current room.
587 void CtdlGetSeen(char *buf, int which_set) {
588 struct CitContext *CCC = CC;
591 /* Learn about the user and room in question */
592 CtdlGetRelationship(&vbuf, &CCC->user, &CCC->room);
594 if (which_set == ctdlsetseen_seen)
595 safestrncpy(buf, vbuf.v_seen, SIZ);
596 if (which_set == ctdlsetseen_answered)
597 safestrncpy(buf, vbuf.v_answered, SIZ);
603 * Manipulate the "seen msgs" string (or other message set strings)
605 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
606 int target_setting, int which_set,
607 struct ctdluser *which_user, struct ctdlroom *which_room) {
608 struct CitContext *CCC = CC;
609 struct cdbdata *cdbfr;
614 long hi = (-1L); /// TODO: we just write here. y?
623 char *is_set; /* actually an array of booleans */
625 /* Don't bother doing *anything* if we were passed a list of zero messages */
626 if (num_target_msgnums < 1) {
630 /* If no room was specified, we go with the current room. */
632 which_room = &CCC->room;
635 /* If no user was specified, we go with the current user. */
637 which_user = &CCC->user;
640 MSG_syslog(LOG_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %s, %d) in <%s>\n",
641 num_target_msgnums, target_msgnums[0],
642 (target_setting ? "SET" : "CLEAR"),
646 /* Learn about the user and room in question */
647 CtdlGetRelationship(&vbuf, which_user, which_room);
649 /* Load the message list */
650 cdbfr = cdb_fetch(CDB_MSGLISTS, &which_room->QRnumber, sizeof(long));
652 msglist = (long *) cdbfr->ptr;
653 cdbfr->ptr = NULL; /* CtdlSetSeen() now owns this memory */
654 num_msgs = cdbfr->len / sizeof(long);
657 return; /* No messages at all? No further action. */
660 is_set = malloc(num_msgs * sizeof(char));
661 memset(is_set, 0, (num_msgs * sizeof(char)) );
663 /* Decide which message set we're manipulating */
665 case ctdlsetseen_seen:
666 vset = NewStrBufPlain(vbuf.v_seen, -1);
668 case ctdlsetseen_answered:
669 vset = NewStrBufPlain(vbuf.v_answered, -1);
676 #if 0 /* This is a special diagnostic section. Do not allow it to run during normal operation. */
677 MSG_syslog(LOG_DEBUG, "There are %d messages in the room.\n", num_msgs);
678 for (i=0; i<num_msgs; ++i) {
679 if ((i > 0) && (msglist[i] <= msglist[i-1])) abort();
681 MSG_syslog(LOG_DEBUG, "We are twiddling %d of them.\n", num_target_msgnums);
682 for (k=0; k<num_target_msgnums; ++k) {
683 if ((k > 0) && (target_msgnums[k] <= target_msgnums[k-1])) abort();
687 MSG_syslog(LOG_DEBUG, "before update: %s\n", ChrPtr(vset));
689 /* Translate the existing sequence set into an array of booleans */
690 setstr = NewStrBuf();
694 while (StrBufExtract_NextToken(setstr, vset, &pvset, ',') >= 0) {
696 StrBufExtract_token(lostr, setstr, 0, ':');
697 if (StrBufNum_tokens(setstr, ':') >= 2) {
698 StrBufExtract_token(histr, setstr, 1, ':');
702 StrBufAppendBuf(histr, lostr, 0);
705 if (!strcmp(ChrPtr(histr), "*")) {
712 for (i = 0; i < num_msgs; ++i) {
713 if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
723 /* Now translate the array of booleans back into a sequence set */
729 for (i=0; i<num_msgs; ++i) {
733 for (k=0; k<num_target_msgnums; ++k) {
734 if (msglist[i] == target_msgnums[k]) {
735 is_seen = target_setting;
739 if ((was_seen == 0) && (is_seen == 1)) {
742 else if ((was_seen == 1) && (is_seen == 0)) {
745 if (StrLength(vset) > 0) {
746 StrBufAppendBufPlain(vset, HKEY(","), 0);
749 StrBufAppendPrintf(vset, "%ld", hi);
752 StrBufAppendPrintf(vset, "%ld:%ld", lo, hi);
756 if ((is_seen) && (i == num_msgs - 1)) {
757 if (StrLength(vset) > 0) {
758 StrBufAppendBufPlain(vset, HKEY(","), 0);
760 if ((i==0) || (was_seen == 0)) {
761 StrBufAppendPrintf(vset, "%ld", msglist[i]);
764 StrBufAppendPrintf(vset, "%ld:%ld", lo, msglist[i]);
772 * We will have to stuff this string back into a 4096 byte buffer, so if it's
773 * larger than that now, truncate it by removing tokens from the beginning.
774 * The limit of 100 iterations is there to prevent an infinite loop in case
775 * something unexpected happens.
777 int number_of_truncations = 0;
778 while ( (StrLength(vset) > SIZ) && (number_of_truncations < 100) ) {
779 StrBufRemove_token(vset, 0, ',');
780 ++number_of_truncations;
784 * If we're truncating the sequence set of messages marked with the 'seen' flag,
785 * we want the earliest messages (the truncated ones) to be marked, not unmarked.
786 * Otherwise messages at the beginning will suddenly appear to be 'unseen'.
788 if ( (which_set == ctdlsetseen_seen) && (number_of_truncations > 0) ) {
790 first_tok = NewStrBuf();
791 StrBufExtract_token(first_tok, vset, 0, ',');
792 StrBufRemove_token(vset, 0, ',');
794 if (StrBufNum_tokens(first_tok, ':') > 1) {
795 StrBufRemove_token(first_tok, 0, ':');
799 new_set = NewStrBuf();
800 StrBufAppendBufPlain(new_set, HKEY("1:"), 0);
801 StrBufAppendBuf(new_set, first_tok, 0);
802 StrBufAppendBufPlain(new_set, HKEY(":"), 0);
803 StrBufAppendBuf(new_set, vset, 0);
806 FreeStrBuf(&first_tok);
810 MSG_syslog(LOG_DEBUG, " after update: %s\n", ChrPtr(vset));
812 /* Decide which message set we're manipulating */
814 case ctdlsetseen_seen:
815 safestrncpy(vbuf.v_seen, ChrPtr(vset), sizeof vbuf.v_seen);
817 case ctdlsetseen_answered:
818 safestrncpy(vbuf.v_answered, ChrPtr(vset), sizeof vbuf.v_answered);
824 CtdlSetRelationship(&vbuf, which_user, which_room);
830 * API function to perform an operation for each qualifying message in the
831 * current room. (Returns the number of messages processed.)
833 int CtdlForEachMessage(int mode, long ref, char *search_string,
835 struct CtdlMessage *compare,
836 ForEachMsgCallback CallBack,
839 struct CitContext *CCC = CC;
842 struct cdbdata *cdbfr;
843 long *msglist = NULL;
845 int num_processed = 0;
848 struct CtdlMessage *msg = NULL;
851 int printed_lastold = 0;
852 int num_search_msgs = 0;
853 long *search_msgs = NULL;
855 int need_to_free_re = 0;
858 if ((content_type) && (!IsEmptyStr(content_type))) {
859 regcomp(&re, content_type, 0);
863 /* Learn about the user and room in question */
864 if (server_shutting_down) {
865 if (need_to_free_re) regfree(&re);
868 CtdlGetUser(&CCC->user, CCC->curr_user);
870 if (server_shutting_down) {
871 if (need_to_free_re) regfree(&re);
874 CtdlGetRelationship(&vbuf, &CCC->user, &CCC->room);
876 if (server_shutting_down) {
877 if (need_to_free_re) regfree(&re);
881 /* Load the message list */
882 cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
884 if (need_to_free_re) regfree(&re);
885 return 0; /* No messages at all? No further action. */
888 msglist = (long *) cdbfr->ptr;
889 num_msgs = cdbfr->len / sizeof(long);
891 cdbfr->ptr = NULL; /* clear this so that cdb_free() doesn't free it */
892 cdb_free(cdbfr); /* we own this memory now */
895 * Now begin the traversal.
897 if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
899 /* If the caller is looking for a specific MIME type, filter
900 * out all messages which are not of the type requested.
902 if ((content_type != NULL) && (!IsEmptyStr(content_type))) {
904 /* This call to GetMetaData() sits inside this loop
905 * so that we only do the extra database read per msg
906 * if we need to. Doing the extra read all the time
907 * really kills the server. If we ever need to use
908 * metadata for another search criterion, we need to
909 * move the read somewhere else -- but still be smart
910 * enough to only do the read if the caller has
911 * specified something that will need it.
913 if (server_shutting_down) {
914 if (need_to_free_re) regfree(&re);
918 GetMetaData(&smi, msglist[a]);
920 /* if (strcasecmp(smi.meta_content_type, content_type)) { old non-regex way */
921 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) != 0) {
927 num_msgs = sort_msglist(msglist, num_msgs);
929 /* If a template was supplied, filter out the messages which
930 * don't match. (This could induce some delays!)
933 if (compare != NULL) {
934 for (a = 0; a < num_msgs; ++a) {
935 if (server_shutting_down) {
936 if (need_to_free_re) regfree(&re);
940 msg = CtdlFetchMessage(msglist[a], 1);
942 if (CtdlMsgCmp(msg, compare)) {
951 /* If a search string was specified, get a message list from
952 * the full text index and remove messages which aren't on both
956 * Since the lists are sorted and strictly ascending, and the
957 * output list is guaranteed to be shorter than or equal to the
958 * input list, we overwrite the bottom of the input list. This
959 * eliminates the need to memmove big chunks of the list over and
962 if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
964 /* Call search module via hook mechanism.
965 * NULL means use any search function available.
966 * otherwise replace with a char * to name of search routine
968 CtdlModuleDoSearch(&num_search_msgs, &search_msgs, search_string, "fulltext");
970 if (num_search_msgs > 0) {
974 orig_num_msgs = num_msgs;
976 for (i=0; i<orig_num_msgs; ++i) {
977 for (j=0; j<num_search_msgs; ++j) {
978 if (msglist[i] == search_msgs[j]) {
979 msglist[num_msgs++] = msglist[i];
985 num_msgs = 0; /* No messages qualify */
987 if (search_msgs != NULL) free(search_msgs);
989 /* Now that we've purged messages which don't contain the search
990 * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
997 * Now iterate through the message list, according to the
998 * criteria supplied by the caller.
1001 for (a = 0; a < num_msgs; ++a) {
1002 if (server_shutting_down) {
1003 if (need_to_free_re) regfree(&re);
1005 return num_processed;
1007 thismsg = msglist[a];
1008 if (mode == MSGS_ALL) {
1012 is_seen = is_msg_in_sequence_set(
1013 vbuf.v_seen, thismsg);
1014 if (is_seen) lastold = thismsg;
1020 || ((mode == MSGS_OLD) && (is_seen))
1021 || ((mode == MSGS_NEW) && (!is_seen))
1022 || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
1023 || ((mode == MSGS_FIRST) && (a < ref))
1024 || ((mode == MSGS_GT) && (thismsg > ref))
1025 || ((mode == MSGS_LT) && (thismsg < ref))
1026 || ((mode == MSGS_EQ) && (thismsg == ref))
1029 if ((mode == MSGS_NEW) && (CCC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
1031 CallBack(lastold, userdata);
1032 printed_lastold = 1;
1035 if (CallBack) CallBack(thismsg, userdata);
1039 if (need_to_free_re) regfree(&re);
1042 * We cache the most recent msglist in order to do security checks later
1044 if (CCC->client_socket > 0) {
1045 if (CCC->cached_msglist != NULL) {
1046 free(CCC->cached_msglist);
1048 CCC->cached_msglist = msglist;
1049 CCC->cached_num_msgs = num_msgs;
1055 return num_processed;
1061 * cmd_msgs() - get list of message #'s in this room
1062 * implements the MSGS server command using CtdlForEachMessage()
1064 void cmd_msgs(char *cmdbuf)
1073 int with_template = 0;
1074 struct CtdlMessage *template = NULL;
1075 char search_string[1024];
1076 ForEachMsgCallback CallBack;
1078 if (CtdlAccessCheck(ac_logged_in_or_guest)) return;
1080 extract_token(which, cmdbuf, 0, '|', sizeof which);
1081 cm_ref = extract_int(cmdbuf, 1);
1082 extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
1083 with_template = extract_int(cmdbuf, 2);
1084 switch (extract_int(cmdbuf, 3))
1087 case MSG_HDRS_BRIEF:
1088 CallBack = simple_listing;
1091 CallBack = headers_listing;
1094 CallBack = headers_euid;
1099 if (!strncasecmp(which, "OLD", 3))
1101 else if (!strncasecmp(which, "NEW", 3))
1103 else if (!strncasecmp(which, "FIRST", 5))
1105 else if (!strncasecmp(which, "LAST", 4))
1107 else if (!strncasecmp(which, "GT", 2))
1109 else if (!strncasecmp(which, "LT", 2))
1111 else if (!strncasecmp(which, "SEARCH", 6))
1116 if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
1117 cprintf("%d Full text index is not enabled on this server.\n",
1118 ERROR + CMD_NOT_SUPPORTED);
1122 if (with_template) {
1124 cprintf("%d Send template then receive message list\n",
1126 template = (struct CtdlMessage *)
1127 malloc(sizeof(struct CtdlMessage));
1128 memset(template, 0, sizeof(struct CtdlMessage));
1129 template->cm_magic = CTDLMESSAGE_MAGIC;
1130 template->cm_anon_type = MES_NORMAL;
1132 while(client_getln(buf, sizeof buf) >= 0 && strcmp(buf,"000")) {
1134 extract_token(tfield, buf, 0, '|', sizeof tfield);
1135 tValueLen = extract_token(tvalue, buf, 1, '|', sizeof tvalue);
1136 for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
1137 if (!strcasecmp(tfield, msgkeys[i])) {
1138 CM_SetField(template, i, tvalue, tValueLen);
1145 cprintf("%d \n", LISTING_FOLLOWS);
1148 CtdlForEachMessage(mode,
1149 ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
1150 ( (mode == MSGS_SEARCH) ? search_string : NULL ),
1155 if (template != NULL) CM_Free(template);
1161 * memfmout() - Citadel text formatter and paginator.
1162 * Although the original purpose of this routine was to format
1163 * text to the reader's screen width, all we're really using it
1164 * for here is to format text out to 80 columns before sending it
1165 * to the client. The client software may reformat it again.
1168 char *mptr, /* where are we going to get our text from? */
1169 const char *nl /* string to terminate lines with */
1171 struct CitContext *CCC = CC;
1173 unsigned char ch = 0;
1180 while (ch=*(mptr++), ch != 0) {
1183 if (client_write(outbuf, len) == -1)
1185 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1189 if (client_write(nl, nllen) == -1)
1191 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1196 else if (ch == '\r') {
1197 /* Ignore carriage returns. Newlines are always LF or CRLF but never CR. */
1199 else if (isspace(ch)) {
1200 if (column > 72) { /* Beyond 72 columns, break on the next space */
1201 if (client_write(outbuf, len) == -1)
1203 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1207 if (client_write(nl, nllen) == -1)
1209 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1222 if (column > 1000) { /* Beyond 1000 columns, break anywhere */
1223 if (client_write(outbuf, len) == -1)
1225 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1229 if (client_write(nl, nllen) == -1)
1231 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1239 if (client_write(outbuf, len) == -1)
1241 MSGM_syslog(LOG_ERR, "memfmout(): aborting due to write failure.\n");
1245 client_write(nl, nllen);
1253 * Callback function for mime parser that simply lists the part
1255 void list_this_part(char *name, char *filename, char *partnum, char *disp,
1256 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1257 char *cbid, void *cbuserdata)
1261 ma = (struct ma_info *)cbuserdata;
1262 if (ma->is_ma == 0) {
1263 cprintf("part=%s|%s|%s|%s|%s|%ld|%s|%s\n",
1276 * Callback function for multipart prefix
1278 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
1279 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1280 char *cbid, void *cbuserdata)
1284 ma = (struct ma_info *)cbuserdata;
1285 if (!strcasecmp(cbtype, "multipart/alternative")) {
1289 if (ma->is_ma == 0) {
1290 cprintf("pref=%s|%s\n", partnum, cbtype);
1295 * Callback function for multipart sufffix
1297 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
1298 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1299 char *cbid, void *cbuserdata)
1303 ma = (struct ma_info *)cbuserdata;
1304 if (ma->is_ma == 0) {
1305 cprintf("suff=%s|%s\n", partnum, cbtype);
1307 if (!strcasecmp(cbtype, "multipart/alternative")) {
1314 * Callback function for mime parser that opens a section for downloading
1316 void mime_download(char *name, char *filename, char *partnum, char *disp,
1317 void *content, char *cbtype, char *cbcharset, size_t length,
1318 char *encoding, char *cbid, void *cbuserdata)
1321 CitContext *CCC = MyContext();
1323 /* Silently go away if there's already a download open. */
1324 if (CCC->download_fp != NULL)
1328 (!IsEmptyStr(partnum) && (!strcasecmp(CCC->download_desired_section, partnum)))
1329 || (!IsEmptyStr(cbid) && (!strcasecmp(CCC->download_desired_section, cbid)))
1331 CCC->download_fp = tmpfile();
1332 if (CCC->download_fp == NULL) {
1333 MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1335 cprintf("%d cannot open temporary file: %s\n",
1336 ERROR + INTERNAL_ERROR, strerror(errno));
1340 rv = fwrite(content, length, 1, CCC->download_fp);
1342 MSG_syslog(LOG_EMERG, "mime_download(): Couldn't write: %s\n",
1344 cprintf("%d unable to write tempfile.\n",
1346 fclose(CCC->download_fp);
1347 CCC->download_fp = NULL;
1350 fflush(CCC->download_fp);
1351 rewind(CCC->download_fp);
1353 OpenCmdResult(filename, cbtype);
1360 * Callback function for mime parser that outputs a section all at once.
1361 * We can specify the desired section by part number *or* content-id.
1363 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
1364 void *content, char *cbtype, char *cbcharset, size_t length,
1365 char *encoding, char *cbid, void *cbuserdata)
1367 int *found_it = (int *)cbuserdata;
1370 (!IsEmptyStr(partnum) && (!strcasecmp(CC->download_desired_section, partnum)))
1371 || (!IsEmptyStr(cbid) && (!strcasecmp(CC->download_desired_section, cbid)))
1374 cprintf("%d %d|-1|%s|%s|%s\n",
1381 client_write(content, length);
1387 * Load a message from disk into memory.
1388 * This is used by CtdlOutputMsg() and other fetch functions.
1390 * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1391 * using the CtdlMessageFree() function.
1393 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1395 struct CitContext *CCC = CC;
1396 struct cdbdata *dmsgtext;
1397 struct CtdlMessage *ret = NULL;
1401 cit_uint8_t field_header;
1403 MSG_syslog(LOG_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1404 dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1405 if (dmsgtext == NULL) {
1406 MSG_syslog(LOG_ERR, "CtdlFetchMessage(%ld, %d) Failed!\n", msgnum, with_body);
1409 mptr = dmsgtext->ptr;
1410 upper_bound = mptr + dmsgtext->len;
1412 /* Parse the three bytes that begin EVERY message on disk.
1413 * The first is always 0xFF, the on-disk magic number.
1414 * The second is the anonymous/public type byte.
1415 * The third is the format type byte (vari, fixed, or MIME).
1419 MSG_syslog(LOG_ERR, "Message %ld appears to be corrupted.\n", msgnum);
1423 ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1424 memset(ret, 0, sizeof(struct CtdlMessage));
1426 ret->cm_magic = CTDLMESSAGE_MAGIC;
1427 ret->cm_anon_type = *mptr++; /* Anon type byte */
1428 ret->cm_format_type = *mptr++; /* Format type byte */
1431 * The rest is zero or more arbitrary fields. Load them in.
1432 * We're done when we encounter either a zero-length field or
1433 * have just processed the 'M' (message text) field.
1437 if (mptr >= upper_bound) {
1440 field_header = *mptr++;
1442 CM_SetField(ret, field_header, mptr, len);
1444 mptr += len + 1; /* advance to next field */
1446 } while ((mptr < upper_bound) && (field_header != 'M'));
1450 /* Always make sure there's something in the msg text field. If
1451 * it's NULL, the message text is most likely stored separately,
1452 * so go ahead and fetch that. Failing that, just set a dummy
1453 * body so other code doesn't barf.
1455 if ( (CM_IsEmpty(ret, eMesageText)) && (with_body) ) {
1456 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1457 if (dmsgtext != NULL) {
1458 CM_SetAsField(ret, eMesageText, &dmsgtext->ptr, dmsgtext->len);
1462 if (CM_IsEmpty(ret, eMesageText)) {
1463 CM_SetField(ret, eMesageText, HKEY("\r\n\r\n (no text)\r\n"));
1466 /* Perform "before read" hooks (aborting if any return nonzero) */
1467 if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1478 * Pre callback function for multipart/alternative
1480 * NOTE: this differs from the standard behavior for a reason. Normally when
1481 * displaying multipart/alternative you want to show the _last_ usable
1482 * format in the message. Here we show the _first_ one, because it's
1483 * usually text/plain. Since this set of functions is designed for text
1484 * output to non-MIME-aware clients, this is the desired behavior.
1487 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1488 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1489 char *cbid, void *cbuserdata)
1491 struct CitContext *CCC = CC;
1494 ma = (struct ma_info *)cbuserdata;
1495 MSG_syslog(LOG_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);
1496 if (!strcasecmp(cbtype, "multipart/alternative")) {
1500 if (!strcasecmp(cbtype, "message/rfc822")) {
1506 * Post callback function for multipart/alternative
1508 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1509 void *content, char *cbtype, char *cbcharset, size_t length,
1510 char *encoding, char *cbid, void *cbuserdata)
1512 struct CitContext *CCC = CC;
1515 ma = (struct ma_info *)cbuserdata;
1516 MSG_syslog(LOG_DEBUG, "fixed_output_post() type=<%s>\n", cbtype);
1517 if (!strcasecmp(cbtype, "multipart/alternative")) {
1521 if (!strcasecmp(cbtype, "message/rfc822")) {
1527 * Inline callback function for mime parser that wants to display text
1529 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1530 void *content, char *cbtype, char *cbcharset, size_t length,
1531 char *encoding, char *cbid, void *cbuserdata)
1533 struct CitContext *CCC = CC;
1539 ma = (struct ma_info *)cbuserdata;
1541 MSG_syslog(LOG_DEBUG,
1542 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1543 partnum, filename, cbtype, (long)length);
1546 * If we're in the middle of a multipart/alternative scope and
1547 * we've already printed another section, skip this one.
1549 if ( (ma->is_ma) && (ma->did_print) ) {
1550 MSG_syslog(LOG_DEBUG, "Skipping part %s (%s)\n", partnum, cbtype);
1555 if ( (!strcasecmp(cbtype, "text/plain"))
1556 || (IsEmptyStr(cbtype)) ) {
1559 client_write(wptr, length);
1560 if (wptr[length-1] != '\n') {
1567 if (!strcasecmp(cbtype, "text/html")) {
1568 ptr = html_to_ascii(content, length, 80, 0);
1570 client_write(ptr, wlen);
1571 if ((wlen > 0) && (ptr[wlen-1] != '\n')) {
1578 if (ma->use_fo_hooks) {
1579 if (PerformFixedOutputHooks(cbtype, content, length)) {
1580 /* above function returns nonzero if it handled the part */
1585 if (strncasecmp(cbtype, "multipart/", 10)) {
1586 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1587 partnum, filename, cbtype, (long)length);
1593 * The client is elegant and sophisticated and wants to be choosy about
1594 * MIME content types, so figure out which multipart/alternative part
1595 * we're going to send.
1597 * We use a system of weights. When we find a part that matches one of the
1598 * MIME types we've declared as preferential, we can store it in ma->chosen_part
1599 * and then set ma->chosen_pref to that MIME type's position in our preference
1600 * list. If we then hit another match, we only replace the first match if
1601 * the preference value is lower.
1603 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1604 void *content, char *cbtype, char *cbcharset, size_t length,
1605 char *encoding, char *cbid, void *cbuserdata)
1607 struct CitContext *CCC = CC;
1612 ma = (struct ma_info *)cbuserdata;
1614 // NOTE: REMOVING THIS CONDITIONAL FIXES BUG 220
1615 // http://bugzilla.citadel.org/show_bug.cgi?id=220
1616 // I don't know if there are any side effects! Please TEST TEST TEST
1617 //if (ma->is_ma > 0) {
1619 for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1620 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1621 if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1622 if (i < ma->chosen_pref) {
1623 MSG_syslog(LOG_DEBUG, "Setting chosen part: <%s>\n", partnum);
1624 safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1625 ma->chosen_pref = i;
1632 * Now that we've chosen our preferred part, output it.
1634 void output_preferred(char *name,
1646 struct CitContext *CCC = CC;
1649 int add_newline = 0;
1652 char *decoded = NULL;
1653 size_t bytes_decoded;
1656 ma = (struct ma_info *)cbuserdata;
1658 /* This is not the MIME part you're looking for... */
1659 if (strcasecmp(partnum, ma->chosen_part)) return;
1661 /* If the content-type of this part is in our preferred formats
1662 * list, we can simply output it verbatim.
1664 for (i=0; i<num_tokens(CCC->preferred_formats, '|'); ++i) {
1665 extract_token(buf, CCC->preferred_formats, i, '|', sizeof buf);
1666 if (!strcasecmp(buf, cbtype)) {
1667 /* Yeah! Go! W00t!! */
1668 if (ma->dont_decode == 0)
1669 rc = mime_decode_now (content,
1675 break; /* Give us the chance, maybe theres another one. */
1677 if (rc == 0) text_content = (char *)content;
1679 text_content = decoded;
1680 length = bytes_decoded;
1683 if (text_content[length-1] != '\n') {
1686 cprintf("Content-type: %s", cbtype);
1687 if (!IsEmptyStr(cbcharset)) {
1688 cprintf("; charset=%s", cbcharset);
1690 cprintf("\nContent-length: %d\n",
1691 (int)(length + add_newline) );
1692 if (!IsEmptyStr(encoding)) {
1693 cprintf("Content-transfer-encoding: %s\n", encoding);
1696 cprintf("Content-transfer-encoding: 7bit\n");
1698 cprintf("X-Citadel-MSG4-Partnum: %s\n", partnum);
1700 if (client_write(text_content, length) == -1)
1702 MSGM_syslog(LOG_ERR, "output_preferred(): aborting due to write failure.\n");
1705 if (add_newline) cprintf("\n");
1706 if (decoded != NULL) free(decoded);
1711 /* No translations required or possible: output as text/plain */
1712 cprintf("Content-type: text/plain\n\n");
1714 if (ma->dont_decode == 0)
1715 rc = mime_decode_now (content,
1721 return; /* Give us the chance, maybe theres another one. */
1723 if (rc == 0) text_content = (char *)content;
1725 text_content = decoded;
1726 length = bytes_decoded;
1729 fixed_output(name, filename, partnum, disp, text_content, cbtype, cbcharset,
1730 length, encoding, cbid, cbuserdata);
1731 if (decoded != NULL) free(decoded);
1736 char desired_section[64];
1743 * Callback function for
1745 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1746 void *content, char *cbtype, char *cbcharset, size_t length,
1747 char *encoding, char *cbid, void *cbuserdata)
1749 struct encapmsg *encap;
1751 encap = (struct encapmsg *)cbuserdata;
1753 /* Only proceed if this is the desired section... */
1754 if (!strcasecmp(encap->desired_section, partnum)) {
1755 encap->msglen = length;
1756 encap->msg = malloc(length + 2);
1757 memcpy(encap->msg, content, length);
1764 * Determine whether the specified message exists in the cached_msglist
1765 * (This is a security check)
1767 int check_cached_msglist(long msgnum) {
1768 struct CitContext *CCC = CC;
1770 /* cases in which we skip the check */
1771 if (!CCC) return om_ok; /* not a session */
1772 if (CCC->client_socket <= 0) return om_ok; /* not a client session */
1773 if (CCC->cached_msglist == NULL) return om_access_denied; /* no msglist fetched */
1774 if (CCC->cached_num_msgs == 0) return om_access_denied; /* nothing to check */
1777 /* Do a binary search within the cached_msglist for the requested msgnum */
1779 int max = (CC->cached_num_msgs - 1);
1781 while (max >= min) {
1782 int middle = min + (max-min) / 2 ;
1783 if (msgnum == CCC->cached_msglist[middle]) {
1786 if (msgnum > CC->cached_msglist[middle]) {
1794 return om_access_denied;
1799 * Determine whether the currently logged in session has permission to read
1800 * messages in the current room.
1802 int CtdlDoIHavePermissionToReadMessagesInThisRoom(void) {
1803 if ( (!(CC->logged_in))
1804 && (!(CC->internal_pgm))
1805 && (!config.c_guest_logins)
1807 return(om_not_logged_in);
1814 * Get a message off disk. (returns om_* values found in msgbase.h)
1817 int CtdlOutputMsg(long msg_num, /* message number (local) to fetch */
1818 int mode, /* how would you like that message? */
1819 int headers_only, /* eschew the message body? */
1820 int do_proto, /* do Citadel protocol responses? */
1821 int crlf, /* Use CRLF newlines instead of LF? */
1822 char *section, /* NULL or a message/rfc822 section */
1823 int flags, /* various flags; see msgbase.h */
1827 struct CitContext *CCC = CC;
1828 struct CtdlMessage *TheMessage = NULL;
1829 int retcode = CIT_OK;
1830 struct encapmsg encap;
1833 MSG_syslog(LOG_DEBUG, "CtdlOutputMsg(msgnum=%ld, mode=%d, section=%s)\n",
1835 (section ? section : "<>")
1838 r = CtdlDoIHavePermissionToReadMessagesInThisRoom();
1841 if (r == om_not_logged_in) {
1842 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1845 cprintf("%d An unknown error has occurred.\n", ERROR);
1852 * Check to make sure the message is actually IN this room
1854 r = check_cached_msglist(msg_num);
1855 if (r == om_access_denied) {
1856 /* Not in the cache? We get ONE shot to check it again. */
1857 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, NULL, NULL);
1858 r = check_cached_msglist(msg_num);
1861 MSG_syslog(LOG_DEBUG, "Security check fail: message %ld is not in %s\n",
1862 msg_num, CCC->room.QRname
1865 if (r == om_access_denied) {
1866 cprintf("%d message %ld was not found in this room\n",
1867 ERROR + HIGHER_ACCESS_REQUIRED,
1876 * Fetch the message from disk. If we're in HEADERS_FAST mode,
1877 * request that we don't even bother loading the body into memory.
1879 if (headers_only == HEADERS_FAST) {
1880 TheMessage = CtdlFetchMessage(msg_num, 0);
1883 TheMessage = CtdlFetchMessage(msg_num, 1);
1886 if (TheMessage == NULL) {
1887 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1888 ERROR + MESSAGE_NOT_FOUND, msg_num);
1889 return(om_no_such_msg);
1892 /* Here is the weird form of this command, to process only an
1893 * encapsulated message/rfc822 section.
1895 if (section) if (!IsEmptyStr(section)) if (strcmp(section, "0")) {
1896 memset(&encap, 0, sizeof encap);
1897 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1898 mime_parser(TheMessage->cm_fields[eMesageText],
1900 *extract_encapsulated_message,
1901 NULL, NULL, (void *)&encap, 0
1904 if ((Author != NULL) && (*Author == NULL))
1906 *Author = TheMessage->cm_fields[eAuthor];
1907 TheMessage->cm_fields[eAuthor] = NULL;
1909 if ((Address != NULL) && (*Address == NULL))
1911 *Address = TheMessage->cm_fields[erFc822Addr];
1912 TheMessage->cm_fields[erFc822Addr] = NULL;
1914 CM_Free(TheMessage);
1918 encap.msg[encap.msglen] = 0;
1919 TheMessage = convert_internet_message(encap.msg);
1920 encap.msg = NULL; /* no free() here, TheMessage owns it now */
1922 /* Now we let it fall through to the bottom of this
1923 * function, because TheMessage now contains the
1924 * encapsulated message instead of the top-level
1925 * message. Isn't that neat?
1930 cprintf("%d msg %ld has no part %s\n",
1931 ERROR + MESSAGE_NOT_FOUND,
1935 retcode = om_no_such_msg;
1940 /* Ok, output the message now */
1941 if (retcode == CIT_OK)
1942 retcode = CtdlOutputPreLoadedMsg(TheMessage, mode, headers_only, do_proto, crlf, flags);
1943 if ((Author != NULL) && (*Author == NULL))
1945 *Author = TheMessage->cm_fields[eAuthor];
1946 TheMessage->cm_fields[eAuthor] = NULL;
1948 if ((Address != NULL) && (*Address == NULL))
1950 *Address = TheMessage->cm_fields[erFc822Addr];
1951 TheMessage->cm_fields[erFc822Addr] = NULL;
1954 CM_Free(TheMessage);
1960 char *qp_encode_email_addrs(char *source)
1962 struct CitContext *CCC = CC;
1963 char *user, *node, *name;
1964 const char headerStr[] = "=?UTF-8?Q?";
1968 int need_to_encode = 0;
1974 long nAddrPtrMax = 50;
1979 if (source == NULL) return source;
1980 if (IsEmptyStr(source)) return source;
1981 if (MessageDebugEnabled != 0) cit_backtrace();
1982 MSG_syslog(LOG_DEBUG, "qp_encode_email_addrs: [%s]\n", source);
1984 AddrPtr = malloc (sizeof (long) * nAddrPtrMax);
1985 AddrUtf8 = malloc (sizeof (long) * nAddrPtrMax);
1986 memset(AddrUtf8, 0, sizeof (long) * nAddrPtrMax);
1989 while (!IsEmptyStr (&source[i])) {
1990 if (nColons >= nAddrPtrMax){
1993 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1994 memcpy (ptr, AddrPtr, sizeof (long) * nAddrPtrMax);
1995 free (AddrPtr), AddrPtr = ptr;
1997 ptr = (long *) malloc(sizeof (long) * nAddrPtrMax * 2);
1998 memset(&ptr[nAddrPtrMax], 0,
1999 sizeof (long) * nAddrPtrMax);
2001 memcpy (ptr, AddrUtf8, sizeof (long) * nAddrPtrMax);
2002 free (AddrUtf8), AddrUtf8 = ptr;
2005 if (((unsigned char) source[i] < 32) ||
2006 ((unsigned char) source[i] > 126)) {
2008 AddrUtf8[nColons] = 1;
2010 if (source[i] == '"')
2011 InQuotes = !InQuotes;
2012 if (!InQuotes && source[i] == ',') {
2013 AddrPtr[nColons] = i;
2018 if (need_to_encode == 0) {
2025 EncodedMaxLen = nColons * (sizeof(headerStr) + 3) + SourceLen * 3;
2026 Encoded = (char*) malloc (EncodedMaxLen);
2028 for (i = 0; i < nColons; i++)
2029 source[AddrPtr[i]++] = '\0';
2030 /* TODO: if libidn, this might get larger*/
2031 user = malloc(SourceLen + 1);
2032 node = malloc(SourceLen + 1);
2033 name = malloc(SourceLen + 1);
2037 for (i = 0; i < nColons && nPtr != NULL; i++) {
2038 nmax = EncodedMaxLen - (nPtr - Encoded);
2040 process_rfc822_addr(&source[AddrPtr[i]],
2044 /* TODO: libIDN here ! */
2045 if (IsEmptyStr(name)) {
2046 n = snprintf(nPtr, nmax,
2047 (i==0)?"%s@%s" : ",%s@%s",
2051 EncodedName = rfc2047encode(name, strlen(name));
2052 n = snprintf(nPtr, nmax,
2053 (i==0)?"%s <%s@%s>" : ",%s <%s@%s>",
2054 EncodedName, user, node);
2059 n = snprintf(nPtr, nmax,
2060 (i==0)?"%s" : ",%s",
2061 &source[AddrPtr[i]]);
2067 ptr = (char*) malloc(EncodedMaxLen * 2);
2068 memcpy(ptr, Encoded, EncodedMaxLen);
2069 nnPtr = ptr + (nPtr - Encoded), nPtr = nnPtr;
2070 free(Encoded), Encoded = ptr;
2072 i--; /* do it once more with properly lengthened buffer */
2075 for (i = 0; i < nColons; i++)
2076 source[--AddrPtr[i]] = ',';
2087 /* If the last item in a list of recipients was truncated to a partial address,
2088 * remove it completely in order to avoid choking libSieve
2090 void sanitize_truncated_recipient(char *str)
2093 if (num_tokens(str, ',') < 2) return;
2095 int len = strlen(str);
2096 if (len < 900) return;
2097 if (len > 998) str[998] = 0;
2099 char *cptr = strrchr(str, ',');
2102 char *lptr = strchr(cptr, '<');
2103 char *rptr = strchr(cptr, '>');
2105 if ( (lptr) && (rptr) && (rptr > lptr) ) return;
2111 void OutputCtdlMsgHeaders(
2112 struct CtdlMessage *TheMessage,
2113 int do_proto) /* do Citadel protocol responses? */
2118 char display_name[256];
2120 /* begin header processing loop for Citadel message format */
2121 safestrncpy(display_name, "<unknown>", sizeof display_name);
2122 if (!CM_IsEmpty(TheMessage, eAuthor)) {
2123 strcpy(buf, TheMessage->cm_fields[eAuthor]);
2124 if (TheMessage->cm_anon_type == MES_ANONONLY) {
2125 safestrncpy(display_name, "****", sizeof display_name);
2127 else if (TheMessage->cm_anon_type == MES_ANONOPT) {
2128 safestrncpy(display_name, "anonymous", sizeof display_name);
2131 safestrncpy(display_name, buf, sizeof display_name);
2133 if ((is_room_aide())
2134 && ((TheMessage->cm_anon_type == MES_ANONONLY)
2135 || (TheMessage->cm_anon_type == MES_ANONOPT))) {
2136 size_t tmp = strlen(display_name);
2137 snprintf(&display_name[tmp],
2138 sizeof display_name - tmp,
2143 /* Don't show Internet address for users on the
2144 * local Citadel network.
2147 if (!CM_IsEmpty(TheMessage, eNodeName) &&
2148 (haschar(TheMessage->cm_fields[eNodeName], '.') == 0))
2153 /* Now spew the header fields in the order we like them. */
2154 for (i=0; i< NDiskFields; ++i) {
2156 Field = FieldOrder[i];
2157 if (Field != eMesageText) {
2158 if ( (!CM_IsEmpty(TheMessage, Field))
2159 && (msgkeys[Field] != NULL) ) {
2160 if ((Field == eenVelopeTo) ||
2161 (Field == eRecipient) ||
2162 (Field == eCarbonCopY)) {
2163 sanitize_truncated_recipient(TheMessage->cm_fields[Field]);
2165 if (Field == eAuthor) {
2166 if (do_proto) cprintf("%s=%s\n",
2170 else if ((Field == erFc822Addr) && (suppress_f)) {
2173 /* Masquerade display name if needed */
2175 if (do_proto) cprintf("%s=%s\n",
2177 TheMessage->cm_fields[Field]
2186 void OutputRFC822MsgHeaders(
2187 struct CtdlMessage *TheMessage,
2188 int flags, /* should the bessage be exported clean */
2190 char *mid, long sizeof_mid,
2191 char *suser, long sizeof_suser,
2192 char *luser, long sizeof_luser,
2193 char *fuser, long sizeof_fuser,
2194 char *snode, long sizeof_snode)
2196 char datestamp[100];
2197 int subject_found = 0;
2204 for (i = 0; i < 256; ++i) {
2205 if (TheMessage->cm_fields[i]) {
2206 mptr = mpptr = TheMessage->cm_fields[i];
2209 safestrncpy(luser, mptr, sizeof_luser);
2210 safestrncpy(suser, mptr, sizeof_suser);
2212 else if (i == 'Y') {
2213 if ((flags & QP_EADDR) != 0) {
2214 mptr = qp_encode_email_addrs(mptr);
2216 sanitize_truncated_recipient(mptr);
2217 cprintf("CC: %s%s", mptr, nl);
2219 else if (i == 'P') {
2220 cprintf("Return-Path: %s%s", mptr, nl);
2222 else if (i == eListID) {
2223 cprintf("List-ID: %s%s", mptr, nl);
2225 else if (i == 'V') {
2226 if ((flags & QP_EADDR) != 0)
2227 mptr = qp_encode_email_addrs(mptr);
2229 while ((*hptr != '\0') && isspace(*hptr))
2231 if (!IsEmptyStr(hptr))
2232 cprintf("Envelope-To: %s%s", hptr, nl);
2234 else if (i == 'U') {
2235 cprintf("Subject: %s%s", mptr, nl);
2239 safestrncpy(mid, mptr, sizeof_mid); /// TODO: detect @ here and copy @nodename in if not found.
2240 else if (i == erFc822Addr)
2241 safestrncpy(fuser, mptr, sizeof_fuser);
2242 /* else if (i == 'O')
2243 cprintf("X-Citadel-Room: %s%s",
2246 safestrncpy(snode, mptr, sizeof_snode);
2249 if (haschar(mptr, '@') == 0)
2251 sanitize_truncated_recipient(mptr);
2252 cprintf("To: %s@%s", mptr, config.c_fqdn);
2257 if ((flags & QP_EADDR) != 0) {
2258 mptr = qp_encode_email_addrs(mptr);
2260 sanitize_truncated_recipient(mptr);
2261 cprintf("To: %s", mptr);
2265 else if (i == 'T') {
2266 datestring(datestamp, sizeof datestamp,
2267 atol(mptr), DATESTRING_RFC822);
2268 cprintf("Date: %s%s", datestamp, nl);
2270 else if (i == 'W') {
2271 cprintf("References: ");
2272 k = num_tokens(mptr, '|');
2273 for (j=0; j<k; ++j) {
2274 extract_token(buf, mptr, j, '|', sizeof buf);
2275 cprintf("<%s>", buf);
2284 else if (i == eReplyTo) {
2286 while ((*hptr != '\0') && isspace(*hptr))
2288 if (!IsEmptyStr(hptr))
2289 cprintf("Reply-To: %s%s", mptr, nl);
2295 if (subject_found == 0) {
2296 cprintf("Subject: (no subject)%s", nl);
2301 void Dump_RFC822HeadersBody(
2302 struct CtdlMessage *TheMessage,
2303 int headers_only, /* eschew the message body? */
2304 int flags, /* should the bessage be exported clean? */
2308 cit_uint8_t prev_ch;
2310 const char *StartOfText = StrBufNOTNULL;
2313 int nllen = strlen(nl);
2316 mptr = TheMessage->cm_fields[eMesageText];
2320 while (*mptr != '\0') {
2321 if (*mptr == '\r') {
2328 eoh = (*(mptr+1) == '\r') && (*(mptr+2) == '\n');
2330 eoh = *(mptr+1) == '\n';
2334 StartOfText = strchr(StartOfText, '\n');
2335 StartOfText = strchr(StartOfText, '\n');
2338 if (((headers_only == HEADERS_NONE) && (mptr >= StartOfText)) ||
2339 ((headers_only == HEADERS_ONLY) && (mptr < StartOfText)) ||
2340 ((headers_only != HEADERS_NONE) &&
2341 (headers_only != HEADERS_ONLY))
2343 if (*mptr == '\n') {
2344 memcpy(&outbuf[outlen], nl, nllen);
2346 outbuf[outlen] = '\0';
2349 outbuf[outlen++] = *mptr;
2353 if (flags & ESC_DOT)
2355 if ((prev_ch == '\n') &&
2357 ((*(mptr+1) == '\r') || (*(mptr+1) == '\n')))
2359 outbuf[outlen++] = '.';
2364 if (outlen > 1000) {
2365 if (client_write(outbuf, outlen) == -1)
2367 struct CitContext *CCC = CC;
2368 MSGM_syslog(LOG_ERR, "Dump_RFC822HeadersBody(): aborting due to write failure.\n");
2375 client_write(outbuf, outlen);
2381 /* If the format type on disk is 1 (fixed-format), then we want
2382 * everything to be output completely literally ... regardless of
2383 * what message transfer format is in use.
2385 void DumpFormatFixed(
2386 struct CtdlMessage *TheMessage,
2387 int mode, /* how would you like that message? */
2394 int nllen = strlen (nl);
2397 mptr = TheMessage->cm_fields[eMesageText];
2399 if (mode == MT_MIME) {
2400 cprintf("Content-type: text/plain\n\n");
2404 while (ch = *mptr++, ch > 0) {
2408 if ((buflen > 250) && (!xlline)){
2412 while ((buflen > 0) &&
2413 (!isspace(buf[buflen])))
2419 mptr -= tbuflen - buflen;
2424 /* if we reach the outer bounds of our buffer,
2425 abort without respect what whe purge. */
2428 (buflen > SIZ - nllen - 2)))
2432 memcpy (&buf[buflen], nl, nllen);
2436 if (client_write(buf, buflen) == -1)
2438 struct CitContext *CCC = CC;
2439 MSGM_syslog(LOG_ERR, "DumpFormatFixed(): aborting due to write failure.\n");
2451 if (!IsEmptyStr(buf))
2452 cprintf("%s%s", buf, nl);
2456 * Get a message off disk. (returns om_* values found in msgbase.h)
2458 int CtdlOutputPreLoadedMsg(
2459 struct CtdlMessage *TheMessage,
2460 int mode, /* how would you like that message? */
2461 int headers_only, /* eschew the message body? */
2462 int do_proto, /* do Citadel protocol responses? */
2463 int crlf, /* Use CRLF newlines instead of LF? */
2464 int flags /* should the bessage be exported clean? */
2466 struct CitContext *CCC = CC;
2469 const char *nl; /* newline string */
2472 /* Buffers needed for RFC822 translation. These are all filled
2473 * using functions that are bounds-checked, and therefore we can
2474 * make them substantially smaller than SIZ.
2482 MSG_syslog(LOG_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
2483 ((TheMessage == NULL) ? "NULL" : "not null"),
2484 mode, headers_only, do_proto, crlf);
2486 strcpy(mid, "unknown");
2487 nl = (crlf ? "\r\n" : "\n");
2489 if (!CM_IsValidMsg(TheMessage)) {
2490 MSGM_syslog(LOG_ERR,
2491 "ERROR: invalid preloaded message for output\n");
2493 return(om_no_such_msg);
2496 /* Suppress envelope recipients if required to avoid disclosing BCC addresses.
2497 * Pad it with spaces in order to avoid changing the RFC822 length of the message.
2499 if ( (flags & SUPPRESS_ENV_TO) && (!CM_IsEmpty(TheMessage, eenVelopeTo)) ) {
2500 memset(TheMessage->cm_fields[eenVelopeTo], ' ', strlen(TheMessage->cm_fields[eenVelopeTo]));
2503 /* Are we downloading a MIME component? */
2504 if (mode == MT_DOWNLOAD) {
2505 if (TheMessage->cm_format_type != FMT_RFC822) {
2507 cprintf("%d This is not a MIME message.\n",
2508 ERROR + ILLEGAL_VALUE);
2509 } else if (CCC->download_fp != NULL) {
2510 if (do_proto) cprintf(
2511 "%d You already have a download open.\n",
2512 ERROR + RESOURCE_BUSY);
2514 /* Parse the message text component */
2515 mptr = TheMessage->cm_fields[eMesageText];
2516 mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
2517 /* If there's no file open by this time, the requested
2518 * section wasn't found, so print an error
2520 if (CCC->download_fp == NULL) {
2521 if (do_proto) cprintf(
2522 "%d Section %s not found.\n",
2523 ERROR + FILE_NOT_FOUND,
2524 CCC->download_desired_section);
2527 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2530 /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
2531 * in a single server operation instead of opening a download file.
2533 if (mode == MT_SPEW_SECTION) {
2534 if (TheMessage->cm_format_type != FMT_RFC822) {
2536 cprintf("%d This is not a MIME message.\n",
2537 ERROR + ILLEGAL_VALUE);
2539 /* Parse the message text component */
2542 mptr = TheMessage->cm_fields[eMesageText];
2543 mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
2544 /* If section wasn't found, print an error
2547 if (do_proto) cprintf(
2548 "%d Section %s not found.\n",
2549 ERROR + FILE_NOT_FOUND,
2550 CCC->download_desired_section);
2553 return((CCC->download_fp != NULL) ? om_ok : om_mime_error);
2556 /* now for the user-mode message reading loops */
2557 if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
2559 /* Does the caller want to skip the headers? */
2560 if (headers_only == HEADERS_NONE) goto START_TEXT;
2562 /* Tell the client which format type we're using. */
2563 if ( (mode == MT_CITADEL) && (do_proto) ) {
2564 cprintf("type=%d\n", TheMessage->cm_format_type);
2567 /* nhdr=yes means that we're only displaying headers, no body */
2568 if ( (TheMessage->cm_anon_type == MES_ANONONLY)
2569 && ((mode == MT_CITADEL) || (mode == MT_MIME))
2572 cprintf("nhdr=yes\n");
2575 if ((mode == MT_CITADEL) || (mode == MT_MIME))
2576 OutputCtdlMsgHeaders(TheMessage, do_proto);
2579 /* begin header processing loop for RFC822 transfer format */
2583 strcpy(snode, NODENAME);
2584 if (mode == MT_RFC822)
2585 OutputRFC822MsgHeaders(
2590 suser, sizeof(suser),
2591 luser, sizeof(luser),
2592 fuser, sizeof(fuser),
2593 snode, sizeof(snode)
2597 for (i=0; !IsEmptyStr(&suser[i]); ++i) {
2598 suser[i] = tolower(suser[i]);
2599 if (!isalnum(suser[i])) suser[i]='_';
2602 if (mode == MT_RFC822) {
2603 if (!strcasecmp(snode, NODENAME)) {
2604 safestrncpy(snode, FQDN, sizeof snode);
2607 /* Construct a fun message id */
2608 cprintf("Message-ID: <%s", mid);/// todo: this possibly breaks threadding mails.
2609 if (strchr(mid, '@')==NULL) {
2610 cprintf("@%s", snode);
2614 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
2615 cprintf("From: \"----\" <x@x.org>%s", nl);
2617 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
2618 cprintf("From: \"anonymous\" <x@x.org>%s", nl);
2620 else if (!IsEmptyStr(fuser)) {
2621 cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
2624 cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
2627 /* Blank line signifying RFC822 end-of-headers */
2628 if (TheMessage->cm_format_type != FMT_RFC822) {
2633 /* end header processing loop ... at this point, we're in the text */
2635 if (headers_only == HEADERS_FAST) goto DONE;
2637 /* Tell the client about the MIME parts in this message */
2638 if (TheMessage->cm_format_type == FMT_RFC822) {
2639 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2640 mptr = TheMessage->cm_fields[eMesageText];
2641 memset(&ma, 0, sizeof(struct ma_info));
2642 mime_parser(mptr, NULL,
2643 (do_proto ? *list_this_part : NULL),
2644 (do_proto ? *list_this_pref : NULL),
2645 (do_proto ? *list_this_suff : NULL),
2648 else if (mode == MT_RFC822) { /* unparsed RFC822 dump */
2649 Dump_RFC822HeadersBody(
2658 if (headers_only == HEADERS_ONLY) {
2662 /* signify start of msg text */
2663 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
2664 if (do_proto) cprintf("text\n");
2667 if (TheMessage->cm_format_type == FMT_FIXED)
2670 mode, /* how would you like that message? */
2673 /* If the message on disk is format 0 (Citadel vari-format), we
2674 * output using the formatter at 80 columns. This is the final output
2675 * form if the transfer format is RFC822, but if the transfer format
2676 * is Citadel proprietary, it'll still work, because the indentation
2677 * for new paragraphs is correct and the client will reformat the
2678 * message to the reader's screen width.
2680 if (TheMessage->cm_format_type == FMT_CITADEL) {
2681 mptr = TheMessage->cm_fields[eMesageText];
2683 if (mode == MT_MIME) {
2684 cprintf("Content-type: text/x-citadel-variformat\n\n");
2689 /* If the message on disk is format 4 (MIME), we've gotta hand it
2690 * off to the MIME parser. The client has already been told that
2691 * this message is format 1 (fixed format), so the callback function
2692 * we use will display those parts as-is.
2694 if (TheMessage->cm_format_type == FMT_RFC822) {
2695 memset(&ma, 0, sizeof(struct ma_info));
2697 if (mode == MT_MIME) {
2698 ma.use_fo_hooks = 0;
2699 strcpy(ma.chosen_part, "1");
2700 ma.chosen_pref = 9999;
2701 ma.dont_decode = CCC->msg4_dont_decode;
2702 mime_parser(mptr, NULL,
2703 *choose_preferred, *fixed_output_pre,
2704 *fixed_output_post, (void *)&ma, 1);
2705 mime_parser(mptr, NULL,
2706 *output_preferred, NULL, NULL, (void *)&ma, 1);
2709 ma.use_fo_hooks = 1;
2710 mime_parser(mptr, NULL,
2711 *fixed_output, *fixed_output_pre,
2712 *fixed_output_post, (void *)&ma, 0);
2717 DONE: /* now we're done */
2718 if (do_proto) cprintf("000\n");
2724 * display a message (mode 0 - Citadel proprietary)
2726 void cmd_msg0(char *cmdbuf)
2729 int headers_only = HEADERS_ALL;
2731 msgid = extract_long(cmdbuf, 0);
2732 headers_only = extract_int(cmdbuf, 1);
2734 CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL, 0, NULL, NULL);
2740 * display a message (mode 2 - RFC822)
2742 void cmd_msg2(char *cmdbuf)
2745 int headers_only = HEADERS_ALL;
2747 msgid = extract_long(cmdbuf, 0);
2748 headers_only = extract_int(cmdbuf, 1);
2750 CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL, 0, NULL, NULL);
2756 * display a message (mode 3 - IGnet raw format - internal programs only)
2758 void cmd_msg3(char *cmdbuf)
2761 struct CtdlMessage *msg = NULL;
2764 if (CC->internal_pgm == 0) {
2765 cprintf("%d This command is for internal programs only.\n",
2766 ERROR + HIGHER_ACCESS_REQUIRED);
2770 msgnum = extract_long(cmdbuf, 0);
2771 msg = CtdlFetchMessage(msgnum, 1);
2773 cprintf("%d Message %ld not found.\n",
2774 ERROR + MESSAGE_NOT_FOUND, msgnum);
2778 serialize_message(&smr, msg);
2782 cprintf("%d Unable to serialize message\n",
2783 ERROR + INTERNAL_ERROR);
2787 cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
2788 client_write((char *)smr.ser, (int)smr.len);
2795 * Display a message using MIME content types
2797 void cmd_msg4(char *cmdbuf)
2802 msgid = extract_long(cmdbuf, 0);
2803 extract_token(section, cmdbuf, 1, '|', sizeof section);
2804 CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) , 0, NULL, NULL);
2810 * Client tells us its preferred message format(s)
2812 void cmd_msgp(char *cmdbuf)
2814 if (!strcasecmp(cmdbuf, "dont_decode")) {
2815 CC->msg4_dont_decode = 1;
2816 cprintf("%d MSG4 will not pre-decode messages.\n", CIT_OK);
2819 safestrncpy(CC->preferred_formats, cmdbuf, sizeof(CC->preferred_formats));
2820 cprintf("%d Preferred MIME formats have been set.\n", CIT_OK);
2826 * Open a component of a MIME message as a download file
2828 void cmd_opna(char *cmdbuf)
2831 char desired_section[128];
2833 msgid = extract_long(cmdbuf, 0);
2834 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2835 safestrncpy(CC->download_desired_section, desired_section,
2836 sizeof CC->download_desired_section);
2837 CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL, 0, NULL, NULL);
2842 * Open a component of a MIME message and transmit it all at once
2844 void cmd_dlat(char *cmdbuf)
2847 char desired_section[128];
2849 msgid = extract_long(cmdbuf, 0);
2850 extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
2851 safestrncpy(CC->download_desired_section, desired_section,
2852 sizeof CC->download_desired_section);
2853 CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL, 0, NULL, NULL);
2858 * Save one or more message pointers into a specified room
2859 * (Returns 0 for success, nonzero for failure)
2860 * roomname may be NULL to use the current room
2862 * Note that the 'supplied_msg' field may be set to NULL, in which case
2863 * the message will be fetched from disk, by number, if we need to perform
2864 * replication checks. This adds an additional database read, so if the
2865 * caller already has the message in memory then it should be supplied. (Obviously
2866 * this mode of operation only works if we're saving a single message.)
2868 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
2869 int do_repl_check, struct CtdlMessage *supplied_msg, int suppress_refcount_adj
2871 struct CitContext *CCC = CC;
2873 char hold_rm[ROOMNAMELEN];
2874 struct cdbdata *cdbfr;
2877 long highest_msg = 0L;
2880 struct CtdlMessage *msg = NULL;
2882 long *msgs_to_be_merged = NULL;
2883 int num_msgs_to_be_merged = 0;
2885 MSG_syslog(LOG_DEBUG,
2886 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d, suppress_rca=%d)\n",
2887 roomname, num_newmsgs, do_repl_check, suppress_refcount_adj
2890 strcpy(hold_rm, CCC->room.QRname);
2893 if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2894 if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2895 if (num_newmsgs > 1) supplied_msg = NULL;
2897 /* Now the regular stuff */
2898 if (CtdlGetRoomLock(&CCC->room,
2899 ((roomname != NULL) ? roomname : CCC->room.QRname) )
2901 MSG_syslog(LOG_ERR, "No such room <%s>\n", roomname);
2902 return(ERROR + ROOM_NOT_FOUND);
2906 msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2907 num_msgs_to_be_merged = 0;
2910 cdbfr = cdb_fetch(CDB_MSGLISTS, &CCC->room.QRnumber, sizeof(long));
2911 if (cdbfr == NULL) {
2915 msglist = (long *) cdbfr->ptr;
2916 cdbfr->ptr = NULL; /* CtdlSaveMsgPointerInRoom() now owns this memory */
2917 num_msgs = cdbfr->len / sizeof(long);
2922 /* Create a list of msgid's which were supplied by the caller, but do
2923 * not already exist in the target room. It is absolutely taboo to
2924 * have more than one reference to the same message in a room.
2926 for (i=0; i<num_newmsgs; ++i) {
2928 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2929 if (msglist[j] == newmsgidlist[i]) {
2934 msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2938 MSG_syslog(LOG_DEBUG, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2941 * Now merge the new messages
2943 msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2944 if (msglist == NULL) {
2945 MSGM_syslog(LOG_ALERT, "ERROR: can't realloc message list!\n");
2946 free(msgs_to_be_merged);
2947 return (ERROR + INTERNAL_ERROR);
2949 memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2950 num_msgs += num_msgs_to_be_merged;
2952 /* Sort the message list, so all the msgid's are in order */
2953 num_msgs = sort_msglist(msglist, num_msgs);
2955 /* Determine the highest message number */
2956 highest_msg = msglist[num_msgs - 1];
2958 /* Write it back to disk. */
2959 cdb_store(CDB_MSGLISTS, &CCC->room.QRnumber, (int)sizeof(long),
2960 msglist, (int)(num_msgs * sizeof(long)));
2962 /* Free up the memory we used. */
2965 /* Update the highest-message pointer and unlock the room. */
2966 CCC->room.QRhighest = highest_msg;
2967 CtdlPutRoomLock(&CCC->room);
2969 /* Perform replication checks if necessary */
2970 if ( (DoesThisRoomNeedEuidIndexing(&CCC->room)) && (do_repl_check) ) {
2971 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2973 for (i=0; i<num_msgs_to_be_merged; ++i) {
2974 msgid = msgs_to_be_merged[i];
2976 if (supplied_msg != NULL) {
2980 msg = CtdlFetchMessage(msgid, 0);
2984 ReplicationChecks(msg);
2986 /* If the message has an Exclusive ID, index that... */
2987 if (!CM_IsEmpty(msg, eExclusiveID)) {
2988 index_message_by_euid(msg->cm_fields[eExclusiveID], &CCC->room, msgid);
2991 /* Free up the memory we may have allocated */
2992 if (msg != supplied_msg) {
3001 MSGM_syslog(LOG_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
3004 /* Submit this room for processing by hooks */
3005 PerformRoomHooks(&CCC->room);
3007 /* Go back to the room we were in before we wandered here... */
3008 CtdlGetRoom(&CCC->room, hold_rm);
3010 /* Bump the reference count for all messages which were merged */
3011 if (!suppress_refcount_adj) {
3012 AdjRefCountList(msgs_to_be_merged, num_msgs_to_be_merged, +1);
3015 /* Free up memory... */
3016 if (msgs_to_be_merged != NULL) {
3017 free(msgs_to_be_merged);
3020 /* Return success. */
3026 * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
3029 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
3030 int do_repl_check, struct CtdlMessage *supplied_msg)
3032 return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg, 0);
3039 * Message base operation to save a new message to the message store
3040 * (returns new message number)
3042 * This is the back end for CtdlSubmitMsg() and should not be directly
3043 * called by server-side modules.
3046 long send_message(struct CtdlMessage *msg) {
3047 struct CitContext *CCC = CC;
3056 /* Get a new message number */
3057 newmsgid = get_new_message_number();
3058 msgidbuflen = snprintf(msgidbuf, sizeof msgidbuf, "%08lX-%08lX@%s",
3059 (long unsigned int) time(NULL),
3060 (long unsigned int) newmsgid,
3064 /* Generate an ID if we don't have one already */
3065 if (CM_IsEmpty(msg, emessageId)) {
3066 CM_SetField(msg, emessageId, msgidbuf, msgidbuflen);
3069 /* If the message is big, set its body aside for storage elsewhere */
3070 if (!CM_IsEmpty(msg, eMesageText)) {
3071 if (strlen(msg->cm_fields[eMesageText]) > BIGMSG) {
3073 holdM = msg->cm_fields[eMesageText];
3074 msg->cm_fields[eMesageText] = NULL;
3078 /* Serialize our data structure for storage in the database */
3079 serialize_message(&smr, msg);
3082 msg->cm_fields[eMesageText] = holdM;
3086 cprintf("%d Unable to serialize message\n",
3087 ERROR + INTERNAL_ERROR);
3091 /* Write our little bundle of joy into the message base */
3092 if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
3093 smr.ser, smr.len) < 0) {
3094 MSGM_syslog(LOG_ERR, "Can't store message\n");
3098 cdb_store(CDB_BIGMSGS,
3108 /* Free the memory we used for the serialized message */
3111 /* Return the *local* message ID to the caller
3112 * (even if we're storing an incoming network message)
3120 * Serialize a struct CtdlMessage into the format used on disk and network.
3122 * This function loads up a "struct ser_ret" (defined in server.h) which
3123 * contains the length of the serialized message and a pointer to the
3124 * serialized message in memory. THE LATTER MUST BE FREED BY THE CALLER.
3126 void serialize_message(struct ser_ret *ret, /* return values */
3127 struct CtdlMessage *msg) /* unserialized msg */
3129 struct CitContext *CCC = CC;
3130 size_t wlen, fieldlen;
3132 long lengths[NDiskFields];
3134 memset(lengths, 0, sizeof(lengths));
3137 * Check for valid message format
3139 if (CM_IsValidMsg(msg) == 0) {
3140 MSGM_syslog(LOG_ERR, "serialize_message() aborting due to invalid message\n");
3147 for (i=0; i < NDiskFields; ++i)
3148 if (msg->cm_fields[FieldOrder[i]] != NULL)
3150 lengths[i] = strlen(msg->cm_fields[FieldOrder[i]]);
3151 ret->len += lengths[i] + 2;
3154 ret->ser = malloc(ret->len);
3155 if (ret->ser == NULL) {
3156 MSG_syslog(LOG_ERR, "serialize_message() malloc(%ld) failed: %s\n",
3157 (long)ret->len, strerror(errno));
3164 ret->ser[1] = msg->cm_anon_type;
3165 ret->ser[2] = msg->cm_format_type;
3168 for (i=0; i < NDiskFields; ++i)
3169 if (msg->cm_fields[FieldOrder[i]] != NULL)
3171 fieldlen = lengths[i];
3172 ret->ser[wlen++] = (char)FieldOrder[i];
3174 memcpy(&ret->ser[wlen],
3175 msg->cm_fields[FieldOrder[i]],
3178 wlen = wlen + fieldlen + 1;
3181 if (ret->len != wlen) {
3182 MSG_syslog(LOG_ERR, "ERROR: len=%ld wlen=%ld\n",
3183 (long)ret->len, (long)wlen);
3191 * Check to see if any messages already exist in the current room which
3192 * carry the same Exclusive ID as this one. If any are found, delete them.
3194 void ReplicationChecks(struct CtdlMessage *msg) {
3195 struct CitContext *CCC = CC;
3196 long old_msgnum = (-1L);
3198 if (DoesThisRoomNeedEuidIndexing(&CCC->room) == 0) return;
3200 MSG_syslog(LOG_DEBUG, "Performing replication checks in <%s>\n",
3203 /* No exclusive id? Don't do anything. */
3204 if (msg == NULL) return;
3205 if (CM_IsEmpty(msg, eExclusiveID)) return;
3207 /*MSG_syslog(LOG_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
3208 msg->cm_fields[eExclusiveID], CCC->room.QRname);*/
3210 old_msgnum = CtdlLocateMessageByEuid(msg->cm_fields[eExclusiveID], &CCC->room);
3211 if (old_msgnum > 0L) {
3212 MSG_syslog(LOG_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
3213 CtdlDeleteMessages(CCC->room.QRname, &old_msgnum, 1, "");
3220 * Save a message to disk and submit it into the delivery system.
3222 long CtdlSubmitMsg(struct CtdlMessage *msg, /* message to save */
3223 struct recptypes *recps, /* recipients (if mail) */
3224 const char *force, /* force a particular room? */
3225 int flags /* should the message be exported clean? */
3228 char submit_filename[128];
3229 char hold_rm[ROOMNAMELEN];
3230 char actual_rm[ROOMNAMELEN];
3231 char force_room[ROOMNAMELEN];
3232 char content_type[SIZ]; /* We have to learn this */
3233 char recipient[SIZ];
3236 const char *mptr = NULL;
3237 struct ctdluser userbuf;
3239 struct MetaData smi;
3240 FILE *network_fp = NULL;
3241 static int seqnum = 1;
3242 struct CtdlMessage *imsg = NULL;
3244 size_t instr_alloc = 0;
3246 char *hold_R, *hold_D;
3247 char *collected_addresses = NULL;
3248 struct addresses_to_be_filed *aptr = NULL;
3249 StrBuf *saved_rfc822_version = NULL;
3250 int qualified_for_journaling = 0;
3251 CitContext *CCC = MyContext();
3252 char bounce_to[1024] = "";
3255 MSGM_syslog(LOG_DEBUG, "CtdlSubmitMsg() called\n");
3256 if (CM_IsValidMsg(msg) == 0) return(-1); /* self check */
3258 /* If this message has no timestamp, we take the liberty of
3259 * giving it one, right now.
3261 if (CM_IsEmpty(msg, eTimestamp)) {
3262 CM_SetFieldLONG(msg, eTimestamp, time(NULL));
3265 /* If this message has no path, we generate one.
3267 if (CM_IsEmpty(msg, eMessagePath)) {
3268 if (!CM_IsEmpty(msg, eAuthor)) {
3269 CM_CopyField(msg, eMessagePath, eAuthor);
3270 for (a=0; !IsEmptyStr(&msg->cm_fields[eMessagePath][a]); ++a) {
3271 if (isspace(msg->cm_fields[eMessagePath][a])) {
3272 msg->cm_fields[eMessagePath][a] = ' ';
3277 CM_SetField(msg, eMessagePath, HKEY("unknown"));
3281 if (force == NULL) {
3282 force_room[0] = '\0';
3285 strcpy(force_room, force);
3288 /* Learn about what's inside, because it's what's inside that counts */
3289 if (CM_IsEmpty(msg, eMesageText)) {
3290 MSGM_syslog(LOG_ERR, "ERROR: attempt to save message with NULL body\n");
3294 switch (msg->cm_format_type) {
3296 strcpy(content_type, "text/x-citadel-variformat");
3299 strcpy(content_type, "text/plain");
3302 strcpy(content_type, "text/plain");
3303 mptr = bmstrcasestr(msg->cm_fields[eMesageText], "Content-type:");
3306 safestrncpy(content_type, &mptr[13], sizeof content_type);
3307 striplt(content_type);
3308 aptr = content_type;
3309 while (!IsEmptyStr(aptr)) {
3321 /* Goto the correct room */
3322 room = (recps) ? CCC->room.QRname : SENTITEMS;
3323 MSG_syslog(LOG_DEBUG, "Selected room %s\n", room);
3324 strcpy(hold_rm, CCC->room.QRname);
3325 strcpy(actual_rm, CCC->room.QRname);
3326 if (recps != NULL) {
3327 strcpy(actual_rm, SENTITEMS);
3330 /* If the user is a twit, move to the twit room for posting */
3332 if (CCC->user.axlevel == AxProbU) {
3333 strcpy(hold_rm, actual_rm);
3334 strcpy(actual_rm, config.c_twitroom);
3335 MSGM_syslog(LOG_DEBUG, "Diverting to twit room\n");
3339 /* ...or if this message is destined for Aide> then go there. */
3340 if (!IsEmptyStr(force_room)) {
3341 strcpy(actual_rm, force_room);
3344 MSG_syslog(LOG_INFO, "Final selection: %s (%s)\n", actual_rm, room);
3345 if (strcasecmp(actual_rm, CCC->room.QRname)) {
3346 /* CtdlGetRoom(&CCC->room, actual_rm); */
3347 CtdlUserGoto(actual_rm, 0, 1, NULL, NULL);
3351 * If this message has no O (room) field, generate one.
3353 if (CM_IsEmpty(msg, eOriginalRoom)) {
3354 CM_SetField(msg, eOriginalRoom, CCC->room.QRname, strlen(CCC->room.QRname));
3357 /* Perform "before save" hooks (aborting if any return nonzero) */
3358 MSGM_syslog(LOG_DEBUG, "Performing before-save hooks\n");
3359 if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
3362 * If this message has an Exclusive ID, and the room is replication
3363 * checking enabled, then do replication checks.
3365 if (DoesThisRoomNeedEuidIndexing(&CCC->room)) {
3366 ReplicationChecks(msg);
3369 /* Save it to disk */
3370 MSGM_syslog(LOG_DEBUG, "Saving to disk\n");
3371 newmsgid = send_message(msg);
3372 if (newmsgid <= 0L) return(-5);
3374 /* Write a supplemental message info record. This doesn't have to
3375 * be a critical section because nobody else knows about this message
3378 MSGM_syslog(LOG_DEBUG, "Creating MetaData record\n");
3379 memset(&smi, 0, sizeof(struct MetaData));
3380 smi.meta_msgnum = newmsgid;
3381 smi.meta_refcount = 0;
3382 safestrncpy(smi.meta_content_type, content_type,
3383 sizeof smi.meta_content_type);
3386 * Measure how big this message will be when rendered as RFC822.
3387 * We do this for two reasons:
3388 * 1. We need the RFC822 length for the new metadata record, so the
3389 * POP and IMAP services don't have to calculate message lengths
3390 * while the user is waiting (multiplied by potentially hundreds
3391 * or thousands of messages).
3392 * 2. If journaling is enabled, we will need an RFC822 version of the
3393 * message to attach to the journalized copy.
3395 if (CCC->redirect_buffer != NULL) {
3396 MSGM_syslog(LOG_ALERT, "CCC->redirect_buffer is not NULL during message submission!\n");
3399 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
3400 CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1, QP_EADDR);
3401 smi.meta_rfc822_length = StrLength(CCC->redirect_buffer);
3402 saved_rfc822_version = CCC->redirect_buffer;
3403 CCC->redirect_buffer = NULL;
3407 /* Now figure out where to store the pointers */
3408 MSGM_syslog(LOG_DEBUG, "Storing pointers\n");
3410 /* If this is being done by the networker delivering a private
3411 * message, we want to BYPASS saving the sender's copy (because there
3412 * is no local sender; it would otherwise go to the Trashcan).
3414 if ((!CCC->internal_pgm) || (recps == NULL)) {
3415 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
3416 MSGM_syslog(LOG_ERR, "ERROR saving message pointer!\n");
3417 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3421 /* For internet mail, drop a copy in the outbound queue room */
3422 if ((recps != NULL) && (recps->num_internet > 0)) {
3423 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
3426 /* If other rooms are specified, drop them there too. */
3427 if ((recps != NULL) && (recps->num_room > 0))
3428 for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
3429 extract_token(recipient, recps->recp_room, i,
3430 '|', sizeof recipient);
3431 MSG_syslog(LOG_DEBUG, "Delivering to room <%s>\n", recipient);///// xxxx
3432 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
3435 /* Bump this user's messages posted counter. */
3436 MSGM_syslog(LOG_DEBUG, "Updating user\n");
3437 CtdlGetUserLock(&CCC->user, CCC->curr_user);
3438 CCC->user.posted = CCC->user.posted + 1;
3439 CtdlPutUserLock(&CCC->user);
3441 /* Decide where bounces need to be delivered */
3442 if ((recps != NULL) && (recps->bounce_to != NULL)) {
3443 safestrncpy(bounce_to, recps->bounce_to, sizeof bounce_to);
3445 else if (CCC->logged_in) {
3446 snprintf(bounce_to, sizeof bounce_to, "%s@%s", CCC->user.fullname, config.c_nodename);
3449 snprintf(bounce_to, sizeof bounce_to, "%s@%s", msg->cm_fields[eAuthor], msg->cm_fields[eNodeName]);
3452 /* If this is private, local mail, make a copy in the
3453 * recipient's mailbox and bump the reference count.
3455 if ((recps != NULL) && (recps->num_local > 0))
3456 for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
3458 recipientlen = extract_token(recipient,
3459 recps->recp_local, i,
3460 '|', sizeof recipient);
3461 MSG_syslog(LOG_DEBUG, "Delivering private local mail to <%s>\n",
3463 if (CtdlGetUser(&userbuf, recipient) == 0) {
3464 CtdlMailboxName(actual_rm, sizeof actual_rm, &userbuf, MAILROOM);
3465 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
3466 CtdlBumpNewMailCounter(userbuf.usernum);
3467 if (!IsEmptyStr(config.c_funambol_host) || !IsEmptyStr(config.c_pager_program)) {
3468 /* Generate a instruction message for the Funambol notification
3469 * server, in the same style as the SMTP queue
3473 instr = malloc(instr_alloc);
3474 instrlen = snprintf(
3476 "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
3480 (long)time(NULL), //todo: time() is expensive!
3484 imsg = malloc(sizeof(struct CtdlMessage));
3485 memset(imsg, 0, sizeof(struct CtdlMessage));
3486 imsg->cm_magic = CTDLMESSAGE_MAGIC;
3487 imsg->cm_anon_type = MES_NORMAL;
3488 imsg->cm_format_type = FMT_RFC822;
3489 CM_SetField(imsg, eMsgSubject, HKEY("QMSG"));
3490 CM_SetField(imsg, eAuthor, HKEY("Citadel"));
3491 CM_SetField(imsg, eJournal, HKEY("do not journal"));
3492 CM_SetAsField(imsg, eMesageText, &instr, instrlen);
3493 CM_SetField(imsg, eExtnotify, recipient, recipientlen);
3494 CtdlSubmitMsg(imsg, NULL, FNBL_QUEUE_ROOM, 0);
3499 MSG_syslog(LOG_DEBUG, "No user <%s>\n", recipient);
3500 CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
3504 /* Perform "after save" hooks */
3505 MSGM_syslog(LOG_DEBUG, "Performing after-save hooks\n");
3507 CM_SetFieldLONG(msg, eVltMsgNum, newmsgid);
3508 PerformMessageHooks(msg, EVT_AFTERSAVE);
3509 CM_FlushField(msg, eVltMsgNum);
3511 /* For IGnet mail, we have to save a new copy into the spooler for
3512 * each recipient, with the R and D fields set to the recipient and
3513 * destination-node. This has two ugly side effects: all other
3514 * recipients end up being unlisted in this recipient's copy of the
3515 * message, and it has to deliver multiple messages to the same
3516 * node. We'll revisit this again in a year or so when everyone has
3517 * a network spool receiver that can handle the new style messages.
3519 if ((recps != NULL) && (recps->num_ignet > 0))
3520 for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
3521 extract_token(recipient, recps->recp_ignet, i,
3522 '|', sizeof recipient);
3524 hold_R = msg->cm_fields[eRecipient];
3525 hold_D = msg->cm_fields[eDestination];
3526 msg->cm_fields[eRecipient] = malloc(SIZ);
3527 msg->cm_fields[eDestination] = malloc(128);
3528 extract_token(msg->cm_fields[eRecipient], recipient, 0, '@', SIZ);
3529 extract_token(msg->cm_fields[eDestination], recipient, 1, '@', 128);
3531 serialize_message(&smr, msg);
3533 snprintf(submit_filename, sizeof submit_filename,
3534 "%s/netmail.%04lx.%04x.%04x",
3536 (long) getpid(), CCC->cs_pid, ++seqnum);
3537 network_fp = fopen(submit_filename, "wb+");
3538 if (network_fp != NULL) {
3539 rv = fwrite(smr.ser, smr.len, 1, network_fp);
3541 MSG_syslog(LOG_EMERG, "CtdlSubmitMsg(): Couldn't write network spool file: %s\n",
3549 free(msg->cm_fields[eRecipient]);
3550 free(msg->cm_fields[eDestination]);
3551 msg->cm_fields[eRecipient] = hold_R;
3552 msg->cm_fields[eDestination] = hold_D;
3555 /* Go back to the room we started from */
3556 MSG_syslog(LOG_DEBUG, "Returning to original room %s\n", hold_rm);
3557 if (strcasecmp(hold_rm, CCC->room.QRname))
3558 CtdlUserGoto(hold_rm, 0, 1, NULL, NULL);
3560 /* For internet mail, generate delivery instructions.
3561 * Yes, this is recursive. Deal with it. Infinite recursion does
3562 * not happen because the delivery instructions message does not
3563 * contain a recipient.
3565 if ((recps != NULL) && (recps->num_internet > 0)) {
3566 StrBuf *SpoolMsg = NewStrBuf();
3569 MSGM_syslog(LOG_DEBUG, "Generating delivery instructions\n");
3571 StrBufPrintf(SpoolMsg,
3572 "Content-type: "SPOOLMIME"\n"
3581 if (recps->envelope_from != NULL) {
3582 StrBufAppendBufPlain(SpoolMsg, HKEY("envelope_from|"), 0);
3583 StrBufAppendBufPlain(SpoolMsg, recps->envelope_from, -1, 0);
3584 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3586 if (recps->sending_room != NULL) {
3587 StrBufAppendBufPlain(SpoolMsg, HKEY("source_room|"), 0);
3588 StrBufAppendBufPlain(SpoolMsg, recps->sending_room, -1, 0);
3589 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
3592 nTokens = num_tokens(recps->recp_internet, '|');
3593 for (i = 0; i < nTokens; i++) {
3595 len = extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
3597 StrBufAppendBufPlain(SpoolMsg, HKEY("remote|"), 0);
3598 StrBufAppendBufPlain(SpoolMsg, recipient, len, 0);
3599 StrBufAppendBufPlain(SpoolMsg, HKEY("|0||\n"), 0);
3603 imsg = malloc(sizeof(struct CtdlMessage));
3604 memset(imsg, 0, sizeof(struct CtdlMessage));
3605 imsg->cm_magic = CTDLMESSAGE_MAGIC;
3606 imsg->cm_anon_type = MES_NORMAL;
3607 imsg->cm_format_type = FMT_RFC822;
3608 imsg->cm_fields[eMsgSubject] = strdup("QMSG");
3609 imsg->cm_fields[eAuthor] = strdup("Citadel");
3610 imsg->cm_fields[eJournal] = strdup("do not journal");
3611 imsg->cm_fields[eMesageText] = SmashStrBuf(&SpoolMsg); /* imsg owns this memory now */
3612 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
3617 * Any addresses to harvest for someone's address book?
3619 if ( (CCC->logged_in) && (recps != NULL) ) {
3620 collected_addresses = harvest_collected_addresses(msg);
3623 if (collected_addresses != NULL) {
3624 aptr = (struct addresses_to_be_filed *)
3625 malloc(sizeof(struct addresses_to_be_filed));
3626 CtdlMailboxName(actual_rm, sizeof actual_rm,
3627 &CCC->user, USERCONTACTSROOM);
3628 aptr->roomname = strdup(actual_rm);
3629 aptr->collected_addresses = collected_addresses;
3630 begin_critical_section(S_ATBF);
3633 end_critical_section(S_ATBF);
3637 * Determine whether this message qualifies for journaling.
3639 if (!CM_IsEmpty(msg, eJournal)) {
3640 qualified_for_journaling = 0;
3643 if (recps == NULL) {
3644 qualified_for_journaling = config.c_journal_pubmsgs;
3646 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
3647 qualified_for_journaling = config.c_journal_email;
3650 qualified_for_journaling = config.c_journal_pubmsgs;
3655 * Do we have to perform journaling? If so, hand off the saved
3656 * RFC822 version will be handed off to the journaler for background
3657 * submit. Otherwise, we have to free the memory ourselves.
3659 if (saved_rfc822_version != NULL) {
3660 if (qualified_for_journaling) {
3661 JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
3664 FreeStrBuf(&saved_rfc822_version);
3674 * Convenience function for generating small administrative messages.
3676 void quickie_message(const char *from,
3677 const char *fromaddr,
3682 const char *subject)
3684 struct CtdlMessage *msg;
3685 struct recptypes *recp = NULL;
3687 msg = malloc(sizeof(struct CtdlMessage));
3688 memset(msg, 0, sizeof(struct CtdlMessage));
3689 msg->cm_magic = CTDLMESSAGE_MAGIC;
3690 msg->cm_anon_type = MES_NORMAL;
3691 msg->cm_format_type = format_type;
3694 msg->cm_fields[eAuthor] = strdup(from);
3696 else if (fromaddr != NULL) {
3697 msg->cm_fields[eAuthor] = strdup(fromaddr);
3698 if (strchr(msg->cm_fields[eAuthor], '@')) {
3699 *strchr(msg->cm_fields[eAuthor], '@') = 0;
3703 msg->cm_fields[eAuthor] = strdup("Citadel");
3706 if (fromaddr != NULL) msg->cm_fields[erFc822Addr] = strdup(fromaddr);
3707 if (room != NULL) msg->cm_fields[eOriginalRoom] = strdup(room);
3708 msg->cm_fields[eNodeName] = strdup(NODENAME);
3710 msg->cm_fields[eRecipient] = strdup(to);
3711 recp = validate_recipients(to, NULL, 0);
3713 if (subject != NULL) {
3714 msg->cm_fields[eMsgSubject] = strdup(subject);
3716 msg->cm_fields[eMesageText] = strdup(text);
3718 CtdlSubmitMsg(msg, recp, room, 0);
3720 if (recp != NULL) free_recipients(recp);
3723 void flood_protect_quickie_message(const char *from,
3724 const char *fromaddr,
3729 const char *subject,
3731 const char **CritStr,
3738 u_char rawdigest[MD5_DIGEST_LEN];
3739 struct MD5Context md5context;
3743 time_t tsday = NOW / (8*60*60); /* just care for a day... */
3745 tslen = snprintf(timestamp, sizeof(timestamp), "%ld", tsday);
3746 MD5Init(&md5context);
3748 for (i = 0; i < nCriterions; i++)
3749 MD5Update(&md5context,
3750 (const unsigned char*)CritStr[i], CritStrLen[i]);
3751 MD5Update(&md5context,
3752 (const unsigned char*)timestamp, tslen);
3753 MD5Final(rawdigest, &md5context);
3755 guid = NewStrBufPlain(NULL,
3756 MD5_DIGEST_LEN * 2 + 12);
3757 StrBufHexEscAppend(guid, NULL, rawdigest, MD5_DIGEST_LEN);
3758 StrBufAppendBufPlain(guid, HKEY("_fldpt"), 0);
3759 if (StrLength(guid) > 40)
3760 StrBufCutAt(guid, 40, NULL);
3762 if (CheckIfAlreadySeen("FPAideMessage",
3771 /* yes, we did. flood protection kicks in. */
3773 "not sending message again\n");
3777 /* no, this message isn't sent recently; go ahead. */
3778 quickie_message(from,
3789 * Back end function used by CtdlMakeMessage() and similar functions
3791 StrBuf *CtdlReadMessageBodyBuf(char *terminator, /* token signalling EOT */
3793 size_t maxlen, /* maximum message length */
3794 StrBuf *exist, /* if non-null, append to it;
3795 exist is ALWAYS freed */
3796 int crlf, /* CRLF newlines instead of LF */
3797 int *sock /* socket handle or 0 for this session's client socket */
3806 LineBuf = NewStrBufPlain(NULL, SIZ);
3807 if (exist == NULL) {
3808 Message = NewStrBufPlain(NULL, 4 * SIZ);
3811 Message = NewStrBufDup(exist);
3814 /* Do we need to change leading ".." to "." for SMTP escaping? */
3815 if ((tlen == 1) && (*terminator == '.')) {
3819 /* read in the lines of message text one by one */
3822 if ((CtdlSockGetLine(sock, LineBuf, 5) < 0) ||
3827 if (CtdlClientGetLine(LineBuf) < 0) finished = 1;
3829 if ((StrLength(LineBuf) == tlen) &&
3830 (!strcmp(ChrPtr(LineBuf), terminator)))
3833 if ( (!flushing) && (!finished) ) {
3835 StrBufAppendBufPlain(LineBuf, HKEY("\r\n"), 0);
3838 StrBufAppendBufPlain(LineBuf, HKEY("\n"), 0);
3841 /* Unescape SMTP-style input of two dots at the beginning of the line */
3843 (StrLength(LineBuf) == 2) &&
3844 (!strcmp(ChrPtr(LineBuf), "..")))
3846 StrBufCutLeft(LineBuf, 1);
3849 StrBufAppendBuf(Message, LineBuf, 0);
3852 /* if we've hit the max msg length, flush the rest */
3853 if (StrLength(Message) >= maxlen) flushing = 1;
3855 } while (!finished);
3856 FreeStrBuf(&LineBuf);
3860 void DeleteAsyncMsg(ReadAsyncMsg **Msg)
3864 FreeStrBuf(&(*Msg)->MsgBuf);
3870 ReadAsyncMsg *NewAsyncMsg(const char *terminator, /* token signalling EOT */
3872 size_t maxlen, /* maximum message length */
3873 size_t expectlen, /* if we expect a message, how long should it be? */
3874 StrBuf *exist, /* if non-null, append to it;
3875 exist is ALWAYS freed */
3876 long eLen, /* length of exist */
3877 int crlf /* CRLF newlines instead of LF */
3880 ReadAsyncMsg *NewMsg;
3882 NewMsg = (ReadAsyncMsg *)malloc(sizeof(ReadAsyncMsg));
3883 memset(NewMsg, 0, sizeof(ReadAsyncMsg));
3885 if (exist == NULL) {
3888 if (expectlen == 0) {
3892 len = expectlen + 10;
3894 NewMsg->MsgBuf = NewStrBufPlain(NULL, len);
3897 NewMsg->MsgBuf = NewStrBufDup(exist);
3899 /* Do we need to change leading ".." to "." for SMTP escaping? */
3900 if ((tlen == 1) && (*terminator == '.')) {
3904 NewMsg->terminator = terminator;
3905 NewMsg->tlen = tlen;
3907 NewMsg->maxlen = maxlen;
3909 NewMsg->crlf = crlf;
3915 * Back end function used by CtdlMakeMessage() and similar functions
3917 eReadState CtdlReadMessageBodyAsync(AsyncIO *IO)
3919 ReadAsyncMsg *ReadMsg;
3920 int MsgFinished = 0;
3921 eReadState Finished = eMustReadMore;
3926 const char *pch = ChrPtr(IO->SendBuf.Buf);
3927 const char *pchh = IO->SendBuf.ReadWritePointer;
3933 nbytes = StrLength(IO->SendBuf.Buf) - (pchh - pch);
3934 snprintf(fn, SIZ, "/tmp/foolog_ev_%s.%d",
3935 ((CitContext*)(IO->CitContext))->ServiceName,
3938 fd = fopen(fn, "a+");
3941 ReadMsg = IO->ReadMsg;
3943 /* read in the lines of message text one by one */
3945 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
3948 case eMustReadMore: /// read new from socket...
3950 if (IO->RecvBuf.ReadWritePointer != NULL) {
3951 nbytes = StrLength(IO->RecvBuf.Buf) - (IO->RecvBuf.ReadWritePointer - ChrPtr(IO->RecvBuf.Buf));
3952 fprintf(fd, "Read; Line unfinished: %ld Bytes still in buffer [", nbytes);
3954 fwrite(IO->RecvBuf.ReadWritePointer, nbytes, 1, fd);
3958 fprintf(fd, "BufferEmpty! \n");
3964 case eBufferNotEmpty: /* shouldn't happen... */
3965 case eReadSuccess: /// done for now...
3967 case eReadFail: /// WHUT?
3973 if ((StrLength(IO->IOBuf) == ReadMsg->tlen) &&
3974 (!strcmp(ChrPtr(IO->IOBuf), ReadMsg->terminator))) {
3977 fprintf(fd, "found Terminator; Message Size: %d\n", StrLength(ReadMsg->MsgBuf));
3980 else if (!ReadMsg->flushing) {
3983 fprintf(fd, "Read Line: [%d][%s]\n", StrLength(IO->IOBuf), ChrPtr(IO->IOBuf));
3986 /* Unescape SMTP-style input of two dots at the beginning of the line */
3987 if ((ReadMsg->dodot) &&
3988 (StrLength(IO->IOBuf) == 2) && /* TODO: do we just unescape lines with two dots or any line? */
3989 (!strcmp(ChrPtr(IO->IOBuf), "..")))
3992 fprintf(fd, "UnEscaped!\n");
3994 StrBufCutLeft(IO->IOBuf, 1);
3997 if (ReadMsg->crlf) {
3998 StrBufAppendBufPlain(IO->IOBuf, HKEY("\r\n"), 0);
4001 StrBufAppendBufPlain(IO->IOBuf, HKEY("\n"), 0);
4004 StrBufAppendBuf(ReadMsg->MsgBuf, IO->IOBuf, 0);
4007 /* if we've hit the max msg length, flush the rest */
4008 if (StrLength(ReadMsg->MsgBuf) >= ReadMsg->maxlen) ReadMsg->flushing = 1;
4010 } while (!MsgFinished);
4013 fprintf(fd, "Done with reading; %s.\n, ",
4014 (MsgFinished)?"Message Finished": "FAILED");
4018 return eReadSuccess;
4025 * Back end function used by CtdlMakeMessage() and similar functions
4027 char *CtdlReadMessageBody(char *terminator, /* token signalling EOT */
4029 size_t maxlen, /* maximum message length */
4030 StrBuf *exist, /* if non-null, append to it;
4031 exist is ALWAYS freed */
4032 int crlf, /* CRLF newlines instead of LF */
4033 int *sock /* socket handle or 0 for this session's client socket */
4038 Message = CtdlReadMessageBodyBuf(terminator,
4044 if (Message == NULL)
4047 return SmashStrBuf(&Message);
4052 * Build a binary message to be saved on disk.
4053 * (NOTE: if you supply 'preformatted_text', the buffer you give it
4054 * will become part of the message. This means you are no longer
4055 * responsible for managing that memory -- it will be freed along with
4056 * the rest of the fields when CM_Free() is called.)
4059 struct CtdlMessage *CtdlMakeMessage(
4060 struct ctdluser *author, /* author's user structure */
4061 char *recipient, /* NULL if it's not mail */
4062 char *recp_cc, /* NULL if it's not mail */
4063 char *room, /* room where it's going */
4064 int type, /* see MES_ types in header file */
4065 int format_type, /* variformat, plain text, MIME... */
4066 char *fake_name, /* who we're masquerading as */
4067 char *my_email, /* which of my email addresses to use (empty is ok) */
4068 char *subject, /* Subject (optional) */
4069 char *supplied_euid, /* ...or NULL if this is irrelevant */
4070 char *preformatted_text, /* ...or NULL to read text from client */
4071 char *references /* Thread references */
4073 char dest_node[256];
4075 struct CtdlMessage *msg;
4077 StrBuf *FakeEncAuthor = NULL;
4079 msg = malloc(sizeof(struct CtdlMessage));
4080 memset(msg, 0, sizeof(struct CtdlMessage));
4081 msg->cm_magic = CTDLMESSAGE_MAGIC;
4082 msg->cm_anon_type = type;
4083 msg->cm_format_type = format_type;
4085 /* Don't confuse the poor folks if it's not routed mail. */
4086 strcpy(dest_node, "");
4088 if (recipient != NULL) striplt(recipient);
4089 if (recp_cc != NULL) striplt(recp_cc);
4091 /* Path or Return-Path */
4092 if (my_email == NULL) my_email = "";
4094 if (!IsEmptyStr(my_email)) {
4095 msg->cm_fields[eMessagePath] = strdup(my_email);
4098 snprintf(buf, sizeof buf, "%s", author->fullname);
4099 msg->cm_fields[eMessagePath] = strdup(buf);
4101 convert_spaces_to_underscores(msg->cm_fields[eMessagePath]);
4103 snprintf(buf, sizeof buf, "%ld", (long)time(NULL)); /* timestamp */
4104 msg->cm_fields[eTimestamp] = strdup(buf);
4106 if ((fake_name != NULL) && (fake_name[0])) { /* author */
4107 FakeAuthor = NewStrBufPlain (fake_name, -1);
4110 FakeAuthor = NewStrBufPlain (author->fullname, -1);
4112 StrBufRFC2047encode(&FakeEncAuthor, FakeAuthor);
4113 msg->cm_fields[eAuthor] = SmashStrBuf(&FakeEncAuthor);
4114 FreeStrBuf(&FakeAuthor);
4116 if (CC->room.QRflags & QR_MAILBOX) { /* room */
4117 msg->cm_fields[eOriginalRoom] = strdup(&CC->room.QRname[11]);
4120 msg->cm_fields[eOriginalRoom] = strdup(CC->room.QRname);
4123 msg->cm_fields[eNodeName] = strdup(NODENAME); /* nodename */
4124 msg->cm_fields[eHumanNode] = strdup(HUMANNODE); /* hnodename */
4126 if ((recipient != NULL) && (recipient[0] != 0)) {
4127 msg->cm_fields[eRecipient] = strdup(recipient);
4129 if ((recp_cc != NULL) && (recp_cc[0] != 0)) {
4130 msg->cm_fields[eCarbonCopY] = strdup(recp_cc);
4132 if (dest_node[0] != 0) {
4133 msg->cm_fields[eDestination] = strdup(dest_node);
4136 if (!IsEmptyStr(my_email)) {
4137 msg->cm_fields[erFc822Addr] = strdup(my_email);
4139 else if ( (author == &CC->user) && (!IsEmptyStr(CC->cs_inet_email)) ) {
4140 msg->cm_fields[erFc822Addr] = strdup(CC->cs_inet_email);
4143 if (subject != NULL) {
4146 length = strlen(subject);
4152 while ((subject[i] != '\0') &&
4153 (IsAscii = isascii(subject[i]) != 0 ))
4156 msg->cm_fields[eMsgSubject] = strdup(subject);
4157 else /* ok, we've got utf8 in the string. */
4159 msg->cm_fields[eMsgSubject] = rfc2047encode(subject, length);
4165 if (supplied_euid != NULL) {
4166 msg->cm_fields[eExclusiveID] = strdup(supplied_euid);
4169 if ((references != NULL) && (!IsEmptyStr(references))) {
4170 if (msg->cm_fields[eWeferences] != NULL)
4171 free(msg->cm_fields[eWeferences]);
4172 msg->cm_fields[eWeferences] = strdup(references);
4175 if (preformatted_text != NULL) {
4176 msg->cm_fields[eMesageText] = preformatted_text;
4179 msg->cm_fields[eMesageText] = CtdlReadMessageBody(HKEY("000"), config.c_maxmsglen, NULL, 0, 0);
4186 * Check to see whether we have permission to post a message in the current
4187 * room. Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
4188 * returns 0 on success.
4190 int CtdlDoIHavePermissionToPostInThisRoom(
4193 const char* RemoteIdentifier,
4199 if (!(CC->logged_in) &&
4200 (PostPublic == POST_LOGGED_IN)) {
4201 snprintf(errmsgbuf, n, "Not logged in.");
4202 return (ERROR + NOT_LOGGED_IN);
4204 else if (PostPublic == CHECK_EXISTANCE) {
4205 return (0); // We're Evaling whether a recipient exists
4207 else if (!(CC->logged_in)) {
4209 if ((CC->room.QRflags & QR_READONLY)) {
4210 snprintf(errmsgbuf, n, "Not logged in.");
4211 return (ERROR + NOT_LOGGED_IN);
4213 if (CC->room.QRflags2 & QR2_MODERATED) {
4214 snprintf(errmsgbuf, n, "Not logged in Moderation feature not yet implemented!");
4215 return (ERROR + NOT_LOGGED_IN);
4217 if ((PostPublic!=POST_LMTP) &&(CC->room.QRflags2 & QR2_SMTP_PUBLIC) == 0) {
4219 return CtdlNetconfigCheckRoomaccess(errmsgbuf, n, RemoteIdentifier);
4225 if ((CC->user.axlevel < AxProbU)
4226 && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
4227 snprintf(errmsgbuf, n, "Need to be validated to enter (except in %s> to sysop)", MAILROOM);
4228 return (ERROR + HIGHER_ACCESS_REQUIRED);
4231 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
4233 if (ra & UA_POSTALLOWED) {
4234 strcpy(errmsgbuf, "OK to post or reply here");
4238 if ( (ra & UA_REPLYALLOWED) && (is_reply) ) {
4240 * To be thorough, we ought to check to see if the message they are
4241 * replying to is actually a valid one in this room, but unless this
4242 * actually becomes a problem we'll go with high performance instead.
4244 strcpy(errmsgbuf, "OK to reply here");
4248 if ( (ra & UA_REPLYALLOWED) && (!is_reply) ) {
4249 /* Clarify what happened with a better error message */
4250 snprintf(errmsgbuf, n, "You may only reply to existing messages here.");
4251 return (ERROR + HIGHER_ACCESS_REQUIRED);
4254 snprintf(errmsgbuf, n, "Higher access is required to post in this room.");
4255 return (ERROR + HIGHER_ACCESS_REQUIRED);
4261 * Check to see if the specified user has Internet mail permission
4262 * (returns nonzero if permission is granted)
4264 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
4266 /* Do not allow twits to send Internet mail */
4267 if (who->axlevel <= AxProbU) return(0);
4269 /* Globally enabled? */
4270 if (config.c_restrict == 0) return(1);
4272 /* User flagged ok? */
4273 if (who->flags & US_INTERNET) return(2);
4275 /* Admin level access? */
4276 if (who->axlevel >= AxAideU) return(3);
4278 /* No mail for you! */
4284 * Validate recipients, count delivery types and errors, and handle aliasing
4285 * FIXME check for dupes!!!!!
4287 * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses
4288 * were specified, or the number of addresses found invalid.
4290 * Caller needs to free the result using free_recipients()
4292 struct recptypes *validate_recipients(const char *supplied_recipients,
4293 const char *RemoteIdentifier,
4295 struct CitContext *CCC = CC;
4296 struct recptypes *ret;
4297 char *recipients = NULL;
4299 char this_recp[256];
4300 char this_recp_cooked[256];
4307 struct ctdluser tempUS;
4308 struct ctdlroom tempQR;
4309 struct ctdlroom tempQR2;
4315 ret = (struct recptypes *) malloc(sizeof(struct recptypes));
4316 if (ret == NULL) return(NULL);
4318 /* Set all strings to null and numeric values to zero */
4319 memset(ret, 0, sizeof(struct recptypes));
4321 if (supplied_recipients == NULL) {
4322 recipients = strdup("");
4325 recipients = strdup(supplied_recipients);
4328 /* Allocate some memory. Yes, this allocates 500% more memory than we will
4329 * actually need, but it's healthier for the heap than doing lots of tiny
4330 * realloc() calls instead.
4332 len = strlen(recipients) + 1024;
4333 ret->errormsg = malloc(len);
4334 ret->recp_local = malloc(len);
4335 ret->recp_internet = malloc(len);
4336 ret->recp_ignet = malloc(len);
4337 ret->recp_room = malloc(len);
4338 ret->display_recp = malloc(len);
4339 ret->recp_orgroom = malloc(len);
4340 org_recp = malloc(len);
4342 ret->errormsg[0] = 0;
4343 ret->recp_local[0] = 0;
4344 ret->recp_internet[0] = 0;
4345 ret->recp_ignet[0] = 0;
4346 ret->recp_room[0] = 0;
4347 ret->recp_orgroom[0] = 0;
4348 ret->display_recp[0] = 0;
4350 ret->recptypes_magic = RECPTYPES_MAGIC;
4352 /* Change all valid separator characters to commas */
4353 for (i=0; !IsEmptyStr(&recipients[i]); ++i) {
4354 if ((recipients[i] == ';') || (recipients[i] == '|')) {
4355 recipients[i] = ',';
4359 /* Now start extracting recipients... */
4361 while (!IsEmptyStr(recipients)) {
4362 for (i=0; i<=strlen(recipients); ++i) {
4363 if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
4364 if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
4365 safestrncpy(this_recp, recipients, i+1);
4367 if (recipients[i] == ',') {
4368 strcpy(recipients, &recipients[i+1]);
4371 strcpy(recipients, "");
4378 if (IsEmptyStr(this_recp))
4380 MSG_syslog(LOG_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
4383 strcpy(org_recp, this_recp);
4386 mailtype = alias(this_recp);
4388 for (j = 0; !IsEmptyStr(&this_recp[j]); ++j) {
4389 if (this_recp[j]=='_') {
4390 this_recp_cooked[j] = ' ';
4393 this_recp_cooked[j] = this_recp[j];
4396 this_recp_cooked[j] = '\0';
4401 if (!strcasecmp(this_recp, "sysop")) {
4403 strcpy(this_recp, config.c_aideroom);
4404 if (!IsEmptyStr(ret->recp_room)) {
4405 strcat(ret->recp_room, "|");
4407 strcat(ret->recp_room, this_recp);
4409 else if ( (!strncasecmp(this_recp, "room_", 5))
4410 && (!CtdlGetRoom(&tempQR, &this_recp_cooked[5])) ) {
4412 /* Save room so we can restore it later */
4413 tempQR2 = CCC->room;
4416 /* Check permissions to send mail to this room */
4417 err = CtdlDoIHavePermissionToPostInThisRoom(
4422 0 /* 0 = not a reply */
4431 if (!IsEmptyStr(ret->recp_room)) {
4432 strcat(ret->recp_room, "|");
4434 strcat(ret->recp_room, &this_recp_cooked[5]);
4436 if (!IsEmptyStr(ret->recp_orgroom)) {
4437 strcat(ret->recp_orgroom, "|");
4439 strcat(ret->recp_orgroom, org_recp);
4443 /* Restore room in case something needs it */
4444 CCC->room = tempQR2;
4447 else if (CtdlGetUser(&tempUS, this_recp) == 0) {
4449 strcpy(this_recp, tempUS.fullname);
4450 if (!IsEmptyStr(ret->recp_local)) {
4451 strcat(ret->recp_local, "|");
4453 strcat(ret->recp_local, this_recp);
4455 else if (CtdlGetUser(&tempUS, this_recp_cooked) == 0) {
4457 strcpy(this_recp, tempUS.fullname);
4458 if (!IsEmptyStr(ret->recp_local)) {
4459 strcat(ret->recp_local, "|");
4461 strcat(ret->recp_local, this_recp);
4469 /* Yes, you're reading this correctly: if the target
4470 * domain points back to the local system or an attached
4471 * Citadel directory, the address is invalid. That's
4472 * because if the address were valid, we would have
4473 * already translated it to a local address by now.
4475 if (IsDirectory(this_recp, 0)) {
4480 ++ret->num_internet;
4481 if (!IsEmptyStr(ret->recp_internet)) {
4482 strcat(ret->recp_internet, "|");
4484 strcat(ret->recp_internet, this_recp);
4489 if (!IsEmptyStr(ret->recp_ignet)) {
4490 strcat(ret->recp_ignet, "|");
4492 strcat(ret->recp_ignet, this_recp);
4500 if (IsEmptyStr(errmsg)) {
4501 snprintf(append, sizeof append, "Invalid recipient: %s", this_recp);
4504 snprintf(append, sizeof append, "%s", errmsg);
4506 if ( (strlen(ret->errormsg) + strlen(append) + 3) < SIZ) {
4507 if (!IsEmptyStr(ret->errormsg)) {
4508 strcat(ret->errormsg, "; ");
4510 strcat(ret->errormsg, append);
4514 if (IsEmptyStr(ret->display_recp)) {
4515 strcpy(append, this_recp);
4518 snprintf(append, sizeof append, ", %s", this_recp);
4520 if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
4521 strcat(ret->display_recp, append);
4527 if ((ret->num_local + ret->num_internet + ret->num_ignet +
4528 ret->num_room + ret->num_error) == 0) {
4529 ret->num_error = (-1);
4530 strcpy(ret->errormsg, "No recipients specified.");
4533 MSGM_syslog(LOG_DEBUG, "validate_recipients()\n");
4534 MSG_syslog(LOG_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
4535 MSG_syslog(LOG_DEBUG, " room: %d <%s>\n", ret->num_room, ret->recp_room);
4536 MSG_syslog(LOG_DEBUG, " inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
4537 MSG_syslog(LOG_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
4538 MSG_syslog(LOG_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
4546 * Destructor for struct recptypes
4548 void free_recipients(struct recptypes *valid) {
4550 if (valid == NULL) {
4554 if (valid->recptypes_magic != RECPTYPES_MAGIC) {
4555 struct CitContext *CCC = CC;
4556 MSGM_syslog(LOG_EMERG, "Attempt to call free_recipients() on some other data type!\n");
4560 if (valid->errormsg != NULL) free(valid->errormsg);
4561 if (valid->recp_local != NULL) free(valid->recp_local);
4562 if (valid->recp_internet != NULL) free(valid->recp_internet);
4563 if (valid->recp_ignet != NULL) free(valid->recp_ignet);
4564 if (valid->recp_room != NULL) free(valid->recp_room);
4565 if (valid->recp_orgroom != NULL) free(valid->recp_orgroom);
4566 if (valid->display_recp != NULL) free(valid->display_recp);
4567 if (valid->bounce_to != NULL) free(valid->bounce_to);
4568 if (valid->envelope_from != NULL) free(valid->envelope_from);
4569 if (valid->sending_room != NULL) free(valid->sending_room);
4576 * message entry - mode 0 (normal)
4578 void cmd_ent0(char *entargs)
4580 struct CitContext *CCC = CC;
4585 char supplied_euid[128];
4587 int format_type = 0;
4588 char newusername[256];
4589 char newuseremail[256];
4590 struct CtdlMessage *msg;
4594 struct recptypes *valid = NULL;
4595 struct recptypes *valid_to = NULL;
4596 struct recptypes *valid_cc = NULL;
4597 struct recptypes *valid_bcc = NULL;
4599 int subject_required = 0;
4604 int newuseremail_ok = 0;
4605 char references[SIZ];
4610 post = extract_int(entargs, 0);
4611 extract_token(recp, entargs, 1, '|', sizeof recp);
4612 anon_flag = extract_int(entargs, 2);
4613 format_type = extract_int(entargs, 3);
4614 extract_token(subject, entargs, 4, '|', sizeof subject);
4615 extract_token(newusername, entargs, 5, '|', sizeof newusername);
4616 do_confirm = extract_int(entargs, 6);
4617 extract_token(cc, entargs, 7, '|', sizeof cc);
4618 extract_token(bcc, entargs, 8, '|', sizeof bcc);
4619 switch(CC->room.QRdefaultview) {
4622 extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
4625 supplied_euid[0] = 0;
4628 extract_token(newuseremail, entargs, 10, '|', sizeof newuseremail);
4629 extract_token(references, entargs, 11, '|', sizeof references);
4630 for (ptr=references; *ptr != 0; ++ptr) {
4631 if (*ptr == '!') *ptr = '|';
4634 /* first check to make sure the request is valid. */
4636 err = CtdlDoIHavePermissionToPostInThisRoom(
4641 (!IsEmptyStr(references)) /* is this a reply? or a top-level post? */
4645 cprintf("%d %s\n", err, errmsg);
4649 /* Check some other permission type things. */
4651 if (IsEmptyStr(newusername)) {
4652 strcpy(newusername, CCC->user.fullname);
4654 if ( (CCC->user.axlevel < AxAideU)
4655 && (strcasecmp(newusername, CCC->user.fullname))
4656 && (strcasecmp(newusername, CCC->cs_inet_fn))
4658 cprintf("%d You don't have permission to author messages as '%s'.\n",
4659 ERROR + HIGHER_ACCESS_REQUIRED,
4666 if (IsEmptyStr(newuseremail)) {
4667 newuseremail_ok = 1;
4670 if (!IsEmptyStr(newuseremail)) {
4671 if (!strcasecmp(newuseremail, CCC->cs_inet_email)) {
4672 newuseremail_ok = 1;
4674 else if (!IsEmptyStr(CCC->cs_inet_other_emails)) {
4675 j = num_tokens(CCC->cs_inet_other_emails, '|');
4676 for (i=0; i<j; ++i) {
4677 extract_token(buf, CCC->cs_inet_other_emails, i, '|', sizeof buf);
4678 if (!strcasecmp(newuseremail, buf)) {
4679 newuseremail_ok = 1;
4685 if (!newuseremail_ok) {
4686 cprintf("%d You don't have permission to author messages as '%s'.\n",
4687 ERROR + HIGHER_ACCESS_REQUIRED,
4693 CCC->cs_flags |= CS_POSTING;
4695 /* In mailbox rooms we have to behave a little differently --
4696 * make sure the user has specified at least one recipient. Then
4697 * validate the recipient(s). We do this for the Mail> room, as
4698 * well as any room which has the "Mailbox" view set - unless it
4699 * is the DRAFTS room which does not require recipients
4702 if ( ( ( (CCC->room.QRflags & QR_MAILBOX) && (!strcasecmp(&CCC->room.QRname[11], MAILROOM)) )
4703 || ( (CCC->room.QRflags & QR_MAILBOX) && (CCC->curr_view == VIEW_MAILBOX) )
4704 ) && (strcasecmp(&CCC->room.QRname[11], USERDRAFTROOM)) !=0 ) {
4705 if (CCC->user.axlevel < AxProbU) {
4706 strcpy(recp, "sysop");
4711 valid_to = validate_recipients(recp, NULL, 0);
4712 if (valid_to->num_error > 0) {
4713 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_to->errormsg);
4714 free_recipients(valid_to);
4718 valid_cc = validate_recipients(cc, NULL, 0);
4719 if (valid_cc->num_error > 0) {
4720 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_cc->errormsg);
4721 free_recipients(valid_to);
4722 free_recipients(valid_cc);
4726 valid_bcc = validate_recipients(bcc, NULL, 0);
4727 if (valid_bcc->num_error > 0) {
4728 cprintf("%d %s\n", ERROR + NO_SUCH_USER, valid_bcc->errormsg);
4729 free_recipients(valid_to);
4730 free_recipients(valid_cc);
4731 free_recipients(valid_bcc);
4735 /* Recipient required, but none were specified */
4736 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
4737 free_recipients(valid_to);
4738 free_recipients(valid_cc);
4739 free_recipients(valid_bcc);
4740 cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
4744 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
4745 if (CtdlCheckInternetMailPermission(&CCC->user)==0) {
4746 cprintf("%d You do not have permission "
4747 "to send Internet mail.\n",
4748 ERROR + HIGHER_ACCESS_REQUIRED);
4749 free_recipients(valid_to);
4750 free_recipients(valid_cc);
4751 free_recipients(valid_bcc);
4756 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)
4757 && (CCC->user.axlevel < AxNetU) ) {
4758 cprintf("%d Higher access required for network mail.\n",
4759 ERROR + HIGHER_ACCESS_REQUIRED);
4760 free_recipients(valid_to);
4761 free_recipients(valid_cc);
4762 free_recipients(valid_bcc);
4766 if ((RESTRICT_INTERNET == 1)
4767 && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
4768 && ((CCC->user.flags & US_INTERNET) == 0)
4769 && (!CCC->internal_pgm)) {
4770 cprintf("%d You don't have access to Internet mail.\n",
4771 ERROR + HIGHER_ACCESS_REQUIRED);
4772 free_recipients(valid_to);
4773 free_recipients(valid_cc);
4774 free_recipients(valid_bcc);
4780 /* Is this a room which has anonymous-only or anonymous-option? */
4781 anonymous = MES_NORMAL;
4782 if (CCC->room.QRflags & QR_ANONONLY) {
4783 anonymous = MES_ANONONLY;
4785 if (CCC->room.QRflags & QR_ANONOPT) {
4786 if (anon_flag == 1) { /* only if the user requested it */
4787 anonymous = MES_ANONOPT;
4791 if ((CCC->room.QRflags & QR_MAILBOX) == 0) {
4795 /* Recommend to the client that the use of a message subject is
4796 * strongly recommended in this room, if either the SUBJECTREQ flag
4797 * is set, or if there is one or more Internet email recipients.
4799 if (CCC->room.QRflags2 & QR2_SUBJECTREQ) subject_required = 1;
4800 if ((valid_to) && (valid_to->num_internet > 0)) subject_required = 1;
4801 if ((valid_cc) && (valid_cc->num_internet > 0)) subject_required = 1;
4802 if ((valid_bcc) && (valid_bcc->num_internet > 0)) subject_required = 1;
4804 /* If we're only checking the validity of the request, return
4805 * success without creating the message.
4808 cprintf("%d %s|%d\n", CIT_OK,
4809 ((valid_to != NULL) ? valid_to->display_recp : ""),
4811 free_recipients(valid_to);
4812 free_recipients(valid_cc);
4813 free_recipients(valid_bcc);
4817 /* We don't need these anymore because we'll do it differently below */
4818 free_recipients(valid_to);
4819 free_recipients(valid_cc);
4820 free_recipients(valid_bcc);
4822 /* Read in the message from the client. */
4824 cprintf("%d send message\n", START_CHAT_MODE);
4826 cprintf("%d send message\n", SEND_LISTING);
4829 msg = CtdlMakeMessage(&CCC->user, recp, cc,
4830 CCC->room.QRname, anonymous, format_type,
4831 newusername, newuseremail, subject,
4832 ((!IsEmptyStr(supplied_euid)) ? supplied_euid : NULL),
4835 /* Put together one big recipients struct containing to/cc/bcc all in
4836 * one. This is for the envelope.
4838 char *all_recps = malloc(SIZ * 3);
4839 strcpy(all_recps, recp);
4840 if (!IsEmptyStr(cc)) {
4841 if (!IsEmptyStr(all_recps)) {
4842 strcat(all_recps, ",");
4844 strcat(all_recps, cc);
4846 if (!IsEmptyStr(bcc)) {
4847 if (!IsEmptyStr(all_recps)) {
4848 strcat(all_recps, ",");
4850 strcat(all_recps, bcc);
4852 if (!IsEmptyStr(all_recps)) {
4853 valid = validate_recipients(all_recps, NULL, 0);
4860 if ((valid != NULL) && (valid->num_room == 1))
4862 /* posting into an ML room? set the envelope from
4863 * to the actual mail address so others get a valid
4866 msg->cm_fields[eenVelopeTo] = strdup(valid->recp_orgroom);
4870 msgnum = CtdlSubmitMsg(msg, valid, "", QP_EADDR);
4872 cprintf("%ld\n", msgnum);
4874 if (StrLength(CCC->StatusMessage) > 0) {
4875 cprintf("%s\n", ChrPtr(CCC->StatusMessage));
4877 else if (msgnum >= 0L) {
4878 client_write(HKEY("Message accepted.\n"));
4881 client_write(HKEY("Internal error.\n"));
4884 if (!CM_IsEmpty(msg, eExclusiveID)) {
4885 cprintf("%s\n", msg->cm_fields[eExclusiveID]);
4894 if (valid != NULL) {
4895 free_recipients(valid);
4903 * API function to delete messages which match a set of criteria
4904 * (returns the actual number of messages deleted)
4906 int CtdlDeleteMessages(char *room_name, /* which room */
4907 long *dmsgnums, /* array of msg numbers to be deleted */
4908 int num_dmsgnums, /* number of msgs to be deleted, or 0 for "any" */
4909 char *content_type /* or "" for any. regular expressions expected. */
4912 struct CitContext *CCC = CC;
4913 struct ctdlroom qrbuf;
4914 struct cdbdata *cdbfr;
4915 long *msglist = NULL;
4916 long *dellist = NULL;
4919 int num_deleted = 0;
4921 struct MetaData smi;
4924 int need_to_free_re = 0;
4926 if (content_type) if (!IsEmptyStr(content_type)) {
4927 regcomp(&re, content_type, 0);
4928 need_to_free_re = 1;
4930 MSG_syslog(LOG_DEBUG, " CtdlDeleteMessages(%s, %d msgs, %s)\n",
4931 room_name, num_dmsgnums, content_type);
4933 /* get room record, obtaining a lock... */
4934 if (CtdlGetRoomLock(&qrbuf, room_name) != 0) {
4935 MSG_syslog(LOG_ERR, " CtdlDeleteMessages(): Room <%s> not found\n",
4937 if (need_to_free_re) regfree(&re);
4938 return (0); /* room not found */
4940 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
4942 if (cdbfr != NULL) {
4943 dellist = malloc(cdbfr->len);
4944 msglist = (long *) cdbfr->ptr;
4945 cdbfr->ptr = NULL; /* CtdlDeleteMessages() now owns this memory */
4946 num_msgs = cdbfr->len / sizeof(long);
4950 int have_contenttype = (content_type != NULL) && !IsEmptyStr(content_type);
4951 int have_delmsgs = (num_dmsgnums == 0) || (dmsgnums == NULL);
4952 int have_more_del = 1;
4954 num_msgs = sort_msglist(msglist, num_msgs);
4955 if (num_dmsgnums > 1)
4956 num_dmsgnums = sort_msglist(dmsgnums, num_dmsgnums);
4959 StrBuf *dbg = NewStrBuf();
4960 for (i = 0; i < num_dmsgnums; i++)
4961 StrBufAppendPrintf(dbg, ", %ld", dmsgnums[i]);
4962 MSG_syslog(LOG_DEBUG, " Deleting before: %s", ChrPtr(dbg));
4967 while ((i < num_msgs) && (have_more_del)) {
4970 /* Set/clear a bit for each criterion */
4972 /* 0 messages in the list or a null list means that we are
4973 * interested in deleting any messages which meet the other criteria.
4976 delete_this |= 0x01;
4979 while ((i < num_msgs) && (msglist[i] < dmsgnums[j])) i++;
4984 if (msglist[i] == dmsgnums[j]) {
4985 delete_this |= 0x01;
4988 have_more_del = (j < num_dmsgnums);
4991 if (have_contenttype) {
4992 GetMetaData(&smi, msglist[i]);
4993 if (regexec(&re, smi.meta_content_type, 1, &pm, 0) == 0) {
4994 delete_this |= 0x02;
4997 delete_this |= 0x02;
5000 /* Delete message only if all bits are set */
5001 if (delete_this == 0x03) {
5002 dellist[num_deleted++] = msglist[i];
5009 StrBuf *dbg = NewStrBuf();
5010 for (i = 0; i < num_deleted; i++)
5011 StrBufAppendPrintf(dbg, ", %ld", dellist[i]);
5012 MSG_syslog(LOG_DEBUG, " Deleting: %s", ChrPtr(dbg));
5016 num_msgs = sort_msglist(msglist, num_msgs);
5017 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
5018 msglist, (int)(num_msgs * sizeof(long)));
5021 qrbuf.QRhighest = msglist[num_msgs - 1];
5023 qrbuf.QRhighest = 0;
5025 CtdlPutRoomLock(&qrbuf);
5027 /* Go through the messages we pulled out of the index, and decrement
5028 * their reference counts by 1. If this is the only room the message
5029 * was in, the reference count will reach zero and the message will
5030 * automatically be deleted from the database. We do this in a
5031 * separate pass because there might be plug-in hooks getting called,
5032 * and we don't want that happening during an S_ROOMS critical
5036 for (i=0; i<num_deleted; ++i) {
5037 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
5039 AdjRefCountList(dellist, num_deleted, -1);
5041 /* Now free the memory we used, and go away. */
5042 if (msglist != NULL) free(msglist);
5043 if (dellist != NULL) free(dellist);
5044 MSG_syslog(LOG_DEBUG, " %d message(s) deleted.\n", num_deleted);
5045 if (need_to_free_re) regfree(&re);
5046 return (num_deleted);
5052 * Check whether the current user has permission to delete messages from
5053 * the current room (returns 1 for yes, 0 for no)
5055 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
5057 CtdlRoomAccess(&CC->room, &CC->user, &ra, NULL);
5058 if (ra & UA_DELETEALLOWED) return(1);
5066 * Delete message from current room
5068 void cmd_dele(char *args)
5077 extract_token(msgset, args, 0, '|', sizeof msgset);
5078 num_msgs = num_tokens(msgset, ',');
5080 cprintf("%d Nothing to do.\n", CIT_OK);
5084 if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
5085 cprintf("%d Higher access required.\n",
5086 ERROR + HIGHER_ACCESS_REQUIRED);
5091 * Build our message set to be moved/copied
5093 msgs = malloc(num_msgs * sizeof(long));
5094 for (i=0; i<num_msgs; ++i) {
5095 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
5096 msgs[i] = atol(msgtok);
5099 num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
5103 cprintf("%d %d message%s deleted.\n", CIT_OK,
5104 num_deleted, ((num_deleted != 1) ? "s" : ""));
5106 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
5114 * move or copy a message to another room
5116 void cmd_move(char *args)
5123 char targ[ROOMNAMELEN];
5124 struct ctdlroom qtemp;
5131 extract_token(msgset, args, 0, '|', sizeof msgset);
5132 num_msgs = num_tokens(msgset, ',');
5134 cprintf("%d Nothing to do.\n", CIT_OK);
5138 extract_token(targ, args, 1, '|', sizeof targ);
5139 convert_room_name_macros(targ, sizeof targ);
5140 targ[ROOMNAMELEN - 1] = 0;
5141 is_copy = extract_int(args, 2);
5143 if (CtdlGetRoom(&qtemp, targ) != 0) {
5144 cprintf("%d '%s' does not exist.\n", ERROR + ROOM_NOT_FOUND, targ);
5148 if (!strcasecmp(qtemp.QRname, CC->room.QRname)) {
5149 cprintf("%d Source and target rooms are the same.\n", ERROR + ALREADY_EXISTS);
5153 CtdlGetUser(&CC->user, CC->curr_user);
5154 CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
5156 /* Check for permission to perform this operation.
5157 * Remember: "CC->room" is source, "qtemp" is target.
5161 /* Admins can move/copy */
5162 if (CC->user.axlevel >= AxAideU) permit = 1;
5164 /* Room aides can move/copy */
5165 if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
5167 /* Permit move/copy from personal rooms */
5168 if ((CC->room.QRflags & QR_MAILBOX)
5169 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5171 /* Permit only copy from public to personal room */
5173 && (!(CC->room.QRflags & QR_MAILBOX))
5174 && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
5176 /* Permit message removal from collaborative delete rooms */
5177 if (CC->room.QRflags2 & QR2_COLLABDEL) permit = 1;
5179 /* Users allowed to post into the target room may move into it too. */
5180 if ((CC->room.QRflags & QR_MAILBOX) &&
5181 (qtemp.QRflags & UA_POSTALLOWED)) permit = 1;
5183 /* User must have access to target room */
5184 if (!(ra & UA_KNOWN)) permit = 0;
5187 cprintf("%d Higher access required.\n",
5188 ERROR + HIGHER_ACCESS_REQUIRED);
5193 * Build our message set to be moved/copied
5195 msgs = malloc(num_msgs * sizeof(long));
5196 for (i=0; i<num_msgs; ++i) {
5197 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
5198 msgs[i] = atol(msgtok);
5204 err = CtdlSaveMsgPointersInRoom(targ, msgs, num_msgs, 1, NULL, 0);
5206 cprintf("%d Cannot store message(s) in %s: error %d\n",
5212 /* Now delete the message from the source room,
5213 * if this is a 'move' rather than a 'copy' operation.
5216 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "");
5220 cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
5226 * GetMetaData() - Get the supplementary record for a message
5228 void GetMetaData(struct MetaData *smibuf, long msgnum)
5231 struct cdbdata *cdbsmi;
5234 memset(smibuf, 0, sizeof(struct MetaData));
5235 smibuf->meta_msgnum = msgnum;
5236 smibuf->meta_refcount = 1; /* Default reference count is 1 */
5238 /* Use the negative of the message number for its supp record index */
5239 TheIndex = (0L - msgnum);
5241 cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
5242 if (cdbsmi == NULL) {
5243 return; /* record not found; go with defaults */
5245 memcpy(smibuf, cdbsmi->ptr,
5246 ((cdbsmi->len > sizeof(struct MetaData)) ?
5247 sizeof(struct MetaData) : cdbsmi->len));
5254 * PutMetaData() - (re)write supplementary record for a message
5256 void PutMetaData(struct MetaData *smibuf)
5260 /* Use the negative of the message number for the metadata db index */
5261 TheIndex = (0L - smibuf->meta_msgnum);
5263 cdb_store(CDB_MSGMAIN,
5264 &TheIndex, (int)sizeof(long),
5265 smibuf, (int)sizeof(struct MetaData));
5270 * AdjRefCount - submit an adjustment to the reference count for a message.
5271 * (These are just queued -- we actually process them later.)
5273 void AdjRefCount(long msgnum, int incr)
5275 struct CitContext *CCC = CC;
5276 struct arcq new_arcq;
5279 MSG_syslog(LOG_DEBUG, "AdjRefCount() msg %ld ref count delta %+d\n", msgnum, incr);
5281 begin_critical_section(S_SUPPMSGMAIN);
5282 if (arcfp == NULL) {
5283 arcfp = fopen(file_arcq, "ab+");
5284 chown(file_arcq, CTDLUID, (-1));
5285 chmod(file_arcq, 0600);
5287 end_critical_section(S_SUPPMSGMAIN);
5289 /* msgnum < 0 means that we're trying to close the file */
5291 MSGM_syslog(LOG_DEBUG, "Closing the AdjRefCount queue file\n");
5292 begin_critical_section(S_SUPPMSGMAIN);
5293 if (arcfp != NULL) {
5297 end_critical_section(S_SUPPMSGMAIN);
5302 * If we can't open the queue, perform the operation synchronously.
5304 if (arcfp == NULL) {
5305 TDAP_AdjRefCount(msgnum, incr);
5309 new_arcq.arcq_msgnum = msgnum;
5310 new_arcq.arcq_delta = incr;
5311 rv = fwrite(&new_arcq, sizeof(struct arcq), 1, arcfp);
5313 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5322 void AdjRefCountList(long *msgnum, long nmsg, int incr)
5324 struct CitContext *CCC = CC;
5325 long i, the_size, offset;
5326 struct arcq *new_arcq;
5329 MSG_syslog(LOG_DEBUG, "AdjRefCountList() msg %ld ref count delta %+d\n", nmsg, incr);
5331 begin_critical_section(S_SUPPMSGMAIN);
5332 if (arcfp == NULL) {
5333 arcfp = fopen(file_arcq, "ab+");
5334 chown(file_arcq, CTDLUID, (-1));
5335 chmod(file_arcq, 0600);
5337 end_critical_section(S_SUPPMSGMAIN);
5340 * If we can't open the queue, perform the operation synchronously.
5342 if (arcfp == NULL) {
5343 for (i = 0; i < nmsg; i++)
5344 TDAP_AdjRefCount(msgnum[i], incr);
5348 the_size = sizeof(struct arcq) * nmsg;
5349 new_arcq = malloc(the_size);
5350 for (i = 0; i < nmsg; i++) {
5351 new_arcq[i].arcq_msgnum = msgnum[i];
5352 new_arcq[i].arcq_delta = incr;
5356 while ((rv >= 0) && (offset < the_size))
5358 rv = fwrite(new_arcq + offset, 1, the_size - offset, arcfp);
5360 MSG_syslog(LOG_EMERG, "Couldn't write Refcount Queue File %s: %s\n",
5376 * TDAP_ProcessAdjRefCountQueue()
5378 * Process the queue of message count adjustments that was created by calls
5379 * to AdjRefCount() ... by reading the queue and calling TDAP_AdjRefCount()
5380 * for each one. This should be an "off hours" operation.
5382 int TDAP_ProcessAdjRefCountQueue(void)
5384 struct CitContext *CCC = CC;
5385 char file_arcq_temp[PATH_MAX];
5388 struct arcq arcq_rec;
5389 int num_records_processed = 0;
5391 snprintf(file_arcq_temp, sizeof file_arcq_temp, "%s.%04x", file_arcq, rand());
5393 begin_critical_section(S_SUPPMSGMAIN);
5394 if (arcfp != NULL) {
5399 r = link(file_arcq, file_arcq_temp);
5401 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5402 end_critical_section(S_SUPPMSGMAIN);
5403 return(num_records_processed);
5407 end_critical_section(S_SUPPMSGMAIN);
5409 fp = fopen(file_arcq_temp, "rb");
5411 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5412 return(num_records_processed);
5415 while (fread(&arcq_rec, sizeof(struct arcq), 1, fp) == 1) {
5416 TDAP_AdjRefCount(arcq_rec.arcq_msgnum, arcq_rec.arcq_delta);
5417 ++num_records_processed;
5421 r = unlink(file_arcq_temp);
5423 MSG_syslog(LOG_CRIT, "%s: %s\n", file_arcq_temp, strerror(errno));
5426 return(num_records_processed);
5432 * TDAP_AdjRefCount - adjust the reference count for a message.
5433 * This one does it "for real" because it's called by
5434 * the autopurger function that processes the queue
5435 * created by AdjRefCount(). If a message's reference
5436 * count becomes zero, we also delete the message from
5437 * disk and de-index it.
5439 void TDAP_AdjRefCount(long msgnum, int incr)
5441 struct CitContext *CCC = CC;
5443 struct MetaData smi;
5446 /* This is a *tight* critical section; please keep it that way, as
5447 * it may get called while nested in other critical sections.
5448 * Complicating this any further will surely cause deadlock!
5450 begin_critical_section(S_SUPPMSGMAIN);
5451 GetMetaData(&smi, msgnum);
5452 smi.meta_refcount += incr;
5454 end_critical_section(S_SUPPMSGMAIN);
5455 MSG_syslog(LOG_DEBUG, "TDAP_AdjRefCount() msg %ld ref count delta %+d, is now %d\n",
5456 msgnum, incr, smi.meta_refcount
5459 /* If the reference count is now zero, delete the message
5460 * (and its supplementary record as well).
5462 if (smi.meta_refcount == 0) {
5463 MSG_syslog(LOG_DEBUG, "Deleting message <%ld>\n", msgnum);
5465 /* Call delete hooks with NULL room to show it has gone altogether */
5466 PerformDeleteHooks(NULL, msgnum);
5468 /* Remove from message base */
5470 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5471 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
5473 /* Remove metadata record */
5474 delnum = (0L - msgnum);
5475 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
5481 * Write a generic object to this room
5483 * Note: this could be much more efficient. Right now we use two temporary
5484 * files, and still pull the message into memory as with all others.
5486 void CtdlWriteObject(char *req_room, /* Room to stuff it in */
5487 char *content_type, /* MIME type of this object */
5488 char *raw_message, /* Data to be written */
5489 off_t raw_length, /* Size of raw_message */
5490 struct ctdluser *is_mailbox, /* Mailbox room? */
5491 int is_binary, /* Is encoding necessary? */
5492 int is_unique, /* Del others of this type? */
5493 unsigned int flags /* Internal save flags */
5496 struct CitContext *CCC = CC;
5497 struct ctdlroom qrbuf;
5498 char roomname[ROOMNAMELEN];
5499 struct CtdlMessage *msg;
5500 char *encoded_message = NULL;
5502 if (is_mailbox != NULL) {
5503 CtdlMailboxName(roomname, sizeof roomname, is_mailbox, req_room);
5506 safestrncpy(roomname, req_room, sizeof(roomname));
5509 MSG_syslog(LOG_DEBUG, "Raw length is %ld\n", (long)raw_length);
5512 encoded_message = malloc((size_t) (((raw_length * 134) / 100) + 4096 ) );
5515 encoded_message = malloc((size_t)(raw_length + 4096));
5518 sprintf(encoded_message, "Content-type: %s\n", content_type);
5521 sprintf(&encoded_message[strlen(encoded_message)],
5522 "Content-transfer-encoding: base64\n\n"
5526 sprintf(&encoded_message[strlen(encoded_message)],
5527 "Content-transfer-encoding: 7bit\n\n"
5533 &encoded_message[strlen(encoded_message)],
5541 &encoded_message[strlen(encoded_message)],
5547 MSGM_syslog(LOG_DEBUG, "Allocating\n");
5548 msg = malloc(sizeof(struct CtdlMessage));
5549 memset(msg, 0, sizeof(struct CtdlMessage));
5550 msg->cm_magic = CTDLMESSAGE_MAGIC;
5551 msg->cm_anon_type = MES_NORMAL;
5552 msg->cm_format_type = 4;
5553 msg->cm_fields[eAuthor] = strdup(CCC->user.fullname);
5554 msg->cm_fields[eOriginalRoom] = strdup(req_room);
5555 msg->cm_fields[eNodeName] = strdup(config.c_nodename);
5556 msg->cm_fields[eHumanNode] = strdup(config.c_humannode);
5557 msg->cm_flags = flags;
5559 msg->cm_fields[eMesageText] = encoded_message;
5561 /* Create the requested room if we have to. */
5562 if (CtdlGetRoom(&qrbuf, roomname) != 0) {
5563 CtdlCreateRoom(roomname,
5564 ( (is_mailbox != NULL) ? 5 : 3 ),
5565 "", 0, 1, 0, VIEW_BBS);
5567 /* If the caller specified this object as unique, delete all
5568 * other objects of this type that are currently in the room.
5571 MSG_syslog(LOG_DEBUG, "Deleted %d other msgs of this type\n",
5572 CtdlDeleteMessages(roomname, NULL, 0, content_type)
5575 /* Now write the data */
5576 CtdlSubmitMsg(msg, NULL, roomname, 0);
5585 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
5586 config_msgnum = msgnum;
5590 char *CtdlGetSysConfig(char *sysconfname) {
5591 char hold_rm[ROOMNAMELEN];
5594 struct CtdlMessage *msg;
5597 strcpy(hold_rm, CC->room.QRname);
5598 if (CtdlGetRoom(&CC->room, SYSCONFIGROOM) != 0) {
5599 CtdlGetRoom(&CC->room, hold_rm);
5604 /* We want the last (and probably only) config in this room */
5605 begin_critical_section(S_CONFIG);
5606 config_msgnum = (-1L);
5607 CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
5608 CtdlGetSysConfigBackend, NULL);
5609 msgnum = config_msgnum;
5610 end_critical_section(S_CONFIG);
5616 msg = CtdlFetchMessage(msgnum, 1);
5618 conf = strdup(msg->cm_fields[eMesageText]);
5626 CtdlGetRoom(&CC->room, hold_rm);
5628 if (conf != NULL) do {
5629 extract_token(buf, conf, 0, '\n', sizeof buf);
5630 strcpy(conf, &conf[strlen(buf)+1]);
5631 } while ( (!IsEmptyStr(conf)) && (!IsEmptyStr(buf)) );
5637 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
5638 CtdlWriteObject(SYSCONFIGROOM, sysconfname, sysconfdata, (strlen(sysconfdata)+1), NULL, 0, 1, 0);
5643 * Determine whether a given Internet address belongs to the current user
5645 int CtdlIsMe(char *addr, int addr_buf_len)
5647 struct recptypes *recp;
5650 recp = validate_recipients(addr, NULL, 0);
5651 if (recp == NULL) return(0);
5653 if (recp->num_local == 0) {
5654 free_recipients(recp);
5658 for (i=0; i<recp->num_local; ++i) {
5659 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
5660 if (!strcasecmp(addr, CC->user.fullname)) {
5661 free_recipients(recp);
5666 free_recipients(recp);
5672 * Citadel protocol command to do the same
5674 void cmd_isme(char *argbuf) {
5677 if (CtdlAccessCheck(ac_logged_in)) return;
5678 extract_token(addr, argbuf, 0, '|', sizeof addr);
5680 if (CtdlIsMe(addr, sizeof addr)) {
5681 cprintf("%d %s\n", CIT_OK, addr);
5684 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);
5690 /*****************************************************************************/
5691 /* MODULE INITIALIZATION STUFF */
5692 /*****************************************************************************/
5693 void SetMessageDebugEnabled(const int n)
5695 MessageDebugEnabled = n;
5697 CTDL_MODULE_INIT(msgbase)
5700 CtdlRegisterDebugFlagHook(HKEY("messages"), SetMessageDebugEnabled, &MessageDebugEnabled);
5702 CtdlRegisterProtoHook(cmd_msgs, "MSGS", "Output a list of messages in the current room");
5703 CtdlRegisterProtoHook(cmd_msg0, "MSG0", "Output a message in plain text format");
5704 CtdlRegisterProtoHook(cmd_msg2, "MSG2", "Output a message in RFC822 format");
5705 CtdlRegisterProtoHook(cmd_msg3, "MSG3", "Output a message in raw format (deprecated)");
5706 CtdlRegisterProtoHook(cmd_msg4, "MSG4", "Output a message in the client's preferred format");
5707 CtdlRegisterProtoHook(cmd_msgp, "MSGP", "Select preferred format for MSG4 output");
5708 CtdlRegisterProtoHook(cmd_opna, "OPNA", "Open an attachment for download");
5709 CtdlRegisterProtoHook(cmd_dlat, "DLAT", "Download an attachment");
5710 CtdlRegisterProtoHook(cmd_ent0, "ENT0", "Enter a message");
5711 CtdlRegisterProtoHook(cmd_dele, "DELE", "Delete a message");
5712 CtdlRegisterProtoHook(cmd_move, "MOVE", "Move or copy a message to another room");
5713 CtdlRegisterProtoHook(cmd_isme, "ISME", "Determine whether an email address belongs to a user");
5716 /* return our Subversion id for the Log */