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