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