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