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