2 * Copyright (c) 1983, 1988, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
33 * @(#) Copyright (c) 1983, 1988, 1993, 1994 The Regents of the University of California. All rights reserved.
34 * @(#)syslogd.c 8.3 (Berkeley) 4/4/94
35 * $FreeBSD: src/usr.sbin/syslogd/syslogd.c,v 1.59.2.26 2003/05/20 17:13:53 gshapiro Exp $
36 * $DragonFly: src/usr.sbin/syslogd/syslogd.c,v 1.2 2003/06/17 04:30:03 dillon Exp $
40 * syslogd -- log system messages
42 * This program implements a system log. It takes a series of lines.
43 * Each line may have a priority, signified as "<n>" as
44 * the first characters of the line. If this is
45 * not present, a default priority is used.
47 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
48 * cause it to reread its configuration file.
52 * MAXLINE -- the maximimum line length that can be handled.
53 * DEFUPRI -- the default priority for user messages
54 * DEFSPRI -- the default priority for kernel messages
57 * extensive changes by Ralph Campbell
58 * more extensive changes by Eric Allman (again)
59 * Extension to log by program name as well as facility and priority
61 * -u and -v by Harlan Stenn.
62 * Priority comparison code by Harlan Stenn.
65 #define MAXLINE 1024 /* maximum line length */
66 #define MAXSVLINE 120 /* maximum saved line length */
67 #define DEFUPRI (LOG_USER|LOG_NOTICE)
68 #define DEFSPRI (LOG_KERN|LOG_CRIT)
69 #define TIMERINTVL 30 /* interval for checking flush, mark */
70 #define TTYMSGTIME 1 /* timed out passed to ttymsg */
72 #include <sys/param.h>
73 #include <sys/ioctl.h>
76 #include <sys/socket.h>
77 #include <sys/queue.h>
81 #include <sys/resource.h>
82 #include <sys/syslimits.h>
83 #include <sys/types.h>
85 #include <netinet/in.h>
87 #include <arpa/inet.h>
100 #include <sysexits.h>
104 #include "pathnames.h"
108 #include <sys/syslog.h>
110 #ifdef NI_WITHSCOPEID
111 static const int withscopeid = NI_WITHSCOPEID;
113 static const int withscopeid;
116 const char *ConfFile = _PATH_LOGCONF;
117 const char *PidFile = _PATH_LOGPID;
118 const char ctty[] = _PATH_CONSOLE;
120 #define dprintf if (Debug) printf
122 #define MAXUNAMES 20 /* maximum number of user names */
127 const char *funixn[MAXFUNIX] = { _PATH_LOG };
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 */
141 * This structure represents the files that will have log
146 struct filed *f_next; /* next in linked list */
147 short f_type; /* entry type, see below */
148 short f_file; /* file descriptor */
149 time_t f_time; /* time this was last written */
150 char *f_host; /* host from which to recd. */
151 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
152 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
156 char *f_program; /* program this applies to */
158 char f_uname[MAXUNAMES][UT_NAMESIZE+1];
160 char f_hname[MAXHOSTNAMELEN];
161 struct addrinfo *f_addr;
163 } f_forw; /* forwarding address */
164 char f_fname[MAXPATHLEN];
166 char f_pname[MAXPATHLEN];
170 char f_prevline[MAXSVLINE]; /* last message logged */
171 char f_lasttime[16]; /* time of last occurrence */
172 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
173 int f_prevpri; /* pri of f_prevline */
174 int f_prevlen; /* length of f_prevline */
175 int f_prevcount; /* repetition cnt of prevline */
176 u_int f_repeatcount; /* number of "repeated" msgs */
180 * Queue of about-to-be dead processes we should watch out for.
183 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
184 struct stailhead *deadq_headp;
189 TAILQ_ENTRY(deadq_entry) dq_entries;
193 * The timeout to apply to processes waiting on the dead queue. Unit
194 * of measure is `mark intervals', i.e. 20 minutes by default.
195 * Processes on the dead queue will be terminated after that time.
198 #define DQ_TIMO_INIT 2
200 typedef struct deadq_entry *dq_t;
204 * Struct to hold records of network addresses that are allowed to log
212 struct sockaddr_storage addr;
213 struct sockaddr_storage mask;
217 #define a_addr u.numeric.addr
218 #define a_mask u.numeric.mask
219 #define a_name u.name
224 * Intervals at which we flush out "message repeated" messages,
225 * in seconds after previous message is logged. After each flush,
226 * we move to the next interval until we reach the largest.
228 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
229 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
230 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
231 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
232 (f)->f_repeatcount = MAXREPEAT; \
235 /* values for f_type */
236 #define F_UNUSED 0 /* unused entry */
237 #define F_FILE 1 /* regular file */
238 #define F_TTY 2 /* terminal */
239 #define F_CONSOLE 3 /* console terminal */
240 #define F_FORW 4 /* remote machine */
241 #define F_USERS 5 /* list of users */
242 #define F_WALL 6 /* everyone logged on */
243 #define F_PIPE 7 /* pipe to program */
245 const char *TypeNames[8] = {
246 "UNUSED", "FILE", "TTY", "CONSOLE",
247 "FORW", "USERS", "WALL", "PIPE"
250 static struct filed *Files; /* Log files that we write to */
251 static struct filed consfile; /* Console */
253 static int Debug; /* debug flag */
254 static int resolve = 1; /* resolve hostname */
255 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
256 static char *LocalDomain; /* our local domain name */
257 static int *finet; /* Internet datagram socket */
258 static int fklog = -1; /* /dev/klog */
259 static int Initialized; /* set when we have initialized ourselves */
260 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
261 static int MarkSeq; /* mark sequence number */
262 static int SecureMode; /* when true, receive only unix domain socks */
264 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
266 static int family = PF_INET; /* protocol family (IPv4 only) */
268 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
269 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
271 static char bootfile[MAXLINE+1]; /* booted kernel file */
273 struct allowedpeer *AllowedPeers; /* List of allowed peers */
274 static int NumAllowed; /* Number of entries in AllowedPeers */
276 static int UniquePriority; /* Only log specified priority? */
277 static int LogFacPri; /* Put facility and priority in log message: */
278 /* 0=no, 1=numeric, 2=names */
279 static int KeepKernFac; /* Keep remotely logged kernel facility */
281 volatile sig_atomic_t MarkSet, WantDie;
283 static int allowaddr(char *);
284 static void cfline(const char *, struct filed *,
285 const char *, const char *);
286 static const char *cvthname(struct sockaddr *);
287 static void deadq_enter(pid_t, const char *);
288 static int deadq_remove(pid_t);
289 static int decode(const char *, CODE *);
290 static void die(int);
291 static void dodie(int);
292 static void domark(int);
293 static void fprintlog(struct filed *, int, const char *);
294 static int *socksetup(int, const char *);
295 static void init(int);
296 static void logerror(const char *);
297 static void logmsg(int, const char *, const char *, int);
298 static void log_deadchild(pid_t, int, const char *);
299 static void markit(void);
300 static void printline(const char *, char *);
301 static void printsys(char *);
302 static int p_open(const char *, pid_t *);
303 static void readklog(void);
304 static void reapchild(int);
305 static void usage(void);
306 static int validate(struct sockaddr *, const char *);
307 static void unmapped(struct sockaddr *);
308 static void wallmsg(struct filed *, struct iovec *);
309 static int waitdaemon(int, int, int);
310 static void timedout(int);
313 main(int argc, char *argv[])
315 int ch, i, fdsrmax = 0, l;
316 struct sockaddr_un sunx, fromunix;
317 struct sockaddr_storage frominet;
320 char line[MAXLINE + 1];
321 const char *bindhostname, *hname;
322 struct timeval tv, *tvp;
323 struct sigaction sact;
329 while ((ch = getopt(argc, argv, "46Aa:b:cdf:kl:m:np:P:suv")) != -1)
342 case 'a': /* allow specific network addresses only */
343 if (allowaddr(optarg) == -1)
347 bindhostname = optarg;
352 case 'd': /* debug */
355 case 'f': /* configuration file */
358 case 'k': /* keep remote kern fac */
362 if (nfunix < MAXFUNIX)
363 funixn[nfunix++] = optarg;
365 warnx("out of descriptors, ignoring %s",
368 case 'm': /* mark interval */
369 MarkInterval = atoi(optarg) * 60;
377 case 'P': /* path for alt. PID */
380 case 's': /* no network mode */
383 case 'u': /* only log specified priority */
386 case 'v': /* log facility and priority */
393 if ((argc -= optind) != 0)
397 ppid = waitdaemon(0, 0, 30);
399 err(1, "could not become daemon");
407 consfile.f_type = F_CONSOLE;
408 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
409 sizeof(consfile.f_un.f_fname));
410 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
411 (void)signal(SIGTERM, dodie);
412 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
413 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
415 * We don't want the SIGCHLD and SIGHUP handlers to interfere
416 * with each other; they are likely candidates for being called
417 * simultaneously (SIGHUP closes pipe descriptor, process dies,
421 sigaddset(&mask, SIGHUP);
422 sact.sa_handler = reapchild;
424 sact.sa_flags = SA_RESTART;
425 (void)sigaction(SIGCHLD, &sact, NULL);
426 (void)signal(SIGALRM, domark);
427 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
428 (void)alarm(TIMERINTVL);
430 TAILQ_INIT(&deadq_head);
433 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
435 for (i = 0; i < nfunix; i++) {
436 (void)unlink(funixn[i]);
437 memset(&sunx, 0, sizeof(sunx));
438 sunx.sun_family = AF_UNIX;
439 (void)strlcpy(sunx.sun_path, funixn[i], sizeof(sunx.sun_path));
440 funix[i] = socket(AF_UNIX, SOCK_DGRAM, 0);
442 bind(funix[i], (struct sockaddr *)&sunx,
443 SUN_LEN(&sunx)) < 0 ||
444 chmod(funixn[i], 0666) < 0) {
445 (void)snprintf(line, sizeof line,
446 "cannot create %s", funixn[i]);
448 dprintf("cannot create %s (%d)\n", funixn[i], errno);
454 finet = socksetup(family, bindhostname);
458 for (i = 0; i < *finet; i++) {
459 if (shutdown(finet[i+1], SHUT_RD) < 0) {
460 logerror("shutdown");
466 dprintf("listening on inet and/or inet6 socket\n");
468 dprintf("sending on inet and/or inet6 socket\n");
471 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
472 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
475 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
477 /* tuck my process id away */
478 fp = fopen(PidFile, "w");
480 fprintf(fp, "%d\n", getpid());
484 dprintf("off & running....\n");
487 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
489 sigaddset(&mask, SIGCHLD);
490 sact.sa_handler = init;
492 sact.sa_flags = SA_RESTART;
493 (void)sigaction(SIGHUP, &sact, NULL);
496 tv.tv_sec = tv.tv_usec = 0;
498 if (fklog != -1 && fklog > fdsrmax)
500 if (finet && !SecureMode) {
501 for (i = 0; i < *finet; i++) {
502 if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
503 fdsrmax = finet[i+1];
506 for (i = 0; i < nfunix; i++) {
507 if (funix[i] != -1 && funix[i] > fdsrmax)
511 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
514 errx(1, "calloc fd_set");
522 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
527 if (finet && !SecureMode) {
528 for (i = 0; i < *finet; i++) {
529 if (finet[i+1] != -1)
530 FD_SET(finet[i+1], fdsr);
533 for (i = 0; i < nfunix; i++) {
535 FD_SET(funix[i], fdsr);
538 i = select(fdsrmax+1, fdsr, NULL, NULL, tvp);
552 if (fklog != -1 && FD_ISSET(fklog, fdsr))
554 if (finet && !SecureMode) {
555 for (i = 0; i < *finet; i++) {
556 if (FD_ISSET(finet[i+1], fdsr)) {
557 len = sizeof(frominet);
558 l = recvfrom(finet[i+1], line, MAXLINE,
559 0, (struct sockaddr *)&frominet,
563 hname = cvthname((struct sockaddr *)&frominet);
564 unmapped((struct sockaddr *)&frominet);
565 if (validate((struct sockaddr *)&frominet, hname))
566 printline(hname, line);
567 } else if (l < 0 && errno != EINTR)
568 logerror("recvfrom inet");
572 for (i = 0; i < nfunix; i++) {
573 if (funix[i] != -1 && FD_ISSET(funix[i], fdsr)) {
574 len = sizeof(fromunix);
575 l = recvfrom(funix[i], line, MAXLINE, 0,
576 (struct sockaddr *)&fromunix, &len);
579 printline(LocalHostName, line);
580 } else if (l < 0 && errno != EINTR)
581 logerror("recvfrom unix");
590 unmapped(struct sockaddr *sa)
592 struct sockaddr_in6 *sin6;
593 struct sockaddr_in sin4;
595 if (sa->sa_family != AF_INET6)
597 if (sa->sa_len != sizeof(struct sockaddr_in6) ||
598 sizeof(sin4) > sa->sa_len)
600 sin6 = (struct sockaddr_in6 *)sa;
601 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
604 memset(&sin4, 0, sizeof(sin4));
605 sin4.sin_family = AF_INET;
606 sin4.sin_len = sizeof(struct sockaddr_in);
607 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
608 sizeof(sin4.sin_addr));
609 sin4.sin_port = sin6->sin6_port;
611 memcpy(sa, &sin4, sin4.sin_len);
618 fprintf(stderr, "%s\n%s\n%s\n%s\n",
619 "usage: syslogd [-46Acdknsuv] [-a allowed_peer]",
620 " [-b bind address] [-f config_file]",
621 " [-l log_socket] [-m mark_interval]",
622 " [-P pid_file] [-p log_socket]");
627 * Take a raw input line, decode the message, and print the message
628 * on the appropriate log files.
631 printline(const char *hname, char *msg)
634 char *p, *q, line[MAXLINE + 1];
636 /* test for special codes */
641 while (isdigit(*++p))
642 pri = 10 * pri + (*p - '0');
646 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
649 /* don't allow users to log kernel messages */
650 if (LOG_FAC(pri) == LOG_KERN && !KeepKernFac)
651 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
655 while ((c = (unsigned char)*p++) != '\0' &&
656 q < &line[sizeof(line) - 4]) {
657 if ((c & 0x80) && c < 0xA0) {
662 if (isascii(c) && iscntrl(c)) {
665 } else if (c == '\t') {
677 logmsg(pri, line, hname, 0);
681 * Read /dev/klog while data are available, split into lines.
686 char *p, *q, line[MAXLINE + 1];
691 i = read(fklog, line + len, MAXLINE - 1 - len);
693 line[i + len] = '\0';
695 if (i < 0 && errno != EINTR && errno != EAGAIN) {
702 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
707 if (len >= MAXLINE - 1) {
712 memmove(line, p, len + 1);
719 * Take a raw input line from /dev/klog, format similar to syslog().
726 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
730 while (isdigit(*++p))
731 pri = 10 * pri + (*p - '0');
734 if ((pri & LOG_FACMASK) == LOG_CONSOLE)
737 /* kernel printf's come out on console */
740 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
742 logmsg(pri, p, LocalHostName, flags);
748 * Log a message to the appropriate log files, users, etc. based on
752 logmsg(int pri, const char *msg, const char *from, int flags)
755 int i, fac, msglen, omask, prilev;
756 const char *timestamp;
757 char prog[NAME_MAX+1];
760 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
761 pri, flags, from, msg);
763 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
766 * Check to see if msg looks non-standard.
768 msglen = strlen(msg);
769 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
770 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
774 if (flags & ADDDATE) {
775 timestamp = ctime(&now) + 4;
782 /* skip leading blanks */
783 while (isspace(*msg)) {
788 /* extract facility and priority level */
790 fac = LOG_NFACILITIES;
793 prilev = LOG_PRI(pri);
795 /* extract program name */
796 for (i = 0; i < NAME_MAX; i++) {
797 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[')
803 /* add kernel prefix for kernel messages */
804 if (flags & ISKERNEL) {
805 snprintf(buf, sizeof(buf), "%s: %s", bootfile, msg);
807 msglen = strlen(buf);
810 /* log the message to the particular outputs */
813 f->f_file = open(ctty, O_WRONLY, 0);
815 if (f->f_file >= 0) {
816 (void)strlcpy(f->f_lasttime, timestamp,
817 sizeof(f->f_lasttime));
818 fprintlog(f, flags, msg);
819 (void)close(f->f_file);
821 (void)sigsetmask(omask);
824 for (f = Files; f; f = f->f_next) {
825 /* skip messages that are incorrect priority */
826 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
827 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
828 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
830 || f->f_pmask[fac] == INTERNAL_NOPRI)
833 /* skip messages with the incorrect hostname */
835 switch (f->f_host[0]) {
837 if (strcasecmp(from, f->f_host + 1) != 0)
841 if (strcasecmp(from, f->f_host + 1) == 0)
846 /* skip messages with the incorrect program name */
848 switch (f->f_program[0]) {
850 if (strcmp(prog, f->f_program + 1) != 0)
854 if (strcmp(prog, f->f_program + 1) == 0)
858 if (strcmp(prog, f->f_program) != 0)
863 /* skip message to console if it has already been printed */
864 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
867 /* don't output marks to recently written files */
868 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
872 * suppress duplicate lines to this file
874 if (no_compress - (f->f_type != F_PIPE) < 1 &&
875 (flags & MARK) == 0 && msglen == f->f_prevlen &&
876 !strcmp(msg, f->f_prevline) &&
877 !strcasecmp(from, f->f_prevhost)) {
878 (void)strlcpy(f->f_lasttime, timestamp,
879 sizeof(f->f_lasttime));
881 dprintf("msg repeated %d times, %ld sec of %d\n",
882 f->f_prevcount, (long)(now - f->f_time),
883 repeatinterval[f->f_repeatcount]);
885 * If domark would have logged this by now,
886 * flush it now (so we don't hold isolated messages),
887 * but back off so we'll flush less often
890 if (now > REPEATTIME(f)) {
891 fprintlog(f, flags, (char *)NULL);
895 /* new line, save it */
897 fprintlog(f, 0, (char *)NULL);
898 f->f_repeatcount = 0;
900 (void)strlcpy(f->f_lasttime, timestamp,
901 sizeof(f->f_lasttime));
902 (void)strlcpy(f->f_prevhost, from,
903 sizeof(f->f_prevhost));
904 if (msglen < MAXSVLINE) {
905 f->f_prevlen = msglen;
906 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
907 fprintlog(f, flags, (char *)NULL);
909 f->f_prevline[0] = 0;
911 fprintlog(f, flags, msg);
915 (void)sigsetmask(omask);
919 fprintlog(struct filed *f, int flags, const char *msg)
925 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
929 if (f->f_type == F_WALL) {
930 v->iov_base = greetings;
931 v->iov_len = snprintf(greetings, sizeof greetings,
932 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
933 f->f_prevhost, ctime(&now));
940 v->iov_base = f->f_lasttime;
949 static char fp_buf[30]; /* Hollow laugh */
950 int fac = f->f_prevpri & LOG_FACMASK;
951 int pri = LOG_PRI(f->f_prevpri);
952 const char *f_s = NULL;
953 char f_n[5]; /* Hollow laugh */
954 const char *p_s = NULL;
955 char p_n[5]; /* Hollow laugh */
960 for (c = facilitynames; c->c_name; c++) {
961 if (c->c_val == fac) {
966 for (c = prioritynames; c->c_name; c++) {
967 if (c->c_val == pri) {
974 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
978 snprintf(p_n, sizeof p_n, "%d", pri);
981 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
982 v->iov_base = fp_buf;
983 v->iov_len = strlen(fp_buf);
990 v->iov_base = f->f_prevhost;
991 v->iov_len = strlen(v->iov_base);
998 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1004 v->iov_len = strlen(msg);
1005 } else if (f->f_prevcount > 1) {
1006 v->iov_base = repbuf;
1007 v->iov_len = snprintf(repbuf, sizeof repbuf,
1008 "last message repeated %d times", f->f_prevcount);
1010 v->iov_base = f->f_prevline;
1011 v->iov_len = f->f_prevlen;
1015 dprintf("Logging to %s", TypeNames[f->f_type]);
1018 switch (f->f_type) {
1024 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1025 /* check for local vs remote messages */
1026 if (strcasecmp(f->f_prevhost, LocalHostName))
1027 l = snprintf(line, sizeof line - 1,
1028 "<%d>%.15s Forwarded from %s: %s",
1029 f->f_prevpri, iov[0].iov_base, f->f_prevhost,
1032 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1033 f->f_prevpri, iov[0].iov_base, iov[5].iov_base);
1036 else if (l > MAXLINE)
1040 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1041 for (i = 0; i < *finet; i++) {
1044 * should we check AF first, or just
1045 * trial and error? FWD
1048 address_family_of(finet[i+1]))
1050 lsent = sendto(finet[i+1], line, l, 0,
1051 r->ai_addr, r->ai_addrlen);
1055 if (lsent == l && !send_to_all)
1058 dprintf("lsent/l: %d/%d\n", lsent, l);
1069 /* case ENOTSOCK: */
1071 /* case EMSGSIZE: */
1074 /* case ECONNREFUSED: */
1076 dprintf("removing entry\n", e);
1077 (void)close(f->f_file);
1078 f->f_type = F_UNUSED;
1086 dprintf(" %s\n", f->f_un.f_fname);
1089 if (writev(f->f_file, iov, 7) < 0) {
1091 (void)close(f->f_file);
1092 f->f_type = F_UNUSED;
1094 logerror(f->f_un.f_fname);
1095 } else if (flags & SYNC_FILE)
1096 (void)fsync(f->f_file);
1100 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1103 if (f->f_un.f_pipe.f_pid == 0) {
1104 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1105 &f->f_un.f_pipe.f_pid)) < 0) {
1106 f->f_type = F_UNUSED;
1107 logerror(f->f_un.f_pipe.f_pname);
1111 if (writev(f->f_file, iov, 7) < 0) {
1113 (void)close(f->f_file);
1114 if (f->f_un.f_pipe.f_pid > 0)
1115 deadq_enter(f->f_un.f_pipe.f_pid,
1116 f->f_un.f_pipe.f_pname);
1117 f->f_un.f_pipe.f_pid = 0;
1119 logerror(f->f_un.f_pipe.f_pname);
1124 if (flags & IGN_CONS) {
1125 dprintf(" (ignored)\n");
1131 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1132 v->iov_base = "\r\n";
1135 errno = 0; /* ttymsg() only sometimes returns an errno */
1136 if ((msgret = ttymsg(iov, 7, f->f_un.f_fname, 10))) {
1137 f->f_type = F_UNUSED;
1145 v->iov_base = "\r\n";
1156 * WALLMSG -- Write a message to the world at large
1158 * Write the specified message to either the entire
1159 * world, or a list of approved users.
1162 wallmsg(struct filed *f, struct iovec *iov)
1164 static int reenter; /* avoid calling ourselves */
1169 char line[sizeof(ut.ut_line) + 1];
1173 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1174 logerror(_PATH_UTMP);
1179 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
1180 if (ut.ut_name[0] == '\0')
1182 (void)strlcpy(line, ut.ut_line, sizeof(line));
1183 if (f->f_type == F_WALL) {
1184 if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) != NULL) {
1185 errno = 0; /* already in msg */
1190 /* should we send the message to this user? */
1191 for (i = 0; i < MAXUNAMES; i++) {
1192 if (!f->f_un.f_uname[i][0])
1194 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1196 if ((p = ttymsg(iov, 7, line, TTYMSGTIME))
1198 errno = 0; /* already in msg */
1210 reapchild(int signo __unused)
1216 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1218 /* Don't tell while we are initting. */
1221 /* First, look if it's a process from the dead queue. */
1222 if (deadq_remove(pid))
1225 /* Now, look in list of active processes. */
1226 for (f = Files; f; f = f->f_next)
1227 if (f->f_type == F_PIPE &&
1228 f->f_un.f_pipe.f_pid == pid) {
1229 (void)close(f->f_file);
1230 f->f_un.f_pipe.f_pid = 0;
1231 log_deadchild(pid, status,
1232 f->f_un.f_pipe.f_pname);
1241 * Return a printable representation of a host address.
1244 cvthname(struct sockaddr *f)
1247 sigset_t omask, nmask;
1248 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1250 error = getnameinfo((struct sockaddr *)f,
1251 ((struct sockaddr *)f)->sa_len,
1252 ip, sizeof ip, NULL, 0,
1253 NI_NUMERICHOST | withscopeid);
1254 dprintf("cvthname(%s)\n", ip);
1257 dprintf("Malformed from address %s\n", gai_strerror(error));
1263 sigemptyset(&nmask);
1264 sigaddset(&nmask, SIGHUP);
1265 sigprocmask(SIG_BLOCK, &nmask, &omask);
1266 error = getnameinfo((struct sockaddr *)f,
1267 ((struct sockaddr *)f)->sa_len,
1268 hname, sizeof hname, NULL, 0,
1269 NI_NAMEREQD | withscopeid);
1270 sigprocmask(SIG_SETMASK, &omask, NULL);
1272 dprintf("Host name for your address (%s) unknown\n", ip);
1276 if (hl > 0 && hname[hl-1] == '.')
1278 trimdomain(hname, hl);
1290 domark(int signo __unused)
1297 * Print syslogd errors some place.
1300 logerror(const char *type)
1306 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1308 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1310 dprintf("%s\n", buf);
1311 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1318 int was_initialized;
1322 was_initialized = Initialized;
1323 Initialized = 0; /* Don't log SIGCHLDs. */
1324 for (f = Files; f != NULL; f = f->f_next) {
1325 /* flush any pending output */
1327 fprintlog(f, 0, (char *)NULL);
1328 if (f->f_type == F_PIPE)
1329 (void)close(f->f_file);
1331 Initialized = was_initialized;
1333 dprintf("syslogd: exiting on signal %d\n", signo);
1334 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1338 for (i = 0; i < nfunix; i++)
1339 if (funixn[i] && funix[i] != -1)
1340 (void)unlink(funixn[i]);
1345 * INIT -- Initialize syslogd from configuration table
1352 struct filed *f, *next, **nextp;
1354 char cline[LINE_MAX];
1355 char prog[NAME_MAX+1];
1356 char host[MAXHOSTNAMELEN];
1357 char oldLocalHostName[MAXHOSTNAMELEN];
1358 char hostMsg[2*MAXHOSTNAMELEN+40];
1363 * Load hostname (may have changed).
1366 (void)strlcpy(oldLocalHostName, LocalHostName,
1367 sizeof(oldLocalHostName));
1368 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1369 err(EX_OSERR, "gethostname() failed");
1370 if ((p = strchr(LocalHostName, '.')) != NULL) {
1378 * Close all open log files.
1381 for (f = Files; f != NULL; f = next) {
1382 /* flush any pending output */
1384 fprintlog(f, 0, (char *)NULL);
1386 switch (f->f_type) {
1391 (void)close(f->f_file);
1394 (void)close(f->f_file);
1395 if (f->f_un.f_pipe.f_pid > 0)
1396 deadq_enter(f->f_un.f_pipe.f_pid,
1397 f->f_un.f_pipe.f_pname);
1398 f->f_un.f_pipe.f_pid = 0;
1402 if (f->f_program) free(f->f_program);
1403 if (f->f_host) free(f->f_host);
1409 /* open the configuration file */
1410 if ((cf = fopen(ConfFile, "r")) == NULL) {
1411 dprintf("cannot open %s\n", ConfFile);
1412 *nextp = (struct filed *)calloc(1, sizeof(*f));
1413 if (*nextp == NULL) {
1417 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1418 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1419 if ((*nextp)->f_next == NULL) {
1423 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1429 * Foreach line in the conf table, open that file.
1432 (void)strlcpy(host, "*", sizeof(host));
1433 (void)strlcpy(prog, "*", sizeof(prog));
1434 while (fgets(cline, sizeof(cline), cf) != NULL) {
1436 * check for end-of-section, comments, strip off trailing
1437 * spaces and newline character. #!prog is treated specially:
1438 * following lines apply only to that program.
1440 for (p = cline; isspace(*p); ++p)
1446 if (*p != '!' && *p != '+' && *p != '-')
1449 if (*p == '+' || *p == '-') {
1453 if ((!*p) || (*p == '*')) {
1454 (void)strlcpy(host, "*", sizeof(host));
1459 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1460 if (!isalnum(*p) && *p != '.' && *p != '-')
1469 while (isspace(*p)) p++;
1470 if ((!*p) || (*p == '*')) {
1471 (void)strlcpy(prog, "*", sizeof(prog));
1474 for (i = 0; i < NAME_MAX; i++) {
1482 for (p = strchr(cline, '\0'); isspace(*--p);)
1485 f = (struct filed *)calloc(1, sizeof(*f));
1492 cfline(cline, f, prog, host);
1495 /* close the configuration file */
1501 for (f = Files; f; f = f->f_next) {
1502 for (i = 0; i <= LOG_NFACILITIES; i++)
1503 if (f->f_pmask[i] == INTERNAL_NOPRI)
1506 printf("%d ", f->f_pmask[i]);
1507 printf("%s: ", TypeNames[f->f_type]);
1508 switch (f->f_type) {
1510 printf("%s", f->f_un.f_fname);
1515 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1519 printf("%s", f->f_un.f_forw.f_hname);
1523 printf("%s", f->f_un.f_pipe.f_pname);
1527 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1528 printf("%s, ", f->f_un.f_uname[i]);
1532 printf(" (%s)", f->f_program);
1537 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1538 dprintf("syslogd: restarted\n");
1540 * Log a change in hostname, but only on a restart.
1542 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1543 (void)snprintf(hostMsg, sizeof(hostMsg),
1544 "syslogd: hostname changed, \"%s\" to \"%s\"",
1545 oldLocalHostName, LocalHostName);
1546 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1547 dprintf("%s\n", hostMsg);
1552 * Crack a configuration file line
1555 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1557 struct addrinfo hints, *res;
1561 char buf[MAXLINE], ebuf[100];
1563 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1565 errno = 0; /* keep strerror() stuff out of logerror messages */
1567 /* clear out file entry */
1568 memset(f, 0, sizeof(*f));
1569 for (i = 0; i <= LOG_NFACILITIES; i++)
1570 f->f_pmask[i] = INTERNAL_NOPRI;
1572 /* save hostname if any */
1573 if (host && *host == '*')
1578 f->f_host = strdup(host);
1579 if (f->f_host == NULL) {
1583 hl = strlen(f->f_host);
1584 if (hl > 0 && f->f_host[hl-1] == '.')
1585 f->f_host[--hl] = '\0';
1586 trimdomain(f->f_host, hl);
1589 /* save program name if any */
1590 if (prog && *prog == '*')
1593 f->f_program = strdup(prog);
1594 if (f->f_program == NULL) {
1600 /* scan through the list of selectors */
1601 for (p = line; *p && *p != '\t' && *p != ' ';) {
1606 /* find the end of this facility name list */
1607 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1610 /* get the priority comparison */
1638 /* collect priority name */
1639 for (bp = buf; *q && !strchr("\t,; ", *q); )
1644 while (strchr(",;", *q))
1647 /* decode priority name */
1649 pri = LOG_PRIMASK + 1;
1650 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1652 pri = decode(buf, prioritynames);
1654 (void)snprintf(ebuf, sizeof ebuf,
1655 "unknown priority name \"%s\"", buf);
1661 pri_cmp = (UniquePriority)
1666 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1668 /* scan facilities */
1669 while (*p && !strchr("\t.; ", *p)) {
1670 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1675 for (i = 0; i < LOG_NFACILITIES; i++) {
1676 f->f_pmask[i] = pri;
1677 f->f_pcmp[i] = pri_cmp;
1680 i = decode(buf, facilitynames);
1682 (void)snprintf(ebuf, sizeof ebuf,
1683 "unknown facility name \"%s\"",
1688 f->f_pmask[i >> 3] = pri;
1689 f->f_pcmp[i >> 3] = pri_cmp;
1691 while (*p == ',' || *p == ' ')
1698 /* skip to action part */
1699 while (*p == '\t' || *p == ' ')
1704 (void)strlcpy(f->f_un.f_forw.f_hname, ++p,
1705 sizeof(f->f_un.f_forw.f_hname));
1706 memset(&hints, 0, sizeof(hints));
1707 hints.ai_family = family;
1708 hints.ai_socktype = SOCK_DGRAM;
1709 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
1712 logerror(gai_strerror(error));
1715 f->f_un.f_forw.f_addr = res;
1720 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1721 f->f_type = F_UNUSED;
1725 if (isatty(f->f_file)) {
1726 if (strcmp(p, ctty) == 0)
1727 f->f_type = F_CONSOLE;
1730 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1731 sizeof(f->f_un.f_fname));
1733 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1739 f->f_un.f_pipe.f_pid = 0;
1740 (void)strlcpy(f->f_un.f_fname, p + 1, sizeof(f->f_un.f_fname));
1749 for (i = 0; i < MAXUNAMES && *p; i++) {
1750 for (q = p; *q && *q != ','; )
1752 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1753 if ((q - p) > UT_NAMESIZE)
1754 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1756 f->f_un.f_uname[i][q - p] = '\0';
1757 while (*q == ',' || *q == ' ')
1761 f->f_type = F_USERS;
1768 * Decode a symbolic name to a numeric value
1771 decode(const char *name, CODE *codetab)
1777 return (atoi(name));
1779 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1781 *p = tolower(*name);
1786 for (c = codetab; c->c_name; c++)
1787 if (!strcmp(buf, c->c_name))
1799 now = time((time_t *)NULL);
1800 MarkSeq += TIMERINTVL;
1801 if (MarkSeq >= MarkInterval) {
1802 logmsg(LOG_INFO, "-- MARK --",
1803 LocalHostName, ADDDATE|MARK);
1807 for (f = Files; f; f = f->f_next) {
1808 if (f->f_prevcount && now >= REPEATTIME(f)) {
1809 dprintf("flush %s: repeated %d times, %d sec.\n",
1810 TypeNames[f->f_type], f->f_prevcount,
1811 repeatinterval[f->f_repeatcount]);
1812 fprintlog(f, 0, (char *)NULL);
1817 /* Walk the dead queue, and see if we should signal somebody. */
1818 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
1819 next = TAILQ_NEXT(q, dq_entries);
1821 switch (q->dq_timeout) {
1823 /* Already signalled once, try harder now. */
1824 if (kill(q->dq_pid, SIGKILL) != 0)
1825 (void)deadq_remove(q->dq_pid);
1830 * Timed out on dead queue, send terminate
1831 * signal. Note that we leave the removal
1832 * from the dead queue to reapchild(), which
1833 * will also log the event (unless the process
1834 * didn't even really exist, in case we simply
1835 * drop it from the dead queue).
1837 if (kill(q->dq_pid, SIGTERM) != 0)
1838 (void)deadq_remove(q->dq_pid);
1846 (void)alarm(TIMERINTVL);
1850 * fork off and become a daemon, but wait for the child to come online
1851 * before returing to the parent, or we get disk thrashing at boot etc.
1852 * Set a timer so we don't hang forever if it wedges.
1855 waitdaemon(int nochdir, int noclose, int maxwait)
1859 pid_t pid, childpid;
1861 switch (childpid = fork()) {
1867 signal(SIGALRM, timedout);
1869 while ((pid = wait3(&status, 0, NULL)) != -1) {
1870 if (WIFEXITED(status))
1871 errx(1, "child pid %d exited with return code %d",
1872 pid, WEXITSTATUS(status));
1873 if (WIFSIGNALED(status))
1874 errx(1, "child pid %d exited on signal %d%s",
1875 pid, WTERMSIG(status),
1876 WCOREDUMP(status) ? " (core dumped)" :
1878 if (pid == childpid) /* it's gone... */
1890 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1891 (void)dup2(fd, STDIN_FILENO);
1892 (void)dup2(fd, STDOUT_FILENO);
1893 (void)dup2(fd, STDERR_FILENO);
1901 * We get a SIGALRM from the child when it's running and finished doing it's
1902 * fsync()'s or O_SYNC writes for all the boot messages.
1904 * We also get a signal from the kernel if the timer expires, so check to
1905 * see what happened.
1908 timedout(int sig __unused)
1912 signal(SIGALRM, SIG_DFL);
1914 errx(1, "timed out waiting for child");
1920 * Add `s' to the list of allowable peer addresses to accept messages
1923 * `s' is a string in the form:
1925 * [*]domainname[:{servicename|portnumber|*}]
1929 * netaddr/maskbits[:{servicename|portnumber|*}]
1931 * Returns -1 on error, 0 if the argument was valid.
1937 struct allowedpeer ap;
1939 int masklen = -1, i;
1940 struct addrinfo hints, *res;
1941 struct in_addr *addrp, *maskp;
1942 u_int32_t *addr6p, *mask6p;
1943 char ip[NI_MAXHOST];
1946 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
1949 if ((cp1 = strrchr(cp1, ':'))) {
1950 /* service/port provided */
1952 if (strlen(cp1) == 1 && *cp1 == '*')
1953 /* any port allowed */
1955 else if ((se = getservbyname(cp1, "udp"))) {
1956 ap.port = ntohs(se->s_port);
1958 ap.port = strtol(cp1, &cp2, 0);
1960 return (-1); /* port not numeric */
1963 if ((se = getservbyname("syslog", "udp")))
1964 ap.port = ntohs(se->s_port);
1966 /* sanity, should not happen */
1970 if ((cp1 = strchr(s, '/')) != NULL &&
1971 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
1973 if ((masklen = atoi(cp1 + 1)) < 0)
1978 cp2 = s + strlen(s) - 1;
1989 memset(&hints, 0, sizeof(hints));
1990 hints.ai_family = PF_UNSPEC;
1991 hints.ai_socktype = SOCK_DGRAM;
1992 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
1993 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
1995 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
1996 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
1997 ap.a_mask.ss_family = res->ai_family;
1998 if (res->ai_family == AF_INET) {
1999 ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2000 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2001 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2003 /* use default netmask */
2004 if (IN_CLASSA(ntohl(addrp->s_addr)))
2005 maskp->s_addr = htonl(IN_CLASSA_NET);
2006 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2007 maskp->s_addr = htonl(IN_CLASSB_NET);
2009 maskp->s_addr = htonl(IN_CLASSC_NET);
2010 } else if (masklen <= 32) {
2011 /* convert masklen to netmask */
2015 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2020 /* Lose any host bits in the network number. */
2021 addrp->s_addr &= maskp->s_addr;
2024 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2025 ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2028 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2029 /* convert masklen to netmask */
2030 while (masklen > 0) {
2032 *mask6p = htonl(~(0xffffffff >> masklen));
2035 *mask6p++ = 0xffffffff;
2038 /* Lose any host bits in the network number. */
2039 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2040 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2041 for (i = 0; i < 4; i++)
2042 addr6p[i] &= mask6p[i];
2051 /* arg `s' is domain name */
2065 printf("allowaddr: rule %d: ", NumAllowed);
2067 printf("numeric, ");
2068 getnameinfo((struct sockaddr *)&ap.a_addr,
2069 ((struct sockaddr *)&ap.a_addr)->sa_len,
2070 ip, sizeof ip, NULL, 0,
2071 NI_NUMERICHOST | withscopeid);
2072 printf("addr = %s, ", ip);
2073 getnameinfo((struct sockaddr *)&ap.a_mask,
2074 ((struct sockaddr *)&ap.a_mask)->sa_len,
2075 ip, sizeof ip, NULL, 0,
2076 NI_NUMERICHOST | withscopeid);
2077 printf("mask = %s; ", ip);
2079 printf("domainname = %s; ", ap.a_name);
2081 printf("port = %d\n", ap.port);
2084 if ((AllowedPeers = realloc(AllowedPeers,
2085 ++NumAllowed * sizeof(struct allowedpeer)))
2087 logerror("realloc");
2090 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2095 * Validate that the remote peer has permission to log to us.
2098 validate(struct sockaddr *sa, const char *hname)
2102 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2103 struct allowedpeer *ap;
2104 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2105 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2106 struct addrinfo hints, *res;
2109 if (NumAllowed == 0)
2110 /* traditional behaviour, allow everything */
2113 (void)strlcpy(name, hname, sizeof(name));
2114 memset(&hints, 0, sizeof(hints));
2115 hints.ai_family = PF_UNSPEC;
2116 hints.ai_socktype = SOCK_DGRAM;
2117 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2118 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2120 else if (strchr(name, '.') == NULL) {
2121 strlcat(name, ".", sizeof name);
2122 strlcat(name, LocalDomain, sizeof name);
2124 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2125 NI_NUMERICHOST | withscopeid | NI_NUMERICSERV) != 0)
2126 return (0); /* for safety, should not occur */
2127 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2131 /* now, walk down the list */
2132 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2133 if (ap->port != 0 && ap->port != sport) {
2134 dprintf("rejected in rule %d due to port mismatch.\n", i);
2138 if (ap->isnumeric) {
2139 if (ap->a_addr.ss_family != sa->sa_family) {
2140 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2143 if (ap->a_addr.ss_family == AF_INET) {
2144 sin4 = (struct sockaddr_in *)sa;
2145 a4p = (struct sockaddr_in *)&ap->a_addr;
2146 m4p = (struct sockaddr_in *)&ap->a_mask;
2147 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2148 != a4p->sin_addr.s_addr) {
2149 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2154 else if (ap->a_addr.ss_family == AF_INET6) {
2155 sin6 = (struct sockaddr_in6 *)sa;
2156 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2157 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2158 #ifdef NI_WITHSCOPEID
2159 if (a6p->sin6_scope_id != 0 &&
2160 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2161 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2166 for (j = 0; j < 16; j += 4) {
2167 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2168 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2174 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2185 /* allow wildmatch */
2188 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2189 dprintf("rejected in rule %d due to name mismatch.\n", i);
2195 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2196 dprintf("rejected in rule %d due to name mismatch.\n", i);
2201 dprintf("accepted in rule %d.\n", i);
2202 return (1); /* hooray! */
2208 * Fairly similar to popen(3), but returns an open descriptor, as
2209 * opposed to a FILE *.
2212 p_open(const char *prog, pid_t *pid)
2214 int pfd[2], nulldesc, i;
2215 sigset_t omask, mask;
2216 char *argv[4]; /* sh -c cmd NULL */
2219 if (pipe(pfd) == -1)
2221 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2222 /* we are royally screwed anyway */
2226 sigaddset(&mask, SIGALRM);
2227 sigaddset(&mask, SIGHUP);
2228 sigprocmask(SIG_BLOCK, &mask, &omask);
2229 switch ((*pid = fork())) {
2231 sigprocmask(SIG_SETMASK, &omask, 0);
2236 argv[0] = strdup("sh");
2237 argv[1] = strdup("-c");
2238 argv[2] = strdup(prog);
2240 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2246 (void)setsid(); /* Avoid catching SIGHUPs. */
2249 * Throw away pending signals, and reset signal
2250 * behaviour to standard values.
2252 signal(SIGALRM, SIG_IGN);
2253 signal(SIGHUP, SIG_IGN);
2254 sigprocmask(SIG_SETMASK, &omask, 0);
2255 signal(SIGPIPE, SIG_DFL);
2256 signal(SIGQUIT, SIG_DFL);
2257 signal(SIGALRM, SIG_DFL);
2258 signal(SIGHUP, SIG_DFL);
2260 dup2(pfd[0], STDIN_FILENO);
2261 dup2(nulldesc, STDOUT_FILENO);
2262 dup2(nulldesc, STDERR_FILENO);
2263 for (i = getdtablesize(); i > 2; i--)
2266 (void)execvp(_PATH_BSHELL, argv);
2270 sigprocmask(SIG_SETMASK, &omask, 0);
2274 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2275 * supposed to get an EWOULDBLOCK on writev(2), which is
2276 * caught by the logic above anyway, which will in turn close
2277 * the pipe, and fork a new logging subprocess if necessary.
2278 * The stale subprocess will be killed some time later unless
2279 * it terminated itself due to closing its input pipe (so we
2280 * get rid of really dead puppies).
2282 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2284 (void)snprintf(errmsg, sizeof errmsg,
2285 "Warning: cannot change pipe to PID %d to "
2286 "non-blocking behaviour.",
2294 deadq_enter(pid_t pid, const char *name)
2300 * Be paranoid, if we can't signal the process, don't enter it
2301 * into the dead queue (perhaps it's already dead). If possible,
2302 * we try to fetch and log the child's status.
2304 if (kill(pid, 0) != 0) {
2305 if (waitpid(pid, &status, WNOHANG) > 0)
2306 log_deadchild(pid, status, name);
2310 p = malloc(sizeof(struct deadq_entry));
2317 p->dq_timeout = DQ_TIMO_INIT;
2318 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2322 deadq_remove(pid_t pid)
2326 TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2327 if (q->dq_pid == pid) {
2328 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2338 log_deadchild(pid_t pid, int status, const char *name)
2344 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2345 if (WIFSIGNALED(status)) {
2346 reason = "due to signal";
2347 code = WTERMSIG(status);
2349 reason = "with status";
2350 code = WEXITSTATUS(status);
2354 (void)snprintf(buf, sizeof buf,
2355 "Logging subprocess %d (%s) exited %s %d.",
2356 pid, name, reason, code);
2361 socksetup(int af, const char *bindhostname)
2363 struct addrinfo hints, *res, *r;
2364 int error, maxs, *s, *socks;
2366 memset(&hints, 0, sizeof(hints));
2367 hints.ai_flags = AI_PASSIVE;
2368 hints.ai_family = af;
2369 hints.ai_socktype = SOCK_DGRAM;
2370 error = getaddrinfo(bindhostname, "syslog", &hints, &res);
2372 logerror(gai_strerror(error));
2377 /* Count max number of sockets we may open */
2378 for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2379 socks = malloc((maxs+1) * sizeof(int));
2380 if (socks == NULL) {
2381 logerror("couldn't allocate memory for sockets");
2385 *socks = 0; /* num of sockets counter at start of array */
2387 for (r = res; r; r = r->ai_next) {
2388 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2393 if (r->ai_family == AF_INET6) {
2395 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2396 (char *)&on, sizeof (on)) < 0) {
2397 logerror("setsockopt");
2402 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {