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