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