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