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