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