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 MAXLINE /* 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 */
77 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
79 #include <sys/param.h>
80 #include <sys/ioctl.h>
84 #include <sys/socket.h>
85 #include <sys/queue.h>
89 #include <sys/resource.h>
90 #include <sys/syslimits.h>
91 #include <sys/types.h>
93 #include <netinet/in.h>
95 #include <arpa/inet.h>
108 #include <sysexits.h>
112 #include "pathnames.h"
116 #include <sys/syslog.h>
118 const char *ConfFile = _PATH_LOGCONF;
119 const char *PidFile = _PATH_LOGPID;
120 const char ctty[] = _PATH_CONSOLE;
122 #define dprintf if (Debug) printf
124 #define MAXUNAMES 20 /* maximum number of user names */
128 * We have two default sockets, one with 666 permissions,
129 * and one for privileged programs.
135 STAILQ_ENTRY(funix) next;
137 struct funix funix_secure = { -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
139 struct funix funix_default = { -1, _PATH_LOG, DEFFILEMODE,
142 STAILQ_HEAD(, funix) funixes = { &funix_default,
143 &(funix_secure.next.stqe_next) };
149 #define IGN_CONS 0x001 /* don't print on console */
150 #define SYNC_FILE 0x002 /* do fsync on file after printing */
151 #define ADDDATE 0x004 /* add a date to the message */
152 #define MARK 0x008 /* this message is a mark */
153 #define ISKERNEL 0x010 /* kernel generated message */
156 * This structure represents the files that will have log
158 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
159 * or if f_type if F_PIPE and f_pid > 0.
163 struct filed *f_next; /* next in linked list */
164 short f_type; /* entry type, see below */
165 short f_file; /* file descriptor */
166 time_t f_time; /* time this was last written */
167 char *f_host; /* host from which to recd. */
168 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
169 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
173 char *f_program; /* program this applies to */
175 char f_uname[MAXUNAMES][MAXLOGNAME];
177 char f_hname[MAXHOSTNAMELEN];
178 struct addrinfo *f_addr;
180 } f_forw; /* forwarding address */
181 char f_fname[MAXPATHLEN];
183 char f_pname[MAXPATHLEN];
187 char f_prevline[MAXSVLINE]; /* last message logged */
188 char f_lasttime[16]; /* time of last occurrence */
189 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
190 int f_prevpri; /* pri of f_prevline */
191 int f_prevlen; /* length of f_prevline */
192 int f_prevcount; /* repetition cnt of prevline */
193 u_int f_repeatcount; /* number of "repeated" msgs */
194 int f_flags; /* file-specific flags */
195 #define FFLAG_SYNC 0x01
196 #define FFLAG_NEEDSYNC 0x02
200 * Queue of about-to-be dead processes we should watch out for.
203 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
204 struct stailhead *deadq_headp;
209 TAILQ_ENTRY(deadq_entry) dq_entries;
213 * The timeout to apply to processes waiting on the dead queue. Unit
214 * of measure is `mark intervals', i.e. 20 minutes by default.
215 * Processes on the dead queue will be terminated after that time.
218 #define DQ_TIMO_INIT 2
220 typedef struct deadq_entry *dq_t;
224 * Struct to hold records of network addresses that are allowed to log
232 struct sockaddr_storage addr;
233 struct sockaddr_storage mask;
237 #define a_addr u.numeric.addr
238 #define a_mask u.numeric.mask
239 #define a_name u.name
244 * Intervals at which we flush out "message repeated" messages,
245 * in seconds after previous message is logged. After each flush,
246 * we move to the next interval until we reach the largest.
248 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
249 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
250 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
251 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
252 (f)->f_repeatcount = MAXREPEAT; \
255 /* values for f_type */
256 #define F_UNUSED 0 /* unused entry */
257 #define F_FILE 1 /* regular file */
258 #define F_TTY 2 /* terminal */
259 #define F_CONSOLE 3 /* console terminal */
260 #define F_FORW 4 /* remote machine */
261 #define F_USERS 5 /* list of users */
262 #define F_WALL 6 /* everyone logged on */
263 #define F_PIPE 7 /* pipe to program */
265 const char *TypeNames[8] = {
266 "UNUSED", "FILE", "TTY", "CONSOLE",
267 "FORW", "USERS", "WALL", "PIPE"
270 static struct filed *Files; /* Log files that we write to */
271 static struct filed consfile; /* Console */
273 static int Debug; /* debug flag */
274 static int Foreground = 0; /* Run in foreground, instead of daemonizing */
275 static int resolve = 1; /* resolve hostname */
276 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
277 static const char *LocalDomain; /* our local domain name */
278 static int *finet; /* Internet datagram socket */
279 static int fklog = -1; /* /dev/klog */
280 static int Initialized; /* set when we have initialized ourselves */
281 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
282 static int MarkSeq; /* mark sequence number */
283 static int NoBind; /* don't bind() as suggested by RFC 3164 */
284 static int SecureMode; /* when true, receive only unix domain socks */
286 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
288 static int family = PF_INET; /* protocol family (IPv4 only) */
290 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
291 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
292 static int use_bootfile; /* log entire bootfile for every kern msg */
293 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
294 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
296 static char bootfile[MAXLINE+1]; /* booted kernel file */
298 struct allowedpeer *AllowedPeers; /* List of allowed peers */
299 static int NumAllowed; /* Number of entries in AllowedPeers */
300 static int RemoteAddDate; /* Always set the date on remote messages */
302 static int UniquePriority; /* Only log specified priority? */
303 static int LogFacPri; /* Put facility and priority in log message: */
304 /* 0=no, 1=numeric, 2=names */
305 static int KeepKernFac; /* Keep remotely logged kernel facility */
306 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
307 static struct pidfh *pfh;
309 volatile sig_atomic_t MarkSet, WantDie;
311 static int allowaddr(char *);
312 static void cfline(const char *, struct filed *,
313 const char *, const char *);
314 static const char *cvthname(struct sockaddr *);
315 static void deadq_enter(pid_t, const char *);
316 static int deadq_remove(pid_t);
317 static int decode(const char *, const CODE *);
318 static void die(int);
319 static void dodie(int);
320 static void dofsync(void);
321 static void domark(int);
322 static void fprintlog(struct filed *, int, const char *);
323 static int *socksetup(int, char *);
324 static void init(int);
325 static void logerror(const char *);
326 static void logmsg(int, const char *, const char *, int);
327 static void log_deadchild(pid_t, int, const char *);
328 static void markit(void);
329 static int skip_message(const char *, const char *, int);
330 static void printline(const char *, char *, int);
331 static void printsys(char *);
332 static int p_open(const char *, pid_t *);
333 static void readklog(void);
334 static void reapchild(int);
335 static void usage(void);
336 static int validate(struct sockaddr *, const char *);
337 static void unmapped(struct sockaddr *);
338 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
339 static int waitdaemon(int, int, int);
340 static void timedout(int);
341 static void increase_rcvbuf(int);
344 close_filed(struct filed *f)
347 if (f == NULL || f->f_file == -1)
350 (void)close(f->f_file);
352 f->f_type = F_UNUSED;
356 main(int argc, char *argv[])
358 int ch, i, fdsrmax = 0, l;
359 struct sockaddr_un sunx, fromunix;
360 struct sockaddr_storage frominet;
362 char line[MAXLINE + 1];
365 struct timeval tv, *tvp;
366 struct sigaction sact;
367 struct funix *fx, *fx1;
369 pid_t ppid = 1, spid;
372 if (madvise(NULL, 0, MADV_PROTECT) != 0)
373 dprintf("madvise() failed: %s\n", strerror(errno));
376 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:Fkl:m:nNop:P:sS:Tuv"))
393 case 'a': /* allow specific network addresses only */
394 if (allowaddr(optarg) == -1)
398 bindhostname = optarg;
406 case 'd': /* debug */
409 case 'f': /* configuration file */
412 case 'F': /* run in foreground instead of daemon */
415 case 'k': /* keep remote kern fac */
424 if (optarg[0] == '/') {
427 } else if ((name = strchr(optarg, ':')) != NULL) {
430 errx(1, "socket name must be absolute "
432 if (isdigit(*optarg)) {
433 perml = strtol(optarg, &ep, 8);
434 if (*ep || perml < 0 ||
435 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
436 errx(1, "invalid mode %s, exiting",
438 mode = (mode_t )perml;
440 errx(1, "invalid mode %s, exiting",
442 } else /* doesn't begin with '/', and no ':' */
443 errx(1, "can't parse path %s", optarg);
445 if (strlen(name) >= sizeof(sunx.sun_path))
446 errx(1, "%s path too long, exiting", name);
447 if ((fx = malloc(sizeof(struct funix))) == NULL)
448 errx(1, "malloc failed");
452 STAILQ_INSERT_TAIL(&funixes, fx, next);
455 case 'm': /* mark interval */
456 MarkInterval = atoi(optarg) * 60;
469 if (strlen(optarg) >= sizeof(sunx.sun_path))
470 errx(1, "%s path too long, exiting", optarg);
471 funix_default.name = optarg;
473 case 'P': /* path for alt. PID */
476 case 's': /* no network mode */
479 case 'S': /* path for privileged originator */
480 if (strlen(optarg) >= sizeof(sunx.sun_path))
481 errx(1, "%s path too long, exiting", optarg);
482 funix_secure.name = optarg;
487 case 'u': /* only log specified priority */
490 case 'v': /* log facility and priority */
496 if ((argc -= optind) != 0)
499 pfh = pidfile_open(PidFile, 0600, &spid);
502 errx(1, "syslogd already running, pid: %d", spid);
503 warn("cannot open pid file");
506 if ((!Foreground) && (!Debug)) {
507 ppid = waitdaemon(0, 0, 30);
509 warn("could not become daemon");
520 consfile.f_type = F_CONSOLE;
521 (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
522 sizeof(consfile.f_un.f_fname));
523 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
524 (void)signal(SIGTERM, dodie);
525 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
526 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
528 * We don't want the SIGCHLD and SIGHUP handlers to interfere
529 * with each other; they are likely candidates for being called
530 * simultaneously (SIGHUP closes pipe descriptor, process dies,
534 sigaddset(&mask, SIGHUP);
535 sact.sa_handler = reapchild;
537 sact.sa_flags = SA_RESTART;
538 (void)sigaction(SIGCHLD, &sact, NULL);
539 (void)signal(SIGALRM, domark);
540 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
541 (void)alarm(TIMERINTVL);
543 TAILQ_INIT(&deadq_head);
546 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
548 STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
549 (void)unlink(fx->name);
550 memset(&sunx, 0, sizeof(sunx));
551 sunx.sun_family = AF_LOCAL;
552 (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
553 fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
555 bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
556 chmod(fx->name, fx->mode) < 0) {
557 (void)snprintf(line, sizeof line,
558 "cannot create %s", fx->name);
560 dprintf("cannot create %s (%d)\n", fx->name, errno);
561 if (fx == &funix_default || fx == &funix_secure)
564 STAILQ_REMOVE(&funixes, fx, funix, next);
568 increase_rcvbuf(fx->s);
571 finet = socksetup(family, bindhostname);
575 for (i = 0; i < *finet; i++) {
576 if (shutdown(finet[i+1], SHUT_RD) < 0 &&
578 logerror("shutdown");
584 dprintf("listening on inet and/or inet6 socket\n");
586 dprintf("sending on inet and/or inet6 socket\n");
589 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
590 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
593 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
595 /* tuck my process id away */
598 dprintf("off & running....\n");
601 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
603 sigaddset(&mask, SIGCHLD);
604 sact.sa_handler = init;
606 sact.sa_flags = SA_RESTART;
607 (void)sigaction(SIGHUP, &sact, NULL);
610 tv.tv_sec = tv.tv_usec = 0;
612 if (fklog != -1 && fklog > fdsrmax)
614 if (finet && !SecureMode) {
615 for (i = 0; i < *finet; i++) {
616 if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
617 fdsrmax = finet[i+1];
620 STAILQ_FOREACH(fx, &funixes, next)
624 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
627 errx(1, "calloc fd_set");
635 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
640 if (finet && !SecureMode) {
641 for (i = 0; i < *finet; i++) {
642 if (finet[i+1] != -1)
643 FD_SET(finet[i+1], fdsr);
646 STAILQ_FOREACH(fx, &funixes, next)
649 i = select(fdsrmax+1, fdsr, NULL, NULL,
650 needdofsync ? &tv : tvp);
666 if (fklog != -1 && FD_ISSET(fklog, fdsr))
668 if (finet && !SecureMode) {
669 for (i = 0; i < *finet; i++) {
670 if (FD_ISSET(finet[i+1], fdsr)) {
671 len = sizeof(frominet);
672 l = recvfrom(finet[i+1], line, MAXLINE,
673 0, (struct sockaddr *)&frominet,
677 hname = cvthname((struct sockaddr *)&frominet);
678 unmapped((struct sockaddr *)&frominet);
679 if (validate((struct sockaddr *)&frominet, hname))
680 printline(hname, line, RemoteAddDate ? ADDDATE : 0);
681 } else if (l < 0 && errno != EINTR)
682 logerror("recvfrom inet");
686 STAILQ_FOREACH(fx, &funixes, next) {
687 if (FD_ISSET(fx->s, fdsr)) {
688 len = sizeof(fromunix);
689 l = recvfrom(fx->s, line, MAXLINE, 0,
690 (struct sockaddr *)&fromunix, &len);
693 printline(LocalHostName, line, 0);
694 } else if (l < 0 && errno != EINTR)
695 logerror("recvfrom unix");
704 unmapped(struct sockaddr *sa)
706 struct sockaddr_in6 *sin6;
707 struct sockaddr_in sin4;
709 if (sa->sa_family != AF_INET6)
711 if (sa->sa_len != sizeof(struct sockaddr_in6) ||
712 sizeof(sin4) > sa->sa_len)
714 sin6 = (struct sockaddr_in6 *)sa;
715 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
718 memset(&sin4, 0, sizeof(sin4));
719 sin4.sin_family = AF_INET;
720 sin4.sin_len = sizeof(struct sockaddr_in);
721 memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
722 sizeof(sin4.sin_addr));
723 sin4.sin_port = sin6->sin6_port;
725 memcpy(sa, &sin4, sin4.sin_len);
732 fprintf(stderr, "%s\n%s\n%s\n%s\n",
733 "usage: syslogd [-468ACcdFknosTuv] [-a allowed_peer]",
734 " [-b bind_address] [-f config_file]",
735 " [-l [mode:]path] [-m mark_interval]",
736 " [-P pid_file] [-p log_socket]");
741 * Take a raw input line, decode the message, and print the message
742 * on the appropriate log files.
745 printline(const char *hname, char *msg, int flags)
750 char line[MAXLINE + 1];
752 /* test for special codes */
757 n = strtol(p + 1, &q, 10);
758 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
763 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
767 * Don't allow users to log kernel messages.
768 * NOTE: since LOG_KERN == 0 this will also match
769 * messages with no facility specified.
771 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
772 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
776 while ((c = (unsigned char)*p++) != '\0' &&
777 q < &line[sizeof(line) - 4]) {
778 if (mask_C1 && (c & 0x80) && c < 0xA0) {
783 if (isascii(c) && iscntrl(c)) {
786 } else if (c == '\t') {
798 logmsg(pri, line, hname, flags);
802 * Read /dev/klog while data are available, split into lines.
807 char *p, *q, line[MAXLINE + 1];
812 i = read(fklog, line + len, MAXLINE - 1 - len);
814 line[i + len] = '\0';
816 if (i < 0 && errno != EINTR && errno != EAGAIN) {
823 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
828 if (len >= MAXLINE - 1) {
833 memmove(line, p, len + 1);
840 * Take a raw input line from /dev/klog, format similar to syslog().
847 int flags, isprintf, pri;
849 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
855 n = strtol(p + 1, &q, 10);
856 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
863 * Kernel printf's and LOG_CONSOLE messages have been displayed
864 * on the console already.
866 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
868 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
870 logmsg(pri, p, LocalHostName, flags);
876 * Match a program or host name against a specification.
877 * Return a non-0 value if the message must be ignored
878 * based on the specification.
881 skip_message(const char *name, const char *spec, int checkcase)
886 /* Behaviour on explicit match */
901 s = strstr (spec, name);
903 s = strcasestr (spec, name);
906 prev = (s == spec ? ',' : *(s - 1));
907 next = *(s + strlen (name));
909 if (prev == ',' && (next == '\0' || next == ','))
910 /* Explicit match: skip iff the spec is an
915 /* No explicit match for this name: skip the message iff
916 the spec is an inclusive one. */
921 * Log a message to the appropriate log files, users, etc. based on
925 logmsg(int pri, const char *msg, const char *from, int flags)
928 int i, fac, msglen, omask, prilev;
929 const char *timestamp;
930 char prog[NAME_MAX+1];
933 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
934 pri, flags, from, msg);
936 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
939 * Check to see if msg looks non-standard.
941 msglen = strlen(msg);
942 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
943 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
947 if (flags & ADDDATE) {
948 timestamp = ctime(&now) + 4;
955 /* skip leading blanks */
956 while (isspace(*msg)) {
961 /* extract facility and priority level */
963 fac = LOG_NFACILITIES;
967 /* Check maximum facility number. */
968 if (fac > LOG_NFACILITIES) {
969 (void)sigsetmask(omask);
973 prilev = LOG_PRI(pri);
975 /* extract program name */
976 for (i = 0; i < NAME_MAX; i++) {
977 if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
978 msg[i] == '/' || isspace(msg[i]))
984 /* add kernel prefix for kernel messages */
985 if (flags & ISKERNEL) {
986 snprintf(buf, sizeof(buf), "%s: %s",
987 use_bootfile ? bootfile : "kernel", msg);
989 msglen = strlen(buf);
992 /* log the message to the particular outputs */
996 * Open in non-blocking mode to avoid hangs during open
997 * and close(waiting for the port to drain).
999 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1001 if (f->f_file >= 0) {
1002 (void)strlcpy(f->f_lasttime, timestamp,
1003 sizeof(f->f_lasttime));
1004 fprintlog(f, flags, msg);
1008 (void)sigsetmask(omask);
1011 for (f = Files; f; f = f->f_next) {
1012 /* skip messages that are incorrect priority */
1013 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1014 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1015 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1017 || f->f_pmask[fac] == INTERNAL_NOPRI)
1020 /* skip messages with the incorrect hostname */
1021 if (skip_message(from, f->f_host, 0))
1024 /* skip messages with the incorrect program name */
1025 if (skip_message(prog, f->f_program, 1))
1028 /* skip message to console if it has already been printed */
1029 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1032 /* don't output marks to recently written files */
1033 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1037 * suppress duplicate lines to this file
1039 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1040 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1041 !strcmp(msg, f->f_prevline) &&
1042 !strcasecmp(from, f->f_prevhost)) {
1043 (void)strlcpy(f->f_lasttime, timestamp,
1044 sizeof(f->f_lasttime));
1046 dprintf("msg repeated %d times, %ld sec of %d\n",
1047 f->f_prevcount, (long)(now - f->f_time),
1048 repeatinterval[f->f_repeatcount]);
1050 * If domark would have logged this by now,
1051 * flush it now (so we don't hold isolated messages),
1052 * but back off so we'll flush less often
1055 if (now > REPEATTIME(f)) {
1056 fprintlog(f, flags, (char *)NULL);
1060 /* new line, save it */
1062 fprintlog(f, 0, (char *)NULL);
1063 f->f_repeatcount = 0;
1065 (void)strlcpy(f->f_lasttime, timestamp,
1066 sizeof(f->f_lasttime));
1067 (void)strlcpy(f->f_prevhost, from,
1068 sizeof(f->f_prevhost));
1069 if (msglen < MAXSVLINE) {
1070 f->f_prevlen = msglen;
1071 (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1072 fprintlog(f, flags, (char *)NULL);
1074 f->f_prevline[0] = 0;
1076 fprintlog(f, flags, msg);
1080 (void)sigsetmask(omask);
1088 for (f = Files; f; f = f->f_next) {
1089 if ((f->f_type == F_FILE) &&
1090 (f->f_flags & FFLAG_NEEDSYNC)) {
1091 f->f_flags &= ~FFLAG_NEEDSYNC;
1092 (void)fsync(f->f_file);
1099 fprintlog(struct filed *f, int flags, const char *msg)
1101 struct iovec iov[IOV_SIZE];
1104 int i, l, lsent = 0;
1105 char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1106 char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1110 if (f->f_type == F_WALL) {
1111 v->iov_base = greetings;
1112 /* The time displayed is not synchornized with the other log
1113 * destinations (like messages). Following fragment was using
1114 * ctime(&now), which was updating the time every 30 sec.
1115 * With f_lasttime, time is synchronized correctly.
1117 v->iov_len = snprintf(greetings, sizeof greetings,
1118 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1119 f->f_prevhost, f->f_lasttime);
1120 if (v->iov_len >= sizeof greetings)
1121 v->iov_len = sizeof greetings - 1;
1127 v->iov_base = f->f_lasttime;
1128 v->iov_len = strlen(f->f_lasttime);
1130 v->iov_base = space;
1136 static char fp_buf[30]; /* Hollow laugh */
1137 int fac = f->f_prevpri & LOG_FACMASK;
1138 int pri = LOG_PRI(f->f_prevpri);
1139 const char *f_s = NULL;
1140 char f_n[5]; /* Hollow laugh */
1141 const char *p_s = NULL;
1142 char p_n[5]; /* Hollow laugh */
1144 if (LogFacPri > 1) {
1147 for (c = facilitynames; c->c_name; c++) {
1148 if (c->c_val == fac) {
1153 for (c = prioritynames; c->c_name; c++) {
1154 if (c->c_val == pri) {
1161 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1165 snprintf(p_n, sizeof p_n, "%d", pri);
1168 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1169 v->iov_base = fp_buf;
1170 v->iov_len = strlen(fp_buf);
1177 v->iov_base = f->f_prevhost;
1178 v->iov_len = strlen(v->iov_base);
1180 v->iov_base = space;
1185 wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1191 v->iov_len = strlen(msg);
1192 } else if (f->f_prevcount > 1) {
1193 v->iov_base = repbuf;
1194 v->iov_len = snprintf(repbuf, sizeof repbuf,
1195 "last message repeated %d times", f->f_prevcount);
1197 v->iov_base = f->f_prevline;
1198 v->iov_len = f->f_prevlen;
1202 dprintf("Logging to %s", TypeNames[f->f_type]);
1205 switch (f->f_type) {
1212 port = (int)ntohs(((struct sockaddr_in *)
1213 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1215 dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1217 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1219 /* check for local vs remote messages */
1220 if (strcasecmp(f->f_prevhost, LocalHostName))
1221 l = snprintf(line, sizeof line - 1,
1222 "<%d>%.15s Forwarded from %s: %s",
1223 f->f_prevpri, (char *)iov[0].iov_base,
1224 f->f_prevhost, (char *)iov[5].iov_base);
1226 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1227 f->f_prevpri, (char *)iov[0].iov_base,
1228 (char *)iov[5].iov_base);
1231 else if (l > MAXLINE)
1235 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1236 for (i = 0; i < *finet; i++) {
1239 * should we check AF first, or just
1240 * trial and error? FWD
1243 address_family_of(finet[i+1]))
1245 lsent = sendto(finet[i+1], line, l, 0,
1246 r->ai_addr, r->ai_addrlen);
1250 if (lsent == l && !send_to_all)
1253 dprintf("lsent/l: %d/%d\n", lsent, l);
1268 /* case ENOTSOCK: */
1270 /* case EMSGSIZE: */
1273 /* case ECONNREFUSED: */
1275 dprintf("removing entry: errno=%d\n", e);
1276 f->f_type = F_UNUSED;
1284 dprintf(" %s\n", f->f_un.f_fname);
1287 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1289 * If writev(2) fails for potentially transient errors
1290 * like the filesystem being full, ignore it.
1291 * Otherwise remove this logfile from the list.
1293 if (errno != ENOSPC) {
1297 logerror(f->f_un.f_fname);
1299 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1300 f->f_flags |= FFLAG_NEEDSYNC;
1306 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1309 if (f->f_un.f_pipe.f_pid == 0) {
1310 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1311 &f->f_un.f_pipe.f_pid)) < 0) {
1312 f->f_type = F_UNUSED;
1313 logerror(f->f_un.f_pipe.f_pname);
1317 if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1320 if (f->f_un.f_pipe.f_pid > 0)
1321 deadq_enter(f->f_un.f_pipe.f_pid,
1322 f->f_un.f_pipe.f_pname);
1323 f->f_un.f_pipe.f_pid = 0;
1325 logerror(f->f_un.f_pipe.f_pname);
1330 if (flags & IGN_CONS) {
1331 dprintf(" (ignored)\n");
1337 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1341 errno = 0; /* ttymsg() only sometimes returns an errno */
1342 if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1343 f->f_type = F_UNUSED;
1353 wallmsg(f, iov, IOV_SIZE);
1361 * WALLMSG -- Write a message to the world at large
1363 * Write the specified message to either the entire
1364 * world, or a list of approved users.
1367 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1369 static int reenter; /* avoid calling ourselves */
1378 while ((ut = getutxent()) != NULL) {
1379 if (ut->ut_type != USER_PROCESS)
1381 if (f->f_type == F_WALL) {
1382 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1383 TTYMSGTIME)) != NULL) {
1384 errno = 0; /* already in msg */
1389 /* should we send the message to this user? */
1390 for (i = 0; i < MAXUNAMES; i++) {
1391 if (!f->f_un.f_uname[i][0])
1393 if (!strcmp(f->f_un.f_uname[i], ut->ut_user)) {
1394 if ((p = ttymsg(iov, iovlen, ut->ut_line,
1395 TTYMSGTIME)) != NULL) {
1396 errno = 0; /* already in msg */
1408 reapchild(int signo __unused)
1414 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1416 /* Don't tell while we are initting. */
1419 /* First, look if it's a process from the dead queue. */
1420 if (deadq_remove(pid))
1423 /* Now, look in list of active processes. */
1424 for (f = Files; f; f = f->f_next)
1425 if (f->f_type == F_PIPE &&
1426 f->f_un.f_pipe.f_pid == pid) {
1428 f->f_un.f_pipe.f_pid = 0;
1429 log_deadchild(pid, status,
1430 f->f_un.f_pipe.f_pname);
1439 * Return a printable representation of a host address.
1442 cvthname(struct sockaddr *f)
1445 sigset_t omask, nmask;
1446 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1448 error = getnameinfo((struct sockaddr *)f,
1449 ((struct sockaddr *)f)->sa_len,
1450 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1451 dprintf("cvthname(%s)\n", ip);
1454 dprintf("Malformed from address %s\n", gai_strerror(error));
1460 sigemptyset(&nmask);
1461 sigaddset(&nmask, SIGHUP);
1462 sigprocmask(SIG_BLOCK, &nmask, &omask);
1463 error = getnameinfo((struct sockaddr *)f,
1464 ((struct sockaddr *)f)->sa_len,
1465 hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1466 sigprocmask(SIG_SETMASK, &omask, NULL);
1468 dprintf("Host name for your address (%s) unknown\n", ip);
1472 if (hl > 0 && hname[hl-1] == '.')
1474 trimdomain(hname, hl);
1486 domark(int signo __unused)
1493 * Print syslogd errors some place.
1496 logerror(const char *type)
1499 static int recursed = 0;
1501 /* If there's an error while trying to log an error, give up. */
1507 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1509 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1511 dprintf("%s\n", buf);
1512 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1521 int was_initialized;
1524 was_initialized = Initialized;
1525 Initialized = 0; /* Don't log SIGCHLDs. */
1526 for (f = Files; f != NULL; f = f->f_next) {
1527 /* flush any pending output */
1529 fprintlog(f, 0, (char *)NULL);
1530 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1532 f->f_un.f_pipe.f_pid = 0;
1535 Initialized = was_initialized;
1537 dprintf("syslogd: exiting on signal %d\n", signo);
1538 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1542 STAILQ_FOREACH(fx, &funixes, next)
1543 (void)unlink(fx->name);
1544 pidfile_remove(pfh);
1550 * INIT -- Initialize syslogd from configuration table
1557 struct filed *f, *next, **nextp;
1559 char cline[LINE_MAX];
1560 char prog[LINE_MAX];
1561 char host[MAXHOSTNAMELEN];
1562 char oldLocalHostName[MAXHOSTNAMELEN];
1563 char hostMsg[2*MAXHOSTNAMELEN+40];
1564 char bootfileMsg[LINE_MAX];
1569 * Load hostname (may have changed).
1572 (void)strlcpy(oldLocalHostName, LocalHostName,
1573 sizeof(oldLocalHostName));
1574 if (gethostname(LocalHostName, sizeof(LocalHostName)))
1575 err(EX_OSERR, "gethostname() failed");
1576 if ((p = strchr(LocalHostName, '.')) != NULL) {
1584 * Close all open log files.
1587 for (f = Files; f != NULL; f = next) {
1588 /* flush any pending output */
1590 fprintlog(f, 0, (char *)NULL);
1592 switch (f->f_type) {
1600 if (f->f_un.f_pipe.f_pid > 0) {
1602 deadq_enter(f->f_un.f_pipe.f_pid,
1603 f->f_un.f_pipe.f_pname);
1605 f->f_un.f_pipe.f_pid = 0;
1609 if (f->f_program) free(f->f_program);
1610 if (f->f_host) free(f->f_host);
1616 /* open the configuration file */
1617 if ((cf = fopen(ConfFile, "r")) == NULL) {
1618 dprintf("cannot open %s\n", ConfFile);
1619 *nextp = (struct filed *)calloc(1, sizeof(*f));
1620 if (*nextp == NULL) {
1624 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1625 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1626 if ((*nextp)->f_next == NULL) {
1630 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1636 * Foreach line in the conf table, open that file.
1639 (void)strlcpy(host, "*", sizeof(host));
1640 (void)strlcpy(prog, "*", sizeof(prog));
1641 while (fgets(cline, sizeof(cline), cf) != NULL) {
1643 * check for end-of-section, comments, strip off trailing
1644 * spaces and newline character. #!prog is treated specially:
1645 * following lines apply only to that program.
1647 for (p = cline; isspace(*p); ++p)
1653 if (*p != '!' && *p != '+' && *p != '-')
1656 if (*p == '+' || *p == '-') {
1660 if ((!*p) || (*p == '*')) {
1661 (void)strlcpy(host, "*", sizeof(host));
1666 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1667 if (!isalnum(*p) && *p != '.' && *p != '-'
1668 && *p != ',' && *p != ':' && *p != '%')
1677 while (isspace(*p)) p++;
1678 if ((!*p) || (*p == '*')) {
1679 (void)strlcpy(prog, "*", sizeof(prog));
1682 for (i = 0; i < LINE_MAX - 1; i++) {
1683 if (!isprint(p[i]) || isspace(p[i]))
1690 for (p = cline + 1; *p != '\0'; p++) {
1693 if (*(p - 1) == '\\') {
1701 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1703 f = (struct filed *)calloc(1, sizeof(*f));
1710 cfline(cline, f, prog, host);
1713 /* close the configuration file */
1720 for (f = Files; f; f = f->f_next) {
1721 for (i = 0; i <= LOG_NFACILITIES; i++)
1722 if (f->f_pmask[i] == INTERNAL_NOPRI)
1725 printf("%d ", f->f_pmask[i]);
1726 printf("%s: ", TypeNames[f->f_type]);
1727 switch (f->f_type) {
1729 printf("%s", f->f_un.f_fname);
1734 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1738 port = (int)ntohs(((struct sockaddr_in *)
1739 (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1742 f->f_un.f_forw.f_hname, port);
1744 printf("%s", f->f_un.f_forw.f_hname);
1749 printf("%s", f->f_un.f_pipe.f_pname);
1753 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1754 printf("%s, ", f->f_un.f_uname[i]);
1758 printf(" (%s)", f->f_program);
1763 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1764 dprintf("syslogd: restarted\n");
1766 * Log a change in hostname, but only on a restart.
1768 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1769 (void)snprintf(hostMsg, sizeof(hostMsg),
1770 "syslogd: hostname changed, \"%s\" to \"%s\"",
1771 oldLocalHostName, LocalHostName);
1772 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1773 dprintf("%s\n", hostMsg);
1776 * Log the kernel boot file if we aren't going to use it as
1777 * the prefix, and if this is *not* a restart.
1779 if (signo == 0 && !use_bootfile) {
1780 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1781 "syslogd: kernel boot file is %s", bootfile);
1782 logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1783 dprintf("%s\n", bootfileMsg);
1788 * Crack a configuration file line
1791 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1793 struct addrinfo hints, *res;
1794 int error, i, pri, syncfile;
1797 char buf[MAXLINE], ebuf[100];
1799 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1801 errno = 0; /* keep strerror() stuff out of logerror messages */
1803 /* clear out file entry */
1804 memset(f, 0, sizeof(*f));
1805 for (i = 0; i <= LOG_NFACILITIES; i++)
1806 f->f_pmask[i] = INTERNAL_NOPRI;
1808 /* save hostname if any */
1809 if (host && *host == '*')
1814 f->f_host = strdup(host);
1815 if (f->f_host == NULL) {
1819 hl = strlen(f->f_host);
1820 if (hl > 0 && f->f_host[hl-1] == '.')
1821 f->f_host[--hl] = '\0';
1822 trimdomain(f->f_host, hl);
1825 /* save program name if any */
1826 if (prog && *prog == '*')
1829 f->f_program = strdup(prog);
1830 if (f->f_program == NULL) {
1836 /* scan through the list of selectors */
1837 for (p = line; *p && *p != '\t' && *p != ' ';) {
1842 /* find the end of this facility name list */
1843 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1846 /* get the priority comparison */
1874 /* collect priority name */
1875 for (bp = buf; *q && !strchr("\t,; ", *q); )
1880 while (strchr(",;", *q))
1883 /* decode priority name */
1886 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1888 /* Ignore trailing spaces. */
1889 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1892 pri = decode(buf, prioritynames);
1895 (void)snprintf(ebuf, sizeof ebuf,
1896 "unknown priority name \"%s\"", buf);
1902 pri_cmp = (UniquePriority)
1907 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1909 /* scan facilities */
1910 while (*p && !strchr("\t.; ", *p)) {
1911 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1916 for (i = 0; i < LOG_NFACILITIES; i++) {
1917 f->f_pmask[i] = pri;
1918 f->f_pcmp[i] = pri_cmp;
1921 i = decode(buf, facilitynames);
1924 (void)snprintf(ebuf, sizeof ebuf,
1925 "unknown facility name \"%s\"",
1930 f->f_pmask[i >> 3] = pri;
1931 f->f_pcmp[i >> 3] = pri_cmp;
1933 while (*p == ',' || *p == ' ')
1940 /* skip to action part */
1941 while (*p == '\t' || *p == ' ')
1956 * scan forward to see if there is a port defined.
1957 * so we can't use strlcpy..
1959 i = sizeof(f->f_un.f_forw.f_hname);
1960 tp = f->f_un.f_forw.f_hname;
1964 * an ipv6 address should start with a '[' in that case
1965 * we should scan for a ']'
1971 while (*p && (*p != endkey) && (i-- > 0)) {
1974 if (endkey == ']' && *p == endkey)
1978 /* See if we copied a domain and have a port */
1984 memset(&hints, 0, sizeof(hints));
1985 hints.ai_family = family;
1986 hints.ai_socktype = SOCK_DGRAM;
1987 error = getaddrinfo(f->f_un.f_forw.f_hname,
1988 p ? p : "syslog", &hints, &res);
1990 logerror(gai_strerror(error));
1993 f->f_un.f_forw.f_addr = res;
1998 if ((f->f_file = open(p, logflags, 0600)) < 0) {
1999 f->f_type = F_UNUSED;
2004 f->f_flags |= FFLAG_SYNC;
2005 if (isatty(f->f_file)) {
2006 if (strcmp(p, ctty) == 0)
2007 f->f_type = F_CONSOLE;
2010 (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
2011 sizeof(f->f_un.f_fname));
2013 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2019 f->f_un.f_pipe.f_pid = 0;
2020 (void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2021 sizeof(f->f_un.f_pipe.f_pname));
2030 for (i = 0; i < MAXUNAMES && *p; i++) {
2031 for (q = p; *q && *q != ','; )
2033 (void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2034 if ((q - p) >= MAXLOGNAME)
2035 f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2037 f->f_un.f_uname[i][q - p] = '\0';
2038 while (*q == ',' || *q == ' ')
2042 f->f_type = F_USERS;
2049 * Decode a symbolic name to a numeric value
2052 decode(const char *name, const CODE *codetab)
2058 return (atoi(name));
2060 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2062 *p = tolower(*name);
2067 for (c = codetab; c->c_name; c++)
2068 if (!strcmp(buf, c->c_name))
2080 now = time((time_t *)NULL);
2081 MarkSeq += TIMERINTVL;
2082 if (MarkSeq >= MarkInterval) {
2083 logmsg(LOG_INFO, "-- MARK --",
2084 LocalHostName, ADDDATE|MARK);
2088 for (f = Files; f; f = f->f_next) {
2089 if (f->f_prevcount && now >= REPEATTIME(f)) {
2090 dprintf("flush %s: repeated %d times, %d sec.\n",
2091 TypeNames[f->f_type], f->f_prevcount,
2092 repeatinterval[f->f_repeatcount]);
2093 fprintlog(f, 0, (char *)NULL);
2098 /* Walk the dead queue, and see if we should signal somebody. */
2099 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2100 next = TAILQ_NEXT(q, dq_entries);
2102 switch (q->dq_timeout) {
2104 /* Already signalled once, try harder now. */
2105 if (kill(q->dq_pid, SIGKILL) != 0)
2106 (void)deadq_remove(q->dq_pid);
2111 * Timed out on dead queue, send terminate
2112 * signal. Note that we leave the removal
2113 * from the dead queue to reapchild(), which
2114 * will also log the event (unless the process
2115 * didn't even really exist, in case we simply
2116 * drop it from the dead queue).
2118 if (kill(q->dq_pid, SIGTERM) != 0)
2119 (void)deadq_remove(q->dq_pid);
2127 (void)alarm(TIMERINTVL);
2131 * fork off and become a daemon, but wait for the child to come online
2132 * before returing to the parent, or we get disk thrashing at boot etc.
2133 * Set a timer so we don't hang forever if it wedges.
2136 waitdaemon(int nochdir, int noclose, int maxwait)
2140 pid_t pid, childpid;
2142 switch (childpid = fork()) {
2148 signal(SIGALRM, timedout);
2150 while ((pid = wait3(&status, 0, NULL)) != -1) {
2151 if (WIFEXITED(status))
2152 errx(1, "child pid %d exited with return code %d",
2153 pid, WEXITSTATUS(status));
2154 if (WIFSIGNALED(status))
2155 errx(1, "child pid %d exited on signal %d%s",
2156 pid, WTERMSIG(status),
2157 WCOREDUMP(status) ? " (core dumped)" :
2159 if (pid == childpid) /* it's gone... */
2171 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2172 (void)dup2(fd, STDIN_FILENO);
2173 (void)dup2(fd, STDOUT_FILENO);
2174 (void)dup2(fd, STDERR_FILENO);
2182 * We get a SIGALRM from the child when it's running and finished doing it's
2183 * fsync()'s or O_SYNC writes for all the boot messages.
2185 * We also get a signal from the kernel if the timer expires, so check to
2186 * see what happened.
2189 timedout(int sig __unused)
2193 signal(SIGALRM, SIG_DFL);
2195 errx(1, "timed out waiting for child");
2201 * Add `s' to the list of allowable peer addresses to accept messages
2204 * `s' is a string in the form:
2206 * [*]domainname[:{servicename|portnumber|*}]
2210 * netaddr/maskbits[:{servicename|portnumber|*}]
2212 * Returns -1 on error, 0 if the argument was valid.
2218 struct allowedpeer ap;
2221 struct addrinfo hints, *res;
2222 struct in_addr *addrp, *maskp;
2225 u_int32_t *addr6p, *mask6p;
2227 char ip[NI_MAXHOST];
2230 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2233 if ((cp1 = strrchr(cp1, ':'))) {
2234 /* service/port provided */
2236 if (strlen(cp1) == 1 && *cp1 == '*')
2237 /* any port allowed */
2239 else if ((se = getservbyname(cp1, "udp"))) {
2240 ap.port = ntohs(se->s_port);
2242 ap.port = strtol(cp1, &cp2, 0);
2244 return (-1); /* port not numeric */
2247 if ((se = getservbyname("syslog", "udp")))
2248 ap.port = ntohs(se->s_port);
2250 /* sanity, should not happen */
2254 if ((cp1 = strchr(s, '/')) != NULL &&
2255 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2257 if ((masklen = atoi(cp1 + 1)) < 0)
2262 cp2 = s + strlen(s) - 1;
2273 memset(&hints, 0, sizeof(hints));
2274 hints.ai_family = PF_UNSPEC;
2275 hints.ai_socktype = SOCK_DGRAM;
2276 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2277 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2279 memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2280 memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2281 ap.a_mask.ss_family = res->ai_family;
2282 if (res->ai_family == AF_INET) {
2283 ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2284 maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2285 addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2287 /* use default netmask */
2288 if (IN_CLASSA(ntohl(addrp->s_addr)))
2289 maskp->s_addr = htonl(IN_CLASSA_NET);
2290 else if (IN_CLASSB(ntohl(addrp->s_addr)))
2291 maskp->s_addr = htonl(IN_CLASSB_NET);
2293 maskp->s_addr = htonl(IN_CLASSC_NET);
2294 } else if (masklen <= 32) {
2295 /* convert masklen to netmask */
2299 maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2304 /* Lose any host bits in the network number. */
2305 addrp->s_addr &= maskp->s_addr;
2308 else if (res->ai_family == AF_INET6 && masklen <= 128) {
2309 ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2312 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2313 /* convert masklen to netmask */
2314 while (masklen > 0) {
2316 *mask6p = htonl(~(0xffffffff >> masklen));
2319 *mask6p++ = 0xffffffff;
2322 /* Lose any host bits in the network number. */
2323 mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2324 addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2325 for (i = 0; i < 4; i++)
2326 addr6p[i] &= mask6p[i];
2335 /* arg `s' is domain name */
2349 printf("allowaddr: rule %d: ", NumAllowed);
2351 printf("numeric, ");
2352 getnameinfo((struct sockaddr *)&ap.a_addr,
2353 ((struct sockaddr *)&ap.a_addr)->sa_len,
2354 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2355 printf("addr = %s, ", ip);
2356 getnameinfo((struct sockaddr *)&ap.a_mask,
2357 ((struct sockaddr *)&ap.a_mask)->sa_len,
2358 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2359 printf("mask = %s; ", ip);
2361 printf("domainname = %s; ", ap.a_name);
2363 printf("port = %d\n", ap.port);
2366 if ((AllowedPeers = realloc(AllowedPeers,
2367 ++NumAllowed * sizeof(struct allowedpeer)))
2369 logerror("realloc");
2372 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2377 * Validate that the remote peer has permission to log to us.
2380 validate(struct sockaddr *sa, const char *hname)
2384 char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2385 struct allowedpeer *ap;
2386 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2389 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2391 struct addrinfo hints, *res;
2394 if (NumAllowed == 0)
2395 /* traditional behaviour, allow everything */
2398 (void)strlcpy(name, hname, sizeof(name));
2399 memset(&hints, 0, sizeof(hints));
2400 hints.ai_family = PF_UNSPEC;
2401 hints.ai_socktype = SOCK_DGRAM;
2402 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2403 if (getaddrinfo(name, NULL, &hints, &res) == 0)
2405 else if (strchr(name, '.') == NULL) {
2406 strlcat(name, ".", sizeof name);
2407 strlcat(name, LocalDomain, sizeof name);
2409 if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2410 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2411 return (0); /* for safety, should not occur */
2412 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2416 /* now, walk down the list */
2417 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2418 if (ap->port != 0 && ap->port != sport) {
2419 dprintf("rejected in rule %d due to port mismatch.\n", i);
2423 if (ap->isnumeric) {
2424 if (ap->a_addr.ss_family != sa->sa_family) {
2425 dprintf("rejected in rule %d due to address family mismatch.\n", i);
2428 if (ap->a_addr.ss_family == AF_INET) {
2429 sin4 = (struct sockaddr_in *)sa;
2430 a4p = (struct sockaddr_in *)&ap->a_addr;
2431 m4p = (struct sockaddr_in *)&ap->a_mask;
2432 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2433 != a4p->sin_addr.s_addr) {
2434 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2439 else if (ap->a_addr.ss_family == AF_INET6) {
2440 sin6 = (struct sockaddr_in6 *)sa;
2441 a6p = (struct sockaddr_in6 *)&ap->a_addr;
2442 m6p = (struct sockaddr_in6 *)&ap->a_mask;
2443 if (a6p->sin6_scope_id != 0 &&
2444 sin6->sin6_scope_id != a6p->sin6_scope_id) {
2445 dprintf("rejected in rule %d due to scope mismatch.\n", i);
2449 for (j = 0; j < 16; j += 4) {
2450 if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2451 != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2457 dprintf("rejected in rule %d due to IP mismatch.\n", i);
2468 /* allow wildmatch */
2471 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2472 dprintf("rejected in rule %d due to name mismatch.\n", i);
2478 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2479 dprintf("rejected in rule %d due to name mismatch.\n", i);
2484 dprintf("accepted in rule %d.\n", i);
2485 return (1); /* hooray! */
2491 * Fairly similar to popen(3), but returns an open descriptor, as
2492 * opposed to a FILE *.
2495 p_open(const char *prog, pid_t *rpid)
2497 int pfd[2], nulldesc;
2499 sigset_t omask, mask;
2500 char *argv[4]; /* sh -c cmd NULL */
2503 if (pipe(pfd) == -1)
2505 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2506 /* we are royally screwed anyway */
2510 sigaddset(&mask, SIGALRM);
2511 sigaddset(&mask, SIGHUP);
2512 sigprocmask(SIG_BLOCK, &mask, &omask);
2513 switch ((pid = fork())) {
2515 sigprocmask(SIG_SETMASK, &omask, 0);
2520 argv[0] = strdup("sh");
2521 argv[1] = strdup("-c");
2522 argv[2] = strdup(prog);
2524 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2530 (void)setsid(); /* Avoid catching SIGHUPs. */
2533 * Throw away pending signals, and reset signal
2534 * behaviour to standard values.
2536 signal(SIGALRM, SIG_IGN);
2537 signal(SIGHUP, SIG_IGN);
2538 sigprocmask(SIG_SETMASK, &omask, 0);
2539 signal(SIGPIPE, SIG_DFL);
2540 signal(SIGQUIT, SIG_DFL);
2541 signal(SIGALRM, SIG_DFL);
2542 signal(SIGHUP, SIG_DFL);
2544 dup2(pfd[0], STDIN_FILENO);
2545 dup2(nulldesc, STDOUT_FILENO);
2546 dup2(nulldesc, STDERR_FILENO);
2549 (void)execvp(_PATH_BSHELL, argv);
2553 sigprocmask(SIG_SETMASK, &omask, 0);
2557 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2558 * supposed to get an EWOULDBLOCK on writev(2), which is
2559 * caught by the logic above anyway, which will in turn close
2560 * the pipe, and fork a new logging subprocess if necessary.
2561 * The stale subprocess will be killed some time later unless
2562 * it terminated itself due to closing its input pipe (so we
2563 * get rid of really dead puppies).
2565 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2567 (void)snprintf(errmsg, sizeof errmsg,
2568 "Warning: cannot change pipe to PID %d to "
2569 "non-blocking behaviour.",
2578 deadq_enter(pid_t pid, const char *name)
2584 * Be paranoid, if we can't signal the process, don't enter it
2585 * into the dead queue (perhaps it's already dead). If possible,
2586 * we try to fetch and log the child's status.
2588 if (kill(pid, 0) != 0) {
2589 if (waitpid(pid, &status, WNOHANG) > 0)
2590 log_deadchild(pid, status, name);
2594 p = malloc(sizeof(struct deadq_entry));
2601 p->dq_timeout = DQ_TIMO_INIT;
2602 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2606 deadq_remove(pid_t pid)
2610 TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2611 if (q->dq_pid == pid) {
2612 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2622 log_deadchild(pid_t pid, int status, const char *name)
2628 errno = 0; /* Keep strerror() stuff out of logerror messages. */
2629 if (WIFSIGNALED(status)) {
2630 reason = "due to signal";
2631 code = WTERMSIG(status);
2633 reason = "with status";
2634 code = WEXITSTATUS(status);
2638 (void)snprintf(buf, sizeof buf,
2639 "Logging subprocess %d (%s) exited %s %d.",
2640 pid, name, reason, code);
2645 socksetup(int af, char *bindhostname)
2647 struct addrinfo hints, *res, *r;
2648 const char *bindservice;
2650 int error, maxs, *s, *socks;
2653 * We have to handle this case for backwards compatibility:
2654 * If there are two (or more) colons but no '[' and ']',
2655 * assume this is an inet6 address without a service.
2657 bindservice = "syslog";
2658 if (bindhostname != NULL) {
2660 if (*bindhostname == '[' &&
2661 (cp = strchr(bindhostname + 1, ']')) != NULL) {
2664 if (cp[1] == ':' && cp[2] != '\0')
2665 bindservice = cp + 2;
2668 cp = strchr(bindhostname, ':');
2669 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2672 bindservice = cp + 1;
2673 if (cp == bindhostname)
2674 bindhostname = NULL;
2681 memset(&hints, 0, sizeof(hints));
2682 hints.ai_flags = AI_PASSIVE;
2683 hints.ai_family = af;
2684 hints.ai_socktype = SOCK_DGRAM;
2685 error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2687 logerror(gai_strerror(error));
2692 /* Count max number of sockets we may open */
2693 for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2694 socks = malloc((maxs+1) * sizeof(int));
2695 if (socks == NULL) {
2696 logerror("couldn't allocate memory for sockets");
2700 *socks = 0; /* num of sockets counter at start of array */
2702 for (r = res; r; r = r->ai_next) {
2704 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2710 if (r->ai_family == AF_INET6) {
2711 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2712 (char *)&on, sizeof (on)) < 0) {
2713 logerror("setsockopt");
2719 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2720 (char *)&on, sizeof (on)) < 0) {
2721 logerror("setsockopt");
2726 * RFC 3164 recommends that client side message
2727 * should come from the privileged syslogd port.
2729 * If the system administrator choose not to obey
2730 * this, we can skip the bind() step so that the
2731 * system will choose a port for us.
2734 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2741 increase_rcvbuf(*s);
2762 increase_rcvbuf(int fd)
2764 socklen_t len, slen;
2768 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2769 if (len < RCVBUF_MINSIZE) {
2770 len = RCVBUF_MINSIZE;
2771 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));