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