syslogd.c revision 278437
11558Srgrimes/*
21558Srgrimes * Copyright (c) 1983, 1988, 1993, 1994
31558Srgrimes *	The Regents of the University of California.  All rights reserved.
41558Srgrimes *
51558Srgrimes * Redistribution and use in source and binary forms, with or without
61558Srgrimes * modification, are permitted provided that the following conditions
71558Srgrimes * are met:
81558Srgrimes * 1. Redistributions of source code must retain the above copyright
91558Srgrimes *    notice, this list of conditions and the following disclaimer.
101558Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111558Srgrimes *    notice, this list of conditions and the following disclaimer in the
121558Srgrimes *    documentation and/or other materials provided with the distribution.
131558Srgrimes * 4. Neither the name of the University nor the names of its contributors
141558Srgrimes *    may be used to endorse or promote products derived from this software
151558Srgrimes *    without specific prior written permission.
161558Srgrimes *
171558Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
181558Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
191558Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
201558Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
211558Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221558Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
231558Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
241558Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
251558Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
261558Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
271558Srgrimes * SUCH DAMAGE.
281558Srgrimes */
291558Srgrimes
30114589Sobrien#ifndef lint
311558Srgrimesstatic const char copyright[] =
3238040Scharnier"@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
331558Srgrimes	The Regents of the University of California.  All rights reserved.\n";
341558Srgrimes#endif /* not lint */
351558Srgrimes
361558Srgrimes#ifndef lint
371558Srgrimes#if 0
381558Srgrimesstatic char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
39114589Sobrien#endif
4038040Scharnier#endif /* not lint */
41114589Sobrien
42114589Sobrien#include <sys/cdefs.h>
431558Srgrimes__FBSDID("$FreeBSD: stable/10/usr.sbin/syslogd/syslogd.c 278437 2015-02-09 07:52:45Z dim $");
441558Srgrimes
45102231Strhodes/*
461558Srgrimes *  syslogd -- log system messages
471558Srgrimes *
4842873Sluoqi * This program implements a system log. It takes a series of lines.
4996478Sphk * Each line may have a priority, signified as "<n>" as
501558Srgrimes * the first characters of the line.  If this is
511558Srgrimes * not present, a default priority is used.
5298542Smckusick *
5398542Smckusick * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
541558Srgrimes * cause it to reread its configuration file.
55207141Sjeff *
561558Srgrimes * Defined Constants:
57110174Sgordon *
581558Srgrimes * MAXLINE -- the maximum line length that can be handled.
591558Srgrimes * DEFUPRI -- the default priority for user messages
601558Srgrimes * DEFSPRI -- the default priority for kernel messages
61109597Sjmallett *
6238040Scharnier * Author: Eric Allman
631558Srgrimes * extensive changes by Ralph Campbell
641558Srgrimes * more extensive changes by Eric Allman (again)
65207141Sjeff * Extension to log by program name as well as facility and priority
6658047Ssheldonh *   by Peter da Silva.
67226266Smckusick * -u and -v by Harlan Stenn.
681558Srgrimes * Priority comparison code by Harlan Stenn.
691558Srgrimes */
701558Srgrimes
711558Srgrimes#define	MAXLINE		1024		/* maximum line length */
721558Srgrimes#define	MAXSVLINE	120		/* maximum saved line length */
73227081Sed#define	DEFUPRI		(LOG_USER|LOG_NOTICE)
74109597Sjmallett#define	DEFSPRI		(LOG_KERN|LOG_CRIT)
751558Srgrimes#define	TIMERINTVL	30		/* interval for checking flush, mark */
7692883Simp#define	TTYMSGTIME	1		/* timeout passed to ttymsg */
7792883Simp#define	RCVBUF_MINSIZE	(80 * 1024)	/* minimum size of dgram rcv buffer */
78207141Sjeff
79207141Sjeff#include <sys/param.h>
80207141Sjeff#include <sys/ioctl.h>
811558Srgrimes#include <sys/mman.h>
821558Srgrimes#include <sys/stat.h>
83109597Sjmallett#include <sys/wait.h>
841558Srgrimes#include <sys/socket.h>
85207141Sjeff#include <sys/queue.h>
86216798Skib#include <sys/uio.h>
87109963Sjmallett#include <sys/un.h>
8879750Sdd#include <sys/time.h>
89127455Sbde#include <sys/resource.h>
90207141Sjeff#include <sys/syslimits.h>
91207141Sjeff#include <sys/types.h>
92216798Skib
93229911Seadler#include <netinet/in.h>
94127441Sbde#include <netdb.h>
9579750Sdd#include <arpa/inet.h>
9642873Sluoqi
9742873Sluoqi#include <ctype.h>
981558Srgrimes#include <err.h>
99127441Sbde#include <errno.h>
100127441Sbde#include <fcntl.h>
101207141Sjeff#include <libutil.h>
102216798Skib#include <limits.h>
103207141Sjeff#include <paths.h>
104207141Sjeff#include <signal.h>
105127455Sbde#include <stdio.h>
106127441Sbde#include <stdlib.h>
107216798Skib#include <string.h>
108216798Skib#include <sysexits.h>
109127441Sbde#include <unistd.h>
110127441Sbde#include <utmpx.h>
111127441Sbde
112127441Sbde#include "pathnames.h"
113127441Sbde#include "ttymsg.h"
114127441Sbde
115127441Sbde#define SYSLOG_NAMES
116127441Sbde#include <sys/syslog.h>
117127441Sbde
118200796Straszconst char	*ConfFile = _PATH_LOGCONF;
119127441Sbdeconst char	*PidFile = _PATH_LOGPID;
120127441Sbdeconst char	ctty[] = _PATH_CONSOLE;
121127441Sbde
122127441Sbde#define	dprintf		if (Debug) printf
123127441Sbde
124127441Sbde#define	MAXUNAMES	20	/* maximum number of user names */
125127441Sbde
126127441Sbde/*
127127441Sbde * Unix sockets.
128127441Sbde * We have two default sockets, one with 666 permissions,
129127441Sbde * and one for privileged programs.
130127441Sbde */
131127441Sbdestruct funix {
132127441Sbde	int			s;
133127441Sbde	const char		*name;
134127441Sbde	mode_t			mode;
135127441Sbde	STAILQ_ENTRY(funix)	next;
136127441Sbde};
137127441Sbdestruct funix funix_secure =	{ -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
138127441Sbde				{ NULL } };
139127441Sbdestruct funix funix_default =	{ -1, _PATH_LOG, DEFFILEMODE,
140127441Sbde				{ &funix_secure } };
141127441Sbde
142127441SbdeSTAILQ_HEAD(, funix) funixes =	{ &funix_default,
143127441Sbde				&(funix_secure.next.stqe_next) };
144127441Sbde
145127441Sbde/*
146127441Sbde * Flags to logmsg().
147127441Sbde */
148207141Sjeff
149207141Sjeff#define	IGN_CONS	0x001	/* don't print on console */
150207141Sjeff#define	SYNC_FILE	0x002	/* do fsync on file after printing */
151207141Sjeff#define	ADDDATE		0x004	/* add a date to the message */
152207141Sjeff#define	MARK		0x008	/* this message is a mark */
153207141Sjeff#define	ISKERNEL	0x010	/* kernel generated message */
154207141Sjeff
155207141Sjeff/*
156207141Sjeff * This structure represents the files that will have log
157207141Sjeff * copies printed.
158207141Sjeff * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
159207141Sjeff * or if f_type if F_PIPE and f_pid > 0.
160163842Spjd */
161163842Spjd
162163842Spjdstruct filed {
163163842Spjd	struct	filed *f_next;		/* next in linked list */
164163842Spjd	short	f_type;			/* entry type, see below */
165163842Spjd	short	f_file;			/* file descriptor */
166163842Spjd	time_t	f_time;			/* time this was last written */
167163842Spjd	char	*f_host;		/* host from which to recd. */
168163842Spjd	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
169163842Spjd	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
170163842Spjd#define PRI_LT	0x1
171163842Spjd#define PRI_EQ	0x2
172163842Spjd#define PRI_GT	0x4
173127441Sbde	char	*f_program;		/* program this applies to */
174127441Sbde	union {
175127441Sbde		char	f_uname[MAXUNAMES][MAXLOGNAME];
176127441Sbde		struct {
177127441Sbde			char	f_hname[MAXHOSTNAMELEN];
178127441Sbde			struct addrinfo *f_addr;
179127441Sbde
180127441Sbde		} f_forw;		/* forwarding address */
181127441Sbde		char	f_fname[MAXPATHLEN];
182127441Sbde		struct {
183127441Sbde			char	f_pname[MAXPATHLEN];
184127441Sbde			pid_t	f_pid;
185127441Sbde		} f_pipe;
186127441Sbde	} f_un;
187127441Sbde	char	f_prevline[MAXSVLINE];		/* last message logged */
188127441Sbde	char	f_lasttime[16];			/* time of last occurrence */
189127441Sbde	char	f_prevhost[MAXHOSTNAMELEN];	/* host from which recd. */
190127441Sbde	int	f_prevpri;			/* pri of f_prevline */
191127441Sbde	int	f_prevlen;			/* length of f_prevline */
192127441Sbde	int	f_prevcount;			/* repetition cnt of prevline */
193127441Sbde	u_int	f_repeatcount;			/* number of "repeated" msgs */
194127441Sbde	int	f_flags;			/* file-specific flags */
195127441Sbde#define	FFLAG_SYNC 0x01
196127441Sbde#define	FFLAG_NEEDSYNC	0x02
197127441Sbde};
198127441Sbde
199127441Sbde/*
200127441Sbde * Queue of about-to-be dead processes we should watch out for.
201127441Sbde */
202127441Sbde
203127441SbdeTAILQ_HEAD(stailhead, deadq_entry) deadq_head;
204127441Sbdestruct stailhead *deadq_headp;
205127441Sbde
206127441Sbdestruct deadq_entry {
207127441Sbde	pid_t				dq_pid;
208127441Sbde	int				dq_timeout;
209127441Sbde	TAILQ_ENTRY(deadq_entry)	dq_entries;
210127441Sbde};
211127441Sbde
212200796Strasz/*
213200796Strasz * The timeout to apply to processes waiting on the dead queue.  Unit
214200796Strasz * of measure is `mark intervals', i.e. 20 minutes by default.
215200796Strasz * Processes on the dead queue will be terminated after that time.
216200796Strasz */
217200796Strasz
218200796Strasz#define	 DQ_TIMO_INIT	2
219200796Strasz
220200796Strasztypedef struct deadq_entry *dq_t;
221200796Strasz
222200796Strasz
223200796Strasz/*
224127441Sbde * Struct to hold records of network addresses that are allowed to log
225127441Sbde * to us.
226127441Sbde */
227127441Sbdestruct allowedpeer {
228127455Sbde	int isnumeric;
229127455Sbde	u_short port;
230127441Sbde	union {
231127441Sbde		struct {
232127441Sbde			struct sockaddr_storage addr;
233127441Sbde			struct sockaddr_storage mask;
234127441Sbde		} numeric;
235127441Sbde		char *name;
236127441Sbde	} u;
237127441Sbde#define a_addr u.numeric.addr
238127441Sbde#define a_mask u.numeric.mask
239127455Sbde#define a_name u.name
240127441Sbde};
241127455Sbde
242127441Sbde
243127441Sbde/*
244127441Sbde * Intervals at which we flush out "message repeated" messages,
245127441Sbde * in seconds after previous message is logged.  After each flush,
246127441Sbde * we move to the next interval until we reach the largest.
247127441Sbde */
248127441Sbdeint	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
249127441Sbde#define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
250127441Sbde#define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
251127441Sbde#define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
252127441Sbde				 (f)->f_repeatcount = MAXREPEAT; \
253127441Sbde			}
254127441Sbde
255127441Sbde/* values for f_type */
256127441Sbde#define F_UNUSED	0		/* unused entry */
257127441Sbde#define F_FILE		1		/* regular file */
258127441Sbde#define F_TTY		2		/* terminal */
259127441Sbde#define F_CONSOLE	3		/* console terminal */
260127441Sbde#define F_FORW		4		/* remote machine */
261127441Sbde#define F_USERS		5		/* list of users */
262127441Sbde#define F_WALL		6		/* everyone logged on */
263127441Sbde#define F_PIPE		7		/* pipe to program */
264127441Sbde
265207141Sjeffconst char *TypeNames[8] = {
266207141Sjeff	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
267207141Sjeff	"FORW",		"USERS",	"WALL",		"PIPE"
268207141Sjeff};
269207141Sjeff
270207141Sjeffstatic struct filed *Files;	/* Log files that we write to */
271207141Sjeffstatic struct filed consfile;	/* Console */
272207141Sjeff
273207141Sjeffstatic int	Debug;		/* debug flag */
274216798Skibstatic int	resolve = 1;	/* resolve hostname */
275216798Skibstatic char	LocalHostName[MAXHOSTNAMELEN];	/* our hostname */
276216798Skibstatic const char *LocalDomain;	/* our local domain name */
277216798Skibstatic int	*finet;		/* Internet datagram socket */
278216798Skibstatic int	fklog = -1;	/* /dev/klog */
279216798Skibstatic int	Initialized;	/* set when we have initialized ourselves */
280216798Skibstatic int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
281216798Skibstatic int	MarkSeq;	/* mark sequence number */
282216798Skibstatic int	NoBind;		/* don't bind() as suggested by RFC 3164 */
283216798Skibstatic int	SecureMode;	/* when true, receive only unix domain socks */
284216798Skib#ifdef INET6
285216798Skibstatic int	family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
286127441Sbde#else
287127441Sbdestatic int	family = PF_INET; /* protocol family (IPv4 only) */
288105120Srwatson#endif
28969314Scharnierstatic int	mask_C1 = 1;	/* mask characters from 0x80 - 0x9F */
29069314Scharnierstatic int	send_to_all;	/* send message to all IPv4/IPv6 addresses */
29169314Scharnierstatic int	use_bootfile;	/* log entire bootfile for every kern msg */
292127441Sbdestatic int	no_compress;	/* don't compress messages (1=pipes, 2=all) */
29369314Scharnierstatic int	logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
294109963Sjmallett
295109963Sjmallettstatic char	bootfile[MAXLINE+1]; /* booted kernel file */
296109963Sjmallett
297109963Sjmallettstruct allowedpeer *AllowedPeers; /* List of allowed peers */
298207421Sjeffstatic int	NumAllowed;	/* Number of entries in AllowedPeers */
299207421Sjeffstatic int	RemoteAddDate;	/* Always set the date on remote messages */
300207421Sjeff
30169829Scharnierstatic int	UniquePriority;	/* Only log specified priority? */
30269829Scharnierstatic int	LogFacPri;	/* Put facility and priority in log message: */
30369829Scharnier				/* 0=no, 1=numeric, 2=names */
30469829Scharnierstatic int	KeepKernFac;	/* Keep remotely logged kernel facility */
30569829Scharnierstatic int	needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
30669829Scharnierstatic struct pidfh *pfh;
30769829Scharnier
308110174Sgordonvolatile sig_atomic_t MarkSet, WantDie;
309110174Sgordon
310110174Sgordonstatic int	allowaddr(char *);
311110174Sgordonstatic void	cfline(const char *, struct filed *,
312105120Srwatson		    const char *, const char *);
313200796Straszstatic const char *cvthname(struct sockaddr *);
314105120Srwatsonstatic void	deadq_enter(pid_t, const char *);
315105120Srwatsonstatic int	deadq_remove(pid_t);
316105120Srwatsonstatic int	decode(const char *, const CODE *);
317200796Straszstatic void	die(int);
318200796Straszstatic void	dodie(int);
319200796Straszstatic void	dofsync(void);
320105120Srwatsonstatic void	domark(int);
321105120Srwatsonstatic void	fprintlog(struct filed *, int, const char *);
322105120Srwatsonstatic int	*socksetup(int, char *);
323105120Srwatsonstatic void	init(int);
324105120Srwatsonstatic void	logerror(const char *);
325105120Srwatsonstatic void	logmsg(int, const char *, const char *, int);
326105120Srwatsonstatic void	log_deadchild(pid_t, int, const char *);
327105120Srwatsonstatic void	markit(void);
328105120Srwatsonstatic int	skip_message(const char *, const char *, int);
329105120Srwatsonstatic void	printline(const char *, char *, int);
330105120Srwatsonstatic void	printsys(char *);
331105206Srwatsonstatic int	p_open(const char *, pid_t *);
332105120Srwatsonstatic void	readklog(void);
333105120Srwatsonstatic void	reapchild(int);
334105120Srwatsonstatic void	usage(void);
33569829Scharnierstatic int	validate(struct sockaddr *, const char *);
33669829Scharnierstatic void	unmapped(struct sockaddr *);
337127455Sbdestatic void	wallmsg(struct filed *, struct iovec *, const int iovlen);
33869829Scharnierstatic int	waitdaemon(int, int, int);
33969829Scharnierstatic void	timedout(int);
34069829Scharnierstatic void	increase_rcvbuf(int);
341127455Sbde
34269829Scharnierint
34369829Scharniermain(int argc, char *argv[])
34469829Scharnier{
34575377Smckusick	int ch, i, fdsrmax = 0, l;
34675377Smckusick	struct sockaddr_un sunx, fromunix;
347203769Smckusick	struct sockaddr_storage frominet;
34875377Smckusick	fd_set *fdsr = NULL;
34975377Smckusick	char line[MAXLINE + 1];
35075377Smckusick	char *bindhostname;
35175377Smckusick	const char *hname;
35275377Smckusick	struct timeval tv, *tvp;
35375377Smckusick	struct sigaction sact;
35475377Smckusick	struct funix *fx, *fx1;
35575377Smckusick	sigset_t mask;
356207141Sjeff	pid_t ppid = 1, spid;
357207141Sjeff	socklen_t len;
358207141Sjeff
359207141Sjeff	if (madvise(NULL, 0, MADV_PROTECT) != 0)
360207141Sjeff		dprintf("madvise() failed: %s\n", strerror(errno));
361207141Sjeff
362207141Sjeff	bindhostname = NULL;
363207141Sjeff	while ((ch = getopt(argc, argv, "468Aa:b:cCdf:kl:m:nNop:P:sS:Tuv"))
364207141Sjeff	    != -1)
365207141Sjeff		switch (ch) {
366207141Sjeff		case '4':
367207141Sjeff			family = PF_INET;
368207141Sjeff			break;
369207141Sjeff#ifdef INET6
370207141Sjeff		case '6':
371207141Sjeff			family = PF_INET6;
372207141Sjeff			break;
373207141Sjeff#endif
374207141Sjeff		case '8':
375207141Sjeff			mask_C1 = 0;
376208241Sjeff			break;
377207141Sjeff		case 'A':
378208241Sjeff			send_to_all++;
379208241Sjeff			break;
380208241Sjeff		case 'a':		/* allow specific network addresses only */
381208241Sjeff			if (allowaddr(optarg) == -1)
382207141Sjeff				usage();
383207141Sjeff			break;
384207141Sjeff		case 'b':
385163842Spjd			bindhostname = optarg;
386163842Spjd			break;
387163842Spjd		case 'c':
388163842Spjd			no_compress++;
389163842Spjd			break;
390163842Spjd		case 'C':
391163842Spjd			logflags |= O_CREAT;
392163842Spjd			break;
393163842Spjd		case 'd':		/* debug */
394163842Spjd			Debug++;
395163842Spjd			break;
396163842Spjd		case 'f':		/* configuration file */
397163842Spjd			ConfFile = optarg;
398163842Spjd			break;
399163842Spjd		case 'k':		/* keep remote kern fac */
400163842Spjd			KeepKernFac = 1;
401163842Spjd			break;
402163842Spjd		case 'l':
403163842Spjd		    {
404163842Spjd			long	perml;
405105120Srwatson			mode_t	mode;
406105120Srwatson			char	*name, *ep;
407105120Srwatson
408105120Srwatson			if (optarg[0] == '/') {
409105120Srwatson				mode = DEFFILEMODE;
410105120Srwatson				name = optarg;
411105120Srwatson			} else if ((name = strchr(optarg, ':')) != NULL) {
412105120Srwatson				*name++ = '\0';
413105120Srwatson				if (name[0] != '/')
414105120Srwatson					errx(1, "socket name must be absolute "
415105120Srwatson					    "path");
416105120Srwatson				if (isdigit(*optarg)) {
417105120Srwatson					perml = strtol(optarg, &ep, 8);
418105120Srwatson				    if (*ep || perml < 0 ||
419105120Srwatson					perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
420105120Srwatson					    errx(1, "invalid mode %s, exiting",
421105206Srwatson						optarg);
422105120Srwatson				    mode = (mode_t )perml;
423105120Srwatson				} else
424105120Srwatson					errx(1, "invalid mode %s, exiting",
42569829Scharnier					    optarg);
42669829Scharnier			} else	/* doesn't begin with '/', and no ':' */
427127455Sbde				errx(1, "can't parse path %s", optarg);
42869829Scharnier
42969829Scharnier			if (strlen(name) >= sizeof(sunx.sun_path))
43069829Scharnier				errx(1, "%s path too long, exiting", name);
43169829Scharnier			if ((fx = malloc(sizeof(struct funix))) == NULL)
43269829Scharnier				errx(1, "malloc failed");
43369829Scharnier			fx->s = -1;
43469829Scharnier			fx->name = name;
43569829Scharnier			fx->mode = mode;
43669829Scharnier			STAILQ_INSERT_TAIL(&funixes, fx, next);
43769829Scharnier			break;
43869829Scharnier		   }
439200796Strasz		case 'm':		/* mark interval */
440200796Strasz			MarkInterval = atoi(optarg) * 60;
441200796Strasz			break;
442200796Strasz		case 'N':
443200796Strasz			NoBind = 1;
444200796Strasz			SecureMode = 1;
445200796Strasz			break;
446200796Strasz		case 'n':
447200796Strasz			resolve = 0;
448200796Strasz			break;
449200796Strasz		case 'o':
450200796Strasz			use_bootfile = 1;
451200796Strasz			break;
452200796Strasz		case 'p':		/* path */
453200796Strasz			if (strlen(optarg) >= sizeof(sunx.sun_path))
454200796Strasz				errx(1, "%s path too long, exiting", optarg);
455200796Strasz			funix_default.name = optarg;
456200796Strasz			break;
457200796Strasz		case 'P':		/* path for alt. PID */
458200796Strasz			PidFile = optarg;
459200796Strasz			break;
460200796Strasz		case 's':		/* no network mode */
461200796Strasz			SecureMode++;
46269829Scharnier			break;
46369829Scharnier		case 'S':		/* path for privileged originator */
46469829Scharnier			if (strlen(optarg) >= sizeof(sunx.sun_path))
465127455Sbde				errx(1, "%s path too long, exiting", optarg);
46669829Scharnier			funix_secure.name = optarg;
467127455Sbde			break;
46875498Smckusick		case 'T':
46975498Smckusick			RemoteAddDate = 1;
47069829Scharnier			break;
47169829Scharnier		case 'u':		/* only log specified priority */
47269829Scharnier			UniquePriority++;
47369829Scharnier			break;
47469829Scharnier		case 'v':		/* log facility and priority */
475127455Sbde		  	LogFacPri++;
47669829Scharnier			break;
477127455Sbde		default:
47869829Scharnier			usage();
47969829Scharnier		}
48069829Scharnier	if ((argc -= optind) != 0)
48169829Scharnier		usage();
48269829Scharnier
48369829Scharnier	pfh = pidfile_open(PidFile, 0600, &spid);
48469829Scharnier	if (pfh == NULL) {
48569829Scharnier		if (errno == EEXIST)
48669829Scharnier			errx(1, "syslogd already running, pid: %d", spid);
487127455Sbde		warn("cannot open pid file");
48869829Scharnier	}
48969829Scharnier
49069829Scharnier	if (!Debug) {
49169829Scharnier		ppid = waitdaemon(0, 0, 30);
49269829Scharnier		if (ppid < 0) {
49369829Scharnier			warn("could not become daemon");
494127455Sbde			pidfile_remove(pfh);
49569829Scharnier			exit(1);
496127455Sbde		}
49769829Scharnier	} else {
49869829Scharnier		setlinebuf(stdout);
49969829Scharnier	}
50075377Smckusick
50175377Smckusick	if (NumAllowed)
502203769Smckusick		endservent();
50375377Smckusick
50475377Smckusick	consfile.f_type = F_CONSOLE;
50575377Smckusick	(void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
50675377Smckusick	    sizeof(consfile.f_un.f_fname));
50775377Smckusick	(void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
50875377Smckusick	(void)signal(SIGTERM, dodie);
50975377Smckusick	(void)signal(SIGINT, Debug ? dodie : SIG_IGN);
51075377Smckusick	(void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
511216798Skib	/*
512216798Skib	 * We don't want the SIGCHLD and SIGHUP handlers to interfere
513216798Skib	 * with each other; they are likely candidates for being called
514216798Skib	 * simultaneously (SIGHUP closes pipe descriptor, process dies,
515216798Skib	 * SIGCHLD happens).
516216798Skib	 */
517216798Skib	sigemptyset(&mask);
518216798Skib	sigaddset(&mask, SIGHUP);
519216798Skib	sact.sa_handler = reapchild;
520216798Skib	sact.sa_mask = mask;
521216798Skib	sact.sa_flags = SA_RESTART;
522216798Skib	(void)sigaction(SIGCHLD, &sact, NULL);
523216798Skib	(void)signal(SIGALRM, domark);
524216798Skib	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
525216798Skib	(void)alarm(TIMERINTVL);
526216798Skib
527216798Skib	TAILQ_INIT(&deadq_head);
528216798Skib
52969829Scharnier#ifndef SUN_LEN
530109963Sjmallett#define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
531109963Sjmallett#endif
532109963Sjmallett	STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
53342873Sluoqi		(void)unlink(fx->name);
53442873Sluoqi		memset(&sunx, 0, sizeof(sunx));
535109963Sjmallett		sunx.sun_family = AF_LOCAL;
53642873Sluoqi		(void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
53742873Sluoqi		fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
538102231Strhodes		if (fx->s < 0 ||
53942873Sluoqi		    bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
5401558Srgrimes		    chmod(fx->name, fx->mode) < 0) {
541109963Sjmallett			(void)snprintf(line, sizeof line,
542109963Sjmallett					"cannot create %s", fx->name);
543109963Sjmallett			logerror(line);
544109963Sjmallett			dprintf("cannot create %s (%d)\n", fx->name, errno);
545109963Sjmallett			if (fx == &funix_default || fx == &funix_secure)
5461558Srgrimes				die(0);
5471558Srgrimes			else {
5481558Srgrimes				STAILQ_REMOVE(&funixes, fx, funix, next);
549207141Sjeff				continue;
550207141Sjeff			}
551207141Sjeff		}
552207141Sjeff		increase_rcvbuf(fx->s);
553207141Sjeff	}
554207141Sjeff	if (SecureMode <= 1)
555227081Sed		finet = socksetup(family, bindhostname);
556207141Sjeff
557207141Sjeff	if (finet) {
558207141Sjeff		if (SecureMode) {
559207141Sjeff			for (i = 0; i < *finet; i++) {
560207141Sjeff				if (shutdown(finet[i+1], SHUT_RD) < 0) {
561207141Sjeff					logerror("shutdown");
562207141Sjeff					if (!Debug)
563207141Sjeff						die(0);
564207141Sjeff				}
565207141Sjeff			}
566207141Sjeff		} else {
567207141Sjeff			dprintf("listening on inet and/or inet6 socket\n");
568207141Sjeff		}
569207141Sjeff		dprintf("sending on inet and/or inet6 socket\n");
570207141Sjeff	}
571207141Sjeff
572207141Sjeff	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
573207141Sjeff		if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
574207141Sjeff			fklog = -1;
575207141Sjeff	if (fklog < 0)
576207141Sjeff		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
577207141Sjeff
578207141Sjeff	/* tuck my process id away */
579207141Sjeff	pidfile_write(pfh);
580207141Sjeff
581207141Sjeff	dprintf("off & running....\n");
582207141Sjeff
583207141Sjeff	init(0);
584208241Sjeff	/* prevent SIGHUP and SIGCHLD handlers from running in parallel */
585207141Sjeff	sigemptyset(&mask);
586207141Sjeff	sigaddset(&mask, SIGCHLD);
587207141Sjeff	sact.sa_handler = init;
588207141Sjeff	sact.sa_mask = mask;
589207141Sjeff	sact.sa_flags = SA_RESTART;
590207141Sjeff	(void)sigaction(SIGHUP, &sact, NULL);
591207141Sjeff
592207141Sjeff	tvp = &tv;
593207141Sjeff	tv.tv_sec = tv.tv_usec = 0;
594207141Sjeff
595207141Sjeff	if (fklog != -1 && fklog > fdsrmax)
596207141Sjeff		fdsrmax = fklog;
597207141Sjeff	if (finet && !SecureMode) {
598207141Sjeff		for (i = 0; i < *finet; i++) {
599207141Sjeff		    if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
600207141Sjeff			fdsrmax = finet[i+1];
601207141Sjeff		}
602207141Sjeff	}
603207141Sjeff	STAILQ_FOREACH(fx, &funixes, next)
604207141Sjeff		if (fx->s > fdsrmax)
605207141Sjeff			fdsrmax = fx->s;
606207141Sjeff
607207141Sjeff	fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
608207141Sjeff	    sizeof(fd_mask));
609207141Sjeff	if (fdsr == NULL)
610207141Sjeff		errx(1, "calloc fd_set");
611207141Sjeff
612207141Sjeff	for (;;) {
613207141Sjeff		if (MarkSet)
614207141Sjeff			markit();
615207141Sjeff		if (WantDie)
616207141Sjeff			die(WantDie);
617207141Sjeff
618207141Sjeff		bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
619207141Sjeff		    sizeof(fd_mask));
620207141Sjeff
621207141Sjeff		if (fklog != -1)
622207141Sjeff			FD_SET(fklog, fdsr);
623207141Sjeff		if (finet && !SecureMode) {
624207141Sjeff			for (i = 0; i < *finet; i++) {
625207141Sjeff				if (finet[i+1] != -1)
626207141Sjeff					FD_SET(finet[i+1], fdsr);
627207141Sjeff			}
628207141Sjeff		}
629207141Sjeff		STAILQ_FOREACH(fx, &funixes, next)
630207141Sjeff			FD_SET(fx->s, fdsr);
631207141Sjeff
632207141Sjeff		i = select(fdsrmax+1, fdsr, NULL, NULL,
633207141Sjeff		    needdofsync ? &tv : tvp);
634207141Sjeff		switch (i) {
635207141Sjeff		case 0:
636207141Sjeff			dofsync();
637207141Sjeff			needdofsync = 0;
638207141Sjeff			if (tvp) {
639207141Sjeff				tvp = NULL;
640207141Sjeff				if (ppid != 1)
641207141Sjeff					kill(ppid, SIGALRM);
642207141Sjeff			}
643207141Sjeff			continue;
644207141Sjeff		case -1:
645207141Sjeff			if (errno != EINTR)
646207141Sjeff				logerror("select");
647207141Sjeff			continue;
648207141Sjeff		}
649207141Sjeff		if (fklog != -1 && FD_ISSET(fklog, fdsr))
650207141Sjeff			readklog();
651207141Sjeff		if (finet && !SecureMode) {
652207141Sjeff			for (i = 0; i < *finet; i++) {
653207141Sjeff				if (FD_ISSET(finet[i+1], fdsr)) {
654207141Sjeff					len = sizeof(frominet);
655207141Sjeff					l = recvfrom(finet[i+1], line, MAXLINE,
656207141Sjeff					     0, (struct sockaddr *)&frominet,
657207141Sjeff					     &len);
658207141Sjeff					if (l > 0) {
659207141Sjeff						line[l] = '\0';
660207141Sjeff						hname = cvthname((struct sockaddr *)&frominet);
661207141Sjeff						unmapped((struct sockaddr *)&frominet);
662207141Sjeff						if (validate((struct sockaddr *)&frominet, hname))
663207141Sjeff							printline(hname, line, RemoteAddDate ? ADDDATE : 0);
664207141Sjeff					} else if (l < 0 && errno != EINTR)
665207141Sjeff						logerror("recvfrom inet");
666207141Sjeff				}
667207141Sjeff			}
668207141Sjeff		}
669207141Sjeff		STAILQ_FOREACH(fx, &funixes, next) {
670207141Sjeff			if (FD_ISSET(fx->s, fdsr)) {
671207141Sjeff				len = sizeof(fromunix);
672207141Sjeff				l = recvfrom(fx->s, line, MAXLINE, 0,
673207141Sjeff				    (struct sockaddr *)&fromunix, &len);
674207141Sjeff				if (l > 0) {
675207141Sjeff					line[l] = '\0';
676207141Sjeff					printline(LocalHostName, line, 0);
677207141Sjeff				} else if (l < 0 && errno != EINTR)
678207141Sjeff					logerror("recvfrom unix");
679207141Sjeff			}
680207141Sjeff		}
681207141Sjeff	}
682207141Sjeff	if (fdsr)
683207141Sjeff		free(fdsr);
684207141Sjeff}
685207141Sjeff
686207141Sjeffstatic void
687207141Sjeffunmapped(struct sockaddr *sa)
688207141Sjeff{
689207141Sjeff	struct sockaddr_in6 *sin6;
690207141Sjeff	struct sockaddr_in sin4;
691218603Skib
692218603Skib	if (sa->sa_family != AF_INET6)
693218603Skib		return;
694218603Skib	if (sa->sa_len != sizeof(struct sockaddr_in6) ||
695218603Skib	    sizeof(sin4) > sa->sa_len)
696218603Skib		return;
697218603Skib	sin6 = (struct sockaddr_in6 *)sa;
698218603Skib	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
699218603Skib		return;
700218603Skib
701218603Skib	memset(&sin4, 0, sizeof(sin4));
702218603Skib	sin4.sin_family = AF_INET;
703218603Skib	sin4.sin_len = sizeof(struct sockaddr_in);
704207141Sjeff	memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
705207141Sjeff	       sizeof(sin4.sin_addr));
706207141Sjeff	sin4.sin_port = sin6->sin6_port;
707207141Sjeff
708207141Sjeff	memcpy(sa, &sin4, sin4.sin_len);
709207141Sjeff}
710207141Sjeff
711207141Sjeffstatic void
712207141Sjeffusage(void)
713207141Sjeff{
714207141Sjeff
715207141Sjeff	fprintf(stderr, "%s\n%s\n%s\n%s\n",
716207141Sjeff		"usage: syslogd [-468ACcdknosTuv] [-a allowed_peer]",
717207141Sjeff		"               [-b bind_address] [-f config_file]",
718207141Sjeff		"               [-l [mode:]path] [-m mark_interval]",
719207141Sjeff		"               [-P pid_file] [-p log_socket]");
720207141Sjeff	exit(1);
721207141Sjeff}
722207141Sjeff
723207141Sjeff/*
724207141Sjeff * Take a raw input line, decode the message, and print the message
725207141Sjeff * on the appropriate log files.
726218603Skib */
727207141Sjeffstatic void
728207141Sjeffprintline(const char *hname, char *msg, int flags)
729207141Sjeff{
730207141Sjeff	char *p, *q;
731207141Sjeff	long n;
732207141Sjeff	int c, pri;
733207141Sjeff	char line[MAXLINE + 1];
734207141Sjeff
735207141Sjeff	/* test for special codes */
736207141Sjeff	p = msg;
737207141Sjeff	pri = DEFUPRI;
738207141Sjeff	if (*p == '<') {
739207141Sjeff		errno = 0;
740207141Sjeff		n = strtol(p + 1, &q, 10);
741207141Sjeff		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
742207141Sjeff			p = q + 1;
743218603Skib			pri = n;
744218603Skib		}
745207141Sjeff	}
746207141Sjeff	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
747207141Sjeff		pri = DEFUPRI;
748218603Skib
749218603Skib	/*
750218603Skib	 * Don't allow users to log kernel messages.
751207141Sjeff	 * NOTE: since LOG_KERN == 0 this will also match
752207141Sjeff	 *       messages with no facility specified.
753207141Sjeff	 */
754207141Sjeff	if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
755218603Skib		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
756207141Sjeff
757207141Sjeff	q = line;
758207141Sjeff
759207141Sjeff	while ((c = (unsigned char)*p++) != '\0' &&
760207141Sjeff	    q < &line[sizeof(line) - 4]) {
761207141Sjeff		if (mask_C1 && (c & 0x80) && c < 0xA0) {
762207141Sjeff			c &= 0x7F;
763207141Sjeff			*q++ = 'M';
764207141Sjeff			*q++ = '-';
765207141Sjeff		}
766207141Sjeff		if (isascii(c) && iscntrl(c)) {
767207141Sjeff			if (c == '\n') {
768207141Sjeff				*q++ = ' ';
769207141Sjeff			} else if (c == '\t') {
770207141Sjeff				*q++ = '\t';
771207141Sjeff			} else {
772207141Sjeff				*q++ = '^';
773207141Sjeff				*q++ = c ^ 0100;
774207141Sjeff			}
775207141Sjeff		} else {
776207141Sjeff			*q++ = c;
777207141Sjeff		}
778207141Sjeff	}
779207141Sjeff	*q = '\0';
780207141Sjeff
781207141Sjeff	logmsg(pri, line, hname, flags);
782207141Sjeff}
783207141Sjeff
784207141Sjeff/*
785207141Sjeff * Read /dev/klog while data are available, split into lines.
786207141Sjeff */
787207141Sjeffstatic void
788207141Sjeffreadklog(void)
789207141Sjeff{
790207141Sjeff	char *p, *q, line[MAXLINE + 1];
791207141Sjeff	int len, i;
792207141Sjeff
793207141Sjeff	len = 0;
794207141Sjeff	for (;;) {
795207141Sjeff		i = read(fklog, line + len, MAXLINE - 1 - len);
796207141Sjeff		if (i > 0) {
797207141Sjeff			line[i + len] = '\0';
798207141Sjeff		} else {
799207141Sjeff			if (i < 0 && errno != EINTR && errno != EAGAIN) {
800207141Sjeff				logerror("klog");
801207141Sjeff				fklog = -1;
802207141Sjeff			}
803207141Sjeff			break;
804207141Sjeff		}
805207141Sjeff
806207141Sjeff		for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
807207141Sjeff			*q = '\0';
808207141Sjeff			printsys(p);
809207141Sjeff		}
810207141Sjeff		len = strlen(p);
811207141Sjeff		if (len >= MAXLINE - 1) {
812207141Sjeff			printsys(p);
813207141Sjeff			len = 0;
814207141Sjeff		}
815207141Sjeff		if (len > 0)
816207141Sjeff			memmove(line, p, len + 1);
817207141Sjeff	}
818207141Sjeff	if (len > 0)
819207141Sjeff		printsys(line);
820207141Sjeff}
821207141Sjeff
822207141Sjeff/*
823207141Sjeff * Take a raw input line from /dev/klog, format similar to syslog().
824207141Sjeff */
825207141Sjeffstatic void
826207141Sjeffprintsys(char *msg)
827207141Sjeff{
828207141Sjeff	char *p, *q;
829207141Sjeff	long n;
830207141Sjeff	int flags, isprintf, pri;
831207141Sjeff
832207141Sjeff	flags = ISKERNEL | SYNC_FILE | ADDDATE;	/* fsync after write */
833207141Sjeff	p = msg;
834207141Sjeff	pri = DEFSPRI;
835207141Sjeff	isprintf = 1;
836207141Sjeff	if (*p == '<') {
837207141Sjeff		errno = 0;
838207141Sjeff		n = strtol(p + 1, &q, 10);
839207141Sjeff		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
840207141Sjeff			p = q + 1;
841207141Sjeff			pri = n;
842207141Sjeff			isprintf = 0;
843207141Sjeff		}
844207141Sjeff	}
845207141Sjeff	/*
846207141Sjeff	 * Kernel printf's and LOG_CONSOLE messages have been displayed
847207141Sjeff	 * on the console already.
848207141Sjeff	 */
849207141Sjeff	if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
850207141Sjeff		flags |= IGN_CONS;
851207141Sjeff	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
852207141Sjeff		pri = DEFSPRI;
853207141Sjeff	logmsg(pri, p, LocalHostName, flags);
854207141Sjeff}
855207141Sjeff
856207141Sjeffstatic time_t	now;
857207141Sjeff
858207141Sjeff/*
859207141Sjeff * Match a program or host name against a specification.
860207141Sjeff * Return a non-0 value if the message must be ignored
861207141Sjeff * based on the specification.
862207141Sjeff */
863207141Sjeffstatic int
864207141Sjeffskip_message(const char *name, const char *spec, int checkcase)
865207141Sjeff{
866207141Sjeff	const char *s;
867207141Sjeff	char prev, next;
868207141Sjeff	int exclude = 0;
869207141Sjeff	/* Behaviour on explicit match */
870207141Sjeff
871207141Sjeff	if (spec == NULL)
872207141Sjeff		return 0;
873207141Sjeff	switch (*spec) {
874207141Sjeff	case '-':
875207141Sjeff		exclude = 1;
876207141Sjeff		/*FALLTHROUGH*/
877207141Sjeff	case '+':
878207141Sjeff		spec++;
879207141Sjeff		break;
880207141Sjeff	default:
881207141Sjeff		break;
882207141Sjeff	}
883207141Sjeff	if (checkcase)
884207141Sjeff		s = strstr (spec, name);
885207141Sjeff	else
886207141Sjeff		s = strcasestr (spec, name);
887207141Sjeff
888207141Sjeff	if (s != NULL) {
889207141Sjeff		prev = (s == spec ? ',' : *(s - 1));
890207141Sjeff		next = *(s + strlen (name));
891207141Sjeff
892207141Sjeff		if (prev == ',' && (next == '\0' || next == ','))
893207141Sjeff			/* Explicit match: skip iff the spec is an
894207141Sjeff			   exclusive one. */
895207141Sjeff			return exclude;
896207141Sjeff	}
897207141Sjeff
898207141Sjeff	/* No explicit match for this name: skip the message iff
899207141Sjeff	   the spec is an inclusive one. */
900207141Sjeff	return !exclude;
901207141Sjeff}
902207141Sjeff
903207141Sjeff/*
904207141Sjeff * Log a message to the appropriate log files, users, etc. based on
905207141Sjeff * the priority.
906207141Sjeff */
907207141Sjeffstatic void
908207141Sjefflogmsg(int pri, const char *msg, const char *from, int flags)
909207141Sjeff{
910207141Sjeff	struct filed *f;
911207141Sjeff	int i, fac, msglen, omask, prilev;
912207141Sjeff	const char *timestamp;
913207141Sjeff 	char prog[NAME_MAX+1];
914207141Sjeff	char buf[MAXLINE+1];
915207141Sjeff
916207141Sjeff	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
917207141Sjeff	    pri, flags, from, msg);
918207141Sjeff
919207141Sjeff	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
920207141Sjeff
921207141Sjeff	/*
922207141Sjeff	 * Check to see if msg looks non-standard.
923207141Sjeff	 */
924207141Sjeff	msglen = strlen(msg);
925207141Sjeff	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
926226266Smckusick	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
927207141Sjeff		flags |= ADDDATE;
928207141Sjeff
929207141Sjeff	(void)time(&now);
930207141Sjeff	if (flags & ADDDATE) {
931207141Sjeff		timestamp = ctime(&now) + 4;
932207141Sjeff	} else {
933207141Sjeff		timestamp = msg;
934207141Sjeff		msg += 16;
935207141Sjeff		msglen -= 16;
936207141Sjeff	}
937207141Sjeff
938207141Sjeff	/* skip leading blanks */
939207141Sjeff	while (isspace(*msg)) {
940207141Sjeff		msg++;
941207141Sjeff		msglen--;
942207141Sjeff	}
943207141Sjeff
944207141Sjeff	/* extract facility and priority level */
945207141Sjeff	if (flags & MARK)
946207141Sjeff		fac = LOG_NFACILITIES;
947207141Sjeff	else
948207141Sjeff		fac = LOG_FAC(pri);
949207141Sjeff
950207141Sjeff	/* Check maximum facility number. */
951207141Sjeff	if (fac > LOG_NFACILITIES) {
952207141Sjeff		(void)sigsetmask(omask);
953207141Sjeff		return;
954207141Sjeff	}
955208241Sjeff
956208241Sjeff	prilev = LOG_PRI(pri);
957207141Sjeff
958207141Sjeff	/* extract program name */
959207141Sjeff	for (i = 0; i < NAME_MAX; i++) {
960207141Sjeff		if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
961207141Sjeff		    msg[i] == '/' || isspace(msg[i]))
962207141Sjeff			break;
963207141Sjeff		prog[i] = msg[i];
964207141Sjeff	}
965207141Sjeff	prog[i] = 0;
966207141Sjeff
967207141Sjeff	/* add kernel prefix for kernel messages */
968207141Sjeff	if (flags & ISKERNEL) {
969207141Sjeff		snprintf(buf, sizeof(buf), "%s: %s",
970207141Sjeff		    use_bootfile ? bootfile : "kernel", msg);
971207141Sjeff		msg = buf;
972207141Sjeff		msglen = strlen(buf);
973207141Sjeff	}
974207141Sjeff
975207141Sjeff	/* log the message to the particular outputs */
976207141Sjeff	if (!Initialized) {
977207141Sjeff		f = &consfile;
978207141Sjeff		/*
979207141Sjeff		 * Open in non-blocking mode to avoid hangs during open
980207141Sjeff		 * and close(waiting for the port to drain).
981207141Sjeff		 */
982207141Sjeff		f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
983207141Sjeff
984207141Sjeff		if (f->f_file >= 0) {
985207141Sjeff			(void)strlcpy(f->f_lasttime, timestamp,
986207141Sjeff				sizeof(f->f_lasttime));
987226266Smckusick			fprintlog(f, flags, msg);
988207141Sjeff			(void)close(f->f_file);
989207141Sjeff		}
990207141Sjeff		(void)sigsetmask(omask);
991207141Sjeff		return;
992207141Sjeff	}
993207141Sjeff	for (f = Files; f; f = f->f_next) {
994226266Smckusick		/* skip messages that are incorrect priority */
995226266Smckusick		if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
996226266Smckusick		     ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
997207141Sjeff		     ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
998207141Sjeff		     )
999207141Sjeff		    || f->f_pmask[fac] == INTERNAL_NOPRI)
1000207141Sjeff			continue;
1001207141Sjeff
1002207141Sjeff		/* skip messages with the incorrect hostname */
1003226266Smckusick		if (skip_message(from, f->f_host, 0))
1004226266Smckusick			continue;
1005226266Smckusick
1006226266Smckusick		/* skip messages with the incorrect program name */
1007207141Sjeff		if (skip_message(prog, f->f_program, 1))
1008207141Sjeff			continue;
1009207141Sjeff
1010207141Sjeff		/* skip message to console if it has already been printed */
1011207141Sjeff		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1012207141Sjeff			continue;
1013207141Sjeff
1014207141Sjeff		/* don't output marks to recently written files */
1015207141Sjeff		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1016207141Sjeff			continue;
1017207141Sjeff
1018207141Sjeff		/*
1019207141Sjeff		 * suppress duplicate lines to this file
1020207141Sjeff		 */
1021207141Sjeff		if (no_compress - (f->f_type != F_PIPE) < 1 &&
1022207141Sjeff		    (flags & MARK) == 0 && msglen == f->f_prevlen &&
1023207141Sjeff		    !strcmp(msg, f->f_prevline) &&
1024207141Sjeff		    !strcasecmp(from, f->f_prevhost)) {
1025207141Sjeff			(void)strlcpy(f->f_lasttime, timestamp,
1026207141Sjeff				sizeof(f->f_lasttime));
1027207141Sjeff			f->f_prevcount++;
1028207141Sjeff			dprintf("msg repeated %d times, %ld sec of %d\n",
1029207141Sjeff			    f->f_prevcount, (long)(now - f->f_time),
1030207141Sjeff			    repeatinterval[f->f_repeatcount]);
1031207141Sjeff			/*
1032207141Sjeff			 * If domark would have logged this by now,
1033207141Sjeff			 * flush it now (so we don't hold isolated messages),
1034207141Sjeff			 * but back off so we'll flush less often
1035207141Sjeff			 * in the future.
1036207141Sjeff			 */
1037207141Sjeff			if (now > REPEATTIME(f)) {
1038207141Sjeff				fprintlog(f, flags, (char *)NULL);
1039207141Sjeff				BACKOFF(f);
1040207141Sjeff			}
1041207141Sjeff		} else {
1042207141Sjeff			/* new line, save it */
1043207141Sjeff			if (f->f_prevcount)
1044207141Sjeff				fprintlog(f, 0, (char *)NULL);
1045207141Sjeff			f->f_repeatcount = 0;
1046207141Sjeff			f->f_prevpri = pri;
1047207141Sjeff			(void)strlcpy(f->f_lasttime, timestamp,
1048207141Sjeff				sizeof(f->f_lasttime));
1049207141Sjeff			(void)strlcpy(f->f_prevhost, from,
1050207141Sjeff			    sizeof(f->f_prevhost));
1051207141Sjeff			if (msglen < MAXSVLINE) {
1052207141Sjeff				f->f_prevlen = msglen;
1053207141Sjeff				(void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1054207141Sjeff				fprintlog(f, flags, (char *)NULL);
1055207141Sjeff			} else {
1056207141Sjeff				f->f_prevline[0] = 0;
1057207141Sjeff				f->f_prevlen = 0;
1058207141Sjeff				fprintlog(f, flags, msg);
1059207141Sjeff			}
1060207141Sjeff		}
1061207141Sjeff	}
1062207141Sjeff	(void)sigsetmask(omask);
1063207141Sjeff}
1064109597Sjmallett
10651558Srgrimesstatic void
1066216798Skibdofsync(void)
1067111287Sru{
1068207462Sedwin	struct filed *f;
1069207462Sedwin
1070207462Sedwin	for (f = Files; f; f = f->f_next) {
1071216798Skib		if ((f->f_type == F_FILE) &&
1072216798Skib		    (f->f_flags & FFLAG_NEEDSYNC)) {
10731558Srgrimes			f->f_flags &= ~FFLAG_NEEDSYNC;
10741558Srgrimes			(void)fsync(f->f_file);
10751558Srgrimes		}
10761558Srgrimes	}
1077109597Sjmallett}
10781558Srgrimes
1079200796Strasz#define IOV_SIZE 7
1080105162Srwatsonstatic void
1081200796Straszfprintlog(struct filed *f, int flags, const char *msg)
1082200796Strasz{
1083105162Srwatson	struct iovec iov[IOV_SIZE];
1084105162Srwatson	struct iovec *v;
1085109468Sjmallett	struct addrinfo *r;
108634266Sjulian	int i, l, lsent = 0;
1087207141Sjeff	char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1088207141Sjeff	char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1089163842Spjd	const char *msgret;
1090163842Spjd
1091216798Skib	v = iov;
1092216798Skib	if (f->f_type == F_WALL) {
10939315Sjoerg		v->iov_base = greetings;
10949315Sjoerg		/* The time displayed is not synchornized with the other log
109575377Smckusick		 * destinations (like messages).  Following fragment was using
109675377Smckusick		 * ctime(&now), which was updating the time every 30 sec.
109775377Smckusick		 * With f_lasttime, time is synchronized correctly.
109875377Smckusick		 */
10999315Sjoerg		v->iov_len = snprintf(greetings, sizeof greetings,
11009315Sjoerg		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
11019315Sjoerg		    f->f_prevhost, f->f_lasttime);
11029315Sjoerg		if (v->iov_len >= sizeof greetings)
11039315Sjoerg			v->iov_len = sizeof greetings - 1;
11049315Sjoerg		v++;
11059315Sjoerg		v->iov_base = nul;
11069315Sjoerg		v->iov_len = 0;
11079315Sjoerg		v++;
11089315Sjoerg	} else {
1109110174Sgordon		v->iov_base = f->f_lasttime;
1110110174Sgordon		v->iov_len = strlen(f->f_lasttime);
11119315Sjoerg		v++;
1112		v->iov_base = space;
1113		v->iov_len = 1;
1114		v++;
1115	}
1116
1117	if (LogFacPri) {
1118	  	static char fp_buf[30];	/* Hollow laugh */
1119		int fac = f->f_prevpri & LOG_FACMASK;
1120		int pri = LOG_PRI(f->f_prevpri);
1121		const char *f_s = NULL;
1122		char f_n[5];	/* Hollow laugh */
1123		const char *p_s = NULL;
1124		char p_n[5];	/* Hollow laugh */
1125
1126		if (LogFacPri > 1) {
1127		  const CODE *c;
1128
1129		  for (c = facilitynames; c->c_name; c++) {
1130		    if (c->c_val == fac) {
1131		      f_s = c->c_name;
1132		      break;
1133		    }
1134		  }
1135		  for (c = prioritynames; c->c_name; c++) {
1136		    if (c->c_val == pri) {
1137		      p_s = c->c_name;
1138		      break;
1139		    }
1140		  }
1141		}
1142		if (!f_s) {
1143		  snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1144		  f_s = f_n;
1145		}
1146		if (!p_s) {
1147		  snprintf(p_n, sizeof p_n, "%d", pri);
1148		  p_s = p_n;
1149		}
1150		snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1151		v->iov_base = fp_buf;
1152		v->iov_len = strlen(fp_buf);
1153	} else {
1154		v->iov_base = nul;
1155		v->iov_len = 0;
1156	}
1157	v++;
1158
1159	v->iov_base = f->f_prevhost;
1160	v->iov_len = strlen(v->iov_base);
1161	v++;
1162	v->iov_base = space;
1163	v->iov_len = 1;
1164	v++;
1165
1166	if (msg) {
1167		wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1168		if (wmsg == NULL) {
1169			logerror("strdup");
1170			exit(1);
1171		}
1172		v->iov_base = wmsg;
1173		v->iov_len = strlen(msg);
1174	} else if (f->f_prevcount > 1) {
1175		v->iov_base = repbuf;
1176		v->iov_len = snprintf(repbuf, sizeof repbuf,
1177		    "last message repeated %d times", f->f_prevcount);
1178	} else {
1179		v->iov_base = f->f_prevline;
1180		v->iov_len = f->f_prevlen;
1181	}
1182	v++;
1183
1184	dprintf("Logging to %s", TypeNames[f->f_type]);
1185	f->f_time = now;
1186
1187	switch (f->f_type) {
1188		int port;
1189	case F_UNUSED:
1190		dprintf("\n");
1191		break;
1192
1193	case F_FORW:
1194		port = (int)ntohs(((struct sockaddr_in *)
1195			    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1196		if (port != 514) {
1197			dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1198		} else {
1199			dprintf(" %s\n", f->f_un.f_forw.f_hname);
1200		}
1201		/* check for local vs remote messages */
1202		if (strcasecmp(f->f_prevhost, LocalHostName))
1203			l = snprintf(line, sizeof line - 1,
1204			    "<%d>%.15s Forwarded from %s: %s",
1205			    f->f_prevpri, (char *)iov[0].iov_base,
1206			    f->f_prevhost, (char *)iov[5].iov_base);
1207		else
1208			l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1209			     f->f_prevpri, (char *)iov[0].iov_base,
1210			    (char *)iov[5].iov_base);
1211		if (l < 0)
1212			l = 0;
1213		else if (l > MAXLINE)
1214			l = MAXLINE;
1215
1216		if (finet) {
1217			for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1218				for (i = 0; i < *finet; i++) {
1219#if 0
1220					/*
1221					 * should we check AF first, or just
1222					 * trial and error? FWD
1223					 */
1224					if (r->ai_family ==
1225					    address_family_of(finet[i+1]))
1226#endif
1227					lsent = sendto(finet[i+1], line, l, 0,
1228					    r->ai_addr, r->ai_addrlen);
1229					if (lsent == l)
1230						break;
1231				}
1232				if (lsent == l && !send_to_all)
1233					break;
1234			}
1235			dprintf("lsent/l: %d/%d\n", lsent, l);
1236			if (lsent != l) {
1237				int e = errno;
1238				logerror("sendto");
1239				errno = e;
1240				switch (errno) {
1241				case ENOBUFS:
1242				case ENETDOWN:
1243				case ENETUNREACH:
1244				case EHOSTUNREACH:
1245				case EHOSTDOWN:
1246				case EADDRNOTAVAIL:
1247					break;
1248				/* case EBADF: */
1249				/* case EACCES: */
1250				/* case ENOTSOCK: */
1251				/* case EFAULT: */
1252				/* case EMSGSIZE: */
1253				/* case EAGAIN: */
1254				/* case ENOBUFS: */
1255				/* case ECONNREFUSED: */
1256				default:
1257					dprintf("removing entry: errno=%d\n", e);
1258					f->f_type = F_UNUSED;
1259					break;
1260				}
1261			}
1262		}
1263		break;
1264
1265	case F_FILE:
1266		dprintf(" %s\n", f->f_un.f_fname);
1267		v->iov_base = lf;
1268		v->iov_len = 1;
1269		if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1270			/*
1271			 * If writev(2) fails for potentially transient errors
1272			 * like the filesystem being full, ignore it.
1273			 * Otherwise remove this logfile from the list.
1274			 */
1275			if (errno != ENOSPC) {
1276				int e = errno;
1277				(void)close(f->f_file);
1278				f->f_type = F_UNUSED;
1279				errno = e;
1280				logerror(f->f_un.f_fname);
1281			}
1282		} else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1283			f->f_flags |= FFLAG_NEEDSYNC;
1284			needdofsync = 1;
1285		}
1286		break;
1287
1288	case F_PIPE:
1289		dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1290		v->iov_base = lf;
1291		v->iov_len = 1;
1292		if (f->f_un.f_pipe.f_pid == 0) {
1293			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1294						&f->f_un.f_pipe.f_pid)) < 0) {
1295				f->f_type = F_UNUSED;
1296				logerror(f->f_un.f_pipe.f_pname);
1297				break;
1298			}
1299		}
1300		if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1301			int e = errno;
1302			(void)close(f->f_file);
1303			if (f->f_un.f_pipe.f_pid > 0)
1304				deadq_enter(f->f_un.f_pipe.f_pid,
1305					    f->f_un.f_pipe.f_pname);
1306			f->f_un.f_pipe.f_pid = 0;
1307			errno = e;
1308			logerror(f->f_un.f_pipe.f_pname);
1309		}
1310		break;
1311
1312	case F_CONSOLE:
1313		if (flags & IGN_CONS) {
1314			dprintf(" (ignored)\n");
1315			break;
1316		}
1317		/* FALLTHROUGH */
1318
1319	case F_TTY:
1320		dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1321		v->iov_base = crlf;
1322		v->iov_len = 2;
1323
1324		errno = 0;	/* ttymsg() only sometimes returns an errno */
1325		if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1326			f->f_type = F_UNUSED;
1327			logerror(msgret);
1328		}
1329		break;
1330
1331	case F_USERS:
1332	case F_WALL:
1333		dprintf("\n");
1334		v->iov_base = crlf;
1335		v->iov_len = 2;
1336		wallmsg(f, iov, IOV_SIZE);
1337		break;
1338	}
1339	f->f_prevcount = 0;
1340	free(wmsg);
1341}
1342
1343/*
1344 *  WALLMSG -- Write a message to the world at large
1345 *
1346 *	Write the specified message to either the entire
1347 *	world, or a list of approved users.
1348 */
1349static void
1350wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1351{
1352	static int reenter;			/* avoid calling ourselves */
1353	struct utmpx *ut;
1354	int i;
1355	const char *p;
1356
1357	if (reenter++)
1358		return;
1359	setutxent();
1360	/* NOSTRICT */
1361	while ((ut = getutxent()) != NULL) {
1362		if (ut->ut_type != USER_PROCESS)
1363			continue;
1364		if (f->f_type == F_WALL) {
1365			if ((p = ttymsg(iov, iovlen, ut->ut_line,
1366			    TTYMSGTIME)) != NULL) {
1367				errno = 0;	/* already in msg */
1368				logerror(p);
1369			}
1370			continue;
1371		}
1372		/* should we send the message to this user? */
1373		for (i = 0; i < MAXUNAMES; i++) {
1374			if (!f->f_un.f_uname[i][0])
1375				break;
1376			if (!strcmp(f->f_un.f_uname[i], ut->ut_user)) {
1377				if ((p = ttymsg(iov, iovlen, ut->ut_line,
1378				    TTYMSGTIME)) != NULL) {
1379					errno = 0;	/* already in msg */
1380					logerror(p);
1381				}
1382				break;
1383			}
1384		}
1385	}
1386	endutxent();
1387	reenter = 0;
1388}
1389
1390static void
1391reapchild(int signo __unused)
1392{
1393	int status;
1394	pid_t pid;
1395	struct filed *f;
1396
1397	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1398		if (!Initialized)
1399			/* Don't tell while we are initting. */
1400			continue;
1401
1402		/* First, look if it's a process from the dead queue. */
1403		if (deadq_remove(pid))
1404			goto oncemore;
1405
1406		/* Now, look in list of active processes. */
1407		for (f = Files; f; f = f->f_next)
1408			if (f->f_type == F_PIPE &&
1409			    f->f_un.f_pipe.f_pid == pid) {
1410				(void)close(f->f_file);
1411				f->f_un.f_pipe.f_pid = 0;
1412				log_deadchild(pid, status,
1413					      f->f_un.f_pipe.f_pname);
1414				break;
1415			}
1416	  oncemore:
1417		continue;
1418	}
1419}
1420
1421/*
1422 * Return a printable representation of a host address.
1423 */
1424static const char *
1425cvthname(struct sockaddr *f)
1426{
1427	int error, hl;
1428	sigset_t omask, nmask;
1429	static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1430
1431	error = getnameinfo((struct sockaddr *)f,
1432			    ((struct sockaddr *)f)->sa_len,
1433			    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1434	dprintf("cvthname(%s)\n", ip);
1435
1436	if (error) {
1437		dprintf("Malformed from address %s\n", gai_strerror(error));
1438		return ("???");
1439	}
1440	if (!resolve)
1441		return (ip);
1442
1443	sigemptyset(&nmask);
1444	sigaddset(&nmask, SIGHUP);
1445	sigprocmask(SIG_BLOCK, &nmask, &omask);
1446	error = getnameinfo((struct sockaddr *)f,
1447			    ((struct sockaddr *)f)->sa_len,
1448			    hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1449	sigprocmask(SIG_SETMASK, &omask, NULL);
1450	if (error) {
1451		dprintf("Host name for your address (%s) unknown\n", ip);
1452		return (ip);
1453	}
1454	hl = strlen(hname);
1455	if (hl > 0 && hname[hl-1] == '.')
1456		hname[--hl] = '\0';
1457	trimdomain(hname, hl);
1458	return (hname);
1459}
1460
1461static void
1462dodie(int signo)
1463{
1464
1465	WantDie = signo;
1466}
1467
1468static void
1469domark(int signo __unused)
1470{
1471
1472	MarkSet = 1;
1473}
1474
1475/*
1476 * Print syslogd errors some place.
1477 */
1478static void
1479logerror(const char *type)
1480{
1481	char buf[512];
1482	static int recursed = 0;
1483
1484	/* If there's an error while trying to log an error, give up. */
1485	if (recursed)
1486		return;
1487	recursed++;
1488	if (errno)
1489		(void)snprintf(buf,
1490		    sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1491	else
1492		(void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1493	errno = 0;
1494	dprintf("%s\n", buf);
1495	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1496	recursed--;
1497}
1498
1499static void
1500die(int signo)
1501{
1502	struct filed *f;
1503	struct funix *fx;
1504	int was_initialized;
1505	char buf[100];
1506
1507	was_initialized = Initialized;
1508	Initialized = 0;	/* Don't log SIGCHLDs. */
1509	for (f = Files; f != NULL; f = f->f_next) {
1510		/* flush any pending output */
1511		if (f->f_prevcount)
1512			fprintlog(f, 0, (char *)NULL);
1513		if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1514			(void)close(f->f_file);
1515			f->f_un.f_pipe.f_pid = 0;
1516		}
1517	}
1518	Initialized = was_initialized;
1519	if (signo) {
1520		dprintf("syslogd: exiting on signal %d\n", signo);
1521		(void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1522		errno = 0;
1523		logerror(buf);
1524	}
1525	STAILQ_FOREACH(fx, &funixes, next)
1526		(void)unlink(fx->name);
1527	pidfile_remove(pfh);
1528
1529	exit(1);
1530}
1531
1532/*
1533 *  INIT -- Initialize syslogd from configuration table
1534 */
1535static void
1536init(int signo)
1537{
1538	int i;
1539	FILE *cf;
1540	struct filed *f, *next, **nextp;
1541	char *p;
1542	char cline[LINE_MAX];
1543 	char prog[LINE_MAX];
1544	char host[MAXHOSTNAMELEN];
1545	char oldLocalHostName[MAXHOSTNAMELEN];
1546	char hostMsg[2*MAXHOSTNAMELEN+40];
1547	char bootfileMsg[LINE_MAX];
1548
1549	dprintf("init\n");
1550
1551	/*
1552	 * Load hostname (may have changed).
1553	 */
1554	if (signo != 0)
1555		(void)strlcpy(oldLocalHostName, LocalHostName,
1556		    sizeof(oldLocalHostName));
1557	if (gethostname(LocalHostName, sizeof(LocalHostName)))
1558		err(EX_OSERR, "gethostname() failed");
1559	if ((p = strchr(LocalHostName, '.')) != NULL) {
1560		*p++ = '\0';
1561		LocalDomain = p;
1562	} else {
1563		LocalDomain = "";
1564	}
1565
1566	/*
1567	 *  Close all open log files.
1568	 */
1569	Initialized = 0;
1570	for (f = Files; f != NULL; f = next) {
1571		/* flush any pending output */
1572		if (f->f_prevcount)
1573			fprintlog(f, 0, (char *)NULL);
1574
1575		switch (f->f_type) {
1576		case F_FILE:
1577		case F_FORW:
1578		case F_CONSOLE:
1579		case F_TTY:
1580			(void)close(f->f_file);
1581			break;
1582		case F_PIPE:
1583			if (f->f_un.f_pipe.f_pid > 0) {
1584				(void)close(f->f_file);
1585				deadq_enter(f->f_un.f_pipe.f_pid,
1586					    f->f_un.f_pipe.f_pname);
1587			}
1588			f->f_un.f_pipe.f_pid = 0;
1589			break;
1590		}
1591		next = f->f_next;
1592		if (f->f_program) free(f->f_program);
1593		if (f->f_host) free(f->f_host);
1594		free((char *)f);
1595	}
1596	Files = NULL;
1597	nextp = &Files;
1598
1599	/* open the configuration file */
1600	if ((cf = fopen(ConfFile, "r")) == NULL) {
1601		dprintf("cannot open %s\n", ConfFile);
1602		*nextp = (struct filed *)calloc(1, sizeof(*f));
1603		if (*nextp == NULL) {
1604			logerror("calloc");
1605			exit(1);
1606		}
1607		cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1608		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1609		if ((*nextp)->f_next == NULL) {
1610			logerror("calloc");
1611			exit(1);
1612		}
1613		cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1614		Initialized = 1;
1615		return;
1616	}
1617
1618	/*
1619	 *  Foreach line in the conf table, open that file.
1620	 */
1621	f = NULL;
1622	(void)strlcpy(host, "*", sizeof(host));
1623	(void)strlcpy(prog, "*", sizeof(prog));
1624	while (fgets(cline, sizeof(cline), cf) != NULL) {
1625		/*
1626		 * check for end-of-section, comments, strip off trailing
1627		 * spaces and newline character. #!prog is treated specially:
1628		 * following lines apply only to that program.
1629		 */
1630		for (p = cline; isspace(*p); ++p)
1631			continue;
1632		if (*p == 0)
1633			continue;
1634		if (*p == '#') {
1635			p++;
1636			if (*p != '!' && *p != '+' && *p != '-')
1637				continue;
1638		}
1639		if (*p == '+' || *p == '-') {
1640			host[0] = *p++;
1641			while (isspace(*p))
1642				p++;
1643			if ((!*p) || (*p == '*')) {
1644				(void)strlcpy(host, "*", sizeof(host));
1645				continue;
1646			}
1647			if (*p == '@')
1648				p = LocalHostName;
1649			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1650				if (!isalnum(*p) && *p != '.' && *p != '-'
1651				    && *p != ',' && *p != ':' && *p != '%')
1652					break;
1653				host[i] = *p++;
1654			}
1655			host[i] = '\0';
1656			continue;
1657		}
1658		if (*p == '!') {
1659			p++;
1660			while (isspace(*p)) p++;
1661			if ((!*p) || (*p == '*')) {
1662				(void)strlcpy(prog, "*", sizeof(prog));
1663				continue;
1664			}
1665			for (i = 0; i < LINE_MAX - 1; i++) {
1666				if (!isprint(p[i]) || isspace(p[i]))
1667					break;
1668				prog[i] = p[i];
1669			}
1670			prog[i] = 0;
1671			continue;
1672		}
1673		for (p = cline + 1; *p != '\0'; p++) {
1674			if (*p != '#')
1675				continue;
1676			if (*(p - 1) == '\\') {
1677				strcpy(p - 1, p);
1678				p--;
1679				continue;
1680			}
1681			*p = '\0';
1682			break;
1683		}
1684		for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1685			cline[i] = '\0';
1686		f = (struct filed *)calloc(1, sizeof(*f));
1687		if (f == NULL) {
1688			logerror("calloc");
1689			exit(1);
1690		}
1691		*nextp = f;
1692		nextp = &f->f_next;
1693		cfline(cline, f, prog, host);
1694	}
1695
1696	/* close the configuration file */
1697	(void)fclose(cf);
1698
1699	Initialized = 1;
1700
1701	if (Debug) {
1702		int port;
1703		for (f = Files; f; f = f->f_next) {
1704			for (i = 0; i <= LOG_NFACILITIES; i++)
1705				if (f->f_pmask[i] == INTERNAL_NOPRI)
1706					printf("X ");
1707				else
1708					printf("%d ", f->f_pmask[i]);
1709			printf("%s: ", TypeNames[f->f_type]);
1710			switch (f->f_type) {
1711			case F_FILE:
1712				printf("%s", f->f_un.f_fname);
1713				break;
1714
1715			case F_CONSOLE:
1716			case F_TTY:
1717				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1718				break;
1719
1720			case F_FORW:
1721				port = (int)ntohs(((struct sockaddr_in *)
1722				    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1723				if (port != 514) {
1724					printf("%s:%d",
1725						f->f_un.f_forw.f_hname, port);
1726				} else {
1727					printf("%s", f->f_un.f_forw.f_hname);
1728				}
1729				break;
1730
1731			case F_PIPE:
1732				printf("%s", f->f_un.f_pipe.f_pname);
1733				break;
1734
1735			case F_USERS:
1736				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1737					printf("%s, ", f->f_un.f_uname[i]);
1738				break;
1739			}
1740			if (f->f_program)
1741				printf(" (%s)", f->f_program);
1742			printf("\n");
1743		}
1744	}
1745
1746	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1747	dprintf("syslogd: restarted\n");
1748	/*
1749	 * Log a change in hostname, but only on a restart.
1750	 */
1751	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1752		(void)snprintf(hostMsg, sizeof(hostMsg),
1753		    "syslogd: hostname changed, \"%s\" to \"%s\"",
1754		    oldLocalHostName, LocalHostName);
1755		logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1756		dprintf("%s\n", hostMsg);
1757	}
1758	/*
1759	 * Log the kernel boot file if we aren't going to use it as
1760	 * the prefix, and if this is *not* a restart.
1761	 */
1762	if (signo == 0 && !use_bootfile) {
1763		(void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1764		    "syslogd: kernel boot file is %s", bootfile);
1765		logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1766		dprintf("%s\n", bootfileMsg);
1767	}
1768}
1769
1770/*
1771 * Crack a configuration file line
1772 */
1773static void
1774cfline(const char *line, struct filed *f, const char *prog, const char *host)
1775{
1776	struct addrinfo hints, *res;
1777	int error, i, pri, syncfile;
1778	const char *p, *q;
1779	char *bp;
1780	char buf[MAXLINE], ebuf[100];
1781
1782	dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1783
1784	errno = 0;	/* keep strerror() stuff out of logerror messages */
1785
1786	/* clear out file entry */
1787	memset(f, 0, sizeof(*f));
1788	for (i = 0; i <= LOG_NFACILITIES; i++)
1789		f->f_pmask[i] = INTERNAL_NOPRI;
1790
1791	/* save hostname if any */
1792	if (host && *host == '*')
1793		host = NULL;
1794	if (host) {
1795		int hl;
1796
1797		f->f_host = strdup(host);
1798		if (f->f_host == NULL) {
1799			logerror("strdup");
1800			exit(1);
1801		}
1802		hl = strlen(f->f_host);
1803		if (hl > 0 && f->f_host[hl-1] == '.')
1804			f->f_host[--hl] = '\0';
1805		trimdomain(f->f_host, hl);
1806	}
1807
1808	/* save program name if any */
1809	if (prog && *prog == '*')
1810		prog = NULL;
1811	if (prog) {
1812		f->f_program = strdup(prog);
1813		if (f->f_program == NULL) {
1814			logerror("strdup");
1815			exit(1);
1816		}
1817	}
1818
1819	/* scan through the list of selectors */
1820	for (p = line; *p && *p != '\t' && *p != ' ';) {
1821		int pri_done;
1822		int pri_cmp;
1823		int pri_invert;
1824
1825		/* find the end of this facility name list */
1826		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1827			continue;
1828
1829		/* get the priority comparison */
1830		pri_cmp = 0;
1831		pri_done = 0;
1832		pri_invert = 0;
1833		if (*q == '!') {
1834			pri_invert = 1;
1835			q++;
1836		}
1837		while (!pri_done) {
1838			switch (*q) {
1839			case '<':
1840				pri_cmp |= PRI_LT;
1841				q++;
1842				break;
1843			case '=':
1844				pri_cmp |= PRI_EQ;
1845				q++;
1846				break;
1847			case '>':
1848				pri_cmp |= PRI_GT;
1849				q++;
1850				break;
1851			default:
1852				pri_done++;
1853				break;
1854			}
1855		}
1856
1857		/* collect priority name */
1858		for (bp = buf; *q && !strchr("\t,; ", *q); )
1859			*bp++ = *q++;
1860		*bp = '\0';
1861
1862		/* skip cruft */
1863		while (strchr(",;", *q))
1864			q++;
1865
1866		/* decode priority name */
1867		if (*buf == '*') {
1868			pri = LOG_PRIMASK;
1869			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1870		} else {
1871			/* Ignore trailing spaces. */
1872			for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1873				buf[i] = '\0';
1874
1875			pri = decode(buf, prioritynames);
1876			if (pri < 0) {
1877				errno = 0;
1878				(void)snprintf(ebuf, sizeof ebuf,
1879				    "unknown priority name \"%s\"", buf);
1880				logerror(ebuf);
1881				return;
1882			}
1883		}
1884		if (!pri_cmp)
1885			pri_cmp = (UniquePriority)
1886				  ? (PRI_EQ)
1887				  : (PRI_EQ | PRI_GT)
1888				  ;
1889		if (pri_invert)
1890			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1891
1892		/* scan facilities */
1893		while (*p && !strchr("\t.; ", *p)) {
1894			for (bp = buf; *p && !strchr("\t,;. ", *p); )
1895				*bp++ = *p++;
1896			*bp = '\0';
1897
1898			if (*buf == '*') {
1899				for (i = 0; i < LOG_NFACILITIES; i++) {
1900					f->f_pmask[i] = pri;
1901					f->f_pcmp[i] = pri_cmp;
1902				}
1903			} else {
1904				i = decode(buf, facilitynames);
1905				if (i < 0) {
1906					errno = 0;
1907					(void)snprintf(ebuf, sizeof ebuf,
1908					    "unknown facility name \"%s\"",
1909					    buf);
1910					logerror(ebuf);
1911					return;
1912				}
1913				f->f_pmask[i >> 3] = pri;
1914				f->f_pcmp[i >> 3] = pri_cmp;
1915			}
1916			while (*p == ',' || *p == ' ')
1917				p++;
1918		}
1919
1920		p = q;
1921	}
1922
1923	/* skip to action part */
1924	while (*p == '\t' || *p == ' ')
1925		p++;
1926
1927	if (*p == '-') {
1928		syncfile = 0;
1929		p++;
1930	} else
1931		syncfile = 1;
1932
1933	switch (*p) {
1934	case '@':
1935		{
1936			char *tp;
1937			char endkey = ':';
1938			/*
1939			 * scan forward to see if there is a port defined.
1940			 * so we can't use strlcpy..
1941			 */
1942			i = sizeof(f->f_un.f_forw.f_hname);
1943			tp = f->f_un.f_forw.f_hname;
1944			p++;
1945
1946			/*
1947			 * an ipv6 address should start with a '[' in that case
1948			 * we should scan for a ']'
1949			 */
1950			if (*p == '[') {
1951				p++;
1952				endkey = ']';
1953			}
1954			while (*p && (*p != endkey) && (i-- > 0)) {
1955				*tp++ = *p++;
1956			}
1957			if (endkey == ']' && *p == endkey)
1958				p++;
1959			*tp = '\0';
1960		}
1961		/* See if we copied a domain and have a port */
1962		if (*p == ':')
1963			p++;
1964		else
1965			p = NULL;
1966
1967		memset(&hints, 0, sizeof(hints));
1968		hints.ai_family = family;
1969		hints.ai_socktype = SOCK_DGRAM;
1970		error = getaddrinfo(f->f_un.f_forw.f_hname,
1971				p ? p : "syslog", &hints, &res);
1972		if (error) {
1973			logerror(gai_strerror(error));
1974			break;
1975		}
1976		f->f_un.f_forw.f_addr = res;
1977		f->f_type = F_FORW;
1978		break;
1979
1980	case '/':
1981		if ((f->f_file = open(p, logflags, 0600)) < 0) {
1982			f->f_type = F_UNUSED;
1983			logerror(p);
1984			break;
1985		}
1986		if (syncfile)
1987			f->f_flags |= FFLAG_SYNC;
1988		if (isatty(f->f_file)) {
1989			if (strcmp(p, ctty) == 0)
1990				f->f_type = F_CONSOLE;
1991			else
1992				f->f_type = F_TTY;
1993			(void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1994			    sizeof(f->f_un.f_fname));
1995		} else {
1996			(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1997			f->f_type = F_FILE;
1998		}
1999		break;
2000
2001	case '|':
2002		f->f_un.f_pipe.f_pid = 0;
2003		(void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2004		    sizeof(f->f_un.f_pipe.f_pname));
2005		f->f_type = F_PIPE;
2006		break;
2007
2008	case '*':
2009		f->f_type = F_WALL;
2010		break;
2011
2012	default:
2013		for (i = 0; i < MAXUNAMES && *p; i++) {
2014			for (q = p; *q && *q != ','; )
2015				q++;
2016			(void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2017			if ((q - p) >= MAXLOGNAME)
2018				f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2019			else
2020				f->f_un.f_uname[i][q - p] = '\0';
2021			while (*q == ',' || *q == ' ')
2022				q++;
2023			p = q;
2024		}
2025		f->f_type = F_USERS;
2026		break;
2027	}
2028}
2029
2030
2031/*
2032 *  Decode a symbolic name to a numeric value
2033 */
2034static int
2035decode(const char *name, const CODE *codetab)
2036{
2037	const CODE *c;
2038	char *p, buf[40];
2039
2040	if (isdigit(*name))
2041		return (atoi(name));
2042
2043	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2044		if (isupper(*name))
2045			*p = tolower(*name);
2046		else
2047			*p = *name;
2048	}
2049	*p = '\0';
2050	for (c = codetab; c->c_name; c++)
2051		if (!strcmp(buf, c->c_name))
2052			return (c->c_val);
2053
2054	return (-1);
2055}
2056
2057static void
2058markit(void)
2059{
2060	struct filed *f;
2061	dq_t q, next;
2062
2063	now = time((time_t *)NULL);
2064	MarkSeq += TIMERINTVL;
2065	if (MarkSeq >= MarkInterval) {
2066		logmsg(LOG_INFO, "-- MARK --",
2067		    LocalHostName, ADDDATE|MARK);
2068		MarkSeq = 0;
2069	}
2070
2071	for (f = Files; f; f = f->f_next) {
2072		if (f->f_prevcount && now >= REPEATTIME(f)) {
2073			dprintf("flush %s: repeated %d times, %d sec.\n",
2074			    TypeNames[f->f_type], f->f_prevcount,
2075			    repeatinterval[f->f_repeatcount]);
2076			fprintlog(f, 0, (char *)NULL);
2077			BACKOFF(f);
2078		}
2079	}
2080
2081	/* Walk the dead queue, and see if we should signal somebody. */
2082	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2083		next = TAILQ_NEXT(q, dq_entries);
2084
2085		switch (q->dq_timeout) {
2086		case 0:
2087			/* Already signalled once, try harder now. */
2088			if (kill(q->dq_pid, SIGKILL) != 0)
2089				(void)deadq_remove(q->dq_pid);
2090			break;
2091
2092		case 1:
2093			/*
2094			 * Timed out on dead queue, send terminate
2095			 * signal.  Note that we leave the removal
2096			 * from the dead queue to reapchild(), which
2097			 * will also log the event (unless the process
2098			 * didn't even really exist, in case we simply
2099			 * drop it from the dead queue).
2100			 */
2101			if (kill(q->dq_pid, SIGTERM) != 0)
2102				(void)deadq_remove(q->dq_pid);
2103			/* FALLTHROUGH */
2104
2105		default:
2106			q->dq_timeout--;
2107		}
2108	}
2109	MarkSet = 0;
2110	(void)alarm(TIMERINTVL);
2111}
2112
2113/*
2114 * fork off and become a daemon, but wait for the child to come online
2115 * before returing to the parent, or we get disk thrashing at boot etc.
2116 * Set a timer so we don't hang forever if it wedges.
2117 */
2118static int
2119waitdaemon(int nochdir, int noclose, int maxwait)
2120{
2121	int fd;
2122	int status;
2123	pid_t pid, childpid;
2124
2125	switch (childpid = fork()) {
2126	case -1:
2127		return (-1);
2128	case 0:
2129		break;
2130	default:
2131		signal(SIGALRM, timedout);
2132		alarm(maxwait);
2133		while ((pid = wait3(&status, 0, NULL)) != -1) {
2134			if (WIFEXITED(status))
2135				errx(1, "child pid %d exited with return code %d",
2136					pid, WEXITSTATUS(status));
2137			if (WIFSIGNALED(status))
2138				errx(1, "child pid %d exited on signal %d%s",
2139					pid, WTERMSIG(status),
2140					WCOREDUMP(status) ? " (core dumped)" :
2141					"");
2142			if (pid == childpid)	/* it's gone... */
2143				break;
2144		}
2145		exit(0);
2146	}
2147
2148	if (setsid() == -1)
2149		return (-1);
2150
2151	if (!nochdir)
2152		(void)chdir("/");
2153
2154	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2155		(void)dup2(fd, STDIN_FILENO);
2156		(void)dup2(fd, STDOUT_FILENO);
2157		(void)dup2(fd, STDERR_FILENO);
2158		if (fd > 2)
2159			(void)close (fd);
2160	}
2161	return (getppid());
2162}
2163
2164/*
2165 * We get a SIGALRM from the child when it's running and finished doing it's
2166 * fsync()'s or O_SYNC writes for all the boot messages.
2167 *
2168 * We also get a signal from the kernel if the timer expires, so check to
2169 * see what happened.
2170 */
2171static void
2172timedout(int sig __unused)
2173{
2174	int left;
2175	left = alarm(0);
2176	signal(SIGALRM, SIG_DFL);
2177	if (left == 0)
2178		errx(1, "timed out waiting for child");
2179	else
2180		_exit(0);
2181}
2182
2183/*
2184 * Add `s' to the list of allowable peer addresses to accept messages
2185 * from.
2186 *
2187 * `s' is a string in the form:
2188 *
2189 *    [*]domainname[:{servicename|portnumber|*}]
2190 *
2191 * or
2192 *
2193 *    netaddr/maskbits[:{servicename|portnumber|*}]
2194 *
2195 * Returns -1 on error, 0 if the argument was valid.
2196 */
2197static int
2198allowaddr(char *s)
2199{
2200	char *cp1, *cp2;
2201	struct allowedpeer ap;
2202	struct servent *se;
2203	int masklen = -1;
2204	struct addrinfo hints, *res;
2205	struct in_addr *addrp, *maskp;
2206#ifdef INET6
2207	int i;
2208	u_int32_t *addr6p, *mask6p;
2209#endif
2210	char ip[NI_MAXHOST];
2211
2212#ifdef INET6
2213	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2214#endif
2215		cp1 = s;
2216	if ((cp1 = strrchr(cp1, ':'))) {
2217		/* service/port provided */
2218		*cp1++ = '\0';
2219		if (strlen(cp1) == 1 && *cp1 == '*')
2220			/* any port allowed */
2221			ap.port = 0;
2222		else if ((se = getservbyname(cp1, "udp"))) {
2223			ap.port = ntohs(se->s_port);
2224		} else {
2225			ap.port = strtol(cp1, &cp2, 0);
2226			if (*cp2 != '\0')
2227				return (-1); /* port not numeric */
2228		}
2229	} else {
2230		if ((se = getservbyname("syslog", "udp")))
2231			ap.port = ntohs(se->s_port);
2232		else
2233			/* sanity, should not happen */
2234			ap.port = 514;
2235	}
2236
2237	if ((cp1 = strchr(s, '/')) != NULL &&
2238	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2239		*cp1 = '\0';
2240		if ((masklen = atoi(cp1 + 1)) < 0)
2241			return (-1);
2242	}
2243#ifdef INET6
2244	if (*s == '[') {
2245		cp2 = s + strlen(s) - 1;
2246		if (*cp2 == ']') {
2247			++s;
2248			*cp2 = '\0';
2249		} else {
2250			cp2 = NULL;
2251		}
2252	} else {
2253		cp2 = NULL;
2254	}
2255#endif
2256	memset(&hints, 0, sizeof(hints));
2257	hints.ai_family = PF_UNSPEC;
2258	hints.ai_socktype = SOCK_DGRAM;
2259	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2260	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2261		ap.isnumeric = 1;
2262		memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2263		memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2264		ap.a_mask.ss_family = res->ai_family;
2265		if (res->ai_family == AF_INET) {
2266			ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2267			maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2268			addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2269			if (masklen < 0) {
2270				/* use default netmask */
2271				if (IN_CLASSA(ntohl(addrp->s_addr)))
2272					maskp->s_addr = htonl(IN_CLASSA_NET);
2273				else if (IN_CLASSB(ntohl(addrp->s_addr)))
2274					maskp->s_addr = htonl(IN_CLASSB_NET);
2275				else
2276					maskp->s_addr = htonl(IN_CLASSC_NET);
2277			} else if (masklen <= 32) {
2278				/* convert masklen to netmask */
2279				if (masklen == 0)
2280					maskp->s_addr = 0;
2281				else
2282					maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2283			} else {
2284				freeaddrinfo(res);
2285				return (-1);
2286			}
2287			/* Lose any host bits in the network number. */
2288			addrp->s_addr &= maskp->s_addr;
2289		}
2290#ifdef INET6
2291		else if (res->ai_family == AF_INET6 && masklen <= 128) {
2292			ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2293			if (masklen < 0)
2294				masklen = 128;
2295			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2296			/* convert masklen to netmask */
2297			while (masklen > 0) {
2298				if (masklen < 32) {
2299					*mask6p = htonl(~(0xffffffff >> masklen));
2300					break;
2301				}
2302				*mask6p++ = 0xffffffff;
2303				masklen -= 32;
2304			}
2305			/* Lose any host bits in the network number. */
2306			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2307			addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2308			for (i = 0; i < 4; i++)
2309				addr6p[i] &= mask6p[i];
2310		}
2311#endif
2312		else {
2313			freeaddrinfo(res);
2314			return (-1);
2315		}
2316		freeaddrinfo(res);
2317	} else {
2318		/* arg `s' is domain name */
2319		ap.isnumeric = 0;
2320		ap.a_name = s;
2321		if (cp1)
2322			*cp1 = '/';
2323#ifdef INET6
2324		if (cp2) {
2325			*cp2 = ']';
2326			--s;
2327		}
2328#endif
2329	}
2330
2331	if (Debug) {
2332		printf("allowaddr: rule %d: ", NumAllowed);
2333		if (ap.isnumeric) {
2334			printf("numeric, ");
2335			getnameinfo((struct sockaddr *)&ap.a_addr,
2336				    ((struct sockaddr *)&ap.a_addr)->sa_len,
2337				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2338			printf("addr = %s, ", ip);
2339			getnameinfo((struct sockaddr *)&ap.a_mask,
2340				    ((struct sockaddr *)&ap.a_mask)->sa_len,
2341				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2342			printf("mask = %s; ", ip);
2343		} else {
2344			printf("domainname = %s; ", ap.a_name);
2345		}
2346		printf("port = %d\n", ap.port);
2347	}
2348
2349	if ((AllowedPeers = realloc(AllowedPeers,
2350				    ++NumAllowed * sizeof(struct allowedpeer)))
2351	    == NULL) {
2352		logerror("realloc");
2353		exit(1);
2354	}
2355	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2356	return (0);
2357}
2358
2359/*
2360 * Validate that the remote peer has permission to log to us.
2361 */
2362static int
2363validate(struct sockaddr *sa, const char *hname)
2364{
2365	int i;
2366	size_t l1, l2;
2367	char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2368	struct allowedpeer *ap;
2369	struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2370#ifdef INET6
2371	int j, reject;
2372	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2373#endif
2374	struct addrinfo hints, *res;
2375	u_short sport;
2376
2377	if (NumAllowed == 0)
2378		/* traditional behaviour, allow everything */
2379		return (1);
2380
2381	(void)strlcpy(name, hname, sizeof(name));
2382	memset(&hints, 0, sizeof(hints));
2383	hints.ai_family = PF_UNSPEC;
2384	hints.ai_socktype = SOCK_DGRAM;
2385	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2386	if (getaddrinfo(name, NULL, &hints, &res) == 0)
2387		freeaddrinfo(res);
2388	else if (strchr(name, '.') == NULL) {
2389		strlcat(name, ".", sizeof name);
2390		strlcat(name, LocalDomain, sizeof name);
2391	}
2392	if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2393			NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2394		return (0);	/* for safety, should not occur */
2395	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2396		ip, port, name);
2397	sport = atoi(port);
2398
2399	/* now, walk down the list */
2400	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2401		if (ap->port != 0 && ap->port != sport) {
2402			dprintf("rejected in rule %d due to port mismatch.\n", i);
2403			continue;
2404		}
2405
2406		if (ap->isnumeric) {
2407			if (ap->a_addr.ss_family != sa->sa_family) {
2408				dprintf("rejected in rule %d due to address family mismatch.\n", i);
2409				continue;
2410			}
2411			if (ap->a_addr.ss_family == AF_INET) {
2412				sin4 = (struct sockaddr_in *)sa;
2413				a4p = (struct sockaddr_in *)&ap->a_addr;
2414				m4p = (struct sockaddr_in *)&ap->a_mask;
2415				if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2416				    != a4p->sin_addr.s_addr) {
2417					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2418					continue;
2419				}
2420			}
2421#ifdef INET6
2422			else if (ap->a_addr.ss_family == AF_INET6) {
2423				sin6 = (struct sockaddr_in6 *)sa;
2424				a6p = (struct sockaddr_in6 *)&ap->a_addr;
2425				m6p = (struct sockaddr_in6 *)&ap->a_mask;
2426				if (a6p->sin6_scope_id != 0 &&
2427				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
2428					dprintf("rejected in rule %d due to scope mismatch.\n", i);
2429					continue;
2430				}
2431				reject = 0;
2432				for (j = 0; j < 16; j += 4) {
2433					if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2434					    != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2435						++reject;
2436						break;
2437					}
2438				}
2439				if (reject) {
2440					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2441					continue;
2442				}
2443			}
2444#endif
2445			else
2446				continue;
2447		} else {
2448			cp = ap->a_name;
2449			l1 = strlen(name);
2450			if (*cp == '*') {
2451				/* allow wildmatch */
2452				cp++;
2453				l2 = strlen(cp);
2454				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2455					dprintf("rejected in rule %d due to name mismatch.\n", i);
2456					continue;
2457				}
2458			} else {
2459				/* exact match */
2460				l2 = strlen(cp);
2461				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2462					dprintf("rejected in rule %d due to name mismatch.\n", i);
2463					continue;
2464				}
2465			}
2466		}
2467		dprintf("accepted in rule %d.\n", i);
2468		return (1);	/* hooray! */
2469	}
2470	return (0);
2471}
2472
2473/*
2474 * Fairly similar to popen(3), but returns an open descriptor, as
2475 * opposed to a FILE *.
2476 */
2477static int
2478p_open(const char *prog, pid_t *rpid)
2479{
2480	int pfd[2], nulldesc;
2481	pid_t pid;
2482	sigset_t omask, mask;
2483	char *argv[4]; /* sh -c cmd NULL */
2484	char errmsg[200];
2485
2486	if (pipe(pfd) == -1)
2487		return (-1);
2488	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2489		/* we are royally screwed anyway */
2490		return (-1);
2491
2492	sigemptyset(&mask);
2493	sigaddset(&mask, SIGALRM);
2494	sigaddset(&mask, SIGHUP);
2495	sigprocmask(SIG_BLOCK, &mask, &omask);
2496	switch ((pid = fork())) {
2497	case -1:
2498		sigprocmask(SIG_SETMASK, &omask, 0);
2499		close(nulldesc);
2500		return (-1);
2501
2502	case 0:
2503		argv[0] = strdup("sh");
2504		argv[1] = strdup("-c");
2505		argv[2] = strdup(prog);
2506		argv[3] = NULL;
2507		if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2508			logerror("strdup");
2509			exit(1);
2510		}
2511
2512		alarm(0);
2513		(void)setsid();	/* Avoid catching SIGHUPs. */
2514
2515		/*
2516		 * Throw away pending signals, and reset signal
2517		 * behaviour to standard values.
2518		 */
2519		signal(SIGALRM, SIG_IGN);
2520		signal(SIGHUP, SIG_IGN);
2521		sigprocmask(SIG_SETMASK, &omask, 0);
2522		signal(SIGPIPE, SIG_DFL);
2523		signal(SIGQUIT, SIG_DFL);
2524		signal(SIGALRM, SIG_DFL);
2525		signal(SIGHUP, SIG_DFL);
2526
2527		dup2(pfd[0], STDIN_FILENO);
2528		dup2(nulldesc, STDOUT_FILENO);
2529		dup2(nulldesc, STDERR_FILENO);
2530		closefrom(3);
2531
2532		(void)execvp(_PATH_BSHELL, argv);
2533		_exit(255);
2534	}
2535
2536	sigprocmask(SIG_SETMASK, &omask, 0);
2537	close(nulldesc);
2538	close(pfd[0]);
2539	/*
2540	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
2541	 * supposed to get an EWOULDBLOCK on writev(2), which is
2542	 * caught by the logic above anyway, which will in turn close
2543	 * the pipe, and fork a new logging subprocess if necessary.
2544	 * The stale subprocess will be killed some time later unless
2545	 * it terminated itself due to closing its input pipe (so we
2546	 * get rid of really dead puppies).
2547	 */
2548	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2549		/* This is bad. */
2550		(void)snprintf(errmsg, sizeof errmsg,
2551			       "Warning: cannot change pipe to PID %d to "
2552			       "non-blocking behaviour.",
2553			       (int)pid);
2554		logerror(errmsg);
2555	}
2556	*rpid = pid;
2557	return (pfd[1]);
2558}
2559
2560static void
2561deadq_enter(pid_t pid, const char *name)
2562{
2563	dq_t p;
2564	int status;
2565
2566	/*
2567	 * Be paranoid, if we can't signal the process, don't enter it
2568	 * into the dead queue (perhaps it's already dead).  If possible,
2569	 * we try to fetch and log the child's status.
2570	 */
2571	if (kill(pid, 0) != 0) {
2572		if (waitpid(pid, &status, WNOHANG) > 0)
2573			log_deadchild(pid, status, name);
2574		return;
2575	}
2576
2577	p = malloc(sizeof(struct deadq_entry));
2578	if (p == NULL) {
2579		logerror("malloc");
2580		exit(1);
2581	}
2582
2583	p->dq_pid = pid;
2584	p->dq_timeout = DQ_TIMO_INIT;
2585	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2586}
2587
2588static int
2589deadq_remove(pid_t pid)
2590{
2591	dq_t q;
2592
2593	TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2594		if (q->dq_pid == pid) {
2595			TAILQ_REMOVE(&deadq_head, q, dq_entries);
2596				free(q);
2597				return (1);
2598		}
2599	}
2600
2601	return (0);
2602}
2603
2604static void
2605log_deadchild(pid_t pid, int status, const char *name)
2606{
2607	int code;
2608	char buf[256];
2609	const char *reason;
2610
2611	errno = 0; /* Keep strerror() stuff out of logerror messages. */
2612	if (WIFSIGNALED(status)) {
2613		reason = "due to signal";
2614		code = WTERMSIG(status);
2615	} else {
2616		reason = "with status";
2617		code = WEXITSTATUS(status);
2618		if (code == 0)
2619			return;
2620	}
2621	(void)snprintf(buf, sizeof buf,
2622		       "Logging subprocess %d (%s) exited %s %d.",
2623		       pid, name, reason, code);
2624	logerror(buf);
2625}
2626
2627static int *
2628socksetup(int af, char *bindhostname)
2629{
2630	struct addrinfo hints, *res, *r;
2631	const char *bindservice;
2632	char *cp;
2633	int error, maxs, *s, *socks;
2634
2635	/*
2636	 * We have to handle this case for backwards compatibility:
2637	 * If there are two (or more) colons but no '[' and ']',
2638	 * assume this is an inet6 address without a service.
2639	 */
2640	bindservice = "syslog";
2641	if (bindhostname != NULL) {
2642#ifdef INET6
2643		if (*bindhostname == '[' &&
2644		    (cp = strchr(bindhostname + 1, ']')) != NULL) {
2645			++bindhostname;
2646			*cp = '\0';
2647			if (cp[1] == ':' && cp[2] != '\0')
2648				bindservice = cp + 2;
2649		} else {
2650#endif
2651			cp = strchr(bindhostname, ':');
2652			if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2653				*cp = '\0';
2654				if (cp[1] != '\0')
2655					bindservice = cp + 1;
2656				if (cp == bindhostname)
2657					bindhostname = NULL;
2658			}
2659#ifdef INET6
2660		}
2661#endif
2662	}
2663
2664	memset(&hints, 0, sizeof(hints));
2665	hints.ai_flags = AI_PASSIVE;
2666	hints.ai_family = af;
2667	hints.ai_socktype = SOCK_DGRAM;
2668	error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2669	if (error) {
2670		logerror(gai_strerror(error));
2671		errno = 0;
2672		die(0);
2673	}
2674
2675	/* Count max number of sockets we may open */
2676	for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2677	socks = malloc((maxs+1) * sizeof(int));
2678	if (socks == NULL) {
2679		logerror("couldn't allocate memory for sockets");
2680		die(0);
2681	}
2682
2683	*socks = 0;   /* num of sockets counter at start of array */
2684	s = socks + 1;
2685	for (r = res; r; r = r->ai_next) {
2686		int on = 1;
2687		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2688		if (*s < 0) {
2689			logerror("socket");
2690			continue;
2691		}
2692#ifdef INET6
2693		if (r->ai_family == AF_INET6) {
2694			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2695				       (char *)&on, sizeof (on)) < 0) {
2696				logerror("setsockopt");
2697				close(*s);
2698				continue;
2699			}
2700		}
2701#endif
2702		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2703			       (char *)&on, sizeof (on)) < 0) {
2704			logerror("setsockopt");
2705			close(*s);
2706			continue;
2707		}
2708		/*
2709		 * RFC 3164 recommends that client side message
2710		 * should come from the privileged syslogd port.
2711		 *
2712		 * If the system administrator choose not to obey
2713		 * this, we can skip the bind() step so that the
2714		 * system will choose a port for us.
2715		 */
2716		if (!NoBind) {
2717			if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2718				logerror("bind");
2719				close(*s);
2720				continue;
2721			}
2722
2723			if (!SecureMode)
2724				increase_rcvbuf(*s);
2725		}
2726
2727		(*socks)++;
2728		s++;
2729	}
2730
2731	if (*socks == 0) {
2732		free(socks);
2733		if (Debug)
2734			return (NULL);
2735		else
2736			die(0);
2737	}
2738	if (res)
2739		freeaddrinfo(res);
2740
2741	return (socks);
2742}
2743
2744static void
2745increase_rcvbuf(int fd)
2746{
2747	socklen_t len, slen;
2748
2749	slen = sizeof(len);
2750
2751	if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2752		if (len < RCVBUF_MINSIZE) {
2753			len = RCVBUF_MINSIZE;
2754			setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));
2755		}
2756	}
2757}
2758