xref: /freebsd/usr.sbin/syslogd/syslogd.c (revision df7f5d4de4592a8948a25ce01e5bddfbb7ce39dc)
1 /*
2  * Copyright (c) 1983, 1988, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 /*
39 static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
40 */
41 static const char rcsid[] =
42 	"$Id: syslogd.c,v 1.20 1997/02/22 16:14:00 peter Exp $";
43 #endif /* not lint */
44 
45 /*
46  *  syslogd -- log system messages
47  *
48  * This program implements a system log. It takes a series of lines.
49  * Each line may have a priority, signified as "<n>" as
50  * the first characters of the line.  If this is
51  * not present, a default priority is used.
52  *
53  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
54  * cause it to reread its configuration file.
55  *
56  * Defined Constants:
57  *
58  * MAXLINE -- the maximimum line length that can be handled.
59  * DEFUPRI -- the default priority for user messages
60  * DEFSPRI -- the default priority for kernel messages
61  *
62  * Author: Eric Allman
63  * extensive changes by Ralph Campbell
64  * more extensive changes by Eric Allman (again)
65  * Extension to log by program name as well as facility and priority
66  *   by Peter da Silva.
67  */
68 
69 #define	MAXLINE		1024		/* maximum line length */
70 #define	MAXSVLINE	120		/* maximum saved line length */
71 #define DEFUPRI		(LOG_USER|LOG_NOTICE)
72 #define DEFSPRI		(LOG_KERN|LOG_CRIT)
73 #define TIMERINTVL	30		/* interval for checking flush, mark */
74 #define TTYMSGTIME	1		/* timed out passed to ttymsg */
75 
76 #include <sys/param.h>
77 #include <sys/ioctl.h>
78 #include <sys/stat.h>
79 #include <sys/wait.h>
80 #include <sys/socket.h>
81 #include <sys/msgbuf.h>
82 #include <sys/queue.h>
83 #include <sys/uio.h>
84 #include <sys/un.h>
85 #include <sys/time.h>
86 #include <sys/resource.h>
87 #include <sys/syslimits.h>
88 #include <paths.h>
89 
90 #include <netinet/in.h>
91 #include <netdb.h>
92 #include <arpa/inet.h>
93 
94 #include <ctype.h>
95 #include <errno.h>
96 #include <fcntl.h>
97 #include <setjmp.h>
98 #include <signal.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <unistd.h>
103 #include <utmp.h>
104 #include "pathnames.h"
105 
106 #define SYSLOG_NAMES
107 #include <sys/syslog.h>
108 
109 const char	*LogName = _PATH_LOG;
110 const char	*ConfFile = _PATH_LOGCONF;
111 const char	*PidFile = _PATH_LOGPID;
112 const char	ctty[] = _PATH_CONSOLE;
113 
114 #define FDMASK(fd)	(1 << (fd))
115 
116 #define	dprintf		if (Debug) printf
117 
118 #define MAXUNAMES	20	/* maximum number of user names */
119 
120 /*
121  * Flags to logmsg().
122  */
123 
124 #define IGN_CONS	0x001	/* don't print on console */
125 #define SYNC_FILE	0x002	/* do fsync on file after printing */
126 #define ADDDATE		0x004	/* add a date to the message */
127 #define MARK		0x008	/* this message is a mark */
128 
129 /*
130  * This structure represents the files that will have log
131  * copies printed.
132  */
133 
134 struct filed {
135 	struct	filed *f_next;		/* next in linked list */
136 	short	f_type;			/* entry type, see below */
137 	short	f_file;			/* file descriptor */
138 	time_t	f_time;			/* time this was last written */
139 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
140 	char	*f_program;		/* program this applies to */
141 	union {
142 		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
143 		struct {
144 			char	f_hname[MAXHOSTNAMELEN+1];
145 			struct sockaddr_in	f_addr;
146 		} f_forw;		/* forwarding address */
147 		char	f_fname[MAXPATHLEN];
148 		struct {
149 			char	f_pname[MAXPATHLEN];
150 			pid_t	f_pid;
151 		} f_pipe;
152 	} f_un;
153 	char	f_prevline[MAXSVLINE];		/* last message logged */
154 	char	f_lasttime[16];			/* time of last occurrence */
155 	char	f_prevhost[MAXHOSTNAMELEN+1];	/* host from which recd. */
156 	int	f_prevpri;			/* pri of f_prevline */
157 	int	f_prevlen;			/* length of f_prevline */
158 	int	f_prevcount;			/* repetition cnt of prevline */
159 	int	f_repeatcount;			/* number of "repeated" msgs */
160 };
161 
162 /*
163  * Queue of about-to-be dead processes we should watch out for.
164  */
165 
166 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
167 struct stailhead *deadq_headp;
168 
169 struct deadq_entry {
170 	pid_t				dq_pid;
171 	int				dq_timeout;
172 	TAILQ_ENTRY(deadq_entry)	dq_entries;
173 };
174 
175 /*
176  * The timeout to apply to processes waiting on the dead queue.  Unit
177  * of measure is `mark intervals', i.e. 20 minutes by default.
178  * Processes on the dead queue will be terminated after that time.
179  */
180 
181 #define DQ_TIMO_INIT	2
182 
183 typedef struct deadq_entry *dq_t;
184 
185 
186 /*
187  * Intervals at which we flush out "message repeated" messages,
188  * in seconds after previous message is logged.  After each flush,
189  * we move to the next interval until we reach the largest.
190  */
191 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
192 #define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
193 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
194 #define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
195 				 (f)->f_repeatcount = MAXREPEAT; \
196 			}
197 
198 /* values for f_type */
199 #define F_UNUSED	0		/* unused entry */
200 #define F_FILE		1		/* regular file */
201 #define F_TTY		2		/* terminal */
202 #define F_CONSOLE	3		/* console terminal */
203 #define F_FORW		4		/* remote machine */
204 #define F_USERS		5		/* list of users */
205 #define F_WALL		6		/* everyone logged on */
206 #define F_PIPE		7		/* pipe to program */
207 
208 char	*TypeNames[8] = {
209 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
210 	"FORW",		"USERS",	"WALL",		"PIPE"
211 };
212 
213 struct	filed *Files;
214 struct	filed consfile;
215 
216 int	Debug;			/* debug flag */
217 char	LocalHostName[MAXHOSTNAMELEN+1];	/* our hostname */
218 char	*LocalDomain;		/* our local domain name */
219 int	InetInuse = 0;		/* non-zero if INET sockets are being used */
220 int	finet;			/* Internet datagram socket */
221 int	LogPort;		/* port number for INET connections */
222 int	Initialized = 0;	/* set when we have initialized ourselves */
223 int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
224 int	MarkSeq = 0;		/* mark sequence number */
225 int	SecureMode = 0;		/* when true, speak only unix domain socks */
226 
227 int     created_lsock = 0;      /* Flag if local socket created */
228 char	bootfile[MAXLINE+1];	/* booted kernel file */
229 
230 void	cfline __P((char *, struct filed *, char *));
231 char   *cvthname __P((struct sockaddr_in *));
232 void	deadq_enter __P((pid_t));
233 int	decode __P((const char *, CODE *));
234 void	die __P((int));
235 void	domark __P((int));
236 void	fprintlog __P((struct filed *, int, char *));
237 void	init __P((int));
238 void	logerror __P((const char *));
239 void	logmsg __P((int, char *, char *, int));
240 void	printline __P((char *, char *));
241 void	printsys __P((char *));
242 int	p_open __P((char *, pid_t *));
243 void	reapchild __P((int));
244 char   *ttymsg __P((struct iovec *, int, char *, int));
245 void	usage __P((void));
246 void	wallmsg __P((struct filed *, struct iovec *));
247 int	waitdaemon __P((int, int, int));
248 void	timedout __P((int));
249 
250 int
251 main(argc, argv)
252 	int argc;
253 	char *argv[];
254 {
255 	int ch, funix, i, inetm, fklog, klogm, len;
256 	struct sockaddr_un sunx, fromunix;
257 	struct sockaddr_in sin, frominet;
258 	FILE *fp;
259 	char *p, line[MSG_BSIZE + 1];
260 	struct timeval tv, *tvp;
261 	pid_t ppid;
262 
263 	while ((ch = getopt(argc, argv, "dsf:Im:p:")) != EOF)
264 		switch(ch) {
265 		case 'd':		/* debug */
266 			Debug++;
267 			break;
268 		case 'f':		/* configuration file */
269 			ConfFile = optarg;
270 			break;
271 		case 'm':		/* mark interval */
272 			MarkInterval = atoi(optarg) * 60;
273 			break;
274 		case 'p':		/* path */
275 			LogName = optarg;
276 			break;
277 		case 'I':		/* backwards compatible w/FreeBSD */
278 		case 's':		/* no network mode */
279 			SecureMode++;
280 			break;
281 		case '?':
282 		default:
283 			usage();
284 		}
285 	if ((argc -= optind) != 0)
286 		usage();
287 
288 	if (!Debug) {
289 		ppid = waitdaemon(0, 0, 30);
290 		if (ppid < 0)
291 			err(1, "could not become daemon");
292 	} else
293 		setlinebuf(stdout);
294 
295 	consfile.f_type = F_CONSOLE;
296 	(void)strcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1);
297 	(void)gethostname(LocalHostName, sizeof(LocalHostName));
298 	if ((p = strchr(LocalHostName, '.')) != NULL) {
299 		*p++ = '\0';
300 		LocalDomain = p;
301 	} else
302 		LocalDomain = "";
303 	(void)strcpy(bootfile, getbootfile());
304 	(void)signal(SIGTERM, die);
305 	(void)signal(SIGINT, Debug ? die : SIG_IGN);
306 	(void)signal(SIGQUIT, Debug ? die : SIG_IGN);
307 	(void)signal(SIGCHLD, reapchild);
308 	(void)signal(SIGALRM, domark);
309 	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
310 	(void)alarm(TIMERINTVL);
311 
312 #ifndef SUN_LEN
313 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
314 #endif
315 	memset(&sunx, 0, sizeof(sunx));
316 	sunx.sun_family = AF_UNIX;
317 	(void)strncpy(sunx.sun_path, LogName, sizeof(sunx.sun_path));
318 	(void)unlink(LogName);
319 	funix = socket(AF_UNIX, SOCK_DGRAM, 0);
320 	if (funix < 0 ||
321 	    bind(funix, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
322 	    chmod(LogName, 0666) < 0) {
323 		(void) sprintf(line, "cannot create %s", LogName);
324 		logerror(line);
325 		dprintf("cannot create %s (%d)\n", LogName, errno);
326 		die(0);
327 	} else
328 		created_lsock = 1;
329 
330 	if (!SecureMode)
331 		finet = socket(AF_INET, SOCK_DGRAM, 0);
332 	else
333 		finet = -1;
334 
335 	TAILQ_INIT(&deadq_head);
336 
337 	inetm = 0;
338 	if (finet >= 0) {
339 		struct servent *sp;
340 
341 		sp = getservbyname("syslog", "udp");
342 		if (sp == NULL) {
343 			errno = 0;
344 			logerror("syslog/udp: unknown service");
345 			die(0);
346 		}
347 		memset(&sin, 0, sizeof(sin));
348 		sin.sin_family = AF_INET;
349 		sin.sin_port = LogPort = sp->s_port;
350 		if (bind(finet, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
351 			logerror("bind");
352 			if (!Debug)
353 				die(0);
354 		} else {
355 			inetm = FDMASK(finet);
356 			InetInuse = 1;
357 		}
358 	}
359 	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
360 		klogm = FDMASK(fklog);
361 	else {
362 		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
363 		klogm = 0;
364 	}
365 
366 	/* tuck my process id away */
367 	fp = fopen(PidFile, "w");
368 	if (fp != NULL) {
369 		fprintf(fp, "%d\n", getpid());
370 		(void) fclose(fp);
371 	}
372 
373 	dprintf("off & running....\n");
374 
375 	init(0);
376 	(void)signal(SIGHUP, init);
377 
378 	tvp = &tv;
379 	tv.tv_sec = tv.tv_usec = 0;
380 
381 	for (;;) {
382 		int nfds, readfds = FDMASK(funix) | inetm | klogm;
383 
384 		dprintf("readfds = %#x\n", readfds);
385 		nfds = select(20, (fd_set *)&readfds, (fd_set *)NULL,
386 		    (fd_set *)NULL, tvp);
387 		if (nfds == 0) {
388 			if (tvp) {
389 				tvp = NULL;
390 				if (ppid != 1)
391 					kill(ppid, SIGALRM);
392 			}
393 			continue;
394 		}
395 		if (nfds < 0) {
396 			if (errno != EINTR)
397 				logerror("select");
398 			continue;
399 		}
400 		dprintf("got a message (%d, %#x)\n", nfds, readfds);
401 		if (readfds & klogm) {
402 			i = read(fklog, line, sizeof(line) - 1);
403 			if (i > 0) {
404 				line[i] = '\0';
405 				printsys(line);
406 			} else if (i < 0 && errno != EINTR) {
407 				logerror("klog");
408 				fklog = -1;
409 				klogm = 0;
410 			}
411 		}
412 		if (readfds & FDMASK(funix)) {
413 			len = sizeof(fromunix);
414 			i = recvfrom(funix, line, MAXLINE, 0,
415 			    (struct sockaddr *)&fromunix, &len);
416 			if (i > 0) {
417 				line[i] = '\0';
418 				printline(LocalHostName, line);
419 			} else if (i < 0 && errno != EINTR)
420 				logerror("recvfrom unix");
421 		}
422 		if (readfds & inetm) {
423 			len = sizeof(frominet);
424 			i = recvfrom(finet, line, MAXLINE, 0,
425 			    (struct sockaddr *)&frominet, &len);
426 			if (i > 0) {
427 				line[i] = '\0';
428 				printline(cvthname(&frominet), line);
429 			} else if (i < 0 && errno != EINTR)
430 				logerror("recvfrom inet");
431 		}
432 	}
433 }
434 
435 void
436 usage()
437 {
438 
439 	fprintf(stderr,
440 		"usage: syslogd [-ds] [-f conffile] [-m markinterval]"
441 		" [-p logpath]\n");
442 	exit(1);
443 }
444 
445 /*
446  * Take a raw input line, decode the message, and print the message
447  * on the appropriate log files.
448  */
449 void
450 printline(hname, msg)
451 	char *hname;
452 	char *msg;
453 {
454 	int c, pri;
455 	char *p, *q, line[MAXLINE + 1];
456 
457 	/* test for special codes */
458 	pri = DEFUPRI;
459 	p = msg;
460 	if (*p == '<') {
461 		pri = 0;
462 		while (isdigit(*++p))
463 			pri = 10 * pri + (*p - '0');
464 		if (*p == '>')
465 			++p;
466 	}
467 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
468 		pri = DEFUPRI;
469 
470 	/* don't allow users to log kernel messages */
471 	if (LOG_FAC(pri) == LOG_KERN)
472 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
473 
474 	q = line;
475 
476 	while ((c = *p++ & 0177) != '\0' &&
477 	    q < &line[sizeof(line) - 1])
478 		if (iscntrl(c))
479 			if (c == '\n')
480 				*q++ = ' ';
481 			else if (c == '\t')
482 				*q++ = '\t';
483 			else {
484 				*q++ = '^';
485 				*q++ = c ^ 0100;
486 			}
487 		else
488 			*q++ = c;
489 	*q = '\0';
490 
491 	logmsg(pri, line, hname, 0);
492 }
493 
494 /*
495  * Take a raw input line from /dev/klog, split and format similar to syslog().
496  */
497 void
498 printsys(msg)
499 	char *msg;
500 {
501 	int c, pri, flags;
502 	char *lp, *p, *q, line[MAXLINE + 1];
503 
504 	(void)strcpy(line, bootfile);
505 	(void)strcat(line, ": ");
506 	lp = line + strlen(line);
507 	for (p = msg; *p != '\0'; ) {
508 		flags = SYNC_FILE | ADDDATE;	/* fsync file after write */
509 		pri = DEFSPRI;
510 		if (*p == '<') {
511 			pri = 0;
512 			while (isdigit(*++p))
513 				pri = 10 * pri + (*p - '0');
514 			if (*p == '>')
515 				++p;
516 		} else {
517 			/* kernel printf's come out on console */
518 			flags |= IGN_CONS;
519 		}
520 		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
521 			pri = DEFSPRI;
522 		q = lp;
523 		while (*p != '\0' && (c = *p++) != '\n' &&
524 		    q < &line[MAXLINE])
525 			*q++ = c;
526 		*q = '\0';
527 		logmsg(pri, line, LocalHostName, flags);
528 	}
529 }
530 
531 time_t	now;
532 
533 /*
534  * Log a message to the appropriate log files, users, etc. based on
535  * the priority.
536  */
537 void
538 logmsg(pri, msg, from, flags)
539 	int pri;
540 	char *msg, *from;
541 	int flags;
542 {
543 	struct filed *f;
544 	int fac, msglen, omask, prilev;
545 	char *timestamp;
546  	char prog[NAME_MAX+1];
547  	int i;
548 
549 	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
550 	    pri, flags, from, msg);
551 
552 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
553 
554 	/*
555 	 * Check to see if msg looks non-standard.
556 	 */
557 	msglen = strlen(msg);
558 	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
559 	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
560 		flags |= ADDDATE;
561 
562 	(void)time(&now);
563 	if (flags & ADDDATE)
564 		timestamp = ctime(&now) + 4;
565 	else {
566 		timestamp = msg;
567 		msg += 16;
568 		msglen -= 16;
569 	}
570 
571 	/* skip leading blanks */
572 	while(isspace(*msg)) {
573 		msg++;
574 		msglen--;
575 	}
576 
577 	/* extract facility and priority level */
578 	if (flags & MARK)
579 		fac = LOG_NFACILITIES;
580 	else
581 		fac = LOG_FAC(pri);
582 	prilev = LOG_PRI(pri);
583 
584 	/* extract program name */
585 	for(i = 0; i < NAME_MAX; i++) {
586 		if(!isalnum(msg[i]))
587 			break;
588 		prog[i] = msg[i];
589 	}
590 	prog[i] = 0;
591 
592 	/* log the message to the particular outputs */
593 	if (!Initialized) {
594 		f = &consfile;
595 		f->f_file = open(ctty, O_WRONLY, 0);
596 
597 		if (f->f_file >= 0) {
598 			fprintlog(f, flags, msg);
599 			(void)close(f->f_file);
600 		}
601 		(void)sigsetmask(omask);
602 		return;
603 	}
604 	for (f = Files; f; f = f->f_next) {
605 		/* skip messages that are incorrect priority */
606 		if (f->f_pmask[fac] < prilev ||
607 		    f->f_pmask[fac] == INTERNAL_NOPRI)
608 			continue;
609 		/* skip messages with the incorrect program name */
610 		if(f->f_program)
611 			if(strcmp(prog, f->f_program) != 0)
612 				continue;
613 
614 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
615 			continue;
616 
617 		/* don't output marks to recently written files */
618 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
619 			continue;
620 
621 		/*
622 		 * suppress duplicate lines to this file
623 		 */
624 		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
625 		    !strcmp(msg, f->f_prevline) &&
626 		    !strcmp(from, f->f_prevhost)) {
627 			(void)strncpy(f->f_lasttime, timestamp, 15);
628 			f->f_prevcount++;
629 			dprintf("msg repeated %d times, %ld sec of %d\n",
630 			    f->f_prevcount, now - f->f_time,
631 			    repeatinterval[f->f_repeatcount]);
632 			/*
633 			 * If domark would have logged this by now,
634 			 * flush it now (so we don't hold isolated messages),
635 			 * but back off so we'll flush less often
636 			 * in the future.
637 			 */
638 			if (now > REPEATTIME(f)) {
639 				fprintlog(f, flags, (char *)NULL);
640 				BACKOFF(f);
641 			}
642 		} else {
643 			/* new line, save it */
644 			if (f->f_prevcount)
645 				fprintlog(f, 0, (char *)NULL);
646 			f->f_repeatcount = 0;
647 			f->f_prevpri = pri;
648 			(void)strncpy(f->f_lasttime, timestamp, 15);
649 			(void)strncpy(f->f_prevhost, from,
650 					sizeof(f->f_prevhost));
651 			if (msglen < MAXSVLINE) {
652 				f->f_prevlen = msglen;
653 				(void)strcpy(f->f_prevline, msg);
654 				fprintlog(f, flags, (char *)NULL);
655 			} else {
656 				f->f_prevline[0] = 0;
657 				f->f_prevlen = 0;
658 				fprintlog(f, flags, msg);
659 			}
660 		}
661 	}
662 	(void)sigsetmask(omask);
663 }
664 
665 void
666 fprintlog(f, flags, msg)
667 	struct filed *f;
668 	int flags;
669 	char *msg;
670 {
671 	struct iovec iov[6];
672 	struct iovec *v;
673 	int l;
674 	char line[MAXLINE + 1], repbuf[80], greetings[200];
675 	char *msgret;
676 	dq_t q;
677 
678 	v = iov;
679 	if (f->f_type == F_WALL) {
680 		v->iov_base = greetings;
681 		v->iov_len = sprintf(greetings,
682 		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
683 		    f->f_prevhost, ctime(&now));
684 		v++;
685 		v->iov_base = "";
686 		v->iov_len = 0;
687 		v++;
688 	} else {
689 		v->iov_base = f->f_lasttime;
690 		v->iov_len = 15;
691 		v++;
692 		v->iov_base = " ";
693 		v->iov_len = 1;
694 		v++;
695 	}
696 	v->iov_base = f->f_prevhost;
697 	v->iov_len = strlen(v->iov_base);
698 	v++;
699 	v->iov_base = " ";
700 	v->iov_len = 1;
701 	v++;
702 
703 	if (msg) {
704 		v->iov_base = msg;
705 		v->iov_len = strlen(msg);
706 	} else if (f->f_prevcount > 1) {
707 		v->iov_base = repbuf;
708 		v->iov_len = sprintf(repbuf, "last message repeated %d times",
709 		    f->f_prevcount);
710 	} else {
711 		v->iov_base = f->f_prevline;
712 		v->iov_len = f->f_prevlen;
713 	}
714 	v++;
715 
716 	dprintf("Logging to %s", TypeNames[f->f_type]);
717 	f->f_time = now;
718 
719 	switch (f->f_type) {
720 	case F_UNUSED:
721 		dprintf("\n");
722 		break;
723 
724 	case F_FORW:
725 		dprintf(" %s\n", f->f_un.f_forw.f_hname);
726 		l = sprintf(line, "<%d>%.15s %s", f->f_prevpri,
727 		    iov[0].iov_base, iov[4].iov_base);
728 		if (l > MAXLINE)
729 			l = MAXLINE;
730 		if ((finet >= 0) &&
731 		     (sendto(finet, line, l, 0,
732 			     (struct sockaddr *)&f->f_un.f_forw.f_addr,
733 			     sizeof(f->f_un.f_forw.f_addr)) != l)) {
734 			int e = errno;
735 			(void)close(f->f_file);
736 			f->f_type = F_UNUSED;
737 			errno = e;
738 			logerror("sendto");
739 		}
740 		break;
741 
742 	case F_FILE:
743 		dprintf(" %s\n", f->f_un.f_fname);
744 		v->iov_base = "\n";
745 		v->iov_len = 1;
746 		if (writev(f->f_file, iov, 6) < 0) {
747 			int e = errno;
748 			(void)close(f->f_file);
749 			f->f_type = F_UNUSED;
750 			errno = e;
751 			logerror(f->f_un.f_fname);
752 		} else if (flags & SYNC_FILE)
753 			(void)fsync(f->f_file);
754 		break;
755 
756 	case F_PIPE:
757 		dprintf(" %s\n", f->f_un.f_pipe.f_pname);
758 		v->iov_base = "\n";
759 		v->iov_len = 1;
760 		if (f->f_un.f_pipe.f_pid == 0) {
761 			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
762 						&f->f_un.f_pipe.f_pid)) < 0) {
763 				f->f_type = F_UNUSED;
764 				logerror(f->f_un.f_pipe.f_pname);
765 				break;
766 			}
767 		}
768 		if (writev(f->f_file, iov, 6) < 0) {
769 			int e = errno;
770 			(void)close(f->f_file);
771 			if (f->f_un.f_pipe.f_pid > 0)
772 				deadq_enter(f->f_un.f_pipe.f_pid);
773 			f->f_un.f_pipe.f_pid = 0;
774 			errno = e;
775 			logerror(f->f_un.f_pipe.f_pname);
776 		}
777 		break;
778 
779 	case F_CONSOLE:
780 		if (flags & IGN_CONS) {
781 			dprintf(" (ignored)\n");
782 			break;
783 		}
784 		/* FALLTHROUGH */
785 
786 	case F_TTY:
787 		dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
788 		v->iov_base = "\r\n";
789 		v->iov_len = 2;
790 
791 		errno = 0;	/* ttymsg() only sometimes returns an errno */
792 		if ((msgret = ttymsg(iov, 6, f->f_un.f_fname, 10))) {
793 			f->f_type = F_UNUSED;
794 			logerror(msgret);
795 		}
796 		break;
797 
798 	case F_USERS:
799 	case F_WALL:
800 		dprintf("\n");
801 		v->iov_base = "\r\n";
802 		v->iov_len = 2;
803 		wallmsg(f, iov);
804 		break;
805 	}
806 	f->f_prevcount = 0;
807 }
808 
809 /*
810  *  WALLMSG -- Write a message to the world at large
811  *
812  *	Write the specified message to either the entire
813  *	world, or a list of approved users.
814  */
815 void
816 wallmsg(f, iov)
817 	struct filed *f;
818 	struct iovec *iov;
819 {
820 	static int reenter;			/* avoid calling ourselves */
821 	FILE *uf;
822 	struct utmp ut;
823 	int i;
824 	char *p;
825 	char line[sizeof(ut.ut_line) + 1];
826 
827 	if (reenter++)
828 		return;
829 	if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
830 		logerror(_PATH_UTMP);
831 		reenter = 0;
832 		return;
833 	}
834 	/* NOSTRICT */
835 	while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
836 		if (ut.ut_name[0] == '\0')
837 			continue;
838 		strncpy(line, ut.ut_line, sizeof(ut.ut_line));
839 		line[sizeof(ut.ut_line)] = '\0';
840 		if (f->f_type == F_WALL) {
841 			if ((p = ttymsg(iov, 6, line, TTYMSGTIME)) != NULL) {
842 				errno = 0;	/* already in msg */
843 				logerror(p);
844 			}
845 			continue;
846 		}
847 		/* should we send the message to this user? */
848 		for (i = 0; i < MAXUNAMES; i++) {
849 			if (!f->f_un.f_uname[i][0])
850 				break;
851 			if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
852 			    UT_NAMESIZE)) {
853 				if ((p = ttymsg(iov, 6, line, TTYMSGTIME))
854 								!= NULL) {
855 					errno = 0;	/* already in msg */
856 					logerror(p);
857 				}
858 				break;
859 			}
860 		}
861 	}
862 	(void)fclose(uf);
863 	reenter = 0;
864 }
865 
866 void
867 reapchild(signo)
868 	int signo;
869 {
870 	int status, code;
871 	pid_t pid;
872 	struct filed *f;
873 	char buf[256];
874 	const char *reason;
875 	dq_t q;
876 
877 	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
878 		if (!Initialized)
879 			/* Don't tell while we are initting. */
880 			continue;
881 
882 		/* First, look if it's a process from the dead queue. */
883 		for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
884 			if (q->dq_pid == pid) {
885 				TAILQ_REMOVE(&deadq_head, q, dq_entries);
886 				free(q);
887 				goto oncemore;
888 			}
889 
890 		/* Now, look in list of active processes. */
891 		for (f = Files; f; f = f->f_next)
892 			if (f->f_type == F_PIPE &&
893 			    f->f_un.f_pipe.f_pid == pid) {
894 				(void)close(f->f_file);
895 
896 				errno = 0; /* Keep strerror() stuff out of logerror messages. */
897 				f->f_un.f_pipe.f_pid = 0;
898 				if (WIFSIGNALED(status)) {
899 					reason = "due to signal";
900 					code = WTERMSIG(status);
901 				} else {
902 					reason = "with status";
903 					code = WEXITSTATUS(status);
904 					if (code == 0)
905 						goto oncemore; /* Exited OK. */
906 				}
907 				(void)snprintf(buf, sizeof buf,
908 				"Logging subprocess %d (%s) exited %s %d.",
909 					       pid, f->f_un.f_pipe.f_pname,
910 					       reason, code);
911 				logerror(buf);
912 				break;
913 			}
914 	  oncemore:
915 	}
916 }
917 
918 /*
919  * Return a printable representation of a host address.
920  */
921 char *
922 cvthname(f)
923 	struct sockaddr_in *f;
924 {
925 	struct hostent *hp;
926 	char *p;
927 
928 	dprintf("cvthname(%s)\n", inet_ntoa(f->sin_addr));
929 
930 	if (f->sin_family != AF_INET) {
931 		dprintf("Malformed from address\n");
932 		return ("???");
933 	}
934 	hp = gethostbyaddr((char *)&f->sin_addr,
935 	    sizeof(struct in_addr), f->sin_family);
936 	if (hp == 0) {
937 		dprintf("Host name for your address (%s) unknown\n",
938 			inet_ntoa(f->sin_addr));
939 		return (inet_ntoa(f->sin_addr));
940 	}
941 	if ((p = strchr(hp->h_name, '.')) && strcmp(p + 1, LocalDomain) == 0)
942 		*p = '\0';
943 	return (hp->h_name);
944 }
945 
946 void
947 domark(signo)
948 	int signo;
949 {
950 	struct filed *f;
951 	dq_t q;
952 
953 	now = time((time_t *)NULL);
954 	MarkSeq += TIMERINTVL;
955 	if (MarkSeq >= MarkInterval) {
956 		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
957 		MarkSeq = 0;
958 	}
959 
960 	for (f = Files; f; f = f->f_next) {
961 		if (f->f_prevcount && now >= REPEATTIME(f)) {
962 			dprintf("flush %s: repeated %d times, %d sec.\n",
963 			    TypeNames[f->f_type], f->f_prevcount,
964 			    repeatinterval[f->f_repeatcount]);
965 			fprintlog(f, 0, (char *)NULL);
966 			BACKOFF(f);
967 		}
968 	}
969 
970 	/* Walk the dead queue, and see if we should signal somebody. */
971 	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
972 		switch (q->dq_timeout) {
973 		case 0:
974 			/* Already signalled once, try harder now. */
975 			kill(q->dq_pid, SIGKILL);
976 			break;
977 
978 		case 1:
979 			/*
980 			 * Timed out on dead queue, send terminate
981 			 * signal.  Note that we leave the removal
982 			 * from the dead queue to reapchild(), which
983 			 * will also log the event.
984 			 */
985 			kill(q->dq_pid, SIGTERM);
986 			/* FALLTROUGH */
987 
988 		default:
989 			q->dq_timeout--;
990 		}
991 
992 	(void)alarm(TIMERINTVL);
993 }
994 
995 /*
996  * Print syslogd errors some place.
997  */
998 void
999 logerror(type)
1000 	const char *type;
1001 {
1002 	char buf[512];
1003 
1004 	if (errno)
1005 		(void)snprintf(buf,
1006 		    sizeof(buf), "syslogd: %s: %s", type, strerror(errno));
1007 	else
1008 		(void)snprintf(buf, sizeof(buf), "syslogd: %s", type);
1009 	errno = 0;
1010 	dprintf("%s\n", buf);
1011 	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1012 }
1013 
1014 void
1015 die(signo)
1016 	int signo;
1017 {
1018 	struct filed *f;
1019 	int was_initialized;
1020 	char buf[100];
1021 
1022 	was_initialized = Initialized;
1023 	Initialized = 0;	/* Don't log SIGCHLDs. */
1024 	for (f = Files; f != NULL; f = f->f_next) {
1025 		/* flush any pending output */
1026 		if (f->f_prevcount)
1027 			fprintlog(f, 0, (char *)NULL);
1028 		if (f->f_type == F_PIPE)
1029 			(void)close(f->f_file);
1030 	}
1031 	Initialized = was_initialized;
1032 	if (signo) {
1033 		dprintf("syslogd: exiting on signal %d\n", signo);
1034 		(void)sprintf(buf, "exiting on signal %d", signo);
1035 		errno = 0;
1036 		logerror(buf);
1037 	}
1038 	if (created_lsock)
1039 		(void)unlink(LogName);
1040 	exit(1);
1041 }
1042 
1043 /*
1044  *  INIT -- Initialize syslogd from configuration table
1045  */
1046 void
1047 init(signo)
1048 	int signo;
1049 {
1050 	int i;
1051 	FILE *cf;
1052 	struct filed *f, *next, **nextp;
1053 	char *p;
1054 	char cline[LINE_MAX];
1055  	char prog[NAME_MAX+1];
1056 
1057 	dprintf("init\n");
1058 
1059 	/*
1060 	 *  Close all open log files.
1061 	 */
1062 	Initialized = 0;
1063 	for (f = Files; f != NULL; f = next) {
1064 		/* flush any pending output */
1065 		if (f->f_prevcount)
1066 			fprintlog(f, 0, (char *)NULL);
1067 
1068 		switch (f->f_type) {
1069 		case F_FILE:
1070 		case F_FORW:
1071 		case F_CONSOLE:
1072 		case F_TTY:
1073 			(void)close(f->f_file);
1074 			break;
1075 		case F_PIPE:
1076 			(void)close(f->f_file);
1077 			if (f->f_un.f_pipe.f_pid > 0)
1078 				deadq_enter(f->f_un.f_pipe.f_pid);
1079 			f->f_un.f_pipe.f_pid = 0;
1080 			break;
1081 		}
1082 		next = f->f_next;
1083 		if(f->f_program) free(f->f_program);
1084 		free((char *)f);
1085 	}
1086 	Files = NULL;
1087 	nextp = &Files;
1088 
1089 	/* open the configuration file */
1090 	if ((cf = fopen(ConfFile, "r")) == NULL) {
1091 		dprintf("cannot open %s\n", ConfFile);
1092 		*nextp = (struct filed *)calloc(1, sizeof(*f));
1093 		cfline("*.ERR\t/dev/console", *nextp, "*");
1094 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1095 		cfline("*.PANIC\t*", (*nextp)->f_next, "*");
1096 		Initialized = 1;
1097 		return;
1098 	}
1099 
1100 	/*
1101 	 *  Foreach line in the conf table, open that file.
1102 	 */
1103 	f = NULL;
1104 	strcpy(prog, "*");
1105 	while (fgets(cline, sizeof(cline), cf) != NULL) {
1106 		/*
1107 		 * check for end-of-section, comments, strip off trailing
1108 		 * spaces and newline character. #!prog is treated specially:
1109 		 * following lines apply only to that program.
1110 		 */
1111 		for (p = cline; isspace(*p); ++p)
1112 			continue;
1113 		if (*p == 0)
1114 			continue;
1115 		if(*p == '#') {
1116 			p++;
1117 			if(*p!='!')
1118 				continue;
1119 		}
1120 		if(*p=='!') {
1121 			p++;
1122 			while(isspace(*p)) p++;
1123 			if(!*p) {
1124 				strcpy(prog, "*");
1125 				continue;
1126 			}
1127 			for(i = 0; i < NAME_MAX; i++) {
1128 				if(!isalnum(p[i]))
1129 					break;
1130 				prog[i] = p[i];
1131 			}
1132 			prog[i] = 0;
1133 			continue;
1134 		}
1135 		for (p = strchr(cline, '\0'); isspace(*--p);)
1136 			continue;
1137 		*++p = '\0';
1138 		f = (struct filed *)calloc(1, sizeof(*f));
1139 		*nextp = f;
1140 		nextp = &f->f_next;
1141 		cfline(cline, f, prog);
1142 	}
1143 
1144 	/* close the configuration file */
1145 	(void)fclose(cf);
1146 
1147 	Initialized = 1;
1148 
1149 	if (Debug) {
1150 		for (f = Files; f; f = f->f_next) {
1151 			for (i = 0; i <= LOG_NFACILITIES; i++)
1152 				if (f->f_pmask[i] == INTERNAL_NOPRI)
1153 					printf("X ");
1154 				else
1155 					printf("%d ", f->f_pmask[i]);
1156 			printf("%s: ", TypeNames[f->f_type]);
1157 			switch (f->f_type) {
1158 			case F_FILE:
1159 				printf("%s", f->f_un.f_fname);
1160 				break;
1161 
1162 			case F_CONSOLE:
1163 			case F_TTY:
1164 				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1165 				break;
1166 
1167 			case F_FORW:
1168 				printf("%s", f->f_un.f_forw.f_hname);
1169 				break;
1170 
1171 			case F_PIPE:
1172 				printf("%s", f->f_un.f_pipe.f_pname);
1173 				break;
1174 
1175 			case F_USERS:
1176 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1177 					printf("%s, ", f->f_un.f_uname[i]);
1178 				break;
1179 			}
1180 			if(f->f_program) {
1181 				printf(" (%s)", f->f_program);
1182 			}
1183 			printf("\n");
1184 		}
1185 	}
1186 
1187 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1188 	dprintf("syslogd: restarted\n");
1189 }
1190 
1191 /*
1192  * Crack a configuration file line
1193  */
1194 void
1195 cfline(line, f, prog)
1196 	char *line;
1197 	struct filed *f;
1198 	char *prog;
1199 {
1200 	struct hostent *hp;
1201 	int i, pri;
1202 	char *bp, *p, *q;
1203 	char buf[MAXLINE], ebuf[100];
1204 
1205 	dprintf("cfline(\"%s\", f, \"%s\")\n", line, prog);
1206 
1207 	errno = 0;	/* keep strerror() stuff out of logerror messages */
1208 
1209 	/* clear out file entry */
1210 	memset(f, 0, sizeof(*f));
1211 	for (i = 0; i <= LOG_NFACILITIES; i++)
1212 		f->f_pmask[i] = INTERNAL_NOPRI;
1213 
1214 	/* save program name if any */
1215 	if(prog && *prog=='*') prog = NULL;
1216 	if(prog) {
1217 		f->f_program = calloc(1, strlen(prog)+1);
1218 		if(f->f_program) {
1219 			strcpy(f->f_program, prog);
1220 		}
1221 	}
1222 
1223 	/* scan through the list of selectors */
1224 	for (p = line; *p && *p != '\t';) {
1225 
1226 		/* find the end of this facility name list */
1227 		for (q = p; *q && *q != '\t' && *q++ != '.'; )
1228 			continue;
1229 
1230 		/* collect priority name */
1231 		for (bp = buf; *q && !strchr("\t,;", *q); )
1232 			*bp++ = *q++;
1233 		*bp = '\0';
1234 
1235 		/* skip cruft */
1236 		while (strchr(", ;", *q))
1237 			q++;
1238 
1239 		/* decode priority name */
1240 		if (*buf == '*')
1241 			pri = LOG_PRIMASK + 1;
1242 		else {
1243 			pri = decode(buf, prioritynames);
1244 			if (pri < 0) {
1245 				(void)sprintf(ebuf,
1246 				    "unknown priority name \"%s\"", buf);
1247 				logerror(ebuf);
1248 				return;
1249 			}
1250 		}
1251 
1252 		/* scan facilities */
1253 		while (*p && !strchr("\t.;", *p)) {
1254 			for (bp = buf; *p && !strchr("\t,;.", *p); )
1255 				*bp++ = *p++;
1256 			*bp = '\0';
1257 			if (*buf == '*')
1258 				for (i = 0; i < LOG_NFACILITIES; i++)
1259 					f->f_pmask[i] = pri;
1260 			else {
1261 				i = decode(buf, facilitynames);
1262 				if (i < 0) {
1263 					(void)sprintf(ebuf,
1264 					    "unknown facility name \"%s\"",
1265 					    buf);
1266 					logerror(ebuf);
1267 					return;
1268 				}
1269 				f->f_pmask[i >> 3] = pri;
1270 			}
1271 			while (*p == ',' || *p == ' ')
1272 				p++;
1273 		}
1274 
1275 		p = q;
1276 	}
1277 
1278 	/* skip to action part */
1279 	while (*p == '\t')
1280 		p++;
1281 
1282 	switch (*p)
1283 	{
1284 	case '@':
1285 		if (!InetInuse)
1286 			break;
1287 		(void)strcpy(f->f_un.f_forw.f_hname, ++p);
1288 		hp = gethostbyname(p);
1289 		if (hp == NULL) {
1290 			extern int h_errno;
1291 
1292 			logerror(hstrerror(h_errno));
1293 			break;
1294 		}
1295 		memset(&f->f_un.f_forw.f_addr, 0,
1296 			 sizeof(f->f_un.f_forw.f_addr));
1297 		f->f_un.f_forw.f_addr.sin_family = AF_INET;
1298 		f->f_un.f_forw.f_addr.sin_port = LogPort;
1299 		memmove(&f->f_un.f_forw.f_addr.sin_addr, hp->h_addr, hp->h_length);
1300 		f->f_type = F_FORW;
1301 		break;
1302 
1303 	case '/':
1304 		if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1305 			f->f_type = F_UNUSED;
1306 			logerror(p);
1307 			break;
1308 		}
1309 		if (isatty(f->f_file)) {
1310 			if (strcmp(p, ctty) == 0)
1311 				f->f_type = F_CONSOLE;
1312 			else
1313 				f->f_type = F_TTY;
1314 			(void)strcpy(f->f_un.f_fname, p + sizeof _PATH_DEV - 1);
1315 		} else {
1316 			(void)strcpy(f->f_un.f_fname, p);
1317 			f->f_type = F_FILE;
1318 		}
1319 		break;
1320 
1321 	case '|':
1322 		f->f_un.f_pipe.f_pid = 0;
1323 		(void)strcpy(f->f_un.f_pipe.f_pname, p + 1);
1324 		f->f_type = F_PIPE;
1325 		break;
1326 
1327 	case '*':
1328 		f->f_type = F_WALL;
1329 		break;
1330 
1331 	default:
1332 		for (i = 0; i < MAXUNAMES && *p; i++) {
1333 			for (q = p; *q && *q != ','; )
1334 				q++;
1335 			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1336 			if ((q - p) > UT_NAMESIZE)
1337 				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1338 			else
1339 				f->f_un.f_uname[i][q - p] = '\0';
1340 			while (*q == ',' || *q == ' ')
1341 				q++;
1342 			p = q;
1343 		}
1344 		f->f_type = F_USERS;
1345 		break;
1346 	}
1347 }
1348 
1349 
1350 /*
1351  *  Decode a symbolic name to a numeric value
1352  */
1353 int
1354 decode(name, codetab)
1355 	const char *name;
1356 	CODE *codetab;
1357 {
1358 	CODE *c;
1359 	char *p, buf[40];
1360 
1361 	if (isdigit(*name))
1362 		return (atoi(name));
1363 
1364 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1365 		if (isupper(*name))
1366 			*p = tolower(*name);
1367 		else
1368 			*p = *name;
1369 	}
1370 	*p = '\0';
1371 	for (c = codetab; c->c_name; c++)
1372 		if (!strcmp(buf, c->c_name))
1373 			return (c->c_val);
1374 
1375 	return (-1);
1376 }
1377 
1378 /*
1379  * fork off and become a daemon, but wait for the child to come online
1380  * before returing to the parent, or we get disk thrashing at boot etc.
1381  * Set a timer so we don't hang forever if it wedges.
1382  */
1383 int
1384 waitdaemon(nochdir, noclose, maxwait)
1385 	int nochdir, noclose, maxwait;
1386 {
1387 	int fd;
1388 	int status;
1389 	pid_t pid, childpid;
1390 
1391 	switch (childpid = fork()) {
1392 	case -1:
1393 		return (-1);
1394 	case 0:
1395 		break;
1396 	default:
1397 		signal(SIGALRM, timedout);
1398 		alarm(maxwait);
1399 		while ((pid = wait3(&status, 0, NULL)) != -1) {
1400 			if (WIFEXITED(status))
1401 				errx(1, "child pid %d exited with return code %d",
1402 					pid, WEXITSTATUS(status));
1403 			if (WIFSIGNALED(status))
1404 				errx(1, "child pid %d exited on signal %d%s",
1405 					pid, WTERMSIG(status),
1406 					WCOREDUMP(status) ? " (core dumped)" :
1407 					"");
1408 			if (pid == childpid)	/* it's gone... */
1409 				break;
1410 		}
1411 		exit(0);
1412 	}
1413 
1414 	if (setsid() == -1)
1415 		return (-1);
1416 
1417 	if (!nochdir)
1418 		(void)chdir("/");
1419 
1420 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1421 		(void)dup2(fd, STDIN_FILENO);
1422 		(void)dup2(fd, STDOUT_FILENO);
1423 		(void)dup2(fd, STDERR_FILENO);
1424 		if (fd > 2)
1425 			(void)close (fd);
1426 	}
1427 	return (getppid());
1428 }
1429 
1430 /*
1431  * We get a SIGALRM from the child when it's running and finished doing it's
1432  * fsync()'s or O_SYNC writes for all the boot messages.
1433  *
1434  * We also get a signal from the kernel if the timer expires, so check to
1435  * see what happened.
1436  */
1437 void
1438 timedout(sig)
1439 	int sig __unused;
1440 {
1441 	int left;
1442 	left = alarm(0);
1443 	signal(SIGALRM, SIG_DFL);
1444 	if (left == 0)
1445 		errx(1, "timed out waiting for child");
1446 	else
1447 		exit(0);
1448 }
1449 
1450 /*
1451  * Fairly similar to popen(3), but returns an open descriptor, as
1452  * opposed to a FILE *.
1453  */
1454 int
1455 p_open(prog, pid)
1456 	char *prog;
1457 	pid_t *pid;
1458 {
1459 	int pfd[2], nulldesc, i;
1460 	sigset_t omask, mask;
1461 	char *argv[4]; /* sh -c cmd NULL */
1462 	char errmsg[200];
1463 
1464 	if (pipe(pfd) == -1)
1465 		return -1;
1466 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
1467 		/* we are royally screwed anyway */
1468 		return -1;
1469 
1470 	mask = sigmask(SIGALRM) | sigmask(SIGHUP);
1471 	sigprocmask(SIG_BLOCK, &omask, &mask);
1472 	switch ((*pid = fork())) {
1473 	case -1:
1474 		sigprocmask(SIG_SETMASK, 0, &omask);
1475 		close(nulldesc);
1476 		return -1;
1477 
1478 	case 0:
1479 		argv[0] = "sh";
1480 		argv[1] = "-c";
1481 		argv[2] = prog;
1482 		argv[3] = NULL;
1483 
1484 		alarm(0);
1485 		(void)setsid();	/* Avoid catching SIGHUPs. */
1486 
1487 		/*
1488 		 * Throw away pending signals, and reset signal
1489 		 * behaviour to standard values.
1490 		 */
1491 		signal(SIGALRM, SIG_IGN);
1492 		signal(SIGHUP, SIG_IGN);
1493 		sigprocmask(SIG_SETMASK, 0, &omask);
1494 		signal(SIGPIPE, SIG_DFL);
1495 		signal(SIGQUIT, SIG_DFL);
1496 		signal(SIGALRM, SIG_DFL);
1497 		signal(SIGHUP, SIG_DFL);
1498 
1499 		dup2(pfd[0], STDIN_FILENO);
1500 		dup2(nulldesc, STDOUT_FILENO);
1501 		dup2(nulldesc, STDERR_FILENO);
1502 		for (i = getdtablesize(); i > 2; i--)
1503 			(void) close(i);
1504 
1505 		(void) execvp(_PATH_BSHELL, argv);
1506 		_exit(255);
1507 	}
1508 
1509 	sigprocmask(SIG_SETMASK, 0, &omask);
1510 	close(nulldesc);
1511 	close(pfd[0]);
1512 	/*
1513 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
1514 	 * supposed to get an EWOULDBLOCK on writev(2), which is
1515 	 * caught by the logic above anyway, which will in turn close
1516 	 * the pipe, and fork a new logging subprocess if necessary.
1517 	 * The stale subprocess will be killed some time later unless
1518 	 * it terminated itself due to closing its input pipe (so we
1519 	 * get rid of really dead puppies).
1520 	 */
1521 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
1522 		/* This is bad. */
1523 		(void)snprintf(errmsg, sizeof errmsg,
1524 			       "Warning: cannot change pipe to PID %d to "
1525 			       "non-blocking behaviour.",
1526 			       (int)*pid);
1527 		logerror(errmsg);
1528 	}
1529 	return pfd[1];
1530 }
1531 
1532 void
1533 deadq_enter(pid)
1534 	pid_t pid;
1535 {
1536 	dq_t p;
1537 
1538 	p = malloc(sizeof(struct deadq_entry));
1539 	if (p == 0) {
1540 		errno = 0;
1541 		logerror("panic: out of virtual memory!");
1542 		exit(1);
1543 	}
1544 
1545 	p->dq_pid = pid;
1546 	p->dq_timeout = DQ_TIMO_INIT;
1547 	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
1548 }
1549