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