2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1983, 1988, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
34 * Copyright (c) 2018 Prodrive Technologies, https://prodrive-technologies.com/
35 * Author: Ed Schouten <ed@FreeBSD.org>
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
46 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
47 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
50 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 static const char copyright[] =
61 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
62 The Regents of the University of California. All rights reserved.\n";
67 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
75 * syslogd -- log system messages
77 * This program implements a system log. It takes a series of lines.
78 * Each line may have a priority, signified as "<n>" as
79 * the first characters of the line. If this is
80 * not present, a default priority is used.
82 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
83 * cause it to reread its configuration file.
87 * MAXLINE -- the maximum line length that can be handled.
88 * DEFUPRI -- the default priority for user messages
89 * DEFSPRI -- the default priority for kernel messages
92 * extensive changes by Ralph Campbell
93 * more extensive changes by Eric Allman (again)
94 * Extension to log by program name as well as facility and priority
96 * -u and -v by Harlan Stenn.
97 * Priority comparison code by Harlan Stenn.
100 /* Maximum number of characters in time of last occurrence */
101 #define MAXLINE 2048 /* maximum line length */
102 #define MAXSVLINE MAXLINE /* maximum saved line length */
103 #define DEFUPRI (LOG_USER|LOG_NOTICE)
104 #define DEFSPRI (LOG_KERN|LOG_CRIT)
105 #define TIMERINTVL 30 /* interval for checking flush, mark */
106 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
107 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
109 #include <sys/param.h>
110 #include <sys/ioctl.h>
111 #include <sys/mman.h>
112 #include <sys/queue.h>
113 #include <sys/resource.h>
114 #include <sys/socket.h>
115 #include <sys/stat.h>
116 #include <sys/syslimits.h>
117 #include <sys/time.h>
120 #include <sys/wait.h>
122 #if defined(INET) || defined(INET6)
123 #include <netinet/in.h>
124 #include <arpa/inet.h>
144 #include <sysexits.h>
149 #include "pathnames.h"
153 #include <sys/syslog.h>
155 static const char *ConfFile = _PATH_LOGCONF;
156 static const char *PidFile = _PATH_LOGPID;
157 static const char ctty[] = _PATH_CONSOLE;
158 static const char include_str[] = "include";
159 static const char include_ext[] = ".conf";
161 #define dprintf if (Debug) printf
163 #define MAXUNAMES 20 /* maximum number of user names */
165 #define sstosa(ss) ((struct sockaddr *)(ss))
167 #define sstosin(ss) ((struct sockaddr_in *)(void *)(ss))
168 #define satosin(sa) ((struct sockaddr_in *)(void *)(sa))
171 #define sstosin6(ss) ((struct sockaddr_in6 *)(void *)(ss))
172 #define satosin6(sa) ((struct sockaddr_in6 *)(void *)(sa))
173 #define s6_addr32 __u6_addr.__u6_addr32
174 #define IN6_ARE_MASKED_ADDR_EQUAL(d, a, m) ( \
175 (((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
176 (((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
177 (((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
178 (((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
181 * List of peers and sockets for binding.
187 STAILQ_ENTRY(peer) next;
189 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
192 struct addrinfo sl_ai;
193 #define sl_sa sl_ai.ai_addr
194 #define sl_salen sl_ai.ai_addrlen
195 #define sl_family sl_ai.ai_family
197 struct peer *sl_peer;
198 int (*sl_recv)(struct socklist *);
199 STAILQ_ENTRY(socklist) next;
201 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
207 #define IGN_CONS 0x001 /* don't print on console */
208 #define SYNC_FILE 0x002 /* do fsync on file after printing */
209 #define MARK 0x008 /* this message is a mark */
210 #define ISKERNEL 0x010 /* kernel generated message */
212 /* Timestamps of log entries. */
218 /* Traditional syslog timestamp format. */
219 #define RFC3164_DATELEN 15
220 #define RFC3164_DATEFMT "%b %e %H:%M:%S"
223 * This structure holds a property-based filter
228 #define PROP_TYPE_NOOP 0
229 #define PROP_TYPE_MSG 1
230 #define PROP_TYPE_HOSTNAME 2
231 #define PROP_TYPE_PROGNAME 3
234 #define PROP_CMP_CONTAINS 1
235 #define PROP_CMP_EQUAL 2
236 #define PROP_CMP_STARTS 3
237 #define PROP_CMP_REGEX 4
240 #define PROP_FLAG_EXCLUDE (1 << 0)
241 #define PROP_FLAG_ICASE (1 << 1)
247 #define pflt_strval pflt_uniptr.p_strval
248 #define pflt_re pflt_uniptr.p_re
254 * This structure represents the files that will have log
256 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
257 * or if f_type is F_PIPE and f_pid > 0.
261 STAILQ_ENTRY(filed) next; /* next in linked list */
262 short f_type; /* entry type, see below */
263 short f_file; /* file descriptor */
264 time_t f_time; /* time this was last written */
265 char *f_host; /* host from which to recd. */
266 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
267 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
271 char *f_program; /* program this applies to */
272 struct prop_filter *f_prop_filter; /* property-based filter */
274 char f_uname[MAXUNAMES][MAXLOGNAME];
276 char f_hname[MAXHOSTNAMELEN];
277 struct addrinfo *f_addr;
279 } f_forw; /* forwarding address */
280 char f_fname[MAXPATHLEN];
282 char f_pname[MAXPATHLEN];
286 #define fu_uname f_un.f_uname
287 #define fu_forw_hname f_un.f_forw.f_hname
288 #define fu_forw_addr f_un.f_forw.f_addr
289 #define fu_fname f_un.f_fname
290 #define fu_pipe_pname f_un.f_pipe.f_pname
291 #define fu_pipe_pid f_un.f_pipe.f_pid
292 char f_prevline[MAXSVLINE]; /* last message logged */
293 struct logtime f_lasttime; /* time of last occurrence */
294 int f_prevpri; /* pri of f_prevline */
295 size_t f_prevlen; /* length of f_prevline */
296 int f_prevcount; /* repetition cnt of prevline */
297 u_int f_repeatcount; /* number of "repeated" msgs */
298 int f_flags; /* file-specific flags */
299 #define FFLAG_SYNC 0x01
300 #define FFLAG_NEEDSYNC 0x02
304 * Queue of about-to-be dead processes we should watch out for.
309 TAILQ_ENTRY(deadq_entry) dq_entries;
311 static TAILQ_HEAD(, deadq_entry) deadq_head =
312 TAILQ_HEAD_INITIALIZER(deadq_head);
315 * The timeout to apply to processes waiting on the dead queue. Unit
316 * of measure is `mark intervals', i.e. 20 minutes by default.
317 * Processes on the dead queue will be terminated after that time.
320 #define DQ_TIMO_INIT 2
323 * Struct to hold records of network addresses that are allowed to log
331 struct sockaddr_storage addr;
332 struct sockaddr_storage mask;
336 #define a_addr u.numeric.addr
337 #define a_mask u.numeric.mask
338 #define a_name u.name
339 STAILQ_ENTRY(allowedpeer) next;
341 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
345 * Intervals at which we flush out "message repeated" messages,
346 * in seconds after previous message is logged. After each flush,
347 * we move to the next interval until we reach the largest.
349 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
350 #define MAXREPEAT (nitems(repeatinterval) - 1)
351 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
352 #define BACKOFF(f) do { \
353 if (++(f)->f_repeatcount > MAXREPEAT) \
354 (f)->f_repeatcount = MAXREPEAT; \
357 /* values for f_type */
358 #define F_UNUSED 0 /* unused entry */
359 #define F_FILE 1 /* regular file */
360 #define F_TTY 2 /* terminal */
361 #define F_CONSOLE 3 /* console terminal */
362 #define F_FORW 4 /* remote machine */
363 #define F_USERS 5 /* list of users */
364 #define F_WALL 6 /* everyone logged on */
365 #define F_PIPE 7 /* pipe to program */
367 static const char *TypeNames[] = {
368 "UNUSED", "FILE", "TTY", "CONSOLE",
369 "FORW", "USERS", "WALL", "PIPE"
372 static STAILQ_HEAD(, filed) fhead =
373 STAILQ_HEAD_INITIALIZER(fhead); /* Log files that we write to */
374 static struct filed consfile; /* Console */
376 static int Debug; /* debug flag */
377 static int Foreground = 0; /* Run in foreground, instead of daemonizing */
378 static int resolve = 1; /* resolve hostname */
379 static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
380 static const char *LocalDomain; /* our local domain name */
381 static int Initialized; /* set when we have initialized ourselves */
382 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
383 static int MarkSeq; /* mark sequence number */
384 static int NoBind; /* don't bind() as suggested by RFC 3164 */
385 static int SecureMode; /* when true, receive only unix domain socks */
387 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
389 static int family = PF_INET; /* protocol family (IPv4 only) */
391 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
392 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
393 static int use_bootfile; /* log entire bootfile for every kern msg */
394 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
395 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
397 static char bootfile[MAXLINE+1]; /* booted kernel file */
399 static int RemoteAddDate; /* Always set the date on remote messages */
400 static int RemoteHostname; /* Log remote hostname from the message */
402 static int UniquePriority; /* Only log specified priority? */
403 static int LogFacPri; /* Put facility and priority in log message: */
404 /* 0=no, 1=numeric, 2=names */
405 static int KeepKernFac; /* Keep remotely logged kernel facility */
406 static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
407 static struct pidfh *pfh;
408 static int sigpipe[2]; /* Pipe to catch a signal during select(). */
409 static bool RFC3164OutputFormat = true; /* Use legacy format by default. */
411 static volatile sig_atomic_t MarkSet, WantDie, WantInitialize, WantReapchild;
415 static int allowaddr(char *);
416 static int addfile(struct filed *);
417 static int addpeer(struct peer *);
418 static int addsock(struct addrinfo *, struct socklist *);
419 static struct filed *cfline(const char *, const char *, const char *,
421 static const char *cvthname(struct sockaddr *);
422 static void deadq_enter(pid_t, const char *);
423 static int deadq_remove(struct deadq_entry *);
424 static int deadq_removebypid(pid_t);
425 static int decode(const char *, const CODE *);
426 static void die(int) __dead2;
427 static void dodie(int);
428 static void dofsync(void);
429 static void domark(int);
430 static void fprintlog_first(struct filed *, const char *, const char *,
431 const char *, const char *, const char *, const char *, int);
432 static void fprintlog_write(struct filed *, struct iovlist *, int);
433 static void fprintlog_successive(struct filed *, int);
434 static void init(int);
435 static void logerror(const char *);
436 static void logmsg(int, const struct logtime *, const char *, const char *,
437 const char *, const char *, const char *, const char *, int);
438 static void log_deadchild(pid_t, int, const char *);
439 static void markit(void);
440 static int socksetup(struct peer *);
441 static int socklist_recv_file(struct socklist *);
442 static int socklist_recv_sock(struct socklist *);
443 static int socklist_recv_signal(struct socklist *);
444 static void sighandler(int);
445 static int skip_message(const char *, const char *, int);
446 static int evaluate_prop_filter(const struct prop_filter *filter,
448 static int prop_filter_compile(struct prop_filter *pfilter,
450 static void parsemsg(const char *, char *);
451 static void printsys(char *);
452 static int p_open(const char *, pid_t *);
453 static void reapchild(int);
454 static const char *ttymsg_check(struct iovec *, int, char *, int);
455 static void usage(void);
456 static int validate(struct sockaddr *, const char *);
457 static void unmapped(struct sockaddr *);
458 static void wallmsg(struct filed *, struct iovec *, const int iovlen);
459 static int waitdaemon(int);
460 static void timedout(int);
461 static void increase_rcvbuf(int);
464 close_filed(struct filed *f)
467 if (f == NULL || f->f_file == -1)
472 if (f->fu_forw_addr != NULL) {
473 freeaddrinfo(f->fu_forw_addr);
474 f->fu_forw_addr = NULL;
481 f->f_type = F_UNUSED;
487 (void)close(f->f_file);
492 addfile(struct filed *f0)
496 f = calloc(1, sizeof(*f));
498 err(1, "malloc failed");
500 STAILQ_INSERT_TAIL(&fhead, f, next);
506 addpeer(struct peer *pe0)
510 pe = calloc(1, sizeof(*pe));
512 err(1, "malloc failed");
514 STAILQ_INSERT_TAIL(&pqueue, pe, next);
520 addsock(struct addrinfo *ai, struct socklist *sl0)
524 /* Copy *ai->ai_addr to the tail of struct socklist if any. */
525 sl = calloc(1, sizeof(*sl) + ((ai != NULL) ? ai->ai_addrlen : 0));
527 err(1, "malloc failed");
530 memcpy(&sl->sl_ai, ai, sizeof(*ai));
531 if (ai->ai_addrlen > 0) {
532 memcpy((sl + 1), ai->ai_addr, ai->ai_addrlen);
533 sl->sl_sa = (struct sockaddr *)(sl + 1);
537 STAILQ_INSERT_TAIL(&shead, sl, next);
543 main(int argc, char *argv[])
545 int ch, i, s, fdsrmax = 0, bflag = 0, pflag = 0, Sflag = 0;
547 struct timeval tv, *tvp;
550 pid_t ppid = 1, spid;
553 if (madvise(NULL, 0, MADV_PROTECT) != 0)
554 dprintf("madvise() failed: %s\n", strerror(errno));
556 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:m:nNoO:p:P:sS:Tuv"))
575 case 'a': /* allow specific network addresses only */
576 if (allowaddr(optarg) == -1)
581 p = strchr(optarg, ']');
583 p = strchr(p + 1, ':');
585 p = strchr(optarg, ':');
586 if (p != NULL && strchr(p + 1, ':') != NULL)
587 p = NULL; /* backward compatibility */
590 /* A hostname or filename only. */
591 addpeer(&(struct peer){
596 /* The case of "name:service". */
598 addpeer(&(struct peer){
600 .pe_name = (strlen(optarg) == 0) ?
611 case 'd': /* debug */
614 case 'f': /* configuration file */
617 case 'F': /* run in foreground instead of daemon */
623 case 'k': /* keep remote kern fac */
636 else if (ch == 'p') {
640 mode = S_IRUSR | S_IWUSR;
643 if (optarg[0] == '/')
645 else if ((name = strchr(optarg, ':')) != NULL) {
648 errx(1, "socket name must be absolute "
650 if (isdigit(*optarg)) {
651 perml = strtol(optarg, &ep, 8);
652 if (*ep || perml < 0 ||
653 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
654 errx(1, "invalid mode %s, exiting",
656 mode = (mode_t )perml;
658 errx(1, "invalid mode %s, exiting",
661 errx(1, "invalid filename %s, exiting",
663 addpeer(&(struct peer){
669 case 'm': /* mark interval */
670 MarkInterval = atoi(optarg) * 60;
680 if (strcmp(optarg, "bsd") == 0 ||
681 strcmp(optarg, "rfc3164") == 0)
682 RFC3164OutputFormat = true;
683 else if (strcmp(optarg, "syslog") == 0 ||
684 strcmp(optarg, "rfc5424") == 0)
685 RFC3164OutputFormat = false;
692 case 'P': /* path for alt. PID */
695 case 's': /* no network mode */
701 case 'u': /* only log specified priority */
704 case 'v': /* log facility and priority */
710 if ((argc -= optind) != 0)
713 /* Pipe to catch a signal during select(). */
714 s = pipe2(sigpipe, O_CLOEXEC);
716 err(1, "cannot open a pipe for signals");
718 addsock(NULL, &(struct socklist){
719 .sl_socket = sigpipe[0],
720 .sl_recv = socklist_recv_signal
724 /* Listen by default: /dev/klog. */
725 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
727 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
729 addsock(NULL, &(struct socklist){
731 .sl_recv = socklist_recv_file,
734 /* Listen by default: *:514 if no -b flag. */
736 addpeer(&(struct peer){
739 /* Listen by default: /var/run/log if no -p flag. */
741 addpeer(&(struct peer){
742 .pe_name = _PATH_LOG,
743 .pe_mode = DEFFILEMODE,
745 /* Listen by default: /var/run/logpriv if no -S flag. */
747 addpeer(&(struct peer){
748 .pe_name = _PATH_LOG_PRIV,
749 .pe_mode = S_IRUSR | S_IWUSR,
751 STAILQ_FOREACH(pe, &pqueue, next)
754 pfh = pidfile_open(PidFile, 0600, &spid);
757 errx(1, "syslogd already running, pid: %d", spid);
758 warn("cannot open pid file");
761 if ((!Foreground) && (!Debug)) {
762 ppid = waitdaemon(30);
764 warn("could not become daemon");
771 consfile.f_type = F_CONSOLE;
772 (void)strlcpy(consfile.fu_fname, ctty + sizeof _PATH_DEV - 1,
773 sizeof(consfile.fu_fname));
774 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
775 (void)signal(SIGTERM, dodie);
776 (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
777 (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
778 (void)signal(SIGHUP, sighandler);
779 (void)signal(SIGCHLD, sighandler);
780 (void)signal(SIGALRM, domark);
781 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
782 (void)alarm(TIMERINTVL);
784 /* tuck my process id away */
787 dprintf("off & running....\n");
790 tv.tv_sec = tv.tv_usec = 0;
792 STAILQ_FOREACH(sl, &shead, next) {
793 if (sl->sl_socket > fdsrmax)
794 fdsrmax = sl->sl_socket;
796 fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
799 errx(1, "calloc fd_set");
802 if (Initialized == 0)
804 else if (WantInitialize)
805 init(WantInitialize);
807 reapchild(WantReapchild);
815 bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
818 STAILQ_FOREACH(sl, &shead, next) {
819 if (sl->sl_socket != -1 && sl->sl_recv != NULL)
820 FD_SET(sl->sl_socket, fdsr);
822 i = select(fdsrmax + 1, fdsr, NULL, NULL,
823 needdofsync ? &tv : tvp);
839 STAILQ_FOREACH(sl, &shead, next) {
840 if (FD_ISSET(sl->sl_socket, fdsr))
848 socklist_recv_signal(struct socklist *sl __unused)
853 if (ioctl(sigpipe[0], FIONREAD, &i) != 0) {
854 logerror("ioctl(FIONREAD)");
855 err(1, "signal pipe read failed");
857 nsig = i / sizeof(signo);
858 dprintf("# of received signals = %d\n", nsig);
859 for (i = 0; i < nsig; i++) {
860 len = read(sigpipe[0], &signo, sizeof(signo));
861 if (len != sizeof(signo)) {
862 logerror("signal pipe read failed");
863 err(1, "signal pipe read failed");
865 dprintf("Received signal: %d from fd=%d\n", signo,
880 socklist_recv_sock(struct socklist *sl)
882 struct sockaddr_storage ss;
883 struct sockaddr *sa = (struct sockaddr *)&ss;
886 char line[MAXLINE + 1];
890 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
891 dprintf("received sa_len = %d\n", sslen);
896 logerror("recvfrom");
899 /* Received valid data. */
901 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
902 hname = LocalHostName;
904 hname = cvthname(sa);
906 if (validate(sa, hname) == 0) {
907 dprintf("Message from %s was ignored.", hname);
911 parsemsg(hname, line);
917 unmapped(struct sockaddr *sa)
919 #if defined(INET) && defined(INET6)
920 struct sockaddr_in6 *sin6;
921 struct sockaddr_in sin;
924 sa->sa_family != AF_INET6 ||
925 sa->sa_len != sizeof(*sin6))
928 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
930 sin = (struct sockaddr_in){
931 .sin_family = AF_INET,
932 .sin_len = sizeof(sin),
933 .sin_port = sin6->sin6_port
935 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
936 sizeof(sin.sin_addr));
937 memcpy(sa, &sin, sizeof(sin));
949 "usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]\n"
950 " [-b bind_address] [-f config_file]\n"
951 " [-l [mode:]path] [-m mark_interval]\n"
952 " [-O format] [-P pid_file] [-p log_socket]\n"
953 " [-S logpriv_socket]\n");
958 * Removes characters from log messages that are unsafe to display.
959 * TODO: Permit UTF-8 strings that include a BOM per RFC 5424?
962 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen)
968 while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) {
969 if (mask_C1 && (c & 0x80) && c < 0xA0) {
974 if (isascii(c) && iscntrl(c)) {
977 } else if (c == '\t') {
991 * Parses a syslog message according to RFC 5424, assuming that PRI and
992 * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The
993 * parsed result is passed to logmsg().
996 parsemsg_rfc5424(const char *from, int pri, char *msg)
998 const struct logtime *timestamp;
999 struct logtime timestamp_remote;
1000 const char *omsg, *hostname, *app_name, *procid, *msgid,
1002 char line[MAXLINE + 1];
1004 #define FAIL_IF(field, expr) do { \
1006 dprintf("Failed to parse " field " from %s: %s\n", \
1011 #define PARSE_CHAR(field, sep) do { \
1012 FAIL_IF(field, *msg != sep); \
1015 #define IF_NOT_NILVALUE(var) \
1016 if (msg[0] == '-' && msg[1] == ' ') { \
1019 } else if (msg[0] == '-' && msg[1] == '\0') { \
1025 IF_NOT_NILVALUE(timestamp) {
1026 /* Parse RFC 3339-like timestamp. */
1027 #define PARSE_NUMBER(dest, length, min, max) do { \
1031 for (i = 0; i < length; ++i) { \
1032 FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9'); \
1033 v = v * 10 + *msg++ - '0'; \
1035 FAIL_IF("TIMESTAMP", v < min || v > max); \
1038 /* Date and time. */
1039 memset(×tamp_remote, 0, sizeof(timestamp_remote));
1040 PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999);
1041 timestamp_remote.tm.tm_year -= 1900;
1042 PARSE_CHAR("TIMESTAMP", '-');
1043 PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12);
1044 --timestamp_remote.tm.tm_mon;
1045 PARSE_CHAR("TIMESTAMP", '-');
1046 PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31);
1047 PARSE_CHAR("TIMESTAMP", 'T');
1048 PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23);
1049 PARSE_CHAR("TIMESTAMP", ':');
1050 PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59);
1051 PARSE_CHAR("TIMESTAMP", ':');
1052 PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59);
1053 /* Perform normalization. */
1054 timegm(×tamp_remote.tm);
1055 /* Optional: fractional seconds. */
1056 if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') {
1060 for (i = 100000; i != 0; i /= 10) {
1061 if (*msg < '0' || *msg > '9')
1063 timestamp_remote.usec += (*msg++ - '0') * i;
1071 int sign, tz_hour, tz_min;
1073 /* Local time zone offset. */
1074 FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+');
1075 sign = *msg++ == '-' ? -1 : 1;
1076 PARSE_NUMBER(tz_hour, 2, 0, 23);
1077 PARSE_CHAR("TIMESTAMP", ':');
1078 PARSE_NUMBER(tz_min, 2, 0, 59);
1079 timestamp_remote.tm.tm_gmtoff =
1080 sign * (tz_hour * 3600 + tz_min * 60);
1083 PARSE_CHAR("TIMESTAMP", ' ');
1084 timestamp = RemoteAddDate ? NULL : ×tamp_remote;
1087 /* String fields part of the HEADER. */
1088 #define PARSE_STRING(field, var) \
1089 IF_NOT_NILVALUE(var) { \
1091 while (*msg >= '!' && *msg <= '~') \
1093 FAIL_IF(field, var == msg); \
1094 PARSE_CHAR(field, ' '); \
1097 PARSE_STRING("HOSTNAME", hostname);
1098 if (hostname == NULL || !RemoteHostname)
1100 PARSE_STRING("APP-NAME", app_name);
1101 PARSE_STRING("PROCID", procid);
1102 PARSE_STRING("MSGID", msgid);
1105 /* Structured data. */
1106 #define PARSE_SD_NAME() do { \
1107 const char *start; \
1110 while (*msg >= '!' && *msg <= '~' && *msg != '=' && \
1111 *msg != ']' && *msg != '"') \
1113 FAIL_IF("STRUCTURED-NAME", start == msg); \
1115 IF_NOT_NILVALUE(structured_data) {
1117 while (*msg == '[') {
1122 while (*msg == ' ') {
1126 PARSE_CHAR("STRUCTURED-NAME", '=');
1127 PARSE_CHAR("STRUCTURED-NAME", '"');
1128 while (*msg != '"') {
1129 FAIL_IF("STRUCTURED-NAME",
1131 if (*msg++ == '\\') {
1132 FAIL_IF("STRUCTURED-NAME",
1139 PARSE_CHAR("STRUCTURED-NAME", ']');
1141 PARSE_CHAR("STRUCTURED-NAME", ' ');
1144 #undef PARSE_SD_NAME
1148 #undef IF_NOT_NILVALUE
1150 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1151 logmsg(pri, timestamp, hostname, app_name, procid, msgid,
1152 structured_data, line, 0);
1156 * Returns the length of the application name ("TAG" in RFC 3164
1157 * terminology) and process ID from a message if present.
1160 parsemsg_rfc3164_get_app_name_procid(const char *msg, size_t *app_name_length_p,
1161 ptrdiff_t *procid_begin_offset_p, size_t *procid_length_p)
1163 const char *m, *procid_begin;
1164 size_t app_name_length, procid_length;
1168 /* Application name. */
1169 app_name_length = strspn(m,
1170 "abcdefghijklmnopqrstuvwxyz"
1171 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1174 if (app_name_length == 0)
1176 m += app_name_length;
1178 /* Process identifier (optional). */
1181 procid_length = strspn(m, "0123456789");
1182 if (procid_length == 0)
1188 procid_begin = NULL;
1193 if (m[0] != ':' || m[1] != ' ')
1196 *app_name_length_p = app_name_length;
1197 if (procid_begin_offset_p != NULL)
1198 *procid_begin_offset_p =
1199 procid_begin == NULL ? 0 : procid_begin - msg;
1200 if (procid_length_p != NULL)
1201 *procid_length_p = procid_length;
1204 *app_name_length_p = 0;
1205 if (procid_begin_offset_p != NULL)
1206 *procid_begin_offset_p = 0;
1207 if (procid_length_p != NULL)
1208 *procid_length_p = 0;
1212 * Trims the application name ("TAG" in RFC 3164 terminology) and
1213 * process ID from a message if present.
1216 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name,
1217 const char **procid)
1219 char *m, *app_name_begin, *procid_begin;
1220 size_t app_name_length, procid_length;
1221 ptrdiff_t procid_begin_offset;
1226 parsemsg_rfc3164_get_app_name_procid(app_name_begin, &app_name_length,
1227 &procid_begin_offset, &procid_length);
1228 if (app_name_length == 0)
1230 procid_begin = procid_begin_offset == 0 ? NULL :
1231 app_name_begin + procid_begin_offset;
1233 /* Split strings from input. */
1234 app_name_begin[app_name_length] = '\0';
1235 m += app_name_length + 1;
1236 if (procid_begin != NULL) {
1237 procid_begin[procid_length] = '\0';
1238 m += procid_length + 2;
1242 *app_name = app_name_begin;
1243 *procid = procid_begin;
1251 * Parses a syslog message according to RFC 3164, assuming that PRI
1252 * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed
1253 * result is passed to logmsg().
1256 parsemsg_rfc3164(const char *from, int pri, char *msg)
1258 struct tm tm_parsed;
1259 const struct logtime *timestamp;
1260 struct logtime timestamp_remote;
1261 const char *app_name, *procid;
1263 char line[MAXLINE + 1];
1266 * Parse the TIMESTAMP provided by the remote side. If none is
1267 * found, assume this is not an RFC 3164 formatted message,
1268 * only containing a TAG and a MSG.
1271 if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) ==
1272 msg + RFC3164_DATELEN && msg[RFC3164_DATELEN] == ' ') {
1273 msg += RFC3164_DATELEN + 1;
1274 if (!RemoteAddDate) {
1280 * As the timestamp does not contain the year
1281 * number, daylight saving time information, nor
1282 * a time zone, attempt to infer it. Due to
1283 * clock skews, the timestamp may even be part
1284 * of the next year. Use the last year for which
1285 * the timestamp is at most one week in the
1288 * This loop can only run for at most three
1289 * iterations before terminating.
1292 localtime_r(&t_now, &tm_now);
1293 for (year = tm_now.tm_year + 1;; --year) {
1294 assert(year >= tm_now.tm_year - 1);
1295 timestamp_remote.tm = tm_parsed;
1296 timestamp_remote.tm.tm_year = year;
1297 timestamp_remote.tm.tm_isdst = -1;
1298 timestamp_remote.usec = 0;
1299 if (mktime(×tamp_remote.tm) <
1300 t_now + 7 * 24 * 60 * 60)
1303 timestamp = ×tamp_remote;
1307 * A single space character MUST also follow the HOSTNAME field.
1309 msglen = strlen(msg);
1310 for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
1311 if (msg[i] == ' ') {
1312 if (RemoteHostname) {
1320 * Support non RFC compliant messages, without hostname.
1325 if (i == MIN(MAXHOSTNAMELEN, msglen)) {
1326 dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
1331 /* Remove the TAG, if present. */
1332 parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid);
1333 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1334 logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0);
1338 * Takes a raw input line, extracts PRI and determines whether the
1339 * message is formatted according to RFC 3164 or RFC 5424. Continues
1340 * parsing of addition fields in the message according to those
1341 * standards and prints the message on the appropriate log files.
1344 parsemsg(const char *from, char *msg)
1352 if (msg[0] != '<' || !isdigit(msg[1])) {
1353 dprintf("Invalid PRI from %s\n", from);
1356 for (i = 2; i <= 4; i++) {
1359 if (!isdigit(msg[i])) {
1360 dprintf("Invalid PRI header from %s\n", from);
1364 if (msg[i] != '>') {
1365 dprintf("Invalid PRI header from %s\n", from);
1369 n = strtol(msg + 1, &q, 10);
1370 if (errno != 0 || *q != msg[i] || n < 0 || n >= INT_MAX) {
1371 dprintf("Invalid PRI %ld from %s: %s\n",
1372 n, from, strerror(errno));
1376 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1380 * Don't allow users to log kernel messages.
1381 * NOTE: since LOG_KERN == 0 this will also match
1382 * messages with no facility specified.
1384 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
1385 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1387 /* Parse VERSION. */
1389 if (msg[0] == '1' && msg[1] == ' ')
1390 parsemsg_rfc5424(from, pri, msg + 2);
1392 parsemsg_rfc3164(from, pri, msg);
1396 * Read /dev/klog while data are available, split into lines.
1399 socklist_recv_file(struct socklist *sl)
1401 char *p, *q, line[MAXLINE + 1];
1406 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
1408 line[i + len] = '\0';
1410 if (i < 0 && errno != EINTR && errno != EAGAIN) {
1412 close(sl->sl_socket);
1418 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
1423 if (len >= MAXLINE - 1) {
1428 memmove(line, p, len + 1);
1437 * Take a raw input line from /dev/klog, format similar to syslog().
1444 int flags, isprintf, pri;
1446 flags = ISKERNEL | SYNC_FILE; /* fsync after write */
1452 n = strtol(p + 1, &q, 10);
1453 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1460 * Kernel printf's and LOG_CONSOLE messages have been displayed
1461 * on the console already.
1463 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1465 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1467 logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags);
1473 * Match a program or host name against a specification.
1474 * Return a non-0 value if the message must be ignored
1475 * based on the specification.
1478 skip_message(const char *name, const char *spec, int checkcase)
1483 /* Behaviour on explicit match */
1498 s = strstr (spec, name);
1500 s = strcasestr (spec, name);
1503 prev = (s == spec ? ',' : *(s - 1));
1504 next = *(s + strlen (name));
1506 if (prev == ',' && (next == '\0' || next == ','))
1507 /* Explicit match: skip iff the spec is an
1512 /* No explicit match for this name: skip the message iff
1513 the spec is an inclusive one. */
1518 * Match some property of the message against a filter.
1519 * Return a non-0 value if the message must be ignored
1520 * based on the filter.
1523 evaluate_prop_filter(const struct prop_filter *filter, const char *value)
1525 const char *s = NULL;
1526 const int exclude = ((filter->cmp_flags & PROP_FLAG_EXCLUDE) > 0);
1532 if (filter->cmp_type == PROP_CMP_REGEX) {
1533 if (regexec(filter->pflt_re, value, 0, NULL, 0) == 0)
1539 valuelen = strlen(value);
1541 /* a shortcut for equal with different length is always false */
1542 if (filter->cmp_type == PROP_CMP_EQUAL &&
1543 valuelen != filter->pflt_strlen)
1546 if (filter->cmp_flags & PROP_FLAG_ICASE)
1547 s = strcasestr(value, filter->pflt_strval);
1549 s = strstr(value, filter->pflt_strval);
1552 * PROP_CMP_CONTAINS true if s
1553 * PROP_CMP_STARTS true if s && s == value
1554 * PROP_CMP_EQUAL true if s && s == value &&
1555 * valuelen == filter->pflt_strlen
1556 * (and length match is checked
1560 switch (filter->cmp_type) {
1561 case PROP_CMP_STARTS:
1562 case PROP_CMP_EQUAL:
1566 case PROP_CMP_CONTAINS:
1573 /* unknown cmp_type */
1581 * Logs a message to the appropriate log files, users, etc. based on the
1582 * priority. Log messages are always formatted according to RFC 3164,
1583 * even if they were in RFC 5424 format originally, The MSGID and
1584 * STRUCTURED-DATA fields are thus discarded for the time being.
1587 logmsg(int pri, const struct logtime *timestamp, const char *hostname,
1588 const char *app_name, const char *procid, const char *msgid,
1589 const char *structured_data, const char *msg, int flags)
1592 struct logtime timestamp_now;
1596 char saved[MAXSVLINE], kernel_app_name[100];
1598 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1599 pri, flags, hostname, msg);
1601 (void)gettimeofday(&tv, NULL);
1603 if (timestamp == NULL) {
1604 localtime_r(&now, ×tamp_now.tm);
1605 timestamp_now.usec = tv.tv_usec;
1606 timestamp = ×tamp_now;
1609 /* extract facility and priority level */
1611 fac = LOG_NFACILITIES;
1615 /* Check maximum facility number. */
1616 if (fac > LOG_NFACILITIES)
1619 prilev = LOG_PRI(pri);
1622 * Lookup kernel app name from log prefix if present.
1623 * This is only used for local program specification matching.
1625 if (flags & ISKERNEL) {
1626 size_t kernel_app_name_length;
1628 parsemsg_rfc3164_get_app_name_procid(msg,
1629 &kernel_app_name_length, NULL, NULL);
1630 if (kernel_app_name_length != 0) {
1631 strlcpy(kernel_app_name, msg,
1632 MIN(sizeof(kernel_app_name),
1633 kernel_app_name_length + 1));
1635 kernel_app_name[0] = '\0';
1638 /* log the message to the particular outputs */
1642 * Open in non-blocking mode to avoid hangs during open
1643 * and close(waiting for the port to drain).
1645 f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1647 if (f->f_file >= 0) {
1648 f->f_lasttime = *timestamp;
1649 fprintlog_first(f, hostname, app_name, procid, msgid,
1650 structured_data, msg, flags);
1658 * Store all of the fields of the message, except the timestamp,
1659 * in a single string. This string is used to detect duplicate
1662 assert(hostname != NULL);
1663 assert(msg != NULL);
1664 savedlen = snprintf(saved, sizeof(saved),
1665 "%d %s %s %s %s %s %s", pri, hostname,
1666 app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid,
1667 msgid == NULL ? "-" : msgid,
1668 structured_data == NULL ? "-" : structured_data, msg);
1670 STAILQ_FOREACH(f, &fhead, next) {
1671 /* skip messages that are incorrect priority */
1672 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1673 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1674 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1676 || f->f_pmask[fac] == INTERNAL_NOPRI)
1679 /* skip messages with the incorrect hostname */
1680 if (skip_message(hostname, f->f_host, 0))
1683 /* skip messages with the incorrect program name */
1684 if (flags & ISKERNEL && kernel_app_name[0] != '\0') {
1685 if (skip_message(kernel_app_name, f->f_program, 1))
1687 } else if (skip_message(app_name == NULL ? "" : app_name,
1691 /* skip messages if a property does not match filter */
1692 if (f->f_prop_filter != NULL &&
1693 f->f_prop_filter->prop_type != PROP_TYPE_NOOP) {
1694 switch (f->f_prop_filter->prop_type) {
1696 if (evaluate_prop_filter(f->f_prop_filter,
1700 case PROP_TYPE_HOSTNAME:
1701 if (evaluate_prop_filter(f->f_prop_filter,
1705 case PROP_TYPE_PROGNAME:
1706 if (evaluate_prop_filter(f->f_prop_filter,
1707 app_name == NULL ? "" : app_name))
1715 /* skip message to console if it has already been printed */
1716 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1719 /* don't output marks to recently written files */
1720 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1724 * suppress duplicate lines to this file
1726 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1727 (flags & MARK) == 0 && savedlen == f->f_prevlen &&
1728 strcmp(saved, f->f_prevline) == 0) {
1729 f->f_lasttime = *timestamp;
1731 dprintf("msg repeated %d times, %ld sec of %d\n",
1732 f->f_prevcount, (long)(now - f->f_time),
1733 repeatinterval[f->f_repeatcount]);
1735 * If domark would have logged this by now,
1736 * flush it now (so we don't hold isolated messages),
1737 * but back off so we'll flush less often
1740 if (now > REPEATTIME(f)) {
1741 fprintlog_successive(f, flags);
1745 /* new line, save it */
1747 fprintlog_successive(f, 0);
1748 f->f_repeatcount = 0;
1750 f->f_lasttime = *timestamp;
1751 static_assert(sizeof(f->f_prevline) == sizeof(saved),
1752 "Space to store saved line incorrect");
1753 (void)strcpy(f->f_prevline, saved);
1754 f->f_prevlen = savedlen;
1755 fprintlog_first(f, hostname, app_name, procid, msgid,
1756 structured_data, msg, flags);
1766 STAILQ_FOREACH(f, &fhead, next) {
1767 if ((f->f_type == F_FILE) &&
1768 (f->f_flags & FFLAG_NEEDSYNC)) {
1769 f->f_flags &= ~FFLAG_NEEDSYNC;
1770 (void)fsync(f->f_file);
1776 * List of iovecs to which entries can be appended.
1777 * Used for constructing the message to be logged.
1780 struct iovec iov[TTYMSG_IOV_MAX];
1786 iovlist_init(struct iovlist *il)
1794 iovlist_append(struct iovlist *il, const char *str)
1798 /* Discard components if we've run out of iovecs. */
1799 if (il->iovcnt < nitems(il->iov)) {
1801 il->iov[il->iovcnt++] = (struct iovec){
1802 .iov_base = __DECONST(char *, str),
1805 il->totalsize += size;
1809 #if defined(INET) || defined(INET6)
1811 iovlist_truncate(struct iovlist *il, size_t size)
1816 while (il->totalsize > size) {
1817 diff = il->totalsize - size;
1818 last = &il->iov[il->iovcnt - 1];
1819 if (diff >= last->iov_len) {
1820 /* Remove the last iovec entirely. */
1822 il->totalsize -= last->iov_len;
1824 /* Remove the last iovec partially. */
1825 last->iov_len -= diff;
1826 il->totalsize -= diff;
1833 fprintlog_write(struct filed *f, struct iovlist *il, int flags)
1835 struct msghdr msghdr;
1837 struct socklist *sl;
1841 switch (f->f_type) {
1843 /* Truncate messages to RFC 5426 recommended size. */
1844 dprintf(" %s", f->fu_forw_hname);
1845 switch (f->fu_forw_addr->ai_family) {
1849 ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1850 iovlist_truncate(il, 480);
1856 ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1857 iovlist_truncate(il, 1180);
1865 for (r = f->fu_forw_addr; r; r = r->ai_next) {
1866 memset(&msghdr, 0, sizeof(msghdr));
1867 msghdr.msg_name = r->ai_addr;
1868 msghdr.msg_namelen = r->ai_addrlen;
1869 msghdr.msg_iov = il->iov;
1870 msghdr.msg_iovlen = il->iovcnt;
1871 STAILQ_FOREACH(sl, &shead, next) {
1872 if (sl->sl_socket < 0)
1874 if (sl->sl_sa == NULL ||
1875 sl->sl_family == AF_UNSPEC ||
1876 sl->sl_family == AF_LOCAL)
1878 lsent = sendmsg(sl->sl_socket, &msghdr, 0);
1879 if (lsent == (ssize_t)il->totalsize)
1882 if (lsent == (ssize_t)il->totalsize && !send_to_all)
1885 dprintf("lsent/totalsize: %zd/%zu\n", lsent, il->totalsize);
1886 if (lsent != (ssize_t)il->totalsize) {
1900 /* case ENOTSOCK: */
1902 /* case EMSGSIZE: */
1905 /* case ECONNREFUSED: */
1907 dprintf("removing entry: errno=%d\n", e);
1908 f->f_type = F_UNUSED;
1915 dprintf(" %s\n", f->fu_fname);
1916 iovlist_append(il, "\n");
1917 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1919 * If writev(2) fails for potentially transient errors
1920 * like the filesystem being full, ignore it.
1921 * Otherwise remove this logfile from the list.
1923 if (errno != ENOSPC) {
1927 logerror(f->fu_fname);
1929 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1930 f->f_flags |= FFLAG_NEEDSYNC;
1936 dprintf(" %s\n", f->fu_pipe_pname);
1937 iovlist_append(il, "\n");
1938 if (f->fu_pipe_pid == 0) {
1939 if ((f->f_file = p_open(f->fu_pipe_pname,
1940 &f->fu_pipe_pid)) < 0) {
1941 logerror(f->fu_pipe_pname);
1945 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1948 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1951 logerror(f->fu_pipe_pname);
1956 if (flags & IGN_CONS) {
1957 dprintf(" (ignored)\n");
1963 dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1964 iovlist_append(il, "\r\n");
1965 errno = 0; /* ttymsg() only sometimes returns an errno */
1966 if ((msgret = ttymsg(il->iov, il->iovcnt, f->fu_fname, 10))) {
1967 f->f_type = F_UNUSED;
1975 iovlist_append(il, "\r\n");
1976 wallmsg(f, il->iov, il->iovcnt);
1982 fprintlog_rfc5424(struct filed *f, const char *hostname, const char *app_name,
1983 const char *procid, const char *msgid, const char *structured_data,
1984 const char *msg, int flags)
1989 char timebuf[33], priority_number[5];
1992 if (f->f_type == F_WALL)
1993 iovlist_append(&il, "\r\n\aMessage from syslogd ...\r\n");
1994 iovlist_append(&il, "<");
1995 snprintf(priority_number, sizeof(priority_number), "%d", f->f_prevpri);
1996 iovlist_append(&il, priority_number);
1997 iovlist_append(&il, ">1 ");
1998 if (strftime(timebuf, sizeof(timebuf), "%FT%T.______%z",
1999 &f->f_lasttime.tm) == sizeof(timebuf) - 2) {
2000 /* Add colon to the time zone offset, which %z doesn't do. */
2002 timebuf[31] = timebuf[30];
2003 timebuf[30] = timebuf[29];
2006 /* Overwrite space for microseconds with actual value. */
2007 usec = f->f_lasttime.usec;
2008 for (i = 25; i >= 20; --i) {
2009 timebuf[i] = usec % 10 + '0';
2012 iovlist_append(&il, timebuf);
2014 iovlist_append(&il, "-");
2015 iovlist_append(&il, " ");
2016 iovlist_append(&il, hostname);
2017 iovlist_append(&il, " ");
2018 iovlist_append(&il, app_name == NULL ? "-" : app_name);
2019 iovlist_append(&il, " ");
2020 iovlist_append(&il, procid == NULL ? "-" : procid);
2021 iovlist_append(&il, " ");
2022 iovlist_append(&il, msgid == NULL ? "-" : msgid);
2023 iovlist_append(&il, " ");
2024 iovlist_append(&il, structured_data == NULL ? "-" : structured_data);
2025 iovlist_append(&il, " ");
2026 iovlist_append(&il, msg);
2028 fprintlog_write(f, &il, flags);
2032 fprintlog_rfc3164(struct filed *f, const char *hostname, const char *app_name,
2033 const char *procid, const char *msg, int flags)
2037 int facility, priority;
2038 char timebuf[RFC3164_DATELEN + 1], facility_number[5],
2040 bool facility_found, priority_found;
2042 if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT,
2043 &f->f_lasttime.tm) == 0)
2047 switch (f->f_type) {
2049 /* Message forwarded over the network. */
2050 iovlist_append(&il, "<");
2051 snprintf(priority_number, sizeof(priority_number), "%d",
2053 iovlist_append(&il, priority_number);
2054 iovlist_append(&il, ">");
2055 iovlist_append(&il, timebuf);
2056 if (strcasecmp(hostname, LocalHostName) != 0) {
2057 iovlist_append(&il, " Forwarded from ");
2058 iovlist_append(&il, hostname);
2059 iovlist_append(&il, ":");
2061 iovlist_append(&il, " ");
2065 /* Message written to terminals. */
2066 iovlist_append(&il, "\r\n\aMessage from syslogd@");
2067 iovlist_append(&il, hostname);
2068 iovlist_append(&il, " at ");
2069 iovlist_append(&il, timebuf);
2070 iovlist_append(&il, " ...\r\n");
2074 /* Message written to files. */
2075 iovlist_append(&il, timebuf);
2076 iovlist_append(&il, " ");
2079 iovlist_append(&il, "<");
2081 facility = f->f_prevpri & LOG_FACMASK;
2082 facility_found = false;
2083 if (LogFacPri > 1) {
2084 for (c = facilitynames; c->c_name; c++) {
2085 if (c->c_val == facility) {
2086 iovlist_append(&il, c->c_name);
2087 facility_found = true;
2092 if (!facility_found) {
2093 snprintf(facility_number,
2094 sizeof(facility_number), "%d",
2096 iovlist_append(&il, facility_number);
2099 iovlist_append(&il, ".");
2101 priority = LOG_PRI(f->f_prevpri);
2102 priority_found = false;
2103 if (LogFacPri > 1) {
2104 for (c = prioritynames; c->c_name; c++) {
2105 if (c->c_val == priority) {
2106 iovlist_append(&il, c->c_name);
2107 priority_found = true;
2112 if (!priority_found) {
2113 snprintf(priority_number,
2114 sizeof(priority_number), "%d", priority);
2115 iovlist_append(&il, priority_number);
2118 iovlist_append(&il, "> ");
2121 iovlist_append(&il, hostname);
2122 iovlist_append(&il, " ");
2126 /* Message body with application name and process ID prefixed. */
2127 if (app_name != NULL) {
2128 iovlist_append(&il, app_name);
2129 if (procid != NULL) {
2130 iovlist_append(&il, "[");
2131 iovlist_append(&il, procid);
2132 iovlist_append(&il, "]");
2134 iovlist_append(&il, ": ");
2136 iovlist_append(&il, msg);
2138 fprintlog_write(f, &il, flags);
2142 fprintlog_first(struct filed *f, const char *hostname, const char *app_name,
2143 const char *procid, const char *msgid __unused,
2144 const char *structured_data __unused, const char *msg, int flags)
2147 dprintf("Logging to %s", TypeNames[f->f_type]);
2150 if (f->f_type == F_UNUSED) {
2155 if (RFC3164OutputFormat)
2156 fprintlog_rfc3164(f, hostname, app_name, procid, msg, flags);
2158 fprintlog_rfc5424(f, hostname, app_name, procid, msgid,
2159 structured_data, msg, flags);
2163 * Prints a message to a log file that the previously logged message was
2164 * received multiple times.
2167 fprintlog_successive(struct filed *f, int flags)
2171 assert(f->f_prevcount > 0);
2172 snprintf(msg, sizeof(msg), "last message repeated %d times",
2174 fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg,
2179 * WALLMSG -- Write a message to the world at large
2181 * Write the specified message to either the entire
2182 * world, or a list of approved users.
2185 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
2187 static int reenter; /* avoid calling ourselves */
2196 while ((ut = getutxent()) != NULL) {
2197 if (ut->ut_type != USER_PROCESS)
2199 if (f->f_type == F_WALL) {
2200 if ((p = ttymsg(iov, iovlen, ut->ut_line,
2201 TTYMSGTIME)) != NULL) {
2202 errno = 0; /* already in msg */
2207 /* should we send the message to this user? */
2208 for (i = 0; i < MAXUNAMES; i++) {
2209 if (!f->fu_uname[i][0])
2211 if (!strcmp(f->fu_uname[i], ut->ut_user)) {
2212 if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
2213 TTYMSGTIME)) != NULL) {
2214 errno = 0; /* already in msg */
2226 * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
2229 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
2231 static char device[1024];
2232 static char errbuf[1024];
2235 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
2237 if (stat(device, &sb) < 0) {
2238 (void) snprintf(errbuf, sizeof(errbuf),
2239 "%s: %s", device, strerror(errno));
2242 if ((sb.st_mode & S_IWGRP) == 0)
2243 /* Messages disabled. */
2245 return ttymsg(iov, iovcnt, line, tmout);
2249 reapchild(int signo __unused)
2255 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
2256 /* First, look if it's a process from the dead queue. */
2257 if (deadq_removebypid(pid))
2260 /* Now, look in list of active processes. */
2261 STAILQ_FOREACH(f, &fhead, next) {
2262 if (f->f_type == F_PIPE &&
2263 f->fu_pipe_pid == pid) {
2265 log_deadchild(pid, status, f->fu_pipe_pname);
2274 * Return a printable representation of a host address.
2277 cvthname(struct sockaddr *f)
2280 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
2282 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
2283 error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
2286 dprintf("Malformed from address %s\n", gai_strerror(error));
2289 dprintf("cvthname(%s)\n", ip);
2294 error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
2295 NULL, 0, NI_NAMEREQD);
2297 dprintf("Host name for your address (%s) unknown\n", ip);
2301 if (hl > 0 && hname[hl-1] == '.')
2303 /* RFC 5424 prefers logging FQDNs. */
2304 if (RFC3164OutputFormat)
2305 trimdomain(hname, hl);
2317 domark(int signo __unused)
2324 * Print syslogd errors some place.
2327 logerror(const char *msg)
2330 static int recursed = 0;
2332 /* If there's an error while trying to log an error, give up. */
2337 (void)snprintf(buf, sizeof(buf), "%s: %s", msg,
2342 dprintf("%s\n", buf);
2343 logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL,
2352 struct socklist *sl;
2355 STAILQ_FOREACH(f, &fhead, next) {
2356 /* flush any pending output */
2358 fprintlog_successive(f, 0);
2359 if (f->f_type == F_PIPE && f->fu_pipe_pid > 0)
2363 dprintf("syslogd: exiting on signal %d\n", signo);
2364 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
2368 STAILQ_FOREACH(sl, &shead, next) {
2369 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
2370 unlink(sl->sl_peer->pe_name);
2372 pidfile_remove(pfh);
2378 configfiles(const struct dirent *dp)
2383 if (dp->d_name[0] == '.')
2386 ext_len = sizeof(include_ext) -1;
2388 if (dp->d_namlen <= ext_len)
2391 p = &dp->d_name[dp->d_namlen - ext_len];
2392 if (strcmp(p, include_ext) != 0)
2399 readconfigfile(FILE *cf, int allow_includes)
2403 struct dirent **ent;
2404 char cline[LINE_MAX];
2405 char host[MAXHOSTNAMELEN];
2406 char prog[LINE_MAX];
2407 char file[MAXPATHLEN];
2408 char pfilter[LINE_MAX];
2414 * Foreach line in the conf table, open that file.
2416 include_len = sizeof(include_str) -1;
2417 (void)strlcpy(host, "*", sizeof(host));
2418 (void)strlcpy(prog, "*", sizeof(prog));
2419 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2420 while (fgets(cline, sizeof(cline), cf) != NULL) {
2422 * check for end-of-section, comments, strip off trailing
2423 * spaces and newline character. #!prog is treated specially:
2424 * following lines apply only to that program.
2426 for (p = cline; isspace(*p); ++p)
2430 if (allow_includes &&
2431 strncmp(p, include_str, include_len) == 0 &&
2432 isspace(p[include_len])) {
2437 while (*tmp != '\0' && !isspace(*tmp))
2440 dprintf("Trying to include files in '%s'\n", p);
2441 nents = scandir(p, &ent, configfiles, alphasort);
2443 dprintf("Unable to open '%s': %s\n", p,
2447 for (i = 0; i < nents; i++) {
2448 if (snprintf(file, sizeof(file), "%s/%s", p,
2449 ent[i]->d_name) >= (int)sizeof(file)) {
2450 dprintf("ignoring path too long: "
2451 "'%s/%s'\n", p, ent[i]->d_name);
2456 cf2 = fopen(file, "r");
2459 dprintf("reading %s\n", file);
2460 readconfigfile(cf2, 0);
2468 if (*p == '\0' || strchr("!+-:", *p) == NULL)
2471 if (*p == '+' || *p == '-') {
2475 if ((!*p) || (*p == '*')) {
2476 (void)strlcpy(host, "*", sizeof(host));
2481 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
2482 if (!isalnum(*p) && *p != '.' && *p != '-'
2483 && *p != ',' && *p != ':' && *p != '%')
2492 while (isspace(*p)) p++;
2493 if ((!*p) || (*p == '*')) {
2494 (void)strlcpy(prog, "*", sizeof(prog));
2497 for (i = 0; i < LINE_MAX - 1; i++) {
2498 if (!isprint(p[i]) || isspace(p[i]))
2509 if ((!*p) || (*p == '*')) {
2510 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2513 (void)strlcpy(pfilter, p, sizeof(pfilter));
2516 for (p = cline + 1; *p != '\0'; p++) {
2519 if (*(p - 1) == '\\') {
2527 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
2529 f = cfline(cline, prog, host, pfilter);
2537 sighandler(int signo)
2540 /* Send an wake-up signal to the select() loop. */
2541 write(sigpipe[1], &signo, sizeof(signo));
2545 * INIT -- Initialize syslogd from configuration table
2554 char oldLocalHostName[MAXHOSTNAMELEN];
2555 char hostMsg[2*MAXHOSTNAMELEN+40];
2556 char bootfileMsg[LINE_MAX];
2562 * Load hostname (may have changed).
2565 (void)strlcpy(oldLocalHostName, LocalHostName,
2566 sizeof(oldLocalHostName));
2567 if (gethostname(LocalHostName, sizeof(LocalHostName)))
2568 err(EX_OSERR, "gethostname() failed");
2569 if ((p = strchr(LocalHostName, '.')) != NULL) {
2570 /* RFC 5424 prefers logging FQDNs. */
2571 if (RFC3164OutputFormat)
2573 LocalDomain = p + 1;
2579 * Load / reload timezone data (in case it changed).
2581 * Just calling tzset() again does not work, the timezone code
2582 * caches the result. However, by setting the TZ variable, one
2583 * can defeat the caching and have the timezone code really
2584 * reload the timezone data. Respect any initial setting of
2585 * TZ, in case the system is configured specially.
2587 dprintf("loading timezone data via tzset()\n");
2591 setenv("TZ", ":/etc/localtime", 1);
2597 * Close all open log files.
2600 STAILQ_FOREACH(f, &fhead, next) {
2601 /* flush any pending output */
2603 fprintlog_successive(f, 0);
2605 switch (f->f_type) {
2613 deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
2618 while(!STAILQ_EMPTY(&fhead)) {
2619 f = STAILQ_FIRST(&fhead);
2620 STAILQ_REMOVE_HEAD(&fhead, next);
2623 if (f->f_prop_filter) {
2624 switch (f->f_prop_filter->cmp_type) {
2625 case PROP_CMP_REGEX:
2626 regfree(f->f_prop_filter->pflt_re);
2627 free(f->f_prop_filter->pflt_re);
2629 case PROP_CMP_CONTAINS:
2630 case PROP_CMP_EQUAL:
2631 case PROP_CMP_STARTS:
2632 free(f->f_prop_filter->pflt_strval);
2635 free(f->f_prop_filter);
2640 /* open the configuration file */
2641 if ((cf = fopen(ConfFile, "r")) == NULL) {
2642 dprintf("cannot open %s\n", ConfFile);
2643 f = cfline("*.ERR\t/dev/console", "*", "*", "*");
2647 f = cfline("*.PANIC\t*", "*", "*", "*");
2656 readconfigfile(cf, 1);
2658 /* close the configuration file */
2665 STAILQ_FOREACH(f, &fhead, next) {
2666 for (i = 0; i <= LOG_NFACILITIES; i++)
2667 if (f->f_pmask[i] == INTERNAL_NOPRI)
2670 printf("%d ", f->f_pmask[i]);
2671 printf("%s: ", TypeNames[f->f_type]);
2672 switch (f->f_type) {
2674 printf("%s", f->fu_fname);
2679 printf("%s%s", _PATH_DEV, f->fu_fname);
2683 switch (f->fu_forw_addr->ai_family) {
2686 port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
2691 port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
2699 f->fu_forw_hname, port);
2701 printf("%s", f->fu_forw_hname);
2706 printf("%s", f->fu_pipe_pname);
2710 for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
2711 printf("%s, ", f->fu_uname[i]);
2715 printf(" (%s)", f->f_program);
2720 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL,
2721 NULL, NULL, "restart", 0);
2722 dprintf("syslogd: restarted\n");
2724 * Log a change in hostname, but only on a restart.
2726 if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
2727 (void)snprintf(hostMsg, sizeof(hostMsg),
2728 "hostname changed, \"%s\" to \"%s\"",
2729 oldLocalHostName, LocalHostName);
2730 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd",
2731 NULL, NULL, NULL, hostMsg, 0);
2732 dprintf("%s\n", hostMsg);
2735 * Log the kernel boot file if we aren't going to use it as
2736 * the prefix, and if this is *not* a restart.
2738 if (signo == 0 && !use_bootfile) {
2739 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2740 "kernel boot file is %s", bootfile);
2741 logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd",
2742 NULL, NULL, NULL, bootfileMsg, 0);
2743 dprintf("%s\n", bootfileMsg);
2748 * Compile property-based filter.
2749 * Returns 0 on success, -1 otherwise.
2752 prop_filter_compile(struct prop_filter *pfilter, char *filter)
2754 char *filter_endpos, *p;
2755 char **ap, *argv[2] = {NULL, NULL};
2756 int re_flags = REG_NOSUB;
2759 bzero(pfilter, sizeof(struct prop_filter));
2762 * Here's some filter examples mentioned in syslog.conf(5)
2763 * 'msg, contains, ".*Deny.*"'
2764 * 'programname, regex, "^bird6?$"'
2765 * 'hostname, icase_ereregex, "^server-(dcA|podB)-rack1[0-9]{2}\\..*"'
2769 * Split filter into 3 parts: property name (argv[0]),
2770 * cmp type (argv[1]) and lvalue for comparison (filter).
2772 for (ap = argv; (*ap = strsep(&filter, ", \t\n")) != NULL;) {
2774 if (++ap >= &argv[2])
2778 if (argv[0] == NULL || argv[1] == NULL) {
2779 logerror("filter parse error");
2783 /* fill in prop_type */
2784 if (strcasecmp(argv[0], "msg") == 0)
2785 pfilter->prop_type = PROP_TYPE_MSG;
2786 else if(strcasecmp(argv[0], "hostname") == 0)
2787 pfilter->prop_type = PROP_TYPE_HOSTNAME;
2788 else if(strcasecmp(argv[0], "source") == 0)
2789 pfilter->prop_type = PROP_TYPE_HOSTNAME;
2790 else if(strcasecmp(argv[0], "programname") == 0)
2791 pfilter->prop_type = PROP_TYPE_PROGNAME;
2793 logerror("unknown property");
2797 /* full in cmp_flags (i.e. !contains, icase_regex, etc.) */
2798 if (*argv[1] == '!') {
2799 pfilter->cmp_flags |= PROP_FLAG_EXCLUDE;
2802 if (strncasecmp(argv[1], "icase_", (sizeof("icase_") - 1)) == 0) {
2803 pfilter->cmp_flags |= PROP_FLAG_ICASE;
2804 argv[1] += sizeof("icase_") - 1;
2807 /* fill in cmp_type */
2808 if (strcasecmp(argv[1], "contains") == 0)
2809 pfilter->cmp_type = PROP_CMP_CONTAINS;
2810 else if (strcasecmp(argv[1], "isequal") == 0)
2811 pfilter->cmp_type = PROP_CMP_EQUAL;
2812 else if (strcasecmp(argv[1], "startswith") == 0)
2813 pfilter->cmp_type = PROP_CMP_STARTS;
2814 else if (strcasecmp(argv[1], "regex") == 0)
2815 pfilter->cmp_type = PROP_CMP_REGEX;
2816 else if (strcasecmp(argv[1], "ereregex") == 0) {
2817 pfilter->cmp_type = PROP_CMP_REGEX;
2818 re_flags |= REG_EXTENDED;
2820 logerror("unknown cmp function");
2825 * Handle filter value
2829 /* remove leading whitespace and check for '"' next character */
2830 filter += strspn(filter, ", \t\n");
2831 if (*filter != '"' || strlen(filter) < 3) {
2832 logerror("property value parse error");
2838 /* process possible backslash (\") escaping */
2840 filter_endpos = filter;
2841 for (p = filter; *p != '\0'; p++) {
2842 if (*p == '\\' && !escaped) {
2844 /* do not shift filter_endpos */
2847 if (*p == '"' && !escaped) {
2851 /* we've seen some esc symbols, need to compress the line */
2852 if (filter_endpos != p)
2853 *filter_endpos = *p;
2859 *filter_endpos = '\0';
2862 /* We should not have anything but whitespace left after closing '"' */
2863 if (*p != '\0' && strspn(p, " \t\n") != strlen(p)) {
2864 logerror("property value parse error");
2868 if (pfilter->cmp_type == PROP_CMP_REGEX) {
2869 pfilter->pflt_re = calloc(1, sizeof(*pfilter->pflt_re));
2870 if (pfilter->pflt_re == NULL) {
2871 logerror("RE calloc() error");
2872 free(pfilter->pflt_re);
2875 if (pfilter->cmp_flags & PROP_FLAG_ICASE)
2876 re_flags |= REG_ICASE;
2877 if (regcomp(pfilter->pflt_re, filter, re_flags) != 0) {
2878 logerror("RE compilation error");
2879 free(pfilter->pflt_re);
2883 pfilter->pflt_strval = strdup(filter);
2884 pfilter->pflt_strlen = strlen(filter);
2892 * Crack a configuration file line
2894 static struct filed *
2895 cfline(const char *line, const char *prog, const char *host,
2896 const char *pfilter)
2899 struct addrinfo hints, *res;
2900 int error, i, pri, syncfile;
2902 char *bp, *pfilter_dup;
2903 char buf[MAXLINE], ebuf[100];
2905 dprintf("cfline(\"%s\", f, \"%s\", \"%s\", \"%s\")\n", line, prog,
2908 f = calloc(1, sizeof(*f));
2913 errno = 0; /* keep strerror() stuff out of logerror messages */
2915 for (i = 0; i <= LOG_NFACILITIES; i++)
2916 f->f_pmask[i] = INTERNAL_NOPRI;
2918 /* save hostname if any */
2919 if (host && *host == '*')
2924 f->f_host = strdup(host);
2925 if (f->f_host == NULL) {
2929 hl = strlen(f->f_host);
2930 if (hl > 0 && f->f_host[hl-1] == '.')
2931 f->f_host[--hl] = '\0';
2932 /* RFC 5424 prefers logging FQDNs. */
2933 if (RFC3164OutputFormat)
2934 trimdomain(f->f_host, hl);
2937 /* save program name if any */
2938 if (prog && *prog == '*')
2941 f->f_program = strdup(prog);
2942 if (f->f_program == NULL) {
2949 f->f_prop_filter = calloc(1, sizeof(*(f->f_prop_filter)));
2950 if (f->f_prop_filter == NULL) {
2951 logerror("pfilter calloc");
2954 if (*pfilter == '*')
2955 f->f_prop_filter->prop_type = PROP_TYPE_NOOP;
2957 pfilter_dup = strdup(pfilter);
2958 if (pfilter_dup == NULL) {
2962 if (prop_filter_compile(f->f_prop_filter, pfilter_dup)) {
2963 logerror("filter compile error");
2969 /* scan through the list of selectors */
2970 for (p = line; *p && *p != '\t' && *p != ' ';) {
2975 /* find the end of this facility name list */
2976 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2979 /* get the priority comparison */
3007 /* collect priority name */
3008 for (bp = buf; *q && !strchr("\t,; ", *q); )
3013 while (strchr(",;", *q))
3016 /* decode priority name */
3019 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
3021 /* Ignore trailing spaces. */
3022 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
3025 pri = decode(buf, prioritynames);
3028 (void)snprintf(ebuf, sizeof ebuf,
3029 "unknown priority name \"%s\"", buf);
3036 pri_cmp = (UniquePriority)
3041 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
3043 /* scan facilities */
3044 while (*p && !strchr("\t.; ", *p)) {
3045 for (bp = buf; *p && !strchr("\t,;. ", *p); )
3050 for (i = 0; i < LOG_NFACILITIES; i++) {
3051 f->f_pmask[i] = pri;
3052 f->f_pcmp[i] = pri_cmp;
3055 i = decode(buf, facilitynames);
3058 (void)snprintf(ebuf, sizeof ebuf,
3059 "unknown facility name \"%s\"",
3065 f->f_pmask[i >> 3] = pri;
3066 f->f_pcmp[i >> 3] = pri_cmp;
3068 while (*p == ',' || *p == ' ')
3075 /* skip to action part */
3076 while (*p == '\t' || *p == ' ')
3091 * scan forward to see if there is a port defined.
3092 * so we can't use strlcpy..
3094 i = sizeof(f->fu_forw_hname);
3095 tp = f->fu_forw_hname;
3099 * an ipv6 address should start with a '[' in that case
3100 * we should scan for a ']'
3106 while (*p && (*p != endkey) && (i-- > 0)) {
3109 if (endkey == ']' && *p == endkey)
3113 /* See if we copied a domain and have a port */
3119 hints = (struct addrinfo){
3120 .ai_family = family,
3121 .ai_socktype = SOCK_DGRAM
3123 error = getaddrinfo(f->fu_forw_hname,
3124 p ? p : "syslog", &hints, &res);
3126 logerror(gai_strerror(error));
3129 f->fu_forw_addr = res;
3134 if ((f->f_file = open(p, logflags, 0600)) < 0) {
3135 f->f_type = F_UNUSED;
3140 f->f_flags |= FFLAG_SYNC;
3141 if (isatty(f->f_file)) {
3142 if (strcmp(p, ctty) == 0)
3143 f->f_type = F_CONSOLE;
3146 (void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
3147 sizeof(f->fu_fname));
3149 (void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
3156 (void)strlcpy(f->fu_pipe_pname, p + 1,
3157 sizeof(f->fu_pipe_pname));
3166 for (i = 0; i < MAXUNAMES && *p; i++) {
3167 for (q = p; *q && *q != ','; )
3169 (void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
3170 if ((q - p) >= MAXLOGNAME)
3171 f->fu_uname[i][MAXLOGNAME - 1] = '\0';
3173 f->fu_uname[i][q - p] = '\0';
3174 while (*q == ',' || *q == ' ')
3178 f->f_type = F_USERS;
3186 * Decode a symbolic name to a numeric value
3189 decode(const char *name, const CODE *codetab)
3195 return (atoi(name));
3197 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3199 *p = tolower(*name);
3204 for (c = codetab; c->c_name; c++)
3205 if (!strcmp(buf, c->c_name))
3215 struct deadq_entry *dq, *dq0;
3217 now = time((time_t *)NULL);
3218 MarkSeq += TIMERINTVL;
3219 if (MarkSeq >= MarkInterval) {
3220 logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL,
3221 "-- MARK --", MARK);
3225 STAILQ_FOREACH(f, &fhead, next) {
3226 if (f->f_prevcount && now >= REPEATTIME(f)) {
3227 dprintf("flush %s: repeated %d times, %d sec.\n",
3228 TypeNames[f->f_type], f->f_prevcount,
3229 repeatinterval[f->f_repeatcount]);
3230 fprintlog_successive(f, 0);
3235 /* Walk the dead queue, and see if we should signal somebody. */
3236 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
3237 switch (dq->dq_timeout) {
3239 /* Already signalled once, try harder now. */
3240 if (kill(dq->dq_pid, SIGKILL) != 0)
3241 (void)deadq_remove(dq);
3246 * Timed out on dead queue, send terminate
3247 * signal. Note that we leave the removal
3248 * from the dead queue to reapchild(), which
3249 * will also log the event (unless the process
3250 * didn't even really exist, in case we simply
3251 * drop it from the dead queue).
3253 if (kill(dq->dq_pid, SIGTERM) != 0)
3254 (void)deadq_remove(dq);
3263 (void)alarm(TIMERINTVL);
3267 * fork off and become a daemon, but wait for the child to come online
3268 * before returning to the parent, or we get disk thrashing at boot etc.
3269 * Set a timer so we don't hang forever if it wedges.
3272 waitdaemon(int maxwait)
3276 pid_t pid, childpid;
3278 switch (childpid = fork()) {
3284 signal(SIGALRM, timedout);
3286 while ((pid = wait3(&status, 0, NULL)) != -1) {
3287 if (WIFEXITED(status))
3288 errx(1, "child pid %d exited with return code %d",
3289 pid, WEXITSTATUS(status));
3290 if (WIFSIGNALED(status))
3291 errx(1, "child pid %d exited on signal %d%s",
3292 pid, WTERMSIG(status),
3293 WCOREDUMP(status) ? " (core dumped)" :
3295 if (pid == childpid) /* it's gone... */
3305 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
3306 (void)dup2(fd, STDIN_FILENO);
3307 (void)dup2(fd, STDOUT_FILENO);
3308 (void)dup2(fd, STDERR_FILENO);
3309 if (fd > STDERR_FILENO)
3316 * We get a SIGALRM from the child when it's running and finished doing it's
3317 * fsync()'s or O_SYNC writes for all the boot messages.
3319 * We also get a signal from the kernel if the timer expires, so check to
3320 * see what happened.
3323 timedout(int sig __unused)
3327 signal(SIGALRM, SIG_DFL);
3329 errx(1, "timed out waiting for child");
3335 * Add `s' to the list of allowable peer addresses to accept messages
3338 * `s' is a string in the form:
3340 * [*]domainname[:{servicename|portnumber|*}]
3344 * netaddr/maskbits[:{servicename|portnumber|*}]
3346 * Returns -1 on error, 0 if the argument was valid.
3349 #if defined(INET) || defined(INET6)
3352 allowaddr(char *s __unused)
3355 #if defined(INET) || defined(INET6)
3357 struct allowedpeer *ap;
3360 struct addrinfo hints, *res = NULL;
3362 in_addr_t *addrp, *maskp;
3365 uint32_t *addr6p, *mask6p;
3367 char ip[NI_MAXHOST];
3369 ap = calloc(1, sizeof(*ap));
3371 err(1, "malloc failed");
3374 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
3377 if ((cp1 = strrchr(cp1, ':'))) {
3378 /* service/port provided */
3380 if (strlen(cp1) == 1 && *cp1 == '*')
3381 /* any port allowed */
3383 else if ((se = getservbyname(cp1, "udp"))) {
3384 ap->port = ntohs(se->s_port);
3386 ap->port = strtol(cp1, &cp2, 0);
3387 /* port not numeric */
3392 if ((se = getservbyname("syslog", "udp")))
3393 ap->port = ntohs(se->s_port);
3395 /* sanity, should not happen */
3399 if ((cp1 = strchr(s, '/')) != NULL &&
3400 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
3402 if ((masklen = atoi(cp1 + 1)) < 0)
3407 cp2 = s + strlen(s) - 1;
3418 hints = (struct addrinfo){
3419 .ai_family = PF_UNSPEC,
3420 .ai_socktype = SOCK_DGRAM,
3421 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3423 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
3425 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
3426 ap->a_mask = (struct sockaddr_storage){
3427 .ss_family = res->ai_family,
3428 .ss_len = res->ai_addrlen
3430 switch (res->ai_family) {
3433 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
3434 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
3436 /* use default netmask */
3437 if (IN_CLASSA(ntohl(*addrp)))
3438 *maskp = htonl(IN_CLASSA_NET);
3439 else if (IN_CLASSB(ntohl(*addrp)))
3440 *maskp = htonl(IN_CLASSB_NET);
3442 *maskp = htonl(IN_CLASSC_NET);
3443 } else if (masklen == 0) {
3445 } else if (masklen <= 32) {
3446 /* convert masklen to netmask */
3447 *maskp = htonl(~((1 << (32 - masklen)) - 1));
3451 /* Lose any host bits in the network number. */
3462 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
3463 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
3464 /* convert masklen to netmask */
3465 while (masklen > 0) {
3468 htonl(~(0xffffffff >> masklen));
3472 *mask6p++ = 0xffffffff;
3484 /* arg `s' is domain name */
3496 STAILQ_INSERT_TAIL(&aphead, ap, next);
3499 printf("allowaddr: rule ");
3500 if (ap->isnumeric) {
3501 printf("numeric, ");
3502 getnameinfo(sstosa(&ap->a_addr),
3503 (sstosa(&ap->a_addr))->sa_len,
3504 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3505 printf("addr = %s, ", ip);
3506 getnameinfo(sstosa(&ap->a_mask),
3507 (sstosa(&ap->a_mask))->sa_len,
3508 ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3509 printf("mask = %s; ", ip);
3511 printf("domainname = %s; ", ap->a_name);
3513 printf("port = %d\n", ap->port);
3526 * Validate that the remote peer has permission to log to us.
3529 validate(struct sockaddr *sa, const char *hname)
3532 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
3533 struct allowedpeer *ap;
3535 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
3538 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
3540 struct addrinfo hints, *res;
3544 STAILQ_FOREACH(ap, &aphead, next) {
3547 dprintf("# of validation rule: %d\n", num);
3549 /* traditional behaviour, allow everything */
3552 (void)strlcpy(name, hname, sizeof(name));
3553 hints = (struct addrinfo){
3554 .ai_family = PF_UNSPEC,
3555 .ai_socktype = SOCK_DGRAM,
3556 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3558 if (getaddrinfo(name, NULL, &hints, &res) == 0)
3560 else if (strchr(name, '.') == NULL) {
3561 strlcat(name, ".", sizeof name);
3562 strlcat(name, LocalDomain, sizeof name);
3564 if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
3565 NI_NUMERICHOST | NI_NUMERICSERV) != 0)
3566 return (0); /* for safety, should not occur */
3567 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
3571 /* now, walk down the list */
3573 STAILQ_FOREACH(ap, &aphead, next) {
3575 if (ap->port != 0 && ap->port != sport) {
3576 dprintf("rejected in rule %d due to port mismatch.\n",
3581 if (ap->isnumeric) {
3582 if (ap->a_addr.ss_family != sa->sa_family) {
3583 dprintf("rejected in rule %d due to address family mismatch.\n", i);
3587 else if (ap->a_addr.ss_family == AF_INET) {
3589 a4p = satosin(&ap->a_addr);
3590 m4p = satosin(&ap->a_mask);
3591 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
3592 != a4p->sin_addr.s_addr) {
3593 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3599 else if (ap->a_addr.ss_family == AF_INET6) {
3600 sin6 = satosin6(sa);
3601 a6p = satosin6(&ap->a_addr);
3602 m6p = satosin6(&ap->a_mask);
3603 if (a6p->sin6_scope_id != 0 &&
3604 sin6->sin6_scope_id != a6p->sin6_scope_id) {
3605 dprintf("rejected in rule %d due to scope mismatch.\n", i);
3608 if (!IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
3609 &a6p->sin6_addr, &m6p->sin6_addr)) {
3610 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3618 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
3620 dprintf("rejected in rule %d due to name "
3625 dprintf("accepted in rule %d.\n", i);
3626 return (1); /* hooray! */
3632 * Fairly similar to popen(3), but returns an open descriptor, as
3633 * opposed to a FILE *.
3636 p_open(const char *prog, pid_t *rpid)
3638 int pfd[2], nulldesc;
3640 char *argv[4]; /* sh -c cmd NULL */
3643 if (pipe(pfd) == -1)
3645 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
3646 /* we are royally screwed anyway */
3649 switch ((pid = fork())) {
3655 (void)setsid(); /* Avoid catching SIGHUPs. */
3656 argv[0] = strdup("sh");
3657 argv[1] = strdup("-c");
3658 argv[2] = strdup(prog);
3660 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
3667 /* Restore signals marked as SIG_IGN. */
3668 (void)signal(SIGINT, SIG_DFL);
3669 (void)signal(SIGQUIT, SIG_DFL);
3670 (void)signal(SIGPIPE, SIG_DFL);
3672 dup2(pfd[0], STDIN_FILENO);
3673 dup2(nulldesc, STDOUT_FILENO);
3674 dup2(nulldesc, STDERR_FILENO);
3675 closefrom(STDERR_FILENO + 1);
3677 (void)execvp(_PATH_BSHELL, argv);
3683 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
3684 * supposed to get an EWOULDBLOCK on writev(2), which is
3685 * caught by the logic above anyway, which will in turn close
3686 * the pipe, and fork a new logging subprocess if necessary.
3687 * The stale subprocess will be killed some time later unless
3688 * it terminated itself due to closing its input pipe (so we
3689 * get rid of really dead puppies).
3691 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
3693 (void)snprintf(errmsg, sizeof errmsg,
3694 "Warning: cannot change pipe to PID %d to "
3695 "non-blocking behaviour.",
3704 deadq_enter(pid_t pid, const char *name)
3706 struct deadq_entry *dq;
3712 * Be paranoid, if we can't signal the process, don't enter it
3713 * into the dead queue (perhaps it's already dead). If possible,
3714 * we try to fetch and log the child's status.
3716 if (kill(pid, 0) != 0) {
3717 if (waitpid(pid, &status, WNOHANG) > 0)
3718 log_deadchild(pid, status, name);
3722 dq = malloc(sizeof(*dq));
3727 *dq = (struct deadq_entry){
3729 .dq_timeout = DQ_TIMO_INIT
3731 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
3735 deadq_remove(struct deadq_entry *dq)
3738 TAILQ_REMOVE(&deadq_head, dq, dq_entries);
3747 deadq_removebypid(pid_t pid)
3749 struct deadq_entry *dq;
3751 TAILQ_FOREACH(dq, &deadq_head, dq_entries) {
3752 if (dq->dq_pid == pid)
3755 return (deadq_remove(dq));
3759 log_deadchild(pid_t pid, int status, const char *name)
3765 errno = 0; /* Keep strerror() stuff out of logerror messages. */
3766 if (WIFSIGNALED(status)) {
3767 reason = "due to signal";
3768 code = WTERMSIG(status);
3770 reason = "with status";
3771 code = WEXITSTATUS(status);
3775 (void)snprintf(buf, sizeof buf,
3776 "Logging subprocess %d (%s) exited %s %d.",
3777 pid, name, reason, code);
3782 socksetup(struct peer *pe)
3784 struct addrinfo hints, *res, *res0;
3787 int (*sl_recv)(struct socklist *);
3789 * We have to handle this case for backwards compatibility:
3790 * If there are two (or more) colons but no '[' and ']',
3791 * assume this is an inet6 address without a service.
3793 if (pe->pe_name != NULL) {
3795 if (pe->pe_name[0] == '[' &&
3796 (cp = strchr(pe->pe_name + 1, ']')) != NULL) {
3797 pe->pe_name = &pe->pe_name[1];
3799 if (cp[1] == ':' && cp[2] != '\0')
3800 pe->pe_serv = cp + 2;
3803 cp = strchr(pe->pe_name, ':');
3804 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
3807 pe->pe_serv = cp + 1;
3808 if (cp == pe->pe_name)
3815 hints = (struct addrinfo){
3816 .ai_family = AF_UNSPEC,
3817 .ai_socktype = SOCK_DGRAM,
3818 .ai_flags = AI_PASSIVE
3820 if (pe->pe_name != NULL)
3821 dprintf("Trying peer: %s\n", pe->pe_name);
3822 if (pe->pe_serv == NULL)
3823 pe->pe_serv = "syslog";
3824 error = getaddrinfo(pe->pe_name, pe->pe_serv, &hints, &res0);
3828 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
3829 pe->pe_name == NULL ? "" : pe->pe_name, pe->pe_serv,
3830 gai_strerror(error));
3833 logerror(gai_strerror(error));
3839 for (res = res0; res != NULL; res = res->ai_next) {
3842 if (res->ai_family != AF_LOCAL &&
3844 /* Only AF_LOCAL in secure mode. */
3847 if (family != AF_UNSPEC &&
3848 res->ai_family != AF_LOCAL && res->ai_family != family)
3851 s = socket(res->ai_family, res->ai_socktype,
3859 if (res->ai_family == AF_INET6) {
3860 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
3861 &(int){1}, sizeof(int)) < 0) {
3862 logerror("setsockopt(IPV6_V6ONLY)");
3869 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
3870 &(int){1}, sizeof(int)) < 0) {
3871 logerror("setsockopt(SO_REUSEADDR)");
3878 * Bind INET and UNIX-domain sockets.
3880 * A UNIX-domain socket is always bound to a pathname
3881 * regardless of -N flag.
3883 * For INET sockets, RFC 3164 recommends that client
3884 * side message should come from the privileged syslogd port.
3886 * If the system administrator chooses not to obey
3887 * this, we can skip the bind() step so that the
3888 * system will choose a port for us.
3890 if (res->ai_family == AF_LOCAL)
3891 unlink(pe->pe_name);
3892 if (res->ai_family == AF_LOCAL ||
3893 NoBind == 0 || pe->pe_name != NULL) {
3894 if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
3900 if (res->ai_family == AF_LOCAL ||
3904 if (res->ai_family == AF_LOCAL &&
3905 chmod(pe->pe_name, pe->pe_mode) < 0) {
3906 dprintf("chmod %s: %s\n", pe->pe_name,
3912 dprintf("new socket fd is %d\n", s);
3913 if (res->ai_socktype != SOCK_DGRAM) {
3916 sl_recv = socklist_recv_sock;
3917 #if defined(INET) || defined(INET6)
3918 if (SecureMode && (res->ai_family == AF_INET ||
3919 res->ai_family == AF_INET6)) {
3920 dprintf("shutdown\n");
3921 /* Forbid communication in secure mode. */
3922 if (shutdown(s, SHUT_RD) < 0 &&
3923 errno != ENOTCONN) {
3924 logerror("shutdown");
3931 dprintf("listening on socket\n");
3932 dprintf("sending on socket\n");
3933 addsock(res, &(struct socklist){
3945 increase_rcvbuf(int fd)
3949 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3950 &(socklen_t){sizeof(len)}) == 0) {
3951 if (len < RCVBUF_MINSIZE) {
3952 len = RCVBUF_MINSIZE;
3953 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));