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