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 /* Maximum number of characters in time of last occurrence */
73 #define MAXLINE 1024 /* maximum line length */
74 #define MAXSVLINE MAXLINE /* maximum saved line length */
75 #define DEFUPRI (LOG_USER|LOG_NOTICE)
76 #define DEFSPRI (LOG_KERN|LOG_CRIT)
77 #define TIMERINTVL 30 /* interval for checking flush, mark */
78 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
79 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
81 #include <sys/param.h>
82 #include <sys/ioctl.h>
84 #include <sys/queue.h>
85 #include <sys/resource.h>
86 #include <sys/socket.h>
88 #include <sys/syslimits.h>
93 #include <sys/types.h>
95 #include <netinet/in.h>
97 #include <arpa/inet.h>
110 #include <sysexits.h>
114 #include "pathnames.h"
118 #include <sys/syslog.h>
120 const char *ConfFile = _PATH_LOGCONF;
121 const char *PidFile = _PATH_LOGPID;
122 const char ctty[] = _PATH_CONSOLE;
124 #define dprintf if (Debug) printf
126 #define MAXUNAMES 20 /* maximum number of user names */
130 * We have two default sockets, one with 666 permissions,
131 * and one for privileged programs.
137 STAILQ_ENTRY(funix) next;
139 struct funix funix_secure = { -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
141 struct funix funix_default = { -1, _PATH_LOG, DEFFILEMODE,
144 STAILQ_HEAD(, funix) funixes = { &funix_default,
145 &(funix_secure.next.stqe_next) };
151 #define IGN_CONS 0x001 /* don't print on console */
152 #define SYNC_FILE 0x002 /* do fsync on file after printing */
153 #define ADDDATE 0x004 /* add a date to the message */
154 #define MARK 0x008 /* this message is a mark */
155 #define ISKERNEL 0x010 /* kernel generated message */
158 * This structure represents the files that will have log
160 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
161 * or if f_type if F_PIPE and f_pid > 0.
165 struct filed *f_next; /* next in linked list */
166 short f_type; /* entry type, see below */
167 short f_file; /* file descriptor */
168 time_t f_time; /* time this was last written */
169 char *f_host; /* host from which to recd. */
170 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
171 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
175 char *f_program; /* program this applies to */
177 char f_uname[MAXUNAMES][MAXLOGNAME];
179 char f_hname[MAXHOSTNAMELEN];
180 struct addrinfo *f_addr;
182 } f_forw; /* forwarding address */
183 char f_fname[MAXPATHLEN];
185 char f_pname[MAXPATHLEN];
189 char f_prevline[MAXSVLINE]; /* last message logged */
190 char f_lasttime[MAXDATELEN]; /* time of last occurrence */
191 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
192 int f_prevpri; /* pri of f_prevline */
193 int f_prevlen; /* length of f_prevline */
194 int f_prevcount; /* repetition cnt of prevline */
195 u_int f_repeatcount; /* number of "repeated" msgs */
196 int f_flags; /* file-specific flags */
197 #define FFLAG_SYNC 0x01
198 #define FFLAG_NEEDSYNC 0x02
202 * Queue of about-to-be dead processes we should watch out for.
205 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
206 struct stailhead *deadq_headp;
211 TAILQ_ENTRY(deadq_entry) dq_entries;
215 * The timeout to apply to processes waiting on the dead queue. Unit
216 * of measure is `mark intervals', i.e. 20 minutes by default.
217 * Processes on the dead queue will be terminated after that time.
220 #define DQ_TIMO_INIT 2
222 typedef struct deadq_entry *dq_t;
226 * Struct to hold records of network addresses that are allowed to log
234 struct sockaddr_storage addr;
235 struct sockaddr_storage mask;
239 #define a_addr u.numeric.addr
240 #define a_mask u.numeric.mask
241 #define a_name u.name
246 * Intervals at which we flush out "message repeated" messages,
247 * in seconds after previous message is logged. After each flush,
248 * we move to the next interval until we reach the largest.
250 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
251 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
252 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
253 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
254 (f)->f_repeatcount = MAXREPEAT; \
257 /* values for f_type */
258 #define F_UNUSED 0 /* unused entry */
259 #define F_FILE 1 /* regular file */
260 #define F_TTY 2 /* terminal */
261 #define F_CONSOLE 3 /* console terminal */
262 #define F_FORW 4 /* remote machine */
263 #define F_USERS 5 /* list of users */
264 #define F_WALL 6 /* everyone logged on */
265 #define F_PIPE 7 /* pipe to program */
267 const char *TypeNames[8] = {
268 "UNUSED", "FILE", "TTY", "CONSOLE",
269 "FORW", "USERS", "WALL", "PIPE"
272 static struct filed *Files; /* Log files that we write to */
273 static struct filed consfile; /* Console */
275 static int Debug; /* debug flag */
276 static int Foreground = 0; /* Run in foreground, instead of daemonizing */
277 static int resolve = 1; /* resolve hostname */
278 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
279 static const char *LocalDomain; /* our local domain name */
280 static int *finet; /* Internet datagram socket */
281 static int fklog = -1; /* /dev/klog */
282 static int Initialized; /* set when we have initialized ourselves */
283 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
284 static int MarkSeq; /* mark sequence number */
285 static int NoBind; /* don't bind() as suggested by RFC 3164 */
286 static int SecureMode; /* when true, receive only unix domain socks */
288 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
290 static int family = PF_INET; /* protocol family (IPv4 only) */
292 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
293 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
294 static int use_bootfile; /* log entire bootfile for every kern msg */
295 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
296 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
298 static char bootfile[MAXLINE+1]; /* booted kernel file */
300 struct allowedpeer *AllowedPeers; /* List of allowed peers */
301 static int NumAllowed; /* Number of entries in AllowedPeers */
302 static int RemoteAddDate; /* Always set the date on remote messages */
304 static int UniquePriority; /* Only log specified priority? */
305 static int LogFacPri; /* Put facility and priority in log message: */
306 /* 0=no, 1=numeric, 2=names */
307 static int KeepKernFac; /* Keep remotely logged kernel facility */
308 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
309 static struct pidfh *pfh;
311 volatile sig_atomic_t MarkSet, WantDie;
313 static int allowaddr(char *);
314 static void cfline(const char *, struct filed *,
315 const char *, const char *);
316 static const char *cvthname(struct sockaddr *);
317 static void deadq_enter(pid_t, const char *);
318 static int deadq_remove(pid_t);
319 static int decode(const char *, const CODE *);
320 static void die(int);
321 static void dodie(int);
322 static void dofsync(void);
323 static void domark(int);
324 static void fprintlog(struct filed *, int, const char *);
325 static int *socksetup(int, char *);
326 static void init(int);
327 static void logerror(const char *);
328 static void logmsg(int, const char *, const char *, int);
329 static void log_deadchild(pid_t, int, const char *);
330 static void markit(void);
331 static int skip_message(const char *, const char *, int);
332 static void printline(const char *, char *, int);
333 static void printsys(char *);
334 static int p_open(const char *, pid_t *);
335 static void readklog(void);
336 static void reapchild(int);
337 static void usage(void);
338 static int validate(struct sockaddr *, const char *);
339 static void unmapped(struct sockaddr *);
340 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
341 static int waitdaemon(int, int, int);
342 static void timedout(int);
343 static void increase_rcvbuf(int);
346 close_filed(struct filed *f)
349 if (f == NULL || f->f_file == -1)
357 f->f_type = F_UNUSED;
360 f->f_un.f_pipe.f_pid = 0;
363 (void)close(f->f_file);
368 main(int argc, char *argv[])
370 int ch, i, fdsrmax = 0, l;
371 struct sockaddr_un sunx, fromunix;
372 struct sockaddr_storage frominet;
374 char line[MAXLINE + 1];
377 struct timeval tv, *tvp;
378 struct sigaction sact;
379 struct funix *fx, *fx1;
381 pid_t ppid = 1, spid;
384 if (madvise(NULL, 0, MADV_PROTECT) != 0)
385 dprintf("madvise() failed: %s\n", strerror(errno));
388 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:Fkl:m:nNop:P:sS:Tuv"))
405 case 'a': /* allow specific network addresses only */
406 if (allowaddr(optarg) == -1)
410 bindhostname = optarg;
418 case 'd': /* debug */
421 case 'f': /* configuration file */
424 case 'F': /* run in foreground instead of daemon */
427 case 'k': /* keep remote kern fac */
436 if (optarg[0] == '/') {
439 } else if ((name = strchr(optarg, ':')) != NULL) {
442 errx(1, "socket name must be absolute "
444 if (isdigit(*optarg)) {
445 perml = strtol(optarg, &ep, 8);
446 if (*ep || perml < 0 ||
447 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
448 errx(1, "invalid mode %s, exiting",
450 mode = (mode_t )perml;
452 errx(1, "invalid mode %s, exiting",
454 } else /* doesn't begin with '/', and no ':' */
455 errx(1, "can't parse path %s", optarg);
457 if (strlen(name) >= sizeof(sunx.sun_path))
458 errx(1, "%s path too long, exiting", name);
459 if ((fx = malloc(sizeof(struct funix))) == NULL)
460 errx(1, "malloc failed");
464 STAILQ_INSERT_TAIL(&funixes, fx, next);
467 case 'm': /* mark interval */
468 MarkInterval = atoi(optarg) * 60;
481 if (strlen(optarg) >= sizeof(sunx.sun_path))
482 errx(1, "%s path too long, exiting", optarg);
483 funix_default.name = optarg;
485 case 'P': /* path for alt. PID */
488 case 's': /* no network mode */
491 case 'S': /* path for privileged originator */
492 if (strlen(optarg) >= sizeof(sunx.sun_path))
493 errx(1, "%s path too long, exiting", optarg);
494 funix_secure.name = optarg;
499 case 'u': /* only log specified priority */
502 case 'v': /* log facility and priority */
508 if ((argc -= optind) != 0)
511 pfh = pidfile_open(PidFile, 0600, &spid);
514 errx(1, "syslogd already running, pid: %d", spid);
515 warn("cannot open pid file");
518 if ((!Foreground) && (!Debug)) {
519 ppid = waitdaemon(0, 0, 30);
521 warn("could not become daemon");
532 consfile.f_type = F_CONSOLE;
533 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
534 sizeof(consfile.f_un.f_fname));
535 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
536 (void)signal(SIGTERM, dodie);
537 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
538 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
540 * We don't want the SIGCHLD and SIGHUP handlers to interfere
541 * with each other; they are likely candidates for being called
542 * simultaneously (SIGHUP closes pipe descriptor, process dies,
546 sigaddset(&mask, SIGHUP);
547 sact.sa_handler = reapchild;
549 sact.sa_flags = SA_RESTART;
550 (void)sigaction(SIGCHLD, &sact, NULL);
551 (void)signal(SIGALRM, domark);
552 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
553 (void)alarm(TIMERINTVL);
555 TAILQ_INIT(&deadq_head);
558 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
560 STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
561 (void)unlink(fx->name);
562 memset(&sunx, 0, sizeof(sunx));
563 sunx.sun_family = AF_LOCAL;
564 (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
565 fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
567 bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
568 chmod(fx->name, fx->mode) < 0) {
569 (void)snprintf(line, sizeof line,
570 "cannot create %s", fx->name);
572 dprintf("cannot create %s (%d)\n", fx->name, errno);
573 if (fx == &funix_default || fx == &funix_secure)
576 STAILQ_REMOVE(&funixes, fx, funix, next);
580 increase_rcvbuf(fx->s);
583 finet = socksetup(family, bindhostname);
587 for (i = 0; i < *finet; i++) {
588 if (shutdown(finet[i+1], SHUT_RD) < 0 &&
590 logerror("shutdown");
596 dprintf("listening on inet and/or inet6 socket\n");
598 dprintf("sending on inet and/or inet6 socket\n");
601 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
602 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
605 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
607 /* tuck my process id away */
610 dprintf("off & running....\n");
613 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
615 sigaddset(&mask, SIGCHLD);
616 sact.sa_handler = init;
618 sact.sa_flags = SA_RESTART;
619 (void)sigaction(SIGHUP, &sact, NULL);
622 tv.tv_sec = tv.tv_usec = 0;
624 if (fklog != -1 && fklog > fdsrmax)
626 if (finet && !SecureMode) {
627 for (i = 0; i < *finet; i++) {
628 if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
629 fdsrmax = finet[i+1];
632 STAILQ_FOREACH(fx, &funixes, next)
636 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
639 errx(1, "calloc fd_set");
647 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
652 if (finet && !SecureMode) {
653 for (i = 0; i < *finet; i++) {
654 if (finet[i+1] != -1)
655 FD_SET(finet[i+1], fdsr);
658 STAILQ_FOREACH(fx, &funixes, next)
661 i = select(fdsrmax+1, fdsr, NULL, NULL,
662 needdofsync ? &tv : tvp);
678 if (fklog != -1 && FD_ISSET(fklog, fdsr))
680 if (finet && !SecureMode) {
681 for (i = 0; i < *finet; i++) {
682 if (FD_ISSET(finet[i+1], fdsr)) {
683 len = sizeof(frominet);
684 l = recvfrom(finet[i+1], line, MAXLINE,
685 0, (struct sockaddr *)&frominet,
689 hname = cvthname((struct sockaddr *)&frominet);
690 unmapped((struct sockaddr *)&frominet);
691 if (validate((struct sockaddr *)&frominet, hname))
692 printline(hname, line, RemoteAddDate ? ADDDATE : 0);
693 } else if (l < 0 && errno != EINTR)
694 logerror("recvfrom inet");
698 STAILQ_FOREACH(fx, &funixes, next) {
699 if (FD_ISSET(fx->s, fdsr)) {
700 len = sizeof(fromunix);
701 l = recvfrom(fx->s, line, MAXLINE, 0,
702 (struct sockaddr *)&fromunix, &len);
705 printline(LocalHostName, line, 0);
706 } else if (l < 0 && errno != EINTR)
707 logerror("recvfrom unix");
716 unmapped(struct sockaddr *sa)
718 struct sockaddr_in6 *sin6;
719 struct sockaddr_in sin4;
721 if (sa->sa_family != AF_INET6)
723 if (sa->sa_len != sizeof(struct sockaddr_in6) ||
724 sizeof(sin4) > sa->sa_len)
726 sin6 = (struct sockaddr_in6 *)sa;
727 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
730 memset(&sin4, 0, sizeof(sin4));
731 sin4.sin_family = AF_INET;
732 sin4.sin_len = sizeof(struct sockaddr_in);
733 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
734 sizeof(sin4.sin_addr));
735 sin4.sin_port = sin6->sin6_port;
737 memcpy(sa, &sin4, sin4.sin_len);
744 fprintf(stderr, "%s\n%s\n%s\n%s\n",
745 "usage: syslogd [-468ACcdFknosTuv] [-a allowed_peer]",
746 " [-b bind_address] [-f config_file]",
747 " [-l [mode:]path] [-m mark_interval]",
748 " [-P pid_file] [-p log_socket]");
753 * Take a raw input line, decode the message, and print the message
754 * on the appropriate log files.
757 printline(const char *hname, char *msg, int flags)
762 char line[MAXLINE + 1];
764 /* test for special codes */
769 n = strtol(p + 1, &q, 10);
770 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
775 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
779 * Don't allow users to log kernel messages.
780 * NOTE: since LOG_KERN == 0 this will also match
781 * messages with no facility specified.
783 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
784 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
788 while ((c = (unsigned char)*p++) != '\0' &&
789 q < &line[sizeof(line) - 4]) {
790 if (mask_C1 && (c & 0x80) && c < 0xA0) {
795 if (isascii(c) && iscntrl(c)) {
798 } else if (c == '\t') {
810 logmsg(pri, line, hname, flags);
814 * Read /dev/klog while data are available, split into lines.
819 char *p, *q, line[MAXLINE + 1];
824 i = read(fklog, line + len, MAXLINE - 1 - len);
826 line[i + len] = '\0';
828 if (i < 0 && errno != EINTR && errno != EAGAIN) {
835 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
840 if (len >= MAXLINE - 1) {
845 memmove(line, p, len + 1);
852 * Take a raw input line from /dev/klog, format similar to syslog().
859 int flags, isprintf, pri;
861 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
867 n = strtol(p + 1, &q, 10);
868 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
875 * Kernel printf's and LOG_CONSOLE messages have been displayed
876 * on the console already.
878 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
880 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
882 logmsg(pri, p, LocalHostName, flags);
888 * Match a program or host name against a specification.
889 * Return a non-0 value if the message must be ignored
890 * based on the specification.
893 skip_message(const char *name, const char *spec, int checkcase)
898 /* Behaviour on explicit match */
913 s = strstr (spec, name);
915 s = strcasestr (spec, name);
918 prev = (s == spec ? ',' : *(s - 1));
919 next = *(s + strlen (name));
921 if (prev == ',' && (next == '\0' || next == ','))
922 /* Explicit match: skip iff the spec is an
927 /* No explicit match for this name: skip the message iff
928 the spec is an inclusive one. */
933 * Log a message to the appropriate log files, users, etc. based on
937 logmsg(int pri, const char *msg, const char *from, int flags)
940 int i, fac, msglen, omask, prilev;
941 const char *timestamp;
942 char prog[NAME_MAX+1];
945 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
946 pri, flags, from, msg);
948 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
951 * Check to see if msg looks non-standard.
953 msglen = strlen(msg);
954 if (msglen < MAXDATELEN || msg[3] != ' ' || msg[6] != ' ' ||
955 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
959 if (flags & ADDDATE) {
960 timestamp = ctime(&now) + 4;
964 msglen -= MAXDATELEN;
967 /* skip leading blanks */
968 while (isspace(*msg)) {
973 /* extract facility and priority level */
975 fac = LOG_NFACILITIES;
979 /* Check maximum facility number. */
980 if (fac > LOG_NFACILITIES) {
981 (void)sigsetmask(omask);
985 prilev = LOG_PRI(pri);
987 /* extract program name */
988 for (i = 0; i < NAME_MAX; i++) {
989 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
990 msg[i] == '/' || isspace(msg[i]))
996 /* add kernel prefix for kernel messages */
997 if (flags & ISKERNEL) {
998 snprintf(buf, sizeof(buf), "%s: %s",
999 use_bootfile ? bootfile : "kernel", msg);
1001 msglen = strlen(buf);
1004 /* log the message to the particular outputs */
1008 * Open in non-blocking mode to avoid hangs during open
1009 * and close(waiting for the port to drain).
1011 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1013 if (f->f_file >= 0) {
1014 (void)strlcpy(f->f_lasttime, timestamp,
1015 sizeof(f->f_lasttime));
1016 fprintlog(f, flags, msg);
1020 (void)sigsetmask(omask);
1023 for (f = Files; f; f = f->f_next) {
1024 /* skip messages that are incorrect priority */
1025 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1026 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1027 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1029 || f->f_pmask[fac] == INTERNAL_NOPRI)
1032 /* skip messages with the incorrect hostname */
1033 if (skip_message(from, f->f_host, 0))
1036 /* skip messages with the incorrect program name */
1037 if (skip_message(prog, f->f_program, 1))
1040 /* skip message to console if it has already been printed */
1041 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1044 /* don't output marks to recently written files */
1045 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1049 * suppress duplicate lines to this file
1051 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1052 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1053 !strcmp(msg, f->f_prevline) &&
1054 !strcasecmp(from, f->f_prevhost)) {
1055 (void)strlcpy(f->f_lasttime, timestamp,
1056 sizeof(f->f_lasttime));
1058 dprintf("msg repeated %d times, %ld sec of %d\n",
1059 f->f_prevcount, (long)(now - f->f_time),
1060 repeatinterval[f->f_repeatcount]);
1062 * If domark would have logged this by now,
1063 * flush it now (so we don't hold isolated messages),
1064 * but back off so we'll flush less often
1067 if (now > REPEATTIME(f)) {
1068 fprintlog(f, flags, (char *)NULL);
1072 /* new line, save it */
1074 fprintlog(f, 0, (char *)NULL);
1075 f->f_repeatcount = 0;
1077 (void)strlcpy(f->f_lasttime, timestamp,
1078 sizeof(f->f_lasttime));
1079 (void)strlcpy(f->f_prevhost, from,
1080 sizeof(f->f_prevhost));
1081 if (msglen < MAXSVLINE) {
1082 f->f_prevlen = msglen;
1083 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1084 fprintlog(f, flags, (char *)NULL);
1086 f->f_prevline[0] = 0;
1088 fprintlog(f, flags, msg);
1092 (void)sigsetmask(omask);
1100 for (f = Files; f; f = f->f_next) {
1101 if ((f->f_type == F_FILE) &&
1102 (f->f_flags & FFLAG_NEEDSYNC)) {
1103 f->f_flags &= ~FFLAG_NEEDSYNC;
1104 (void)fsync(f->f_file);
1111 fprintlog(struct filed *f, int flags, const char *msg)
1113 struct iovec iov[IOV_SIZE];
1116 int i, l, lsent = 0;
1117 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1118 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1122 if (f->f_type == F_WALL) {
1123 v->iov_base = greetings;
1124 /* The time displayed is not synchornized with the other log
1125 * destinations (like messages). Following fragment was using
1126 * ctime(&now), which was updating the time every 30 sec.
1127 * With f_lasttime, time is synchronized correctly.
1129 v->iov_len = snprintf(greetings, sizeof greetings,
1130 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1131 f->f_prevhost, f->f_lasttime);
1132 if (v->iov_len >= sizeof greetings)
1133 v->iov_len = sizeof greetings - 1;
1139 v->iov_base = f->f_lasttime;
1140 v->iov_len = strlen(f->f_lasttime);
1142 v->iov_base = space;
1148 static char fp_buf[30]; /* Hollow laugh */
1149 int fac = f->f_prevpri & LOG_FACMASK;
1150 int pri = LOG_PRI(f->f_prevpri);
1151 const char *f_s = NULL;
1152 char f_n[5]; /* Hollow laugh */
1153 const char *p_s = NULL;
1154 char p_n[5]; /* Hollow laugh */
1156 if (LogFacPri > 1) {
1159 for (c = facilitynames; c->c_name; c++) {
1160 if (c->c_val == fac) {
1165 for (c = prioritynames; c->c_name; c++) {
1166 if (c->c_val == pri) {
1173 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1177 snprintf(p_n, sizeof p_n, "%d", pri);
1180 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1181 v->iov_base = fp_buf;
1182 v->iov_len = strlen(fp_buf);
1189 v->iov_base = f->f_prevhost;
1190 v->iov_len = strlen(v->iov_base);
1192 v->iov_base = space;
1197 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1203 v->iov_len = strlen(msg);
1204 } else if (f->f_prevcount > 1) {
1205 v->iov_base = repbuf;
1206 v->iov_len = snprintf(repbuf, sizeof repbuf,
1207 "last message repeated %d times", f->f_prevcount);
1209 v->iov_base = f->f_prevline;
1210 v->iov_len = f->f_prevlen;
1214 dprintf("Logging to %s", TypeNames[f->f_type]);
1217 switch (f->f_type) {
1224 port = (int)ntohs(((struct sockaddr_in *)
1225 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1227 dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1229 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1231 /* check for local vs remote messages */
1232 if (strcasecmp(f->f_prevhost, LocalHostName))
1233 l = snprintf(line, sizeof line - 1,
1234 "<%d>%.15s Forwarded from %s: %s",
1235 f->f_prevpri, (char *)iov[0].iov_base,
1236 f->f_prevhost, (char *)iov[5].iov_base);
1238 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1239 f->f_prevpri, (char *)iov[0].iov_base,
1240 (char *)iov[5].iov_base);
1243 else if (l > MAXLINE)
1247 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1248 for (i = 0; i < *finet; i++) {
1251 * should we check AF first, or just
1252 * trial and error? FWD
1255 address_family_of(finet[i+1]))
1257 lsent = sendto(finet[i+1], line, l, 0,
1258 r->ai_addr, r->ai_addrlen);
1262 if (lsent == l && !send_to_all)
1265 dprintf("lsent/l: %d/%d\n", lsent, l);
1280 /* case ENOTSOCK: */
1282 /* case EMSGSIZE: */
1285 /* case ECONNREFUSED: */
1287 dprintf("removing entry: errno=%d\n", e);
1288 f->f_type = F_UNUSED;
1296 dprintf(" %s\n", f->f_un.f_fname);
1299 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1301 * If writev(2) fails for potentially transient errors
1302 * like the filesystem being full, ignore it.
1303 * Otherwise remove this logfile from the list.
1305 if (errno != ENOSPC) {
1309 logerror(f->f_un.f_fname);
1311 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1312 f->f_flags |= FFLAG_NEEDSYNC;
1318 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1321 if (f->f_un.f_pipe.f_pid == 0) {
1322 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1323 &f->f_un.f_pipe.f_pid)) < 0) {
1324 logerror(f->f_un.f_pipe.f_pname);
1328 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1332 deadq_enter(f->f_un.f_pipe.f_pid,
1333 f->f_un.f_pipe.f_pname);
1335 logerror(f->f_un.f_pipe.f_pname);
1340 if (flags & IGN_CONS) {
1341 dprintf(" (ignored)\n");
1347 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1351 errno = 0; /* ttymsg() only sometimes returns an errno */
1352 if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1353 f->f_type = F_UNUSED;
1363 wallmsg(f, iov, IOV_SIZE);
1371 * WALLMSG -- Write a message to the world at large
1373 * Write the specified message to either the entire
1374 * world, or a list of approved users.
1377 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1379 static int reenter; /* avoid calling ourselves */
1388 while ((ut = getutxent()) != NULL) {
1389 if (ut->ut_type != USER_PROCESS)
1391 if (f->f_type == F_WALL) {
1392 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1393 TTYMSGTIME)) != NULL) {
1394 errno = 0; /* already in msg */
1399 /* should we send the message to this user? */
1400 for (i = 0; i < MAXUNAMES; i++) {
1401 if (!f->f_un.f_uname[i][0])
1403 if (!strcmp(f->f_un.f_uname[i], ut->ut_user)) {
1404 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1405 TTYMSGTIME)) != NULL) {
1406 errno = 0; /* already in msg */
1418 reapchild(int signo __unused)
1424 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1426 /* Don't tell while we are initting. */
1429 /* First, look if it's a process from the dead queue. */
1430 if (deadq_remove(pid))
1433 /* Now, look in list of active processes. */
1434 for (f = Files; f; f = f->f_next)
1435 if (f->f_type == F_PIPE &&
1436 f->f_un.f_pipe.f_pid == pid) {
1438 log_deadchild(pid, status,
1439 f->f_un.f_pipe.f_pname);
1448 * Return a printable representation of a host address.
1451 cvthname(struct sockaddr *f)
1454 sigset_t omask, nmask;
1455 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1457 error = getnameinfo((struct sockaddr *)f,
1458 ((struct sockaddr *)f)->sa_len,
1459 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1460 dprintf("cvthname(%s)\n", ip);
1463 dprintf("Malformed from address %s\n", gai_strerror(error));
1469 sigemptyset(&nmask);
1470 sigaddset(&nmask, SIGHUP);
1471 sigprocmask(SIG_BLOCK, &nmask, &omask);
1472 error = getnameinfo((struct sockaddr *)f,
1473 ((struct sockaddr *)f)->sa_len,
1474 hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1475 sigprocmask(SIG_SETMASK, &omask, NULL);
1477 dprintf("Host name for your address (%s) unknown\n", ip);
1481 if (hl > 0 && hname[hl-1] == '.')
1483 trimdomain(hname, hl);
1495 domark(int signo __unused)
1502 * Print syslogd errors some place.
1505 logerror(const char *type)
1508 static int recursed = 0;
1510 /* If there's an error while trying to log an error, give up. */
1516 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1518 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1520 dprintf("%s\n", buf);
1521 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1530 int was_initialized;
1533 was_initialized = Initialized;
1534 Initialized = 0; /* Don't log SIGCHLDs. */
1535 for (f = Files; f != NULL; f = f->f_next) {
1536 /* flush any pending output */
1538 fprintlog(f, 0, (char *)NULL);
1539 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0)
1542 Initialized = was_initialized;
1544 dprintf("syslogd: exiting on signal %d\n", signo);
1545 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1549 STAILQ_FOREACH(fx, &funixes, next)
1550 (void)unlink(fx->name);
1551 pidfile_remove(pfh);
1557 * INIT -- Initialize syslogd from configuration table
1564 struct filed *f, *next, **nextp;
1566 char cline[LINE_MAX];
1567 char prog[LINE_MAX];
1568 char host[MAXHOSTNAMELEN];
1569 char oldLocalHostName[MAXHOSTNAMELEN];
1570 char hostMsg[2*MAXHOSTNAMELEN+40];
1571 char bootfileMsg[LINE_MAX];
1576 * Load hostname (may have changed).
1579 (void)strlcpy(oldLocalHostName, LocalHostName,
1580 sizeof(oldLocalHostName));
1581 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1582 err(EX_OSERR, "gethostname() failed");
1583 if ((p = strchr(LocalHostName, '.')) != NULL) {
1591 * Close all open log files.
1594 for (f = Files; f != NULL; f = next) {
1595 /* flush any pending output */
1597 fprintlog(f, 0, (char *)NULL);
1599 switch (f->f_type) {
1608 deadq_enter(f->f_un.f_pipe.f_pid,
1609 f->f_un.f_pipe.f_pname);
1613 if (f->f_program) free(f->f_program);
1614 if (f->f_host) free(f->f_host);
1620 /* open the configuration file */
1621 if ((cf = fopen(ConfFile, "r")) == NULL) {
1622 dprintf("cannot open %s\n", ConfFile);
1623 *nextp = (struct filed *)calloc(1, sizeof(*f));
1624 if (*nextp == NULL) {
1628 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1629 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1630 if ((*nextp)->f_next == NULL) {
1634 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1640 * Foreach line in the conf table, open that file.
1643 (void)strlcpy(host, "*", sizeof(host));
1644 (void)strlcpy(prog, "*", sizeof(prog));
1645 while (fgets(cline, sizeof(cline), cf) != NULL) {
1647 * check for end-of-section, comments, strip off trailing
1648 * spaces and newline character. #!prog is treated specially:
1649 * following lines apply only to that program.
1651 for (p = cline; isspace(*p); ++p)
1657 if (*p != '!' && *p != '+' && *p != '-')
1660 if (*p == '+' || *p == '-') {
1664 if ((!*p) || (*p == '*')) {
1665 (void)strlcpy(host, "*", sizeof(host));
1670 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1671 if (!isalnum(*p) && *p != '.' && *p != '-'
1672 && *p != ',' && *p != ':' && *p != '%')
1681 while (isspace(*p)) p++;
1682 if ((!*p) || (*p == '*')) {
1683 (void)strlcpy(prog, "*", sizeof(prog));
1686 for (i = 0; i < LINE_MAX - 1; i++) {
1687 if (!isprint(p[i]) || isspace(p[i]))
1694 for (p = cline + 1; *p != '\0'; p++) {
1697 if (*(p - 1) == '\\') {
1705 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1707 f = (struct filed *)calloc(1, sizeof(*f));
1714 cfline(cline, f, prog, host);
1717 /* close the configuration file */
1724 for (f = Files; f; f = f->f_next) {
1725 for (i = 0; i <= LOG_NFACILITIES; i++)
1726 if (f->f_pmask[i] == INTERNAL_NOPRI)
1729 printf("%d ", f->f_pmask[i]);
1730 printf("%s: ", TypeNames[f->f_type]);
1731 switch (f->f_type) {
1733 printf("%s", f->f_un.f_fname);
1738 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1742 port = (int)ntohs(((struct sockaddr_in *)
1743 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1746 f->f_un.f_forw.f_hname, port);
1748 printf("%s", f->f_un.f_forw.f_hname);
1753 printf("%s", f->f_un.f_pipe.f_pname);
1757 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1758 printf("%s, ", f->f_un.f_uname[i]);
1762 printf(" (%s)", f->f_program);
1767 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1768 dprintf("syslogd: restarted\n");
1770 * Log a change in hostname, but only on a restart.
1772 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1773 (void)snprintf(hostMsg, sizeof(hostMsg),
1774 "syslogd: hostname changed, \"%s\" to \"%s\"",
1775 oldLocalHostName, LocalHostName);
1776 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1777 dprintf("%s\n", hostMsg);
1780 * Log the kernel boot file if we aren't going to use it as
1781 * the prefix, and if this is *not* a restart.
1783 if (signo == 0 && !use_bootfile) {
1784 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1785 "syslogd: kernel boot file is %s", bootfile);
1786 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1787 dprintf("%s\n", bootfileMsg);
1792 * Crack a configuration file line
1795 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1797 struct addrinfo hints, *res;
1798 int error, i, pri, syncfile;
1801 char buf[MAXLINE], ebuf[100];
1803 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1805 errno = 0; /* keep strerror() stuff out of logerror messages */
1807 /* clear out file entry */
1808 memset(f, 0, sizeof(*f));
1809 for (i = 0; i <= LOG_NFACILITIES; i++)
1810 f->f_pmask[i] = INTERNAL_NOPRI;
1812 /* save hostname if any */
1813 if (host && *host == '*')
1818 f->f_host = strdup(host);
1819 if (f->f_host == NULL) {
1823 hl = strlen(f->f_host);
1824 if (hl > 0 && f->f_host[hl-1] == '.')
1825 f->f_host[--hl] = '\0';
1826 trimdomain(f->f_host, hl);
1829 /* save program name if any */
1830 if (prog && *prog == '*')
1833 f->f_program = strdup(prog);
1834 if (f->f_program == NULL) {
1840 /* scan through the list of selectors */
1841 for (p = line; *p && *p != '\t' && *p != ' ';) {
1846 /* find the end of this facility name list */
1847 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1850 /* get the priority comparison */
1878 /* collect priority name */
1879 for (bp = buf; *q && !strchr("\t,; ", *q); )
1884 while (strchr(",;", *q))
1887 /* decode priority name */
1890 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1892 /* Ignore trailing spaces. */
1893 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1896 pri = decode(buf, prioritynames);
1899 (void)snprintf(ebuf, sizeof ebuf,
1900 "unknown priority name \"%s\"", buf);
1906 pri_cmp = (UniquePriority)
1911 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1913 /* scan facilities */
1914 while (*p && !strchr("\t.; ", *p)) {
1915 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1920 for (i = 0; i < LOG_NFACILITIES; i++) {
1921 f->f_pmask[i] = pri;
1922 f->f_pcmp[i] = pri_cmp;
1925 i = decode(buf, facilitynames);
1928 (void)snprintf(ebuf, sizeof ebuf,
1929 "unknown facility name \"%s\"",
1934 f->f_pmask[i >> 3] = pri;
1935 f->f_pcmp[i >> 3] = pri_cmp;
1937 while (*p == ',' || *p == ' ')
1944 /* skip to action part */
1945 while (*p == '\t' || *p == ' ')
1960 * scan forward to see if there is a port defined.
1961 * so we can't use strlcpy..
1963 i = sizeof(f->f_un.f_forw.f_hname);
1964 tp = f->f_un.f_forw.f_hname;
1968 * an ipv6 address should start with a '[' in that case
1969 * we should scan for a ']'
1975 while (*p && (*p != endkey) && (i-- > 0)) {
1978 if (endkey == ']' && *p == endkey)
1982 /* See if we copied a domain and have a port */
1988 memset(&hints, 0, sizeof(hints));
1989 hints.ai_family = family;
1990 hints.ai_socktype = SOCK_DGRAM;
1991 error = getaddrinfo(f->f_un.f_forw.f_hname,
1992 p ? p : "syslog", &hints, &res);
1994 logerror(gai_strerror(error));
1997 f->f_un.f_forw.f_addr = res;
2002 if ((f->f_file = open(p, logflags, 0600)) < 0) {
2003 f->f_type = F_UNUSED;
2008 f->f_flags |= FFLAG_SYNC;
2009 if (isatty(f->f_file)) {
2010 if (strcmp(p, ctty) == 0)
2011 f->f_type = F_CONSOLE;
2014 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
2015 sizeof(f->f_un.f_fname));
2017 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2023 f->f_un.f_pipe.f_pid = 0;
2024 (void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2025 sizeof(f->f_un.f_pipe.f_pname));
2034 for (i = 0; i < MAXUNAMES && *p; i++) {
2035 for (q = p; *q && *q != ','; )
2037 (void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2038 if ((q - p) >= MAXLOGNAME)
2039 f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2041 f->f_un.f_uname[i][q - p] = '\0';
2042 while (*q == ',' || *q == ' ')
2046 f->f_type = F_USERS;
2053 * Decode a symbolic name to a numeric value
2056 decode(const char *name, const CODE *codetab)
2062 return (atoi(name));
2064 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2066 *p = tolower(*name);
2071 for (c = codetab; c->c_name; c++)
2072 if (!strcmp(buf, c->c_name))
2084 now = time((time_t *)NULL);
2085 MarkSeq += TIMERINTVL;
2086 if (MarkSeq >= MarkInterval) {
2087 logmsg(LOG_INFO, "-- MARK --",
2088 LocalHostName, ADDDATE|MARK);
2092 for (f = Files; f; f = f->f_next) {
2093 if (f->f_prevcount && now >= REPEATTIME(f)) {
2094 dprintf("flush %s: repeated %d times, %d sec.\n",
2095 TypeNames[f->f_type], f->f_prevcount,
2096 repeatinterval[f->f_repeatcount]);
2097 fprintlog(f, 0, (char *)NULL);
2102 /* Walk the dead queue, and see if we should signal somebody. */
2103 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2104 next = TAILQ_NEXT(q, dq_entries);
2106 switch (q->dq_timeout) {
2108 /* Already signalled once, try harder now. */
2109 if (kill(q->dq_pid, SIGKILL) != 0)
2110 (void)deadq_remove(q->dq_pid);
2115 * Timed out on dead queue, send terminate
2116 * signal. Note that we leave the removal
2117 * from the dead queue to reapchild(), which
2118 * will also log the event (unless the process
2119 * didn't even really exist, in case we simply
2120 * drop it from the dead queue).
2122 if (kill(q->dq_pid, SIGTERM) != 0)
2123 (void)deadq_remove(q->dq_pid);
2131 (void)alarm(TIMERINTVL);
2135 * fork off and become a daemon, but wait for the child to come online
2136 * before returning to the parent, or we get disk thrashing at boot etc.
2137 * Set a timer so we don't hang forever if it wedges.
2140 waitdaemon(int nochdir, int noclose, int maxwait)
2144 pid_t pid, childpid;
2146 switch (childpid = fork()) {
2152 signal(SIGALRM, timedout);
2154 while ((pid = wait3(&status, 0, NULL)) != -1) {
2155 if (WIFEXITED(status))
2156 errx(1, "child pid %d exited with return code %d",
2157 pid, WEXITSTATUS(status));
2158 if (WIFSIGNALED(status))
2159 errx(1, "child pid %d exited on signal %d%s",
2160 pid, WTERMSIG(status),
2161 WCOREDUMP(status) ? " (core dumped)" :
2163 if (pid == childpid) /* it's gone... */
2175 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2176 (void)dup2(fd, STDIN_FILENO);
2177 (void)dup2(fd, STDOUT_FILENO);
2178 (void)dup2(fd, STDERR_FILENO);
2186 * We get a SIGALRM from the child when it's running and finished doing it's
2187 * fsync()'s or O_SYNC writes for all the boot messages.
2189 * We also get a signal from the kernel if the timer expires, so check to
2190 * see what happened.
2193 timedout(int sig __unused)
2197 signal(SIGALRM, SIG_DFL);
2199 errx(1, "timed out waiting for child");
2205 * Add `s' to the list of allowable peer addresses to accept messages
2208 * `s' is a string in the form:
2210 * [*]domainname[:{servicename|portnumber|*}]
2214 * netaddr/maskbits[:{servicename|portnumber|*}]
2216 * Returns -1 on error, 0 if the argument was valid.
2222 struct allowedpeer ap;
2225 struct addrinfo hints, *res;
2226 struct in_addr *addrp, *maskp;
2229 u_int32_t *addr6p, *mask6p;
2231 char ip[NI_MAXHOST];
2234 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2237 if ((cp1 = strrchr(cp1, ':'))) {
2238 /* service/port provided */
2240 if (strlen(cp1) == 1 && *cp1 == '*')
2241 /* any port allowed */
2243 else if ((se = getservbyname(cp1, "udp"))) {
2244 ap.port = ntohs(se->s_port);
2246 ap.port = strtol(cp1, &cp2, 0);
2248 return (-1); /* port not numeric */
2251 if ((se = getservbyname("syslog", "udp")))
2252 ap.port = ntohs(se->s_port);
2254 /* sanity, should not happen */
2258 if ((cp1 = strchr(s, '/')) != NULL &&
2259 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2261 if ((masklen = atoi(cp1 + 1)) < 0)
2266 cp2 = s + strlen(s) - 1;
2277 memset(&hints, 0, sizeof(hints));
2278 hints.ai_family = PF_UNSPEC;
2279 hints.ai_socktype = SOCK_DGRAM;
2280 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2281 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2283 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2284 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2285 ap.a_mask.ss_family = res->ai_family;
2286 if (res->ai_family == AF_INET) {
2287 ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2288 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2289 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2291 /* use default netmask */
2292 if (IN_CLASSA(ntohl(addrp->s_addr)))
2293 maskp->s_addr = htonl(IN_CLASSA_NET);
2294 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2295 maskp->s_addr = htonl(IN_CLASSB_NET);
2297 maskp->s_addr = htonl(IN_CLASSC_NET);
2298 } else if (masklen <= 32) {
2299 /* convert masklen to netmask */
2303 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2308 /* Lose any host bits in the network number. */
2309 addrp->s_addr &= maskp->s_addr;
2312 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2313 ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2316 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2317 /* convert masklen to netmask */
2318 while (masklen > 0) {
2320 *mask6p = htonl(~(0xffffffff >> masklen));
2323 *mask6p++ = 0xffffffff;
2326 /* Lose any host bits in the network number. */
2327 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2328 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2329 for (i = 0; i < 4; i++)
2330 addr6p[i] &= mask6p[i];
2339 /* arg `s' is domain name */
2353 printf("allowaddr: rule %d: ", NumAllowed);
2355 printf("numeric, ");
2356 getnameinfo((struct sockaddr *)&ap.a_addr,
2357 ((struct sockaddr *)&ap.a_addr)->sa_len,
2358 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2359 printf("addr = %s, ", ip);
2360 getnameinfo((struct sockaddr *)&ap.a_mask,
2361 ((struct sockaddr *)&ap.a_mask)->sa_len,
2362 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2363 printf("mask = %s; ", ip);
2365 printf("domainname = %s; ", ap.a_name);
2367 printf("port = %d\n", ap.port);
2370 if ((AllowedPeers = realloc(AllowedPeers,
2371 ++NumAllowed * sizeof(struct allowedpeer)))
2373 logerror("realloc");
2376 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2381 * Validate that the remote peer has permission to log to us.
2384 validate(struct sockaddr *sa, const char *hname)
2388 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2389 struct allowedpeer *ap;
2390 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2393 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2395 struct addrinfo hints, *res;
2398 if (NumAllowed == 0)
2399 /* traditional behaviour, allow everything */
2402 (void)strlcpy(name, hname, sizeof(name));
2403 memset(&hints, 0, sizeof(hints));
2404 hints.ai_family = PF_UNSPEC;
2405 hints.ai_socktype = SOCK_DGRAM;
2406 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2407 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2409 else if (strchr(name, '.') == NULL) {
2410 strlcat(name, ".", sizeof name);
2411 strlcat(name, LocalDomain, sizeof name);
2413 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2414 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2415 return (0); /* for safety, should not occur */
2416 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2420 /* now, walk down the list */
2421 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2422 if (ap->port != 0 && ap->port != sport) {
2423 dprintf("rejected in rule %d due to port mismatch.\n", i);
2427 if (ap->isnumeric) {
2428 if (ap->a_addr.ss_family != sa->sa_family) {
2429 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2432 if (ap->a_addr.ss_family == AF_INET) {
2433 sin4 = (struct sockaddr_in *)sa;
2434 a4p = (struct sockaddr_in *)&ap->a_addr;
2435 m4p = (struct sockaddr_in *)&ap->a_mask;
2436 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2437 != a4p->sin_addr.s_addr) {
2438 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2443 else if (ap->a_addr.ss_family == AF_INET6) {
2444 sin6 = (struct sockaddr_in6 *)sa;
2445 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2446 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2447 if (a6p->sin6_scope_id != 0 &&
2448 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2449 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2453 for (j = 0; j < 16; j += 4) {
2454 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2455 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2461 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2472 /* allow wildmatch */
2475 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2476 dprintf("rejected in rule %d due to name mismatch.\n", i);
2482 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2483 dprintf("rejected in rule %d due to name mismatch.\n", i);
2488 dprintf("accepted in rule %d.\n", i);
2489 return (1); /* hooray! */
2495 * Fairly similar to popen(3), but returns an open descriptor, as
2496 * opposed to a FILE *.
2499 p_open(const char *prog, pid_t *rpid)
2501 int pfd[2], nulldesc;
2503 sigset_t omask, mask;
2504 char *argv[4]; /* sh -c cmd NULL */
2507 if (pipe(pfd) == -1)
2509 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2510 /* we are royally screwed anyway */
2514 sigaddset(&mask, SIGALRM);
2515 sigaddset(&mask, SIGHUP);
2516 sigprocmask(SIG_BLOCK, &mask, &omask);
2517 switch ((pid = fork())) {
2519 sigprocmask(SIG_SETMASK, &omask, 0);
2524 argv[0] = strdup("sh");
2525 argv[1] = strdup("-c");
2526 argv[2] = strdup(prog);
2528 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2534 (void)setsid(); /* Avoid catching SIGHUPs. */
2537 * Throw away pending signals, and reset signal
2538 * behaviour to standard values.
2540 signal(SIGALRM, SIG_IGN);
2541 signal(SIGHUP, SIG_IGN);
2542 sigprocmask(SIG_SETMASK, &omask, 0);
2543 signal(SIGPIPE, SIG_DFL);
2544 signal(SIGQUIT, SIG_DFL);
2545 signal(SIGALRM, SIG_DFL);
2546 signal(SIGHUP, SIG_DFL);
2548 dup2(pfd[0], STDIN_FILENO);
2549 dup2(nulldesc, STDOUT_FILENO);
2550 dup2(nulldesc, STDERR_FILENO);
2553 (void)execvp(_PATH_BSHELL, argv);
2557 sigprocmask(SIG_SETMASK, &omask, 0);
2561 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2562 * supposed to get an EWOULDBLOCK on writev(2), which is
2563 * caught by the logic above anyway, which will in turn close
2564 * the pipe, and fork a new logging subprocess if necessary.
2565 * The stale subprocess will be killed some time later unless
2566 * it terminated itself due to closing its input pipe (so we
2567 * get rid of really dead puppies).
2569 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2571 (void)snprintf(errmsg, sizeof errmsg,
2572 "Warning: cannot change pipe to PID %d to "
2573 "non-blocking behaviour.",
2582 deadq_enter(pid_t pid, const char *name)
2590 * Be paranoid, if we can't signal the process, don't enter it
2591 * into the dead queue (perhaps it's already dead). If possible,
2592 * we try to fetch and log the child's status.
2594 if (kill(pid, 0) != 0) {
2595 if (waitpid(pid, &status, WNOHANG) > 0)
2596 log_deadchild(pid, status, name);
2600 p = malloc(sizeof(struct deadq_entry));
2607 p->dq_timeout = DQ_TIMO_INIT;
2608 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2612 deadq_remove(pid_t pid)
2616 TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2617 if (q->dq_pid == pid) {
2618 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2628 log_deadchild(pid_t pid, int status, const char *name)
2634 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2635 if (WIFSIGNALED(status)) {
2636 reason = "due to signal";
2637 code = WTERMSIG(status);
2639 reason = "with status";
2640 code = WEXITSTATUS(status);
2644 (void)snprintf(buf, sizeof buf,
2645 "Logging subprocess %d (%s) exited %s %d.",
2646 pid, name, reason, code);
2651 socksetup(int af, char *bindhostname)
2653 struct addrinfo hints, *res, *r;
2654 const char *bindservice;
2656 int error, maxs, *s, *socks;
2659 * We have to handle this case for backwards compatibility:
2660 * If there are two (or more) colons but no '[' and ']',
2661 * assume this is an inet6 address without a service.
2663 bindservice = "syslog";
2664 if (bindhostname != NULL) {
2666 if (*bindhostname == '[' &&
2667 (cp = strchr(bindhostname + 1, ']')) != NULL) {
2670 if (cp[1] == ':' && cp[2] != '\0')
2671 bindservice = cp + 2;
2674 cp = strchr(bindhostname, ':');
2675 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2678 bindservice = cp + 1;
2679 if (cp == bindhostname)
2680 bindhostname = NULL;
2687 memset(&hints, 0, sizeof(hints));
2688 hints.ai_flags = AI_PASSIVE;
2689 hints.ai_family = af;
2690 hints.ai_socktype = SOCK_DGRAM;
2691 error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2693 logerror(gai_strerror(error));
2698 /* Count max number of sockets we may open */
2699 for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2700 socks = malloc((maxs+1) * sizeof(int));
2701 if (socks == NULL) {
2702 logerror("couldn't allocate memory for sockets");
2706 *socks = 0; /* num of sockets counter at start of array */
2708 for (r = res; r; r = r->ai_next) {
2710 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2716 if (r->ai_family == AF_INET6) {
2717 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2718 (char *)&on, sizeof (on)) < 0) {
2719 logerror("setsockopt");
2725 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2726 (char *)&on, sizeof (on)) < 0) {
2727 logerror("setsockopt");
2732 * RFC 3164 recommends that client side message
2733 * should come from the privileged syslogd port.
2735 * If the system administrator choose not to obey
2736 * this, we can skip the bind() step so that the
2737 * system will choose a port for us.
2740 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2747 increase_rcvbuf(*s);
2768 increase_rcvbuf(int fd)
2770 socklen_t len, slen;
2774 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2775 if (len < RCVBUF_MINSIZE) {
2776 len = RCVBUF_MINSIZE;
2777 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));