Use asprintf for string construction
[openafs.git] / src / bozo / bnode.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
13 #include <afs/procmgmt.h>
14 #include <roken.h>
15
16 #include <stddef.h>
17
18 #include <lwp.h>
19 #include <rx/rx.h>
20 #include <afs/audit.h>
21 #include <afs/afsutil.h>
22 #include <afs/fileutil.h>
23
24 #include "bnode.h"
25 #include "bosprototypes.h"
26
27 #ifndef WCOREDUMP
28 #define WCOREDUMP(x) ((x) & 0200)
29 #endif
30
31 #define BNODE_LWP_STACKSIZE     (16 * 1024)
32 #define BNODE_ERROR_COUNT_MAX   16   /* maximum number of retries */
33
34 int bnode_waiting = 0;
35 static PROCESS bproc_pid;       /* pid of waker-upper */
36 static struct bnode *allBnodes = 0;     /* list of all bnodes */
37 static struct bnode_proc *allProcs = 0; /* list of all processes for which we're waiting */
38 static struct bnode_type *allTypes = 0; /* list of registered type handlers */
39
40 static struct bnode_stats {
41     int weirdPids;
42 } bnode_stats;
43
44 extern const char *DoCore;
45 extern const char *DoPidFiles;
46 #ifndef AFS_NT40_ENV
47 extern char **environ;          /* env structure */
48 #endif
49
50 int hdl_notifier(struct bnode_proc *tp);
51
52 /* Remember the name of the process, if any, that failed last */
53 static void
54 RememberProcName(struct bnode_proc *ap)
55 {
56     struct bnode *tbnodep;
57
58     tbnodep = ap->bnode;
59     if (tbnodep->lastErrorName) {
60         free(tbnodep->lastErrorName);
61         tbnodep->lastErrorName = NULL;
62     }
63     if (ap->coreName)
64         tbnodep->lastErrorName = strdup(ap->coreName);
65 }
66
67 /* utility for use by BOP_HASCORE functions to determine where a core file might
68  * be stored.
69  */
70 int
71 bnode_CoreName(struct bnode *abnode, char *acoreName, char *abuffer)
72 {
73     if (DoCore) {
74         strcpy(abuffer, DoCore);
75         strcat(abuffer, "/");
76         strcat(abuffer, AFSDIR_CORE_FILE);
77     } else
78         strcpy(abuffer, AFSDIR_SERVER_CORELOG_FILEPATH);
79     if (acoreName) {
80         strcat(abuffer, acoreName);
81         strcat(abuffer, ".");
82     }
83     strcat(abuffer, abnode->name);
84     return 0;
85 }
86
87 /* save core file, if any */
88 static void
89 SaveCore(struct bnode *abnode, struct bnode_proc
90          *aproc)
91 {
92     char tbuffer[256];
93     struct stat tstat;
94     afs_int32 code = 0;
95     char *corefile = NULL;
96 #ifdef BOZO_SAVE_CORES
97     struct timeval Start;
98     struct tm *TimeFields;
99     char FileName[256];
100 #endif
101
102     /* Linux always appends the PID to core dumps from threaded processes, so
103      * we have to scan the directory to find core files under another name. */
104     if (DoCore) {
105         strcpy(tbuffer, DoCore);
106         strcat(tbuffer, "/");
107         strcat(tbuffer, AFSDIR_CORE_FILE);
108     } else
109         code = stat(AFSDIR_SERVER_CORELOG_FILEPATH, &tstat);
110     if (code) {
111         DIR *logdir;
112         struct dirent *file;
113         unsigned long pid;
114         const char *coredir = AFSDIR_LOGS_DIR;
115
116         if (DoCore)
117           coredir = DoCore;
118
119         logdir = opendir(coredir);
120         if (logdir == NULL)
121             return;
122         while ((file = readdir(logdir)) != NULL) {
123             if (strncmp(file->d_name, "core.", 5) != 0)
124                 continue;
125             pid = atol(file->d_name + 5);
126             if (pid == aproc->pid) {
127                 asprintf(&corefile, "%s/%s", coredir, file->d_name);
128                 if (corefile == NULL) {
129                     closedir(logdir);
130                     return;
131                 }
132                 code = 0;
133                 break;
134             }
135         }
136         closedir(logdir);
137     } else {
138         corefile = strdup(tbuffer);
139     }
140     if (code)
141         return;
142
143     bnode_CoreName(abnode, aproc->coreName, tbuffer);
144 #ifdef BOZO_SAVE_CORES
145     FT_GetTimeOfDay(&Start, 0);
146     TimeFields = localtime(&Start.tv_sec);
147     sprintf(FileName, "%s.%d%02d%02d%02d%02d%02d", tbuffer,
148             TimeFields->tm_year + 1900, TimeFields->tm_mon + 1, TimeFields->tm_mday,
149             TimeFields->tm_hour, TimeFields->tm_min, TimeFields->tm_sec);
150     strcpy(tbuffer, FileName);
151 #endif
152     code = renamefile(corefile, tbuffer);
153     free(corefile);
154 }
155
156 int
157 bnode_GetString(struct bnode *abnode, char *abuffer,
158                 afs_int32 alen)
159 {
160     return BOP_GETSTRING(abnode, abuffer, alen);
161 }
162
163 int
164 bnode_GetParm(struct bnode *abnode, afs_int32 aindex,
165               char *abuffer, afs_int32 alen)
166 {
167     return BOP_GETPARM(abnode, aindex, abuffer, alen);
168 }
169
170 int
171 bnode_GetStat(struct bnode *abnode, afs_int32 * astatus)
172 {
173     return BOP_GETSTAT(abnode, astatus);
174 }
175
176 int
177 bnode_RestartP(struct bnode *abnode)
178 {
179     return BOP_RESTARTP(abnode);
180 }
181
182 static int
183 bnode_Check(struct bnode *abnode)
184 {
185     if (abnode->flags & BNODE_WAIT) {
186         abnode->flags &= ~BNODE_WAIT;
187         LWP_NoYieldSignal(abnode);
188     }
189     return 0;
190 }
191
192 /* tell if an instance has a core file */
193 int
194 bnode_HasCore(struct bnode *abnode)
195 {
196     return BOP_HASCORE(abnode);
197 }
198
199 /* wait for all bnodes to stabilize */
200 int
201 bnode_WaitAll(void)
202 {
203     struct bnode *tb;
204     afs_int32 code;
205     afs_int32 stat;
206
207   retry:
208     for (tb = allBnodes; tb; tb = tb->next) {
209         bnode_Hold(tb);
210         code = BOP_GETSTAT(tb, &stat);
211         if (code) {
212             bnode_Release(tb);
213             return code;
214         }
215         if (stat != tb->goal) {
216             tb->flags |= BNODE_WAIT;
217             LWP_WaitProcess(tb);
218             bnode_Release(tb);
219             goto retry;
220         }
221         bnode_Release(tb);
222     }
223     return 0;
224 }
225
226 /* wait until bnode status is correct */
227 int
228 bnode_WaitStatus(struct bnode *abnode, int astatus)
229 {
230     afs_int32 code;
231     afs_int32 stat;
232
233     bnode_Hold(abnode);
234     while (1) {
235         /* get the status */
236         code = BOP_GETSTAT(abnode, &stat);
237         if (code)
238             return code;
239
240         /* otherwise, check if we're done */
241         if (stat == astatus) {
242             bnode_Release(abnode);
243             return 0;           /* done */
244         }
245         if (astatus != abnode->goal) {
246             bnode_Release(abnode);
247             return -1;          /* no longer our goal, don't keep waiting */
248         }
249         /* otherwise, block */
250         abnode->flags |= BNODE_WAIT;
251         LWP_WaitProcess(abnode);
252     }
253 }
254
255 int
256 bnode_ResetErrorCount(struct bnode *abnode)
257 {
258     abnode->errorStopCount = 0;
259     abnode->errorStopDelay = 0;
260     return 0;
261 }
262
263 int
264 bnode_SetStat(struct bnode *abnode, int agoal)
265 {
266     abnode->goal = agoal;
267     bnode_Check(abnode);
268     BOP_SETSTAT(abnode, agoal);
269     abnode->flags &= ~BNODE_ERRORSTOP;
270     return 0;
271 }
272
273 int
274 bnode_SetGoal(struct bnode *abnode, int agoal)
275 {
276     abnode->goal = agoal;
277     bnode_Check(abnode);
278     return 0;
279 }
280
281 int
282 bnode_SetFileGoal(struct bnode *abnode, int agoal)
283 {
284     if (abnode->fileGoal == agoal)
285         return 0;               /* already done */
286     abnode->fileGoal = agoal;
287     WriteBozoFile(0);
288     return 0;
289 }
290
291 /* apply a function to all bnodes in the system */
292 int
293 bnode_ApplyInstance(int (*aproc) (struct bnode *tb, void *), void *arock)
294 {
295     struct bnode *tb, *nb;
296     afs_int32 code;
297
298     for (tb = allBnodes; tb; tb = nb) {
299         nb = tb->next;
300         code = (*aproc) (tb, arock);
301         if (code)
302             return code;
303     }
304     return 0;
305 }
306
307 struct bnode *
308 bnode_FindInstance(char *aname)
309 {
310     struct bnode *tb;
311
312     for (tb = allBnodes; tb; tb = tb->next) {
313         if (!strcmp(tb->name, aname))
314             return tb;
315     }
316     return NULL;
317 }
318
319 static struct bnode_type *
320 FindType(char *aname)
321 {
322     struct bnode_type *tt;
323
324     for (tt = allTypes; tt; tt = tt->next) {
325         if (!strcmp(tt->name, aname))
326             return tt;
327     }
328     return (struct bnode_type *)0;
329 }
330
331 int
332 bnode_Register(char *atype, struct bnode_ops *aprocs, int anparms)
333 {
334     struct bnode_type *tt;
335
336     for (tt = allTypes; tt; tt = tt->next) {
337         if (!strcmp(tt->name, atype))
338             break;
339     }
340     if (!tt) {
341         tt = (struct bnode_type *)malloc(sizeof(struct bnode_type));
342         memset(tt, 0, sizeof(struct bnode_type));
343         tt->next = allTypes;
344         allTypes = tt;
345         tt->name = atype;
346     }
347     tt->ops = aprocs;
348     return 0;
349 }
350
351 afs_int32
352 bnode_Create(char *atype, char *ainstance, struct bnode ** abp, char *ap1,
353              char *ap2, char *ap3, char *ap4, char *ap5, char *notifier,
354              int fileGoal, int rewritefile)
355 {
356     struct bnode_type *type;
357     struct bnode *tb;
358     char *notifierpath = NULL;
359     struct stat tstat;
360
361     if (bnode_FindInstance(ainstance))
362         return BZEXISTS;
363     type = FindType(atype);
364     if (!type)
365         return BZBADTYPE;
366
367     if (notifier && strcmp(notifier, NONOTIFIER)) {
368         /* construct local path from canonical (wire-format) path */
369         if (ConstructLocalBinPath(notifier, &notifierpath)) {
370             bozo_Log("BNODE-Create: Notifier program path invalid '%s'\n",
371                      notifier);
372             return BZNOCREATE;
373         }
374
375         if (stat(notifierpath, &tstat)) {
376             bozo_Log("BNODE-Create: Notifier program '%s' not found\n",
377                      notifierpath);
378             free(notifierpath);
379             return BZNOCREATE;
380         }
381     }
382     tb = (*type->ops->create) (ainstance, ap1, ap2, ap3, ap4, ap5);
383     if (!tb) {
384         free(notifierpath);
385         return BZNOCREATE;
386     }
387     tb->notifier = notifierpath;
388     *abp = tb;
389     tb->type = type;
390
391     /* The fs_create above calls bnode_InitBnode() which always sets the
392      ** fileGoal to BSTAT_NORMAL .... overwrite it with whatever is passed into
393      ** this function as a parameter... */
394     tb->fileGoal = fileGoal;
395
396     bnode_SetStat(tb, tb->goal);        /* nudge it once */
397
398     if (rewritefile != 0)
399         WriteBozoFile(0);
400
401     return 0;
402 }
403
404 int
405 bnode_DeleteName(char *ainstance)
406 {
407     struct bnode *tb;
408
409     tb = bnode_FindInstance(ainstance);
410     if (!tb)
411         return BZNOENT;
412
413     return bnode_Delete(tb);
414 }
415
416 int
417 bnode_Hold(struct bnode *abnode)
418 {
419     abnode->refCount++;
420     return 0;
421 }
422
423 int
424 bnode_Release(struct bnode *abnode)
425 {
426     abnode->refCount--;
427     if (abnode->refCount == 0 && abnode->flags & BNODE_DELETE) {
428         abnode->flags &= ~BNODE_DELETE; /* we're going for it */
429         bnode_Delete(abnode);
430     }
431     return 0;
432 }
433
434 int
435 bnode_Delete(struct bnode *abnode)
436 {
437     afs_int32 code;
438     struct bnode **lb, *ub;
439     afs_int32 temp;
440
441     if (abnode->refCount != 0) {
442         abnode->flags |= BNODE_DELETE;
443         return 0;
444     }
445
446     /* make sure the bnode is idle before zapping */
447     bnode_Hold(abnode);
448     code = BOP_GETSTAT(abnode, &temp);
449     bnode_Release(abnode);
450     if (code)
451         return code;
452     if (temp != BSTAT_SHUTDOWN)
453         return BZBUSY;
454
455     /* all clear to zap */
456     for (lb = &allBnodes, ub = *lb; ub; lb = &ub->next, ub = *lb) {
457         if (ub == abnode) {
458             /* unthread it from the list */
459             *lb = ub->next;
460             break;
461         }
462     }
463     free(abnode->name);         /* do this first, since bnode fields may be bad after BOP_DELETE */
464     code = BOP_DELETE(abnode);  /* don't play games like holding over this one */
465     WriteBozoFile(0);
466     return code;
467 }
468
469 /* function to tell if there's a timeout coming up */
470 int
471 bnode_PendingTimeout(struct bnode *abnode)
472 {
473     return (abnode->flags & BNODE_NEEDTIMEOUT);
474 }
475
476 /* function called to set / clear periodic bnode wakeup times */
477 int
478 bnode_SetTimeout(struct bnode *abnode, afs_int32 atimeout)
479 {
480     if (atimeout != 0) {
481         abnode->nextTimeout = FT_ApproxTime() + atimeout;
482         abnode->flags |= BNODE_NEEDTIMEOUT;
483         abnode->period = atimeout;
484         IOMGR_Cancel(bproc_pid);
485     } else {
486         abnode->flags &= ~BNODE_NEEDTIMEOUT;
487     }
488     return 0;
489 }
490
491 /* used by new bnode creation code to format bnode header */
492 int
493 bnode_InitBnode(struct bnode *abnode, struct bnode_ops *abnodeops,
494                 char *aname)
495 {
496     struct bnode **lb, *nb;
497
498     /* format the bnode properly */
499     memset(abnode, 0, sizeof(struct bnode));
500     abnode->ops = abnodeops;
501     abnode->name = strdup(aname);
502     if (!abnode->name)
503         return ENOMEM;
504     abnode->flags = BNODE_ACTIVE;
505     abnode->fileGoal = BSTAT_NORMAL;
506     abnode->goal = BSTAT_SHUTDOWN;
507
508     /* put the bnode at the end of the list so we write bnode file in same order */
509     for (lb = &allBnodes, nb = *lb; nb; lb = &nb->next, nb = *lb);
510     *lb = abnode;
511
512     return 0;
513 }
514
515 static int
516 DeleteProc(struct bnode_proc *abproc)
517 {
518     struct bnode_proc **pb, *tb;
519     struct bnode_proc *nb;
520
521     for (pb = &allProcs, tb = *pb; tb; pb = &tb->next, tb = nb) {
522         nb = tb->next;
523         if (tb == abproc) {
524             *pb = nb;
525             free(tb);
526             return 0;
527         }
528     }
529     return BZNOENT;
530 }
531
532 /* bnode lwp executes this code repeatedly */
533 static void *
534 bproc(void *unused)
535 {
536     afs_int32 code;
537     struct bnode *tb;
538     afs_int32 temp;
539     struct bnode_proc *tp;
540     struct bnode *nb;
541     int options;                /* must not be register */
542     struct timeval tv;
543     int setAny;
544     int status;
545
546     while (1) {
547         /* first figure out how long to sleep for */
548         temp = 0x7fffffff;      /* afs_int32 time; maxint doesn't work in select */
549         setAny = 0;
550         for (tb = allBnodes; tb; tb = tb->next) {
551             if (tb->flags & BNODE_NEEDTIMEOUT) {
552                 if (tb->nextTimeout < temp) {
553                     setAny = 1;
554                     temp = tb->nextTimeout;
555                 }
556             }
557         }
558         /* now temp has the time at which we should wakeup next */
559
560         /* sleep */
561         if (setAny)
562             temp -= FT_ApproxTime();    /* how many seconds until next event */
563         else
564             temp = 999999;
565         if (temp > 0) {
566             tv.tv_sec = temp;
567             tv.tv_usec = 0;
568             code = IOMGR_Select(0, 0, 0, 0, &tv);
569         } else
570             code = 0;           /* fake timeout code */
571
572         /* figure out why we woke up; child exit or timeouts */
573         FT_GetTimeOfDay(&tv, 0);        /* must do the real gettimeofday once and a while */
574         temp = tv.tv_sec;
575
576         /* check all bnodes to see which ones need timeout events */
577         for (tb = allBnodes; tb; tb = nb) {
578             if ((tb->flags & BNODE_NEEDTIMEOUT) && temp > tb->nextTimeout) {
579                 bnode_Hold(tb);
580                 BOP_TIMEOUT(tb);
581                 bnode_Check(tb);
582                 if (tb->flags & BNODE_NEEDTIMEOUT) {    /* check again, BOP_TIMEOUT could change */
583                     tb->nextTimeout = FT_ApproxTime() + tb->period;
584                 }
585                 nb = tb->next;
586                 bnode_Release(tb);      /* delete may occur here */
587             } else
588                 nb = tb->next;
589         }
590
591         if (code < 0) {
592             /* signalled, probably by incoming signal */
593             while (1) {
594                 options = WNOHANG;
595                 bnode_waiting = options | 0x800000;
596                 code = waitpid((pid_t) - 1, &status, options);
597                 bnode_waiting = 0;
598                 if (code == 0 || code == -1)
599                     break;      /* all done */
600                 /* otherwise code has a process id, which we now search for */
601                 for (tp = allProcs; tp; tp = tp->next)
602                     if (tp->pid == code)
603                         break;
604                 if (tp) {
605                     /* found the pid */
606                     tb = tp->bnode;
607                     bnode_Hold(tb);
608
609                     /* count restarts in last 30 seconds */
610                     if (temp > tb->rsTime + 30) {
611                         /* it's been 30 seconds we've been counting */
612                         tb->rsTime = temp;
613                         tb->rsCount = 0;
614                     }
615
616
617                     if (WIFSIGNALED(status) == 0) {
618                         /* exited, not signalled */
619                         tp->lastExit = WEXITSTATUS(status);
620                         tp->lastSignal = 0;
621                         if (tp->lastExit) {
622                             tb->errorCode = tp->lastExit;
623                             tb->lastErrorExit = FT_ApproxTime();
624                             RememberProcName(tp);
625                             tb->errorSignal = 0;
626                         }
627                         if (tp->coreName)
628                             bozo_Log("%s:%s exited with code %d\n", tb->name,
629                                      tp->coreName, tp->lastExit);
630                         else
631                             bozo_Log("%s exited with code %d\n", tb->name,
632                                      tp->lastExit);
633                     } else {
634                         /* Signal occurred, perhaps spurious due to shutdown request.
635                          * If due to a shutdown request, don't overwrite last error
636                          * information.
637                          */
638                         tp->lastSignal = WTERMSIG(status);
639                         tp->lastExit = 0;
640                         if (tp->lastSignal != SIGQUIT
641                             && tp->lastSignal != SIGTERM
642                             && tp->lastSignal != SIGKILL) {
643                             tb->errorSignal = tp->lastSignal;
644                             tb->lastErrorExit = FT_ApproxTime();
645                             RememberProcName(tp);
646                         }
647                         if (tp->coreName)
648                             bozo_Log("%s:%s exited on signal %d%s\n",
649                                      tb->name, tp->coreName, tp->lastSignal,
650                                      WCOREDUMP(status) ? " (core dumped)" :
651                                      "");
652                         else
653                             bozo_Log("%s exited on signal %d%s\n", tb->name,
654                                      tp->lastSignal,
655                                      WCOREDUMP(status) ? " (core dumped)" :
656                                      "");
657                         SaveCore(tb, tp);
658                     }
659                     tb->lastAnyExit = FT_ApproxTime();
660
661                     if (tb->notifier) {
662                         bozo_Log("BNODE: Notifier %s will be called\n",
663                                  tb->notifier);
664                         hdl_notifier(tp);
665                     }
666
667                     if (tb->goal && tb->rsCount++ > 10) {
668                         /* 10 in 30 seconds */
669                         if (tb->errorStopCount >= BNODE_ERROR_COUNT_MAX) {
670                             tb->errorStopDelay = 0;     /* max reached, give up. */
671                         } else {
672                             tb->errorStopCount++;
673                             if (!tb->errorStopDelay) {
674                                 tb->errorStopDelay = 1;
675                             } else {
676                                 tb->errorStopDelay *= 2;
677                             }
678                         }
679                         tb->flags |= BNODE_ERRORSTOP;
680                         bnode_SetGoal(tb, BSTAT_SHUTDOWN);
681                         bozo_Log
682                             ("BNODE '%s' repeatedly failed to start, perhaps missing executable.\n",
683                              tb->name);
684                     }
685                     BOP_PROCEXIT(tb, tp);
686                     bnode_Check(tb);
687                     bnode_Release(tb);  /* bnode delete can happen here */
688                     DeleteProc(tp);
689                 } else
690                     bnode_stats.weirdPids++;
691             }
692         }
693     }
694     return NULL;
695 }
696
697 static afs_int32
698 SendNotifierData(int fd, struct bnode_proc *tp)
699 {
700     struct bnode *tb = tp->bnode;
701     char buffer[1000], *bufp = buffer, *buf1;
702     int len;
703
704     /*
705      * First sent out the bnode_proc struct
706      */
707     (void)sprintf(bufp, "BEGIN bnode_proc\n");
708     bufp += strlen(bufp);
709     (void)sprintf(bufp, "comLine: %s\n", tp->comLine);
710     bufp += strlen(bufp);
711     if (!(buf1 = tp->coreName))
712         buf1 = "(null)";
713     (void)sprintf(bufp, "coreName: %s\n", buf1);
714     bufp += strlen(bufp);
715     (void)sprintf(bufp, "pid: %ld\n", afs_printable_int32_ld(tp->pid));
716     bufp += strlen(bufp);
717     (void)sprintf(bufp, "lastExit: %ld\n", afs_printable_int32_ld(tp->lastExit));
718     bufp += strlen(bufp);
719 #ifdef notdef
720     (void)sprintf(bufp, "lastSignal: %ld\n", afs_printable_int32_ld(tp->lastSignal));
721     bufp += strlen(bufp);
722 #endif
723     (void)sprintf(bufp, "flags: %ld\n", afs_printable_int32_ld(tp->flags));
724     bufp += strlen(bufp);
725     (void)sprintf(bufp, "END bnode_proc\n");
726     bufp += strlen(bufp);
727     len = (int)(bufp - buffer);
728     if (write(fd, buffer, len) < 0) {
729         return -1;
730     }
731
732     /*
733      * Now sent out the bnode struct
734      */
735     bufp = buffer;
736     (void)sprintf(bufp, "BEGIN bnode\n");
737     bufp += strlen(bufp);
738     (void)sprintf(bufp, "name: %s\n", tb->name);
739     bufp += strlen(bufp);
740     (void)sprintf(bufp, "rsTime: %ld\n", afs_printable_int32_ld(tb->rsTime));
741     bufp += strlen(bufp);
742     (void)sprintf(bufp, "rsCount: %ld\n", afs_printable_int32_ld(tb->rsCount));
743     bufp += strlen(bufp);
744     (void)sprintf(bufp, "procStartTime: %ld\n", afs_printable_int32_ld(tb->procStartTime));
745     bufp += strlen(bufp);
746     (void)sprintf(bufp, "procStarts: %ld\n", afs_printable_int32_ld(tb->procStarts));
747     bufp += strlen(bufp);
748     (void)sprintf(bufp, "lastAnyExit: %ld\n", afs_printable_int32_ld(tb->lastAnyExit));
749     bufp += strlen(bufp);
750     (void)sprintf(bufp, "lastErrorExit: %ld\n", afs_printable_int32_ld(tb->lastErrorExit));
751     bufp += strlen(bufp);
752     (void)sprintf(bufp, "errorCode: %ld\n", afs_printable_int32_ld(tb->errorCode));
753     bufp += strlen(bufp);
754     (void)sprintf(bufp, "errorSignal: %ld\n", afs_printable_int32_ld(tb->errorSignal));
755     bufp += strlen(bufp);
756 /*
757     (void) sprintf(bufp, "lastErrorName: %s\n", tb->lastErrorName);
758     bufp += strlen(bufp);
759 */
760     (void)sprintf(bufp, "goal: %d\n", tb->goal);
761     bufp += strlen(bufp);
762     (void)sprintf(bufp, "END bnode\n");
763     bufp += strlen(bufp);
764     len = (int)(bufp - buffer);
765     if (write(fd, buffer, len) < 0) {
766         return -1;
767     }
768     return 0;
769 }
770
771 int
772 hdl_notifier(struct bnode_proc *tp)
773 {
774 #ifndef AFS_NT40_ENV            /* NT notifier callout not yet implemented */
775     int pid;
776     struct stat tstat;
777
778     if (stat(tp->bnode->notifier, &tstat)) {
779         bozo_Log("BNODE: Failed to find notifier '%s'; ignored\n",
780                  tp->bnode->notifier);
781         return (1);
782     }
783     if ((pid = fork()) == 0) {
784         FILE *fout;
785         struct bnode *tb = tp->bnode;
786
787 #if defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV) || defined(AFS_SGI51_ENV)
788         setsid();
789 #elif defined(AFS_DARWIN90_ENV)
790         setpgid(0, 0);
791 #elif defined(AFS_LINUX20_ENV) || defined(AFS_AIX_ENV)
792         setpgrp();
793 #else
794         setpgrp(0, 0);
795 #endif
796         fout = popen(tb->notifier, "w");
797         if (fout == NULL) {
798             bozo_Log("BNODE: Failed to find notifier '%s'; ignored\n",
799                      tb->notifier);
800             perror(tb->notifier);
801             exit(1);
802         }
803         SendNotifierData(fileno(fout), tp);
804         pclose(fout);
805         exit(0);
806     } else if (pid < 0) {
807         bozo_Log("Failed to fork creating process to handle notifier '%s'\n",
808                  tp->bnode->notifier);
809         return -1;
810     }
811 #endif /* AFS_NT40_ENV */
812     return (0);
813 }
814
815 /* Called by IOMGR at low priority on IOMGR's stack shortly after a SIGCHLD
816  * occurs.  Wakes up bproc do redo things */
817 void *
818 bnode_SoftInt(void *param)
819 {
820     /* int asignal = (int) param; */
821
822     IOMGR_Cancel(bproc_pid);
823     return 0;
824 }
825
826 /* Called at signal interrupt level; queues function to be called
827  * when IOMGR runs again.
828  */
829 void
830 bnode_Int(int asignal)
831 {
832     if (asignal == SIGQUIT || asignal == SIGTERM) {
833         IOMGR_SoftSig(bozo_ShutdownAndExit, (void *)(intptr_t)asignal);
834     } else {
835         IOMGR_SoftSig(bnode_SoftInt, (void *)(intptr_t)asignal);
836     }
837 }
838
839
840 /* intialize the whole system */
841 int
842 bnode_Init(void)
843 {
844     PROCESS junk;
845     afs_int32 code;
846     struct sigaction newaction;
847     static int initDone = 0;
848
849     if (initDone)
850         return 0;
851     initDone = 1;
852     memset(&bnode_stats, 0, sizeof(bnode_stats));
853     LWP_InitializeProcessSupport(1, &junk);     /* just in case */
854     IOMGR_Initialize();
855     code = LWP_CreateProcess(bproc, BNODE_LWP_STACKSIZE,
856                              /* priority */ 1, (void *) /* parm */ 0,
857                              "bnode-manager", &bproc_pid);
858     if (code)
859         return code;
860     memset(&newaction, 0, sizeof(newaction));
861     newaction.sa_handler = bnode_Int;
862     code = sigaction(SIGCHLD, &newaction, NULL);
863     if (code)
864         return errno;
865     code = sigaction(SIGQUIT, &newaction, NULL);
866     if (code)
867         return errno;
868     code = sigaction(SIGTERM, &newaction, NULL);
869     if (code)
870         return errno;
871     return code;
872 }
873
874 /* free token list returned by parseLine */
875 int
876 bnode_FreeTokens(struct bnode_token *alist)
877 {
878     struct bnode_token *nlist;
879     for (; alist; alist = nlist) {
880         nlist = alist->next;
881         free(alist->key);
882         free(alist);
883     }
884     return 0;
885 }
886
887 static int
888 space(int x)
889 {
890     if (x == 0 || x == ' ' || x == '\t' || x == '\n')
891         return 1;
892     else
893         return 0;
894 }
895
896 int
897 bnode_ParseLine(char *aline, struct bnode_token **alist)
898 {
899     char tbuffer[256];
900     char *tptr = NULL;
901     int inToken;
902     struct bnode_token *first, *last;
903     struct bnode_token *ttok;
904     int tc;
905
906     inToken = 0;                /* not copying token chars at start */
907     first = (struct bnode_token *)0;
908     last = (struct bnode_token *)0;
909     while (1) {
910         tc = *aline++;
911         if (tc == 0 || space(tc)) {     /* terminating null gets us in here, too */
912             if (inToken) {
913                 inToken = 0;    /* end of this token */
914                 *tptr++ = 0;
915                 ttok =
916                     (struct bnode_token *)malloc(sizeof(struct bnode_token));
917                 ttok->next = (struct bnode_token *)0;
918                 ttok->key = strdup(tbuffer);
919                 if (last) {
920                     last->next = ttok;
921                     last = ttok;
922                 } else
923                     last = ttok;
924                 if (!first)
925                     first = ttok;
926             }
927         } else {
928             /* an alpha character */
929             if (!inToken) {
930                 tptr = tbuffer;
931                 inToken = 1;
932             }
933             if (tptr - tbuffer >= sizeof(tbuffer))
934                 return -1;      /* token too long */
935             *tptr++ = tc;
936         }
937         if (tc == 0) {
938             /* last token flushed 'cause space(0) --> true */
939             if (last)
940                 last->next = (struct bnode_token *)0;
941             *alist = first;
942             return 0;
943         }
944     }
945 }
946
947 #define MAXVARGS            128
948 int
949 bnode_NewProc(struct bnode *abnode, char *aexecString, char *coreName,
950               struct bnode_proc **aproc)
951 {
952     struct bnode_token *tlist, *tt;
953     afs_int32 code;
954     struct bnode_proc *tp;
955     pid_t cpid;
956     char *argv[MAXVARGS];
957     int i;
958
959     code = bnode_ParseLine(aexecString, &tlist);        /* try parsing first */
960     if (code)
961         return code;
962     tp = (struct bnode_proc *)malloc(sizeof(struct bnode_proc));
963     memset(tp, 0, sizeof(struct bnode_proc));
964     tp->next = allProcs;
965     tp->bnode = abnode;
966     tp->comLine = aexecString;
967     tp->coreName = coreName;    /* may be null */
968     abnode->procStartTime = FT_ApproxTime();
969     abnode->procStarts++;
970
971     /* convert linked list of tokens into argv structure */
972     for (tt = tlist, i = 0; i < (MAXVARGS - 1) && tt; tt = tt->next, i++) {
973         argv[i] = tt->key;
974     }
975     argv[i] = NULL;             /* null-terminated */
976
977     cpid = spawnprocve(argv[0], argv, environ, -1);
978     osi_audit(BOSSpawnProcEvent, 0, AUD_STR, aexecString, AUD_END);
979
980     if (cpid == (pid_t) - 1) {
981         bozo_Log("Failed to spawn process for bnode '%s'\n", abnode->name);
982         bnode_FreeTokens(tlist);
983         free(tp);
984         return errno;
985     }
986     bozo_Log("%s started pid %ld: %s\n", abnode->name, cpid, aexecString);
987
988     bnode_FreeTokens(tlist);
989     allProcs = tp;
990     *aproc = tp;
991     tp->pid = cpid;
992     tp->flags = BPROC_STARTED;
993     tp->flags &= ~BPROC_EXITED;
994     BOP_PROCSTARTED(abnode, tp);
995     bnode_Check(abnode);
996     return 0;
997 }
998
999 int
1000 bnode_StopProc(struct bnode_proc *aproc, int asignal)
1001 {
1002     int code;
1003     if (!(aproc->flags & BPROC_STARTED) || (aproc->flags & BPROC_EXITED))
1004         return BZNOTACTIVE;
1005
1006     osi_audit(BOSStopProcEvent, 0, AUD_STR, (aproc ? aproc->comLine : NULL),
1007               AUD_END);
1008
1009     code = kill(aproc->pid, asignal);
1010     bnode_Check(aproc->bnode);
1011     return code;
1012 }
1013
1014 int
1015 bnode_Deactivate(struct bnode *abnode)
1016 {
1017     struct bnode **pb, *tb;
1018     struct bnode *nb;
1019     if (!(abnode->flags & BNODE_ACTIVE))
1020         return BZNOTACTIVE;
1021     for (pb = &allBnodes, tb = *pb; tb; tb = nb) {
1022         nb = tb->next;
1023         if (tb == abnode) {
1024             *pb = nb;
1025             tb->flags &= ~BNODE_ACTIVE;
1026             return 0;
1027         }
1028     }
1029     return BZNOENT;
1030 }