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