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