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