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