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