syslogd.c revision 82442
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
35static const char copyright[] =
36"@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
43#endif
44static const char rcsid[] =
45  "$FreeBSD: head/usr.sbin/syslogd/syslogd.c 82442 2001-08-27 21:37:15Z cjc $";
46#endif /* not lint */
47
48/*
49 *  syslogd -- log system messages
50 *
51 * This program implements a system log. It takes a series of lines.
52 * Each line may have a priority, signified as "<n>" as
53 * the first characters of the line.  If this is
54 * not present, a default priority is used.
55 *
56 * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
57 * cause it to reread its configuration file.
58 *
59 * Defined Constants:
60 *
61 * MAXLINE -- the maximimum line length that can be handled.
62 * DEFUPRI -- the default priority for user messages
63 * DEFSPRI -- the default priority for kernel messages
64 *
65 * Author: Eric Allman
66 * extensive changes by Ralph Campbell
67 * more extensive changes by Eric Allman (again)
68 * Extension to log by program name as well as facility and priority
69 *   by Peter da Silva.
70 * -u and -v by Harlan Stenn.
71 * Priority comparison code by Harlan Stenn.
72 */
73
74#define	MAXLINE		1024		/* maximum line length */
75#define	MAXSVLINE	120		/* maximum saved line length */
76#define DEFUPRI		(LOG_USER|LOG_NOTICE)
77#define DEFSPRI		(LOG_KERN|LOG_CRIT)
78#define TIMERINTVL	30		/* interval for checking flush, mark */
79#define TTYMSGTIME	1		/* timed out passed to ttymsg */
80
81#include <sys/param.h>
82#include <sys/ioctl.h>
83#include <sys/stat.h>
84#include <sys/wait.h>
85#include <sys/socket.h>
86#include <sys/queue.h>
87#include <sys/uio.h>
88#include <sys/un.h>
89#include <sys/time.h>
90#include <sys/resource.h>
91#include <sys/syslimits.h>
92#include <paths.h>
93
94#include <netinet/in.h>
95#include <netdb.h>
96#include <arpa/inet.h>
97
98#include <ctype.h>
99#include <err.h>
100#include <errno.h>
101#include <fcntl.h>
102#include <setjmp.h>
103#include <signal.h>
104#include <stdio.h>
105#include <stdlib.h>
106#include <string.h>
107#include <sysexits.h>
108#include <unistd.h>
109#include <utmp.h>
110#include "pathnames.h"
111
112#define SYSLOG_NAMES
113#include <sys/syslog.h>
114
115#ifdef NI_WITHSCOPEID
116static const int withscopeid = NI_WITHSCOPEID;
117#else
118static const int withscopeid = 0;
119#endif
120
121const char	*ConfFile = _PATH_LOGCONF;
122const char	*PidFile = _PATH_LOGPID;
123const char	ctty[] = _PATH_CONSOLE;
124
125#define	dprintf		if (Debug) printf
126
127#define MAXUNAMES	20	/* maximum number of user names */
128
129#define MAXFUNIX       20
130
131int nfunix = 1;
132char *funixn[MAXFUNIX] = { _PATH_LOG };
133int funix[MAXFUNIX];
134
135/*
136 * Flags to logmsg().
137 */
138
139#define IGN_CONS	0x001	/* don't print on console */
140#define SYNC_FILE	0x002	/* do fsync on file after printing */
141#define ADDDATE		0x004	/* add a date to the message */
142#define MARK		0x008	/* this message is a mark */
143#define ISKERNEL	0x010	/* kernel generated message */
144
145/*
146 * This structure represents the files that will have log
147 * copies printed.
148 */
149
150struct filed {
151	struct	filed *f_next;		/* next in linked list */
152	short	f_type;			/* entry type, see below */
153	short	f_file;			/* file descriptor */
154	time_t	f_time;			/* time this was last written */
155	char	*f_host;		/* host from which to recd. */
156	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
157	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
158#define PRI_LT	0x1
159#define PRI_EQ	0x2
160#define PRI_GT	0x4
161	char	*f_program;		/* program this applies to */
162	union {
163		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
164		struct {
165			char	f_hname[MAXHOSTNAMELEN];
166			struct addrinfo *f_addr;
167
168		} f_forw;		/* forwarding address */
169		char	f_fname[MAXPATHLEN];
170		struct {
171			char	f_pname[MAXPATHLEN];
172			pid_t	f_pid;
173		} f_pipe;
174	} f_un;
175	char	f_prevline[MAXSVLINE];		/* last message logged */
176	char	f_lasttime[16];			/* time of last occurrence */
177	char	f_prevhost[MAXHOSTNAMELEN];	/* host from which recd. */
178	int	f_prevpri;			/* pri of f_prevline */
179	int	f_prevlen;			/* length of f_prevline */
180	int	f_prevcount;			/* repetition cnt of prevline */
181	int	f_repeatcount;			/* number of "repeated" msgs */
182};
183
184/*
185 * Queue of about-to-be dead processes we should watch out for.
186 */
187
188TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
189struct stailhead *deadq_headp;
190
191struct deadq_entry {
192	pid_t				dq_pid;
193	int				dq_timeout;
194	TAILQ_ENTRY(deadq_entry)	dq_entries;
195};
196
197/*
198 * The timeout to apply to processes waiting on the dead queue.  Unit
199 * of measure is `mark intervals', i.e. 20 minutes by default.
200 * Processes on the dead queue will be terminated after that time.
201 */
202
203#define DQ_TIMO_INIT	2
204
205typedef struct deadq_entry *dq_t;
206
207
208/*
209 * Struct to hold records of network addresses that are allowed to log
210 * to us.
211 */
212struct allowedpeer {
213	int isnumeric;
214	u_short port;
215	union {
216		struct {
217			struct sockaddr_storage addr;
218			struct sockaddr_storage mask;
219		} numeric;
220		char *name;
221	} u;
222#define a_addr u.numeric.addr
223#define a_mask u.numeric.mask
224#define a_name u.name
225};
226
227
228/*
229 * Intervals at which we flush out "message repeated" messages,
230 * in seconds after previous message is logged.  After each flush,
231 * we move to the next interval until we reach the largest.
232 */
233int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
234#define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
235#define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
236#define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
237				 (f)->f_repeatcount = MAXREPEAT; \
238			}
239
240/* values for f_type */
241#define F_UNUSED	0		/* unused entry */
242#define F_FILE		1		/* regular file */
243#define F_TTY		2		/* terminal */
244#define F_CONSOLE	3		/* console terminal */
245#define F_FORW		4		/* remote machine */
246#define F_USERS		5		/* list of users */
247#define F_WALL		6		/* everyone logged on */
248#define F_PIPE		7		/* pipe to program */
249
250char	*TypeNames[8] = {
251	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
252	"FORW",		"USERS",	"WALL",		"PIPE"
253};
254
255struct	filed *Files;
256struct	filed consfile;
257
258int	Debug;			/* debug flag */
259int	resolve = 1;		/* resolve hostname */
260char	LocalHostName[MAXHOSTNAMELEN];	/* our hostname */
261char	*LocalDomain;		/* our local domain name */
262int	*finet = NULL;		/* Internet datagram socket */
263int	fklog = -1;		/* /dev/klog */
264int	Initialized = 0;	/* set when we have initialized ourselves */
265int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
266int	MarkSeq = 0;		/* mark sequence number */
267int	SecureMode = 0;		/* when true, receive only unix domain socks */
268#ifdef INET6
269int	family = PF_UNSPEC;	/* protocol family (IPv4, IPv6 or both) */
270#else
271int	family = PF_INET;	/* protocol family (IPv4 only) */
272#endif
273int	send_to_all = 0;	/* send message to all IPv4/IPv6 addresses */
274
275char	bootfile[MAXLINE+1];	/* booted kernel file */
276
277struct allowedpeer *AllowedPeers;
278int	NumAllowed = 0;		/* # of AllowedPeer entries */
279
280int	UniquePriority = 0;	/* Only log specified priority? */
281int	LogFacPri = 0;		/* Put facility and priority in log message: */
282				/* 0=no, 1=numeric, 2=names */
283int	KeepKernFac = 0;	/* Keep remotely logged kernel facility */
284
285int	allowaddr __P((char *));
286void	cfline __P((char *, struct filed *, char *, char *));
287char   *cvthname __P((struct sockaddr *));
288void	deadq_enter __P((pid_t, const char *));
289int	deadq_remove __P((pid_t));
290int	decode __P((const char *, CODE *));
291void	die __P((int));
292void	domark __P((int));
293void	fprintlog __P((struct filed *, int, char *));
294int*	socksetup __P((int));
295void	init __P((int));
296void	logerror __P((const char *));
297void	logmsg __P((int, char *, char *, int));
298void	log_deadchild __P((pid_t, int, const char *));
299void	printline __P((char *, char *));
300void	printsys __P((char *));
301int	p_open __P((char *, pid_t *));
302void	readklog __P((void));
303void	reapchild __P((int));
304char   *ttymsg __P((struct iovec *, int, char *, int));
305static void	usage __P((void));
306int	validate __P((struct sockaddr *, const char *));
307static void	unmapped __P((struct sockaddr *));
308void	wallmsg __P((struct filed *, struct iovec *));
309int	waitdaemon __P((int, int, int));
310void	timedout __P((int));
311
312int
313main(argc, argv)
314	int argc;
315	char *argv[];
316{
317	int ch, i, l;
318	struct sockaddr_un sunx, fromunix;
319	struct sockaddr_storage frominet;
320	FILE *fp;
321	char *hname, line[MAXLINE + 1];
322	struct timeval tv, *tvp;
323	struct sigaction sact;
324	sigset_t mask;
325	pid_t ppid = 1;
326	socklen_t len;
327
328	while ((ch = getopt(argc, argv, "46Aa:df:kl:m:np:P:suv")) != -1)
329		switch (ch) {
330		case '4':
331			family = PF_INET;
332			break;
333#ifdef INET6
334		case '6':
335			family = PF_INET6;
336			break;
337#endif
338		case 'A':
339			send_to_all++;
340			break;
341		case 'a':		/* allow specific network addresses only */
342			if (allowaddr(optarg) == -1)
343				usage();
344			break;
345		case 'd':		/* debug */
346			Debug++;
347			break;
348		case 'f':		/* configuration file */
349			ConfFile = optarg;
350			break;
351		case 'k':		/* keep remote kern fac */
352			KeepKernFac = 1;
353			break;
354		case 'l':
355			if (nfunix < MAXFUNIX)
356				funixn[nfunix++] = optarg;
357			else
358				warnx("out of descriptors, ignoring %s",
359					optarg);
360			break;
361		case 'm':		/* mark interval */
362			MarkInterval = atoi(optarg) * 60;
363			break;
364		case 'n':
365			resolve = 0;
366			break;
367		case 'p':		/* path */
368			funixn[0] = optarg;
369			break;
370		case 'P':		/* path for alt. PID */
371			PidFile = optarg;
372			break;
373		case 's':		/* no network mode */
374			SecureMode++;
375			break;
376		case 'u':		/* only log specified priority */
377		        UniquePriority++;
378			break;
379		case 'v':		/* log facility and priority */
380		  	LogFacPri++;
381			break;
382		case '?':
383		default:
384			usage();
385		}
386	if ((argc -= optind) != 0)
387		usage();
388
389	if (!Debug) {
390		ppid = waitdaemon(0, 0, 30);
391		if (ppid < 0)
392			err(1, "could not become daemon");
393	} else
394		setlinebuf(stdout);
395
396	if (NumAllowed)
397		endservent();
398
399	consfile.f_type = F_CONSOLE;
400	(void)strcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1);
401	(void)strcpy(bootfile, getbootfile());
402	(void)signal(SIGTERM, die);
403	(void)signal(SIGINT, Debug ? die : SIG_IGN);
404	(void)signal(SIGQUIT, Debug ? die : SIG_IGN);
405	/*
406	 * We don't want the SIGCHLD and SIGHUP handlers to interfere
407	 * with each other; they are likely candidates for being called
408	 * simultaneously (SIGHUP closes pipe descriptor, process dies,
409	 * SIGCHLD happens).
410	 */
411	sigemptyset(&mask);
412	sigaddset(&mask, SIGHUP);
413	sact.sa_handler = reapchild;
414	sact.sa_mask = mask;
415	sact.sa_flags = SA_RESTART;
416	(void)sigaction(SIGCHLD, &sact, NULL);
417	(void)signal(SIGALRM, domark);
418	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
419	(void)alarm(TIMERINTVL);
420
421	TAILQ_INIT(&deadq_head);
422
423#ifndef SUN_LEN
424#define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
425#endif
426	for (i = 0; i < nfunix; i++) {
427		memset(&sunx, 0, sizeof(sunx));
428		sunx.sun_family = AF_UNIX;
429		(void)strncpy(sunx.sun_path, funixn[i], sizeof(sunx.sun_path));
430		funix[i] = socket(AF_UNIX, SOCK_DGRAM, 0);
431		if (funix[i] < 0 ||
432		    bind(funix[i], (struct sockaddr *)&sunx,
433			 SUN_LEN(&sunx)) < 0 ||
434		    chmod(funixn[i], 0666) < 0) {
435			(void) snprintf(line, sizeof line,
436					"cannot create %s", funixn[i]);
437			logerror(line);
438			dprintf("cannot create %s (%d)\n", funixn[i], errno);
439			if (i == 0)
440				die(0);
441		}
442	}
443	if (SecureMode <= 1)
444		finet = socksetup(family);
445
446	if (finet) {
447		if (SecureMode) {
448			for (i = 0; i < *finet; i++) {
449				if (shutdown(finet[i+1], SHUT_RD) < 0) {
450					logerror("shutdown");
451					if (!Debug)
452						die(0);
453				}
454			}
455		} else
456			dprintf("listening on inet and/or inet6 socket\n");
457		dprintf("sending on inet and/or inet6 socket\n");
458	}
459
460	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
461		if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
462			fklog = -1;
463	if (fklog < 0)
464		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
465
466	/* tuck my process id away */
467	fp = fopen(PidFile, "w");
468	if (fp != NULL) {
469		fprintf(fp, "%d\n", getpid());
470		(void) fclose(fp);
471	}
472
473	dprintf("off & running....\n");
474
475	init(0);
476	/* prevent SIGHUP and SIGCHLD handlers from running in parallel */
477	sigemptyset(&mask);
478	sigaddset(&mask, SIGCHLD);
479	sact.sa_handler = init;
480	sact.sa_mask = mask;
481	sact.sa_flags = SA_RESTART;
482	(void)sigaction(SIGHUP, &sact, NULL);
483
484	tvp = &tv;
485	tv.tv_sec = tv.tv_usec = 0;
486
487	for (;;) {
488		fd_set readfds;
489		int nfds = 0;
490
491		FD_ZERO(&readfds);
492		if (fklog != -1) {
493			FD_SET(fklog, &readfds);
494			if (fklog > nfds)
495				nfds = fklog;
496		}
497		if (finet && !SecureMode) {
498			for (i = 0; i < *finet; i++) {
499				FD_SET(finet[i+1], &readfds);
500				if (finet[i+1] > nfds)
501					nfds = finet[i+1];
502			}
503		}
504		for (i = 0; i < nfunix; i++) {
505			if (funix[i] != -1) {
506				FD_SET(funix[i], &readfds);
507				if (funix[i] > nfds)
508					nfds = funix[i];
509			}
510		}
511
512		/*dprintf("readfds = %#x\n", readfds);*/
513		nfds = select(nfds+1, &readfds, (fd_set *)NULL,
514			      (fd_set *)NULL, tvp);
515		if (nfds == 0) {
516			if (tvp) {
517				tvp = NULL;
518				if (ppid != 1)
519					kill(ppid, SIGALRM);
520			}
521			continue;
522		}
523		if (nfds < 0) {
524			if (errno != EINTR)
525				logerror("select");
526			continue;
527		}
528		/*dprintf("got a message (%d, %#x)\n", nfds, readfds);*/
529		if (fklog != -1 && FD_ISSET(fklog, &readfds))
530			readklog();
531		if (finet && !SecureMode) {
532			for (i = 0; i < *finet; i++) {
533				if (FD_ISSET(finet[i+1], &readfds)) {
534					len = sizeof(frominet);
535					l = recvfrom(finet[i+1], line, MAXLINE,
536					     0, (struct sockaddr *)&frominet,
537					     &len);
538					if (l > 0) {
539						line[l] = '\0';
540						hname = cvthname((struct sockaddr *)&frominet);
541						unmapped((struct sockaddr *)&frominet);
542						if (validate((struct sockaddr *)&frominet, hname))
543							printline(hname, line);
544					} else if (l < 0 && errno != EINTR)
545						logerror("recvfrom inet");
546				}
547			}
548		}
549		for (i = 0; i < nfunix; i++) {
550			if (funix[i] != -1 && FD_ISSET(funix[i], &readfds)) {
551				len = sizeof(fromunix);
552				l = recvfrom(funix[i], line, MAXLINE, 0,
553				    (struct sockaddr *)&fromunix, &len);
554				if (l > 0) {
555					line[l] = '\0';
556					printline(LocalHostName, line);
557				} else if (l < 0 && errno != EINTR)
558					logerror("recvfrom unix");
559			}
560		}
561	}
562}
563
564static void
565unmapped(sa)
566	struct sockaddr *sa;
567{
568	struct sockaddr_in6 *sin6;
569	struct sockaddr_in sin;
570
571	if (sa->sa_family != AF_INET6)
572		return;
573	if (sa->sa_len != sizeof(struct sockaddr_in6) ||
574	    sizeof(sin) > sa->sa_len)
575		return;
576	sin6 = (struct sockaddr_in6 *)sa;
577	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
578		return;
579
580	memset(&sin, 0, sizeof(sin));
581	sin.sin_family = AF_INET;
582	sin.sin_len = sizeof(struct sockaddr_in);
583	memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
584	       sizeof(sin.sin_addr));
585	sin.sin_port = sin6->sin6_port;
586
587	memcpy(sa, &sin, sin.sin_len);
588}
589
590static void
591usage()
592{
593
594	fprintf(stderr, "%s\n%s\n%s\n",
595		"usage: syslogd [-46Adnsuv] [-a allowed_peer] [-f config_file]",
596		"               [-m mark_interval] [-l log_socket]",
597		"               [-p log_socket] [-P pid_file]");
598	exit(1);
599}
600
601/*
602 * Take a raw input line, decode the message, and print the message
603 * on the appropriate log files.
604 */
605void
606printline(hname, msg)
607	char *hname;
608	char *msg;
609{
610	int c, pri;
611	char *p, *q, line[MAXLINE + 1];
612
613	/* test for special codes */
614	pri = DEFUPRI;
615	p = msg;
616	if (*p == '<') {
617		pri = 0;
618		while (isdigit(*++p))
619			pri = 10 * pri + (*p - '0');
620		if (*p == '>')
621			++p;
622	}
623	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
624		pri = DEFUPRI;
625
626	/* don't allow users to log kernel messages */
627	if (LOG_FAC(pri) == LOG_KERN && !KeepKernFac)
628		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
629
630	q = line;
631
632	while ((c = (unsigned char)*p++) != '\0' &&
633	    q < &line[sizeof(line) - 4]) {
634		if ((c & 0x80) && c < 0xA0) {
635			c &= 0x7F;
636			*q++ = 'M';
637			*q++ = '-';
638		}
639		if (isascii(c) && iscntrl(c)) {
640			if (c == '\n')
641				*q++ = ' ';
642			else if (c == '\t')
643				*q++ = '\t';
644			else {
645				*q++ = '^';
646				*q++ = c ^ 0100;
647			}
648		} else
649			*q++ = c;
650	}
651	*q = '\0';
652
653	logmsg(pri, line, hname, 0);
654}
655
656/*
657 * Read /dev/klog while data are available, split into lines.
658 */
659void
660readklog()
661{
662	char *p, *q, line[MAXLINE + 1];
663	int len, i;
664
665	len = 0;
666	for (;;) {
667		i = read(fklog, line + len, MAXLINE - 1 - len);
668		if (i > 0)
669			line[i + len] = '\0';
670		else if (i < 0 && errno != EINTR && errno != EAGAIN) {
671			logerror("klog");
672			fklog = -1;
673			break;
674		} else
675			break;
676
677		for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
678			*q = '\0';
679			printsys(p);
680		}
681		len = strlen(p);
682		if (len >= MAXLINE - 1) {
683			printsys(p);
684			len = 0;
685		}
686		if (len > 0)
687			memmove(line, p, len + 1);
688	}
689	if (len > 0)
690		printsys(line);
691}
692
693/*
694 * Take a raw input line from /dev/klog, format similar to syslog().
695 */
696void
697printsys(p)
698	char *p;
699{
700	int pri, flags;
701
702	flags = ISKERNEL | SYNC_FILE | ADDDATE;	/* fsync after write */
703	pri = DEFSPRI;
704	if (*p == '<') {
705		pri = 0;
706		while (isdigit(*++p))
707			pri = 10 * pri + (*p - '0');
708		if (*p == '>')
709			++p;
710		if ((pri & LOG_FACMASK) == LOG_CONSOLE)
711			flags |= IGN_CONS;
712	} else {
713		/* kernel printf's come out on console */
714		flags |= IGN_CONS;
715	}
716	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
717		pri = DEFSPRI;
718	logmsg(pri, p, LocalHostName, flags);
719}
720
721time_t	now;
722
723/*
724 * Log a message to the appropriate log files, users, etc. based on
725 * the priority.
726 */
727void
728logmsg(pri, msg, from, flags)
729	int pri;
730	char *msg, *from;
731	int flags;
732{
733	struct filed *f;
734	int i, fac, msglen, omask, prilev;
735	char *timestamp;
736 	char prog[NAME_MAX+1];
737	char buf[MAXLINE+1];
738
739	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
740	    pri, flags, from, msg);
741
742	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
743
744	/*
745	 * Check to see if msg looks non-standard.
746	 */
747	msglen = strlen(msg);
748	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
749	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
750		flags |= ADDDATE;
751
752	(void)time(&now);
753	if (flags & ADDDATE)
754		timestamp = ctime(&now) + 4;
755	else {
756		timestamp = msg;
757		msg += 16;
758		msglen -= 16;
759	}
760
761	/* skip leading blanks */
762	while (isspace(*msg)) {
763		msg++;
764		msglen--;
765	}
766
767	/* extract facility and priority level */
768	if (flags & MARK)
769		fac = LOG_NFACILITIES;
770	else
771		fac = LOG_FAC(pri);
772	prilev = LOG_PRI(pri);
773
774	/* extract program name */
775	for (i = 0; i < NAME_MAX; i++) {
776		if (!isalnum(msg[i]))
777			break;
778		prog[i] = msg[i];
779	}
780	prog[i] = 0;
781
782	/* add kernel prefix for kernel messages */
783	if (flags & ISKERNEL) {
784		snprintf(buf, sizeof(buf), "%s: %s", bootfile, msg);
785		msg = buf;
786		msglen = strlen(buf);
787	}
788
789	/* log the message to the particular outputs */
790	if (!Initialized) {
791		f = &consfile;
792		f->f_file = open(ctty, O_WRONLY, 0);
793
794		if (f->f_file >= 0) {
795			fprintlog(f, flags, msg);
796			(void)close(f->f_file);
797		}
798		(void)sigsetmask(omask);
799		return;
800	}
801	for (f = Files; f; f = f->f_next) {
802		/* skip messages that are incorrect priority */
803		if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
804		     ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
805		     ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
806		     )
807		    || f->f_pmask[fac] == INTERNAL_NOPRI)
808			continue;
809		/* skip messages with the incorrect hostname */
810		if (f->f_host)
811			switch (f->f_host[0]) {
812			case '+':
813				if (strcmp(from, f->f_host + 1) != 0)
814					continue;
815				break;
816			case '-':
817				if (strcmp(from, f->f_host + 1) == 0)
818					continue;
819				break;
820			}
821
822		/* skip messages with the incorrect program name */
823		if (f->f_program)
824			if (strcmp(prog, f->f_program) != 0)
825				continue;
826
827		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
828			continue;
829
830		/* don't output marks to recently written files */
831		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
832			continue;
833
834		/*
835		 * suppress duplicate lines to this file
836		 */
837		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
838		    !strcmp(msg, f->f_prevline) &&
839		    !strcasecmp(from, f->f_prevhost)) {
840			(void)strncpy(f->f_lasttime, timestamp, 15);
841			f->f_prevcount++;
842			dprintf("msg repeated %d times, %ld sec of %d\n",
843			    f->f_prevcount, (long)(now - f->f_time),
844			    repeatinterval[f->f_repeatcount]);
845			/*
846			 * If domark would have logged this by now,
847			 * flush it now (so we don't hold isolated messages),
848			 * but back off so we'll flush less often
849			 * in the future.
850			 */
851			if (now > REPEATTIME(f)) {
852				fprintlog(f, flags, (char *)NULL);
853				BACKOFF(f);
854			}
855		} else {
856			/* new line, save it */
857			if (f->f_prevcount)
858				fprintlog(f, 0, (char *)NULL);
859			f->f_repeatcount = 0;
860			f->f_prevpri = pri;
861			(void)strncpy(f->f_lasttime, timestamp, 15);
862			(void)strncpy(f->f_prevhost, from,
863					sizeof(f->f_prevhost)-1);
864			f->f_prevhost[sizeof(f->f_prevhost)-1] = '\0';
865			if (msglen < MAXSVLINE) {
866				f->f_prevlen = msglen;
867				(void)strcpy(f->f_prevline, msg);
868				fprintlog(f, flags, (char *)NULL);
869			} else {
870				f->f_prevline[0] = 0;
871				f->f_prevlen = 0;
872				fprintlog(f, flags, msg);
873			}
874		}
875	}
876	(void)sigsetmask(omask);
877}
878
879void
880fprintlog(f, flags, msg)
881	struct filed *f;
882	int flags;
883	char *msg;
884{
885	struct iovec iov[7];
886	struct iovec *v;
887	struct addrinfo *r;
888	int i, l, lsent = 0;
889	char line[MAXLINE + 1], repbuf[80], greetings[200];
890	char *msgret;
891
892	v = iov;
893	if (f->f_type == F_WALL) {
894		v->iov_base = greetings;
895		v->iov_len = snprintf(greetings, sizeof greetings,
896		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
897		    f->f_prevhost, ctime(&now));
898		if (v->iov_len > 0)
899			v++;
900		v->iov_base = "";
901		v->iov_len = 0;
902		v++;
903	} else {
904		v->iov_base = f->f_lasttime;
905		v->iov_len = 15;
906		v++;
907		v->iov_base = " ";
908		v->iov_len = 1;
909		v++;
910	}
911
912	if (LogFacPri) {
913	  	static char fp_buf[30];	/* Hollow laugh */
914		int fac = f->f_prevpri & LOG_FACMASK;
915		int pri = LOG_PRI(f->f_prevpri);
916		const char *f_s = NULL;
917		char f_n[5];	/* Hollow laugh */
918		const char *p_s = NULL;
919		char p_n[5];	/* Hollow laugh */
920
921		if (LogFacPri > 1) {
922		  CODE *c;
923
924		  for (c = facilitynames; c->c_name; c++) {
925		    if (c->c_val == fac) {
926		      f_s = c->c_name;
927		      break;
928		    }
929		  }
930		  for (c = prioritynames; c->c_name; c++) {
931		    if (c->c_val == pri) {
932		      p_s = c->c_name;
933		      break;
934		    }
935		  }
936		}
937		if (!f_s) {
938		  snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
939		  f_s = f_n;
940		}
941		if (!p_s) {
942		  snprintf(p_n, sizeof p_n, "%d", pri);
943		  p_s = p_n;
944		}
945		snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
946		v->iov_base = fp_buf;
947		v->iov_len = strlen(fp_buf);
948	} else {
949	        v->iov_base="";
950		v->iov_len = 0;
951	}
952	v++;
953
954	v->iov_base = f->f_prevhost;
955	v->iov_len = strlen(v->iov_base);
956	v++;
957	v->iov_base = " ";
958	v->iov_len = 1;
959	v++;
960
961	if (msg) {
962		v->iov_base = msg;
963		v->iov_len = strlen(msg);
964	} else if (f->f_prevcount > 1) {
965		v->iov_base = repbuf;
966		v->iov_len = sprintf(repbuf, "last message repeated %d times",
967		    f->f_prevcount);
968	} else {
969		v->iov_base = f->f_prevline;
970		v->iov_len = f->f_prevlen;
971	}
972	v++;
973
974	dprintf("Logging to %s", TypeNames[f->f_type]);
975	f->f_time = now;
976
977	switch (f->f_type) {
978	case F_UNUSED:
979		dprintf("\n");
980		break;
981
982	case F_FORW:
983		dprintf(" %s\n", f->f_un.f_forw.f_hname);
984		/* check for local vs remote messages */
985		if (strcasecmp(f->f_prevhost, LocalHostName))
986			l = snprintf(line, sizeof line - 1,
987			    "<%d>%.15s Forwarded from %s: %s",
988			    f->f_prevpri, iov[0].iov_base, f->f_prevhost,
989			    iov[5].iov_base);
990		else
991			l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
992			     f->f_prevpri, iov[0].iov_base, iov[5].iov_base);
993		if (l < 0)
994			l = 0;
995		else if (l > MAXLINE)
996			l = MAXLINE;
997
998		if (finet) {
999			for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1000				for (i = 0; i < *finet; i++) {
1001#if 0
1002					/*
1003					 * should we check AF first, or just
1004					 * trial and error? FWD
1005					 */
1006					if (r->ai_family ==
1007					    address_family_of(finet[i+1]))
1008#endif
1009					lsent = sendto(finet[i+1], line, l, 0,
1010					    r->ai_addr, r->ai_addrlen);
1011					if (lsent == l)
1012						break;
1013				}
1014				if (lsent == l && !send_to_all)
1015					break;
1016			}
1017			if (lsent != l) {
1018				int e = errno;
1019				(void)close(f->f_file);
1020				errno = e;
1021				f->f_type = F_UNUSED;
1022				logerror("sendto");
1023			}
1024		}
1025		break;
1026
1027	case F_FILE:
1028		dprintf(" %s\n", f->f_un.f_fname);
1029		v->iov_base = "\n";
1030		v->iov_len = 1;
1031		if (writev(f->f_file, iov, 7) < 0) {
1032			int e = errno;
1033			(void)close(f->f_file);
1034			f->f_type = F_UNUSED;
1035			errno = e;
1036			logerror(f->f_un.f_fname);
1037		} else if (flags & SYNC_FILE)
1038			(void)fsync(f->f_file);
1039		break;
1040
1041	case F_PIPE:
1042		dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1043		v->iov_base = "\n";
1044		v->iov_len = 1;
1045		if (f->f_un.f_pipe.f_pid == 0) {
1046			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1047						&f->f_un.f_pipe.f_pid)) < 0) {
1048				f->f_type = F_UNUSED;
1049				logerror(f->f_un.f_pipe.f_pname);
1050				break;
1051			}
1052		}
1053		if (writev(f->f_file, iov, 7) < 0) {
1054			int e = errno;
1055			(void)close(f->f_file);
1056			if (f->f_un.f_pipe.f_pid > 0)
1057				deadq_enter(f->f_un.f_pipe.f_pid,
1058					    f->f_un.f_pipe.f_pname);
1059			f->f_un.f_pipe.f_pid = 0;
1060			errno = e;
1061			logerror(f->f_un.f_pipe.f_pname);
1062		}
1063		break;
1064
1065	case F_CONSOLE:
1066		if (flags & IGN_CONS) {
1067			dprintf(" (ignored)\n");
1068			break;
1069		}
1070		/* FALLTHROUGH */
1071
1072	case F_TTY:
1073		dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1074		v->iov_base = "\r\n";
1075		v->iov_len = 2;
1076
1077		errno = 0;	/* ttymsg() only sometimes returns an errno */
1078		if ((msgret = ttymsg(iov, 7, f->f_un.f_fname, 10))) {
1079			f->f_type = F_UNUSED;
1080			logerror(msgret);
1081		}
1082		break;
1083
1084	case F_USERS:
1085	case F_WALL:
1086		dprintf("\n");
1087		v->iov_base = "\r\n";
1088		v->iov_len = 2;
1089		wallmsg(f, iov);
1090		break;
1091	}
1092	f->f_prevcount = 0;
1093}
1094
1095/*
1096 *  WALLMSG -- Write a message to the world at large
1097 *
1098 *	Write the specified message to either the entire
1099 *	world, or a list of approved users.
1100 */
1101void
1102wallmsg(f, iov)
1103	struct filed *f;
1104	struct iovec *iov;
1105{
1106	static int reenter;			/* avoid calling ourselves */
1107	FILE *uf;
1108	struct utmp ut;
1109	int i;
1110	char *p;
1111	char line[sizeof(ut.ut_line) + 1];
1112
1113	if (reenter++)
1114		return;
1115	if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1116		logerror(_PATH_UTMP);
1117		reenter = 0;
1118		return;
1119	}
1120	/* NOSTRICT */
1121	while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
1122		if (ut.ut_name[0] == '\0')
1123			continue;
1124		strncpy(line, ut.ut_line, sizeof(ut.ut_line));
1125		line[sizeof(ut.ut_line)] = '\0';
1126		if (f->f_type == F_WALL) {
1127			if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) != NULL) {
1128				errno = 0;	/* already in msg */
1129				logerror(p);
1130			}
1131			continue;
1132		}
1133		/* should we send the message to this user? */
1134		for (i = 0; i < MAXUNAMES; i++) {
1135			if (!f->f_un.f_uname[i][0])
1136				break;
1137			if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1138			    UT_NAMESIZE)) {
1139				if ((p = ttymsg(iov, 7, line, TTYMSGTIME))
1140								!= NULL) {
1141					errno = 0;	/* already in msg */
1142					logerror(p);
1143				}
1144				break;
1145			}
1146		}
1147	}
1148	(void)fclose(uf);
1149	reenter = 0;
1150}
1151
1152void
1153reapchild(signo)
1154	int signo;
1155{
1156	int status;
1157	pid_t pid;
1158	struct filed *f;
1159
1160	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1161		if (!Initialized)
1162			/* Don't tell while we are initting. */
1163			continue;
1164
1165		/* First, look if it's a process from the dead queue. */
1166		if (deadq_remove(pid))
1167			goto oncemore;
1168
1169		/* Now, look in list of active processes. */
1170		for (f = Files; f; f = f->f_next)
1171			if (f->f_type == F_PIPE &&
1172			    f->f_un.f_pipe.f_pid == pid) {
1173				(void)close(f->f_file);
1174				f->f_un.f_pipe.f_pid = 0;
1175				log_deadchild(pid, status,
1176					      f->f_un.f_pipe.f_pname);
1177				break;
1178			}
1179	  oncemore:
1180		continue;
1181	}
1182}
1183
1184/*
1185 * Return a printable representation of a host address.
1186 */
1187char *
1188cvthname(f)
1189	struct sockaddr *f;
1190{
1191	int error;
1192	sigset_t omask, nmask;
1193	char *p;
1194	static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1195
1196	error = getnameinfo((struct sockaddr *)f,
1197			    ((struct sockaddr *)f)->sa_len,
1198			    ip, sizeof ip, NULL, 0,
1199			    NI_NUMERICHOST | withscopeid);
1200	dprintf("cvthname(%s)\n", ip);
1201
1202	if (error) {
1203		dprintf("Malformed from address %s\n", gai_strerror(error));
1204		return ("???");
1205	}
1206	if (!resolve)
1207		return (ip);
1208
1209	sigemptyset(&nmask);
1210	sigaddset(&nmask, SIGHUP);
1211	sigprocmask(SIG_BLOCK, &nmask, &omask);
1212	error = getnameinfo((struct sockaddr *)f,
1213			    ((struct sockaddr *)f)->sa_len,
1214			    hname, sizeof hname, NULL, 0,
1215			    NI_NAMEREQD | withscopeid);
1216	sigprocmask(SIG_SETMASK, &omask, NULL);
1217	if (error) {
1218		dprintf("Host name for your address (%s) unknown\n", ip);
1219		return (ip);
1220	}
1221	if ((p = strchr(hname, '.')) && strcasecmp(p + 1, LocalDomain) == 0)
1222		*p = '\0';
1223	return (hname);
1224}
1225
1226void
1227domark(signo)
1228	int signo;
1229{
1230	struct filed *f;
1231	dq_t q;
1232
1233	now = time((time_t *)NULL);
1234	MarkSeq += TIMERINTVL;
1235	if (MarkSeq >= MarkInterval) {
1236		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
1237		MarkSeq = 0;
1238	}
1239
1240	for (f = Files; f; f = f->f_next) {
1241		if (f->f_prevcount && now >= REPEATTIME(f)) {
1242			dprintf("flush %s: repeated %d times, %d sec.\n",
1243			    TypeNames[f->f_type], f->f_prevcount,
1244			    repeatinterval[f->f_repeatcount]);
1245			fprintlog(f, 0, (char *)NULL);
1246			BACKOFF(f);
1247		}
1248	}
1249
1250	/* Walk the dead queue, and see if we should signal somebody. */
1251	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
1252		switch (q->dq_timeout) {
1253		case 0:
1254			/* Already signalled once, try harder now. */
1255			if (kill(q->dq_pid, SIGKILL) != 0)
1256				(void)deadq_remove(q->dq_pid);
1257			break;
1258
1259		case 1:
1260			/*
1261			 * Timed out on dead queue, send terminate
1262			 * signal.  Note that we leave the removal
1263			 * from the dead queue to reapchild(), which
1264			 * will also log the event (unless the process
1265			 * didn't even really exist, in case we simply
1266			 * drop it from the dead queue).
1267			 */
1268			if (kill(q->dq_pid, SIGTERM) != 0)
1269				(void)deadq_remove(q->dq_pid);
1270			/* FALLTHROUGH */
1271
1272		default:
1273			q->dq_timeout--;
1274		}
1275
1276	(void)alarm(TIMERINTVL);
1277}
1278
1279/*
1280 * Print syslogd errors some place.
1281 */
1282void
1283logerror(type)
1284	const char *type;
1285{
1286	char buf[512];
1287
1288	if (errno)
1289		(void)snprintf(buf,
1290		    sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1291	else
1292		(void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1293	errno = 0;
1294	dprintf("%s\n", buf);
1295	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1296}
1297
1298void
1299die(signo)
1300	int signo;
1301{
1302	struct filed *f;
1303	int was_initialized;
1304	char buf[100];
1305	int i;
1306
1307	was_initialized = Initialized;
1308	Initialized = 0;	/* Don't log SIGCHLDs. */
1309	for (f = Files; f != NULL; f = f->f_next) {
1310		/* flush any pending output */
1311		if (f->f_prevcount)
1312			fprintlog(f, 0, (char *)NULL);
1313		if (f->f_type == F_PIPE)
1314			(void)close(f->f_file);
1315	}
1316	Initialized = was_initialized;
1317	if (signo) {
1318		dprintf("syslogd: exiting on signal %d\n", signo);
1319		(void)sprintf(buf, "exiting on signal %d", signo);
1320		errno = 0;
1321		logerror(buf);
1322	}
1323	for (i = 0; i < nfunix; i++)
1324		if (funixn[i] && funix[i] != -1)
1325			(void)unlink(funixn[i]);
1326	exit(1);
1327}
1328
1329/*
1330 *  INIT -- Initialize syslogd from configuration table
1331 */
1332void
1333init(signo)
1334	int signo;
1335{
1336	int i;
1337	FILE *cf;
1338	struct filed *f, *next, **nextp;
1339	char *p;
1340	char cline[LINE_MAX];
1341 	char prog[NAME_MAX+1];
1342	char host[MAXHOSTNAMELEN];
1343	char oldLocalHostName[MAXHOSTNAMELEN];
1344	char hostMsg[2*MAXHOSTNAMELEN+40];
1345
1346	dprintf("init\n");
1347
1348	/*
1349	 * Load hostname (may have changed).
1350	 */
1351	if (signo != 0)
1352		(void)strlcpy(oldLocalHostName, LocalHostName,
1353		    sizeof(oldLocalHostName));
1354	if (gethostname(LocalHostName, sizeof(LocalHostName)))
1355		err(EX_OSERR, "gethostname() failed");
1356	if ((p = strchr(LocalHostName, '.')) != NULL) {
1357		*p++ = '\0';
1358		LocalDomain = p;
1359	} else
1360		LocalDomain = "";
1361
1362	/*
1363	 *  Close all open log files.
1364	 */
1365	Initialized = 0;
1366	for (f = Files; f != NULL; f = next) {
1367		/* flush any pending output */
1368		if (f->f_prevcount)
1369			fprintlog(f, 0, (char *)NULL);
1370
1371		switch (f->f_type) {
1372		case F_FILE:
1373		case F_FORW:
1374		case F_CONSOLE:
1375		case F_TTY:
1376			(void)close(f->f_file);
1377			break;
1378		case F_PIPE:
1379			(void)close(f->f_file);
1380			if (f->f_un.f_pipe.f_pid > 0)
1381				deadq_enter(f->f_un.f_pipe.f_pid,
1382					    f->f_un.f_pipe.f_pname);
1383			f->f_un.f_pipe.f_pid = 0;
1384			break;
1385		}
1386		next = f->f_next;
1387		if (f->f_program) free(f->f_program);
1388		if (f->f_host) free(f->f_host);
1389		free((char *)f);
1390	}
1391	Files = NULL;
1392	nextp = &Files;
1393
1394	/* open the configuration file */
1395	if ((cf = fopen(ConfFile, "r")) == NULL) {
1396		dprintf("cannot open %s\n", ConfFile);
1397		*nextp = (struct filed *)calloc(1, sizeof(*f));
1398		cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1399		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1400		cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1401		Initialized = 1;
1402		return;
1403	}
1404
1405	/*
1406	 *  Foreach line in the conf table, open that file.
1407	 */
1408	f = NULL;
1409	strcpy(host, "*");
1410	strcpy(prog, "*");
1411	while (fgets(cline, sizeof(cline), cf) != NULL) {
1412		/*
1413		 * check for end-of-section, comments, strip off trailing
1414		 * spaces and newline character. #!prog is treated specially:
1415		 * following lines apply only to that program.
1416		 */
1417		for (p = cline; isspace(*p); ++p)
1418			continue;
1419		if (*p == 0)
1420			continue;
1421		if (*p == '#') {
1422			p++;
1423			if (*p != '!' && *p != '+' && *p != '-')
1424				continue;
1425		}
1426		if (*p == '+' || *p == '-') {
1427			host[0] = *p++;
1428			while (isspace(*p)) p++;
1429			if ((!*p) || (*p == '*')) {
1430				strcpy(host, "*");
1431				continue;
1432			}
1433			if (*p == '@')
1434				p = LocalHostName;
1435			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1436				if (!isalnum(*p) && *p != '.' && *p != '-')
1437					break;
1438				host[i] = *p++;
1439			}
1440			host[i] = '\0';
1441			continue;
1442		}
1443		if (*p == '!') {
1444			p++;
1445			while (isspace(*p)) p++;
1446			if ((!*p) || (*p == '*')) {
1447				strcpy(prog, "*");
1448				continue;
1449			}
1450			for (i = 0; i < NAME_MAX; i++) {
1451				if (!isalnum(p[i]))
1452					break;
1453				prog[i] = p[i];
1454			}
1455			prog[i] = 0;
1456			continue;
1457		}
1458		for (p = strchr(cline, '\0'); isspace(*--p);)
1459			continue;
1460		*++p = '\0';
1461		f = (struct filed *)calloc(1, sizeof(*f));
1462		*nextp = f;
1463		nextp = &f->f_next;
1464		cfline(cline, f, prog, host);
1465	}
1466
1467	/* close the configuration file */
1468	(void)fclose(cf);
1469
1470	Initialized = 1;
1471
1472	if (Debug) {
1473		for (f = Files; f; f = f->f_next) {
1474			for (i = 0; i <= LOG_NFACILITIES; i++)
1475				if (f->f_pmask[i] == INTERNAL_NOPRI)
1476					printf("X ");
1477				else
1478					printf("%d ", f->f_pmask[i]);
1479			printf("%s: ", TypeNames[f->f_type]);
1480			switch (f->f_type) {
1481			case F_FILE:
1482				printf("%s", f->f_un.f_fname);
1483				break;
1484
1485			case F_CONSOLE:
1486			case F_TTY:
1487				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1488				break;
1489
1490			case F_FORW:
1491				printf("%s", f->f_un.f_forw.f_hname);
1492				break;
1493
1494			case F_PIPE:
1495				printf("%s", f->f_un.f_pipe.f_pname);
1496				break;
1497
1498			case F_USERS:
1499				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1500					printf("%s, ", f->f_un.f_uname[i]);
1501				break;
1502			}
1503			if (f->f_program)
1504				printf(" (%s)", f->f_program);
1505			printf("\n");
1506		}
1507	}
1508
1509	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1510	dprintf("syslogd: restarted\n");
1511	/*
1512	 * Log a change in hostname, but only on a restart.
1513	 */
1514	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1515		(void)snprintf(hostMsg, sizeof(hostMsg),
1516		    "syslogd: hostname changed, \"%s\" to \"%s\"",
1517		    oldLocalHostName, LocalHostName);
1518		logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1519		dprintf("%s\n", hostMsg);
1520	}
1521}
1522
1523/*
1524 * Crack a configuration file line
1525 */
1526void
1527cfline(line, f, prog, host)
1528	char *line;
1529	struct filed *f;
1530	char *prog;
1531	char *host;
1532{
1533	struct addrinfo hints, *res;
1534	int error, i, pri;
1535	char *bp, *p, *q;
1536	char buf[MAXLINE], ebuf[100];
1537
1538	dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1539
1540	errno = 0;	/* keep strerror() stuff out of logerror messages */
1541
1542	/* clear out file entry */
1543	memset(f, 0, sizeof(*f));
1544	for (i = 0; i <= LOG_NFACILITIES; i++)
1545		f->f_pmask[i] = INTERNAL_NOPRI;
1546
1547	/* save hostname if any */
1548	if (host && *host == '*')
1549		host = NULL;
1550	if (host)
1551		f->f_host = strdup(host);
1552
1553	/* save program name if any */
1554	if (prog && *prog == '*')
1555		prog = NULL;
1556	if (prog)
1557		f->f_program = strdup(prog);
1558
1559	/* scan through the list of selectors */
1560	for (p = line; *p && *p != '\t' && *p != ' ';) {
1561		int pri_done;
1562		int pri_cmp;
1563
1564		/* find the end of this facility name list */
1565		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1566			continue;
1567
1568		/* get the priority comparison */
1569		pri_cmp = 0;
1570		pri_done = 0;
1571		while (!pri_done) {
1572			switch (*q) {
1573			case '<':
1574				pri_cmp |= PRI_LT;
1575				q++;
1576				break;
1577			case '=':
1578				pri_cmp |= PRI_EQ;
1579				q++;
1580				break;
1581			case '>':
1582				pri_cmp |= PRI_GT;
1583				q++;
1584				break;
1585			default:
1586				pri_done++;
1587				break;
1588			}
1589		}
1590		if (!pri_cmp)
1591			pri_cmp = (UniquePriority)
1592				  ? (PRI_EQ)
1593				  : (PRI_EQ | PRI_GT)
1594				  ;
1595
1596		/* collect priority name */
1597		for (bp = buf; *q && !strchr("\t,; ", *q); )
1598			*bp++ = *q++;
1599		*bp = '\0';
1600
1601		/* skip cruft */
1602		while (strchr(",;", *q))
1603			q++;
1604
1605		/* decode priority name */
1606		if (*buf == '*')
1607			pri = LOG_PRIMASK + 1;
1608		else {
1609			pri = decode(buf, prioritynames);
1610			if (pri < 0) {
1611				(void)snprintf(ebuf, sizeof ebuf,
1612				    "unknown priority name \"%s\"", buf);
1613				logerror(ebuf);
1614				return;
1615			}
1616		}
1617
1618		/* scan facilities */
1619		while (*p && !strchr("\t.; ", *p)) {
1620			for (bp = buf; *p && !strchr("\t,;. ", *p); )
1621				*bp++ = *p++;
1622			*bp = '\0';
1623
1624			if (*buf == '*')
1625				for (i = 0; i < LOG_NFACILITIES; i++) {
1626					f->f_pmask[i] = pri;
1627					f->f_pcmp[i] = pri_cmp;
1628				}
1629			else {
1630				i = decode(buf, facilitynames);
1631				if (i < 0) {
1632					(void)snprintf(ebuf, sizeof ebuf,
1633					    "unknown facility name \"%s\"",
1634					    buf);
1635					logerror(ebuf);
1636					return;
1637				}
1638				f->f_pmask[i >> 3] = pri;
1639				f->f_pcmp[i >> 3] = pri_cmp;
1640			}
1641			while (*p == ',' || *p == ' ')
1642				p++;
1643		}
1644
1645		p = q;
1646	}
1647
1648	/* skip to action part */
1649	while (*p == '\t' || *p == ' ')
1650		p++;
1651
1652	switch (*p)
1653	{
1654	case '@':
1655		(void)strncpy(f->f_un.f_forw.f_hname, ++p,
1656			sizeof(f->f_un.f_forw.f_hname)-1);
1657		f->f_un.f_forw.f_hname[sizeof(f->f_un.f_forw.f_hname)-1] = '\0';
1658		memset(&hints, 0, sizeof(hints));
1659		hints.ai_family = family;
1660		hints.ai_socktype = SOCK_DGRAM;
1661		error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
1662				    &res);
1663		if (error) {
1664			logerror(gai_strerror(error));
1665			break;
1666		}
1667		f->f_un.f_forw.f_addr = res;
1668		f->f_type = F_FORW;
1669		break;
1670
1671	case '/':
1672		if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1673			f->f_type = F_UNUSED;
1674			logerror(p);
1675			break;
1676		}
1677		if (isatty(f->f_file)) {
1678			if (strcmp(p, ctty) == 0)
1679				f->f_type = F_CONSOLE;
1680			else
1681				f->f_type = F_TTY;
1682			(void)strcpy(f->f_un.f_fname, p + sizeof _PATH_DEV - 1);
1683		} else {
1684			(void)strcpy(f->f_un.f_fname, p);
1685			f->f_type = F_FILE;
1686		}
1687		break;
1688
1689	case '|':
1690		f->f_un.f_pipe.f_pid = 0;
1691		(void)strcpy(f->f_un.f_pipe.f_pname, p + 1);
1692		f->f_type = F_PIPE;
1693		break;
1694
1695	case '*':
1696		f->f_type = F_WALL;
1697		break;
1698
1699	default:
1700		for (i = 0; i < MAXUNAMES && *p; i++) {
1701			for (q = p; *q && *q != ','; )
1702				q++;
1703			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1704			if ((q - p) > UT_NAMESIZE)
1705				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1706			else
1707				f->f_un.f_uname[i][q - p] = '\0';
1708			while (*q == ',' || *q == ' ')
1709				q++;
1710			p = q;
1711		}
1712		f->f_type = F_USERS;
1713		break;
1714	}
1715}
1716
1717
1718/*
1719 *  Decode a symbolic name to a numeric value
1720 */
1721int
1722decode(name, codetab)
1723	const char *name;
1724	CODE *codetab;
1725{
1726	CODE *c;
1727	char *p, buf[40];
1728
1729	if (isdigit(*name))
1730		return (atoi(name));
1731
1732	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1733		if (isupper(*name))
1734			*p = tolower(*name);
1735		else
1736			*p = *name;
1737	}
1738	*p = '\0';
1739	for (c = codetab; c->c_name; c++)
1740		if (!strcmp(buf, c->c_name))
1741			return (c->c_val);
1742
1743	return (-1);
1744}
1745
1746/*
1747 * fork off and become a daemon, but wait for the child to come online
1748 * before returing to the parent, or we get disk thrashing at boot etc.
1749 * Set a timer so we don't hang forever if it wedges.
1750 */
1751int
1752waitdaemon(nochdir, noclose, maxwait)
1753	int nochdir, noclose, maxwait;
1754{
1755	int fd;
1756	int status;
1757	pid_t pid, childpid;
1758
1759	switch (childpid = fork()) {
1760	case -1:
1761		return (-1);
1762	case 0:
1763		break;
1764	default:
1765		signal(SIGALRM, timedout);
1766		alarm(maxwait);
1767		while ((pid = wait3(&status, 0, NULL)) != -1) {
1768			if (WIFEXITED(status))
1769				errx(1, "child pid %d exited with return code %d",
1770					pid, WEXITSTATUS(status));
1771			if (WIFSIGNALED(status))
1772				errx(1, "child pid %d exited on signal %d%s",
1773					pid, WTERMSIG(status),
1774					WCOREDUMP(status) ? " (core dumped)" :
1775					"");
1776			if (pid == childpid)	/* it's gone... */
1777				break;
1778		}
1779		exit(0);
1780	}
1781
1782	if (setsid() == -1)
1783		return (-1);
1784
1785	if (!nochdir)
1786		(void)chdir("/");
1787
1788	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1789		(void)dup2(fd, STDIN_FILENO);
1790		(void)dup2(fd, STDOUT_FILENO);
1791		(void)dup2(fd, STDERR_FILENO);
1792		if (fd > 2)
1793			(void)close (fd);
1794	}
1795	return (getppid());
1796}
1797
1798/*
1799 * We get a SIGALRM from the child when it's running and finished doing it's
1800 * fsync()'s or O_SYNC writes for all the boot messages.
1801 *
1802 * We also get a signal from the kernel if the timer expires, so check to
1803 * see what happened.
1804 */
1805void
1806timedout(sig)
1807	int sig __unused;
1808{
1809	int left;
1810	left = alarm(0);
1811	signal(SIGALRM, SIG_DFL);
1812	if (left == 0)
1813		errx(1, "timed out waiting for child");
1814	else
1815		exit(0);
1816}
1817
1818/*
1819 * Add `s' to the list of allowable peer addresses to accept messages
1820 * from.
1821 *
1822 * `s' is a string in the form:
1823 *
1824 *    [*]domainname[:{servicename|portnumber|*}]
1825 *
1826 * or
1827 *
1828 *    netaddr/maskbits[:{servicename|portnumber|*}]
1829 *
1830 * Returns -1 on error, 0 if the argument was valid.
1831 */
1832int
1833allowaddr(s)
1834	char *s;
1835{
1836	char *cp1, *cp2;
1837	struct allowedpeer ap;
1838	struct servent *se;
1839	int masklen = -1, i;
1840	struct addrinfo hints, *res;
1841	struct in_addr *addrp, *maskp;
1842	u_int32_t *addr6p, *mask6p;
1843	char ip[NI_MAXHOST];
1844
1845#ifdef INET6
1846	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
1847#endif
1848		cp1 = s;
1849	if ((cp1 = strrchr(cp1, ':'))) {
1850		/* service/port provided */
1851		*cp1++ = '\0';
1852		if (strlen(cp1) == 1 && *cp1 == '*')
1853			/* any port allowed */
1854			ap.port = 0;
1855		else if ((se = getservbyname(cp1, "udp")))
1856			ap.port = ntohs(se->s_port);
1857		else {
1858			ap.port = strtol(cp1, &cp2, 0);
1859			if (*cp2 != '\0')
1860				return -1; /* port not numeric */
1861		}
1862	} else {
1863		if ((se = getservbyname("syslog", "udp")))
1864			ap.port = ntohs(se->s_port);
1865		else
1866			/* sanity, should not happen */
1867			ap.port = 514;
1868	}
1869
1870	if ((cp1 = strchr(s, '/')) != NULL &&
1871	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
1872		*cp1 = '\0';
1873		if ((masklen = atoi(cp1 + 1)) < 0)
1874			return -1;
1875	}
1876#ifdef INET6
1877	if (*s == '[') {
1878		cp2 = s + strlen(s) - 1;
1879		if (*cp2 == ']') {
1880			++s;
1881			*cp2 = '\0';
1882		} else
1883			cp2 = NULL;
1884	} else
1885		cp2 = NULL;
1886#endif
1887	memset(&hints, 0, sizeof(hints));
1888	hints.ai_family = PF_UNSPEC;
1889	hints.ai_socktype = SOCK_DGRAM;
1890	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
1891	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
1892		ap.isnumeric = 1;
1893		memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
1894		memset(&ap.a_mask, 0, sizeof(ap.a_mask));
1895		ap.a_mask.ss_family = res->ai_family;
1896		if (res->ai_family == AF_INET) {
1897			ap.a_mask.ss_len = sizeof(struct sockaddr_in);
1898			maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
1899			addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
1900			if (masklen < 0) {
1901				/* use default netmask */
1902				if (IN_CLASSA(ntohl(addrp->s_addr)))
1903					maskp->s_addr = htonl(IN_CLASSA_NET);
1904				else if (IN_CLASSB(ntohl(addrp->s_addr)))
1905					maskp->s_addr = htonl(IN_CLASSB_NET);
1906				else
1907					maskp->s_addr = htonl(IN_CLASSC_NET);
1908			} else if (masklen <= 32) {
1909				/* convert masklen to netmask */
1910				maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
1911			} else {
1912				freeaddrinfo(res);
1913				return -1;
1914			}
1915			/* Lose any host bits in the network number. */
1916			addrp->s_addr &= maskp->s_addr;
1917		}
1918#ifdef INET6
1919		else if (res->ai_family == AF_INET6 && masklen <= 128) {
1920			ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
1921			if (masklen < 0)
1922				masklen = 128;
1923			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
1924			/* convert masklen to netmask */
1925			while (masklen > 0) {
1926				if (masklen < 32) {
1927					*mask6p = htonl(~(0xffffffff >> masklen));
1928					break;
1929				}
1930				*mask6p++ = 0xffffffff;
1931				masklen -= 32;
1932			}
1933			/* Lose any host bits in the network number. */
1934			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
1935			addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
1936			for (i = 0; i < 4; i++)
1937				addr6p[i] &= mask6p[i];
1938		}
1939#endif
1940		else {
1941			freeaddrinfo(res);
1942			return -1;
1943		}
1944		freeaddrinfo(res);
1945	} else {
1946		/* arg `s' is domain name */
1947		ap.isnumeric = 0;
1948		ap.a_name = s;
1949		if (cp1)
1950			*cp1 = '/';
1951#ifdef INET6
1952		if (cp2) {
1953			*cp2 = ']';
1954			--s;
1955		}
1956#endif
1957	}
1958
1959	if (Debug) {
1960		printf("allowaddr: rule %d: ", NumAllowed);
1961		if (ap.isnumeric) {
1962			printf("numeric, ");
1963			getnameinfo((struct sockaddr *)&ap.a_addr,
1964				    ((struct sockaddr *)&ap.a_addr)->sa_len,
1965				    ip, sizeof ip, NULL, 0,
1966				    NI_NUMERICHOST | withscopeid);
1967			printf("addr = %s, ", ip);
1968			getnameinfo((struct sockaddr *)&ap.a_mask,
1969				    ((struct sockaddr *)&ap.a_mask)->sa_len,
1970				    ip, sizeof ip, NULL, 0,
1971				    NI_NUMERICHOST | withscopeid);
1972			printf("mask = %s; ", ip);
1973		} else
1974			printf("domainname = %s; ", ap.a_name);
1975		printf("port = %d\n", ap.port);
1976	}
1977
1978	if ((AllowedPeers = realloc(AllowedPeers,
1979				    ++NumAllowed * sizeof(struct allowedpeer)))
1980	    == NULL) {
1981		fprintf(stderr, "Out of memory!\n");
1982		exit(EX_OSERR);
1983	}
1984	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
1985	return 0;
1986}
1987
1988/*
1989 * Validate that the remote peer has permission to log to us.
1990 */
1991int
1992validate(sa, hname)
1993	struct sockaddr *sa;
1994	const char *hname;
1995{
1996	int i, j, reject;
1997	size_t l1, l2;
1998	char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
1999	struct allowedpeer *ap;
2000	struct sockaddr_in *sin, *a4p = NULL, *m4p = NULL;
2001	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2002	struct addrinfo hints, *res;
2003	u_short sport;
2004
2005	if (NumAllowed == 0)
2006		/* traditional behaviour, allow everything */
2007		return 1;
2008
2009	strlcpy(name, hname, sizeof name);
2010	memset(&hints, 0, sizeof(hints));
2011	hints.ai_family = PF_UNSPEC;
2012	hints.ai_socktype = SOCK_DGRAM;
2013	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2014	if (getaddrinfo(name, NULL, &hints, &res) == 0)
2015		freeaddrinfo(res);
2016	else if (strchr(name, '.') == NULL) {
2017		strlcat(name, ".", sizeof name);
2018		strlcat(name, LocalDomain, sizeof name);
2019	}
2020	if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2021			NI_NUMERICHOST | withscopeid | NI_NUMERICSERV) != 0)
2022		return 0;	/* for safety, should not occur */
2023	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2024		ip, port, name);
2025	sport = atoi(port);
2026
2027	/* now, walk down the list */
2028	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2029		if (ap->port != 0 && ap->port != sport) {
2030			dprintf("rejected in rule %d due to port mismatch.\n", i);
2031			continue;
2032		}
2033
2034		if (ap->isnumeric) {
2035			if (ap->a_addr.ss_family != sa->sa_family) {
2036				dprintf("rejected in rule %d due to address family mismatch.\n", i);
2037				continue;
2038			}
2039			if (ap->a_addr.ss_family == AF_INET) {
2040				sin = (struct sockaddr_in *)sa;
2041				a4p = (struct sockaddr_in *)&ap->a_addr;
2042				m4p = (struct sockaddr_in *)&ap->a_mask;
2043				if ((sin->sin_addr.s_addr & m4p->sin_addr.s_addr)
2044				    != a4p->sin_addr.s_addr) {
2045					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2046					continue;
2047				}
2048			}
2049#ifdef INET6
2050			else if (ap->a_addr.ss_family == AF_INET6) {
2051				sin6 = (struct sockaddr_in6 *)sa;
2052				a6p = (struct sockaddr_in6 *)&ap->a_addr;
2053				m6p = (struct sockaddr_in6 *)&ap->a_mask;
2054#ifdef NI_WITHSCOPEID
2055				if (a6p->sin6_scope_id != 0 &&
2056				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
2057					dprintf("rejected in rule %d due to scope mismatch.\n", i);
2058					continue;
2059				}
2060#endif
2061				reject = 0;
2062				for (j = 0; j < 16; j += 4) {
2063					if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2064					    != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2065						++reject;
2066						break;
2067					}
2068				}
2069				if (reject) {
2070					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2071					continue;
2072				}
2073			}
2074#endif
2075			else
2076				continue;
2077		} else {
2078			cp = ap->a_name;
2079			l1 = strlen(name);
2080			if (*cp == '*') {
2081				/* allow wildmatch */
2082				cp++;
2083				l2 = strlen(cp);
2084				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2085					dprintf("rejected in rule %d due to name mismatch.\n", i);
2086					continue;
2087				}
2088			} else {
2089				/* exact match */
2090				l2 = strlen(cp);
2091				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2092					dprintf("rejected in rule %d due to name mismatch.\n", i);
2093					continue;
2094				}
2095			}
2096		}
2097		dprintf("accepted in rule %d.\n", i);
2098		return 1;	/* hooray! */
2099	}
2100	return 0;
2101}
2102
2103/*
2104 * Fairly similar to popen(3), but returns an open descriptor, as
2105 * opposed to a FILE *.
2106 */
2107int
2108p_open(prog, pid)
2109	char *prog;
2110	pid_t *pid;
2111{
2112	int pfd[2], nulldesc, i;
2113	sigset_t omask, mask;
2114	char *argv[4]; /* sh -c cmd NULL */
2115	char errmsg[200];
2116
2117	if (pipe(pfd) == -1)
2118		return -1;
2119	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2120		/* we are royally screwed anyway */
2121		return -1;
2122
2123	sigemptyset(&mask);
2124	sigaddset(&mask, SIGALRM);
2125	sigaddset(&mask, SIGHUP);
2126	sigprocmask(SIG_BLOCK, &mask, &omask);
2127	switch ((*pid = fork())) {
2128	case -1:
2129		sigprocmask(SIG_SETMASK, &omask, 0);
2130		close(nulldesc);
2131		return -1;
2132
2133	case 0:
2134		argv[0] = "sh";
2135		argv[1] = "-c";
2136		argv[2] = prog;
2137		argv[3] = NULL;
2138
2139		alarm(0);
2140		(void)setsid();	/* Avoid catching SIGHUPs. */
2141
2142		/*
2143		 * Throw away pending signals, and reset signal
2144		 * behaviour to standard values.
2145		 */
2146		signal(SIGALRM, SIG_IGN);
2147		signal(SIGHUP, SIG_IGN);
2148		sigprocmask(SIG_SETMASK, &omask, 0);
2149		signal(SIGPIPE, SIG_DFL);
2150		signal(SIGQUIT, SIG_DFL);
2151		signal(SIGALRM, SIG_DFL);
2152		signal(SIGHUP, SIG_DFL);
2153
2154		dup2(pfd[0], STDIN_FILENO);
2155		dup2(nulldesc, STDOUT_FILENO);
2156		dup2(nulldesc, STDERR_FILENO);
2157		for (i = getdtablesize(); i > 2; i--)
2158			(void) close(i);
2159
2160		(void) execvp(_PATH_BSHELL, argv);
2161		_exit(255);
2162	}
2163
2164	sigprocmask(SIG_SETMASK, &omask, 0);
2165	close(nulldesc);
2166	close(pfd[0]);
2167	/*
2168	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
2169	 * supposed to get an EWOULDBLOCK on writev(2), which is
2170	 * caught by the logic above anyway, which will in turn close
2171	 * the pipe, and fork a new logging subprocess if necessary.
2172	 * The stale subprocess will be killed some time later unless
2173	 * it terminated itself due to closing its input pipe (so we
2174	 * get rid of really dead puppies).
2175	 */
2176	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2177		/* This is bad. */
2178		(void)snprintf(errmsg, sizeof errmsg,
2179			       "Warning: cannot change pipe to PID %d to "
2180			       "non-blocking behaviour.",
2181			       (int)*pid);
2182		logerror(errmsg);
2183	}
2184	return pfd[1];
2185}
2186
2187void
2188deadq_enter(pid, name)
2189	pid_t pid;
2190	const char *name;
2191{
2192	dq_t p;
2193	int status;
2194
2195	/*
2196	 * Be paranoid, if we can't signal the process, don't enter it
2197	 * into the dead queue (perhaps it's already dead).  If possible,
2198	 * we try to fetch and log the child's status.
2199	 */
2200	if (kill(pid, 0) != 0) {
2201		if (waitpid(pid, &status, WNOHANG) > 0)
2202			log_deadchild(pid, status, name);
2203		return;
2204	}
2205
2206	p = malloc(sizeof(struct deadq_entry));
2207	if (p == 0) {
2208		errno = 0;
2209		logerror("panic: out of virtual memory!");
2210		exit(1);
2211	}
2212
2213	p->dq_pid = pid;
2214	p->dq_timeout = DQ_TIMO_INIT;
2215	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2216}
2217
2218int
2219deadq_remove(pid)
2220	pid_t pid;
2221{
2222	dq_t q;
2223
2224	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
2225		if (q->dq_pid == pid) {
2226			TAILQ_REMOVE(&deadq_head, q, dq_entries);
2227				free(q);
2228				return 1;
2229		}
2230
2231	return 0;
2232}
2233
2234void
2235log_deadchild(pid, status, name)
2236	pid_t pid;
2237	int status;
2238	const char *name;
2239{
2240	int code;
2241	char buf[256];
2242	const char *reason;
2243
2244	errno = 0; /* Keep strerror() stuff out of logerror messages. */
2245	if (WIFSIGNALED(status)) {
2246		reason = "due to signal";
2247		code = WTERMSIG(status);
2248	} else {
2249		reason = "with status";
2250		code = WEXITSTATUS(status);
2251		if (code == 0)
2252			return;
2253	}
2254	(void)snprintf(buf, sizeof buf,
2255		       "Logging subprocess %d (%s) exited %s %d.",
2256		       pid, name, reason, code);
2257	logerror(buf);
2258}
2259
2260int *
2261socksetup(af)
2262	int af;
2263{
2264	struct addrinfo hints, *res, *r;
2265	int error, maxs, *s, *socks;
2266
2267	memset(&hints, 0, sizeof(hints));
2268	hints.ai_flags = AI_PASSIVE;
2269	hints.ai_family = af;
2270	hints.ai_socktype = SOCK_DGRAM;
2271	error = getaddrinfo(NULL, "syslog", &hints, &res);
2272	if (error) {
2273		logerror(gai_strerror(error));
2274		errno = 0;
2275		die(0);
2276	}
2277
2278	/* Count max number of sockets we may open */
2279	for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2280	socks = malloc((maxs+1) * sizeof(int));
2281	if (!socks) {
2282		logerror("couldn't allocate memory for sockets");
2283		die(0);
2284	}
2285
2286	*socks = 0;   /* num of sockets counter at start of array */
2287	s = socks + 1;
2288	for (r = res; r; r = r->ai_next) {
2289		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2290		if (*s < 0) {
2291			logerror("socket");
2292			continue;
2293		}
2294#ifdef IPV6_BINDV6ONLY
2295		if (r->ai_family == AF_INET6) {
2296			int on = 1;
2297			if (setsockopt(*s, IPPROTO_IPV6, IPV6_BINDV6ONLY,
2298				       (char *)&on, sizeof (on)) < 0) {
2299				logerror("setsockopt");
2300				close(*s);
2301				continue;
2302			}
2303		}
2304#endif
2305		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2306			close(*s);
2307			logerror("bind");
2308			continue;
2309		}
2310
2311		(*socks)++;
2312		s++;
2313	}
2314
2315	if (*socks == 0) {
2316		free(socks);
2317		if (Debug)
2318			return(NULL);
2319		else
2320			die(0);
2321	}
2322	if (res)
2323		freeaddrinfo(res);
2324
2325	return(socks);
2326}
2327