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