* Removed code from some of the utilities which was still attempting
[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 = 0;
143         int mode = 0;
144         char which[256];
145         int cm_howmany = 0;
146         long cm_gt = 0L;
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,
316                         int headers_only, int desired_section) {
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         int has_attachments = 0;
327
328         struct cdbdata *dmsgtext;
329         char *mptr;
330
331         /* buffers needed for RFC822 translation */
332         char suser[256];
333         char luser[256];
334         char snode[256];
335         char lnode[256];
336         char mid[256];
337         long xtime;
338         /* */
339
340         strcpy(boundary, "");
341         msg_num = atol(msgid);
342
343
344         if ((!(CC->logged_in))&&(!(CC->internal_pgm))) {
345                 cprintf("%d Not logged in.\n",ERROR+NOT_LOGGED_IN);
346                 return;
347                 }
348         if (CC->curr_rm < 0) {
349                 cprintf("%d No room selected.\n",ERROR);
350                 return;
351                 }
352
353         /* We used to need to check in the current room's message list
354          * to determine where the message's disk position.  We no longer need
355          * to do this, but we do it anyway as a security measure, in order to
356          * prevent rogue clients from reading messages not in the current room.
357          */
358
359         msg_ok = 0;
360         if (CC->num_msgs > 0) {
361                 for (a=0; a<CC->num_msgs; ++a) {
362                         if (MessageFromList(a) == msg_num) {
363                                 msg_ok = 1;
364                                 }
365                         }
366                 }
367
368         if (!msg_ok) {
369                 cprintf("%d Message %ld is not in this room.\n",
370                         ERROR, msg_num);
371                 return;
372                 }
373         
374
375         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msg_num, sizeof(long));
376         
377         if (dmsgtext == NULL) {
378                 cprintf("%d Can't find message %ld\n", ERROR+INTERNAL_ERROR);
379                 return;
380                 }
381
382         msg_len = (long) dmsgtext->len;
383         mptr = dmsgtext->ptr;
384         lprintf(9, "Returned message length is %ld\n", msg_len);
385
386         /* this loop spews out the whole message if we're doing raw format */
387         if (mode == MT_RAW) {
388                 cprintf("%d %ld\n", BINARY_FOLLOWS, msg_len);
389                 client_write(dmsgtext->ptr, (int) msg_len);
390                 cdb_free(dmsgtext);
391                 return;
392                 }
393
394         /* Otherwise, we'll start parsing it field by field... */
395         ch = *mptr++;
396         if (ch != 255) {
397                 cprintf("%d Illegal message format on disk\n",
398                         ERROR+INTERNAL_ERROR);
399                 cdb_free(dmsgtext);
400                 return;
401                 }
402
403         anon_flag = *mptr++;
404         format_type = *mptr++;
405
406         /* now for the user-mode message reading loops */
407         cprintf("%d Message %ld:\n",LISTING_FOLLOWS,msg_num);
408
409         if (mode == MT_CITADEL) cprintf("type=%d\n",format_type);
410
411         if ( (anon_flag == MES_ANON) && (mode == MT_CITADEL) ) {
412                 cprintf("nhdr=yes\n");
413                 }
414
415         /* begin header processing loop for Citadel message format */
416
417         if (mode == MT_CITADEL) while(ch = *mptr++, (ch!='M' && ch!=0)) {
418                 buf[0] = 0;
419                 do {
420                         buf[strlen(buf)+1] = 0;
421                         rch = *mptr++;
422                         buf[strlen(buf)] = rch;
423                         } while (rch > 0);
424
425                 if (ch=='A') {
426                         PerformUserHooks(buf, (-1L), EVT_OUTPUTMSG);
427                         if (anon_flag==MES_ANON) cprintf("from=****");
428                         else if (anon_flag==MES_AN2) cprintf("from=anonymous");
429                         else cprintf("from=%s",buf);
430                         if ((is_room_aide()) && ((anon_flag == MES_ANON)
431                            || (anon_flag == MES_AN2)))
432                                 cprintf(" [%s]",buf);
433                         cprintf("\n");
434                         }
435                 else if (ch=='Z') {
436                         has_attachments = 1;
437                         sprintf(boundary, "--%s", buf);
438                         }
439                 else if (ch=='P') cprintf("path=%s\n",buf);
440                 else if (ch=='U') cprintf("subj=%s\n",buf);
441                 else if (ch=='I') cprintf("msgn=%s\n",buf);
442                 else if (ch=='H') cprintf("hnod=%s\n",buf);
443                 else if (ch=='O') cprintf("room=%s\n",buf);
444                 else if (ch=='N') cprintf("node=%s\n",buf);
445                 else if (ch=='R') cprintf("rcpt=%s\n",buf);
446                 else if (ch=='T') cprintf("time=%s\n",buf);
447                 /* else cprintf("fld%c=%s\n",ch,buf); */
448                 }
449
450         /* begin header processing loop for RFC822 transfer format */
451
452         strcpy(suser, "");
453         strcpy(luser, "");
454         strcpy(snode, NODENAME);
455         strcpy(lnode, HUMANNODE);
456         if (mode == MT_RFC822) while(ch = *mptr++, (ch!='M' && ch!=0)) {
457                 buf[0] = 0;
458                 do {
459                         buf[strlen(buf)+1] = 0;
460                         rch = *mptr++;
461                         buf[strlen(buf)] = rch;
462                         } while (rch > 0);
463
464                 if (ch=='A') strcpy(luser, buf);
465                 else if (ch=='P') {
466                         cprintf("Path: %s\n",buf);
467                         for (a=0; a<strlen(buf); ++a) {
468                                 if (buf[a] == '!') {
469                                         strcpy(buf,&buf[a+1]);
470                                         a=0;
471                                         }
472                                 }
473                         strcpy(suser, buf);
474                         }
475                 else if (ch=='U') cprintf("Subject: %s\n",buf);
476                 else if (ch=='I') strcpy(mid, buf);
477                 else if (ch=='H') strcpy(lnode, buf);
478                 else if (ch=='O') cprintf("X-Citadel-Room: %s\n",buf);
479                 else if (ch=='N') strcpy(snode, buf);
480                 else if (ch=='R') cprintf("To: %s\n",buf);
481                 else if (ch=='T')  {
482                         xtime = atol(buf);
483                         cprintf("Date: %s", asctime(localtime(&xtime)));
484                         }
485                 }
486
487         if (mode == MT_RFC822) {
488                 if (!strcasecmp(snode, NODENAME)) {
489                         strcpy(snode, FQDN);
490                         }
491                 cprintf("Message-ID: <%s@%s>\n", mid, snode);
492                 PerformUserHooks(luser, (-1L), EVT_OUTPUTMSG);
493                 cprintf("From: %s@%s (%s)\n",
494                         suser, snode, luser);
495                 cprintf("Organization: %s\n", lnode);
496                 }
497
498         /* end header processing loop ... at this point, we're in the text */
499
500         if (ch==0) {
501                 cprintf("text\n*** ?Message truncated\n000\n");
502                 cdb_free(dmsgtext);
503                 return;
504                 }
505
506         if (headers_only) {
507                 /* give 'em a length */
508                 msg_len = 0L;
509                 while(ch = *mptr++, ch>0) {
510                         ++msg_len;
511                         }
512                 cprintf("mlen=%ld\n", msg_len);
513                 cprintf("000\n");
514                 cdb_free(dmsgtext);
515                 return;
516                 }
517
518         /* signify start of msg text */
519         if (mode == MT_CITADEL) cprintf("text\n");
520         if (mode == MT_RFC822) cprintf("\n");
521
522         /* If the format type on disk is 1 (fixed-format), then we want
523          * everything to be output completely literally ... regardless of
524          * what message transfer format is in use.
525          */
526         if (format_type == 1) {
527                 strcpy(buf, "");
528                 while(ch = *mptr++, ch>0) {
529                         if (ch == 13) ch = 10;
530                         if ( (ch == 10) || (strlen(buf)>250) ) {
531                                 if (has_attachments) if (!strncmp(buf, boundary, strlen(boundary))) {
532                                         ++current_section;
533                                         }
534                                 if (current_section == desired_section) {
535                                         if ( (has_attachments == 0) || (strncmp(buf, boundary, strlen(boundary)))) {
536                                                 cprintf("%s\n", buf);
537                                                 }
538                                         }
539                                 strcpy(buf, "");
540                                 }
541                         else {
542                                 buf[strlen(buf)+1] = 0;
543                                 buf[strlen(buf)] = ch;
544                                 }
545                         }
546                 if (strlen(buf)>0) cprintf("%s\n", buf);
547                 }
548         /* If the message on disk is format 0 (Citadel vari-format), we
549          * output using the formatter at 80 columns.  This is the final output
550          * form if the transfer format is RFC822, but if the transfer format
551          * is Citadel proprietary, it'll still work, because the indentation
552          * for new paragraphs is correct and the client will reformat the
553          * message to the reader's screen width.
554          */
555         if (format_type == 0) {
556                 memfmout(80,mptr,0);
557                 }
558
559
560         /* now we're done */
561         cprintf("000\n");
562         cdb_free(dmsgtext);
563         }
564
565
566 /*
567  * display a message (mode 0 - Citadel proprietary)
568  */
569 void cmd_msg0(char *cmdbuf)
570 {
571         char msgid[256];
572         int headers_only = 0;
573         int desired_section = 0;
574
575         extract(msgid,cmdbuf,0);
576         headers_only = extract_int(cmdbuf, 1);
577         desired_section = extract_int(cmdbuf, 2);
578
579         output_message(msgid,MT_CITADEL, headers_only, desired_section);
580         }
581
582
583 /*
584  * display a message (mode 2 - RFC822)
585  */
586 void cmd_msg2(char *cmdbuf)
587 {
588         char msgid[256];
589         int headers_only = 0;
590
591         extract(msgid,cmdbuf,0);
592         headers_only = extract_int(cmdbuf,1);
593
594         output_message(msgid,MT_RFC822,headers_only,0);
595         }
596
597 /* 
598  * display a message (mode 3 - IGnet raw format - internal programs only)
599  */
600 void cmd_msg3(char *cmdbuf)
601 {
602         char msgid[256];
603         int headers_only = 0;
604
605         if (CC->internal_pgm == 0) {
606                 cprintf("%d This command is for internal programs only.\n",
607                         ERROR);
608                 return;
609                 }
610
611         extract(msgid,cmdbuf,0);
612         headers_only = extract_int(cmdbuf,1);
613
614         output_message(msgid,MT_RAW,headers_only,0);
615         }
616
617
618
619 /*
620  * Message base operation to send a message to the master file
621  * (returns new message number)
622  */
623 long send_message(char *message_in_memory,      /* pointer to buffer */
624                 size_t message_length,          /* length of buffer */
625                 int generate_id) {              /* 1 to generate an I field */
626
627         long newmsgid;
628
629         /* Get a new message number */
630         newmsgid = get_new_message_number();
631
632         /* Write our little bundle of joy into the message base */
633
634         lprintf(9, "Storing message %ld\n", newmsgid);
635         begin_critical_section(S_MSGMAIN);
636         if ( cdb_store(CDB_MSGMAIN, &newmsgid, sizeof(long),
637                         message_in_memory, message_length) < 0 ) {
638                 lprintf(2, "Can't store message\n");
639                 end_critical_section(S_MSGMAIN);
640                 return 0L;
641                 }
642         end_critical_section(S_MSGMAIN);
643
644         /* Finally, return the pointers */
645         return(newmsgid);
646         }
647
648
649
650
651
652 /* FIX ... rewrite this to simply check for the existence of the twitroom,
653  * and create it if necessary.  No slot-numbers will need to be loaded.
654  * (Actually, twitroom should be created during the same portion of startup
655  * that creates Lobby/Mail/Aide.)
656  */
657 void loadtroom(void) {
658         struct quickroom qrbuf;
659         int a;
660         unsigned newflags;
661
662         /* first try to locate the twit room */
663         for (a=0; a<MAXROOMS; ++a) {
664                 getroom(&qrbuf,a);
665                 if (!strcasecmp(qrbuf.QRname,config.c_twitroom)) {
666                         twitroom = a;
667                         return;
668                         }
669                 }
670
671         /* if not found, try to create it  -  put it in the last slot */
672         twitroom = get_free_room_slot(-1);
673         if (twitroom>=0) {
674                 newflags = create_room(twitroom,config.c_twitroom,0,"",0);
675                 return;
676                 }
677
678         /* as a last resort, point to Aide> */
679         twitroom = 2;
680         }
681
682
683 /*
684  * this is a simple file copy routine.
685  */
686 void copy_file(char *from, char *to)
687 {
688         FILE *ffp,*tfp;
689         int a;
690
691         ffp=fopen(from,"r");
692         if (ffp==NULL) return;
693         tfp=fopen(to,"w");
694         if (tfp==NULL) {
695                 fclose(ffp);
696                 return;
697                 }
698         while (a=getc(ffp), a>=0) {
699                 putc(a,tfp);
700                 }
701         fclose(ffp);
702         fclose(tfp);
703         return;
704         }
705
706
707
708 /*
709  * message base operation to save a message and install its pointers
710  */
711 void save_message(char *mtmp,   /* file containing proper message */
712                 char *rec,      /* Recipient (if mail) */
713                 char mtsflag,   /* 0 for normal, 1 to force Aide> room */
714                 int mailtype,   /* local or remote type, see citadel.h */
715                 int generate_id) /* set to 1 to generate an 'I' field */
716 {
717         struct usersupp tempUS;
718         char aaa[100];
719         int hold_rm;
720         struct cdbdata *cdbmb;
721         long *dmailbox;
722         int dnum_mails;
723         long newmsgid;
724         char *message_in_memory;
725         struct stat statbuf;
726         size_t templen;
727         FILE *fp;
728
729         /* Measure the message */
730         lprintf(9, "Measuring the message\n");
731         stat(mtmp, &statbuf);
732         templen = statbuf.st_size;
733
734         /* Now read it into memory */
735         lprintf(9, "Allocating %ld bytes\n", templen);
736         message_in_memory = (char *) malloc(templen);
737         if (message_in_memory == NULL) {
738                 lprintf(2, "Can't allocate memory to save message!\n");
739                 return;
740                 }
741
742         lprintf(9, "Reading it into memory\n"); 
743         fp = fopen(mtmp, "rb");
744         fread(message_in_memory, templen, 1, fp);
745         fclose(fp);
746
747         newmsgid = send_message(message_in_memory, templen, generate_id);
748         free(message_in_memory);
749         if (newmsgid <= 0L) return;
750         hold_rm=(-1);
751
752         /* If the user is a twit, move to the twit room for posting... */
753         if (TWITDETECT) if (CC->usersupp.axlevel==2) {
754                 if (twitroom<0) loadtroom();
755                 hold_rm=CC->curr_rm;
756                 CC->curr_rm=twitroom;
757                 }
758
759         /* ...or if this message is destined for Aide> then go there. */
760         if (mtsflag) {
761                 hold_rm=CC->curr_rm;
762                 CC->curr_rm=2;
763                 }
764
765         /* This call to usergoto() changes rooms if necessary.  It also
766          * causes the latest message list to be read into memory.
767          */
768         usergoto(CC->curr_rm,0);
769
770         /* Store the message pointer, but NOT for sent mail! */
771         if (CC->curr_rm != 1) {
772
773                 /* read in the quickroom record, obtaining a lock... */
774                 lgetroom(&CC->quickroom,CC->curr_rm);
775                 get_msglist(CC->curr_rm);
776
777                 /* FIX here's where we have to to message expiry!! */
778
779                 /* Now add the new message */
780                 CC->num_msgs = CC->num_msgs + 1;
781                 CC->msglist = realloc(CC->msglist,
782                         ((CC->num_msgs) * sizeof(long)) );
783                 if (CC->msglist == NULL) {
784                         lprintf(3, "ERROR can't realloc message list!\n");
785                         }
786                 SetMessageInList(CC->num_msgs - 1, newmsgid);
787         
788                 /* Write it back to disk. */
789                 put_msglist(CC->curr_rm);
790         
791                 /* update quickroom */
792                 CC->quickroom.QRhighest = newmsgid;
793                 lputroom(&CC->quickroom,CC->curr_rm);
794                 }
795
796         /* Bump this user's messages posted counter.  Also, if the user is a
797          * twit, give them access to the twit room.
798          */
799         lgetuser(&CC->usersupp,CC->curr_user);
800         CC->usersupp.posted = CC->usersupp.posted + 1;
801         if (CC->curr_rm==twitroom) {
802                 CC->usersupp.generation[twitroom] = CC->quickroom.QRgen;
803                 }
804         lputuser(&CC->usersupp, CC->curr_user);
805
806         /* If mail, there's still more to do, if not, skip it. */
807         if ((CC->curr_rm!=1)||(mtsflag)) goto ENTFIN;
808
809         /* Network mail - send a copy to the network program. */
810         if (mailtype!=M_LOCAL) {
811                 sprintf(aaa,"./network/spoolin/nm.%d",getpid());
812                 copy_file(mtmp,aaa);
813                 system("exec nohup ./netproc >/dev/null 2>&1 &");
814                 }
815
816         /* Local mail - put a copy in the recipient's mailbox. */
817         /* FIX here's where we have to handle expiry, stuffed boxes, etc. */
818         if (mailtype == M_LOCAL) {
819                 if (lgetuser(&tempUS,rec)==0) {
820
821                         cdbmb = cdb_fetch(CDB_MAILBOXES,
822                                         &tempUS.usernum, sizeof(long));
823                         if (cdbmb != NULL) {
824                                 memcpy(dmailbox, cdbmb->ptr, cdbmb->len);
825                                 dnum_mails = cdbmb->len / sizeof(long);
826                                 cdb_free(cdbmb);
827                                 }
828                         else {
829                                 dmailbox = NULL;
830                                 dnum_mails = 0;
831                                 }
832         
833                         ++dnum_mails;
834                         if (dmailbox == NULL) {
835                                 dmailbox = malloc(sizeof(long) * dnum_mails);
836                                 }
837                         else {
838                                 dmailbox = realloc(dmailbox,
839                                                 sizeof(long) * dnum_mails);
840                                 }
841                         
842                         dmailbox[dnum_mails - 1] = newmsgid;
843                         cdb_store(CDB_MAILBOXES, &tempUS.usernum, sizeof(long),
844                                 dmailbox, (dnum_mails * sizeof(long)) );
845                         lputuser(&tempUS,rec);
846                         free(dmailbox);
847                         }
848                 }
849
850         /* If we've posted in a room other than the current room, then we
851          * have to now go back to the current room...
852          */
853 ENTFIN: if (hold_rm!=(-1)) {
854                 usergoto(hold_rm,0);
855                 }
856         unlink(mtmp);           /* delete the temporary file */
857         }
858
859
860 /*
861  * Generate an administrative message and post it in the Aide> room.
862  */
863 void aide_message(char *text)
864 {
865         long now;
866         FILE *fp;
867
868         time(&now);
869         fp=fopen(CC->temp,"wb");
870         fprintf(fp,"%c%c%c",255,MES_NORMAL,0);
871         fprintf(fp,"Psysop%c",0);
872         fprintf(fp,"T%ld%c",now,0);
873         fprintf(fp,"ACitadel%c",0);
874         fprintf(fp,"OAide%c",0);
875         fprintf(fp,"N%s%c",NODENAME,0);
876         fprintf(fp,"M%s\n%c",text,0);
877         fclose(fp);
878         save_message(CC->temp,"",1,M_LOCAL,1);
879         syslog(LOG_NOTICE,text);
880         }
881
882
883
884 /*
885  * Build a binary message to be saved on disk.
886  */
887 void make_message(
888         char *filename,                 /* temporary file name */
889         struct usersupp *author,        /* author's usersupp structure */
890         char *recipient,                /* NULL if it's not mail */
891         char *room,                     /* room where it's going */
892         int type,                       /* see MES_ types in header file */
893         int net_type,                   /* see MES_ types in header file */
894         int format_type,                /* local or remote (see citadel.h) */
895         char *fake_name,                /* who we're masquerading as */
896         char *boundary) {               /* boundary (if exist attachments) */
897
898         FILE *fp;
899         int a;
900         long now;
901         char dest_node[32];
902         char buf[256];
903
904         /* Don't confuse the poor folks if it's not routed mail. */
905         strcpy(dest_node, "");
906
907         /* If net_type is M_BINARY, split out the destination node. */
908         if (net_type == M_BINARY) {
909                 strcpy(dest_node,NODENAME);
910                 for (a=0; a<strlen(recipient); ++a) {
911                         if (recipient[a]=='@') {
912                                 recipient[a]=0;
913                                 strcpy(dest_node,&recipient[a+1]);
914                                 }
915                         }
916                 }
917
918         /* if net_type is M_INTERNET, set the dest node to 'internet' */
919         if (net_type == M_INTERNET) {
920                 strcpy(dest_node,"internet");
921                 }
922
923         while (isspace(recipient[strlen(recipient)-1]))
924                 recipient[strlen(recipient)-1] = 0;
925
926         time(&now);
927         fp=fopen(filename,"w");
928         putc(255,fp);
929         putc(type,fp);  /* Normal or anonymous, see MES_ flags */
930         putc(format_type,fp);   /* Formatted or unformatted */
931         fprintf(fp,"Pcit%ld%c",author->usernum,0);      /* path */
932         fprintf(fp,"T%ld%c",now,0);                     /* date/time */
933         if (fake_name[0])
934            fprintf(fp,"A%s%c",fake_name,0);
935         else
936            fprintf(fp,"A%s%c",author->fullname,0);      /* author */
937         fprintf(fp,"O%s%c",CC->quickroom.QRname,0);     /* room */
938         fprintf(fp,"N%s%c",NODENAME,0);                 /* nodename */
939         fprintf(fp,"H%s%c",HUMANNODE,0);                /* human nodename */
940
941         if (recipient[0]!=0) fprintf(fp, "R%s%c", recipient, 0);
942         if (dest_node[0]!=0) fprintf(fp, "D%s%c", dest_node, 0);
943         if (boundary[0]!=0) fprintf(fp, "Z%s%c", boundary, 0);
944
945         putc('M',fp);
946
947         while (client_gets(buf), strcmp(buf,"000"))
948         {
949            fprintf(fp,"%s\n",buf);
950         }
951         syslog(LOG_INFO, "Closing message");
952         putc(0,fp);
953         fclose(fp);
954         }
955
956
957
958
959
960 /*
961  * message entry  -  mode 0 (normal) <bc>
962  */
963 void cmd_ent0(char *entargs)
964 {
965         int post = 0;
966         char recipient[256];
967         int anon_flag = 0;
968         int format_type = 0;
969         char newusername[256];          /* <bc> */
970         char boundary[256];
971
972         int a,b,e;
973         int mtsflag = 0;
974         struct usersupp tempUS;
975         char buf[256];
976
977         post = extract_int(entargs,0);
978         extract(recipient,entargs,1);
979         anon_flag = extract_int(entargs,2);
980         format_type = extract_int(entargs,3);
981         extract(boundary, entargs, 5);
982
983         /* first check to make sure the request is valid. */
984
985         if (!(CC->logged_in)) {
986                 cprintf("%d Not logged in.\n",ERROR+NOT_LOGGED_IN);
987                 return;
988                 }
989         if (CC->curr_rm < 0) {
990                 cprintf("%d No room selected.\n",ERROR);
991                 return;
992                 }
993         if ((CC->usersupp.axlevel<2)&&(CC->curr_rm!=1)) {
994                 cprintf("%d Need to be validated to enter (except in Mail> to sysop)\n",
995                         ERROR+HIGHER_ACCESS_REQUIRED);
996                 return;
997                 }
998         if ((CC->usersupp.axlevel<4)&&(CC->quickroom.QRflags&QR_NETWORK)) {
999                 cprintf("%d Need net privileges to enter here.\n",
1000                         ERROR+HIGHER_ACCESS_REQUIRED);
1001                 return;
1002                 }
1003         if ((CC->usersupp.axlevel<6)&&(CC->quickroom.QRflags&QR_READONLY)) {
1004                 cprintf("%d Sorry, this is a read-only room.\n",
1005                         ERROR+HIGHER_ACCESS_REQUIRED);
1006                 return;
1007                 }
1008
1009         mtsflag=0;
1010         
1011                 
1012         if (post==2) {                  /* <bc> */
1013            if (CC->usersupp.axlevel<6)
1014            {
1015               cprintf("%d\nYou don't have sufficient permission to do an aide post.\n", ERROR+HIGHER_ACCESS_REQUIRED);
1016               return;
1017            }
1018            extract(newusername,entargs,4);
1019            bzero(CC->fake_postname, 32);
1020            strcpy(CC->fake_postname, newusername);
1021            cprintf("%d Ok\n",OK);
1022            return;
1023         }
1024         
1025         CC->cs_flags |= CS_POSTING;
1026         
1027         buf[0]=0;
1028         if (CC->curr_rm==1) {
1029                 if (CC->usersupp.axlevel>=2) {
1030                         strcpy(buf,recipient);
1031                         }
1032                 else strcpy(buf,"sysop");
1033                 lprintf(9, "aliasing...\n");
1034                 e=alias(buf);                   /* alias and mail type */
1035                 lprintf(9,"...type is %d\n", e);
1036                 if ((buf[0]==0) || (e==M_ERROR)) {
1037                         cprintf("%d Unknown address - cannot send message.\n",
1038                                 ERROR+NO_SUCH_USER);
1039                         return;
1040                         }
1041                 if ((e!=M_LOCAL)&&(CC->usersupp.axlevel<4)) {
1042                         cprintf("%d Net privileges required for network mail.\n",
1043                                 ERROR+HIGHER_ACCESS_REQUIRED);
1044                         return;
1045                         }
1046                 if ((RESTRICT_INTERNET==1)&&(e==M_INTERNET)
1047                    &&((CC->usersupp.flags&US_INTERNET)==0)
1048                    &&(!CC->internal_pgm) ) {
1049                         cprintf("%d You don't have access to Internet mail.\n",
1050                                 ERROR+HIGHER_ACCESS_REQUIRED);
1051                         return;
1052                         }
1053                 if (!strcasecmp(buf,"sysop")) {
1054                         mtsflag=1;
1055                         goto SKFALL;
1056                         }
1057                 if (e!=M_LOCAL) goto SKFALL;    /* don't search local file  */
1058                 if (!strcasecmp(buf,CC->usersupp.fullname)) {
1059                         cprintf("%d Can't send mail to yourself!\n",
1060                                 ERROR+NO_SUCH_USER);
1061                         return;
1062                         }
1063
1064                 /* Check to make sure the user exists; also get the correct
1065                 * upper/lower casing of the name. 
1066                 */
1067                 lprintf(9, "checking validity of %s\n", buf);
1068                 a = getuser(&tempUS,buf);
1069                 lprintf(9, "getuser() returned %d\n", a);
1070                 if (a != 0) {
1071                         cprintf("%d No such user.\n",ERROR+NO_SUCH_USER);
1072                         return;
1073                         }
1074                 strcpy(buf,tempUS.fullname);
1075                 }
1076         
1077 SKFALL: b=MES_NORMAL;
1078         if (CC->quickroom.QRflags&QR_ANONONLY) b=MES_ANON;
1079         if (CC->quickroom.QRflags&QR_ANON2) {
1080                 if (anon_flag==1) b=MES_AN2;
1081                 }
1082         if (CC->curr_rm!=1) buf[0]=0;
1083
1084         /* If we're only checking the validity of the request, return
1085          * success without creating the message.
1086          */
1087         if (post==0) {
1088                 cprintf("%d %s\n",OK,buf);
1089                 return;
1090                 }
1091         
1092         cprintf("%d send message\n",SEND_LISTING);
1093         if (CC->fake_postname[0])
1094            make_message(CC->temp,&CC->usersupp,buf,CC->quickroom.QRname,b,e,format_type, CC->fake_postname, boundary);
1095         else
1096            if (CC->fake_username[0])
1097               make_message(CC->temp,&CC->usersupp,buf,CC->quickroom.QRname,b,e,format_type, CC->fake_username, boundary);
1098            else
1099               make_message(CC->temp,&CC->usersupp,buf,CC->quickroom.QRname,b,e,format_type, "", boundary);
1100         save_message(CC->temp,buf,mtsflag,e,1);
1101         CC->fake_postname[0]='\0';
1102         return;
1103         }
1104
1105
1106
1107 /* 
1108  * message entry - mode 3 (raw)
1109  */
1110 void cmd_ent3(char *entargs)
1111 {
1112         char recp[256];
1113         char buf[256];
1114         int a, e;
1115         struct usersupp tempUS;
1116         long msglen;
1117         long bloklen;
1118         FILE *fp;
1119
1120         if (CC->internal_pgm == 0) {
1121                 cprintf("%d This command is for internal programs only.\n",
1122                         ERROR);
1123                 return;
1124                 }
1125
1126         if (CC->curr_rm < 0) {
1127                 cprintf("%d No room selected.\n",ERROR);
1128                 return;
1129                 }
1130
1131         if (CC->curr_rm == 1) { /* If we're in Mail, check the recipient */
1132                 extract(recp, entargs, 1);
1133                 lprintf(9, "aliasing...\n");
1134                 e=alias(recp);                  /* alias and mail type */
1135                 lprintf(9,"...type is %d\n", e);
1136                 if ((buf[0]==0) || (e==M_ERROR)) {
1137                         cprintf("%d Unknown address - cannot send message.\n",
1138                                 ERROR+NO_SUCH_USER);
1139                         return;
1140                         }
1141                 if (e == M_LOCAL) {
1142                         a = getuser(&tempUS,recp);
1143                         if (a!=0) {
1144                                 cprintf("%d No such user.\n", ERROR+NO_SUCH_USER);
1145                                 return;
1146                                 }
1147                         }
1148                 }
1149
1150         /* At this point, message has been approved. */
1151         if (extract_int(entargs, 0) == 0) {
1152                 cprintf("%d OK to send\n", OK);
1153                 return;
1154                 }
1155
1156         /* open a temp file to hold the message */
1157         fp = fopen(CC->temp, "wb");
1158         if (fp == NULL) {
1159                 cprintf("%d Cannot open %s: %s\n", 
1160                         ERROR + INTERNAL_ERROR,
1161                         CC->temp, strerror(errno) );
1162                 return;
1163                 }
1164
1165         msglen = extract_long(entargs, 2);
1166         cprintf("%d %ld\n", SEND_BINARY, msglen);
1167         while(msglen > 0L) {
1168                 bloklen = ((msglen >= 255L) ? 255 : msglen);
1169                 client_read(buf, (int)bloklen );
1170                 fwrite(buf, (int)bloklen, 1, fp);
1171                 msglen = msglen - bloklen;
1172                 }
1173         fclose(fp);
1174
1175         save_message(CC->temp, recp, 0, e, 0);
1176         }
1177
1178
1179 /*
1180  * Delete message from current room
1181  */
1182 void cmd_dele(char *delstr)
1183 {
1184         long delnum;
1185         int a,ok;
1186
1187         getuser(&CC->usersupp,CC->curr_user);
1188         if ((CC->usersupp.axlevel < 6)
1189            && (CC->usersupp.usernum != CC->quickroom.QRroomaide)) {
1190                 cprintf("%d Higher access required.\n",
1191                         ERROR+HIGHER_ACCESS_REQUIRED);
1192                 return;
1193                 }
1194
1195         delnum = atol(delstr);
1196         if (CC->curr_rm==1) {
1197                 cprintf("%d Can't delete mail.\n",ERROR);
1198                 return;
1199                 }
1200         
1201         /* get room records, obtaining a lock... */
1202         lgetroom(&CC->quickroom,CC->curr_rm);
1203         get_msglist(CC->curr_rm);
1204
1205         ok = 0;
1206         if (CC->num_msgs > 0) for (a=0; a<(CC->num_msgs); ++a) {
1207                 if (MessageFromList(a) == delnum) {
1208                         SetMessageInList(a, 0L);
1209                         ok = 1;
1210                         }
1211                 }
1212
1213         CC->num_msgs = sort_msglist(CC->msglist, CC->num_msgs);
1214         CC->quickroom.QRhighest = MessageFromList(CC->num_msgs - 1);
1215
1216         put_msglist(CC->curr_rm);
1217         lputroom(&CC->quickroom,CC->curr_rm);
1218         if (ok==1) {
1219                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
1220                 cprintf("%d Message deleted.\n",OK);
1221                 }
1222         else cprintf("%d No message %ld.\n",ERROR,delnum);
1223         } 
1224
1225
1226 /*
1227  * move a message to another room    FIX  Rework this to use name indices
1228  */
1229 void cmd_move(char *args)
1230 {
1231         long num;
1232         char targ[32];
1233         int a;
1234         int targ_slot;
1235         struct quickroom qtemp;
1236         int foundit;
1237         struct cdbdata *cdbtarg;
1238         long *targmsgs;
1239         int targ_count;
1240
1241         num = extract_long(args,0);
1242         extract(targ,args,1);
1243         
1244         if (CC->curr_rm < 0) {
1245                 cprintf("%d no room\n",ERROR);
1246                 return;
1247                 }
1248
1249         getuser(&CC->usersupp,CC->curr_user);
1250         if ((CC->usersupp.axlevel < 6)
1251            && (CC->usersupp.usernum != CC->quickroom.QRroomaide)) {
1252                 cprintf("%d Higher access required.\n",
1253                         ERROR+HIGHER_ACCESS_REQUIRED);
1254                 return;
1255                 }
1256
1257         targ_slot = (-1);
1258         for (a=0; a<MAXROOMS; ++a) {
1259                 getroom(&qtemp,a);
1260                 if (!strcasecmp(qtemp.QRname,targ)) {
1261                         targ_slot = a;
1262                         a = MAXROOMS;
1263                         }
1264                 }
1265         if (targ_slot < 0) {
1266                 cprintf("%d '%s' does not exist.\n",ERROR,targ);
1267                 return;
1268                 }
1269
1270         /* yank the message out of the current room... */
1271         lgetroom(&CC->quickroom,CC->curr_rm);
1272         get_msglist(CC->curr_rm);
1273
1274         foundit = 0;
1275         for (a=0; a<(CC->num_msgs); ++a) {
1276                 if (MessageFromList(a) == num) {
1277                         foundit = 1;
1278                         SetMessageInList(a, 0L);
1279                         }
1280                 }
1281         if (foundit) {
1282                 CC->num_msgs = sort_msglist(CC->msglist, CC->num_msgs);
1283                 put_msglist(CC->curr_rm);
1284                 CC->quickroom.QRhighest = MessageFromList((CC->num_msgs)-1);
1285                 }
1286         lputroom(&CC->quickroom,CC->curr_rm);
1287         if (!foundit) {
1288                 cprintf("%d msg %ld does not exist.\n",ERROR,num);
1289                 return;
1290                 }
1291
1292         /* put the message into the target room */
1293         lgetroom(&qtemp,targ_slot);
1294         cdbtarg = cdb_fetch(CDB_MSGLISTS, &targ_slot, sizeof(int));
1295         if (cdbtarg != NULL) {
1296                 targmsgs = malloc(cdbtarg->len);
1297                 memcpy(targmsgs, cdbtarg->ptr, cdbtarg->len);
1298                 targ_count = cdbtarg->len / sizeof(long);
1299                 cdb_free(cdbtarg);
1300                 }
1301         else {
1302                 targmsgs = NULL;
1303                 targ_count = 0;
1304                 }
1305
1306         ++targ_count;
1307         targmsgs = realloc(targmsgs, ((CC->num_msgs) * sizeof(long)));
1308         targmsgs[targ_count - 1] = num;
1309         targ_count = sort_msglist(targmsgs, targ_count);
1310         qtemp.QRhighest = targmsgs[targ_count - 1];
1311         cdb_store(CDB_MSGLISTS, &targ_slot, sizeof(int),
1312                         targmsgs, targ_count * sizeof(long));
1313         free(targmsgs);
1314         lputroom(&qtemp,targ_slot);
1315         cprintf("%d ok\n",OK);
1316         }