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