rxkad-v5-dot-check-20080122
[openafs.git] / src / bozo / bosserver.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 RCSID
14     ("$Header$");
15
16 #include <afs/stds.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <errno.h>
21 #include <string.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdarg.h>
25 #ifdef AFS_NT40_ENV
26 #include <winsock2.h>
27 #include <direct.h>
28 #include <io.h>
29 #include <WINNT/afsevent.h>
30 #else
31 #include <unistd.h>
32 #include <netinet/in.h>
33 #include <syslog.h>
34 #endif /* AFS_NT40_ENV */
35 #include <afs/cellconfig.h>
36 #include <rx/rx.h>
37 #include <rx/xdr.h>
38 #include <rx/rx_globals.h>
39 #include "bosint.h"
40 #include "bnode.h"
41 #include "bosprototypes.h"
42 #include <rx/rxkad.h>
43 #include <afs/keys.h>
44 #include <afs/ktime.h>
45 #include <afs/afsutil.h>
46 #include <afs/fileutil.h>
47 #include <afs/procmgmt.h>       /* signal(), kill(), wait(), etc. */
48 #if defined(AFS_SGI_ENV)
49 #include <afs/afs_args.h>
50 #endif
51
52 #define BOZO_LWP_STACKSIZE      16000
53 extern int BOZO_ExecuteRequest();
54 extern int RXSTATS_ExecuteRequest();
55 extern struct bnode_ops fsbnode_ops, dafsbnode_ops, ezbnode_ops, cronbnode_ops;
56
57 struct afsconf_dir *bozo_confdir = 0;   /* bozo configuration dir */
58 static PROCESS bozo_pid;
59 struct rx_securityClass *bozo_rxsc[3];
60 const char *bozo_fileName;
61 FILE *bozo_logFile;
62
63 int DoLogging = 0;
64 int DoSyslog = 0;
65 #ifndef AFS_NT40_ENV
66 int DoSyslogFacility = LOG_DAEMON;
67 #endif
68 static afs_int32 nextRestart;
69 static afs_int32 nextDay;
70
71 struct ktime bozo_nextRestartKT, bozo_nextDayKT;
72 int bozo_newKTs;
73 int rxBind = 0;
74 int rxkadDisableDotCheck = 0;
75
76 #define ADDRSPERSITE 16         /* Same global is in rx/rx_user.c */
77 afs_uint32 SHostAddrs[ADDRSPERSITE];
78
79 #ifdef BOS_RESTRICTED_MODE
80 int bozo_isrestricted = 0;
81 int bozo_restdisable = 0;
82
83 void
84 bozo_insecureme(int sig)
85 {
86     signal(SIGFPE, bozo_insecureme);
87     bozo_isrestricted = 0;
88     bozo_restdisable = 1;
89 }
90 #endif
91
92 struct bztemp {
93     FILE *file;
94 };
95
96 /* check whether caller is authorized to manage RX statistics */
97 int
98 bozo_rxstat_userok(struct rx_call *call)
99 {
100     return afsconf_SuperUser(bozo_confdir, call, NULL);
101 }
102
103 /* restart bozo process */
104 int
105 bozo_ReBozo()
106 {
107 #ifdef AFS_NT40_ENV
108     /* exit with restart code; SCM integrator process will restart bosserver */
109     int status = BOSEXIT_RESTART;
110
111     /* if noauth flag is set, pass "-noauth" to new bosserver */
112     if (afsconf_GetNoAuthFlag(bozo_confdir)) {
113         status |= BOSEXIT_NOAUTH_FLAG;
114     }
115     /* if logging is on, pass "-log" to new bosserver */
116     if (DoLogging) {
117         status |= BOSEXIT_LOGGING_FLAG;
118     }
119     exit(status);
120 #else
121     /* exec new bosserver process */
122     char *argv[4];
123     int i = 0;
124
125     argv[i] = (char *)AFSDIR_SERVER_BOSVR_FILEPATH;
126     i++;
127
128     /* if noauth flag is set, pass "-noauth" to new bosserver */
129     if (afsconf_GetNoAuthFlag(bozo_confdir)) {
130         argv[i] = "-noauth";
131         i++;
132     }
133     /* if logging is on, pass "-log" to new bosserver */
134     if (DoLogging) {
135         argv[i] = "-log";
136         i++;
137     }
138 #ifndef AFS_NT40_ENV
139     /* if syslog logging is on, pass "-syslog" to new bosserver */
140     if (DoSyslog) {
141         char *arg = (char *)malloc(40); /* enough for -syslog=# */
142         if (DoSyslogFacility != LOG_DAEMON) {
143             snprintf(arg, 40, "-syslog=%d", DoSyslogFacility);
144         } else {
145             strcpy(arg, "-syslog");
146         }
147         argv[i] = arg;
148         i++;
149     }
150 #endif
151
152     /* null-terminate argument list */
153     argv[i] = NULL;
154
155     /* close random fd's */
156     for (i = 3; i < 64; i++) {
157         close(i);
158     }
159
160     execv(argv[0], argv);       /* should not return */
161     _exit(1);
162 #endif /* AFS_NT40_ENV */
163 }
164
165 /* make sure a dir exists */
166 static int
167 MakeDir(const char *adir)
168 {
169     struct stat tstat;
170     register afs_int32 code;
171     if (stat(adir, &tstat) < 0 || (tstat.st_mode & S_IFMT) != S_IFDIR) {
172         int reqPerm;
173         unlink(adir);
174         reqPerm = GetRequiredDirPerm(adir);
175         if (reqPerm == -1)
176             reqPerm = 0777;
177 #ifdef AFS_NT40_ENV
178         /* underlying filesystem may not support directory protection */
179         code = mkdir(adir);
180 #else
181         code = mkdir(adir, reqPerm);
182 #endif
183         return code;
184     }
185     return 0;
186 }
187
188 /* create all the bozo dirs */
189 static int
190 CreateDirs()
191 {
192     if ((!strncmp
193          (AFSDIR_USR_DIRPATH, AFSDIR_CLIENT_ETC_DIRPATH,
194           strlen(AFSDIR_USR_DIRPATH)))
195         ||
196         (!strncmp
197          (AFSDIR_USR_DIRPATH, AFSDIR_SERVER_BIN_DIRPATH,
198           strlen(AFSDIR_USR_DIRPATH)))) {
199         MakeDir(AFSDIR_USR_DIRPATH);
200     }
201     if (!strncmp
202         (AFSDIR_SERVER_AFS_DIRPATH, AFSDIR_SERVER_BIN_DIRPATH,
203          strlen(AFSDIR_SERVER_AFS_DIRPATH))) {
204         MakeDir(AFSDIR_SERVER_AFS_DIRPATH);
205     }
206     MakeDir(AFSDIR_SERVER_BIN_DIRPATH);
207     MakeDir(AFSDIR_SERVER_ETC_DIRPATH);
208     MakeDir(AFSDIR_SERVER_LOCAL_DIRPATH);
209     MakeDir(AFSDIR_SERVER_DB_DIRPATH);
210     MakeDir(AFSDIR_SERVER_LOGS_DIRPATH);
211 #ifndef AFS_NT40_ENV
212     if (!strncmp
213         (AFSDIR_CLIENT_VICE_DIRPATH, AFSDIR_CLIENT_ETC_DIRPATH,
214          strlen(AFSDIR_CLIENT_VICE_DIRPATH))) {
215         MakeDir(AFSDIR_CLIENT_VICE_DIRPATH);
216     }
217     MakeDir(AFSDIR_CLIENT_ETC_DIRPATH);
218
219     symlink(AFSDIR_SERVER_THISCELL_FILEPATH, AFSDIR_CLIENT_THISCELL_FILEPATH);
220     symlink(AFSDIR_SERVER_CELLSERVDB_FILEPATH,
221             AFSDIR_CLIENT_CELLSERVDB_FILEPATH);
222 #endif /* AFS_NT40_ENV */
223     return 0;
224 }
225
226 /* strip the \\n from the end of the line, if it is present */
227 static int
228 StripLine(register char *abuffer)
229 {
230     register char *tp;
231
232     tp = abuffer + strlen(abuffer);     /* starts off pointing at the null  */
233     if (tp == abuffer)
234         return 0;               /* null string, no last character to check */
235     tp--;                       /* aim at last character */
236     if (*tp == '\n')
237         *tp = 0;
238     return 0;
239 }
240
241 /* write one bnode's worth of entry into the file */
242 static
243 bzwrite(register struct bnode *abnode, register struct bztemp *at)
244 {
245     register int i;
246     char tbuffer[BOZO_BSSIZE];
247     register afs_int32 code;
248
249     if (abnode->notifier)
250         fprintf(at->file, "bnode %s %s %d %s\n", abnode->type->name,
251                 abnode->name, abnode->fileGoal, abnode->notifier);
252     else
253         fprintf(at->file, "bnode %s %s %d\n", abnode->type->name,
254                 abnode->name, abnode->fileGoal);
255     for (i = 0;; i++) {
256         code = bnode_GetParm(abnode, i, tbuffer, BOZO_BSSIZE);
257         if (code) {
258             if (code != BZDOM)
259                 return code;
260             break;
261         }
262         fprintf(at->file, "parm %s\n", tbuffer);
263     }
264     fprintf(at->file, "end\n");
265     return 0;
266 }
267
268 #define MAXPARMS    20
269 int
270 ReadBozoFile(char *aname)
271 {
272     register FILE *tfile;
273     char tbuffer[BOZO_BSSIZE];
274     register char *tp;
275     char *instp, *typep, *notifier, *notp;
276     register afs_int32 code;
277     afs_int32 ktmask, ktday, kthour, ktmin, ktsec;
278     afs_int32 i, goal;
279     struct bnode *tb;
280     char *parms[MAXPARMS];
281 #ifdef BOS_RESTRICTED_MODE
282     int rmode;
283 #endif
284
285     /* rename BozoInit to BosServer for the user */
286     if (!aname) {
287         /* if BozoInit exists and BosConfig doesn't, try a rename */
288         if (access(AFSDIR_SERVER_BOZINIT_FILEPATH, 0) == 0
289             && access(AFSDIR_SERVER_BOZCONF_FILEPATH, 0) != 0) {
290             code =
291                 renamefile(AFSDIR_SERVER_BOZINIT_FILEPATH,
292                            AFSDIR_SERVER_BOZCONF_FILEPATH);
293             if (code < 0)
294                 perror("bosconfig rename");
295         }
296 #ifdef BOS_NEW_CONFIG
297         if (access(AFSDIR_SERVER_BOZCONFNEW_FILEPATH, 0) == 0) {
298             code =
299                 renamefile(AFSDIR_SERVER_BOZCONFNEW_FILEPATH,
300                            AFSDIR_SERVER_BOZCONF_FILEPATH);
301             if (code < 0)
302                 perror("bosconfig rename");
303         }
304 #endif
305     }
306
307     /* setup default times we want to do restarts */
308     bozo_nextRestartKT.mask = KTIME_HOUR | KTIME_MIN | KTIME_DAY;
309     bozo_nextRestartKT.hour = 4;        /* 4 am */
310     bozo_nextRestartKT.min = 0;
311     bozo_nextRestartKT.day = 0; /* Sunday */
312     bozo_nextDayKT.mask = KTIME_HOUR | KTIME_MIN;
313     bozo_nextDayKT.hour = 5;
314     bozo_nextDayKT.min = 0;
315
316     for (code = 0; code < MAXPARMS; code++)
317         parms[code] = NULL;
318     instp = typep = notifier = NULL;
319     tfile = (FILE *) 0;
320     if (!aname)
321         aname = (char *)bozo_fileName;
322     tfile = fopen(aname, "r");
323     if (!tfile)
324         return 0;               /* -1 */
325     instp = (char *)malloc(BOZO_BSSIZE);
326     typep = (char *)malloc(BOZO_BSSIZE);
327     notifier = notp = (char *)malloc(BOZO_BSSIZE);
328     while (1) {
329         /* ok, read lines giving parms and such from the file */
330         tp = fgets(tbuffer, sizeof(tbuffer), tfile);
331         if (tp == (char *)0)
332             break;              /* all done */
333
334         if (strncmp(tbuffer, "restarttime", 11) == 0) {
335             code =
336                 sscanf(tbuffer, "restarttime %d %d %d %d %d", &ktmask, &ktday,
337                        &kthour, &ktmin, &ktsec);
338             if (code != 5) {
339                 code = -1;
340                 goto fail;
341             }
342             /* otherwise we've read in the proper ktime structure; now assign
343              * it and continue processing */
344             bozo_nextRestartKT.mask = ktmask;
345             bozo_nextRestartKT.day = ktday;
346             bozo_nextRestartKT.hour = kthour;
347             bozo_nextRestartKT.min = ktmin;
348             bozo_nextRestartKT.sec = ktsec;
349             continue;
350         }
351
352         if (strncmp(tbuffer, "checkbintime", 12) == 0) {
353             code =
354                 sscanf(tbuffer, "checkbintime %d %d %d %d %d", &ktmask,
355                        &ktday, &kthour, &ktmin, &ktsec);
356             if (code != 5) {
357                 code = -1;
358                 goto fail;
359             }
360             /* otherwise we've read in the proper ktime structure; now assign
361              * it and continue processing */
362             bozo_nextDayKT.mask = ktmask;       /* time to restart the system */
363             bozo_nextDayKT.day = ktday;
364             bozo_nextDayKT.hour = kthour;
365             bozo_nextDayKT.min = ktmin;
366             bozo_nextDayKT.sec = ktsec;
367             continue;
368         }
369 #ifdef BOS_RESTRICTED_MODE
370         if (strncmp(tbuffer, "restrictmode", 12) == 0) {
371             code = sscanf(tbuffer, "restrictmode %d", &rmode);
372             if (code != 1) {
373                 code = -1;
374                 goto fail;
375             }
376             if (rmode != 0 && rmode != 1) {
377                 code = -1;
378                 goto fail;
379             }
380             bozo_isrestricted = rmode;
381             continue;
382         }
383 #endif
384
385         if (strncmp("bnode", tbuffer, 5) != 0) {
386             code = -1;
387             goto fail;
388         }
389         notifier = notp;
390         code =
391             sscanf(tbuffer, "bnode %s %s %d %s", typep, instp, &goal,
392                    notifier);
393         if (code < 3) {
394             code = -1;
395             goto fail;
396         } else if (code == 3)
397             notifier = NULL;
398
399         for (i = 0; i < MAXPARMS; i++) {
400             /* now read the parms, until we see an "end" line */
401             tp = fgets(tbuffer, sizeof(tbuffer), tfile);
402             if (!tp) {
403                 code = -1;
404                 goto fail;
405             }
406             StripLine(tbuffer);
407             if (!strncmp(tbuffer, "end", 3))
408                 break;
409             if (strncmp(tbuffer, "parm ", 5)) {
410                 code = -1;
411                 goto fail;      /* no "parm " either */
412             }
413             if (!parms[i])      /* make sure there's space */
414                 parms[i] = (char *)malloc(BOZO_BSSIZE);
415             strcpy(parms[i], tbuffer + 5);      /* remember the parameter for later */
416         }
417
418         /* ok, we have the type and parms, now create the object */
419         code =
420             bnode_Create(typep, instp, &tb, parms[0], parms[1], parms[2],
421                          parms[3], parms[4], notifier,
422                          goal ? BSTAT_NORMAL : BSTAT_SHUTDOWN, 0);
423         if (code)
424             goto fail;
425
426         /* bnode created in 'temporarily shutdown' state;
427          * check to see if we are supposed to run this guy,
428          * and if so, start the process up */
429         if (goal) {
430             bnode_SetStat(tb, BSTAT_NORMAL);    /* set goal, taking effect immediately */
431         } else {
432             bnode_SetStat(tb, BSTAT_SHUTDOWN);
433         }
434     }
435     /* all done */
436     code = 0;
437
438   fail:
439     if (instp)
440         free(instp);
441     if (typep)
442         free(typep);
443     for (i = 0; i < MAXPARMS; i++)
444         if (parms[i])
445             free(parms[i]);
446     if (tfile)
447         fclose(tfile);
448     return code;
449 }
450
451 /* write a new bozo file */
452 int
453 WriteBozoFile(char *aname)
454 {
455     register FILE *tfile;
456     char tbuffer[AFSDIR_PATH_MAX];
457     register afs_int32 code;
458     struct bztemp btemp;
459
460     if (!aname)
461         aname = (char *)bozo_fileName;
462     strcpy(tbuffer, aname);
463     strcat(tbuffer, ".NBZ");
464     tfile = fopen(tbuffer, "w");
465     if (!tfile)
466         return -1;
467     btemp.file = tfile;
468 #ifdef BOS_RESTRICTED_MODE
469     fprintf(tfile, "restrictmode %d\n", bozo_isrestricted);
470 #endif
471     fprintf(tfile, "restarttime %d %d %d %d %d\n", bozo_nextRestartKT.mask,
472             bozo_nextRestartKT.day, bozo_nextRestartKT.hour,
473             bozo_nextRestartKT.min, bozo_nextRestartKT.sec);
474     fprintf(tfile, "checkbintime %d %d %d %d %d\n", bozo_nextDayKT.mask,
475             bozo_nextDayKT.day, bozo_nextDayKT.hour, bozo_nextDayKT.min,
476             bozo_nextDayKT.sec);
477     code = bnode_ApplyInstance(bzwrite, &btemp);
478     if (code || (code = ferror(tfile))) {       /* something went wrong */
479         fclose(tfile);
480         unlink(tbuffer);
481         return code;
482     }
483     /* close the file, check for errors and snap new file into place */
484     if (fclose(tfile) == EOF) {
485         unlink(tbuffer);
486         return -1;
487     }
488     code = renamefile(tbuffer, aname);
489     if (code) {
490         unlink(tbuffer);
491         return -1;
492     }
493     return 0;
494 }
495
496 static int
497 bdrestart(register struct bnode *abnode, char *arock)
498 {
499     register afs_int32 code;
500
501     if (abnode->fileGoal != BSTAT_NORMAL || abnode->goal != BSTAT_NORMAL)
502         return 0;               /* don't restart stopped bnodes */
503     bnode_Hold(abnode);
504     code = bnode_RestartP(abnode);
505     if (code) {
506         /* restart the dude */
507         bnode_SetStat(abnode, BSTAT_SHUTDOWN);
508         bnode_WaitStatus(abnode, BSTAT_SHUTDOWN);
509         bnode_SetStat(abnode, BSTAT_NORMAL);
510     }
511     bnode_Release(abnode);
512     return 0;                   /* keep trying all bnodes */
513 }
514
515 #define BOZO_MINSKIP 3600       /* minimum to advance clock */
516 /* lwp to handle system restarts */
517 static int
518 BozoDaemon()
519 {
520     register afs_int32 now;
521
522     /* now initialize the values */
523     bozo_newKTs = 1;
524     while (1) {
525         IOMGR_Sleep(60);
526         now = FT_ApproxTime();
527
528 #ifdef BOS_RESTRICTED_MODE
529         if (bozo_restdisable) {
530             bozo_Log("Restricted mode disabled by signal\n");
531             bozo_restdisable = 0;
532         }
533 #endif
534         if (bozo_newKTs) {      /* need to recompute restart times */
535             bozo_newKTs = 0;    /* done for a while */
536             nextRestart = ktime_next(&bozo_nextRestartKT, BOZO_MINSKIP);
537             nextDay = ktime_next(&bozo_nextDayKT, BOZO_MINSKIP);
538         }
539
540         /* see if we should do a restart */
541         if (now > nextRestart) {
542             SBOZO_ReBozo(0);    /* doesn't come back */
543         }
544
545         /* see if we should restart a server */
546         if (now > nextDay) {
547             nextDay = ktime_next(&bozo_nextDayKT, BOZO_MINSKIP);
548
549             /* call the bnode restartp function, and restart all that require it */
550             bnode_ApplyInstance(bdrestart, 0);
551         }
552     }
553 }
554
555 #ifdef AFS_AIX32_ENV
556 static int
557 tweak_config()
558 {
559     FILE *f;
560     char c[80];
561     int s, sb_max, ipfragttl;
562
563     sb_max = 131072;
564     ipfragttl = 20;
565     f = popen("/usr/sbin/no -o sb_max", "r");
566     s = fscanf(f, "sb_max = %d", &sb_max);
567     fclose(f);
568     if (s < 1)
569         return;
570     f = popen("/usr/sbin/no -o ipfragttl", "r");
571     s = fscanf(f, "ipfragttl = %d", &ipfragttl);
572     fclose(f);
573     if (s < 1)
574         ipfragttl = 20;
575
576     if (sb_max < 131072)
577         sb_max = 131072;
578     if (ipfragttl > 20)
579         ipfragttl = 20;
580
581     sprintf(c, "/usr/sbin/no -o sb_max=%d -o ipfragttl=%d", sb_max,
582             ipfragttl);
583     f = popen(c, "r");
584     fclose(f);
585 }
586 #endif
587
588 #if 0
589 /*
590  * This routine causes the calling process to go into the background and
591  * to lose its controlling tty.
592  *
593  * It does not close or otherwise alter the standard file descriptors.
594  *
595  * It writes warning messages to the standard error output if certain
596  * fundamental errors occur.
597  *
598  * This routine requires
599  * 
600  * #include <sys/types.h>
601  * #include <sys/stat.h>
602  * #include <fcntl.h>
603  * #include <unistd.h>
604  * #include <stdlib.h>
605  *
606  * and has been tested on:
607  *
608  * AIX 4.2
609  * Digital Unix 4.0D
610  * HP-UX 11.0
611  * IRIX 6.5
612  * Linux 2.1.125
613  * Solaris 2.5
614  * Solaris 2.6
615  */
616
617 #ifndef AFS_NT40_ENV
618 static void
619 background(void)
620 {
621     /* 
622      * A process is a process group leader if its process ID
623      * (getpid()) and its process group ID (getpgrp()) are the same.
624      */
625
626     /*
627      * To create a new session (and thereby lose our controlling
628      * terminal) we cannot be a process group leader.
629      *
630      * To guarantee we are not a process group leader, we fork and
631      * let the parent process exit.
632      */
633
634     if (getpid() == getpgrp()) {
635         pid_t pid;
636         pid = fork();
637         switch (pid) {
638         case -1:
639             abort();            /* leave footprints */
640             break;
641         case 0:         /* child */
642             break;
643         default:                /* parent */
644             exit(0);
645             break;
646         }
647     }
648
649     /*
650      * By here, we are not a process group leader, so we can make a
651      * new session and become the session leader.
652      */
653
654     {
655         pid_t sid = setsid();
656
657         if (sid == -1) {
658             static char err[] = "bosserver: WARNING: setsid() failed\n";
659             write(STDERR_FILENO, err, sizeof err - 1);
660         }
661     }
662
663     /*
664      * Once we create a new session, the current process is a
665      * session leader without a controlling tty.
666      *
667      * On some systems, the first tty device the session leader
668      * opens automatically becomes the controlling tty for the
669      * session.
670      *
671      * So, to guarantee we do not acquire a controlling tty, we fork
672      * and let the parent process exit.  The child process is not a
673      * session leader, and so it will not acquire a controlling tty
674      * even if it should happen to open a tty device.
675      */
676
677     if (getpid() == getpgrp()) {
678         pid_t pid;
679         pid = fork();
680         switch (pid) {
681         case -1:
682             abort();            /* leave footprints */
683             break;
684         case 0:         /* child */
685             break;
686         default:                /* parent */
687             exit(0);
688             break;
689         }
690     }
691
692     /*
693      * check that we no longer have a controlling tty
694      */
695
696     {
697         int fd;
698
699         fd = open("/dev/tty", O_RDONLY);
700
701         if (fd >= 0) {
702             static char err[] =
703                 "bosserver: WARNING: /dev/tty still attached\n";
704             close(fd);
705             write(STDERR_FILENO, err, sizeof err - 1);
706         }
707     }
708 }
709 #endif /* ! AFS_NT40_ENV */
710 #endif
711
712 /* start a process and monitor it */
713
714 #include "AFS_component_version_number.c"
715
716 int
717 main(int argc, char **argv, char **envp)
718 {
719     struct rx_service *tservice;
720     register afs_int32 code;
721     struct afsconf_dir *tdir;
722     int noAuth = 0;
723     int i;
724     char namebuf[AFSDIR_PATH_MAX];
725     int rxMaxMTU = -1;
726     afs_uint32 host = htonl(INADDR_ANY);
727 #ifndef AFS_NT40_ENV
728     int nofork = 0;
729     struct stat sb;
730 #endif
731 #ifdef  AFS_AIX32_ENV
732     struct sigaction nsa;
733
734     /* for some reason, this permits user-mode RX to run a lot faster.
735      * we do it here in the bosserver, so we don't have to do it 
736      * individually in each server.
737      */
738     tweak_config();
739
740     /*
741      * The following signal action for AIX is necessary so that in case of a 
742      * crash (i.e. core is generated) we can include the user's data section 
743      * in the core dump. Unfortunately, by default, only a partial core is
744      * generated which, in many cases, isn't too useful.
745      */
746     sigemptyset(&nsa.sa_mask);
747     nsa.sa_handler = SIG_DFL;
748     nsa.sa_flags = SA_FULLDUMP;
749     sigaction(SIGSEGV, &nsa, NULL);
750     sigaction(SIGABRT, &nsa, NULL);
751 #endif
752     osi_audit_init();
753 #ifdef BOS_RESTRICTED_MODE
754     signal(SIGFPE, bozo_insecureme);
755 #endif
756
757 #ifdef AFS_NT40_ENV
758     /* Initialize winsock */
759     if (afs_winsockInit() < 0) {
760         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
761         fprintf(stderr, "%s: Couldn't initialize winsock.\n", argv[0]);
762         exit(2);
763     }
764 #endif
765
766     /* Initialize dirpaths */
767     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
768 #ifdef AFS_NT40_ENV
769         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
770 #endif
771         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
772                 argv[0]);
773         exit(2);
774     }
775
776     /* some path inits */
777     bozo_fileName = AFSDIR_SERVER_BOZCONF_FILEPATH;
778
779     /* initialize the list of dirpaths that the bosserver has
780      * an interest in monitoring */
781     initBosEntryStats();
782
783 #if defined(AFS_SGI_ENV)
784     /* offer some protection if AFS isn't loaded */
785     if (syscall(AFS_SYSCALL, AFSOP_ENDLOG) < 0 && errno == ENOPKG) {
786         printf("bosserver: AFS doesn't appear to be configured in O.S..\n");
787         exit(1);
788     }
789 #endif
790
791     /* parse cmd line */
792     for (code = 1; code < argc; code++) {
793         if (strcmp(argv[code], "-noauth") == 0) {
794             /* set noauth flag */
795             noAuth = 1;
796         } else if (strcmp(argv[code], "-log") == 0) {
797             /* set extra logging flag */
798             DoLogging = 1;
799         }
800 #ifndef AFS_NT40_ENV
801         else if (strcmp(argv[code], "-syslog") == 0) {
802             /* set syslog logging flag */
803             DoSyslog = 1;
804         } else if (strncmp(argv[code], "-syslog=", 8) == 0) {
805             DoSyslog = 1;
806             DoSyslogFacility = atoi(argv[code] + 8);
807         } else if (strcmp(argv[code], "-nofork") == 0) {
808             nofork = 1;
809         }
810 #endif
811         else if (strcmp(argv[code], "-enable_peer_stats") == 0) {
812             rx_enablePeerRPCStats();
813         } else if (strcmp(argv[code], "-enable_process_stats") == 0) {
814             rx_enableProcessRPCStats();
815         }
816 #ifdef BOS_RESTRICTED_MODE
817         else if (strcmp(argv[code], "-restricted") == 0) {
818             bozo_isrestricted = 1;
819         }
820 #endif
821         else if (strcmp(argv[code], "-rxbind") == 0) {
822             rxBind = 1;
823         }
824         else if (strcmp(argv[code], "-allow-dotted-principals") == 0) {
825             rxkadDisableDotCheck = 1;
826         }
827         else if (!strcmp(argv[i], "-rxmaxmtu")) {
828             if ((i + 1) >= argc) {
829                 fprintf(stderr, "missing argument for -rxmaxmtu\n"); 
830                 exit(1); 
831             }
832             rxMaxMTU = atoi(argv[++i]);
833             if ((rxMaxMTU < RX_MIN_PACKET_SIZE) || 
834                 (rxMaxMTU > RX_MAX_PACKET_DATA_SIZE)) {
835                 printf("rxMaxMTU %d% invalid; must be between %d-%d\n",
836                         rxMaxMTU, RX_MIN_PACKET_SIZE, 
837                         RX_MAX_PACKET_DATA_SIZE);
838                 exit(1);
839             }
840         }
841         else if (strcmp(argv[code], "-auditlog") == 0) {
842             int tempfd, flags;
843             FILE *auditout;
844             char oldName[MAXPATHLEN];
845             char *fileName = argv[++code];
846
847 #ifndef AFS_NT40_ENV
848             struct stat statbuf;
849             
850             if ((lstat(fileName, &statbuf) == 0) 
851                 && (S_ISFIFO(statbuf.st_mode))) {
852                 flags = O_WRONLY | O_NONBLOCK;
853             } else 
854 #endif
855             {
856                 strcpy(oldName, fileName);
857                 strcat(oldName, ".old");
858                 renamefile(fileName, oldName);
859                 flags = O_WRONLY | O_TRUNC | O_CREAT;
860             }
861             tempfd = open(fileName, flags, 0666);
862             if (tempfd > -1) {
863                 auditout = fdopen(tempfd, "a");
864                 if (auditout) {
865                     osi_audit_file(auditout);
866                 } else
867                     printf("Warning: auditlog %s not writable, ignored.\n", fileName);
868             } else
869                 printf("Warning: auditlog %s not writable, ignored.\n", fileName);
870         }
871         else {
872
873             /* hack to support help flag */
874
875 #ifndef AFS_NT40_ENV
876             printf("Usage: bosserver [-noauth] [-log] "
877                    "[-auditlog <log path>] "
878                    "[-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals]"
879                    "[-syslog[=FACILITY]] "
880                    "[-enable_peer_stats] [-enable_process_stats] "
881                    "[-nofork] " "[-help]\n");
882 #else
883             printf("Usage: bosserver [-noauth] [-log] "
884                    "[-auditlog <log path>] "
885                    "[-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals]"
886                    "[-enable_peer_stats] [-enable_process_stats] "
887                    "[-help]\n");
888 #endif
889             fflush(stdout);
890
891             exit(0);
892         }
893     }
894
895 #ifndef AFS_NT40_ENV
896     if (geteuid() != 0) {
897         printf("bosserver: must be run as root.\n");
898         exit(1);
899     }
900 #endif
901
902     code = bnode_Init();
903     if (code) {
904         printf("bosserver: could not init bnode package, code %d\n", code);
905         exit(1);
906     }
907
908     bnode_Register("fs", &fsbnode_ops, 3);
909     bnode_Register("dafs", &dafsbnode_ops, 4);
910     bnode_Register("simple", &ezbnode_ops, 1);
911     bnode_Register("cron", &cronbnode_ops, 2);
912
913     /* create useful dirs */
914     CreateDirs();
915
916     /* chdir to AFS log directory */
917     chdir(AFSDIR_SERVER_LOGS_DIRPATH);
918
919 #if 0
920     fputs(AFS_GOVERNMENT_MESSAGE, stdout);
921     fflush(stdout);
922 #endif
923
924     /* go into the background and remove our controlling tty, close open 
925        file desriptors
926      */
927
928 #ifndef AFS_NT40_ENV
929     if (!nofork)
930         daemon(1, 0);
931 #endif /* ! AFS_NT40_ENV */
932
933     if ((!DoSyslog)
934 #ifndef AFS_NT40_ENV
935         && ((lstat(AFSDIR_BOZLOG_FILE, &sb) == 0) && 
936         !(S_ISFIFO(sb.st_mode)))
937 #endif
938         ) {
939         strcpy(namebuf, AFSDIR_BOZLOG_FILE);
940         strcat(namebuf, ".old");
941         renamefile(AFSDIR_BOZLOG_FILE, namebuf);        /* try rename first */
942         bozo_logFile = fopen(AFSDIR_BOZLOG_FILE, "a");
943         if (!bozo_logFile) {
944             printf("bosserver: can't initialize log file (%s).\n",
945                    AFSDIR_SERVER_BOZLOG_FILEPATH);
946             exit(1);
947         }
948         /* keep log closed normally, so can be removed */
949         fclose(bozo_logFile);
950     } else {
951 #ifndef AFS_NT40_ENV
952         openlog("bosserver", LOG_PID, DoSyslogFacility);
953 #endif
954     }
955
956     /* Write current state of directory permissions to log file */
957     DirAccessOK();
958
959     for (i = 0; i < 10; i++) {
960         code = rx_Init(htons(AFSCONF_NANNYPORT));
961         if (code) {
962             bozo_Log("can't initialize rx: code=%d\n", code);
963             sleep(3);
964         } else
965             break;
966     }
967     if (i >= 10) {
968         bozo_Log("Bos giving up, can't initialize rx\n");
969         exit(code);
970     }
971
972     code = LWP_CreateProcess(BozoDaemon, BOZO_LWP_STACKSIZE, /* priority */ 1,
973                              (void *) /*parm */ 0, "bozo-the-clown",
974                              &bozo_pid);
975
976     /* try to read the key from the config file */
977     tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
978     if (!tdir) {
979         /* try to create local cell config file */
980         struct afsconf_cell tcell;
981         strcpy(tcell.name, "localcell");
982         tcell.numServers = 1;
983         code = gethostname(tcell.hostName[0], MAXHOSTCHARS);
984         if (code) {
985             bozo_Log("failed to get hostname, code %d\n", errno);
986             exit(1);
987         }
988         if (tcell.hostName[0][0] == 0) {
989             bozo_Log("host name not set, can't start\n");
990             bozo_Log("try the 'hostname' command\n");
991             exit(1);
992         }
993         memset(tcell.hostAddr, 0, sizeof(tcell.hostAddr));      /* not computed */
994         code =
995             afsconf_SetCellInfo(bozo_confdir, AFSDIR_SERVER_ETC_DIRPATH,
996                                 &tcell);
997         if (code) {
998             bozo_Log
999                 ("could not create cell database in '%s' (code %d), quitting\n",
1000                  AFSDIR_SERVER_ETC_DIRPATH, code);
1001             exit(1);
1002         }
1003         tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
1004         if (!tdir) {
1005             bozo_Log
1006                 ("failed to open newly-created cell database, quitting\n");
1007             exit(1);
1008         }
1009     }
1010
1011     /* read init file, starting up programs */
1012     if (code = ReadBozoFile(0)) {
1013         bozo_Log
1014             ("bosserver: Something is wrong (%d) with the bos configuration file %s; aborting\n",
1015              code, AFSDIR_SERVER_BOZCONF_FILEPATH);
1016         exit(code);
1017     }
1018
1019     /* opened the cell databse */
1020     bozo_confdir = tdir;
1021
1022     /* allow super users to manage RX statistics */
1023     rx_SetRxStatUserOk(bozo_rxstat_userok);
1024
1025     /* have bcrypt key now */
1026
1027     afsconf_SetNoAuthFlag(tdir, noAuth);
1028
1029     bozo_rxsc[0] = rxnull_NewServerSecurityObject();
1030     bozo_rxsc[1] = (struct rx_securityClass *)0;
1031     bozo_rxsc[2] =
1032         rxkad_NewServerSecurityObject(0, tdir, afsconf_GetKey, NULL);
1033
1034     /* Disable jumbograms */
1035     rx_SetNoJumbo();
1036
1037     if (rxMaxMTU != -1) {
1038         rx_SetMaxMTU(rxMaxMTU);
1039     }
1040
1041     if (rxBind) {
1042         afs_int32 ccode;
1043 #ifndef AFS_NT40_ENV
1044         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH || 
1045             AFSDIR_SERVER_NETINFO_FILEPATH) {
1046             char reason[1024];
1047             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
1048                                            ADDRSPERSITE, reason,
1049                                            AFSDIR_SERVER_NETINFO_FILEPATH,
1050                                            AFSDIR_SERVER_NETRESTRICT_FILEPATH);
1051         } else 
1052 #endif  
1053         {
1054             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
1055         }
1056         if (ccode == 1) 
1057             host = SHostAddrs[0];
1058     }
1059
1060     tservice = rx_NewServiceHost(host,  /* port */ 0, /* service id */ 1,
1061                              /*service name */ "bozo",
1062                              /* security classes */
1063                              bozo_rxsc,
1064                              /* numb sec classes */ 3, BOZO_ExecuteRequest);
1065     rx_SetMinProcs(tservice, 2);
1066     rx_SetMaxProcs(tservice, 4);
1067     rx_SetStackSize(tservice, BOZO_LWP_STACKSIZE);      /* so gethostbyname works (in cell stuff) */
1068     if (rxkadDisableDotCheck) {
1069         rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
1070                                     (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK, 
1071                                     NULL);
1072     }
1073
1074     tservice =
1075         rx_NewServiceHost(host, 0, RX_STATS_SERVICE_ID, "rpcstats", bozo_rxsc,
1076                           3, RXSTATS_ExecuteRequest);
1077     rx_SetMinProcs(tservice, 2);
1078     rx_SetMaxProcs(tservice, 4);
1079     rx_StartServer(1);          /* donate this process */
1080     return 0;
1081 }
1082
1083 void
1084 bozo_Log(char *format, ...)
1085 {
1086     char tdate[27];
1087     time_t myTime;
1088     va_list ap;
1089
1090     va_start(ap, format);
1091
1092     if (DoSyslog) {
1093 #ifndef AFS_NT40_ENV
1094         vsyslog(LOG_INFO, format, ap);
1095 #endif
1096     } else {
1097         myTime = time(0);
1098         strcpy(tdate, ctime(&myTime));  /* copy out of static area asap */
1099         tdate[24] = ':';
1100
1101         /* log normally closed, so can be removed */
1102
1103         bozo_logFile = fopen(AFSDIR_SERVER_BOZLOG_FILEPATH, "a");
1104         if (bozo_logFile == NULL) {
1105             printf("bosserver: WARNING: problem with %s\n",
1106                    AFSDIR_SERVER_BOZLOG_FILEPATH);
1107             printf("%s ", tdate);
1108             vprintf(format, ap);
1109             fflush(stdout);
1110         } else {
1111             fprintf(bozo_logFile, "%s ", tdate);
1112             vfprintf(bozo_logFile, format, ap);
1113
1114             /* close so rm BosLog works */
1115             fclose(bozo_logFile);
1116         }
1117     }
1118 }