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