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