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