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 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 static const char copyright[] =
32 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
33 The Regents of the University of California. All rights reserved.\n";
38 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
46 * syslogd -- log system messages
48 * This program implements a system log. It takes a series of lines.
49 * Each line may have a priority, signified as "<n>" as
50 * the first characters of the line. If this is
51 * not present, a default priority is used.
53 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
54 * cause it to reread its configuration file.
58 * MAXLINE -- the maximum line length that can be handled.
59 * DEFUPRI -- the default priority for user messages
60 * DEFSPRI -- the default priority for kernel messages
63 * extensive changes by Ralph Campbell
64 * more extensive changes by Eric Allman (again)
65 * Extension to log by program name as well as facility and priority
67 * -u and -v by Harlan Stenn.
68 * Priority comparison code by Harlan Stenn.
71 #define MAXLINE 1024 /* maximum line length */
72 #define MAXSVLINE 120 /* maximum saved line length */
73 #define DEFUPRI (LOG_USER|LOG_NOTICE)
74 #define DEFSPRI (LOG_KERN|LOG_CRIT)
75 #define TIMERINTVL 30 /* interval for checking flush, mark */
76 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
78 #include <sys/param.h>
79 #include <sys/ioctl.h>
82 #include <sys/socket.h>
83 #include <sys/queue.h>
87 #include <sys/resource.h>
88 #include <sys/syslimits.h>
89 #include <sys/types.h>
91 #include <netinet/in.h>
93 #include <arpa/inet.h>
106 #include <sysexits.h>
110 #include "pathnames.h"
114 #include <sys/syslog.h>
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 */
126 * We have two default sockets, one with 666 permissions,
127 * and one for privileged programs.
133 STAILQ_ENTRY(funix) next;
135 struct funix funix_secure = { -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
137 struct funix funix_default = { -1, _PATH_LOG, DEFFILEMODE,
140 STAILQ_HEAD(, funix) funixes = { &funix_default,
141 &(funix_secure.next.stqe_next) };
147 #define IGN_CONS 0x001 /* don't print on console */
148 #define SYNC_FILE 0x002 /* do fsync on file after printing */
149 #define ADDDATE 0x004 /* add a date to the message */
150 #define MARK 0x008 /* this message is a mark */
151 #define ISKERNEL 0x010 /* kernel generated message */
154 * This structure represents the files that will have log
156 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
157 * or if f_type if F_PIPE and f_pid > 0.
161 struct filed *f_next; /* next in linked list */
162 short f_type; /* entry type, see below */
163 short f_file; /* file descriptor */
164 time_t f_time; /* time this was last written */
165 char *f_host; /* host from which to recd. */
166 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
167 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
171 char *f_program; /* program this applies to */
173 char f_uname[MAXUNAMES][UT_NAMESIZE+1];
175 char f_hname[MAXHOSTNAMELEN];
176 struct addrinfo *f_addr;
178 } f_forw; /* forwarding address */
179 char f_fname[MAXPATHLEN];
181 char f_pname[MAXPATHLEN];
185 char f_prevline[MAXSVLINE]; /* last message logged */
186 char f_lasttime[16]; /* time of last occurrence */
187 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
188 int f_prevpri; /* pri of f_prevline */
189 int f_prevlen; /* length of f_prevline */
190 int f_prevcount; /* repetition cnt of prevline */
191 u_int f_repeatcount; /* number of "repeated" msgs */
192 int f_flags; /* file-specific flags */
193 #define FFLAG_SYNC 0x01
194 #define FFLAG_NEEDSYNC 0x02
198 * Queue of about-to-be dead processes we should watch out for.
201 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
202 struct stailhead *deadq_headp;
207 TAILQ_ENTRY(deadq_entry) dq_entries;
211 * The timeout to apply to processes waiting on the dead queue. Unit
212 * of measure is `mark intervals', i.e. 20 minutes by default.
213 * Processes on the dead queue will be terminated after that time.
216 #define DQ_TIMO_INIT 2
218 typedef struct deadq_entry *dq_t;
222 * Struct to hold records of network addresses that are allowed to log
230 struct sockaddr_storage addr;
231 struct sockaddr_storage mask;
235 #define a_addr u.numeric.addr
236 #define a_mask u.numeric.mask
237 #define a_name u.name
242 * Intervals at which we flush out "message repeated" messages,
243 * in seconds after previous message is logged. After each flush,
244 * we move to the next interval until we reach the largest.
246 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
247 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
248 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
249 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
250 (f)->f_repeatcount = MAXREPEAT; \
253 /* values for f_type */
254 #define F_UNUSED 0 /* unused entry */
255 #define F_FILE 1 /* regular file */
256 #define F_TTY 2 /* terminal */
257 #define F_CONSOLE 3 /* console terminal */
258 #define F_FORW 4 /* remote machine */
259 #define F_USERS 5 /* list of users */
260 #define F_WALL 6 /* everyone logged on */
261 #define F_PIPE 7 /* pipe to program */
263 const char *TypeNames[8] = {
264 "UNUSED", "FILE", "TTY", "CONSOLE",
265 "FORW", "USERS", "WALL", "PIPE"
268 static struct filed *Files; /* Log files that we write to */
269 static struct filed consfile; /* Console */
271 static int Debug; /* debug flag */
272 static int resolve = 1; /* resolve hostname */
273 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
274 static const char *LocalDomain; /* our local domain name */
275 static int *finet; /* Internet datagram socket */
276 static int fklog = -1; /* /dev/klog */
277 static int Initialized; /* set when we have initialized ourselves */
278 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
279 static int MarkSeq; /* mark sequence number */
280 static int SecureMode; /* when true, receive only unix domain socks */
282 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
284 static int family = PF_INET; /* protocol family (IPv4 only) */
286 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
287 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
288 static int use_bootfile; /* log entire bootfile for every kern msg */
289 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
290 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
292 static char bootfile[MAXLINE+1]; /* booted kernel file */
294 struct allowedpeer *AllowedPeers; /* List of allowed peers */
295 static int NumAllowed; /* Number of entries in AllowedPeers */
297 static int UniquePriority; /* Only log specified priority? */
298 static int LogFacPri; /* Put facility and priority in log message: */
299 /* 0=no, 1=numeric, 2=names */
300 static int KeepKernFac; /* Keep remotely logged kernel facility */
301 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
302 static struct pidfh *pfh;
304 volatile sig_atomic_t MarkSet, WantDie;
306 static int allowaddr(char *);
307 static void cfline(const char *, struct filed *,
308 const char *, const char *);
309 static const char *cvthname(struct sockaddr *);
310 static void deadq_enter(pid_t, const char *);
311 static int deadq_remove(pid_t);
312 static int decode(const char *, CODE *);
313 static void die(int);
314 static void dodie(int);
315 static void dofsync(void);
316 static void domark(int);
317 static void fprintlog(struct filed *, int, const char *);
318 static int *socksetup(int, const char *);
319 static void init(int);
320 static void logerror(const char *);
321 static void logmsg(int, const char *, const char *, int);
322 static void log_deadchild(pid_t, int, const char *);
323 static void markit(void);
324 static int skip_message(const char *, const char *, int);
325 static void printline(const char *, char *);
326 static void printsys(char *);
327 static int p_open(const char *, pid_t *);
328 static void readklog(void);
329 static void reapchild(int);
330 static void usage(void);
331 static int validate(struct sockaddr *, const char *);
332 static void unmapped(struct sockaddr *);
333 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
334 static int waitdaemon(int, int, int);
335 static void timedout(int);
336 static void double_rbuf(int);
339 main(int argc, char *argv[])
341 int ch, i, fdsrmax = 0, l;
342 struct sockaddr_un sunx, fromunix;
343 struct sockaddr_storage frominet;
345 char line[MAXLINE + 1];
346 const char *bindhostname, *hname;
347 struct timeval tv, *tvp;
348 struct sigaction sact;
349 struct funix *fx, *fx1;
351 pid_t ppid = 1, spid;
355 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:kl:m:nop:P:sS:uv")) != -1)
371 case 'a': /* allow specific network addresses only */
372 if (allowaddr(optarg) == -1)
376 bindhostname = optarg;
384 case 'd': /* debug */
387 case 'f': /* configuration file */
390 case 'k': /* keep remote kern fac */
399 if (optarg[0] == '/') {
402 } else if ((name = strchr(optarg, ':')) != NULL) {
405 errx(1, "socket name must be absolute "
407 if (isdigit(*optarg)) {
408 perml = strtol(optarg, &ep, 8);
409 if (*ep || perml < 0 ||
410 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
411 errx(1, "invalid mode %s, exiting",
413 mode = (mode_t )perml;
415 errx(1, "invalid mode %s, exiting",
417 } else /* doesn't begin with '/', and no ':' */
418 errx(1, "can't parse path %s", optarg);
420 if (strlen(name) >= sizeof(sunx.sun_path))
421 errx(1, "%s path too long, exiting", name);
422 if ((fx = malloc(sizeof(struct funix))) == NULL)
423 errx(1, "malloc failed");
427 STAILQ_INSERT_TAIL(&funixes, fx, next);
430 case 'm': /* mark interval */
431 MarkInterval = atoi(optarg) * 60;
440 if (strlen(optarg) >= sizeof(sunx.sun_path))
441 errx(1, "%s path too long, exiting", optarg);
442 funix_default.name = optarg;
444 case 'P': /* path for alt. PID */
447 case 's': /* no network mode */
450 case 'S': /* path for privileged originator */
451 if (strlen(optarg) >= sizeof(sunx.sun_path))
452 errx(1, "%s path too long, exiting", optarg);
453 funix_secure.name = optarg;
455 case 'u': /* only log specified priority */
458 case 'v': /* log facility and priority */
464 if ((argc -= optind) != 0)
467 pfh = pidfile_open(PidFile, 0600, &spid);
470 errx(1, "syslogd already running, pid: %d", spid);
471 warn("cannot open pid file");
475 ppid = waitdaemon(0, 0, 30);
477 warn("could not become daemon");
488 consfile.f_type = F_CONSOLE;
489 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
490 sizeof(consfile.f_un.f_fname));
491 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
492 (void)signal(SIGTERM, dodie);
493 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
494 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
496 * We don't want the SIGCHLD and SIGHUP handlers to interfere
497 * with each other; they are likely candidates for being called
498 * simultaneously (SIGHUP closes pipe descriptor, process dies,
502 sigaddset(&mask, SIGHUP);
503 sact.sa_handler = reapchild;
505 sact.sa_flags = SA_RESTART;
506 (void)sigaction(SIGCHLD, &sact, NULL);
507 (void)signal(SIGALRM, domark);
508 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
509 (void)alarm(TIMERINTVL);
511 TAILQ_INIT(&deadq_head);
514 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
516 STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
517 (void)unlink(fx->name);
518 memset(&sunx, 0, sizeof(sunx));
519 sunx.sun_family = AF_LOCAL;
520 (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
521 fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
523 bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
524 chmod(fx->name, fx->mode) < 0) {
525 (void)snprintf(line, sizeof line,
526 "cannot create %s", fx->name);
528 dprintf("cannot create %s (%d)\n", fx->name, errno);
529 if (fx == &funix_default || fx == &funix_secure)
532 STAILQ_REMOVE(&funixes, fx, funix, next);
539 finet = socksetup(family, bindhostname);
543 for (i = 0; i < *finet; i++) {
544 if (shutdown(finet[i+1], SHUT_RD) < 0) {
545 logerror("shutdown");
551 dprintf("listening on inet and/or inet6 socket\n");
553 dprintf("sending on inet and/or inet6 socket\n");
556 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
557 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
560 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
562 /* tuck my process id away */
565 dprintf("off & running....\n");
568 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
570 sigaddset(&mask, SIGCHLD);
571 sact.sa_handler = init;
573 sact.sa_flags = SA_RESTART;
574 (void)sigaction(SIGHUP, &sact, NULL);
577 tv.tv_sec = tv.tv_usec = 0;
579 if (fklog != -1 && fklog > fdsrmax)
581 if (finet && !SecureMode) {
582 for (i = 0; i < *finet; i++) {
583 if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
584 fdsrmax = finet[i+1];
587 STAILQ_FOREACH(fx, &funixes, next)
591 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
594 errx(1, "calloc fd_set");
602 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
607 if (finet && !SecureMode) {
608 for (i = 0; i < *finet; i++) {
609 if (finet[i+1] != -1)
610 FD_SET(finet[i+1], fdsr);
613 STAILQ_FOREACH(fx, &funixes, next)
616 i = select(fdsrmax+1, fdsr, NULL, NULL,
617 needdofsync ? &tv : tvp);
633 if (fklog != -1 && FD_ISSET(fklog, fdsr))
635 if (finet && !SecureMode) {
636 for (i = 0; i < *finet; i++) {
637 if (FD_ISSET(finet[i+1], fdsr)) {
638 len = sizeof(frominet);
639 l = recvfrom(finet[i+1], line, MAXLINE,
640 0, (struct sockaddr *)&frominet,
644 hname = cvthname((struct sockaddr *)&frominet);
645 unmapped((struct sockaddr *)&frominet);
646 if (validate((struct sockaddr *)&frominet, hname))
647 printline(hname, line);
648 } else if (l < 0 && errno != EINTR)
649 logerror("recvfrom inet");
653 STAILQ_FOREACH(fx, &funixes, next) {
654 if (FD_ISSET(fx->s, fdsr)) {
655 len = sizeof(fromunix);
656 l = recvfrom(fx->s, line, MAXLINE, 0,
657 (struct sockaddr *)&fromunix, &len);
660 printline(LocalHostName, line);
661 } else if (l < 0 && errno != EINTR)
662 logerror("recvfrom unix");
671 unmapped(struct sockaddr *sa)
673 struct sockaddr_in6 *sin6;
674 struct sockaddr_in sin4;
676 if (sa->sa_family != AF_INET6)
678 if (sa->sa_len != sizeof(struct sockaddr_in6) ||
679 sizeof(sin4) > sa->sa_len)
681 sin6 = (struct sockaddr_in6 *)sa;
682 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
685 memset(&sin4, 0, sizeof(sin4));
686 sin4.sin_family = AF_INET;
687 sin4.sin_len = sizeof(struct sockaddr_in);
688 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
689 sizeof(sin4.sin_addr));
690 sin4.sin_port = sin6->sin6_port;
692 memcpy(sa, &sin4, sin4.sin_len);
699 fprintf(stderr, "%s\n%s\n%s\n%s\n",
700 "usage: syslogd [-468ACcdknosuv] [-a allowed_peer]",
701 " [-b bind_address] [-f config_file]",
702 " [-l [mode:]path] [-m mark_interval]",
703 " [-P pid_file] [-p log_socket]");
708 * Take a raw input line, decode the message, and print the message
709 * on the appropriate log files.
712 printline(const char *hname, char *msg)
717 char line[MAXLINE + 1];
719 /* test for special codes */
724 n = strtol(p + 1, &q, 10);
725 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
730 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
734 * Don't allow users to log kernel messages.
735 * NOTE: since LOG_KERN == 0 this will also match
736 * messages with no facility specified.
738 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
739 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
743 while ((c = (unsigned char)*p++) != '\0' &&
744 q < &line[sizeof(line) - 4]) {
745 if (mask_C1 && (c & 0x80) && c < 0xA0) {
750 if (isascii(c) && iscntrl(c)) {
753 } else if (c == '\t') {
765 logmsg(pri, line, hname, 0);
769 * Read /dev/klog while data are available, split into lines.
774 char *p, *q, line[MAXLINE + 1];
779 i = read(fklog, line + len, MAXLINE - 1 - len);
781 line[i + len] = '\0';
783 if (i < 0 && errno != EINTR && errno != EAGAIN) {
790 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
795 if (len >= MAXLINE - 1) {
800 memmove(line, p, len + 1);
807 * Take a raw input line from /dev/klog, format similar to syslog().
814 int flags, isprintf, pri;
816 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
822 n = strtol(p + 1, &q, 10);
823 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
830 * Kernel printf's and LOG_CONSOLE messages have been displayed
831 * on the console already.
833 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
835 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
837 logmsg(pri, p, LocalHostName, flags);
843 * Match a program or host name against a specification.
844 * Return a non-0 value if the message must be ignored
845 * based on the specification.
848 skip_message(const char *name, const char *spec, int checkcase)
853 /* Behaviour on explicit match */
868 s = strstr (spec, name);
870 s = strcasestr (spec, name);
873 prev = (s == spec ? ',' : *(s - 1));
874 next = *(s + strlen (name));
876 if (prev == ',' && (next == '\0' || next == ','))
877 /* Explicit match: skip iff the spec is an
882 /* No explicit match for this name: skip the message iff
883 the spec is an inclusive one. */
888 * Log a message to the appropriate log files, users, etc. based on
892 logmsg(int pri, const char *msg, const char *from, int flags)
895 int i, fac, msglen, omask, prilev;
896 const char *timestamp;
897 char prog[NAME_MAX+1];
900 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
901 pri, flags, from, msg);
903 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
906 * Check to see if msg looks non-standard.
908 msglen = strlen(msg);
909 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
910 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
914 if (flags & ADDDATE) {
915 timestamp = ctime(&now) + 4;
922 /* skip leading blanks */
923 while (isspace(*msg)) {
928 /* extract facility and priority level */
930 fac = LOG_NFACILITIES;
934 /* Check maximum facility number. */
935 if (fac > LOG_NFACILITIES) {
936 (void)sigsetmask(omask);
940 prilev = LOG_PRI(pri);
942 /* extract program name */
943 for (i = 0; i < NAME_MAX; i++) {
944 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
945 msg[i] == '/' || isspace(msg[i]))
951 /* add kernel prefix for kernel messages */
952 if (flags & ISKERNEL) {
953 snprintf(buf, sizeof(buf), "%s: %s",
954 use_bootfile ? bootfile : "kernel", msg);
956 msglen = strlen(buf);
959 /* log the message to the particular outputs */
963 * Open in non-blocking mode to avoid hangs during open
964 * and close(waiting for the port to drain).
966 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
968 if (f->f_file >= 0) {
969 (void)strlcpy(f->f_lasttime, timestamp,
970 sizeof(f->f_lasttime));
971 fprintlog(f, flags, msg);
972 (void)close(f->f_file);
974 (void)sigsetmask(omask);
977 for (f = Files; f; f = f->f_next) {
978 /* skip messages that are incorrect priority */
979 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
980 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
981 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
983 || f->f_pmask[fac] == INTERNAL_NOPRI)
986 /* skip messages with the incorrect hostname */
987 if (skip_message(from, f->f_host, 0))
990 /* skip messages with the incorrect program name */
991 if (skip_message(prog, f->f_program, 1))
994 /* skip message to console if it has already been printed */
995 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
998 /* don't output marks to recently written files */
999 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1003 * suppress duplicate lines to this file
1005 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1006 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1007 f->f_prevline && !strcmp(msg, f->f_prevline) &&
1008 !strcasecmp(from, f->f_prevhost)) {
1009 (void)strlcpy(f->f_lasttime, timestamp,
1010 sizeof(f->f_lasttime));
1012 dprintf("msg repeated %d times, %ld sec of %d\n",
1013 f->f_prevcount, (long)(now - f->f_time),
1014 repeatinterval[f->f_repeatcount]);
1016 * If domark would have logged this by now,
1017 * flush it now (so we don't hold isolated messages),
1018 * but back off so we'll flush less often
1021 if (now > REPEATTIME(f)) {
1022 fprintlog(f, flags, (char *)NULL);
1026 /* new line, save it */
1028 fprintlog(f, 0, (char *)NULL);
1029 f->f_repeatcount = 0;
1031 (void)strlcpy(f->f_lasttime, timestamp,
1032 sizeof(f->f_lasttime));
1033 (void)strlcpy(f->f_prevhost, from,
1034 sizeof(f->f_prevhost));
1035 if (msglen < MAXSVLINE) {
1036 f->f_prevlen = msglen;
1037 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1038 fprintlog(f, flags, (char *)NULL);
1040 f->f_prevline[0] = 0;
1042 fprintlog(f, flags, msg);
1046 (void)sigsetmask(omask);
1054 for (f = Files; f; f = f->f_next) {
1055 if ((f->f_type == F_FILE) &&
1056 (f->f_flags & FFLAG_NEEDSYNC)) {
1057 f->f_flags &= ~FFLAG_NEEDSYNC;
1058 (void)fsync(f->f_file);
1065 fprintlog(struct filed *f, int flags, const char *msg)
1067 struct iovec iov[IOV_SIZE];
1070 int i, l, lsent = 0;
1071 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1072 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1076 if (f->f_type == F_WALL) {
1077 v->iov_base = greetings;
1078 /* The time displayed is not synchornized with the other log
1079 * destinations (like messages). Following fragment was using
1080 * ctime(&now), which was updating the time every 30 sec.
1081 * With f_lasttime, time is synchronized correctly.
1083 v->iov_len = snprintf(greetings, sizeof greetings,
1084 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1085 f->f_prevhost, f->f_lasttime);
1092 v->iov_base = f->f_lasttime;
1093 v->iov_len = strlen(f->f_lasttime);
1095 v->iov_base = space;
1101 static char fp_buf[30]; /* Hollow laugh */
1102 int fac = f->f_prevpri & LOG_FACMASK;
1103 int pri = LOG_PRI(f->f_prevpri);
1104 const char *f_s = NULL;
1105 char f_n[5]; /* Hollow laugh */
1106 const char *p_s = NULL;
1107 char p_n[5]; /* Hollow laugh */
1109 if (LogFacPri > 1) {
1112 for (c = facilitynames; c->c_name; c++) {
1113 if (c->c_val == fac) {
1118 for (c = prioritynames; c->c_name; c++) {
1119 if (c->c_val == pri) {
1126 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1130 snprintf(p_n, sizeof p_n, "%d", pri);
1133 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1134 v->iov_base = fp_buf;
1135 v->iov_len = strlen(fp_buf);
1142 v->iov_base = f->f_prevhost;
1143 v->iov_len = strlen(v->iov_base);
1145 v->iov_base = space;
1150 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1156 v->iov_len = strlen(msg);
1157 } else if (f->f_prevcount > 1) {
1158 v->iov_base = repbuf;
1159 v->iov_len = snprintf(repbuf, sizeof repbuf,
1160 "last message repeated %d times", f->f_prevcount);
1161 } else if (f->f_prevline) {
1162 v->iov_base = f->f_prevline;
1163 v->iov_len = f->f_prevlen;
1169 dprintf("Logging to %s", TypeNames[f->f_type]);
1172 switch (f->f_type) {
1179 port = (int)ntohs(((struct sockaddr_in *)
1180 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1182 dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1184 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1186 /* check for local vs remote messages */
1187 if (strcasecmp(f->f_prevhost, LocalHostName))
1188 l = snprintf(line, sizeof line - 1,
1189 "<%d>%.15s Forwarded from %s: %s",
1190 f->f_prevpri, (char *)iov[0].iov_base,
1191 f->f_prevhost, (char *)iov[5].iov_base);
1193 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1194 f->f_prevpri, (char *)iov[0].iov_base,
1195 (char *)iov[5].iov_base);
1198 else if (l > MAXLINE)
1202 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1203 for (i = 0; i < *finet; i++) {
1206 * should we check AF first, or just
1207 * trial and error? FWD
1210 address_family_of(finet[i+1]))
1212 lsent = sendto(finet[i+1], line, l, 0,
1213 r->ai_addr, r->ai_addrlen);
1217 if (lsent == l && !send_to_all)
1220 dprintf("lsent/l: %d/%d\n", lsent, l);
1233 /* case ENOTSOCK: */
1235 /* case EMSGSIZE: */
1238 /* case ECONNREFUSED: */
1240 dprintf("removing entry\n");
1241 f->f_type = F_UNUSED;
1249 dprintf(" %s\n", f->f_un.f_fname);
1252 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1254 * If writev(2) fails for potentially transient errors
1255 * like the filesystem being full, ignore it.
1256 * Otherwise remove this logfile from the list.
1258 if (errno != ENOSPC) {
1260 (void)close(f->f_file);
1261 f->f_type = F_UNUSED;
1263 logerror(f->f_un.f_fname);
1265 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1266 f->f_flags |= FFLAG_NEEDSYNC;
1272 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1275 if (f->f_un.f_pipe.f_pid == 0) {
1276 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1277 &f->f_un.f_pipe.f_pid)) < 0) {
1278 f->f_type = F_UNUSED;
1279 logerror(f->f_un.f_pipe.f_pname);
1283 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1285 (void)close(f->f_file);
1286 if (f->f_un.f_pipe.f_pid > 0)
1287 deadq_enter(f->f_un.f_pipe.f_pid,
1288 f->f_un.f_pipe.f_pname);
1289 f->f_un.f_pipe.f_pid = 0;
1291 logerror(f->f_un.f_pipe.f_pname);
1296 if (flags & IGN_CONS) {
1297 dprintf(" (ignored)\n");
1303 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1307 errno = 0; /* ttymsg() only sometimes returns an errno */
1308 if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1309 f->f_type = F_UNUSED;
1319 wallmsg(f, iov, IOV_SIZE);
1327 * WALLMSG -- Write a message to the world at large
1329 * Write the specified message to either the entire
1330 * world, or a list of approved users.
1333 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1335 static int reenter; /* avoid calling ourselves */
1340 char line[sizeof(ut.ut_line) + 1];
1344 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1345 logerror(_PATH_UTMP);
1350 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
1351 if (ut.ut_name[0] == '\0')
1353 /* We must use strncpy since ut_* may not be NUL terminated. */
1354 strncpy(line, ut.ut_line, sizeof(line) - 1);
1355 line[sizeof(line) - 1] = '\0';
1356 if (f->f_type == F_WALL) {
1357 if ((p = ttymsg(iov, iovlen, line, TTYMSGTIME)) !=
1359 errno = 0; /* already in msg */
1364 /* should we send the message to this user? */
1365 for (i = 0; i < MAXUNAMES; i++) {
1366 if (!f->f_un.f_uname[i][0])
1368 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1370 if ((p = ttymsg(iov, iovlen, line, TTYMSGTIME))
1372 errno = 0; /* already in msg */
1384 reapchild(int signo __unused)
1390 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1392 /* Don't tell while we are initting. */
1395 /* First, look if it's a process from the dead queue. */
1396 if (deadq_remove(pid))
1399 /* Now, look in list of active processes. */
1400 for (f = Files; f; f = f->f_next)
1401 if (f->f_type == F_PIPE &&
1402 f->f_un.f_pipe.f_pid == pid) {
1403 (void)close(f->f_file);
1404 f->f_un.f_pipe.f_pid = 0;
1405 log_deadchild(pid, status,
1406 f->f_un.f_pipe.f_pname);
1415 * Return a printable representation of a host address.
1418 cvthname(struct sockaddr *f)
1421 sigset_t omask, nmask;
1422 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1424 error = getnameinfo((struct sockaddr *)f,
1425 ((struct sockaddr *)f)->sa_len,
1426 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1427 dprintf("cvthname(%s)\n", ip);
1430 dprintf("Malformed from address %s\n", gai_strerror(error));
1436 sigemptyset(&nmask);
1437 sigaddset(&nmask, SIGHUP);
1438 sigprocmask(SIG_BLOCK, &nmask, &omask);
1439 error = getnameinfo((struct sockaddr *)f,
1440 ((struct sockaddr *)f)->sa_len,
1441 hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1442 sigprocmask(SIG_SETMASK, &omask, NULL);
1444 dprintf("Host name for your address (%s) unknown\n", ip);
1448 if (hl > 0 && hname[hl-1] == '.')
1450 trimdomain(hname, hl);
1462 domark(int signo __unused)
1469 * Print syslogd errors some place.
1472 logerror(const char *type)
1475 static int recursed = 0;
1477 /* If there's an error while trying to log an error, give up. */
1483 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1485 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1487 dprintf("%s\n", buf);
1488 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1497 int was_initialized;
1500 was_initialized = Initialized;
1501 Initialized = 0; /* Don't log SIGCHLDs. */
1502 for (f = Files; f != NULL; f = f->f_next) {
1503 /* flush any pending output */
1505 fprintlog(f, 0, (char *)NULL);
1506 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1507 (void)close(f->f_file);
1508 f->f_un.f_pipe.f_pid = 0;
1511 Initialized = was_initialized;
1513 dprintf("syslogd: exiting on signal %d\n", signo);
1514 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1518 STAILQ_FOREACH(fx, &funixes, next)
1519 (void)unlink(fx->name);
1520 pidfile_remove(pfh);
1526 * INIT -- Initialize syslogd from configuration table
1533 struct filed *f, *next, **nextp;
1535 char cline[LINE_MAX];
1536 char prog[NAME_MAX+1];
1537 char host[MAXHOSTNAMELEN];
1538 char oldLocalHostName[MAXHOSTNAMELEN];
1539 char hostMsg[2*MAXHOSTNAMELEN+40];
1540 char bootfileMsg[LINE_MAX];
1545 * Load hostname (may have changed).
1548 (void)strlcpy(oldLocalHostName, LocalHostName,
1549 sizeof(oldLocalHostName));
1550 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1551 err(EX_OSERR, "gethostname() failed");
1552 if ((p = strchr(LocalHostName, '.')) != NULL) {
1560 * Close all open log files.
1563 for (f = Files; f != NULL; f = next) {
1564 /* flush any pending output */
1566 fprintlog(f, 0, (char *)NULL);
1568 switch (f->f_type) {
1573 (void)close(f->f_file);
1576 if (f->f_un.f_pipe.f_pid > 0) {
1577 (void)close(f->f_file);
1578 deadq_enter(f->f_un.f_pipe.f_pid,
1579 f->f_un.f_pipe.f_pname);
1581 f->f_un.f_pipe.f_pid = 0;
1585 if (f->f_program) free(f->f_program);
1586 if (f->f_host) free(f->f_host);
1592 /* open the configuration file */
1593 if ((cf = fopen(ConfFile, "r")) == NULL) {
1594 dprintf("cannot open %s\n", ConfFile);
1595 *nextp = (struct filed *)calloc(1, sizeof(*f));
1596 if (*nextp == NULL) {
1600 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1601 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1602 if ((*nextp)->f_next == NULL) {
1606 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1612 * Foreach line in the conf table, open that file.
1615 (void)strlcpy(host, "*", sizeof(host));
1616 (void)strlcpy(prog, "*", sizeof(prog));
1617 while (fgets(cline, sizeof(cline), cf) != NULL) {
1619 * check for end-of-section, comments, strip off trailing
1620 * spaces and newline character. #!prog is treated specially:
1621 * following lines apply only to that program.
1623 for (p = cline; isspace(*p); ++p)
1629 if (*p != '!' && *p != '+' && *p != '-')
1632 if (*p == '+' || *p == '-') {
1636 if ((!*p) || (*p == '*')) {
1637 (void)strlcpy(host, "*", sizeof(host));
1642 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1643 if (!isalnum(*p) && *p != '.' && *p != '-'
1644 && *p != ',' && *p != ':' && *p != '%')
1653 while (isspace(*p)) p++;
1654 if ((!*p) || (*p == '*')) {
1655 (void)strlcpy(prog, "*", sizeof(prog));
1658 for (i = 0; i < NAME_MAX; i++) {
1659 if (!isprint(p[i]) || isspace(p[i]))
1666 for (p = cline + 1; *p != '\0'; p++) {
1669 if (*(p - 1) == '\\') {
1677 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1679 f = (struct filed *)calloc(1, sizeof(*f));
1686 cfline(cline, f, prog, host);
1689 /* close the configuration file */
1696 for (f = Files; f; f = f->f_next) {
1697 for (i = 0; i <= LOG_NFACILITIES; i++)
1698 if (f->f_pmask[i] == INTERNAL_NOPRI)
1701 printf("%d ", f->f_pmask[i]);
1702 printf("%s: ", TypeNames[f->f_type]);
1703 switch (f->f_type) {
1705 printf("%s", f->f_un.f_fname);
1710 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1714 port = (int)ntohs(((struct sockaddr_in *)
1715 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1718 f->f_un.f_forw.f_hname, port);
1720 printf("%s", f->f_un.f_forw.f_hname);
1725 printf("%s", f->f_un.f_pipe.f_pname);
1729 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1730 printf("%s, ", f->f_un.f_uname[i]);
1734 printf(" (%s)", f->f_program);
1739 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1740 dprintf("syslogd: restarted\n");
1742 * Log a change in hostname, but only on a restart.
1744 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1745 (void)snprintf(hostMsg, sizeof(hostMsg),
1746 "syslogd: hostname changed, \"%s\" to \"%s\"",
1747 oldLocalHostName, LocalHostName);
1748 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1749 dprintf("%s\n", hostMsg);
1752 * Log the kernel boot file if we aren't going to use it as
1753 * the prefix, and if this is *not* a restart.
1755 if (signo == 0 && !use_bootfile) {
1756 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1757 "syslogd: kernel boot file is %s", bootfile);
1758 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1759 dprintf("%s\n", bootfileMsg);
1764 * Crack a configuration file line
1767 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1769 struct addrinfo hints, *res;
1770 int error, i, pri, syncfile;
1773 char buf[MAXLINE], ebuf[100];
1775 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1777 errno = 0; /* keep strerror() stuff out of logerror messages */
1779 /* clear out file entry */
1780 memset(f, 0, sizeof(*f));
1781 for (i = 0; i <= LOG_NFACILITIES; i++)
1782 f->f_pmask[i] = INTERNAL_NOPRI;
1784 /* save hostname if any */
1785 if (host && *host == '*')
1790 f->f_host = strdup(host);
1791 if (f->f_host == NULL) {
1795 hl = strlen(f->f_host);
1796 if (hl > 0 && f->f_host[hl-1] == '.')
1797 f->f_host[--hl] = '\0';
1798 trimdomain(f->f_host, hl);
1801 /* save program name if any */
1802 if (prog && *prog == '*')
1805 f->f_program = strdup(prog);
1806 if (f->f_program == NULL) {
1812 /* scan through the list of selectors */
1813 for (p = line; *p && *p != '\t' && *p != ' ';) {
1818 /* find the end of this facility name list */
1819 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1822 /* get the priority comparison */
1850 /* collect priority name */
1851 for (bp = buf; *q && !strchr("\t,; ", *q); )
1856 while (strchr(",;", *q))
1859 /* decode priority name */
1862 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1864 /* Ignore trailing spaces. */
1865 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1868 pri = decode(buf, prioritynames);
1870 (void)snprintf(ebuf, sizeof ebuf,
1871 "unknown priority name \"%s\"", buf);
1877 pri_cmp = (UniquePriority)
1882 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1884 /* scan facilities */
1885 while (*p && !strchr("\t.; ", *p)) {
1886 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1891 for (i = 0; i < LOG_NFACILITIES; i++) {
1892 f->f_pmask[i] = pri;
1893 f->f_pcmp[i] = pri_cmp;
1896 i = decode(buf, facilitynames);
1898 (void)snprintf(ebuf, sizeof ebuf,
1899 "unknown facility name \"%s\"",
1904 f->f_pmask[i >> 3] = pri;
1905 f->f_pcmp[i >> 3] = pri_cmp;
1907 while (*p == ',' || *p == ' ')
1914 /* skip to action part */
1915 while (*p == '\t' || *p == ' ')
1929 * scan forward to see if there is a port defined.
1930 * so we can't use strlcpy..
1932 i = sizeof(f->f_un.f_forw.f_hname);
1933 tp = f->f_un.f_forw.f_hname;
1936 while (*p && (*p != ':') && (i-- > 0)) {
1941 /* See if we copied a domain and have a port */
1947 memset(&hints, 0, sizeof(hints));
1948 hints.ai_family = family;
1949 hints.ai_socktype = SOCK_DGRAM;
1950 error = getaddrinfo(f->f_un.f_forw.f_hname,
1951 p ? p : "syslog", &hints, &res);
1953 logerror(gai_strerror(error));
1956 f->f_un.f_forw.f_addr = res;
1961 if ((f->f_file = open(p, logflags, 0600)) < 0) {
1962 f->f_type = F_UNUSED;
1967 f->f_flags |= FFLAG_SYNC;
1968 if (isatty(f->f_file)) {
1969 if (strcmp(p, ctty) == 0)
1970 f->f_type = F_CONSOLE;
1973 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1974 sizeof(f->f_un.f_fname));
1976 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1982 f->f_un.f_pipe.f_pid = 0;
1983 (void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
1984 sizeof(f->f_un.f_pipe.f_pname));
1993 for (i = 0; i < MAXUNAMES && *p; i++) {
1994 for (q = p; *q && *q != ','; )
1996 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1997 if ((q - p) > UT_NAMESIZE)
1998 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
2000 f->f_un.f_uname[i][q - p] = '\0';
2001 while (*q == ',' || *q == ' ')
2005 f->f_type = F_USERS;
2012 * Decode a symbolic name to a numeric value
2015 decode(const char *name, CODE *codetab)
2021 return (atoi(name));
2023 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2025 *p = tolower(*name);
2030 for (c = codetab; c->c_name; c++)
2031 if (!strcmp(buf, c->c_name))
2043 now = time((time_t *)NULL);
2044 MarkSeq += TIMERINTVL;
2045 if (MarkSeq >= MarkInterval) {
2046 logmsg(LOG_INFO, "-- MARK --",
2047 LocalHostName, ADDDATE|MARK);
2051 for (f = Files; f; f = f->f_next) {
2052 if (f->f_prevcount && now >= REPEATTIME(f)) {
2053 dprintf("flush %s: repeated %d times, %d sec.\n",
2054 TypeNames[f->f_type], f->f_prevcount,
2055 repeatinterval[f->f_repeatcount]);
2056 fprintlog(f, 0, (char *)NULL);
2061 /* Walk the dead queue, and see if we should signal somebody. */
2062 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2063 next = TAILQ_NEXT(q, dq_entries);
2065 switch (q->dq_timeout) {
2067 /* Already signalled once, try harder now. */
2068 if (kill(q->dq_pid, SIGKILL) != 0)
2069 (void)deadq_remove(q->dq_pid);
2074 * Timed out on dead queue, send terminate
2075 * signal. Note that we leave the removal
2076 * from the dead queue to reapchild(), which
2077 * will also log the event (unless the process
2078 * didn't even really exist, in case we simply
2079 * drop it from the dead queue).
2081 if (kill(q->dq_pid, SIGTERM) != 0)
2082 (void)deadq_remove(q->dq_pid);
2090 (void)alarm(TIMERINTVL);
2094 * fork off and become a daemon, but wait for the child to come online
2095 * before returing to the parent, or we get disk thrashing at boot etc.
2096 * Set a timer so we don't hang forever if it wedges.
2099 waitdaemon(int nochdir, int noclose, int maxwait)
2103 pid_t pid, childpid;
2105 switch (childpid = fork()) {
2111 signal(SIGALRM, timedout);
2113 while ((pid = wait3(&status, 0, NULL)) != -1) {
2114 if (WIFEXITED(status))
2115 errx(1, "child pid %d exited with return code %d",
2116 pid, WEXITSTATUS(status));
2117 if (WIFSIGNALED(status))
2118 errx(1, "child pid %d exited on signal %d%s",
2119 pid, WTERMSIG(status),
2120 WCOREDUMP(status) ? " (core dumped)" :
2122 if (pid == childpid) /* it's gone... */
2134 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2135 (void)dup2(fd, STDIN_FILENO);
2136 (void)dup2(fd, STDOUT_FILENO);
2137 (void)dup2(fd, STDERR_FILENO);
2145 * We get a SIGALRM from the child when it's running and finished doing it's
2146 * fsync()'s or O_SYNC writes for all the boot messages.
2148 * We also get a signal from the kernel if the timer expires, so check to
2149 * see what happened.
2152 timedout(int sig __unused)
2156 signal(SIGALRM, SIG_DFL);
2158 errx(1, "timed out waiting for child");
2164 * Add `s' to the list of allowable peer addresses to accept messages
2167 * `s' is a string in the form:
2169 * [*]domainname[:{servicename|portnumber|*}]
2173 * netaddr/maskbits[:{servicename|portnumber|*}]
2175 * Returns -1 on error, 0 if the argument was valid.
2181 struct allowedpeer ap;
2183 int masklen = -1, i;
2184 struct addrinfo hints, *res;
2185 struct in_addr *addrp, *maskp;
2186 u_int32_t *addr6p, *mask6p;
2187 char ip[NI_MAXHOST];
2190 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2193 if ((cp1 = strrchr(cp1, ':'))) {
2194 /* service/port provided */
2196 if (strlen(cp1) == 1 && *cp1 == '*')
2197 /* any port allowed */
2199 else if ((se = getservbyname(cp1, "udp"))) {
2200 ap.port = ntohs(se->s_port);
2202 ap.port = strtol(cp1, &cp2, 0);
2204 return (-1); /* port not numeric */
2207 if ((se = getservbyname("syslog", "udp")))
2208 ap.port = ntohs(se->s_port);
2210 /* sanity, should not happen */
2214 if ((cp1 = strchr(s, '/')) != NULL &&
2215 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2217 if ((masklen = atoi(cp1 + 1)) < 0)
2222 cp2 = s + strlen(s) - 1;
2233 memset(&hints, 0, sizeof(hints));
2234 hints.ai_family = PF_UNSPEC;
2235 hints.ai_socktype = SOCK_DGRAM;
2236 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2237 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2239 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2240 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2241 ap.a_mask.ss_family = res->ai_family;
2242 if (res->ai_family == AF_INET) {
2243 ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2244 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2245 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2247 /* use default netmask */
2248 if (IN_CLASSA(ntohl(addrp->s_addr)))
2249 maskp->s_addr = htonl(IN_CLASSA_NET);
2250 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2251 maskp->s_addr = htonl(IN_CLASSB_NET);
2253 maskp->s_addr = htonl(IN_CLASSC_NET);
2254 } else if (masklen <= 32) {
2255 /* convert masklen to netmask */
2259 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2264 /* Lose any host bits in the network number. */
2265 addrp->s_addr &= maskp->s_addr;
2268 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2269 ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2272 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2273 /* convert masklen to netmask */
2274 while (masklen > 0) {
2276 *mask6p = htonl(~(0xffffffff >> masklen));
2279 *mask6p++ = 0xffffffff;
2282 /* Lose any host bits in the network number. */
2283 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2284 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2285 for (i = 0; i < 4; i++)
2286 addr6p[i] &= mask6p[i];
2295 /* arg `s' is domain name */
2309 printf("allowaddr: rule %d: ", NumAllowed);
2311 printf("numeric, ");
2312 getnameinfo((struct sockaddr *)&ap.a_addr,
2313 ((struct sockaddr *)&ap.a_addr)->sa_len,
2314 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2315 printf("addr = %s, ", ip);
2316 getnameinfo((struct sockaddr *)&ap.a_mask,
2317 ((struct sockaddr *)&ap.a_mask)->sa_len,
2318 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2319 printf("mask = %s; ", ip);
2321 printf("domainname = %s; ", ap.a_name);
2323 printf("port = %d\n", ap.port);
2326 if ((AllowedPeers = realloc(AllowedPeers,
2327 ++NumAllowed * sizeof(struct allowedpeer)))
2329 logerror("realloc");
2332 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2337 * Validate that the remote peer has permission to log to us.
2340 validate(struct sockaddr *sa, const char *hname)
2344 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2345 struct allowedpeer *ap;
2346 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2347 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2348 struct addrinfo hints, *res;
2351 if (NumAllowed == 0)
2352 /* traditional behaviour, allow everything */
2355 (void)strlcpy(name, hname, sizeof(name));
2356 memset(&hints, 0, sizeof(hints));
2357 hints.ai_family = PF_UNSPEC;
2358 hints.ai_socktype = SOCK_DGRAM;
2359 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2360 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2362 else if (strchr(name, '.') == NULL) {
2363 strlcat(name, ".", sizeof name);
2364 strlcat(name, LocalDomain, sizeof name);
2366 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2367 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2368 return (0); /* for safety, should not occur */
2369 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2373 /* now, walk down the list */
2374 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2375 if (ap->port != 0 && ap->port != sport) {
2376 dprintf("rejected in rule %d due to port mismatch.\n", i);
2380 if (ap->isnumeric) {
2381 if (ap->a_addr.ss_family != sa->sa_family) {
2382 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2385 if (ap->a_addr.ss_family == AF_INET) {
2386 sin4 = (struct sockaddr_in *)sa;
2387 a4p = (struct sockaddr_in *)&ap->a_addr;
2388 m4p = (struct sockaddr_in *)&ap->a_mask;
2389 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2390 != a4p->sin_addr.s_addr) {
2391 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2396 else if (ap->a_addr.ss_family == AF_INET6) {
2397 sin6 = (struct sockaddr_in6 *)sa;
2398 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2399 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2400 if (a6p->sin6_scope_id != 0 &&
2401 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2402 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2406 for (j = 0; j < 16; j += 4) {
2407 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2408 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2414 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2425 /* allow wildmatch */
2428 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2429 dprintf("rejected in rule %d due to name mismatch.\n", i);
2435 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2436 dprintf("rejected in rule %d due to name mismatch.\n", i);
2441 dprintf("accepted in rule %d.\n", i);
2442 return (1); /* hooray! */
2448 * Fairly similar to popen(3), but returns an open descriptor, as
2449 * opposed to a FILE *.
2452 p_open(const char *prog, pid_t *rpid)
2454 int pfd[2], nulldesc, i;
2456 sigset_t omask, mask;
2457 char *argv[4]; /* sh -c cmd NULL */
2460 if (pipe(pfd) == -1)
2462 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2463 /* we are royally screwed anyway */
2467 sigaddset(&mask, SIGALRM);
2468 sigaddset(&mask, SIGHUP);
2469 sigprocmask(SIG_BLOCK, &mask, &omask);
2470 switch ((pid = fork())) {
2472 sigprocmask(SIG_SETMASK, &omask, 0);
2477 argv[0] = strdup("sh");
2478 argv[1] = strdup("-c");
2479 argv[2] = strdup(prog);
2481 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2487 (void)setsid(); /* Avoid catching SIGHUPs. */
2490 * Throw away pending signals, and reset signal
2491 * behaviour to standard values.
2493 signal(SIGALRM, SIG_IGN);
2494 signal(SIGHUP, SIG_IGN);
2495 sigprocmask(SIG_SETMASK, &omask, 0);
2496 signal(SIGPIPE, SIG_DFL);
2497 signal(SIGQUIT, SIG_DFL);
2498 signal(SIGALRM, SIG_DFL);
2499 signal(SIGHUP, SIG_DFL);
2501 dup2(pfd[0], STDIN_FILENO);
2502 dup2(nulldesc, STDOUT_FILENO);
2503 dup2(nulldesc, STDERR_FILENO);
2504 for (i = getdtablesize(); i > 2; i--)
2507 (void)execvp(_PATH_BSHELL, argv);
2511 sigprocmask(SIG_SETMASK, &omask, 0);
2515 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2516 * supposed to get an EWOULDBLOCK on writev(2), which is
2517 * caught by the logic above anyway, which will in turn close
2518 * the pipe, and fork a new logging subprocess if necessary.
2519 * The stale subprocess will be killed some time later unless
2520 * it terminated itself due to closing its input pipe (so we
2521 * get rid of really dead puppies).
2523 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2525 (void)snprintf(errmsg, sizeof errmsg,
2526 "Warning: cannot change pipe to PID %d to "
2527 "non-blocking behaviour.",
2536 deadq_enter(pid_t pid, const char *name)
2542 * Be paranoid, if we can't signal the process, don't enter it
2543 * into the dead queue (perhaps it's already dead). If possible,
2544 * we try to fetch and log the child's status.
2546 if (kill(pid, 0) != 0) {
2547 if (waitpid(pid, &status, WNOHANG) > 0)
2548 log_deadchild(pid, status, name);
2552 p = malloc(sizeof(struct deadq_entry));
2559 p->dq_timeout = DQ_TIMO_INIT;
2560 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2564 deadq_remove(pid_t pid)
2568 TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2569 if (q->dq_pid == pid) {
2570 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2580 log_deadchild(pid_t pid, int status, const char *name)
2586 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2587 if (WIFSIGNALED(status)) {
2588 reason = "due to signal";
2589 code = WTERMSIG(status);
2591 reason = "with status";
2592 code = WEXITSTATUS(status);
2596 (void)snprintf(buf, sizeof buf,
2597 "Logging subprocess %d (%s) exited %s %d.",
2598 pid, name, reason, code);
2603 socksetup(int af, const char *bindhostname)
2605 struct addrinfo hints, *res, *r;
2606 int error, maxs, *s, *socks;
2608 memset(&hints, 0, sizeof(hints));
2609 hints.ai_flags = AI_PASSIVE;
2610 hints.ai_family = af;
2611 hints.ai_socktype = SOCK_DGRAM;
2612 error = getaddrinfo(bindhostname, "syslog", &hints, &res);
2614 logerror(gai_strerror(error));
2619 /* Count max number of sockets we may open */
2620 for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2621 socks = malloc((maxs+1) * sizeof(int));
2622 if (socks == NULL) {
2623 logerror("couldn't allocate memory for sockets");
2627 *socks = 0; /* num of sockets counter at start of array */
2629 for (r = res; r; r = r->ai_next) {
2631 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2636 if (r->ai_family == AF_INET6) {
2637 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2638 (char *)&on, sizeof (on)) < 0) {
2639 logerror("setsockopt");
2644 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2645 (char *)&on, sizeof (on)) < 0) {
2646 logerror("setsockopt");
2650 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2678 socklen_t slen, len;
2680 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2682 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, slen);