38b4d69c75718c4b043cdc6cee176f30cfa29ce1
[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 #ifdef HAVE_PTHREAD_H
12 #include <pthread.h>
13 #endif
14 #include <limits.h>
15 #include "citadel.h"
16 #include "server.h"
17 #include <errno.h>
18 #include <sys/stat.h>
19 #include "database.h"
20 #include "msgbase.h"
21 #include "support.h"
22 #include "sysdep_decls.h"
23 #include "citserver.h"
24 #include "room_ops.h"
25 #include "user_ops.h"
26 #include "file_ops.h"
27 #include "control.h"
28 #include "dynloader.h"
29 #include "tools.h"
30 #include "mime_parser.h"
31 #include "html.h"
32
33 #define desired_section ((char *)CtdlGetUserData(SYM_DESIRED_SECTION))
34 #define ma ((struct ma_info *)CtdlGetUserData(SYM_MA_INFO))
35
36 extern struct config config;
37
38 /* FIX dumb stub function */
39 void save_message(char *junk, char *more_junk, char *foo, int wahw, int ee) {
40 }
41
42 /*
43  * This function is self explanatory.
44  * (What can I say, I'm in a weird mood today...)
45  */
46 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
47 {
48         int i;
49
50         for (i = 0; i < strlen(name); ++i)
51                 if (name[i] == '@') {
52                         if (i > 0)
53                                 if (isspace(name[i - 1])) {
54                                         strcpy(&name[i - 1], &name[i]);
55                                         i = 0;
56                                 }
57                         while (isspace(name[i + 1])) {
58                                 strcpy(&name[i + 1], &name[i + 2]);
59                         }
60                 }
61 }
62
63
64 /*
65  * Aliasing for network mail.
66  * (Error messages have been commented out, because this is a server.)
67  */
68 int alias(char *name)
69 {                               /* process alias and routing info for mail */
70         FILE *fp;
71         int a, b;
72         char aaa[300], bbb[300];
73
74         lprintf(9, "alias() called for <%s>\n", name);
75
76         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
77
78         fp = fopen("network/mail.aliases", "r");
79         if (fp == NULL)
80                 fp = fopen("/dev/null", "r");
81         if (fp == NULL)
82                 return (MES_ERROR);
83         strcpy(aaa, "");
84         strcpy(bbb, "");
85         while (fgets(aaa, sizeof aaa, fp) != NULL) {
86                 while (isspace(name[0]))
87                         strcpy(name, &name[1]);
88                 aaa[strlen(aaa) - 1] = 0;
89                 strcpy(bbb, "");
90                 for (a = 0; a < strlen(aaa); ++a) {
91                         if (aaa[a] == ',') {
92                                 strcpy(bbb, &aaa[a + 1]);
93                                 aaa[a] = 0;
94                         }
95                 }
96                 if (!strcasecmp(name, aaa))
97                         strcpy(name, bbb);
98         }
99         fclose(fp);
100         lprintf(7, "Mail is being forwarded to %s\n", name);
101
102         /* determine local or remote type, see citadel.h */
103         for (a = 0; a < strlen(name); ++a)
104                 if (name[a] == '!')
105                         return (MES_INTERNET);
106         for (a = 0; a < strlen(name); ++a)
107                 if (name[a] == '@')
108                         for (b = a; b < strlen(name); ++b)
109                                 if (name[b] == '.')
110                                         return (MES_INTERNET);
111         b = 0;
112         for (a = 0; a < strlen(name); ++a)
113                 if (name[a] == '@')
114                         ++b;
115         if (b > 1) {
116                 lprintf(7, "Too many @'s in address\n");
117                 return (MES_ERROR);
118         }
119         if (b == 1) {
120                 for (a = 0; a < strlen(name); ++a)
121                         if (name[a] == '@')
122                                 strcpy(bbb, &name[a + 1]);
123                 while (bbb[0] == 32)
124                         strcpy(bbb, &bbb[1]);
125                 fp = fopen("network/mail.sysinfo", "r");
126                 if (fp == NULL)
127                         return (MES_ERROR);
128               GETSN:do {
129                         a = getstring(fp, aaa);
130                 } while ((a >= 0) && (strcasecmp(aaa, bbb)));
131                 a = getstring(fp, aaa);
132                 if (!strncmp(aaa, "use ", 4)) {
133                         strcpy(bbb, &aaa[4]);
134                         fseek(fp, 0L, 0);
135                         goto GETSN;
136                 }
137                 fclose(fp);
138                 if (!strncmp(aaa, "uum", 3)) {
139                         strcpy(bbb, name);
140                         for (a = 0; a < strlen(bbb); ++a) {
141                                 if (bbb[a] == '@')
142                                         bbb[a] = 0;
143                                 if (bbb[a] == ' ')
144                                         bbb[a] = '_';
145                         }
146                         while (bbb[strlen(bbb) - 1] == '_')
147                                 bbb[strlen(bbb) - 1] = 0;
148                         sprintf(name, &aaa[4], bbb);
149                         return (MES_INTERNET);
150                 }
151                 if (!strncmp(aaa, "bin", 3)) {
152                         strcpy(aaa, name);
153                         strcpy(bbb, name);
154                         while (aaa[strlen(aaa) - 1] != '@')
155                                 aaa[strlen(aaa) - 1] = 0;
156                         aaa[strlen(aaa) - 1] = 0;
157                         while (aaa[strlen(aaa) - 1] == ' ')
158                                 aaa[strlen(aaa) - 1] = 0;
159                         while (bbb[0] != '@')
160                                 strcpy(bbb, &bbb[1]);
161                         strcpy(bbb, &bbb[1]);
162                         while (bbb[0] == ' ')
163                                 strcpy(bbb, &bbb[1]);
164                         sprintf(name, "%s @%s", aaa, bbb);
165                         return (MES_BINARY);
166                 }
167                 return (MES_ERROR);
168         }
169         return (MES_LOCAL);
170 }
171
172
173 void get_mm(void)
174 {
175         FILE *fp;
176
177         fp = fopen("citadel.control", "r");
178         fread((char *) &CitControl, sizeof(struct CitControl), 1, fp);
179         fclose(fp);
180 }
181
182
183
184 void simple_listing(long msgnum)
185 {
186         cprintf("%ld\n", msgnum);
187 }
188
189
190 /*
191  * API function to perform an operation for each qualifying message in the
192  * current room.
193  */
194 void CtdlForEachMessage(int mode, long ref,
195                         char *content_type,
196                         void (*CallBack) (long msgnum))
197 {
198
199         int a;
200         struct visit vbuf;
201         struct cdbdata *cdbfr;
202         long *msglist = NULL;
203         int num_msgs = 0;
204         long thismsg;
205         struct SuppMsgInfo smi;
206
207         /* Learn about the user and room in question */
208         get_mm();
209         getuser(&CC->usersupp, CC->curr_user);
210         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
211
212         /* Load the message list */
213         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->quickroom.QRnumber, sizeof(long));
214         if (cdbfr != NULL) {
215                 msglist = mallok(cdbfr->len);
216                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
217                 num_msgs = cdbfr->len / sizeof(long);
218                 cdb_free(cdbfr);
219         } else {
220                 return;         /* No messages at all?  No further action. */
221         }
222
223
224         /* If the caller is looking for a specific MIME type, then filter
225          * out all messages which are not of the type requested.
226          */
227         if (num_msgs > 0)
228                 if (content_type != NULL)
229                         if (strlen(content_type) > 0)
230                                 for (a = 0; a < num_msgs; ++a) {
231                                         GetSuppMsgInfo(&smi, msglist[a]);
232                                         if (strcasecmp(smi.smi_content_type, content_type)) {
233                                                 msglist[a] = 0L;
234                                         }
235                                 }
236
237         num_msgs = sort_msglist(msglist, num_msgs);
238         
239         /*
240          * Now iterate through the message list, according to the
241          * criteria supplied by the caller.
242          */
243         if (num_msgs > 0)
244                 for (a = 0; a < num_msgs; ++a) {
245                         thismsg = msglist[a];
246                         if ((thismsg > 0)
247                             && (
248
249                                        (mode == MSGS_ALL)
250                                        || ((mode == MSGS_OLD) && (thismsg <= vbuf.v_lastseen))
251                                        || ((mode == MSGS_NEW) && (thismsg > vbuf.v_lastseen))
252                                        || ((mode == MSGS_NEW) && (thismsg >= vbuf.v_lastseen)
253                                     && (CC->usersupp.flags & US_LASTOLD))
254                                        || ((mode == MSGS_LAST) && (a >= (num_msgs - ref)))
255                                    || ((mode == MSGS_FIRST) && (a < ref))
256                                 || ((mode == MSGS_GT) && (thismsg > ref))
257                             )
258                             ) {
259                                 CallBack(thismsg);
260                         }
261                 }
262         phree(msglist);         /* Clean up */
263 }
264
265
266
267 /*
268  * cmd_msgs()  -  get list of message #'s in this room
269  *                implements the MSGS server command using CtdlForEachMessage()
270  */
271 void cmd_msgs(char *cmdbuf)
272 {
273         int mode = 0;
274         char which[256];
275         int cm_ref = 0;
276
277         extract(which, cmdbuf, 0);
278         cm_ref = extract_int(cmdbuf, 1);
279
280         mode = MSGS_ALL;
281         strcat(which, "   ");
282         if (!strncasecmp(which, "OLD", 3))
283                 mode = MSGS_OLD;
284         else if (!strncasecmp(which, "NEW", 3))
285                 mode = MSGS_NEW;
286         else if (!strncasecmp(which, "FIRST", 5))
287                 mode = MSGS_FIRST;
288         else if (!strncasecmp(which, "LAST", 4))
289                 mode = MSGS_LAST;
290         else if (!strncasecmp(which, "GT", 2))
291                 mode = MSGS_GT;
292
293         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
294                 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
295                 return;
296         }
297         cprintf("%d Message list...\n", LISTING_FOLLOWS);
298         CtdlForEachMessage(mode, cm_ref, NULL, simple_listing);
299         cprintf("000\n");
300 }
301
302
303
304
305 /* 
306  * help_subst()  -  support routine for help file viewer
307  */
308 void help_subst(char *strbuf, char *source, char *dest)
309 {
310         char workbuf[256];
311         int p;
312
313         while (p = pattern2(strbuf, source), (p >= 0)) {
314                 strcpy(workbuf, &strbuf[p + strlen(source)]);
315                 strcpy(&strbuf[p], dest);
316                 strcat(strbuf, workbuf);
317         }
318 }
319
320
321 void do_help_subst(char *buffer)
322 {
323         char buf2[16];
324
325         help_subst(buffer, "^nodename", config.c_nodename);
326         help_subst(buffer, "^humannode", config.c_humannode);
327         help_subst(buffer, "^fqdn", config.c_fqdn);
328         help_subst(buffer, "^username", CC->usersupp.fullname);
329         sprintf(buf2, "%ld", CC->usersupp.usernum);
330         help_subst(buffer, "^usernum", buf2);
331         help_subst(buffer, "^sysadm", config.c_sysadm);
332         help_subst(buffer, "^variantname", CITADEL);
333         sprintf(buf2, "%d", config.c_maxsessions);
334         help_subst(buffer, "^maxsessions", buf2);
335 }
336
337
338
339 /*
340  * memfmout()  -  Citadel text formatter and paginator.
341  *             Although the original purpose of this routine was to format
342  *             text to the reader's screen width, all we're really using it
343  *             for here is to format text out to 80 columns before sending it
344  *             to the client.  The client software may reformat it again.
345  */
346 void memfmout(int width, char *mptr, char subst)
347                         /* screen width to use */
348                         /* where are we going to get our text from? */
349                         /* nonzero if we should use hypertext mode */
350 {
351         int a, b, c;
352         int real = 0;
353         int old = 0;
354         CIT_UBYTE ch;
355         char aaa[140];
356         char buffer[256];
357
358         strcpy(aaa, "");
359         old = 255;
360         strcpy(buffer, "");
361         c = 1;                  /* c is the current pos */
362
363 FMTA:   if (subst) {
364                 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
365                         ch = *mptr++;
366                         buffer[strlen(buffer) + 1] = 0;
367                         buffer[strlen(buffer)] = ch;
368                 }
369
370                 if (buffer[0] == '^')
371                         do_help_subst(buffer);
372
373                 buffer[strlen(buffer) + 1] = 0;
374                 a = buffer[0];
375                 strcpy(buffer, &buffer[1]);
376         } else {
377                 ch = *mptr++;
378         }
379
380         old = real;
381         real = ch;
382         if (ch <= 0)
383                 goto FMTEND;
384
385         if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10))
386                 ch = 32;
387         if (((old == 13) || (old == 10)) && (isspace(real))) {
388                 cprintf("\n");
389                 c = 1;
390         }
391         if (ch > 126)
392                 goto FMTA;
393
394         if (ch > 32) {
395                 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
396                         cprintf("\n%s", aaa);
397                         c = strlen(aaa);
398                         aaa[0] = 0;
399                 }
400                 b = strlen(aaa);
401                 aaa[b] = ch;
402                 aaa[b + 1] = 0;
403         }
404         if (ch == 32) {
405                 if ((strlen(aaa) + c) > (width - 5)) {
406                         cprintf("\n");
407                         c = 1;
408                 }
409                 cprintf("%s ", aaa);
410                 ++c;
411                 c = c + strlen(aaa);
412                 strcpy(aaa, "");
413                 goto FMTA;
414         }
415         if ((ch == 13) || (ch == 10)) {
416                 cprintf("%s\n", aaa);
417                 c = 1;
418                 strcpy(aaa, "");
419                 goto FMTA;
420         }
421         goto FMTA;
422
423 FMTEND: cprintf("%s\n", aaa);
424 }
425
426
427
428 /*
429  * Callback function for mime parser that simply lists the part
430  */
431 void list_this_part(char *name, char *filename, char *partnum, char *disp,
432                     void *content, char *cbtype, size_t length)
433 {
434
435         cprintf("part=%s|%s|%s|%s|%s|%d\n",
436                 name, filename, partnum, disp, cbtype, length);
437 }
438
439
440 /*
441  * Callback function for mime parser that wants to display text
442  */
443 void fixed_output(char *name, char *filename, char *partnum, char *disp,
444                   void *content, char *cbtype, size_t length)
445 {
446         char *ptr;
447
448         if (!strcasecmp(cbtype, "multipart/alternative")) {
449                 strcpy(ma->prefix, partnum);
450                 strcat(ma->prefix, ".");
451                 ma->is_ma = 1;
452                 ma->did_print = 0;
453                 return;
454         }
455
456         if ( (!strncasecmp(partnum, ma->prefix, strlen(ma->prefix)))
457            && (ma->is_ma == 1) 
458            && (ma->did_print == 1) ) {
459                 lprintf(9, "Skipping part %s (%s)\n", partnum, cbtype);
460                 return;
461         }
462
463         ma->did_print = 1;
464
465         if (!strcasecmp(cbtype, "text/plain")) {
466                 client_write(content, length);
467         }
468         else if (!strcasecmp(cbtype, "text/html")) {
469                 ptr = html_to_ascii(content, 80, 0);
470                 client_write(ptr, strlen(ptr));
471                 phree(ptr);
472         }
473         else if (strncasecmp(cbtype, "multipart/", 10)) {
474                 cprintf("Part %s: %s (%s) (%d bytes)\n",
475                         partnum, filename, cbtype, length);
476         }
477 }
478
479
480 /*
481  * Callback function for mime parser that opens a section for downloading
482  */
483 void mime_download(char *name, char *filename, char *partnum, char *disp,
484                    void *content, char *cbtype, size_t length)
485 {
486
487         /* Silently go away if there's already a download open... */
488         if (CC->download_fp != NULL)
489                 return;
490
491         /* ...or if this is not the desired section */
492         if (strcasecmp(desired_section, partnum))
493                 return;
494
495         CC->download_fp = tmpfile();
496         if (CC->download_fp == NULL)
497                 return;
498
499         fwrite(content, length, 1, CC->download_fp);
500         fflush(CC->download_fp);
501         rewind(CC->download_fp);
502
503         OpenCmdResult(filename, cbtype);
504 }
505
506
507
508 /*
509  * Load a message from disk into memory.
510  * This is used by output_message() and other fetch functions.
511  *
512  * NOTE: Caller is responsible for freeing the returned CtdlMessage struct
513  *       using the CtdlMessageFree() function.
514  */
515 struct CtdlMessage *CtdlFetchMessage(long msgnum)
516 {
517         struct cdbdata *dmsgtext;
518         struct CtdlMessage *ret = NULL;
519         char *mptr;
520         CIT_UBYTE ch;
521         CIT_UBYTE field_header;
522         size_t field_length;
523
524
525         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
526         if (dmsgtext == NULL) {
527                 lprintf(9, "CtdlFetchMessage(%ld) failed.\n");
528                 return NULL;
529         }
530         mptr = dmsgtext->ptr;
531
532         /* Parse the three bytes that begin EVERY message on disk.
533          * The first is always 0xFF, the on-disk magic number.
534          * The second is the anonymous/public type byte.
535          * The third is the format type byte (vari, fixed, or MIME).
536          */
537         ch = *mptr++;
538         if (ch != 255) {
539                 lprintf(5, "Message %ld appears to be corrupted.\n", msgnum);
540                 cdb_free(dmsgtext);
541                 return NULL;
542         }
543         ret = (struct CtdlMessage *) mallok(sizeof(struct CtdlMessage));
544         memset(ret, 0, sizeof(struct CtdlMessage));
545
546         ret->cm_magic = CTDLMESSAGE_MAGIC;
547         ret->cm_anon_type = *mptr++;    /* Anon type byte */
548         ret->cm_format_type = *mptr++;  /* Format type byte */
549
550         /*
551          * The rest is zero or more arbitrary fields.  Load them in.
552          * We're done when we encounter either a zero-length field or
553          * have just processed the 'M' (message text) field.
554          */
555         do {
556                 field_length = strlen(mptr);
557                 if (field_length == 0)
558                         break;
559                 field_header = *mptr++;
560                 ret->cm_fields[field_header] = mallok(field_length);
561                 strcpy(ret->cm_fields[field_header], mptr);
562
563                 while (*mptr++ != 0);   /* advance to next field */
564
565         } while ((field_length > 0) && (field_header != 'M'));
566
567         cdb_free(dmsgtext);
568         return (ret);
569 }
570
571
572 /*
573  * Returns 1 if the supplied pointer points to a valid Citadel message.
574  * If the pointer is NULL or the magic number check fails, returns 0.
575  */
576 int is_valid_message(struct CtdlMessage *msg) {
577         if (msg == NULL)
578                 return 0;
579         if ((msg->cm_magic) != CTDLMESSAGE_MAGIC) {
580                 lprintf(3, "is_valid_message() -- self-check failed\n");
581                 return 0;
582         }
583         return 1;
584 }
585
586
587 /*
588  * 'Destructor' for struct CtdlMessage
589  */
590 void CtdlFreeMessage(struct CtdlMessage *msg)
591 {
592         int i;
593
594         if (is_valid_message(msg) == 0) return;
595
596         for (i = 0; i < 256; ++i)
597                 if (msg->cm_fields[i] != NULL)
598                         phree(msg->cm_fields[i]);
599
600         msg->cm_magic = 0;      /* just in case */
601         phree(msg);
602 }
603
604
605
606 /*
607  * Get a message off disk.  (return value is the message's timestamp)
608  * 
609  */
610 void output_message(char *msgid, int mode, int headers_only)
611 {
612         long msg_num;
613         int a, i;
614         char buf[1024];
615         time_t xtime;
616         CIT_UBYTE ch;
617
618         struct CtdlMessage *TheMessage = NULL;
619
620         char *mptr;
621
622         /* buffers needed for RFC822 translation */
623         char suser[256];
624         char luser[256];
625         char snode[256];
626         char lnode[256];
627         char mid[256];
628         /*                                       */
629
630         msg_num = atol(msgid);
631
632         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
633                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
634                 return;
635         }
636
637         /* FIX ... small security issue
638          * We need to check to make sure the requested message is actually
639          * in the current room, and set msg_ok to 1 only if it is.  This
640          * functionality is currently missing because I'm in a hurry to replace
641          * broken production code with nonbroken pre-beta code.  :(   -- ajc
642          *
643          if (!msg_ok) {
644          cprintf("%d Message %ld is not in this room.\n",
645          ERROR, msg_num);
646          return;
647          }
648          */
649
650         /*
651          * Fetch the message from disk
652          */
653         TheMessage = CtdlFetchMessage(msg_num);
654         if (TheMessage == NULL) {
655                 cprintf("%d Can't locate msg %ld on disk\n", ERROR, msg_num);
656                 return;
657         }
658
659         /* Are we downloading a MIME component? */
660         if (mode == MT_DOWNLOAD) {
661                 if (TheMessage->cm_format_type != 4) {
662                         cprintf("%d This is not a MIME message.\n",
663                                 ERROR);
664                 } else if (CC->download_fp != NULL) {
665                         cprintf("%d You already have a download open.\n",
666                                 ERROR);
667                 } else {
668                         /* Parse the message text component */
669                         mptr = TheMessage->cm_fields['M'];
670                         mime_parser(mptr, NULL, *mime_download);
671                         /* If there's no file open by this time, the requested
672                          * section wasn't found, so print an error
673                          */
674                         if (CC->download_fp == NULL) {
675                                 cprintf("%d Section %s not found.\n",
676                                         ERROR + FILE_NOT_FOUND,
677                                         desired_section);
678                         }
679                 }
680                 CtdlFreeMessage(TheMessage);
681                 return;
682         }
683
684         /* now for the user-mode message reading loops */
685         cprintf("%d Message %ld:\n", LISTING_FOLLOWS, msg_num);
686
687         /* Tell the client which format type we're using.  If this is a
688          * MIME message, *lie* about it and tell the user it's fixed-format.
689          */
690         if (mode == MT_CITADEL) {
691                 if (TheMessage->cm_format_type == 4)
692                         cprintf("type=1\n");
693                 else
694                         cprintf("type=%d\n", TheMessage->cm_format_type);
695         }
696
697         /* nhdr=yes means that we're only displaying headers, no body */
698         if ((TheMessage->cm_anon_type == MES_ANON) && (mode == MT_CITADEL)) {
699                 cprintf("nhdr=yes\n");
700         }
701
702         /* begin header processing loop for Citadel message format */
703
704         if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
705
706                 if (TheMessage->cm_fields['P']) {
707                         cprintf("path=%s\n", TheMessage->cm_fields['P']);
708                 }
709                 if (TheMessage->cm_fields['I']) {
710                         cprintf("msgn=%s\n", TheMessage->cm_fields['I']);
711                 }
712                 if (TheMessage->cm_fields['T']) {
713                         cprintf("time=%s\n", TheMessage->cm_fields['T']);
714                 }
715                 if (TheMessage->cm_fields['A']) {
716                         strcpy(buf, TheMessage->cm_fields['A']);
717                         PerformUserHooks(buf, (-1L), EVT_OUTPUTMSG);
718                         if (TheMessage->cm_anon_type == MES_ANON)
719                                 cprintf("from=****");
720                         else if (TheMessage->cm_anon_type == MES_AN2)
721                                 cprintf("from=anonymous");
722                         else
723                                 cprintf("from=%s", buf);
724                         if ((is_room_aide())
725                             && ((TheMessage->cm_anon_type == MES_ANON)
726                              || (TheMessage->cm_anon_type == MES_AN2))) {
727                                 cprintf(" [%s]", buf);
728                         }
729                         cprintf("\n");
730                 }
731                 if (TheMessage->cm_fields['O']) {
732                         cprintf("room=%s\n", TheMessage->cm_fields['O']);
733                 }
734                 if (TheMessage->cm_fields['N']) {
735                         cprintf("node=%s\n", TheMessage->cm_fields['N']);
736                 }
737                 if (TheMessage->cm_fields['H']) {
738                         cprintf("hnod=%s\n", TheMessage->cm_fields['H']);
739                 }
740                 if (TheMessage->cm_fields['R']) {
741                         cprintf("rcpt=%s\n", TheMessage->cm_fields['R']);
742                 }
743                 if (TheMessage->cm_fields['U']) {
744                         cprintf("subj=%s\n", TheMessage->cm_fields['U']);
745                 }
746         }
747
748         /* begin header processing loop for RFC822 transfer format */
749
750         strcpy(suser, "");
751         strcpy(luser, "");
752         strcpy(snode, NODENAME);
753         strcpy(lnode, HUMANNODE);
754         if (mode == MT_RFC822) {
755                 for (i = 0; i < 256; ++i) {
756                         if (TheMessage->cm_fields[i]) {
757                                 mptr = TheMessage->cm_fields[i];
758
759                                 if (i == 'A') {
760                                         strcpy(luser, mptr);
761                                 } else if (i == 'P') {
762                                         cprintf("Path: %s\n", mptr);
763                                         for (a = 0; a < strlen(mptr); ++a) {
764                                                 if (mptr[a] == '!') {
765                                                         strcpy(mptr, &mptr[a + 1]);
766                                                         a = 0;
767                                                 }
768                                         }
769                                         strcpy(suser, mptr);
770                                 } else if (i == 'U')
771                                         cprintf("Subject: %s\n", mptr);
772                                 else if (i == 'I')
773                                         strcpy(mid, mptr);
774                                 else if (i == 'H')
775                                         strcpy(lnode, mptr);
776                                 else if (i == 'O')
777                                         cprintf("X-Citadel-Room: %s\n", mptr);
778                                 else if (i == 'N')
779                                         strcpy(snode, mptr);
780                                 else if (i == 'R')
781                                         cprintf("To: %s\n", mptr);
782                                 else if (i == 'T') {
783                                         xtime = atol(mptr);
784                                         cprintf("Date: %s", asctime(localtime(&xtime)));
785                                 }
786                         }
787                 }
788         }
789
790         if (mode == MT_RFC822) {
791                 if (!strcasecmp(snode, NODENAME)) {
792                         strcpy(snode, FQDN);
793                 }
794                 cprintf("Message-ID: <%s@%s>\n", mid, snode);
795                 PerformUserHooks(luser, (-1L), EVT_OUTPUTMSG);
796                 cprintf("From: %s@%s (%s)\n", suser, snode, luser);
797                 cprintf("Organization: %s\n", lnode);
798         }
799
800         /* end header processing loop ... at this point, we're in the text */
801
802         mptr = TheMessage->cm_fields['M'];
803
804         /* Tell the client about the MIME parts in this message */
805         if (TheMessage->cm_format_type == 4) {  /* legacy textual dump */
806                 if (mode == MT_CITADEL) {
807                         mime_parser(mptr, NULL, *list_this_part);
808                 }
809                 else if (mode == MT_MIME) {     /* list parts only */
810                         mime_parser(mptr, NULL, *list_this_part);
811                         cprintf("000\n");
812                         CtdlFreeMessage(TheMessage);
813                         return;
814                 }
815         }
816
817         if (headers_only) {
818                 cprintf("000\n");
819                 CtdlFreeMessage(TheMessage);
820                 return;
821         }
822
823         /* signify start of msg text */
824         if (mode == MT_CITADEL)
825                 cprintf("text\n");
826         if ((mode == MT_RFC822) && (TheMessage->cm_format_type != 4))
827                 cprintf("\n");
828
829         /* If the format type on disk is 1 (fixed-format), then we want
830          * everything to be output completely literally ... regardless of
831          * what message transfer format is in use.
832          */
833         if (TheMessage->cm_format_type == 1) {
834                 strcpy(buf, "");
835                 while (ch = *mptr++, ch > 0) {
836                         if (ch == 13)
837                                 ch = 10;
838                         if ((ch == 10) || (strlen(buf) > 250)) {
839                                 cprintf("%s\n", buf);
840                                 strcpy(buf, "");
841                         } else {
842                                 buf[strlen(buf) + 1] = 0;
843                                 buf[strlen(buf)] = ch;
844                         }
845                 }
846                 if (strlen(buf) > 0)
847                         cprintf("%s\n", buf);
848         }
849
850         /* If the message on disk is format 0 (Citadel vari-format), we
851          * output using the formatter at 80 columns.  This is the final output
852          * form if the transfer format is RFC822, but if the transfer format
853          * is Citadel proprietary, it'll still work, because the indentation
854          * for new paragraphs is correct and the client will reformat the
855          * message to the reader's screen width.
856          */
857         if (TheMessage->cm_format_type == 0) {
858                 memfmout(80, mptr, 0);
859         }
860
861         /* If the message on disk is format 4 (MIME), we've gotta hand it
862          * off to the MIME parser.  The client has already been told that
863          * this message is format 1 (fixed format), so the callback function
864          * we use will display those parts as-is.
865          */
866         if (TheMessage->cm_format_type == 4) {
867                 CtdlAllocUserData(SYM_MA_INFO, sizeof(struct ma_info));
868                 memset(ma, 0, sizeof(struct ma_info));
869                 mime_parser(mptr, NULL, *fixed_output);
870         }
871
872         /* now we're done */
873         cprintf("000\n");
874         CtdlFreeMessage(TheMessage);
875         return;
876 }
877
878
879
880 /*
881  * display a message (mode 0 - Citadel proprietary)
882  */
883 void cmd_msg0(char *cmdbuf)
884 {
885         char msgid[256];
886         int headers_only = 0;
887
888         extract(msgid, cmdbuf, 0);
889         headers_only = extract_int(cmdbuf, 1);
890
891         output_message(msgid, MT_CITADEL, headers_only);
892         return;
893 }
894
895
896 /*
897  * display a message (mode 2 - RFC822)
898  */
899 void cmd_msg2(char *cmdbuf)
900 {
901         char msgid[256];
902         int headers_only = 0;
903
904         extract(msgid, cmdbuf, 0);
905         headers_only = extract_int(cmdbuf, 1);
906
907         output_message(msgid, MT_RFC822, headers_only);
908 }
909
910
911
912 /* 
913  * display a message (mode 3 - IGnet raw format - internal programs only)
914  */
915 void cmd_msg3(char *cmdbuf)
916 {
917         long msgnum;
918         struct CtdlMessage *msg;
919         struct sermsgret smr;
920
921         if (CC->internal_pgm == 0) {
922                 cprintf("%d This command is for internal programs only.\n",
923                         ERROR);
924                 return;
925         }
926
927         msgnum = extract_long(cmdbuf, 0);
928         msg = CtdlFetchMessage(msgnum);
929         if (msg == NULL) {
930                 cprintf("%d Message %ld not found.\n", 
931                         ERROR, msgnum);
932                 return;
933         }
934
935         serialize_message(&smr, msg);
936         CtdlFreeMessage(msg);
937
938         if (smr.len == 0) {
939                 cprintf("%d Unable to serialize message\n",
940                         ERROR+INTERNAL_ERROR);
941                 return;
942         }
943
944         cprintf("%d %ld\n", BINARY_FOLLOWS, smr.len);
945         client_write(smr.ser, smr.len);
946         phree(smr.ser);
947 }
948
949
950
951 /* 
952  * display a message (mode 4 - MIME) (FIX ... still evolving, not complete)
953  */
954 void cmd_msg4(char *cmdbuf)
955 {
956         char msgid[256];
957
958         extract(msgid, cmdbuf, 0);
959
960         output_message(msgid, MT_MIME, 0);
961 }
962
963 /*
964  * Open a component of a MIME message as a download file 
965  */
966 void cmd_opna(char *cmdbuf)
967 {
968         char msgid[256];
969
970         CtdlAllocUserData(SYM_DESIRED_SECTION, 64);
971
972         extract(msgid, cmdbuf, 0);
973         extract(desired_section, cmdbuf, 1);
974
975         output_message(msgid, MT_DOWNLOAD, 0);
976 }                       
977
978 /*
979  * Message base operation to send a message to the master file
980  * (returns new message number)
981  *
982  * This is the back end for CtdlSaveMsg() and should not be directly
983  * called by server-side modules.
984  *
985  */
986 long send_message(struct CtdlMessage *msg,      /* pointer to buffer */
987                 int generate_id,                /* generate 'I' field? */
988                 FILE *save_a_copy)              /* save a copy to disk? */
989 {
990         long newmsgid;
991         long retval;
992         char msgidbuf[32];
993         struct sermsgret smr;
994
995         /* Get a new message number */
996         newmsgid = get_new_message_number();
997         sprintf(msgidbuf, "%ld", newmsgid);
998
999         if (generate_id) {
1000                 msg->cm_fields['I'] = strdoop(msgidbuf);
1001         }
1002         
1003         serialize_message(&smr, msg);
1004
1005         if (smr.len == 0) {
1006                 cprintf("%d Unable to serialize message\n",
1007                         ERROR+INTERNAL_ERROR);
1008                 return (-1L);
1009         }
1010
1011         /* Write our little bundle of joy into the message base */
1012         begin_critical_section(S_MSGMAIN);
1013         if (cdb_store(CDB_MSGMAIN, &newmsgid, sizeof(long),
1014                       smr.ser, smr.len) < 0) {
1015                 lprintf(2, "Can't store message\n");
1016                 retval = 0L;
1017         } else {
1018                 retval = newmsgid;
1019         }
1020         end_critical_section(S_MSGMAIN);
1021
1022         /* If the caller specified that a copy should be saved to a particular
1023          * file handle, do that now too.
1024          */
1025         if (save_a_copy != NULL) {
1026                 fwrite(smr.ser, smr.len, 1, save_a_copy);
1027         }
1028
1029         /* Free the memory we used for the serialized message */
1030         phree(smr.ser);
1031
1032         /* Return the *local* message ID to the caller
1033          * (even if we're storing an incoming network message)
1034          */
1035         return(retval);
1036 }
1037
1038
1039
1040 /*
1041  * Serialize a struct CtdlMessage into the format used on disk and network.
1042  * 
1043  * This function returns a "struct sermsgret" (defined in msgbase.h) which
1044  * contains the length of the serialized message and a pointer to the
1045  * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
1046  */
1047 void serialize_message(struct sermsgret *ret,           /* return values */
1048                         struct CtdlMessage *msg)        /* unserialized msg */
1049 {
1050         size_t wlen;
1051         int i;
1052         static char *forder = FORDER;
1053
1054         lprintf(9, "serialize_message() called\n");
1055
1056         if (is_valid_message(msg) == 0) return;         /* self check */
1057
1058         lprintf(9, "magic number check OK.\n");
1059
1060         ret->len = 3;
1061         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
1062                 ret->len = ret->len +
1063                         strlen(msg->cm_fields[(int)forder[i]]) + 2;
1064
1065         lprintf(9, "message is %d bytes\n", ret->len);
1066
1067         lprintf(9, "calling malloc\n");
1068         ret->ser = mallok(ret->len);
1069         if (ret->ser == NULL) {
1070                 ret->len = 0;
1071                 return;
1072         }
1073
1074         ret->ser[0] = 0xFF;
1075         ret->ser[1] = msg->cm_anon_type;
1076         ret->ser[2] = msg->cm_format_type;
1077         wlen = 3;
1078         lprintf(9, "stuff\n");
1079
1080         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
1081                 ret->ser[wlen++] = (char)forder[i];
1082                 strcpy(&ret->ser[wlen], msg->cm_fields[(int)forder[i]]);
1083                 wlen = wlen + strlen(msg->cm_fields[(int)forder[i]]) + 1;
1084         }
1085         if (ret->len != wlen) lprintf(3, "ERROR: len=%d wlen=%d\n",
1086                 ret->len, wlen);
1087
1088         return;
1089 }
1090
1091
1092
1093 /*
1094  * Save a message to disk
1095  */
1096 void CtdlSaveMsg(struct CtdlMessage *msg,       /* message to save */
1097                 char *rec,                      /* Recipient (mail) */
1098                 char *force,                    /* force a particular room? */
1099                 int mailtype,                   /* local or remote type */
1100                 int generate_id)                /* 1 = generate 'I' field */
1101 {
1102         char aaa[100];
1103         char hold_rm[ROOMNAMELEN];
1104         char actual_rm[ROOMNAMELEN];
1105         char force_room[ROOMNAMELEN];
1106         char content_type[256]; /* We have to learn this */
1107         char recipient[256];
1108         long newmsgid;
1109         char *mptr;
1110         struct usersupp userbuf;
1111         int a;
1112         int successful_local_recipients = 0;
1113         struct quickroom qtemp;
1114         struct SuppMsgInfo smi;
1115         FILE *network_fp = NULL;
1116         static int seqnum = 1;
1117
1118         lprintf(9, "CtdlSaveMsg() called\n");
1119         if (is_valid_message(msg) == 0) return;         /* self check */
1120
1121         /* If this message has no timestamp, we take the liberty of
1122          * giving it one, right now.
1123          */
1124         if (msg->cm_fields['T'] == NULL) {
1125                 sprintf(aaa, "%ld", time(NULL));
1126                 msg->cm_fields['T'] = strdoop(aaa);
1127         }
1128
1129         /* If this message has no path, we generate one.
1130          */
1131         if (msg->cm_fields['P'] == NULL) {
1132                 msg->cm_fields['P'] = strdoop(msg->cm_fields['A']);
1133                 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
1134                         if (isspace(msg->cm_fields['P'][a])) {
1135                                 msg->cm_fields['P'][a] = ' ';
1136                         }
1137                 }
1138         }
1139
1140         strcpy(force_room, force);
1141
1142         /* Strip non-printable characters out of the recipient name */
1143         strcpy(recipient, rec);
1144         for (a = 0; a < strlen(recipient); ++a)
1145                 if (!isprint(recipient[a]))
1146                         strcpy(&recipient[a], &recipient[a + 1]);
1147
1148         /* Learn about what's inside, because it's what's inside that counts */
1149
1150         switch (msg->cm_format_type) {
1151         case 0:
1152                 strcpy(content_type, "text/x-citadel-variformat");
1153                 break;
1154         case 1:
1155                 strcpy(content_type, "text/plain");
1156                 break;
1157         case 4:
1158                 strcpy(content_type, "text/plain");
1159                 /* advance past header fields */
1160                 mptr = msg->cm_fields['M'];
1161                 a = strlen(mptr);
1162                 while (--a) {
1163                         if (!strncasecmp(mptr, "Content-type: ", 14)) {
1164                                 safestrncpy(content_type, mptr,
1165                                             sizeof(content_type));
1166                                 strcpy(content_type, &content_type[14]);
1167                                 for (a = 0; a < strlen(content_type); ++a)
1168                                         if ((content_type[a] == ';')
1169                                             || (content_type[a] == ' ')
1170                                             || (content_type[a] == 13)
1171                                             || (content_type[a] == 10))
1172                                                 content_type[a] = 0;
1173                                 break;
1174                         }
1175                         ++mptr;
1176                 }
1177         }
1178
1179         /* Network mail - send a copy to the network program. */
1180         if ((strlen(recipient) > 0) && (mailtype != MES_LOCAL)) {
1181                 sprintf(aaa, "./network/spoolin/netmail.%04lx.%04x.%04x",
1182                         (long) getpid(), CC->cs_pid, ++seqnum);
1183                 lprintf(9, "Saving a copy to %s\n", aaa);
1184                 network_fp = fopen(aaa, "ab+");
1185                 if (network_fp == NULL)
1186                         lprintf(2, "ERROR: %s\n", strerror(errno));
1187         }
1188
1189         /* Save it to disk */
1190         newmsgid = send_message(msg, generate_id, network_fp);
1191         if (network_fp != NULL) {
1192                 fclose(network_fp);
1193                 system("exec nohup ./netproc -i >/dev/null 2>&1 &");
1194         }
1195         if (newmsgid <= 0L)
1196                 return;
1197
1198         strcpy(actual_rm, CC->quickroom.QRname);
1199         strcpy(hold_rm, "");
1200
1201         /* If this is being done by the networker delivering a private
1202          * message, we want to BYPASS saving the sender's copy (because there
1203          * is no local sender; it would otherwise go to the Trashcan).
1204          */
1205         if ((!CC->internal_pgm) || (strlen(recipient) == 0)) {
1206                 /* If the user is a twit, move to the twit room for posting */
1207                 if (TWITDETECT)
1208                         if (CC->usersupp.axlevel == 2) {
1209                                 strcpy(hold_rm, actual_rm);
1210                                 strcpy(actual_rm, config.c_twitroom);
1211                         }
1212                 /* ...or if this message is destined for Aide> then go there. */
1213                 if (strlen(force_room) > 0) {
1214                         strcpy(hold_rm, actual_rm);
1215                         strcpy(actual_rm, force_room);
1216                 }
1217                 /* This call to usergoto() changes rooms if necessary.  It also
1218                    * causes the latest message list to be read into memory.
1219                  */
1220                 usergoto(actual_rm, 0);
1221
1222                 /* read in the quickroom record, obtaining a lock... */
1223                 lgetroom(&CC->quickroom, actual_rm);
1224
1225                 /* Fix an obscure bug */
1226                 if (!strcasecmp(CC->quickroom.QRname, AIDEROOM)) {
1227                         CC->quickroom.QRflags =
1228                             CC->quickroom.QRflags & ~QR_MAILBOX;
1229                 }
1230                 /* Add the message pointer to the room */
1231                 CC->quickroom.QRhighest =
1232                     AddMessageToRoom(&CC->quickroom, newmsgid);
1233
1234                 /* update quickroom */
1235                 lputroom(&CC->quickroom);
1236                 ++successful_local_recipients;
1237         }
1238
1239         /* Bump this user's messages posted counter. */
1240         lgetuser(&CC->usersupp, CC->curr_user);
1241         CC->usersupp.posted = CC->usersupp.posted + 1;
1242         lputuser(&CC->usersupp);
1243
1244         /* If this is private, local mail, make a copy in the
1245          * recipient's mailbox and bump the reference count.
1246          */
1247         if ((strlen(recipient) > 0) && (mailtype == MES_LOCAL)) {
1248                 if (getuser(&userbuf, recipient) == 0) {
1249                         MailboxName(actual_rm, &userbuf, MAILROOM);
1250                         if (lgetroom(&qtemp, actual_rm) == 0) {
1251                                 qtemp.QRhighest =
1252                                     AddMessageToRoom(&qtemp, newmsgid);
1253                                 lputroom(&qtemp);
1254                                 ++successful_local_recipients;
1255                         }
1256                 }
1257         }
1258         /* If we've posted in a room other than the current room, then we
1259          * have to now go back to the current room...
1260          */
1261         if (strlen(hold_rm) > 0) {
1262                 usergoto(hold_rm, 0);
1263         }
1264
1265         /* Write a supplemental message info record.  This doesn't have to
1266          * be a critical section because nobody else knows about this message
1267          * yet.
1268          */
1269         memset(&smi, 0, sizeof(struct SuppMsgInfo));
1270         smi.smi_msgnum = newmsgid;
1271         smi.smi_refcount = successful_local_recipients;
1272         safestrncpy(smi.smi_content_type, content_type, 64);
1273         PutSuppMsgInfo(&smi);
1274 }
1275
1276
1277
1278 /*
1279  * Convenience function for generating small administrative messages.
1280  */
1281 void quickie_message(char *from, char *room, char *text)
1282 {
1283         struct CtdlMessage *msg;
1284
1285         msg = mallok(sizeof(struct CtdlMessage));
1286         memset(msg, 0, sizeof(struct CtdlMessage));
1287         msg->cm_magic = CTDLMESSAGE_MAGIC;
1288         msg->cm_anon_type = MES_NORMAL;
1289         msg->cm_format_type = 0;
1290         msg->cm_fields['A'] = strdoop(from);
1291         msg->cm_fields['O'] = strdoop(room);
1292         msg->cm_fields['N'] = strdoop(NODENAME);
1293         msg->cm_fields['M'] = strdoop(text);
1294
1295         CtdlSaveMsg(msg, "", room, MES_LOCAL, 1);
1296         CtdlFreeMessage(msg);
1297         syslog(LOG_NOTICE, text);
1298 }
1299
1300
1301 /*
1302  * Build a binary message to be saved on disk.
1303  */
1304
1305 struct CtdlMessage *make_message(
1306         struct usersupp *author,        /* author's usersupp structure */
1307         char *recipient,                /* NULL if it's not mail */
1308         char *room,                     /* room where it's going */
1309         int type,                       /* see MES_ types in header file */
1310         int net_type,                   /* see MES_ types in header file */
1311         int format_type,                /* local or remote (see citadel.h) */
1312         char *fake_name)                /* who we're masquerading as */
1313 {
1314
1315         int a;
1316         char dest_node[32];
1317         char buf[256];
1318         size_t message_len = 0;
1319         size_t buffer_len = 0;
1320         char *ptr;
1321         struct CtdlMessage *msg;
1322
1323         msg = mallok(sizeof(struct CtdlMessage));
1324         memset(msg, 0, sizeof(struct CtdlMessage));
1325         msg->cm_magic = CTDLMESSAGE_MAGIC;
1326         msg->cm_anon_type = type;
1327         msg->cm_format_type = format_type;
1328
1329         /* Don't confuse the poor folks if it's not routed mail. */
1330         strcpy(dest_node, "");
1331
1332         /* If net_type is MES_BINARY, split out the destination node. */
1333         if (net_type == MES_BINARY) {
1334                 strcpy(dest_node, NODENAME);
1335                 for (a = 0; a < strlen(recipient); ++a) {
1336                         if (recipient[a] == '@') {
1337                                 recipient[a] = 0;
1338                                 strcpy(dest_node, &recipient[a + 1]);
1339                         }
1340                 }
1341         }
1342
1343         /* if net_type is MES_INTERNET, set the dest node to 'internet' */
1344         if (net_type == MES_INTERNET) {
1345                 strcpy(dest_node, "internet");
1346         }
1347
1348         while (isspace(recipient[strlen(recipient) - 1]))
1349                 recipient[strlen(recipient) - 1] = 0;
1350
1351         sprintf(buf, "cit%ld", author->usernum);                /* Path */
1352         msg->cm_fields['P'] = strdoop(buf);
1353
1354         sprintf(buf, "%ld", time(NULL));                        /* timestamp */
1355         msg->cm_fields['T'] = strdoop(buf);
1356
1357         if (fake_name[0])                                       /* author */
1358                 msg->cm_fields['A'] = strdoop(fake_name);
1359         else
1360                 msg->cm_fields['A'] = strdoop(author->fullname);
1361
1362         if (CC->quickroom.QRflags & QR_MAILBOX)                 /* room */
1363                 msg->cm_fields['O'] = strdoop(&CC->quickroom.QRname[11]);
1364         else
1365                 msg->cm_fields['O'] = strdoop(CC->quickroom.QRname);
1366
1367         msg->cm_fields['N'] = strdoop(NODENAME);                /* nodename */
1368         msg->cm_fields['H'] = strdoop(HUMANNODE);               /* hnodename */
1369
1370         if (recipient[0] != 0)
1371                 msg->cm_fields['R'] = strdoop(recipient);
1372         if (dest_node[0] != 0)
1373                 msg->cm_fields['D'] = strdoop(dest_node);
1374
1375         msg->cm_fields['M'] = mallok(4096);
1376         if (msg->cm_fields['M'] == NULL) {
1377                 while (client_gets(buf), strcmp(buf, "000")) ;; /* flush */
1378                 return(msg);
1379         } else {
1380                 buffer_len = 4096;
1381                 msg->cm_fields['M'][0] = 0;
1382                 message_len = 0;
1383         }
1384
1385         /* read in the lines of message text one by one */
1386         while (client_gets(buf), strcmp(buf, "000")) {
1387
1388                 /* augment the buffer if we have to */
1389                 if ((message_len + strlen(buf) + 2) > buffer_len) {
1390                         ptr = reallok(msg->cm_fields['M'], (buffer_len * 2) );
1391                         if (ptr == NULL) {      /* flush if can't allocate */
1392                                 while (client_gets(buf), strcmp(buf, "000")) ;;
1393                                 return(msg);
1394                         } else {
1395                                 buffer_len = (buffer_len * 2);
1396                                 msg->cm_fields['M'] = ptr;
1397                         }
1398                 }
1399
1400                 strcat(msg->cm_fields['M'], buf);
1401                 strcat(msg->cm_fields['M'], "\n");
1402
1403                 /* if we've hit the max msg length, flush the rest */
1404                 if (message_len >= config.c_maxmsglen) {
1405                         while (client_gets(buf), strcmp(buf, "000")) ;;
1406                         return(msg);
1407                 }
1408         }
1409
1410         return(msg);
1411 }
1412
1413
1414
1415
1416
1417 /*
1418  * message entry  -  mode 0 (normal)
1419  */
1420 void cmd_ent0(char *entargs)
1421 {
1422         int post = 0;
1423         char recipient[256];
1424         int anon_flag = 0;
1425         int format_type = 0;
1426         char newusername[256];
1427         struct CtdlMessage *msg;
1428         int a, b;
1429         int e = 0;
1430         int mtsflag = 0;
1431         struct usersupp tempUS;
1432         char buf[256];
1433
1434         post = extract_int(entargs, 0);
1435         extract(recipient, entargs, 1);
1436         anon_flag = extract_int(entargs, 2);
1437         format_type = extract_int(entargs, 3);
1438
1439         /* first check to make sure the request is valid. */
1440
1441         if (!(CC->logged_in)) {
1442                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1443                 return;
1444         }
1445         if ((CC->usersupp.axlevel < 2) && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)) {
1446                 cprintf("%d Need to be validated to enter ",
1447                         ERROR + HIGHER_ACCESS_REQUIRED);
1448                 cprintf("(except in %s> to sysop)\n", MAILROOM);
1449                 return;
1450         }
1451         if ((CC->usersupp.axlevel < 4) && (CC->quickroom.QRflags & QR_NETWORK)) {
1452                 cprintf("%d Need net privileges to enter here.\n",
1453                         ERROR + HIGHER_ACCESS_REQUIRED);
1454                 return;
1455         }
1456         if ((CC->usersupp.axlevel < 6) && (CC->quickroom.QRflags & QR_READONLY)) {
1457                 cprintf("%d Sorry, this is a read-only room.\n",
1458                         ERROR + HIGHER_ACCESS_REQUIRED);
1459                 return;
1460         }
1461         mtsflag = 0;
1462
1463
1464         if (post == 2) {
1465                 if (CC->usersupp.axlevel < 6) {
1466                         cprintf("%d You don't have permission to masquerade.\n",
1467                                 ERROR + HIGHER_ACCESS_REQUIRED);
1468                         return;
1469                 }
1470                 extract(newusername, entargs, 4);
1471                 memset(CC->fake_postname, 0, 32);
1472                 strcpy(CC->fake_postname, newusername);
1473                 cprintf("%d Ok\n", OK);
1474                 return;
1475         }
1476         CC->cs_flags |= CS_POSTING;
1477
1478         buf[0] = 0;
1479         if (CC->quickroom.QRflags & QR_MAILBOX) {
1480                 if (CC->usersupp.axlevel >= 2) {
1481                         strcpy(buf, recipient);
1482                 } else
1483                         strcpy(buf, "sysop");
1484                 e = alias(buf); /* alias and mail type */
1485                 if ((buf[0] == 0) || (e == MES_ERROR)) {
1486                         cprintf("%d Unknown address - cannot send message.\n",
1487                                 ERROR + NO_SUCH_USER);
1488                         return;
1489                 }
1490                 if ((e != MES_LOCAL) && (CC->usersupp.axlevel < 4)) {
1491                         cprintf("%d Net privileges required for network mail.\n",
1492                                 ERROR + HIGHER_ACCESS_REQUIRED);
1493                         return;
1494                 }
1495                 if ((RESTRICT_INTERNET == 1) && (e == MES_INTERNET)
1496                     && ((CC->usersupp.flags & US_INTERNET) == 0)
1497                     && (!CC->internal_pgm)) {
1498                         cprintf("%d You don't have access to Internet mail.\n",
1499                                 ERROR + HIGHER_ACCESS_REQUIRED);
1500                         return;
1501                 }
1502                 if (!strcasecmp(buf, "sysop")) {
1503                         mtsflag = 1;
1504                         goto SKFALL;
1505                 }
1506                 if (e != MES_LOCAL)
1507                         goto SKFALL;    /* don't search local file  */
1508                 if (!strcasecmp(buf, CC->usersupp.fullname)) {
1509                         cprintf("%d Can't send mail to yourself!\n",
1510                                 ERROR + NO_SUCH_USER);
1511                         return;
1512                 }
1513                 /* Check to make sure the user exists; also get the correct
1514                  * upper/lower casing of the name. 
1515                  */
1516                 a = getuser(&tempUS, buf);
1517                 if (a != 0) {
1518                         cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1519                         return;
1520                 }
1521                 strcpy(buf, tempUS.fullname);
1522         }
1523
1524 SKFALL: b = MES_NORMAL;
1525         if (CC->quickroom.QRflags & QR_ANONONLY)
1526                 b = MES_ANON;
1527         if (CC->quickroom.QRflags & QR_ANONOPT) {
1528                 if (anon_flag == 1)
1529                         b = MES_AN2;
1530         }
1531         if ((CC->quickroom.QRflags & QR_MAILBOX) == 0)
1532                 buf[0] = 0;
1533
1534         /* If we're only checking the validity of the request, return
1535          * success without creating the message.
1536          */
1537         if (post == 0) {
1538                 cprintf("%d %s\n", OK, buf);
1539                 return;
1540         }
1541
1542         cprintf("%d send message\n", SEND_LISTING);
1543
1544         /* Read in the message from the client. */
1545         if (CC->fake_postname[0])
1546                 msg = make_message(&CC->usersupp, buf,
1547                         CC->quickroom.QRname, b, e, format_type,
1548                         CC->fake_postname);
1549         else if (CC->fake_username[0])
1550                 msg = make_message(&CC->usersupp, buf,
1551                         CC->quickroom.QRname, b, e, format_type,
1552                         CC->fake_username);
1553         else
1554                 msg = make_message(&CC->usersupp, buf,
1555                         CC->quickroom.QRname, b, e, format_type, "");
1556
1557         if (msg != NULL)
1558                 CtdlSaveMsg(msg, buf, (mtsflag ? AIDEROOM : ""), e, 1);
1559                 CtdlFreeMessage(msg);
1560         CC->fake_postname[0] = '\0';
1561         return;
1562 }
1563
1564
1565
1566 /* 
1567  * message entry - mode 3 (raw)
1568  */
1569 void cmd_ent3(char *entargs)
1570 {
1571         char recp[256];
1572         char buf[256];
1573         int a;
1574         int e = 0;
1575         struct usersupp tempUS;
1576         long msglen;
1577         long bloklen;
1578         FILE *fp;
1579
1580         if (CC->internal_pgm == 0) {
1581                 cprintf("%d This command is for internal programs only.\n",
1582                         ERROR);
1583                 return;
1584         }
1585
1586         /* See if there's a recipient, but make sure it's a real one */
1587         extract(recp, entargs, 1);
1588         for (a = 0; a < strlen(recp); ++a)
1589                 if (!isprint(recp[a]))
1590                         strcpy(&recp[a], &recp[a + 1]);
1591         while (isspace(recp[0]))
1592                 strcpy(recp, &recp[1]);
1593         while (isspace(recp[strlen(recp) - 1]))
1594                 recp[strlen(recp) - 1] = 0;
1595
1596         /* If we're in Mail, check the recipient */
1597         if (strlen(recp) > 0) {
1598                 e = alias(recp);        /* alias and mail type */
1599                 if ((recp[0] == 0) || (e == MES_ERROR)) {
1600                         cprintf("%d Unknown address - cannot send message.\n",
1601                                 ERROR + NO_SUCH_USER);
1602                         return;
1603                 }
1604                 if (e == MES_LOCAL) {
1605                         a = getuser(&tempUS, recp);
1606                         if (a != 0) {
1607                                 cprintf("%d No such user.\n",
1608                                         ERROR + NO_SUCH_USER);
1609                                 return;
1610                         }
1611                 }
1612         }
1613         /* At this point, message has been approved. */
1614         if (extract_int(entargs, 0) == 0) {
1615                 cprintf("%d OK to send\n", OK);
1616                 return;
1617         }
1618         /* open a temp file to hold the message */
1619         fp = fopen(CC->temp, "wb");
1620         if (fp == NULL) {
1621                 cprintf("%d Cannot open %s: %s\n",
1622                         ERROR + INTERNAL_ERROR,
1623                         CC->temp, strerror(errno));
1624                 return;
1625         }
1626         msglen = extract_long(entargs, 2);
1627         cprintf("%d %ld\n", SEND_BINARY, msglen);
1628         while (msglen > 0L) {
1629                 bloklen = ((msglen >= 255L) ? 255 : msglen);
1630                 client_read(buf, (int) bloklen);
1631                 fwrite(buf, (int) bloklen, 1, fp);
1632                 msglen = msglen - bloklen;
1633         }
1634         fclose(fp);
1635
1636         save_message(CC->temp, recp, "", e, 0);
1637 }
1638
1639
1640 /*
1641  * API function to delete messages which match a set of criteria
1642  * (returns the actual number of messages deleted)
1643  * FIX ... still need to implement delete by content type
1644  */
1645 int CtdlDeleteMessages(char *room_name,         /* which room */
1646                        long dmsgnum,            /* or "0" for any */
1647                        char *content_type       /* or NULL for any */
1648 )
1649 {
1650
1651         struct quickroom qrbuf;
1652         struct cdbdata *cdbfr;
1653         long *msglist = NULL;
1654         int num_msgs = 0;
1655         int i;
1656         int num_deleted = 0;
1657         int delete_this;
1658         struct SuppMsgInfo smi;
1659
1660         lprintf(9, "CtdlDeleteMessages(%s, %ld, %s)\n",
1661                 room_name, dmsgnum, content_type);
1662
1663         /* get room record, obtaining a lock... */
1664         if (lgetroom(&qrbuf, room_name) != 0) {
1665                 lprintf(7, "CtdlDeleteMessages(): Room <%s> not found\n",
1666                         room_name);
1667                 return (0);     /* room not found */
1668         }
1669         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
1670
1671         if (cdbfr != NULL) {
1672                 msglist = mallok(cdbfr->len);
1673                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1674                 num_msgs = cdbfr->len / sizeof(long);
1675                 cdb_free(cdbfr);
1676         }
1677         if (num_msgs > 0) {
1678                 for (i = 0; i < num_msgs; ++i) {
1679                         delete_this = 0x00;
1680
1681                         /* Set/clear a bit for each criterion */
1682
1683                         if ((dmsgnum == 0L) || (msglist[i] == dmsgnum)) {
1684                                 delete_this |= 0x01;
1685                         }
1686                         if (content_type == NULL) {
1687                                 delete_this |= 0x02;
1688                         } else {
1689                                 GetSuppMsgInfo(&smi, msglist[i]);
1690                                 if (!strcasecmp(smi.smi_content_type,
1691                                                 content_type)) {
1692                                         delete_this |= 0x02;
1693                                 }
1694                         }
1695
1696                         /* Delete message only if all bits are set */
1697                         if (delete_this == 0x03) {
1698                                 AdjRefCount(msglist[i], -1);
1699                                 msglist[i] = 0L;
1700                                 ++num_deleted;
1701                         }
1702                 }
1703
1704                 num_msgs = sort_msglist(msglist, num_msgs);
1705                 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long),
1706                           msglist, (num_msgs * sizeof(long)));
1707
1708                 qrbuf.QRhighest = msglist[num_msgs - 1];
1709                 phree(msglist);
1710         }
1711         lputroom(&qrbuf);
1712         lprintf(9, "%d message(s) deleted.\n", num_deleted);
1713         return (num_deleted);
1714 }
1715
1716
1717
1718 /*
1719  * Delete message from current room
1720  */
1721 void cmd_dele(char *delstr)
1722 {
1723         long delnum;
1724         int num_deleted;
1725
1726         getuser(&CC->usersupp, CC->curr_user);
1727         if ((CC->usersupp.axlevel < 6)
1728             && (CC->usersupp.usernum != CC->quickroom.QRroomaide)
1729             && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)) {
1730                 cprintf("%d Higher access required.\n",
1731                         ERROR + HIGHER_ACCESS_REQUIRED);
1732                 return;
1733         }
1734         delnum = extract_long(delstr, 0);
1735
1736         num_deleted = CtdlDeleteMessages(CC->quickroom.QRname, delnum, NULL);
1737
1738         if (num_deleted) {
1739                 cprintf("%d %d message%s deleted.\n", OK,
1740                         num_deleted, ((num_deleted != 1) ? "s" : ""));
1741         } else {
1742                 cprintf("%d Message %ld not found.\n", ERROR, delnum);
1743         }
1744 }
1745
1746
1747 /*
1748  * move a message to another room
1749  */
1750 void cmd_move(char *args)
1751 {
1752         long num;
1753         char targ[32];
1754         struct quickroom qtemp;
1755         int foundit;
1756
1757         num = extract_long(args, 0);
1758         extract(targ, args, 1);
1759
1760         getuser(&CC->usersupp, CC->curr_user);
1761         if ((CC->usersupp.axlevel < 6)
1762             && (CC->usersupp.usernum != CC->quickroom.QRroomaide)) {
1763                 cprintf("%d Higher access required.\n",
1764                         ERROR + HIGHER_ACCESS_REQUIRED);
1765                 return;
1766         }
1767         if (getroom(&qtemp, targ) != 0) {
1768                 cprintf("%d '%s' does not exist.\n", ERROR, targ);
1769                 return;
1770         }
1771         /* Bump the reference count, otherwise the message will be deleted
1772          * from disk when we remove it from the source room.
1773          */
1774         AdjRefCount(num, 1);
1775
1776         /* yank the message out of the current room... */
1777         foundit = CtdlDeleteMessages(CC->quickroom.QRname, num, NULL);
1778
1779         if (foundit) {
1780                 /* put the message into the target room */
1781                 lgetroom(&qtemp, targ);
1782                 qtemp.QRhighest = AddMessageToRoom(&qtemp, num);
1783                 lputroom(&qtemp);
1784                 cprintf("%d Message moved.\n", OK);
1785         } else {
1786                 AdjRefCount(num, (-1));         /* oops */
1787                 cprintf("%d msg %ld does not exist.\n", ERROR, num);
1788         }
1789 }
1790
1791
1792
1793 /*
1794  * GetSuppMsgInfo()  -  Get the supplementary record for a message
1795  */
1796 void GetSuppMsgInfo(struct SuppMsgInfo *smibuf, long msgnum)
1797 {
1798
1799         struct cdbdata *cdbsmi;
1800         long TheIndex;
1801
1802         memset(smibuf, 0, sizeof(struct SuppMsgInfo));
1803         smibuf->smi_msgnum = msgnum;
1804         smibuf->smi_refcount = 1;       /* Default reference count is 1 */
1805
1806         /* Use the negative of the message number for its supp record index */
1807         TheIndex = (0L - msgnum);
1808
1809         cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
1810         if (cdbsmi == NULL) {
1811                 return;         /* record not found; go with defaults */
1812         }
1813         memcpy(smibuf, cdbsmi->ptr,
1814                ((cdbsmi->len > sizeof(struct SuppMsgInfo)) ?
1815                 sizeof(struct SuppMsgInfo) : cdbsmi->len));
1816         cdb_free(cdbsmi);
1817         return;
1818 }
1819
1820
1821 /*
1822  * PutSuppMsgInfo()  -  (re)write supplementary record for a message
1823  */
1824 void PutSuppMsgInfo(struct SuppMsgInfo *smibuf)
1825 {
1826         long TheIndex;
1827
1828         /* Use the negative of the message number for its supp record index */
1829         TheIndex = (0L - smibuf->smi_msgnum);
1830
1831         lprintf(9, "PuttSuppMsgInfo(%ld) - ref count is %d\n",
1832                 smibuf->smi_msgnum, smibuf->smi_refcount);
1833
1834         cdb_store(CDB_MSGMAIN,
1835                   &TheIndex, sizeof(long),
1836                   smibuf, sizeof(struct SuppMsgInfo));
1837
1838 }
1839
1840 /*
1841  * AdjRefCount  -  change the reference count for a message;
1842  *                 delete the message if it reaches zero
1843  */
1844 void AdjRefCount(long msgnum, int incr)
1845 {
1846
1847         struct SuppMsgInfo smi;
1848         long delnum;
1849
1850         /* This is a *tight* critical section; please keep it that way, as
1851          * it may get called while nested in other critical sections.  
1852          * Complicating this any further will surely cause deadlock!
1853          */
1854         begin_critical_section(S_SUPPMSGMAIN);
1855         GetSuppMsgInfo(&smi, msgnum);
1856         smi.smi_refcount += incr;
1857         PutSuppMsgInfo(&smi);
1858         end_critical_section(S_SUPPMSGMAIN);
1859
1860         lprintf(9, "Ref count for message <%ld> after write is <%d>\n",
1861                 msgnum, smi.smi_refcount);
1862
1863         /* If the reference count is now zero, delete the message
1864          * (and its supplementary record as well).
1865          */
1866         if (smi.smi_refcount == 0) {
1867                 lprintf(9, "Deleting message <%ld>\n", msgnum);
1868                 delnum = msgnum;
1869                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
1870                 delnum = (0L - msgnum);
1871                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
1872         }
1873 }
1874
1875 /*
1876  * Write a generic object to this room
1877  */
1878 void CtdlWriteObject(char *req_room,            /* Room to stuff it in */
1879                         char *content_type,     /* MIME type of this object */
1880                         char *tempfilename,     /* Where to fetch it from */
1881                         int is_mailbox,         /* Private mailbox room? */
1882                         int is_binary,          /* Is encoding necessary? */
1883                         int is_unique           /* Del others of this type? */
1884                         )
1885 {
1886
1887         FILE *fp, *tempfp;
1888         char filename[PATH_MAX];
1889         char cmdbuf[256];
1890         int ch;
1891         struct quickroom qrbuf;
1892         char roomname[ROOMNAMELEN];
1893         struct CtdlMessage *msg;
1894         size_t len;
1895
1896         lprintf(9, "CtdlWriteObject() called\n");
1897
1898         if (is_mailbox)
1899                 MailboxName(roomname, &CC->usersupp, req_room);
1900         else
1901                 safestrncpy(roomname, req_room, sizeof(roomname));
1902
1903         strcpy(filename, tmpnam(NULL));
1904         fp = fopen(filename, "w");
1905         if (fp == NULL)
1906                 return;
1907
1908         tempfp = fopen(tempfilename, "r");
1909         if (tempfp == NULL) {
1910                 fclose(fp);
1911                 unlink(filename);
1912                 return;
1913         }
1914
1915         fprintf(fp, "Content-type: %s\n", content_type);
1916         lprintf(9, "Content-type: %s\n", content_type);
1917
1918         if (is_binary == 0) {
1919                 fprintf(fp, "Content-transfer-encoding: 7bit\n\n");
1920                 while (ch = getc(tempfp), ch > 0)
1921                         putc(ch, fp);
1922                 fclose(tempfp);
1923                 putc(0, fp);
1924                 fclose(fp);
1925         } else {
1926                 fprintf(fp, "Content-transfer-encoding: base64\n\n");
1927                 fclose(tempfp);
1928                 fclose(fp);
1929                 sprintf(cmdbuf, "./base64 -e <%s >>%s",
1930                         tempfilename, filename);
1931                 system(cmdbuf);
1932         }
1933
1934         lprintf(9, "Allocating\n");
1935         msg = mallok(sizeof(struct CtdlMessage));
1936         memset(msg, 0, sizeof(struct CtdlMessage));
1937         msg->cm_magic = CTDLMESSAGE_MAGIC;
1938         msg->cm_anon_type = MES_NORMAL;
1939         msg->cm_format_type = 4;
1940         msg->cm_fields['A'] = strdoop(CC->usersupp.fullname);
1941         msg->cm_fields['O'] = strdoop(roomname);
1942         msg->cm_fields['N'] = strdoop(config.c_nodename);
1943         msg->cm_fields['H'] = strdoop(config.c_humannode);
1944         
1945         lprintf(9, "Loading\n");
1946         fp = fopen(filename, "rb");
1947         fseek(fp, 0L, SEEK_END);
1948         len = ftell(fp);
1949         rewind(fp);
1950         msg->cm_fields['M'] = mallok(len);
1951         fread(msg->cm_fields['M'], len, 1, fp);
1952         fclose(fp);
1953         unlink(filename);
1954
1955         /* Create the requested room if we have to. */
1956         lprintf(9, "Checking room\n");
1957         if (getroom(&qrbuf, roomname) != 0) {
1958                 create_room(roomname, 4, "", 0);
1959         }
1960         /* If the caller specified this object as unique, delete all
1961          * other objects of this type that are currently in the room.
1962          */
1963         if (is_unique) {
1964                 lprintf(9, "Deleted %d other msgs of this type\n",
1965                         CtdlDeleteMessages(roomname, 0L, content_type));
1966         }
1967         /* Now write the data */
1968         lprintf(9, "Calling CtdlSaveMsg()\n");
1969         CtdlSaveMsg(msg, "", roomname, MES_LOCAL, 1);
1970         lprintf(9, "is valid? %d\n",
1971                 is_valid_message(msg) );
1972         lprintf(9, "Calling CtdlFreeMsg()\n");
1973         CtdlFreeMessage(msg);
1974         lprintf(9, "Done.\n");
1975 }