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