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