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 send_to_all; /* send message to all IPv4/IPv6 addresses */
287 static int use_bootfile; /* log entire bootfile for every kern msg */
288 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
289 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
291 static char bootfile[MAXLINE+1]; /* booted kernel file */
293 struct allowedpeer *AllowedPeers; /* List of allowed peers */
294 static int NumAllowed; /* Number of entries in AllowedPeers */
296 static int UniquePriority; /* Only log specified priority? */
297 static int LogFacPri; /* Put facility and priority in log message: */
298 /* 0=no, 1=numeric, 2=names */
299 static int KeepKernFac; /* Keep remotely logged kernel facility */
300 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
301 static struct pidfh *pfh;
303 volatile sig_atomic_t MarkSet, WantDie;
305 static int allowaddr(char *);
306 static void cfline(const char *, struct filed *,
307 const char *, const char *);
308 static const char *cvthname(struct sockaddr *);
309 static void deadq_enter(pid_t, const char *);
310 static int deadq_remove(pid_t);
311 static int decode(const char *, CODE *);
312 static void die(int);
313 static void dodie(int);
314 static void dofsync(void);
315 static void domark(int);
316 static void fprintlog(struct filed *, int, const char *);
317 static int *socksetup(int, const char *);
318 static void init(int);
319 static void logerror(const char *);
320 static void logmsg(int, const char *, const char *, int);
321 static void log_deadchild(pid_t, int, const char *);
322 static void markit(void);
323 static int skip_message(const char *, const char *, int);
324 static void printline(const char *, char *);
325 static void printsys(char *);
326 static int p_open(const char *, pid_t *);
327 static void readklog(void);
328 static void reapchild(int);
329 static void usage(void);
330 static int validate(struct sockaddr *, const char *);
331 static void unmapped(struct sockaddr *);
332 static void wallmsg(struct filed *, struct iovec *);
333 static int waitdaemon(int, int, int);
334 static void timedout(int);
335 static void double_rbuf(int);
338 main(int argc, char *argv[])
340 int ch, i, fdsrmax = 0, l;
341 struct sockaddr_un sunx, fromunix;
342 struct sockaddr_storage frominet;
344 char line[MAXLINE + 1];
345 const char *bindhostname, *hname;
346 struct timeval tv, *tvp;
347 struct sigaction sact;
348 struct funix *fx, *fx1;
350 pid_t ppid = 1, spid;
354 while ((ch = getopt(argc, argv, "46Aa:b:cCdf:kl:m:nop:P:sS:uv")) != -1)
367 case 'a': /* allow specific network addresses only */
368 if (allowaddr(optarg) == -1)
372 bindhostname = optarg;
380 case 'd': /* debug */
383 case 'f': /* configuration file */
386 case 'k': /* keep remote kern fac */
395 if (optarg[0] == '/') {
398 } else if ((name = strchr(optarg, ':')) != NULL) {
401 errx(1, "socket name must be absolute "
403 if (isdigit(*optarg)) {
404 perml = strtol(optarg, &ep, 8);
405 if (*ep || perml < 0 ||
406 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
407 errx(1, "invalid mode %s, exiting",
409 mode = (mode_t )perml;
411 errx(1, "invalid mode %s, exiting",
413 } else /* doesn't begin with '/', and no ':' */
414 errx(1, "can't parse path %s", optarg);
416 if (strlen(name) >= sizeof(sunx.sun_path))
417 errx(1, "%s path too long, exiting", name);
418 if ((fx = malloc(sizeof(struct funix))) == NULL)
419 errx(1, "malloc failed");
423 STAILQ_INSERT_TAIL(&funixes, fx, next);
426 case 'm': /* mark interval */
427 MarkInterval = atoi(optarg) * 60;
436 if (strlen(optarg) >= sizeof(sunx.sun_path))
437 errx(1, "%s path too long, exiting", optarg);
438 funix_default.name = optarg;
440 case 'P': /* path for alt. PID */
443 case 's': /* no network mode */
446 case 'S': /* path for privileged originator */
447 if (strlen(optarg) >= sizeof(sunx.sun_path))
448 errx(1, "%s path too long, exiting", optarg);
449 funix_secure.name = optarg;
451 case 'u': /* only log specified priority */
454 case 'v': /* log facility and priority */
460 if ((argc -= optind) != 0)
463 pfh = pidfile_open(PidFile, 0600, &spid);
466 errx(1, "syslogd already running, pid: %d", spid);
467 warn("cannot open pid file");
471 ppid = waitdaemon(0, 0, 30);
473 warn("could not become daemon");
484 consfile.f_type = F_CONSOLE;
485 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
486 sizeof(consfile.f_un.f_fname));
487 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
488 (void)signal(SIGTERM, dodie);
489 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
490 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
492 * We don't want the SIGCHLD and SIGHUP handlers to interfere
493 * with each other; they are likely candidates for being called
494 * simultaneously (SIGHUP closes pipe descriptor, process dies,
498 sigaddset(&mask, SIGHUP);
499 sact.sa_handler = reapchild;
501 sact.sa_flags = SA_RESTART;
502 (void)sigaction(SIGCHLD, &sact, NULL);
503 (void)signal(SIGALRM, domark);
504 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
505 (void)alarm(TIMERINTVL);
507 TAILQ_INIT(&deadq_head);
510 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
512 STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
513 (void)unlink(fx->name);
514 memset(&sunx, 0, sizeof(sunx));
515 sunx.sun_family = AF_UNIX;
516 (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
517 fx->s = socket(AF_UNIX, SOCK_DGRAM, 0);
519 bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
520 chmod(fx->name, fx->mode) < 0) {
521 (void)snprintf(line, sizeof line,
522 "cannot create %s", fx->name);
524 dprintf("cannot create %s (%d)\n", fx->name, errno);
525 if (fx == &funix_default || fx == &funix_secure)
528 STAILQ_REMOVE(&funixes, fx, funix, next);
535 finet = socksetup(family, bindhostname);
539 for (i = 0; i < *finet; i++) {
540 if (shutdown(finet[i+1], SHUT_RD) < 0) {
541 logerror("shutdown");
547 dprintf("listening on inet and/or inet6 socket\n");
549 dprintf("sending on inet and/or inet6 socket\n");
552 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
553 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
556 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
558 /* tuck my process id away */
561 dprintf("off & running....\n");
564 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
566 sigaddset(&mask, SIGCHLD);
567 sact.sa_handler = init;
569 sact.sa_flags = SA_RESTART;
570 (void)sigaction(SIGHUP, &sact, NULL);
573 tv.tv_sec = tv.tv_usec = 0;
575 if (fklog != -1 && fklog > fdsrmax)
577 if (finet && !SecureMode) {
578 for (i = 0; i < *finet; i++) {
579 if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
580 fdsrmax = finet[i+1];
583 STAILQ_FOREACH(fx, &funixes, next)
587 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
590 errx(1, "calloc fd_set");
598 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
603 if (finet && !SecureMode) {
604 for (i = 0; i < *finet; i++) {
605 if (finet[i+1] != -1)
606 FD_SET(finet[i+1], fdsr);
609 STAILQ_FOREACH(fx, &funixes, next)
612 i = select(fdsrmax+1, fdsr, NULL, NULL,
613 needdofsync ? &tv : tvp);
629 if (fklog != -1 && FD_ISSET(fklog, fdsr))
631 if (finet && !SecureMode) {
632 for (i = 0; i < *finet; i++) {
633 if (FD_ISSET(finet[i+1], fdsr)) {
634 len = sizeof(frominet);
635 l = recvfrom(finet[i+1], line, MAXLINE,
636 0, (struct sockaddr *)&frominet,
640 hname = cvthname((struct sockaddr *)&frominet);
641 unmapped((struct sockaddr *)&frominet);
642 if (validate((struct sockaddr *)&frominet, hname))
643 printline(hname, line);
644 } else if (l < 0 && errno != EINTR)
645 logerror("recvfrom inet");
649 STAILQ_FOREACH(fx, &funixes, next) {
650 if (FD_ISSET(fx->s, fdsr)) {
651 len = sizeof(fromunix);
652 l = recvfrom(fx->s, line, MAXLINE, 0,
653 (struct sockaddr *)&fromunix, &len);
656 printline(LocalHostName, line);
657 } else if (l < 0 && errno != EINTR)
658 logerror("recvfrom unix");
667 unmapped(struct sockaddr *sa)
669 struct sockaddr_in6 *sin6;
670 struct sockaddr_in sin4;
672 if (sa->sa_family != AF_INET6)
674 if (sa->sa_len != sizeof(struct sockaddr_in6) ||
675 sizeof(sin4) > sa->sa_len)
677 sin6 = (struct sockaddr_in6 *)sa;
678 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
681 memset(&sin4, 0, sizeof(sin4));
682 sin4.sin_family = AF_INET;
683 sin4.sin_len = sizeof(struct sockaddr_in);
684 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
685 sizeof(sin4.sin_addr));
686 sin4.sin_port = sin6->sin6_port;
688 memcpy(sa, &sin4, sin4.sin_len);
695 fprintf(stderr, "%s\n%s\n%s\n%s\n",
696 "usage: syslogd [-46ACcdknosuv] [-a allowed_peer]",
697 " [-b bind_address] [-f config_file]",
698 " [-l [mode:]path] [-m mark_interval]",
699 " [-P pid_file] [-p log_socket]");
704 * Take a raw input line, decode the message, and print the message
705 * on the appropriate log files.
708 printline(const char *hname, char *msg)
713 char line[MAXLINE + 1];
715 /* test for special codes */
720 n = strtol(p + 1, &q, 10);
721 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
726 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
730 * Don't allow users to log kernel messages.
731 * NOTE: since LOG_KERN == 0 this will also match
732 * messages with no facility specified.
734 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
735 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
739 while ((c = (unsigned char)*p++) != '\0' &&
740 q < &line[sizeof(line) - 4]) {
741 if ((c & 0x80) && c < 0xA0) {
746 if (isascii(c) && iscntrl(c)) {
749 } else if (c == '\t') {
761 logmsg(pri, line, hname, 0);
765 * Read /dev/klog while data are available, split into lines.
770 char *p, *q, line[MAXLINE + 1];
775 i = read(fklog, line + len, MAXLINE - 1 - len);
777 line[i + len] = '\0';
779 if (i < 0 && errno != EINTR && errno != EAGAIN) {
786 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
791 if (len >= MAXLINE - 1) {
796 memmove(line, p, len + 1);
803 * Take a raw input line from /dev/klog, format similar to syslog().
810 int flags, isprintf, pri;
812 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
818 n = strtol(p + 1, &q, 10);
819 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
826 * Kernel printf's and LOG_CONSOLE messages have been displayed
827 * on the console already.
829 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
831 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
833 logmsg(pri, p, LocalHostName, flags);
839 * Match a program or host name against a specification.
840 * Return a non-0 value if the message must be ignored
841 * based on the specification.
844 skip_message(const char *name, const char *spec, int checkcase)
849 /* Behaviour on explicit match */
864 s = strstr (spec, name);
866 s = strcasestr (spec, name);
869 prev = (s == spec ? ',' : *(s - 1));
870 next = *(s + strlen (name));
872 if (prev == ',' && (next == '\0' || next == ','))
873 /* Explicit match: skip iff the spec is an
878 /* No explicit match for this name: skip the message iff
879 the spec is an inclusive one. */
884 * Log a message to the appropriate log files, users, etc. based on
888 logmsg(int pri, const char *msg, const char *from, int flags)
891 int i, fac, msglen, omask, prilev;
892 const char *timestamp;
893 char prog[NAME_MAX+1];
896 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
897 pri, flags, from, msg);
899 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
902 * Check to see if msg looks non-standard.
904 msglen = strlen(msg);
905 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
906 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
910 if (flags & ADDDATE) {
911 timestamp = ctime(&now) + 4;
918 /* skip leading blanks */
919 while (isspace(*msg)) {
924 /* extract facility and priority level */
926 fac = LOG_NFACILITIES;
930 /* Check maximum facility number. */
931 if (fac > LOG_NFACILITIES) {
932 (void)sigsetmask(omask);
936 prilev = LOG_PRI(pri);
938 /* extract program name */
939 for (i = 0; i < NAME_MAX; i++) {
940 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
941 msg[i] == '/' || isspace(msg[i]))
947 /* add kernel prefix for kernel messages */
948 if (flags & ISKERNEL) {
949 snprintf(buf, sizeof(buf), "%s: %s",
950 use_bootfile ? bootfile : "kernel", msg);
952 msglen = strlen(buf);
955 /* log the message to the particular outputs */
959 * Open in non-blocking mode to avoid hangs during open
960 * and close(waiting for the port to drain).
962 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
964 if (f->f_file >= 0) {
965 (void)strlcpy(f->f_lasttime, timestamp,
966 sizeof(f->f_lasttime));
967 fprintlog(f, flags, msg);
968 (void)close(f->f_file);
970 (void)sigsetmask(omask);
973 for (f = Files; f; f = f->f_next) {
974 /* skip messages that are incorrect priority */
975 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
976 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
977 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
979 || f->f_pmask[fac] == INTERNAL_NOPRI)
982 /* skip messages with the incorrect hostname */
983 if (skip_message(from, f->f_host, 0))
986 /* skip messages with the incorrect program name */
987 if (skip_message(prog, f->f_program, 1))
990 /* skip message to console if it has already been printed */
991 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
994 /* don't output marks to recently written files */
995 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
999 * suppress duplicate lines to this file
1001 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1002 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1003 f->f_prevline && !strcmp(msg, f->f_prevline) &&
1004 !strcasecmp(from, f->f_prevhost)) {
1005 (void)strlcpy(f->f_lasttime, timestamp,
1006 sizeof(f->f_lasttime));
1008 dprintf("msg repeated %d times, %ld sec of %d\n",
1009 f->f_prevcount, (long)(now - f->f_time),
1010 repeatinterval[f->f_repeatcount]);
1012 * If domark would have logged this by now,
1013 * flush it now (so we don't hold isolated messages),
1014 * but back off so we'll flush less often
1017 if (now > REPEATTIME(f)) {
1018 fprintlog(f, flags, (char *)NULL);
1022 /* new line, save it */
1024 fprintlog(f, 0, (char *)NULL);
1025 f->f_repeatcount = 0;
1027 (void)strlcpy(f->f_lasttime, timestamp,
1028 sizeof(f->f_lasttime));
1029 (void)strlcpy(f->f_prevhost, from,
1030 sizeof(f->f_prevhost));
1031 if (msglen < MAXSVLINE) {
1032 f->f_prevlen = msglen;
1033 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1034 fprintlog(f, flags, (char *)NULL);
1036 f->f_prevline[0] = 0;
1038 fprintlog(f, flags, msg);
1042 (void)sigsetmask(omask);
1050 for (f = Files; f; f = f->f_next) {
1051 if ((f->f_type == F_FILE) &&
1052 (f->f_flags & FFLAG_NEEDSYNC)) {
1053 f->f_flags &= ~FFLAG_NEEDSYNC;
1054 (void)fsync(f->f_file);
1060 fprintlog(struct filed *f, int flags, const char *msg)
1062 struct iovec iov[7];
1065 int i, l, lsent = 0;
1066 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1067 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1071 if (f->f_type == F_WALL) {
1072 v->iov_base = greetings;
1073 /* The time displayed is not synchornized with the other log
1074 * destinations (like messages). Following fragment was using
1075 * ctime(&now), which was updating the time every 30 sec.
1076 * With f_lasttime, time is synchronized correctly.
1078 v->iov_len = snprintf(greetings, sizeof greetings,
1079 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1080 f->f_prevhost, f->f_lasttime);
1087 v->iov_base = f->f_lasttime;
1088 v->iov_len = strlen(f->f_lasttime);
1090 v->iov_base = space;
1096 static char fp_buf[30]; /* Hollow laugh */
1097 int fac = f->f_prevpri & LOG_FACMASK;
1098 int pri = LOG_PRI(f->f_prevpri);
1099 const char *f_s = NULL;
1100 char f_n[5]; /* Hollow laugh */
1101 const char *p_s = NULL;
1102 char p_n[5]; /* Hollow laugh */
1104 if (LogFacPri > 1) {
1107 for (c = facilitynames; c->c_name; c++) {
1108 if (c->c_val == fac) {
1113 for (c = prioritynames; c->c_name; c++) {
1114 if (c->c_val == pri) {
1121 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1125 snprintf(p_n, sizeof p_n, "%d", pri);
1128 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1129 v->iov_base = fp_buf;
1130 v->iov_len = strlen(fp_buf);
1137 v->iov_base = f->f_prevhost;
1138 v->iov_len = strlen(v->iov_base);
1140 v->iov_base = space;
1145 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1151 v->iov_len = strlen(msg);
1152 } else if (f->f_prevcount > 1) {
1153 v->iov_base = repbuf;
1154 v->iov_len = snprintf(repbuf, sizeof repbuf,
1155 "last message repeated %d times", f->f_prevcount);
1156 } else if (f->f_prevline) {
1157 v->iov_base = f->f_prevline;
1158 v->iov_len = f->f_prevlen;
1164 dprintf("Logging to %s", TypeNames[f->f_type]);
1167 switch (f->f_type) {
1174 port = (int)ntohs(((struct sockaddr_in *)
1175 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1177 dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1179 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1181 /* check for local vs remote messages */
1182 if (strcasecmp(f->f_prevhost, LocalHostName))
1183 l = snprintf(line, sizeof line - 1,
1184 "<%d>%.15s Forwarded from %s: %s",
1185 f->f_prevpri, (char *)iov[0].iov_base,
1186 f->f_prevhost, (char *)iov[5].iov_base);
1188 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1189 f->f_prevpri, (char *)iov[0].iov_base,
1190 (char *)iov[5].iov_base);
1193 else if (l > MAXLINE)
1197 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1198 for (i = 0; i < *finet; i++) {
1201 * should we check AF first, or just
1202 * trial and error? FWD
1205 address_family_of(finet[i+1]))
1207 lsent = sendto(finet[i+1], line, l, 0,
1208 r->ai_addr, r->ai_addrlen);
1212 if (lsent == l && !send_to_all)
1215 dprintf("lsent/l: %d/%d\n", lsent, l);
1228 /* case ENOTSOCK: */
1230 /* case EMSGSIZE: */
1233 /* case ECONNREFUSED: */
1235 dprintf("removing entry\n");
1236 f->f_type = F_UNUSED;
1244 dprintf(" %s\n", f->f_un.f_fname);
1247 if (writev(f->f_file, iov, 7) < 0) {
1249 * If writev(2) fails for potentially transient errors
1250 * like the filesystem being full, ignore it.
1251 * Otherwise remove this logfile from the list.
1253 if (errno != ENOSPC) {
1255 (void)close(f->f_file);
1256 f->f_type = F_UNUSED;
1258 logerror(f->f_un.f_fname);
1260 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1261 f->f_flags |= FFLAG_NEEDSYNC;
1267 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1270 if (f->f_un.f_pipe.f_pid == 0) {
1271 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1272 &f->f_un.f_pipe.f_pid)) < 0) {
1273 f->f_type = F_UNUSED;
1274 logerror(f->f_un.f_pipe.f_pname);
1278 if (writev(f->f_file, iov, 7) < 0) {
1280 (void)close(f->f_file);
1281 if (f->f_un.f_pipe.f_pid > 0)
1282 deadq_enter(f->f_un.f_pipe.f_pid,
1283 f->f_un.f_pipe.f_pname);
1284 f->f_un.f_pipe.f_pid = 0;
1286 logerror(f->f_un.f_pipe.f_pname);
1291 if (flags & IGN_CONS) {
1292 dprintf(" (ignored)\n");
1298 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1302 errno = 0; /* ttymsg() only sometimes returns an errno */
1303 if ((msgret = ttymsg(iov, 7, f->f_un.f_fname, 10))) {
1304 f->f_type = F_UNUSED;
1323 * WALLMSG -- Write a message to the world at large
1325 * Write the specified message to either the entire
1326 * world, or a list of approved users.
1329 wallmsg(struct filed *f, struct iovec *iov)
1331 static int reenter; /* avoid calling ourselves */
1336 char line[sizeof(ut.ut_line) + 1];
1340 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1341 logerror(_PATH_UTMP);
1346 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
1347 if (ut.ut_name[0] == '\0')
1349 /* We must use strncpy since ut_* may not be NUL terminated. */
1350 strncpy(line, ut.ut_line, sizeof(line) - 1);
1351 line[sizeof(line) - 1] = '\0';
1352 if (f->f_type == F_WALL) {
1353 if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) != NULL) {
1354 errno = 0; /* already in msg */
1359 /* should we send the message to this user? */
1360 for (i = 0; i < MAXUNAMES; i++) {
1361 if (!f->f_un.f_uname[i][0])
1363 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1365 if ((p = ttymsg(iov, 7, line, TTYMSGTIME))
1367 errno = 0; /* already in msg */
1379 reapchild(int signo __unused)
1385 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1387 /* Don't tell while we are initting. */
1390 /* First, look if it's a process from the dead queue. */
1391 if (deadq_remove(pid))
1394 /* Now, look in list of active processes. */
1395 for (f = Files; f; f = f->f_next)
1396 if (f->f_type == F_PIPE &&
1397 f->f_un.f_pipe.f_pid == pid) {
1398 (void)close(f->f_file);
1399 f->f_un.f_pipe.f_pid = 0;
1400 log_deadchild(pid, status,
1401 f->f_un.f_pipe.f_pname);
1410 * Return a printable representation of a host address.
1413 cvthname(struct sockaddr *f)
1416 sigset_t omask, nmask;
1417 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1419 error = getnameinfo((struct sockaddr *)f,
1420 ((struct sockaddr *)f)->sa_len,
1421 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1422 dprintf("cvthname(%s)\n", ip);
1425 dprintf("Malformed from address %s\n", gai_strerror(error));
1431 sigemptyset(&nmask);
1432 sigaddset(&nmask, SIGHUP);
1433 sigprocmask(SIG_BLOCK, &nmask, &omask);
1434 error = getnameinfo((struct sockaddr *)f,
1435 ((struct sockaddr *)f)->sa_len,
1436 hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1437 sigprocmask(SIG_SETMASK, &omask, NULL);
1439 dprintf("Host name for your address (%s) unknown\n", ip);
1443 if (hl > 0 && hname[hl-1] == '.')
1445 trimdomain(hname, hl);
1457 domark(int signo __unused)
1464 * Print syslogd errors some place.
1467 logerror(const char *type)
1470 static int recursed = 0;
1472 /* If there's an error while trying to log an error, give up. */
1478 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1480 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1482 dprintf("%s\n", buf);
1483 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1492 int was_initialized;
1495 was_initialized = Initialized;
1496 Initialized = 0; /* Don't log SIGCHLDs. */
1497 for (f = Files; f != NULL; f = f->f_next) {
1498 /* flush any pending output */
1500 fprintlog(f, 0, (char *)NULL);
1501 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1502 (void)close(f->f_file);
1503 f->f_un.f_pipe.f_pid = 0;
1506 Initialized = was_initialized;
1508 dprintf("syslogd: exiting on signal %d\n", signo);
1509 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1513 STAILQ_FOREACH(fx, &funixes, next)
1514 (void)unlink(fx->name);
1515 pidfile_remove(pfh);
1521 * INIT -- Initialize syslogd from configuration table
1528 struct filed *f, *next, **nextp;
1530 char cline[LINE_MAX];
1531 char prog[NAME_MAX+1];
1532 char host[MAXHOSTNAMELEN];
1533 char oldLocalHostName[MAXHOSTNAMELEN];
1534 char hostMsg[2*MAXHOSTNAMELEN+40];
1535 char bootfileMsg[LINE_MAX];
1540 * Load hostname (may have changed).
1543 (void)strlcpy(oldLocalHostName, LocalHostName,
1544 sizeof(oldLocalHostName));
1545 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1546 err(EX_OSERR, "gethostname() failed");
1547 if ((p = strchr(LocalHostName, '.')) != NULL) {
1555 * Close all open log files.
1558 for (f = Files; f != NULL; f = next) {
1559 /* flush any pending output */
1561 fprintlog(f, 0, (char *)NULL);
1563 switch (f->f_type) {
1568 (void)close(f->f_file);
1571 if (f->f_un.f_pipe.f_pid > 0) {
1572 (void)close(f->f_file);
1573 deadq_enter(f->f_un.f_pipe.f_pid,
1574 f->f_un.f_pipe.f_pname);
1576 f->f_un.f_pipe.f_pid = 0;
1580 if (f->f_program) free(f->f_program);
1581 if (f->f_host) free(f->f_host);
1587 /* open the configuration file */
1588 if ((cf = fopen(ConfFile, "r")) == NULL) {
1589 dprintf("cannot open %s\n", ConfFile);
1590 *nextp = (struct filed *)calloc(1, sizeof(*f));
1591 if (*nextp == NULL) {
1595 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1596 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1597 if ((*nextp)->f_next == NULL) {
1601 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1607 * Foreach line in the conf table, open that file.
1610 (void)strlcpy(host, "*", sizeof(host));
1611 (void)strlcpy(prog, "*", sizeof(prog));
1612 while (fgets(cline, sizeof(cline), cf) != NULL) {
1614 * check for end-of-section, comments, strip off trailing
1615 * spaces and newline character. #!prog is treated specially:
1616 * following lines apply only to that program.
1618 for (p = cline; isspace(*p); ++p)
1624 if (*p != '!' && *p != '+' && *p != '-')
1627 if (*p == '+' || *p == '-') {
1631 if ((!*p) || (*p == '*')) {
1632 (void)strlcpy(host, "*", sizeof(host));
1637 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1638 if (!isalnum(*p) && *p != '.' && *p != '-'
1639 && *p != ',' && *p != ':' && *p != '%')
1648 while (isspace(*p)) p++;
1649 if ((!*p) || (*p == '*')) {
1650 (void)strlcpy(prog, "*", sizeof(prog));
1653 for (i = 0; i < NAME_MAX; i++) {
1654 if (!isprint(p[i]) || isspace(p[i]))
1661 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1663 f = (struct filed *)calloc(1, sizeof(*f));
1670 cfline(cline, f, prog, host);
1673 /* close the configuration file */
1680 for (f = Files; f; f = f->f_next) {
1681 for (i = 0; i <= LOG_NFACILITIES; i++)
1682 if (f->f_pmask[i] == INTERNAL_NOPRI)
1685 printf("%d ", f->f_pmask[i]);
1686 printf("%s: ", TypeNames[f->f_type]);
1687 switch (f->f_type) {
1689 printf("%s", f->f_un.f_fname);
1694 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1698 port = (int)ntohs(((struct sockaddr_in *)
1699 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1702 f->f_un.f_forw.f_hname, port);
1704 printf("%s", f->f_un.f_forw.f_hname);
1709 printf("%s", f->f_un.f_pipe.f_pname);
1713 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1714 printf("%s, ", f->f_un.f_uname[i]);
1718 printf(" (%s)", f->f_program);
1723 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1724 dprintf("syslogd: restarted\n");
1726 * Log a change in hostname, but only on a restart.
1728 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1729 (void)snprintf(hostMsg, sizeof(hostMsg),
1730 "syslogd: hostname changed, \"%s\" to \"%s\"",
1731 oldLocalHostName, LocalHostName);
1732 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1733 dprintf("%s\n", hostMsg);
1736 * Log the kernel boot file if we aren't going to use it as
1737 * the prefix, and if this is *not* a restart.
1739 if (signo == 0 && !use_bootfile) {
1740 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1741 "syslogd: kernel boot file is %s", bootfile);
1742 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1743 dprintf("%s\n", bootfileMsg);
1748 * Crack a configuration file line
1751 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1753 struct addrinfo hints, *res;
1754 int error, i, pri, syncfile;
1757 char buf[MAXLINE], ebuf[100];
1759 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1761 errno = 0; /* keep strerror() stuff out of logerror messages */
1763 /* clear out file entry */
1764 memset(f, 0, sizeof(*f));
1765 for (i = 0; i <= LOG_NFACILITIES; i++)
1766 f->f_pmask[i] = INTERNAL_NOPRI;
1768 /* save hostname if any */
1769 if (host && *host == '*')
1774 f->f_host = strdup(host);
1775 if (f->f_host == NULL) {
1779 hl = strlen(f->f_host);
1780 if (hl > 0 && f->f_host[hl-1] == '.')
1781 f->f_host[--hl] = '\0';
1782 trimdomain(f->f_host, hl);
1785 /* save program name if any */
1786 if (prog && *prog == '*')
1789 f->f_program = strdup(prog);
1790 if (f->f_program == NULL) {
1796 /* scan through the list of selectors */
1797 for (p = line; *p && *p != '\t' && *p != ' ';) {
1802 /* find the end of this facility name list */
1803 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1806 /* get the priority comparison */
1834 /* collect priority name */
1835 for (bp = buf; *q && !strchr("\t,; ", *q); )
1840 while (strchr(",;", *q))
1843 /* decode priority name */
1846 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1848 /* Ignore trailing spaces. */
1849 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1852 pri = decode(buf, prioritynames);
1854 (void)snprintf(ebuf, sizeof ebuf,
1855 "unknown priority name \"%s\"", buf);
1861 pri_cmp = (UniquePriority)
1866 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1868 /* scan facilities */
1869 while (*p && !strchr("\t.; ", *p)) {
1870 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1875 for (i = 0; i < LOG_NFACILITIES; i++) {
1876 f->f_pmask[i] = pri;
1877 f->f_pcmp[i] = pri_cmp;
1880 i = decode(buf, facilitynames);
1882 (void)snprintf(ebuf, sizeof ebuf,
1883 "unknown facility name \"%s\"",
1888 f->f_pmask[i >> 3] = pri;
1889 f->f_pcmp[i >> 3] = pri_cmp;
1891 while (*p == ',' || *p == ' ')
1898 /* skip to action part */
1899 while (*p == '\t' || *p == ' ')
1913 * scan forward to see if there is a port defined.
1914 * so we can't use strlcpy..
1916 i = sizeof(f->f_un.f_forw.f_hname);
1917 tp = f->f_un.f_forw.f_hname;
1920 while (*p && (*p != ':') && (i-- > 0)) {
1925 /* See if we copied a domain and have a port */
1931 memset(&hints, 0, sizeof(hints));
1932 hints.ai_family = family;
1933 hints.ai_socktype = SOCK_DGRAM;
1934 error = getaddrinfo(f->f_un.f_forw.f_hname,
1935 p ? p : "syslog", &hints, &res);
1937 logerror(gai_strerror(error));
1940 f->f_un.f_forw.f_addr = res;
1945 if ((f->f_file = open(p, logflags, 0600)) < 0) {
1946 f->f_type = F_UNUSED;
1951 f->f_flags |= FFLAG_SYNC;
1952 if (isatty(f->f_file)) {
1953 if (strcmp(p, ctty) == 0)
1954 f->f_type = F_CONSOLE;
1957 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1958 sizeof(f->f_un.f_fname));
1960 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1966 f->f_un.f_pipe.f_pid = 0;
1967 (void)strlcpy(f->f_un.f_fname, p + 1, sizeof(f->f_un.f_fname));
1976 for (i = 0; i < MAXUNAMES && *p; i++) {
1977 for (q = p; *q && *q != ','; )
1979 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1980 if ((q - p) > UT_NAMESIZE)
1981 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1983 f->f_un.f_uname[i][q - p] = '\0';
1984 while (*q == ',' || *q == ' ')
1988 f->f_type = F_USERS;
1995 * Decode a symbolic name to a numeric value
1998 decode(const char *name, CODE *codetab)
2004 return (atoi(name));
2006 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2008 *p = tolower(*name);
2013 for (c = codetab; c->c_name; c++)
2014 if (!strcmp(buf, c->c_name))
2026 now = time((time_t *)NULL);
2027 MarkSeq += TIMERINTVL;
2028 if (MarkSeq >= MarkInterval) {
2029 logmsg(LOG_INFO, "-- MARK --",
2030 LocalHostName, ADDDATE|MARK);
2034 for (f = Files; f; f = f->f_next) {
2035 if (f->f_prevcount && now >= REPEATTIME(f)) {
2036 dprintf("flush %s: repeated %d times, %d sec.\n",
2037 TypeNames[f->f_type], f->f_prevcount,
2038 repeatinterval[f->f_repeatcount]);
2039 fprintlog(f, 0, (char *)NULL);
2044 /* Walk the dead queue, and see if we should signal somebody. */
2045 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2046 next = TAILQ_NEXT(q, dq_entries);
2048 switch (q->dq_timeout) {
2050 /* Already signalled once, try harder now. */
2051 if (kill(q->dq_pid, SIGKILL) != 0)
2052 (void)deadq_remove(q->dq_pid);
2057 * Timed out on dead queue, send terminate
2058 * signal. Note that we leave the removal
2059 * from the dead queue to reapchild(), which
2060 * will also log the event (unless the process
2061 * didn't even really exist, in case we simply
2062 * drop it from the dead queue).
2064 if (kill(q->dq_pid, SIGTERM) != 0)
2065 (void)deadq_remove(q->dq_pid);
2073 (void)alarm(TIMERINTVL);
2077 * fork off and become a daemon, but wait for the child to come online
2078 * before returing to the parent, or we get disk thrashing at boot etc.
2079 * Set a timer so we don't hang forever if it wedges.
2082 waitdaemon(int nochdir, int noclose, int maxwait)
2086 pid_t pid, childpid;
2088 switch (childpid = fork()) {
2094 signal(SIGALRM, timedout);
2096 while ((pid = wait3(&status, 0, NULL)) != -1) {
2097 if (WIFEXITED(status))
2098 errx(1, "child pid %d exited with return code %d",
2099 pid, WEXITSTATUS(status));
2100 if (WIFSIGNALED(status))
2101 errx(1, "child pid %d exited on signal %d%s",
2102 pid, WTERMSIG(status),
2103 WCOREDUMP(status) ? " (core dumped)" :
2105 if (pid == childpid) /* it's gone... */
2117 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2118 (void)dup2(fd, STDIN_FILENO);
2119 (void)dup2(fd, STDOUT_FILENO);
2120 (void)dup2(fd, STDERR_FILENO);
2128 * We get a SIGALRM from the child when it's running and finished doing it's
2129 * fsync()'s or O_SYNC writes for all the boot messages.
2131 * We also get a signal from the kernel if the timer expires, so check to
2132 * see what happened.
2135 timedout(int sig __unused)
2139 signal(SIGALRM, SIG_DFL);
2141 errx(1, "timed out waiting for child");
2147 * Add `s' to the list of allowable peer addresses to accept messages
2150 * `s' is a string in the form:
2152 * [*]domainname[:{servicename|portnumber|*}]
2156 * netaddr/maskbits[:{servicename|portnumber|*}]
2158 * Returns -1 on error, 0 if the argument was valid.
2164 struct allowedpeer ap;
2166 int masklen = -1, i;
2167 struct addrinfo hints, *res;
2168 struct in_addr *addrp, *maskp;
2169 u_int32_t *addr6p, *mask6p;
2170 char ip[NI_MAXHOST];
2173 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2176 if ((cp1 = strrchr(cp1, ':'))) {
2177 /* service/port provided */
2179 if (strlen(cp1) == 1 && *cp1 == '*')
2180 /* any port allowed */
2182 else if ((se = getservbyname(cp1, "udp"))) {
2183 ap.port = ntohs(se->s_port);
2185 ap.port = strtol(cp1, &cp2, 0);
2187 return (-1); /* port not numeric */
2190 if ((se = getservbyname("syslog", "udp")))
2191 ap.port = ntohs(se->s_port);
2193 /* sanity, should not happen */
2197 if ((cp1 = strchr(s, '/')) != NULL &&
2198 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2200 if ((masklen = atoi(cp1 + 1)) < 0)
2205 cp2 = s + strlen(s) - 1;
2216 memset(&hints, 0, sizeof(hints));
2217 hints.ai_family = PF_UNSPEC;
2218 hints.ai_socktype = SOCK_DGRAM;
2219 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2220 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2222 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2223 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2224 ap.a_mask.ss_family = res->ai_family;
2225 if (res->ai_family == AF_INET) {
2226 ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2227 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2228 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2230 /* use default netmask */
2231 if (IN_CLASSA(ntohl(addrp->s_addr)))
2232 maskp->s_addr = htonl(IN_CLASSA_NET);
2233 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2234 maskp->s_addr = htonl(IN_CLASSB_NET);
2236 maskp->s_addr = htonl(IN_CLASSC_NET);
2237 } else if (masklen <= 32) {
2238 /* convert masklen to netmask */
2242 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2247 /* Lose any host bits in the network number. */
2248 addrp->s_addr &= maskp->s_addr;
2251 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2252 ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2255 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2256 /* convert masklen to netmask */
2257 while (masklen > 0) {
2259 *mask6p = htonl(~(0xffffffff >> masklen));
2262 *mask6p++ = 0xffffffff;
2265 /* Lose any host bits in the network number. */
2266 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2267 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2268 for (i = 0; i < 4; i++)
2269 addr6p[i] &= mask6p[i];
2278 /* arg `s' is domain name */
2292 printf("allowaddr: rule %d: ", NumAllowed);
2294 printf("numeric, ");
2295 getnameinfo((struct sockaddr *)&ap.a_addr,
2296 ((struct sockaddr *)&ap.a_addr)->sa_len,
2297 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2298 printf("addr = %s, ", ip);
2299 getnameinfo((struct sockaddr *)&ap.a_mask,
2300 ((struct sockaddr *)&ap.a_mask)->sa_len,
2301 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2302 printf("mask = %s; ", ip);
2304 printf("domainname = %s; ", ap.a_name);
2306 printf("port = %d\n", ap.port);
2309 if ((AllowedPeers = realloc(AllowedPeers,
2310 ++NumAllowed * sizeof(struct allowedpeer)))
2312 logerror("realloc");
2315 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2320 * Validate that the remote peer has permission to log to us.
2323 validate(struct sockaddr *sa, const char *hname)
2327 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2328 struct allowedpeer *ap;
2329 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2330 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2331 struct addrinfo hints, *res;
2334 if (NumAllowed == 0)
2335 /* traditional behaviour, allow everything */
2338 (void)strlcpy(name, hname, sizeof(name));
2339 memset(&hints, 0, sizeof(hints));
2340 hints.ai_family = PF_UNSPEC;
2341 hints.ai_socktype = SOCK_DGRAM;
2342 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2343 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2345 else if (strchr(name, '.') == NULL) {
2346 strlcat(name, ".", sizeof name);
2347 strlcat(name, LocalDomain, sizeof name);
2349 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2350 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2351 return (0); /* for safety, should not occur */
2352 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2356 /* now, walk down the list */
2357 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2358 if (ap->port != 0 && ap->port != sport) {
2359 dprintf("rejected in rule %d due to port mismatch.\n", i);
2363 if (ap->isnumeric) {
2364 if (ap->a_addr.ss_family != sa->sa_family) {
2365 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2368 if (ap->a_addr.ss_family == AF_INET) {
2369 sin4 = (struct sockaddr_in *)sa;
2370 a4p = (struct sockaddr_in *)&ap->a_addr;
2371 m4p = (struct sockaddr_in *)&ap->a_mask;
2372 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2373 != a4p->sin_addr.s_addr) {
2374 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2379 else if (ap->a_addr.ss_family == AF_INET6) {
2380 sin6 = (struct sockaddr_in6 *)sa;
2381 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2382 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2383 if (a6p->sin6_scope_id != 0 &&
2384 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2385 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2389 for (j = 0; j < 16; j += 4) {
2390 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2391 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2397 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2408 /* allow wildmatch */
2411 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2412 dprintf("rejected in rule %d due to name mismatch.\n", i);
2418 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2419 dprintf("rejected in rule %d due to name mismatch.\n", i);
2424 dprintf("accepted in rule %d.\n", i);
2425 return (1); /* hooray! */
2431 * Fairly similar to popen(3), but returns an open descriptor, as
2432 * opposed to a FILE *.
2435 p_open(const char *prog, pid_t *rpid)
2437 int pfd[2], nulldesc, i;
2439 sigset_t omask, mask;
2440 char *argv[4]; /* sh -c cmd NULL */
2443 if (pipe(pfd) == -1)
2445 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2446 /* we are royally screwed anyway */
2450 sigaddset(&mask, SIGALRM);
2451 sigaddset(&mask, SIGHUP);
2452 sigprocmask(SIG_BLOCK, &mask, &omask);
2453 switch ((pid = fork())) {
2455 sigprocmask(SIG_SETMASK, &omask, 0);
2460 argv[0] = strdup("sh");
2461 argv[1] = strdup("-c");
2462 argv[2] = strdup(prog);
2464 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2470 (void)setsid(); /* Avoid catching SIGHUPs. */
2473 * Throw away pending signals, and reset signal
2474 * behaviour to standard values.
2476 signal(SIGALRM, SIG_IGN);
2477 signal(SIGHUP, SIG_IGN);
2478 sigprocmask(SIG_SETMASK, &omask, 0);
2479 signal(SIGPIPE, SIG_DFL);
2480 signal(SIGQUIT, SIG_DFL);
2481 signal(SIGALRM, SIG_DFL);
2482 signal(SIGHUP, SIG_DFL);
2484 dup2(pfd[0], STDIN_FILENO);
2485 dup2(nulldesc, STDOUT_FILENO);
2486 dup2(nulldesc, STDERR_FILENO);
2487 for (i = getdtablesize(); i > 2; i--)
2490 (void)execvp(_PATH_BSHELL, argv);
2494 sigprocmask(SIG_SETMASK, &omask, 0);
2498 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2499 * supposed to get an EWOULDBLOCK on writev(2), which is
2500 * caught by the logic above anyway, which will in turn close
2501 * the pipe, and fork a new logging subprocess if necessary.
2502 * The stale subprocess will be killed some time later unless
2503 * it terminated itself due to closing its input pipe (so we
2504 * get rid of really dead puppies).
2506 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2508 (void)snprintf(errmsg, sizeof errmsg,
2509 "Warning: cannot change pipe to PID %d to "
2510 "non-blocking behaviour.",
2519 deadq_enter(pid_t pid, const char *name)
2525 * Be paranoid, if we can't signal the process, don't enter it
2526 * into the dead queue (perhaps it's already dead). If possible,
2527 * we try to fetch and log the child's status.
2529 if (kill(pid, 0) != 0) {
2530 if (waitpid(pid, &status, WNOHANG) > 0)
2531 log_deadchild(pid, status, name);
2535 p = malloc(sizeof(struct deadq_entry));
2542 p->dq_timeout = DQ_TIMO_INIT;
2543 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2547 deadq_remove(pid_t pid)
2551 TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2552 if (q->dq_pid == pid) {
2553 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2563 log_deadchild(pid_t pid, int status, const char *name)
2569 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2570 if (WIFSIGNALED(status)) {
2571 reason = "due to signal";
2572 code = WTERMSIG(status);
2574 reason = "with status";
2575 code = WEXITSTATUS(status);
2579 (void)snprintf(buf, sizeof buf,
2580 "Logging subprocess %d (%s) exited %s %d.",
2581 pid, name, reason, code);
2586 socksetup(int af, const char *bindhostname)
2588 struct addrinfo hints, *res, *r;
2589 int error, maxs, *s, *socks;
2591 memset(&hints, 0, sizeof(hints));
2592 hints.ai_flags = AI_PASSIVE;
2593 hints.ai_family = af;
2594 hints.ai_socktype = SOCK_DGRAM;
2595 error = getaddrinfo(bindhostname, "syslog", &hints, &res);
2597 logerror(gai_strerror(error));
2602 /* Count max number of sockets we may open */
2603 for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2604 socks = malloc((maxs+1) * sizeof(int));
2605 if (socks == NULL) {
2606 logerror("couldn't allocate memory for sockets");
2610 *socks = 0; /* num of sockets counter at start of array */
2612 for (r = res; r; r = r->ai_next) {
2614 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2619 if (r->ai_family == AF_INET6) {
2620 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2621 (char *)&on, sizeof (on)) < 0) {
2622 logerror("setsockopt");
2627 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2628 (char *)&on, sizeof (on)) < 0) {
2629 logerror("setsockopt");
2633 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2661 socklen_t slen, len;
2663 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2665 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, slen);