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