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