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