syslogd.c revision 321234
12255Ssos/*
22255Ssos * Copyright (c) 1983, 1988, 1993, 1994
32255Ssos *	The Regents of the University of California.  All rights reserved.
42255Ssos *
52255Ssos * Redistribution and use in source and binary forms, with or without
62255Ssos * modification, are permitted provided that the following conditions
72255Ssos * are met:
82255Ssos * 1. Redistributions of source code must retain the above copyright
92255Ssos *    notice, this list of conditions and the following disclaimer.
102255Ssos * 2. Redistributions in binary form must reproduce the above copyright
112255Ssos *    notice, this list of conditions and the following disclaimer in the
122255Ssos *    documentation and/or other materials provided with the distribution.
132255Ssos * 4. Neither the name of the University nor the names of its contributors
142255Ssos *    may be used to endorse or promote products derived from this software
152255Ssos *    without specific prior written permission.
162255Ssos *
172255Ssos * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
182255Ssos * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
192255Ssos * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
202255Ssos * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
212255Ssos * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
222255Ssos * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
232255Ssos * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
242255Ssos * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
252255Ssos * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
262255Ssos * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
272255Ssos * SUCH DAMAGE.
282255Ssos */
292255Ssos
302255Ssos#ifndef lint
312255Ssosstatic const char copyright[] =
322255Ssos"@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
3314331Speter	The Regents of the University of California.  All rights reserved.\n";
342255Ssos#endif /* not lint */
352255Ssos
362255Ssos#ifndef lint
372255Ssos#if 0
382255Ssosstatic char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
3912453Sbde#endif
4010905Sbde#endif /* not lint */
412255Ssos
422255Ssos#include <sys/cdefs.h>
4310905Sbde__FBSDID("$FreeBSD: stable/10/usr.sbin/syslogd/syslogd.c 321234 2017-07-19 19:30:13Z ngie $");
442255Ssos
452255Ssos/*
4610905Sbde *  syslogd -- log system messages
4714331Speter *
4810905Sbde * This program implements a system log. It takes a series of lines.
492255Ssos * Each line may have a priority, signified as "<n>" as
502255Ssos * the first characters of the line.  If this is
512255Ssos * not present, a default priority is used.
522255Ssos *
533472Ssos * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
543472Ssos * cause it to reread its configuration file.
553472Ssos *
563472Ssos * Defined Constants:
5710905Sbde *
5810905Sbde * MAXLINE -- the maximum line length that can be handled.
5914331Speter * DEFUPRI -- the default priority for user messages
6014331Speter * DEFSPRI -- the default priority for kernel messages
6114331Speter *
6214331Speter * Author: Eric Allman
6314331Speter * extensive changes by Ralph Campbell
6414331Speter * more extensive changes by Eric Allman (again)
652255Ssos * Extension to log by program name as well as facility and priority
662255Ssos *   by Peter da Silva.
672255Ssos * -u and -v by Harlan Stenn.
687090Sbde * Priority comparison code by Harlan Stenn.
692255Ssos */
702255Ssos
712255Ssos/* Maximum number of characters in time of last occurrence */
722255Ssos#define	MAXDATELEN	16
732255Ssos#define	MAXLINE		1024		/* maximum line length */
742255Ssos#define	MAXSVLINE	MAXLINE		/* maximum saved line length */
75#define	DEFUPRI		(LOG_USER|LOG_NOTICE)
76#define	DEFSPRI		(LOG_KERN|LOG_CRIT)
77#define	TIMERINTVL	30		/* interval for checking flush, mark */
78#define	TTYMSGTIME	1		/* timeout passed to ttymsg */
79#define	RCVBUF_MINSIZE	(80 * 1024)	/* minimum size of dgram rcv buffer */
80
81#include <sys/param.h>
82#include <sys/ioctl.h>
83#include <sys/mman.h>
84#include <sys/queue.h>
85#include <sys/resource.h>
86#include <sys/socket.h>
87#include <sys/stat.h>
88#include <sys/syslimits.h>
89#include <sys/time.h>
90#include <sys/uio.h>
91#include <sys/un.h>
92#include <sys/wait.h>
93#include <sys/types.h>
94
95#include <netinet/in.h>
96#include <netdb.h>
97#include <arpa/inet.h>
98
99#include <ctype.h>
100#include <dirent.h>
101#include <err.h>
102#include <errno.h>
103#include <fcntl.h>
104#include <libutil.h>
105#include <limits.h>
106#include <paths.h>
107#include <signal.h>
108#include <stdio.h>
109#include <stdlib.h>
110#include <string.h>
111#include <sysexits.h>
112#include <unistd.h>
113#include <utmpx.h>
114
115#include "pathnames.h"
116#include "ttymsg.h"
117
118#define SYSLOG_NAMES
119#include <sys/syslog.h>
120
121const char	*ConfFile = _PATH_LOGCONF;
122const char	*PidFile = _PATH_LOGPID;
123const char	ctty[] = _PATH_CONSOLE;
124static const char	include_str[] = "include";
125static const char	include_ext[] = ".conf";
126
127#define	dprintf		if (Debug) printf
128
129#define	MAXUNAMES	20	/* maximum number of user names */
130
131/*
132 * Unix sockets.
133 * We have two default sockets, one with 666 permissions,
134 * and one for privileged programs.
135 */
136struct funix {
137	int			s;
138	const char		*name;
139	mode_t			mode;
140	STAILQ_ENTRY(funix)	next;
141};
142struct funix funix_secure =	{ -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
143				{ NULL } };
144struct funix funix_default =	{ -1, _PATH_LOG, DEFFILEMODE,
145				{ &funix_secure } };
146
147STAILQ_HEAD(, funix) funixes =	{ &funix_default,
148				&(funix_secure.next.stqe_next) };
149
150/*
151 * Flags to logmsg().
152 */
153
154#define	IGN_CONS	0x001	/* don't print on console */
155#define	SYNC_FILE	0x002	/* do fsync on file after printing */
156#define	ADDDATE		0x004	/* add a date to the message */
157#define	MARK		0x008	/* this message is a mark */
158#define	ISKERNEL	0x010	/* kernel generated message */
159
160/*
161 * This structure represents the files that will have log
162 * copies printed.
163 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
164 * or if f_type if F_PIPE and f_pid > 0.
165 */
166
167struct filed {
168	struct	filed *f_next;		/* next in linked list */
169	short	f_type;			/* entry type, see below */
170	short	f_file;			/* file descriptor */
171	time_t	f_time;			/* time this was last written */
172	char	*f_host;		/* host from which to recd. */
173	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
174	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
175#define PRI_LT	0x1
176#define PRI_EQ	0x2
177#define PRI_GT	0x4
178	char	*f_program;		/* program this applies to */
179	union {
180		char	f_uname[MAXUNAMES][MAXLOGNAME];
181		struct {
182			char	f_hname[MAXHOSTNAMELEN];
183			struct addrinfo *f_addr;
184
185		} f_forw;		/* forwarding address */
186		char	f_fname[MAXPATHLEN];
187		struct {
188			char	f_pname[MAXPATHLEN];
189			pid_t	f_pid;
190		} f_pipe;
191	} f_un;
192	char	f_prevline[MAXSVLINE];		/* last message logged */
193	char	f_lasttime[MAXDATELEN];		/* time of last occurrence */
194	char	f_prevhost[MAXHOSTNAMELEN];	/* host from which recd. */
195	int	f_prevpri;			/* pri of f_prevline */
196	int	f_prevlen;			/* length of f_prevline */
197	int	f_prevcount;			/* repetition cnt of prevline */
198	u_int	f_repeatcount;			/* number of "repeated" msgs */
199	int	f_flags;			/* file-specific flags */
200#define	FFLAG_SYNC 0x01
201#define	FFLAG_NEEDSYNC	0x02
202};
203
204/*
205 * Queue of about-to-be dead processes we should watch out for.
206 */
207
208TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
209struct stailhead *deadq_headp;
210
211struct deadq_entry {
212	pid_t				dq_pid;
213	int				dq_timeout;
214	TAILQ_ENTRY(deadq_entry)	dq_entries;
215};
216
217/*
218 * The timeout to apply to processes waiting on the dead queue.  Unit
219 * of measure is `mark intervals', i.e. 20 minutes by default.
220 * Processes on the dead queue will be terminated after that time.
221 */
222
223#define	 DQ_TIMO_INIT	2
224
225typedef struct deadq_entry *dq_t;
226
227
228/*
229 * Struct to hold records of network addresses that are allowed to log
230 * to us.
231 */
232struct allowedpeer {
233	int isnumeric;
234	u_short port;
235	union {
236		struct {
237			struct sockaddr_storage addr;
238			struct sockaddr_storage mask;
239		} numeric;
240		char *name;
241	} u;
242#define a_addr u.numeric.addr
243#define a_mask u.numeric.mask
244#define a_name u.name
245};
246
247
248/*
249 * Intervals at which we flush out "message repeated" messages,
250 * in seconds after previous message is logged.  After each flush,
251 * we move to the next interval until we reach the largest.
252 */
253int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
254#define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
255#define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
256#define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
257				 (f)->f_repeatcount = MAXREPEAT; \
258			}
259
260/* values for f_type */
261#define F_UNUSED	0		/* unused entry */
262#define F_FILE		1		/* regular file */
263#define F_TTY		2		/* terminal */
264#define F_CONSOLE	3		/* console terminal */
265#define F_FORW		4		/* remote machine */
266#define F_USERS		5		/* list of users */
267#define F_WALL		6		/* everyone logged on */
268#define F_PIPE		7		/* pipe to program */
269
270const char *TypeNames[8] = {
271	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
272	"FORW",		"USERS",	"WALL",		"PIPE"
273};
274
275static struct filed *Files;	/* Log files that we write to */
276static struct filed consfile;	/* Console */
277
278static int	Debug;		/* debug flag */
279static int	Foreground = 0;	/* Run in foreground, instead of daemonizing */
280static int	resolve = 1;	/* resolve hostname */
281static char	LocalHostName[MAXHOSTNAMELEN];	/* our hostname */
282static const char *LocalDomain;	/* our local domain name */
283static int	*finet;		/* Internet datagram socket */
284static int	fklog = -1;	/* /dev/klog */
285static int	Initialized;	/* set when we have initialized ourselves */
286static int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
287static int	MarkSeq;	/* mark sequence number */
288static int	NoBind;		/* don't bind() as suggested by RFC 3164 */
289static int	SecureMode;	/* when true, receive only unix domain socks */
290#ifdef INET6
291static int	family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
292#else
293static int	family = PF_INET; /* protocol family (IPv4 only) */
294#endif
295static int	mask_C1 = 1;	/* mask characters from 0x80 - 0x9F */
296static int	send_to_all;	/* send message to all IPv4/IPv6 addresses */
297static int	use_bootfile;	/* log entire bootfile for every kern msg */
298static int	no_compress;	/* don't compress messages (1=pipes, 2=all) */
299static int	logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
300
301static char	bootfile[MAXLINE+1]; /* booted kernel file */
302
303struct allowedpeer *AllowedPeers; /* List of allowed peers */
304static int	NumAllowed;	/* Number of entries in AllowedPeers */
305static int	RemoteAddDate;	/* Always set the date on remote messages */
306
307static int	UniquePriority;	/* Only log specified priority? */
308static int	LogFacPri;	/* Put facility and priority in log message: */
309				/* 0=no, 1=numeric, 2=names */
310static int	KeepKernFac;	/* Keep remotely logged kernel facility */
311static int	needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
312static struct pidfh *pfh;
313
314volatile sig_atomic_t MarkSet, WantDie;
315
316static int	allowaddr(char *);
317static void	cfline(const char *, struct filed *,
318		    const char *, const char *);
319static const char *cvthname(struct sockaddr *);
320static void	deadq_enter(pid_t, const char *);
321static int	deadq_remove(pid_t);
322static int	decode(const char *, const CODE *);
323static void	die(int);
324static void	dodie(int);
325static void	dofsync(void);
326static void	domark(int);
327static void	fprintlog(struct filed *, int, const char *);
328static int	*socksetup(int, char *);
329static void	init(int);
330static void	logerror(const char *);
331static void	logmsg(int, const char *, const char *, int);
332static void	log_deadchild(pid_t, int, const char *);
333static void	markit(void);
334static int	skip_message(const char *, const char *, int);
335static void	printline(const char *, char *, int);
336static void	printsys(char *);
337static int	p_open(const char *, pid_t *);
338static void	readklog(void);
339static void	reapchild(int);
340static void	usage(void);
341static int	validate(struct sockaddr *, const char *);
342static void	unmapped(struct sockaddr *);
343static void	wallmsg(struct filed *, struct iovec *, const int iovlen);
344static int	waitdaemon(int, int, int);
345static void	timedout(int);
346static void	increase_rcvbuf(int);
347
348static void
349close_filed(struct filed *f)
350{
351
352	if (f == NULL || f->f_file == -1)
353		return;
354
355	switch (f->f_type) {
356	case F_FILE:
357	case F_TTY:
358	case F_CONSOLE:
359	case F_FORW:
360		f->f_type = F_UNUSED;
361		break;
362	case F_PIPE:
363		f->f_un.f_pipe.f_pid = 0;
364		break;
365	}
366	(void)close(f->f_file);
367	f->f_file = -1;
368}
369
370int
371main(int argc, char *argv[])
372{
373	int ch, i, fdsrmax = 0, l;
374	struct sockaddr_un sunx, fromunix;
375	struct sockaddr_storage frominet;
376	fd_set *fdsr = NULL;
377	char line[MAXLINE + 1];
378	char *bindhostname;
379	const char *hname;
380	struct timeval tv, *tvp;
381	struct sigaction sact;
382	struct funix *fx, *fx1;
383	sigset_t mask;
384	pid_t ppid = 1, spid;
385	socklen_t len;
386
387	if (madvise(NULL, 0, MADV_PROTECT) != 0)
388		dprintf("madvise() failed: %s\n", strerror(errno));
389
390	bindhostname = NULL;
391	while ((ch = getopt(argc, argv, "468Aa:b:cCdf:Fkl:m:nNop:P:sS:Tuv"))
392	    != -1)
393		switch (ch) {
394		case '4':
395			family = PF_INET;
396			break;
397#ifdef INET6
398		case '6':
399			family = PF_INET6;
400			break;
401#endif
402		case '8':
403			mask_C1 = 0;
404			break;
405		case 'A':
406			send_to_all++;
407			break;
408		case 'a':		/* allow specific network addresses only */
409			if (allowaddr(optarg) == -1)
410				usage();
411			break;
412		case 'b':
413			bindhostname = optarg;
414			break;
415		case 'c':
416			no_compress++;
417			break;
418		case 'C':
419			logflags |= O_CREAT;
420			break;
421		case 'd':		/* debug */
422			Debug++;
423			break;
424		case 'f':		/* configuration file */
425			ConfFile = optarg;
426			break;
427		case 'F':		/* run in foreground instead of daemon */
428			Foreground++;
429			break;
430		case 'k':		/* keep remote kern fac */
431			KeepKernFac = 1;
432			break;
433		case 'l':
434		    {
435			long	perml;
436			mode_t	mode;
437			char	*name, *ep;
438
439			if (optarg[0] == '/') {
440				mode = DEFFILEMODE;
441				name = optarg;
442			} else if ((name = strchr(optarg, ':')) != NULL) {
443				*name++ = '\0';
444				if (name[0] != '/')
445					errx(1, "socket name must be absolute "
446					    "path");
447				if (isdigit(*optarg)) {
448					perml = strtol(optarg, &ep, 8);
449				    if (*ep || perml < 0 ||
450					perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
451					    errx(1, "invalid mode %s, exiting",
452						optarg);
453				    mode = (mode_t )perml;
454				} else
455					errx(1, "invalid mode %s, exiting",
456					    optarg);
457			} else	/* doesn't begin with '/', and no ':' */
458				errx(1, "can't parse path %s", optarg);
459
460			if (strlen(name) >= sizeof(sunx.sun_path))
461				errx(1, "%s path too long, exiting", name);
462			if ((fx = malloc(sizeof(struct funix))) == NULL)
463				errx(1, "malloc failed");
464			fx->s = -1;
465			fx->name = name;
466			fx->mode = mode;
467			STAILQ_INSERT_TAIL(&funixes, fx, next);
468			break;
469		   }
470		case 'm':		/* mark interval */
471			MarkInterval = atoi(optarg) * 60;
472			break;
473		case 'N':
474			NoBind = 1;
475			SecureMode = 1;
476			break;
477		case 'n':
478			resolve = 0;
479			break;
480		case 'o':
481			use_bootfile = 1;
482			break;
483		case 'p':		/* path */
484			if (strlen(optarg) >= sizeof(sunx.sun_path))
485				errx(1, "%s path too long, exiting", optarg);
486			funix_default.name = optarg;
487			break;
488		case 'P':		/* path for alt. PID */
489			PidFile = optarg;
490			break;
491		case 's':		/* no network mode */
492			SecureMode++;
493			break;
494		case 'S':		/* path for privileged originator */
495			if (strlen(optarg) >= sizeof(sunx.sun_path))
496				errx(1, "%s path too long, exiting", optarg);
497			funix_secure.name = optarg;
498			break;
499		case 'T':
500			RemoteAddDate = 1;
501			break;
502		case 'u':		/* only log specified priority */
503			UniquePriority++;
504			break;
505		case 'v':		/* log facility and priority */
506		  	LogFacPri++;
507			break;
508		default:
509			usage();
510		}
511	if ((argc -= optind) != 0)
512		usage();
513
514	pfh = pidfile_open(PidFile, 0600, &spid);
515	if (pfh == NULL) {
516		if (errno == EEXIST)
517			errx(1, "syslogd already running, pid: %d", spid);
518		warn("cannot open pid file");
519	}
520
521	if ((!Foreground) && (!Debug)) {
522		ppid = waitdaemon(0, 0, 30);
523		if (ppid < 0) {
524			warn("could not become daemon");
525			pidfile_remove(pfh);
526			exit(1);
527		}
528	} else if (Debug) {
529		setlinebuf(stdout);
530	}
531
532	if (NumAllowed)
533		endservent();
534
535	consfile.f_type = F_CONSOLE;
536	(void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
537	    sizeof(consfile.f_un.f_fname));
538	(void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
539	(void)signal(SIGTERM, dodie);
540	(void)signal(SIGINT, Debug ? dodie : SIG_IGN);
541	(void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
542	/*
543	 * We don't want the SIGCHLD and SIGHUP handlers to interfere
544	 * with each other; they are likely candidates for being called
545	 * simultaneously (SIGHUP closes pipe descriptor, process dies,
546	 * SIGCHLD happens).
547	 */
548	sigemptyset(&mask);
549	sigaddset(&mask, SIGHUP);
550	sact.sa_handler = reapchild;
551	sact.sa_mask = mask;
552	sact.sa_flags = SA_RESTART;
553	(void)sigaction(SIGCHLD, &sact, NULL);
554	(void)signal(SIGALRM, domark);
555	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
556	(void)alarm(TIMERINTVL);
557
558	TAILQ_INIT(&deadq_head);
559
560#ifndef SUN_LEN
561#define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
562#endif
563	STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
564		(void)unlink(fx->name);
565		memset(&sunx, 0, sizeof(sunx));
566		sunx.sun_family = AF_LOCAL;
567		(void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
568		fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
569		if (fx->s < 0 ||
570		    bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
571		    chmod(fx->name, fx->mode) < 0) {
572			(void)snprintf(line, sizeof line,
573					"cannot create %s", fx->name);
574			logerror(line);
575			dprintf("cannot create %s (%d)\n", fx->name, errno);
576			if (fx == &funix_default || fx == &funix_secure)
577				die(0);
578			else {
579				STAILQ_REMOVE(&funixes, fx, funix, next);
580				continue;
581			}
582		}
583		increase_rcvbuf(fx->s);
584	}
585	if (SecureMode <= 1)
586		finet = socksetup(family, bindhostname);
587
588	if (finet) {
589		if (SecureMode) {
590			for (i = 0; i < *finet; i++) {
591				if (shutdown(finet[i+1], SHUT_RD) < 0 &&
592				    errno != ENOTCONN) {
593					logerror("shutdown");
594					if (!Debug)
595						die(0);
596				}
597			}
598		} else {
599			dprintf("listening on inet and/or inet6 socket\n");
600		}
601		dprintf("sending on inet and/or inet6 socket\n");
602	}
603
604	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
605		if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
606			fklog = -1;
607	if (fklog < 0)
608		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
609
610	/* tuck my process id away */
611	pidfile_write(pfh);
612
613	dprintf("off & running....\n");
614
615	init(0);
616	/* prevent SIGHUP and SIGCHLD handlers from running in parallel */
617	sigemptyset(&mask);
618	sigaddset(&mask, SIGCHLD);
619	sact.sa_handler = init;
620	sact.sa_mask = mask;
621	sact.sa_flags = SA_RESTART;
622	(void)sigaction(SIGHUP, &sact, NULL);
623
624	tvp = &tv;
625	tv.tv_sec = tv.tv_usec = 0;
626
627	if (fklog != -1 && fklog > fdsrmax)
628		fdsrmax = fklog;
629	if (finet && !SecureMode) {
630		for (i = 0; i < *finet; i++) {
631		    if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
632			fdsrmax = finet[i+1];
633		}
634	}
635	STAILQ_FOREACH(fx, &funixes, next)
636		if (fx->s > fdsrmax)
637			fdsrmax = fx->s;
638
639	fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
640	    sizeof(fd_mask));
641	if (fdsr == NULL)
642		errx(1, "calloc fd_set");
643
644	for (;;) {
645		if (MarkSet)
646			markit();
647		if (WantDie)
648			die(WantDie);
649
650		bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
651		    sizeof(fd_mask));
652
653		if (fklog != -1)
654			FD_SET(fklog, fdsr);
655		if (finet && !SecureMode) {
656			for (i = 0; i < *finet; i++) {
657				if (finet[i+1] != -1)
658					FD_SET(finet[i+1], fdsr);
659			}
660		}
661		STAILQ_FOREACH(fx, &funixes, next)
662			FD_SET(fx->s, fdsr);
663
664		i = select(fdsrmax+1, fdsr, NULL, NULL,
665		    needdofsync ? &tv : tvp);
666		switch (i) {
667		case 0:
668			dofsync();
669			needdofsync = 0;
670			if (tvp) {
671				tvp = NULL;
672				if (ppid != 1)
673					kill(ppid, SIGALRM);
674			}
675			continue;
676		case -1:
677			if (errno != EINTR)
678				logerror("select");
679			continue;
680		}
681		if (fklog != -1 && FD_ISSET(fklog, fdsr))
682			readklog();
683		if (finet && !SecureMode) {
684			for (i = 0; i < *finet; i++) {
685				if (FD_ISSET(finet[i+1], fdsr)) {
686					len = sizeof(frominet);
687					l = recvfrom(finet[i+1], line, MAXLINE,
688					     0, (struct sockaddr *)&frominet,
689					     &len);
690					if (l > 0) {
691						line[l] = '\0';
692						hname = cvthname((struct sockaddr *)&frominet);
693						unmapped((struct sockaddr *)&frominet);
694						if (validate((struct sockaddr *)&frominet, hname))
695							printline(hname, line, RemoteAddDate ? ADDDATE : 0);
696					} else if (l < 0 && errno != EINTR)
697						logerror("recvfrom inet");
698				}
699			}
700		}
701		STAILQ_FOREACH(fx, &funixes, next) {
702			if (FD_ISSET(fx->s, fdsr)) {
703				len = sizeof(fromunix);
704				l = recvfrom(fx->s, line, MAXLINE, 0,
705				    (struct sockaddr *)&fromunix, &len);
706				if (l > 0) {
707					line[l] = '\0';
708					printline(LocalHostName, line, 0);
709				} else if (l < 0 && errno != EINTR)
710					logerror("recvfrom unix");
711			}
712		}
713	}
714	if (fdsr)
715		free(fdsr);
716}
717
718static void
719unmapped(struct sockaddr *sa)
720{
721	struct sockaddr_in6 *sin6;
722	struct sockaddr_in sin4;
723
724	if (sa->sa_family != AF_INET6)
725		return;
726	if (sa->sa_len != sizeof(struct sockaddr_in6) ||
727	    sizeof(sin4) > sa->sa_len)
728		return;
729	sin6 = (struct sockaddr_in6 *)sa;
730	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
731		return;
732
733	memset(&sin4, 0, sizeof(sin4));
734	sin4.sin_family = AF_INET;
735	sin4.sin_len = sizeof(struct sockaddr_in);
736	memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
737	       sizeof(sin4.sin_addr));
738	sin4.sin_port = sin6->sin6_port;
739
740	memcpy(sa, &sin4, sin4.sin_len);
741}
742
743static void
744usage(void)
745{
746
747	fprintf(stderr, "%s\n%s\n%s\n%s\n",
748		"usage: syslogd [-468ACcdFknosTuv] [-a allowed_peer]",
749		"               [-b bind_address] [-f config_file]",
750		"               [-l [mode:]path] [-m mark_interval]",
751		"               [-P pid_file] [-p log_socket]");
752	exit(1);
753}
754
755/*
756 * Take a raw input line, decode the message, and print the message
757 * on the appropriate log files.
758 */
759static void
760printline(const char *hname, char *msg, int flags)
761{
762	char *p, *q;
763	long n;
764	int c, pri;
765	char line[MAXLINE + 1];
766
767	/* test for special codes */
768	p = msg;
769	pri = DEFUPRI;
770	if (*p == '<') {
771		errno = 0;
772		n = strtol(p + 1, &q, 10);
773		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
774			p = q + 1;
775			pri = n;
776		}
777	}
778	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
779		pri = DEFUPRI;
780
781	/*
782	 * Don't allow users to log kernel messages.
783	 * NOTE: since LOG_KERN == 0 this will also match
784	 *       messages with no facility specified.
785	 */
786	if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
787		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
788
789	q = line;
790
791	while ((c = (unsigned char)*p++) != '\0' &&
792	    q < &line[sizeof(line) - 4]) {
793		if (mask_C1 && (c & 0x80) && c < 0xA0) {
794			c &= 0x7F;
795			*q++ = 'M';
796			*q++ = '-';
797		}
798		if (isascii(c) && iscntrl(c)) {
799			if (c == '\n') {
800				*q++ = ' ';
801			} else if (c == '\t') {
802				*q++ = '\t';
803			} else {
804				*q++ = '^';
805				*q++ = c ^ 0100;
806			}
807		} else {
808			*q++ = c;
809		}
810	}
811	*q = '\0';
812
813	logmsg(pri, line, hname, flags);
814}
815
816/*
817 * Read /dev/klog while data are available, split into lines.
818 */
819static void
820readklog(void)
821{
822	char *p, *q, line[MAXLINE + 1];
823	int len, i;
824
825	len = 0;
826	for (;;) {
827		i = read(fklog, line + len, MAXLINE - 1 - len);
828		if (i > 0) {
829			line[i + len] = '\0';
830		} else {
831			if (i < 0 && errno != EINTR && errno != EAGAIN) {
832				logerror("klog");
833				fklog = -1;
834			}
835			break;
836		}
837
838		for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
839			*q = '\0';
840			printsys(p);
841		}
842		len = strlen(p);
843		if (len >= MAXLINE - 1) {
844			printsys(p);
845			len = 0;
846		}
847		if (len > 0)
848			memmove(line, p, len + 1);
849	}
850	if (len > 0)
851		printsys(line);
852}
853
854/*
855 * Take a raw input line from /dev/klog, format similar to syslog().
856 */
857static void
858printsys(char *msg)
859{
860	char *p, *q;
861	long n;
862	int flags, isprintf, pri;
863
864	flags = ISKERNEL | SYNC_FILE | ADDDATE;	/* fsync after write */
865	p = msg;
866	pri = DEFSPRI;
867	isprintf = 1;
868	if (*p == '<') {
869		errno = 0;
870		n = strtol(p + 1, &q, 10);
871		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
872			p = q + 1;
873			pri = n;
874			isprintf = 0;
875		}
876	}
877	/*
878	 * Kernel printf's and LOG_CONSOLE messages have been displayed
879	 * on the console already.
880	 */
881	if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
882		flags |= IGN_CONS;
883	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
884		pri = DEFSPRI;
885	logmsg(pri, p, LocalHostName, flags);
886}
887
888static time_t	now;
889
890/*
891 * Match a program or host name against a specification.
892 * Return a non-0 value if the message must be ignored
893 * based on the specification.
894 */
895static int
896skip_message(const char *name, const char *spec, int checkcase)
897{
898	const char *s;
899	char prev, next;
900	int exclude = 0;
901	/* Behaviour on explicit match */
902
903	if (spec == NULL)
904		return 0;
905	switch (*spec) {
906	case '-':
907		exclude = 1;
908		/*FALLTHROUGH*/
909	case '+':
910		spec++;
911		break;
912	default:
913		break;
914	}
915	if (checkcase)
916		s = strstr (spec, name);
917	else
918		s = strcasestr (spec, name);
919
920	if (s != NULL) {
921		prev = (s == spec ? ',' : *(s - 1));
922		next = *(s + strlen (name));
923
924		if (prev == ',' && (next == '\0' || next == ','))
925			/* Explicit match: skip iff the spec is an
926			   exclusive one. */
927			return exclude;
928	}
929
930	/* No explicit match for this name: skip the message iff
931	   the spec is an inclusive one. */
932	return !exclude;
933}
934
935/*
936 * Log a message to the appropriate log files, users, etc. based on
937 * the priority.
938 */
939static void
940logmsg(int pri, const char *msg, const char *from, int flags)
941{
942	struct filed *f;
943	int i, fac, msglen, omask, prilev;
944	const char *timestamp;
945 	char prog[NAME_MAX+1];
946	char buf[MAXLINE+1];
947
948	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
949	    pri, flags, from, msg);
950
951	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
952
953	/*
954	 * Check to see if msg looks non-standard.
955	 */
956	msglen = strlen(msg);
957	if (msglen < MAXDATELEN || msg[3] != ' ' || msg[6] != ' ' ||
958	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
959		flags |= ADDDATE;
960
961	(void)time(&now);
962	if (flags & ADDDATE) {
963		timestamp = ctime(&now) + 4;
964	} else {
965		timestamp = msg;
966		msg += MAXDATELEN;
967		msglen -= MAXDATELEN;
968	}
969
970	/* skip leading blanks */
971	while (isspace(*msg)) {
972		msg++;
973		msglen--;
974	}
975
976	/* extract facility and priority level */
977	if (flags & MARK)
978		fac = LOG_NFACILITIES;
979	else
980		fac = LOG_FAC(pri);
981
982	/* Check maximum facility number. */
983	if (fac > LOG_NFACILITIES) {
984		(void)sigsetmask(omask);
985		return;
986	}
987
988	prilev = LOG_PRI(pri);
989
990	/* extract program name */
991	for (i = 0; i < NAME_MAX; i++) {
992		if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
993		    msg[i] == '/' || isspace(msg[i]))
994			break;
995		prog[i] = msg[i];
996	}
997	prog[i] = 0;
998
999	/* add kernel prefix for kernel messages */
1000	if (flags & ISKERNEL) {
1001		snprintf(buf, sizeof(buf), "%s: %s",
1002		    use_bootfile ? bootfile : "kernel", msg);
1003		msg = buf;
1004		msglen = strlen(buf);
1005	}
1006
1007	/* log the message to the particular outputs */
1008	if (!Initialized) {
1009		f = &consfile;
1010		/*
1011		 * Open in non-blocking mode to avoid hangs during open
1012		 * and close(waiting for the port to drain).
1013		 */
1014		f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1015
1016		if (f->f_file >= 0) {
1017			(void)strlcpy(f->f_lasttime, timestamp,
1018				sizeof(f->f_lasttime));
1019			fprintlog(f, flags, msg);
1020			close(f->f_file);
1021			f->f_file = -1;
1022		}
1023		(void)sigsetmask(omask);
1024		return;
1025	}
1026	for (f = Files; f; f = f->f_next) {
1027		/* skip messages that are incorrect priority */
1028		if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1029		     ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1030		     ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1031		     )
1032		    || f->f_pmask[fac] == INTERNAL_NOPRI)
1033			continue;
1034
1035		/* skip messages with the incorrect hostname */
1036		if (skip_message(from, f->f_host, 0))
1037			continue;
1038
1039		/* skip messages with the incorrect program name */
1040		if (skip_message(prog, f->f_program, 1))
1041			continue;
1042
1043		/* skip message to console if it has already been printed */
1044		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1045			continue;
1046
1047		/* don't output marks to recently written files */
1048		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1049			continue;
1050
1051		/*
1052		 * suppress duplicate lines to this file
1053		 */
1054		if (no_compress - (f->f_type != F_PIPE) < 1 &&
1055		    (flags & MARK) == 0 && msglen == f->f_prevlen &&
1056		    !strcmp(msg, f->f_prevline) &&
1057		    !strcasecmp(from, f->f_prevhost)) {
1058			(void)strlcpy(f->f_lasttime, timestamp,
1059				sizeof(f->f_lasttime));
1060			f->f_prevcount++;
1061			dprintf("msg repeated %d times, %ld sec of %d\n",
1062			    f->f_prevcount, (long)(now - f->f_time),
1063			    repeatinterval[f->f_repeatcount]);
1064			/*
1065			 * If domark would have logged this by now,
1066			 * flush it now (so we don't hold isolated messages),
1067			 * but back off so we'll flush less often
1068			 * in the future.
1069			 */
1070			if (now > REPEATTIME(f)) {
1071				fprintlog(f, flags, (char *)NULL);
1072				BACKOFF(f);
1073			}
1074		} else {
1075			/* new line, save it */
1076			if (f->f_prevcount)
1077				fprintlog(f, 0, (char *)NULL);
1078			f->f_repeatcount = 0;
1079			f->f_prevpri = pri;
1080			(void)strlcpy(f->f_lasttime, timestamp,
1081				sizeof(f->f_lasttime));
1082			(void)strlcpy(f->f_prevhost, from,
1083			    sizeof(f->f_prevhost));
1084			if (msglen < MAXSVLINE) {
1085				f->f_prevlen = msglen;
1086				(void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1087				fprintlog(f, flags, (char *)NULL);
1088			} else {
1089				f->f_prevline[0] = 0;
1090				f->f_prevlen = 0;
1091				fprintlog(f, flags, msg);
1092			}
1093		}
1094	}
1095	(void)sigsetmask(omask);
1096}
1097
1098static void
1099dofsync(void)
1100{
1101	struct filed *f;
1102
1103	for (f = Files; f; f = f->f_next) {
1104		if ((f->f_type == F_FILE) &&
1105		    (f->f_flags & FFLAG_NEEDSYNC)) {
1106			f->f_flags &= ~FFLAG_NEEDSYNC;
1107			(void)fsync(f->f_file);
1108		}
1109	}
1110}
1111
1112#define IOV_SIZE 7
1113static void
1114fprintlog(struct filed *f, int flags, const char *msg)
1115{
1116	struct iovec iov[IOV_SIZE];
1117	struct iovec *v;
1118	struct addrinfo *r;
1119	int i, l, lsent = 0;
1120	char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1121	char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1122	const char *msgret;
1123
1124	v = iov;
1125	if (f->f_type == F_WALL) {
1126		v->iov_base = greetings;
1127		/* The time displayed is not synchornized with the other log
1128		 * destinations (like messages).  Following fragment was using
1129		 * ctime(&now), which was updating the time every 30 sec.
1130		 * With f_lasttime, time is synchronized correctly.
1131		 */
1132		v->iov_len = snprintf(greetings, sizeof greetings,
1133		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1134		    f->f_prevhost, f->f_lasttime);
1135		if (v->iov_len >= sizeof greetings)
1136			v->iov_len = sizeof greetings - 1;
1137		v++;
1138		v->iov_base = nul;
1139		v->iov_len = 0;
1140		v++;
1141	} else {
1142		v->iov_base = f->f_lasttime;
1143		v->iov_len = strlen(f->f_lasttime);
1144		v++;
1145		v->iov_base = space;
1146		v->iov_len = 1;
1147		v++;
1148	}
1149
1150	if (LogFacPri) {
1151	  	static char fp_buf[30];	/* Hollow laugh */
1152		int fac = f->f_prevpri & LOG_FACMASK;
1153		int pri = LOG_PRI(f->f_prevpri);
1154		const char *f_s = NULL;
1155		char f_n[5];	/* Hollow laugh */
1156		const char *p_s = NULL;
1157		char p_n[5];	/* Hollow laugh */
1158
1159		if (LogFacPri > 1) {
1160		  const CODE *c;
1161
1162		  for (c = facilitynames; c->c_name; c++) {
1163		    if (c->c_val == fac) {
1164		      f_s = c->c_name;
1165		      break;
1166		    }
1167		  }
1168		  for (c = prioritynames; c->c_name; c++) {
1169		    if (c->c_val == pri) {
1170		      p_s = c->c_name;
1171		      break;
1172		    }
1173		  }
1174		}
1175		if (!f_s) {
1176		  snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1177		  f_s = f_n;
1178		}
1179		if (!p_s) {
1180		  snprintf(p_n, sizeof p_n, "%d", pri);
1181		  p_s = p_n;
1182		}
1183		snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1184		v->iov_base = fp_buf;
1185		v->iov_len = strlen(fp_buf);
1186	} else {
1187		v->iov_base = nul;
1188		v->iov_len = 0;
1189	}
1190	v++;
1191
1192	v->iov_base = f->f_prevhost;
1193	v->iov_len = strlen(v->iov_base);
1194	v++;
1195	v->iov_base = space;
1196	v->iov_len = 1;
1197	v++;
1198
1199	if (msg) {
1200		wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1201		if (wmsg == NULL) {
1202			logerror("strdup");
1203			exit(1);
1204		}
1205		v->iov_base = wmsg;
1206		v->iov_len = strlen(msg);
1207	} else if (f->f_prevcount > 1) {
1208		v->iov_base = repbuf;
1209		v->iov_len = snprintf(repbuf, sizeof repbuf,
1210		    "last message repeated %d times", f->f_prevcount);
1211	} else {
1212		v->iov_base = f->f_prevline;
1213		v->iov_len = f->f_prevlen;
1214	}
1215	v++;
1216
1217	dprintf("Logging to %s", TypeNames[f->f_type]);
1218	f->f_time = now;
1219
1220	switch (f->f_type) {
1221		int port;
1222	case F_UNUSED:
1223		dprintf("\n");
1224		break;
1225
1226	case F_FORW:
1227		port = (int)ntohs(((struct sockaddr_in *)
1228			    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1229		if (port != 514) {
1230			dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1231		} else {
1232			dprintf(" %s\n", f->f_un.f_forw.f_hname);
1233		}
1234		/* check for local vs remote messages */
1235		if (strcasecmp(f->f_prevhost, LocalHostName))
1236			l = snprintf(line, sizeof line - 1,
1237			    "<%d>%.15s Forwarded from %s: %s",
1238			    f->f_prevpri, (char *)iov[0].iov_base,
1239			    f->f_prevhost, (char *)iov[5].iov_base);
1240		else
1241			l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1242			     f->f_prevpri, (char *)iov[0].iov_base,
1243			    (char *)iov[5].iov_base);
1244		if (l < 0)
1245			l = 0;
1246		else if (l > MAXLINE)
1247			l = MAXLINE;
1248
1249		if (finet) {
1250			for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1251				for (i = 0; i < *finet; i++) {
1252#if 0
1253					/*
1254					 * should we check AF first, or just
1255					 * trial and error? FWD
1256					 */
1257					if (r->ai_family ==
1258					    address_family_of(finet[i+1]))
1259#endif
1260					lsent = sendto(finet[i+1], line, l, 0,
1261					    r->ai_addr, r->ai_addrlen);
1262					if (lsent == l)
1263						break;
1264				}
1265				if (lsent == l && !send_to_all)
1266					break;
1267			}
1268			dprintf("lsent/l: %d/%d\n", lsent, l);
1269			if (lsent != l) {
1270				int e = errno;
1271				logerror("sendto");
1272				errno = e;
1273				switch (errno) {
1274				case ENOBUFS:
1275				case ENETDOWN:
1276				case ENETUNREACH:
1277				case EHOSTUNREACH:
1278				case EHOSTDOWN:
1279				case EADDRNOTAVAIL:
1280					break;
1281				/* case EBADF: */
1282				/* case EACCES: */
1283				/* case ENOTSOCK: */
1284				/* case EFAULT: */
1285				/* case EMSGSIZE: */
1286				/* case EAGAIN: */
1287				/* case ENOBUFS: */
1288				/* case ECONNREFUSED: */
1289				default:
1290					dprintf("removing entry: errno=%d\n", e);
1291					f->f_type = F_UNUSED;
1292					break;
1293				}
1294			}
1295		}
1296		break;
1297
1298	case F_FILE:
1299		dprintf(" %s\n", f->f_un.f_fname);
1300		v->iov_base = lf;
1301		v->iov_len = 1;
1302		if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1303			/*
1304			 * If writev(2) fails for potentially transient errors
1305			 * like the filesystem being full, ignore it.
1306			 * Otherwise remove this logfile from the list.
1307			 */
1308			if (errno != ENOSPC) {
1309				int e = errno;
1310				close_filed(f);
1311				errno = e;
1312				logerror(f->f_un.f_fname);
1313			}
1314		} else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1315			f->f_flags |= FFLAG_NEEDSYNC;
1316			needdofsync = 1;
1317		}
1318		break;
1319
1320	case F_PIPE:
1321		dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1322		v->iov_base = lf;
1323		v->iov_len = 1;
1324		if (f->f_un.f_pipe.f_pid == 0) {
1325			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1326						&f->f_un.f_pipe.f_pid)) < 0) {
1327				logerror(f->f_un.f_pipe.f_pname);
1328				break;
1329			}
1330		}
1331		if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1332			int e = errno;
1333
1334			close_filed(f);
1335			deadq_enter(f->f_un.f_pipe.f_pid,
1336				    f->f_un.f_pipe.f_pname);
1337			errno = e;
1338			logerror(f->f_un.f_pipe.f_pname);
1339		}
1340		break;
1341
1342	case F_CONSOLE:
1343		if (flags & IGN_CONS) {
1344			dprintf(" (ignored)\n");
1345			break;
1346		}
1347		/* FALLTHROUGH */
1348
1349	case F_TTY:
1350		dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1351		v->iov_base = crlf;
1352		v->iov_len = 2;
1353
1354		errno = 0;	/* ttymsg() only sometimes returns an errno */
1355		if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1356			f->f_type = F_UNUSED;
1357			logerror(msgret);
1358		}
1359		break;
1360
1361	case F_USERS:
1362	case F_WALL:
1363		dprintf("\n");
1364		v->iov_base = crlf;
1365		v->iov_len = 2;
1366		wallmsg(f, iov, IOV_SIZE);
1367		break;
1368	}
1369	f->f_prevcount = 0;
1370	free(wmsg);
1371}
1372
1373/*
1374 *  WALLMSG -- Write a message to the world at large
1375 *
1376 *	Write the specified message to either the entire
1377 *	world, or a list of approved users.
1378 */
1379static void
1380wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1381{
1382	static int reenter;			/* avoid calling ourselves */
1383	struct utmpx *ut;
1384	int i;
1385	const char *p;
1386
1387	if (reenter++)
1388		return;
1389	setutxent();
1390	/* NOSTRICT */
1391	while ((ut = getutxent()) != NULL) {
1392		if (ut->ut_type != USER_PROCESS)
1393			continue;
1394		if (f->f_type == F_WALL) {
1395			if ((p = ttymsg(iov, iovlen, ut->ut_line,
1396			    TTYMSGTIME)) != NULL) {
1397				errno = 0;	/* already in msg */
1398				logerror(p);
1399			}
1400			continue;
1401		}
1402		/* should we send the message to this user? */
1403		for (i = 0; i < MAXUNAMES; i++) {
1404			if (!f->f_un.f_uname[i][0])
1405				break;
1406			if (!strcmp(f->f_un.f_uname[i], ut->ut_user)) {
1407				if ((p = ttymsg(iov, iovlen, ut->ut_line,
1408				    TTYMSGTIME)) != NULL) {
1409					errno = 0;	/* already in msg */
1410					logerror(p);
1411				}
1412				break;
1413			}
1414		}
1415	}
1416	endutxent();
1417	reenter = 0;
1418}
1419
1420static void
1421reapchild(int signo __unused)
1422{
1423	int status;
1424	pid_t pid;
1425	struct filed *f;
1426
1427	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1428		if (!Initialized)
1429			/* Don't tell while we are initting. */
1430			continue;
1431
1432		/* First, look if it's a process from the dead queue. */
1433		if (deadq_remove(pid))
1434			goto oncemore;
1435
1436		/* Now, look in list of active processes. */
1437		for (f = Files; f; f = f->f_next)
1438			if (f->f_type == F_PIPE &&
1439			    f->f_un.f_pipe.f_pid == pid) {
1440				close_filed(f);
1441				log_deadchild(pid, status,
1442					      f->f_un.f_pipe.f_pname);
1443				break;
1444			}
1445	  oncemore:
1446		continue;
1447	}
1448}
1449
1450/*
1451 * Return a printable representation of a host address.
1452 */
1453static const char *
1454cvthname(struct sockaddr *f)
1455{
1456	int error, hl;
1457	sigset_t omask, nmask;
1458	static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1459
1460	error = getnameinfo((struct sockaddr *)f,
1461			    ((struct sockaddr *)f)->sa_len,
1462			    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1463	dprintf("cvthname(%s)\n", ip);
1464
1465	if (error) {
1466		dprintf("Malformed from address %s\n", gai_strerror(error));
1467		return ("???");
1468	}
1469	if (!resolve)
1470		return (ip);
1471
1472	sigemptyset(&nmask);
1473	sigaddset(&nmask, SIGHUP);
1474	sigprocmask(SIG_BLOCK, &nmask, &omask);
1475	error = getnameinfo((struct sockaddr *)f,
1476			    ((struct sockaddr *)f)->sa_len,
1477			    hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1478	sigprocmask(SIG_SETMASK, &omask, NULL);
1479	if (error) {
1480		dprintf("Host name for your address (%s) unknown\n", ip);
1481		return (ip);
1482	}
1483	hl = strlen(hname);
1484	if (hl > 0 && hname[hl-1] == '.')
1485		hname[--hl] = '\0';
1486	trimdomain(hname, hl);
1487	return (hname);
1488}
1489
1490static void
1491dodie(int signo)
1492{
1493
1494	WantDie = signo;
1495}
1496
1497static void
1498domark(int signo __unused)
1499{
1500
1501	MarkSet = 1;
1502}
1503
1504/*
1505 * Print syslogd errors some place.
1506 */
1507static void
1508logerror(const char *type)
1509{
1510	char buf[512];
1511	static int recursed = 0;
1512
1513	/* If there's an error while trying to log an error, give up. */
1514	if (recursed)
1515		return;
1516	recursed++;
1517	if (errno)
1518		(void)snprintf(buf,
1519		    sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1520	else
1521		(void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1522	errno = 0;
1523	dprintf("%s\n", buf);
1524	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1525	recursed--;
1526}
1527
1528static void
1529die(int signo)
1530{
1531	struct filed *f;
1532	struct funix *fx;
1533	int was_initialized;
1534	char buf[100];
1535
1536	was_initialized = Initialized;
1537	Initialized = 0;	/* Don't log SIGCHLDs. */
1538	for (f = Files; f != NULL; f = f->f_next) {
1539		/* flush any pending output */
1540		if (f->f_prevcount)
1541			fprintlog(f, 0, (char *)NULL);
1542		if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0)
1543			close_filed(f);
1544	}
1545	Initialized = was_initialized;
1546	if (signo) {
1547		dprintf("syslogd: exiting on signal %d\n", signo);
1548		(void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1549		errno = 0;
1550		logerror(buf);
1551	}
1552	STAILQ_FOREACH(fx, &funixes, next)
1553		(void)unlink(fx->name);
1554	pidfile_remove(pfh);
1555
1556	exit(1);
1557}
1558
1559static int
1560configfiles(const struct dirent *dp)
1561{
1562	const char *p;
1563	size_t ext_len;
1564
1565	if (dp->d_name[0] == '.')
1566		return (0);
1567
1568	ext_len = sizeof(include_ext) -1;
1569
1570	if (dp->d_namlen <= ext_len)
1571		return (0);
1572
1573	p = &dp->d_name[dp->d_namlen - ext_len];
1574	if (strcmp(p, include_ext) != 0)
1575		return (0);
1576
1577	return (1);
1578}
1579
1580static void
1581readconfigfile(FILE *cf, struct filed **nextp, int allow_includes)
1582{
1583	FILE *cf2;
1584	struct filed *f;
1585	struct dirent **ent;
1586	char cline[LINE_MAX];
1587	char host[MAXHOSTNAMELEN];
1588	char prog[LINE_MAX];
1589	char file[MAXPATHLEN];
1590	char *p, *tmp;
1591	int i, nents;
1592	size_t include_len;
1593
1594	/*
1595	 *  Foreach line in the conf table, open that file.
1596	 */
1597	f = NULL;
1598	include_len = sizeof(include_str) -1;
1599	(void)strlcpy(host, "*", sizeof(host));
1600	(void)strlcpy(prog, "*", sizeof(prog));
1601	while (fgets(cline, sizeof(cline), cf) != NULL) {
1602		/*
1603		 * check for end-of-section, comments, strip off trailing
1604		 * spaces and newline character. #!prog is treated specially:
1605		 * following lines apply only to that program.
1606		 */
1607		for (p = cline; isspace(*p); ++p)
1608			continue;
1609		if (*p == 0)
1610			continue;
1611		if (allow_includes &&
1612		    strncmp(p, include_str, include_len) == 0 &&
1613		    isspace(p[include_len])) {
1614			p += include_len;
1615			while (isspace(*p))
1616				p++;
1617			tmp = p;
1618			while (*tmp != '\0' && !isspace(*tmp))
1619				tmp++;
1620			*tmp = '\0';
1621			dprintf("Trying to include files in '%s'\n", p);
1622			nents = scandir(p, &ent, configfiles, alphasort);
1623			if (nents == -1) {
1624				dprintf("Unable to open '%s': %s\n", p,
1625				    strerror(errno));
1626				continue;
1627			}
1628			for (i = 0; i < nents; i++) {
1629				if (snprintf(file, sizeof(file), "%s/%s", p,
1630				    ent[i]->d_name) >= (int)sizeof(file)) {
1631					dprintf("ignoring path too long: "
1632					    "'%s/%s'\n", p, ent[i]->d_name);
1633					free(ent[i]);
1634					continue;
1635				}
1636				free(ent[i]);
1637				cf2 = fopen(file, "r");
1638				if (cf2 == NULL)
1639					continue;
1640				dprintf("reading %s\n", file);
1641				readconfigfile(cf2, nextp, 0);
1642				fclose(cf2);
1643			}
1644			free(ent);
1645			continue;
1646		}
1647		if (*p == '#') {
1648			p++;
1649			if (*p != '!' && *p != '+' && *p != '-')
1650				continue;
1651		}
1652		if (*p == '+' || *p == '-') {
1653			host[0] = *p++;
1654			while (isspace(*p))
1655				p++;
1656			if ((!*p) || (*p == '*')) {
1657				(void)strlcpy(host, "*", sizeof(host));
1658				continue;
1659			}
1660			if (*p == '@')
1661				p = LocalHostName;
1662			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1663				if (!isalnum(*p) && *p != '.' && *p != '-'
1664				    && *p != ',' && *p != ':' && *p != '%')
1665					break;
1666				host[i] = *p++;
1667			}
1668			host[i] = '\0';
1669			continue;
1670		}
1671		if (*p == '!') {
1672			p++;
1673			while (isspace(*p)) p++;
1674			if ((!*p) || (*p == '*')) {
1675				(void)strlcpy(prog, "*", sizeof(prog));
1676				continue;
1677			}
1678			for (i = 0; i < LINE_MAX - 1; i++) {
1679				if (!isprint(p[i]) || isspace(p[i]))
1680					break;
1681				prog[i] = p[i];
1682			}
1683			prog[i] = 0;
1684			continue;
1685		}
1686		for (p = cline + 1; *p != '\0'; p++) {
1687			if (*p != '#')
1688				continue;
1689			if (*(p - 1) == '\\') {
1690				strcpy(p - 1, p);
1691				p--;
1692				continue;
1693			}
1694			*p = '\0';
1695			break;
1696		}
1697		for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1698			cline[i] = '\0';
1699		f = (struct filed *)calloc(1, sizeof(*f));
1700		if (f == NULL) {
1701			logerror("calloc");
1702			exit(1);
1703		}
1704		*nextp = f;
1705		nextp = &f->f_next;
1706		cfline(cline, f, prog, host);
1707	}
1708}
1709
1710/*
1711 *  INIT -- Initialize syslogd from configuration table
1712 */
1713static void
1714init(int signo)
1715{
1716	int i;
1717	FILE *cf;
1718	struct filed *f, *next, **nextp;
1719	char *p;
1720	char oldLocalHostName[MAXHOSTNAMELEN];
1721	char hostMsg[2*MAXHOSTNAMELEN+40];
1722	char bootfileMsg[LINE_MAX];
1723
1724	dprintf("init\n");
1725
1726	/*
1727	 * Load hostname (may have changed).
1728	 */
1729	if (signo != 0)
1730		(void)strlcpy(oldLocalHostName, LocalHostName,
1731		    sizeof(oldLocalHostName));
1732	if (gethostname(LocalHostName, sizeof(LocalHostName)))
1733		err(EX_OSERR, "gethostname() failed");
1734	if ((p = strchr(LocalHostName, '.')) != NULL) {
1735		*p++ = '\0';
1736		LocalDomain = p;
1737	} else {
1738		LocalDomain = "";
1739	}
1740
1741	/*
1742	 *  Close all open log files.
1743	 */
1744	Initialized = 0;
1745	for (f = Files; f != NULL; f = next) {
1746		/* flush any pending output */
1747		if (f->f_prevcount)
1748			fprintlog(f, 0, (char *)NULL);
1749
1750		switch (f->f_type) {
1751		case F_FILE:
1752		case F_FORW:
1753		case F_CONSOLE:
1754		case F_TTY:
1755			close_filed(f);
1756			break;
1757		case F_PIPE:
1758			close_filed(f);
1759			deadq_enter(f->f_un.f_pipe.f_pid,
1760				    f->f_un.f_pipe.f_pname);
1761			break;
1762		}
1763		next = f->f_next;
1764		if (f->f_program) free(f->f_program);
1765		if (f->f_host) free(f->f_host);
1766		free((char *)f);
1767	}
1768	Files = NULL;
1769	nextp = &Files;
1770
1771	/* open the configuration file */
1772	if ((cf = fopen(ConfFile, "r")) == NULL) {
1773		dprintf("cannot open %s\n", ConfFile);
1774		*nextp = (struct filed *)calloc(1, sizeof(*f));
1775		if (*nextp == NULL) {
1776			logerror("calloc");
1777			exit(1);
1778		}
1779		cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1780		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1781		if ((*nextp)->f_next == NULL) {
1782			logerror("calloc");
1783			exit(1);
1784		}
1785		cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1786		Initialized = 1;
1787		return;
1788	}
1789
1790	readconfigfile(cf, &Files, 1);
1791
1792	/* close the configuration file */
1793	(void)fclose(cf);
1794
1795	Initialized = 1;
1796
1797	if (Debug) {
1798		int port;
1799		for (f = Files; f; f = f->f_next) {
1800			for (i = 0; i <= LOG_NFACILITIES; i++)
1801				if (f->f_pmask[i] == INTERNAL_NOPRI)
1802					printf("X ");
1803				else
1804					printf("%d ", f->f_pmask[i]);
1805			printf("%s: ", TypeNames[f->f_type]);
1806			switch (f->f_type) {
1807			case F_FILE:
1808				printf("%s", f->f_un.f_fname);
1809				break;
1810
1811			case F_CONSOLE:
1812			case F_TTY:
1813				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1814				break;
1815
1816			case F_FORW:
1817				port = (int)ntohs(((struct sockaddr_in *)
1818				    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1819				if (port != 514) {
1820					printf("%s:%d",
1821						f->f_un.f_forw.f_hname, port);
1822				} else {
1823					printf("%s", f->f_un.f_forw.f_hname);
1824				}
1825				break;
1826
1827			case F_PIPE:
1828				printf("%s", f->f_un.f_pipe.f_pname);
1829				break;
1830
1831			case F_USERS:
1832				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1833					printf("%s, ", f->f_un.f_uname[i]);
1834				break;
1835			}
1836			if (f->f_program)
1837				printf(" (%s)", f->f_program);
1838			printf("\n");
1839		}
1840	}
1841
1842	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1843	dprintf("syslogd: restarted\n");
1844	/*
1845	 * Log a change in hostname, but only on a restart.
1846	 */
1847	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1848		(void)snprintf(hostMsg, sizeof(hostMsg),
1849		    "syslogd: hostname changed, \"%s\" to \"%s\"",
1850		    oldLocalHostName, LocalHostName);
1851		logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1852		dprintf("%s\n", hostMsg);
1853	}
1854	/*
1855	 * Log the kernel boot file if we aren't going to use it as
1856	 * the prefix, and if this is *not* a restart.
1857	 */
1858	if (signo == 0 && !use_bootfile) {
1859		(void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1860		    "syslogd: kernel boot file is %s", bootfile);
1861		logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1862		dprintf("%s\n", bootfileMsg);
1863	}
1864}
1865
1866/*
1867 * Crack a configuration file line
1868 */
1869static void
1870cfline(const char *line, struct filed *f, const char *prog, const char *host)
1871{
1872	struct addrinfo hints, *res;
1873	int error, i, pri, syncfile;
1874	const char *p, *q;
1875	char *bp;
1876	char buf[MAXLINE], ebuf[100];
1877
1878	dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1879
1880	errno = 0;	/* keep strerror() stuff out of logerror messages */
1881
1882	/* clear out file entry */
1883	memset(f, 0, sizeof(*f));
1884	for (i = 0; i <= LOG_NFACILITIES; i++)
1885		f->f_pmask[i] = INTERNAL_NOPRI;
1886
1887	/* save hostname if any */
1888	if (host && *host == '*')
1889		host = NULL;
1890	if (host) {
1891		int hl;
1892
1893		f->f_host = strdup(host);
1894		if (f->f_host == NULL) {
1895			logerror("strdup");
1896			exit(1);
1897		}
1898		hl = strlen(f->f_host);
1899		if (hl > 0 && f->f_host[hl-1] == '.')
1900			f->f_host[--hl] = '\0';
1901		trimdomain(f->f_host, hl);
1902	}
1903
1904	/* save program name if any */
1905	if (prog && *prog == '*')
1906		prog = NULL;
1907	if (prog) {
1908		f->f_program = strdup(prog);
1909		if (f->f_program == NULL) {
1910			logerror("strdup");
1911			exit(1);
1912		}
1913	}
1914
1915	/* scan through the list of selectors */
1916	for (p = line; *p && *p != '\t' && *p != ' ';) {
1917		int pri_done;
1918		int pri_cmp;
1919		int pri_invert;
1920
1921		/* find the end of this facility name list */
1922		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1923			continue;
1924
1925		/* get the priority comparison */
1926		pri_cmp = 0;
1927		pri_done = 0;
1928		pri_invert = 0;
1929		if (*q == '!') {
1930			pri_invert = 1;
1931			q++;
1932		}
1933		while (!pri_done) {
1934			switch (*q) {
1935			case '<':
1936				pri_cmp |= PRI_LT;
1937				q++;
1938				break;
1939			case '=':
1940				pri_cmp |= PRI_EQ;
1941				q++;
1942				break;
1943			case '>':
1944				pri_cmp |= PRI_GT;
1945				q++;
1946				break;
1947			default:
1948				pri_done++;
1949				break;
1950			}
1951		}
1952
1953		/* collect priority name */
1954		for (bp = buf; *q && !strchr("\t,; ", *q); )
1955			*bp++ = *q++;
1956		*bp = '\0';
1957
1958		/* skip cruft */
1959		while (strchr(",;", *q))
1960			q++;
1961
1962		/* decode priority name */
1963		if (*buf == '*') {
1964			pri = LOG_PRIMASK;
1965			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1966		} else {
1967			/* Ignore trailing spaces. */
1968			for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1969				buf[i] = '\0';
1970
1971			pri = decode(buf, prioritynames);
1972			if (pri < 0) {
1973				errno = 0;
1974				(void)snprintf(ebuf, sizeof ebuf,
1975				    "unknown priority name \"%s\"", buf);
1976				logerror(ebuf);
1977				return;
1978			}
1979		}
1980		if (!pri_cmp)
1981			pri_cmp = (UniquePriority)
1982				  ? (PRI_EQ)
1983				  : (PRI_EQ | PRI_GT)
1984				  ;
1985		if (pri_invert)
1986			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1987
1988		/* scan facilities */
1989		while (*p && !strchr("\t.; ", *p)) {
1990			for (bp = buf; *p && !strchr("\t,;. ", *p); )
1991				*bp++ = *p++;
1992			*bp = '\0';
1993
1994			if (*buf == '*') {
1995				for (i = 0; i < LOG_NFACILITIES; i++) {
1996					f->f_pmask[i] = pri;
1997					f->f_pcmp[i] = pri_cmp;
1998				}
1999			} else {
2000				i = decode(buf, facilitynames);
2001				if (i < 0) {
2002					errno = 0;
2003					(void)snprintf(ebuf, sizeof ebuf,
2004					    "unknown facility name \"%s\"",
2005					    buf);
2006					logerror(ebuf);
2007					return;
2008				}
2009				f->f_pmask[i >> 3] = pri;
2010				f->f_pcmp[i >> 3] = pri_cmp;
2011			}
2012			while (*p == ',' || *p == ' ')
2013				p++;
2014		}
2015
2016		p = q;
2017	}
2018
2019	/* skip to action part */
2020	while (*p == '\t' || *p == ' ')
2021		p++;
2022
2023	if (*p == '-') {
2024		syncfile = 0;
2025		p++;
2026	} else
2027		syncfile = 1;
2028
2029	switch (*p) {
2030	case '@':
2031		{
2032			char *tp;
2033			char endkey = ':';
2034			/*
2035			 * scan forward to see if there is a port defined.
2036			 * so we can't use strlcpy..
2037			 */
2038			i = sizeof(f->f_un.f_forw.f_hname);
2039			tp = f->f_un.f_forw.f_hname;
2040			p++;
2041
2042			/*
2043			 * an ipv6 address should start with a '[' in that case
2044			 * we should scan for a ']'
2045			 */
2046			if (*p == '[') {
2047				p++;
2048				endkey = ']';
2049			}
2050			while (*p && (*p != endkey) && (i-- > 0)) {
2051				*tp++ = *p++;
2052			}
2053			if (endkey == ']' && *p == endkey)
2054				p++;
2055			*tp = '\0';
2056		}
2057		/* See if we copied a domain and have a port */
2058		if (*p == ':')
2059			p++;
2060		else
2061			p = NULL;
2062
2063		memset(&hints, 0, sizeof(hints));
2064		hints.ai_family = family;
2065		hints.ai_socktype = SOCK_DGRAM;
2066		error = getaddrinfo(f->f_un.f_forw.f_hname,
2067				p ? p : "syslog", &hints, &res);
2068		if (error) {
2069			logerror(gai_strerror(error));
2070			break;
2071		}
2072		f->f_un.f_forw.f_addr = res;
2073		f->f_type = F_FORW;
2074		break;
2075
2076	case '/':
2077		if ((f->f_file = open(p, logflags, 0600)) < 0) {
2078			f->f_type = F_UNUSED;
2079			logerror(p);
2080			break;
2081		}
2082		if (syncfile)
2083			f->f_flags |= FFLAG_SYNC;
2084		if (isatty(f->f_file)) {
2085			if (strcmp(p, ctty) == 0)
2086				f->f_type = F_CONSOLE;
2087			else
2088				f->f_type = F_TTY;
2089			(void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
2090			    sizeof(f->f_un.f_fname));
2091		} else {
2092			(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2093			f->f_type = F_FILE;
2094		}
2095		break;
2096
2097	case '|':
2098		f->f_un.f_pipe.f_pid = 0;
2099		(void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2100		    sizeof(f->f_un.f_pipe.f_pname));
2101		f->f_type = F_PIPE;
2102		break;
2103
2104	case '*':
2105		f->f_type = F_WALL;
2106		break;
2107
2108	default:
2109		for (i = 0; i < MAXUNAMES && *p; i++) {
2110			for (q = p; *q && *q != ','; )
2111				q++;
2112			(void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2113			if ((q - p) >= MAXLOGNAME)
2114				f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2115			else
2116				f->f_un.f_uname[i][q - p] = '\0';
2117			while (*q == ',' || *q == ' ')
2118				q++;
2119			p = q;
2120		}
2121		f->f_type = F_USERS;
2122		break;
2123	}
2124}
2125
2126
2127/*
2128 *  Decode a symbolic name to a numeric value
2129 */
2130static int
2131decode(const char *name, const CODE *codetab)
2132{
2133	const CODE *c;
2134	char *p, buf[40];
2135
2136	if (isdigit(*name))
2137		return (atoi(name));
2138
2139	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2140		if (isupper(*name))
2141			*p = tolower(*name);
2142		else
2143			*p = *name;
2144	}
2145	*p = '\0';
2146	for (c = codetab; c->c_name; c++)
2147		if (!strcmp(buf, c->c_name))
2148			return (c->c_val);
2149
2150	return (-1);
2151}
2152
2153static void
2154markit(void)
2155{
2156	struct filed *f;
2157	dq_t q, next;
2158
2159	now = time((time_t *)NULL);
2160	MarkSeq += TIMERINTVL;
2161	if (MarkSeq >= MarkInterval) {
2162		logmsg(LOG_INFO, "-- MARK --",
2163		    LocalHostName, ADDDATE|MARK);
2164		MarkSeq = 0;
2165	}
2166
2167	for (f = Files; f; f = f->f_next) {
2168		if (f->f_prevcount && now >= REPEATTIME(f)) {
2169			dprintf("flush %s: repeated %d times, %d sec.\n",
2170			    TypeNames[f->f_type], f->f_prevcount,
2171			    repeatinterval[f->f_repeatcount]);
2172			fprintlog(f, 0, (char *)NULL);
2173			BACKOFF(f);
2174		}
2175	}
2176
2177	/* Walk the dead queue, and see if we should signal somebody. */
2178	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2179		next = TAILQ_NEXT(q, dq_entries);
2180
2181		switch (q->dq_timeout) {
2182		case 0:
2183			/* Already signalled once, try harder now. */
2184			if (kill(q->dq_pid, SIGKILL) != 0)
2185				(void)deadq_remove(q->dq_pid);
2186			break;
2187
2188		case 1:
2189			/*
2190			 * Timed out on dead queue, send terminate
2191			 * signal.  Note that we leave the removal
2192			 * from the dead queue to reapchild(), which
2193			 * will also log the event (unless the process
2194			 * didn't even really exist, in case we simply
2195			 * drop it from the dead queue).
2196			 */
2197			if (kill(q->dq_pid, SIGTERM) != 0)
2198				(void)deadq_remove(q->dq_pid);
2199			/* FALLTHROUGH */
2200
2201		default:
2202			q->dq_timeout--;
2203		}
2204	}
2205	MarkSet = 0;
2206	(void)alarm(TIMERINTVL);
2207}
2208
2209/*
2210 * fork off and become a daemon, but wait for the child to come online
2211 * before returning to the parent, or we get disk thrashing at boot etc.
2212 * Set a timer so we don't hang forever if it wedges.
2213 */
2214static int
2215waitdaemon(int nochdir, int noclose, int maxwait)
2216{
2217	int fd;
2218	int status;
2219	pid_t pid, childpid;
2220
2221	switch (childpid = fork()) {
2222	case -1:
2223		return (-1);
2224	case 0:
2225		break;
2226	default:
2227		signal(SIGALRM, timedout);
2228		alarm(maxwait);
2229		while ((pid = wait3(&status, 0, NULL)) != -1) {
2230			if (WIFEXITED(status))
2231				errx(1, "child pid %d exited with return code %d",
2232					pid, WEXITSTATUS(status));
2233			if (WIFSIGNALED(status))
2234				errx(1, "child pid %d exited on signal %d%s",
2235					pid, WTERMSIG(status),
2236					WCOREDUMP(status) ? " (core dumped)" :
2237					"");
2238			if (pid == childpid)	/* it's gone... */
2239				break;
2240		}
2241		exit(0);
2242	}
2243
2244	if (setsid() == -1)
2245		return (-1);
2246
2247	if (!nochdir)
2248		(void)chdir("/");
2249
2250	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2251		(void)dup2(fd, STDIN_FILENO);
2252		(void)dup2(fd, STDOUT_FILENO);
2253		(void)dup2(fd, STDERR_FILENO);
2254		if (fd > 2)
2255			(void)close (fd);
2256	}
2257	return (getppid());
2258}
2259
2260/*
2261 * We get a SIGALRM from the child when it's running and finished doing it's
2262 * fsync()'s or O_SYNC writes for all the boot messages.
2263 *
2264 * We also get a signal from the kernel if the timer expires, so check to
2265 * see what happened.
2266 */
2267static void
2268timedout(int sig __unused)
2269{
2270	int left;
2271	left = alarm(0);
2272	signal(SIGALRM, SIG_DFL);
2273	if (left == 0)
2274		errx(1, "timed out waiting for child");
2275	else
2276		_exit(0);
2277}
2278
2279/*
2280 * Add `s' to the list of allowable peer addresses to accept messages
2281 * from.
2282 *
2283 * `s' is a string in the form:
2284 *
2285 *    [*]domainname[:{servicename|portnumber|*}]
2286 *
2287 * or
2288 *
2289 *    netaddr/maskbits[:{servicename|portnumber|*}]
2290 *
2291 * Returns -1 on error, 0 if the argument was valid.
2292 */
2293static int
2294allowaddr(char *s)
2295{
2296	char *cp1, *cp2;
2297	struct allowedpeer ap;
2298	struct servent *se;
2299	int masklen = -1;
2300	struct addrinfo hints, *res;
2301	struct in_addr *addrp, *maskp;
2302#ifdef INET6
2303	int i;
2304	u_int32_t *addr6p, *mask6p;
2305#endif
2306	char ip[NI_MAXHOST];
2307
2308#ifdef INET6
2309	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2310#endif
2311		cp1 = s;
2312	if ((cp1 = strrchr(cp1, ':'))) {
2313		/* service/port provided */
2314		*cp1++ = '\0';
2315		if (strlen(cp1) == 1 && *cp1 == '*')
2316			/* any port allowed */
2317			ap.port = 0;
2318		else if ((se = getservbyname(cp1, "udp"))) {
2319			ap.port = ntohs(se->s_port);
2320		} else {
2321			ap.port = strtol(cp1, &cp2, 0);
2322			if (*cp2 != '\0')
2323				return (-1); /* port not numeric */
2324		}
2325	} else {
2326		if ((se = getservbyname("syslog", "udp")))
2327			ap.port = ntohs(se->s_port);
2328		else
2329			/* sanity, should not happen */
2330			ap.port = 514;
2331	}
2332
2333	if ((cp1 = strchr(s, '/')) != NULL &&
2334	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2335		*cp1 = '\0';
2336		if ((masklen = atoi(cp1 + 1)) < 0)
2337			return (-1);
2338	}
2339#ifdef INET6
2340	if (*s == '[') {
2341		cp2 = s + strlen(s) - 1;
2342		if (*cp2 == ']') {
2343			++s;
2344			*cp2 = '\0';
2345		} else {
2346			cp2 = NULL;
2347		}
2348	} else {
2349		cp2 = NULL;
2350	}
2351#endif
2352	memset(&hints, 0, sizeof(hints));
2353	hints.ai_family = PF_UNSPEC;
2354	hints.ai_socktype = SOCK_DGRAM;
2355	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2356	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2357		ap.isnumeric = 1;
2358		memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2359		memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2360		ap.a_mask.ss_family = res->ai_family;
2361		if (res->ai_family == AF_INET) {
2362			ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2363			maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2364			addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2365			if (masklen < 0) {
2366				/* use default netmask */
2367				if (IN_CLASSA(ntohl(addrp->s_addr)))
2368					maskp->s_addr = htonl(IN_CLASSA_NET);
2369				else if (IN_CLASSB(ntohl(addrp->s_addr)))
2370					maskp->s_addr = htonl(IN_CLASSB_NET);
2371				else
2372					maskp->s_addr = htonl(IN_CLASSC_NET);
2373			} else if (masklen <= 32) {
2374				/* convert masklen to netmask */
2375				if (masklen == 0)
2376					maskp->s_addr = 0;
2377				else
2378					maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2379			} else {
2380				freeaddrinfo(res);
2381				return (-1);
2382			}
2383			/* Lose any host bits in the network number. */
2384			addrp->s_addr &= maskp->s_addr;
2385		}
2386#ifdef INET6
2387		else if (res->ai_family == AF_INET6 && masklen <= 128) {
2388			ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2389			if (masklen < 0)
2390				masklen = 128;
2391			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2392			/* convert masklen to netmask */
2393			while (masklen > 0) {
2394				if (masklen < 32) {
2395					*mask6p = htonl(~(0xffffffff >> masklen));
2396					break;
2397				}
2398				*mask6p++ = 0xffffffff;
2399				masklen -= 32;
2400			}
2401			/* Lose any host bits in the network number. */
2402			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2403			addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2404			for (i = 0; i < 4; i++)
2405				addr6p[i] &= mask6p[i];
2406		}
2407#endif
2408		else {
2409			freeaddrinfo(res);
2410			return (-1);
2411		}
2412		freeaddrinfo(res);
2413	} else {
2414		/* arg `s' is domain name */
2415		ap.isnumeric = 0;
2416		ap.a_name = s;
2417		if (cp1)
2418			*cp1 = '/';
2419#ifdef INET6
2420		if (cp2) {
2421			*cp2 = ']';
2422			--s;
2423		}
2424#endif
2425	}
2426
2427	if (Debug) {
2428		printf("allowaddr: rule %d: ", NumAllowed);
2429		if (ap.isnumeric) {
2430			printf("numeric, ");
2431			getnameinfo((struct sockaddr *)&ap.a_addr,
2432				    ((struct sockaddr *)&ap.a_addr)->sa_len,
2433				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2434			printf("addr = %s, ", ip);
2435			getnameinfo((struct sockaddr *)&ap.a_mask,
2436				    ((struct sockaddr *)&ap.a_mask)->sa_len,
2437				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2438			printf("mask = %s; ", ip);
2439		} else {
2440			printf("domainname = %s; ", ap.a_name);
2441		}
2442		printf("port = %d\n", ap.port);
2443	}
2444
2445	if ((AllowedPeers = realloc(AllowedPeers,
2446				    ++NumAllowed * sizeof(struct allowedpeer)))
2447	    == NULL) {
2448		logerror("realloc");
2449		exit(1);
2450	}
2451	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2452	return (0);
2453}
2454
2455/*
2456 * Validate that the remote peer has permission to log to us.
2457 */
2458static int
2459validate(struct sockaddr *sa, const char *hname)
2460{
2461	int i;
2462	size_t l1, l2;
2463	char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2464	struct allowedpeer *ap;
2465	struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2466#ifdef INET6
2467	int j, reject;
2468	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2469#endif
2470	struct addrinfo hints, *res;
2471	u_short sport;
2472
2473	if (NumAllowed == 0)
2474		/* traditional behaviour, allow everything */
2475		return (1);
2476
2477	(void)strlcpy(name, hname, sizeof(name));
2478	memset(&hints, 0, sizeof(hints));
2479	hints.ai_family = PF_UNSPEC;
2480	hints.ai_socktype = SOCK_DGRAM;
2481	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2482	if (getaddrinfo(name, NULL, &hints, &res) == 0)
2483		freeaddrinfo(res);
2484	else if (strchr(name, '.') == NULL) {
2485		strlcat(name, ".", sizeof name);
2486		strlcat(name, LocalDomain, sizeof name);
2487	}
2488	if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2489			NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2490		return (0);	/* for safety, should not occur */
2491	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2492		ip, port, name);
2493	sport = atoi(port);
2494
2495	/* now, walk down the list */
2496	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2497		if (ap->port != 0 && ap->port != sport) {
2498			dprintf("rejected in rule %d due to port mismatch.\n", i);
2499			continue;
2500		}
2501
2502		if (ap->isnumeric) {
2503			if (ap->a_addr.ss_family != sa->sa_family) {
2504				dprintf("rejected in rule %d due to address family mismatch.\n", i);
2505				continue;
2506			}
2507			if (ap->a_addr.ss_family == AF_INET) {
2508				sin4 = (struct sockaddr_in *)sa;
2509				a4p = (struct sockaddr_in *)&ap->a_addr;
2510				m4p = (struct sockaddr_in *)&ap->a_mask;
2511				if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2512				    != a4p->sin_addr.s_addr) {
2513					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2514					continue;
2515				}
2516			}
2517#ifdef INET6
2518			else if (ap->a_addr.ss_family == AF_INET6) {
2519				sin6 = (struct sockaddr_in6 *)sa;
2520				a6p = (struct sockaddr_in6 *)&ap->a_addr;
2521				m6p = (struct sockaddr_in6 *)&ap->a_mask;
2522				if (a6p->sin6_scope_id != 0 &&
2523				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
2524					dprintf("rejected in rule %d due to scope mismatch.\n", i);
2525					continue;
2526				}
2527				reject = 0;
2528				for (j = 0; j < 16; j += 4) {
2529					if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2530					    != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2531						++reject;
2532						break;
2533					}
2534				}
2535				if (reject) {
2536					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2537					continue;
2538				}
2539			}
2540#endif
2541			else
2542				continue;
2543		} else {
2544			cp = ap->a_name;
2545			l1 = strlen(name);
2546			if (*cp == '*') {
2547				/* allow wildmatch */
2548				cp++;
2549				l2 = strlen(cp);
2550				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2551					dprintf("rejected in rule %d due to name mismatch.\n", i);
2552					continue;
2553				}
2554			} else {
2555				/* exact match */
2556				l2 = strlen(cp);
2557				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2558					dprintf("rejected in rule %d due to name mismatch.\n", i);
2559					continue;
2560				}
2561			}
2562		}
2563		dprintf("accepted in rule %d.\n", i);
2564		return (1);	/* hooray! */
2565	}
2566	return (0);
2567}
2568
2569/*
2570 * Fairly similar to popen(3), but returns an open descriptor, as
2571 * opposed to a FILE *.
2572 */
2573static int
2574p_open(const char *prog, pid_t *rpid)
2575{
2576	int pfd[2], nulldesc;
2577	pid_t pid;
2578	sigset_t omask, mask;
2579	char *argv[4]; /* sh -c cmd NULL */
2580	char errmsg[200];
2581
2582	if (pipe(pfd) == -1)
2583		return (-1);
2584	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2585		/* we are royally screwed anyway */
2586		return (-1);
2587
2588	sigemptyset(&mask);
2589	sigaddset(&mask, SIGALRM);
2590	sigaddset(&mask, SIGHUP);
2591	sigprocmask(SIG_BLOCK, &mask, &omask);
2592	switch ((pid = fork())) {
2593	case -1:
2594		sigprocmask(SIG_SETMASK, &omask, 0);
2595		close(nulldesc);
2596		return (-1);
2597
2598	case 0:
2599		argv[0] = strdup("sh");
2600		argv[1] = strdup("-c");
2601		argv[2] = strdup(prog);
2602		argv[3] = NULL;
2603		if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2604			logerror("strdup");
2605			exit(1);
2606		}
2607
2608		alarm(0);
2609		(void)setsid();	/* Avoid catching SIGHUPs. */
2610
2611		/*
2612		 * Throw away pending signals, and reset signal
2613		 * behaviour to standard values.
2614		 */
2615		signal(SIGALRM, SIG_IGN);
2616		signal(SIGHUP, SIG_IGN);
2617		sigprocmask(SIG_SETMASK, &omask, 0);
2618		signal(SIGPIPE, SIG_DFL);
2619		signal(SIGQUIT, SIG_DFL);
2620		signal(SIGALRM, SIG_DFL);
2621		signal(SIGHUP, SIG_DFL);
2622
2623		dup2(pfd[0], STDIN_FILENO);
2624		dup2(nulldesc, STDOUT_FILENO);
2625		dup2(nulldesc, STDERR_FILENO);
2626		closefrom(3);
2627
2628		(void)execvp(_PATH_BSHELL, argv);
2629		_exit(255);
2630	}
2631
2632	sigprocmask(SIG_SETMASK, &omask, 0);
2633	close(nulldesc);
2634	close(pfd[0]);
2635	/*
2636	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
2637	 * supposed to get an EWOULDBLOCK on writev(2), which is
2638	 * caught by the logic above anyway, which will in turn close
2639	 * the pipe, and fork a new logging subprocess if necessary.
2640	 * The stale subprocess will be killed some time later unless
2641	 * it terminated itself due to closing its input pipe (so we
2642	 * get rid of really dead puppies).
2643	 */
2644	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2645		/* This is bad. */
2646		(void)snprintf(errmsg, sizeof errmsg,
2647			       "Warning: cannot change pipe to PID %d to "
2648			       "non-blocking behaviour.",
2649			       (int)pid);
2650		logerror(errmsg);
2651	}
2652	*rpid = pid;
2653	return (pfd[1]);
2654}
2655
2656static void
2657deadq_enter(pid_t pid, const char *name)
2658{
2659	dq_t p;
2660	int status;
2661
2662	if (pid == 0)
2663		return;
2664	/*
2665	 * Be paranoid, if we can't signal the process, don't enter it
2666	 * into the dead queue (perhaps it's already dead).  If possible,
2667	 * we try to fetch and log the child's status.
2668	 */
2669	if (kill(pid, 0) != 0) {
2670		if (waitpid(pid, &status, WNOHANG) > 0)
2671			log_deadchild(pid, status, name);
2672		return;
2673	}
2674
2675	p = malloc(sizeof(struct deadq_entry));
2676	if (p == NULL) {
2677		logerror("malloc");
2678		exit(1);
2679	}
2680
2681	p->dq_pid = pid;
2682	p->dq_timeout = DQ_TIMO_INIT;
2683	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2684}
2685
2686static int
2687deadq_remove(pid_t pid)
2688{
2689	dq_t q;
2690
2691	TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2692		if (q->dq_pid == pid) {
2693			TAILQ_REMOVE(&deadq_head, q, dq_entries);
2694				free(q);
2695				return (1);
2696		}
2697	}
2698
2699	return (0);
2700}
2701
2702static void
2703log_deadchild(pid_t pid, int status, const char *name)
2704{
2705	int code;
2706	char buf[256];
2707	const char *reason;
2708
2709	errno = 0; /* Keep strerror() stuff out of logerror messages. */
2710	if (WIFSIGNALED(status)) {
2711		reason = "due to signal";
2712		code = WTERMSIG(status);
2713	} else {
2714		reason = "with status";
2715		code = WEXITSTATUS(status);
2716		if (code == 0)
2717			return;
2718	}
2719	(void)snprintf(buf, sizeof buf,
2720		       "Logging subprocess %d (%s) exited %s %d.",
2721		       pid, name, reason, code);
2722	logerror(buf);
2723}
2724
2725static int *
2726socksetup(int af, char *bindhostname)
2727{
2728	struct addrinfo hints, *res, *r;
2729	const char *bindservice;
2730	char *cp;
2731	int error, maxs, *s, *socks;
2732
2733	/*
2734	 * We have to handle this case for backwards compatibility:
2735	 * If there are two (or more) colons but no '[' and ']',
2736	 * assume this is an inet6 address without a service.
2737	 */
2738	bindservice = "syslog";
2739	if (bindhostname != NULL) {
2740#ifdef INET6
2741		if (*bindhostname == '[' &&
2742		    (cp = strchr(bindhostname + 1, ']')) != NULL) {
2743			++bindhostname;
2744			*cp = '\0';
2745			if (cp[1] == ':' && cp[2] != '\0')
2746				bindservice = cp + 2;
2747		} else {
2748#endif
2749			cp = strchr(bindhostname, ':');
2750			if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2751				*cp = '\0';
2752				if (cp[1] != '\0')
2753					bindservice = cp + 1;
2754				if (cp == bindhostname)
2755					bindhostname = NULL;
2756			}
2757#ifdef INET6
2758		}
2759#endif
2760	}
2761
2762	memset(&hints, 0, sizeof(hints));
2763	hints.ai_flags = AI_PASSIVE;
2764	hints.ai_family = af;
2765	hints.ai_socktype = SOCK_DGRAM;
2766	error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2767	if (error) {
2768		logerror(gai_strerror(error));
2769		errno = 0;
2770		die(0);
2771	}
2772
2773	/* Count max number of sockets we may open */
2774	for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2775	socks = malloc((maxs+1) * sizeof(int));
2776	if (socks == NULL) {
2777		logerror("couldn't allocate memory for sockets");
2778		die(0);
2779	}
2780
2781	*socks = 0;   /* num of sockets counter at start of array */
2782	s = socks + 1;
2783	for (r = res; r; r = r->ai_next) {
2784		int on = 1;
2785		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2786		if (*s < 0) {
2787			logerror("socket");
2788			continue;
2789		}
2790#ifdef INET6
2791		if (r->ai_family == AF_INET6) {
2792			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2793				       (char *)&on, sizeof (on)) < 0) {
2794				logerror("setsockopt");
2795				close(*s);
2796				continue;
2797			}
2798		}
2799#endif
2800		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2801			       (char *)&on, sizeof (on)) < 0) {
2802			logerror("setsockopt");
2803			close(*s);
2804			continue;
2805		}
2806		/*
2807		 * RFC 3164 recommends that client side message
2808		 * should come from the privileged syslogd port.
2809		 *
2810		 * If the system administrator choose not to obey
2811		 * this, we can skip the bind() step so that the
2812		 * system will choose a port for us.
2813		 */
2814		if (!NoBind) {
2815			if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2816				logerror("bind");
2817				close(*s);
2818				continue;
2819			}
2820
2821			if (!SecureMode)
2822				increase_rcvbuf(*s);
2823		}
2824
2825		(*socks)++;
2826		s++;
2827	}
2828
2829	if (*socks == 0) {
2830		free(socks);
2831		if (Debug)
2832			return (NULL);
2833		else
2834			die(0);
2835	}
2836	if (res)
2837		freeaddrinfo(res);
2838
2839	return (socks);
2840}
2841
2842static void
2843increase_rcvbuf(int fd)
2844{
2845	socklen_t len, slen;
2846
2847	slen = sizeof(len);
2848
2849	if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2850		if (len < RCVBUF_MINSIZE) {
2851			len = RCVBUF_MINSIZE;
2852			setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));
2853		}
2854	}
2855}
2856