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