1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1983, 1988, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
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.
18 *
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
29 * SUCH DAMAGE.
30 */
31 /*-
32 * SPDX-License-Identifier: BSD-2-Clause
33 *
34 * Copyright (c) 2018 Prodrive Technologies, https://prodrive-technologies.com/
35 * Author: Ed Schouten <ed@FreeBSD.org>
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
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.
45 *
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
56 * SUCH DAMAGE.
57 */
58
59 /*
60 * syslogd -- log system messages
61 *
62 * This program implements a system log. It takes a series of lines.
63 * Each line may have a priority, signified as "<n>" as
64 * the first characters of the line. If this is
65 * not present, a default priority is used.
66 *
67 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
68 * cause it to reread its configuration file.
69 *
70 * Author: Eric Allman
71 * extensive changes by Ralph Campbell
72 * more extensive changes by Eric Allman (again)
73 * Extension to log by program name as well as facility and priority
74 * by Peter da Silva.
75 * -u and -v by Harlan Stenn.
76 * Priority comparison code by Harlan Stenn.
77 */
78
79 #define DEFUPRI (LOG_USER|LOG_NOTICE)
80 #define DEFSPRI (LOG_KERN|LOG_CRIT)
81 #define TIMERINTVL 30 /* interval for checking flush, mark */
82 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
83 #define RCVBUF_MINSIZE (80 * 1024) /* minimum size of dgram rcv buffer */
84
85 #include <sys/param.h>
86 #include <sys/event.h>
87 #include <sys/ioctl.h>
88 #include <sys/mman.h>
89 #include <sys/procdesc.h>
90 #include <sys/queue.h>
91 #include <sys/resource.h>
92 #include <sys/socket.h>
93 #include <sys/stat.h>
94 #include <sys/syslimits.h>
95 #include <sys/time.h>
96 #include <sys/uio.h>
97 #include <sys/un.h>
98 #include <sys/wait.h>
99
100 #if defined(INET) || defined(INET6)
101 #include <netinet/in.h>
102 #include <arpa/inet.h>
103 #endif
104
105 #include <assert.h>
106 #include <ctype.h>
107 #include <dirent.h>
108 #include <err.h>
109 #include <errno.h>
110 #include <fcntl.h>
111 #include <fnmatch.h>
112 #include <libgen.h>
113 #include <libutil.h>
114 #include <limits.h>
115 #include <netdb.h>
116 #include <paths.h>
117 #include <poll.h>
118 #include <regex.h>
119 #include <signal.h>
120 #include <stdbool.h>
121 #include <stddef.h>
122 #include <stdio.h>
123 #include <stdlib.h>
124 #include <string.h>
125 #include <sysexits.h>
126 #include <unistd.h>
127 #include <utmpx.h>
128
129 #include "pathnames.h"
130 #include "syslogd.h"
131 #include "syslogd_cap.h"
132
133 const char *ConfFile = _PATH_LOGCONF;
134 static const char *PidFile = _PATH_LOGPID;
135 static const char include_str[] = "include";
136 static const char include_ext[] = ".conf";
137
138 #define dprintf if (Debug) printf
139
140 #define sstosa(ss) ((struct sockaddr *)(ss))
141 #ifdef INET
142 #define sstosin(ss) ((struct sockaddr_in *)(void *)(ss))
143 #define satosin(sa) ((struct sockaddr_in *)(void *)(sa))
144 #endif
145 #ifdef INET6
146 #define sstosin6(ss) ((struct sockaddr_in6 *)(void *)(ss))
147 #define satosin6(sa) ((struct sockaddr_in6 *)(void *)(sa))
148 #define s6_addr32 __u6_addr.__u6_addr32
149 #define IN6_ARE_MASKED_ADDR_EQUAL(d, a, m) ( \
150 (((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
151 (((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
152 (((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
153 (((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
154 #endif
155
156 /*
157 * List of peers and sockets that can't be bound until
158 * flags have been parsed.
159 */
160 struct peer {
161 const char *pe_name;
162 const char *pe_serv;
163 mode_t pe_mode;
164 STAILQ_ENTRY(peer) next;
165 };
166 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
167
168 /*
169 * Sockets used for logging; monitored by kevent().
170 */
171 struct socklist {
172 struct addrinfo sl_ai;
173 #define sl_sa sl_ai.ai_addr
174 #define sl_salen sl_ai.ai_addrlen
175 #define sl_family sl_ai.ai_family
176 int sl_socket;
177 char *sl_name;
178 int sl_dirfd;
179 int (*sl_recv)(struct socklist *);
180 STAILQ_ENTRY(socklist) next;
181 };
182 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
183
184 /*
185 * Flags to logmsg().
186 */
187
188 #define IGN_CONS 0x001 /* don't print on console */
189 #define SYNC_FILE 0x002 /* do fsync on file after printing */
190 #define MARK 0x008 /* this message is a mark */
191 #define ISKERNEL 0x010 /* kernel generated message */
192
193 /* Traditional syslog timestamp format. */
194 #define RFC3164_DATELEN 15
195 #define RFC3164_DATEFMT "%b %e %H:%M:%S"
196
197 /*
198 * FORMAT_BSD_LEGACY and FORMAT_RFC3164_STRICT are two variations of
199 * the RFC 3164 logging format.
200 */
201 #define IS_RFC3164_FORMAT (output_format == FORMAT_BSD_LEGACY || \
202 output_format == FORMAT_RFC3164_STRICT)
203
204 static STAILQ_HEAD(, filed) fhead =
205 STAILQ_HEAD_INITIALIZER(fhead); /* Log files that we write to */
206 static struct filed consfile; /* Console */
207
208 /*
209 * Queue of about-to-be dead processes we should watch out for.
210 */
211 struct deadq_entry {
212 int dq_procdesc;
213 int dq_timeout;
214 TAILQ_ENTRY(deadq_entry) dq_entries;
215 };
216 static TAILQ_HEAD(, deadq_entry) deadq_head =
217 TAILQ_HEAD_INITIALIZER(deadq_head);
218
219 /*
220 * The timeout to apply to processes waiting on the dead queue. Unit
221 * of measure is `mark intervals', i.e. 20 minutes by default.
222 * Processes on the dead queue will be terminated after that time.
223 */
224
225 #define DQ_TIMO_INIT 2
226
227 /*
228 * Network addresses that are allowed to log to us.
229 */
230 struct allowedpeer {
231 bool isnumeric;
232 u_short port;
233 union {
234 struct {
235 struct sockaddr_storage addr;
236 struct sockaddr_storage mask;
237 } numeric;
238 char *name;
239 } u;
240 #define a_addr u.numeric.addr
241 #define a_mask u.numeric.mask
242 #define a_name u.name
243 STAILQ_ENTRY(allowedpeer) next;
244 };
245 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
246
247 /*
248 * Intervals at which we flush out "message repeated" messages,
249 * in seconds after previous message is logged. After each flush,
250 * we move to the next interval until we reach the largest.
251 */
252 static int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
253 #define MAXREPEAT (nitems(repeatinterval) - 1)
254 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
255 #define BACKOFF(f) do { \
256 if (++(f)->f_repeatcount > MAXREPEAT) \
257 (f)->f_repeatcount = MAXREPEAT; \
258 } while (0)
259
260 static const char *TypeNames[] = {
261 "UNUSED",
262 "FILE",
263 "TTY",
264 "CONSOLE",
265 "FORW",
266 "USERS",
267 "WALL",
268 "PIPE",
269 };
270
271 static const int sigcatch[] = {
272 SIGHUP,
273 SIGINT,
274 SIGQUIT,
275 SIGPIPE,
276 SIGALRM,
277 SIGTERM,
278 SIGCHLD,
279 };
280
281 /*
282 * Communication channels between syslogd and libcasper
283 * services. These channels are used to request external
284 * resources while in capability mode.
285 */
286 #ifdef WITH_CASPER
287 static cap_channel_t *cap_syslogd;
288 static cap_channel_t *cap_net;
289 #endif
290
291 static int nulldesc; /* /dev/null descriptor */
292 static bool Debug; /* debug flag */
293 static bool Foreground = false; /* Run in foreground, instead of daemonizing */
294 static bool resolve = true; /* resolve hostname */
295 char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
296 static const char *LocalDomain; /* our local domain name */
297 static bool Initialized; /* set when we have initialized ourselves */
298 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
299 static int MarkSeq; /* mark sequence number */
300 static bool NoBind; /* don't bind() as suggested by RFC 3164 */
301 static int SecureMode; /* when true, receive only unix domain socks */
302 static int MaxForwardLen = 1024; /* max length of forwared message */
303 #ifdef INET6
304 static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
305 #else
306 static int family = PF_INET; /* protocol family (IPv4 only) */
307 #endif
308 static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
309 static int send_to_all; /* send message to all IPv4/IPv6 addresses */
310 static int use_bootfile; /* log entire bootfile for every kern msg */
311 static int no_compress; /* don't compress messages (1=pipes, 2=all) */
312 static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
313
314 static char bootfile[MAXPATHLEN]; /* booted kernel file */
315
316 static bool RemoteAddDate; /* Always set the date on remote messages */
317 static bool RemoteHostname; /* Log remote hostname from the message */
318
319 static bool UniquePriority; /* Only log specified priority? */
320 static int LogFacPri; /* Put facility and priority in log message: */
321 /* 0=no, 1=numeric, 2=names */
322 static bool KeepKernFac; /* Keep remotely logged kernel facility */
323 static bool needdofsync = true; /* Are any file(s) waiting to be fsynced? */
324 static struct pidfh *pfh;
325 static enum {
326 FORMAT_BSD_LEGACY, /* default, RFC 3164 with legacy deviations */
327 FORMAT_RFC3164_STRICT, /* compliant to RFC 3164 recommendataions */
328 FORMAT_RFC5424, /* RFC 5424 format */
329 } output_format = FORMAT_BSD_LEGACY;
330 static int kq; /* kqueue(2) descriptor. */
331
332 struct iovlist;
333
334 static bool allowaddr(char *);
335 static void addpeer(const char *, const char *, mode_t);
336 static void addsock(const char *, const char *, mode_t);
337 static void cfline(nvlist_t *, const char *, const char *, const char *,
338 const char *);
339 static const char *cvthname(struct sockaddr *);
340 static struct deadq_entry *deadq_enter(int);
341 static void deadq_remove(struct deadq_entry *);
342 static int decode(const char *, const CODE *);
343 static void die(int) __dead2;
344 static void dofsync(void);
345 static void fprintlog_first(struct filed *, const char *, const char *,
346 const char *, const char *, const char *, const char *, int);
347 static void fprintlog_write(struct filed *, struct iovlist *, int);
348 static void fprintlog_successive(struct filed *, int);
349 static void init(bool);
350 static void logmsg(int, const struct logtime *, const char *, const char *,
351 const char *, const char *, const char *, const char *, int);
352 static void log_deadchild(int, int, const struct filed *);
353 static void markit(void);
354 static struct socklist *socksetup(struct addrinfo *, const char *, mode_t);
355 static int socklist_recv_file(struct socklist *);
356 static int socklist_recv_sock(struct socklist *);
357 static int skip_message(const char *, const char *, int);
358 static int evaluate_prop_filter(const struct prop_filter *filter,
359 const char *value);
360 static nvlist_t *prop_filter_compile(const char *);
361 static void parsemsg(const char *, char *);
362 static void printsys(char *);
363 static const char *ttymsg_check(struct iovec *, int, char *, int);
364 static void usage(void);
365 static bool validate(struct sockaddr *, const char *);
366 static void unmapped(struct sockaddr *);
367 static int waitdaemon(int);
368 static void increase_rcvbuf(int);
369
370 static void
close_filed(struct filed * f)371 close_filed(struct filed *f)
372 {
373 switch (f->f_type) {
374 case F_FORW:
375 if (f->f_addr_fds != NULL) {
376 free(f->f_addrs);
377 for (size_t i = 0; i < f->f_num_addr_fds; ++i)
378 close(f->f_addr_fds[i]);
379 free(f->f_addr_fds);
380 f->f_addr_fds = NULL;
381 f->f_num_addr_fds = 0;
382 }
383 /* FALLTHROUGH */
384 case F_FILE:
385 case F_TTY:
386 case F_CONSOLE:
387 f->f_type = F_UNUSED;
388 break;
389 case F_PIPE:
390 if (f->f_procdesc != -1) {
391 /*
392 * Close the procdesc, killing the underlying
393 * process (if it is still alive).
394 */
395 (void)close(f->f_procdesc);
396 f->f_procdesc = -1;
397 /*
398 * The pipe process is guaranteed to be dead now,
399 * so remove it from the deadq.
400 */
401 if (f->f_dq != NULL) {
402 deadq_remove(f->f_dq);
403 f->f_dq = NULL;
404 }
405 }
406 break;
407 default:
408 break;
409 }
410 if (f->f_file != -1)
411 (void)close(f->f_file);
412 f->f_file = -1;
413 }
414
415 static void
addpeer(const char * name,const char * serv,mode_t mode)416 addpeer(const char *name, const char *serv, mode_t mode)
417 {
418 struct peer *pe = calloc(1, sizeof(*pe));
419 if (pe == NULL)
420 err(1, "malloc failed");
421 pe->pe_name = name;
422 pe->pe_serv = serv;
423 pe->pe_mode = mode;
424 STAILQ_INSERT_TAIL(&pqueue, pe, next);
425 }
426
427 static void
addsock(const char * name,const char * serv,mode_t mode)428 addsock(const char *name, const char *serv, mode_t mode)
429 {
430 struct addrinfo hints = { }, *res, *res0;
431 struct socklist *sl;
432 int error;
433 char *cp, *msgbuf;
434
435 /*
436 * We have to handle this case for backwards compatibility:
437 * If there are two (or more) colons but no '[' and ']',
438 * assume this is an inet6 address without a service.
439 */
440 if (name != NULL) {
441 #ifdef INET6
442 if (name[0] == '[' &&
443 (cp = strchr(name + 1, ']')) != NULL) {
444 name = &name[1];
445 *cp = '\0';
446 if (cp[1] == ':' && cp[2] != '\0')
447 serv = cp + 2;
448 } else {
449 #endif
450 cp = strchr(name, ':');
451 if (cp != NULL && strchr(cp + 1, ':') == NULL) {
452 *cp = '\0';
453 if (cp[1] != '\0')
454 serv = cp + 1;
455 if (cp == name)
456 name = NULL;
457 }
458 #ifdef INET6
459 }
460 #endif
461 }
462 hints.ai_family = AF_UNSPEC;
463 hints.ai_socktype = SOCK_DGRAM;
464 hints.ai_flags = AI_PASSIVE;
465 if (name != NULL)
466 dprintf("Trying peer: %s\n", name);
467 if (serv == NULL)
468 serv = "syslog";
469 error = getaddrinfo(name, serv, &hints, &res0);
470 if (error == EAI_NONAME && name == NULL && SecureMode > 1) {
471 /*
472 * If we're in secure mode, we won't open inet sockets anyway.
473 * This failure can arise legitimately when running in a jail
474 * without networking.
475 */
476 return;
477 }
478 if (error) {
479 asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
480 name == NULL ? "" : name, serv,
481 gai_strerror(error));
482 errno = 0;
483 if (msgbuf == NULL)
484 logerror(gai_strerror(error));
485 else
486 logerror(msgbuf);
487 free(msgbuf);
488 die(0);
489 }
490 for (res = res0; res != NULL; res = res->ai_next) {
491 sl = socksetup(res, name, mode);
492 if (sl == NULL)
493 continue;
494 STAILQ_INSERT_TAIL(&shead, sl, next);
495 }
496 freeaddrinfo(res0);
497 }
498
499 static void
addfile(int fd)500 addfile(int fd)
501 {
502 struct socklist *sl = calloc(1, sizeof(*sl));
503 if (sl == NULL)
504 err(1, "malloc failed");
505 sl->sl_socket = fd;
506 sl->sl_recv = socklist_recv_file;
507 STAILQ_INSERT_TAIL(&shead, sl, next);
508 }
509
510 int
main(int argc,char * argv[])511 main(int argc, char *argv[])
512 {
513 struct sigaction act = { };
514 struct kevent ev;
515 struct socklist *sl;
516 pid_t spid;
517 int ch, ppipe_w = -1, s;
518 char *p;
519 bool bflag = false, pflag = false, Sflag = false;
520
521 if (madvise(NULL, 0, MADV_PROTECT) != 0)
522 dprintf("madvise() failed: %s\n", strerror(errno));
523
524 while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:M:m:nNoO:p:P:sS:Tuv"))
525 != -1)
526 switch (ch) {
527 #ifdef INET
528 case '4':
529 family = PF_INET;
530 break;
531 #endif
532 #ifdef INET6
533 case '6':
534 family = PF_INET6;
535 break;
536 #endif
537 case '8':
538 mask_C1 = 0;
539 break;
540 case 'A':
541 send_to_all = true;
542 break;
543 case 'a': /* allow specific network addresses only */
544 if (!allowaddr(optarg))
545 usage();
546 break;
547 case 'b':
548 bflag = true;
549 p = strchr(optarg, ']');
550 if (p != NULL)
551 p = strchr(p + 1, ':');
552 else {
553 p = strchr(optarg, ':');
554 if (p != NULL && strchr(p + 1, ':') != NULL)
555 p = NULL; /* backward compatibility */
556 }
557 if (p == NULL) {
558 /* A hostname or filename only. */
559 addpeer(optarg, "syslog", 0);
560 } else {
561 /* The case of "name:service". */
562 *p++ = '\0';
563 addpeer(strlen(optarg) == 0 ? NULL : optarg,
564 p, 0);
565 }
566 break;
567 case 'c':
568 no_compress++;
569 break;
570 case 'C':
571 logflags |= O_CREAT;
572 break;
573 case 'd': /* debug */
574 Debug = true;
575 break;
576 case 'f': /* configuration file */
577 ConfFile = optarg;
578 break;
579 case 'F': /* run in foreground instead of daemon */
580 Foreground = true;
581 break;
582 case 'H':
583 RemoteHostname = true;
584 break;
585 case 'k': /* keep remote kern fac */
586 KeepKernFac = true;
587 break;
588 case 'l':
589 case 'p':
590 case 'S':
591 {
592 long perml;
593 mode_t mode;
594 char *name, *ep;
595
596 if (ch == 'l')
597 mode = DEFFILEMODE;
598 else if (ch == 'p') {
599 mode = DEFFILEMODE;
600 pflag = true;
601 } else {
602 mode = S_IRUSR | S_IWUSR;
603 Sflag = true;
604 }
605 if (optarg[0] == '/')
606 name = optarg;
607 else if ((name = strchr(optarg, ':')) != NULL) {
608 *name++ = '\0';
609 if (name[0] != '/')
610 errx(1, "socket name must be absolute "
611 "path");
612 if (isdigit(*optarg)) {
613 perml = strtol(optarg, &ep, 8);
614 if (*ep || perml < 0 ||
615 perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
616 errx(1, "invalid mode %s, exiting",
617 optarg);
618 mode = (mode_t )perml;
619 } else
620 errx(1, "invalid mode %s, exiting",
621 optarg);
622 } else
623 errx(1, "invalid filename %s, exiting",
624 optarg);
625 addpeer(name, NULL, mode);
626 break;
627 }
628 case 'M': /* max length of forwarded message */
629 MaxForwardLen = atoi(optarg);
630 if (MaxForwardLen < 480)
631 errx(1, "minimum length limit of forwarded "
632 "messages is 480 bytes");
633 break;
634 case 'm': /* mark interval */
635 MarkInterval = atoi(optarg) * 60;
636 break;
637 case 'N':
638 NoBind = true;
639 if (!SecureMode)
640 SecureMode = 1;
641 break;
642 case 'n':
643 resolve = false;
644 break;
645 case 'O':
646 if (strcmp(optarg, "bsd") == 0 ||
647 strcmp(optarg, "rfc3164") == 0)
648 output_format = FORMAT_BSD_LEGACY;
649 else if (strcmp(optarg, "rfc3164-strict") == 0)
650 output_format = FORMAT_RFC3164_STRICT;
651 else if (strcmp(optarg, "syslog") == 0 ||
652 strcmp(optarg, "rfc5424") == 0)
653 output_format = FORMAT_RFC5424;
654 else
655 usage();
656 break;
657 case 'o':
658 use_bootfile = true;
659 break;
660 case 'P': /* path for alt. PID */
661 PidFile = optarg;
662 break;
663 case 's': /* no network mode */
664 SecureMode++;
665 break;
666 case 'T':
667 RemoteAddDate = true;
668 break;
669 case 'u': /* only log specified priority */
670 UniquePriority = true;
671 break;
672 case 'v': /* log facility and priority */
673 LogFacPri++;
674 break;
675 default:
676 usage();
677 }
678 if ((argc -= optind) != 0)
679 usage();
680
681 if (IS_RFC3164_FORMAT && MaxForwardLen > 1024)
682 errx(1, "RFC 3164 messages may not exceed 1024 bytes");
683
684 pfh = pidfile_open(PidFile, 0600, &spid);
685 if (pfh == NULL) {
686 if (errno == EEXIST)
687 errx(1, "syslogd already running, pid: %d", spid);
688 warn("cannot open pid file");
689 }
690
691 /*
692 * Now that flags have been parsed, we know if we're in
693 * secure mode. Add peers to the socklist, if allowed.
694 */
695 while (!STAILQ_EMPTY(&pqueue)) {
696 struct peer *pe = STAILQ_FIRST(&pqueue);
697 STAILQ_REMOVE_HEAD(&pqueue, next);
698 addsock(pe->pe_name, pe->pe_serv, pe->pe_mode);
699 free(pe);
700 }
701 /* Listen by default: /dev/klog. */
702 s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
703 if (s < 0) {
704 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
705 } else {
706 addfile(s);
707 }
708 /* Listen by default: *:514 if no -b flag. */
709 if (bflag == 0)
710 addsock(NULL, "syslog", 0);
711 /* Listen by default: /var/run/log if no -p flag. */
712 if (pflag == 0)
713 addsock(_PATH_LOG, NULL, DEFFILEMODE);
714 /* Listen by default: /var/run/logpriv if no -S flag. */
715 if (Sflag == 0)
716 addsock(_PATH_LOG_PRIV, NULL, S_IRUSR | S_IWUSR);
717
718 consfile.f_type = F_CONSOLE;
719 consfile.f_file = -1;
720 (void)strlcpy(consfile.f_fname, _PATH_CONSOLE + sizeof(_PATH_DEV) - 1,
721 sizeof(consfile.f_fname));
722
723 nulldesc = open(_PATH_DEVNULL, O_RDWR);
724 if (nulldesc == -1) {
725 warn("cannot open %s", _PATH_DEVNULL);
726 pidfile_remove(pfh);
727 exit(1);
728 }
729
730 (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
731
732 if (!Foreground && !Debug)
733 ppipe_w = waitdaemon(30);
734 else if (Debug)
735 setlinebuf(stdout);
736
737 kq = kqueue();
738 if (kq == -1) {
739 warn("failed to initialize kqueue");
740 pidfile_remove(pfh);
741 exit(1);
742 }
743 STAILQ_FOREACH(sl, &shead, next) {
744 if (sl->sl_recv == NULL)
745 continue;
746 EV_SET(&ev, sl->sl_socket, EVFILT_READ, EV_ADD, 0, 0, sl);
747 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) {
748 warn("failed to add kevent to kqueue");
749 pidfile_remove(pfh);
750 exit(1);
751 }
752 }
753
754 /*
755 * Syslogd will not reap its children via wait().
756 * When SIGCHLD is ignored, zombie processes are
757 * not created. A child's PID will be recycled
758 * upon its exit.
759 */
760 act.sa_handler = SIG_IGN;
761 for (size_t i = 0; i < nitems(sigcatch); ++i) {
762 EV_SET(&ev, sigcatch[i], EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
763 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) {
764 warn("failed to add kevent to kqueue");
765 pidfile_remove(pfh);
766 exit(1);
767 }
768 if (sigaction(sigcatch[i], &act, NULL) == -1) {
769 warn("failed to apply signal handler");
770 pidfile_remove(pfh);
771 exit(1);
772 }
773 }
774 (void)alarm(TIMERINTVL);
775
776 /* tuck my process id away */
777 pidfile_write(pfh);
778
779 dprintf("off & running....\n");
780 init(false);
781 for (;;) {
782 if (needdofsync) {
783 dofsync();
784 if (ppipe_w != -1) {
785 /*
786 * Close our end of the pipe so our
787 * parent knows that we have finished
788 * initialization.
789 */
790 (void)close(ppipe_w);
791 ppipe_w = -1;
792 }
793 }
794 if (kevent(kq, NULL, 0, &ev, 1, NULL) == -1) {
795 if (errno != EINTR)
796 logerror("kevent");
797 continue;
798 }
799 switch (ev.filter) {
800 case EVFILT_READ:
801 sl = ev.udata;
802 if (sl->sl_socket != -1 && sl->sl_recv != NULL)
803 sl->sl_recv(sl);
804 break;
805 case EVFILT_SIGNAL:
806 switch (ev.ident) {
807 case SIGHUP:
808 init(true);
809 break;
810 case SIGINT:
811 case SIGQUIT:
812 case SIGTERM:
813 if (ev.ident == SIGTERM || Debug)
814 die(ev.ident);
815 break;
816 case SIGALRM:
817 markit();
818 break;
819 }
820 break;
821 case EVFILT_PROCDESC:
822 if ((ev.fflags & NOTE_EXIT) != 0) {
823 log_deadchild(ev.ident, ev.data, ev.udata);
824 close_filed(ev.udata);
825 }
826 break;
827 }
828 }
829 }
830
831 static int
socklist_recv_sock(struct socklist * sl)832 socklist_recv_sock(struct socklist *sl)
833 {
834 struct sockaddr_storage ss;
835 struct sockaddr *sa = (struct sockaddr *)&ss;
836 socklen_t sslen;
837 const char *hname;
838 char line[MAXLINE + 1];
839 int len;
840
841 sslen = sizeof(ss);
842 len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
843 dprintf("received sa_len = %d\n", sslen);
844 if (len == 0)
845 return (-1);
846 if (len < 0) {
847 if (errno != EINTR)
848 logerror("recvfrom");
849 return (-1);
850 }
851 /* Received valid data. */
852 line[len] = '\0';
853 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
854 hname = LocalHostName;
855 else {
856 hname = cvthname(sa);
857 unmapped(sa);
858 if (validate(sa, hname) == 0) {
859 dprintf("Message from %s was ignored.", hname);
860 return (-1);
861 }
862 }
863 parsemsg(hname, line);
864
865 return (0);
866 }
867
868 static void
unmapped(struct sockaddr * sa)869 unmapped(struct sockaddr *sa)
870 {
871 #if defined(INET) && defined(INET6)
872 struct sockaddr_in6 *sin6;
873 struct sockaddr_in sin;
874
875 if (sa == NULL ||
876 sa->sa_family != AF_INET6 ||
877 sa->sa_len != sizeof(*sin6))
878 return;
879 sin6 = satosin6(sa);
880 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
881 return;
882 sin = (struct sockaddr_in){
883 .sin_family = AF_INET,
884 .sin_len = sizeof(sin),
885 .sin_port = sin6->sin6_port
886 };
887 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
888 sizeof(sin.sin_addr));
889 memcpy(sa, &sin, sizeof(sin));
890 #else
891 if (sa == NULL)
892 return;
893 #endif
894 }
895
896 static void
usage(void)897 usage(void)
898 {
899
900 fprintf(stderr,
901 "usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]\n"
902 " [-b bind_address] [-f config_file]\n"
903 " [-l [mode:]path] [-M fwd_length]\n"
904 " [-m mark_interval] [-O format] [-P pid_file]\n"
905 " [-p log_socket] [-S logpriv_socket]\n");
906 exit(1);
907 }
908
909 /*
910 * Removes characters from log messages that are unsafe to display.
911 * TODO: Permit UTF-8 strings that include a BOM per RFC 5424?
912 */
913 static void
parsemsg_remove_unsafe_characters(const char * in,char * out,size_t outlen)914 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen)
915 {
916 char *q;
917 int c;
918
919 q = out;
920 while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) {
921 if (mask_C1 && (c & 0x80) && c < 0xA0) {
922 c &= 0x7F;
923 *q++ = 'M';
924 *q++ = '-';
925 }
926 if (isascii(c) && iscntrl(c)) {
927 if (c == '\n') {
928 *q++ = ' ';
929 } else if (c == '\t') {
930 *q++ = '\t';
931 } else {
932 *q++ = '^';
933 *q++ = c ^ 0100;
934 }
935 } else {
936 *q++ = c;
937 }
938 }
939 *q = '\0';
940 }
941
942 /*
943 * Parses a syslog message according to RFC 5424, assuming that PRI and
944 * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The
945 * parsed result is passed to logmsg().
946 */
947 static void
parsemsg_rfc5424(const char * from,int pri,char * msg)948 parsemsg_rfc5424(const char *from, int pri, char *msg)
949 {
950 const struct logtime *timestamp;
951 struct logtime timestamp_remote;
952 const char *omsg, *hostname, *app_name, *procid, *msgid,
953 *structured_data;
954 char line[MAXLINE + 1];
955
956 #define FAIL_IF(field, expr) do { \
957 if (expr) { \
958 dprintf("Failed to parse " field " from %s: %s\n", \
959 from, omsg); \
960 return; \
961 } \
962 } while (0)
963 #define PARSE_CHAR(field, sep) do { \
964 FAIL_IF(field, *msg != sep); \
965 ++msg; \
966 } while (0)
967 #define IF_NOT_NILVALUE(var) \
968 if (msg[0] == '-' && msg[1] == ' ') { \
969 msg += 2; \
970 var = NULL; \
971 } else if (msg[0] == '-' && msg[1] == '\0') { \
972 ++msg; \
973 var = NULL; \
974 } else
975
976 omsg = msg;
977 IF_NOT_NILVALUE(timestamp) {
978 /* Parse RFC 3339-like timestamp. */
979 #define PARSE_NUMBER(dest, length, min, max) do { \
980 int i, v; \
981 \
982 v = 0; \
983 for (i = 0; i < length; ++i) { \
984 FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9'); \
985 v = v * 10 + *msg++ - '0'; \
986 } \
987 FAIL_IF("TIMESTAMP", v < min || v > max); \
988 dest = v; \
989 } while (0)
990 /* Date and time. */
991 memset(×tamp_remote, 0, sizeof(timestamp_remote));
992 PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999);
993 timestamp_remote.tm.tm_year -= 1900;
994 PARSE_CHAR("TIMESTAMP", '-');
995 PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12);
996 --timestamp_remote.tm.tm_mon;
997 PARSE_CHAR("TIMESTAMP", '-');
998 PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31);
999 PARSE_CHAR("TIMESTAMP", 'T');
1000 PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23);
1001 PARSE_CHAR("TIMESTAMP", ':');
1002 PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59);
1003 PARSE_CHAR("TIMESTAMP", ':');
1004 PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59);
1005 /* Perform normalization. */
1006 timegm(×tamp_remote.tm);
1007 /* Optional: fractional seconds. */
1008 if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') {
1009 int i;
1010
1011 ++msg;
1012 for (i = 100000; i != 0; i /= 10) {
1013 if (*msg < '0' || *msg > '9')
1014 break;
1015 timestamp_remote.usec += (*msg++ - '0') * i;
1016 }
1017 }
1018 /* Timezone. */
1019 if (*msg == 'Z') {
1020 /* UTC. */
1021 ++msg;
1022 } else {
1023 int sign, tz_hour, tz_min;
1024
1025 /* Local time zone offset. */
1026 FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+');
1027 sign = *msg++ == '-' ? -1 : 1;
1028 PARSE_NUMBER(tz_hour, 2, 0, 23);
1029 PARSE_CHAR("TIMESTAMP", ':');
1030 PARSE_NUMBER(tz_min, 2, 0, 59);
1031 timestamp_remote.tm.tm_gmtoff =
1032 sign * (tz_hour * 3600 + tz_min * 60);
1033 }
1034 #undef PARSE_NUMBER
1035 PARSE_CHAR("TIMESTAMP", ' ');
1036 timestamp = RemoteAddDate ? NULL : ×tamp_remote;
1037 }
1038
1039 /* String fields part of the HEADER. */
1040 #define PARSE_STRING(field, var) \
1041 IF_NOT_NILVALUE(var) { \
1042 var = msg; \
1043 while (*msg >= '!' && *msg <= '~') \
1044 ++msg; \
1045 FAIL_IF(field, var == msg); \
1046 PARSE_CHAR(field, ' '); \
1047 msg[-1] = '\0'; \
1048 }
1049 PARSE_STRING("HOSTNAME", hostname);
1050 if (hostname == NULL || !RemoteHostname)
1051 hostname = from;
1052 PARSE_STRING("APP-NAME", app_name);
1053 PARSE_STRING("PROCID", procid);
1054 PARSE_STRING("MSGID", msgid);
1055 #undef PARSE_STRING
1056
1057 /* Structured data. */
1058 #define PARSE_SD_NAME() do { \
1059 const char *start; \
1060 \
1061 start = msg; \
1062 while (*msg >= '!' && *msg <= '~' && *msg != '=' && \
1063 *msg != ']' && *msg != '"') \
1064 ++msg; \
1065 FAIL_IF("STRUCTURED-NAME", start == msg); \
1066 } while (0)
1067 IF_NOT_NILVALUE(structured_data) {
1068 structured_data = msg;
1069 /* SD-ELEMENT. */
1070 while (*msg == '[') {
1071 ++msg;
1072 /* SD-ID. */
1073 PARSE_SD_NAME();
1074 /* SD-PARAM. */
1075 while (*msg == ' ') {
1076 ++msg;
1077 /* PARAM-NAME. */
1078 PARSE_SD_NAME();
1079 PARSE_CHAR("STRUCTURED-NAME", '=');
1080 PARSE_CHAR("STRUCTURED-NAME", '"');
1081 while (*msg != '"') {
1082 FAIL_IF("STRUCTURED-NAME",
1083 *msg == '\0');
1084 if (*msg++ == '\\') {
1085 FAIL_IF("STRUCTURED-NAME",
1086 *msg == '\0');
1087 ++msg;
1088 }
1089 }
1090 ++msg;
1091 }
1092 PARSE_CHAR("STRUCTURED-NAME", ']');
1093 }
1094 PARSE_CHAR("STRUCTURED-NAME", ' ');
1095 msg[-1] = '\0';
1096 }
1097 #undef PARSE_SD_NAME
1098
1099 #undef FAIL_IF
1100 #undef PARSE_CHAR
1101 #undef IF_NOT_NILVALUE
1102
1103 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1104 logmsg(pri, timestamp, hostname, app_name, procid, msgid,
1105 structured_data, line, 0);
1106 }
1107
1108 /*
1109 * Returns the length of the application name ("TAG" in RFC 3164
1110 * terminology) and process ID from a message if present.
1111 */
1112 static void
parsemsg_rfc3164_get_app_name_procid(const char * msg,size_t * app_name_length_p,ptrdiff_t * procid_begin_offset_p,size_t * procid_length_p)1113 parsemsg_rfc3164_get_app_name_procid(const char *msg, size_t *app_name_length_p,
1114 ptrdiff_t *procid_begin_offset_p, size_t *procid_length_p)
1115 {
1116 const char *m, *procid_begin;
1117 size_t app_name_length, procid_length;
1118
1119 m = msg;
1120
1121 /* Application name. */
1122 app_name_length = strspn(m,
1123 "abcdefghijklmnopqrstuvwxyz"
1124 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1125 "0123456789"
1126 "_-/");
1127 if (app_name_length == 0)
1128 goto bad;
1129 m += app_name_length;
1130
1131 /* Process identifier (optional). */
1132 if (*m == '[') {
1133 procid_begin = ++m;
1134 procid_length = strspn(m, "0123456789");
1135 if (procid_length == 0)
1136 goto bad;
1137 m += procid_length;
1138 if (*m++ != ']')
1139 goto bad;
1140 } else {
1141 procid_begin = NULL;
1142 procid_length = 0;
1143 }
1144
1145 /* Separator. */
1146 if (m[0] != ':' || m[1] != ' ')
1147 goto bad;
1148
1149 *app_name_length_p = app_name_length;
1150 if (procid_begin_offset_p != NULL)
1151 *procid_begin_offset_p =
1152 procid_begin == NULL ? 0 : procid_begin - msg;
1153 if (procid_length_p != NULL)
1154 *procid_length_p = procid_length;
1155 return;
1156 bad:
1157 *app_name_length_p = 0;
1158 if (procid_begin_offset_p != NULL)
1159 *procid_begin_offset_p = 0;
1160 if (procid_length_p != NULL)
1161 *procid_length_p = 0;
1162 }
1163
1164 /*
1165 * Trims the application name ("TAG" in RFC 3164 terminology) and
1166 * process ID from a message if present.
1167 */
1168 static void
parsemsg_rfc3164_app_name_procid(char ** msg,const char ** app_name,const char ** procid)1169 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name,
1170 const char **procid)
1171 {
1172 char *m, *app_name_begin, *procid_begin;
1173 size_t app_name_length, procid_length;
1174 ptrdiff_t procid_begin_offset;
1175
1176 m = *msg;
1177 app_name_begin = m;
1178
1179 parsemsg_rfc3164_get_app_name_procid(app_name_begin, &app_name_length,
1180 &procid_begin_offset, &procid_length);
1181 if (app_name_length == 0)
1182 goto bad;
1183 procid_begin = procid_begin_offset == 0 ? NULL :
1184 app_name_begin + procid_begin_offset;
1185
1186 /* Split strings from input. */
1187 app_name_begin[app_name_length] = '\0';
1188 m += app_name_length + 1;
1189 if (procid_begin != NULL) {
1190 procid_begin[procid_length] = '\0';
1191 m += procid_length + 2;
1192 }
1193
1194 *msg = m + 1;
1195 *app_name = app_name_begin;
1196 *procid = procid_begin;
1197 return;
1198 bad:
1199 *app_name = NULL;
1200 *procid = NULL;
1201 }
1202
1203 /*
1204 * Parses a syslog message according to RFC 3164, assuming that PRI
1205 * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed
1206 * result is passed to logmsg().
1207 */
1208 static void
parsemsg_rfc3164(const char * from,int pri,char * msg)1209 parsemsg_rfc3164(const char *from, int pri, char *msg)
1210 {
1211 struct tm tm_parsed;
1212 const struct logtime *timestamp;
1213 struct logtime timestamp_remote;
1214 const char *app_name, *procid;
1215 size_t i, msglen;
1216 char line[MAXLINE + 1];
1217
1218 /*
1219 * Parse the TIMESTAMP provided by the remote side. If none is
1220 * found, assume this is not an RFC 3164 formatted message,
1221 * only containing a TAG and a MSG.
1222 */
1223 timestamp = NULL;
1224 if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) ==
1225 msg + RFC3164_DATELEN && msg[RFC3164_DATELEN] == ' ') {
1226 msg += RFC3164_DATELEN + 1;
1227 if (!RemoteAddDate) {
1228 struct tm tm_now;
1229 time_t t_now;
1230 int year;
1231
1232 /*
1233 * As the timestamp does not contain the year
1234 * number, daylight saving time information, nor
1235 * a time zone, attempt to infer it. Due to
1236 * clock skews, the timestamp may even be part
1237 * of the next year. Use the last year for which
1238 * the timestamp is at most one week in the
1239 * future.
1240 *
1241 * This loop can only run for at most three
1242 * iterations before terminating.
1243 */
1244 t_now = time(NULL);
1245 localtime_r(&t_now, &tm_now);
1246 for (year = tm_now.tm_year + 1;; --year) {
1247 assert(year >= tm_now.tm_year - 1);
1248 timestamp_remote.tm = tm_parsed;
1249 timestamp_remote.tm.tm_year = year;
1250 timestamp_remote.tm.tm_isdst = -1;
1251 timestamp_remote.usec = 0;
1252 if (mktime(×tamp_remote.tm) <
1253 t_now + 7 * 24 * 60 * 60)
1254 break;
1255 }
1256 timestamp = ×tamp_remote;
1257 }
1258
1259 /*
1260 * A single space character MUST also follow the HOSTNAME field.
1261 */
1262 msglen = strlen(msg);
1263 for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
1264 if (msg[i] == ' ') {
1265 if (RemoteHostname) {
1266 msg[i] = '\0';
1267 from = msg;
1268 }
1269 msg += i + 1;
1270 break;
1271 }
1272 /*
1273 * Support non RFC compliant messages, without hostname.
1274 */
1275 if (msg[i] == ':')
1276 break;
1277 }
1278 if (i == MIN(MAXHOSTNAMELEN, msglen)) {
1279 dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
1280 return;
1281 }
1282 }
1283
1284 /* Remove the TAG, if present. */
1285 parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid);
1286 parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1287 logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0);
1288 }
1289
1290 /*
1291 * Takes a raw input line, extracts PRI and determines whether the
1292 * message is formatted according to RFC 3164 or RFC 5424. Continues
1293 * parsing of addition fields in the message according to those
1294 * standards and prints the message on the appropriate log files.
1295 */
1296 static void
parsemsg(const char * from,char * msg)1297 parsemsg(const char *from, char *msg)
1298 {
1299 char *q;
1300 long n;
1301 size_t i;
1302 int pri;
1303
1304 i = -1;
1305 pri = DEFUPRI;
1306
1307 /* Parse PRI. */
1308 if (msg[0] == '<' && isdigit(msg[1])) {
1309 for (i = 2; i <= 4; i++) {
1310 if (msg[i] == '>') {
1311 errno = 0;
1312 n = strtol(msg + 1, &q, 10);
1313 if (errno == 0 && *q == msg[i] && n >= 0 && n <= INT_MAX) {
1314 pri = n;
1315 msg += i + 1;
1316 i = 0;
1317 }
1318 break;
1319 }
1320 }
1321 }
1322
1323 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1324 pri = DEFUPRI;
1325
1326 /*
1327 * Don't allow users to log kernel messages.
1328 * NOTE: since LOG_KERN == 0 this will also match
1329 * messages with no facility specified.
1330 */
1331 if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
1332 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1333
1334 /* Parse VERSION. */
1335 if (i == 0 && msg[0] == '1' && msg[1] == ' ')
1336 parsemsg_rfc5424(from, pri, msg + 2);
1337 else
1338 parsemsg_rfc3164(from, pri, msg);
1339 }
1340
1341 /*
1342 * Read /dev/klog while data are available, split into lines.
1343 */
1344 static int
socklist_recv_file(struct socklist * sl)1345 socklist_recv_file(struct socklist *sl)
1346 {
1347 char *p, *q, line[MAXLINE + 1];
1348 int len, i;
1349
1350 len = 0;
1351 for (;;) {
1352 i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
1353 if (i > 0) {
1354 line[i + len] = '\0';
1355 } else {
1356 if (i < 0 && errno != EINTR && errno != EAGAIN) {
1357 logerror("klog");
1358 close(sl->sl_socket);
1359 sl->sl_socket = -1;
1360 }
1361 break;
1362 }
1363
1364 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
1365 *q = '\0';
1366 printsys(p);
1367 }
1368 len = strlen(p);
1369 if (len >= MAXLINE - 1) {
1370 printsys(p);
1371 len = 0;
1372 }
1373 if (len > 0)
1374 memmove(line, p, len + 1);
1375 }
1376 if (len > 0)
1377 printsys(line);
1378
1379 return (len);
1380 }
1381
1382 /*
1383 * Take a raw input line from /dev/klog, format similar to syslog().
1384 */
1385 static void
printsys(char * msg)1386 printsys(char *msg)
1387 {
1388 char *p, *q;
1389 long n;
1390 int flags, isprintf, pri;
1391
1392 flags = ISKERNEL | SYNC_FILE; /* fsync after write */
1393 p = msg;
1394 pri = DEFSPRI;
1395 isprintf = 1;
1396 if (*p == '<') {
1397 errno = 0;
1398 n = strtol(p + 1, &q, 10);
1399 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1400 p = q + 1;
1401 pri = n;
1402 isprintf = 0;
1403 }
1404 }
1405 /*
1406 * Kernel printf's and LOG_CONSOLE messages have been displayed
1407 * on the console already.
1408 */
1409 if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1410 flags |= IGN_CONS;
1411 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1412 pri = DEFSPRI;
1413 logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags);
1414 }
1415
1416 static time_t now;
1417
1418 /*
1419 * Match a program or host name against a specification.
1420 * Return a non-0 value if the message must be ignored
1421 * based on the specification.
1422 */
1423 static int
skip_message(const char * name,const char * spec,int checkcase)1424 skip_message(const char *name, const char *spec, int checkcase)
1425 {
1426 const char *s;
1427 char prev, next;
1428 int exclude = 0;
1429 /* Behaviour on explicit match */
1430
1431 if (spec == NULL || *spec == '\0')
1432 return (0);
1433 switch (*spec) {
1434 case '-':
1435 exclude = 1;
1436 /*FALLTHROUGH*/
1437 case '+':
1438 spec++;
1439 break;
1440 default:
1441 break;
1442 }
1443 if (checkcase)
1444 s = strstr (spec, name);
1445 else
1446 s = strcasestr (spec, name);
1447
1448 if (s != NULL) {
1449 prev = (s == spec ? ',' : *(s - 1));
1450 next = *(s + strlen (name));
1451
1452 if (prev == ',' && (next == '\0' || next == ','))
1453 /* Explicit match: skip iff the spec is an
1454 exclusive one. */
1455 return (exclude);
1456 }
1457
1458 /* No explicit match for this name: skip the message iff
1459 the spec is an inclusive one. */
1460 return (!exclude);
1461 }
1462
1463 /*
1464 * Match some property of the message against a filter.
1465 * Return a non-0 value if the message must be ignored
1466 * based on the filter.
1467 */
1468 static int
evaluate_prop_filter(const struct prop_filter * filter,const char * value)1469 evaluate_prop_filter(const struct prop_filter *filter, const char *value)
1470 {
1471 const char *s = NULL;
1472 const int exclude = ((filter->cmp_flags & FILT_FLAG_EXCLUDE) > 0);
1473 size_t valuelen;
1474
1475 if (value == NULL)
1476 return (-1);
1477
1478 if (filter->cmp_type == FILT_CMP_REGEX) {
1479 if (regexec(filter->pflt_re, value, 0, NULL, 0) == 0)
1480 return (exclude);
1481 else
1482 return (!exclude);
1483 }
1484
1485 valuelen = strlen(value);
1486
1487 /* a shortcut for equal with different length is always false */
1488 if (filter->cmp_type == FILT_CMP_EQUAL &&
1489 valuelen != strlen(filter->pflt_strval))
1490 return (!exclude);
1491
1492 if (filter->cmp_flags & FILT_FLAG_ICASE)
1493 s = strcasestr(value, filter->pflt_strval);
1494 else
1495 s = strstr(value, filter->pflt_strval);
1496
1497 /*
1498 * FILT_CMP_CONTAINS true if s
1499 * FILT_CMP_STARTS true if s && s == value
1500 * FILT_CMP_EQUAL true if s && s == value &&
1501 * valuelen == filter->pflt_strlen
1502 * (and length match is checked
1503 * already)
1504 */
1505
1506 switch (filter->cmp_type) {
1507 case FILT_CMP_STARTS:
1508 case FILT_CMP_EQUAL:
1509 if (s != value)
1510 return (!exclude);
1511 /* FALLTHROUGH */
1512 case FILT_CMP_CONTAINS:
1513 if (s)
1514 return (exclude);
1515 else
1516 return (!exclude);
1517 break;
1518 default:
1519 /* unknown cmp_type */
1520 break;
1521 }
1522
1523 return (-1);
1524 }
1525
1526 /*
1527 * Logs a message to the appropriate log files, users, etc. based on the
1528 * priority. Log messages are formatted according to RFC 3164 or
1529 * RFC 5424 in subsequent fprintlog_*() functions.
1530 */
1531 static void
logmsg(int pri,const struct logtime * timestamp,const char * hostname,const char * app_name,const char * procid,const char * msgid,const char * structured_data,const char * msg,int flags)1532 logmsg(int pri, const struct logtime *timestamp, const char *hostname,
1533 const char *app_name, const char *procid, const char *msgid,
1534 const char *structured_data, const char *msg, int flags)
1535 {
1536 struct timeval tv;
1537 struct logtime timestamp_now;
1538 struct filed *f;
1539 size_t savedlen;
1540 int fac, prilev;
1541 char saved[MAXSVLINE], kernel_app_name[100];
1542
1543 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1544 pri, flags, hostname, msg);
1545
1546 (void)gettimeofday(&tv, NULL);
1547 now = tv.tv_sec;
1548 if (timestamp == NULL) {
1549 localtime_r(&now, ×tamp_now.tm);
1550 timestamp_now.usec = tv.tv_usec;
1551 timestamp = ×tamp_now;
1552 }
1553
1554 /* extract facility and priority level */
1555 if (flags & MARK)
1556 fac = LOG_NFACILITIES;
1557 else
1558 fac = LOG_FAC(pri);
1559
1560 /* Check maximum facility number. */
1561 if (fac > LOG_NFACILITIES)
1562 return;
1563
1564 prilev = LOG_PRI(pri);
1565
1566 /*
1567 * Lookup kernel app name from log prefix if present.
1568 * This is only used for local program specification matching.
1569 */
1570 if (flags & ISKERNEL) {
1571 size_t kernel_app_name_length;
1572
1573 parsemsg_rfc3164_get_app_name_procid(msg,
1574 &kernel_app_name_length, NULL, NULL);
1575 if (kernel_app_name_length != 0) {
1576 strlcpy(kernel_app_name, msg,
1577 MIN(sizeof(kernel_app_name),
1578 kernel_app_name_length + 1));
1579 } else
1580 kernel_app_name[0] = '\0';
1581 }
1582
1583 /* log the message to the particular outputs */
1584 if (!Initialized) {
1585 consfile.f_lasttime = *timestamp;
1586 fprintlog_first(&consfile, hostname, app_name, procid,
1587 msgid, structured_data, msg, flags);
1588 return;
1589 }
1590
1591 /*
1592 * Store all of the fields of the message, except the timestamp,
1593 * in a single string. This string is used to detect duplicate
1594 * messages.
1595 */
1596 assert(hostname != NULL);
1597 assert(msg != NULL);
1598 savedlen = snprintf(saved, sizeof(saved),
1599 "%d %s %s %s %s %s %s", pri, hostname,
1600 app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid,
1601 msgid == NULL ? "-" : msgid,
1602 structured_data == NULL ? "-" : structured_data, msg);
1603
1604 STAILQ_FOREACH(f, &fhead, next) {
1605 /* skip messages that are incorrect priority */
1606 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1607 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1608 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1609 )
1610 || f->f_pmask[fac] == INTERNAL_NOPRI)
1611 continue;
1612
1613 /* skip messages with the incorrect hostname */
1614 if (skip_message(hostname, f->f_host, 0))
1615 continue;
1616
1617 /* skip messages with the incorrect program name */
1618 if (flags & ISKERNEL && kernel_app_name[0] != '\0') {
1619 if (skip_message(kernel_app_name, f->f_program, 1))
1620 continue;
1621 } else if (skip_message(app_name == NULL ? "" : app_name,
1622 f->f_program, 1))
1623 continue;
1624
1625 /* skip messages if a property does not match filter */
1626 if (f->f_prop_filter != NULL &&
1627 f->f_prop_filter->prop_type != FILT_PROP_NOOP) {
1628 switch (f->f_prop_filter->prop_type) {
1629 case FILT_PROP_MSG:
1630 if (evaluate_prop_filter(f->f_prop_filter,
1631 msg))
1632 continue;
1633 break;
1634 case FILT_PROP_HOSTNAME:
1635 if (evaluate_prop_filter(f->f_prop_filter,
1636 hostname))
1637 continue;
1638 break;
1639 case FILT_PROP_PROGNAME:
1640 if (evaluate_prop_filter(f->f_prop_filter,
1641 app_name == NULL ? "" : app_name))
1642 continue;
1643 break;
1644 default:
1645 continue;
1646 }
1647 }
1648
1649 /* skip message to console if it has already been printed */
1650 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1651 continue;
1652
1653 /* don't output marks to recently written files */
1654 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1655 continue;
1656
1657 /*
1658 * suppress duplicate lines to this file
1659 */
1660 if (no_compress - (f->f_type != F_PIPE) < 1 &&
1661 (flags & MARK) == 0 && savedlen == f->f_prevlen &&
1662 strcmp(saved, f->f_prevline) == 0) {
1663 f->f_lasttime = *timestamp;
1664 f->f_prevcount++;
1665 dprintf("msg repeated %d times, %ld sec of %d\n",
1666 f->f_prevcount, (long)(now - f->f_time),
1667 repeatinterval[f->f_repeatcount]);
1668 /*
1669 * If domark would have logged this by now,
1670 * flush it now (so we don't hold isolated messages),
1671 * but back off so we'll flush less often
1672 * in the future.
1673 */
1674 if (now > REPEATTIME(f)) {
1675 fprintlog_successive(f, flags);
1676 BACKOFF(f);
1677 }
1678 } else {
1679 /* new line, save it */
1680 if (f->f_prevcount)
1681 fprintlog_successive(f, 0);
1682 f->f_repeatcount = 0;
1683 f->f_prevpri = pri;
1684 f->f_lasttime = *timestamp;
1685 static_assert(sizeof(f->f_prevline) == sizeof(saved),
1686 "Space to store saved line incorrect");
1687 (void)strcpy(f->f_prevline, saved);
1688 f->f_prevlen = savedlen;
1689 fprintlog_first(f, hostname, app_name, procid, msgid,
1690 structured_data, msg, flags);
1691 }
1692 }
1693 }
1694
1695 static void
dofsync(void)1696 dofsync(void)
1697 {
1698 struct filed *f;
1699
1700 STAILQ_FOREACH(f, &fhead, next) {
1701 if (f->f_type == F_FILE &&
1702 (f->f_flags & FFLAG_NEEDSYNC) != 0) {
1703 f->f_flags &= ~FFLAG_NEEDSYNC;
1704 (void)fsync(f->f_file);
1705 }
1706 }
1707 needdofsync = false;
1708 }
1709
1710 static void
iovlist_init(struct iovlist * il)1711 iovlist_init(struct iovlist *il)
1712 {
1713
1714 il->iovcnt = 0;
1715 il->totalsize = 0;
1716 }
1717
1718 static void
iovlist_append(struct iovlist * il,const char * str)1719 iovlist_append(struct iovlist *il, const char *str)
1720 {
1721 size_t size;
1722
1723 /* Discard components if we've run out of iovecs. */
1724 if (il->iovcnt < nitems(il->iov)) {
1725 size = strlen(str);
1726 il->iov[il->iovcnt++] = (struct iovec){
1727 .iov_base = __DECONST(char *, str),
1728 .iov_len = size,
1729 };
1730 il->totalsize += size;
1731 }
1732 }
1733
1734 #if defined(INET) || defined(INET6)
1735 static void
iovlist_truncate(struct iovlist * il,size_t size)1736 iovlist_truncate(struct iovlist *il, size_t size)
1737 {
1738 struct iovec *last;
1739 size_t diff;
1740
1741 while (il->totalsize > size) {
1742 diff = il->totalsize - size;
1743 last = &il->iov[il->iovcnt - 1];
1744 if (diff >= last->iov_len) {
1745 /* Remove the last iovec entirely. */
1746 --il->iovcnt;
1747 il->totalsize -= last->iov_len;
1748 } else {
1749 /* Remove the last iovec partially. */
1750 last->iov_len -= diff;
1751 il->totalsize -= diff;
1752 }
1753 }
1754 }
1755 #endif
1756
1757 static void
fprintlog_write(struct filed * f,struct iovlist * il,int flags)1758 fprintlog_write(struct filed *f, struct iovlist *il, int flags)
1759 {
1760 const char *msgret;
1761
1762 switch (f->f_type) {
1763 case F_FORW: {
1764 ssize_t lsent;
1765
1766 if (Debug) {
1767 int domain, sockfd = f->f_addr_fds[0];
1768 socklen_t len = sizeof(domain);
1769
1770 if (getsockopt(sockfd, SOL_SOCKET, SO_DOMAIN,
1771 &domain, &len) < 0)
1772 err(1, "getsockopt");
1773
1774 printf(" %s", f->f_hname);
1775 switch (domain) {
1776 #ifdef INET
1777 case AF_INET: {
1778 struct sockaddr_in sin;
1779
1780 len = sizeof(sin);
1781 if (getpeername(sockfd,
1782 (struct sockaddr *)&sin, &len) < 0)
1783 err(1, "getpeername");
1784 printf(":%d\n", ntohs(sin.sin_port));
1785 break;
1786 }
1787 #endif
1788 #ifdef INET6
1789 case AF_INET6: {
1790 struct sockaddr_in6 sin6;
1791
1792 len = sizeof(sin6);
1793 if (getpeername(sockfd,
1794 (struct sockaddr *)&sin6, &len) < 0)
1795 err(1, "getpeername");
1796 printf(":%d\n", ntohs(sin6.sin6_port));
1797 break;
1798 }
1799 #endif
1800 default:
1801 printf("\n");
1802 }
1803 }
1804
1805 #if defined(INET) || defined(INET6)
1806 /* Truncate messages to maximum forward length. */
1807 iovlist_truncate(il, MaxForwardLen);
1808 #endif
1809
1810 lsent = 0;
1811 for (size_t i = 0; i < f->f_num_addr_fds; ++i) {
1812 struct msghdr msg = {
1813 .msg_iov = il->iov,
1814 .msg_iovlen = il->iovcnt,
1815 };
1816
1817 lsent = sendmsg(f->f_addr_fds[i], &msg, 0);
1818 if (lsent == (ssize_t)il->totalsize && !send_to_all)
1819 break;
1820 }
1821 dprintf("lsent/totalsize: %zd/%zu\n", lsent, il->totalsize);
1822 if (lsent != (ssize_t)il->totalsize) {
1823 int e = errno;
1824 logerror("sendto");
1825 errno = e;
1826 switch (errno) {
1827 case ENOBUFS:
1828 case ENETDOWN:
1829 case ENETUNREACH:
1830 case EHOSTUNREACH:
1831 case EHOSTDOWN:
1832 case EADDRNOTAVAIL:
1833 break;
1834 /* case EBADF: */
1835 /* case EACCES: */
1836 /* case ENOTSOCK: */
1837 /* case EFAULT: */
1838 /* case EMSGSIZE: */
1839 /* case EAGAIN: */
1840 /* case ENOBUFS: */
1841 /* case ECONNREFUSED: */
1842 default:
1843 dprintf("removing entry: errno=%d\n", e);
1844 f->f_type = F_UNUSED;
1845 break;
1846 }
1847 }
1848 break;
1849 }
1850
1851 case F_FILE:
1852 dprintf(" %s\n", f->f_fname);
1853 iovlist_append(il, "\n");
1854 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1855 /*
1856 * If writev(2) fails for potentially transient errors
1857 * like the filesystem being full, ignore it.
1858 * Otherwise remove this logfile from the list.
1859 */
1860 if (errno != ENOSPC) {
1861 int e = errno;
1862 close_filed(f);
1863 errno = e;
1864 logerror(f->f_fname);
1865 }
1866 } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1867 f->f_flags |= FFLAG_NEEDSYNC;
1868 needdofsync = true;
1869 }
1870 break;
1871
1872 case F_PIPE:
1873 dprintf(" %s\n", f->f_pname);
1874 iovlist_append(il, "\n");
1875 if (f->f_procdesc == -1) {
1876 struct kevent ev;
1877 struct filed *f_in_list;
1878 size_t i = 0;
1879
1880 STAILQ_FOREACH(f_in_list, &fhead, next) {
1881 if (f_in_list == f)
1882 break;
1883 ++i;
1884 }
1885 f->f_file = cap_p_open(cap_syslogd, i, f->f_pname,
1886 &f->f_procdesc);
1887 if (f->f_file < 0) {
1888 logerror(f->f_pname);
1889 break;
1890 }
1891 EV_SET(&ev, f->f_procdesc, EVFILT_PROCDESC, EV_ADD,
1892 NOTE_EXIT, 0, f);
1893 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) {
1894 logerror("failed to add procdesc kevent");
1895 exit(1);
1896 }
1897 }
1898 if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1899 logerror(f->f_pname);
1900 f->f_dq = deadq_enter(f->f_procdesc);
1901 }
1902 break;
1903
1904 case F_CONSOLE:
1905 if (flags & IGN_CONS) {
1906 dprintf(" (ignored)\n");
1907 break;
1908 }
1909 /* FALLTHROUGH */
1910
1911 case F_TTY:
1912 dprintf(" %s%s\n", _PATH_DEV, f->f_fname);
1913 iovlist_append(il, "\r\n");
1914 errno = 0; /* ttymsg() only sometimes returns an errno */
1915 if ((msgret = cap_ttymsg(cap_syslogd, il->iov, il->iovcnt,
1916 f->f_fname, 10))) {
1917 f->f_type = F_UNUSED;
1918 logerror(msgret);
1919 }
1920 break;
1921
1922 case F_USERS:
1923 case F_WALL:
1924 dprintf("\n");
1925 iovlist_append(il, "\r\n");
1926 cap_wallmsg(cap_syslogd, f, il->iov, il->iovcnt);
1927 break;
1928 default:
1929 break;
1930 }
1931 }
1932
1933 static void
fprintlog_rfc5424(struct filed * f,const char * hostname,const char * app_name,const char * procid,const char * msgid,const char * structured_data,const char * msg,int flags)1934 fprintlog_rfc5424(struct filed *f, const char *hostname, const char *app_name,
1935 const char *procid, const char *msgid, const char *structured_data,
1936 const char *msg, int flags)
1937 {
1938 struct iovlist il;
1939 suseconds_t usec;
1940 int i;
1941 char timebuf[33], priority_number[5];
1942
1943 iovlist_init(&il);
1944 if (f->f_type == F_WALL)
1945 iovlist_append(&il, "\r\n\aMessage from syslogd ...\r\n");
1946 iovlist_append(&il, "<");
1947 snprintf(priority_number, sizeof(priority_number), "%d", f->f_prevpri);
1948 iovlist_append(&il, priority_number);
1949 iovlist_append(&il, ">1 ");
1950 if (strftime(timebuf, sizeof(timebuf), "%FT%T.______%z",
1951 &f->f_lasttime.tm) == sizeof(timebuf) - 2) {
1952 /* Add colon to the time zone offset, which %z doesn't do. */
1953 timebuf[32] = '\0';
1954 timebuf[31] = timebuf[30];
1955 timebuf[30] = timebuf[29];
1956 timebuf[29] = ':';
1957
1958 /* Overwrite space for microseconds with actual value. */
1959 usec = f->f_lasttime.usec;
1960 for (i = 25; i >= 20; --i) {
1961 timebuf[i] = usec % 10 + '0';
1962 usec /= 10;
1963 }
1964 iovlist_append(&il, timebuf);
1965 } else
1966 iovlist_append(&il, "-");
1967 iovlist_append(&il, " ");
1968 iovlist_append(&il, hostname);
1969 iovlist_append(&il, " ");
1970 iovlist_append(&il, app_name == NULL ? "-" : app_name);
1971 iovlist_append(&il, " ");
1972 iovlist_append(&il, procid == NULL ? "-" : procid);
1973 iovlist_append(&il, " ");
1974 iovlist_append(&il, msgid == NULL ? "-" : msgid);
1975 iovlist_append(&il, " ");
1976 iovlist_append(&il, structured_data == NULL ? "-" : structured_data);
1977 iovlist_append(&il, " ");
1978 iovlist_append(&il, msg);
1979
1980 fprintlog_write(f, &il, flags);
1981 }
1982
1983 static void
fprintlog_rfc3164(struct filed * f,const char * hostname,const char * app_name,const char * procid,const char * msg,int flags)1984 fprintlog_rfc3164(struct filed *f, const char *hostname, const char *app_name,
1985 const char *procid, const char *msg, int flags)
1986 {
1987 struct iovlist il;
1988 const CODE *c;
1989 int facility, priority;
1990 char timebuf[RFC3164_DATELEN + 1], facility_number[5],
1991 priority_number[5];
1992 bool facility_found, priority_found;
1993
1994 if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT,
1995 &f->f_lasttime.tm) == 0)
1996 timebuf[0] = '\0';
1997
1998 iovlist_init(&il);
1999 switch (f->f_type) {
2000 case F_FORW:
2001 /* Message forwarded over the network. */
2002 iovlist_append(&il, "<");
2003 snprintf(priority_number, sizeof(priority_number), "%d",
2004 f->f_prevpri);
2005 iovlist_append(&il, priority_number);
2006 iovlist_append(&il, ">");
2007 iovlist_append(&il, timebuf);
2008 if (output_format == FORMAT_RFC3164_STRICT) {
2009 iovlist_append(&il, " ");
2010 iovlist_append(&il, hostname);
2011 } else if (strcasecmp(hostname, LocalHostName) != 0) {
2012 iovlist_append(&il, " Forwarded from ");
2013 iovlist_append(&il, hostname);
2014 iovlist_append(&il, ":");
2015 }
2016 iovlist_append(&il, " ");
2017 break;
2018
2019 case F_WALL:
2020 /* Message written to terminals. */
2021 iovlist_append(&il, "\r\n\aMessage from syslogd@");
2022 iovlist_append(&il, hostname);
2023 iovlist_append(&il, " at ");
2024 iovlist_append(&il, timebuf);
2025 iovlist_append(&il, " ...\r\n");
2026 break;
2027
2028 default:
2029 /* Message written to files. */
2030 iovlist_append(&il, timebuf);
2031 iovlist_append(&il, " ");
2032
2033 if (LogFacPri) {
2034 iovlist_append(&il, "<");
2035
2036 facility = f->f_prevpri & LOG_FACMASK;
2037 facility_found = false;
2038 if (LogFacPri > 1) {
2039 for (c = facilitynames; c->c_name; c++) {
2040 if (c->c_val == facility) {
2041 iovlist_append(&il, c->c_name);
2042 facility_found = true;
2043 break;
2044 }
2045 }
2046 }
2047 if (!facility_found) {
2048 snprintf(facility_number,
2049 sizeof(facility_number), "%d",
2050 LOG_FAC(facility));
2051 iovlist_append(&il, facility_number);
2052 }
2053
2054 iovlist_append(&il, ".");
2055
2056 priority = LOG_PRI(f->f_prevpri);
2057 priority_found = false;
2058 if (LogFacPri > 1) {
2059 for (c = prioritynames; c->c_name; c++) {
2060 if (c->c_val == priority) {
2061 iovlist_append(&il, c->c_name);
2062 priority_found = true;
2063 break;
2064 }
2065 }
2066 }
2067 if (!priority_found) {
2068 snprintf(priority_number,
2069 sizeof(priority_number), "%d", priority);
2070 iovlist_append(&il, priority_number);
2071 }
2072
2073 iovlist_append(&il, "> ");
2074 }
2075
2076 iovlist_append(&il, hostname);
2077 iovlist_append(&il, " ");
2078 break;
2079 }
2080
2081 /* Message body with application name and process ID prefixed. */
2082 if (app_name != NULL) {
2083 iovlist_append(&il, app_name);
2084 if (procid != NULL) {
2085 iovlist_append(&il, "[");
2086 iovlist_append(&il, procid);
2087 iovlist_append(&il, "]");
2088 }
2089 iovlist_append(&il, ": ");
2090 }
2091 iovlist_append(&il, msg);
2092
2093 fprintlog_write(f, &il, flags);
2094 }
2095
2096 static void
fprintlog_first(struct filed * f,const char * hostname,const char * app_name,const char * procid,const char * msgid __unused,const char * structured_data __unused,const char * msg,int flags)2097 fprintlog_first(struct filed *f, const char *hostname, const char *app_name,
2098 const char *procid, const char *msgid __unused,
2099 const char *structured_data __unused, const char *msg, int flags)
2100 {
2101
2102 dprintf("Logging to %s", TypeNames[f->f_type]);
2103 f->f_time = now;
2104 f->f_prevcount = 0;
2105 if (f->f_type == F_UNUSED) {
2106 dprintf("\n");
2107 return;
2108 }
2109
2110 if (IS_RFC3164_FORMAT)
2111 fprintlog_rfc3164(f, hostname, app_name, procid, msg, flags);
2112 else
2113 fprintlog_rfc5424(f, hostname, app_name, procid, msgid,
2114 structured_data, msg, flags);
2115 }
2116
2117 /*
2118 * Prints a message to a log file that the previously logged message was
2119 * received multiple times.
2120 */
2121 static void
fprintlog_successive(struct filed * f,int flags)2122 fprintlog_successive(struct filed *f, int flags)
2123 {
2124 char msg[100];
2125
2126 assert(f->f_prevcount > 0);
2127 snprintf(msg, sizeof(msg), "last message repeated %d times",
2128 f->f_prevcount);
2129 fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg,
2130 flags);
2131 }
2132
2133 /*
2134 * WALLMSG -- Write a message to the world at large
2135 *
2136 * Write the specified message to either the entire
2137 * world, or a list of approved users.
2138 *
2139 * Note: This function is wrapped by cap_wallmsg() when Capsicum support is
2140 * enabled so ttymsg() can be called.
2141 */
2142 void
wallmsg(const struct filed * f,struct iovec * iov,const int iovlen)2143 wallmsg(const struct filed *f, struct iovec *iov, const int iovlen)
2144 {
2145 static int reenter; /* avoid calling ourselves */
2146 struct utmpx *ut;
2147 int i;
2148 const char *p;
2149
2150 if (reenter++)
2151 return;
2152 setutxent();
2153 /* NOSTRICT */
2154 while ((ut = getutxent()) != NULL) {
2155 if (ut->ut_type != USER_PROCESS)
2156 continue;
2157 if (f->f_type == F_WALL) {
2158 if ((p = ttymsg(iov, iovlen, ut->ut_line,
2159 TTYMSGTIME)) != NULL)
2160 dprintf("%s\n", p);
2161 continue;
2162 }
2163 /* should we send the message to this user? */
2164 for (i = 0; i < MAXUNAMES; i++) {
2165 if (!f->f_uname[i][0])
2166 break;
2167 if (!strcmp(f->f_uname[i], ut->ut_user)) {
2168 if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
2169 TTYMSGTIME)) != NULL)
2170 dprintf("%s\n", p);
2171 break;
2172 }
2173 }
2174 }
2175 endutxent();
2176 reenter = 0;
2177 }
2178
2179 /*
2180 * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
2181 */
2182 static const char *
ttymsg_check(struct iovec * iov,int iovcnt,char * line,int tmout)2183 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
2184 {
2185 static char device[1024];
2186 static char errbuf[1024];
2187 struct stat sb;
2188
2189 (void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
2190
2191 if (stat(device, &sb) < 0) {
2192 (void) snprintf(errbuf, sizeof(errbuf),
2193 "%s: %s", device, strerror(errno));
2194 return (errbuf);
2195 }
2196 if ((sb.st_mode & S_IWGRP) == 0)
2197 /* Messages disabled. */
2198 return (NULL);
2199 return (ttymsg(iov, iovcnt, line, tmout));
2200 }
2201
2202 /*
2203 * Return a printable representation of a host address.
2204 */
2205 static const char *
cvthname(struct sockaddr * f)2206 cvthname(struct sockaddr *f)
2207 {
2208 int error, hl;
2209 static char hname[NI_MAXHOST], ip[NI_MAXHOST];
2210
2211 dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
2212 error = cap_getnameinfo(cap_net, f, f->sa_len, ip, sizeof(ip), NULL, 0,
2213 NI_NUMERICHOST);
2214 if (error) {
2215 dprintf("Malformed from address %s\n", gai_strerror(error));
2216 return ("???");
2217 }
2218 dprintf("cvthname(%s)\n", ip);
2219
2220 if (!resolve)
2221 return (ip);
2222
2223 error = cap_getnameinfo(cap_net, f, f->sa_len, hname, sizeof(hname),
2224 NULL, 0, NI_NAMEREQD);
2225 if (error) {
2226 dprintf("Host name for your address (%s) unknown\n", ip);
2227 return (ip);
2228 }
2229 hl = strlen(hname);
2230 if (hl > 0 && hname[hl-1] == '.')
2231 hname[--hl] = '\0';
2232 /* RFC 5424 prefers logging FQDNs. */
2233 if (IS_RFC3164_FORMAT)
2234 trimdomain(hname, hl);
2235 return (hname);
2236 }
2237
2238 /*
2239 * Print syslogd errors some place.
2240 */
2241 void
logerror(const char * msg)2242 logerror(const char *msg)
2243 {
2244 char buf[512];
2245 static int recursed = 0;
2246
2247 /* If there's an error while trying to log an error, give up. */
2248 if (recursed)
2249 return;
2250 recursed++;
2251 if (errno != 0) {
2252 (void)snprintf(buf, sizeof(buf), "%s: %s", msg,
2253 strerror(errno));
2254 msg = buf;
2255 }
2256 errno = 0;
2257 dprintf("%s\n", msg);
2258 logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL,
2259 NULL, msg, 0);
2260 recursed--;
2261 }
2262
2263 static void
die(int signo)2264 die(int signo)
2265 {
2266 struct filed *f;
2267 struct socklist *sl;
2268 char buf[100];
2269
2270 STAILQ_FOREACH(f, &fhead, next) {
2271 /* flush any pending output */
2272 if (f->f_prevcount)
2273 fprintlog_successive(f, 0);
2274 /* terminate existing pipe processes */
2275 if (f->f_type == F_PIPE)
2276 close_filed(f);
2277 }
2278 if (signo) {
2279 dprintf("syslogd: exiting on signal %d\n", signo);
2280 (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
2281 errno = 0;
2282 logerror(buf);
2283 }
2284 STAILQ_FOREACH(sl, &shead, next) {
2285 if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL) {
2286 if (unlinkat(sl->sl_dirfd, sl->sl_name, 0) == -1) {
2287 dprintf("Failed to unlink %s: %s", sl->sl_name,
2288 strerror(errno));
2289 }
2290 }
2291 }
2292 pidfile_remove(pfh);
2293
2294 exit(1);
2295 }
2296
2297 static int
configfiles(const struct dirent * dp)2298 configfiles(const struct dirent *dp)
2299 {
2300 const char *p;
2301 size_t ext_len;
2302
2303 if (dp->d_name[0] == '.')
2304 return (0);
2305
2306 ext_len = sizeof(include_ext) -1;
2307
2308 if (dp->d_namlen <= ext_len)
2309 return (0);
2310
2311 p = &dp->d_name[dp->d_namlen - ext_len];
2312 if (strcmp(p, include_ext) != 0)
2313 return (0);
2314
2315 return (1);
2316 }
2317
2318 static nvlist_t *
parseconfigfile(FILE * cf,bool allow_includes,nvlist_t * nvl_conf)2319 parseconfigfile(FILE *cf, bool allow_includes, nvlist_t *nvl_conf)
2320 {
2321 FILE *cf2;
2322 struct dirent **ent;
2323 char cline[LINE_MAX];
2324 char host[MAXHOSTNAMELEN];
2325 char prog[LINE_MAX];
2326 char file[MAXPATHLEN];
2327 char pfilter[LINE_MAX];
2328 char *p, *tmp;
2329 int i, nents;
2330 size_t include_len;
2331
2332 /*
2333 * Foreach line in the conf table, open that file.
2334 */
2335 include_len = sizeof(include_str) - 1;
2336 (void)strlcpy(host, "*", sizeof(host));
2337 (void)strlcpy(prog, "*", sizeof(prog));
2338 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2339 while (fgets(cline, sizeof(cline), cf) != NULL) {
2340 /*
2341 * check for end-of-section, comments, strip off trailing
2342 * spaces and newline character. #!prog is treated specially:
2343 * following lines apply only to that program.
2344 */
2345 for (p = cline; isspace(*p); ++p)
2346 continue;
2347 if (*p == '\0')
2348 continue;
2349 if (allow_includes &&
2350 strncmp(p, include_str, include_len) == 0 &&
2351 isspace(p[include_len])) {
2352 p += include_len;
2353 while (isspace(*p))
2354 p++;
2355 tmp = p;
2356 while (*tmp != '\0' && !isspace(*tmp))
2357 tmp++;
2358 *tmp = '\0';
2359 dprintf("Trying to include files in '%s'\n", p);
2360 nents = scandir(p, &ent, configfiles, alphasort);
2361 if (nents == -1) {
2362 dprintf("Unable to open '%s': %s\n", p,
2363 strerror(errno));
2364 continue;
2365 }
2366 for (i = 0; i < nents; i++) {
2367 if (snprintf(file, sizeof(file), "%s/%s", p,
2368 ent[i]->d_name) >= (int)sizeof(file)) {
2369 dprintf("ignoring path too long: "
2370 "'%s/%s'\n", p, ent[i]->d_name);
2371 free(ent[i]);
2372 continue;
2373 }
2374 free(ent[i]);
2375 cf2 = fopen(file, "r");
2376 if (cf2 == NULL)
2377 continue;
2378 dprintf("reading %s\n", file);
2379 parseconfigfile(cf2, false, nvl_conf);
2380 fclose(cf2);
2381 }
2382 free(ent);
2383 continue;
2384 }
2385 if (*p == '#') {
2386 p++;
2387 if (*p == '\0' || strchr("!+-:", *p) == NULL)
2388 continue;
2389 }
2390 if (*p == '+' || *p == '-') {
2391 host[0] = *p++;
2392 while (isspace(*p))
2393 p++;
2394 if (*p == '\0' || *p == '*') {
2395 (void)strlcpy(host, "*", sizeof(host));
2396 continue;
2397 }
2398 if (*p == '@')
2399 p = LocalHostName;
2400 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
2401 if (!isalnum(*p) && *p != '.' && *p != '-'
2402 && *p != ',' && *p != ':' && *p != '%')
2403 break;
2404 host[i] = *p++;
2405 }
2406 host[i] = '\0';
2407 continue;
2408 }
2409 if (*p == '!') {
2410 p++;
2411 while (isspace(*p))
2412 p++;
2413 if (*p == '\0' || *p == '*') {
2414 (void)strlcpy(prog, "*", sizeof(prog));
2415 continue;
2416 }
2417 for (i = 0; i < LINE_MAX - 1; i++) {
2418 if (!isprint(p[i]) || isspace(p[i]))
2419 break;
2420 prog[i] = p[i];
2421 }
2422 prog[i] = '\0';
2423 continue;
2424 }
2425 if (*p == ':') {
2426 p++;
2427 while (isspace(*p))
2428 p++;
2429 if (*p == '\0' || *p == '*') {
2430 (void)strlcpy(pfilter, "*", sizeof(pfilter));
2431 continue;
2432 }
2433 (void)strlcpy(pfilter, p, sizeof(pfilter));
2434 continue;
2435 }
2436 for (p = cline + 1; *p != '\0'; p++) {
2437 if (*p != '#')
2438 continue;
2439 if (*(p - 1) == '\\') {
2440 strcpy(p - 1, p);
2441 p--;
2442 continue;
2443 }
2444 *p = '\0';
2445 break;
2446 }
2447 for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
2448 cline[i] = '\0';
2449 cfline(nvl_conf, cline, prog, host, pfilter);
2450
2451 }
2452 return (nvl_conf);
2453 }
2454
2455 /*
2456 * Read configuration file and create filed entries for each line.
2457 *
2458 * Note: This function is wrapped by cap_readconfigfile() when Capsicum
2459 * support is enabled so resources can be acquired outside of the security
2460 * sandbox.
2461 */
2462 nvlist_t *
readconfigfile(const char * path)2463 readconfigfile(const char *path)
2464 {
2465 FILE *cf;
2466 nvlist_t *nvl_conf = nvlist_create(0);
2467
2468 if ((cf = fopen(path, "r")) != NULL) {
2469 nvl_conf = parseconfigfile(cf, true, nvl_conf);
2470 (void)fclose(cf);
2471 } else {
2472 dprintf("cannot open %s\n", path);
2473 cfline(nvl_conf, "*.ERR\t/dev/console", "*", "*", "*");
2474 cfline(nvl_conf, "*.PANIC\t*", "*", "*", "*");
2475 }
2476 return (nvl_conf);
2477 }
2478
2479 static void
fill_flist(nvlist_t * nvl_conf)2480 fill_flist(nvlist_t *nvl_conf)
2481 {
2482 const nvlist_t * const *filed_list;
2483 size_t nfileds;
2484
2485 if (!nvlist_exists_nvlist_array(nvl_conf, "filed_list"))
2486 return;
2487 filed_list = nvlist_get_nvlist_array(nvl_conf, "filed_list",
2488 &nfileds);
2489 for (size_t i = 0; i < nfileds; ++i) {
2490 struct filed *f;
2491
2492 f = nvlist_to_filed(filed_list[i]);
2493 STAILQ_INSERT_TAIL(&fhead, f, next);
2494 }
2495 nvlist_destroy(nvl_conf);
2496 }
2497
2498 /*
2499 * Close all open log files.
2500 */
2501 void
closelogfiles(void)2502 closelogfiles(void)
2503 {
2504 struct filed *f;
2505
2506 while (!STAILQ_EMPTY(&fhead)) {
2507 f = STAILQ_FIRST(&fhead);
2508 STAILQ_REMOVE_HEAD(&fhead, next);
2509
2510 /* flush any pending output */
2511 if (f->f_prevcount)
2512 fprintlog_successive(f, 0);
2513
2514 switch (f->f_type) {
2515 case F_FILE:
2516 case F_FORW:
2517 case F_CONSOLE:
2518 case F_TTY:
2519 close_filed(f);
2520 break;
2521 case F_PIPE:
2522 if (f->f_procdesc != -1) {
2523 struct kevent ev;
2524 /*
2525 * This filed is going to be freed.
2526 * Delete procdesc kevents that reference it.
2527 */
2528 EV_SET(&ev, f->f_procdesc, EVFILT_PROCDESC,
2529 EV_DELETE, NOTE_EXIT, 0, f);
2530 if (kevent(kq, &ev, 1, NULL, 0, NULL) == -1) {
2531 logerror("failed to delete procdesc"
2532 "kevent");
2533 exit(1);
2534 }
2535 }
2536 close_filed(f);
2537 break;
2538 default:
2539 break;
2540 }
2541
2542 if (f->f_prop_filter) {
2543 switch (f->f_prop_filter->cmp_type) {
2544 case FILT_CMP_REGEX:
2545 regfree(f->f_prop_filter->pflt_re);
2546 free(f->f_prop_filter->pflt_re);
2547 /* FALLTHROUGH */
2548 case FILT_CMP_CONTAINS:
2549 case FILT_CMP_EQUAL:
2550 case FILT_CMP_STARTS:
2551 free(f->f_prop_filter->pflt_strval);
2552 break;
2553 }
2554 free(f->f_prop_filter);
2555 }
2556 free(f);
2557 }
2558 }
2559
2560 static void
syslogd_cap_enter(void)2561 syslogd_cap_enter(void)
2562 {
2563 #ifdef WITH_CASPER
2564 cap_channel_t *cap_casper;
2565 cap_net_limit_t *limit;
2566
2567 cap_casper = cap_init();
2568 if (cap_casper == NULL)
2569 err(1, "Failed to communicate with libcasper");
2570 cap_syslogd = cap_service_open(cap_casper, "syslogd.casper");
2571 if (cap_syslogd == NULL)
2572 err(1, "Failed to open the syslogd.casper libcasper service");
2573 cap_net = cap_service_open(cap_casper, "system.net");
2574 if (cap_syslogd == NULL)
2575 err(1, "Failed to open the system.net libcasper service");
2576 cap_close(cap_casper);
2577 limit = cap_net_limit_init(cap_net,
2578 CAPNET_ADDR2NAME | CAPNET_NAME2ADDR);
2579 if (limit == NULL)
2580 err(1, "Failed to create system.net limits");
2581 if (cap_net_limit(limit) == -1)
2582 err(1, "Failed to apply system.net limits");
2583 caph_cache_tzdata();
2584 caph_cache_catpages();
2585 if (caph_enter_casper() == -1)
2586 err(1, "Failed to enter capability mode");
2587 #endif
2588 }
2589
2590 /*
2591 * INIT -- Initialize syslogd from configuration table
2592 */
2593 static void
init(bool reload)2594 init(bool reload)
2595 {
2596 int i;
2597 char *p;
2598 char oldLocalHostName[MAXHOSTNAMELEN];
2599 char hostMsg[2*MAXHOSTNAMELEN+40];
2600 char bootfileMsg[MAXLINE + 1];
2601
2602 dprintf("init\n");
2603
2604 /*
2605 * Load hostname (may have changed).
2606 */
2607 if (reload)
2608 (void)strlcpy(oldLocalHostName, LocalHostName,
2609 sizeof(oldLocalHostName));
2610 if (gethostname(LocalHostName, sizeof(LocalHostName)))
2611 err(EX_OSERR, "gethostname() failed");
2612 if ((p = strchr(LocalHostName, '.')) != NULL) {
2613 /* RFC 5424 prefers logging FQDNs. */
2614 if (IS_RFC3164_FORMAT)
2615 *p = '\0';
2616 LocalDomain = p + 1;
2617 } else {
2618 LocalDomain = "";
2619 }
2620
2621 #ifndef WITH_CASPER
2622 /*
2623 * XXX: Disable when running in capability mode, for now.
2624 * This requires a new interface in the tzcode module to
2625 * get running without capability violations.
2626 *
2627 * Load / reload timezone data (in case it changed).
2628 *
2629 * Just calling tzset() again does not work, the timezone code
2630 * caches the result. However, by setting the TZ variable, one
2631 * can defeat the caching and have the timezone code really
2632 * reload the timezone data. Respect any initial setting of
2633 * TZ, in case the system is configured specially.
2634 */
2635 dprintf("loading timezone data via tzset()\n");
2636 if (getenv("TZ")) {
2637 tzset();
2638 } else {
2639 setenv("TZ", ":/etc/localtime", 1);
2640 tzset();
2641 unsetenv("TZ");
2642 }
2643 #endif
2644
2645 if (!reload) {
2646 struct tm tm;
2647 /* Cache time files before entering capability mode. */
2648 timegm(&tm);
2649 syslogd_cap_enter();
2650 }
2651
2652 Initialized = false;
2653 closelogfiles();
2654 fill_flist(cap_readconfigfile(cap_syslogd, ConfFile));
2655 Initialized = true;
2656
2657 if (Debug) {
2658 struct filed *f;
2659 int port;
2660
2661 STAILQ_FOREACH(f, &fhead, next) {
2662 for (i = 0; i <= LOG_NFACILITIES; i++)
2663 if (f->f_pmask[i] == INTERNAL_NOPRI)
2664 printf("X ");
2665 else
2666 printf("%d ", f->f_pmask[i]);
2667 printf("%s: ", TypeNames[f->f_type]);
2668 switch (f->f_type) {
2669 case F_FILE:
2670 printf("%s", f->f_fname);
2671 break;
2672
2673 case F_CONSOLE:
2674 case F_TTY:
2675 printf("%s%s", _PATH_DEV, f->f_fname);
2676 break;
2677
2678 case F_FORW: {
2679 int domain, sockfd = f->f_addr_fds[0];
2680 socklen_t len = sizeof(domain);
2681
2682 if (getsockopt(sockfd, SOL_SOCKET, SO_DOMAIN,
2683 &domain, &len) < 0)
2684 err(1, "getsockopt");
2685
2686 switch (domain) {
2687 #ifdef INET
2688 case AF_INET: {
2689 struct sockaddr_in sin;
2690
2691 len = sizeof(sin);
2692 if (getpeername(sockfd, (struct sockaddr *)&sin, &len) < 0)
2693 err(1, "getpeername");
2694 port = ntohs(sin.sin_port);
2695 break;
2696 }
2697 #endif
2698 #ifdef INET6
2699 case AF_INET6: {
2700 struct sockaddr_in6 sin6;
2701
2702 len = sizeof(sin6);
2703 if (getpeername(sockfd, (struct sockaddr *)&sin6, &len) < 0)
2704 err(1, "getpeername");
2705 port = ntohs(sin6.sin6_port);
2706 break;
2707 }
2708 #endif
2709 default:
2710 port = 0;
2711 }
2712 if (port != 514) {
2713 printf("%s:%d", f->f_hname, port);
2714 } else {
2715 printf("%s", f->f_hname);
2716 }
2717 break;
2718 }
2719
2720 case F_PIPE:
2721 printf("%s", f->f_pname);
2722 break;
2723
2724 case F_USERS:
2725 for (i = 0; i < MAXUNAMES && *f->f_uname[i]; i++)
2726 printf("%s, ", f->f_uname[i]);
2727 break;
2728 default:
2729 break;
2730 }
2731 if (*f->f_program != '\0')
2732 printf(" (%s)", f->f_program);
2733 printf("\n");
2734 }
2735 }
2736
2737 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL,
2738 NULL, NULL, "restart", 0);
2739 dprintf("syslogd: restarted\n");
2740 /*
2741 * Log a change in hostname, but only on reload.
2742 */
2743 if (reload && strcmp(oldLocalHostName, LocalHostName) != 0) {
2744 (void)snprintf(hostMsg, sizeof(hostMsg),
2745 "hostname changed, \"%s\" to \"%s\"",
2746 oldLocalHostName, LocalHostName);
2747 logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd",
2748 NULL, NULL, NULL, hostMsg, 0);
2749 dprintf("%s\n", hostMsg);
2750 }
2751 /*
2752 * Log the kernel boot file if we aren't going to use it as
2753 * the prefix, and if this is *not* a reload.
2754 */
2755 if (!reload && !use_bootfile) {
2756 (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2757 "kernel boot file is %s", bootfile);
2758 logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd",
2759 NULL, NULL, NULL, bootfileMsg, 0);
2760 dprintf("%s\n", bootfileMsg);
2761 }
2762 }
2763
2764 /*
2765 * Compile property-based filter.
2766 */
2767 static nvlist_t *
prop_filter_compile(const char * cfilter)2768 prop_filter_compile(const char *cfilter)
2769 {
2770 nvlist_t *nvl_pfilter;
2771 struct prop_filter pfilter = { };
2772 char *filter, *filter_endpos, *filter_begpos, *p;
2773 char **ap, *argv[2] = {NULL, NULL};
2774 int escaped;
2775
2776 filter = strdup(cfilter);
2777 if (filter == NULL)
2778 err(1, "strdup");
2779 filter_begpos = filter;
2780
2781 /*
2782 * Here's some filter examples mentioned in syslog.conf(5)
2783 * 'msg, contains, ".*Deny.*"'
2784 * 'programname, regex, "^bird6?$"'
2785 * 'hostname, icase_ereregex, "^server-(dcA|podB)-rack1[0-9]{2}\\..*"'
2786 */
2787
2788 /*
2789 * Split filter into 3 parts: property name (argv[0]),
2790 * cmp type (argv[1]) and lvalue for comparison (filter).
2791 */
2792 for (ap = argv; (*ap = strsep(&filter, ", \t\n")) != NULL;) {
2793 if (**ap != '\0')
2794 if (++ap >= &argv[2])
2795 break;
2796 }
2797
2798 if (argv[0] == NULL || argv[1] == NULL) {
2799 dprintf("filter parse error");
2800 goto error;
2801 }
2802
2803 /* fill in prop_type */
2804 if (strcasecmp(argv[0], "msg") == 0)
2805 pfilter.prop_type = FILT_PROP_MSG;
2806 else if (strcasecmp(argv[0], "hostname") == 0)
2807 pfilter.prop_type = FILT_PROP_HOSTNAME;
2808 else if (strcasecmp(argv[0], "source") == 0)
2809 pfilter.prop_type = FILT_PROP_HOSTNAME;
2810 else if (strcasecmp(argv[0], "programname") == 0)
2811 pfilter.prop_type = FILT_PROP_PROGNAME;
2812 else {
2813 dprintf("unknown property");
2814 goto error;
2815 }
2816
2817 /* full in cmp_flags (i.e. !contains, icase_regex, etc.) */
2818 if (*argv[1] == '!') {
2819 pfilter.cmp_flags |= FILT_FLAG_EXCLUDE;
2820 argv[1]++;
2821 }
2822 if (strncasecmp(argv[1], "icase_", (sizeof("icase_") - 1)) == 0) {
2823 pfilter.cmp_flags |= FILT_FLAG_ICASE;
2824 argv[1] += sizeof("icase_") - 1;
2825 }
2826
2827 /* fill in cmp_type */
2828 if (strcasecmp(argv[1], "contains") == 0)
2829 pfilter.cmp_type = FILT_CMP_CONTAINS;
2830 else if (strcasecmp(argv[1], "isequal") == 0)
2831 pfilter.cmp_type = FILT_CMP_EQUAL;
2832 else if (strcasecmp(argv[1], "startswith") == 0)
2833 pfilter.cmp_type = FILT_CMP_STARTS;
2834 else if (strcasecmp(argv[1], "regex") == 0)
2835 pfilter.cmp_type = FILT_CMP_REGEX;
2836 else if (strcasecmp(argv[1], "ereregex") == 0) {
2837 pfilter.cmp_type = FILT_CMP_REGEX;
2838 pfilter.cmp_flags |= REG_EXTENDED;
2839 } else {
2840 dprintf("unknown cmp function");
2841 goto error;
2842 }
2843
2844 /*
2845 * Handle filter value
2846 */
2847
2848 /* ' ".*Deny.*"' */
2849 /* remove leading whitespace and check for '"' next character */
2850 filter += strspn(filter, ", \t\n");
2851 if (*filter != '"' || strlen(filter) < 3) {
2852 dprintf("property value parse error");
2853 goto error;
2854 }
2855 filter++;
2856
2857 /* '.*Deny.*"' */
2858 /* process possible backslash (\") escaping */
2859 escaped = 0;
2860 filter_endpos = filter;
2861 for (p = filter; *p != '\0'; p++) {
2862 if (*p == '\\' && !escaped) {
2863 escaped = 1;
2864 /* do not shift filter_endpos */
2865 continue;
2866 }
2867 if (*p == '"' && !escaped) {
2868 p++;
2869 break;
2870 }
2871 /* we've seen some esc symbols, need to compress the line */
2872 if (filter_endpos != p)
2873 *filter_endpos = *p;
2874
2875 filter_endpos++;
2876 escaped = 0;
2877 }
2878
2879 *filter_endpos = '\0';
2880 /* '.*Deny.*' */
2881
2882 /* We should not have anything but whitespace left after closing '"' */
2883 if (*p != '\0' && strspn(p, " \t\n") != strlen(p)) {
2884 dprintf("property value parse error");
2885 goto error;
2886 }
2887
2888 pfilter.pflt_strval = filter;
2889 /* An nvlist is heap allocated heap here. */
2890 nvl_pfilter = prop_filter_to_nvlist(&pfilter);
2891
2892 free(filter_begpos);
2893 return (nvl_pfilter);
2894 error:
2895 free(filter_begpos);
2896 return (NULL);
2897 }
2898
2899 static const char *
parse_selector(const char * p,struct filed * f)2900 parse_selector(const char *p, struct filed *f)
2901 {
2902 int i, pri;
2903 int pri_done = 0, pri_cmp = 0, pri_invert = 0;
2904 char *bp, buf[LINE_MAX];
2905 const char *q;
2906
2907 /* find the end of this facility name list */
2908 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.';)
2909 continue;
2910
2911 /* get the priority comparison */
2912 if (*q == '!') {
2913 pri_invert = 1;
2914 q++;
2915 }
2916 while (!pri_done) {
2917 switch (*q) {
2918 case '<':
2919 pri_cmp |= PRI_LT;
2920 q++;
2921 break;
2922 case '=':
2923 pri_cmp |= PRI_EQ;
2924 q++;
2925 break;
2926 case '>':
2927 pri_cmp |= PRI_GT;
2928 q++;
2929 break;
2930 default:
2931 pri_done++;
2932 break;
2933 }
2934 }
2935
2936 /* collect priority name */
2937 for (bp = buf; *q != '\0' && !strchr("\t,; ", *q); )
2938 *bp++ = *q++;
2939 *bp = '\0';
2940
2941 /* skip cruft */
2942 while (strchr(",;", *q))
2943 q++;
2944
2945 /* decode priority name */
2946 if (*buf == '*') {
2947 pri = LOG_PRIMASK;
2948 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2949 } else {
2950 /* Ignore trailing spaces. */
2951 for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2952 buf[i] = '\0';
2953
2954 pri = decode(buf, prioritynames);
2955 if (pri < 0) {
2956 dprintf("unknown priority name \"%s\"", buf);
2957 return (NULL);
2958 }
2959 }
2960 if (!pri_cmp)
2961 pri_cmp = UniquePriority ? PRI_EQ : (PRI_EQ | PRI_GT);
2962 if (pri_invert)
2963 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2964
2965 /* scan facilities */
2966 while (*p != '\0' && !strchr("\t.; ", *p)) {
2967 for (bp = buf; *p != '\0' && !strchr("\t,;. ", *p); )
2968 *bp++ = *p++;
2969 *bp = '\0';
2970
2971 if (*buf == '*') {
2972 for (i = 0; i < LOG_NFACILITIES; i++) {
2973 f->f_pmask[i] = pri;
2974 f->f_pcmp[i] = pri_cmp;
2975 }
2976 } else {
2977 i = decode(buf, facilitynames);
2978 if (i < 0) {
2979 dprintf("unknown facility name \"%s\"", buf);
2980 return (NULL);
2981 }
2982 f->f_pmask[i >> 3] = pri;
2983 f->f_pcmp[i >> 3] = pri_cmp;
2984 }
2985 while (*p == ',' || *p == ' ')
2986 p++;
2987 }
2988 return (q);
2989 }
2990
2991 static int
maybe_dup_forw_socket(const nvlist_t * nvl,const struct sockaddr * rsa,const struct sockaddr * lsa)2992 maybe_dup_forw_socket(const nvlist_t *nvl, const struct sockaddr *rsa,
2993 const struct sockaddr *lsa)
2994 {
2995 const nvlist_t * const *line;
2996 size_t linecount;
2997
2998 if (!nvlist_exists_nvlist_array(nvl, "filed_list"))
2999 return (-1);
3000 line = nvlist_get_nvlist_array(nvl, "filed_list", &linecount);
3001 for (size_t i = 0; i < linecount; i++) {
3002 const struct forw_addr *forw;
3003 const int *fdp;
3004 size_t fdc;
3005
3006 if (nvlist_get_number(line[i], "f_type") != F_FORW)
3007 continue;
3008 fdp = nvlist_get_descriptor_array(line[i], "f_addr_fds", &fdc);
3009 forw = nvlist_get_binary(line[i], "f_addrs", NULL);
3010 for (size_t j = 0; j < fdc; j++) {
3011 int fd;
3012
3013 if (memcmp(&forw[j].raddr, rsa, rsa->sa_len) != 0 ||
3014 memcmp(&forw[j].laddr, lsa, lsa->sa_len) != 0)
3015 continue;
3016
3017 fd = dup(fdp[j]);
3018 if (fd < 0)
3019 err(1, "dup");
3020 return (fd);
3021 }
3022 }
3023
3024 return (-1);
3025 }
3026
3027 /*
3028 * Create a UDP socket that will forward messages from "lai" to "ai".
3029 * Capsicum doesn't permit connect() or sendto(), so we can't reuse the (bound)
3030 * sockets used to listen for messages.
3031 */
3032 static int
make_forw_socket(const nvlist_t * nvl,struct addrinfo * ai,struct addrinfo * lai)3033 make_forw_socket(const nvlist_t *nvl, struct addrinfo *ai, struct addrinfo *lai)
3034 {
3035 int s;
3036
3037 s = socket(ai->ai_family, ai->ai_socktype, 0);
3038 if (s < 0)
3039 err(1, "socket");
3040 if (lai != NULL) {
3041 if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &(int){1},
3042 sizeof(int)) < 0)
3043 err(1, "setsockopt");
3044 if (bind(s, lai->ai_addr, lai->ai_addrlen) < 0)
3045 err(1, "bind");
3046 }
3047 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
3048 if (errno == EADDRINUSE && lai != NULL) {
3049 int s1;
3050
3051 s1 = maybe_dup_forw_socket(nvl, ai->ai_addr,
3052 lai->ai_addr);
3053 if (s1 < 0)
3054 errc(1, EADDRINUSE, "connect");
3055 (void)close(s);
3056 s = s1;
3057 } else {
3058 err(1, "connect");
3059 }
3060 }
3061 /* Make it a write-only socket. */
3062 if (shutdown(s, SHUT_RD) < 0)
3063 err(1, "shutdown");
3064
3065 return (s);
3066 }
3067
3068 static void
make_forw_socket_array(const nvlist_t * nvl,struct filed * f,struct addrinfo * res)3069 make_forw_socket_array(const nvlist_t *nvl, struct filed *f,
3070 struct addrinfo *res)
3071 {
3072 struct addrinfo *ai;
3073 size_t i;
3074
3075 f->f_num_addr_fds = 0;
3076
3077 /* How many sockets do we need? */
3078 for (ai = res; ai != NULL; ai = ai->ai_next) {
3079 struct socklist *boundsock;
3080 int count;
3081
3082 count = 0;
3083 STAILQ_FOREACH(boundsock, &shead, next) {
3084 if (boundsock->sl_ai.ai_family == ai->ai_family)
3085 count++;
3086 }
3087 if (count == 0)
3088 count = 1;
3089 f->f_num_addr_fds += count;
3090 }
3091
3092 f->f_addr_fds = calloc(f->f_num_addr_fds, sizeof(*f->f_addr_fds));
3093 f->f_addrs = calloc(f->f_num_addr_fds, sizeof(*f->f_addrs));
3094 if (f->f_addr_fds == NULL || f->f_addrs == NULL)
3095 err(1, "malloc failed");
3096
3097 /*
3098 * Create our forwarding sockets: for each bound socket
3099 * belonging to the destination address, create one socket
3100 * connected to the destination and bound to the address of the
3101 * listening socket.
3102 */
3103 i = 0;
3104 for (ai = res; ai != NULL; ai = ai->ai_next) {
3105 struct socklist *boundsock;
3106 int count;
3107
3108 count = 0;
3109 STAILQ_FOREACH(boundsock, &shead, next) {
3110 if (boundsock->sl_ai.ai_family ==
3111 ai->ai_family) {
3112 memcpy(&f->f_addrs[i].raddr, ai->ai_addr,
3113 ai->ai_addrlen);
3114 memcpy(&f->f_addrs[i].laddr,
3115 boundsock->sl_ai.ai_addr,
3116 boundsock->sl_ai.ai_addrlen);
3117 f->f_addr_fds[i++] = make_forw_socket(nvl, ai,
3118 &boundsock->sl_ai);
3119 count++;
3120 }
3121 }
3122 if (count == 0) {
3123 memcpy(&f->f_addrs[i].raddr, ai->ai_addr,
3124 ai->ai_addrlen);
3125 f->f_addr_fds[i++] = make_forw_socket(nvl, ai, NULL);
3126 }
3127 }
3128 assert(i == f->f_num_addr_fds);
3129 }
3130
3131 static void
parse_action(const nvlist_t * nvl,const char * p,struct filed * f)3132 parse_action(const nvlist_t *nvl, const char *p, struct filed *f)
3133 {
3134 struct addrinfo hints, *res;
3135 size_t i;
3136 int error;
3137 const char *q;
3138 bool syncfile;
3139
3140 if (*p == '-') {
3141 syncfile = false;
3142 p++;
3143 } else
3144 syncfile = true;
3145
3146 f->f_file = -1;
3147 switch (*p) {
3148 case '@':
3149 {
3150 char *tp;
3151 char endkey = ':';
3152 /*
3153 * scan forward to see if there is a port defined.
3154 * so we can't use strlcpy..
3155 */
3156 i = sizeof(f->f_hname);
3157 tp = f->f_hname;
3158 p++;
3159
3160 /*
3161 * an ipv6 address should start with a '[' in that case
3162 * we should scan for a ']'
3163 */
3164 if (*p == '[') {
3165 p++;
3166 endkey = ']';
3167 }
3168 while (*p && (*p != endkey) && (i-- > 0)) {
3169 *tp++ = *p++;
3170 }
3171 if (endkey == ']' && *p == endkey)
3172 p++;
3173 *tp = '\0';
3174 }
3175 /* See if we copied a domain and have a port */
3176 if (*p == ':')
3177 p++;
3178 else
3179 p = NULL;
3180
3181 hints = (struct addrinfo){
3182 .ai_family = family,
3183 .ai_socktype = SOCK_DGRAM
3184 };
3185 error = getaddrinfo(f->f_hname, p ? p : "syslog", &hints, &res);
3186 if (error) {
3187 dprintf("%s\n", gai_strerror(error));
3188 break;
3189 }
3190 make_forw_socket_array(nvl, f, res);
3191 freeaddrinfo(res);
3192 f->f_type = F_FORW;
3193 break;
3194
3195 case '/':
3196 if ((f->f_file = open(p, logflags, 0600)) < 0) {
3197 f->f_type = F_UNUSED;
3198 dprintf("%s\n", p);
3199 break;
3200 }
3201 if (syncfile)
3202 f->f_flags |= FFLAG_SYNC;
3203 if (isatty(f->f_file)) {
3204 if (strcmp(p, _PATH_CONSOLE) == 0)
3205 f->f_type = F_CONSOLE;
3206 else
3207 f->f_type = F_TTY;
3208 (void)strlcpy(f->f_fname, p + sizeof(_PATH_DEV) - 1,
3209 sizeof(f->f_fname));
3210 } else {
3211 (void)strlcpy(f->f_fname, p, sizeof(f->f_fname));
3212 f->f_type = F_FILE;
3213 }
3214 break;
3215
3216 case '|':
3217 f->f_procdesc = -1;
3218 (void)strlcpy(f->f_pname, p + 1, sizeof(f->f_pname));
3219 f->f_type = F_PIPE;
3220 break;
3221
3222 case '*':
3223 f->f_type = F_WALL;
3224 break;
3225
3226 default:
3227 for (i = 0; i < MAXUNAMES && *p; i++) {
3228 for (q = p; *q && *q != ','; )
3229 q++;
3230 (void)strncpy(f->f_uname[i], p, MAXLOGNAME - 1);
3231 if ((q - p) >= MAXLOGNAME)
3232 f->f_uname[i][MAXLOGNAME - 1] = '\0';
3233 else
3234 f->f_uname[i][q - p] = '\0';
3235 while (*q == ',' || *q == ' ')
3236 q++;
3237 p = q;
3238 }
3239 f->f_type = F_USERS;
3240 break;
3241 }
3242 }
3243
3244 /*
3245 * Convert a configuration file line to an nvlist and add to "nvl", which
3246 * contains all of the log configuration processed thus far.
3247 */
3248 static void
cfline(nvlist_t * nvl,const char * line,const char * prog,const char * host,const char * pfilter)3249 cfline(nvlist_t *nvl, const char *line, const char *prog, const char *host,
3250 const char *pfilter)
3251 {
3252 nvlist_t *nvl_filed;
3253 struct filed f = { };
3254 const char *p;
3255
3256 dprintf("cfline(\"%s\", f, \"%s\", \"%s\", \"%s\")\n", line, prog,
3257 host, pfilter);
3258
3259 for (int i = 0; i <= LOG_NFACILITIES; i++)
3260 f.f_pmask[i] = INTERNAL_NOPRI;
3261
3262 /* save hostname if any */
3263 if (host != NULL && *host != '*') {
3264 int hl;
3265
3266 strlcpy(f.f_host, host, sizeof(f.f_host));
3267 hl = strlen(f.f_host);
3268 if (hl > 0 && f.f_host[hl-1] == '.')
3269 f.f_host[--hl] = '\0';
3270 /* RFC 5424 prefers logging FQDNs. */
3271 if (IS_RFC3164_FORMAT)
3272 trimdomain(f.f_host, hl);
3273 }
3274
3275 /* save program name if any */
3276 if (prog != NULL && *prog != '*')
3277 strlcpy(f.f_program, prog, sizeof(f.f_program));
3278
3279 /* scan through the list of selectors */
3280 for (p = line; *p != '\0' && *p != '\t' && *p != ' ';)
3281 p = parse_selector(p, &f);
3282
3283 /* skip to action part */
3284 while (*p == '\t' || *p == ' ')
3285 p++;
3286 parse_action(nvl, p, &f);
3287
3288 /* An nvlist is heap allocated heap here. */
3289 nvl_filed = filed_to_nvlist(&f);
3290 close_filed(&f);
3291
3292 if (pfilter && *pfilter != '*') {
3293 nvlist_t *nvl_pfilter;
3294
3295 nvl_pfilter = prop_filter_compile(pfilter);
3296 if (nvl_pfilter == NULL)
3297 err(1, "filter compile error");
3298 nvlist_add_nvlist(nvl_filed, "f_prop_filter", nvl_pfilter);
3299 }
3300
3301 nvlist_append_nvlist_array(nvl, "filed_list", nvl_filed);
3302 nvlist_destroy(nvl_filed);
3303 }
3304
3305 /*
3306 * Decode a symbolic name to a numeric value
3307 */
3308 static int
decode(const char * name,const CODE * codetab)3309 decode(const char *name, const CODE *codetab)
3310 {
3311 const CODE *c;
3312 char *p, buf[40];
3313
3314 if (isdigit(*name))
3315 return (atoi(name));
3316
3317 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3318 if (isupper(*name))
3319 *p = tolower(*name);
3320 else
3321 *p = *name;
3322 }
3323 *p = '\0';
3324 for (c = codetab; c->c_name; c++)
3325 if (!strcmp(buf, c->c_name))
3326 return (c->c_val);
3327
3328 return (-1);
3329 }
3330
3331 static void
markit(void)3332 markit(void)
3333 {
3334 struct filed *f;
3335 struct deadq_entry *dq, *dq0;
3336
3337 now = time((time_t *)NULL);
3338 MarkSeq += TIMERINTVL;
3339 if (MarkSeq >= MarkInterval) {
3340 logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL,
3341 "-- MARK --", MARK);
3342 MarkSeq = 0;
3343 }
3344
3345 STAILQ_FOREACH(f, &fhead, next) {
3346 if (f->f_prevcount && now >= REPEATTIME(f)) {
3347 dprintf("flush %s: repeated %d times, %d sec.\n",
3348 TypeNames[f->f_type], f->f_prevcount,
3349 repeatinterval[f->f_repeatcount]);
3350 fprintlog_successive(f, 0);
3351 BACKOFF(f);
3352 }
3353 }
3354
3355 /* Walk the dead queue, and see if we should signal somebody. */
3356 TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
3357 switch (dq->dq_timeout) {
3358 case 0:
3359 /* Already signalled once, try harder now. */
3360 (void)pdkill(dq->dq_procdesc, SIGKILL);
3361 break;
3362
3363 case 1:
3364 (void)pdkill(dq->dq_procdesc, SIGTERM);
3365 /* FALLTHROUGH. */
3366 default:
3367 dq->dq_timeout--;
3368 }
3369 }
3370 (void)alarm(TIMERINTVL);
3371 }
3372
3373 /*
3374 * fork off and become a daemon, but wait for the child to come online
3375 * before returning to the parent, or we get disk thrashing at boot etc.
3376 */
3377 static int
waitdaemon(int maxwait)3378 waitdaemon(int maxwait)
3379 {
3380 struct pollfd pollfd;
3381 int events, pipefd[2], status;
3382 pid_t pid;
3383
3384 if (pipe(pipefd) == -1) {
3385 warn("failed to daemonize, pipe");
3386 die(0);
3387 }
3388 pid = fork();
3389 if (pid == -1) {
3390 warn("failed to daemonize, fork");
3391 die(0);
3392 } else if (pid > 0) {
3393 close(pipefd[1]);
3394 pollfd.fd = pipefd[0];
3395 pollfd.events = POLLHUP;
3396 events = poll(&pollfd, 1, maxwait * 1000);
3397 if (events == -1)
3398 err(1, "failed to daemonize, poll");
3399 else if (events == 0)
3400 errx(1, "timed out waiting for child");
3401 if (waitpid(pid, &status, WNOHANG) > 0) {
3402 if (WIFEXITED(status))
3403 errx(1, "child pid %d exited with return code %d",
3404 pid, WEXITSTATUS(status));
3405 if (WIFSIGNALED(status))
3406 errx(1, "child pid %d exited on signal %d%s",
3407 pid, WTERMSIG(status),
3408 WCOREDUMP(status) ? " (core dumped)" : "");
3409 }
3410 exit(0);
3411 }
3412 close(pipefd[0]);
3413 if (setsid() == -1) {
3414 warn("failed to daemonize, setsid");
3415 die(0);
3416 }
3417 (void)chdir("/");
3418 (void)dup2(nulldesc, STDIN_FILENO);
3419 (void)dup2(nulldesc, STDOUT_FILENO);
3420 (void)dup2(nulldesc, STDERR_FILENO);
3421 return (pipefd[1]);
3422 }
3423
3424 /*
3425 * Add `s' to the list of allowable peer addresses to accept messages
3426 * from.
3427 *
3428 * `s' is a string in the form:
3429 *
3430 * [*]domainname[:{servicename|portnumber|*}]
3431 *
3432 * or
3433 *
3434 * netaddr/maskbits[:{servicename|portnumber|*}]
3435 *
3436 * Returns false on error, true if the argument was valid.
3437 */
3438 static bool
3439 #if defined(INET) || defined(INET6)
allowaddr(char * s)3440 allowaddr(char *s)
3441 #else
3442 allowaddr(char *s __unused)
3443 #endif
3444 {
3445 #if defined(INET) || defined(INET6)
3446 char *cp1, *cp2;
3447 struct allowedpeer *ap;
3448 struct servent *se;
3449 int masklen = -1;
3450 struct addrinfo hints, *res = NULL;
3451 #ifdef INET
3452 in_addr_t *addrp, *maskp;
3453 #endif
3454 #ifdef INET6
3455 uint32_t *addr6p, *mask6p;
3456 #endif
3457 char ip[NI_MAXHOST];
3458
3459 ap = calloc(1, sizeof(*ap));
3460 if (ap == NULL)
3461 err(1, "malloc failed");
3462
3463 #ifdef INET6
3464 if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
3465 #endif
3466 cp1 = s;
3467 if ((cp1 = strrchr(cp1, ':'))) {
3468 /* service/port provided */
3469 *cp1++ = '\0';
3470 if (strlen(cp1) == 1 && *cp1 == '*')
3471 /* any port allowed */
3472 ap->port = 0;
3473 else if ((se = getservbyname(cp1, "udp"))) {
3474 ap->port = ntohs(se->s_port);
3475 } else {
3476 ap->port = strtol(cp1, &cp2, 0);
3477 /* port not numeric */
3478 if (*cp2 != '\0')
3479 goto err;
3480 }
3481 } else {
3482 if ((se = getservbyname("syslog", "udp")))
3483 ap->port = ntohs(se->s_port);
3484 else
3485 /* sanity, should not happen */
3486 ap->port = 514;
3487 }
3488
3489 if ((cp1 = strchr(s, '/')) != NULL &&
3490 strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
3491 *cp1 = '\0';
3492 if ((masklen = atoi(cp1 + 1)) < 0)
3493 goto err;
3494 }
3495 #ifdef INET6
3496 if (*s == '[') {
3497 cp2 = s + strlen(s) - 1;
3498 if (*cp2 == ']') {
3499 ++s;
3500 *cp2 = '\0';
3501 } else {
3502 cp2 = NULL;
3503 }
3504 } else {
3505 cp2 = NULL;
3506 }
3507 #endif
3508 hints = (struct addrinfo){
3509 .ai_family = PF_UNSPEC,
3510 .ai_socktype = SOCK_DGRAM,
3511 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3512 };
3513 if (getaddrinfo(s, NULL, &hints, &res) == 0) {
3514 ap->isnumeric = true;
3515 memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
3516 ap->a_mask = (struct sockaddr_storage){
3517 .ss_family = res->ai_family,
3518 .ss_len = res->ai_addrlen
3519 };
3520 switch (res->ai_family) {
3521 #ifdef INET
3522 case AF_INET:
3523 maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
3524 addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
3525 if (masklen < 0) {
3526 /* use default netmask */
3527 if (IN_CLASSA(ntohl(*addrp)))
3528 *maskp = htonl(IN_CLASSA_NET);
3529 else if (IN_CLASSB(ntohl(*addrp)))
3530 *maskp = htonl(IN_CLASSB_NET);
3531 else
3532 *maskp = htonl(IN_CLASSC_NET);
3533 } else if (masklen == 0) {
3534 *maskp = 0;
3535 } else if (masklen <= 32) {
3536 /* convert masklen to netmask */
3537 *maskp = htonl(~((1 << (32 - masklen)) - 1));
3538 } else {
3539 goto err;
3540 }
3541 /* Lose any host bits in the network number. */
3542 *addrp &= *maskp;
3543 break;
3544 #endif
3545 #ifdef INET6
3546 case AF_INET6:
3547 if (masklen > 128)
3548 goto err;
3549
3550 if (masklen < 0)
3551 masklen = 128;
3552 mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
3553 addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
3554 /* convert masklen to netmask */
3555 while (masklen > 0) {
3556 if (masklen < 32) {
3557 *mask6p =
3558 htonl(~(0xffffffff >> masklen));
3559 *addr6p &= *mask6p;
3560 break;
3561 } else {
3562 *mask6p++ = 0xffffffff;
3563 addr6p++;
3564 masklen -= 32;
3565 }
3566 }
3567 break;
3568 #endif
3569 default:
3570 goto err;
3571 }
3572 freeaddrinfo(res);
3573 } else {
3574 /* arg `s' is domain name */
3575 ap->isnumeric = false;
3576 ap->a_name = s;
3577 if (cp1)
3578 *cp1 = '/';
3579 #ifdef INET6
3580 if (cp2) {
3581 *cp2 = ']';
3582 --s;
3583 }
3584 #endif
3585 }
3586 STAILQ_INSERT_TAIL(&aphead, ap, next);
3587
3588 if (Debug) {
3589 printf("allowaddr: rule ");
3590 if (ap->isnumeric) {
3591 printf("numeric, ");
3592 getnameinfo(sstosa(&ap->a_addr),
3593 (sstosa(&ap->a_addr))->sa_len,
3594 ip, sizeof(ip), NULL, 0, NI_NUMERICHOST);
3595 printf("addr = %s, ", ip);
3596 getnameinfo(sstosa(&ap->a_mask),
3597 (sstosa(&ap->a_mask))->sa_len,
3598 ip, sizeof(ip), NULL, 0, NI_NUMERICHOST);
3599 printf("mask = %s; ", ip);
3600 } else {
3601 printf("domainname = %s; ", ap->a_name);
3602 }
3603 printf("port = %d\n", ap->port);
3604 }
3605
3606 return (true);
3607 err:
3608 if (res != NULL)
3609 freeaddrinfo(res);
3610 free(ap);
3611 #endif
3612 return (false);
3613 }
3614
3615 /*
3616 * Validate that the remote peer has permission to log to us.
3617 */
3618 static bool
validate(struct sockaddr * sa,const char * hname)3619 validate(struct sockaddr *sa, const char *hname)
3620 {
3621 int i;
3622 char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
3623 struct allowedpeer *ap;
3624 #ifdef INET
3625 struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
3626 #endif
3627 #ifdef INET6
3628 struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
3629 #endif
3630 struct addrinfo hints, *res;
3631 u_short sport;
3632
3633 /* traditional behaviour, allow everything */
3634 if (STAILQ_EMPTY(&aphead))
3635 return (true);
3636
3637 (void)strlcpy(name, hname, sizeof(name));
3638 hints = (struct addrinfo){
3639 .ai_family = PF_UNSPEC,
3640 .ai_socktype = SOCK_DGRAM,
3641 .ai_flags = AI_PASSIVE | AI_NUMERICHOST
3642 };
3643 if (cap_getaddrinfo(cap_net, name, NULL, &hints, &res) == 0)
3644 freeaddrinfo(res);
3645 else if (strchr(name, '.') == NULL) {
3646 strlcat(name, ".", sizeof(name));
3647 strlcat(name, LocalDomain, sizeof(name));
3648 }
3649 if (cap_getnameinfo(cap_net, sa, sa->sa_len, ip, sizeof(ip), port,
3650 sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV) != 0)
3651 return (false); /* for safety, should not occur */
3652 dprintf("validate: dgram from IP %s, port %s, name %s;\n",
3653 ip, port, name);
3654 sport = atoi(port);
3655
3656 /* now, walk down the list */
3657 i = 0;
3658 STAILQ_FOREACH(ap, &aphead, next) {
3659 i++;
3660 if (ap->port != 0 && ap->port != sport) {
3661 dprintf("rejected in rule %d due to port mismatch.\n",
3662 i);
3663 continue;
3664 }
3665
3666 if (ap->isnumeric) {
3667 if (ap->a_addr.ss_family != sa->sa_family) {
3668 dprintf("rejected in rule %d due to address family mismatch.\n", i);
3669 continue;
3670 }
3671 #ifdef INET
3672 else if (ap->a_addr.ss_family == AF_INET) {
3673 sin4 = satosin(sa);
3674 a4p = satosin(&ap->a_addr);
3675 m4p = satosin(&ap->a_mask);
3676 if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
3677 != a4p->sin_addr.s_addr) {
3678 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3679 continue;
3680 }
3681 }
3682 #endif
3683 #ifdef INET6
3684 else if (ap->a_addr.ss_family == AF_INET6) {
3685 sin6 = satosin6(sa);
3686 a6p = satosin6(&ap->a_addr);
3687 m6p = satosin6(&ap->a_mask);
3688 if (a6p->sin6_scope_id != 0 &&
3689 sin6->sin6_scope_id != a6p->sin6_scope_id) {
3690 dprintf("rejected in rule %d due to scope mismatch.\n", i);
3691 continue;
3692 }
3693 if (!IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
3694 &a6p->sin6_addr, &m6p->sin6_addr)) {
3695 dprintf("rejected in rule %d due to IP mismatch.\n", i);
3696 continue;
3697 }
3698 }
3699 #endif
3700 else
3701 continue;
3702 } else {
3703 if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
3704 FNM_NOMATCH) {
3705 dprintf("rejected in rule %d due to name "
3706 "mismatch.\n", i);
3707 continue;
3708 }
3709 }
3710 dprintf("accepted in rule %d.\n", i);
3711 return (true); /* hooray! */
3712 }
3713 return (false);
3714 }
3715
3716 /*
3717 * Fairly similar to popen(3), but returns an open descriptor, as
3718 * opposed to a FILE *.
3719 *
3720 * Note: This function is wrapped by cap_p_open() when Capsicum support is
3721 * enabled, which allows piped processes to run outside of the capability
3722 * sandbox.
3723 */
3724 int
p_open(const char * prog,int * rpd)3725 p_open(const char *prog, int *rpd)
3726 {
3727 struct sigaction act = { };
3728 int pfd[2], pd;
3729 pid_t pid;
3730 char *argv[4]; /* sh -c cmd NULL */
3731
3732 if (pipe(pfd) == -1)
3733 return (-1);
3734
3735 switch ((pid = pdfork(&pd, PD_CLOEXEC))) {
3736 case -1:
3737 return (-1);
3738
3739 case 0:
3740 (void)setsid(); /* Avoid catching SIGHUPs. */
3741 argv[0] = strdup("sh");
3742 argv[1] = strdup("-c");
3743 argv[2] = strdup(prog);
3744 argv[3] = NULL;
3745 if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL)
3746 err(1, "strdup");
3747
3748 alarm(0);
3749 act.sa_handler = SIG_DFL;
3750 for (size_t i = 0; i < nitems(sigcatch); ++i) {
3751 if (sigaction(sigcatch[i], &act, NULL) == -1)
3752 err(1, "sigaction");
3753 }
3754
3755 dup2(pfd[0], STDIN_FILENO);
3756 dup2(nulldesc, STDOUT_FILENO);
3757 dup2(nulldesc, STDERR_FILENO);
3758 closefrom(STDERR_FILENO + 1);
3759
3760 (void)execvp(_PATH_BSHELL, argv);
3761 _exit(255);
3762 }
3763 close(pfd[0]);
3764 /*
3765 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
3766 * supposed to get an EWOULDBLOCK on writev(2), which is
3767 * caught by the logic above anyway, which will in turn close
3768 * the pipe, and fork a new logging subprocess if necessary.
3769 * The stale subprocess will be killed some time later unless
3770 * it terminated itself due to closing its input pipe (so we
3771 * get rid of really dead puppies).
3772 */
3773 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
3774 /* This is bad. */
3775 dprintf("Warning: cannot change pipe to PID %d to non-blocking"
3776 "behaviour.", pid);
3777 }
3778 *rpd = pd;
3779 return (pfd[1]);
3780 }
3781
3782 static struct deadq_entry *
deadq_enter(int pd)3783 deadq_enter(int pd)
3784 {
3785 struct deadq_entry *dq;
3786
3787 if (pd == -1)
3788 return (NULL);
3789
3790 dq = malloc(sizeof(*dq));
3791 if (dq == NULL) {
3792 logerror("malloc");
3793 exit(1);
3794 }
3795
3796 dq->dq_procdesc = pd;
3797 dq->dq_timeout = DQ_TIMO_INIT;
3798 TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
3799 return (dq);
3800 }
3801
3802 static void
deadq_remove(struct deadq_entry * dq)3803 deadq_remove(struct deadq_entry *dq)
3804 {
3805 TAILQ_REMOVE(&deadq_head, dq, dq_entries);
3806 free(dq);
3807 }
3808
3809 static void
log_deadchild(int pd,int status,const struct filed * f)3810 log_deadchild(int pd, int status, const struct filed *f)
3811 {
3812 pid_t pid;
3813 int code;
3814 char buf[256];
3815 const char *reason;
3816
3817 errno = 0; /* Keep strerror() stuff out of logerror messages. */
3818 if (WIFSIGNALED(status)) {
3819 reason = "due to signal";
3820 code = WTERMSIG(status);
3821 } else {
3822 reason = "with status";
3823 code = WEXITSTATUS(status);
3824 if (code == 0)
3825 return;
3826 }
3827 if (pdgetpid(pd, &pid) == -1)
3828 err(1, "pdgetpid");
3829 (void)snprintf(buf, sizeof(buf),
3830 "Logging subprocess %d (%s) exited %s %d.",
3831 pid, f->f_pname, reason, code);
3832 logerror(buf);
3833 }
3834
3835 static struct socklist *
socksetup(struct addrinfo * ai,const char * name,mode_t mode)3836 socksetup(struct addrinfo *ai, const char *name, mode_t mode)
3837 {
3838 struct socklist *sl;
3839 int (*sl_recv)(struct socklist *);
3840 int s, optval = 1;
3841
3842 if (ai->ai_family != AF_LOCAL && SecureMode > 1) {
3843 /* Only AF_LOCAL in secure mode. */
3844 return (NULL);
3845 }
3846 if (family != AF_UNSPEC && ai->ai_family != AF_LOCAL &&
3847 ai->ai_family != family)
3848 return (NULL);
3849
3850 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3851 if (s < 0) {
3852 logerror("socket");
3853 return (NULL);
3854 }
3855 #ifdef INET6
3856 if (ai->ai_family == AF_INET6) {
3857 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &optval,
3858 sizeof(int)) < 0) {
3859 logerror("setsockopt(IPV6_V6ONLY)");
3860 close(s);
3861 return (NULL);
3862 }
3863 }
3864 #endif
3865 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval,
3866 sizeof(int)) < 0) {
3867 logerror("setsockopt(SO_REUSEADDR)");
3868 close(s);
3869 return (NULL);
3870 }
3871
3872 /*
3873 * Bind INET and UNIX-domain sockets.
3874 *
3875 * A UNIX-domain socket is always bound to a pathname
3876 * regardless of -N flag.
3877 *
3878 * For INET sockets, RFC 3164 recommends that client
3879 * side message should come from the privileged syslogd port.
3880 *
3881 * If the system administrator chooses not to obey
3882 * this, we can skip the bind() step so that the
3883 * system will choose a port for us.
3884 */
3885 if (ai->ai_family == AF_LOCAL)
3886 unlink(name);
3887 if (ai->ai_family == AF_LOCAL || NoBind == 0 || name != NULL) {
3888 mode_t mask;
3889 int error;
3890
3891 if (ai->ai_family == AF_LOCAL && fchmod(s, mode) < 0) {
3892 dprintf("fchmod %s: %s\n", name, strerror(errno));
3893 close(s);
3894 return (NULL);
3895 }
3896
3897 if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &(int){1},
3898 sizeof(int)) < 0) {
3899 logerror("setsockopt(SO_REUSEPORT)");
3900 close(s);
3901 return (NULL);
3902 }
3903
3904 /*
3905 * For AF_LOCAL sockets, the process umask is applied to the
3906 * mode set above, so temporarily clear it to ensure that the
3907 * socket always has the correct permissions.
3908 */
3909 mask = umask(0);
3910 error = bind(s, ai->ai_addr, ai->ai_addrlen);
3911 (void)umask(mask);
3912 if (error < 0) {
3913 logerror("bind");
3914 close(s);
3915 return (NULL);
3916 }
3917 if (ai->ai_family == AF_LOCAL || SecureMode == 0)
3918 increase_rcvbuf(s);
3919 }
3920 dprintf("new socket fd is %d\n", s);
3921 sl_recv = socklist_recv_sock;
3922 #if defined(INET) || defined(INET6)
3923 if (SecureMode && (ai->ai_family == AF_INET ||
3924 ai->ai_family == AF_INET6)) {
3925 dprintf("shutdown\n");
3926 /* Forbid communication in secure mode. */
3927 if (shutdown(s, SHUT_RD) < 0 && errno != ENOTCONN) {
3928 logerror("shutdown");
3929 if (!Debug)
3930 die(0);
3931 }
3932 sl_recv = NULL;
3933 } else
3934 #endif
3935 dprintf("listening on socket\n");
3936 dprintf("sending on socket\n");
3937 /* Copy *ai->ai_addr to the tail of struct socklist if any. */
3938 sl = calloc(1, sizeof(*sl) + ai->ai_addrlen);
3939 if (sl == NULL)
3940 err(1, "malloc failed");
3941 sl->sl_socket = s;
3942 if (ai->ai_family == AF_LOCAL) {
3943 char *name2 = strdup(name);
3944 if (name2 == NULL)
3945 err(1, "strdup failed");
3946 sl->sl_name = strdup(basename(name2));
3947 sl->sl_dirfd = open(dirname(name2), O_DIRECTORY);
3948 if (sl->sl_name == NULL || sl->sl_dirfd == -1)
3949 err(1, "failed to save dir info for %s", name);
3950 free(name2);
3951 }
3952 sl->sl_recv = sl_recv;
3953 (void)memcpy(&sl->sl_ai, ai, sizeof(*ai));
3954 if (ai->ai_addrlen > 0) {
3955 (void)memcpy((sl + 1), ai->ai_addr, ai->ai_addrlen);
3956 sl->sl_sa = (struct sockaddr *)(sl + 1);
3957 } else {
3958 sl->sl_sa = NULL;
3959 }
3960 return (sl);
3961 }
3962
3963 static void
increase_rcvbuf(int fd)3964 increase_rcvbuf(int fd)
3965 {
3966 socklen_t len;
3967
3968 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3969 &(socklen_t){sizeof(len)}) == 0) {
3970 if (len < RCVBUF_MINSIZE) {
3971 len = RCVBUF_MINSIZE;
3972 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));
3973 }
3974 }
3975 }
3976