]> code.citadel.org Git - citadel.git/blob - citadel/msgbase.c
* Did most of the migration from save_message() to CtdlSaveMsg(). The
[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         phree(msg);
601 }
602
603
604
605 /*
606  * Get a message off disk.  (return value is the message's timestamp)
607  * 
608  */
609 void output_message(char *msgid, int mode, int headers_only)
610 {
611         long msg_num;
612         int a, i;
613         char buf[1024];
614         time_t xtime;
615         CIT_UBYTE ch;
616
617         struct CtdlMessage *TheMessage = NULL;
618
619         char *mptr;
620
621         /* buffers needed for RFC822 translation */
622         char suser[256];
623         char luser[256];
624         char snode[256];
625         char lnode[256];
626         char mid[256];
627         /*                                       */
628
629         msg_num = atol(msgid);
630
631         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
632                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
633                 return;
634         }
635
636         /* FIX ... small security issue
637          * We need to check to make sure the requested message is actually
638          * in the current room, and set msg_ok to 1 only if it is.  This
639          * functionality is currently missing because I'm in a hurry to replace
640          * broken production code with nonbroken pre-beta code.  :(   -- ajc
641          *
642          if (!msg_ok) {
643          cprintf("%d Message %ld is not in this room.\n",
644          ERROR, msg_num);
645          return;
646          }
647          */
648
649         /*
650          * Fetch the message from disk
651          */
652         TheMessage = CtdlFetchMessage(msg_num);
653         if (TheMessage == NULL) {
654                 cprintf("%d Can't locate msg %ld on disk\n", ERROR, msg_num);
655                 return;
656         }
657
658         /* Are we downloading a MIME component? */
659         if (mode == MT_DOWNLOAD) {
660                 if (TheMessage->cm_format_type != 4) {
661                         cprintf("%d This is not a MIME message.\n",
662                                 ERROR);
663                 } else if (CC->download_fp != NULL) {
664                         cprintf("%d You already have a download open.\n",
665                                 ERROR);
666                 } else {
667                         /* Parse the message text component */
668                         mptr = TheMessage->cm_fields['M'];
669                         mime_parser(mptr, NULL, *mime_download);
670                         /* If there's no file open by this time, the requested
671                          * section wasn't found, so print an error
672                          */
673                         if (CC->download_fp == NULL) {
674                                 cprintf("%d Section %s not found.\n",
675                                         ERROR + FILE_NOT_FOUND,
676                                         desired_section);
677                         }
678                 }
679                 CtdlFreeMessage(TheMessage);
680                 return;
681         }
682
683         /* now for the user-mode message reading loops */
684         cprintf("%d Message %ld:\n", LISTING_FOLLOWS, msg_num);
685
686         /* Tell the client which format type we're using.  If this is a
687          * MIME message, *lie* about it and tell the user it's fixed-format.
688          */
689         if (mode == MT_CITADEL) {
690                 if (TheMessage->cm_format_type == 4)
691                         cprintf("type=1\n");
692                 else
693                         cprintf("type=%d\n", TheMessage->cm_format_type);
694         }
695
696         /* nhdr=yes means that we're only displaying headers, no body */
697         if ((TheMessage->cm_anon_type == MES_ANON) && (mode == MT_CITADEL)) {
698                 cprintf("nhdr=yes\n");
699         }
700
701         /* begin header processing loop for Citadel message format */
702
703         if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
704
705                 if (TheMessage->cm_fields['P']) {
706                         cprintf("path=%s\n", TheMessage->cm_fields['P']);
707                 }
708                 if (TheMessage->cm_fields['I']) {
709                         cprintf("msgn=%s\n", TheMessage->cm_fields['I']);
710                 }
711                 if (TheMessage->cm_fields['T']) {
712                         cprintf("time=%s\n", TheMessage->cm_fields['T']);
713                 }
714                 if (TheMessage->cm_fields['A']) {
715                         strcpy(buf, TheMessage->cm_fields['A']);
716                         PerformUserHooks(buf, (-1L), EVT_OUTPUTMSG);
717                         if (TheMessage->cm_anon_type == MES_ANON)
718                                 cprintf("from=****");
719                         else if (TheMessage->cm_anon_type == MES_AN2)
720                                 cprintf("from=anonymous");
721                         else
722                                 cprintf("from=%s", buf);
723                         if ((is_room_aide())
724                             && ((TheMessage->cm_anon_type == MES_ANON)
725                              || (TheMessage->cm_anon_type == MES_AN2))) {
726                                 cprintf(" [%s]", buf);
727                         }
728                         cprintf("\n");
729                 }
730                 if (TheMessage->cm_fields['O']) {
731                         cprintf("room=%s\n", TheMessage->cm_fields['O']);
732                 }
733                 if (TheMessage->cm_fields['N']) {
734                         cprintf("node=%s\n", TheMessage->cm_fields['N']);
735                 }
736                 if (TheMessage->cm_fields['H']) {
737                         cprintf("hnod=%s\n", TheMessage->cm_fields['H']);
738                 }
739                 if (TheMessage->cm_fields['R']) {
740                         cprintf("rcpt=%s\n", TheMessage->cm_fields['R']);
741                 }
742                 if (TheMessage->cm_fields['U']) {
743                         cprintf("subj=%s\n", TheMessage->cm_fields['U']);
744                 }
745         }
746
747         /* begin header processing loop for RFC822 transfer format */
748
749         strcpy(suser, "");
750         strcpy(luser, "");
751         strcpy(snode, NODENAME);
752         strcpy(lnode, HUMANNODE);
753         if (mode == MT_RFC822) {
754                 for (i = 0; i < 256; ++i) {
755                         if (TheMessage->cm_fields[i]) {
756                                 mptr = TheMessage->cm_fields[i];
757
758                                 if (i == 'A') {
759                                         strcpy(luser, mptr);
760                                 } else if (i == 'P') {
761                                         cprintf("Path: %s\n", mptr);
762                                         for (a = 0; a < strlen(mptr); ++a) {
763                                                 if (mptr[a] == '!') {
764                                                         strcpy(mptr, &mptr[a + 1]);
765                                                         a = 0;
766                                                 }
767                                         }
768                                         strcpy(suser, mptr);
769                                 } else if (i == 'U')
770                                         cprintf("Subject: %s\n", mptr);
771                                 else if (i == 'I')
772                                         strcpy(mid, mptr);
773                                 else if (i == 'H')
774                                         strcpy(lnode, mptr);
775                                 else if (i == 'O')
776                                         cprintf("X-Citadel-Room: %s\n", mptr);
777                                 else if (i == 'N')
778                                         strcpy(snode, mptr);
779                                 else if (i == 'R')
780                                         cprintf("To: %s\n", mptr);
781                                 else if (i == 'T') {
782                                         xtime = atol(mptr);
783                                         cprintf("Date: %s", asctime(localtime(&xtime)));
784                                 }
785                         }
786                 }
787         }
788
789         if (mode == MT_RFC822) {
790                 if (!strcasecmp(snode, NODENAME)) {
791                         strcpy(snode, FQDN);
792                 }
793                 cprintf("Message-ID: <%s@%s>\n", mid, snode);
794                 PerformUserHooks(luser, (-1L), EVT_OUTPUTMSG);
795                 cprintf("From: %s@%s (%s)\n", suser, snode, luser);
796                 cprintf("Organization: %s\n", lnode);
797         }
798
799         /* end header processing loop ... at this point, we're in the text */
800
801         mptr = TheMessage->cm_fields['M'];
802
803         /* Tell the client about the MIME parts in this message */
804         if (TheMessage->cm_format_type == 4) {  /* legacy textual dump */
805                 if (mode == MT_CITADEL) {
806                         mime_parser(mptr, NULL, *list_this_part);
807                 }
808                 else if (mode == MT_MIME) {     /* list parts only */
809                         mime_parser(mptr, NULL, *list_this_part);
810                         cprintf("000\n");
811                         CtdlFreeMessage(TheMessage);
812                         return;
813                 }
814         }
815
816         if (headers_only) {
817                 cprintf("000\n");
818                 CtdlFreeMessage(TheMessage);
819                 return;
820         }
821
822         /* signify start of msg text */
823         if (mode == MT_CITADEL)
824                 cprintf("text\n");
825         if ((mode == MT_RFC822) && (TheMessage->cm_format_type != 4))
826                 cprintf("\n");
827
828         /* If the format type on disk is 1 (fixed-format), then we want
829          * everything to be output completely literally ... regardless of
830          * what message transfer format is in use.
831          */
832         if (TheMessage->cm_format_type == 1) {
833                 strcpy(buf, "");
834                 while (ch = *mptr++, ch > 0) {
835                         if (ch == 13)
836                                 ch = 10;
837                         if ((ch == 10) || (strlen(buf) > 250)) {
838                                 cprintf("%s\n", buf);
839                                 strcpy(buf, "");
840                         } else {
841                                 buf[strlen(buf) + 1] = 0;
842                                 buf[strlen(buf)] = ch;
843                         }
844                 }
845                 if (strlen(buf) > 0)
846                         cprintf("%s\n", buf);
847         }
848
849         /* If the message on disk is format 0 (Citadel vari-format), we
850          * output using the formatter at 80 columns.  This is the final output
851          * form if the transfer format is RFC822, but if the transfer format
852          * is Citadel proprietary, it'll still work, because the indentation
853          * for new paragraphs is correct and the client will reformat the
854          * message to the reader's screen width.
855          */
856         if (TheMessage->cm_format_type == 0) {
857                 memfmout(80, mptr, 0);
858         }
859
860         /* If the message on disk is format 4 (MIME), we've gotta hand it
861          * off to the MIME parser.  The client has already been told that
862          * this message is format 1 (fixed format), so the callback function
863          * we use will display those parts as-is.
864          */
865         if (TheMessage->cm_format_type == 4) {
866                 CtdlAllocUserData(SYM_MA_INFO, sizeof(struct ma_info));
867                 memset(ma, 0, sizeof(struct ma_info));
868                 mime_parser(mptr, NULL, *fixed_output);
869         }
870
871         /* now we're done */
872         cprintf("000\n");
873         CtdlFreeMessage(TheMessage);
874         return;
875 }
876
877
878
879 /*
880  * display a message (mode 0 - Citadel proprietary)
881  */
882 void cmd_msg0(char *cmdbuf)
883 {
884         char msgid[256];
885         int headers_only = 0;
886
887         extract(msgid, cmdbuf, 0);
888         headers_only = extract_int(cmdbuf, 1);
889
890         output_message(msgid, MT_CITADEL, headers_only);
891         return;
892 }
893
894
895 /*
896  * display a message (mode 2 - RFC822)
897  */
898 void cmd_msg2(char *cmdbuf)
899 {
900         char msgid[256];
901         int headers_only = 0;
902
903         extract(msgid, cmdbuf, 0);
904         headers_only = extract_int(cmdbuf, 1);
905
906         output_message(msgid, MT_RFC822, headers_only);
907 }
908
909
910
911 /* 
912  * display a message (mode 3 - IGnet raw format - internal programs only)
913  */
914 void cmd_msg3(char *cmdbuf)
915 {
916         long msgnum;
917         struct CtdlMessage *msg;
918         struct sermsgret smr;
919
920         if (CC->internal_pgm == 0) {
921                 cprintf("%d This command is for internal programs only.\n",
922                         ERROR);
923                 return;
924         }
925
926         msgnum = extract_long(cmdbuf, 0);
927         msg = CtdlFetchMessage(msgnum);
928         if (msg == NULL) {
929                 cprintf("%d Message %ld not found.\n", 
930                         ERROR, msgnum);
931                 return;
932         }
933
934         serialize_message(&smr, msg);
935         CtdlFreeMessage(msg);
936
937         if (smr.len == 0) {
938                 cprintf("%d Unable to serialize message\n",
939                         ERROR+INTERNAL_ERROR);
940                 return;
941         }
942
943         cprintf("%d %ld\n", BINARY_FOLLOWS, smr.len);
944         client_write(smr.ser, smr.len);
945         phree(smr.ser);
946 }
947
948
949
950 /* 
951  * display a message (mode 4 - MIME) (FIX ... still evolving, not complete)
952  */
953 void cmd_msg4(char *cmdbuf)
954 {
955         char msgid[256];
956
957         extract(msgid, cmdbuf, 0);
958
959         output_message(msgid, MT_MIME, 0);
960 }
961
962 /*
963  * Open a component of a MIME message as a download file 
964  */
965 void cmd_opna(char *cmdbuf)
966 {
967         char msgid[256];
968
969         CtdlAllocUserData(SYM_DESIRED_SECTION, 64);
970
971         extract(msgid, cmdbuf, 0);
972         extract(desired_section, cmdbuf, 1);
973
974         output_message(msgid, MT_DOWNLOAD, 0);
975 }                       
976
977 /*
978  * Message base operation to send a message to the master file
979  * (returns new message number)
980  *
981  * This is the back end for CtdlSaveMsg() and should not be directly
982  * called by server-side modules.
983  *
984  */
985 long send_message(struct CtdlMessage *msg,      /* pointer to buffer */
986                 int generate_id,                /* generate 'I' field? */
987                 FILE *save_a_copy)              /* save a copy to disk? */
988 {
989         long newmsgid;
990         long retval;
991         char msgidbuf[32];
992         struct sermsgret smr;
993
994         /* Get a new message number */
995         newmsgid = get_new_message_number();
996         sprintf(msgidbuf, "%ld", newmsgid);
997
998         if (generate_id) {
999                 msg->cm_fields['I'] = strdoop(msgidbuf);
1000         }
1001         
1002         serialize_message(&smr, msg);
1003
1004         if (smr.len == 0) {
1005                 cprintf("%d Unable to serialize message\n",
1006                         ERROR+INTERNAL_ERROR);
1007                 return (-1L);
1008         }
1009
1010         /* Write our little bundle of joy into the message base */
1011         begin_critical_section(S_MSGMAIN);
1012         if (cdb_store(CDB_MSGMAIN, &newmsgid, sizeof(long),
1013                       smr.ser, smr.len) < 0) {
1014                 lprintf(2, "Can't store message\n");
1015                 retval = 0L;
1016         } else {
1017                 retval = newmsgid;
1018         }
1019         end_critical_section(S_MSGMAIN);
1020
1021         /* If the caller specified that a copy should be saved to a particular
1022          * file handle, do that now too.
1023          */
1024         if (save_a_copy != NULL) {
1025                 fwrite(smr.ser, smr.len, 1, save_a_copy);
1026         }
1027
1028         /* Free the memory we used for the serialized message */
1029         phree(smr.ser);
1030
1031         /* Return the *local* message ID to the caller
1032          * (even if we're storing an incoming network message)
1033          */
1034         return(retval);
1035 }
1036
1037
1038
1039 /*
1040  * Serialize a struct CtdlMessage into the format used on disk and network.
1041  * 
1042  * This function returns a "struct sermsgret" (defined in msgbase.h) which
1043  * contains the length of the serialized message and a pointer to the
1044  * serialized message in memory.  THE LATTER MUST BE FREED BY THE CALLER.
1045  */
1046 void serialize_message(struct sermsgret *ret,           /* return values */
1047                         struct CtdlMessage *msg)        /* unserialized msg */
1048 {
1049         size_t wlen;
1050         int i;
1051         static char *forder = FORDER;
1052
1053         lprintf(9, "serialize_message() called\n");
1054
1055         if (is_valid_message(msg) == 0) return;         /* self check */
1056
1057         lprintf(9, "magic number check OK.\n");
1058
1059         ret->len = 3;
1060         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL)
1061                 ret->len = ret->len +
1062                         strlen(msg->cm_fields[(int)forder[i]]) + 2;
1063
1064         lprintf(9, "message is %d bytes\n", ret->len);
1065
1066         lprintf(9, "calling malloc\n");
1067         ret->ser = mallok(ret->len);
1068         if (ret->ser == NULL) {
1069                 ret->len = 0;
1070                 return;
1071         }
1072
1073         ret->ser[0] = 0xFF;
1074         ret->ser[1] = msg->cm_anon_type;
1075         ret->ser[2] = msg->cm_format_type;
1076         wlen = 3;
1077         lprintf(9, "stuff\n");
1078
1079         for (i=0; i<26; ++i) if (msg->cm_fields[(int)forder[i]] != NULL) {
1080                 ret->ser[wlen++] = (char)forder[i];
1081                 strcpy(&ret->ser[wlen], msg->cm_fields[(int)forder[i]]);
1082                 wlen = wlen + strlen(msg->cm_fields[(int)forder[i]]) + 1;
1083         }
1084         if (ret->len != wlen) lprintf(3, "ERROR: len=%d wlen=%d\n",
1085                 ret->len, wlen);
1086
1087         return;
1088 }
1089
1090
1091
1092 /*
1093  * Save a message to disk
1094  */
1095 void CtdlSaveMsg(struct CtdlMessage *msg,       /* message to save */
1096                 char *rec,                      /* Recipient (mail) */
1097                 char *force,                    /* force a particular room? */
1098                 int mailtype,                   /* local or remote type */
1099                 int generate_id)                /* 1 = generate 'I' field */
1100 {
1101         char aaa[100];
1102         char hold_rm[ROOMNAMELEN];
1103         char actual_rm[ROOMNAMELEN];
1104         char force_room[ROOMNAMELEN];
1105         char content_type[256]; /* We have to learn this */
1106         char recipient[256];
1107         long newmsgid;
1108         char *mptr;
1109         struct usersupp userbuf;
1110         int a;
1111         int successful_local_recipients = 0;
1112         struct quickroom qtemp;
1113         struct SuppMsgInfo smi;
1114         FILE *network_fp = NULL;
1115         static int seqnum = 1;
1116
1117         lprintf(9, "CtdlSaveMsg() called\n");
1118         if (is_valid_message(msg) == 0) return;         /* self check */
1119
1120         /* If this message has no timestamp, we take the liberty of
1121          * giving it one, right now.
1122          */
1123         if (msg->cm_fields['T'] == NULL) {
1124                 sprintf(aaa, "%ld", time(NULL));
1125                 msg->cm_fields['T'] = strdoop(aaa);
1126         }
1127
1128         /* If this message has no path, we generate one.
1129          */
1130         if (msg->cm_fields['P'] == NULL) {
1131                 msg->cm_fields['P'] = strdoop(msg->cm_fields['A']);
1132                 for (a=0; a<strlen(msg->cm_fields['P']); ++a) {
1133                         if (isspace(msg->cm_fields['P'][a])) {
1134                                 msg->cm_fields['P'][a] = ' ';
1135                         }
1136                 }
1137         }
1138
1139         strcpy(force_room, force);
1140
1141         /* Strip non-printable characters out of the recipient name */
1142         strcpy(recipient, rec);
1143         for (a = 0; a < strlen(recipient); ++a)
1144                 if (!isprint(recipient[a]))
1145                         strcpy(&recipient[a], &recipient[a + 1]);
1146
1147         /* Learn about what's inside, because it's what's inside that counts */
1148
1149         switch (msg->cm_format_type) {
1150         case 0:
1151                 strcpy(content_type, "text/x-citadel-variformat");
1152                 break;
1153         case 1:
1154                 strcpy(content_type, "text/plain");
1155                 break;
1156         case 4:
1157                 strcpy(content_type, "text/plain");
1158                 /* advance past header fields */
1159                 mptr = msg->cm_fields['M'];
1160                 a = strlen(mptr);
1161                 while (--a) {
1162                         if (!strncasecmp(mptr, "Content-type: ", 14)) {
1163                                 safestrncpy(content_type, mptr,
1164                                             sizeof(content_type));
1165                                 strcpy(content_type, &content_type[14]);
1166                                 for (a = 0; a < strlen(content_type); ++a)
1167                                         if ((content_type[a] == ';')
1168                                             || (content_type[a] == ' ')
1169                                             || (content_type[a] == 13)
1170                                             || (content_type[a] == 10))
1171                                                 content_type[a] = 0;
1172                                 break;
1173                         }
1174                         ++mptr;
1175                 }
1176         }
1177
1178         /* Network mail - send a copy to the network program. */
1179         if ((strlen(recipient) > 0) && (mailtype != MES_LOCAL)) {
1180                 sprintf(aaa, "./network/spoolin/netmail.%04lx.%04x.%04x",
1181                         (long) getpid(), CC->cs_pid, ++seqnum);
1182                 lprintf(9, "Saving a copy to %s\n", aaa);
1183                 network_fp = fopen(aaa, "ab+");
1184                 if (network_fp == NULL)
1185                         lprintf(2, "ERROR: %s\n", strerror(errno));
1186         }
1187
1188         /* Save it to disk */
1189         newmsgid = send_message(msg, generate_id, network_fp);
1190         if (network_fp != NULL) {
1191                 fclose(network_fp);
1192                 system("exec nohup ./netproc -i >/dev/null 2>&1 &");
1193         }
1194         if (newmsgid <= 0L)
1195                 return;
1196
1197         strcpy(actual_rm, CC->quickroom.QRname);
1198         strcpy(hold_rm, "");
1199
1200         /* If this is being done by the networker delivering a private
1201          * message, we want to BYPASS saving the sender's copy (because there
1202          * is no local sender; it would otherwise go to the Trashcan).
1203          */
1204         if ((!CC->internal_pgm) || (strlen(recipient) == 0)) {
1205                 /* If the user is a twit, move to the twit room for posting */
1206                 if (TWITDETECT)
1207                         if (CC->usersupp.axlevel == 2) {
1208                                 strcpy(hold_rm, actual_rm);
1209                                 strcpy(actual_rm, config.c_twitroom);
1210                         }
1211                 /* ...or if this message is destined for Aide> then go there. */
1212                 if (strlen(force_room) > 0) {
1213                         strcpy(hold_rm, actual_rm);
1214                         strcpy(actual_rm, force_room);
1215                 }
1216                 /* This call to usergoto() changes rooms if necessary.  It also
1217                    * causes the latest message list to be read into memory.
1218                  */
1219                 usergoto(actual_rm, 0);
1220
1221                 /* read in the quickroom record, obtaining a lock... */
1222                 lgetroom(&CC->quickroom, actual_rm);
1223
1224                 /* Fix an obscure bug */
1225                 if (!strcasecmp(CC->quickroom.QRname, AIDEROOM)) {
1226                         CC->quickroom.QRflags =
1227                             CC->quickroom.QRflags & ~QR_MAILBOX;
1228                 }
1229                 /* Add the message pointer to the room */
1230                 CC->quickroom.QRhighest =
1231                     AddMessageToRoom(&CC->quickroom, newmsgid);
1232
1233                 /* update quickroom */
1234                 lputroom(&CC->quickroom);
1235                 ++successful_local_recipients;
1236         }
1237
1238         /* Bump this user's messages posted counter. */
1239         lgetuser(&CC->usersupp, CC->curr_user);
1240         CC->usersupp.posted = CC->usersupp.posted + 1;
1241         lputuser(&CC->usersupp);
1242
1243         /* If this is private, local mail, make a copy in the
1244          * recipient's mailbox and bump the reference count.
1245          */
1246         if ((strlen(recipient) > 0) && (mailtype == MES_LOCAL)) {
1247                 if (getuser(&userbuf, recipient) == 0) {
1248                         MailboxName(actual_rm, &userbuf, MAILROOM);
1249                         if (lgetroom(&qtemp, actual_rm) == 0) {
1250                                 qtemp.QRhighest =
1251                                     AddMessageToRoom(&qtemp, newmsgid);
1252                                 lputroom(&qtemp);
1253                                 ++successful_local_recipients;
1254                         }
1255                 }
1256         }
1257         /* If we've posted in a room other than the current room, then we
1258          * have to now go back to the current room...
1259          */
1260         if (strlen(hold_rm) > 0) {
1261                 usergoto(hold_rm, 0);
1262         }
1263
1264         /* Write a supplemental message info record.  This doesn't have to
1265          * be a critical section because nobody else knows about this message
1266          * yet.
1267          */
1268         memset(&smi, 0, sizeof(struct SuppMsgInfo));
1269         smi.smi_msgnum = newmsgid;
1270         smi.smi_refcount = successful_local_recipients;
1271         safestrncpy(smi.smi_content_type, content_type, 64);
1272         PutSuppMsgInfo(&smi);
1273 }
1274
1275
1276
1277 /*
1278  * Convenience function for generating small administrative messages.
1279  */
1280 void quickie_message(char *from, char *room, char *text)
1281 {
1282         struct CtdlMessage *msg;
1283
1284         msg = mallok(sizeof(struct CtdlMessage));
1285         memset(msg, 0, sizeof(struct CtdlMessage));
1286         msg->cm_magic = CTDLMESSAGE_MAGIC;
1287         msg->cm_anon_type = MES_NORMAL;
1288         msg->cm_format_type = 0;
1289         msg->cm_fields['A'] = strdoop(from);
1290         msg->cm_fields['O'] = strdoop(room);
1291         msg->cm_fields['N'] = strdoop(NODENAME);
1292         msg->cm_fields['M'] = strdoop(text);
1293
1294         CtdlSaveMsg(msg, "", room, MES_LOCAL, 1);
1295         CtdlFreeMessage(msg);
1296         syslog(LOG_NOTICE, text);
1297 }
1298
1299
1300 /*
1301  * Build a binary message to be saved on disk.
1302  */
1303
1304 struct CtdlMessage *make_message(
1305         struct usersupp *author,        /* author's usersupp structure */
1306         char *recipient,                /* NULL if it's not mail */
1307         char *room,                     /* room where it's going */
1308         int type,                       /* see MES_ types in header file */
1309         int net_type,                   /* see MES_ types in header file */
1310         int format_type,                /* local or remote (see citadel.h) */
1311         char *fake_name)                /* who we're masquerading as */
1312 {
1313
1314         int a;
1315         char dest_node[32];
1316         char buf[256];
1317         size_t message_len = 0;
1318         size_t buffer_len = 0;
1319         char *ptr;
1320         struct CtdlMessage *msg;
1321
1322         msg = mallok(sizeof(struct CtdlMessage));
1323         memset(msg, 0, sizeof(struct CtdlMessage));
1324         msg->cm_magic = CTDLMESSAGE_MAGIC;
1325         msg->cm_anon_type = type;
1326         msg->cm_format_type = format_type;
1327
1328         /* Don't confuse the poor folks if it's not routed mail. */
1329         strcpy(dest_node, "");
1330
1331         /* If net_type is MES_BINARY, split out the destination node. */
1332         if (net_type == MES_BINARY) {
1333                 strcpy(dest_node, NODENAME);
1334                 for (a = 0; a < strlen(recipient); ++a) {
1335                         if (recipient[a] == '@') {
1336                                 recipient[a] = 0;
1337                                 strcpy(dest_node, &recipient[a + 1]);
1338                         }
1339                 }
1340         }
1341
1342         /* if net_type is MES_INTERNET, set the dest node to 'internet' */
1343         if (net_type == MES_INTERNET) {
1344                 strcpy(dest_node, "internet");
1345         }
1346
1347         while (isspace(recipient[strlen(recipient) - 1]))
1348                 recipient[strlen(recipient) - 1] = 0;
1349
1350         sprintf(buf, "cit%ld", author->usernum);                /* Path */
1351         msg->cm_fields['P'] = strdoop(buf);
1352
1353         sprintf(buf, "%ld", time(NULL));                        /* timestamp */
1354         msg->cm_fields['T'] = strdoop(buf);
1355
1356         if (fake_name[0])                                       /* author */
1357                 msg->cm_fields['A'] = strdoop(fake_name);
1358         else
1359                 msg->cm_fields['A'] = strdoop(author->fullname);
1360
1361         if (CC->quickroom.QRflags & QR_MAILBOX)                 /* room */
1362                 msg->cm_fields['O'] = strdoop(&CC->quickroom.QRname[11]);
1363         else
1364                 msg->cm_fields['O'] = strdoop(CC->quickroom.QRname);
1365
1366         msg->cm_fields['N'] = strdoop(NODENAME);                /* nodename */
1367         msg->cm_fields['H'] = strdoop(HUMANNODE);               /* hnodename */
1368
1369         if (recipient[0] != 0)
1370                 msg->cm_fields['R'] = strdoop(recipient);
1371         if (dest_node[0] != 0)
1372                 msg->cm_fields['D'] = strdoop(dest_node);
1373
1374         msg->cm_fields['M'] = mallok(4096);
1375         if (msg->cm_fields['M'] == NULL) {
1376                 while (client_gets(buf), strcmp(buf, "000")) ;; /* flush */
1377                 return(msg);
1378         } else {
1379                 buffer_len = 4096;
1380                 msg->cm_fields['M'][0] = 0;
1381                 message_len = 0;
1382         }
1383
1384         /* read in the lines of message text one by one */
1385         while (client_gets(buf), strcmp(buf, "000")) {
1386
1387                 /* augment the buffer if we have to */
1388                 if ((message_len + strlen(buf) + 2) > buffer_len) {
1389                         ptr = reallok(msg->cm_fields['M'], (buffer_len * 2) );
1390                         if (ptr == NULL) {      /* flush if can't allocate */
1391                                 while (client_gets(buf), strcmp(buf, "000")) ;;
1392                                 return(msg);
1393                         } else {
1394                                 buffer_len = (buffer_len * 2);
1395                                 msg->cm_fields['M'] = ptr;
1396                         }
1397                 }
1398
1399                 strcat(msg->cm_fields['M'], buf);
1400                 strcat(msg->cm_fields['M'], "\n");
1401
1402                 /* if we've hit the max msg length, flush the rest */
1403                 if (message_len >= config.c_maxmsglen) {
1404                         while (client_gets(buf), strcmp(buf, "000")) ;;
1405                         return(msg);
1406                 }
1407         }
1408
1409         return(msg);
1410 }
1411
1412
1413
1414
1415
1416 /*
1417  * message entry  -  mode 0 (normal)
1418  */
1419 void cmd_ent0(char *entargs)
1420 {
1421         int post = 0;
1422         char recipient[256];
1423         int anon_flag = 0;
1424         int format_type = 0;
1425         char newusername[256];
1426         struct CtdlMessage *msg;
1427         int a, b;
1428         int e = 0;
1429         int mtsflag = 0;
1430         struct usersupp tempUS;
1431         char buf[256];
1432
1433         post = extract_int(entargs, 0);
1434         extract(recipient, entargs, 1);
1435         anon_flag = extract_int(entargs, 2);
1436         format_type = extract_int(entargs, 3);
1437
1438         /* first check to make sure the request is valid. */
1439
1440         if (!(CC->logged_in)) {
1441                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1442                 return;
1443         }
1444         if ((CC->usersupp.axlevel < 2) && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)) {
1445                 cprintf("%d Need to be validated to enter ",
1446                         ERROR + HIGHER_ACCESS_REQUIRED);
1447                 cprintf("(except in %s> to sysop)\n", MAILROOM);
1448                 return;
1449         }
1450         if ((CC->usersupp.axlevel < 4) && (CC->quickroom.QRflags & QR_NETWORK)) {
1451                 cprintf("%d Need net privileges to enter here.\n",
1452                         ERROR + HIGHER_ACCESS_REQUIRED);
1453                 return;
1454         }
1455         if ((CC->usersupp.axlevel < 6) && (CC->quickroom.QRflags & QR_READONLY)) {
1456                 cprintf("%d Sorry, this is a read-only room.\n",
1457                         ERROR + HIGHER_ACCESS_REQUIRED);
1458                 return;
1459         }
1460         mtsflag = 0;
1461
1462
1463         if (post == 2) {
1464                 if (CC->usersupp.axlevel < 6) {
1465                         cprintf("%d You don't have permission to masquerade.\n",
1466                                 ERROR + HIGHER_ACCESS_REQUIRED);
1467                         return;
1468                 }
1469                 extract(newusername, entargs, 4);
1470                 memset(CC->fake_postname, 0, 32);
1471                 strcpy(CC->fake_postname, newusername);
1472                 cprintf("%d Ok\n", OK);
1473                 return;
1474         }
1475         CC->cs_flags |= CS_POSTING;
1476
1477         buf[0] = 0;
1478         if (CC->quickroom.QRflags & QR_MAILBOX) {
1479                 if (CC->usersupp.axlevel >= 2) {
1480                         strcpy(buf, recipient);
1481                 } else
1482                         strcpy(buf, "sysop");
1483                 e = alias(buf); /* alias and mail type */
1484                 if ((buf[0] == 0) || (e == MES_ERROR)) {
1485                         cprintf("%d Unknown address - cannot send message.\n",
1486                                 ERROR + NO_SUCH_USER);
1487                         return;
1488                 }
1489                 if ((e != MES_LOCAL) && (CC->usersupp.axlevel < 4)) {
1490                         cprintf("%d Net privileges required for network mail.\n",
1491                                 ERROR + HIGHER_ACCESS_REQUIRED);
1492                         return;
1493                 }
1494                 if ((RESTRICT_INTERNET == 1) && (e == MES_INTERNET)
1495                     && ((CC->usersupp.flags & US_INTERNET) == 0)
1496                     && (!CC->internal_pgm)) {
1497                         cprintf("%d You don't have access to Internet mail.\n",
1498                                 ERROR + HIGHER_ACCESS_REQUIRED);
1499                         return;
1500                 }
1501                 if (!strcasecmp(buf, "sysop")) {
1502                         mtsflag = 1;
1503                         goto SKFALL;
1504                 }
1505                 if (e != MES_LOCAL)
1506                         goto SKFALL;    /* don't search local file  */
1507                 if (!strcasecmp(buf, CC->usersupp.fullname)) {
1508                         cprintf("%d Can't send mail to yourself!\n",
1509                                 ERROR + NO_SUCH_USER);
1510                         return;
1511                 }
1512                 /* Check to make sure the user exists; also get the correct
1513                  * upper/lower casing of the name. 
1514                  */
1515                 a = getuser(&tempUS, buf);
1516                 if (a != 0) {
1517                         cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1518                         return;
1519                 }
1520                 strcpy(buf, tempUS.fullname);
1521         }
1522
1523 SKFALL: b = MES_NORMAL;
1524         if (CC->quickroom.QRflags & QR_ANONONLY)
1525                 b = MES_ANON;
1526         if (CC->quickroom.QRflags & QR_ANONOPT) {
1527                 if (anon_flag == 1)
1528                         b = MES_AN2;
1529         }
1530         if ((CC->quickroom.QRflags & QR_MAILBOX) == 0)
1531                 buf[0] = 0;
1532
1533         /* If we're only checking the validity of the request, return
1534          * success without creating the message.
1535          */
1536         if (post == 0) {
1537                 cprintf("%d %s\n", OK, buf);
1538                 return;
1539         }
1540
1541         cprintf("%d send message\n", SEND_LISTING);
1542
1543         /* Read in the message from the client. */
1544         if (CC->fake_postname[0])
1545                 msg = make_message(&CC->usersupp, buf,
1546                         CC->quickroom.QRname, b, e, format_type,
1547                         CC->fake_postname);
1548         else if (CC->fake_username[0])
1549                 msg = make_message(&CC->usersupp, buf,
1550                         CC->quickroom.QRname, b, e, format_type,
1551                         CC->fake_username);
1552         else
1553                 msg = make_message(&CC->usersupp, buf,
1554                         CC->quickroom.QRname, b, e, format_type, "");
1555
1556         if (msg != NULL)
1557                 CtdlSaveMsg(msg, buf, (mtsflag ? AIDEROOM : ""), e, 1);
1558                 CtdlFreeMessage(msg);
1559         CC->fake_postname[0] = '\0';
1560         return;
1561 }
1562
1563
1564
1565 /* 
1566  * message entry - mode 3 (raw)
1567  */
1568 void cmd_ent3(char *entargs)
1569 {
1570         char recp[256];
1571         char buf[256];
1572         int a;
1573         int e = 0;
1574         struct usersupp tempUS;
1575         long msglen;
1576         long bloklen;
1577         FILE *fp;
1578
1579         if (CC->internal_pgm == 0) {
1580                 cprintf("%d This command is for internal programs only.\n",
1581                         ERROR);
1582                 return;
1583         }
1584
1585         /* See if there's a recipient, but make sure it's a real one */
1586         extract(recp, entargs, 1);
1587         for (a = 0; a < strlen(recp); ++a)
1588                 if (!isprint(recp[a]))
1589                         strcpy(&recp[a], &recp[a + 1]);
1590         while (isspace(recp[0]))
1591                 strcpy(recp, &recp[1]);
1592         while (isspace(recp[strlen(recp) - 1]))
1593                 recp[strlen(recp) - 1] = 0;
1594
1595         /* If we're in Mail, check the recipient */
1596         if (strlen(recp) > 0) {
1597                 e = alias(recp);        /* alias and mail type */
1598                 if ((recp[0] == 0) || (e == MES_ERROR)) {
1599                         cprintf("%d Unknown address - cannot send message.\n",
1600                                 ERROR + NO_SUCH_USER);
1601                         return;
1602                 }
1603                 if (e == MES_LOCAL) {
1604                         a = getuser(&tempUS, recp);
1605                         if (a != 0) {
1606                                 cprintf("%d No such user.\n",
1607                                         ERROR + NO_SUCH_USER);
1608                                 return;
1609                         }
1610                 }
1611         }
1612         /* At this point, message has been approved. */
1613         if (extract_int(entargs, 0) == 0) {
1614                 cprintf("%d OK to send\n", OK);
1615                 return;
1616         }
1617         /* open a temp file to hold the message */
1618         fp = fopen(CC->temp, "wb");
1619         if (fp == NULL) {
1620                 cprintf("%d Cannot open %s: %s\n",
1621                         ERROR + INTERNAL_ERROR,
1622                         CC->temp, strerror(errno));
1623                 return;
1624         }
1625         msglen = extract_long(entargs, 2);
1626         cprintf("%d %ld\n", SEND_BINARY, msglen);
1627         while (msglen > 0L) {
1628                 bloklen = ((msglen >= 255L) ? 255 : msglen);
1629                 client_read(buf, (int) bloklen);
1630                 fwrite(buf, (int) bloklen, 1, fp);
1631                 msglen = msglen - bloklen;
1632         }
1633         fclose(fp);
1634
1635         save_message(CC->temp, recp, "", e, 0);
1636 }
1637
1638
1639 /*
1640  * API function to delete messages which match a set of criteria
1641  * (returns the actual number of messages deleted)
1642  * FIX ... still need to implement delete by content type
1643  */
1644 int CtdlDeleteMessages(char *room_name,         /* which room */
1645                        long dmsgnum,            /* or "0" for any */
1646                        char *content_type       /* or NULL for any */
1647 )
1648 {
1649
1650         struct quickroom qrbuf;
1651         struct cdbdata *cdbfr;
1652         long *msglist = NULL;
1653         int num_msgs = 0;
1654         int i;
1655         int num_deleted = 0;
1656         int delete_this;
1657         struct SuppMsgInfo smi;
1658
1659         lprintf(9, "CtdlDeleteMessages(%s, %ld, %s)\n",
1660                 room_name, dmsgnum, content_type);
1661
1662         /* get room record, obtaining a lock... */
1663         if (lgetroom(&qrbuf, room_name) != 0) {
1664                 lprintf(7, "CtdlDeleteMessages(): Room <%s> not found\n",
1665                         room_name);
1666                 return (0);     /* room not found */
1667         }
1668         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long));
1669
1670         if (cdbfr != NULL) {
1671                 msglist = mallok(cdbfr->len);
1672                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
1673                 num_msgs = cdbfr->len / sizeof(long);
1674                 cdb_free(cdbfr);
1675         }
1676         if (num_msgs > 0) {
1677                 for (i = 0; i < num_msgs; ++i) {
1678                         delete_this = 0x00;
1679
1680                         /* Set/clear a bit for each criterion */
1681
1682                         if ((dmsgnum == 0L) || (msglist[i] == dmsgnum)) {
1683                                 delete_this |= 0x01;
1684                         }
1685                         if (content_type == NULL) {
1686                                 delete_this |= 0x02;
1687                         } else {
1688                                 GetSuppMsgInfo(&smi, msglist[i]);
1689                                 if (!strcasecmp(smi.smi_content_type,
1690                                                 content_type)) {
1691                                         delete_this |= 0x02;
1692                                 }
1693                         }
1694
1695                         /* Delete message only if all bits are set */
1696                         if (delete_this == 0x03) {
1697                                 AdjRefCount(msglist[i], -1);
1698                                 msglist[i] = 0L;
1699                                 ++num_deleted;
1700                         }
1701                 }
1702
1703                 num_msgs = sort_msglist(msglist, num_msgs);
1704                 cdb_store(CDB_MSGLISTS, &qrbuf.QRnumber, sizeof(long),
1705                           msglist, (num_msgs * sizeof(long)));
1706
1707                 qrbuf.QRhighest = msglist[num_msgs - 1];
1708                 phree(msglist);
1709         }
1710         lputroom(&qrbuf);
1711         lprintf(9, "%d message(s) deleted.\n", num_deleted);
1712         return (num_deleted);
1713 }
1714
1715
1716
1717 /*
1718  * Delete message from current room
1719  */
1720 void cmd_dele(char *delstr)
1721 {
1722         long delnum;
1723         int num_deleted;
1724
1725         getuser(&CC->usersupp, CC->curr_user);
1726         if ((CC->usersupp.axlevel < 6)
1727             && (CC->usersupp.usernum != CC->quickroom.QRroomaide)
1728             && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)) {
1729                 cprintf("%d Higher access required.\n",
1730                         ERROR + HIGHER_ACCESS_REQUIRED);
1731                 return;
1732         }
1733         delnum = extract_long(delstr, 0);
1734
1735         num_deleted = CtdlDeleteMessages(CC->quickroom.QRname, delnum, NULL);
1736
1737         if (num_deleted) {
1738                 cprintf("%d %d message%s deleted.\n", OK,
1739                         num_deleted, ((num_deleted != 1) ? "s" : ""));
1740         } else {
1741                 cprintf("%d Message %ld not found.\n", ERROR, delnum);
1742         }
1743 }
1744
1745
1746 /*
1747  * move a message to another room
1748  */
1749 void cmd_move(char *args)
1750 {
1751         long num;
1752         char targ[32];
1753         struct quickroom qtemp;
1754         int foundit;
1755
1756         num = extract_long(args, 0);
1757         extract(targ, args, 1);
1758
1759         getuser(&CC->usersupp, CC->curr_user);
1760         if ((CC->usersupp.axlevel < 6)
1761             && (CC->usersupp.usernum != CC->quickroom.QRroomaide)) {
1762                 cprintf("%d Higher access required.\n",
1763                         ERROR + HIGHER_ACCESS_REQUIRED);
1764                 return;
1765         }
1766         if (getroom(&qtemp, targ) != 0) {
1767                 cprintf("%d '%s' does not exist.\n", ERROR, targ);
1768                 return;
1769         }
1770         /* Bump the reference count, otherwise the message will be deleted
1771          * from disk when we remove it from the source room.
1772          */
1773         AdjRefCount(num, 1);
1774
1775         /* yank the message out of the current room... */
1776         foundit = CtdlDeleteMessages(CC->quickroom.QRname, num, NULL);
1777
1778         if (foundit) {
1779                 /* put the message into the target room */
1780                 lgetroom(&qtemp, targ);
1781                 qtemp.QRhighest = AddMessageToRoom(&qtemp, num);
1782                 lputroom(&qtemp);
1783                 cprintf("%d Message moved.\n", OK);
1784         } else {
1785                 AdjRefCount(num, (-1));         /* oops */
1786                 cprintf("%d msg %ld does not exist.\n", ERROR, num);
1787         }
1788 }
1789
1790
1791
1792 /*
1793  * GetSuppMsgInfo()  -  Get the supplementary record for a message
1794  */
1795 void GetSuppMsgInfo(struct SuppMsgInfo *smibuf, long msgnum)
1796 {
1797
1798         struct cdbdata *cdbsmi;
1799         long TheIndex;
1800
1801         memset(smibuf, 0, sizeof(struct SuppMsgInfo));
1802         smibuf->smi_msgnum = msgnum;
1803         smibuf->smi_refcount = 1;       /* Default reference count is 1 */
1804
1805         /* Use the negative of the message number for its supp record index */
1806         TheIndex = (0L - msgnum);
1807
1808         cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
1809         if (cdbsmi == NULL) {
1810                 return;         /* record not found; go with defaults */
1811         }
1812         memcpy(smibuf, cdbsmi->ptr,
1813                ((cdbsmi->len > sizeof(struct SuppMsgInfo)) ?
1814                 sizeof(struct SuppMsgInfo) : cdbsmi->len));
1815         cdb_free(cdbsmi);
1816         return;
1817 }
1818
1819
1820 /*
1821  * PutSuppMsgInfo()  -  (re)write supplementary record for a message
1822  */
1823 void PutSuppMsgInfo(struct SuppMsgInfo *smibuf)
1824 {
1825         long TheIndex;
1826
1827         /* Use the negative of the message number for its supp record index */
1828         TheIndex = (0L - smibuf->smi_msgnum);
1829
1830         lprintf(9, "PuttSuppMsgInfo(%ld) - ref count is %d\n",
1831                 smibuf->smi_msgnum, smibuf->smi_refcount);
1832
1833         cdb_store(CDB_MSGMAIN,
1834                   &TheIndex, sizeof(long),
1835                   smibuf, sizeof(struct SuppMsgInfo));
1836
1837 }                               /*
1838
1839                                  * AdjRefCount  -  change the reference count for a message;
1840                                  *                 delete the message if it reaches zero
1841                                  */ void AdjRefCount(long msgnum, int incr)
1842 {
1843
1844         struct SuppMsgInfo smi;
1845         long delnum;
1846
1847         /* This is a *tight* critical section; please keep it that way, as
1848          * it may get called while nested in other critical sections.  
1849          * Complicating this any further will surely cause deadlock!
1850          */
1851         begin_critical_section(S_SUPPMSGMAIN);
1852         GetSuppMsgInfo(&smi, msgnum);
1853         smi.smi_refcount += incr;
1854         PutSuppMsgInfo(&smi);
1855         end_critical_section(S_SUPPMSGMAIN);
1856
1857         lprintf(9, "Ref count for message <%ld> after write is <%d>\n",
1858                 msgnum, smi.smi_refcount);
1859
1860         /* If the reference count is now zero, delete the message
1861          * (and its supplementary record as well).
1862          */
1863         if (smi.smi_refcount == 0) {
1864                 lprintf(9, "Deleting message <%ld>\n", msgnum);
1865                 delnum = msgnum;
1866                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
1867                 delnum = (0L - msgnum);
1868                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
1869         }
1870 }
1871
1872 /*
1873  * Write a generic object to this room
1874  */
1875 void CtdlWriteObject(char *req_room,            /* Room to stuff it in */
1876                         char *content_type,     /* MIME type of this object */
1877                         char *tempfilename,     /* Where to fetch it from */
1878                         int is_mailbox,         /* Private mailbox room? */
1879                         int is_binary,          /* Is encoding necessary? */
1880                         int is_unique   /* Del others of this type? */
1881                         )
1882 {
1883
1884         FILE *fp, *tempfp;
1885         char filename[PATH_MAX];
1886         char cmdbuf[256];
1887         int ch;
1888         struct quickroom qrbuf;
1889         char roomname[ROOMNAMELEN];
1890
1891         if (is_mailbox)
1892                 MailboxName(roomname, &CC->usersupp, req_room);
1893         else
1894                 safestrncpy(roomname, req_room, sizeof(roomname));
1895
1896         strcpy(filename, tmpnam(NULL));
1897         fp = fopen(filename, "w");
1898         if (fp == NULL)
1899                 return;
1900
1901         fprintf(fp, "%c%c%c", 0xFF, MES_NORMAL, 4);
1902         fprintf(fp, "T%ld%c", time(NULL), 0);
1903         fprintf(fp, "A%s%c", CC->usersupp.fullname, 0);
1904         fprintf(fp, "O%s%c", roomname, 0);
1905         fprintf(fp, "N%s%c", config.c_nodename, 0);
1906         fprintf(fp, "MContent-type: %s\n", content_type);
1907
1908         tempfp = fopen(tempfilename, "r");
1909         if (tempfp == NULL) {
1910                 fclose(fp);
1911                 unlink(filename);
1912                 return;
1913         }
1914         if (is_binary == 0) {
1915                 fprintf(fp, "Content-transfer-encoding: 7bit\n\n");
1916                 while (ch = getc(tempfp), ch > 0)
1917                         putc(ch, fp);
1918                 fclose(tempfp);
1919                 putc(0, fp);
1920                 fclose(fp);
1921         } else {
1922                 fprintf(fp, "Content-transfer-encoding: base64\n\n");
1923                 fclose(tempfp);
1924                 fclose(fp);
1925                 sprintf(cmdbuf, "./base64 -e <%s >>%s",
1926                         tempfilename, filename);
1927                 system(cmdbuf);
1928         }
1929
1930         /* Create the requested room if we have to. */
1931         if (getroom(&qrbuf, roomname) != 0) {
1932                 create_room(roomname, 4, "", 0);
1933         }
1934         /* If the caller specified this object as unique, delete all
1935          * other objects of this type that are currently in the room.
1936          */
1937         if (is_unique) {
1938                 lprintf(9, "Deleted %d other msgs of this type\n",
1939                         CtdlDeleteMessages(roomname, 0L, content_type));
1940         }
1941         /* Now write the data */
1942         save_message(filename, "", roomname, MES_LOCAL, 1);
1943 }