dca9cbb0cd10282829d7322112a218c7bb70641f
[citadel.git] / citadel / msgbase.c
1 /* $Id$ */
2 #include "sysdep.h"
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <stdio.h>
6 #include <fcntl.h>
7 #include <time.h>
8 #include <ctype.h>
9 #include <string.h>
10 #include <syslog.h>
11 #include <limits.h>
12 #include <errno.h>
13 #include <stdarg.h>
14 #include <sys/stat.h>
15 #include "citadel.h"
16 #include "server.h"
17 #include "database.h"
18 #include "msgbase.h"
19 #include "support.h"
20 #include "sysdep_decls.h"
21 #include "citserver.h"
22 #include "room_ops.h"
23 #include "user_ops.h"
24 #include "file_ops.h"
25 #include "control.h"
26 #include "dynloader.h"
27 #include "tools.h"
28 #include "mime_parser.h"
29 #include "html.h"
30
31 #define desired_section ((char *)CtdlGetUserData(SYM_DESIRED_SECTION))
32 #define ma ((struct ma_info *)CtdlGetUserData(SYM_MA_INFO))
33 #define msg_repl ((struct repl *)CtdlGetUserData(SYM_REPL))
34
35 extern struct config config;
36 long config_msgnum;
37
38 char *msgkeys[] = {
39         "", "", "", "", "", "", "", "", 
40         "", "", "", "", "", "", "", "", 
41         "", "", "", "", "", "", "", "", 
42         "", "", "", "", "", "", "", "", 
43         "", "", "", "", "", "", "", "", 
44         "", "", "", "", "", "", "", "", 
45         "", "", "", "", "", "", "", "", 
46         "", "", "", "", "", "", "", "", 
47         "", 
48         "from",
49         "", "", "",
50         "exti",
51         "", "", 
52         "hnod",
53         "msgn",
54         "", "", "",
55         "text",
56         "node",
57         "room",
58         "path",
59         "",
60         "rcpt",
61         "spec",
62         "time",
63         "subj",
64         "",
65         "",
66         "",
67         "",
68         ""
69 };
70
71 /*
72  * This function is self explanatory.
73  * (What can I say, I'm in a weird mood today...)
74  */
75 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
76 {
77         int i;
78
79         for (i = 0; i < strlen(name); ++i)
80                 if (name[i] == '@') {
81                         if (i > 0)
82                                 if (isspace(name[i - 1])) {
83                                         strcpy(&name[i - 1], &name[i]);
84                                         i = 0;
85                                 }
86                         while (isspace(name[i + 1])) {
87                                 strcpy(&name[i + 1], &name[i + 2]);
88                         }
89                 }
90 }
91
92
93 /*
94  * Aliasing for network mail.
95  * (Error messages have been commented out, because this is a server.)
96  */
97 int alias(char *name)
98 {                               /* process alias and routing info for mail */
99         FILE *fp;
100         int a, b;
101         char aaa[300], bbb[300];
102
103         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
104
105         fp = fopen("network/mail.aliases", "r");
106         if (fp == NULL)
107                 fp = fopen("/dev/null", "r");
108         if (fp == NULL)
109                 return (MES_ERROR);
110         strcpy(aaa, "");
111         strcpy(bbb, "");
112         while (fgets(aaa, sizeof aaa, fp) != NULL) {
113                 while (isspace(name[0]))
114                         strcpy(name, &name[1]);
115                 aaa[strlen(aaa) - 1] = 0;
116                 strcpy(bbb, "");
117                 for (a = 0; a < strlen(aaa); ++a) {
118                         if (aaa[a] == ',') {
119                                 strcpy(bbb, &aaa[a + 1]);
120                                 aaa[a] = 0;
121                         }
122                 }
123                 if (!strcasecmp(name, aaa))
124                         strcpy(name, bbb);
125         }
126         fclose(fp);
127         lprintf(7, "Mail is being forwarded to %s\n", name);
128
129         /* determine local or remote type, see citadel.h */
130         for (a = 0; a < strlen(name); ++a)
131                 if (name[a] == '!')
132                         return (MES_INTERNET);
133         for (a = 0; a < strlen(name); ++a)
134                 if (name[a] == '@')
135                         for (b = a; b < strlen(name); ++b)
136                                 if (name[b] == '.')
137                                         return (MES_INTERNET);
138         b = 0;
139         for (a = 0; a < strlen(name); ++a)
140                 if (name[a] == '@')
141                         ++b;
142         if (b > 1) {
143                 lprintf(7, "Too many @'s in address\n");
144                 return (MES_ERROR);
145         }
146         if (b == 1) {
147                 for (a = 0; a < strlen(name); ++a)
148                         if (name[a] == '@')
149                                 strcpy(bbb, &name[a + 1]);
150                 while (bbb[0] == 32)
151                         strcpy(bbb, &bbb[1]);
152                 fp = fopen("network/mail.sysinfo", "r");
153                 if (fp == NULL)
154                         return (MES_ERROR);
155               GETSN:do {
156                         a = getstring(fp, aaa);
157                 } while ((a >= 0) && (strcasecmp(aaa, bbb)));
158                 a = getstring(fp, aaa);
159                 if (!strncmp(aaa, "use ", 4)) {
160                         strcpy(bbb, &aaa[4]);
161                         fseek(fp, 0L, 0);
162                         goto GETSN;
163                 }
164                 fclose(fp);
165                 if (!strncmp(aaa, "uum", 3)) {
166                         strcpy(bbb, name);
167                         for (a = 0; a < strlen(bbb); ++a) {
168                                 if (bbb[a] == '@')
169                                         bbb[a] = 0;
170                                 if (bbb[a] == ' ')
171                                         bbb[a] = '_';
172                         }
173                         while (bbb[strlen(bbb) - 1] == '_')
174                                 bbb[strlen(bbb) - 1] = 0;
175                         sprintf(name, &aaa[4], bbb);
176                         return (MES_INTERNET);
177                 }
178                 if (!strncmp(aaa, "bin", 3)) {
179                         strcpy(aaa, name);
180                         strcpy(bbb, name);
181                         while (aaa[strlen(aaa) - 1] != '@')
182                                 aaa[strlen(aaa) - 1] = 0;
183                         aaa[strlen(aaa) - 1] = 0;
184                         while (aaa[strlen(aaa) - 1] == ' ')
185                                 aaa[strlen(aaa) - 1] = 0;
186                         while (bbb[0] != '@')
187                                 strcpy(bbb, &bbb[1]);
188                         strcpy(bbb, &bbb[1]);
189                         while (bbb[0] == ' ')
190                                 strcpy(bbb, &bbb[1]);
191                         sprintf(name, "%s @%s", aaa, bbb);
192                         return (MES_BINARY);
193                 }
194                 return (MES_ERROR);
195         }
196         return (MES_LOCAL);
197 }
198
199
200 void get_mm(void)
201 {
202         FILE *fp;
203
204         fp = fopen("citadel.control", "r");
205         fread((char *) &CitControl, sizeof(struct CitControl), 1, fp);
206         fclose(fp);
207 }
208
209
210
211 void simple_listing(long msgnum)
212 {
213         cprintf("%ld\n", msgnum);
214 }
215
216
217
218 /* Determine if a given message matches the fields in a message template.
219  * Return 0 for a successful match.
220  */
221 int CtdlMsgCmp(struct CtdlMessage *msg, struct CtdlMessage *template) {
222         int i;
223
224         /* If there aren't any fields in the template, all messages will
225          * match.
226          */
227         if (template == NULL) return(0);
228
229         /* Null messages are bogus. */
230         if (msg == NULL) return(1);
231
232         for (i='A'; i<='Z'; ++i) {
233                 if (template->cm_fields[i] != NULL) {
234                         if (msg->cm_fields[i] == NULL) {
235                                 return 1;
236                         }
237                         if (strcasecmp(msg->cm_fields[i],
238                                 template->cm_fields[i])) return 1;
239                 }
240         }
241
242         /* All compares succeeded: we have a match! */
243         return 0;
244 }
245
246
247
248
249 /*
250  * API function to perform an operation for each qualifying message in the
251  * current room.
252  */
253 void CtdlForEachMessage(int mode, long ref,
254                         char *content_type,
255                         struct CtdlMessage *compare,
256                         void (*CallBack) (long msgnum))
257 {
258
259         int a;
260         struct visit vbuf;
261         struct cdbdata *cdbfr;
262         long *msglist = NULL;
263         int num_msgs = 0;
264         long thismsg;
265         struct SuppMsgInfo smi;
266         struct CtdlMessage *msg;
267
268         /* Learn about the user and room in question */
269         get_mm();
270         getuser(&CC->usersupp, CC->curr_user);
271         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
272
273         /* Load the message list */
274         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long));
275         if (cdbfr != NULL) {
276                 msglist = mallok(cdbfr->len);
277                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
278                 num_msgs = cdbfr->len / sizeof(long);
279                 cdb_free(cdbfr);
280         } else {
281                 return;         /* No messages at all?  No further action. */
282         }
283
284
285         /* If the caller is looking for a specific MIME type, then filter
286          * out all messages which are not of the type requested.
287          */
288         if (num_msgs > 0)
289                 if (content_type != NULL)
290                         if (strlen(content_type) > 0)
291                                 for (a = 0; a < num_msgs; ++a) {
292                                         lprintf(9, "Trying %ld\n", msglist[a]);
293                                         GetSuppMsgInfo(&smi, msglist[a]);
294                                         lprintf(9, "ct is %s\n", smi.smi_content_type);
295                                         if (strcasecmp(smi.smi_content_type, content_type)) {
296                                                 msglist[a] = 0L;
297                                         }
298                                 }
299
300         num_msgs = sort_msglist(msglist, num_msgs);
301
302         /* If a template was supplied, filter out the messages which
303          * don't match.  (This could induce some delays!)
304          */
305         if (num_msgs > 0) {
306                 if (compare != NULL) {
307                         for (a = 0; a < num_msgs; ++a) {
308                                 msg = CtdlFetchMessage(msglist[a]);
309                                 if (msg != NULL) {
310                                         if (CtdlMsgCmp(msg, compare)) {
311                                                 msglist[a] = 0L;
312                                         }
313                                         CtdlFreeMessage(msg);
314                                 }
315                         }
316                 }
317         }
318
319         
320         /*
321          * Now iterate through the message list, according to the
322          * criteria supplied by the caller.
323          */
324         if (num_msgs > 0)
325                 for (a = 0; a < num_msgs; ++a) {
326                         thismsg = msglist[a];
327                         if ((thismsg > 0)
328                             && (
329
330                                        (mode == MSGS_ALL)
331                                        || ((mode == MSGS_OLD) && (thismsg <= vbuf.v_lastseen))
332                                        || ((mode == MSGS_NEW) && (thismsg > vbuf.v_lastseen))
333                                        || ((mode == MSGS_NEW) && (thismsg >= vbuf.v_lastseen)
334                                     && (CC->usersupp.flags & US_LASTOLD))
335                                        || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
336                                    || ((mode == MSGS_FIRST) && (a < ref))
337                                 || ((mode == MSGS_GT) && (thismsg > ref))
338                             )
339                             ) {
340                                 CallBack(thismsg);
341                         }
342                 }
343         phree(msglist);         /* Clean up */
344 }
345
346
347
348 /*
349  * cmd_msgs()  -  get list of message #'s in this room
350  *                implements the MSGS server command using CtdlForEachMessage()
351  */
352 void cmd_msgs(char *cmdbuf)
353 {
354         int mode = 0;
355         char which[256];
356         char buf[256];
357         char tfield[256];
358         char tvalue[256];
359         int cm_ref = 0;
360         int i;
361         int with_template = 0;
362         struct CtdlMessage *template = NULL;
363
364         extract(which, cmdbuf, 0);
365         cm_ref = extract_int(cmdbuf, 1);
366         with_template = extract_int(cmdbuf, 2);
367
368         mode = MSGS_ALL;
369         strcat(which, "   ");
370         if (!strncasecmp(which, "OLD", 3))
371                 mode = MSGS_OLD;
372         else if (!strncasecmp(which, "NEW", 3))
373                 mode = MSGS_NEW;
374         else if (!strncasecmp(which, "FIRST", 5))
375                 mode = MSGS_FIRST;
376         else if (!strncasecmp(which, "LAST", 4))
377                 mode = MSGS_LAST;
378         else if (!strncasecmp(which, "GT", 2))
379                 mode = MSGS_GT;
380
381         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
382                 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
383                 return;
384         }
385
386         if (with_template) {
387                 cprintf("%d Send template then receive message list\n",
388                         START_CHAT_MODE);
389                 template = (struct CtdlMessage *)
390                         mallok(sizeof(struct CtdlMessage));
391                 memset(template, 0, sizeof(struct CtdlMessage));
392                 while(client_gets(buf), strcmp(buf,"000")) {
393                         extract(tfield, buf, 0);
394                         extract(tvalue, buf, 1);
395                         for (i='A'; i<='Z'; ++i) if (msgkeys[i]!=NULL) {
396                                 if (!strcasecmp(tfield, msgkeys[i])) {
397                                         template->cm_fields[i] =
398                                                 strdoop(tvalue);
399                                 }
400                         }
401                 }
402         }
403         else {
404                 cprintf("%d Message list...\n", LISTING_FOLLOWS);
405         }
406
407         CtdlForEachMessage(mode, cm_ref, NULL, template, simple_listing);
408         if (template != NULL) CtdlFreeMessage(template);
409         cprintf("000\n");
410 }
411
412
413
414
415 /* 
416  * help_subst()  -  support routine for help file viewer
417  */
418 void help_subst(char *strbuf, char *source, char *dest)
419 {
420         char workbuf[256];
421         int p;
422
423         while (p = pattern2(strbuf, source), (p >= 0)) {
424                 strcpy(workbuf, &strbuf[p + strlen(source)]);
425                 strcpy(&strbuf[p], dest);
426                 strcat(strbuf, workbuf);
427         }
428 }
429
430
431 void do_help_subst(char *buffer)
432 {
433         char buf2[16];
434
435         help_subst(buffer, "^nodename", config.c_nodename);
436         help_subst(buffer, "^humannode", config.c_humannode);
437         help_subst(buffer, "^fqdn", config.c_fqdn);
438         help_subst(buffer, "^username", CC->usersupp.fullname);
439         sprintf(buf2, "%ld", CC->usersupp.usernum);
440         help_subst(buffer, "^usernum", buf2);
441         help_subst(buffer, "^sysadm", config.c_sysadm);
442         help_subst(buffer, "^variantname", CITADEL);
443         sprintf(buf2, "%d", config.c_maxsessions);
444         help_subst(buffer, "^maxsessions", buf2);
445 }
446
447
448
449 /*
450  * memfmout()  -  Citadel text formatter and paginator.
451  *             Although the original purpose of this routine was to format
452  *             text to the reader's screen width, all we're really using it
453  *             for here is to format text out to 80 columns before sending it
454  *             to the client.  The client software may reformat it again.
455  */
456 void memfmout(
457         int width,              /* screen width to use */
458         char *mptr,             /* where are we going to get our text from? */
459         char subst)             /* nonzero if we should do substitutions */
460 {
461         int a, b, c;
462         int real = 0;
463         int old = 0;
464         CIT_UBYTE ch;
465         char aaa[140];
466         char buffer[256];
467
468         strcpy(aaa, "");
469         old = 255;
470         strcpy(buffer, "");
471         c = 1;                  /* c is the current pos */
472
473 FMTA:   if (subst) {
474                 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
475                         ch = *mptr++;
476                         buffer[strlen(buffer) + 1] = 0;
477                         buffer[strlen(buffer)] = ch;
478                 }
479
480                 if (buffer[0] == '^')
481                         do_help_subst(buffer);
482
483                 buffer[strlen(buffer) + 1] = 0;
484                 a = buffer[0];
485                 strcpy(buffer, &buffer[1]);
486         } else {
487                 ch = *mptr++;
488         }
489
490         old = real;
491         real = ch;
492         if (ch <= 0)
493                 goto FMTEND;
494
495         if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10))
496                 ch = 32;
497         if (((old == 13) || (old == 10)) && (isspace(real))) {
498                 cprintf("\n");
499                 c = 1;
500         }
501         if (ch > 126)
502                 goto FMTA;
503
504         if (ch > 32) {
505                 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
506                         cprintf("\n%s", aaa);
507                         c = strlen(aaa);
508                         aaa[0] = 0;
509                 }
510                 b = strlen(aaa);
511                 aaa[b] = ch;
512                 aaa[b + 1] = 0;
513         }
514         if (ch == 32) {
515                 if ((strlen(aaa) + c) > (width - 5)) {
516                         cprintf("\n");
517                         c = 1;
518                 }
519                 cprintf("%s ", aaa);
520                 ++c;
521                 c = c + strlen(aaa);
522                 strcpy(aaa, "");
523                 goto FMTA;
524         }
525         if ((ch == 13) || (ch == 10)) {
526                 cprintf("%s\n", aaa);
527                 c = 1;
528                 strcpy(aaa, "");
529                 goto FMTA;
530         }
531         goto FMTA;
532
533 FMTEND: cprintf("%s\n", aaa);
534 }
535
536
537
538 /*
539  * Callback function for mime parser that simply lists the part
540  */
541 void list_this_part(char *name, char *filename, char *partnum, char *disp,
542                     void *content, char *cbtype, size_t length)
543 {
544
545         cprintf("part=%s|%s|%s|%s|%s|%d\n",
546                 name, filename, partnum, disp, cbtype, length);
547 }
548
549
550 /*
551  * Callback function for mime parser that opens a section for downloading
552  */
553 void mime_download(char *name, char *filename, char *partnum, char *disp,
554                    void *content, char *cbtype, size_t length)
555 {
556
557         /* Silently go away if there's already a download open... */
558         if (CC->download_fp != NULL)
559                 return;
560
561         /* ...or if this is not the desired section */
562         if (strcasecmp(desired_section, partnum))
563                 return;
564
565         CC->download_fp = tmpfile();
566         if (CC->download_fp == NULL)
567                 return;
568
569         fwrite(content, length, 1, CC->download_fp);
570         fflush(CC->download_fp);
571         rewind(CC->download_fp);
572
573         OpenCmdResult(filename, cbtype);
574 }
575
576
577
578 /*
579  * Load a message from disk into memory.
580  * This is used by CtdlOutputMsg() and other fetch functions.
581  *
582  * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
583  *       using the CtdlMessageFree() function.
584  */
585 struct CtdlMessage *CtdlFetchMessage(long msgnum)
586 {
587         struct cdbdata *dmsgtext;
588         struct CtdlMessage *ret = NULL;
589         char *mptr;
590         CIT_UBYTE ch;
591         CIT_UBYTE field_header;
592         size_t field_length;
593
594         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
595         if (dmsgtext == NULL) {
596                 return NULL;
597         }
598         mptr = dmsgtext->ptr;
599
600         /* Parse the three bytes that begin EVERY message on disk.
601          * The first is always 0xFF, the on-disk magic number.
602          * The second is the anonymous/public type byte.
603          * The third is the format type byte (vari, fixed, or MIME).
604          */
605         ch = *mptr++;
606         if (ch != 255) {
607                 lprintf(5, "Message %ld appears to be corrupted.\n", msgnum);
608                 cdb_free(dmsgtext);
609                 return NULL;
610         }
611         ret = (struct CtdlMessage *) mallok(sizeof(struct CtdlMessage));
612         memset(ret, 0, sizeof(struct CtdlMessage));
613
614         ret->cm_magic = CTDLMESSAGE_MAGIC;
615         ret->cm_anon_type = *mptr++;    /* Anon type byte */
616         ret->cm_format_type = *mptr++;  /* Format type byte */
617
618         /*
619          * The rest is zero or more arbitrary fields.  Load them in.
620          * We're done when we encounter either a zero-length field or
621          * have just processed the 'M' (message text) field.
622          */
623         do {
624                 field_length = strlen(mptr);
625                 if (field_length == 0)
626                         break;
627                 field_header = *mptr++;
628                 ret->cm_fields[field_header] = mallok(field_length);
629                 strcpy(ret->cm_fields[field_header], mptr);
630
631                 while (*mptr++ != 0);   /* advance to next field */
632
633         } while ((field_length > 0) && (field_header != 'M'));
634
635         cdb_free(dmsgtext);
636
637         /* Always make sure there's something in the msg text field */
638         if (ret->cm_fields['M'] == NULL)
639                 ret->cm_fields['M'] = strdoop("<no text>\n");
640
641         /* Perform "before read" hooks (aborting if any return nonzero) */
642         if (PerformMessageHooks(ret, EVT_BEFOREREAD) > 0) {
643                 CtdlFreeMessage(ret);
644                 return NULL;
645         }
646
647         return (ret);
648 }
649
650
651 /*
652  * Returns 1 if the supplied pointer points to a valid Citadel message.
653  * If the pointer is NULL or the magic number check fails, returns 0.
654  */
655 int is_valid_message(struct CtdlMessage *msg) {
656         if (msg == NULL)
657                 return 0;
658         if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
659                 lprintf(3, "is_valid_message() -- self-check failed\n");
660                 return 0;
661         }
662         return 1;
663 }
664
665
666 /*
667  * 'Destructor' for struct CtdlMessage
668  */
669 void CtdlFreeMessage(struct CtdlMessage *msg)
670 {
671         int i;
672
673         if (is_valid_message(msg) == 0) return;
674
675         for (i = 0; i < 256; ++i)
676                 if (msg->cm_fields[i] != NULL)
677                         phree(msg->cm_fields[i]);
678
679         msg->cm_magic = 0;      /* just in case */
680         phree(msg);
681 }
682
683
684 /*
685  * Get a message off disk.  (return value is the message's timestamp)
686  * 
687  */
688 int CtdlOutputMsg(long msg_num,         /* message number (local) to fetch */
689                 int mode,               /* how would you like that message? */
690                 int headers_only,       /* eschew the message body? */
691                 int do_proto,           /* do Citadel protocol responses? */
692                 FILE *outfp,
693                 int outsock,
694                 int crlf                /* Use CRLF newlines instead of LF? */
695 ) {
696         int a, i, k;
697         char buf[1024];
698         time_t xtime;
699         CIT_UBYTE ch;
700         char allkeys[256];
701         char display_name[256];
702         struct CtdlMessage *TheMessage;
703         char *mptr;
704         char *nl;       /* newline string */
705
706         /* buffers needed for RFC822 translation */
707         char suser[256];
708         char luser[256];
709         char snode[256];
710         char lnode[256];
711         char mid[256];
712         /*                                       */
713
714
715         /* BEGIN NESTED FUNCTION omprintf() */
716         void omprintf(const char *format, ...) {   
717                 va_list arg_ptr;   
718                 char buf[256];   
719          
720                 va_start(arg_ptr, format);   
721                 if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
722                         buf[sizeof buf - 2] = '\n';
723                 if (outfp != NULL) {
724                         fwrite(buf, strlen(buf), 1, outfp);
725                 }
726                 else if (outsock >= 0) {
727                         write(outsock, buf, strlen(buf));
728                 }
729                 else {
730                         client_write(buf, strlen(buf)); 
731                 }
732                 va_end(arg_ptr);
733         }   
734         /* END NESTED FUNCTION omprintf() */
735
736         /* BEGIN NESTED FUNCTION omfmout() */
737         void omfmout(char *mptr) {
738                 int b, c;
739                 int real = 0;
740                 int old = 0;
741                 CIT_UBYTE ch;
742                 char aaa[140];
743                 char buffer[256];
744
745                 strcpy(aaa, "");
746                 old = 255;
747                 strcpy(buffer, "");
748                 c = 1;                  /* c is the current pos */
749
750 FMTA:           ch = *mptr++;
751                 old = real;
752                 real = ch;
753                 if (ch <= 0)
754                         goto FMTEND;
755         
756                 if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10))
757                         ch = 32;
758                 if (((old == 13) || (old == 10)) && (isspace(real))) {
759                         omprintf("%s", nl);
760                         c = 1;
761                 }
762                 if (ch > 126)
763                         goto FMTA;
764         
765                 if (ch > 32) {
766                         if (((strlen(aaa) + c) > (75)) && (strlen(aaa) > (75))) {
767                                 omprintf("%s%s", nl, aaa);
768                                 c = strlen(aaa);
769                                 aaa[0] = 0;
770                         }
771                         b = strlen(aaa);
772                         aaa[b] = ch;
773                         aaa[b + 1] = 0;
774                 }
775                 if (ch == 32) {
776                         if ((strlen(aaa) + c) > (75)) {
777                                 omprintf("%s", nl);
778                                 c = 1;
779                         }
780                         omprintf("%s ", aaa);
781                         ++c;
782                         c = c + strlen(aaa);
783                         strcpy(aaa, "");
784                         goto FMTA;
785                 }
786                 if ((ch == 13) || (ch == 10)) {
787                         omprintf("%s%s", aaa, nl);
788                         c = 1;
789                         strcpy(aaa, "");
790                         goto FMTA;
791                 }
792                 goto FMTA;
793
794 FMTEND:         omprintf("%s%s", aaa, nl);
795         }
796         /* END NESTED FUNCTION omfmout() */
797
798         /* BEGIN NESTED FUNCTION fixed_output() */
799         /*
800         * Callback function for mime parser that wants to display text
801         */
802         void fixed_output(char *name, char *filename, char *partnum, char *disp,
803                         void *content, char *cbtype, size_t length)
804         {
805                 char *ptr;
806                 char *wptr;
807                 size_t wlen;
808         
809                 if (!strcasecmp(cbtype, "multipart/alternative")) {
810                         strcpy(ma->prefix, partnum);
811                         strcat(ma->prefix, ".");
812                         ma->is_ma = 1;
813                         ma->did_print = 0;
814                         return;
815                 }
816         
817                 if ( (!strncasecmp(partnum, ma->prefix, strlen(ma->prefix)))
818                 && (ma->is_ma == 1) 
819                 && (ma->did_print == 1) ) {
820                         lprintf(9, "Skipping part %s (%s)\n", partnum, cbtype);
821                         return;
822                 }
823         
824                 ma->did_print = 1;
825         
826                 if (!strcasecmp(cbtype, "text/plain")) {
827                         wlen = length;
828                         wptr = content;
829                         while (wlen--) {
830                                 ch = *wptr++;
831                                 if (ch==10) omprintf("%s", nl);
832                                 else omprintf("%c", ch);
833                         }
834                 }
835                 else if (!strcasecmp(cbtype, "text/html")) {
836                         ptr = html_to_ascii(content, 80, 0);
837                         wlen = strlen(ptr);
838                         wptr = ptr;
839                         while (wlen--) {
840                                 ch = *wptr++;
841                                 if (ch==10) omprintf("%s", nl);
842                                 else omprintf("%c", ch);
843                         }
844                         phree(ptr);
845                 }
846                 else if (strncasecmp(cbtype, "multipart/", 10)) {
847                         omprintf("Part %s: %s (%s) (%d bytes)%s",
848                                 partnum, filename, cbtype, length, nl);
849                 }
850         }
851
852         /* END NESTED FUNCTION fixed_output() */
853
854
855         TheMessage = NULL;
856         sprintf(mid, "%ld", msg_num);
857         nl = (crlf ? "\r\n" : "\n");
858
859         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
860                 if (do_proto) cprintf("%d Not logged in.\n",
861                         ERROR + NOT_LOGGED_IN);
862                 return(om_not_logged_in);
863         }
864
865         /* FIX ... small security issue
866          * We need to check to make sure the requested message is actually
867          * in the current room, and set msg_ok to 1 only if it is.  This
868          * functionality is currently missing because I'm in a hurry to replace
869          * broken production code with nonbroken pre-beta code.  :(   -- ajc
870          *
871          if (!msg_ok) {
872          if (do_proto) cprintf("%d Message %ld is not in this room.\n",
873          ERROR, msg_num);
874          return(om_no_such_msg);
875          }
876          */
877
878         /*
879          * Fetch the message from disk
880          */
881         TheMessage = CtdlFetchMessage(msg_num);
882         if (TheMessage == NULL) {
883                 if (do_proto) cprintf("%d Can't locate msg %ld on disk\n",
884                         ERROR, msg_num);
885                 return(om_no_such_msg);
886         }
887
888         /* Are we downloading a MIME component? */
889         if (mode == MT_DOWNLOAD) {
890                 if (TheMessage->cm_format_type != FMT_RFC822) {
891                         if (do_proto)
892                                 cprintf("%d This is not a MIME message.\n",
893                                 ERROR);
894                 } else if (CC->download_fp != NULL) {
895                         if (do_proto) cprintf(
896                                 "%d You already have a download open.\n",
897                                 ERROR);
898                 } else {
899                         /* Parse the message text component */
900                         mptr = TheMessage->cm_fields['M'];
901                         mime_parser(mptr, NULL, *mime_download);
902                         /* If there's no file open by this time, the requested
903                          * section wasn't found, so print an error
904                          */
905                         if (CC->download_fp == NULL) {
906                                 if (do_proto) cprintf(
907                                         "%d Section %s not found.\n",
908                                         ERROR + FILE_NOT_FOUND,
909                                         desired_section);
910                         }
911                 }
912                 CtdlFreeMessage(TheMessage);
913                 return((CC->download_fp != NULL) ? om_ok : om_mime_error);
914         }
915
916         /* now for the user-mode message reading loops */
917         if (do_proto) cprintf("%d Message %ld:\n", LISTING_FOLLOWS, msg_num);
918
919         /* Tell the client which format type we're using.  If this is a
920          * MIME message, *lie* about it and tell the user it's fixed-format.
921          */
922         if (mode == MT_CITADEL) {
923                 if (TheMessage->cm_format_type == FMT_RFC822) {
924                         if (do_proto) cprintf("type=1\n");
925                 }
926                 else {
927                         if (do_proto) cprintf("type=%d\n",
928                                 TheMessage->cm_format_type);
929                 }
930         }
931
932         /* nhdr=yes means that we're only displaying headers, no body */
933         if ((TheMessage->cm_anon_type == MES_ANON) && (mode == MT_CITADEL)) {
934                 if (do_proto) cprintf("nhdr=yes\n");
935         }
936
937         /* begin header processing loop for Citadel message format */
938
939         if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
940
941                 strcpy(display_name, "<unknown>");
942                 if (TheMessage->cm_fields['A']) {
943                         strcpy(buf, TheMessage->cm_fields['A']);
944                         PerformUserHooks(buf, (-1L), EVT_OUTPUTMSG);
945                         if (TheMessage->cm_anon_type == MES_ANON)
946                                 strcpy(display_name, "****");
947                         else if (TheMessage->cm_anon_type == MES_AN2)
948                                 strcpy(display_name, "anonymous");
949                         else
950                                 strcpy(display_name, buf);
951                         if ((is_room_aide())
952                             && ((TheMessage->cm_anon_type == MES_ANON)
953                              || (TheMessage->cm_anon_type == MES_AN2))) {
954                                 sprintf(&display_name[strlen(display_name)],
955                                         " [%s]", buf);
956                         }
957                 }
958
959                 strcpy(allkeys, FORDER);
960                 for (i=0; i<strlen(allkeys); ++i) {
961                         k = (int) allkeys[i];
962                         if (k != 'M') {
963                                 if (TheMessage->cm_fields[k] != NULL) {
964                                         if (k == 'A') {
965                                                 if (do_proto) cprintf("%s=%s\n",
966                                                         msgkeys[k],
967                                                         display_name);
968                                         }
969                                         else {
970                                                 if (do_proto) cprintf("%s=%s\n",
971                                                         msgkeys[k],
972                                                         TheMessage->cm_fields[k]
973                                         );
974                                         }
975                                 }
976                         }
977                 }
978
979         }
980
981         /* begin header processing loop for RFC822 transfer format */
982
983         strcpy(suser, "");
984         strcpy(luser, "");
985         strcpy(snode, NODENAME);
986         strcpy(lnode, HUMANNODE);
987         if (mode == MT_RFC822) {
988                 for (i = 0; i < 256; ++i) {
989                         if (TheMessage->cm_fields[i]) {
990                                 mptr = TheMessage->cm_fields[i];
991
992                                 if (i == 'A') {
993                                         strcpy(luser, mptr);
994                                 } else if (i == 'P') {
995                                         omprintf("Path: %s%s", mptr, nl);
996                                         for (a = 0; a < strlen(mptr); ++a) {
997                                                 if (mptr[a] == '!') {
998                                                         strcpy(mptr, &mptr[a + 1]);
999                                                         a = 0;
1000                                                 }
1001                                         }
1002                                         strcpy(suser, mptr);
1003                                 } else if (i == 'U')
1004                                         omprintf("Subject: %s%s", mptr, nl);
1005                                 else if (i == 'I')
1006                                         strcpy(mid, mptr);
1007                                 else if (i == 'H')
1008                                         strcpy(lnode, mptr);
1009                                 else if (i == 'O')
1010                                         omprintf("X-Citadel-Room: %s%s",
1011                                                 mptr, nl);
1012                                 else if (i == 'N')
1013                                         strcpy(snode, mptr);
1014                                 else if (i == 'R')
1015                                         omprintf("To: %s%s", mptr, nl);
1016                                 else if (i == 'T') {
1017                                         xtime = atol(mptr);
1018                                         omprintf("Date: %s", asctime(localtime(&xtime)));
1019                                 }
1020                         }
1021                 }
1022         }
1023
1024         if (mode == MT_RFC822) {
1025                 if (!strcasecmp(snode, NODENAME)) {
1026                         strcpy(snode, FQDN);
1027                 }
1028                 omprintf("Message-ID: <%s@%s>%s", mid, snode, nl);
1029                 PerformUserHooks(luser, (-1L), EVT_OUTPUTMSG);
1030                 omprintf("From: %s@%s (%s)%s", suser, snode, luser, nl);
1031                 omprintf("Organization: %s%s", lnode, nl);
1032         }
1033
1034         /* end header processing loop ... at this point, we're in the text */
1035
1036         mptr = TheMessage->cm_fields['M'];
1037
1038         /* Tell the client about the MIME parts in this message */
1039         if (TheMessage->cm_format_type == FMT_RFC822) { /* legacy text dump */
1040                 if (mode == MT_CITADEL) {
1041                         mime_parser(mptr, NULL, *list_this_part);
1042                 }
1043                 else if (mode == MT_MIME) {     /* list parts only */
1044                         mime_parser(mptr, NULL, *list_this_part);
1045                         if (do_proto) cprintf("000\n");
1046                         CtdlFreeMessage(TheMessage);
1047                         return(om_ok);
1048                 }
1049         }
1050
1051         if (headers_only) {
1052                 if (do_proto) cprintf("000\n");
1053                 CtdlFreeMessage(TheMessage);
1054                 return(om_ok);
1055         }
1056
1057         /* signify start of msg text */
1058         if (mode == MT_CITADEL)
1059                 if (do_proto) cprintf("text\n");
1060         /* if ((mode == MT_RFC822) && (TheMessage->cm_format_type != FMT_RFC822)) { */
1061         if (mode == MT_RFC822) {
1062                 omprintf("%s", nl);
1063         }
1064
1065         /* If the format type on disk is 1 (fixed-format), then we want
1066          * everything to be output completely literally ... regardless of
1067          * what message transfer format is in use.
1068          */
1069         if (TheMessage->cm_format_type == FMT_FIXED) {
1070                 strcpy(buf, "");
1071                 while (ch = *mptr++, ch > 0) {
1072                         if (ch == 13)
1073                                 ch = 10;
1074                         if ((ch == 10) || (strlen(buf) > 250)) {
1075                                 omprintf("%s%s", buf, nl);
1076                                 strcpy(buf, "");
1077                         } else {
1078                                 buf[strlen(buf) + 1] = 0;
1079                                 buf[strlen(buf)] = ch;
1080                         }
1081                 }
1082                 if (strlen(buf) > 0)
1083                         omprintf("%s%s", buf, nl);
1084         }
1085
1086         /* If the message on disk is format 0 (Citadel vari-format), we
1087          * output using the formatter at 80 columns.  This is the final output
1088          * form if the transfer format is RFC822, but if the transfer format
1089          * is Citadel proprietary, it'll still work, because the indentation
1090          * for new paragraphs is correct and the client will reformat the
1091          * message to the reader's screen width.
1092          */
1093         if (TheMessage->cm_format_type == FMT_CITADEL) {
1094                 omfmout(mptr);
1095         }
1096
1097         /* If the message on disk is format 4 (MIME), we've gotta hand it
1098          * off to the MIME parser.  The client has already been told that
1099          * this message is format 1 (fixed format), so the callback function
1100          * we use will display those parts as-is.
1101          */
1102         if (TheMessage->cm_format_type == FMT_RFC822) {
1103                 CtdlAllocUserData(SYM_MA_INFO, sizeof(struct ma_info));
1104                 memset(ma, 0, sizeof(struct ma_info));
1105                 mime_parser(mptr, NULL, *fixed_output);
1106         }
1107
1108         /* now we're done */
1109         if (do_proto) cprintf("000\n");
1110         CtdlFreeMessage(TheMessage);
1111         return(om_ok);
1112 }
1113
1114
1115
1116 /*
1117  * display a message (mode 0 - Citadel proprietary)
1118  */
1119 void cmd_msg0(char *cmdbuf)
1120 {
1121         long msgid;
1122         int headers_only = 0;
1123
1124         msgid = extract_long(cmdbuf, 0);
1125         headers_only = extract_int(cmdbuf, 1);
1126
1127         CtdlOutputMsg(msgid, MT_CITADEL, headers_only, 1, NULL, -1, 0);
1128         return;
1129 }
1130
1131
1132 /*
1133  * display a message (mode 2 - RFC822)
1134  */
1135 void cmd_msg2(char *cmdbuf)
1136 {
1137         long msgid;
1138         int headers_only = 0;
1139
1140         msgid = extract_long(cmdbuf, 0);
1141         headers_only = extract_int(cmdbuf, 1);
1142
1143         CtdlOutputMsg(msgid, MT_RFC822, headers_only, 1, NULL, -1, 1);
1144 }
1145
1146
1147
1148 /* 
1149  * display a message (mode 3 - IGnet raw format - internal programs only)
1150  */
1151 void cmd_msg3(char *cmdbuf)
1152 {
1153         long msgnum;
1154         struct CtdlMessage *msg;
1155         struct ser_ret smr;
1156
1157         if (CC->internal_pgm == 0) {
1158                 cprintf("%d This command is for internal programs only.\n",
1159                         ERROR);
1160                 return;
1161         }
1162
1163         msgnum = extract_long(cmdbuf, 0);
1164         msg = CtdlFetchMessage(msgnum);
1165         if (msg == NULL) {
1166                 cprintf("%d Message %ld not found.\n", 
1167                         ERROR, msgnum);
1168                 return;
1169         }
1170
1171         serialize_message(&smr, msg);
1172         CtdlFreeMessage(msg);
1173
1174         if (smr.len == 0) {
1175                 cprintf("%d Unable to serialize message\n",
1176                         ERROR+INTERNAL_ERROR);
1177                 return;
1178         }
1179
1180         cprintf("%d %ld\n", BINARY_FOLLOWS, smr.len);
1181         client_write(smr.ser, smr.len);
1182         phree(smr.ser);
1183 }
1184
1185
1186
1187 /* 
1188  * display a message (mode 4 - MIME) (FIX ... still evolving, not complete)
1189  */
1190 void cmd_msg4(char *cmdbuf)
1191 {
1192         long msgid;
1193
1194         msgid = extract_long(cmdbuf, 0);
1195         CtdlOutputMsg(msgid, MT_MIME, 0, 1, NULL, -1, 0);
1196 }
1197
1198 /*
1199  * Open a component of a MIME message as a download file 
1200  */
1201 void cmd_opna(char *cmdbuf)
1202 {
1203         long msgid;
1204
1205         CtdlAllocUserData(SYM_DESIRED_SECTION, 64);
1206
1207         msgid = extract_long(cmdbuf, 0);
1208         extract(desired_section, cmdbuf, 1);
1209
1210         CtdlOutputMsg(msgid, MT_DOWNLOAD, 0, 1, NULL, -1, 1);
1211 }                       
1212
1213
1214 /*
1215  * Save a message pointer into a specified room
1216  * (Returns 0 for success, nonzero for failure)
1217  * roomname may be NULL to use the current room
1218  */
1219 int CtdlSaveMsgPointerInRoom(char *roomname, long msgid, int flags) {
1220         int i;
1221         char hold_rm[ROOMNAMELEN];
1222         struct cdbdata *cdbfr;
1223         int num_msgs;
1224         long *msglist;
1225         long highest_msg = 0L;
1226         struct CtdlMessage *msg = NULL;
1227
1228         lprintf(9, "CtdlSaveMsgPointerInRoom(%s, %ld, %d)\n",
1229                 roomname, msgid, flags);
1230
1231         strcpy(hold_rm, CC->quickroom.QRname);
1232
1233         /* We may need to check to see if this message is real */
1234         if (  (flags & SM_VERIFY_GOODNESS)
1235            || (flags & SM_DO_REPL_CHECK)
1236            ) {
1237                 msg = CtdlFetchMessage(msgid);
1238                 if (msg == NULL) return(ERROR + ILLEGAL_VALUE);
1239         }
1240
1241         /* Perform replication checks if necessary */
1242         if ( (flags & SM_DO_REPL_CHECK) && (msg != NULL) ) {
1243
1244                 if (getroom(&CC->quickroom,
1245                    ((roomname != NULL) ? roomname : CC->quickroom.QRname) )
1246                    != 0) {
1247                         lprintf(9, "No such room <%s>\n", roomname);
1248                         if (msg != NULL) CtdlFreeMessage(msg);
1249                         return(ERROR + ROOM_NOT_FOUND);
1250                 }
1251
1252                 if (ReplicationChecks(msg) != 0) {
1253                         getroom(&CC->quickroom, hold_rm);
1254                         if (msg != NULL) CtdlFreeMessage(msg);
1255                         lprintf(9, "Did replication, and newer exists\n");
1256                         return(0);
1257                 }
1258         }
1259
1260         /* Now the regular stuff */
1261         if (lgetroom(&CC->quickroom,
1262            ((roomname != NULL) ? roomname : CC->quickroom.QRname) )
1263            != 0) {
1264                 lprintf(9, "No such room <%s>\n", roomname);
1265                 if (msg != NULL) CtdlFreeMessage(msg);
1266                 return(ERROR + ROOM_NOT_FOUND);
1267         }
1268
1269         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long));
1270         if (cdbfr == NULL) {
1271                 msglist = NULL;
1272                 num_msgs = 0;
1273         } else {
1274                 msglist = mallok(cdbfr->len);
1275                 if (msglist == NULL)
1276                         lprintf(3, "ERROR malloc msglist!\n");
1277                 num_msgs = cdbfr->len / sizeof(long);
1278                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1279                 cdb_free(cdbfr);
1280         }
1281
1282
1283         /* Make sure the message doesn't already exist in this room.  It
1284          * is absolutely taboo to have more than one reference to the same
1285          * message in a room.
1286          */
1287         if (num_msgs > 0) for (i=0; i<num_msgs; ++i) {
1288                 if (msglist[i] == msgid) {
1289                         lputroom(&CC->quickroom);       /* unlock the room */
1290                         getroom(&CC->quickroom, hold_rm);
1291                         if (msg != NULL) CtdlFreeMessage(msg);
1292                         return(ERROR + ALREADY_EXISTS);
1293                 }
1294         }
1295
1296         /* Now add the new message */
1297         ++num_msgs;
1298         msglist = reallok(msglist,
1299                           (num_msgs * sizeof(long)));
1300
1301         if (msglist == NULL) {
1302                 lprintf(3, "ERROR: can't realloc message list!\n");
1303         }
1304         msglist[num_msgs - 1] = msgid;
1305
1306         /* Sort the message list, so all the msgid's are in order */
1307         num_msgs = sort_msglist(msglist, num_msgs);
1308
1309         /* Determine the highest message number */
1310         highest_msg = msglist[num_msgs - 1];
1311
1312         /* Write it back to disk. */
1313         cdb_store(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long),
1314                   msglist, num_msgs * sizeof(long));
1315
1316         /* Free up the memory we used. */
1317         phree(msglist);
1318
1319         /* Update the highest-message pointer and unlock the room. */
1320         CC->quickroom.QRhighest = highest_msg;
1321         lputroom(&CC->quickroom);
1322         getroom(&CC->quickroom, hold_rm);
1323
1324         /* Bump the reference count for this message. */
1325         if ((flags & SM_DONT_BUMP_REF)==0) {
1326                 AdjRefCount(msgid, +1);
1327         }
1328
1329         /* Return success. */
1330         if (msg != NULL) CtdlFreeMessage(msg);
1331         return (0);
1332 }
1333
1334
1335
1336 /*
1337  * Message base operation to send a message to the master file
1338  * (returns new message number)
1339  *
1340  * This is the back end for CtdlSaveMsg() and should not be directly
1341  * called by server-side modules.
1342  *
1343  */
1344 long send_message(struct CtdlMessage *msg,      /* pointer to buffer */
1345                 int generate_id,                /* generate 'I' field? */
1346                 FILE *save_a_copy)              /* save a copy to disk? */
1347 {
1348         long newmsgid;
1349         long retval;
1350         char msgidbuf[32];
1351         struct ser_ret smr;
1352
1353         /* Get a new message number */
1354         newmsgid = get_new_message_number();
1355         sprintf(msgidbuf, "%ld", newmsgid);
1356
1357         if (generate_id) {
1358                 msg->cm_fields['I'] = strdoop(msgidbuf);
1359         }
1360         
1361         serialize_message(&smr, msg);
1362
1363         if (smr.len == 0) {
1364                 cprintf("%d Unable to serialize message\n",
1365                         ERROR+INTERNAL_ERROR);
1366                 return (-1L);
1367         }
1368
1369         /* Write our little bundle of joy into the message base */
1370         begin_critical_section(S_MSGMAIN);
1371         if (cdb_store(CDB_MSGMAIN, &newmsgid, sizeof(long),
1372                       smr.ser, smr.len) < 0) {
1373                 lprintf(2, "Can't store message\n");
1374                 retval = 0L;
1375         } else {
1376                 retval = newmsgid;
1377         }
1378         end_critical_section(S_MSGMAIN);
1379
1380         /* If the caller specified that a copy should be saved to a particular
1381          * file handle, do that now too.
1382          */
1383         if (save_a_copy != NULL) {
1384                 fwrite(smr.ser, smr.len, 1, save_a_copy);
1385         }
1386
1387         /* Free the memory we used for the serialized message */
1388         phree(smr.ser);
1389
1390         /* Return the *local* message ID to the caller
1391          * (even if we're storing an incoming network message)
1392          */
1393         return(retval);
1394 }
1395
1396
1397
1398 /*
1399  * Serialize a struct CtdlMessage into the format used on disk and network.
1400  * 
1401  * This function loads up a "struct ser_ret" (defined in server.h) which
1402  * contains the length of the serialized message and a pointer to the
1403  * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
1404  */
1405 void serialize_message(struct ser_ret *ret,             /* return values */
1406                         struct CtdlMessage *msg)        /* unserialized msg */
1407 {
1408         size_t wlen;
1409         int i;
1410         static char *forder = FORDER;
1411
1412         if (is_valid_message(msg) == 0) return;         /* self check */
1413
1414         ret->len = 3;
1415         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
1416                 ret->len = ret->len +
1417                         strlen(msg->cm_fields[(int)forder[i]]) + 2;
1418
1419         lprintf(9, "calling malloc\n");
1420         ret->ser = mallok(ret->len);
1421         if (ret->ser == NULL) {
1422                 ret->len = 0;
1423                 return;
1424         }
1425
1426         ret->ser[0] = 0xFF;
1427         ret->ser[1] = msg->cm_anon_type;
1428         ret->ser[2] = msg->cm_format_type;
1429         wlen = 3;
1430
1431         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
1432                 ret->ser[wlen++] = (char)forder[i];
1433                 strcpy(&ret->ser[wlen], msg->cm_fields[(int)forder[i]]);
1434                 wlen = wlen + strlen(msg->cm_fields[(int)forder[i]]) + 1;
1435         }
1436         if (ret->len != wlen) lprintf(3, "ERROR: len=%d wlen=%d\n",
1437                 ret->len, wlen);
1438
1439         return;
1440 }
1441
1442
1443
1444 /*
1445  * Back end for the ReplicationChecks() function
1446  */
1447 void check_repl(long msgnum) {
1448         struct CtdlMessage *msg;
1449         time_t timestamp = (-1L);
1450
1451         lprintf(9, "check_repl() found message %ld\n", msgnum);
1452         msg = CtdlFetchMessage(msgnum);
1453         if (msg == NULL) return;
1454         if (msg->cm_fields['T'] != NULL) {
1455                 timestamp = atol(msg->cm_fields['T']);
1456         }
1457         CtdlFreeMessage(msg);
1458
1459         if (timestamp > msg_repl->highest) {
1460                 msg_repl->highest = timestamp;  /* newer! */
1461                 lprintf(9, "newer!\n");
1462                 return;
1463         }
1464         lprintf(9, "older!\n");
1465
1466         /* Existing isn't newer?  Then delete the old one(s). */
1467         CtdlDeleteMessages(CC->quickroom.QRname, msgnum, NULL);
1468 }
1469
1470
1471 /*
1472  * Check to see if any messages already exist which carry the same Extended ID
1473  * as this one.  
1474  *
1475  * If any are found:
1476  * -> With older timestamps: delete them and return 0.  Message will be saved.
1477  * -> With newer timestamps: return 1.  Message save will be aborted.
1478  */
1479 int ReplicationChecks(struct CtdlMessage *msg) {
1480         struct CtdlMessage *template;
1481         int abort_this = 0;
1482
1483         lprintf(9, "ReplicationChecks() started\n");
1484         /* No extended id?  Don't do anything. */
1485         if (msg->cm_fields['E'] == NULL) return 0;
1486         if (strlen(msg->cm_fields['E']) == 0) return 0;
1487         lprintf(9, "Extended ID: <%s>\n", msg->cm_fields['E']);
1488
1489         CtdlAllocUserData(SYM_REPL, sizeof(struct repl));
1490         strcpy(msg_repl->extended_id, msg->cm_fields['E']);
1491         msg_repl->highest = atol(msg->cm_fields['T']);
1492
1493         template = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
1494         memset(template, 0, sizeof(struct CtdlMessage));
1495         template->cm_fields['E'] = strdoop(msg->cm_fields['E']);
1496
1497         CtdlForEachMessage(MSGS_ALL, 0L, NULL, template, check_repl);
1498
1499         /* If a newer message exists with the same Extended ID, abort
1500          * this save.
1501          */
1502         if (msg_repl->highest > atol(msg->cm_fields['T']) ) {
1503                 abort_this = 1;
1504                 }
1505
1506         CtdlFreeMessage(template);
1507         lprintf(9, "ReplicationChecks() returning %d\n", abort_this);
1508         return(abort_this);
1509 }
1510
1511
1512
1513
1514 /*
1515  * Save a message to disk
1516  */
1517 long CtdlSaveMsg(struct CtdlMessage *msg,       /* message to save */
1518                 char *rec,                      /* Recipient (mail) */
1519                 char *force,                    /* force a particular room? */
1520                 int mailtype,                   /* local or remote type */
1521                 int generate_id)                /* 1 = generate 'I' field */
1522 {
1523         char aaa[100];
1524         char hold_rm[ROOMNAMELEN];
1525         char actual_rm[ROOMNAMELEN];
1526         char force_room[ROOMNAMELEN];
1527         char content_type[256];                 /* We have to learn this */
1528         char recipient[256];
1529         long newmsgid;
1530         char *mptr = NULL;
1531         struct usersupp userbuf;
1532         int a;
1533         struct SuppMsgInfo smi;
1534         FILE *network_fp = NULL;
1535         static int seqnum = 1;
1536         struct CtdlMessage *imsg;
1537         char *instr;
1538
1539         lprintf(9, "CtdlSaveMsg() called\n");
1540         if (is_valid_message(msg) == 0) return(-1);     /* self check */
1541
1542         /* If this message has no timestamp, we take the liberty of
1543          * giving it one, right now.
1544          */
1545         if (msg->cm_fields['T'] == NULL) {
1546                 lprintf(9, "Generating timestamp\n");
1547                 sprintf(aaa, "%ld", time(NULL));
1548                 msg->cm_fields['T'] = strdoop(aaa);
1549         }
1550
1551         /* If this message has no path, we generate one.
1552          */
1553         if (msg->cm_fields['P'] == NULL) {
1554                 lprintf(9, "Generating path\n");
1555                 if (msg->cm_fields['A'] != NULL) {
1556                         msg->cm_fields['P'] = strdoop(msg->cm_fields['A']);
1557                         for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
1558                                 if (isspace(msg->cm_fields['P'][a])) {
1559                                         msg->cm_fields['P'][a] = ' ';
1560                                 }
1561                         }
1562                 }
1563                 else {
1564                         msg->cm_fields['P'] = strdoop("unknown");
1565                 }
1566         }
1567
1568         strcpy(force_room, force);
1569
1570         /* Strip non-printable characters out of the recipient name */
1571         strcpy(recipient, rec);
1572         for (a = 0; a < strlen(recipient); ++a)
1573                 if (!isprint(recipient[a]))
1574                         strcpy(&recipient[a], &recipient[a + 1]);
1575
1576         /* Learn about what's inside, because it's what's inside that counts */
1577         lprintf(9, "Learning what's inside\n");
1578         if (msg->cm_fields['M'] == NULL) {
1579                 lprintf(1, "ERROR: attempt to save message with NULL body\n");
1580         }
1581
1582         switch (msg->cm_format_type) {
1583         case 0:
1584                 strcpy(content_type, "text/x-citadel-variformat");
1585                 break;
1586         case 1:
1587                 strcpy(content_type, "text/plain");
1588                 break;
1589         case 4:
1590                 strcpy(content_type, "text/plain");
1591                 /* advance past header fields */
1592                 mptr = msg->cm_fields['M'];
1593                 a = strlen(mptr);
1594                 while (--a) {
1595                         if (!strncasecmp(mptr, "Content-type: ", 14)) {
1596                                 safestrncpy(content_type, mptr,
1597                                             sizeof(content_type));
1598                                 strcpy(content_type, &content_type[14]);
1599                                 for (a = 0; a < strlen(content_type); ++a)
1600                                         if ((content_type[a] == ';')
1601                                             || (content_type[a] == ' ')
1602                                             || (content_type[a] == 13)
1603                                             || (content_type[a] == 10))
1604                                                 content_type[a] = 0;
1605                                 break;
1606                         }
1607                         ++mptr;
1608                 }
1609         }
1610
1611         /* Goto the correct room */
1612         lprintf(9, "Switching rooms\n");
1613         strcpy(hold_rm, CC->quickroom.QRname);
1614         strcpy(actual_rm, CC->quickroom.QRname);
1615
1616         /* If the user is a twit, move to the twit room for posting */
1617         lprintf(9, "Handling twit stuff\n");
1618         if (TWITDETECT) {
1619                 if (CC->usersupp.axlevel == 2) {
1620                         strcpy(hold_rm, actual_rm);
1621                         strcpy(actual_rm, config.c_twitroom);
1622                 }
1623         }
1624
1625         /* ...or if this message is destined for Aide> then go there. */
1626         if (strlen(force_room) > 0) {
1627                 strcpy(actual_rm, force_room);
1628         }
1629
1630         lprintf(9, "Possibly relocating\n");
1631         if (strcasecmp(actual_rm, CC->quickroom.QRname))
1632                 getroom(&CC->quickroom, actual_rm);
1633
1634         /* Perform "before save" hooks (aborting if any return nonzero) */
1635         lprintf(9, "Performing before-save hooks\n");
1636         if (PerformMessageHooks(msg, EVT_BEFORESAVE) > 0) return(-1);
1637
1638         /* If this message has an Extended ID, perform replication checks */
1639         lprintf(9, "Performing replication checks\n");
1640         if (ReplicationChecks(msg) > 0) return(-1);
1641
1642         /* Network mail - send a copy to the network program. */
1643         if ((strlen(recipient) > 0) && (mailtype == MES_BINARY)) {
1644                 lprintf(9, "Sending network spool\n");
1645                 sprintf(aaa, "./network/spoolin/netmail.%04lx.%04x.%04x",
1646                         (long) getpid(), CC->cs_pid, ++seqnum);
1647                 lprintf(9, "Saving a copy to %s\n", aaa);
1648                 network_fp = fopen(aaa, "ab+");
1649                 if (network_fp == NULL)
1650                         lprintf(2, "ERROR: %s\n", strerror(errno));
1651         }
1652
1653         /* Save it to disk */
1654         lprintf(9, "Saving to disk\n");
1655         newmsgid = send_message(msg, generate_id, network_fp);
1656         if (network_fp != NULL) {
1657                 fclose(network_fp);
1658                 system("exec nohup ./netproc -i >/dev/null 2>&1 &");
1659         }
1660
1661         if (newmsgid <= 0L) return(-1);
1662
1663         /* Write a supplemental message info record.  This doesn't have to
1664          * be a critical section because nobody else knows about this message
1665          * yet.
1666          */
1667         lprintf(9, "Creating SuppMsgInfo record\n");
1668         memset(&smi, 0, sizeof(struct SuppMsgInfo));
1669         smi.smi_msgnum = newmsgid;
1670         smi.smi_refcount = 0;
1671         safestrncpy(smi.smi_content_type, content_type, 64);
1672         PutSuppMsgInfo(&smi);
1673
1674         /* Now figure out where to store the pointers */
1675         lprintf(9, "Storing pointers\n");
1676
1677         /* If this is being done by the networker delivering a private
1678          * message, we want to BYPASS saving the sender's copy (because there
1679          * is no local sender; it would otherwise go to the Trashcan).
1680          */
1681         if ((!CC->internal_pgm) || (strlen(recipient) == 0)) {
1682                 CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0);
1683         }
1684
1685         /* For internet mail, drop a copy in the outbound queue room */
1686         if (mailtype == MES_INTERNET) {
1687                 CtdlSaveMsgPointerInRoom(SMTP_SPOOLOUT_ROOM, newmsgid, 0);
1688         }
1689
1690         /* Bump this user's messages posted counter. */
1691         lprintf(9, "Updating user\n");
1692         lgetuser(&CC->usersupp, CC->curr_user);
1693         CC->usersupp.posted = CC->usersupp.posted + 1;
1694         lputuser(&CC->usersupp);
1695
1696         /* If this is private, local mail, make a copy in the
1697          * recipient's mailbox and bump the reference count.
1698          */
1699         if ((strlen(recipient) > 0) && (mailtype == MES_LOCAL)) {
1700                 if (getuser(&userbuf, recipient) == 0) {
1701                         lprintf(9, "Delivering private mail\n");
1702                         MailboxName(actual_rm, &userbuf, MAILROOM);
1703                         CtdlSaveMsgPointerInRoom(actual_rm, newmsgid, 0);
1704                 }
1705         }
1706
1707         /* Perform "after save" hooks */
1708         lprintf(9, "Performing after-save hooks\n");
1709         PerformMessageHooks(msg, EVT_AFTERSAVE);
1710
1711         /* */
1712         lprintf(9, "Returning to original room\n");
1713         if (strcasecmp(hold_rm, CC->quickroom.QRname))
1714                 getroom(&CC->quickroom, hold_rm);
1715
1716         /* For internet mail, generate delivery instructions 
1717          * (Yes, this is recursive!   Deal with it!)
1718          */
1719         if (mailtype == MES_INTERNET) {
1720                 lprintf(9, "Generating delivery instructions\n");
1721                 instr = mallok(2048);
1722                 sprintf(instr,
1723                         "Content-type: %s\n\nmsgid|%ld\nsubmitted|%ld\n"
1724                         "remote|%s|0||\n",
1725                         SPOOLMIME, newmsgid, time(NULL), recipient );
1726
1727                 imsg = mallok(sizeof(struct CtdlMessage));
1728                 memset(imsg, 0, sizeof(struct CtdlMessage));
1729                 imsg->cm_magic = CTDLMESSAGE_MAGIC;
1730                 imsg->cm_anon_type = MES_NORMAL;
1731                 imsg->cm_format_type = FMT_RFC822;
1732                 imsg->cm_fields['A'] = strdoop("Citadel");
1733                 imsg->cm_fields['M'] = instr;
1734                 CtdlSaveMsg(imsg, "", SMTP_SPOOLOUT_ROOM, MES_LOCAL, 1);
1735                 CtdlFreeMessage(imsg);
1736         }
1737
1738         return(newmsgid);
1739 }
1740
1741
1742
1743 /*
1744  * Convenience function for generating small administrative messages.
1745  */
1746 void quickie_message(char *from, char *to, char *room, char *text)
1747 {
1748         struct CtdlMessage *msg;
1749
1750         msg = mallok(sizeof(struct CtdlMessage));
1751         memset(msg, 0, sizeof(struct CtdlMessage));
1752         msg->cm_magic = CTDLMESSAGE_MAGIC;
1753         msg->cm_anon_type = MES_NORMAL;
1754         msg->cm_format_type = 0;
1755         msg->cm_fields['A'] = strdoop(from);
1756         msg->cm_fields['O'] = strdoop(room);
1757         msg->cm_fields['N'] = strdoop(NODENAME);
1758         if (to != NULL)
1759                 msg->cm_fields['R'] = strdoop(to);
1760         msg->cm_fields['M'] = strdoop(text);
1761
1762         CtdlSaveMsg(msg, "", room, MES_LOCAL, 1);
1763         CtdlFreeMessage(msg);
1764         syslog(LOG_NOTICE, text);
1765 }
1766
1767
1768
1769 /*
1770  * Back end function used by make_message() and similar functions
1771  */
1772 char *CtdlReadMessageBody(char *terminator,     /* token signalling EOT */
1773                         size_t maxlen,          /* maximum message length */
1774                         char *exist             /* if non-null, append to it;
1775                                                    exist is ALWAYS freed  */
1776                         ) {
1777         char buf[256];
1778         size_t message_len = 0;
1779         size_t buffer_len = 0;
1780         char *ptr, *append;
1781         char *m;
1782
1783         if (exist == NULL) {
1784                 m = mallok(4096);
1785         }
1786         else {
1787                 m = reallok(exist, strlen(exist) + 4096);
1788                 if (m == NULL) phree(exist);
1789         }
1790         if (m == NULL) {
1791                 while ( (client_gets(buf)>0) && strcmp(buf, terminator) ) ;;
1792                 return(NULL);
1793         } else {
1794                 buffer_len = 4096;
1795                 m[0] = 0;
1796                 message_len = 0;
1797         }
1798         /* read in the lines of message text one by one */
1799         append = NULL;
1800         while ( (client_gets(buf)>0) && strcmp(buf, terminator) ) {
1801
1802                 /* augment the buffer if we have to */
1803                 if ((message_len + strlen(buf) + 2) > buffer_len) {
1804                         lprintf(9, "realloking\n");
1805                         ptr = reallok(m, (buffer_len * 2) );
1806                         if (ptr == NULL) {      /* flush if can't allocate */
1807                                 while ( (client_gets(buf)>0) &&
1808                                         strcmp(buf, terminator)) ;;
1809                                 return(m);
1810                         } else {
1811                                 buffer_len = (buffer_len * 2);
1812                                 m = ptr;
1813                                 append = NULL;
1814                                 lprintf(9, "buffer_len is %d\n", buffer_len);
1815                         }
1816                 }
1817
1818                 if (append == NULL) append = m;
1819                 while (strlen(append) > 0) ++append;
1820                 strcpy(append, buf);
1821                 strcat(append, "\n");
1822                 message_len = message_len + strlen(buf) + 1;
1823
1824                 /* if we've hit the max msg length, flush the rest */
1825                 if (message_len >= maxlen) {
1826                         while ( (client_gets(buf)>0) && strcmp(buf, terminator)) ;;
1827                         return(m);
1828                 }
1829         }
1830         return(m);
1831 }
1832
1833
1834
1835
1836 /*
1837  * Build a binary message to be saved on disk.
1838  */
1839
1840 struct CtdlMessage *make_message(
1841         struct usersupp *author,        /* author's usersupp structure */
1842         char *recipient,                /* NULL if it's not mail */
1843         char *room,                     /* room where it's going */
1844         int type,                       /* see MES_ types in header file */
1845         int net_type,                   /* see MES_ types in header file */
1846         int format_type,                /* local or remote (see citadel.h) */
1847         char *fake_name)                /* who we're masquerading as */
1848 {
1849
1850         int a;
1851         char dest_node[32];
1852         char buf[256];
1853         struct CtdlMessage *msg;
1854
1855         msg = mallok(sizeof(struct CtdlMessage));
1856         memset(msg, 0, sizeof(struct CtdlMessage));
1857         msg->cm_magic = CTDLMESSAGE_MAGIC;
1858         msg->cm_anon_type = type;
1859         msg->cm_format_type = format_type;
1860
1861         /* Don't confuse the poor folks if it's not routed mail. */
1862         strcpy(dest_node, "");
1863
1864         /* If net_type is MES_BINARY, split out the destination node. */
1865         if (net_type == MES_BINARY) {
1866                 strcpy(dest_node, NODENAME);
1867                 for (a = 0; a < strlen(recipient); ++a) {
1868                         if (recipient[a] == '@') {
1869                                 recipient[a] = 0;
1870                                 strcpy(dest_node, &recipient[a + 1]);
1871                         }
1872                 }
1873         }
1874
1875         /* if net_type is MES_INTERNET, set the dest node to 'internet' */
1876         if (net_type == MES_INTERNET) {
1877                 strcpy(dest_node, "internet");
1878         }
1879
1880         while (isspace(recipient[strlen(recipient) - 1]))
1881                 recipient[strlen(recipient) - 1] = 0;
1882
1883         sprintf(buf, "cit%ld", author->usernum);                /* Path */
1884         msg->cm_fields['P'] = strdoop(buf);
1885
1886         sprintf(buf, "%ld", time(NULL));                        /* timestamp */
1887         msg->cm_fields['T'] = strdoop(buf);
1888
1889         if (fake_name[0])                                       /* author */
1890                 msg->cm_fields['A'] = strdoop(fake_name);
1891         else
1892                 msg->cm_fields['A'] = strdoop(author->fullname);
1893
1894         if (CC->quickroom.QRflags & QR_MAILBOX)                 /* room */
1895                 msg->cm_fields['O'] = strdoop(&CC->quickroom.QRname[11]);
1896         else
1897                 msg->cm_fields['O'] = strdoop(CC->quickroom.QRname);
1898
1899         msg->cm_fields['N'] = strdoop(NODENAME);                /* nodename */
1900         msg->cm_fields['H'] = strdoop(HUMANNODE);               /* hnodename */
1901
1902         if (recipient[0] != 0)
1903                 msg->cm_fields['R'] = strdoop(recipient);
1904         if (dest_node[0] != 0)
1905                 msg->cm_fields['D'] = strdoop(dest_node);
1906
1907
1908         msg->cm_fields['M'] = CtdlReadMessageBody("000",
1909                                                 config.c_maxmsglen, NULL);
1910
1911
1912         return(msg);
1913 }
1914
1915
1916
1917
1918
1919 /*
1920  * message entry  -  mode 0 (normal)
1921  */
1922 void cmd_ent0(char *entargs)
1923 {
1924         int post = 0;
1925         char recipient[256];
1926         int anon_flag = 0;
1927         int format_type = 0;
1928         char newusername[256];
1929         struct CtdlMessage *msg;
1930         int a, b;
1931         int e = 0;
1932         int mtsflag = 0;
1933         struct usersupp tempUS;
1934         char buf[256];
1935
1936         post = extract_int(entargs, 0);
1937         extract(recipient, entargs, 1);
1938         anon_flag = extract_int(entargs, 2);
1939         format_type = extract_int(entargs, 3);
1940
1941         /* first check to make sure the request is valid. */
1942
1943         if (!(CC->logged_in)) {
1944                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1945                 return;
1946         }
1947         if ((CC->usersupp.axlevel < 2) && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)) {
1948                 cprintf("%d Need to be validated to enter ",
1949                         ERROR + HIGHER_ACCESS_REQUIRED);
1950                 cprintf("(except in %s> to sysop)\n", MAILROOM);
1951                 return;
1952         }
1953         if ((CC->usersupp.axlevel < 4) && (CC->quickroom.QRflags & QR_NETWORK)) {
1954                 cprintf("%d Need net privileges to enter here.\n",
1955                         ERROR + HIGHER_ACCESS_REQUIRED);
1956                 return;
1957         }
1958         if ((CC->usersupp.axlevel < 6) && (CC->quickroom.QRflags & QR_READONLY)) {
1959                 cprintf("%d Sorry, this is a read-only room.\n",
1960                         ERROR + HIGHER_ACCESS_REQUIRED);
1961                 return;
1962         }
1963         mtsflag = 0;
1964
1965
1966         if (post == 2) {
1967                 if (CC->usersupp.axlevel < 6) {
1968                         cprintf("%d You don't have permission to masquerade.\n",
1969                                 ERROR + HIGHER_ACCESS_REQUIRED);
1970                         return;
1971                 }
1972                 extract(newusername, entargs, 4);
1973                 memset(CC->fake_postname, 0, 32);
1974                 strcpy(CC->fake_postname, newusername);
1975                 cprintf("%d Ok\n", OK);
1976                 return;
1977         }
1978         CC->cs_flags |= CS_POSTING;
1979
1980         buf[0] = 0;
1981         if (CC->quickroom.QRflags & QR_MAILBOX) {
1982                 if (CC->usersupp.axlevel >= 2) {
1983                         strcpy(buf, recipient);
1984                 } else
1985                         strcpy(buf, "sysop");
1986                 e = alias(buf); /* alias and mail type */
1987                 if ((buf[0] == 0) || (e == MES_ERROR)) {
1988                         cprintf("%d Unknown address - cannot send message.\n",
1989                                 ERROR + NO_SUCH_USER);
1990                         return;
1991                 }
1992                 if ((e != MES_LOCAL) && (CC->usersupp.axlevel < 4)) {
1993                         cprintf("%d Net privileges required for network mail.\n",
1994                                 ERROR + HIGHER_ACCESS_REQUIRED);
1995                         return;
1996                 }
1997                 if ((RESTRICT_INTERNET == 1) && (e == MES_INTERNET)
1998                     && ((CC->usersupp.flags & US_INTERNET) == 0)
1999                     && (!CC->internal_pgm)) {
2000                         cprintf("%d You don't have access to Internet mail.\n",
2001                                 ERROR + HIGHER_ACCESS_REQUIRED);
2002                         return;
2003                 }
2004                 if (!strcasecmp(buf, "sysop")) {
2005                         mtsflag = 1;
2006                         goto SKFALL;
2007                 }
2008                 if (e != MES_LOCAL)
2009                         goto SKFALL;    /* don't search local file  */
2010                 if (!strcasecmp(buf, CC->usersupp.fullname)) {
2011                         cprintf("%d Can't send mail to yourself!\n",
2012                                 ERROR + NO_SUCH_USER);
2013                         return;
2014                 }
2015                 /* Check to make sure the user exists; also get the correct
2016                  * upper/lower casing of the name. 
2017                  */
2018                 a = getuser(&tempUS, buf);
2019                 if (a != 0) {
2020                         cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
2021                         return;
2022                 }
2023                 strcpy(buf, tempUS.fullname);
2024         }
2025
2026 SKFALL: b = MES_NORMAL;
2027         if (CC->quickroom.QRflags & QR_ANONONLY)
2028                 b = MES_ANON;
2029         if (CC->quickroom.QRflags & QR_ANONOPT) {
2030                 if (anon_flag == 1)
2031                         b = MES_AN2;
2032         }
2033         if ((CC->quickroom.QRflags & QR_MAILBOX) == 0)
2034                 buf[0] = 0;
2035
2036         /* If we're only checking the validity of the request, return
2037          * success without creating the message.
2038          */
2039         if (post == 0) {
2040                 cprintf("%d %s\n", OK, buf);
2041                 return;
2042         }
2043
2044         cprintf("%d send message\n", SEND_LISTING);
2045
2046         /* Read in the message from the client. */
2047         if (CC->fake_postname[0])
2048                 msg = make_message(&CC->usersupp, buf,
2049                         CC->quickroom.QRname, b, e, format_type,
2050                         CC->fake_postname);
2051         else if (CC->fake_username[0])
2052                 msg = make_message(&CC->usersupp, buf,
2053                         CC->quickroom.QRname, b, e, format_type,
2054                         CC->fake_username);
2055         else
2056                 msg = make_message(&CC->usersupp, buf,
2057                         CC->quickroom.QRname, b, e, format_type, "");
2058
2059         if (msg != NULL)
2060                 CtdlSaveMsg(msg, buf, (mtsflag ? AIDEROOM : ""), e, 1);
2061                 CtdlFreeMessage(msg);
2062         CC->fake_postname[0] = '\0';
2063         return;
2064 }
2065
2066
2067
2068 /* 
2069  * message entry - mode 3 (raw)
2070  */
2071 void cmd_ent3(char *entargs)
2072 {
2073         char recp[256];
2074         int a;
2075         int e = 0;
2076         int valid_msg = 1;
2077         unsigned char ch, which_field;
2078         struct usersupp tempUS;
2079         long msglen;
2080         struct CtdlMessage *msg;
2081         char *tempbuf;
2082
2083         if (CC->internal_pgm == 0) {
2084                 cprintf("%d This command is for internal programs only.\n",
2085                         ERROR);
2086                 return;
2087         }
2088
2089         /* See if there's a recipient, but make sure it's a real one */
2090         extract(recp, entargs, 1);
2091         for (a = 0; a < strlen(recp); ++a)
2092                 if (!isprint(recp[a]))
2093                         strcpy(&recp[a], &recp[a + 1]);
2094         while (isspace(recp[0]))
2095                 strcpy(recp, &recp[1]);
2096         while (isspace(recp[strlen(recp) - 1]))
2097                 recp[strlen(recp) - 1] = 0;
2098
2099         /* If we're in Mail, check the recipient */
2100         if (strlen(recp) > 0) {
2101                 e = alias(recp);        /* alias and mail type */
2102                 if ((recp[0] == 0) || (e == MES_ERROR)) {
2103                         cprintf("%d Unknown address - cannot send message.\n",
2104                                 ERROR + NO_SUCH_USER);
2105                         return;
2106                 }
2107                 if (e == MES_LOCAL) {
2108                         a = getuser(&tempUS, recp);
2109                         if (a != 0) {
2110                                 cprintf("%d No such user.\n",
2111                                         ERROR + NO_SUCH_USER);
2112                                 return;
2113                         }
2114                 }
2115         }
2116
2117         /* At this point, message has been approved. */
2118         if (extract_int(entargs, 0) == 0) {
2119                 cprintf("%d OK to send\n", OK);
2120                 return;
2121         }
2122
2123         msglen = extract_long(entargs, 2);
2124         msg = mallok(sizeof(struct CtdlMessage));
2125         if (msg == NULL) {
2126                 cprintf("%d Out of memory\n", ERROR+INTERNAL_ERROR);
2127                 return;
2128         }
2129
2130         memset(msg, 0, sizeof(struct CtdlMessage));
2131         tempbuf = mallok(msglen);
2132         if (tempbuf == NULL) {
2133                 cprintf("%d Out of memory\n", ERROR+INTERNAL_ERROR);
2134                 phree(msg);
2135                 return;
2136         }
2137
2138         cprintf("%d %ld\n", SEND_BINARY, msglen);
2139
2140         client_read(&ch, 1);                            /* 0xFF magic number */
2141         msg->cm_magic = CTDLMESSAGE_MAGIC;
2142         client_read(&ch, 1);                            /* anon type */
2143         msg->cm_anon_type = ch;
2144         client_read(&ch, 1);                            /* format type */
2145         msg->cm_format_type = ch;
2146         msglen = msglen - 3;
2147
2148         while (msglen > 0) {
2149                 client_read(&which_field, 1);
2150                 if (!isalpha(which_field)) valid_msg = 0;
2151                 --msglen;
2152                 tempbuf[0] = 0;
2153                 do {
2154                         client_read(&ch, 1);
2155                         --msglen;
2156                         a = strlen(tempbuf);
2157                         tempbuf[a+1] = 0;
2158                         tempbuf[a] = ch;
2159                 } while ( (ch != 0) && (msglen > 0) );
2160                 if (valid_msg)
2161                         msg->cm_fields[which_field] = strdoop(tempbuf);
2162         }
2163
2164         msg->cm_flags = CM_SKIP_HOOKS;
2165         if (valid_msg) CtdlSaveMsg(msg, recp, "", e, 0);
2166         CtdlFreeMessage(msg);
2167         phree(tempbuf);
2168 }
2169
2170
2171 /*
2172  * API function to delete messages which match a set of criteria
2173  * (returns the actual number of messages deleted)
2174  */
2175 int CtdlDeleteMessages(char *room_name,         /* which room */
2176                        long dmsgnum,            /* or "0" for any */
2177                        char *content_type       /* or NULL for any */
2178 )
2179 {
2180
2181         struct quickroom qrbuf;
2182         struct cdbdata *cdbfr;
2183         long *msglist = NULL;
2184         int num_msgs = 0;
2185         int i;
2186         int num_deleted = 0;
2187         int delete_this;
2188         struct SuppMsgInfo smi;
2189
2190         lprintf(9, "CtdlDeleteMessages(%s, %ld, %s)\n",
2191                 room_name, dmsgnum, content_type);
2192
2193         /* get room record, obtaining a lock... */
2194         if (lgetroom(&qrbuf, room_name) != 0) {
2195                 lprintf(7, "CtdlDeleteMessages(): Room <%s> not found\n",
2196                         room_name);
2197                 return (0);     /* room not found */
2198         }
2199         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
2200
2201         if (cdbfr != NULL) {
2202                 msglist = mallok(cdbfr->len);
2203                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
2204                 num_msgs = cdbfr->len / sizeof(long);
2205                 cdb_free(cdbfr);
2206         }
2207         if (num_msgs > 0) {
2208                 for (i = 0; i < num_msgs; ++i) {
2209                         delete_this = 0x00;
2210
2211                         /* Set/clear a bit for each criterion */
2212
2213                         if ((dmsgnum == 0L) || (msglist[i] == dmsgnum)) {
2214                                 delete_this |= 0x01;
2215                         }
2216                         if (content_type == NULL) {
2217                                 delete_this |= 0x02;
2218                         } else {
2219                                 GetSuppMsgInfo(&smi, msglist[i]);
2220                                 if (!strcasecmp(smi.smi_content_type,
2221                                                 content_type)) {
2222                                         delete_this |= 0x02;
2223                                 }
2224                         }
2225
2226                         /* Delete message only if all bits are set */
2227                         if (delete_this == 0x03) {
2228                                 AdjRefCount(msglist[i], -1);
2229                                 msglist[i] = 0L;
2230                                 ++num_deleted;
2231                         }
2232                 }
2233
2234                 num_msgs = sort_msglist(msglist, num_msgs);
2235                 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long),
2236                           msglist, (num_msgs * sizeof(long)));
2237
2238                 qrbuf.QRhighest = msglist[num_msgs - 1];
2239                 phree(msglist);
2240         }
2241         lputroom(&qrbuf);
2242         lprintf(9, "%d message(s) deleted.\n", num_deleted);
2243         return (num_deleted);
2244 }
2245
2246
2247
2248 /*
2249  * Delete message from current room
2250  */
2251 void cmd_dele(char *delstr)
2252 {
2253         long delnum;
2254         int num_deleted;
2255
2256         getuser(&CC->usersupp, CC->curr_user);
2257         if ((CC->usersupp.axlevel < 6)
2258             && (CC->usersupp.usernum != CC->quickroom.QRroomaide)
2259             && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)
2260             && (!(CC->internal_pgm))) {
2261                 cprintf("%d Higher access required.\n",
2262                         ERROR + HIGHER_ACCESS_REQUIRED);
2263                 return;
2264         }
2265         delnum = extract_long(delstr, 0);
2266
2267         num_deleted = CtdlDeleteMessages(CC->quickroom.QRname, delnum, NULL);
2268
2269         if (num_deleted) {
2270                 cprintf("%d %d message%s deleted.\n", OK,
2271                         num_deleted, ((num_deleted != 1) ? "s" : ""));
2272         } else {
2273                 cprintf("%d Message %ld not found.\n", ERROR, delnum);
2274         }
2275 }
2276
2277
2278 /*
2279  * move or copy a message to another room
2280  */
2281 void cmd_move(char *args)
2282 {
2283         long num;
2284         char targ[256];
2285         struct quickroom qtemp;
2286         int err;
2287         int is_copy = 0;
2288
2289         num = extract_long(args, 0);
2290         extract(targ, args, 1);
2291         targ[ROOMNAMELEN - 1] = 0;
2292         is_copy = extract_int(args, 2);
2293
2294         getuser(&CC->usersupp, CC->curr_user);
2295         if ((CC->usersupp.axlevel < 6)
2296             && (CC->usersupp.usernum != CC->quickroom.QRroomaide)) {
2297                 cprintf("%d Higher access required.\n",
2298                         ERROR + HIGHER_ACCESS_REQUIRED);
2299                 return;
2300         }
2301
2302         if (getroom(&qtemp, targ) != 0) {
2303                 cprintf("%d '%s' does not exist.\n", ERROR, targ);
2304                 return;
2305         }
2306
2307         err = CtdlSaveMsgPointerInRoom(targ, num,
2308                 (SM_VERIFY_GOODNESS | SM_DO_REPL_CHECK) );
2309         if (err != 0) {
2310                 cprintf("%d Cannot store message in %s: error %d\n",
2311                         err, targ, err);
2312                 return;
2313         }
2314
2315         /* Now delete the message from the source room,
2316          * if this is a 'move' rather than a 'copy' operation.
2317          */
2318         if (is_copy == 0) CtdlDeleteMessages(CC->quickroom.QRname, num, NULL);
2319
2320         cprintf("%d Message %s.\n", OK, (is_copy ? "copied" : "moved") );
2321 }
2322
2323
2324
2325 /*
2326  * GetSuppMsgInfo()  -  Get the supplementary record for a message
2327  */
2328 void GetSuppMsgInfo(struct SuppMsgInfo *smibuf, long msgnum)
2329 {
2330
2331         struct cdbdata *cdbsmi;
2332         long TheIndex;
2333
2334         memset(smibuf, 0, sizeof(struct SuppMsgInfo));
2335         smibuf->smi_msgnum = msgnum;
2336         smibuf->smi_refcount = 1;       /* Default reference count is 1 */
2337
2338         /* Use the negative of the message number for its supp record index */
2339         TheIndex = (0L - msgnum);
2340
2341         cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
2342         if (cdbsmi == NULL) {
2343                 return;         /* record not found; go with defaults */
2344         }
2345         memcpy(smibuf, cdbsmi->ptr,
2346                ((cdbsmi->len > sizeof(struct SuppMsgInfo)) ?
2347                 sizeof(struct SuppMsgInfo) : cdbsmi->len));
2348         cdb_free(cdbsmi);
2349         return;
2350 }
2351
2352
2353 /*
2354  * PutSuppMsgInfo()  -  (re)write supplementary record for a message
2355  */
2356 void PutSuppMsgInfo(struct SuppMsgInfo *smibuf)
2357 {
2358         long TheIndex;
2359
2360         /* Use the negative of the message number for its supp record index */
2361         TheIndex = (0L - smibuf->smi_msgnum);
2362
2363         lprintf(9, "PuttSuppMsgInfo(%ld) - ref count is %d\n",
2364                 smibuf->smi_msgnum, smibuf->smi_refcount);
2365
2366         cdb_store(CDB_MSGMAIN,
2367                   &TheIndex, sizeof(long),
2368                   smibuf, sizeof(struct SuppMsgInfo));
2369
2370 }
2371
2372 /*
2373  * AdjRefCount  -  change the reference count for a message;
2374  *                 delete the message if it reaches zero
2375  */
2376 void AdjRefCount(long msgnum, int incr)
2377 {
2378
2379         struct SuppMsgInfo smi;
2380         long delnum;
2381
2382         /* This is a *tight* critical section; please keep it that way, as
2383          * it may get called while nested in other critical sections.  
2384          * Complicating this any further will surely cause deadlock!
2385          */
2386         begin_critical_section(S_SUPPMSGMAIN);
2387         GetSuppMsgInfo(&smi, msgnum);
2388         lprintf(9, "Ref count for message <%ld> before write is <%d>\n",
2389                 msgnum, smi.smi_refcount);
2390         smi.smi_refcount += incr;
2391         PutSuppMsgInfo(&smi);
2392         end_critical_section(S_SUPPMSGMAIN);
2393         lprintf(9, "Ref count for message <%ld> after write is <%d>\n",
2394                 msgnum, smi.smi_refcount);
2395
2396         /* If the reference count is now zero, delete the message
2397          * (and its supplementary record as well).
2398          */
2399         if (smi.smi_refcount == 0) {
2400                 lprintf(9, "Deleting message <%ld>\n", msgnum);
2401                 delnum = msgnum;
2402                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
2403                 delnum = (0L - msgnum);
2404                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
2405         }
2406 }
2407
2408 /*
2409  * Write a generic object to this room
2410  *
2411  * Note: this could be much more efficient.  Right now we use two temporary
2412  * files, and still pull the message into memory as with all others.
2413  */
2414 void CtdlWriteObject(char *req_room,            /* Room to stuff it in */
2415                         char *content_type,     /* MIME type of this object */
2416                         char *tempfilename,     /* Where to fetch it from */
2417                         struct usersupp *is_mailbox,    /* Mailbox room? */
2418                         int is_binary,          /* Is encoding necessary? */
2419                         int is_unique,          /* Del others of this type? */
2420                         unsigned int flags      /* Internal save flags */
2421                         )
2422 {
2423
2424         FILE *fp, *tempfp;
2425         char filename[PATH_MAX];
2426         char cmdbuf[256];
2427         int ch;
2428         struct quickroom qrbuf;
2429         char roomname[ROOMNAMELEN];
2430         struct CtdlMessage *msg;
2431         size_t len;
2432
2433         if (is_mailbox != NULL)
2434                 MailboxName(roomname, is_mailbox, req_room);
2435         else
2436                 safestrncpy(roomname, req_room, sizeof(roomname));
2437         lprintf(9, "CtdlWriteObject() to <%s> (flags=%d)\n", roomname, flags);
2438
2439         strcpy(filename, tmpnam(NULL));
2440         fp = fopen(filename, "w");
2441         if (fp == NULL)
2442                 return;
2443
2444         tempfp = fopen(tempfilename, "r");
2445         if (tempfp == NULL) {
2446                 fclose(fp);
2447                 unlink(filename);
2448                 return;
2449         }
2450
2451         fprintf(fp, "Content-type: %s\n", content_type);
2452         lprintf(9, "Content-type: %s\n", content_type);
2453
2454         if (is_binary == 0) {
2455                 fprintf(fp, "Content-transfer-encoding: 7bit\n\n");
2456                 while (ch = getc(tempfp), ch > 0)
2457                         putc(ch, fp);
2458                 fclose(tempfp);
2459                 putc(0, fp);
2460                 fclose(fp);
2461         } else {
2462                 fprintf(fp, "Content-transfer-encoding: base64\n\n");
2463                 fclose(tempfp);
2464                 fclose(fp);
2465                 sprintf(cmdbuf, "./base64 -e <%s >>%s",
2466                         tempfilename, filename);
2467                 system(cmdbuf);
2468         }
2469
2470         lprintf(9, "Allocating\n");
2471         msg = mallok(sizeof(struct CtdlMessage));
2472         memset(msg, 0, sizeof(struct CtdlMessage));
2473         msg->cm_magic = CTDLMESSAGE_MAGIC;
2474         msg->cm_anon_type = MES_NORMAL;
2475         msg->cm_format_type = 4;
2476         msg->cm_fields['A'] = strdoop(CC->usersupp.fullname);
2477         msg->cm_fields['O'] = strdoop(req_room);
2478         msg->cm_fields['N'] = strdoop(config.c_nodename);
2479         msg->cm_fields['H'] = strdoop(config.c_humannode);
2480         msg->cm_flags = flags;
2481         
2482         lprintf(9, "Loading\n");
2483         fp = fopen(filename, "rb");
2484         fseek(fp, 0L, SEEK_END);
2485         len = ftell(fp);
2486         rewind(fp);
2487         msg->cm_fields['M'] = mallok(len);
2488         fread(msg->cm_fields['M'], len, 1, fp);
2489         fclose(fp);
2490         unlink(filename);
2491
2492         /* Create the requested room if we have to. */
2493         if (getroom(&qrbuf, roomname) != 0) {
2494                 create_room(roomname, 
2495                         ( (is_mailbox != NULL) ? 4 : 3 ),
2496                         "", 0);
2497         }
2498         /* If the caller specified this object as unique, delete all
2499          * other objects of this type that are currently in the room.
2500          */
2501         if (is_unique) {
2502                 lprintf(9, "Deleted %d other msgs of this type\n",
2503                         CtdlDeleteMessages(roomname, 0L, content_type));
2504         }
2505         /* Now write the data */
2506         CtdlSaveMsg(msg, "", roomname, MES_LOCAL, 1);
2507         CtdlFreeMessage(msg);
2508 }
2509
2510
2511
2512
2513
2514
2515 void CtdlGetSysConfigBackend(long msgnum) {
2516         config_msgnum = msgnum;
2517 }
2518
2519
2520 char *CtdlGetSysConfig(char *sysconfname) {
2521         char hold_rm[ROOMNAMELEN];
2522         long msgnum;
2523         char *conf;
2524         struct CtdlMessage *msg;
2525         char buf[256];
2526         
2527         strcpy(hold_rm, CC->quickroom.QRname);
2528         if (getroom(&CC->quickroom, SYSCONFIGROOM) != 0) {
2529                 getroom(&CC->quickroom, hold_rm);
2530                 return NULL;
2531         }
2532
2533
2534         /* We want the last (and probably only) config in this room */
2535         begin_critical_section(S_CONFIG);
2536         config_msgnum = (-1L);
2537         CtdlForEachMessage(MSGS_LAST, 1, sysconfname, NULL,
2538                 CtdlGetSysConfigBackend);
2539         msgnum = config_msgnum;
2540         end_critical_section(S_CONFIG);
2541
2542         if (msgnum < 0L) {
2543                 conf = NULL;
2544         }
2545         else {
2546                 msg = CtdlFetchMessage(msgnum);
2547                 if (msg != NULL) {
2548                         conf = strdoop(msg->cm_fields['M']);
2549                         CtdlFreeMessage(msg);
2550                 }
2551                 else {
2552                         conf = NULL;
2553                 }
2554         }
2555
2556         getroom(&CC->quickroom, hold_rm);
2557
2558         lprintf(9, "eggstracting...\n");
2559         if (conf != NULL) do {
2560                 extract_token(buf, conf, 0, '\n');
2561                 lprintf(9, "eggstracted <%s>\n", buf);
2562                 strcpy(conf, &conf[strlen(buf)+1]);
2563         } while ( (strlen(conf)>0) && (strlen(buf)>0) );
2564
2565         return(conf);
2566 }
2567
2568 void CtdlPutSysConfig(char *sysconfname, char *sysconfdata) {
2569         char temp[PATH_MAX];
2570         FILE *fp;
2571
2572         strcpy(temp, tmpnam(NULL));
2573
2574         fp = fopen(temp, "w");
2575         if (fp == NULL) return;
2576         fprintf(fp, "%s", sysconfdata);
2577         fclose(fp);
2578
2579         /* this handy API function does all the work for us */
2580         CtdlWriteObject(SYSCONFIGROOM, sysconfname, temp, NULL, 0, 1, 0);
2581         unlink(temp);
2582 }
2583
2584