syslogd.c revision 178986
1139749Simp/*
2116491Sharti * Copyright (c) 1983, 1988, 1993, 1994
3116491Sharti *	The Regents of the University of California.  All rights reserved.
4116491Sharti *
5116491Sharti * Redistribution and use in source and binary forms, with or without
6116491Sharti * modification, are permitted provided that the following conditions
7116491Sharti * are met:
8116491Sharti * 1. Redistributions of source code must retain the above copyright
9116491Sharti *    notice, this list of conditions and the following disclaimer.
10116491Sharti * 2. Redistributions in binary form must reproduce the above copyright
11116491Sharti *    notice, this list of conditions and the following disclaimer in the
12116491Sharti *    documentation and/or other materials provided with the distribution.
13116491Sharti * 4. Neither the name of the University nor the names of its contributors
14116491Sharti *    may be used to endorse or promote products derived from this software
15116491Sharti *    without specific prior written permission.
16116491Sharti *
17116491Sharti * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18116491Sharti * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19116491Sharti * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20116491Sharti * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21116491Sharti * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22116491Sharti * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23116491Sharti * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24116491Sharti * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25116491Sharti * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26116491Sharti * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27116491Sharti * SUCH DAMAGE.
28116491Sharti */
29116491Sharti
30116491Sharti#ifndef lint
31116491Shartistatic const char copyright[] =
32116491Sharti"@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
33116491Sharti	The Regents of the University of California.  All rights reserved.\n";
34116519Sharti#endif /* not lint */
35116519Sharti
36116519Sharti#ifndef lint
37116491Sharti#if 0
38116491Shartistatic char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
39116491Sharti#endif
40116491Sharti#endif /* not lint */
41116491Sharti
42116491Sharti#include <sys/cdefs.h>
43116491Sharti__FBSDID("$FreeBSD: head/usr.sbin/syslogd/syslogd.c 178986 2008-05-14 00:22:21Z brian $");
44116491Sharti
45116491Sharti/*
46116491Sharti *  syslogd -- log system messages
47116491Sharti *
48116491Sharti * This program implements a system log. It takes a series of lines.
49116491Sharti * Each line may have a priority, signified as "<n>" as
50116491Sharti * the first characters of the line.  If this is
51116491Sharti * not present, a default priority is used.
52116491Sharti *
53116491Sharti * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
54116491Sharti * cause it to reread its configuration file.
55116491Sharti *
56116491Sharti * Defined Constants:
57116491Sharti *
58116491Sharti * MAXLINE -- the maximum line length that can be handled.
59116491Sharti * DEFUPRI -- the default priority for user messages
60116491Sharti * DEFSPRI -- the default priority for kernel messages
61116491Sharti *
62116491Sharti * Author: Eric Allman
63116491Sharti * extensive changes by Ralph Campbell
64116491Sharti * more extensive changes by Eric Allman (again)
65116491Sharti * Extension to log by program name as well as facility and priority
66116491Sharti *   by Peter da Silva.
67116491Sharti * -u and -v by Harlan Stenn.
68116491Sharti * Priority comparison code by Harlan Stenn.
69116491Sharti */
70116491Sharti
71116491Sharti#define	MAXLINE		1024		/* maximum line length */
72116491Sharti#define	MAXSVLINE	120		/* maximum saved line length */
73119280Simp#define	DEFUPRI		(LOG_USER|LOG_NOTICE)
74119280Simp#define	DEFSPRI		(LOG_KERN|LOG_CRIT)
75116491Sharti#define	TIMERINTVL	30		/* interval for checking flush, mark */
76116491Sharti#define	TTYMSGTIME	1		/* timeout passed to ttymsg */
77116491Sharti
78116491Sharti#include <sys/param.h>
79116491Sharti#include <sys/ioctl.h>
80116491Sharti#include <sys/stat.h>
81122112Sharti#include <sys/wait.h>
82116491Sharti#include <sys/socket.h>
83122112Sharti#include <sys/queue.h>
84122112Sharti#include <sys/uio.h>
85122112Sharti#include <sys/un.h>
86122112Sharti#include <sys/time.h>
87122112Sharti#include <sys/resource.h>
88122112Sharti#include <sys/syslimits.h>
89122112Sharti#include <sys/types.h>
90122112Sharti
91122112Sharti#include <netinet/in.h>
92122112Sharti#include <netdb.h>
93122112Sharti#include <arpa/inet.h>
94122112Sharti
95122112Sharti#include <ctype.h>
96122112Sharti#include <err.h>
97146617Sharti#include <errno.h>
98122112Sharti#include <fcntl.h>
99122112Sharti#include <libutil.h>
100122112Sharti#include <limits.h>
101122112Sharti#include <paths.h>
102122112Sharti#include <signal.h>
103122112Sharti#include <stdio.h>
104122112Sharti#include <stdlib.h>
105122112Sharti#include <string.h>
106122112Sharti#include <sysexits.h>
107116491Sharti#include <unistd.h>
108116491Sharti#include <utmp.h>
109116491Sharti
110116491Sharti#include "pathnames.h"
111116491Sharti#include "ttymsg.h"
112116491Sharti
113116491Sharti#define SYSLOG_NAMES
114116491Sharti#include <sys/syslog.h>
115116491Sharti
116116491Sharticonst char	*ConfFile = _PATH_LOGCONF;
117116491Sharticonst char	*PidFile = _PATH_LOGPID;
118116491Sharticonst char	ctty[] = _PATH_CONSOLE;
119116491Sharti
120116491Sharti#define	dprintf		if (Debug) printf
121116491Sharti
122116491Sharti#define	MAXUNAMES	20	/* maximum number of user names */
123116491Sharti
124116491Sharti/*
125116491Sharti * Unix sockets.
126116491Sharti * We have two default sockets, one with 666 permissions,
127116491Sharti * and one for privileged programs.
128116491Sharti */
129116491Shartistruct funix {
130116491Sharti	int			s;
131116491Sharti	char			*name;
132116491Sharti	mode_t			mode;
133116491Sharti	STAILQ_ENTRY(funix)	next;
134116491Sharti};
135116491Shartistruct funix funix_secure =	{ -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
136116491Sharti				{ NULL } };
137116491Shartistruct funix funix_default =	{ -1, _PATH_LOG, DEFFILEMODE,
138116491Sharti				{ &funix_secure } };
139116491Sharti
140116491ShartiSTAILQ_HEAD(, funix) funixes =	{ &funix_default,
141116491Sharti				&(funix_secure.next.stqe_next) };
142116491Sharti
143116491Sharti/*
144116491Sharti * Flags to logmsg().
145116491Sharti */
146116491Sharti
147116491Sharti#define	IGN_CONS	0x001	/* don't print on console */
148116491Sharti#define	SYNC_FILE	0x002	/* do fsync on file after printing */
149116491Sharti#define	ADDDATE		0x004	/* add a date to the message */
150116491Sharti#define	MARK		0x008	/* this message is a mark */
151116491Sharti#define	ISKERNEL	0x010	/* kernel generated message */
152122112Sharti
153116491Sharti/*
154116491Sharti * This structure represents the files that will have log
155116491Sharti * copies printed.
156116491Sharti * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
157116491Sharti * or if f_type if F_PIPE and f_pid > 0.
158116491Sharti */
159116491Sharti
160116491Shartistruct filed {
161116491Sharti	struct	filed *f_next;		/* next in linked list */
162116491Sharti	short	f_type;			/* entry type, see below */
163116491Sharti	short	f_file;			/* file descriptor */
164116491Sharti	time_t	f_time;			/* time this was last written */
165116491Sharti	char	*f_host;		/* host from which to recd. */
166116491Sharti	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
167116491Sharti	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
168116491Sharti#define PRI_LT	0x1
169116491Sharti#define PRI_EQ	0x2
170116491Sharti#define PRI_GT	0x4
171116491Sharti	char	*f_program;		/* program this applies to */
172116491Sharti	union {
173116491Sharti		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
174116491Sharti		struct {
175116491Sharti			char	f_hname[MAXHOSTNAMELEN];
176116491Sharti			struct addrinfo *f_addr;
177116491Sharti
178116491Sharti		} f_forw;		/* forwarding address */
179116491Sharti		char	f_fname[MAXPATHLEN];
180116491Sharti		struct {
181116491Sharti			char	f_pname[MAXPATHLEN];
182116491Sharti			pid_t	f_pid;
183116491Sharti		} f_pipe;
184116491Sharti	} f_un;
185116491Sharti	char	f_prevline[MAXSVLINE];		/* last message logged */
186116491Sharti	char	f_lasttime[16];			/* time of last occurrence */
187116491Sharti	char	f_prevhost[MAXHOSTNAMELEN];	/* host from which recd. */
188116491Sharti	int	f_prevpri;			/* pri of f_prevline */
189116491Sharti	int	f_prevlen;			/* length of f_prevline */
190116491Sharti	int	f_prevcount;			/* repetition cnt of prevline */
191116491Sharti	u_int	f_repeatcount;			/* number of "repeated" msgs */
192116491Sharti	int	f_flags;			/* file-specific flags */
193116491Sharti#define	FFLAG_SYNC 0x01
194116491Sharti#define	FFLAG_NEEDSYNC	0x02
195116491Sharti};
196147256Sbrooks
197116491Sharti/*
198116491Sharti * Queue of about-to-be dead processes we should watch out for.
199116491Sharti */
200116491Sharti
201116491ShartiTAILQ_HEAD(stailhead, deadq_entry) deadq_head;
202116491Shartistruct stailhead *deadq_headp;
203116491Sharti
204116491Shartistruct deadq_entry {
205116491Sharti	pid_t				dq_pid;
206116491Sharti	int				dq_timeout;
207116491Sharti	TAILQ_ENTRY(deadq_entry)	dq_entries;
208116491Sharti};
209116491Sharti
210116491Sharti/*
211116491Sharti * The timeout to apply to processes waiting on the dead queue.  Unit
212116491Sharti * of measure is `mark intervals', i.e. 20 minutes by default.
213116491Sharti * Processes on the dead queue will be terminated after that time.
214116491Sharti */
215116491Sharti
216116491Sharti#define	 DQ_TIMO_INIT	2
217116491Sharti
218116491Shartitypedef struct deadq_entry *dq_t;
219116491Sharti
220116491Sharti
221116491Sharti/*
222116491Sharti * Struct to hold records of network addresses that are allowed to log
223116491Sharti * to us.
224116491Sharti */
225116491Shartistruct allowedpeer {
226116491Sharti	int isnumeric;
227116491Sharti	u_short port;
228116491Sharti	union {
229116491Sharti		struct {
230116491Sharti			struct sockaddr_storage addr;
231116491Sharti			struct sockaddr_storage mask;
232116491Sharti		} numeric;
233116491Sharti		char *name;
234116491Sharti	} u;
235116491Sharti#define a_addr u.numeric.addr
236116491Sharti#define a_mask u.numeric.mask
237116491Sharti#define a_name u.name
238116491Sharti};
239116491Sharti
240116491Sharti
241116491Sharti/*
242116491Sharti * Intervals at which we flush out "message repeated" messages,
243116491Sharti * in seconds after previous message is logged.  After each flush,
244116491Sharti * we move to the next interval until we reach the largest.
245116491Sharti */
246116491Shartiint	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
247116491Sharti#define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
248116491Sharti#define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
249116491Sharti#define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
250116491Sharti				 (f)->f_repeatcount = MAXREPEAT; \
251116491Sharti			}
252116491Sharti
253116491Sharti/* values for f_type */
254116491Sharti#define F_UNUSED	0		/* unused entry */
255116491Sharti#define F_FILE		1		/* regular file */
256116491Sharti#define F_TTY		2		/* terminal */
257116491Sharti#define F_CONSOLE	3		/* console terminal */
258116491Sharti#define F_FORW		4		/* remote machine */
259116491Sharti#define F_USERS		5		/* list of users */
260116491Sharti#define F_WALL		6		/* everyone logged on */
261116491Sharti#define F_PIPE		7		/* pipe to program */
262116491Sharti
263116491Sharticonst char *TypeNames[8] = {
264116491Sharti	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
265147256Sbrooks	"FORW",		"USERS",	"WALL",		"PIPE"
266116491Sharti};
267116491Sharti
268116491Shartistatic struct filed *Files;	/* Log files that we write to */
269116491Shartistatic struct filed consfile;	/* Console */
270116491Sharti
271116491Shartistatic int	Debug;		/* debug flag */
272116491Shartistatic int	resolve = 1;	/* resolve hostname */
273116491Shartistatic char	LocalHostName[MAXHOSTNAMELEN];	/* our hostname */
274116491Shartistatic const char *LocalDomain;	/* our local domain name */
275116491Shartistatic int	*finet;		/* Internet datagram socket */
276116491Shartistatic int	fklog = -1;	/* /dev/klog */
277116491Shartistatic int	Initialized;	/* set when we have initialized ourselves */
278116491Shartistatic int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
279116491Shartistatic int	MarkSeq;	/* mark sequence number */
280147256Sbrooksstatic int	SecureMode;	/* when true, receive only unix domain socks */
281118170Sharti#ifdef INET6
282116491Shartistatic int	family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
283116491Sharti#else
284116491Shartistatic int	family = PF_INET; /* protocol family (IPv4 only) */
285116491Sharti#endif
286116491Shartistatic int	mask_C1 = 1;	/* mask characters from 0x80 - 0x9F */
287116491Shartistatic int	send_to_all;	/* send message to all IPv4/IPv6 addresses */
288116491Shartistatic int	use_bootfile;	/* log entire bootfile for every kern msg */
289116491Shartistatic int	no_compress;	/* don't compress messages (1=pipes, 2=all) */
290116491Shartistatic int	logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
291116491Sharti
292116491Shartistatic char	bootfile[MAXLINE+1]; /* booted kernel file */
293116491Sharti
294116491Shartistruct allowedpeer *AllowedPeers; /* List of allowed peers */
295116491Shartistatic int	NumAllowed;	/* Number of entries in AllowedPeers */
296116491Sharti
297116491Shartistatic int	UniquePriority;	/* Only log specified priority? */
298116491Shartistatic int	LogFacPri;	/* Put facility and priority in log message: */
299116491Sharti				/* 0=no, 1=numeric, 2=names */
300116491Shartistatic int	KeepKernFac;	/* Keep remotely logged kernel facility */
301116491Shartistatic int	needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
302116491Shartistatic struct pidfh *pfh;
303116491Sharti
304116491Shartivolatile sig_atomic_t MarkSet, WantDie;
305116491Sharti
306116491Shartistatic int	allowaddr(char *);
307116491Shartistatic void	cfline(const char *, struct filed *,
308116491Sharti		    const char *, const char *);
309116491Shartistatic const char *cvthname(struct sockaddr *);
310116491Shartistatic void	deadq_enter(pid_t, const char *);
311116491Shartistatic int	deadq_remove(pid_t);
312116491Shartistatic int	decode(const char *, CODE *);
313116491Shartistatic void	die(int);
314116491Shartistatic void	dodie(int);
315116491Shartistatic void	dofsync(void);
316116491Shartistatic void	domark(int);
317116491Shartistatic void	fprintlog(struct filed *, int, const char *);
318116491Shartistatic int	*socksetup(int, const char *);
319116491Shartistatic void	init(int);
320116491Shartistatic void	logerror(const char *);
321116491Shartistatic void	logmsg(int, const char *, const char *, int);
322116491Shartistatic void	log_deadchild(pid_t, int, const char *);
323116491Shartistatic void	markit(void);
324116491Shartistatic int	skip_message(const char *, const char *, int);
325116491Shartistatic void	printline(const char *, char *);
326116491Shartistatic void	printsys(char *);
327116491Shartistatic int	p_open(const char *, pid_t *);
328116491Shartistatic void	readklog(void);
329116491Shartistatic void	reapchild(int);
330116491Shartistatic void	usage(void);
331116491Shartistatic int	validate(struct sockaddr *, const char *);
332116491Shartistatic void	unmapped(struct sockaddr *);
333116491Shartistatic void	wallmsg(struct filed *, struct iovec *);
334116491Shartistatic int	waitdaemon(int, int, int);
335116491Shartistatic void	timedout(int);
336116491Shartistatic void	double_rbuf(int);
337116491Sharti
338116491Shartiint
339116491Shartimain(int argc, char *argv[])
340116491Sharti{
341116491Sharti	int ch, i, fdsrmax = 0, l;
342116491Sharti	struct sockaddr_un sunx, fromunix;
343116491Sharti	struct sockaddr_storage frominet;
344116491Sharti	fd_set *fdsr = NULL;
345116491Sharti	char line[MAXLINE + 1];
346116491Sharti	const char *bindhostname, *hname;
347116491Sharti	struct timeval tv, *tvp;
348116491Sharti	struct sigaction sact;
349116491Sharti	struct funix *fx, *fx1;
350116491Sharti	sigset_t mask;
351116491Sharti	pid_t ppid = 1, spid;
352116491Sharti	socklen_t len;
353116491Sharti
354147721Sharti	bindhostname = NULL;
355116491Sharti	while ((ch = getopt(argc, argv, "468Aa:b:cCdf:kl:m:nop:P:sS:uv")) != -1)
356116491Sharti		switch (ch) {
357116491Sharti		case '4':
358116491Sharti			family = PF_INET;
359116491Sharti			break;
360116491Sharti#ifdef INET6
361116491Sharti		case '6':
362116491Sharti			family = PF_INET6;
363116491Sharti			break;
364116491Sharti#endif
365116491Sharti		case '8':
366116491Sharti			mask_C1 = 0;
367116491Sharti			break;
368116491Sharti		case 'A':
369116491Sharti			send_to_all++;
370116491Sharti			break;
371116491Sharti		case 'a':		/* allow specific network addresses only */
372116491Sharti			if (allowaddr(optarg) == -1)
373122112Sharti				usage();
374122112Sharti			break;
375116491Sharti		case 'b':
376122112Sharti			bindhostname = optarg;
377122112Sharti			break;
378116491Sharti		case 'c':
379122112Sharti			no_compress++;
380116491Sharti			break;
381116491Sharti		case 'C':
382116491Sharti			logflags |= O_CREAT;
383116491Sharti			break;
384116491Sharti		case 'd':		/* debug */
385116491Sharti			Debug++;
386116491Sharti			break;
387122112Sharti		case 'f':		/* configuration file */
388116491Sharti			ConfFile = optarg;
389116491Sharti			break;
390116491Sharti		case 'k':		/* keep remote kern fac */
391116491Sharti			KeepKernFac = 1;
392116491Sharti			break;
393116491Sharti		case 'l':
394122112Sharti		    {
395116491Sharti			long	perml;
396116491Sharti			mode_t	mode;
397116491Sharti			char	*name, *ep;
398116491Sharti
399116491Sharti			if (optarg[0] == '/') {
400116491Sharti				mode = DEFFILEMODE;
401116491Sharti				name = optarg;
402122112Sharti			} else if ((name = strchr(optarg, ':')) != NULL) {
403116491Sharti				*name++ = '\0';
404116491Sharti				if (name[0] != '/')
405116491Sharti					errx(1, "socket name must be absolute "
406116491Sharti					    "path");
407122112Sharti				if (isdigit(*optarg)) {
408116491Sharti					perml = strtol(optarg, &ep, 8);
409116491Sharti				    if (*ep || perml < 0 ||
410116491Sharti					perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
411116491Sharti					    errx(1, "invalid mode %s, exiting",
412116491Sharti						optarg);
413116491Sharti				    mode = (mode_t )perml;
414116491Sharti				} else
415116491Sharti					errx(1, "invalid mode %s, exiting",
416121687Sharti					    optarg);
417122112Sharti			} else	/* doesn't begin with '/', and no ':' */
418116491Sharti				errx(1, "can't parse path %s", optarg);
419116491Sharti
420116491Sharti			if (strlen(name) >= sizeof(sunx.sun_path))
421121687Sharti				errx(1, "%s path too long, exiting", name);
422121687Sharti			if ((fx = malloc(sizeof(struct funix))) == NULL)
423121687Sharti				errx(1, "malloc failed");
424121687Sharti			fx->s = -1;
425121687Sharti			fx->name = name;
426122112Sharti			fx->mode = mode;
427122112Sharti			STAILQ_INSERT_TAIL(&funixes, fx, next);
428116491Sharti			break;
429122112Sharti		   }
430116491Sharti		case 'm':		/* mark interval */
431116491Sharti			MarkInterval = atoi(optarg) * 60;
432116491Sharti			break;
433116491Sharti		case 'n':
434121687Sharti			resolve = 0;
435121687Sharti			break;
436121687Sharti		case 'o':
437121687Sharti			use_bootfile = 1;
438121687Sharti			break;
439116491Sharti		case 'p':		/* path */
440116491Sharti			if (strlen(optarg) >= sizeof(sunx.sun_path))
441116491Sharti				errx(1, "%s path too long, exiting", optarg);
442116491Sharti			funix_default.name = optarg;
443118540Sharti			break;
444116491Sharti		case 'P':		/* path for alt. PID */
445116491Sharti			PidFile = optarg;
446116491Sharti			break;
447116491Sharti		case 's':		/* no network mode */
448116491Sharti			SecureMode++;
449116491Sharti			break;
450116491Sharti		case 'S':		/* path for privileged originator */
451116491Sharti			if (strlen(optarg) >= sizeof(sunx.sun_path))
452122112Sharti				errx(1, "%s path too long, exiting", optarg);
453116491Sharti			funix_secure.name = optarg;
454147256Sbrooks			break;
455116491Sharti		case 'u':		/* only log specified priority */
456116491Sharti			UniquePriority++;
457116491Sharti			break;
458116491Sharti		case 'v':		/* log facility and priority */
459116491Sharti		  	LogFacPri++;
460116491Sharti			break;
461116491Sharti		default:
462116491Sharti			usage();
463116491Sharti		}
464117382Sharti	if ((argc -= optind) != 0)
465116491Sharti		usage();
466116491Sharti
467116491Sharti	pfh = pidfile_open(PidFile, 0600, &spid);
468116491Sharti	if (pfh == NULL) {
469116491Sharti		if (errno == EEXIST)
470116491Sharti			errx(1, "syslogd already running, pid: %d", spid);
471122112Sharti		warn("cannot open pid file");
472122112Sharti	}
473122112Sharti
474147256Sbrooks	if (!Debug) {
475116491Sharti		ppid = waitdaemon(0, 0, 30);
476116491Sharti		if (ppid < 0) {
477116491Sharti			warn("could not become daemon");
478116491Sharti			pidfile_remove(pfh);
479117382Sharti			exit(1);
480116491Sharti		}
481116491Sharti	} else {
482116491Sharti		setlinebuf(stdout);
483147256Sbrooks	}
484116491Sharti
485116491Sharti	if (NumAllowed)
486147256Sbrooks		endservent();
487116491Sharti
488116491Sharti	consfile.f_type = F_CONSOLE;
489116491Sharti	(void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
490116491Sharti	    sizeof(consfile.f_un.f_fname));
491147256Sbrooks	(void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
492116491Sharti	(void)signal(SIGTERM, dodie);
493116491Sharti	(void)signal(SIGINT, Debug ? dodie : SIG_IGN);
494116491Sharti	(void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
495116491Sharti	/*
496147256Sbrooks	 * We don't want the SIGCHLD and SIGHUP handlers to interfere
497116491Sharti	 * with each other; they are likely candidates for being called
498116491Sharti	 * simultaneously (SIGHUP closes pipe descriptor, process dies,
499116491Sharti	 * SIGCHLD happens).
500116491Sharti	 */
501116491Sharti	sigemptyset(&mask);
502116491Sharti	sigaddset(&mask, SIGHUP);
503116491Sharti	sact.sa_handler = reapchild;
504116491Sharti	sact.sa_mask = mask;
505116491Sharti	sact.sa_flags = SA_RESTART;
506116491Sharti	(void)sigaction(SIGCHLD, &sact, NULL);
507116491Sharti	(void)signal(SIGALRM, domark);
508116491Sharti	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
509116491Sharti	(void)alarm(TIMERINTVL);
510116491Sharti
511116491Sharti	TAILQ_INIT(&deadq_head);
512118540Sharti
513116491Sharti#ifndef SUN_LEN
514116491Sharti#define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
515116491Sharti#endif
516116491Sharti	STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
517116491Sharti		(void)unlink(fx->name);
518116491Sharti		memset(&sunx, 0, sizeof(sunx));
519116491Sharti		sunx.sun_family = AF_LOCAL;
520116491Sharti		(void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
521116491Sharti		fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
522116491Sharti		if (fx->s < 0 ||
523116491Sharti		    bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
524116491Sharti		    chmod(fx->name, fx->mode) < 0) {
525116491Sharti			(void)snprintf(line, sizeof line,
526116491Sharti					"cannot create %s", fx->name);
527116491Sharti			logerror(line);
528116491Sharti			dprintf("cannot create %s (%d)\n", fx->name, errno);
529116491Sharti			if (fx == &funix_default || fx == &funix_secure)
530116491Sharti				die(0);
531147256Sbrooks			else {
532118170Sharti				STAILQ_REMOVE(&funixes, fx, funix, next);
533116491Sharti				continue;
534116491Sharti			}
535116491Sharti			double_rbuf(fx->s);
536116491Sharti		}
537116491Sharti	}
538116491Sharti	if (SecureMode <= 1)
539116491Sharti		finet = socksetup(family, bindhostname);
540116491Sharti
541116491Sharti	if (finet) {
542116491Sharti		if (SecureMode) {
543116491Sharti			for (i = 0; i < *finet; i++) {
544116491Sharti				if (shutdown(finet[i+1], SHUT_RD) < 0) {
545116491Sharti					logerror("shutdown");
546116491Sharti					if (!Debug)
547116491Sharti						die(0);
548116491Sharti				}
549116491Sharti			}
550116491Sharti		} else {
551116491Sharti			dprintf("listening on inet and/or inet6 socket\n");
552116491Sharti		}
553116491Sharti		dprintf("sending on inet and/or inet6 socket\n");
554116491Sharti	}
555116491Sharti
556116491Sharti	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
557116491Sharti		if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
558116491Sharti			fklog = -1;
559116491Sharti	if (fklog < 0)
560116491Sharti		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
561116491Sharti
562116491Sharti	/* tuck my process id away */
563116491Sharti	pidfile_write(pfh);
564116491Sharti
565116491Sharti	dprintf("off & running....\n");
566116491Sharti
567116491Sharti	init(0);
568116491Sharti	/* prevent SIGHUP and SIGCHLD handlers from running in parallel */
569116491Sharti	sigemptyset(&mask);
570116491Sharti	sigaddset(&mask, SIGCHLD);
571116491Sharti	sact.sa_handler = init;
572147256Sbrooks	sact.sa_mask = mask;
573116491Sharti	sact.sa_flags = SA_RESTART;
574116491Sharti	(void)sigaction(SIGHUP, &sact, NULL);
575116491Sharti
576116491Sharti	tvp = &tv;
577116491Sharti	tv.tv_sec = tv.tv_usec = 0;
578147256Sbrooks
579116491Sharti	if (fklog != -1 && fklog > fdsrmax)
580116491Sharti		fdsrmax = fklog;
581116491Sharti	if (finet && !SecureMode) {
582116491Sharti		for (i = 0; i < *finet; i++) {
583116491Sharti		    if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
584116491Sharti			fdsrmax = finet[i+1];
585116491Sharti		}
586116491Sharti	}
587116491Sharti	STAILQ_FOREACH(fx, &funixes, next)
588116491Sharti		if (fx->s > fdsrmax)
589116491Sharti			fdsrmax = fx->s;
590116491Sharti
591116491Sharti	fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
592116491Sharti	    sizeof(fd_mask));
593116491Sharti	if (fdsr == NULL)
594116491Sharti		errx(1, "calloc fd_set");
595116491Sharti
596116491Sharti	for (;;) {
597116491Sharti		if (MarkSet)
598116491Sharti			markit();
599116491Sharti		if (WantDie)
600116491Sharti			die(WantDie);
601116491Sharti
602116491Sharti		bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
603116491Sharti		    sizeof(fd_mask));
604116491Sharti
605116491Sharti		if (fklog != -1)
606116491Sharti			FD_SET(fklog, fdsr);
607116491Sharti		if (finet && !SecureMode) {
608116491Sharti			for (i = 0; i < *finet; i++) {
609116491Sharti				if (finet[i+1] != -1)
610116491Sharti					FD_SET(finet[i+1], fdsr);
611116491Sharti			}
612116491Sharti		}
613116491Sharti		STAILQ_FOREACH(fx, &funixes, next)
614116491Sharti			FD_SET(fx->s, fdsr);
615116491Sharti
616116491Sharti		i = select(fdsrmax+1, fdsr, NULL, NULL,
617116491Sharti		    needdofsync ? &tv : tvp);
618116491Sharti		switch (i) {
619116491Sharti		case 0:
620116491Sharti			dofsync();
621116491Sharti			needdofsync = 0;
622116491Sharti			if (tvp) {
623116491Sharti				tvp = NULL;
624116491Sharti				if (ppid != 1)
625116491Sharti					kill(ppid, SIGALRM);
626118598Sharti			}
627118598Sharti			continue;
628118598Sharti		case -1:
629118598Sharti			if (errno != EINTR)
630116491Sharti				logerror("select");
631116491Sharti			continue;
632116491Sharti		}
633116491Sharti		if (fklog != -1 && FD_ISSET(fklog, fdsr))
634116491Sharti			readklog();
635116491Sharti		if (finet && !SecureMode) {
636116491Sharti			for (i = 0; i < *finet; i++) {
637116491Sharti				if (FD_ISSET(finet[i+1], fdsr)) {
638116491Sharti					len = sizeof(frominet);
639116491Sharti					l = recvfrom(finet[i+1], line, MAXLINE,
640116491Sharti					     0, (struct sockaddr *)&frominet,
641116491Sharti					     &len);
642116491Sharti					if (l > 0) {
643116491Sharti						line[l] = '\0';
644116491Sharti						hname = cvthname((struct sockaddr *)&frominet);
645116491Sharti						unmapped((struct sockaddr *)&frominet);
646116491Sharti						if (validate((struct sockaddr *)&frominet, hname))
647116491Sharti							printline(hname, line);
648116491Sharti					} else if (l < 0 && errno != EINTR)
649116491Sharti						logerror("recvfrom inet");
650116491Sharti				}
651116491Sharti			}
652116491Sharti		}
653116491Sharti		STAILQ_FOREACH(fx, &funixes, next) {
654116491Sharti			if (FD_ISSET(fx->s, fdsr)) {
655116491Sharti				len = sizeof(fromunix);
656116491Sharti				l = recvfrom(fx->s, line, MAXLINE, 0,
657116491Sharti				    (struct sockaddr *)&fromunix, &len);
658116491Sharti				if (l > 0) {
659116491Sharti					line[l] = '\0';
660116491Sharti					printline(LocalHostName, line);
661116491Sharti				} else if (l < 0 && errno != EINTR)
662116491Sharti					logerror("recvfrom unix");
663116491Sharti			}
664116491Sharti		}
665116491Sharti	}
666116491Sharti	if (fdsr)
667116491Sharti		free(fdsr);
668116491Sharti}
669116491Sharti
670116491Shartistatic void
671116491Shartiunmapped(struct sockaddr *sa)
672116491Sharti{
673116491Sharti	struct sockaddr_in6 *sin6;
674116491Sharti	struct sockaddr_in sin4;
675116491Sharti
676116491Sharti	if (sa->sa_family != AF_INET6)
677116491Sharti		return;
678116491Sharti	if (sa->sa_len != sizeof(struct sockaddr_in6) ||
679116491Sharti	    sizeof(sin4) > sa->sa_len)
680116491Sharti		return;
681116491Sharti	sin6 = (struct sockaddr_in6 *)sa;
682116491Sharti	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
683116491Sharti		return;
684116491Sharti
685116491Sharti	memset(&sin4, 0, sizeof(sin4));
686116491Sharti	sin4.sin_family = AF_INET;
687116491Sharti	sin4.sin_len = sizeof(struct sockaddr_in);
688116491Sharti	memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
689116491Sharti	       sizeof(sin4.sin_addr));
690116491Sharti	sin4.sin_port = sin6->sin6_port;
691116491Sharti
692116491Sharti	memcpy(sa, &sin4, sin4.sin_len);
693116491Sharti}
694116491Sharti
695116491Shartistatic void
696116491Shartiusage(void)
697116491Sharti{
698116491Sharti
699116491Sharti	fprintf(stderr, "%s\n%s\n%s\n%s\n",
700118598Sharti		"usage: syslogd [-468ACcdknosuv] [-a allowed_peer]",
701118598Sharti		"               [-b bind_address] [-f config_file]",
702118598Sharti		"               [-l [mode:]path] [-m mark_interval]",
703118598Sharti		"               [-P pid_file] [-p log_socket]");
704116491Sharti	exit(1);
705116491Sharti}
706116491Sharti
707116491Sharti/*
708116491Sharti * Take a raw input line, decode the message, and print the message
709116491Sharti * on the appropriate log files.
710116491Sharti */
711116491Shartistatic void
712116491Shartiprintline(const char *hname, char *msg)
713116491Sharti{
714116491Sharti	char *p, *q;
715116491Sharti	long n;
716116491Sharti	int c, pri;
717116491Sharti	char line[MAXLINE + 1];
718116491Sharti
719116491Sharti	/* test for special codes */
720116491Sharti	p = msg;
721116491Sharti	pri = DEFUPRI;
722116491Sharti	if (*p == '<') {
723116491Sharti		errno = 0;
724116491Sharti		n = strtol(p + 1, &q, 10);
725116491Sharti		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
726116491Sharti			p = q + 1;
727116491Sharti			pri = n;
728116491Sharti		}
729116491Sharti	}
730116491Sharti	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
731116491Sharti		pri = DEFUPRI;
732116491Sharti
733116491Sharti	/*
734116491Sharti	 * Don't allow users to log kernel messages.
735116491Sharti	 * NOTE: since LOG_KERN == 0 this will also match
736116491Sharti	 *       messages with no facility specified.
737116491Sharti	 */
738116491Sharti	if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
739116491Sharti		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
740116491Sharti
741116491Sharti	q = line;
742116491Sharti
743116491Sharti	while ((c = (unsigned char)*p++) != '\0' &&
744116491Sharti	    q < &line[sizeof(line) - 4]) {
745116491Sharti		if (mask_C1 && (c & 0x80) && c < 0xA0) {
746116491Sharti			c &= 0x7F;
747116491Sharti			*q++ = 'M';
748116491Sharti			*q++ = '-';
749116491Sharti		}
750116491Sharti		if (isascii(c) && iscntrl(c)) {
751116491Sharti			if (c == '\n') {
752116491Sharti				*q++ = ' ';
753116491Sharti			} else if (c == '\t') {
754116491Sharti				*q++ = '\t';
755116491Sharti			} else {
756116491Sharti				*q++ = '^';
757116491Sharti				*q++ = c ^ 0100;
758116491Sharti			}
759116491Sharti		} else {
760116491Sharti			*q++ = c;
761116491Sharti		}
762116491Sharti	}
763116491Sharti	*q = '\0';
764116491Sharti
765116491Sharti	logmsg(pri, line, hname, 0);
766116491Sharti}
767116491Sharti
768116491Sharti/*
769116491Sharti * Read /dev/klog while data are available, split into lines.
770116491Sharti */
771116491Shartistatic void
772116491Shartireadklog(void)
773116491Sharti{
774116491Sharti	char *p, *q, line[MAXLINE + 1];
775116491Sharti	int len, i;
776116491Sharti
777116491Sharti	len = 0;
778116491Sharti	for (;;) {
779116491Sharti		i = read(fklog, line + len, MAXLINE - 1 - len);
780116491Sharti		if (i > 0) {
781116491Sharti			line[i + len] = '\0';
782116491Sharti		} else {
783116491Sharti			if (i < 0 && errno != EINTR && errno != EAGAIN) {
784116491Sharti				logerror("klog");
785116491Sharti				fklog = -1;
786116491Sharti			}
787116491Sharti			break;
788116491Sharti		}
789116491Sharti
790116491Sharti		for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
791116491Sharti			*q = '\0';
792116491Sharti			printsys(p);
793116491Sharti		}
794116491Sharti		len = strlen(p);
795116491Sharti		if (len >= MAXLINE - 1) {
796116491Sharti			printsys(p);
797116491Sharti			len = 0;
798116491Sharti		}
799116491Sharti		if (len > 0)
800116491Sharti			memmove(line, p, len + 1);
801116491Sharti	}
802116491Sharti	if (len > 0)
803116491Sharti		printsys(line);
804116491Sharti}
805116491Sharti
806116491Sharti/*
807116491Sharti * Take a raw input line from /dev/klog, format similar to syslog().
808116491Sharti */
809116491Shartistatic void
810116491Shartiprintsys(char *msg)
811116491Sharti{
812116491Sharti	char *p, *q;
813116491Sharti	long n;
814116491Sharti	int flags, isprintf, pri;
815116491Sharti
816116491Sharti	flags = ISKERNEL | SYNC_FILE | ADDDATE;	/* fsync after write */
817116491Sharti	p = msg;
818116491Sharti	pri = DEFSPRI;
819116491Sharti	isprintf = 1;
820116491Sharti	if (*p == '<') {
821116491Sharti		errno = 0;
822116491Sharti		n = strtol(p + 1, &q, 10);
823116491Sharti		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
824116491Sharti			p = q + 1;
825116491Sharti			pri = n;
826116491Sharti			isprintf = 0;
827		}
828	}
829	/*
830	 * Kernel printf's and LOG_CONSOLE messages have been displayed
831	 * on the console already.
832	 */
833	if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
834		flags |= IGN_CONS;
835	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
836		pri = DEFSPRI;
837	logmsg(pri, p, LocalHostName, flags);
838}
839
840static time_t	now;
841
842/*
843 * Match a program or host name against a specification.
844 * Return a non-0 value if the message must be ignored
845 * based on the specification.
846 */
847static int
848skip_message(const char *name, const char *spec, int checkcase)
849{
850	const char *s;
851	char prev, next;
852	int exclude = 0;
853	/* Behaviour on explicit match */
854
855	if (spec == NULL)
856		return 0;
857	switch (*spec) {
858	case '-':
859		exclude = 1;
860		/*FALLTHROUGH*/
861	case '+':
862		spec++;
863		break;
864	default:
865		break;
866	}
867	if (checkcase)
868		s = strstr (spec, name);
869	else
870		s = strcasestr (spec, name);
871
872	if (s != NULL) {
873		prev = (s == spec ? ',' : *(s - 1));
874		next = *(s + strlen (name));
875
876		if (prev == ',' && (next == '\0' || next == ','))
877			/* Explicit match: skip iff the spec is an
878			   exclusive one. */
879			return exclude;
880	}
881
882	/* No explicit match for this name: skip the message iff
883	   the spec is an inclusive one. */
884	return !exclude;
885}
886
887/*
888 * Log a message to the appropriate log files, users, etc. based on
889 * the priority.
890 */
891static void
892logmsg(int pri, const char *msg, const char *from, int flags)
893{
894	struct filed *f;
895	int i, fac, msglen, omask, prilev;
896	const char *timestamp;
897 	char prog[NAME_MAX+1];
898	char buf[MAXLINE+1];
899
900	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
901	    pri, flags, from, msg);
902
903	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
904
905	/*
906	 * Check to see if msg looks non-standard.
907	 */
908	msglen = strlen(msg);
909	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
910	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
911		flags |= ADDDATE;
912
913	(void)time(&now);
914	if (flags & ADDDATE) {
915		timestamp = ctime(&now) + 4;
916	} else {
917		timestamp = msg;
918		msg += 16;
919		msglen -= 16;
920	}
921
922	/* skip leading blanks */
923	while (isspace(*msg)) {
924		msg++;
925		msglen--;
926	}
927
928	/* extract facility and priority level */
929	if (flags & MARK)
930		fac = LOG_NFACILITIES;
931	else
932		fac = LOG_FAC(pri);
933
934	/* Check maximum facility number. */
935	if (fac > LOG_NFACILITIES) {
936		(void)sigsetmask(omask);
937		return;
938	}
939
940	prilev = LOG_PRI(pri);
941
942	/* extract program name */
943	for (i = 0; i < NAME_MAX; i++) {
944		if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
945		    msg[i] == '/' || isspace(msg[i]))
946			break;
947		prog[i] = msg[i];
948	}
949	prog[i] = 0;
950
951	/* add kernel prefix for kernel messages */
952	if (flags & ISKERNEL) {
953		snprintf(buf, sizeof(buf), "%s: %s",
954		    use_bootfile ? bootfile : "kernel", msg);
955		msg = buf;
956		msglen = strlen(buf);
957	}
958
959	/* log the message to the particular outputs */
960	if (!Initialized) {
961		f = &consfile;
962		/*
963		 * Open in non-blocking mode to avoid hangs during open
964		 * and close(waiting for the port to drain).
965		 */
966		f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
967
968		if (f->f_file >= 0) {
969			(void)strlcpy(f->f_lasttime, timestamp,
970				sizeof(f->f_lasttime));
971			fprintlog(f, flags, msg);
972			(void)close(f->f_file);
973		}
974		(void)sigsetmask(omask);
975		return;
976	}
977	for (f = Files; f; f = f->f_next) {
978		/* skip messages that are incorrect priority */
979		if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
980		     ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
981		     ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
982		     )
983		    || f->f_pmask[fac] == INTERNAL_NOPRI)
984			continue;
985
986		/* skip messages with the incorrect hostname */
987		if (skip_message(from, f->f_host, 0))
988			continue;
989
990		/* skip messages with the incorrect program name */
991		if (skip_message(prog, f->f_program, 1))
992			continue;
993
994		/* skip message to console if it has already been printed */
995		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
996			continue;
997
998		/* don't output marks to recently written files */
999		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1000			continue;
1001
1002		/*
1003		 * suppress duplicate lines to this file
1004		 */
1005		if (no_compress - (f->f_type != F_PIPE) < 1 &&
1006		    (flags & MARK) == 0 && msglen == f->f_prevlen &&
1007		    f->f_prevline && !strcmp(msg, f->f_prevline) &&
1008		    !strcasecmp(from, f->f_prevhost)) {
1009			(void)strlcpy(f->f_lasttime, timestamp,
1010				sizeof(f->f_lasttime));
1011			f->f_prevcount++;
1012			dprintf("msg repeated %d times, %ld sec of %d\n",
1013			    f->f_prevcount, (long)(now - f->f_time),
1014			    repeatinterval[f->f_repeatcount]);
1015			/*
1016			 * If domark would have logged this by now,
1017			 * flush it now (so we don't hold isolated messages),
1018			 * but back off so we'll flush less often
1019			 * in the future.
1020			 */
1021			if (now > REPEATTIME(f)) {
1022				fprintlog(f, flags, (char *)NULL);
1023				BACKOFF(f);
1024			}
1025		} else {
1026			/* new line, save it */
1027			if (f->f_prevcount)
1028				fprintlog(f, 0, (char *)NULL);
1029			f->f_repeatcount = 0;
1030			f->f_prevpri = pri;
1031			(void)strlcpy(f->f_lasttime, timestamp,
1032				sizeof(f->f_lasttime));
1033			(void)strlcpy(f->f_prevhost, from,
1034			    sizeof(f->f_prevhost));
1035			if (msglen < MAXSVLINE) {
1036				f->f_prevlen = msglen;
1037				(void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1038				fprintlog(f, flags, (char *)NULL);
1039			} else {
1040				f->f_prevline[0] = 0;
1041				f->f_prevlen = 0;
1042				fprintlog(f, flags, msg);
1043			}
1044		}
1045	}
1046	(void)sigsetmask(omask);
1047}
1048
1049static void
1050dofsync(void)
1051{
1052	struct filed *f;
1053
1054	for (f = Files; f; f = f->f_next) {
1055		if ((f->f_type == F_FILE) &&
1056		    (f->f_flags & FFLAG_NEEDSYNC)) {
1057			f->f_flags &= ~FFLAG_NEEDSYNC;
1058			(void)fsync(f->f_file);
1059		}
1060	}
1061}
1062
1063static void
1064fprintlog(struct filed *f, int flags, const char *msg)
1065{
1066	struct iovec iov[7];
1067	struct iovec *v;
1068	struct addrinfo *r;
1069	int i, l, lsent = 0;
1070	char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1071	char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1072	const char *msgret;
1073
1074	v = iov;
1075	if (f->f_type == F_WALL) {
1076		v->iov_base = greetings;
1077		/* The time displayed is not synchornized with the other log
1078		 * destinations (like messages).  Following fragment was using
1079		 * ctime(&now), which was updating the time every 30 sec.
1080		 * With f_lasttime, time is synchronized correctly.
1081		 */
1082		v->iov_len = snprintf(greetings, sizeof greetings,
1083		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1084		    f->f_prevhost, f->f_lasttime);
1085		if (v->iov_len > 0)
1086			v++;
1087		v->iov_base = nul;
1088		v->iov_len = 0;
1089		v++;
1090	} else {
1091		v->iov_base = f->f_lasttime;
1092		v->iov_len = strlen(f->f_lasttime);
1093		v++;
1094		v->iov_base = space;
1095		v->iov_len = 1;
1096		v++;
1097	}
1098
1099	if (LogFacPri) {
1100	  	static char fp_buf[30];	/* Hollow laugh */
1101		int fac = f->f_prevpri & LOG_FACMASK;
1102		int pri = LOG_PRI(f->f_prevpri);
1103		const char *f_s = NULL;
1104		char f_n[5];	/* Hollow laugh */
1105		const char *p_s = NULL;
1106		char p_n[5];	/* Hollow laugh */
1107
1108		if (LogFacPri > 1) {
1109		  CODE *c;
1110
1111		  for (c = facilitynames; c->c_name; c++) {
1112		    if (c->c_val == fac) {
1113		      f_s = c->c_name;
1114		      break;
1115		    }
1116		  }
1117		  for (c = prioritynames; c->c_name; c++) {
1118		    if (c->c_val == pri) {
1119		      p_s = c->c_name;
1120		      break;
1121		    }
1122		  }
1123		}
1124		if (!f_s) {
1125		  snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1126		  f_s = f_n;
1127		}
1128		if (!p_s) {
1129		  snprintf(p_n, sizeof p_n, "%d", pri);
1130		  p_s = p_n;
1131		}
1132		snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1133		v->iov_base = fp_buf;
1134		v->iov_len = strlen(fp_buf);
1135	} else {
1136		v->iov_base = nul;
1137		v->iov_len = 0;
1138	}
1139	v++;
1140
1141	v->iov_base = f->f_prevhost;
1142	v->iov_len = strlen(v->iov_base);
1143	v++;
1144	v->iov_base = space;
1145	v->iov_len = 1;
1146	v++;
1147
1148	if (msg) {
1149		wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1150		if (wmsg == NULL) {
1151			logerror("strdup");
1152			exit(1);
1153		}
1154		v->iov_base = wmsg;
1155		v->iov_len = strlen(msg);
1156	} else if (f->f_prevcount > 1) {
1157		v->iov_base = repbuf;
1158		v->iov_len = snprintf(repbuf, sizeof repbuf,
1159		    "last message repeated %d times", f->f_prevcount);
1160	} else if (f->f_prevline) {
1161		v->iov_base = f->f_prevline;
1162		v->iov_len = f->f_prevlen;
1163	} else {
1164		return;
1165	}
1166	v++;
1167
1168	dprintf("Logging to %s", TypeNames[f->f_type]);
1169	f->f_time = now;
1170
1171	switch (f->f_type) {
1172		int port;
1173	case F_UNUSED:
1174		dprintf("\n");
1175		break;
1176
1177	case F_FORW:
1178		port = (int)ntohs(((struct sockaddr_in *)
1179			    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1180		if (port != 514) {
1181			dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1182		} else {
1183			dprintf(" %s\n", f->f_un.f_forw.f_hname);
1184		}
1185		/* check for local vs remote messages */
1186		if (strcasecmp(f->f_prevhost, LocalHostName))
1187			l = snprintf(line, sizeof line - 1,
1188			    "<%d>%.15s Forwarded from %s: %s",
1189			    f->f_prevpri, (char *)iov[0].iov_base,
1190			    f->f_prevhost, (char *)iov[5].iov_base);
1191		else
1192			l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1193			     f->f_prevpri, (char *)iov[0].iov_base,
1194			    (char *)iov[5].iov_base);
1195		if (l < 0)
1196			l = 0;
1197		else if (l > MAXLINE)
1198			l = MAXLINE;
1199
1200		if (finet) {
1201			for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1202				for (i = 0; i < *finet; i++) {
1203#if 0
1204					/*
1205					 * should we check AF first, or just
1206					 * trial and error? FWD
1207					 */
1208					if (r->ai_family ==
1209					    address_family_of(finet[i+1]))
1210#endif
1211					lsent = sendto(finet[i+1], line, l, 0,
1212					    r->ai_addr, r->ai_addrlen);
1213					if (lsent == l)
1214						break;
1215				}
1216				if (lsent == l && !send_to_all)
1217					break;
1218			}
1219			dprintf("lsent/l: %d/%d\n", lsent, l);
1220			if (lsent != l) {
1221				int e = errno;
1222				logerror("sendto");
1223				errno = e;
1224				switch (errno) {
1225				case ENOBUFS:
1226				case ENETDOWN:
1227				case EHOSTUNREACH:
1228				case EHOSTDOWN:
1229					break;
1230				/* case EBADF: */
1231				/* case EACCES: */
1232				/* case ENOTSOCK: */
1233				/* case EFAULT: */
1234				/* case EMSGSIZE: */
1235				/* case EAGAIN: */
1236				/* case ENOBUFS: */
1237				/* case ECONNREFUSED: */
1238				default:
1239					dprintf("removing entry\n");
1240					f->f_type = F_UNUSED;
1241					break;
1242				}
1243			}
1244		}
1245		break;
1246
1247	case F_FILE:
1248		dprintf(" %s\n", f->f_un.f_fname);
1249		v->iov_base = lf;
1250		v->iov_len = 1;
1251		if (writev(f->f_file, iov, 7) < 0) {
1252			/*
1253			 * If writev(2) fails for potentially transient errors
1254			 * like the filesystem being full, ignore it.
1255			 * Otherwise remove this logfile from the list.
1256			 */
1257			if (errno != ENOSPC) {
1258				int e = errno;
1259				(void)close(f->f_file);
1260				f->f_type = F_UNUSED;
1261				errno = e;
1262				logerror(f->f_un.f_fname);
1263			}
1264		} else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1265			f->f_flags |= FFLAG_NEEDSYNC;
1266			needdofsync = 1;
1267		}
1268		break;
1269
1270	case F_PIPE:
1271		dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1272		v->iov_base = lf;
1273		v->iov_len = 1;
1274		if (f->f_un.f_pipe.f_pid == 0) {
1275			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1276						&f->f_un.f_pipe.f_pid)) < 0) {
1277				f->f_type = F_UNUSED;
1278				logerror(f->f_un.f_pipe.f_pname);
1279				break;
1280			}
1281		}
1282		if (writev(f->f_file, iov, 7) < 0) {
1283			int e = errno;
1284			(void)close(f->f_file);
1285			if (f->f_un.f_pipe.f_pid > 0)
1286				deadq_enter(f->f_un.f_pipe.f_pid,
1287					    f->f_un.f_pipe.f_pname);
1288			f->f_un.f_pipe.f_pid = 0;
1289			errno = e;
1290			logerror(f->f_un.f_pipe.f_pname);
1291		}
1292		break;
1293
1294	case F_CONSOLE:
1295		if (flags & IGN_CONS) {
1296			dprintf(" (ignored)\n");
1297			break;
1298		}
1299		/* FALLTHROUGH */
1300
1301	case F_TTY:
1302		dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1303		v->iov_base = crlf;
1304		v->iov_len = 2;
1305
1306		errno = 0;	/* ttymsg() only sometimes returns an errno */
1307		if ((msgret = ttymsg(iov, 7, f->f_un.f_fname, 10))) {
1308			f->f_type = F_UNUSED;
1309			logerror(msgret);
1310		}
1311		break;
1312
1313	case F_USERS:
1314	case F_WALL:
1315		dprintf("\n");
1316		v->iov_base = crlf;
1317		v->iov_len = 2;
1318		wallmsg(f, iov);
1319		break;
1320	}
1321	f->f_prevcount = 0;
1322	if (wmsg)
1323		free(wmsg);
1324}
1325
1326/*
1327 *  WALLMSG -- Write a message to the world at large
1328 *
1329 *	Write the specified message to either the entire
1330 *	world, or a list of approved users.
1331 */
1332static void
1333wallmsg(struct filed *f, struct iovec *iov)
1334{
1335	static int reenter;			/* avoid calling ourselves */
1336	FILE *uf;
1337	struct utmp ut;
1338	int i;
1339	const char *p;
1340	char line[sizeof(ut.ut_line) + 1];
1341
1342	if (reenter++)
1343		return;
1344	if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1345		logerror(_PATH_UTMP);
1346		reenter = 0;
1347		return;
1348	}
1349	/* NOSTRICT */
1350	while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
1351		if (ut.ut_name[0] == '\0')
1352			continue;
1353		/* We must use strncpy since ut_* may not be NUL terminated. */
1354		strncpy(line, ut.ut_line, sizeof(line) - 1);
1355		line[sizeof(line) - 1] = '\0';
1356		if (f->f_type == F_WALL) {
1357			if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) != NULL) {
1358				errno = 0;	/* already in msg */
1359				logerror(p);
1360			}
1361			continue;
1362		}
1363		/* should we send the message to this user? */
1364		for (i = 0; i < MAXUNAMES; i++) {
1365			if (!f->f_un.f_uname[i][0])
1366				break;
1367			if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1368			    UT_NAMESIZE)) {
1369				if ((p = ttymsg(iov, 7, line, TTYMSGTIME))
1370								!= NULL) {
1371					errno = 0;	/* already in msg */
1372					logerror(p);
1373				}
1374				break;
1375			}
1376		}
1377	}
1378	(void)fclose(uf);
1379	reenter = 0;
1380}
1381
1382static void
1383reapchild(int signo __unused)
1384{
1385	int status;
1386	pid_t pid;
1387	struct filed *f;
1388
1389	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1390		if (!Initialized)
1391			/* Don't tell while we are initting. */
1392			continue;
1393
1394		/* First, look if it's a process from the dead queue. */
1395		if (deadq_remove(pid))
1396			goto oncemore;
1397
1398		/* Now, look in list of active processes. */
1399		for (f = Files; f; f = f->f_next)
1400			if (f->f_type == F_PIPE &&
1401			    f->f_un.f_pipe.f_pid == pid) {
1402				(void)close(f->f_file);
1403				f->f_un.f_pipe.f_pid = 0;
1404				log_deadchild(pid, status,
1405					      f->f_un.f_pipe.f_pname);
1406				break;
1407			}
1408	  oncemore:
1409		continue;
1410	}
1411}
1412
1413/*
1414 * Return a printable representation of a host address.
1415 */
1416static const char *
1417cvthname(struct sockaddr *f)
1418{
1419	int error, hl;
1420	sigset_t omask, nmask;
1421	static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1422
1423	error = getnameinfo((struct sockaddr *)f,
1424			    ((struct sockaddr *)f)->sa_len,
1425			    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1426	dprintf("cvthname(%s)\n", ip);
1427
1428	if (error) {
1429		dprintf("Malformed from address %s\n", gai_strerror(error));
1430		return ("???");
1431	}
1432	if (!resolve)
1433		return (ip);
1434
1435	sigemptyset(&nmask);
1436	sigaddset(&nmask, SIGHUP);
1437	sigprocmask(SIG_BLOCK, &nmask, &omask);
1438	error = getnameinfo((struct sockaddr *)f,
1439			    ((struct sockaddr *)f)->sa_len,
1440			    hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1441	sigprocmask(SIG_SETMASK, &omask, NULL);
1442	if (error) {
1443		dprintf("Host name for your address (%s) unknown\n", ip);
1444		return (ip);
1445	}
1446	hl = strlen(hname);
1447	if (hl > 0 && hname[hl-1] == '.')
1448		hname[--hl] = '\0';
1449	trimdomain(hname, hl);
1450	return (hname);
1451}
1452
1453static void
1454dodie(int signo)
1455{
1456
1457	WantDie = signo;
1458}
1459
1460static void
1461domark(int signo __unused)
1462{
1463
1464	MarkSet = 1;
1465}
1466
1467/*
1468 * Print syslogd errors some place.
1469 */
1470static void
1471logerror(const char *type)
1472{
1473	char buf[512];
1474	static int recursed = 0;
1475
1476	/* If there's an error while trying to log an error, give up. */
1477	if (recursed)
1478		return;
1479	recursed++;
1480	if (errno)
1481		(void)snprintf(buf,
1482		    sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1483	else
1484		(void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1485	errno = 0;
1486	dprintf("%s\n", buf);
1487	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1488	recursed--;
1489}
1490
1491static void
1492die(int signo)
1493{
1494	struct filed *f;
1495	struct funix *fx;
1496	int was_initialized;
1497	char buf[100];
1498
1499	was_initialized = Initialized;
1500	Initialized = 0;	/* Don't log SIGCHLDs. */
1501	for (f = Files; f != NULL; f = f->f_next) {
1502		/* flush any pending output */
1503		if (f->f_prevcount)
1504			fprintlog(f, 0, (char *)NULL);
1505		if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1506			(void)close(f->f_file);
1507			f->f_un.f_pipe.f_pid = 0;
1508		}
1509	}
1510	Initialized = was_initialized;
1511	if (signo) {
1512		dprintf("syslogd: exiting on signal %d\n", signo);
1513		(void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1514		errno = 0;
1515		logerror(buf);
1516	}
1517	STAILQ_FOREACH(fx, &funixes, next)
1518		(void)unlink(fx->name);
1519	pidfile_remove(pfh);
1520
1521	exit(1);
1522}
1523
1524/*
1525 *  INIT -- Initialize syslogd from configuration table
1526 */
1527static void
1528init(int signo)
1529{
1530	int i;
1531	FILE *cf;
1532	struct filed *f, *next, **nextp;
1533	char *p;
1534	char cline[LINE_MAX];
1535 	char prog[NAME_MAX+1];
1536	char host[MAXHOSTNAMELEN];
1537	char oldLocalHostName[MAXHOSTNAMELEN];
1538	char hostMsg[2*MAXHOSTNAMELEN+40];
1539	char bootfileMsg[LINE_MAX];
1540
1541	dprintf("init\n");
1542
1543	/*
1544	 * Load hostname (may have changed).
1545	 */
1546	if (signo != 0)
1547		(void)strlcpy(oldLocalHostName, LocalHostName,
1548		    sizeof(oldLocalHostName));
1549	if (gethostname(LocalHostName, sizeof(LocalHostName)))
1550		err(EX_OSERR, "gethostname() failed");
1551	if ((p = strchr(LocalHostName, '.')) != NULL) {
1552		*p++ = '\0';
1553		LocalDomain = p;
1554	} else {
1555		LocalDomain = "";
1556	}
1557
1558	/*
1559	 *  Close all open log files.
1560	 */
1561	Initialized = 0;
1562	for (f = Files; f != NULL; f = next) {
1563		/* flush any pending output */
1564		if (f->f_prevcount)
1565			fprintlog(f, 0, (char *)NULL);
1566
1567		switch (f->f_type) {
1568		case F_FILE:
1569		case F_FORW:
1570		case F_CONSOLE:
1571		case F_TTY:
1572			(void)close(f->f_file);
1573			break;
1574		case F_PIPE:
1575			if (f->f_un.f_pipe.f_pid > 0) {
1576				(void)close(f->f_file);
1577				deadq_enter(f->f_un.f_pipe.f_pid,
1578					    f->f_un.f_pipe.f_pname);
1579			}
1580			f->f_un.f_pipe.f_pid = 0;
1581			break;
1582		}
1583		next = f->f_next;
1584		if (f->f_program) free(f->f_program);
1585		if (f->f_host) free(f->f_host);
1586		free((char *)f);
1587	}
1588	Files = NULL;
1589	nextp = &Files;
1590
1591	/* open the configuration file */
1592	if ((cf = fopen(ConfFile, "r")) == NULL) {
1593		dprintf("cannot open %s\n", ConfFile);
1594		*nextp = (struct filed *)calloc(1, sizeof(*f));
1595		if (*nextp == NULL) {
1596			logerror("calloc");
1597			exit(1);
1598		}
1599		cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1600		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1601		if ((*nextp)->f_next == NULL) {
1602			logerror("calloc");
1603			exit(1);
1604		}
1605		cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1606		Initialized = 1;
1607		return;
1608	}
1609
1610	/*
1611	 *  Foreach line in the conf table, open that file.
1612	 */
1613	f = NULL;
1614	(void)strlcpy(host, "*", sizeof(host));
1615	(void)strlcpy(prog, "*", sizeof(prog));
1616	while (fgets(cline, sizeof(cline), cf) != NULL) {
1617		/*
1618		 * check for end-of-section, comments, strip off trailing
1619		 * spaces and newline character. #!prog is treated specially:
1620		 * following lines apply only to that program.
1621		 */
1622		for (p = cline; isspace(*p); ++p)
1623			continue;
1624		if (*p == 0)
1625			continue;
1626		if (*p == '#') {
1627			p++;
1628			if (*p != '!' && *p != '+' && *p != '-')
1629				continue;
1630		}
1631		if (*p == '+' || *p == '-') {
1632			host[0] = *p++;
1633			while (isspace(*p))
1634				p++;
1635			if ((!*p) || (*p == '*')) {
1636				(void)strlcpy(host, "*", sizeof(host));
1637				continue;
1638			}
1639			if (*p == '@')
1640				p = LocalHostName;
1641			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1642				if (!isalnum(*p) && *p != '.' && *p != '-'
1643				    && *p != ',' && *p != ':' && *p != '%')
1644					break;
1645				host[i] = *p++;
1646			}
1647			host[i] = '\0';
1648			continue;
1649		}
1650		if (*p == '!') {
1651			p++;
1652			while (isspace(*p)) p++;
1653			if ((!*p) || (*p == '*')) {
1654				(void)strlcpy(prog, "*", sizeof(prog));
1655				continue;
1656			}
1657			for (i = 0; i < NAME_MAX; i++) {
1658				if (!isprint(p[i]) || isspace(p[i]))
1659					break;
1660				prog[i] = p[i];
1661			}
1662			prog[i] = 0;
1663			continue;
1664		}
1665		for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1666			cline[i] = '\0';
1667		f = (struct filed *)calloc(1, sizeof(*f));
1668		if (f == NULL) {
1669			logerror("calloc");
1670			exit(1);
1671		}
1672		*nextp = f;
1673		nextp = &f->f_next;
1674		cfline(cline, f, prog, host);
1675	}
1676
1677	/* close the configuration file */
1678	(void)fclose(cf);
1679
1680	Initialized = 1;
1681
1682	if (Debug) {
1683		int port;
1684		for (f = Files; f; f = f->f_next) {
1685			for (i = 0; i <= LOG_NFACILITIES; i++)
1686				if (f->f_pmask[i] == INTERNAL_NOPRI)
1687					printf("X ");
1688				else
1689					printf("%d ", f->f_pmask[i]);
1690			printf("%s: ", TypeNames[f->f_type]);
1691			switch (f->f_type) {
1692			case F_FILE:
1693				printf("%s", f->f_un.f_fname);
1694				break;
1695
1696			case F_CONSOLE:
1697			case F_TTY:
1698				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1699				break;
1700
1701			case F_FORW:
1702				port = (int)ntohs(((struct sockaddr_in *)
1703				    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1704				if (port != 514) {
1705					printf("%s:%d",
1706						f->f_un.f_forw.f_hname, port);
1707				} else {
1708					printf("%s", f->f_un.f_forw.f_hname);
1709				}
1710				break;
1711
1712			case F_PIPE:
1713				printf("%s", f->f_un.f_pipe.f_pname);
1714				break;
1715
1716			case F_USERS:
1717				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1718					printf("%s, ", f->f_un.f_uname[i]);
1719				break;
1720			}
1721			if (f->f_program)
1722				printf(" (%s)", f->f_program);
1723			printf("\n");
1724		}
1725	}
1726
1727	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1728	dprintf("syslogd: restarted\n");
1729	/*
1730	 * Log a change in hostname, but only on a restart.
1731	 */
1732	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1733		(void)snprintf(hostMsg, sizeof(hostMsg),
1734		    "syslogd: hostname changed, \"%s\" to \"%s\"",
1735		    oldLocalHostName, LocalHostName);
1736		logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1737		dprintf("%s\n", hostMsg);
1738	}
1739	/*
1740	 * Log the kernel boot file if we aren't going to use it as
1741	 * the prefix, and if this is *not* a restart.
1742	 */
1743	if (signo == 0 && !use_bootfile) {
1744		(void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1745		    "syslogd: kernel boot file is %s", bootfile);
1746		logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1747		dprintf("%s\n", bootfileMsg);
1748	}
1749}
1750
1751/*
1752 * Crack a configuration file line
1753 */
1754static void
1755cfline(const char *line, struct filed *f, const char *prog, const char *host)
1756{
1757	struct addrinfo hints, *res;
1758	int error, i, pri, syncfile;
1759	const char *p, *q;
1760	char *bp;
1761	char buf[MAXLINE], ebuf[100];
1762
1763	dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1764
1765	errno = 0;	/* keep strerror() stuff out of logerror messages */
1766
1767	/* clear out file entry */
1768	memset(f, 0, sizeof(*f));
1769	for (i = 0; i <= LOG_NFACILITIES; i++)
1770		f->f_pmask[i] = INTERNAL_NOPRI;
1771
1772	/* save hostname if any */
1773	if (host && *host == '*')
1774		host = NULL;
1775	if (host) {
1776		int hl;
1777
1778		f->f_host = strdup(host);
1779		if (f->f_host == NULL) {
1780			logerror("strdup");
1781			exit(1);
1782		}
1783		hl = strlen(f->f_host);
1784		if (hl > 0 && f->f_host[hl-1] == '.')
1785			f->f_host[--hl] = '\0';
1786		trimdomain(f->f_host, hl);
1787	}
1788
1789	/* save program name if any */
1790	if (prog && *prog == '*')
1791		prog = NULL;
1792	if (prog) {
1793		f->f_program = strdup(prog);
1794		if (f->f_program == NULL) {
1795			logerror("strdup");
1796			exit(1);
1797		}
1798	}
1799
1800	/* scan through the list of selectors */
1801	for (p = line; *p && *p != '\t' && *p != ' ';) {
1802		int pri_done;
1803		int pri_cmp;
1804		int pri_invert;
1805
1806		/* find the end of this facility name list */
1807		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1808			continue;
1809
1810		/* get the priority comparison */
1811		pri_cmp = 0;
1812		pri_done = 0;
1813		pri_invert = 0;
1814		if (*q == '!') {
1815			pri_invert = 1;
1816			q++;
1817		}
1818		while (!pri_done) {
1819			switch (*q) {
1820			case '<':
1821				pri_cmp |= PRI_LT;
1822				q++;
1823				break;
1824			case '=':
1825				pri_cmp |= PRI_EQ;
1826				q++;
1827				break;
1828			case '>':
1829				pri_cmp |= PRI_GT;
1830				q++;
1831				break;
1832			default:
1833				pri_done++;
1834				break;
1835			}
1836		}
1837
1838		/* collect priority name */
1839		for (bp = buf; *q && !strchr("\t,; ", *q); )
1840			*bp++ = *q++;
1841		*bp = '\0';
1842
1843		/* skip cruft */
1844		while (strchr(",;", *q))
1845			q++;
1846
1847		/* decode priority name */
1848		if (*buf == '*') {
1849			pri = LOG_PRIMASK;
1850			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1851		} else {
1852			/* Ignore trailing spaces. */
1853			for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1854				buf[i] = '\0';
1855
1856			pri = decode(buf, prioritynames);
1857			if (pri < 0) {
1858				(void)snprintf(ebuf, sizeof ebuf,
1859				    "unknown priority name \"%s\"", buf);
1860				logerror(ebuf);
1861				return;
1862			}
1863		}
1864		if (!pri_cmp)
1865			pri_cmp = (UniquePriority)
1866				  ? (PRI_EQ)
1867				  : (PRI_EQ | PRI_GT)
1868				  ;
1869		if (pri_invert)
1870			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1871
1872		/* scan facilities */
1873		while (*p && !strchr("\t.; ", *p)) {
1874			for (bp = buf; *p && !strchr("\t,;. ", *p); )
1875				*bp++ = *p++;
1876			*bp = '\0';
1877
1878			if (*buf == '*') {
1879				for (i = 0; i < LOG_NFACILITIES; i++) {
1880					f->f_pmask[i] = pri;
1881					f->f_pcmp[i] = pri_cmp;
1882				}
1883			} else {
1884				i = decode(buf, facilitynames);
1885				if (i < 0) {
1886					(void)snprintf(ebuf, sizeof ebuf,
1887					    "unknown facility name \"%s\"",
1888					    buf);
1889					logerror(ebuf);
1890					return;
1891				}
1892				f->f_pmask[i >> 3] = pri;
1893				f->f_pcmp[i >> 3] = pri_cmp;
1894			}
1895			while (*p == ',' || *p == ' ')
1896				p++;
1897		}
1898
1899		p = q;
1900	}
1901
1902	/* skip to action part */
1903	while (*p == '\t' || *p == ' ')
1904		p++;
1905
1906	if (*p == '-') {
1907		syncfile = 0;
1908		p++;
1909	} else
1910		syncfile = 1;
1911
1912	switch (*p) {
1913	case '@':
1914		{
1915			char *tp;
1916			/*
1917			 * scan forward to see if there is a port defined.
1918			 * so we can't use strlcpy..
1919			 */
1920			i = sizeof(f->f_un.f_forw.f_hname);
1921			tp = f->f_un.f_forw.f_hname;
1922			p++;
1923
1924			while (*p && (*p != ':') && (i-- > 0)) {
1925				*tp++ = *p++;
1926			}
1927			*tp = '\0';
1928		}
1929		/* See if we copied a domain and have a port */
1930		if (*p == ':')
1931			p++;
1932		else
1933			p = NULL;
1934
1935		memset(&hints, 0, sizeof(hints));
1936		hints.ai_family = family;
1937		hints.ai_socktype = SOCK_DGRAM;
1938		error = getaddrinfo(f->f_un.f_forw.f_hname,
1939				p ? p : "syslog", &hints, &res);
1940		if (error) {
1941			logerror(gai_strerror(error));
1942			break;
1943		}
1944		f->f_un.f_forw.f_addr = res;
1945		f->f_type = F_FORW;
1946		break;
1947
1948	case '/':
1949		if ((f->f_file = open(p, logflags, 0600)) < 0) {
1950			f->f_type = F_UNUSED;
1951			logerror(p);
1952			break;
1953		}
1954		if (syncfile)
1955			f->f_flags |= FFLAG_SYNC;
1956		if (isatty(f->f_file)) {
1957			if (strcmp(p, ctty) == 0)
1958				f->f_type = F_CONSOLE;
1959			else
1960				f->f_type = F_TTY;
1961			(void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1962			    sizeof(f->f_un.f_fname));
1963		} else {
1964			(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1965			f->f_type = F_FILE;
1966		}
1967		break;
1968
1969	case '|':
1970		f->f_un.f_pipe.f_pid = 0;
1971		(void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
1972		    sizeof(f->f_un.f_pipe.f_pname));
1973		f->f_type = F_PIPE;
1974		break;
1975
1976	case '*':
1977		f->f_type = F_WALL;
1978		break;
1979
1980	default:
1981		for (i = 0; i < MAXUNAMES && *p; i++) {
1982			for (q = p; *q && *q != ','; )
1983				q++;
1984			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1985			if ((q - p) > UT_NAMESIZE)
1986				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1987			else
1988				f->f_un.f_uname[i][q - p] = '\0';
1989			while (*q == ',' || *q == ' ')
1990				q++;
1991			p = q;
1992		}
1993		f->f_type = F_USERS;
1994		break;
1995	}
1996}
1997
1998
1999/*
2000 *  Decode a symbolic name to a numeric value
2001 */
2002static int
2003decode(const char *name, CODE *codetab)
2004{
2005	CODE *c;
2006	char *p, buf[40];
2007
2008	if (isdigit(*name))
2009		return (atoi(name));
2010
2011	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2012		if (isupper(*name))
2013			*p = tolower(*name);
2014		else
2015			*p = *name;
2016	}
2017	*p = '\0';
2018	for (c = codetab; c->c_name; c++)
2019		if (!strcmp(buf, c->c_name))
2020			return (c->c_val);
2021
2022	return (-1);
2023}
2024
2025static void
2026markit(void)
2027{
2028	struct filed *f;
2029	dq_t q, next;
2030
2031	now = time((time_t *)NULL);
2032	MarkSeq += TIMERINTVL;
2033	if (MarkSeq >= MarkInterval) {
2034		logmsg(LOG_INFO, "-- MARK --",
2035		    LocalHostName, ADDDATE|MARK);
2036		MarkSeq = 0;
2037	}
2038
2039	for (f = Files; f; f = f->f_next) {
2040		if (f->f_prevcount && now >= REPEATTIME(f)) {
2041			dprintf("flush %s: repeated %d times, %d sec.\n",
2042			    TypeNames[f->f_type], f->f_prevcount,
2043			    repeatinterval[f->f_repeatcount]);
2044			fprintlog(f, 0, (char *)NULL);
2045			BACKOFF(f);
2046		}
2047	}
2048
2049	/* Walk the dead queue, and see if we should signal somebody. */
2050	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2051		next = TAILQ_NEXT(q, dq_entries);
2052
2053		switch (q->dq_timeout) {
2054		case 0:
2055			/* Already signalled once, try harder now. */
2056			if (kill(q->dq_pid, SIGKILL) != 0)
2057				(void)deadq_remove(q->dq_pid);
2058			break;
2059
2060		case 1:
2061			/*
2062			 * Timed out on dead queue, send terminate
2063			 * signal.  Note that we leave the removal
2064			 * from the dead queue to reapchild(), which
2065			 * will also log the event (unless the process
2066			 * didn't even really exist, in case we simply
2067			 * drop it from the dead queue).
2068			 */
2069			if (kill(q->dq_pid, SIGTERM) != 0)
2070				(void)deadq_remove(q->dq_pid);
2071			/* FALLTHROUGH */
2072
2073		default:
2074			q->dq_timeout--;
2075		}
2076	}
2077	MarkSet = 0;
2078	(void)alarm(TIMERINTVL);
2079}
2080
2081/*
2082 * fork off and become a daemon, but wait for the child to come online
2083 * before returing to the parent, or we get disk thrashing at boot etc.
2084 * Set a timer so we don't hang forever if it wedges.
2085 */
2086static int
2087waitdaemon(int nochdir, int noclose, int maxwait)
2088{
2089	int fd;
2090	int status;
2091	pid_t pid, childpid;
2092
2093	switch (childpid = fork()) {
2094	case -1:
2095		return (-1);
2096	case 0:
2097		break;
2098	default:
2099		signal(SIGALRM, timedout);
2100		alarm(maxwait);
2101		while ((pid = wait3(&status, 0, NULL)) != -1) {
2102			if (WIFEXITED(status))
2103				errx(1, "child pid %d exited with return code %d",
2104					pid, WEXITSTATUS(status));
2105			if (WIFSIGNALED(status))
2106				errx(1, "child pid %d exited on signal %d%s",
2107					pid, WTERMSIG(status),
2108					WCOREDUMP(status) ? " (core dumped)" :
2109					"");
2110			if (pid == childpid)	/* it's gone... */
2111				break;
2112		}
2113		exit(0);
2114	}
2115
2116	if (setsid() == -1)
2117		return (-1);
2118
2119	if (!nochdir)
2120		(void)chdir("/");
2121
2122	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2123		(void)dup2(fd, STDIN_FILENO);
2124		(void)dup2(fd, STDOUT_FILENO);
2125		(void)dup2(fd, STDERR_FILENO);
2126		if (fd > 2)
2127			(void)close (fd);
2128	}
2129	return (getppid());
2130}
2131
2132/*
2133 * We get a SIGALRM from the child when it's running and finished doing it's
2134 * fsync()'s or O_SYNC writes for all the boot messages.
2135 *
2136 * We also get a signal from the kernel if the timer expires, so check to
2137 * see what happened.
2138 */
2139static void
2140timedout(int sig __unused)
2141{
2142	int left;
2143	left = alarm(0);
2144	signal(SIGALRM, SIG_DFL);
2145	if (left == 0)
2146		errx(1, "timed out waiting for child");
2147	else
2148		_exit(0);
2149}
2150
2151/*
2152 * Add `s' to the list of allowable peer addresses to accept messages
2153 * from.
2154 *
2155 * `s' is a string in the form:
2156 *
2157 *    [*]domainname[:{servicename|portnumber|*}]
2158 *
2159 * or
2160 *
2161 *    netaddr/maskbits[:{servicename|portnumber|*}]
2162 *
2163 * Returns -1 on error, 0 if the argument was valid.
2164 */
2165static int
2166allowaddr(char *s)
2167{
2168	char *cp1, *cp2;
2169	struct allowedpeer ap;
2170	struct servent *se;
2171	int masklen = -1, i;
2172	struct addrinfo hints, *res;
2173	struct in_addr *addrp, *maskp;
2174	u_int32_t *addr6p, *mask6p;
2175	char ip[NI_MAXHOST];
2176
2177#ifdef INET6
2178	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2179#endif
2180		cp1 = s;
2181	if ((cp1 = strrchr(cp1, ':'))) {
2182		/* service/port provided */
2183		*cp1++ = '\0';
2184		if (strlen(cp1) == 1 && *cp1 == '*')
2185			/* any port allowed */
2186			ap.port = 0;
2187		else if ((se = getservbyname(cp1, "udp"))) {
2188			ap.port = ntohs(se->s_port);
2189		} else {
2190			ap.port = strtol(cp1, &cp2, 0);
2191			if (*cp2 != '\0')
2192				return (-1); /* port not numeric */
2193		}
2194	} else {
2195		if ((se = getservbyname("syslog", "udp")))
2196			ap.port = ntohs(se->s_port);
2197		else
2198			/* sanity, should not happen */
2199			ap.port = 514;
2200	}
2201
2202	if ((cp1 = strchr(s, '/')) != NULL &&
2203	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2204		*cp1 = '\0';
2205		if ((masklen = atoi(cp1 + 1)) < 0)
2206			return (-1);
2207	}
2208#ifdef INET6
2209	if (*s == '[') {
2210		cp2 = s + strlen(s) - 1;
2211		if (*cp2 == ']') {
2212			++s;
2213			*cp2 = '\0';
2214		} else {
2215			cp2 = NULL;
2216		}
2217	} else {
2218		cp2 = NULL;
2219	}
2220#endif
2221	memset(&hints, 0, sizeof(hints));
2222	hints.ai_family = PF_UNSPEC;
2223	hints.ai_socktype = SOCK_DGRAM;
2224	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2225	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2226		ap.isnumeric = 1;
2227		memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2228		memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2229		ap.a_mask.ss_family = res->ai_family;
2230		if (res->ai_family == AF_INET) {
2231			ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2232			maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2233			addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2234			if (masklen < 0) {
2235				/* use default netmask */
2236				if (IN_CLASSA(ntohl(addrp->s_addr)))
2237					maskp->s_addr = htonl(IN_CLASSA_NET);
2238				else if (IN_CLASSB(ntohl(addrp->s_addr)))
2239					maskp->s_addr = htonl(IN_CLASSB_NET);
2240				else
2241					maskp->s_addr = htonl(IN_CLASSC_NET);
2242			} else if (masklen <= 32) {
2243				/* convert masklen to netmask */
2244				if (masklen == 0)
2245					maskp->s_addr = 0;
2246				else
2247					maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2248			} else {
2249				freeaddrinfo(res);
2250				return (-1);
2251			}
2252			/* Lose any host bits in the network number. */
2253			addrp->s_addr &= maskp->s_addr;
2254		}
2255#ifdef INET6
2256		else if (res->ai_family == AF_INET6 && masklen <= 128) {
2257			ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2258			if (masklen < 0)
2259				masklen = 128;
2260			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2261			/* convert masklen to netmask */
2262			while (masklen > 0) {
2263				if (masklen < 32) {
2264					*mask6p = htonl(~(0xffffffff >> masklen));
2265					break;
2266				}
2267				*mask6p++ = 0xffffffff;
2268				masklen -= 32;
2269			}
2270			/* Lose any host bits in the network number. */
2271			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2272			addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2273			for (i = 0; i < 4; i++)
2274				addr6p[i] &= mask6p[i];
2275		}
2276#endif
2277		else {
2278			freeaddrinfo(res);
2279			return (-1);
2280		}
2281		freeaddrinfo(res);
2282	} else {
2283		/* arg `s' is domain name */
2284		ap.isnumeric = 0;
2285		ap.a_name = s;
2286		if (cp1)
2287			*cp1 = '/';
2288#ifdef INET6
2289		if (cp2) {
2290			*cp2 = ']';
2291			--s;
2292		}
2293#endif
2294	}
2295
2296	if (Debug) {
2297		printf("allowaddr: rule %d: ", NumAllowed);
2298		if (ap.isnumeric) {
2299			printf("numeric, ");
2300			getnameinfo((struct sockaddr *)&ap.a_addr,
2301				    ((struct sockaddr *)&ap.a_addr)->sa_len,
2302				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2303			printf("addr = %s, ", ip);
2304			getnameinfo((struct sockaddr *)&ap.a_mask,
2305				    ((struct sockaddr *)&ap.a_mask)->sa_len,
2306				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2307			printf("mask = %s; ", ip);
2308		} else {
2309			printf("domainname = %s; ", ap.a_name);
2310		}
2311		printf("port = %d\n", ap.port);
2312	}
2313
2314	if ((AllowedPeers = realloc(AllowedPeers,
2315				    ++NumAllowed * sizeof(struct allowedpeer)))
2316	    == NULL) {
2317		logerror("realloc");
2318		exit(1);
2319	}
2320	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2321	return (0);
2322}
2323
2324/*
2325 * Validate that the remote peer has permission to log to us.
2326 */
2327static int
2328validate(struct sockaddr *sa, const char *hname)
2329{
2330	int i, j, reject;
2331	size_t l1, l2;
2332	char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2333	struct allowedpeer *ap;
2334	struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2335	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2336	struct addrinfo hints, *res;
2337	u_short sport;
2338
2339	if (NumAllowed == 0)
2340		/* traditional behaviour, allow everything */
2341		return (1);
2342
2343	(void)strlcpy(name, hname, sizeof(name));
2344	memset(&hints, 0, sizeof(hints));
2345	hints.ai_family = PF_UNSPEC;
2346	hints.ai_socktype = SOCK_DGRAM;
2347	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2348	if (getaddrinfo(name, NULL, &hints, &res) == 0)
2349		freeaddrinfo(res);
2350	else if (strchr(name, '.') == NULL) {
2351		strlcat(name, ".", sizeof name);
2352		strlcat(name, LocalDomain, sizeof name);
2353	}
2354	if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2355			NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2356		return (0);	/* for safety, should not occur */
2357	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2358		ip, port, name);
2359	sport = atoi(port);
2360
2361	/* now, walk down the list */
2362	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2363		if (ap->port != 0 && ap->port != sport) {
2364			dprintf("rejected in rule %d due to port mismatch.\n", i);
2365			continue;
2366		}
2367
2368		if (ap->isnumeric) {
2369			if (ap->a_addr.ss_family != sa->sa_family) {
2370				dprintf("rejected in rule %d due to address family mismatch.\n", i);
2371				continue;
2372			}
2373			if (ap->a_addr.ss_family == AF_INET) {
2374				sin4 = (struct sockaddr_in *)sa;
2375				a4p = (struct sockaddr_in *)&ap->a_addr;
2376				m4p = (struct sockaddr_in *)&ap->a_mask;
2377				if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2378				    != a4p->sin_addr.s_addr) {
2379					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2380					continue;
2381				}
2382			}
2383#ifdef INET6
2384			else if (ap->a_addr.ss_family == AF_INET6) {
2385				sin6 = (struct sockaddr_in6 *)sa;
2386				a6p = (struct sockaddr_in6 *)&ap->a_addr;
2387				m6p = (struct sockaddr_in6 *)&ap->a_mask;
2388				if (a6p->sin6_scope_id != 0 &&
2389				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
2390					dprintf("rejected in rule %d due to scope mismatch.\n", i);
2391					continue;
2392				}
2393				reject = 0;
2394				for (j = 0; j < 16; j += 4) {
2395					if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2396					    != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2397						++reject;
2398						break;
2399					}
2400				}
2401				if (reject) {
2402					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2403					continue;
2404				}
2405			}
2406#endif
2407			else
2408				continue;
2409		} else {
2410			cp = ap->a_name;
2411			l1 = strlen(name);
2412			if (*cp == '*') {
2413				/* allow wildmatch */
2414				cp++;
2415				l2 = strlen(cp);
2416				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2417					dprintf("rejected in rule %d due to name mismatch.\n", i);
2418					continue;
2419				}
2420			} else {
2421				/* exact match */
2422				l2 = strlen(cp);
2423				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2424					dprintf("rejected in rule %d due to name mismatch.\n", i);
2425					continue;
2426				}
2427			}
2428		}
2429		dprintf("accepted in rule %d.\n", i);
2430		return (1);	/* hooray! */
2431	}
2432	return (0);
2433}
2434
2435/*
2436 * Fairly similar to popen(3), but returns an open descriptor, as
2437 * opposed to a FILE *.
2438 */
2439static int
2440p_open(const char *prog, pid_t *rpid)
2441{
2442	int pfd[2], nulldesc, i;
2443	pid_t pid;
2444	sigset_t omask, mask;
2445	char *argv[4]; /* sh -c cmd NULL */
2446	char errmsg[200];
2447
2448	if (pipe(pfd) == -1)
2449		return (-1);
2450	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2451		/* we are royally screwed anyway */
2452		return (-1);
2453
2454	sigemptyset(&mask);
2455	sigaddset(&mask, SIGALRM);
2456	sigaddset(&mask, SIGHUP);
2457	sigprocmask(SIG_BLOCK, &mask, &omask);
2458	switch ((pid = fork())) {
2459	case -1:
2460		sigprocmask(SIG_SETMASK, &omask, 0);
2461		close(nulldesc);
2462		return (-1);
2463
2464	case 0:
2465		argv[0] = strdup("sh");
2466		argv[1] = strdup("-c");
2467		argv[2] = strdup(prog);
2468		argv[3] = NULL;
2469		if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2470			logerror("strdup");
2471			exit(1);
2472		}
2473
2474		alarm(0);
2475		(void)setsid();	/* Avoid catching SIGHUPs. */
2476
2477		/*
2478		 * Throw away pending signals, and reset signal
2479		 * behaviour to standard values.
2480		 */
2481		signal(SIGALRM, SIG_IGN);
2482		signal(SIGHUP, SIG_IGN);
2483		sigprocmask(SIG_SETMASK, &omask, 0);
2484		signal(SIGPIPE, SIG_DFL);
2485		signal(SIGQUIT, SIG_DFL);
2486		signal(SIGALRM, SIG_DFL);
2487		signal(SIGHUP, SIG_DFL);
2488
2489		dup2(pfd[0], STDIN_FILENO);
2490		dup2(nulldesc, STDOUT_FILENO);
2491		dup2(nulldesc, STDERR_FILENO);
2492		for (i = getdtablesize(); i > 2; i--)
2493			(void)close(i);
2494
2495		(void)execvp(_PATH_BSHELL, argv);
2496		_exit(255);
2497	}
2498
2499	sigprocmask(SIG_SETMASK, &omask, 0);
2500	close(nulldesc);
2501	close(pfd[0]);
2502	/*
2503	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
2504	 * supposed to get an EWOULDBLOCK on writev(2), which is
2505	 * caught by the logic above anyway, which will in turn close
2506	 * the pipe, and fork a new logging subprocess if necessary.
2507	 * The stale subprocess will be killed some time later unless
2508	 * it terminated itself due to closing its input pipe (so we
2509	 * get rid of really dead puppies).
2510	 */
2511	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2512		/* This is bad. */
2513		(void)snprintf(errmsg, sizeof errmsg,
2514			       "Warning: cannot change pipe to PID %d to "
2515			       "non-blocking behaviour.",
2516			       (int)pid);
2517		logerror(errmsg);
2518	}
2519	*rpid = pid;
2520	return (pfd[1]);
2521}
2522
2523static void
2524deadq_enter(pid_t pid, const char *name)
2525{
2526	dq_t p;
2527	int status;
2528
2529	/*
2530	 * Be paranoid, if we can't signal the process, don't enter it
2531	 * into the dead queue (perhaps it's already dead).  If possible,
2532	 * we try to fetch and log the child's status.
2533	 */
2534	if (kill(pid, 0) != 0) {
2535		if (waitpid(pid, &status, WNOHANG) > 0)
2536			log_deadchild(pid, status, name);
2537		return;
2538	}
2539
2540	p = malloc(sizeof(struct deadq_entry));
2541	if (p == NULL) {
2542		logerror("malloc");
2543		exit(1);
2544	}
2545
2546	p->dq_pid = pid;
2547	p->dq_timeout = DQ_TIMO_INIT;
2548	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2549}
2550
2551static int
2552deadq_remove(pid_t pid)
2553{
2554	dq_t q;
2555
2556	TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2557		if (q->dq_pid == pid) {
2558			TAILQ_REMOVE(&deadq_head, q, dq_entries);
2559				free(q);
2560				return (1);
2561		}
2562	}
2563
2564	return (0);
2565}
2566
2567static void
2568log_deadchild(pid_t pid, int status, const char *name)
2569{
2570	int code;
2571	char buf[256];
2572	const char *reason;
2573
2574	errno = 0; /* Keep strerror() stuff out of logerror messages. */
2575	if (WIFSIGNALED(status)) {
2576		reason = "due to signal";
2577		code = WTERMSIG(status);
2578	} else {
2579		reason = "with status";
2580		code = WEXITSTATUS(status);
2581		if (code == 0)
2582			return;
2583	}
2584	(void)snprintf(buf, sizeof buf,
2585		       "Logging subprocess %d (%s) exited %s %d.",
2586		       pid, name, reason, code);
2587	logerror(buf);
2588}
2589
2590static int *
2591socksetup(int af, const char *bindhostname)
2592{
2593	struct addrinfo hints, *res, *r;
2594	int error, maxs, *s, *socks;
2595
2596	memset(&hints, 0, sizeof(hints));
2597	hints.ai_flags = AI_PASSIVE;
2598	hints.ai_family = af;
2599	hints.ai_socktype = SOCK_DGRAM;
2600	error = getaddrinfo(bindhostname, "syslog", &hints, &res);
2601	if (error) {
2602		logerror(gai_strerror(error));
2603		errno = 0;
2604		die(0);
2605	}
2606
2607	/* Count max number of sockets we may open */
2608	for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2609	socks = malloc((maxs+1) * sizeof(int));
2610	if (socks == NULL) {
2611		logerror("couldn't allocate memory for sockets");
2612		die(0);
2613	}
2614
2615	*socks = 0;   /* num of sockets counter at start of array */
2616	s = socks + 1;
2617	for (r = res; r; r = r->ai_next) {
2618		int on = 1;
2619		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2620		if (*s < 0) {
2621			logerror("socket");
2622			continue;
2623		}
2624		if (r->ai_family == AF_INET6) {
2625			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2626				       (char *)&on, sizeof (on)) < 0) {
2627				logerror("setsockopt");
2628				close(*s);
2629				continue;
2630			}
2631		}
2632		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2633			       (char *)&on, sizeof (on)) < 0) {
2634			logerror("setsockopt");
2635			close(*s);
2636			continue;
2637		}
2638		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2639			close(*s);
2640			logerror("bind");
2641			continue;
2642		}
2643
2644		double_rbuf(*s);
2645
2646		(*socks)++;
2647		s++;
2648	}
2649
2650	if (*socks == 0) {
2651		free(socks);
2652		if (Debug)
2653			return (NULL);
2654		else
2655			die(0);
2656	}
2657	if (res)
2658		freeaddrinfo(res);
2659
2660	return (socks);
2661}
2662
2663static void
2664double_rbuf(int fd)
2665{
2666	socklen_t slen, len;
2667
2668	if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2669		len *= 2;
2670		setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, slen);
2671	}
2672}
2673