xref: /netbsd-src/usr.sbin/syslogd/syslogd.c (revision 4472dbe5e3bd91ef2540bada7a7ca7384627ff9b)
1 /*	$NetBSD: syslogd.c,v 1.34 2000/02/18 09:44:46 lukem Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1988, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n");
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
45 #else
46 __RCSID("$NetBSD: syslogd.c,v 1.34 2000/02/18 09:44:46 lukem Exp $");
47 #endif
48 #endif /* not lint */
49 
50 /*
51  *  syslogd -- log system messages
52  *
53  * This program implements a system log. It takes a series of lines.
54  * Each line may have a priority, signified as "<n>" as
55  * the first characters of the line.  If this is
56  * not present, a default priority is used.
57  *
58  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
59  * cause it to reread its configuration file.
60  *
61  * Defined Constants:
62  *
63  * MAXLINE -- the maximimum line length that can be handled.
64  * DEFUPRI -- the default priority for user messages
65  * DEFSPRI -- the default priority for kernel messages
66  *
67  * Author: Eric Allman
68  * extensive changes by Ralph Campbell
69  * more extensive changes by Eric Allman (again)
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		/* timeout 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/msgbuf.h>
85 #include <sys/uio.h>
86 #include <sys/poll.h>
87 #include <sys/un.h>
88 #include <sys/time.h>
89 #include <sys/resource.h>
90 #include <sys/sysctl.h>
91 
92 #include <netinet/in.h>
93 #include <netdb.h>
94 #include <arpa/inet.h>
95 
96 #include <ctype.h>
97 #include <errno.h>
98 #include <fcntl.h>
99 #include <setjmp.h>
100 #include <signal.h>
101 #include <stdio.h>
102 #include <stdlib.h>
103 #include <string.h>
104 #include <unistd.h>
105 #include <utmp.h>
106 #include <util.h>
107 #include "pathnames.h"
108 
109 #define SYSLOG_NAMES
110 #include <sys/syslog.h>
111 
112 char	*ConfFile = _PATH_LOGCONF;
113 char	ctty[] = _PATH_CONSOLE;
114 
115 #define FDMASK(fd)	(1 << (fd))
116 
117 #define	dprintf		if (Debug) printf
118 
119 #define MAXUNAMES	20	/* maximum number of user names */
120 
121 /*
122  * Flags to logmsg().
123  */
124 
125 #define IGN_CONS	0x001	/* don't print on console */
126 #define SYNC_FILE	0x002	/* do fsync on file after printing */
127 #define ADDDATE		0x004	/* add a date to the message */
128 #define MARK		0x008	/* this message is a mark */
129 
130 /*
131  * This structure represents the files that will have log
132  * copies printed.
133  */
134 
135 struct filed {
136 	struct	filed *f_next;		/* next in linked list */
137 	short	f_type;			/* entry type, see below */
138 	short	f_file;			/* file descriptor */
139 	time_t	f_time;			/* time this was last written */
140 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
141 	union {
142 		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
143 		struct {
144 			char	f_hname[MAXHOSTNAMELEN+1];
145 			struct	addrinfo *f_addr;
146 		} f_forw;		/* forwarding address */
147 		char	f_fname[MAXPATHLEN];
148 	} f_un;
149 	char	f_prevline[MAXSVLINE];		/* last message logged */
150 	char	f_lasttime[16];			/* time of last occurrence */
151 	char	f_prevhost[MAXHOSTNAMELEN+1];	/* host from which recd. */
152 	int	f_prevpri;			/* pri of f_prevline */
153 	int	f_prevlen;			/* length of f_prevline */
154 	int	f_prevcount;			/* repetition cnt of prevline */
155 	int	f_repeatcount;			/* number of "repeated" msgs */
156 };
157 
158 /*
159  * Intervals at which we flush out "message repeated" messages,
160  * in seconds after previous message is logged.  After each flush,
161  * we move to the next interval until we reach the largest.
162  */
163 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
164 #define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
165 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
166 #define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
167 				 (f)->f_repeatcount = MAXREPEAT; \
168 			}
169 
170 /* values for f_type */
171 #define F_UNUSED	0		/* unused entry */
172 #define F_FILE		1		/* regular file */
173 #define F_TTY		2		/* terminal */
174 #define F_CONSOLE	3		/* console terminal */
175 #define F_FORW		4		/* remote machine */
176 #define F_USERS		5		/* list of users */
177 #define F_WALL		6		/* everyone logged on */
178 
179 char	*TypeNames[7] = {
180 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
181 	"FORW",		"USERS",	"WALL"
182 };
183 
184 struct	filed *Files;
185 struct	filed consfile;
186 
187 int	Debug;			/* debug flag */
188 char	LocalHostName[MAXHOSTNAMELEN+1];	/* our hostname */
189 char	*LocalDomain;		/* our local domain name */
190 int	*finet;			/* Internet datagram sockets */
191 int	Initialized = 0;	/* set when we have initialized ourselves */
192 int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
193 int	MarkSeq = 0;		/* mark sequence number */
194 int	SecureMode = 0;		/* when true, speak only unix domain socks */
195 char	**LogPaths;		/* array of pathnames to read messages from */
196 
197 void	cfline __P((char *, struct filed *));
198 char   *cvthname __P((struct sockaddr_storage *));
199 int	decode __P((const char *, CODE *));
200 void	die __P((int));
201 void	domark __P((int));
202 void	fprintlog __P((struct filed *, int, char *));
203 int	getmsgbufsize __P((void));
204 int*	socksetup __P((int));
205 void	init __P((int));
206 void	logerror __P((char *));
207 void	logmsg __P((int, char *, char *, int));
208 void	printline __P((char *, char *));
209 void	printsys __P((char *));
210 void	reapchild __P((int));
211 void	usage __P((void));
212 void	wallmsg __P((struct filed *, struct iovec *));
213 int	main __P((int, char *[]));
214 void	logpath_add __P((char ***, int *, int *, char *));
215 void	logpath_fileadd __P((char ***, int *, int *, char *));
216 
217 int
218 main(argc, argv)
219 	int argc;
220 	char *argv[];
221 {
222 	int ch, *funix, i, j, fklog, len, linesize;
223 	int *nfinetix, nfklogix, nfunixbaseix, nfds;
224 	int funixsize = 0, funixmaxsize = 0;
225 	struct sockaddr_un sunx, fromunix;
226 	struct sockaddr_storage frominet;
227 	char *p, *line, **pp;
228 	struct pollfd *readfds;
229 
230 	while ((ch = getopt(argc, argv, "dsf:m:p:P:")) != -1)
231 		switch(ch) {
232 		case 'd':		/* debug */
233 			Debug++;
234 			break;
235 		case 'f':		/* configuration file */
236 			ConfFile = optarg;
237 			break;
238 		case 'm':		/* mark interval */
239 			MarkInterval = atoi(optarg) * 60;
240 			break;
241 		case 'p':		/* path */
242 			logpath_add(&LogPaths, &funixsize,
243 			    &funixmaxsize, optarg);
244 			break;
245 		case 'P':		/* file of paths */
246 			logpath_fileadd(&LogPaths, &funixsize,
247 			    &funixmaxsize, optarg);
248 			break;
249 		case 's':		/* no network mode */
250 			SecureMode++;
251 			break;
252 		case '?':
253 		default:
254 			usage();
255 		}
256 	if ((argc -= optind) != 0)
257 		usage();
258 
259 	if (!Debug)
260 		(void)daemon(0, 0);
261 	else
262 		setlinebuf(stdout);
263 
264 	consfile.f_type = F_CONSOLE;
265 	(void)strcpy(consfile.f_un.f_fname, ctty);
266 	(void)gethostname(LocalHostName, sizeof(LocalHostName));
267 	LocalHostName[sizeof(LocalHostName) - 1] = '\0';
268 	if ((p = strchr(LocalHostName, '.')) != NULL) {
269 		*p++ = '\0';
270 		LocalDomain = p;
271 	} else
272 		LocalDomain = "";
273 	linesize = getmsgbufsize();
274 	if (linesize < MAXLINE)
275 		linesize = MAXLINE;
276 	linesize++;
277 	line = malloc(linesize);
278 	if (line == NULL) {
279 		logerror("couldn't allocate line buffer");
280 		die(0);
281 	}
282 	(void)signal(SIGTERM, die);
283 	(void)signal(SIGINT, Debug ? die : SIG_IGN);
284 	(void)signal(SIGQUIT, Debug ? die : SIG_IGN);
285 	(void)signal(SIGCHLD, reapchild);
286 	(void)signal(SIGALRM, domark);
287 	(void)alarm(TIMERINTVL);
288 
289 #ifndef SUN_LEN
290 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
291 #endif
292 	if (funixsize == 0)
293 		logpath_add(&LogPaths, &funixsize,
294 		    &funixmaxsize, _PATH_LOG);
295 	funix = (int *)malloc(sizeof(int) * funixsize);
296 	if (funix == NULL) {
297 		logerror("couldn't allocate funix descriptors");
298 		die(0);
299 	}
300 	for (j = 0, pp = LogPaths; *pp; pp++, j++) {
301 		dprintf("making unix dgram socket %s\n", *pp);
302 		unlink(*pp);
303 		memset(&sunx, 0, sizeof(sunx));
304 		sunx.sun_family = AF_LOCAL;
305 		(void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
306 		funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
307 		if (funix[j] < 0 || bind(funix[j],
308 		    (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
309 		    chmod(*pp, 0666) < 0) {
310 			int serrno = errno;
311 			(void)snprintf(line, sizeof line,
312 			    "cannot create %s", *pp);
313 			errno = serrno;
314 			logerror(line);
315 			errno = serrno;
316 			dprintf("cannot create %s (%d)\n", *pp, errno);
317 			die(0);
318 		}
319 		dprintf("listening on unix dgram socket %s\n", *pp);
320 	}
321 
322 	finet = socksetup(PF_UNSPEC);
323 	if (finet) {
324 		if (SecureMode) {
325 			for (j = 0; j < *finet; j++) {
326 				if (shutdown(finet[j+1], SHUT_RD) < 0) {
327 					logerror("shutdown");
328 					die(0);
329 				}
330 			}
331 		} else
332 			dprintf("listening on inet and/or inet6 socket\n");
333 		dprintf("sending on inet and/or inet6 socket\n");
334 	}
335 
336 	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
337 		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
338 	} else {
339 		dprintf("listening on kernel log %s\n", _PATH_KLOG);
340 	}
341 
342 	/* tuck my process id away, if i'm not in debug mode */
343 	if (Debug == 0)
344 		pidfile(NULL);
345 
346 	dprintf("off & running....\n");
347 
348 	init(0);
349 	(void)signal(SIGHUP, init);
350 
351 	/* setup pollfd set. */
352 	readfds = (struct pollfd *)malloc(sizeof(struct pollfd) *
353 			(funixsize + (finet ? *finet : 0) + 1));
354 	if (readfds == NULL) {
355 		logerror("couldn't allocate pollfds");
356 		die(0);
357 	}
358 	nfds = 0;
359 	if (fklog >= 0) {
360 		nfklogix = nfds++;
361 		readfds[nfklogix].fd = fklog;
362 		readfds[nfklogix].events = POLLIN | POLLPRI;
363 	}
364 	if (finet && !SecureMode) {
365 		nfinetix = malloc(*finet * sizeof(*nfinetix));
366 		for (j = 0; j < *finet; j++) {
367 			nfinetix[j] = nfds++;
368 			readfds[nfinetix[j]].fd = finet[j+1];
369 			readfds[nfinetix[j]].events = POLLIN | POLLPRI;
370 		}
371 	}
372 	nfunixbaseix = nfds;
373 	for (j = 0, pp = LogPaths; *pp; pp++) {
374 		readfds[nfds].fd = funix[j++];
375 		readfds[nfds++].events = POLLIN | POLLPRI;
376 	}
377 
378 	for (;;) {
379 		int rv;
380 
381 		rv = poll(readfds, nfds, INFTIM);
382 		if (rv == 0)
383 			continue;
384 		if (rv < 0) {
385 			if (errno != EINTR)
386 				logerror("poll");
387 			continue;
388 		}
389 		dprintf("got a message (%d)\n", rv);
390 		if (fklog >= 0 &&
391 		    (readfds[nfklogix].revents & (POLLIN | POLLPRI))) {
392 			dprintf("kernel log active\n");
393 			i = read(fklog, line, linesize - 1);
394 			if (i > 0) {
395 				line[i] = '\0';
396 				printsys(line);
397 			} else if (i < 0 && errno != EINTR) {
398 				logerror("klog");
399 				fklog = -1;
400 			}
401 		}
402 		for (j = 0, pp = LogPaths; *pp; pp++, j++) {
403 			if ((readfds[nfunixbaseix + j].revents &
404 			    (POLLIN | POLLPRI)) == 0)
405 				continue;
406 
407 			dprintf("unix socket (%s) active\n", *pp);
408 			len = sizeof(fromunix);
409 			i = recvfrom(funix[j], line, MAXLINE, 0,
410 			    (struct sockaddr *)&fromunix, &len);
411 			if (i > 0) {
412 				line[i] = '\0';
413 				printline(LocalHostName, line);
414 			} else if (i < 0 && errno != EINTR) {
415 				char buf[MAXPATHLEN];
416 				int serrno = errno;
417 
418 				(void)snprintf(buf, sizeof buf,
419 				    "recvfrom unix %s", *pp);
420 				errno = serrno;
421 				logerror(buf);
422 			}
423 		}
424 		if (finet && !SecureMode) {
425 			for (j = 0; j < *finet; j++) {
426 		    		if (readfds[nfinetix[j]].revents &
427 				    (POLLIN | POLLPRI)) {
428 					dprintf("inet socket active\n");
429 					len = sizeof(frominet);
430 					i = recvfrom(finet[j+1], line, MAXLINE,
431 					    0, (struct sockaddr *)&frominet,
432 					    &len);
433 					if (i > 0) {
434 						line[i] = '\0';
435 						printline(cvthname(&frominet),
436 						    line);
437 					} else if (i < 0 && errno != EINTR)
438 						logerror("recvfrom inet");
439 				}
440 			}
441 		}
442 	}
443 }
444 
445 void
446 usage()
447 {
448 	extern char *__progname;
449 
450 	(void)fprintf(stderr,
451 "usage: %s [-f conffile] [-m markinterval] [-p logpath1] [-p logpath2 ..]\n",
452 	    __progname);
453 	exit(1);
454 }
455 
456 /*
457  * given a pointer to an array of char *'s, a pointer to it's current
458  * size and current allocated max size, and a new char * to add, add
459  * it, update everything as necessary, possibly allocating a new array
460  */
461 void
462 logpath_add(lp, szp, maxszp, new)
463 	char ***lp;
464 	int *szp;
465 	int *maxszp;
466 	char *new;
467 {
468 
469 	dprintf("adding %s to the %p logpath list\n", new, *lp);
470 	if (*szp == *maxszp) {
471 		if (*maxszp == 0) {
472 			*maxszp = 4;	/* start of with enough for now */
473 			*lp = NULL;
474 		}
475 		else
476 			*maxszp *= 2;
477 		*lp = realloc(*lp, sizeof(char *) * (*maxszp + 1));
478 		if (*lp == NULL) {
479 			logerror("couldn't allocate line buffer");
480 			die(0);
481 		}
482 	}
483 	(*lp)[(*szp)++] = new;
484 	(*lp)[(*szp)] = NULL;		/* always keep it NULL terminated */
485 }
486 
487 /* do a file of log sockets */
488 void
489 logpath_fileadd(lp, szp, maxszp, file)
490 	char ***lp;
491 	int *szp;
492 	int *maxszp;
493 	char *file;
494 {
495 	FILE *fp;
496 	char *line;
497 	size_t len;
498 
499 	fp = fopen(file, "r");
500 	if (fp == NULL) {
501 		int serrno = errno;
502 
503 		dprintf("can't open %s (%d)\n", file, errno);
504 		errno = serrno;
505 		logerror("could not open socket file list");
506 		die(0);
507 	}
508 
509 	while ((line = fgetln(fp, &len))) {
510 		line[len - 1] = 0;
511 		logpath_add(lp, szp, maxszp, line);
512 	}
513 	fclose(fp);
514 }
515 
516 /*
517  * Take a raw input line, decode the message, and print the message
518  * on the appropriate log files.
519  */
520 void
521 printline(hname, msg)
522 	char *hname;
523 	char *msg;
524 {
525 	int c, pri;
526 	char *p, *q, line[MAXLINE + 1];
527 
528 	/* test for special codes */
529 	pri = DEFUPRI;
530 	p = msg;
531 	if (*p == '<') {
532 		pri = 0;
533 		while (isdigit(*++p))
534 			pri = 10 * pri + (*p - '0');
535 		if (*p == '>')
536 			++p;
537 	}
538 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
539 		pri = DEFUPRI;
540 
541 	/* don't allow users to log kernel messages */
542 	if (LOG_FAC(pri) == LOG_KERN)
543 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
544 
545 	q = line;
546 
547 	while ((c = *p++ & 0177) != '\0' &&
548 	    q < &line[sizeof(line) - 1])
549 		if (iscntrl(c))
550 			if (c == '\n')
551 				*q++ = ' ';
552 			else if (c == '\t')
553 				*q++ = '\t';
554 			else {
555 				*q++ = '^';
556 				*q++ = c ^ 0100;
557 			}
558 		else
559 			*q++ = c;
560 	*q = '\0';
561 
562 	logmsg(pri, line, hname, 0);
563 }
564 
565 /*
566  * Take a raw input line from /dev/klog, split and format similar to syslog().
567  */
568 void
569 printsys(msg)
570 	char *msg;
571 {
572 	int c, pri, flags;
573 	char *lp, *p, *q, line[MAXLINE + 1];
574 
575 	(void)strcpy(line, _PATH_UNIX);
576 	(void)strcat(line, ": ");
577 	lp = line + strlen(line);
578 	for (p = msg; *p != '\0'; ) {
579 		flags = SYNC_FILE | ADDDATE;	/* fsync file after write */
580 		pri = DEFSPRI;
581 		if (*p == '<') {
582 			pri = 0;
583 			while (isdigit(*++p))
584 				pri = 10 * pri + (*p - '0');
585 			if (*p == '>')
586 				++p;
587 		} else {
588 			/* kernel printf's come out on console */
589 			flags |= IGN_CONS;
590 		}
591 		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
592 			pri = DEFSPRI;
593 		q = lp;
594 		while (*p != '\0' && (c = *p++) != '\n' &&
595 		    q < &line[MAXLINE])
596 			*q++ = c;
597 		*q = '\0';
598 		logmsg(pri, line, LocalHostName, flags);
599 	}
600 }
601 
602 time_t	now;
603 
604 /*
605  * Log a message to the appropriate log files, users, etc. based on
606  * the priority.
607  */
608 void
609 logmsg(pri, msg, from, flags)
610 	int pri;
611 	char *msg, *from;
612 	int flags;
613 {
614 	struct filed *f;
615 	int fac, msglen, omask, prilev;
616 	char *timestamp;
617 
618 	dprintf("logmsg: pri 0%o, flags 0x%x, from %s, msg %s\n",
619 	    pri, flags, from, msg);
620 
621 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
622 
623 	/*
624 	 * Check to see if msg looks non-standard.
625 	 */
626 	msglen = strlen(msg);
627 	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
628 	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
629 		flags |= ADDDATE;
630 
631 	(void)time(&now);
632 	if (flags & ADDDATE)
633 		timestamp = ctime(&now) + 4;
634 	else {
635 		timestamp = msg;
636 		msg += 16;
637 		msglen -= 16;
638 	}
639 
640 	/* extract facility and priority level */
641 	if (flags & MARK)
642 		fac = LOG_NFACILITIES;
643 	else
644 		fac = LOG_FAC(pri);
645 	prilev = LOG_PRI(pri);
646 
647 	/* log the message to the particular outputs */
648 	if (!Initialized) {
649 		f = &consfile;
650 		f->f_file = open(ctty, O_WRONLY, 0);
651 
652 		if (f->f_file >= 0) {
653 			fprintlog(f, flags, msg);
654 			(void)close(f->f_file);
655 		}
656 		(void)sigsetmask(omask);
657 		return;
658 	}
659 	for (f = Files; f; f = f->f_next) {
660 		/* skip messages that are incorrect priority */
661 		if (f->f_pmask[fac] < prilev ||
662 		    f->f_pmask[fac] == INTERNAL_NOPRI)
663 			continue;
664 
665 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
666 			continue;
667 
668 		/* don't output marks to recently written files */
669 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
670 			continue;
671 
672 		/*
673 		 * suppress duplicate lines to this file
674 		 */
675 		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
676 		    !strcmp(msg, f->f_prevline) &&
677 		    !strcmp(from, f->f_prevhost)) {
678 			(void)strncpy(f->f_lasttime, timestamp, 15);
679 			f->f_prevcount++;
680 			dprintf("msg repeated %d times, %ld sec of %d\n",
681 			    f->f_prevcount, (long)(now - f->f_time),
682 			    repeatinterval[f->f_repeatcount]);
683 			/*
684 			 * If domark would have logged this by now,
685 			 * flush it now (so we don't hold isolated messages),
686 			 * but back off so we'll flush less often
687 			 * in the future.
688 			 */
689 			if (now > REPEATTIME(f)) {
690 				fprintlog(f, flags, (char *)NULL);
691 				BACKOFF(f);
692 			}
693 		} else {
694 			/* new line, save it */
695 			if (f->f_prevcount)
696 				fprintlog(f, 0, (char *)NULL);
697 			f->f_repeatcount = 0;
698 			f->f_prevpri = pri;
699 			(void)strncpy(f->f_lasttime, timestamp, 15);
700 			(void)strncpy(f->f_prevhost, from,
701 					sizeof(f->f_prevhost));
702 			if (msglen < MAXSVLINE) {
703 				f->f_prevlen = msglen;
704 				(void)strcpy(f->f_prevline, msg);
705 				fprintlog(f, flags, (char *)NULL);
706 			} else {
707 				f->f_prevline[0] = 0;
708 				f->f_prevlen = 0;
709 				fprintlog(f, flags, msg);
710 			}
711 		}
712 	}
713 	(void)sigsetmask(omask);
714 }
715 
716 void
717 fprintlog(f, flags, msg)
718 	struct filed *f;
719 	int flags;
720 	char *msg;
721 {
722 	struct iovec iov[6];
723 	struct iovec *v;
724 	struct addrinfo *r;
725 	int j, l, lsent;
726 	char line[MAXLINE + 1], repbuf[80], greetings[200];
727 
728 	v = iov;
729 	if (f->f_type == F_WALL) {
730 		v->iov_base = greetings;
731 		v->iov_len = snprintf(greetings, sizeof greetings,
732 		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
733 		    f->f_prevhost, ctime(&now));
734 		v++;
735 		v->iov_base = "";
736 		v->iov_len = 0;
737 		v++;
738 	} else {
739 		v->iov_base = f->f_lasttime;
740 		v->iov_len = 15;
741 		v++;
742 		v->iov_base = " ";
743 		v->iov_len = 1;
744 		v++;
745 	}
746 	v->iov_base = f->f_prevhost;
747 	v->iov_len = strlen(v->iov_base);
748 	v++;
749 	v->iov_base = " ";
750 	v->iov_len = 1;
751 	v++;
752 
753 	if (msg) {
754 		v->iov_base = msg;
755 		v->iov_len = strlen(msg);
756 	} else if (f->f_prevcount > 1) {
757 		v->iov_base = repbuf;
758 		v->iov_len = snprintf(repbuf, sizeof repbuf,
759 		    "last message repeated %d times", f->f_prevcount);
760 	} else {
761 		v->iov_base = f->f_prevline;
762 		v->iov_len = f->f_prevlen;
763 	}
764 	v++;
765 
766 	dprintf("Logging to %s", TypeNames[f->f_type]);
767 	f->f_time = now;
768 
769 	switch (f->f_type) {
770 	case F_UNUSED:
771 		dprintf("\n");
772 		break;
773 
774 	case F_FORW:
775 		dprintf(" %s\n", f->f_un.f_forw.f_hname);
776 			/*
777 			 * check for local vs remote messages
778 			 * (from FreeBSD PR#bin/7055)
779 			 */
780 		if (strcmp(f->f_prevhost, LocalHostName)) {
781 			l = snprintf(line, sizeof(line) - 1,
782 				     "<%d>%.15s [%s]: %s",
783 				     f->f_prevpri, (char *) iov[0].iov_base,
784 				     f->f_prevhost, (char *) iov[4].iov_base);
785 		} else {
786 			l = snprintf(line, sizeof(line) - 1, "<%d>%.15s %s",
787 				     f->f_prevpri, (char *) iov[0].iov_base,
788 				     (char *) iov[4].iov_base);
789 		}
790 		if (l > MAXLINE)
791 			l = MAXLINE;
792 		if (finet) {
793 			for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
794 				for (j = 0; j < *finet; j++) {
795 #if 0
796 					/*
797 					 * should we check AF first, or just
798 					 * trial and error? FWD
799 					 */
800 					if (r->ai_family ==
801 					    address_family_of(finet[j+1]))
802 #endif
803 					lsent = sendto(finet[j+1], line, l, 0,
804 					    r->ai_addr, r->ai_addrlen);
805 					if (lsent == l)
806 						break;
807 				}
808 			}
809 			if (lsent != l) {
810 				f->f_type = F_UNUSED;
811 				logerror("sendto");
812 			}
813 		}
814 		break;
815 
816 	case F_CONSOLE:
817 		if (flags & IGN_CONS) {
818 			dprintf(" (ignored)\n");
819 			break;
820 		}
821 		/* FALLTHROUGH */
822 
823 	case F_TTY:
824 	case F_FILE:
825 		dprintf(" %s\n", f->f_un.f_fname);
826 		if (f->f_type != F_FILE) {
827 			v->iov_base = "\r\n";
828 			v->iov_len = 2;
829 		} else {
830 			v->iov_base = "\n";
831 			v->iov_len = 1;
832 		}
833 	again:
834 		if (writev(f->f_file, iov, 6) < 0) {
835 			int e = errno;
836 			(void)close(f->f_file);
837 			/*
838 			 * Check for errors on TTY's due to loss of tty
839 			 */
840 			if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
841 				f->f_file = open(f->f_un.f_fname,
842 				    O_WRONLY|O_APPEND, 0);
843 				if (f->f_file < 0) {
844 					f->f_type = F_UNUSED;
845 					logerror(f->f_un.f_fname);
846 				} else
847 					goto again;
848 			} else {
849 				f->f_type = F_UNUSED;
850 				errno = e;
851 				logerror(f->f_un.f_fname);
852 			}
853 		} else if (flags & SYNC_FILE)
854 			(void)fsync(f->f_file);
855 		break;
856 
857 	case F_USERS:
858 	case F_WALL:
859 		dprintf("\n");
860 		v->iov_base = "\r\n";
861 		v->iov_len = 2;
862 		wallmsg(f, iov);
863 		break;
864 	}
865 	f->f_prevcount = 0;
866 }
867 
868 /*
869  *  WALLMSG -- Write a message to the world at large
870  *
871  *	Write the specified message to either the entire
872  *	world, or a list of approved users.
873  */
874 void
875 wallmsg(f, iov)
876 	struct filed *f;
877 	struct iovec *iov;
878 {
879 	static int reenter;			/* avoid calling ourselves */
880 	FILE *uf;
881 	struct utmp ut;
882 	int i;
883 	char *p;
884 	char line[sizeof(ut.ut_line) + 1];
885 
886 	if (reenter++)
887 		return;
888 	if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
889 		logerror(_PATH_UTMP);
890 		reenter = 0;
891 		return;
892 	}
893 	/* NOSTRICT */
894 	while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
895 		if (ut.ut_name[0] == '\0')
896 			continue;
897 		strncpy(line, ut.ut_line, sizeof(ut.ut_line));
898 		line[sizeof(ut.ut_line)] = '\0';
899 		if (f->f_type == F_WALL) {
900 			if ((p = ttymsg(iov, 6, line, TTYMSGTIME)) != NULL) {
901 				errno = 0;	/* already in msg */
902 				logerror(p);
903 			}
904 			continue;
905 		}
906 		/* should we send the message to this user? */
907 		for (i = 0; i < MAXUNAMES; i++) {
908 			if (!f->f_un.f_uname[i][0])
909 				break;
910 			if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
911 			    UT_NAMESIZE)) {
912 				if ((p = ttymsg(iov, 6, line, TTYMSGTIME))
913 								!= NULL) {
914 					errno = 0;	/* already in msg */
915 					logerror(p);
916 				}
917 				break;
918 			}
919 		}
920 	}
921 	(void)fclose(uf);
922 	reenter = 0;
923 }
924 
925 void
926 reapchild(signo)
927 	int signo;
928 {
929 	union wait status;
930 
931 	while (wait3((int *)&status, WNOHANG, (struct rusage *)NULL) > 0)
932 		;
933 }
934 
935 /*
936  * Return a printable representation of a host address.
937  */
938 char *
939 cvthname(f)
940 	struct sockaddr_storage *f;
941 {
942 	int error;
943 	char *p;
944 #ifdef KAME_SCOPEID
945 	const int niflag = NI_DGRAM | NI_WITHSCOPEID;
946 #else
947 	const int niflag = NI_DGRAM;
948 #endif
949 	static char host[NI_MAXHOST], ip[NI_MAXHOST];
950 
951 	error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
952 			ip, sizeof ip, NULL, 0, NI_NUMERICHOST|niflag);
953 
954 	dprintf("cvthname(%s)\n", ip);
955 
956 	if (error) {
957 		dprintf("Malformed from address %s\n", gai_strerror(error));
958 		return ("???");
959 	}
960 
961 	error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
962 			host, sizeof host, NULL, 0, niflag);
963 	if (error) {
964 		dprintf("Host name for your address (%s) unknown\n", ip);
965 		return (ip);
966 	}
967 	if ((p = strchr(host, '.')) && strcmp(p + 1, LocalDomain) == 0)
968 		*p = '\0';
969 	return (host);
970 }
971 
972 void
973 domark(signo)
974 	int signo;
975 {
976 	struct filed *f;
977 
978 	now = time((time_t *)NULL);
979 	MarkSeq += TIMERINTVL;
980 	if (MarkSeq >= MarkInterval) {
981 		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
982 		MarkSeq = 0;
983 	}
984 
985 	for (f = Files; f; f = f->f_next) {
986 		if (f->f_prevcount && now >= REPEATTIME(f)) {
987 			dprintf("flush %s: repeated %d times, %d sec.\n",
988 			    TypeNames[f->f_type], f->f_prevcount,
989 			    repeatinterval[f->f_repeatcount]);
990 			fprintlog(f, 0, (char *)NULL);
991 			BACKOFF(f);
992 		}
993 	}
994 	(void)alarm(TIMERINTVL);
995 }
996 
997 /*
998  * Print syslogd errors some place.
999  */
1000 void
1001 logerror(type)
1002 	char *type;
1003 {
1004 	char buf[100];
1005 
1006 	if (errno)
1007 		(void)snprintf(buf,
1008 		    sizeof(buf), "syslogd: %s: %s", type, strerror(errno));
1009 	else
1010 		(void)snprintf(buf, sizeof(buf), "syslogd: %s", type);
1011 	errno = 0;
1012 	dprintf("%s\n", buf);
1013 	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1014 }
1015 
1016 void
1017 die(signo)
1018 	int signo;
1019 {
1020 	struct filed *f;
1021 	char buf[100], **p;
1022 
1023 	for (f = Files; f != NULL; f = f->f_next) {
1024 		/* flush any pending output */
1025 		if (f->f_prevcount)
1026 			fprintlog(f, 0, (char *)NULL);
1027 	}
1028 	if (signo) {
1029 		dprintf("syslogd: exiting on signal %d\n", signo);
1030 		(void)snprintf(buf, sizeof buf, "exiting on signal %d", signo);
1031 		errno = 0;
1032 		logerror(buf);
1033 	}
1034 	for (p = LogPaths; p && *p; p++)
1035 		unlink(*p);
1036 	exit(0);
1037 }
1038 
1039 /*
1040  *  INIT -- Initialize syslogd from configuration table
1041  */
1042 void
1043 init(signo)
1044 	int signo;
1045 {
1046 	int i;
1047 	FILE *cf;
1048 	struct filed *f, *next, **nextp;
1049 	char *p;
1050 	char cline[LINE_MAX];
1051 
1052 	dprintf("init\n");
1053 
1054 	/*
1055 	 *  Close all open log files.
1056 	 */
1057 	Initialized = 0;
1058 	for (f = Files; f != NULL; f = next) {
1059 		/* flush any pending output */
1060 		if (f->f_prevcount)
1061 			fprintlog(f, 0, (char *)NULL);
1062 
1063 		switch (f->f_type) {
1064 		case F_FILE:
1065 		case F_TTY:
1066 		case F_CONSOLE:
1067 			(void)close(f->f_file);
1068 			break;
1069 		}
1070 		next = f->f_next;
1071 		free((char *)f);
1072 	}
1073 	Files = NULL;
1074 	nextp = &Files;
1075 
1076 	/* open the configuration file */
1077 	if ((cf = fopen(ConfFile, "r")) == NULL) {
1078 		dprintf("cannot open %s\n", ConfFile);
1079 		*nextp = (struct filed *)calloc(1, sizeof(*f));
1080 		cfline("*.ERR\t/dev/console", *nextp);
1081 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1082 		cfline("*.PANIC\t*", (*nextp)->f_next);
1083 		Initialized = 1;
1084 		return;
1085 	}
1086 
1087 	/*
1088 	 *  Foreach line in the conf table, open that file.
1089 	 */
1090 	f = NULL;
1091 	while (fgets(cline, sizeof(cline), cf) != NULL) {
1092 		/*
1093 		 * check for end-of-section, comments, strip off trailing
1094 		 * spaces and newline character.
1095 		 */
1096 		for (p = cline; isspace(*p); ++p)
1097 			continue;
1098 		if (*p == '\0' || *p == '#')
1099 			continue;
1100 		for (p = strchr(cline, '\0'); isspace(*--p);)
1101 			continue;
1102 		*++p = '\0';
1103 		f = (struct filed *)calloc(1, sizeof(*f));
1104 		*nextp = f;
1105 		nextp = &f->f_next;
1106 		cfline(cline, f);
1107 	}
1108 
1109 	/* close the configuration file */
1110 	(void)fclose(cf);
1111 
1112 	Initialized = 1;
1113 
1114 	if (Debug) {
1115 		for (f = Files; f; f = f->f_next) {
1116 			for (i = 0; i <= LOG_NFACILITIES; i++)
1117 				if (f->f_pmask[i] == INTERNAL_NOPRI)
1118 					printf("X ");
1119 				else
1120 					printf("%d ", f->f_pmask[i]);
1121 			printf("%s: ", TypeNames[f->f_type]);
1122 			switch (f->f_type) {
1123 			case F_FILE:
1124 			case F_TTY:
1125 			case F_CONSOLE:
1126 				printf("%s", f->f_un.f_fname);
1127 				break;
1128 
1129 			case F_FORW:
1130 				printf("%s", f->f_un.f_forw.f_hname);
1131 				break;
1132 
1133 			case F_USERS:
1134 				for (i = 0;
1135 				    i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1136 					printf("%s, ", f->f_un.f_uname[i]);
1137 				break;
1138 			}
1139 			printf("\n");
1140 		}
1141 	}
1142 
1143 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1144 	dprintf("syslogd: restarted\n");
1145 }
1146 
1147 /*
1148  * Crack a configuration file line
1149  */
1150 void
1151 cfline(line, f)
1152 	char *line;
1153 	struct filed *f;
1154 {
1155 	struct addrinfo hints, *res;
1156 	int    error, i, pri;
1157 	char   *bp, *p, *q;
1158 	char   buf[MAXLINE], ebuf[100];
1159 
1160 	dprintf("cfline(%s)\n", line);
1161 
1162 	errno = 0;	/* keep strerror() stuff out of logerror messages */
1163 
1164 	/* clear out file entry */
1165 	memset(f, 0, sizeof(*f));
1166 	for (i = 0; i <= LOG_NFACILITIES; i++)
1167 		f->f_pmask[i] = INTERNAL_NOPRI;
1168 
1169 	/* scan through the list of selectors */
1170 	for (p = line; *p && *p != '\t';) {
1171 
1172 		/* find the end of this facility name list */
1173 		for (q = p; *q && *q != '\t' && *q++ != '.'; )
1174 			continue;
1175 
1176 		/* collect priority name */
1177 		for (bp = buf; *q && !strchr("\t,;", *q); )
1178 			*bp++ = *q++;
1179 		*bp = '\0';
1180 
1181 		/* skip cruft */
1182 		while (strchr(", ;", *q))
1183 			q++;
1184 
1185 		/* decode priority name */
1186 		if (*buf == '*')
1187 			pri = LOG_PRIMASK + 1;
1188 		else {
1189 			pri = decode(buf, prioritynames);
1190 			if (pri < 0) {
1191 				(void)snprintf(ebuf, sizeof ebuf,
1192 				    "unknown priority name \"%s\"", buf);
1193 				logerror(ebuf);
1194 				return;
1195 			}
1196 		}
1197 
1198 		/* scan facilities */
1199 		while (*p && !strchr("\t.;", *p)) {
1200 			for (bp = buf; *p && !strchr("\t,;.", *p); )
1201 				*bp++ = *p++;
1202 			*bp = '\0';
1203 			if (*buf == '*')
1204 				for (i = 0; i < LOG_NFACILITIES; i++)
1205 					f->f_pmask[i] = pri;
1206 			else {
1207 				i = decode(buf, facilitynames);
1208 				if (i < 0) {
1209 					(void)snprintf(ebuf, sizeof ebuf,
1210 					    "unknown facility name \"%s\"",
1211 					    buf);
1212 					logerror(ebuf);
1213 					return;
1214 				}
1215 				f->f_pmask[i >> 3] = pri;
1216 			}
1217 			while (*p == ',' || *p == ' ')
1218 				p++;
1219 		}
1220 
1221 		p = q;
1222 	}
1223 
1224 	/* skip to action part */
1225 	while (*p == '\t')
1226 		p++;
1227 
1228 	switch (*p)
1229 	{
1230 	case '@':
1231 		if (!finet)
1232 			break;
1233 		(void)strcpy(f->f_un.f_forw.f_hname, ++p);
1234 		memset(&hints, 0, sizeof(hints));
1235 		hints.ai_family = AF_UNSPEC;
1236 		hints.ai_socktype = SOCK_DGRAM;
1237 		hints.ai_protocol = 0;
1238 		error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
1239 		    &res);
1240 		if (error) {
1241 			logerror(gai_strerror(error));
1242 			break;
1243 		}
1244 		f->f_un.f_forw.f_addr = res;
1245 		f->f_type = F_FORW;
1246 		break;
1247 
1248 	case '/':
1249 		(void)strcpy(f->f_un.f_fname, p);
1250 		if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1251 			f->f_type = F_UNUSED;
1252 			logerror(p);
1253 			break;
1254 		}
1255 		if (isatty(f->f_file))
1256 			f->f_type = F_TTY;
1257 		else
1258 			f->f_type = F_FILE;
1259 		if (strcmp(p, ctty) == 0)
1260 			f->f_type = F_CONSOLE;
1261 		break;
1262 
1263 	case '*':
1264 		f->f_type = F_WALL;
1265 		break;
1266 
1267 	default:
1268 		for (i = 0; i < MAXUNAMES && *p; i++) {
1269 			for (q = p; *q && *q != ','; )
1270 				q++;
1271 			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1272 			if ((q - p) > UT_NAMESIZE)
1273 				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1274 			else
1275 				f->f_un.f_uname[i][q - p] = '\0';
1276 			while (*q == ',' || *q == ' ')
1277 				q++;
1278 			p = q;
1279 		}
1280 		f->f_type = F_USERS;
1281 		break;
1282 	}
1283 }
1284 
1285 
1286 /*
1287  *  Decode a symbolic name to a numeric value
1288  */
1289 int
1290 decode(name, codetab)
1291 	const char *name;
1292 	CODE *codetab;
1293 {
1294 	CODE *c;
1295 	char *p, buf[40];
1296 
1297 	if (isdigit(*name))
1298 		return (atoi(name));
1299 
1300 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1301 		if (isupper(*name))
1302 			*p = tolower(*name);
1303 		else
1304 			*p = *name;
1305 	}
1306 	*p = '\0';
1307 	for (c = codetab; c->c_name; c++)
1308 		if (!strcmp(buf, c->c_name))
1309 			return (c->c_val);
1310 
1311 	return (-1);
1312 }
1313 
1314 /*
1315  * Retrieve the size of the kernel message buffer, via sysctl.
1316  */
1317 int
1318 getmsgbufsize()
1319 {
1320 	int msgbufsize, mib[2];
1321 	size_t size;
1322 
1323 	mib[0] = CTL_KERN;
1324 	mib[1] = KERN_MSGBUFSIZE;
1325 	size = sizeof msgbufsize;
1326 	if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
1327 		dprintf("couldn't get kern.msgbufsize\n");
1328 		return (0);
1329 	}
1330 	return (msgbufsize);
1331 }
1332 
1333 int *
1334 socksetup(af)
1335 	int af;
1336 {
1337 	struct addrinfo hints, *res, *r;
1338 	int error, maxs, *s, *socks;
1339 
1340 	memset(&hints, 0, sizeof(hints));
1341 	hints.ai_flags = AI_PASSIVE;
1342 	hints.ai_family = af;
1343 	hints.ai_socktype = SOCK_DGRAM;
1344 	error = getaddrinfo(NULL, "syslog", &hints, &res);
1345 	if (error) {
1346 		logerror(gai_strerror(error));
1347 		errno = 0;
1348 		die(0);
1349 	}
1350 
1351 	/* Count max number of sockets we may open */
1352 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
1353 		continue;
1354 	socks = malloc ((maxs+1) * sizeof(int));
1355 	if (!socks) {
1356 		logerror("couldn't allocate memory for sockets");
1357 		die(0);
1358 	}
1359 
1360 	*socks = 0;   /* num of sockets counter at start of array */
1361 	s = socks+1;
1362 	for (r = res; r; r = r->ai_next) {
1363 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
1364 		if (*s < 0) {
1365 			logerror("socket");
1366 			continue;
1367 		}
1368 		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
1369 			close (*s);
1370 			logerror("bind");
1371 			continue;
1372 		}
1373 
1374 		*socks = *socks + 1;
1375 		s++;
1376 	}
1377 
1378 	if (*socks == 0) {
1379 		free (socks);
1380 		if(Debug)
1381 			return(NULL);
1382 		else
1383 			die(0);
1384 	}
1385 	if (res)
1386 		freeaddrinfo(res);
1387 
1388 	return(socks);
1389 }
1390