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