bozo: preserve all options over restart
[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 requires
562  *
563  * #include <sys/types.h>
564  * #include <sys/stat.h>
565  * #include <fcntl.h>
566  * #include <unistd.h>
567  * #include <stdlib.h>
568  *
569  * and has been tested on:
570  *
571  * AIX 4.2
572  * Digital Unix 4.0D
573  * HP-UX 11.0
574  * IRIX 6.5
575  * Linux 2.1.125
576  * Solaris 2.5
577  * Solaris 2.6
578  */
579
580 #ifndef AFS_NT40_ENV
581 static void
582 background(void)
583 {
584     /*
585      * A process is a process group leader if its process ID
586      * (getpid()) and its process group ID (getpgrp()) are the same.
587      */
588
589     /*
590      * To create a new session (and thereby lose our controlling
591      * terminal) we cannot be a process group leader.
592      *
593      * To guarantee we are not a process group leader, we fork and
594      * let the parent process exit.
595      */
596
597     if (getpid() == getpgrp()) {
598         pid_t pid;
599         pid = fork();
600         switch (pid) {
601         case -1:
602             abort();            /* leave footprints */
603             break;
604         case 0:         /* child */
605             break;
606         default:                /* parent */
607             exit(0);
608             break;
609         }
610     }
611
612     /*
613      * By here, we are not a process group leader, so we can make a
614      * new session and become the session leader.
615      */
616
617     {
618         pid_t sid = setsid();
619
620         if (sid == -1) {
621             static char err[] = "bosserver: WARNING: setsid() failed\n";
622             write(STDERR_FILENO, err, sizeof err - 1);
623         }
624     }
625
626     /*
627      * Once we create a new session, the current process is a
628      * session leader without a controlling tty.
629      *
630      * On some systems, the first tty device the session leader
631      * opens automatically becomes the controlling tty for the
632      * session.
633      *
634      * So, to guarantee we do not acquire a controlling tty, we fork
635      * and let the parent process exit.  The child process is not a
636      * session leader, and so it will not acquire a controlling tty
637      * even if it should happen to open a tty device.
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      * check that we no longer have a controlling tty
657      */
658
659     {
660         int fd;
661
662         fd = open("/dev/tty", O_RDONLY);
663
664         if (fd >= 0) {
665             static char err[] =
666                 "bosserver: WARNING: /dev/tty still attached\n";
667             close(fd);
668             write(STDERR_FILENO, err, sizeof err - 1);
669         }
670     }
671 }
672 #endif /* ! AFS_NT40_ENV */
673 #endif
674
675 static char *
676 make_pid_filename(char *ainst, char *aname)
677 {
678     char *buffer = NULL;
679     int length;
680
681     length = strlen(DoPidFiles) + strlen(ainst) + 6;
682     if (aname && *aname) {
683         length += strlen(aname) + 1;
684     }
685     buffer = malloc(length * sizeof(char));
686     if (!buffer) {
687         if (aname) {
688             bozo_Log("Failed to alloc pid filename buffer for %s.%s.\n",
689                      ainst, aname);
690         } else {
691             bozo_Log("Failed to alloc pid filename buffer for %s.\n", ainst);
692         }
693     } else {
694         if (aname && *aname) {
695             snprintf(buffer, length, "%s/%s.%s.pid", DoPidFiles, ainst,
696                      aname);
697         } else {
698             snprintf(buffer, length, "%s/%s.pid", DoPidFiles, ainst);
699         }
700     }
701     return buffer;
702 }
703
704 /**
705  * Write a file containing the pid of the named process.
706  *
707  * @param ainst instance name
708  * @param aname sub-process name of the instance, may be null
709  * @param apid  process id of the newly started process
710  *
711  * @returns status
712  */
713 int
714 bozo_CreatePidFile(char *ainst, char *aname, pid_t apid)
715 {
716     int code = 0;
717     char *pidfile = NULL;
718     FILE *fp;
719
720     pidfile = make_pid_filename(ainst, aname);
721     if (!pidfile) {
722         return ENOMEM;
723     }
724     if ((fp = fopen(pidfile, "w")) == NULL) {
725         bozo_Log("Failed to open pidfile %s; errno=%d\n", pidfile, errno);
726         free(pidfile);
727         return errno;
728     }
729     if (fprintf(fp, "%ld\n", afs_printable_int32_ld(apid)) < 0) {
730         code = errno;
731     }
732     if (fclose(fp) != 0) {
733         code = errno;
734     }
735     free(pidfile);
736     return code;
737 }
738
739 /**
740  * Clean a pid file for a process which just exited.
741  *
742  * @param ainst instance name
743  * @param aname sub-process name of the instance, may be null
744  *
745  * @returns status
746  */
747 int
748 bozo_DeletePidFile(char *ainst, char *aname)
749 {
750     char *pidfile = NULL;
751     pidfile = make_pid_filename(ainst, aname);
752     if (pidfile) {
753         unlink(pidfile);
754         free(pidfile);
755     }
756     return 0;
757 }
758
759 /**
760  * Create the rxbind file of this bosserver.
761  *
762  * @param host  bind address of this server
763  *
764  * @returns status
765  */
766 void
767 bozo_CreateRxBindFile(afs_uint32 host)
768 {
769     char buffer[16];
770     FILE *fp;
771
772     if (host == htonl(INADDR_ANY)) {
773         host = htonl(0x7f000001);
774     }
775
776     afs_inet_ntoa_r(host, buffer);
777     bozo_Log("Listening on %s:%d\n", buffer, AFSCONF_NANNYPORT);
778     if ((fp = fopen(AFSDIR_SERVER_BOZRXBIND_FILEPATH, "w")) == NULL) {
779         bozo_Log("Unable to open rxbind address file: %s, code=%d\n",
780                  AFSDIR_SERVER_BOZRXBIND_FILEPATH, errno);
781     } else {
782         fprintf(fp, "%s\n", buffer);
783         fclose(fp);
784     }
785 }
786
787 /* start a process and monitor it */
788
789 #include "AFS_component_version_number.c"
790
791 int
792 main(int argc, char **argv, char **envp)
793 {
794     struct rx_service *tservice;
795     afs_int32 code;
796     struct afsconf_dir *tdir;
797     int noAuth = 0;
798     int i;
799     char namebuf[AFSDIR_PATH_MAX];
800     int rxMaxMTU = -1;
801     afs_uint32 host = htonl(INADDR_ANY);
802     char *auditFileName = NULL;
803     struct rx_securityClass **securityClasses;
804     afs_int32 numClasses;
805 #ifndef AFS_NT40_ENV
806     int nofork = 0;
807     struct stat sb;
808 #endif
809 #ifdef  AFS_AIX32_ENV
810     struct sigaction nsa;
811
812     /* for some reason, this permits user-mode RX to run a lot faster.
813      * we do it here in the bosserver, so we don't have to do it
814      * individually in each server.
815      */
816     tweak_config();
817
818     /*
819      * The following signal action for AIX is necessary so that in case of a
820      * crash (i.e. core is generated) we can include the user's data section
821      * in the core dump. Unfortunately, by default, only a partial core is
822      * generated which, in many cases, isn't too useful.
823      */
824     sigemptyset(&nsa.sa_mask);
825     nsa.sa_handler = SIG_DFL;
826     nsa.sa_flags = SA_FULLDUMP;
827     sigaction(SIGSEGV, &nsa, NULL);
828     sigaction(SIGABRT, &nsa, NULL);
829 #endif
830     osi_audit_init();
831     signal(SIGFPE, bozo_insecureme);
832
833 #ifdef AFS_NT40_ENV
834     /* Initialize winsock */
835     if (afs_winsockInit() < 0) {
836         ReportErrorEventAlt(AFSEVT_SVR_WINSOCK_INIT_FAILED, 0, argv[0], 0);
837         fprintf(stderr, "%s: Couldn't initialize winsock.\n", argv[0]);
838         exit(2);
839     }
840 #endif
841
842     /* Initialize dirpaths */
843     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
844 #ifdef AFS_NT40_ENV
845         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
846 #endif
847         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
848                 argv[0]);
849         exit(2);
850     }
851
852     /* some path inits */
853     bozo_fileName = AFSDIR_SERVER_BOZCONF_FILEPATH;
854     DoCore = AFSDIR_SERVER_LOGS_DIRPATH;
855
856     /* initialize the list of dirpaths that the bosserver has
857      * an interest in monitoring */
858     initBosEntryStats();
859
860 #if defined(AFS_SGI_ENV)
861     /* offer some protection if AFS isn't loaded */
862     if (syscall(AFS_SYSCALL, AFSOP_ENDLOG) < 0 && errno == ENOPKG) {
863         printf("bosserver: AFS doesn't appear to be configured in O.S..\n");
864         exit(1);
865     }
866 #endif
867
868 #ifndef AFS_NT40_ENV
869     /* save args for restart */
870     bozo_argc = argc;
871     bozo_argv = malloc((argc+1) * sizeof(char*));
872     if (!bozo_argv) {
873         fprintf(stderr, "%s: Failed to allocate argument list.\n", argv[0]);
874         exit(1);
875     }
876     bozo_argv[0] = (char*)AFSDIR_SERVER_BOSVR_FILEPATH; /* expected path */
877     bozo_argv[bozo_argc] = NULL; /* null terminate list */
878 #endif  /* AFS_NT40_ENV */
879
880     /* parse cmd line */
881     for (code = 1; code < argc; code++) {
882 #ifndef AFS_NT40_ENV
883         bozo_argv[code] = argv[code];
884 #endif  /* AFS_NT40_ENV */
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         }
929         else if (strcmp(argv[code], "-auditlog") == 0) {
930             auditFileName = argv[++code];
931
932         } else if (strcmp(argv[code], "-audit-interface") == 0) {
933             char *interface = argv[++code];
934
935             if (osi_audit_interface(interface)) {
936                 printf("Invalid audit interface '%s'\n", interface);
937                 exit(1);
938             }
939         } else if (strncmp(argv[code], "-pidfiles=", 10) == 0) {
940             DoPidFiles = (argv[code]+10);
941         } else if (strncmp(argv[code], "-pidfiles", 9) == 0) {
942             DoPidFiles = AFSDIR_BOSCONFIG_DIR;
943         }
944         else {
945
946             /* hack to support help flag */
947
948 #ifndef AFS_NT40_ENV
949             printf("Usage: bosserver [-noauth] [-log] "
950                    "[-auditlog <log path>] "
951                    "[-audit-interafce <file|sysvmq> (default is file)] "
952                    "[-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals]"
953                    "[-syslog[=FACILITY]] "
954                    "[-restricted] "
955                    "[-enable_peer_stats] [-enable_process_stats] "
956                    "[-cores=<none|path>] \n"
957                    "[-pidfiles[=path]] "
958                    "[-nofork] " "[-help]\n");
959 #else
960             printf("Usage: bosserver [-noauth] [-log] "
961                    "[-auditlog <log path>] "
962                    "[-audit-interafce <file|sysvmq> (default is file)] "
963                    "[-rxmaxmtu <bytes>] [-rxbind] [-allow-dotted-principals]"
964                    "[-restricted] "
965                    "[-enable_peer_stats] [-enable_process_stats] "
966                    "[-cores=<none|path>] \n"
967                    "[-pidfiles[=path]] "
968                    "[-help]\n");
969 #endif
970             fflush(stdout);
971
972             exit(0);
973         }
974     }
975     if (auditFileName) {
976         osi_audit_file(auditFileName);
977     }
978
979 #ifndef AFS_NT40_ENV
980     if (geteuid() != 0) {
981         printf("bosserver: must be run as root.\n");
982         exit(1);
983     }
984 #endif
985
986     code = bnode_Init();
987     if (code) {
988         printf("bosserver: could not init bnode package, code %d\n", code);
989         exit(1);
990     }
991
992     bnode_Register("fs", &fsbnode_ops, 3);
993     bnode_Register("dafs", &dafsbnode_ops, 4);
994     bnode_Register("simple", &ezbnode_ops, 1);
995     bnode_Register("cron", &cronbnode_ops, 2);
996
997     /* create useful dirs */
998     CreateDirs(DoCore);
999
1000     /* chdir to AFS log directory */
1001     if (DoCore)
1002         chdir(DoCore);
1003     else
1004         chdir(AFSDIR_SERVER_LOGS_DIRPATH);
1005
1006 #if 0
1007     fputs(AFS_GOVERNMENT_MESSAGE, stdout);
1008     fflush(stdout);
1009 #endif
1010
1011     /* go into the background and remove our controlling tty, close open
1012        file desriptors
1013      */
1014
1015 #ifndef AFS_NT40_ENV
1016     if (!nofork)
1017         daemon(1, 0);
1018 #endif /* ! AFS_NT40_ENV */
1019
1020     if ((!DoSyslog)
1021 #ifndef AFS_NT40_ENV
1022         && ((lstat(AFSDIR_BOZLOG_FILE, &sb) == 0) &&
1023         !(S_ISFIFO(sb.st_mode)))
1024 #endif
1025         ) {
1026         strcpy(namebuf, AFSDIR_BOZLOG_FILE);
1027         strcat(namebuf, ".old");
1028         renamefile(AFSDIR_BOZLOG_FILE, namebuf);        /* try rename first */
1029         bozo_logFile = fopen(AFSDIR_BOZLOG_FILE, "a");
1030         if (!bozo_logFile) {
1031             printf("bosserver: can't initialize log file (%s).\n",
1032                    AFSDIR_SERVER_BOZLOG_FILEPATH);
1033             exit(1);
1034         }
1035         /* keep log closed normally, so can be removed */
1036         fclose(bozo_logFile);
1037     } else {
1038 #ifndef AFS_NT40_ENV
1039         openlog("bosserver", LOG_PID, DoSyslogFacility);
1040 #endif
1041     }
1042
1043 #if defined(RLIMIT_CORE) && defined(HAVE_GETRLIMIT)
1044     {
1045       struct rlimit rlp;
1046       getrlimit(RLIMIT_CORE, &rlp);
1047       if (!DoCore)
1048           rlp.rlim_cur = 0;
1049       else
1050           rlp.rlim_max = rlp.rlim_cur = RLIM_INFINITY;
1051       setrlimit(RLIMIT_CORE, &rlp);
1052       getrlimit(RLIMIT_CORE, &rlp);
1053       bozo_Log("Core limits now %d %d\n",(int)rlp.rlim_cur,(int)rlp.rlim_max);
1054     }
1055 #endif
1056
1057     /* Write current state of directory permissions to log file */
1058     DirAccessOK();
1059
1060     if (rxBind) {
1061         afs_int32 ccode;
1062         if (AFSDIR_SERVER_NETRESTRICT_FILEPATH ||
1063             AFSDIR_SERVER_NETINFO_FILEPATH) {
1064             char reason[1024];
1065             ccode = parseNetFiles(SHostAddrs, NULL, NULL,
1066                                   ADDRSPERSITE, reason,
1067                                   AFSDIR_SERVER_NETINFO_FILEPATH,
1068                                   AFSDIR_SERVER_NETRESTRICT_FILEPATH);
1069         } else {
1070             ccode = rx_getAllAddr(SHostAddrs, ADDRSPERSITE);
1071         }
1072         if (ccode == 1)
1073             host = SHostAddrs[0];
1074     }
1075
1076     for (i = 0; i < 10; i++) {
1077         if (rxBind) {
1078             code = rx_InitHost(host, htons(AFSCONF_NANNYPORT));
1079         } else {
1080             code = rx_Init(htons(AFSCONF_NANNYPORT));
1081         }
1082         if (code) {
1083             bozo_Log("can't initialize rx: code=%d\n", code);
1084             sleep(3);
1085         } else
1086             break;
1087     }
1088     if (i >= 10) {
1089         bozo_Log("Bos giving up, can't initialize rx\n");
1090         exit(code);
1091     }
1092
1093     code = LWP_CreateProcess(BozoDaemon, BOZO_LWP_STACKSIZE, /* priority */ 1,
1094                              /* param */ NULL , "bozo-the-clown",
1095                              &bozo_pid);
1096
1097     /* try to read the key from the config file */
1098     tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
1099     if (!tdir) {
1100         /* try to create local cell config file */
1101         struct afsconf_cell tcell;
1102         strcpy(tcell.name, "localcell");
1103         tcell.numServers = 1;
1104         code = gethostname(tcell.hostName[0], MAXHOSTCHARS);
1105         if (code) {
1106             bozo_Log("failed to get hostname, code %d\n", errno);
1107             exit(1);
1108         }
1109         if (tcell.hostName[0][0] == 0) {
1110             bozo_Log("host name not set, can't start\n");
1111             bozo_Log("try the 'hostname' command\n");
1112             exit(1);
1113         }
1114         memset(tcell.hostAddr, 0, sizeof(tcell.hostAddr));      /* not computed */
1115         code =
1116             afsconf_SetCellInfo(bozo_confdir, AFSDIR_SERVER_ETC_DIRPATH,
1117                                 &tcell);
1118         if (code) {
1119             bozo_Log
1120                 ("could not create cell database in '%s' (code %d), quitting\n",
1121                  AFSDIR_SERVER_ETC_DIRPATH, code);
1122             exit(1);
1123         }
1124         tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
1125         if (!tdir) {
1126             bozo_Log
1127                 ("failed to open newly-created cell database, quitting\n");
1128             exit(1);
1129         }
1130     }
1131
1132     /* read init file, starting up programs */
1133     if ((code = ReadBozoFile(0))) {
1134         bozo_Log
1135             ("bosserver: Something is wrong (%d) with the bos configuration file %s; aborting\n",
1136              code, AFSDIR_SERVER_BOZCONF_FILEPATH);
1137         exit(code);
1138     }
1139
1140     bozo_CreateRxBindFile(host);        /* for local scripts */
1141
1142     /* opened the cell databse */
1143     bozo_confdir = tdir;
1144
1145     /* allow super users to manage RX statistics */
1146     rx_SetRxStatUserOk(bozo_rxstat_userok);
1147
1148     afsconf_SetNoAuthFlag(tdir, noAuth);
1149     afsconf_BuildServerSecurityObjects(tdir, &securityClasses, &numClasses);
1150
1151     if (DoPidFiles) {
1152         bozo_CreatePidFile("bosserver", NULL, getpid());
1153     }
1154
1155     /* Disable jumbograms */
1156     rx_SetNoJumbo();
1157
1158     if (rxMaxMTU != -1) {
1159         if (rx_SetMaxMTU(rxMaxMTU) != 0) {
1160             bozo_Log("bosserver: rxMaxMTU %d is invalid\n", rxMaxMTU);
1161             exit(1);
1162         }
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 }