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