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