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