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