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