]> code.citadel.org Git - citadel.git/blob - citadel/msgbase.c
c7b7ce6b891c2a22ac0bcdd91dd875cf738b1991
[citadel.git] / citadel / msgbase.c
1 /*
2  * $Id$
3  *
4  * Implements the message store.
5  *
6  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13
14 #if TIME_WITH_SYS_TIME
15 # include <sys/time.h>
16 # include <time.h>
17 #else
18 # if HAVE_SYS_TIME_H
19 #  include <sys/time.h>
20 # else
21 #  include <time.h>
22 # endif
23 #endif
24
25
26 #include <ctype.h>
27 #include <string.h>
28 #include <limits.h>
29 #include <errno.h>
30 #include <stdarg.h>
31 #include <sys/stat.h>
32 #include "citadel.h"
33 #include "server.h"
34 #include "serv_extensions.h"
35 #include "database.h"
36 #include "msgbase.h"
37 #include "support.h"
38 #include "sysdep_decls.h"
39 #include "citserver.h"
40 #include "room_ops.h"
41 #include "user_ops.h"
42 #include "file_ops.h"
43 #include "config.h"
44 #include "control.h"
45 #include "tools.h"
46 #include "mime_parser.h"
47 #include "html.h"
48 #include "genstamp.h"
49 #include "internet_addressing.h"
50 #include "serv_fulltext.h"
51 #include "vcard.h"
52 #include "euidindex.h"
53 #include "journaling.h"
54 #include "citadel_dirs.h"
55 #include "serv_network.h"
56
57 #ifdef HAVE_LIBSIEVE
58 # include "serv_sieve.h"
59 #endif /* HAVE_LIBSIEVE */
60
61 long config_msgnum;
62 struct addresses_to_be_filed *atbf = NULL;
63
64 /* 
65  * This really belongs in serv_network.c, but I don't know how to export
66  * symbols between modules.
67  */
68 struct FilterList *filterlist = NULL;
69
70
71 /*
72  * These are the four-character field headers we use when outputting
73  * messages in Citadel format (as opposed to RFC822 format).
74  */
75 char *msgkeys[] = {
76         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
77         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
78         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
79         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
80         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
81         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
82         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
83         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
84         NULL, 
85         "from",
86         NULL, NULL, NULL,
87         "exti",
88         "rfca",
89         NULL, 
90         "hnod",
91         "msgn",
92         "jrnl",
93         NULL, NULL,
94         "text",
95         "node",
96         "room",
97         "path",
98         NULL,
99         "rcpt",
100         "spec",
101         "time",
102         "subj",
103         NULL,
104         NULL,
105         NULL,
106         "cccc",
107         NULL
108 };
109
110 /*
111  * This function is self explanatory.
112  * (What can I say, I'm in a weird mood today...)
113  */
114 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
115 {
116         int i;
117
118         for (i = 0; i < strlen(name); ++i) {
119                 if (name[i] == '@') {
120                         while (isspace(name[i - 1]) && i > 0) {
121                                 strcpy(&name[i - 1], &name[i]);
122                                 --i;
123                         }
124                         while (isspace(name[i + 1])) {
125                                 strcpy(&name[i + 1], &name[i + 2]);
126                         }
127                 }
128         }
129 }
130
131
132 /*
133  * Aliasing for network mail.
134  * (Error messages have been commented out, because this is a server.)
135  */
136 int alias(char *name)
137 {                               /* process alias and routing info for mail */
138         FILE *fp;
139         int a, i;
140         char aaa[SIZ], bbb[SIZ];
141         char *ignetcfg = NULL;
142         char *ignetmap = NULL;
143         int at = 0;
144         char node[64];
145         char testnode[64];
146         char buf[SIZ];
147
148         striplt(name);
149         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
150         stripallbut(name, '<', '>');
151
152         fp = fopen(file_mail_aliases, "r");
153         if (fp == NULL) {
154                 fp = fopen("/dev/null", "r");
155         }
156         if (fp == NULL) {
157                 return (MES_ERROR);
158         }
159         strcpy(aaa, "");
160         strcpy(bbb, "");
161         while (fgets(aaa, sizeof aaa, fp) != NULL) {
162                 while (isspace(name[0]))
163                         strcpy(name, &name[1]);
164                 aaa[strlen(aaa) - 1] = 0;
165                 strcpy(bbb, "");
166                 for (a = 0; a < strlen(aaa); ++a) {
167                         if (aaa[a] == ',') {
168                                 strcpy(bbb, &aaa[a + 1]);
169                                 aaa[a] = 0;
170                         }
171                 }
172                 if (!strcasecmp(name, aaa))
173                         strcpy(name, bbb);
174         }
175         fclose(fp);
176
177         /* Hit the Global Address Book */
178         if (CtdlDirectoryLookup(aaa, name, sizeof aaa) == 0) {
179                 strcpy(name, aaa);
180         }
181
182         lprintf(CTDL_INFO, "Mail is being forwarded to %s\n", name);
183
184         /* Change "user @ xxx" to "user" if xxx is an alias for this host */
185         for (a=0; a<strlen(name); ++a) {
186                 if (name[a] == '@') {
187                         if (CtdlHostAlias(&name[a+1]) == hostalias_localhost) {
188                                 name[a] = 0;
189                                 lprintf(CTDL_INFO, "Changed to <%s>\n", name);
190                         }
191                 }
192         }
193
194         /* determine local or remote type, see citadel.h */
195         at = haschar(name, '@');
196         if (at == 0) return(MES_LOCAL);         /* no @'s - local address */
197         if (at > 1) return(MES_ERROR);          /* >1 @'s - invalid address */
198         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
199
200         /* figure out the delivery mode */
201         extract_token(node, name, 1, '@', sizeof node);
202
203         /* If there are one or more dots in the nodename, we assume that it
204          * is an FQDN and will attempt SMTP delivery to the Internet.
205          */
206         if (haschar(node, '.') > 0) {
207                 return(MES_INTERNET);
208         }
209
210         /* Otherwise we look in the IGnet maps for a valid Citadel node.
211          * Try directly-connected nodes first...
212          */
213         ignetcfg = CtdlGetSysConfig(IGNETCFG);
214         for (i=0; i<num_tokens(ignetcfg, '\n'); ++i) {
215                 extract_token(buf, ignetcfg, i, '\n', sizeof buf);
216                 extract_token(testnode, buf, 0, '|', sizeof testnode);
217                 if (!strcasecmp(node, testnode)) {
218                         free(ignetcfg);
219                         return(MES_IGNET);
220                 }
221         }
222         free(ignetcfg);
223
224         /*
225          * Then try nodes that are two or more hops away.
226          */
227         ignetmap = CtdlGetSysConfig(IGNETMAP);
228         for (i=0; i<num_tokens(ignetmap, '\n'); ++i) {
229                 extract_token(buf, ignetmap, i, '\n', sizeof buf);
230                 extract_token(testnode, buf, 0, '|', sizeof testnode);
231                 if (!strcasecmp(node, testnode)) {
232                         free(ignetmap);
233                         return(MES_IGNET);
234                 }
235         }
236         free(ignetmap);
237
238         /* If we get to this point it's an invalid node name */
239         return (MES_ERROR);
240 }
241
242
243 void get_mm(void)
244 {
245         FILE *fp;
246
247         fp = fopen(file_citadel_control, "r");
248         if (fp == NULL) {
249                 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
250                                 file_citadel_control,
251                                 strerror(errno));
252                 exit(errno);
253         }
254         fread((char *) &CitControl, sizeof(struct CitControl), 1, fp);
255         fclose(fp);
256 }
257
258
259 /*
260  * Back end for the MSGS command: output message number only.
261  */
262 void simple_listing(long msgnum, void *userdata)
263 {
264         cprintf("%ld\n", msgnum);
265 }
266
267
268
269 /*
270  * Back end for the MSGS command: output header summary.
271  */
272 void headers_listing(long msgnum, void *userdata)
273 {
274         struct CtdlMessage *msg;
275
276         msg = CtdlFetchMessage(msgnum, 0);
277         if (msg == NULL) {
278                 cprintf("%ld|0|||||\n", msgnum);
279                 return;
280         }
281
282         cprintf("%ld|%s|%s|%s|%s|%s|\n",
283                 msgnum,
284                 (msg->cm_fields['T'] ? msg->cm_fields['T'] : "0"),
285                 (msg->cm_fields['A'] ? msg->cm_fields['A'] : ""),
286                 (msg->cm_fields['N'] ? msg->cm_fields['N'] : ""),
287                 (msg->cm_fields['F'] ? msg->cm_fields['F'] : ""),
288                 (msg->cm_fields['U'] ? msg->cm_fields['U'] : "")
289         );
290         CtdlFreeMessage(msg);
291 }
292
293
294
295 /* Determine if a given message matches the fields in a message template.
296  * Return 0 for a successful match.
297  */
298 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
299         int i;
300
301         /* If there aren't any fields in the template, all messages will
302          * match.
303          */
304         if (template == NULL) return(0);
305
306         /* Null messages are bogus. */
307         if (msg == NULL) return(1);
308
309         for (i='A'; i<='Z'; ++i) {
310                 if (template->cm_fields[i] != NULL) {
311                         if (msg->cm_fields[i] == NULL) {
312                                 return 1;
313                         }
314                         if (strcasecmp(msg->cm_fields[i],
315                                 template->cm_fields[i])) return 1;
316                 }
317         }
318
319         /* All compares succeeded: we have a match! */
320         return 0;
321 }
322
323
324
325 /*
326  * Retrieve the "seen" message list for the current room.
327  */
328 void CtdlGetSeen(char *buf, int which_set) {
329         struct visit vbuf;
330
331         /* Learn about the user and room in question */
332         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
333
334         if (which_set == ctdlsetseen_seen)
335                 safestrncpy(buf, vbuf.v_seen, SIZ);
336         if (which_set == ctdlsetseen_answered)
337                 safestrncpy(buf, vbuf.v_answered, SIZ);
338 }
339
340
341
342 /*
343  * Manipulate the "seen msgs" string (or other message set strings)
344  */
345 void CtdlSetSeen(long *target_msgnums, int num_target_msgnums,
346                 int target_setting, int which_set,
347                 struct ctdluser *which_user, struct ctdlroom *which_room) {
348         struct cdbdata *cdbfr;
349         int i, j, k;
350         int is_seen = 0;
351         int was_seen = 0;
352         long lo = (-1L);
353         long hi = (-1L);
354         long t = (-1L);
355         int trimming = 0;
356         struct visit vbuf;
357         long *msglist;
358         int num_msgs = 0;
359         char vset[SIZ];
360         char *is_set;   /* actually an array of booleans */
361         int num_sets;
362         int s;
363         char setstr[SIZ], lostr[SIZ], histr[SIZ];
364         size_t tmp;
365
366         /* Don't bother doing *anything* if we were passed a list of zero messages */
367         if (num_target_msgnums < 1) {
368                 return;
369         }
370
371         lprintf(CTDL_DEBUG, "CtdlSetSeen(%d msgs starting with %ld, %d, %d)\n",
372                 num_target_msgnums, target_msgnums[0],
373                 target_setting, which_set);
374
375         /* Learn about the user and room in question */
376         CtdlGetRelationship(&vbuf,
377                 ((which_user != NULL) ? which_user : &CC->user),
378                 ((which_room != NULL) ? which_room : &CC->room)
379         );
380
381         /* Load the message list */
382         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
383         if (cdbfr != NULL) {
384                 msglist = (long *) cdbfr->ptr;
385                 cdbfr->ptr = NULL;      /* CtdlSetSeen() now owns this memory */
386                 num_msgs = cdbfr->len / sizeof(long);
387                 cdb_free(cdbfr);
388         } else {
389                 return; /* No messages at all?  No further action. */
390         }
391
392         is_set = malloc(num_msgs * sizeof(char));
393         memset(is_set, 0, (num_msgs * sizeof(char)) );
394
395         /* Decide which message set we're manipulating */
396         switch(which_set) {
397                 case ctdlsetseen_seen:
398                         safestrncpy(vset, vbuf.v_seen, sizeof vset);
399                         break;
400                 case ctdlsetseen_answered:
401                         safestrncpy(vset, vbuf.v_answered, sizeof vset);
402                         break;
403         }
404
405         /* lprintf(CTDL_DEBUG, "before optimize: %s\n", vset); */
406
407         /* Translate the existing sequence set into an array of booleans */
408         num_sets = num_tokens(vset, ',');
409         for (s=0; s<num_sets; ++s) {
410                 extract_token(setstr, vset, s, ',', sizeof setstr);
411
412                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
413                 if (num_tokens(setstr, ':') >= 2) {
414                         extract_token(histr, setstr, 1, ':', sizeof histr);
415                         if (!strcmp(histr, "*")) {
416                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
417                         }
418                 }
419                 else {
420                         strcpy(histr, lostr);
421                 }
422                 lo = atol(lostr);
423                 hi = atol(histr);
424
425                 for (i = 0; i < num_msgs; ++i) {
426                         if ((msglist[i] >= lo) && (msglist[i] <= hi)) {
427                                 is_set[i] = 1;
428                         }
429                 }
430         }
431
432         /* Now translate the array of booleans back into a sequence set */
433         strcpy(vset, "");
434         lo = (-1L);
435         hi = (-1L);
436
437         for (i=0; i<num_msgs; ++i) {
438
439                 is_seen = is_set[i];    /* Default to existing setting */
440
441                 for (k=0; k<num_target_msgnums; ++k) {
442                         if (msglist[i] == target_msgnums[k]) {
443                                 is_seen = target_setting;
444                         }
445                 }
446
447                 if (is_seen) {
448                         if (lo < 0L) lo = msglist[i];
449                         hi = msglist[i];
450                 }
451
452                 if (  ((is_seen == 0) && (was_seen == 1))
453                    || ((is_seen == 1) && (i == num_msgs-1)) ) {
454
455                         /* begin trim-o-matic code */
456                         j=9;
457                         trimming = 0;
458                         while ( (strlen(vset) + 20) > sizeof vset) {
459                                 remove_token(vset, 0, ',');
460                                 trimming = 1;
461                                 if (j--) break; /* loop no more than 9 times */
462                         }
463                         if ( (trimming) && (which_set == ctdlsetseen_seen) ) {
464                                 t = atol(vset);
465                                 if (t<2) t=2;
466                                 --t;
467                                 snprintf(lostr, sizeof lostr,
468                                         "1:%ld,%s", t, vset);
469                                 safestrncpy(vset, lostr, sizeof vset);
470                         }
471                         /* end trim-o-matic code */
472
473                         tmp = strlen(vset);
474                         if (tmp > 0) {
475                                 strcat(vset, ",");
476                                 ++tmp;
477                         }
478                         if (lo == hi) {
479                                 snprintf(&vset[tmp], (sizeof vset) - tmp,
480                                          "%ld", lo);
481                         }
482                         else {
483                                 snprintf(&vset[tmp], (sizeof vset) - tmp,
484                                          "%ld:%ld", lo, hi);
485                         }
486                         lo = (-1L);
487                         hi = (-1L);
488                 }
489                 was_seen = is_seen;
490         }
491
492         /* Decide which message set we're manipulating */
493         switch (which_set) {
494                 case ctdlsetseen_seen:
495                         safestrncpy(vbuf.v_seen, vset, sizeof vbuf.v_seen);
496                         break;
497                 case ctdlsetseen_answered:
498                         safestrncpy(vbuf.v_answered, vset,
499                                                 sizeof vbuf.v_answered);
500                         break;
501         }
502         free(is_set);
503
504         /* lprintf(CTDL_DEBUG, " after optimize: %s\n", vset); */
505         free(msglist);
506         CtdlSetRelationship(&vbuf,
507                 ((which_user != NULL) ? which_user : &CC->user),
508                 ((which_room != NULL) ? which_room : &CC->room)
509         );
510 }
511
512
513 /*
514  * API function to perform an operation for each qualifying message in the
515  * current room.  (Returns the number of messages processed.)
516  */
517 int CtdlForEachMessage(int mode, long ref, char *search_string,
518                         char *content_type,
519                         struct CtdlMessage *compare,
520                         void (*CallBack) (long, void *),
521                         void *userdata)
522 {
523
524         int a, i, j;
525         struct visit vbuf;
526         struct cdbdata *cdbfr;
527         long *msglist = NULL;
528         int num_msgs = 0;
529         int num_processed = 0;
530         long thismsg;
531         struct MetaData smi;
532         struct CtdlMessage *msg;
533         int is_seen = 0;
534         long lastold = 0L;
535         int printed_lastold = 0;
536         int num_search_msgs = 0;
537         long *search_msgs = NULL;
538
539         /* Learn about the user and room in question */
540         get_mm();
541         getuser(&CC->user, CC->curr_user);
542         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
543
544         /* Load the message list */
545         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
546         if (cdbfr != NULL) {
547                 msglist = (long *) cdbfr->ptr;
548                 cdbfr->ptr = NULL;      /* CtdlForEachMessage() now owns this memory */
549                 num_msgs = cdbfr->len / sizeof(long);
550                 cdb_free(cdbfr);
551         } else {
552                 return 0;       /* No messages at all?  No further action. */
553         }
554
555
556         /*
557          * Now begin the traversal.
558          */
559         if (num_msgs > 0) for (a = 0; a < num_msgs; ++a) {
560
561                 /* If the caller is looking for a specific MIME type, filter
562                  * out all messages which are not of the type requested.
563                  */
564                 if (content_type != NULL) if (strlen(content_type) > 0) {
565
566                         /* This call to GetMetaData() sits inside this loop
567                          * so that we only do the extra database read per msg
568                          * if we need to.  Doing the extra read all the time
569                          * really kills the server.  If we ever need to use
570                          * metadata for another search criterion, we need to
571                          * move the read somewhere else -- but still be smart
572                          * enough to only do the read if the caller has
573                          * specified something that will need it.
574                          */
575                         GetMetaData(&smi, msglist[a]);
576
577                         if (strcasecmp(smi.meta_content_type, content_type)) {
578                                 msglist[a] = 0L;
579                         }
580                 }
581         }
582
583         num_msgs = sort_msglist(msglist, num_msgs);
584
585         /* If a template was supplied, filter out the messages which
586          * don't match.  (This could induce some delays!)
587          */
588         if (num_msgs > 0) {
589                 if (compare != NULL) {
590                         for (a = 0; a < num_msgs; ++a) {
591                                 msg = CtdlFetchMessage(msglist[a], 1);
592                                 if (msg != NULL) {
593                                         if (CtdlMsgCmp(msg, compare)) {
594                                                 msglist[a] = 0L;
595                                         }
596                                         CtdlFreeMessage(msg);
597                                 }
598                         }
599                 }
600         }
601
602         /* If a search string was specified, get a message list from
603          * the full text index and remove messages which aren't on both
604          * lists.
605          *
606          * How this works:
607          * Since the lists are sorted and strictly ascending, and the
608          * output list is guaranteed to be shorter than or equal to the
609          * input list, we overwrite the bottom of the input list.  This
610          * eliminates the need to memmove big chunks of the list over and
611          * over again.
612          */
613         if ( (num_msgs > 0) && (mode == MSGS_SEARCH) && (search_string) ) {
614                 ft_search(&num_search_msgs, &search_msgs, search_string);
615                 if (num_search_msgs > 0) {
616         
617                         int orig_num_msgs;
618
619                         orig_num_msgs = num_msgs;
620                         num_msgs = 0;
621                         for (i=0; i<orig_num_msgs; ++i) {
622                                 for (j=0; j<num_search_msgs; ++j) {
623                                         if (msglist[i] == search_msgs[j]) {
624                                                 msglist[num_msgs++] = msglist[i];
625                                         }
626                                 }
627                         }
628                 }
629                 else {
630                         num_msgs = 0;   /* No messages qualify */
631                 }
632                 if (search_msgs != NULL) free(search_msgs);
633
634                 /* Now that we've purged messages which don't contain the search
635                  * string, treat a MSGS_SEARCH just like a MSGS_ALL from this
636                  * point on.
637                  */
638                 mode = MSGS_ALL;
639         }
640
641         /*
642          * Now iterate through the message list, according to the
643          * criteria supplied by the caller.
644          */
645         if (num_msgs > 0)
646                 for (a = 0; a < num_msgs; ++a) {
647                         thismsg = msglist[a];
648                         if (mode == MSGS_ALL) {
649                                 is_seen = 0;
650                         }
651                         else {
652                                 is_seen = is_msg_in_sequence_set(
653                                                         vbuf.v_seen, thismsg);
654                                 if (is_seen) lastold = thismsg;
655                         }
656                         if ((thismsg > 0L)
657                             && (
658
659                                        (mode == MSGS_ALL)
660                                        || ((mode == MSGS_OLD) && (is_seen))
661                                        || ((mode == MSGS_NEW) && (!is_seen))
662                                        || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
663                                    || ((mode == MSGS_FIRST) && (a < ref))
664                                 || ((mode == MSGS_GT) && (thismsg > ref))
665                                 || ((mode == MSGS_EQ) && (thismsg == ref))
666                             )
667                             ) {
668                                 if ((mode == MSGS_NEW) && (CC->user.flags & US_LASTOLD) && (lastold > 0L) && (printed_lastold == 0) && (!is_seen)) {
669                                         if (CallBack)
670                                                 CallBack(lastold, userdata);
671                                         printed_lastold = 1;
672                                         ++num_processed;
673                                 }
674                                 if (CallBack) CallBack(thismsg, userdata);
675                                 ++num_processed;
676                         }
677                 }
678         free(msglist);          /* Clean up */
679         return num_processed;
680 }
681
682
683
684 /*
685  * cmd_msgs()  -  get list of message #'s in this room
686  *              implements the MSGS server command using CtdlForEachMessage()
687  */
688 void cmd_msgs(char *cmdbuf)
689 {
690         int mode = 0;
691         char which[16];
692         char buf[256];
693         char tfield[256];
694         char tvalue[256];
695         int cm_ref = 0;
696         int i;
697         int with_template = 0;
698         struct CtdlMessage *template = NULL;
699         int with_headers = 0;
700         char search_string[1024];
701
702         extract_token(which, cmdbuf, 0, '|', sizeof which);
703         cm_ref = extract_int(cmdbuf, 1);
704         extract_token(search_string, cmdbuf, 1, '|', sizeof search_string);
705         with_template = extract_int(cmdbuf, 2);
706         with_headers = extract_int(cmdbuf, 3);
707
708         strcat(which, "   ");
709         if (!strncasecmp(which, "OLD", 3))
710                 mode = MSGS_OLD;
711         else if (!strncasecmp(which, "NEW", 3))
712                 mode = MSGS_NEW;
713         else if (!strncasecmp(which, "FIRST", 5))
714                 mode = MSGS_FIRST;
715         else if (!strncasecmp(which, "LAST", 4))
716                 mode = MSGS_LAST;
717         else if (!strncasecmp(which, "GT", 2))
718                 mode = MSGS_GT;
719         else if (!strncasecmp(which, "SEARCH", 6))
720                 mode = MSGS_SEARCH;
721         else
722                 mode = MSGS_ALL;
723
724         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
725                 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
726                 return;
727         }
728
729         if ( (mode == MSGS_SEARCH) && (!config.c_enable_fulltext) ) {
730                 cprintf("%d Full text index is not enabled on this server.\n",
731                         ERROR + CMD_NOT_SUPPORTED);
732                 return;
733         }
734
735         if (with_template) {
736                 unbuffer_output();
737                 cprintf("%d Send template then receive message list\n",
738                         START_CHAT_MODE);
739                 template = (struct CtdlMessage *)
740                         malloc(sizeof(struct CtdlMessage));
741                 memset(template, 0, sizeof(struct CtdlMessage));
742                 while(client_getln(buf, sizeof buf), strcmp(buf,"000")) {
743                         extract_token(tfield, buf, 0, '|', sizeof tfield);
744                         extract_token(tvalue, buf, 1, '|', sizeof tvalue);
745                         for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
746                                 if (!strcasecmp(tfield, msgkeys[i])) {
747                                         template->cm_fields[i] =
748                                                 strdup(tvalue);
749                                 }
750                         }
751                 }
752                 buffer_output();
753         }
754         else {
755                 cprintf("%d  \n", LISTING_FOLLOWS);
756         }
757
758         CtdlForEachMessage(mode,
759                         ( (mode == MSGS_SEARCH) ? 0 : cm_ref ),
760                         ( (mode == MSGS_SEARCH) ? search_string : NULL ),
761                         NULL,
762                         template,
763                         (with_headers ? headers_listing : simple_listing),
764                         NULL
765         );
766         if (template != NULL) CtdlFreeMessage(template);
767         cprintf("000\n");
768 }
769
770
771
772
773 /* 
774  * help_subst()  -  support routine for help file viewer
775  */
776 void help_subst(char *strbuf, char *source, char *dest)
777 {
778         char workbuf[SIZ];
779         int p;
780
781         while (p = pattern2(strbuf, source), (p >= 0)) {
782                 strcpy(workbuf, &strbuf[p + strlen(source)]);
783                 strcpy(&strbuf[p], dest);
784                 strcat(strbuf, workbuf);
785         }
786 }
787
788
789 void do_help_subst(char *buffer)
790 {
791         char buf2[16];
792
793         help_subst(buffer, "^nodename", config.c_nodename);
794         help_subst(buffer, "^humannode", config.c_humannode);
795         help_subst(buffer, "^fqdn", config.c_fqdn);
796         help_subst(buffer, "^username", CC->user.fullname);
797         snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
798         help_subst(buffer, "^usernum", buf2);
799         help_subst(buffer, "^sysadm", config.c_sysadm);
800         help_subst(buffer, "^variantname", CITADEL);
801         snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
802         help_subst(buffer, "^maxsessions", buf2);
803         help_subst(buffer, "^bbsdir", ctdl_bbsbase_dir);
804 }
805
806
807
808 /*
809  * memfmout()  -  Citadel text formatter and paginator.
810  *           Although the original purpose of this routine was to format
811  *           text to the reader's screen width, all we're really using it
812  *           for here is to format text out to 80 columns before sending it
813  *           to the client.  The client software may reformat it again.
814  */
815 void memfmout(
816         char *mptr,             /* where are we going to get our text from? */
817         char subst,             /* nonzero if we should do substitutions */
818         char *nl)               /* string to terminate lines with */
819 {
820         int a, b, c;
821         int real = 0;
822         int old = 0;
823         cit_uint8_t ch;
824         char aaa[140];
825         char buffer[SIZ];
826         static int width = 80;
827
828         strcpy(aaa, "");
829         old = 255;
830         strcpy(buffer, "");
831         c = 1;                  /* c is the current pos */
832
833         do {
834                 if (subst) {
835                         while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
836                                 ch = *mptr++;
837                                 buffer[strlen(buffer) + 1] = 0;
838                                 buffer[strlen(buffer)] = ch;
839                         }
840
841                         if (buffer[0] == '^')
842                                 do_help_subst(buffer);
843
844                         buffer[strlen(buffer) + 1] = 0;
845                         a = buffer[0];
846                         strcpy(buffer, &buffer[1]);
847                 } else {
848                         ch = *mptr++;
849                 }
850
851                 old = real;
852                 real = ch;
853
854                 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10)) {
855                         ch = 32;
856                 }
857                 if (((old == 13) || (old == 10)) && (isspace(real))) {
858                         cprintf("%s", nl);
859                         c = 1;
860                 }
861                 if (ch > 32) {
862                         if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
863                                 cprintf("%s%s", nl, aaa);
864                                 c = strlen(aaa);
865                                 aaa[0] = 0;
866                         }
867                         b = strlen(aaa);
868                         aaa[b] = ch;
869                         aaa[b + 1] = 0;
870                 }
871                 if (ch == 32) {
872                         if ((strlen(aaa) + c) > (width - 5)) {
873                                 cprintf("%s", nl);
874                                 c = 1;
875                         }
876                         cprintf("%s ", aaa);
877                         ++c;
878                         c = c + strlen(aaa);
879                         strcpy(aaa, "");
880                 }
881                 if ((ch == 13) || (ch == 10)) {
882                         cprintf("%s%s", aaa, nl);
883                         c = 1;
884                         strcpy(aaa, "");
885                 }
886
887         } while (ch > 0);
888
889         cprintf("%s%s", aaa, nl);
890 }
891
892
893
894 /*
895  * Callback function for mime parser that simply lists the part
896  */
897 void list_this_part(char *name, char *filename, char *partnum, char *disp,
898                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
899                     void *cbuserdata)
900 {
901         struct ma_info *ma;
902         
903         ma = (struct ma_info *)cbuserdata;
904         if (ma->is_ma == 0) {
905                 cprintf("part=%s|%s|%s|%s|%s|%ld\n",
906                         name, filename, partnum, disp, cbtype, (long)length);
907         }
908 }
909
910 /* 
911  * Callback function for multipart prefix
912  */
913 void list_this_pref(char *name, char *filename, char *partnum, char *disp,
914                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
915                     void *cbuserdata)
916 {
917         struct ma_info *ma;
918         
919         ma = (struct ma_info *)cbuserdata;
920         if (!strcasecmp(cbtype, "multipart/alternative")) {
921                 ++ma->is_ma;
922         }
923
924         if (ma->is_ma == 0) {
925                 cprintf("pref=%s|%s\n", partnum, cbtype);
926         }
927 }
928
929 /* 
930  * Callback function for multipart sufffix
931  */
932 void list_this_suff(char *name, char *filename, char *partnum, char *disp,
933                     void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
934                     void *cbuserdata)
935 {
936         struct ma_info *ma;
937         
938         ma = (struct ma_info *)cbuserdata;
939         if (ma->is_ma == 0) {
940                 cprintf("suff=%s|%s\n", partnum, cbtype);
941         }
942         if (!strcasecmp(cbtype, "multipart/alternative")) {
943                 --ma->is_ma;
944         }
945 }
946
947
948 /*
949  * Callback function for mime parser that opens a section for downloading
950  */
951 void mime_download(char *name, char *filename, char *partnum, char *disp,
952                    void *content, char *cbtype, char *cbcharset, size_t length,
953                    char *encoding, void *cbuserdata)
954 {
955
956         /* Silently go away if there's already a download open... */
957         if (CC->download_fp != NULL)
958                 return;
959
960         /* ...or if this is not the desired section */
961         if (strcasecmp(CC->download_desired_section, partnum))
962                 return;
963
964         CC->download_fp = tmpfile();
965         if (CC->download_fp == NULL)
966                 return;
967
968         fwrite(content, length, 1, CC->download_fp);
969         fflush(CC->download_fp);
970         rewind(CC->download_fp);
971
972         OpenCmdResult(filename, cbtype);
973 }
974
975
976
977 /*
978  * Callback function for mime parser that outputs a section all at once
979  */
980 void mime_spew_section(char *name, char *filename, char *partnum, char *disp,
981                    void *content, char *cbtype, char *cbcharset, size_t length,
982                    char *encoding, void *cbuserdata)
983 {
984         int *found_it = (int *)cbuserdata;
985
986         /* ...or if this is not the desired section */
987         if (strcasecmp(CC->download_desired_section, partnum))
988                 return;
989
990         *found_it = 1;
991
992         cprintf("%d %d\n", BINARY_FOLLOWS, length);
993         client_write(content, length);
994 }
995
996
997
998 /*
999  * Load a message from disk into memory.
1000  * This is used by CtdlOutputMsg() and other fetch functions.
1001  *
1002  * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
1003  *       using the CtdlMessageFree() function.
1004  */
1005 struct CtdlMessage *CtdlFetchMessage(long msgnum, int with_body)
1006 {
1007         struct cdbdata *dmsgtext;
1008         struct CtdlMessage *ret = NULL;
1009         char *mptr;
1010         char *upper_bound;
1011         cit_uint8_t ch;
1012         cit_uint8_t field_header;
1013
1014         lprintf(CTDL_DEBUG, "CtdlFetchMessage(%ld, %d)\n", msgnum, with_body);
1015
1016         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
1017         if (dmsgtext == NULL) {
1018                 return NULL;
1019         }
1020         mptr = dmsgtext->ptr;
1021         upper_bound = mptr + dmsgtext->len;
1022
1023         /* Parse the three bytes that begin EVERY message on disk.
1024          * The first is always 0xFF, the on-disk magic number.
1025          * The second is the anonymous/public type byte.
1026          * The third is the format type byte (vari, fixed, or MIME).
1027          */
1028         ch = *mptr++;
1029         if (ch != 255) {
1030                 lprintf(CTDL_ERR,
1031                         "Message %ld appears to be corrupted.\n",
1032                         msgnum);
1033                 cdb_free(dmsgtext);
1034                 return NULL;
1035         }
1036         ret = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1037         memset(ret, 0, sizeof(struct CtdlMessage));
1038
1039         ret->cm_magic = CTDLMESSAGE_MAGIC;
1040         ret->cm_anon_type = *mptr++;    /* Anon type byte */
1041         ret->cm_format_type = *mptr++;  /* Format type byte */
1042
1043         /*
1044          * The rest is zero or more arbitrary fields.  Load them in.
1045          * We're done when we encounter either a zero-length field or
1046          * have just processed the 'M' (message text) field.
1047          */
1048         do {
1049                 if (mptr >= upper_bound) {
1050                         break;
1051                 }
1052                 field_header = *mptr++;
1053                 ret->cm_fields[field_header] = strdup(mptr);
1054
1055                 while (*mptr++ != 0);   /* advance to next field */
1056
1057         } while ((mptr < upper_bound) && (field_header != 'M'));
1058
1059         cdb_free(dmsgtext);
1060
1061         /* Always make sure there's something in the msg text field.  If
1062          * it's NULL, the message text is most likely stored separately,
1063          * so go ahead and fetch that.  Failing that, just set a dummy
1064          * body so other code doesn't barf.
1065          */
1066         if ( (ret->cm_fields['M'] == NULL) && (with_body) ) {
1067                 dmsgtext = cdb_fetch(CDB_BIGMSGS, &msgnum, sizeof(long));
1068                 if (dmsgtext != NULL) {
1069                         ret->cm_fields['M'] = strdup(dmsgtext->ptr);
1070                         cdb_free(dmsgtext);
1071                 }
1072         }
1073         if (ret->cm_fields['M'] == NULL) {
1074                 ret->cm_fields['M'] = strdup("\r\n\r\n (no text)\r\n");
1075         }
1076
1077         /* Perform "before read" hooks (aborting if any return nonzero) */
1078         if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
1079                 CtdlFreeMessage(ret);
1080                 return NULL;
1081         }
1082
1083         return (ret);
1084 }
1085
1086
1087 /*
1088  * Returns 1 if the supplied pointer points to a valid Citadel message.
1089  * If the pointer is NULL or the magic number check fails, returns 0.
1090  */
1091 int is_valid_message(struct CtdlMessage *msg) {
1092         if (msg == NULL)
1093                 return 0;
1094         if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
1095                 lprintf(CTDL_WARNING, "is_valid_message() -- self-check failed\n");
1096                 return 0;
1097         }
1098         return 1;
1099 }
1100
1101
1102 /*
1103  * 'Destructor' for struct CtdlMessage
1104  */
1105 void CtdlFreeMessage(struct CtdlMessage *msg)
1106 {
1107         int i;
1108
1109         if (is_valid_message(msg) == 0) return;
1110
1111         for (i = 0; i < 256; ++i)
1112                 if (msg->cm_fields[i] != NULL) {
1113                         free(msg->cm_fields[i]);
1114                 }
1115
1116         msg->cm_magic = 0;      /* just in case */
1117         free(msg);
1118 }
1119
1120
1121 /*
1122  * Pre callback function for multipart/alternative
1123  *
1124  * NOTE: this differs from the standard behavior for a reason.  Normally when
1125  *       displaying multipart/alternative you want to show the _last_ usable
1126  *       format in the message.  Here we show the _first_ one, because it's
1127  *       usually text/plain.  Since this set of functions is designed for text
1128  *       output to non-MIME-aware clients, this is the desired behavior.
1129  *
1130  */
1131 void fixed_output_pre(char *name, char *filename, char *partnum, char *disp,
1132                 void *content, char *cbtype, char *cbcharset, size_t length, char *encoding,
1133                 void *cbuserdata)
1134 {
1135         struct ma_info *ma;
1136         
1137         ma = (struct ma_info *)cbuserdata;
1138         lprintf(CTDL_DEBUG, "fixed_output_pre() type=<%s>\n", cbtype);  
1139         if (!strcasecmp(cbtype, "multipart/alternative")) {
1140                 ++ma->is_ma;
1141                 ma->did_print = 0;
1142         }
1143         if (!strcasecmp(cbtype, "message/rfc822")) {
1144                 ++ma->freeze;
1145         }
1146 }
1147
1148 /*
1149  * Post callback function for multipart/alternative
1150  */
1151 void fixed_output_post(char *name, char *filename, char *partnum, char *disp,
1152                 void *content, char *cbtype, char *cbcharset, size_t length,
1153                 char *encoding, void *cbuserdata)
1154 {
1155         struct ma_info *ma;
1156         
1157         ma = (struct ma_info *)cbuserdata;
1158         lprintf(CTDL_DEBUG, "fixed_output_post() type=<%s>\n", cbtype); 
1159         if (!strcasecmp(cbtype, "multipart/alternative")) {
1160                 --ma->is_ma;
1161                 ma->did_print = 0;
1162         }
1163         if (!strcasecmp(cbtype, "message/rfc822")) {
1164                 --ma->freeze;
1165         }
1166 }
1167
1168 /*
1169  * Inline callback function for mime parser that wants to display text
1170  */
1171 void fixed_output(char *name, char *filename, char *partnum, char *disp,
1172                 void *content, char *cbtype, char *cbcharset, size_t length,
1173                 char *encoding, void *cbuserdata)
1174 {
1175         char *ptr;
1176         char *wptr;
1177         size_t wlen;
1178         struct ma_info *ma;
1179
1180         ma = (struct ma_info *)cbuserdata;
1181
1182         lprintf(CTDL_DEBUG,
1183                 "fixed_output() part %s: %s (%s) (%ld bytes)\n",
1184                 partnum, filename, cbtype, (long)length);
1185
1186         /*
1187          * If we're in the middle of a multipart/alternative scope and
1188          * we've already printed another section, skip this one.
1189          */     
1190         if ( (ma->is_ma) && (ma->did_print) ) {
1191                 lprintf(CTDL_DEBUG, "Skipping part %s (%s)\n",
1192                         partnum, cbtype);
1193                 return;
1194         }
1195         ma->did_print = 1;
1196
1197         if ( (!strcasecmp(cbtype, "text/plain")) 
1198            || (strlen(cbtype)==0) ) {
1199                 wptr = content;
1200                 if (length > 0) {
1201                         client_write(wptr, length);
1202                         if (wptr[length-1] != '\n') {
1203                                 cprintf("\n");
1204                         }
1205                 }
1206                 return;
1207         }
1208
1209         if (!strcasecmp(cbtype, "text/html")) {
1210                 ptr = html_to_ascii(content, length, 80, 0);
1211                 wlen = strlen(ptr);
1212                 client_write(ptr, wlen);
1213                 if (ptr[wlen-1] != '\n') {
1214                         cprintf("\n");
1215                 }
1216                 free(ptr);
1217                 return;
1218         }
1219
1220         if (ma->use_fo_hooks) {
1221                 if (PerformFixedOutputHooks(cbtype, content, length)) {
1222                 /* above function returns nonzero if it handled the part */
1223                         return;
1224                 }
1225         }
1226
1227         if (strncasecmp(cbtype, "multipart/", 10)) {
1228                 cprintf("Part %s: %s (%s) (%ld bytes)\r\n",
1229                         partnum, filename, cbtype, (long)length);
1230                 return;
1231         }
1232 }
1233
1234 /*
1235  * The client is elegant and sophisticated and wants to be choosy about
1236  * MIME content types, so figure out which multipart/alternative part
1237  * we're going to send.
1238  *
1239  * We use a system of weights.  When we find a part that matches one of the
1240  * MIME types we've declared as preferential, we can store it in ma->chosen_part
1241  * and then set ma->chosen_pref to that MIME type's position in our preference
1242  * list.  If we then hit another match, we only replace the first match if
1243  * the preference value is lower.
1244  */
1245 void choose_preferred(char *name, char *filename, char *partnum, char *disp,
1246                 void *content, char *cbtype, char *cbcharset, size_t length,
1247                 char *encoding, void *cbuserdata)
1248 {
1249         char buf[1024];
1250         int i;
1251         struct ma_info *ma;
1252         
1253         ma = (struct ma_info *)cbuserdata;
1254
1255         if (ma->is_ma > 0) {
1256                 for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1257                         extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1258                         lprintf(CTDL_DEBUG, "Is <%s> == <%s> ??\n", buf, cbtype);
1259                         if ( (!strcasecmp(buf, cbtype)) && (!ma->freeze) ) {
1260                                 if (i < ma->chosen_pref) {
1261                                         safestrncpy(ma->chosen_part, partnum, sizeof ma->chosen_part);
1262                                         ma->chosen_pref = i;
1263                                 }
1264                         }
1265                 }
1266         }
1267 }
1268
1269 /*
1270  * Now that we've chosen our preferred part, output it.
1271  */
1272 void output_preferred(char *name, char *filename, char *partnum, char *disp,
1273                 void *content, char *cbtype, char *cbcharset, size_t length,
1274                 char *encoding, void *cbuserdata)
1275 {
1276         int i;
1277         char buf[128];
1278         int add_newline = 0;
1279         char *text_content;
1280         struct ma_info *ma;
1281         
1282         ma = (struct ma_info *)cbuserdata;
1283
1284         /* This is not the MIME part you're looking for... */
1285         if (strcasecmp(partnum, ma->chosen_part)) return;
1286
1287         /* If the content-type of this part is in our preferred formats
1288          * list, we can simply output it verbatim.
1289          */
1290         for (i=0; i<num_tokens(CC->preferred_formats, '|'); ++i) {
1291                 extract_token(buf, CC->preferred_formats, i, '|', sizeof buf);
1292                 if (!strcasecmp(buf, cbtype)) {
1293                         /* Yeah!  Go!  W00t!! */
1294
1295                         text_content = (char *)content;
1296                         if (text_content[length-1] != '\n') {
1297                                 ++add_newline;
1298                         }
1299
1300                         cprintf("Content-type: %s", cbtype);
1301                         if (strlen(cbcharset) > 0) {
1302                                 cprintf("; charset=%s", cbcharset);
1303                         }
1304                         cprintf("\nContent-length: %d\n",
1305                                 (int)(length + add_newline) );
1306                         if (strlen(encoding) > 0) {
1307                                 cprintf("Content-transfer-encoding: %s\n", encoding);
1308                         }
1309                         else {
1310                                 cprintf("Content-transfer-encoding: 7bit\n");
1311                         }
1312                         cprintf("\n");
1313                         client_write(content, length);
1314                         if (add_newline) cprintf("\n");
1315                         return;
1316                 }
1317         }
1318
1319         /* No translations required or possible: output as text/plain */
1320         cprintf("Content-type: text/plain\n\n");
1321         fixed_output(name, filename, partnum, disp, content, cbtype, cbcharset,
1322                         length, encoding, cbuserdata);
1323 }
1324
1325
1326 struct encapmsg {
1327         char desired_section[64];
1328         char *msg;
1329         size_t msglen;
1330 };
1331
1332
1333 /*
1334  * Callback function for
1335  */
1336 void extract_encapsulated_message(char *name, char *filename, char *partnum, char *disp,
1337                    void *content, char *cbtype, char *cbcharset, size_t length,
1338                    char *encoding, void *cbuserdata)
1339 {
1340         struct encapmsg *encap;
1341
1342         encap = (struct encapmsg *)cbuserdata;
1343
1344         /* Only proceed if this is the desired section... */
1345         if (!strcasecmp(encap->desired_section, partnum)) {
1346                 encap->msglen = length;
1347                 encap->msg = malloc(length + 2);
1348                 memcpy(encap->msg, content, length);
1349                 return;
1350         }
1351
1352 }
1353
1354
1355
1356
1357 /*
1358  * Get a message off disk.  (returns om_* values found in msgbase.h)
1359  * 
1360  */
1361 int CtdlOutputMsg(long msg_num,         /* message number (local) to fetch */
1362                 int mode,               /* how would you like that message? */
1363                 int headers_only,       /* eschew the message body? */
1364                 int do_proto,           /* do Citadel protocol responses? */
1365                 int crlf,               /* Use CRLF newlines instead of LF? */
1366                 char *section           /* NULL or a message/rfc822 section */
1367 ) {
1368         struct CtdlMessage *TheMessage = NULL;
1369         int retcode = om_no_such_msg;
1370         struct encapmsg encap;
1371
1372         lprintf(CTDL_DEBUG, "CtdlOutputMsg() msgnum=%ld, mode=%d, section=%s\n", 
1373                 msg_num, mode,
1374                 (section ? section : "<>")
1375         );
1376
1377         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
1378                 if (do_proto) cprintf("%d Not logged in.\n",
1379                         ERROR + NOT_LOGGED_IN);
1380                 return(om_not_logged_in);
1381         }
1382
1383         /* FIXME: check message id against msglist for this room */
1384
1385         /*
1386          * Fetch the message from disk.  If we're in any sort of headers
1387          * only mode, request that we don't even bother loading the body
1388          * into memory.
1389          */
1390         if ( (headers_only == HEADERS_FAST) || (headers_only == HEADERS_ONLY) ) {
1391                 TheMessage = CtdlFetchMessage(msg_num, 0);
1392         }
1393         else {
1394                 TheMessage = CtdlFetchMessage(msg_num, 1);
1395         }
1396
1397         if (TheMessage == NULL) {
1398                 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
1399                         ERROR + MESSAGE_NOT_FOUND, msg_num);
1400                 return(om_no_such_msg);
1401         }
1402
1403         /* Here is the weird form of this command, to process only an
1404          * encapsulated message/rfc822 section.
1405          */
1406         if (section) if (strlen(section)>0) if (strcmp(section, "0")) {
1407                 memset(&encap, 0, sizeof encap);
1408                 safestrncpy(encap.desired_section, section, sizeof encap.desired_section);
1409                 mime_parser(TheMessage->cm_fields['M'],
1410                         NULL,
1411                         *extract_encapsulated_message,
1412                         NULL, NULL, (void *)&encap, 0
1413                 );
1414                 CtdlFreeMessage(TheMessage);
1415                 TheMessage = NULL;
1416
1417                 if (encap.msg) {
1418                         encap.msg[encap.msglen] = 0;
1419                         TheMessage = convert_internet_message(encap.msg);
1420                         encap.msg = NULL;       /* no free() here, TheMessage owns it now */
1421
1422                         /* Now we let it fall through to the bottom of this
1423                          * function, because TheMessage now contains the
1424                          * encapsulated message instead of the top-level
1425                          * message.  Isn't that neat?
1426                          */
1427
1428                 }
1429                 else {
1430                         if (do_proto) cprintf("%d msg %ld has no part %s\n",
1431                                 ERROR + MESSAGE_NOT_FOUND, msg_num, section);
1432                         retcode = om_no_such_msg;
1433                 }
1434
1435         }
1436
1437         /* Ok, output the message now */
1438         retcode = CtdlOutputPreLoadedMsg(
1439                 TheMessage, mode,
1440                 headers_only, do_proto, crlf);
1441         CtdlFreeMessage(TheMessage);
1442
1443         return(retcode);
1444 }
1445
1446
1447 /*
1448  * Get a message off disk.  (returns om_* values found in msgbase.h)
1449  * 
1450  */
1451 int CtdlOutputPreLoadedMsg(
1452                 struct CtdlMessage *TheMessage,
1453                 int mode,               /* how would you like that message? */
1454                 int headers_only,       /* eschew the message body? */
1455                 int do_proto,           /* do Citadel protocol responses? */
1456                 int crlf                /* Use CRLF newlines instead of LF? */
1457 ) {
1458         int i, k;
1459         char buf[SIZ];
1460         cit_uint8_t ch;
1461         char allkeys[30];
1462         char display_name[256];
1463         char *mptr;
1464         char *nl;       /* newline string */
1465         int suppress_f = 0;
1466         int subject_found = 0;
1467         struct ma_info ma;
1468
1469         /* Buffers needed for RFC822 translation.  These are all filled
1470          * using functions that are bounds-checked, and therefore we can
1471          * make them substantially smaller than SIZ.
1472          */
1473         char suser[100];
1474         char luser[100];
1475         char fuser[100];
1476         char snode[100];
1477         char lnode[100];
1478         char mid[100];
1479         char datestamp[100];
1480
1481         lprintf(CTDL_DEBUG, "CtdlOutputPreLoadedMsg(TheMessage=%s, %d, %d, %d, %d\n",
1482                 ((TheMessage == NULL) ? "NULL" : "not null"),
1483                 mode, headers_only, do_proto, crlf);
1484
1485         strcpy(mid, "unknown");
1486         nl = (crlf ? "\r\n" : "\n");
1487
1488         if (!is_valid_message(TheMessage)) {
1489                 lprintf(CTDL_ERR,
1490                         "ERROR: invalid preloaded message for output\n");
1491                 return(om_no_such_msg);
1492         }
1493
1494         /* Are we downloading a MIME component? */
1495         if (mode == MT_DOWNLOAD) {
1496                 if (TheMessage->cm_format_type != FMT_RFC822) {
1497                         if (do_proto)
1498                                 cprintf("%d This is not a MIME message.\n",
1499                                 ERROR + ILLEGAL_VALUE);
1500                 } else if (CC->download_fp != NULL) {
1501                         if (do_proto) cprintf(
1502                                 "%d You already have a download open.\n",
1503                                 ERROR + RESOURCE_BUSY);
1504                 } else {
1505                         /* Parse the message text component */
1506                         mptr = TheMessage->cm_fields['M'];
1507                         mime_parser(mptr, NULL, *mime_download, NULL, NULL, NULL, 0);
1508                         /* If there's no file open by this time, the requested
1509                          * section wasn't found, so print an error
1510                          */
1511                         if (CC->download_fp == NULL) {
1512                                 if (do_proto) cprintf(
1513                                         "%d Section %s not found.\n",
1514                                         ERROR + FILE_NOT_FOUND,
1515                                         CC->download_desired_section);
1516                         }
1517                 }
1518                 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1519         }
1520
1521         /* MT_SPEW_SECTION is like MT_DOWNLOAD except it outputs the whole MIME part
1522          * in a single server operation instead of opening a download file.
1523          */
1524         if (mode == MT_SPEW_SECTION) {
1525                 if (TheMessage->cm_format_type != FMT_RFC822) {
1526                         if (do_proto)
1527                                 cprintf("%d This is not a MIME message.\n",
1528                                 ERROR + ILLEGAL_VALUE);
1529                 } else {
1530                         /* Parse the message text component */
1531                         int found_it = 0;
1532
1533                         mptr = TheMessage->cm_fields['M'];
1534                         mime_parser(mptr, NULL, *mime_spew_section, NULL, NULL, (void *)&found_it, 0);
1535                         /* If section wasn't found, print an error
1536                          */
1537                         if (!found_it) {
1538                                 if (do_proto) cprintf(
1539                                         "%d Section %s not found.\n",
1540                                         ERROR + FILE_NOT_FOUND,
1541                                         CC->download_desired_section);
1542                         }
1543                 }
1544                 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
1545         }
1546
1547         /* now for the user-mode message reading loops */
1548         if (do_proto) cprintf("%d msg:\n", LISTING_FOLLOWS);
1549
1550         /* Does the caller want to skip the headers? */
1551         if (headers_only == HEADERS_NONE) goto START_TEXT;
1552
1553         /* Tell the client which format type we're using. */
1554         if ( (mode == MT_CITADEL) && (do_proto) ) {
1555                 cprintf("type=%d\n", TheMessage->cm_format_type);
1556         }
1557
1558         /* nhdr=yes means that we're only displaying headers, no body */
1559         if ( (TheMessage->cm_anon_type == MES_ANONONLY)
1560            && (mode == MT_CITADEL)
1561            && (do_proto)
1562            ) {
1563                 cprintf("nhdr=yes\n");
1564         }
1565
1566         /* begin header processing loop for Citadel message format */
1567
1568         if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
1569
1570                 safestrncpy(display_name, "<unknown>", sizeof display_name);
1571                 if (TheMessage->cm_fields['A']) {
1572                         strcpy(buf, TheMessage->cm_fields['A']);
1573                         if (TheMessage->cm_anon_type == MES_ANONONLY) {
1574                                 safestrncpy(display_name, "****", sizeof display_name);
1575                         }
1576                         else if (TheMessage->cm_anon_type == MES_ANONOPT) {
1577                                 safestrncpy(display_name, "anonymous", sizeof display_name);
1578                         }
1579                         else {
1580                                 safestrncpy(display_name, buf, sizeof display_name);
1581                         }
1582                         if ((is_room_aide())
1583                             && ((TheMessage->cm_anon_type == MES_ANONONLY)
1584                              || (TheMessage->cm_anon_type == MES_ANONOPT))) {
1585                                 size_t tmp = strlen(display_name);
1586                                 snprintf(&display_name[tmp],
1587                                          sizeof display_name - tmp,
1588                                          " [%s]", buf);
1589                         }
1590                 }
1591
1592                 /* Don't show Internet address for users on the
1593                  * local Citadel network.
1594                  */
1595                 suppress_f = 0;
1596                 if (TheMessage->cm_fields['N'] != NULL)
1597                    if (strlen(TheMessage->cm_fields['N']) > 0)
1598                       if (haschar(TheMessage->cm_fields['N'], '.') == 0) {
1599                         suppress_f = 1;
1600                 }
1601                 
1602                 /* Now spew the header fields in the order we like them. */
1603                 safestrncpy(allkeys, FORDER, sizeof allkeys);
1604                 for (i=0; i<strlen(allkeys); ++i) {
1605                         k = (int) allkeys[i];
1606                         if (k != 'M') {
1607                                 if ( (TheMessage->cm_fields[k] != NULL)
1608                                    && (msgkeys[k] != NULL) ) {
1609                                         if (k == 'A') {
1610                                                 if (do_proto) cprintf("%s=%s\n",
1611                                                         msgkeys[k],
1612                                                         display_name);
1613                                         }
1614                                         else if ((k == 'F') && (suppress_f)) {
1615                                                 /* do nothing */
1616                                         }
1617                                         /* Masquerade display name if needed */
1618                                         else {
1619                                                 if (do_proto) cprintf("%s=%s\n",
1620                                                         msgkeys[k],
1621                                                         TheMessage->cm_fields[k]
1622                                         );
1623                                         }
1624                                 }
1625                         }
1626                 }
1627
1628         }
1629
1630         /* begin header processing loop for RFC822 transfer format */
1631
1632         strcpy(suser, "");
1633         strcpy(luser, "");
1634         strcpy(fuser, "");
1635         strcpy(snode, NODENAME);
1636         strcpy(lnode, HUMANNODE);
1637         if (mode == MT_RFC822) {
1638                 for (i = 0; i < 256; ++i) {
1639                         if (TheMessage->cm_fields[i]) {
1640                                 mptr = TheMessage->cm_fields[i];
1641
1642                                 if (i == 'A') {
1643                                         safestrncpy(luser, mptr, sizeof luser);
1644                                         safestrncpy(suser, mptr, sizeof suser);
1645                                 }
1646                                 else if (i == 'Y') {
1647                                         cprintf("CC: %s%s", mptr, nl);
1648                                 }
1649                                 else if (i == 'P') {
1650                                         cprintf("Return-Path: %s%s", mptr, nl);
1651                                 }
1652                                 else if (i == 'V') {
1653                                         cprintf("Envelope-To: %s%s", mptr, nl);
1654                                 }
1655                                 else if (i == 'U') {
1656                                         cprintf("Subject: %s%s", mptr, nl);
1657                                         subject_found = 1;
1658                                 }
1659                                 else if (i == 'I')
1660                                         safestrncpy(mid, mptr, sizeof mid);
1661                                 else if (i == 'H')
1662                                         safestrncpy(lnode, mptr, sizeof lnode);
1663                                 else if (i == 'F')
1664                                         safestrncpy(fuser, mptr, sizeof fuser);
1665                                 /* else if (i == 'O')
1666                                         cprintf("X-Citadel-Room: %s%s",
1667                                                 mptr, nl); */
1668                                 else if (i == 'N')
1669                                         safestrncpy(snode, mptr, sizeof snode);
1670                                 else if (i == 'R')
1671                                         cprintf("To: %s%s", mptr, nl);
1672                                 else if (i == 'T') {
1673                                         datestring(datestamp, sizeof datestamp,
1674                                                 atol(mptr), DATESTRING_RFC822);
1675                                         cprintf("Date: %s%s", datestamp, nl);
1676                                 }
1677                         }
1678                 }
1679                 if (subject_found == 0) {
1680                         cprintf("Subject: (no subject)%s", nl);
1681                 }
1682         }
1683
1684         for (i=0; i<strlen(suser); ++i) {
1685                 suser[i] = tolower(suser[i]);
1686                 if (!isalnum(suser[i])) suser[i]='_';
1687         }
1688
1689         if (mode == MT_RFC822) {
1690                 if (!strcasecmp(snode, NODENAME)) {
1691                         safestrncpy(snode, FQDN, sizeof snode);
1692                 }
1693
1694                 /* Construct a fun message id */
1695                 cprintf("Message-ID: <%s", mid);
1696                 if (strchr(mid, '@')==NULL) {
1697                         cprintf("@%s", snode);
1698                 }
1699                 cprintf(">%s", nl);
1700
1701                 if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONONLY)) {
1702                         cprintf("From: \"----\" <x@x.org>%s", nl);
1703                 }
1704                 else if (!is_room_aide() && (TheMessage->cm_anon_type == MES_ANONOPT)) {
1705                         cprintf("From: \"anonymous\" <x@x.org>%s", nl);
1706                 }
1707                 else if (strlen(fuser) > 0) {
1708                         cprintf("From: \"%s\" <%s>%s", luser, fuser, nl);
1709                 }
1710                 else {
1711                         cprintf("From: \"%s\" <%s@%s>%s", luser, suser, snode, nl);
1712                 }
1713
1714                 cprintf("Organization: %s%s", lnode, nl);
1715
1716                 /* Blank line signifying RFC822 end-of-headers */
1717                 if (TheMessage->cm_format_type != FMT_RFC822) {
1718                         cprintf("%s", nl);
1719                 }
1720         }
1721
1722         /* end header processing loop ... at this point, we're in the text */
1723 START_TEXT:
1724         if (headers_only == HEADERS_FAST) goto DONE;
1725         mptr = TheMessage->cm_fields['M'];
1726
1727         /* Tell the client about the MIME parts in this message */
1728         if (TheMessage->cm_format_type == FMT_RFC822) {
1729                 if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1730                         memset(&ma, 0, sizeof(struct ma_info));
1731                         mime_parser(mptr, NULL,
1732                                 (do_proto ? *list_this_part : NULL),
1733                                 (do_proto ? *list_this_pref : NULL),
1734                                 (do_proto ? *list_this_suff : NULL),
1735                                 (void *)&ma, 0);
1736                 }
1737                 else if (mode == MT_RFC822) {   /* unparsed RFC822 dump */
1738                         char *start_of_text = NULL;
1739                         start_of_text = strstr(mptr, "\n\r\n");
1740                         if (start_of_text == NULL) start_of_text = strstr(mptr, "\n\n");
1741                         if (start_of_text == NULL) start_of_text = mptr;
1742                         ++start_of_text;
1743                         start_of_text = strstr(start_of_text, "\n");
1744                         ++start_of_text;
1745                         while (ch=*mptr, ch!=0) {
1746                                 if (ch==13) {
1747                                         /* do nothing */
1748                                 }
1749                                 else switch(headers_only) {
1750                                         case HEADERS_NONE:
1751                                                 if (mptr >= start_of_text) {
1752                                                         if (ch == 10) cprintf("%s", nl);
1753                                                         else cprintf("%c", ch);
1754                                                 }
1755                                                 break;
1756                                         case HEADERS_ONLY:
1757                                                 if (mptr < start_of_text) {
1758                                                         if (ch == 10) cprintf("%s", nl);
1759                                                         else cprintf("%c", ch);
1760                                                 }
1761                                                 break;
1762                                         default:
1763                                                 if (ch == 10) cprintf("%s", nl);
1764                                                 else cprintf("%c", ch);
1765                                                 break;
1766                                 }
1767                                 ++mptr;
1768                         }
1769                         goto DONE;
1770                 }
1771         }
1772
1773         if (headers_only == HEADERS_ONLY) {
1774                 goto DONE;
1775         }
1776
1777         /* signify start of msg text */
1778         if ( (mode == MT_CITADEL) || (mode == MT_MIME) ) {
1779                 if (do_proto) cprintf("text\n");
1780         }
1781
1782         /* If the format type on disk is 1 (fixed-format), then we want
1783          * everything to be output completely literally ... regardless of
1784          * what message transfer format is in use.
1785          */
1786         if (TheMessage->cm_format_type == FMT_FIXED) {
1787                 if (mode == MT_MIME) {
1788                         cprintf("Content-type: text/plain\n\n");
1789                 }
1790                 strcpy(buf, "");
1791                 while (ch = *mptr++, ch > 0) {
1792                         if (ch == 13)
1793                                 ch = 10;
1794                         if ((ch == 10) || (strlen(buf) > 250)) {
1795                                 cprintf("%s%s", buf, nl);
1796                                 strcpy(buf, "");
1797                         } else {
1798                                 buf[strlen(buf) + 1] = 0;
1799                                 buf[strlen(buf)] = ch;
1800                         }
1801                 }
1802                 if (strlen(buf) > 0)
1803                         cprintf("%s%s", buf, nl);
1804         }
1805
1806         /* If the message on disk is format 0 (Citadel vari-format), we
1807          * output using the formatter at 80 columns.  This is the final output
1808          * form if the transfer format is RFC822, but if the transfer format
1809          * is Citadel proprietary, it'll still work, because the indentation
1810          * for new paragraphs is correct and the client will reformat the
1811          * message to the reader's screen width.
1812          */
1813         if (TheMessage->cm_format_type == FMT_CITADEL) {
1814                 if (mode == MT_MIME) {
1815                         cprintf("Content-type: text/x-citadel-variformat\n\n");
1816                 }
1817                 memfmout(mptr, 0, nl);
1818         }
1819
1820         /* If the message on disk is format 4 (MIME), we've gotta hand it
1821          * off to the MIME parser.  The client has already been told that
1822          * this message is format 1 (fixed format), so the callback function
1823          * we use will display those parts as-is.
1824          */
1825         if (TheMessage->cm_format_type == FMT_RFC822) {
1826                 memset(&ma, 0, sizeof(struct ma_info));
1827
1828                 if (mode == MT_MIME) {
1829                         ma.use_fo_hooks = 0;
1830                         strcpy(ma.chosen_part, "1");
1831                         ma.chosen_pref = 9999;
1832                         mime_parser(mptr, NULL,
1833                                 *choose_preferred, *fixed_output_pre,
1834                                 *fixed_output_post, (void *)&ma, 0);
1835                         mime_parser(mptr, NULL,
1836                                 *output_preferred, NULL, NULL, (void *)&ma, 0);
1837                 }
1838                 else {
1839                         ma.use_fo_hooks = 1;
1840                         mime_parser(mptr, NULL,
1841                                 *fixed_output, *fixed_output_pre,
1842                                 *fixed_output_post, (void *)&ma, 0);
1843                 }
1844
1845         }
1846
1847 DONE:   /* now we're done */
1848         if (do_proto) cprintf("000\n");
1849         return(om_ok);
1850 }
1851
1852
1853
1854 /*
1855  * display a message (mode 0 - Citadel proprietary)
1856  */
1857 void cmd_msg0(char *cmdbuf)
1858 {
1859         long msgid;
1860         int headers_only = HEADERS_ALL;
1861
1862         msgid = extract_long(cmdbuf, 0);
1863         headers_only = extract_int(cmdbuf, 1);
1864
1865         CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, 0, NULL);
1866         return;
1867 }
1868
1869
1870 /*
1871  * display a message (mode 2 - RFC822)
1872  */
1873 void cmd_msg2(char *cmdbuf)
1874 {
1875         long msgid;
1876         int headers_only = HEADERS_ALL;
1877
1878         msgid = extract_long(cmdbuf, 0);
1879         headers_only = extract_int(cmdbuf, 1);
1880
1881         CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, 1, NULL);
1882 }
1883
1884
1885
1886 /* 
1887  * display a message (mode 3 - IGnet raw format - internal programs only)
1888  */
1889 void cmd_msg3(char *cmdbuf)
1890 {
1891         long msgnum;
1892         struct CtdlMessage *msg;
1893         struct ser_ret smr;
1894
1895         if (CC->internal_pgm == 0) {
1896                 cprintf("%d This command is for internal programs only.\n",
1897                         ERROR + HIGHER_ACCESS_REQUIRED);
1898                 return;
1899         }
1900
1901         msgnum = extract_long(cmdbuf, 0);
1902         msg = CtdlFetchMessage(msgnum, 1);
1903         if (msg == NULL) {
1904                 cprintf("%d Message %ld not found.\n", 
1905                         ERROR + MESSAGE_NOT_FOUND, msgnum);
1906                 return;
1907         }
1908
1909         serialize_message(&smr, msg);
1910         CtdlFreeMessage(msg);
1911
1912         if (smr.len == 0) {
1913                 cprintf("%d Unable to serialize message\n",
1914                         ERROR + INTERNAL_ERROR);
1915                 return;
1916         }
1917
1918         cprintf("%d %ld\n", BINARY_FOLLOWS, (long)smr.len);
1919         client_write((char *)smr.ser, (int)smr.len);
1920         free(smr.ser);
1921 }
1922
1923
1924
1925 /* 
1926  * Display a message using MIME content types
1927  */
1928 void cmd_msg4(char *cmdbuf)
1929 {
1930         long msgid;
1931         char section[64];
1932
1933         msgid = extract_long(cmdbuf, 0);
1934         extract_token(section, cmdbuf, 1, '|', sizeof section);
1935         CtdlOutputMsg(msgid, MT_MIME, 0, 1, 0, (section[0] ? section : NULL) );
1936 }
1937
1938
1939
1940 /* 
1941  * Client tells us its preferred message format(s)
1942  */
1943 void cmd_msgp(char *cmdbuf)
1944 {
1945         safestrncpy(CC->preferred_formats, cmdbuf,
1946                         sizeof(CC->preferred_formats));
1947         cprintf("%d ok\n", CIT_OK);
1948 }
1949
1950
1951 /*
1952  * Open a component of a MIME message as a download file 
1953  */
1954 void cmd_opna(char *cmdbuf)
1955 {
1956         long msgid;
1957         char desired_section[128];
1958
1959         msgid = extract_long(cmdbuf, 0);
1960         extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1961         safestrncpy(CC->download_desired_section, desired_section,
1962                 sizeof CC->download_desired_section);
1963         CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, 1, NULL);
1964 }                       
1965
1966
1967 /*
1968  * Open a component of a MIME message and transmit it all at once
1969  */
1970 void cmd_dlat(char *cmdbuf)
1971 {
1972         long msgid;
1973         char desired_section[128];
1974
1975         msgid = extract_long(cmdbuf, 0);
1976         extract_token(desired_section, cmdbuf, 1, '|', sizeof desired_section);
1977         safestrncpy(CC->download_desired_section, desired_section,
1978                 sizeof CC->download_desired_section);
1979         CtdlOutputMsg(msgid, MT_SPEW_SECTION, 0, 1, 1, NULL);
1980 }                       
1981
1982
1983 /*
1984  * Save one or more message pointers into a specified room
1985  * (Returns 0 for success, nonzero for failure)
1986  * roomname may be NULL to use the current room
1987  *
1988  * Note that the 'supplied_msg' field may be set to NULL, in which case
1989  * the message will be fetched from disk, by number, if we need to perform
1990  * replication checks.  This adds an additional database read, so if the
1991  * caller already has the message in memory then it should be supplied.  (Obviously
1992  * this mode of operation only works if we're saving a single message.)
1993  */
1994 int CtdlSaveMsgPointersInRoom(char *roomname, long newmsgidlist[], int num_newmsgs,
1995                                 int do_repl_check, struct CtdlMessage *supplied_msg)
1996 {
1997         int i, j, unique;
1998         char hold_rm[ROOMNAMELEN];
1999         struct cdbdata *cdbfr;
2000         int num_msgs;
2001         long *msglist;
2002         long highest_msg = 0L;
2003
2004         long msgid = 0;
2005         struct CtdlMessage *msg = NULL;
2006
2007         long *msgs_to_be_merged = NULL;
2008         int num_msgs_to_be_merged = 0;
2009
2010         lprintf(CTDL_DEBUG,
2011                 "CtdlSaveMsgPointersInRoom(room=%s, num_msgs=%d, repl=%d)\n",
2012                 roomname, num_newmsgs, do_repl_check);
2013
2014         strcpy(hold_rm, CC->room.QRname);
2015
2016         /* Sanity checks */
2017         if (newmsgidlist == NULL) return(ERROR + INTERNAL_ERROR);
2018         if (num_newmsgs < 1) return(ERROR + INTERNAL_ERROR);
2019         if (num_newmsgs > 1) supplied_msg = NULL;
2020
2021         /* Now the regular stuff */
2022         if (lgetroom(&CC->room,
2023            ((roomname != NULL) ? roomname : CC->room.QRname) )
2024            != 0) {
2025                 lprintf(CTDL_ERR, "No such room <%s>\n", roomname);
2026                 return(ERROR + ROOM_NOT_FOUND);
2027         }
2028
2029
2030         msgs_to_be_merged = malloc(sizeof(long) * num_newmsgs);
2031         num_msgs_to_be_merged = 0;
2032
2033
2034         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
2035         if (cdbfr == NULL) {
2036                 msglist = NULL;
2037                 num_msgs = 0;
2038         } else {
2039                 msglist = (long *) cdbfr->ptr;
2040                 cdbfr->ptr = NULL;      /* CtdlSaveMsgPointerInRoom() now owns this memory */
2041                 num_msgs = cdbfr->len / sizeof(long);
2042                 cdb_free(cdbfr);
2043         }
2044
2045
2046         /* Create a list of msgid's which were supplied by the caller, but do
2047          * not already exist in the target room.  It is absolutely taboo to
2048          * have more than one reference to the same message in a room.
2049          */
2050         for (i=0; i<num_newmsgs; ++i) {
2051                 unique = 1;
2052                 if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
2053                         if (msglist[j] == newmsgidlist[i]) {
2054                                 unique = 0;
2055                         }
2056                 }
2057                 if (unique) {
2058                         msgs_to_be_merged[num_msgs_to_be_merged++] = newmsgidlist[i];
2059                 }
2060         }
2061
2062         lprintf(9, "%d unique messages to be merged\n", num_msgs_to_be_merged);
2063
2064         /*
2065          * Now merge the new messages
2066          */
2067         msglist = realloc(msglist, (sizeof(long) * (num_msgs + num_msgs_to_be_merged)) );
2068         if (msglist == NULL) {
2069                 lprintf(CTDL_ALERT, "ERROR: can't realloc message list!\n");
2070         }
2071         memcpy(&msglist[num_msgs], msgs_to_be_merged, (sizeof(long) * num_msgs_to_be_merged) );
2072         num_msgs += num_msgs_to_be_merged;
2073
2074         /* Sort the message list, so all the msgid's are in order */
2075         num_msgs = sort_msglist(msglist, num_msgs);
2076
2077         /* Determine the highest message number */
2078         highest_msg = msglist[num_msgs - 1];
2079
2080         /* Write it back to disk. */
2081         cdb_store(CDB_MSGLISTS, &CC->room.QRnumber, (int)sizeof(long),
2082                   msglist, (int)(num_msgs * sizeof(long)));
2083
2084         /* Free up the memory we used. */
2085         free(msglist);
2086
2087         /* Update the highest-message pointer and unlock the room. */
2088         CC->room.QRhighest = highest_msg;
2089         lputroom(&CC->room);
2090
2091         /* Perform replication checks if necessary */
2092         if ( (DoesThisRoomNeedEuidIndexing(&CC->room)) && (do_repl_check) ) {
2093                 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() doing repl checks\n");
2094
2095                 for (i=0; i<num_msgs_to_be_merged; ++i) {
2096                         msgid = msgs_to_be_merged[i];
2097         
2098                         if (supplied_msg != NULL) {
2099                                 msg = supplied_msg;
2100                         }
2101                         else {
2102                                 msg = CtdlFetchMessage(msgid, 0);
2103                         }
2104         
2105                         if (msg != NULL) {
2106                                 ReplicationChecks(msg);
2107                 
2108                                 /* If the message has an Exclusive ID, index that... */
2109                                 if (msg->cm_fields['E'] != NULL) {
2110                                         index_message_by_euid(msg->cm_fields['E'], &CC->room, msgid);
2111                                 }
2112
2113                                 /* Free up the memory we may have allocated */
2114                                 if (msg != supplied_msg) {
2115                                         CtdlFreeMessage(msg);
2116                                 }
2117                         }
2118         
2119                 }
2120         }
2121
2122         else {
2123                 lprintf(CTDL_DEBUG, "CtdlSaveMsgPointerInRoom() skips repl checks\n");
2124         }
2125
2126         /* Submit this room for net processing */
2127         network_queue_room(&CC->room, NULL);
2128
2129 #ifdef HAVE_LIBSIEVE
2130         /* If this is someone's inbox, submit the room for sieve processing */
2131         if (!strcasecmp(&CC->room.QRname[11], MAILROOM)) {
2132                 sieve_queue_room(&CC->room);
2133         }
2134 #endif /* HAVE_LIBSIEVE */
2135
2136         /* Go back to the room we were in before we wandered here... */
2137         getroom(&CC->room, hold_rm);
2138
2139         /* Bump the reference count for all messages which were merged */
2140         for (i=0; i<num_msgs_to_be_merged; ++i) {
2141                 AdjRefCount(msgs_to_be_merged[i], +1);
2142         }
2143
2144         /* Free up memory... */
2145         if (msgs_to_be_merged != NULL) {
2146                 free(msgs_to_be_merged);
2147         }
2148
2149         /* Return success. */
2150         return (0);
2151 }
2152
2153
2154 /*
2155  * This is the same as CtdlSaveMsgPointersInRoom() but it only accepts
2156  * a single message.
2157  */
2158 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid,
2159                         int do_repl_check, struct CtdlMessage *supplied_msg)
2160 {
2161         return CtdlSaveMsgPointersInRoom(roomname, &msgid, 1, do_repl_check, supplied_msg);
2162 }
2163
2164
2165
2166
2167 /*
2168  * Message base operation to save a new message to the message store
2169  * (returns new message number)
2170  *
2171  * This is the back end for CtdlSubmitMsg() and should not be directly
2172  * called by server-side modules.
2173  *
2174  */
2175 long send_message(struct CtdlMessage *msg) {
2176         long newmsgid;
2177         long retval;
2178         char msgidbuf[256];
2179         struct ser_ret smr;
2180         int is_bigmsg = 0;
2181         char *holdM = NULL;
2182
2183         /* Get a new message number */
2184         newmsgid = get_new_message_number();
2185         snprintf(msgidbuf, sizeof msgidbuf, "%010ld@%s", newmsgid, config.c_fqdn);
2186
2187         /* Generate an ID if we don't have one already */
2188         if (msg->cm_fields['I']==NULL) {
2189                 msg->cm_fields['I'] = strdup(msgidbuf);
2190         }
2191
2192         /* If the message is big, set its body aside for storage elsewhere */
2193         if (msg->cm_fields['M'] != NULL) {
2194                 if (strlen(msg->cm_fields['M']) > BIGMSG) {
2195                         is_bigmsg = 1;
2196                         holdM = msg->cm_fields['M'];
2197                         msg->cm_fields['M'] = NULL;
2198                 }
2199         }
2200
2201         /* Serialize our data structure for storage in the database */  
2202         serialize_message(&smr, msg);
2203
2204         if (is_bigmsg) {
2205                 msg->cm_fields['M'] = holdM;
2206         }
2207
2208         if (smr.len == 0) {
2209                 cprintf("%d Unable to serialize message\n",
2210                         ERROR + INTERNAL_ERROR);
2211                 return (-1L);
2212         }
2213
2214         /* Write our little bundle of joy into the message base */
2215         if (cdb_store(CDB_MSGMAIN, &newmsgid, (int)sizeof(long),
2216                       smr.ser, smr.len) < 0) {
2217                 lprintf(CTDL_ERR, "Can't store message\n");
2218                 retval = 0L;
2219         } else {
2220                 if (is_bigmsg) {
2221                         cdb_store(CDB_BIGMSGS,
2222                                 &newmsgid,
2223                                 (int)sizeof(long),
2224                                 holdM,
2225                                 (strlen(holdM) + 1)
2226                         );
2227                 }
2228                 retval = newmsgid;
2229         }
2230
2231         /* Free the memory we used for the serialized message */
2232         free(smr.ser);
2233
2234         /* Return the *local* message ID to the caller
2235          * (even if we're storing an incoming network message)
2236          */
2237         return(retval);
2238 }
2239
2240
2241
2242 /*
2243  * Serialize a struct CtdlMessage into the format used on disk and network.
2244  * 
2245  * This function loads up a "struct ser_ret" (defined in server.h) which
2246  * contains the length of the serialized message and a pointer to the
2247  * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
2248  */
2249 void serialize_message(struct ser_ret *ret,             /* return values */
2250                         struct CtdlMessage *msg)        /* unserialized msg */
2251 {
2252         size_t wlen, fieldlen;
2253         int i;
2254         static char *forder = FORDER;
2255
2256         /*
2257          * Check for valid message format
2258          */
2259         if (is_valid_message(msg) == 0) {
2260                 lprintf(CTDL_ERR, "serialize_message() aborting due to invalid message\n");
2261                 ret->len = 0;
2262                 ret->ser = NULL;
2263                 return;
2264         }
2265
2266         ret->len = 3;
2267         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
2268                 ret->len = ret->len +
2269                         strlen(msg->cm_fields[(int)forder[i]]) + 2;
2270
2271         ret->ser = malloc(ret->len);
2272         if (ret->ser == NULL) {
2273                 lprintf(CTDL_ERR, "serialize_message() malloc(%ld) failed: %s\n",
2274                         (long)ret->len, strerror(errno));
2275                 ret->len = 0;
2276                 ret->ser = NULL;
2277                 return;
2278         }
2279
2280         ret->ser[0] = 0xFF;
2281         ret->ser[1] = msg->cm_anon_type;
2282         ret->ser[2] = msg->cm_format_type;
2283         wlen = 3;
2284
2285         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
2286                 fieldlen = strlen(msg->cm_fields[(int)forder[i]]);
2287                 ret->ser[wlen++] = (char)forder[i];
2288                 safestrncpy((char *)&ret->ser[wlen], msg->cm_fields[(int)forder[i]], fieldlen+1);
2289                 wlen = wlen + fieldlen + 1;
2290         }
2291         if (ret->len != wlen) lprintf(CTDL_ERR, "ERROR: len=%ld wlen=%ld\n",
2292                 (long)ret->len, (long)wlen);
2293
2294         return;
2295 }
2296
2297
2298
2299 /*
2300  * Check to see if any messages already exist in the current room which
2301  * carry the same Exclusive ID as this one.  If any are found, delete them.
2302  */
2303 void ReplicationChecks(struct CtdlMessage *msg) {
2304         long old_msgnum = (-1L);
2305
2306         if (DoesThisRoomNeedEuidIndexing(&CC->room) == 0) return;
2307
2308         lprintf(CTDL_DEBUG, "Performing replication checks in <%s>\n",
2309                 CC->room.QRname);
2310
2311         /* No exclusive id?  Don't do anything. */
2312         if (msg == NULL) return;
2313         if (msg->cm_fields['E'] == NULL) return;
2314         if (strlen(msg->cm_fields['E']) == 0) return;
2315         /*lprintf(CTDL_DEBUG, "Exclusive ID: <%s> for room <%s>\n",
2316                 msg->cm_fields['E'], CC->room.QRname);*/
2317
2318         old_msgnum = locate_message_by_euid(msg->cm_fields['E'], &CC->room);
2319         if (old_msgnum > 0L) {
2320                 lprintf(CTDL_DEBUG, "ReplicationChecks() replacing message %ld\n", old_msgnum);
2321                 CtdlDeleteMessages(CC->room.QRname, &old_msgnum, 1, "", 0);
2322         }
2323 }
2324
2325
2326
2327 /*
2328  * Save a message to disk and submit it into the delivery system.
2329  */
2330 long CtdlSubmitMsg(struct CtdlMessage *msg,     /* message to save */
2331                 struct recptypes *recps,        /* recipients (if mail) */
2332                 char *force                     /* force a particular room? */
2333 ) {
2334         char submit_filename[128];
2335         char generated_timestamp[32];
2336         char hold_rm[ROOMNAMELEN];
2337         char actual_rm[ROOMNAMELEN];
2338         char force_room[ROOMNAMELEN];
2339         char content_type[SIZ];                 /* We have to learn this */
2340         char recipient[SIZ];
2341         long newmsgid;
2342         char *mptr = NULL;
2343         struct ctdluser userbuf;
2344         int a, i;
2345         struct MetaData smi;
2346         FILE *network_fp = NULL;
2347         static int seqnum = 1;
2348         struct CtdlMessage *imsg = NULL;
2349         char *instr;
2350         struct ser_ret smr;
2351         char *hold_R, *hold_D;
2352         char *collected_addresses = NULL;
2353         struct addresses_to_be_filed *aptr = NULL;
2354         char *saved_rfc822_version = NULL;
2355         int qualified_for_journaling = 0;
2356
2357         lprintf(CTDL_DEBUG, "CtdlSubmitMsg() called\n");
2358         if (is_valid_message(msg) == 0) return(-1);     /* self check */
2359
2360         /* If this message has no timestamp, we take the liberty of
2361          * giving it one, right now.
2362          */
2363         if (msg->cm_fields['T'] == NULL) {
2364                 snprintf(generated_timestamp, sizeof generated_timestamp, "%ld", (long)time(NULL));
2365                 msg->cm_fields['T'] = strdup(generated_timestamp);
2366         }
2367
2368         /* If this message has no path, we generate one.
2369          */
2370         if (msg->cm_fields['P'] == NULL) {
2371                 if (msg->cm_fields['A'] != NULL) {
2372                         msg->cm_fields['P'] = strdup(msg->cm_fields['A']);
2373                         for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
2374                                 if (isspace(msg->cm_fields['P'][a])) {
2375                                         msg->cm_fields['P'][a] = ' ';
2376                                 }
2377                         }
2378                 }
2379                 else {
2380                         msg->cm_fields['P'] = strdup("unknown");
2381                 }
2382         }
2383
2384         if (force == NULL) {
2385                 strcpy(force_room, "");
2386         }
2387         else {
2388                 strcpy(force_room, force);
2389         }
2390
2391         /* Learn about what's inside, because it's what's inside that counts */
2392         if (msg->cm_fields['M'] == NULL) {
2393                 lprintf(CTDL_ERR, "ERROR: attempt to save message with NULL body\n");
2394                 return(-2);
2395         }
2396
2397         switch (msg->cm_format_type) {
2398         case 0:
2399                 strcpy(content_type, "text/x-citadel-variformat");
2400                 break;
2401         case 1:
2402                 strcpy(content_type, "text/plain");
2403                 break;
2404         case 4:
2405                 strcpy(content_type, "text/plain");
2406                 mptr = bmstrcasestr(msg->cm_fields['M'], "Content-type: ");
2407                 if (mptr != NULL) {
2408                         safestrncpy(content_type, &mptr[14], 
2409                                         sizeof content_type);
2410                         for (a = 0; a < strlen(content_type); ++a) {
2411                                 if ((content_type[a] == ';')
2412                                     || (content_type[a] == ' ')
2413                                     || (content_type[a] == 13)
2414                                     || (content_type[a] == 10)) {
2415                                         content_type[a] = 0;
2416                                 }
2417                         }
2418                 }
2419         }
2420
2421         /* Goto the correct room */
2422         lprintf(CTDL_DEBUG, "Selected room %s\n", (recps) ? CC->room.QRname : SENTITEMS);
2423         strcpy(hold_rm, CC->room.QRname);
2424         strcpy(actual_rm, CC->room.QRname);
2425         if (recps != NULL) {
2426                 strcpy(actual_rm, SENTITEMS);
2427         }
2428
2429         /* If the user is a twit, move to the twit room for posting */
2430         if (TWITDETECT) {
2431                 if (CC->user.axlevel == 2) {
2432                         strcpy(hold_rm, actual_rm);
2433                         strcpy(actual_rm, config.c_twitroom);
2434                         lprintf(CTDL_DEBUG, "Diverting to twit room\n");
2435                 }
2436         }
2437
2438         /* ...or if this message is destined for Aide> then go there. */
2439         if (strlen(force_room) > 0) {
2440                 strcpy(actual_rm, force_room);
2441         }
2442
2443         lprintf(CTDL_DEBUG, "Final selection: %s\n", actual_rm);
2444         if (strcasecmp(actual_rm, CC->room.QRname)) {
2445                 /* getroom(&CC->room, actual_rm); */
2446                 usergoto(actual_rm, 0, 1, NULL, NULL);
2447         }
2448
2449         /*
2450          * If this message has no O (room) field, generate one.
2451          */
2452         if (msg->cm_fields['O'] == NULL) {
2453                 msg->cm_fields['O'] = strdup(CC->room.QRname);
2454         }
2455
2456         /* Perform "before save" hooks (aborting if any return nonzero) */
2457         lprintf(CTDL_DEBUG, "Performing before-save hooks\n");
2458         if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-3);
2459
2460         /*
2461          * If this message has an Exclusive ID, and the room is replication
2462          * checking enabled, then do replication checks.
2463          */
2464         if (DoesThisRoomNeedEuidIndexing(&CC->room)) {
2465                 ReplicationChecks(msg);
2466         }
2467
2468         /* Save it to disk */
2469         lprintf(CTDL_DEBUG, "Saving to disk\n");
2470         newmsgid = send_message(msg);
2471         if (newmsgid <= 0L) return(-5);
2472
2473         /* Write a supplemental message info record.  This doesn't have to
2474          * be a critical section because nobody else knows about this message
2475          * yet.
2476          */
2477         lprintf(CTDL_DEBUG, "Creating MetaData record\n");
2478         memset(&smi, 0, sizeof(struct MetaData));
2479         smi.meta_msgnum = newmsgid;
2480         smi.meta_refcount = 0;
2481         safestrncpy(smi.meta_content_type, content_type,
2482                         sizeof smi.meta_content_type);
2483
2484         /*
2485          * Measure how big this message will be when rendered as RFC822.
2486          * We do this for two reasons:
2487          * 1. We need the RFC822 length for the new metadata record, so the
2488          *    POP and IMAP services don't have to calculate message lengths
2489          *    while the user is waiting (multiplied by potentially hundreds
2490          *    or thousands of messages).
2491          * 2. If journaling is enabled, we will need an RFC822 version of the
2492          *    message to attach to the journalized copy.
2493          */
2494         if (CC->redirect_buffer != NULL) {
2495                 lprintf(CTDL_ALERT, "CC->redirect_buffer is not NULL during message submission!\n");
2496                 abort();
2497         }
2498         CC->redirect_buffer = malloc(SIZ);
2499         CC->redirect_len = 0;
2500         CC->redirect_alloc = SIZ;
2501         CtdlOutputPreLoadedMsg(msg, MT_RFC822, HEADERS_ALL, 0, 1);
2502         smi.meta_rfc822_length = CC->redirect_len;
2503         saved_rfc822_version = CC->redirect_buffer;
2504         CC->redirect_buffer = NULL;
2505         CC->redirect_len = 0;
2506         CC->redirect_alloc = 0;
2507
2508         PutMetaData(&smi);
2509
2510         /* Now figure out where to store the pointers */
2511         lprintf(CTDL_DEBUG, "Storing pointers\n");
2512
2513         /* If this is being done by the networker delivering a private
2514          * message, we want to BYPASS saving the sender's copy (because there
2515          * is no local sender; it would otherwise go to the Trashcan).
2516          */
2517         if ((!CC->internal_pgm) || (recps == NULL)) {
2518                 if (CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 1, msg) != 0) {
2519                         lprintf(CTDL_ERR, "ERROR saving message pointer!\n");
2520                         CtdlSaveMsgPointerInRoom(config.c_aideroom, newmsgid, 0, msg);
2521                 }
2522         }
2523
2524         /* For internet mail, drop a copy in the outbound queue room */
2525         if (recps != NULL)
2526          if (recps->num_internet > 0) {
2527                 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0, msg);
2528         }
2529
2530         /* If other rooms are specified, drop them there too. */
2531         if (recps != NULL)
2532          if (recps->num_room > 0)
2533           for (i=0; i<num_tokens(recps->recp_room, '|'); ++i) {
2534                 extract_token(recipient, recps->recp_room, i,
2535                                         '|', sizeof recipient);
2536                 lprintf(CTDL_DEBUG, "Delivering to room <%s>\n", recipient);
2537                 CtdlSaveMsgPointerInRoom(recipient, newmsgid, 0, msg);
2538         }
2539
2540         /* Bump this user's messages posted counter. */
2541         lprintf(CTDL_DEBUG, "Updating user\n");
2542         lgetuser(&CC->user, CC->curr_user);
2543         CC->user.posted = CC->user.posted + 1;
2544         lputuser(&CC->user);
2545
2546         /* If this is private, local mail, make a copy in the
2547          * recipient's mailbox and bump the reference count.
2548          */
2549         if (recps != NULL)
2550          if (recps->num_local > 0)
2551           for (i=0; i<num_tokens(recps->recp_local, '|'); ++i) {
2552                 extract_token(recipient, recps->recp_local, i,
2553                                         '|', sizeof recipient);
2554                 lprintf(CTDL_DEBUG, "Delivering private local mail to <%s>\n",
2555                         recipient);
2556                 if (getuser(&userbuf, recipient) == 0) {
2557                         MailboxName(actual_rm, sizeof actual_rm,
2558                                         &userbuf, MAILROOM);
2559                         CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0, msg);
2560                         BumpNewMailCounter(userbuf.usernum);
2561                 }
2562                 else {
2563                         lprintf(CTDL_DEBUG, "No user <%s>\n", recipient);
2564                         CtdlSaveMsgPointerInRoom(config.c_aideroom,
2565                                 newmsgid, 0, msg);
2566                 }
2567         }
2568
2569         /* Perform "after save" hooks */
2570         lprintf(CTDL_DEBUG, "Performing after-save hooks\n");
2571         PerformMessageHooks(msg, EVT_AFTERSAVE);
2572
2573         /* For IGnet mail, we have to save a new copy into the spooler for
2574          * each recipient, with the R and D fields set to the recipient and
2575          * destination-node.  This has two ugly side effects: all other
2576          * recipients end up being unlisted in this recipient's copy of the
2577          * message, and it has to deliver multiple messages to the same
2578          * node.  We'll revisit this again in a year or so when everyone has
2579          * a network spool receiver that can handle the new style messages.
2580          */
2581         if (recps != NULL)
2582          if (recps->num_ignet > 0)
2583           for (i=0; i<num_tokens(recps->recp_ignet, '|'); ++i) {
2584                 extract_token(recipient, recps->recp_ignet, i,
2585                                 '|', sizeof recipient);
2586
2587                 hold_R = msg->cm_fields['R'];
2588                 hold_D = msg->cm_fields['D'];
2589                 msg->cm_fields['R'] = malloc(SIZ);
2590                 msg->cm_fields['D'] = malloc(128);
2591                 extract_token(msg->cm_fields['R'], recipient, 0, '@', SIZ);
2592                 extract_token(msg->cm_fields['D'], recipient, 1, '@', 128);
2593                 
2594                 serialize_message(&smr, msg);
2595                 if (smr.len > 0) {
2596                         snprintf(submit_filename, sizeof submit_filename,
2597                                          "%s/netmail.%04lx.%04x.%04x",
2598                                          ctdl_netin_dir,
2599                                          (long) getpid(), CC->cs_pid, ++seqnum);
2600                         network_fp = fopen(submit_filename, "wb+");
2601                         if (network_fp != NULL) {
2602                                 fwrite(smr.ser, smr.len, 1, network_fp);
2603                                 fclose(network_fp);
2604                         }
2605                         free(smr.ser);
2606                 }
2607
2608                 free(msg->cm_fields['R']);
2609                 free(msg->cm_fields['D']);
2610                 msg->cm_fields['R'] = hold_R;
2611                 msg->cm_fields['D'] = hold_D;
2612         }
2613
2614         /* Go back to the room we started from */
2615         lprintf(CTDL_DEBUG, "Returning to original room %s\n", hold_rm);
2616         if (strcasecmp(hold_rm, CC->room.QRname))
2617                 /* getroom(&CC->room, hold_rm); */
2618                 usergoto(hold_rm, 0, 1, NULL, NULL);
2619
2620         /* For internet mail, generate delivery instructions.
2621          * Yes, this is recursive.  Deal with it.  Infinite recursion does
2622          * not happen because the delivery instructions message does not
2623          * contain a recipient.
2624          */
2625         if (recps != NULL)
2626          if (recps->num_internet > 0) {
2627                 lprintf(CTDL_DEBUG, "Generating delivery instructions\n");
2628                 instr = malloc(SIZ * 2);
2629                 snprintf(instr, SIZ * 2,
2630                         "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
2631                         "bounceto|%s@%s\n",
2632                         SPOOLMIME, newmsgid, (long)time(NULL),
2633                         msg->cm_fields['A'], msg->cm_fields['N']
2634                 );
2635
2636                 for (i=0; i<num_tokens(recps->recp_internet, '|'); ++i) {
2637                         size_t tmp = strlen(instr);
2638                         extract_token(recipient, recps->recp_internet,
2639                                 i, '|', sizeof recipient);
2640                         snprintf(&instr[tmp], SIZ * 2 - tmp,
2641                                  "remote|%s|0||\n", recipient);
2642                 }
2643
2644                 imsg = malloc(sizeof(struct CtdlMessage));
2645                 memset(imsg, 0, sizeof(struct CtdlMessage));
2646                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
2647                 imsg->cm_anon_type = MES_NORMAL;
2648                 imsg->cm_format_type = FMT_RFC822;
2649                 imsg->cm_fields['A'] = strdup("Citadel");
2650                 imsg->cm_fields['J'] = strdup("do not journal");
2651                 imsg->cm_fields['M'] = instr;
2652                 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM);
2653                 CtdlFreeMessage(imsg);
2654         }
2655
2656         /*
2657          * Any addresses to harvest for someone's address book?
2658          */
2659         if ( (CC->logged_in) && (recps != NULL) ) {
2660                 collected_addresses = harvest_collected_addresses(msg);
2661         }
2662
2663         if (collected_addresses != NULL) {
2664                 begin_critical_section(S_ATBF);
2665                 aptr = (struct addresses_to_be_filed *)
2666                         malloc(sizeof(struct addresses_to_be_filed));
2667                 aptr->next = atbf;
2668                 MailboxName(actual_rm, sizeof actual_rm,
2669                         &CC->user, USERCONTACTSROOM);
2670                 aptr->roomname = strdup(actual_rm);
2671                 aptr->collected_addresses = collected_addresses;
2672                 atbf = aptr;
2673                 end_critical_section(S_ATBF);
2674         }
2675
2676         /*
2677          * Determine whether this message qualifies for journaling.
2678          */
2679         if (msg->cm_fields['J'] != NULL) {
2680                 qualified_for_journaling = 0;
2681         }
2682         else {
2683                 if (recps == NULL) {
2684                         qualified_for_journaling = config.c_journal_pubmsgs;
2685                 }
2686                 else if (recps->num_local + recps->num_ignet + recps->num_internet > 0) {
2687                         qualified_for_journaling = config.c_journal_email;
2688                 }
2689                 else {
2690                         qualified_for_journaling = config.c_journal_pubmsgs;
2691                 }
2692         }
2693
2694         /*
2695          * Do we have to perform journaling?  If so, hand off the saved
2696          * RFC822 version will be handed off to the journaler for background
2697          * submit.  Otherwise, we have to free the memory ourselves.
2698          */
2699         if (saved_rfc822_version != NULL) {
2700                 if (qualified_for_journaling) {
2701                         JournalBackgroundSubmit(msg, saved_rfc822_version, recps);
2702                 }
2703                 else {
2704                         free(saved_rfc822_version);
2705                 }
2706         }
2707
2708         /* Done. */
2709         return(newmsgid);
2710 }
2711
2712
2713
2714
2715
2716 /*
2717  * Convenience function for generating small administrative messages.
2718  */
2719 void quickie_message(char *from, char *fromaddr, char *to, char *room, char *text, 
2720                         int format_type, char *subject)
2721 {
2722         struct CtdlMessage *msg;
2723         struct recptypes *recp = NULL;
2724
2725         msg = malloc(sizeof(struct CtdlMessage));
2726         memset(msg, 0, sizeof(struct CtdlMessage));
2727         msg->cm_magic = CTDLMESSAGE_MAGIC;
2728         msg->cm_anon_type = MES_NORMAL;
2729         msg->cm_format_type = format_type;
2730
2731         if (from != NULL) {
2732                 msg->cm_fields['A'] = strdup(from);
2733         }
2734         else if (fromaddr != NULL) {
2735                 msg->cm_fields['A'] = strdup(fromaddr);
2736                 if (strchr(msg->cm_fields['A'], '@')) {
2737                         *strchr(msg->cm_fields['A'], '@') = 0;
2738                 }
2739         }
2740         else {
2741                 msg->cm_fields['A'] = strdup("Citadel");
2742         }
2743
2744         if (fromaddr != NULL) msg->cm_fields['F'] = strdup(fromaddr);
2745         if (room != NULL) msg->cm_fields['O'] = strdup(room);
2746         msg->cm_fields['N'] = strdup(NODENAME);
2747         if (to != NULL) {
2748                 msg->cm_fields['R'] = strdup(to);
2749                 recp = validate_recipients(to);
2750         }
2751         if (subject != NULL) {
2752                 msg->cm_fields['U'] = strdup(subject);
2753         }
2754         msg->cm_fields['M'] = strdup(text);
2755
2756         CtdlSubmitMsg(msg, recp, room);
2757         CtdlFreeMessage(msg);
2758         if (recp != NULL) free(recp);
2759 }
2760
2761
2762
2763 /*
2764  * Back end function used by CtdlMakeMessage() and similar functions
2765  */
2766 char *CtdlReadMessageBody(char *terminator,     /* token signalling EOT */
2767                         size_t maxlen,          /* maximum message length */
2768                         char *exist,            /* if non-null, append to it;
2769                                                    exist is ALWAYS freed  */
2770                         int crlf                /* CRLF newlines instead of LF */
2771                         ) {
2772         char buf[1024];
2773         int linelen;
2774         size_t message_len = 0;
2775         size_t buffer_len = 0;
2776         char *ptr;
2777         char *m;
2778         int flushing = 0;
2779         int finished = 0;
2780         int dotdot = 0;
2781
2782         if (exist == NULL) {
2783                 m = malloc(4096);
2784                 m[0] = 0;
2785                 buffer_len = 4096;
2786                 message_len = 0;
2787         }
2788         else {
2789                 message_len = strlen(exist);
2790                 buffer_len = message_len + 4096;
2791                 m = realloc(exist, buffer_len);
2792                 if (m == NULL) {
2793                         free(exist);
2794                         return m;
2795                 }
2796         }
2797
2798         /* Do we need to change leading ".." to "." for SMTP escaping? */
2799         if (!strcmp(terminator, ".")) {
2800                 dotdot = 1;
2801         }
2802
2803         /* flush the input if we have nowhere to store it */
2804         if (m == NULL) {
2805                 flushing = 1;
2806         }
2807
2808         /* read in the lines of message text one by one */
2809         do {
2810                 if (client_getln(buf, (sizeof buf - 3)) < 1) finished = 1;
2811                 if (!strcmp(buf, terminator)) finished = 1;
2812                 if (crlf) {
2813                         strcat(buf, "\r\n");
2814                 }
2815                 else {
2816                         strcat(buf, "\n");
2817                 }
2818
2819                 /* Unescape SMTP-style input of two dots at the beginning of the line */
2820                 if (dotdot) {
2821                         if (!strncmp(buf, "..", 2)) {
2822                                 strcpy(buf, &buf[1]);
2823                         }
2824                 }
2825
2826                 if ( (!flushing) && (!finished) ) {
2827                         /* Measure the line */
2828                         linelen = strlen(buf);
2829         
2830                         /* augment the buffer if we have to */
2831                         if ((message_len + linelen) >= buffer_len) {
2832                                 ptr = realloc(m, (buffer_len * 2) );
2833                                 if (ptr == NULL) {      /* flush if can't allocate */
2834                                         flushing = 1;
2835                                 } else {
2836                                         buffer_len = (buffer_len * 2);
2837                                         m = ptr;
2838                                         lprintf(CTDL_DEBUG, "buffer_len is now %ld\n", (long)buffer_len);
2839                                 }
2840                         }
2841         
2842                         /* Add the new line to the buffer.  NOTE: this loop must avoid
2843                         * using functions like strcat() and strlen() because they
2844                         * traverse the entire buffer upon every call, and doing that
2845                         * for a multi-megabyte message slows it down beyond usability.
2846                         */
2847                         strcpy(&m[message_len], buf);
2848                         message_len += linelen;
2849                 }
2850
2851                 /* if we've hit the max msg length, flush the rest */
2852                 if (message_len >= maxlen) flushing = 1;
2853
2854         } while (!finished);
2855         return(m);
2856 }
2857
2858
2859
2860
2861 /*
2862  * Build a binary message to be saved on disk.
2863  * (NOTE: if you supply 'preformatted_text', the buffer you give it
2864  * will become part of the message.  This means you are no longer
2865  * responsible for managing that memory -- it will be freed along with
2866  * the rest of the fields when CtdlFreeMessage() is called.)
2867  */
2868
2869 struct CtdlMessage *CtdlMakeMessage(
2870         struct ctdluser *author,        /* author's user structure */
2871         char *recipient,                /* NULL if it's not mail */
2872         char *recp_cc,                  /* NULL if it's not mail */
2873         char *room,                     /* room where it's going */
2874         int type,                       /* see MES_ types in header file */
2875         int format_type,                /* variformat, plain text, MIME... */
2876         char *fake_name,                /* who we're masquerading as */
2877         char *subject,                  /* Subject (optional) */
2878         char *supplied_euid,            /* ...or NULL if this is irrelevant */
2879         char *preformatted_text         /* ...or NULL to read text from client */
2880 ) {
2881         char dest_node[SIZ];
2882         char buf[SIZ];
2883         struct CtdlMessage *msg;
2884
2885         msg = malloc(sizeof(struct CtdlMessage));
2886         memset(msg, 0, sizeof(struct CtdlMessage));
2887         msg->cm_magic = CTDLMESSAGE_MAGIC;
2888         msg->cm_anon_type = type;
2889         msg->cm_format_type = format_type;
2890
2891         /* Don't confuse the poor folks if it's not routed mail. */
2892         strcpy(dest_node, "");
2893
2894         striplt(recipient);
2895         striplt(recp_cc);
2896
2897         snprintf(buf, sizeof buf, "cit%ld", author->usernum);   /* Path */
2898         msg->cm_fields['P'] = strdup(buf);
2899
2900         snprintf(buf, sizeof buf, "%ld", (long)time(NULL));     /* timestamp */
2901         msg->cm_fields['T'] = strdup(buf);
2902
2903         if (fake_name[0])                                       /* author */
2904                 msg->cm_fields['A'] = strdup(fake_name);
2905         else
2906                 msg->cm_fields['A'] = strdup(author->fullname);
2907
2908         if (CC->room.QRflags & QR_MAILBOX) {            /* room */
2909                 msg->cm_fields['O'] = strdup(&CC->room.QRname[11]);
2910         }
2911         else {
2912                 msg->cm_fields['O'] = strdup(CC->room.QRname);
2913         }
2914
2915         msg->cm_fields['N'] = strdup(NODENAME);         /* nodename */
2916         msg->cm_fields['H'] = strdup(HUMANNODE);                /* hnodename */
2917
2918         if (recipient[0] != 0) {
2919                 msg->cm_fields['R'] = strdup(recipient);
2920         }
2921         if (recp_cc[0] != 0) {
2922                 msg->cm_fields['Y'] = strdup(recp_cc);
2923         }
2924         if (dest_node[0] != 0) {
2925                 msg->cm_fields['D'] = strdup(dest_node);
2926         }
2927
2928         if ( (author == &CC->user) && (strlen(CC->cs_inet_email) > 0) ) {
2929                 msg->cm_fields['F'] = strdup(CC->cs_inet_email);
2930         }
2931
2932         if (subject != NULL) {
2933                 striplt(subject);
2934                 if (strlen(subject) > 0) {
2935                         msg->cm_fields['U'] = strdup(subject);
2936                 }
2937         }
2938
2939         if (supplied_euid != NULL) {
2940                 msg->cm_fields['E'] = strdup(supplied_euid);
2941         }
2942
2943         if (preformatted_text != NULL) {
2944                 msg->cm_fields['M'] = preformatted_text;
2945         }
2946         else {
2947                 msg->cm_fields['M'] = CtdlReadMessageBody("000",
2948                                         config.c_maxmsglen, NULL, 0);
2949         }
2950
2951         return(msg);
2952 }
2953
2954
2955 /*
2956  * Check to see whether we have permission to post a message in the current
2957  * room.  Returns a *CITADEL ERROR CODE* and puts a message in errmsgbuf, or
2958  * returns 0 on success.
2959  */
2960 int CtdlDoIHavePermissionToPostInThisRoom(char *errmsgbuf, size_t n) {
2961
2962         if (!(CC->logged_in)) {
2963                 snprintf(errmsgbuf, n, "Not logged in.");
2964                 return (ERROR + NOT_LOGGED_IN);
2965         }
2966
2967         if ((CC->user.axlevel < 2)
2968             && ((CC->room.QRflags & QR_MAILBOX) == 0)) {
2969                 snprintf(errmsgbuf, n, "Need to be validated to enter "
2970                                 "(except in %s> to sysop)", MAILROOM);
2971                 return (ERROR + HIGHER_ACCESS_REQUIRED);
2972         }
2973
2974         if ((CC->user.axlevel < 4)
2975            && (CC->room.QRflags & QR_NETWORK)) {
2976                 snprintf(errmsgbuf, n, "Need net privileges to enter here.");
2977                 return (ERROR + HIGHER_ACCESS_REQUIRED);
2978         }
2979
2980         if ((CC->user.axlevel < 6)
2981            && (CC->room.QRflags & QR_READONLY)) {
2982                 snprintf(errmsgbuf, n, "Sorry, this is a read-only room.");
2983                 return (ERROR + HIGHER_ACCESS_REQUIRED);
2984         }
2985
2986         strcpy(errmsgbuf, "Ok");
2987         return(0);
2988 }
2989
2990
2991 /*
2992  * Check to see if the specified user has Internet mail permission
2993  * (returns nonzero if permission is granted)
2994  */
2995 int CtdlCheckInternetMailPermission(struct ctdluser *who) {
2996
2997         /* Do not allow twits to send Internet mail */
2998         if (who->axlevel <= 2) return(0);
2999
3000         /* Globally enabled? */
3001         if (config.c_restrict == 0) return(1);
3002
3003         /* User flagged ok? */
3004         if (who->flags & US_INTERNET) return(2);
3005
3006         /* Aide level access? */
3007         if (who->axlevel >= 6) return(3);
3008
3009         /* No mail for you! */
3010         return(0);
3011 }
3012
3013
3014 /*
3015  * Validate recipients, count delivery types and errors, and handle aliasing
3016  * FIXME check for dupes!!!!!
3017  * Returns 0 if all addresses are ok, ret->num_error = -1 if no addresses 
3018  * were specified, or the number of addresses found invalid.
3019  * caller needs to free the result.
3020  */
3021 struct recptypes *validate_recipients(char *supplied_recipients) {
3022         struct recptypes *ret;
3023         char recipients[SIZ];
3024         char this_recp[256];
3025         char this_recp_cooked[256];
3026         char append[SIZ];
3027         int num_recps = 0;
3028         int i, j;
3029         int mailtype;
3030         int invalid;
3031         struct ctdluser tempUS;
3032         struct ctdlroom tempQR;
3033         int in_quotes = 0;
3034
3035         /* Initialize */
3036         ret = (struct recptypes *) malloc(sizeof(struct recptypes));
3037         if (ret == NULL) return(NULL);
3038         memset(ret, 0, sizeof(struct recptypes));
3039
3040         ret->num_local = 0;
3041         ret->num_internet = 0;
3042         ret->num_ignet = 0;
3043         ret->num_error = 0;
3044         ret->num_room = 0;
3045
3046         if (supplied_recipients == NULL) {
3047                 strcpy(recipients, "");
3048         }
3049         else {
3050                 safestrncpy(recipients, supplied_recipients, sizeof recipients);
3051         }
3052
3053         /* Change all valid separator characters to commas */
3054         for (i=0; i<strlen(recipients); ++i) {
3055                 if ((recipients[i] == ';') || (recipients[i] == '|')) {
3056                         recipients[i] = ',';
3057                 }
3058         }
3059
3060         /* Now start extracting recipients... */
3061
3062         while (strlen(recipients) > 0) {
3063
3064                 for (i=0; i<=strlen(recipients); ++i) {
3065                         if (recipients[i] == '\"') in_quotes = 1 - in_quotes;
3066                         if ( ( (recipients[i] == ',') && (!in_quotes) ) || (recipients[i] == 0) ) {
3067                                 safestrncpy(this_recp, recipients, i+1);
3068                                 this_recp[i] = 0;
3069                                 if (recipients[i] == ',') {
3070                                         strcpy(recipients, &recipients[i+1]);
3071                                 }
3072                                 else {
3073                                         strcpy(recipients, "");
3074                                 }
3075                                 break;
3076                         }
3077                 }
3078
3079                 striplt(this_recp);
3080                 lprintf(CTDL_DEBUG, "Evaluating recipient #%d: %s\n", num_recps, this_recp);
3081                 ++num_recps;
3082                 mailtype = alias(this_recp);
3083                 mailtype = alias(this_recp);
3084                 mailtype = alias(this_recp);
3085                 for (j=0; j<=strlen(this_recp); ++j) {
3086                         if (this_recp[j]=='_') {
3087                                 this_recp_cooked[j] = ' ';
3088                         }
3089                         else {
3090                                 this_recp_cooked[j] = this_recp[j];
3091                         }
3092                 }
3093                 invalid = 0;
3094                 switch(mailtype) {
3095                         case MES_LOCAL:
3096                                 if (!strcasecmp(this_recp, "sysop")) {
3097                                         ++ret->num_room;
3098                                         strcpy(this_recp, config.c_aideroom);
3099                                         if (strlen(ret->recp_room) > 0) {
3100                                                 strcat(ret->recp_room, "|");
3101                                         }
3102                                         strcat(ret->recp_room, this_recp);
3103                                 }
3104                                 else if (getuser(&tempUS, this_recp) == 0) {
3105                                         ++ret->num_local;
3106                                         strcpy(this_recp, tempUS.fullname);
3107                                         if (strlen(ret->recp_local) > 0) {
3108                                                 strcat(ret->recp_local, "|");
3109                                         }
3110                                         strcat(ret->recp_local, this_recp);
3111                                 }
3112                                 else if (getuser(&tempUS, this_recp_cooked) == 0) {
3113                                         ++ret->num_local;
3114                                         strcpy(this_recp, tempUS.fullname);
3115                                         if (strlen(ret->recp_local) > 0) {
3116                                                 strcat(ret->recp_local, "|");
3117                                         }
3118                                         strcat(ret->recp_local, this_recp);
3119                                 }
3120                                 else if ( (!strncasecmp(this_recp, "room_", 5))
3121                                       && (!getroom(&tempQR, &this_recp_cooked[5])) ) {
3122                                         ++ret->num_room;
3123                                         if (strlen(ret->recp_room) > 0) {
3124                                                 strcat(ret->recp_room, "|");
3125                                         }
3126                                         strcat(ret->recp_room, &this_recp_cooked[5]);
3127                                 }
3128                                 else {
3129                                         ++ret->num_error;
3130                                         invalid = 1;
3131                                 }
3132                                 break;
3133                         case MES_INTERNET:
3134                                 /* Yes, you're reading this correctly: if the target
3135                                  * domain points back to the local system or an attached
3136                                  * Citadel directory, the address is invalid.  That's
3137                                  * because if the address were valid, we would have
3138                                  * already translated it to a local address by now.
3139                                  */
3140                                 if (IsDirectory(this_recp)) {
3141                                         ++ret->num_error;
3142                                         invalid = 1;
3143                                 }
3144                                 else {
3145                                         ++ret->num_internet;
3146                                         if (strlen(ret->recp_internet) > 0) {
3147                                                 strcat(ret->recp_internet, "|");
3148                                         }
3149                                         strcat(ret->recp_internet, this_recp);
3150                                 }
3151                                 break;
3152                         case MES_IGNET:
3153                                 ++ret->num_ignet;
3154                                 if (strlen(ret->recp_ignet) > 0) {
3155                                         strcat(ret->recp_ignet, "|");
3156                                 }
3157                                 strcat(ret->recp_ignet, this_recp);
3158                                 break;
3159                         case MES_ERROR:
3160                                 ++ret->num_error;
3161                                 invalid = 1;
3162                                 break;
3163                 }
3164                 if (invalid) {
3165                         if (strlen(ret->errormsg) == 0) {
3166                                 snprintf(append, sizeof append,
3167                                          "Invalid recipient: %s",
3168                                          this_recp);
3169                         }
3170                         else {
3171                                 snprintf(append, sizeof append,
3172                                          ", %s", this_recp);
3173                         }
3174                         if ( (strlen(ret->errormsg) + strlen(append)) < SIZ) {
3175                                 strcat(ret->errormsg, append);
3176                         }
3177                 }
3178                 else {
3179                         if (strlen(ret->display_recp) == 0) {
3180                                 strcpy(append, this_recp);
3181                         }
3182                         else {
3183                                 snprintf(append, sizeof append, ", %s",
3184                                          this_recp);
3185                         }
3186                         if ( (strlen(ret->display_recp)+strlen(append)) < SIZ) {
3187                                 strcat(ret->display_recp, append);
3188                         }
3189                 }
3190         }
3191
3192         if ((ret->num_local + ret->num_internet + ret->num_ignet +
3193            ret->num_room + ret->num_error) == 0) {
3194                 ret->num_error = (-1);
3195                 strcpy(ret->errormsg, "No recipients specified.");
3196         }
3197
3198         lprintf(CTDL_DEBUG, "validate_recipients()\n");
3199         lprintf(CTDL_DEBUG, " local: %d <%s>\n", ret->num_local, ret->recp_local);
3200         lprintf(CTDL_DEBUG, "  room: %d <%s>\n", ret->num_room, ret->recp_room);
3201         lprintf(CTDL_DEBUG, "  inet: %d <%s>\n", ret->num_internet, ret->recp_internet);
3202         lprintf(CTDL_DEBUG, " ignet: %d <%s>\n", ret->num_ignet, ret->recp_ignet);
3203         lprintf(CTDL_DEBUG, " error: %d <%s>\n", ret->num_error, ret->errormsg);
3204
3205         return(ret);
3206 }
3207
3208
3209
3210 /*
3211  * message entry  -  mode 0 (normal)
3212  */
3213 void cmd_ent0(char *entargs)
3214 {
3215         int post = 0;
3216         char recp[SIZ];
3217         char cc[SIZ];
3218         char bcc[SIZ];
3219         char supplied_euid[128];
3220         char masquerade_as[SIZ];
3221         int anon_flag = 0;
3222         int format_type = 0;
3223         char newusername[SIZ];
3224         struct CtdlMessage *msg;
3225         int anonymous = 0;
3226         char errmsg[SIZ];
3227         int err = 0;
3228         struct recptypes *valid = NULL;
3229         struct recptypes *valid_to = NULL;
3230         struct recptypes *valid_cc = NULL;
3231         struct recptypes *valid_bcc = NULL;
3232         char subject[SIZ];
3233         int do_confirm = 0;
3234         long msgnum;
3235
3236         unbuffer_output();
3237
3238         post = extract_int(entargs, 0);
3239         extract_token(recp, entargs, 1, '|', sizeof recp);
3240         anon_flag = extract_int(entargs, 2);
3241         format_type = extract_int(entargs, 3);
3242         extract_token(subject, entargs, 4, '|', sizeof subject);
3243         do_confirm = extract_int(entargs, 6);
3244         extract_token(cc, entargs, 7, '|', sizeof cc);
3245         extract_token(bcc, entargs, 8, '|', sizeof bcc);
3246         switch(CC->room.QRdefaultview) {
3247                 case VIEW_NOTES:
3248                 case VIEW_WIKI:
3249                         extract_token(supplied_euid, entargs, 9, '|', sizeof supplied_euid);
3250                         break;
3251                 default:
3252                         supplied_euid[0] = 0;
3253                         break;
3254         }
3255
3256         /* first check to make sure the request is valid. */
3257
3258         err = CtdlDoIHavePermissionToPostInThisRoom(errmsg, sizeof errmsg);
3259         if (err) {
3260                 cprintf("%d %s\n", err, errmsg);
3261                 return;
3262         }
3263
3264         /* Check some other permission type things. */
3265
3266         if (post == 2) {
3267                 if (CC->user.axlevel < 6) {
3268                         cprintf("%d You don't have permission to masquerade.\n",
3269                                 ERROR + HIGHER_ACCESS_REQUIRED);
3270                         return;
3271                 }
3272                 extract_token(newusername, entargs, 5, '|', sizeof newusername);
3273                 memset(CC->fake_postname, 0, sizeof(CC->fake_postname) );
3274                 safestrncpy(CC->fake_postname, newusername,
3275                         sizeof(CC->fake_postname) );
3276                 cprintf("%d ok\n", CIT_OK);
3277                 return;
3278         }
3279         CC->cs_flags |= CS_POSTING;
3280
3281         /* In the Mail> room we have to behave a little differently --
3282          * make sure the user has specified at least one recipient.  Then
3283          * validate the recipient(s).
3284          */
3285         if ( (CC->room.QRflags & QR_MAILBOX)
3286            && (!strcasecmp(&CC->room.QRname[11], MAILROOM)) ) {
3287
3288                 if (CC->user.axlevel < 2) {
3289                         strcpy(recp, "sysop");
3290                         strcpy(cc, "");
3291                         strcpy(bcc, "");
3292                 }
3293
3294                 valid_to = validate_recipients(recp);
3295                 if (valid_to->num_error > 0) {
3296                         cprintf("%d Invalid recipient (To)\n", ERROR + NO_SUCH_USER);
3297                         free(valid_to);
3298                         return;
3299                 }
3300
3301                 valid_cc = validate_recipients(cc);
3302                 if (valid_cc->num_error > 0) {
3303                         cprintf("%d Invalid recipient (CC)\n", ERROR + NO_SUCH_USER);
3304                         free(valid_to);
3305                         free(valid_cc);
3306                         return;
3307                 }
3308
3309                 valid_bcc = validate_recipients(bcc);
3310                 if (valid_bcc->num_error > 0) {
3311                         cprintf("%d Invalid recipient (BCC)\n", ERROR + NO_SUCH_USER);
3312                         free(valid_to);
3313                         free(valid_cc);
3314                         free(valid_bcc);
3315                         return;
3316                 }
3317
3318                 /* Recipient required, but none were specified */
3319                 if ( (valid_to->num_error < 0) && (valid_cc->num_error < 0) && (valid_bcc->num_error < 0) ) {
3320                         free(valid_to);
3321                         free(valid_cc);
3322                         free(valid_bcc);
3323                         cprintf("%d At least one recipient is required.\n", ERROR + NO_SUCH_USER);
3324                         return;
3325                 }
3326
3327                 if (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0) {
3328                         if (CtdlCheckInternetMailPermission(&CC->user)==0) {
3329                                 cprintf("%d You do not have permission "
3330                                         "to send Internet mail.\n",
3331                                         ERROR + HIGHER_ACCESS_REQUIRED);
3332                                 free(valid_to);
3333                                 free(valid_cc);
3334                                 free(valid_bcc);
3335                                 return;
3336                         }
3337                 }
3338
3339                 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)
3340                    && (CC->user.axlevel < 4) ) {
3341                         cprintf("%d Higher access required for network mail.\n",
3342                                 ERROR + HIGHER_ACCESS_REQUIRED);
3343                         free(valid_to);
3344                         free(valid_cc);
3345                         free(valid_bcc);
3346                         return;
3347                 }
3348         
3349                 if ((RESTRICT_INTERNET == 1)
3350                     && (valid_to->num_internet + valid_cc->num_internet + valid_bcc->num_internet > 0)
3351                     && ((CC->user.flags & US_INTERNET) == 0)
3352                     && (!CC->internal_pgm)) {
3353                         cprintf("%d You don't have access to Internet mail.\n",
3354                                 ERROR + HIGHER_ACCESS_REQUIRED);
3355                         free(valid_to);
3356                         free(valid_cc);
3357                         free(valid_bcc);
3358                         return;
3359                 }
3360
3361         }
3362
3363         /* Is this a room which has anonymous-only or anonymous-option? */
3364         anonymous = MES_NORMAL;
3365         if (CC->room.QRflags & QR_ANONONLY) {
3366                 anonymous = MES_ANONONLY;
3367         }
3368         if (CC->room.QRflags & QR_ANONOPT) {
3369                 if (anon_flag == 1) {   /* only if the user requested it */
3370                         anonymous = MES_ANONOPT;
3371                 }
3372         }
3373
3374         if ((CC->room.QRflags & QR_MAILBOX) == 0) {
3375                 recp[0] = 0;
3376         }
3377
3378         /* If we're only checking the validity of the request, return
3379          * success without creating the message.
3380          */
3381         if (post == 0) {
3382                 cprintf("%d %s\n", CIT_OK,
3383                         ((valid_to != NULL) ? valid_to->display_recp : "") );
3384                 free(valid_to);
3385                 free(valid_cc);
3386                 free(valid_bcc);
3387                 return;
3388         }
3389
3390         /* We don't need these anymore because we'll do it differently below */
3391         free(valid_to);
3392         free(valid_cc);
3393         free(valid_bcc);
3394
3395         /* Handle author masquerading */
3396         if (CC->fake_postname[0]) {
3397                 strcpy(masquerade_as, CC->fake_postname);
3398         }
3399         else if (CC->fake_username[0]) {
3400                 strcpy(masquerade_as, CC->fake_username);
3401         }
3402         else {
3403                 strcpy(masquerade_as, "");
3404         }
3405
3406         /* Read in the message from the client. */
3407         if (do_confirm) {
3408                 cprintf("%d send message\n", START_CHAT_MODE);
3409         } else {
3410                 cprintf("%d send message\n", SEND_LISTING);
3411         }
3412
3413         msg = CtdlMakeMessage(&CC->user, recp, cc,
3414                 CC->room.QRname, anonymous, format_type,
3415                 masquerade_as, subject,
3416                 ((strlen(supplied_euid) > 0) ? supplied_euid : NULL),
3417                 NULL);
3418
3419         /* Put together one big recipients struct containing to/cc/bcc all in
3420          * one.  This is for the envelope.
3421          */
3422         char *all_recps = malloc(SIZ * 3);
3423         strcpy(all_recps, recp);
3424         if (strlen(cc) > 0) {
3425                 if (strlen(all_recps) > 0) {
3426                         strcat(all_recps, ",");
3427                 }
3428                 strcat(all_recps, cc);
3429         }
3430         if (strlen(bcc) > 0) {
3431                 if (strlen(all_recps) > 0) {
3432                         strcat(all_recps, ",");
3433                 }
3434                 strcat(all_recps, bcc);
3435         }
3436         if (strlen(all_recps) > 0) {
3437                 valid = validate_recipients(all_recps);
3438         }
3439         else {
3440                 valid = NULL;
3441         }
3442         free(all_recps);
3443
3444         if (msg != NULL) {
3445                 msgnum = CtdlSubmitMsg(msg, valid, "");
3446
3447                 if (do_confirm) {
3448                         cprintf("%ld\n", msgnum);
3449                         if (msgnum >= 0L) {
3450                                 cprintf("Message accepted.\n");
3451                         }
3452                         else {
3453                                 cprintf("Internal error.\n");
3454                         }
3455                         if (msg->cm_fields['E'] != NULL) {
3456                                 cprintf("%s\n", msg->cm_fields['E']);
3457                         } else {
3458                                 cprintf("\n");
3459                         }
3460                         cprintf("000\n");
3461                 }
3462
3463                 CtdlFreeMessage(msg);
3464         }
3465         CC->fake_postname[0] = '\0';
3466         if (valid != NULL) {
3467                 free(valid);
3468         }
3469         return;
3470 }
3471
3472
3473
3474 /*
3475  * API function to delete messages which match a set of criteria
3476  * (returns the actual number of messages deleted)
3477  */
3478 int CtdlDeleteMessages(char *room_name,         /* which room */
3479                         long *dmsgnums,         /* array of msg numbers to be deleted */
3480                         int num_dmsgnums,       /* number of msgs to be deleted, or 0 for "any" */
3481                         char *content_type,     /* or "" for any */
3482                         int deferred            /* let TDAP sweep it later */
3483 )
3484 {
3485
3486         struct ctdlroom qrbuf;
3487         struct cdbdata *cdbfr;
3488         long *msglist = NULL;
3489         long *dellist = NULL;
3490         int num_msgs = 0;
3491         int i, j;
3492         int num_deleted = 0;
3493         int delete_this;
3494         struct MetaData smi;
3495
3496         lprintf(CTDL_DEBUG, "CtdlDeleteMessages(%s, %d msgs, %s, %d)\n",
3497                 room_name, num_dmsgnums, content_type, deferred);
3498
3499         /* get room record, obtaining a lock... */
3500         if (lgetroom(&qrbuf, room_name) != 0) {
3501                 lprintf(CTDL_ERR, "CtdlDeleteMessages(): Room <%s> not found\n",
3502                         room_name);
3503                 return (0);     /* room not found */
3504         }
3505         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
3506
3507         if (cdbfr != NULL) {
3508                 dellist = malloc(cdbfr->len);
3509                 msglist = (long *) cdbfr->ptr;
3510                 cdbfr->ptr = NULL;      /* CtdlDeleteMessages() now owns this memory */
3511                 num_msgs = cdbfr->len / sizeof(long);
3512                 cdb_free(cdbfr);
3513         }
3514         if (num_msgs > 0) {
3515                 for (i = 0; i < num_msgs; ++i) {
3516                         delete_this = 0x00;
3517
3518                         /* Set/clear a bit for each criterion */
3519
3520                         /* 0 messages in the list or a null list means that we are
3521                          * interested in deleting any messages which meet the other criteria.
3522                          */
3523                         if ((num_dmsgnums == 0) || (dmsgnums == NULL)) {
3524                                 delete_this |= 0x01;
3525                         }
3526                         else {
3527                                 for (j=0; j<num_dmsgnums; ++j) {
3528                                         if (msglist[i] == dmsgnums[j]) {
3529                                                 delete_this |= 0x01;
3530                                         }
3531                                 }
3532                         }
3533
3534                         if (strlen(content_type) == 0) {
3535                                 delete_this |= 0x02;
3536                         } else {
3537                                 GetMetaData(&smi, msglist[i]);
3538                                 if (!strcasecmp(smi.meta_content_type,
3539                                                 content_type)) {
3540                                         delete_this |= 0x02;
3541                                 }
3542                         }
3543
3544                         /* Delete message only if all bits are set */
3545                         if (delete_this == 0x03) {
3546                                 dellist[num_deleted++] = msglist[i];
3547                                 msglist[i] = 0L;
3548                         }
3549                 }
3550
3551                 num_msgs = sort_msglist(msglist, num_msgs);
3552                 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, (int)sizeof(long),
3553                           msglist, (int)(num_msgs * sizeof(long)));
3554
3555                 qrbuf.QRhighest = msglist[num_msgs - 1];
3556         }
3557         lputroom(&qrbuf);
3558
3559         /*
3560          * If the delete operation is "deferred" (and technically, any delete
3561          * operation not performed by THE DREADED AUTO-PURGER ought to be
3562          * a deferred delete) then we save a pointer to the message in the
3563          * DELETED_MSGS_ROOM.  This will cause the reference count to remain
3564          * at least 1, which will save the user from having to synchronously
3565          * wait for various disk-intensive operations to complete.
3566          *
3567          * Slick -- we now use the new bulk API for moving messages.
3568          */
3569         if ( (deferred) && (num_deleted) ) {
3570                 CtdlCopyMsgsToRoom(dellist, num_deleted, DELETED_MSGS_ROOM);
3571         }
3572
3573         /* Go through the messages we pulled out of the index, and decrement
3574          * their reference counts by 1.  If this is the only room the message
3575          * was in, the reference count will reach zero and the message will
3576          * automatically be deleted from the database.  We do this in a
3577          * separate pass because there might be plug-in hooks getting called,
3578          * and we don't want that happening during an S_ROOMS critical
3579          * section.
3580          */
3581         if (num_deleted) for (i=0; i<num_deleted; ++i) {
3582                 PerformDeleteHooks(qrbuf.QRname, dellist[i]);
3583                 AdjRefCount(dellist[i], -1);
3584         }
3585
3586         /* Now free the memory we used, and go away. */
3587         if (msglist != NULL) free(msglist);
3588         if (dellist != NULL) free(dellist);
3589         lprintf(CTDL_DEBUG, "%d message(s) deleted.\n", num_deleted);
3590         return (num_deleted);
3591 }
3592
3593
3594
3595 /*
3596  * Check whether the current user has permission to delete messages from
3597  * the current room (returns 1 for yes, 0 for no)
3598  */
3599 int CtdlDoIHavePermissionToDeleteMessagesFromThisRoom(void) {
3600         getuser(&CC->user, CC->curr_user);
3601         if ((CC->user.axlevel < 6)
3602             && (CC->user.usernum != CC->room.QRroomaide)
3603             && ((CC->room.QRflags & QR_MAILBOX) == 0)
3604             && (!(CC->internal_pgm))) {
3605                 return(0);
3606         }
3607         return(1);
3608 }
3609
3610
3611
3612 /*
3613  * Delete message from current room
3614  */
3615 void cmd_dele(char *args)
3616 {
3617         int num_deleted;
3618         int i;
3619         char msgset[SIZ];
3620         char msgtok[32];
3621         long *msgs;
3622         int num_msgs = 0;
3623
3624         extract_token(msgset, args, 0, '|', sizeof msgset);
3625         num_msgs = num_tokens(msgset, ',');
3626         if (num_msgs < 1) {
3627                 cprintf("%d Nothing to do.\n", CIT_OK);
3628                 return;
3629         }
3630
3631         if (CtdlDoIHavePermissionToDeleteMessagesFromThisRoom() == 0) {
3632                 cprintf("%d Higher access required.\n",
3633                         ERROR + HIGHER_ACCESS_REQUIRED);
3634                 return;
3635         }
3636
3637         /*
3638          * Build our message set to be moved/copied
3639          */
3640         msgs = malloc(num_msgs * sizeof(long));
3641         for (i=0; i<num_msgs; ++i) {
3642                 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3643                 msgs[i] = atol(msgtok);
3644         }
3645
3646         num_deleted = CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "", 1);
3647         free(msgs);
3648
3649         if (num_deleted) {
3650                 cprintf("%d %d message%s deleted.\n", CIT_OK,
3651                         num_deleted, ((num_deleted != 1) ? "s" : ""));
3652         } else {
3653                 cprintf("%d Message not found.\n", ERROR + MESSAGE_NOT_FOUND);
3654         }
3655 }
3656
3657
3658 /*
3659  * Back end API function for moves and deletes (multiple messages)
3660  */
3661 int CtdlCopyMsgsToRoom(long *msgnums, int num_msgs, char *dest) {
3662         int err;
3663
3664         err = CtdlSaveMsgPointersInRoom(dest, msgnums, num_msgs, 1, NULL);
3665         if (err != 0) return(err);
3666
3667         return(0);
3668 }
3669
3670
3671
3672
3673 /*
3674  * move or copy a message to another room
3675  */
3676 void cmd_move(char *args)
3677 {
3678         char msgset[SIZ];
3679         char msgtok[32];
3680         long *msgs;
3681         int num_msgs = 0;
3682
3683         char targ[ROOMNAMELEN];
3684         struct ctdlroom qtemp;
3685         int err;
3686         int is_copy = 0;
3687         int ra;
3688         int permit = 0;
3689         int i;
3690
3691         extract_token(msgset, args, 0, '|', sizeof msgset);
3692         num_msgs = num_tokens(msgset, ',');
3693         if (num_msgs < 1) {
3694                 cprintf("%d Nothing to do.\n", CIT_OK);
3695                 return;
3696         }
3697
3698         extract_token(targ, args, 1, '|', sizeof targ);
3699         convert_room_name_macros(targ, sizeof targ);
3700         targ[ROOMNAMELEN - 1] = 0;
3701         is_copy = extract_int(args, 2);
3702
3703         if (getroom(&qtemp, targ) != 0) {
3704                 cprintf("%d '%s' does not exist.\n",
3705                         ERROR + ROOM_NOT_FOUND, targ);
3706                 return;
3707         }
3708
3709         getuser(&CC->user, CC->curr_user);
3710         CtdlRoomAccess(&qtemp, &CC->user, &ra, NULL);
3711
3712         /* Check for permission to perform this operation.
3713          * Remember: "CC->room" is source, "qtemp" is target.
3714          */
3715         permit = 0;
3716
3717         /* Aides can move/copy */
3718         if (CC->user.axlevel >= 6) permit = 1;
3719
3720         /* Room aides can move/copy */
3721         if (CC->user.usernum == CC->room.QRroomaide) permit = 1;
3722
3723         /* Permit move/copy from personal rooms */
3724         if ((CC->room.QRflags & QR_MAILBOX)
3725            && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3726
3727         /* Permit only copy from public to personal room */
3728         if ( (is_copy)
3729            && (!(CC->room.QRflags & QR_MAILBOX))
3730            && (qtemp.QRflags & QR_MAILBOX)) permit = 1;
3731
3732         /* User must have access to target room */
3733         if (!(ra & UA_KNOWN))  permit = 0;
3734
3735         if (!permit) {
3736                 cprintf("%d Higher access required.\n",
3737                         ERROR + HIGHER_ACCESS_REQUIRED);
3738                 return;
3739         }
3740
3741         /*
3742          * Build our message set to be moved/copied
3743          */
3744         msgs = malloc(num_msgs * sizeof(long));
3745         for (i=0; i<num_msgs; ++i) {
3746                 extract_token(msgtok, msgset, i, ',', sizeof msgtok);
3747                 msgs[i] = atol(msgtok);
3748         }
3749
3750         /*
3751          * Do the copy
3752          */
3753         err = CtdlCopyMsgsToRoom(msgs, num_msgs, targ);
3754         if (err != 0) {
3755                 cprintf("%d Cannot store message(s) in %s: error %d\n",
3756                         err, targ, err);
3757                 free(msgs);
3758                 return;
3759         }
3760
3761         /* Now delete the message from the source room,
3762          * if this is a 'move' rather than a 'copy' operation.
3763          */
3764         if (is_copy == 0) {
3765                 CtdlDeleteMessages(CC->room.QRname, msgs, num_msgs, "", 0);
3766         }
3767         free(msgs);
3768
3769         cprintf("%d Message(s) %s.\n", CIT_OK, (is_copy ? "copied" : "moved") );
3770 }
3771
3772
3773
3774 /*
3775  * GetMetaData()  -  Get the supplementary record for a message
3776  */
3777 void GetMetaData(struct MetaData *smibuf, long msgnum)
3778 {
3779
3780         struct cdbdata *cdbsmi;
3781         long TheIndex;
3782
3783         memset(smibuf, 0, sizeof(struct MetaData));
3784         smibuf->meta_msgnum = msgnum;
3785         smibuf->meta_refcount = 1;      /* Default reference count is 1 */
3786
3787         /* Use the negative of the message number for its supp record index */
3788         TheIndex = (0L - msgnum);
3789
3790         cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
3791         if (cdbsmi == NULL) {
3792                 return;         /* record not found; go with defaults */
3793         }
3794         memcpy(smibuf, cdbsmi->ptr,
3795                ((cdbsmi->len > sizeof(struct MetaData)) ?
3796                 sizeof(struct MetaData) : cdbsmi->len));
3797         cdb_free(cdbsmi);
3798         return;
3799 }
3800
3801
3802 /*
3803  * PutMetaData()  -  (re)write supplementary record for a message
3804  */
3805 void PutMetaData(struct MetaData *smibuf)
3806 {
3807         long TheIndex;
3808
3809         /* Use the negative of the message number for the metadata db index */
3810         TheIndex = (0L - smibuf->meta_msgnum);
3811
3812         lprintf(CTDL_DEBUG, "PutMetaData(%ld) - ref count is %d\n",
3813                 smibuf->meta_msgnum, smibuf->meta_refcount);
3814
3815         cdb_store(CDB_MSGMAIN,
3816                   &TheIndex, (int)sizeof(long),
3817                   smibuf, (int)sizeof(struct MetaData));
3818
3819 }
3820
3821 /*
3822  * AdjRefCount  -  change the reference count for a message;
3823  *               delete the message if it reaches zero
3824  */
3825 void AdjRefCount(long msgnum, int incr)
3826 {
3827
3828         struct MetaData smi;
3829         long delnum;
3830
3831         /* This is a *tight* critical section; please keep it that way, as
3832          * it may get called while nested in other critical sections.  
3833          * Complicating this any further will surely cause deadlock!
3834          */
3835         begin_critical_section(S_SUPPMSGMAIN);
3836         GetMetaData(&smi, msgnum);
3837         smi.meta_refcount += incr;
3838         PutMetaData(&smi);
3839         end_critical_section(S_SUPPMSGMAIN);
3840         lprintf(CTDL_DEBUG, "msg %ld ref count incr %d, is now %d\n",
3841                 msgnum, incr, smi.meta_refcount);
3842
3843         /* If the reference count is now zero, delete the message
3844          * (and its supplementary record as well).
3845          */
3846         if (smi.meta_refcount == 0) {
3847                 lprintf(CTDL_DEBUG, "Deleting message <%ld>\n", msgnum);
3848
3849                 /* Remove from fulltext index */
3850                 if (config.c_enable_fulltext) {
3851                         ft_index_message(msgnum, 0);
3852                 }
3853
3854                 /* Remove from message base */
3855                 delnum = msgnum;
3856                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3857                 cdb_delete(CDB_BIGMSGS, &delnum, (int)sizeof(long));
3858
3859                 /* Remove metadata record */
3860                 delnum = (0L - msgnum);
3861                 cdb_delete(CDB_MSGMAIN, &delnum, (int)sizeof(long));
3862         }
3863 }
3864
3865 /*
3866  * Write a generic object to this room
3867  *
3868  * Note: this could be much more efficient.  Right now we use two temporary
3869  * files, and still pull the message into memory as with all others.
3870  */
3871 void CtdlWriteObject(char *req_room,            /* Room to stuff it in */
3872                         char *content_type,     /* MIME type of this object */
3873                         char *tempfilename,     /* Where to fetch it from */
3874                         struct ctdluser *is_mailbox,    /* Mailbox room? */
3875                         int is_binary,          /* Is encoding necessary? */
3876                         int is_unique,          /* Del others of this type? */
3877                         unsigned int flags      /* Internal save flags */
3878                         )
3879 {
3880
3881         FILE *fp;
3882         struct ctdlroom qrbuf;
3883         char roomname[ROOMNAMELEN];
3884         struct CtdlMessage *msg;
3885
3886         char *raw_message = NULL;
3887         char *encoded_message = NULL;
3888         off_t raw_length = 0;
3889
3890         if (is_mailbox != NULL) {
3891                 MailboxName(roomname, sizeof roomname, is_mailbox, req_room);
3892         }
3893         else {
3894                 safestrncpy(roomname, req_room, sizeof(roomname));
3895         }
3896
3897         fp = fopen(tempfilename, "rb");
3898         if (fp == NULL) {
3899                 lprintf(CTDL_CRIT, "Cannot open %s: %s\n",
3900                         tempfilename, strerror(errno));
3901                 return;
3902         }
3903         fseek(fp, 0L, SEEK_END);
3904         raw_length = ftell(fp);
3905         rewind(fp);
3906         lprintf(CTDL_DEBUG, "Raw length is %ld\n", (long)raw_length);
3907
3908         raw_message = malloc((size_t)raw_length + 2);
3909         fread(raw_message, (size_t)raw_length, 1, fp);
3910         fclose(fp);
3911
3912         if (is_binary) {
3913                 encoded_message = malloc((size_t)
3914                         (((raw_length * 134) / 100) + 4096 ) );
3915         }
3916         else {
3917                 encoded_message = malloc((size_t)(raw_length + 4096));
3918         }
3919
3920         sprintf(encoded_message, "Content-type: %s\n", content_type);
3921
3922         if (is_binary) {
3923                 sprintf(&encoded_message[strlen(encoded_message)],
3924                         "Content-transfer-encoding: base64\n\n"
3925                 );
3926         }
3927         else {
3928                 sprintf(&encoded_message[strlen(encoded_message)],
3929                         "Content-transfer-encoding: 7bit\n\n"
3930                 );
3931         }
3932
3933         if (is_binary) {
3934                 CtdlEncodeBase64(
3935                         &encoded_message[strlen(encoded_message)],
3936                         raw_message,
3937                         (int)raw_length
3938                 );
3939         }
3940         else {
3941                 raw_message[raw_length] = 0;
3942                 memcpy(
3943                         &encoded_message[strlen(encoded_message)],
3944                         raw_message,
3945                         (int)(raw_length+1)
3946                 );
3947         }
3948
3949         free(raw_message);
3950
3951         lprintf(CTDL_DEBUG, "Allocating\n");
3952         msg = malloc(sizeof(struct CtdlMessage));
3953         memset(msg, 0, sizeof(struct CtdlMessage));
3954         msg->cm_magic = CTDLMESSAGE_MAGIC;
3955         msg->cm_anon_type = MES_NORMAL;
3956         msg->cm_format_type = 4;
3957         msg->cm_fields['A'] = strdup(CC->user.fullname);
3958         msg->cm_fields['O'] = strdup(req_room);
3959         msg->cm_fields['N'] = strdup(config.c_nodename);
3960         msg->cm_fields['H'] = strdup(config.c_humannode);
3961         msg->cm_flags = flags;
3962         
3963         msg->cm_fields['M'] = encoded_message;
3964
3965         /* Create the requested room if we have to. */
3966         if (getroom(&qrbuf, roomname) != 0) {
3967                 create_room(roomname, 
3968                         ( (is_mailbox != NULL) ? 5 : 3 ),
3969                         "", 0, 1, 0, VIEW_BBS);
3970         }
3971         /* If the caller specified this object as unique, delete all
3972          * other objects of this type that are currently in the room.
3973          */
3974         if (is_unique) {
3975                 lprintf(CTDL_DEBUG, "Deleted %d other msgs of this type\n",
3976                         CtdlDeleteMessages(roomname, NULL, 0, content_type, 0)
3977                 );
3978         }
3979         /* Now write the data */
3980         CtdlSubmitMsg(msg, NULL, roomname);
3981         CtdlFreeMessage(msg);
3982 }
3983
3984
3985
3986
3987
3988
3989 void CtdlGetSysConfigBackend(long msgnum, void *userdata) {
3990         config_msgnum = msgnum;
3991 }
3992
3993
3994 char *CtdlGetSysConfig(char *sysconfname) {
3995         char hold_rm[ROOMNAMELEN];
3996         long msgnum;
3997         char *conf;
3998         struct CtdlMessage *msg;
3999         char buf[SIZ];
4000         
4001         strcpy(hold_rm, CC->room.QRname);
4002         if (getroom(&CC->room, SYSCONFIGROOM) != 0) {
4003                 getroom(&CC->room, hold_rm);
4004                 return NULL;
4005         }
4006
4007
4008         /* We want the last (and probably only) config in this room */
4009         begin_critical_section(S_CONFIG);
4010         config_msgnum = (-1L);
4011         CtdlForEachMessage(MSGS_LAST, 1, NULL, sysconfname, NULL,
4012                 CtdlGetSysConfigBackend, NULL);
4013         msgnum = config_msgnum;
4014         end_critical_section(S_CONFIG);
4015
4016         if (msgnum < 0L) {
4017                 conf = NULL;
4018         }
4019         else {
4020                 msg = CtdlFetchMessage(msgnum, 1);
4021                 if (msg != NULL) {
4022                         conf = strdup(msg->cm_fields['M']);
4023                         CtdlFreeMessage(msg);
4024                 }
4025                 else {
4026                         conf = NULL;
4027                 }
4028         }
4029
4030         getroom(&CC->room, hold_rm);
4031
4032         if (conf != NULL) do {
4033                 extract_token(buf, conf, 0, '\n', sizeof buf);
4034                 strcpy(conf, &conf[strlen(buf)+1]);
4035         } while ( (strlen(conf)>0) && (strlen(buf)>0) );
4036
4037         return(conf);
4038 }
4039
4040 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
4041         char temp[PATH_MAX];
4042         FILE *fp;
4043
4044         CtdlMakeTempFileName(temp, sizeof temp);
4045
4046         fp = fopen(temp, "w");
4047         if (fp == NULL) return;
4048         fprintf(fp, "%s", sysconfdata);
4049         fclose(fp);
4050
4051         /* this handy API function does all the work for us */
4052         CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
4053         unlink(temp);
4054 }
4055
4056
4057 /*
4058  * Determine whether a given Internet address belongs to the current user
4059  */
4060 int CtdlIsMe(char *addr, int addr_buf_len)
4061 {
4062         struct recptypes *recp;
4063         int i;
4064
4065         recp = validate_recipients(addr);
4066         if (recp == NULL) return(0);
4067
4068         if (recp->num_local == 0) {
4069                 free(recp);
4070                 return(0);
4071         }
4072
4073         for (i=0; i<recp->num_local; ++i) {
4074                 extract_token(addr, recp->recp_local, i, '|', addr_buf_len);
4075                 if (!strcasecmp(addr, CC->user.fullname)) {
4076                         free(recp);
4077                         return(1);
4078                 }
4079         }
4080
4081         free(recp);
4082         return(0);
4083 }
4084
4085
4086 /*
4087  * Citadel protocol command to do the same
4088  */
4089 void cmd_isme(char *argbuf) {
4090         char addr[256];
4091
4092         if (CtdlAccessCheck(ac_logged_in)) return;
4093         extract_token(addr, argbuf, 0, '|', sizeof addr);
4094
4095         if (CtdlIsMe(addr, sizeof addr)) {
4096                 cprintf("%d %s\n", CIT_OK, addr);
4097         }
4098         else {
4099                 cprintf("%d Not you.\n", ERROR + ILLEGAL_VALUE);
4100         }
4101
4102 }