bos: Don't cast returns from malloc()
[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 /**
103  * Return true if this name is a member of the local realm.
104  */
105 int
106 bozo_IsLocalRealmMatch(void *rock, char *name, char *inst, char *cell)
107 {
108     struct afsconf_dir *dir = (struct afsconf_dir *)rock;
109     afs_int32 islocal = 0;      /* default to no */
110     int code;
111
112     code = afsconf_IsLocalRealmMatch(dir, &islocal, name, inst, cell);
113     if (code) {
114         bozo_Log("Failed local realm check; code=%d, name=%s, inst=%s, cell=%s\n",
115                  code, name, inst, cell);
116     }
117     return islocal;
118 }
119
120 /* restart bozo process */
121 int
122 bozo_ReBozo(void)
123 {
124 #ifdef AFS_NT40_ENV
125     /* exit with restart code; SCM integrator process will restart bosserver with
126        the same arguments */
127     exit(BOSEXIT_RESTART);
128 #else
129     /* exec new bosserver process */
130     int i = 0;
131
132     /* close random fd's */
133     for (i = 3; i < 64; i++) {
134         close(i);
135     }
136
137     unlink(AFSDIR_SERVER_BOZRXBIND_FILEPATH);
138
139     execv(bozo_argv[0], bozo_argv);     /* should not return */
140     _exit(1);
141 #endif /* AFS_NT40_ENV */
142 }
143
144 /* make sure a dir exists */
145 static int
146 MakeDir(const char *adir)
147 {
148     struct stat tstat;
149     afs_int32 code;
150     if (stat(adir, &tstat) < 0 || (tstat.st_mode & S_IFMT) != S_IFDIR) {
151         int reqPerm;
152         unlink(adir);
153         reqPerm = GetRequiredDirPerm(adir);
154         if (reqPerm == -1)
155             reqPerm = 0777;
156 #ifdef AFS_NT40_ENV
157         /* underlying filesystem may not support directory protection */
158         code = mkdir(adir);
159 #else
160         code = mkdir(adir, reqPerm);
161 #endif
162         return code;
163     }
164     return 0;
165 }
166
167 /* create all the bozo dirs */
168 static int
169 CreateDirs(const char *coredir)
170 {
171     if ((!strncmp
172          (AFSDIR_USR_DIRPATH, AFSDIR_CLIENT_ETC_DIRPATH,
173           strlen(AFSDIR_USR_DIRPATH)))
174         ||
175         (!strncmp
176          (AFSDIR_USR_DIRPATH, AFSDIR_SERVER_BIN_DIRPATH,
177           strlen(AFSDIR_USR_DIRPATH)))) {
178         MakeDir(AFSDIR_USR_DIRPATH);
179     }
180     if (!strncmp
181         (AFSDIR_SERVER_AFS_DIRPATH, AFSDIR_SERVER_BIN_DIRPATH,
182          strlen(AFSDIR_SERVER_AFS_DIRPATH))) {
183         MakeDir(AFSDIR_SERVER_AFS_DIRPATH);
184     }
185     MakeDir(AFSDIR_SERVER_BIN_DIRPATH);
186     MakeDir(AFSDIR_SERVER_ETC_DIRPATH);
187     MakeDir(AFSDIR_SERVER_LOCAL_DIRPATH);
188     MakeDir(AFSDIR_SERVER_DB_DIRPATH);
189     MakeDir(AFSDIR_SERVER_LOGS_DIRPATH);
190 #ifndef AFS_NT40_ENV
191     if (!strncmp
192         (AFSDIR_CLIENT_VICE_DIRPATH, AFSDIR_CLIENT_ETC_DIRPATH,
193          strlen(AFSDIR_CLIENT_VICE_DIRPATH))) {
194         MakeDir(AFSDIR_CLIENT_VICE_DIRPATH);
195     }
196     MakeDir(AFSDIR_CLIENT_ETC_DIRPATH);
197
198     symlink(AFSDIR_SERVER_THISCELL_FILEPATH, AFSDIR_CLIENT_THISCELL_FILEPATH);
199     symlink(AFSDIR_SERVER_CELLSERVDB_FILEPATH,
200             AFSDIR_CLIENT_CELLSERVDB_FILEPATH);
201 #endif /* AFS_NT40_ENV */
202     if (coredir)
203         MakeDir(coredir);
204     return 0;
205 }
206
207 /* strip the \\n from the end of the line, if it is present */
208 static int
209 StripLine(char *abuffer)
210 {
211     char *tp;
212
213     tp = abuffer + strlen(abuffer);     /* starts off pointing at the null  */
214     if (tp == abuffer)
215         return 0;               /* null string, no last character to check */
216     tp--;                       /* aim at last character */
217     if (*tp == '\n')
218         *tp = 0;
219     return 0;
220 }
221
222 /* write one bnode's worth of entry into the file */
223 static int
224 bzwrite(struct bnode *abnode, void *arock)
225 {
226     struct bztemp *at = (struct bztemp *)arock;
227     int i;
228     char tbuffer[BOZO_BSSIZE];
229     afs_int32 code;
230
231     if (abnode->notifier)
232         fprintf(at->file, "bnode %s %s %d %s\n", abnode->type->name,
233                 abnode->name, abnode->fileGoal, abnode->notifier);
234     else
235         fprintf(at->file, "bnode %s %s %d\n", abnode->type->name,
236                 abnode->name, abnode->fileGoal);
237     for (i = 0;; i++) {
238         code = bnode_GetParm(abnode, i, tbuffer, BOZO_BSSIZE);
239         if (code) {
240             if (code != BZDOM)
241                 return code;
242             break;
243         }
244         fprintf(at->file, "parm %s\n", tbuffer);
245     }
246     fprintf(at->file, "end\n");
247     return 0;
248 }
249
250 #define MAXPARMS    20
251 int
252 ReadBozoFile(char *aname)
253 {
254     FILE *tfile;
255     char tbuffer[BOZO_BSSIZE];
256     char *tp;
257     char *instp, *typep, *notifier, *notp;
258     afs_int32 code;
259     afs_int32 ktmask, ktday, kthour, ktmin, ktsec;
260     afs_int32 i, goal;
261     struct bnode *tb;
262     char *parms[MAXPARMS];
263     char *thisparms[MAXPARMS];
264     int rmode;
265
266     /* rename BozoInit to BosServer for the user */
267     if (!aname) {
268         /* if BozoInit exists and BosConfig doesn't, try a rename */
269         if (access(AFSDIR_SERVER_BOZINIT_FILEPATH, 0) == 0
270             && access(AFSDIR_SERVER_BOZCONF_FILEPATH, 0) != 0) {
271             code =
272                 renamefile(AFSDIR_SERVER_BOZINIT_FILEPATH,
273                            AFSDIR_SERVER_BOZCONF_FILEPATH);
274             if (code < 0)
275                 perror("bosconfig rename");
276         }
277         if (access(AFSDIR_SERVER_BOZCONFNEW_FILEPATH, 0) == 0) {
278             code =
279                 renamefile(AFSDIR_SERVER_BOZCONFNEW_FILEPATH,
280                            AFSDIR_SERVER_BOZCONF_FILEPATH);
281             if (code < 0)
282                 perror("bosconfig rename");
283         }
284     }
285
286     /* don't do server restarts by default */
287     bozo_nextRestartKT.mask = KTIME_NEVER;
288     bozo_nextRestartKT.hour = 0;
289     bozo_nextRestartKT.min = 0;
290     bozo_nextRestartKT.day = 0;
291
292     /* restart processes at 5am if their binaries have changed */
293     bozo_nextDayKT.mask = KTIME_HOUR | KTIME_MIN;
294     bozo_nextDayKT.hour = 5;
295     bozo_nextDayKT.min = 0;
296
297     for (code = 0; code < MAXPARMS; code++)
298         parms[code] = NULL;
299     tfile = (FILE *) 0;
300     if (!aname)
301         aname = (char *)bozo_fileName;
302     tfile = fopen(aname, "r");
303     if (!tfile)
304         return 0;               /* -1 */
305     instp = malloc(BOZO_BSSIZE);
306     typep = malloc(BOZO_BSSIZE);
307     notifier = notp = malloc(BOZO_BSSIZE);
308     while (1) {
309         /* ok, read lines giving parms and such from the file */
310         tp = fgets(tbuffer, sizeof(tbuffer), tfile);
311         if (tp == (char *)0)
312             break;              /* all done */
313
314         if (strncmp(tbuffer, "restarttime", 11) == 0) {
315             code =
316                 sscanf(tbuffer, "restarttime %d %d %d %d %d", &ktmask, &ktday,
317                        &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_nextRestartKT.mask = ktmask;
325             bozo_nextRestartKT.day = ktday;
326             bozo_nextRestartKT.hour = kthour;
327             bozo_nextRestartKT.min = ktmin;
328             bozo_nextRestartKT.sec = ktsec;
329             continue;
330         }
331
332         if (strncmp(tbuffer, "checkbintime", 12) == 0) {
333             code =
334                 sscanf(tbuffer, "checkbintime %d %d %d %d %d", &ktmask,
335                        &ktday, &kthour, &ktmin, &ktsec);
336             if (code != 5) {
337                 code = -1;
338                 goto fail;
339             }
340             /* otherwise we've read in the proper ktime structure; now assign
341              * it and continue processing */
342             bozo_nextDayKT.mask = ktmask;       /* time to restart the system */
343             bozo_nextDayKT.day = ktday;
344             bozo_nextDayKT.hour = kthour;
345             bozo_nextDayKT.min = ktmin;
346             bozo_nextDayKT.sec = ktsec;
347             continue;
348         }
349
350         if (strncmp(tbuffer, "restrictmode", 12) == 0) {
351             code = sscanf(tbuffer, "restrictmode %d", &rmode);
352             if (code != 1) {
353                 code = -1;
354                 goto fail;
355             }
356             if (rmode != 0 && rmode != 1) {
357                 code = -1;
358                 goto fail;
359             }
360             bozo_isrestricted = rmode;
361             continue;
362         }
363
364         if (strncmp("bnode", tbuffer, 5) != 0) {
365             code = -1;
366             goto fail;
367         }
368         notifier = notp;
369         code =
370             sscanf(tbuffer, "bnode %s %s %d %s", typep, instp, &goal,
371                    notifier);
372         if (code < 3) {
373             code = -1;
374             goto fail;
375         } else if (code == 3)
376             notifier = NULL;
377
378         memset(thisparms, 0, sizeof(thisparms));
379
380         for (i = 0; i < MAXPARMS; i++) {
381             /* now read the parms, until we see an "end" line */
382             tp = fgets(tbuffer, sizeof(tbuffer), tfile);
383             if (!tp) {
384                 code = -1;
385                 goto fail;
386             }
387             StripLine(tbuffer);
388             if (!strncmp(tbuffer, "end", 3))
389                 break;
390             if (strncmp(tbuffer, "parm ", 5)) {
391                 code = -1;
392                 goto fail;      /* no "parm " either */
393             }
394             if (!parms[i])      /* make sure there's space */
395                 parms[i] = malloc(BOZO_BSSIZE);
396             strcpy(parms[i], tbuffer + 5);      /* remember the parameter for later */
397             thisparms[i] = parms[i];
398         }
399
400         /* ok, we have the type and parms, now create the object */
401         code =
402             bnode_Create(typep, instp, &tb, thisparms[0], thisparms[1],
403                          thisparms[2], thisparms[3], thisparms[4], notifier,
404                          goal ? BSTAT_NORMAL : BSTAT_SHUTDOWN, 0);
405         if (code)
406             goto fail;
407
408         /* bnode created in 'temporarily shutdown' state;
409          * check to see if we are supposed to run this guy,
410          * and if so, start the process up */
411         if (goal) {
412             bnode_SetStat(tb, BSTAT_NORMAL);    /* set goal, taking effect immediately */
413         } else {
414             bnode_SetStat(tb, BSTAT_SHUTDOWN);
415         }
416     }
417     /* all done */
418     code = 0;
419
420   fail:
421     if (instp)
422         free(instp);
423     if (typep)
424         free(typep);
425     for (i = 0; i < MAXPARMS; i++)
426         if (parms[i])
427             free(parms[i]);
428     if (tfile)
429         fclose(tfile);
430     return code;
431 }
432
433 /* write a new bozo file */
434 int
435 WriteBozoFile(char *aname)
436 {
437     FILE *tfile;
438     char tbuffer[AFSDIR_PATH_MAX];
439     afs_int32 code;
440     struct bztemp btemp;
441
442     if (!aname)
443         aname = (char *)bozo_fileName;
444     strcpy(tbuffer, aname);
445     strcat(tbuffer, ".NBZ");
446     tfile = fopen(tbuffer, "w");
447     if (!tfile)
448         return -1;
449     btemp.file = tfile;
450
451     fprintf(tfile, "restrictmode %d\n", bozo_isrestricted);
452     fprintf(tfile, "restarttime %d %d %d %d %d\n", bozo_nextRestartKT.mask,
453             bozo_nextRestartKT.day, bozo_nextRestartKT.hour,
454             bozo_nextRestartKT.min, bozo_nextRestartKT.sec);
455     fprintf(tfile, "checkbintime %d %d %d %d %d\n", bozo_nextDayKT.mask,
456             bozo_nextDayKT.day, bozo_nextDayKT.hour, bozo_nextDayKT.min,
457             bozo_nextDayKT.sec);
458     code = bnode_ApplyInstance(bzwrite, &btemp);
459     if (code || (code = ferror(tfile))) {       /* something went wrong */
460         fclose(tfile);
461         unlink(tbuffer);
462         return code;
463     }
464     /* close the file, check for errors and snap new file into place */
465     if (fclose(tfile) == EOF) {
466         unlink(tbuffer);
467         return -1;
468     }
469     code = renamefile(tbuffer, aname);
470     if (code) {
471         unlink(tbuffer);
472         return -1;
473     }
474     return 0;
475 }
476
477 static int
478 bdrestart(struct bnode *abnode, void *arock)
479 {
480     afs_int32 code;
481
482     if (abnode->fileGoal != BSTAT_NORMAL || abnode->goal != BSTAT_NORMAL)
483         return 0;               /* don't restart stopped bnodes */
484     bnode_Hold(abnode);
485     code = bnode_RestartP(abnode);
486     if (code) {
487         /* restart the dude */
488         bnode_SetStat(abnode, BSTAT_SHUTDOWN);
489         bnode_WaitStatus(abnode, BSTAT_SHUTDOWN);
490         bnode_SetStat(abnode, BSTAT_NORMAL);
491     }
492     bnode_Release(abnode);
493     return 0;                   /* keep trying all bnodes */
494 }
495
496 #define BOZO_MINSKIP 3600       /* minimum to advance clock */
497 /* lwp to handle system restarts */
498 static void *
499 BozoDaemon(void *unused)
500 {
501     afs_int32 now;
502
503     /* now initialize the values */
504     bozo_newKTs = 1;
505     while (1) {
506         IOMGR_Sleep(60);
507         now = FT_ApproxTime();
508
509         if (bozo_restdisable) {
510             bozo_Log("Restricted mode disabled by signal\n");
511             bozo_restdisable = 0;
512         }
513
514         if (bozo_newKTs) {      /* need to recompute restart times */
515             bozo_newKTs = 0;    /* done for a while */
516             nextRestart = ktime_next(&bozo_nextRestartKT, BOZO_MINSKIP);
517             nextDay = ktime_next(&bozo_nextDayKT, BOZO_MINSKIP);
518         }
519
520         /* see if we should do a restart */
521         if (now > nextRestart) {
522             SBOZO_ReBozo(0);    /* doesn't come back */
523         }
524
525         /* see if we should restart a server */
526         if (now > nextDay) {
527             nextDay = ktime_next(&bozo_nextDayKT, BOZO_MINSKIP);
528
529             /* call the bnode restartp function, and restart all that require it */
530             bnode_ApplyInstance(bdrestart, 0);
531         }
532     }
533     return NULL;
534 }
535
536 #ifdef AFS_AIX32_ENV
537 static int
538 tweak_config(void)
539 {
540     FILE *f;
541     char c[80];
542     int s, sb_max, ipfragttl;
543
544     sb_max = 131072;
545     ipfragttl = 20;
546     f = popen("/usr/sbin/no -o sb_max", "r");
547     s = fscanf(f, "sb_max = %d", &sb_max);
548     fclose(f);
549     if (s < 1)
550         return;
551     f = popen("/usr/sbin/no -o ipfragttl", "r");
552     s = fscanf(f, "ipfragttl = %d", &ipfragttl);
553     fclose(f);
554     if (s < 1)
555         ipfragttl = 20;
556
557     if (sb_max < 131072)
558         sb_max = 131072;
559     if (ipfragttl > 20)
560         ipfragttl = 20;
561
562     sprintf(c, "/usr/sbin/no -o sb_max=%d -o ipfragttl=%d", sb_max,
563             ipfragttl);
564     f = popen(c, "r");
565     fclose(f);
566 }
567 #endif
568
569 #if 0
570 /*
571  * This routine causes the calling process to go into the background and
572  * to lose its controlling tty.
573  *
574  * It does not close or otherwise alter the standard file descriptors.
575  *
576  * It writes warning messages to the standard error output if certain
577  * fundamental errors occur.
578  *
579  * This routine has been tested on:
580  *
581  * AIX 4.2
582  * Digital Unix 4.0D
583  * HP-UX 11.0
584  * IRIX 6.5
585  * Linux 2.1.125
586  * Solaris 2.5
587  * Solaris 2.6
588  */
589
590 #ifndef AFS_NT40_ENV
591 static void
592 background(void)
593 {
594     /*
595      * A process is a process group leader if its process ID
596      * (getpid()) and its process group ID (getpgrp()) are the same.
597      */
598
599     /*
600      * To create a new session (and thereby lose our controlling
601      * terminal) we cannot be a process group leader.
602      *
603      * To guarantee we are not a process group leader, we fork and
604      * let the parent process exit.
605      */
606
607     if (getpid() == getpgrp()) {
608         pid_t pid;
609         pid = fork();
610         switch (pid) {
611         case -1:
612             abort();            /* leave footprints */
613             break;
614         case 0:         /* child */
615             break;
616         default:                /* parent */
617             exit(0);
618             break;
619         }
620     }
621
622     /*
623      * By here, we are not a process group leader, so we can make a
624      * new session and become the session leader.
625      */
626
627     {
628         pid_t sid = setsid();
629
630         if (sid == -1) {
631             static char err[] = "bosserver: WARNING: setsid() failed\n";
632             write(STDERR_FILENO, err, sizeof err - 1);
633         }
634     }
635
636     /*
637      * Once we create a new session, the current process is a
638      * session leader without a controlling tty.
639      *
640      * On some systems, the first tty device the session leader
641      * opens automatically becomes the controlling tty for the
642      * session.
643      *
644      * So, to guarantee we do not acquire a controlling tty, we fork
645      * and let the parent process exit.  The child process is not a
646      * session leader, and so it will not acquire a controlling tty
647      * even if it should happen to open a tty device.
648      */
649
650     if (getpid() == getpgrp()) {
651         pid_t pid;
652         pid = fork();
653         switch (pid) {
654         case -1:
655             abort();            /* leave footprints */
656             break;
657         case 0:         /* child */
658             break;
659         default:                /* parent */
660             exit(0);
661             break;
662         }
663     }
664
665     /*
666      * check that we no longer have a controlling tty
667      */
668
669     {
670         int fd;
671
672         fd = open("/dev/tty", O_RDONLY);
673
674         if (fd >= 0) {
675             static char err[] =
676                 "bosserver: WARNING: /dev/tty still attached\n";
677             close(fd);
678             write(STDERR_FILENO, err, sizeof err - 1);
679         }
680     }
681 }
682 #endif /* ! AFS_NT40_ENV */
683 #endif
684
685 static char *
686 make_pid_filename(char *ainst, char *aname)
687 {
688     char *buffer = NULL;
689
690     if (aname && *aname) {
691         asprintf(&buffer, "%s/%s.%s.pid", DoPidFiles, ainst, aname);
692         if (buffer == NULL)
693             bozo_Log("Failed to alloc pid filename buffer for %s.%s.\n",
694                      ainst, aname);
695     } else {
696         asprintf(&buffer, "%s/%s.pid", DoPidFiles, ainst);
697         if (buffer == NULL)
698             bozo_Log("Failed to alloc pid filename buffer for %s.\n", 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     /* Disable jumbograms */
1094     rx_SetNoJumbo();
1095
1096     if (rxMaxMTU != -1) {
1097         if (rx_SetMaxMTU(rxMaxMTU) != 0) {
1098             bozo_Log("bosserver: rxMaxMTU %d is invalid\n", rxMaxMTU);
1099             exit(1);
1100         }
1101     }
1102
1103     code = LWP_CreateProcess(BozoDaemon, BOZO_LWP_STACKSIZE, /* priority */ 1,
1104                              /* param */ NULL , "bozo-the-clown",
1105                              &bozo_pid);
1106
1107     /* try to read the key from the config file */
1108     tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
1109     if (!tdir) {
1110         /* try to create local cell config file */
1111         struct afsconf_cell tcell;
1112         strcpy(tcell.name, "localcell");
1113         tcell.numServers = 1;
1114         code = gethostname(tcell.hostName[0], MAXHOSTCHARS);
1115         if (code) {
1116             bozo_Log("failed to get hostname, code %d\n", errno);
1117             exit(1);
1118         }
1119         if (tcell.hostName[0][0] == 0) {
1120             bozo_Log("host name not set, can't start\n");
1121             bozo_Log("try the 'hostname' command\n");
1122             exit(1);
1123         }
1124         memset(tcell.hostAddr, 0, sizeof(tcell.hostAddr));      /* not computed */
1125         code =
1126             afsconf_SetCellInfo(bozo_confdir, AFSDIR_SERVER_ETC_DIRPATH,
1127                                 &tcell);
1128         if (code) {
1129             bozo_Log
1130                 ("could not create cell database in '%s' (code %d), quitting\n",
1131                  AFSDIR_SERVER_ETC_DIRPATH, code);
1132             exit(1);
1133         }
1134         tdir = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH);
1135         if (!tdir) {
1136             bozo_Log
1137                 ("failed to open newly-created cell database, quitting\n");
1138             exit(1);
1139         }
1140     }
1141
1142     /* initialize audit user check */
1143     osi_audit_set_user_check(tdir, bozo_IsLocalRealmMatch);
1144
1145     /* read init file, starting up programs */
1146     if ((code = ReadBozoFile(0))) {
1147         bozo_Log
1148             ("bosserver: Something is wrong (%d) with the bos configuration file %s; aborting\n",
1149              code, AFSDIR_SERVER_BOZCONF_FILEPATH);
1150         exit(code);
1151     }
1152
1153     bozo_CreateRxBindFile(host);        /* for local scripts */
1154
1155     /* opened the cell databse */
1156     bozo_confdir = tdir;
1157
1158     /* allow super users to manage RX statistics */
1159     rx_SetRxStatUserOk(bozo_rxstat_userok);
1160
1161     afsconf_SetNoAuthFlag(tdir, noAuth);
1162     afsconf_BuildServerSecurityObjects(tdir, &securityClasses, &numClasses);
1163
1164     if (DoPidFiles) {
1165         bozo_CreatePidFile("bosserver", NULL, getpid());
1166     }
1167
1168     tservice = rx_NewServiceHost(host, 0, /* service id */ 1,
1169                                  "bozo", securityClasses, numClasses,
1170                                  BOZO_ExecuteRequest);
1171     rx_SetMinProcs(tservice, 2);
1172     rx_SetMaxProcs(tservice, 4);
1173     rx_SetStackSize(tservice, BOZO_LWP_STACKSIZE);      /* so gethostbyname works (in cell stuff) */
1174     if (rxkadDisableDotCheck) {
1175         rx_SetSecurityConfiguration(tservice, RXS_CONFIG_FLAGS,
1176                                     (void *)RXS_CONFIG_FLAGS_DISABLE_DOTCHECK);
1177     }
1178
1179     tservice =
1180         rx_NewServiceHost(host, 0, RX_STATS_SERVICE_ID, "rpcstats",
1181                           securityClasses, numClasses, RXSTATS_ExecuteRequest);
1182     rx_SetMinProcs(tservice, 2);
1183     rx_SetMaxProcs(tservice, 4);
1184     rx_StartServer(1);          /* donate this process */
1185     return 0;
1186 }
1187
1188 void
1189 bozo_Log(char *format, ...)
1190 {
1191     char tdate[27];
1192     time_t myTime;
1193     va_list ap;
1194
1195     va_start(ap, format);
1196
1197     if (DoSyslog) {
1198 #ifndef AFS_NT40_ENV
1199         vsyslog(LOG_INFO, format, ap);
1200 #endif
1201     } else {
1202         myTime = time(0);
1203         strcpy(tdate, ctime(&myTime));  /* copy out of static area asap */
1204         tdate[24] = ':';
1205
1206         /* log normally closed, so can be removed */
1207
1208         bozo_logFile = fopen(AFSDIR_SERVER_BOZLOG_FILEPATH, "a");
1209         if (bozo_logFile == NULL) {
1210             printf("bosserver: WARNING: problem with %s\n",
1211                    AFSDIR_SERVER_BOZLOG_FILEPATH);
1212             printf("%s ", tdate);
1213             vprintf(format, ap);
1214             fflush(stdout);
1215         } else {
1216             fprintf(bozo_logFile, "%s ", tdate);
1217             vfprintf(bozo_logFile, format, ap);
1218
1219             /* close so rm BosLog works */
1220             fclose(bozo_logFile);
1221         }
1222     }
1223 }