more fixes to msgbase.c for delivery of network mail
[citadel.git] / citadel / msgbase.c
1 /* $Id$ */
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <stdio.h>
5 #include <fcntl.h>
6 #include <time.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <syslog.h>
10 #include <pthread.h>
11 #include "citadel.h"
12 #include "server.h"
13 #include <errno.h>
14 #include <sys/stat.h>
15 #include "database.h"
16 #include "msgbase.h"
17 #include "support.h"
18 #include "sysdep_decls.h"
19 #include "room_ops.h"
20 #include "user_ops.h"
21 #include "control.h"
22 #include "dynloader.h"
23
24 #define MSGS_ALL        0
25 #define MSGS_OLD        1
26 #define MSGS_NEW        2
27 #define MSGS_FIRST      3
28 #define MSGS_LAST       4
29 #define MSGS_GT         5
30
31 extern struct config config;
32
33
34 /*
35  * Aliasing for network mail.
36  * (Error messages have been commented out, because this is a server.)
37  */
38 int alias(char *name)           /* process alias and routing info for mail */
39              {
40         FILE *fp;
41         int a,b;
42         char aaa[300],bbb[300];
43
44         lprintf(9, "alias() called for <%s>\n", name);
45         
46         fp=fopen("network/mail.aliases","r");
47         if (fp==NULL) fp=fopen("/dev/null","r");
48         if (fp==NULL) return(M_ERROR);
49 GNA:    strcpy(aaa,""); strcpy(bbb,"");
50         do {
51                 a=getc(fp);
52                 if (a==',') a=0;
53                 if (a>0) {
54                         b=strlen(aaa);
55                         aaa[b]=a;
56                         aaa[b+1]=0;
57                         }
58                 } while(a>0);
59         do {
60                 a=getc(fp);
61                 if (a==10) a=0;
62                 if (a>0) {
63                         b=strlen(bbb);
64                         bbb[b]=a;
65                         bbb[b+1]=0;
66                         }
67                 } while(a>0);
68         if (a<0) {
69                 fclose(fp);
70                 goto DETYPE;
71                 }
72         if (strcasecmp(name,aaa)) goto GNA;
73         fclose(fp);
74         strcpy(name,bbb);
75         lprintf(7, "Mail is being forwarded to %s\n", name);
76
77 DETYPE: /* determine local or remote type, see citadel.h */
78         for (a=0; a<strlen(name); ++a) if (name[a]=='!') return(M_INTERNET);
79         for (a=0; a<strlen(name); ++a)
80                 if (name[a]=='@')
81                         for (b=a; b<strlen(name); ++b)
82                                 if (name[b]=='.') return(M_INTERNET);
83         b=0; for (a=0; a<strlen(name); ++a) if (name[a]=='@') ++b;
84         if (b>1) {
85                 lprintf(7, "Too many @'s in address\n");
86                 return(M_ERROR);
87                 }
88         if (b==1) {
89                 for (a=0; a<strlen(name); ++a)
90                         if (name[a]=='@') strcpy(bbb,&name[a+1]);
91                 while (bbb[0]==32) strcpy(bbb,&bbb[1]);
92                 fp = fopen("network/mail.sysinfo","r");
93                 if (fp==NULL) return(M_ERROR);
94 GETSN:          do {
95                         a=getstring(fp,aaa);
96                         } while ((a>=0)&&(strcasecmp(aaa,bbb)));
97                 a=getstring(fp,aaa);
98                 if (!strncmp(aaa,"use ",4)) {
99                         strcpy(bbb,&aaa[4]);
100                         fseek(fp,0L,0);
101                         goto GETSN;
102                         }
103                 fclose(fp);
104                 if (!strncmp(aaa,"uum",3)) {
105                         strcpy(bbb,name);
106                         for (a=0; a<strlen(bbb); ++a) {
107                                 if (bbb[a]=='@') bbb[a]=0;
108                                 if (bbb[a]==' ') bbb[a]='_';
109                                 }
110                         while(bbb[strlen(bbb)-1]=='_') bbb[strlen(bbb)-1]=0;
111                         sprintf(name,&aaa[4],bbb);
112                         return(M_INTERNET);
113                         }
114                 if (!strncmp(aaa,"bin",3)) {
115                         strcpy(aaa,name); strcpy(bbb,name);
116                         while (aaa[strlen(aaa)-1]!='@') aaa[strlen(aaa)-1]=0;
117                         aaa[strlen(aaa)-1]=0;
118                         while (aaa[strlen(aaa)-1]==' ') aaa[strlen(aaa)-1]=0;
119                         while (bbb[0]!='@') strcpy(bbb,&bbb[1]);
120                         strcpy(bbb,&bbb[1]);
121                         while (bbb[0]==' ') strcpy(bbb,&bbb[1]);
122                         sprintf(name,"%s @%s",aaa,bbb);
123                         return(M_BINARY);
124                         }
125                 return(M_ERROR);
126                 }
127         return(M_LOCAL);
128         }
129
130
131 void get_mm(void) {
132         FILE *fp;
133
134         fp=fopen("citadel.control","r");
135         fread((char *)&CitControl,sizeof(struct CitControl),1,fp);
136         fclose(fp);
137         }
138
139 /*
140  * cmd_msgs()  -  get list of message #'s in this room
141  */
142 void cmd_msgs(char *cmdbuf)
143 {
144         int a = 0;
145         int mode = 0;
146         char which[256];
147         int cm_howmany = 0;
148         long cm_gt = 0L;
149         struct visit vbuf;
150
151         extract(which,cmdbuf,0);
152
153         mode = MSGS_ALL;
154         strcat(which,"   ");
155         if (!strncasecmp(which,"OLD",3))        mode = MSGS_OLD;
156         if (!strncasecmp(which,"NEW",3))        mode = MSGS_NEW;
157         if (!strncasecmp(which,"FIRST",5))      {
158                 mode = MSGS_FIRST;
159                 cm_howmany = extract_int(cmdbuf,1);
160                 }
161         if (!strncasecmp(which,"LAST",4))       {
162                 mode = MSGS_LAST;
163                 cm_howmany = extract_int(cmdbuf,1);
164                 }
165         if (!strncasecmp(which,"GT",2)) {
166                 mode = MSGS_GT;
167                 cm_gt = extract_long(cmdbuf,1);
168                 }
169
170         if ((!(CC->logged_in))&&(!(CC->internal_pgm))) {
171                 cprintf("%d not logged in\n",ERROR+NOT_LOGGED_IN);
172                 return;
173                 }
174         get_mm();
175         get_msglist(&CC->quickroom);
176         getuser(&CC->usersupp,CC->curr_user);
177         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
178
179         cprintf("%d Message list...\n",LISTING_FOLLOWS);
180         if (CC->num_msgs != 0) {
181            for (a=0; a<(CC->num_msgs); ++a) 
182                if ((MessageFromList(a) >=0)
183                && ( 
184
185 (mode==MSGS_ALL)
186 || ((mode==MSGS_OLD) && (MessageFromList(a) <= vbuf.v_lastseen))
187 || ((mode==MSGS_NEW) && (MessageFromList(a) > vbuf.v_lastseen))
188 || ((mode==MSGS_NEW) && (MessageFromList(a) >= vbuf.v_lastseen)
189                      && (CC->usersupp.flags & US_LASTOLD))
190 || ((mode==MSGS_LAST)&& (a>=(CC->num_msgs-cm_howmany)))
191 || ((mode==MSGS_FIRST)&&(a<cm_howmany))
192 || ((mode==MSGS_GT) && (MessageFromList(a) > cm_gt))
193
194                         )
195                 ) {
196                         cprintf("%ld\n", MessageFromList(a));
197                         }
198            }
199         cprintf("000\n");
200         }
201
202
203
204 /* 
205  * help_subst()  -  support routine for help file viewer
206  */
207 void help_subst(char *strbuf, char *source, char *dest)
208 {
209         char workbuf[256];
210         int p;
211
212         while (p=pattern2(strbuf,source), (p>=0)) {
213                 strcpy(workbuf,&strbuf[p+strlen(source)]);
214                 strcpy(&strbuf[p],dest);
215                 strcat(strbuf,workbuf);
216                 }
217         }
218
219
220 void do_help_subst(char *buffer)
221 {
222         char buf2[16];
223
224         help_subst(buffer,"^nodename",config.c_nodename);
225         help_subst(buffer,"^humannode",config.c_humannode);
226         help_subst(buffer,"^fqdn",config.c_fqdn);
227         help_subst(buffer,"^username",CC->usersupp.fullname);
228         sprintf(buf2,"%ld",CC->usersupp.usernum);
229         help_subst(buffer,"^usernum",buf2);
230         help_subst(buffer,"^sysadm",config.c_sysadm);
231         help_subst(buffer,"^variantname",CITADEL);
232         sprintf(buf2,"%d",config.c_maxsessions);
233         help_subst(buffer,"^maxsessions",buf2);
234         }
235
236
237
238 /*
239  * memfmout()  -  Citadel text formatter and paginator.
240  *             Although the original purpose of this routine was to format
241  *             text to the reader's screen width, all we're really using it
242  *             for here is to format text out to 80 columns before sending it
243  *             to the client.  The client software may reformat it again.
244  */
245 void memfmout(int width, char *mptr, char subst)
246                         /* screen width to use */
247                         /* where are we going to get our text from? */
248                         /* nonzero if we should use hypertext mode */
249         {
250         int a,b,c;
251         int real = 0;
252         int old = 0;
253         CIT_UBYTE ch;
254         char aaa[140];
255         char buffer[256];
256         
257         strcpy(aaa,""); old=255;
258         strcpy(buffer,"");
259         c=1; /* c is the current pos */
260
261 FMTA:   if (subst) {
262                 while (ch=*mptr, ((ch!=0) && (strlen(buffer)<126) )) {
263                         ch=*mptr++;
264                         buffer[strlen(buffer)+1] = 0;
265                         buffer[strlen(buffer)] = ch;
266                         }
267
268                 if (buffer[0]=='^') do_help_subst(buffer);
269
270                 buffer[strlen(buffer)+1] = 0;
271                 a=buffer[0];
272                 strcpy(buffer,&buffer[1]);
273                 }
274         
275         else ch=*mptr++;
276
277         old=real;
278         real=ch;
279         if (ch<=0) goto FMTEND;
280         
281         if ( ((ch==13)||(ch==10)) && (old!=13) && (old!=10) ) ch=32;
282         if ( ((old==13)||(old==10)) && (isspace(real)) ) {
283                 cprintf("\n");
284                 c=1;
285                 }
286         if (ch>126) goto FMTA;
287
288         if (ch>32) {
289         if ( ((strlen(aaa)+c)>(width-5)) && (strlen(aaa)>(width-5)) )
290                 { cprintf("\n%s",aaa); c=strlen(aaa); aaa[0]=0;
291                 }
292          b=strlen(aaa); aaa[b]=ch; aaa[b+1]=0; }
293         if (ch==32) {
294                 if ((strlen(aaa)+c)>(width-5)) { 
295                         cprintf("\n");
296                         c=1;
297                         }
298                 cprintf("%s ",aaa); ++c; c=c+strlen(aaa);
299                 strcpy(aaa,"");
300                 goto FMTA;
301                 }
302         if ((ch==13)||(ch==10)) {
303                 cprintf("%s\n",aaa);
304                 c=1;
305                 strcpy(aaa,"");
306                 goto FMTA;
307                 }
308         goto FMTA;
309
310 FMTEND: cprintf("\n");
311         }
312
313
314 /*
315  * Get a message off disk.  (return value is the message's timestamp)
316  * 
317  */
318 time_t output_message(char *msgid, int mode,
319                         int headers_only, int desired_section) {
320         long msg_num;
321         int a;
322         CIT_UBYTE ch, rch;
323         CIT_UBYTE format_type,anon_flag;
324         char buf[1024];
325         long msg_len;
326         int msg_ok = 0;
327         char boundary[256];             /* attachment boundary */
328         char current_section = 0;       /* section currently being parsed */
329         int has_attachments = 0;
330
331         struct cdbdata *dmsgtext;
332         char *mptr;
333
334         /* buffers needed for RFC822 translation */
335         char suser[256];
336         char luser[256];
337         char snode[256];
338         char lnode[256];
339         char mid[256];
340         time_t xtime = 0L;
341         /* */
342
343         strcpy(boundary, "");
344         msg_num = atol(msgid);
345
346
347         if ((!(CC->logged_in))&&(!(CC->internal_pgm))&&(mode!=MT_DATE)) {
348                 cprintf("%d Not logged in.\n",ERROR+NOT_LOGGED_IN);
349                 return(xtime);
350                 }
351
352         /* We used to need to check in the current room's message list
353          * to determine where the message's disk position.  We no longer need
354          * to do this, but we do it anyway as a security measure, in order to
355          * prevent rogue clients from reading messages not in the current room.
356          */
357
358         msg_ok = 0;
359         if (CC->num_msgs > 0) {
360                 for (a=0; a<CC->num_msgs; ++a) {
361                         if (MessageFromList(a) == msg_num) {
362                                 msg_ok = 1;
363                                 }
364                         }
365                 }
366
367         if (!msg_ok) {
368                 if (mode != MT_DATE)
369                         cprintf("%d Message %ld is not in this room.\n",
370                                 ERROR, msg_num);
371                 return(xtime);
372                 }
373         
374
375         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msg_num, sizeof(long));
376         
377         if (dmsgtext == NULL) {
378                 if (mode != MT_DATE)
379                         cprintf("%d Can't find message %ld\n",
380                                 ERROR+INTERNAL_ERROR);
381                 return(xtime);
382                 }
383
384         msg_len = (long) dmsgtext->len;
385         mptr = dmsgtext->ptr;
386
387         /* this loop spews out the whole message if we're doing raw format */
388         if (mode == MT_RAW) {
389                 cprintf("%d %ld\n", BINARY_FOLLOWS, msg_len);
390                 client_write(dmsgtext->ptr, (int) msg_len);
391                 cdb_free(dmsgtext);
392                 return(xtime);
393                 }
394
395         /* Otherwise, we'll start parsing it field by field... */
396         ch = *mptr++;
397         if (ch != 255) {
398                 cprintf("%d Illegal message format on disk\n",
399                         ERROR+INTERNAL_ERROR);
400                 cdb_free(dmsgtext);
401                 return(xtime);
402                 }
403
404         anon_flag = *mptr++;
405         format_type = *mptr++;
406
407         /* Are we just looking for the message date? */
408         if (mode == MT_DATE) while(ch = *mptr++, (ch!='M' && ch!=0)) {
409                 buf[0] = 0;
410                 do {
411                         buf[strlen(buf)+1] = 0;
412                         rch = *mptr++;
413                         buf[strlen(buf)] = rch;
414                         } while (rch > 0);
415
416                 if (ch=='T') {
417                         xtime = atol(buf);
418                         cdb_free(dmsgtext);
419                         return(xtime);
420                         }
421                 }
422
423
424         /* now for the user-mode message reading loops */
425         cprintf("%d Message %ld:\n",LISTING_FOLLOWS,msg_num);
426
427         if (mode == MT_CITADEL) cprintf("type=%d\n",format_type);
428
429         if ( (anon_flag == MES_ANON) && (mode == MT_CITADEL) ) {
430                 cprintf("nhdr=yes\n");
431                 }
432
433         /* begin header processing loop for Citadel message format */
434
435         if (mode == MT_CITADEL) while(ch = *mptr++, (ch!='M' && ch!=0)) {
436                 buf[0] = 0;
437                 do {
438                         buf[strlen(buf)+1] = 0;
439                         rch = *mptr++;
440                         buf[strlen(buf)] = rch;
441                         } while (rch > 0);
442
443                 if (ch=='A') {
444                         PerformUserHooks(buf, (-1L), EVT_OUTPUTMSG);
445                         if (anon_flag==MES_ANON) cprintf("from=****");
446                         else if (anon_flag==MES_AN2) cprintf("from=anonymous");
447                         else cprintf("from=%s",buf);
448                         if ((is_room_aide()) && ((anon_flag == MES_ANON)
449                            || (anon_flag == MES_AN2)))
450                                 cprintf(" [%s]",buf);
451                         cprintf("\n");
452                         }
453                 else if (ch=='Z') {
454                         has_attachments = 1;
455                         sprintf(boundary, "--%s", buf);
456                         }
457                 else if (ch=='P') cprintf("path=%s\n",buf);
458                 else if (ch=='U') cprintf("subj=%s\n",buf);
459                 else if (ch=='I') cprintf("msgn=%s\n",buf);
460                 else if (ch=='H') cprintf("hnod=%s\n",buf);
461                 else if (ch=='O') cprintf("room=%s\n",buf);
462                 else if (ch=='N') cprintf("node=%s\n",buf);
463                 else if (ch=='R') cprintf("rcpt=%s\n",buf);
464                 else if (ch=='T') cprintf("time=%s\n",buf);
465                 /* else cprintf("fld%c=%s\n",ch,buf); */
466                 }
467
468         /* begin header processing loop for RFC822 transfer format */
469
470         strcpy(suser, "");
471         strcpy(luser, "");
472         strcpy(snode, NODENAME);
473         strcpy(lnode, HUMANNODE);
474         if (mode == MT_RFC822) while(ch = *mptr++, (ch!='M' && ch!=0)) {
475                 buf[0] = 0;
476                 do {
477                         buf[strlen(buf)+1] = 0;
478                         rch = *mptr++;
479                         buf[strlen(buf)] = rch;
480                         } while (rch > 0);
481
482                 if (ch=='A') strcpy(luser, buf);
483                 else if (ch=='P') {
484                         cprintf("Path: %s\n",buf);
485                         for (a=0; a<strlen(buf); ++a) {
486                                 if (buf[a] == '!') {
487                                         strcpy(buf,&buf[a+1]);
488                                         a=0;
489                                         }
490                                 }
491                         strcpy(suser, buf);
492                         }
493                 else if (ch=='U') cprintf("Subject: %s\n",buf);
494                 else if (ch=='I') strcpy(mid, buf);
495                 else if (ch=='H') strcpy(lnode, buf);
496                 else if (ch=='O') cprintf("X-Citadel-Room: %s\n",buf);
497                 else if (ch=='N') strcpy(snode, buf);
498                 else if (ch=='R') cprintf("To: %s\n",buf);
499                 else if (ch=='T')  {
500                         xtime = atol(buf);
501                         cprintf("Date: %s", asctime(localtime(&xtime)));
502                         }
503                 }
504
505         if (mode == MT_RFC822) {
506                 if (!strcasecmp(snode, NODENAME)) {
507                         strcpy(snode, FQDN);
508                         }
509                 cprintf("Message-ID: <%s@%s>\n", mid, snode);
510                 PerformUserHooks(luser, (-1L), EVT_OUTPUTMSG);
511                 cprintf("From: %s@%s (%s)\n",
512                         suser, snode, luser);
513                 cprintf("Organization: %s\n", lnode);
514                 }
515
516         /* end header processing loop ... at this point, we're in the text */
517
518         if (ch==0) {
519                 cprintf("text\n*** ?Message truncated\n000\n");
520                 cdb_free(dmsgtext);
521                 return(xtime);
522                 }
523
524         if (headers_only) {
525                 /* give 'em a length */
526                 msg_len = 0L;
527                 while(ch = *mptr++, ch>0) {
528                         ++msg_len;
529                         }
530                 cprintf("mlen=%ld\n", msg_len);
531                 cprintf("000\n");
532                 cdb_free(dmsgtext);
533                 return(xtime);
534                 }
535
536         /* signify start of msg text */
537         if (mode == MT_CITADEL) cprintf("text\n");
538         if (mode == MT_RFC822) cprintf("\n");
539
540         /* If the format type on disk is 1 (fixed-format), then we want
541          * everything to be output completely literally ... regardless of
542          * what message transfer format is in use.
543          */
544         if (format_type == 1) {
545                 strcpy(buf, "");
546                 while(ch = *mptr++, ch>0) {
547                         if (ch == 13) ch = 10;
548                         if ( (ch == 10) || (strlen(buf)>250) ) {
549                                 if (has_attachments) if (!strncmp(buf, boundary, strlen(boundary))) {
550                                         ++current_section;
551                                         }
552                                 if (current_section == desired_section) {
553                                         if ( (has_attachments == 0) || (strncmp(buf, boundary, strlen(boundary)))) {
554                                                 cprintf("%s\n", buf);
555                                                 }
556                                         }
557                                 strcpy(buf, "");
558                                 }
559                         else {
560                                 buf[strlen(buf)+1] = 0;
561                                 buf[strlen(buf)] = ch;
562                                 }
563                         }
564                 if (strlen(buf)>0) cprintf("%s\n", buf);
565                 }
566         /* If the message on disk is format 0 (Citadel vari-format), we
567          * output using the formatter at 80 columns.  This is the final output
568          * form if the transfer format is RFC822, but if the transfer format
569          * is Citadel proprietary, it'll still work, because the indentation
570          * for new paragraphs is correct and the client will reformat the
571          * message to the reader's screen width.
572          */
573         if (format_type == 0) {
574                 memfmout(80,mptr,0);
575                 }
576
577
578         /* now we're done */
579         cprintf("000\n");
580         cdb_free(dmsgtext);
581         return(xtime);
582         }
583
584
585 /*
586  * display a message (mode 0 - Citadel proprietary)
587  */
588 void cmd_msg0(char *cmdbuf)
589 {
590         char msgid[256];
591         int headers_only = 0;
592         int desired_section = 0;
593
594         extract(msgid,cmdbuf,0);
595         headers_only = extract_int(cmdbuf, 1);
596         desired_section = extract_int(cmdbuf, 2);
597
598         output_message(msgid,MT_CITADEL, headers_only, desired_section);
599         return;
600         }
601
602
603 /*
604  * display a message (mode 2 - RFC822)
605  */
606 void cmd_msg2(char *cmdbuf)
607 {
608         char msgid[256];
609         int headers_only = 0;
610
611         extract(msgid,cmdbuf,0);
612         headers_only = extract_int(cmdbuf,1);
613
614         output_message(msgid,MT_RFC822,headers_only,0);
615         }
616
617 /* 
618  * display a message (mode 3 - IGnet raw format - internal programs only)
619  */
620 void cmd_msg3(char *cmdbuf)
621 {
622         char msgid[256];
623         int headers_only = 0;
624
625         if (CC->internal_pgm == 0) {
626                 cprintf("%d This command is for internal programs only.\n",
627                         ERROR);
628                 return;
629                 }
630
631         extract(msgid,cmdbuf,0);
632         headers_only = extract_int(cmdbuf,1);
633
634         output_message(msgid,MT_RAW,headers_only,0);
635         }
636
637
638
639 /*
640  * Message base operation to send a message to the master file
641  * (returns new message number)
642  */
643 long send_message(char *message_in_memory,      /* pointer to buffer */
644                 size_t message_length,          /* length of buffer */
645                 int generate_id) {              /* 1 to generate an I field */
646
647         long newmsgid;
648
649         /* Get a new message number */
650         newmsgid = get_new_message_number();
651
652         /* Write our little bundle of joy into the message base */
653
654         begin_critical_section(S_MSGMAIN);
655         if ( cdb_store(CDB_MSGMAIN, &newmsgid, sizeof(long),
656                         message_in_memory, message_length) < 0 ) {
657                 lprintf(2, "Can't store message\n");
658                 end_critical_section(S_MSGMAIN);
659                 return 0L;
660                 }
661         end_critical_section(S_MSGMAIN);
662
663         /* Finally, return the pointers */
664         return(newmsgid);
665         }
666
667
668
669 /*
670  * this is a simple file copy routine.
671  */
672 void copy_file(char *from, char *to)
673 {
674         FILE *ffp,*tfp;
675         int a;
676
677         ffp=fopen(from,"r");
678         if (ffp==NULL) return;
679         tfp=fopen(to,"w");
680         if (tfp==NULL) {
681                 fclose(ffp);
682                 return;
683                 }
684         while (a=getc(ffp), a>=0) {
685                 putc(a,tfp);
686                 }
687         fclose(ffp);
688         fclose(tfp);
689         return;
690         }
691
692
693
694 /*
695  * message base operation to save a message and install its pointers
696  */
697 void save_message(char *mtmp,   /* file containing proper message */
698                 char *rec,      /* Recipient (if mail) */
699                 char mtsflag,   /* 0 for normal, 1 to force Aide> room */
700                 int mailtype,   /* local or remote type, see citadel.h */
701                 int generate_id) /* set to 1 to generate an 'I' field */
702 {
703         char aaa[100];
704         char hold_rm[ROOMNAMELEN];
705         char actual_rm[ROOMNAMELEN];
706         char recipient[256];
707         long newmsgid;
708         char *message_in_memory;
709         struct stat statbuf;
710         size_t templen;
711         FILE *fp;
712         struct usersupp userbuf;
713         int a;
714
715         lprintf(9, "save_message(%s,%s,%d,%d,%d)\n",
716                 mtmp, rec, mtsflag, mailtype, generate_id);
717
718         /* Strip non-printable characters out of the recipient name */
719         strcpy(recipient, rec);
720         for (a=0; a<strlen(recipient); ++a)
721                 if (!isprint(recipient[a]))
722                         strcpy(&recipient[a], &recipient[a+1]);
723
724         /* Measure the message */
725         stat(mtmp, &statbuf);
726         templen = statbuf.st_size;
727
728         /* Now read it into memory */
729         message_in_memory = (char *) malloc(templen);
730         if (message_in_memory == NULL) {
731                 lprintf(2, "Can't allocate memory to save message!\n");
732                 return;
733                 }
734
735         fp = fopen(mtmp, "rb");
736         fread(message_in_memory, templen, 1, fp);
737         fclose(fp);
738
739         newmsgid = send_message(message_in_memory, templen, generate_id);
740         free(message_in_memory);
741         if (newmsgid <= 0L) return;
742
743         strcpy(actual_rm, CC->quickroom.QRname);
744         strcpy(hold_rm, "");
745
746         /* If the user is a twit, move to the twit room for posting... */
747         if (TWITDETECT) if (CC->usersupp.axlevel==2) {
748                 strcpy(hold_rm, actual_rm);
749                 strcpy(actual_rm, config.c_twitroom);
750                 }
751
752         /* ...or if this is a private message, go to the target mailbox. */
753         if (strlen(recipient) > 0) {
754                 mailtype = alias(recipient);
755                 if (mailtype == M_LOCAL) {
756                         if (getuser(&userbuf, recipient)!=0) {
757                                 mtsflag = 1; /* User not found, goto Aide */
758                                 }
759                         else {
760                                 strcpy(hold_rm, actual_rm);
761                                 MailboxName(actual_rm, &userbuf, MAILROOM);
762                                 }
763                         }
764                 }
765
766         /* ...or if this message is destined for Aide> then go there. */
767         if (mtsflag) {
768                 strcpy(hold_rm, actual_rm);
769                 strcpy(actual_rm, AIDEROOM);
770                 }
771
772         /* This call to usergoto() changes rooms if necessary.  It also
773          * causes the latest message list to be read into memory.
774          */
775         usergoto(actual_rm, 0);
776
777         /* read in the quickroom record, obtaining a lock... */
778         lgetroom(&CC->quickroom, actual_rm);
779
780         /* Fix an obscure bug */
781         if (!strcasecmp(CC->quickroom.QRname, AIDEROOM)) {
782                 CC->quickroom.QRflags = CC->quickroom.QRflags & ~QR_MAILBOX;
783                 }
784
785         /* Add the message pointer to the room */
786         AddMessageToRoom(&CC->quickroom, newmsgid);
787
788         /* update quickroom */
789         CC->quickroom.QRhighest = newmsgid;
790         lputroom(&CC->quickroom, actual_rm);
791
792         /* Network mail - send a copy to the network program. */
793         if ( (strlen(recipient)>0) && (mailtype != M_LOCAL) ) {
794                 sprintf(aaa,"./network/spoolin/nm.%d",getpid());
795                 copy_file(mtmp,aaa);
796                 system("exec nohup ./netproc >/dev/null 2>&1 &");
797                 }
798
799         /* Bump this user's messages posted counter. */
800         lgetuser(&CC->usersupp, CC->curr_user);
801         CC->usersupp.posted = CC->usersupp.posted + 1;
802         lputuser(&CC->usersupp, CC->curr_user);
803
804         /* If we've posted in a room other than the current room, then we
805          * have to now go back to the current room...
806          */
807         if (strlen(hold_rm) > 0) {
808                 usergoto(hold_rm, 0);
809                 }
810         unlink(mtmp);           /* delete the temporary file */
811         }
812
813
814 /*
815  * Generate an administrative message and post it in the Aide> room.
816  */
817 void aide_message(char *text)
818 {
819         time_t now;
820         FILE *fp;
821
822         time(&now);
823         fp=fopen(CC->temp,"wb");
824         fprintf(fp,"%c%c%c",255,MES_NORMAL,0);
825         fprintf(fp,"Psysop%c",0);
826         fprintf(fp,"T%ld%c",now,0);
827         fprintf(fp,"ACitadel%c",0);
828         fprintf(fp,"OAide%c",0);
829         fprintf(fp,"N%s%c",NODENAME,0);
830         fprintf(fp,"M%s\n%c",text,0);
831         fclose(fp);
832         save_message(CC->temp,"",1,M_LOCAL,1);
833         syslog(LOG_NOTICE,text);
834         }
835
836
837
838 /*
839  * Build a binary message to be saved on disk.
840  */
841 void make_message(
842         char *filename,                 /* temporary file name */
843         struct usersupp *author,        /* author's usersupp structure */
844         char *recipient,                /* NULL if it's not mail */
845         char *room,                     /* room where it's going */
846         int type,                       /* see MES_ types in header file */
847         int net_type,                   /* see MES_ types in header file */
848         int format_type,                /* local or remote (see citadel.h) */
849         char *fake_name,                /* who we're masquerading as */
850         char *boundary) {               /* boundary (if exist attachments) */
851
852         FILE *fp;
853         int a;
854         time_t now;
855         char dest_node[32];
856         char buf[256];
857
858         /* Don't confuse the poor folks if it's not routed mail. */
859         strcpy(dest_node, "");
860
861
862         /* If net_type is M_BINARY, split out the destination node. */
863         if (net_type == M_BINARY) {
864                 strcpy(dest_node,NODENAME);
865                 for (a=0; a<strlen(recipient); ++a) {
866                         if (recipient[a]=='@') {
867                                 recipient[a]=0;
868                                 strcpy(dest_node,&recipient[a+1]);
869                                 }
870                         }
871                 }
872
873         /* if net_type is M_INTERNET, set the dest node to 'internet' */
874         if (net_type == M_INTERNET) {
875                 strcpy(dest_node,"internet");
876                 }
877
878         while (isspace(recipient[strlen(recipient)-1]))
879                 recipient[strlen(recipient)-1] = 0;
880
881         time(&now);
882         fp=fopen(filename,"w");
883         putc(255,fp);
884         putc(type,fp);  /* Normal or anonymous, see MES_ flags */
885         putc(format_type,fp);   /* Formatted or unformatted */
886         fprintf(fp,"Pcit%ld%c",author->usernum,0);      /* path */
887         fprintf(fp,"T%ld%c",now,0);                     /* date/time */
888         if (fake_name[0])
889            fprintf(fp,"A%s%c",fake_name,0);
890         else
891            fprintf(fp,"A%s%c",author->fullname,0);      /* author */
892
893         if (CC->quickroom.QRflags & QR_MAILBOX) {       /* room */
894                 fprintf(fp,"O%s%c", &CC->quickroom.QRname[11], 0);
895                 }
896         else {
897                 fprintf(fp,"O%s%c",CC->quickroom.QRname,0);
898                 }
899
900         fprintf(fp,"N%s%c",NODENAME,0);                 /* nodename */
901         fprintf(fp,"H%s%c",HUMANNODE,0);                /* human nodename */
902
903         if (recipient[0]!=0) fprintf(fp, "R%s%c", recipient, 0);
904         if (dest_node[0]!=0) fprintf(fp, "D%s%c", dest_node, 0);
905         if (boundary[0]!=0) fprintf(fp, "Z%s%c", boundary, 0);
906
907         putc('M',fp);
908
909         while (client_gets(buf), strcmp(buf,"000"))
910         {
911            fprintf(fp,"%s\n",buf);
912         }
913         syslog(LOG_INFO, "Closing message");
914         putc(0,fp);
915         fclose(fp);
916         }
917
918
919
920
921
922 /*
923  * message entry  -  mode 0 (normal) <bc>
924  */
925 void cmd_ent0(char *entargs)
926 {
927         int post = 0;
928         char recipient[256];
929         int anon_flag = 0;
930         int format_type = 0;
931         char newusername[256];          /* <bc> */
932         char boundary[256];
933
934         int a,b;
935         int e = 0;
936         int mtsflag = 0;
937         struct usersupp tempUS;
938         char buf[256];
939
940         post = extract_int(entargs,0);
941         extract(recipient,entargs,1);
942         anon_flag = extract_int(entargs,2);
943         format_type = extract_int(entargs,3);
944         extract(boundary, entargs, 5);
945
946         /* first check to make sure the request is valid. */
947
948         if (!(CC->logged_in)) {
949                 cprintf("%d Not logged in.\n",ERROR+NOT_LOGGED_IN);
950                 return;
951                 }
952         if ((CC->usersupp.axlevel<2)&&((CC->quickroom.QRflags&QR_MAILBOX)==0)) {
953                 cprintf("%d Need to be validated to enter ",
954                         ERROR+HIGHER_ACCESS_REQUIRED);
955                 cprintf("(except in %s> to sysop)\n", MAILROOM);
956                 return;
957                 }
958         if ((CC->usersupp.axlevel<4)&&(CC->quickroom.QRflags&QR_NETWORK)) {
959                 cprintf("%d Need net privileges to enter here.\n",
960                         ERROR+HIGHER_ACCESS_REQUIRED);
961                 return;
962                 }
963         if ((CC->usersupp.axlevel<6)&&(CC->quickroom.QRflags&QR_READONLY)) {
964                 cprintf("%d Sorry, this is a read-only room.\n",
965                         ERROR+HIGHER_ACCESS_REQUIRED);
966                 return;
967                 }
968
969         mtsflag=0;
970         
971                 
972         if (post==2) {                  /* <bc> */
973            if (CC->usersupp.axlevel<6)
974            {
975               cprintf("%d You don't have permission to do an aide post.\n",
976                 ERROR+HIGHER_ACCESS_REQUIRED);
977               return;
978            }
979            extract(newusername,entargs,4);
980            bzero(CC->fake_postname, 32);
981            strcpy(CC->fake_postname, newusername);
982            cprintf("%d Ok\n",OK);
983            return;
984         }
985         
986         CC->cs_flags |= CS_POSTING;
987         
988         buf[0]=0;
989         if (CC->quickroom.QRflags & QR_MAILBOX) {
990                 if (CC->usersupp.axlevel>=2) {
991                         strcpy(buf,recipient);
992                         }
993                 else strcpy(buf,"sysop");
994                 e=alias(buf);                   /* alias and mail type */
995                 if ((buf[0]==0) || (e==M_ERROR)) {
996                         cprintf("%d Unknown address - cannot send message.\n",
997                                 ERROR+NO_SUCH_USER);
998                         return;
999                         }
1000                 if ((e!=M_LOCAL)&&(CC->usersupp.axlevel<4)) {
1001                         cprintf("%d Net privileges required for network mail.\n",
1002                                 ERROR+HIGHER_ACCESS_REQUIRED);
1003                         return;
1004                         }
1005                 if ((RESTRICT_INTERNET==1)&&(e==M_INTERNET)
1006                    &&((CC->usersupp.flags&US_INTERNET)==0)
1007                    &&(!CC->internal_pgm) ) {
1008                         cprintf("%d You don't have access to Internet mail.\n",
1009                                 ERROR+HIGHER_ACCESS_REQUIRED);
1010                         return;
1011                         }
1012                 if (!strcasecmp(buf,"sysop")) {
1013                         mtsflag=1;
1014                         goto SKFALL;
1015                         }
1016                 if (e!=M_LOCAL) goto SKFALL;    /* don't search local file  */
1017                 if (!strcasecmp(buf,CC->usersupp.fullname)) {
1018                         cprintf("%d Can't send mail to yourself!\n",
1019                                 ERROR+NO_SUCH_USER);
1020                         return;
1021                         }
1022
1023                 /* Check to make sure the user exists; also get the correct
1024                 * upper/lower casing of the name. 
1025                 */
1026                 a = getuser(&tempUS,buf);
1027                 if (a != 0) {
1028                         cprintf("%d No such user.\n",ERROR+NO_SUCH_USER);
1029                         return;
1030                         }
1031                 strcpy(buf,tempUS.fullname);
1032                 }
1033         
1034 SKFALL: b=MES_NORMAL;
1035         if (CC->quickroom.QRflags&QR_ANONONLY) b=MES_ANON;
1036         if (CC->quickroom.QRflags&QR_ANONOPT) {
1037                 if (anon_flag==1) b=MES_AN2;
1038                 }
1039         if ((CC->quickroom.QRflags & QR_MAILBOX) == 0) buf[0]=0;
1040
1041         /* If we're only checking the validity of the request, return
1042          * success without creating the message.
1043          */
1044         if (post==0) {
1045                 cprintf("%d %s\n",OK,buf);
1046                 return;
1047                 }
1048         
1049         cprintf("%d send message\n",SEND_LISTING);
1050         if (CC->fake_postname[0])
1051            make_message(CC->temp,&CC->usersupp,buf,CC->quickroom.QRname,b,e,format_type, CC->fake_postname, boundary);
1052         else
1053            if (CC->fake_username[0])
1054               make_message(CC->temp,&CC->usersupp,buf,CC->quickroom.QRname,b,e,format_type, CC->fake_username, boundary);
1055            else
1056               make_message(CC->temp,&CC->usersupp,buf,CC->quickroom.QRname,b,e,format_type, "", boundary);
1057         save_message(CC->temp,buf,mtsflag,e,1);
1058         CC->fake_postname[0]='\0';
1059         return;
1060         }
1061
1062
1063
1064 /* 
1065  * message entry - mode 3 (raw)
1066  */
1067 void cmd_ent3(char *entargs)
1068 {
1069         char recp[256];
1070         char buf[256];
1071         int a;
1072         int e = 0;
1073         struct usersupp tempUS;
1074         long msglen;
1075         long bloklen;
1076         FILE *fp;
1077
1078         if (CC->internal_pgm == 0) {
1079                 cprintf("%d This command is for internal programs only.\n",
1080                         ERROR);
1081                 return;
1082                 }
1083
1084         /* If we're in Mail, check the recipient */
1085         if (CC->quickroom.QRflags & QR_MAILBOX) {
1086                 extract(recp, entargs, 1);
1087                 e=alias(recp);                  /* alias and mail type */
1088                 if ((buf[0]==0) || (e==M_ERROR)) {
1089                         cprintf("%d Unknown address - cannot send message.\n",
1090                                 ERROR+NO_SUCH_USER);
1091                         return;
1092                         }
1093                 if (e == M_LOCAL) {
1094                         a = getuser(&tempUS,recp);
1095                         if (a!=0) {
1096                                 cprintf("%d No such user.\n", ERROR+NO_SUCH_USER);
1097                                 return;
1098                                 }
1099                         }
1100                 }
1101
1102         /* At this point, message has been approved. */
1103         if (extract_int(entargs, 0) == 0) {
1104                 cprintf("%d OK to send\n", OK);
1105                 return;
1106                 }
1107
1108         /* open a temp file to hold the message */
1109         fp = fopen(CC->temp, "wb");
1110         if (fp == NULL) {
1111                 cprintf("%d Cannot open %s: %s\n", 
1112                         ERROR + INTERNAL_ERROR,
1113                         CC->temp, strerror(errno) );
1114                 return;
1115                 }
1116
1117         msglen = extract_long(entargs, 2);
1118         cprintf("%d %ld\n", SEND_BINARY, msglen);
1119         while(msglen > 0L) {
1120                 bloklen = ((msglen >= 255L) ? 255 : msglen);
1121                 client_read(buf, (int)bloklen );
1122                 fwrite(buf, (int)bloklen, 1, fp);
1123                 msglen = msglen - bloklen;
1124                 }
1125         fclose(fp);
1126
1127         save_message(CC->temp, recp, 0, e, 0);
1128         }
1129
1130
1131 /*
1132  * Delete message from current room
1133  */
1134 void cmd_dele(char *delstr)
1135 {
1136         long delnum;
1137         int a,ok;
1138
1139         getuser(&CC->usersupp,CC->curr_user);
1140         if ((CC->usersupp.axlevel < 6)
1141            && (CC->usersupp.usernum != CC->quickroom.QRroomaide)) {
1142                 cprintf("%d Higher access required.\n",
1143                         ERROR+HIGHER_ACCESS_REQUIRED);
1144                 return;
1145                 }
1146
1147         delnum = atol(delstr);
1148         if (CC->quickroom.QRflags & QR_MAILBOX) {
1149                 cprintf("%d Can't delete mail.\n",ERROR);
1150                 return;
1151                 }
1152         
1153         /* get room records, obtaining a lock... */
1154         lgetroom(&CC->quickroom,CC->quickroom.QRname);
1155         get_msglist(&CC->quickroom);
1156
1157         ok = 0;
1158         if (CC->num_msgs > 0) for (a=0; a<(CC->num_msgs); ++a) {
1159                 if (MessageFromList(a) == delnum) {
1160                         SetMessageInList(a, 0L);
1161                         ok = 1;
1162                         }
1163                 }
1164
1165         CC->num_msgs = sort_msglist(CC->msglist, CC->num_msgs);
1166         CC->quickroom.QRhighest = MessageFromList(CC->num_msgs - 1);
1167
1168         put_msglist(&CC->quickroom);
1169         lputroom(&CC->quickroom,CC->quickroom.QRname);
1170         if (ok==1) {
1171                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
1172                 cprintf("%d Message deleted.\n",OK);
1173                 }
1174         else cprintf("%d No message %ld.\n",ERROR,delnum);
1175         } 
1176
1177
1178 /*
1179  * move a message to another room
1180  */
1181 void cmd_move(char *args)
1182 {
1183         long num;
1184         char targ[32];
1185         int a;
1186         struct quickroom qtemp;
1187         int foundit;
1188
1189         num = extract_long(args,0);
1190         extract(targ,args,1);
1191         
1192         getuser(&CC->usersupp,CC->curr_user);
1193         if ((CC->usersupp.axlevel < 6)
1194            && (CC->usersupp.usernum != CC->quickroom.QRroomaide)) {
1195                 cprintf("%d Higher access required.\n",
1196                         ERROR+HIGHER_ACCESS_REQUIRED);
1197                 return;
1198                 }
1199
1200         if (getroom(&qtemp, targ) != 0) {
1201                 cprintf("%d '%s' does not exist.\n",ERROR,targ);
1202                 return;
1203                 }
1204
1205         /* yank the message out of the current room... */
1206         lgetroom(&CC->quickroom, CC->quickroom.QRname);
1207         get_msglist(&CC->quickroom);
1208
1209         foundit = 0;
1210         for (a=0; a<(CC->num_msgs); ++a) {
1211                 if (MessageFromList(a) == num) {
1212                         foundit = 1;
1213                         SetMessageInList(a, 0L);
1214                         }
1215                 }
1216         if (foundit) {
1217                 CC->num_msgs = sort_msglist(CC->msglist, CC->num_msgs);
1218                 put_msglist(&CC->quickroom);
1219                 CC->quickroom.QRhighest = MessageFromList((CC->num_msgs)-1);
1220                 }
1221         lputroom(&CC->quickroom,CC->quickroom.QRname);
1222         if (!foundit) {
1223                 cprintf("%d msg %ld does not exist.\n",ERROR,num);
1224                 return;
1225                 }
1226
1227         /* put the message into the target room */
1228         lgetroom(&qtemp, targ);
1229         AddMessageToRoom(&qtemp, num);
1230         lputroom(&qtemp, targ);
1231
1232         cprintf("%d Message moved.\n", OK);
1233         }