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