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