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