1 /* $OpenBSD: syslogd.c,v 1.284 2025/01/23 12:27:42 henning Exp $ */
2
3 /*
4 * Copyright (c) 2014-2021 Alexander Bluhm <bluhm@genua.de>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 /*
20 * Copyright (c) 1983, 1988, 1993, 1994
21 * The Regents of the University of California. All rights reserved.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
34 *
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * SUCH DAMAGE.
46 */
47
48 /*
49 * syslogd -- log system messages
50 *
51 * This program implements a system log. It takes a series of lines.
52 * Each line may have a priority, signified as "<n>" as
53 * the first characters of the line. If this is
54 * not present, a default priority is used.
55 *
56 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
57 * cause it to reread its configuration file.
58 *
59 * Defined Constants:
60 *
61 * MAXLINE -- the maximum line length that can be handled.
62 * DEFUPRI -- the default priority for user messages
63 * DEFSPRI -- the default priority for kernel messages
64 *
65 * Author: Eric Allman
66 * extensive changes by Ralph Campbell
67 * more extensive changes by Eric Allman (again)
68 * memory buffer logging by Damien Miller
69 * IPv6, libevent, syslog over TCP and TLS by Alexander Bluhm
70 */
71
72 #define MAX_UDPMSG 1180 /* maximum UDP send size */
73 #define MIN_MEMBUF (LOG_MAXLINE * 4) /* Minimum memory buffer size */
74 #define MAX_MEMBUF (256 * 1024) /* Maximum memory buffer size */
75 #define MAX_MEMBUF_NAME 64 /* Max length of membuf log name */
76 #define MAX_TCPBUF (256 * 1024) /* Maximum tcp event buffer size */
77 #define MAXSVLINE 120 /* maximum saved line length */
78 #define FD_RESERVE 5 /* file descriptors not accepted */
79 #define DEFUPRI (LOG_USER|LOG_NOTICE)
80 #define DEFSPRI (LOG_KERN|LOG_CRIT)
81 #define TIMERINTVL 30 /* interval for checking flush, mark */
82
83 #include <sys/ioctl.h>
84 #include <sys/stat.h>
85 #include <sys/msgbuf.h>
86 #include <sys/queue.h>
87 #include <sys/sysctl.h>
88 #include <sys/un.h>
89 #include <sys/time.h>
90 #include <sys/resource.h>
91
92 #include <netinet/in.h>
93 #include <netdb.h>
94 #include <arpa/inet.h>
95
96 #include <ctype.h>
97 #include <err.h>
98 #include <errno.h>
99 #include <event.h>
100 #include <fcntl.h>
101 #include <fnmatch.h>
102 #include <limits.h>
103 #include <paths.h>
104 #include <signal.h>
105 #include <stdio.h>
106 #include <stdlib.h>
107 #include <string.h>
108 #include <tls.h>
109 #include <unistd.h>
110 #include <utmp.h>
111 #include <vis.h>
112
113 #define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
114 #define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
115
116 #define SYSLOG_NAMES
117 #include <sys/syslog.h>
118
119 #include "log.h"
120 #include "syslogd.h"
121 #include "evbuffer_tls.h"
122 #include "parsemsg.h"
123
124 char *ConfFile = _PATH_LOGCONF;
125 const char ctty[] = _PATH_CONSOLE;
126
127 #define MAXUNAMES 20 /* maximum number of user names */
128
129
130 /*
131 * Flags to logmsg().
132 */
133
134 #define IGN_CONS 0x001 /* don't print on console */
135 #define SYNC_FILE 0x002 /* do fsync on file after printing */
136 #define MARK 0x008 /* this message is a mark */
137
138 /*
139 * This structure represents the files that will have log
140 * copies printed.
141 */
142
143 struct filed {
144 SIMPLEQ_ENTRY(filed) f_next; /* next in linked list */
145 int f_type; /* entry type, see below */
146 int f_file; /* file descriptor */
147 time_t f_time; /* time this was last written */
148 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
149 char *f_program; /* program this applies to */
150 char *f_hostname; /* host this applies to */
151 union {
152 char f_uname[MAXUNAMES][UT_NAMESIZE+1];
153 struct {
154 char f_loghost[1+4+3+1+NI_MAXHOST+1+NI_MAXSERV];
155 /* @proto46://[hostname]:servname\0 */
156 struct sockaddr_storage f_addr;
157 struct buffertls f_buftls;
158 struct bufferevent *f_bufev;
159 struct event f_ev;
160 struct tls *f_ctx;
161 char *f_ipproto;
162 char *f_host;
163 char *f_port;
164 int f_retrywait;
165 } f_forw; /* forwarding address */
166 char f_fname[PATH_MAX];
167 struct {
168 char f_mname[MAX_MEMBUF_NAME];
169 struct ringbuf *f_rb;
170 int f_overflow;
171 int f_attached;
172 size_t f_len;
173 } f_mb; /* Memory buffer */
174 } f_un;
175 char f_prevline[MAXSVLINE]; /* last message logged */
176 char f_lasttime[33]; /* time of last occurrence */
177 char f_prevhost[HOST_NAME_MAX+1]; /* host from which recd. */
178 int f_prevpri; /* pri of f_prevline */
179 int f_prevlen; /* length of f_prevline */
180 int f_prevcount; /* repetition cnt of prevline */
181 unsigned int f_repeatcount; /* number of "repeated" msgs */
182 int f_quick; /* abort when matched */
183 int f_dropped; /* warn, dropped message */
184 time_t f_lasterrtime; /* last error was reported */
185 };
186
187 /*
188 * Intervals at which we flush out "message repeated" messages,
189 * in seconds after previous message is logged. After each flush,
190 * we move to the next interval until we reach the largest.
191 */
192 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
193 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
194 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
195 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
196 (f)->f_repeatcount = MAXREPEAT; \
197 }
198
199 /* values for f_type */
200 #define F_UNUSED 0 /* unused entry */
201 #define F_FILE 1 /* regular file */
202 #define F_TTY 2 /* terminal */
203 #define F_CONSOLE 3 /* console terminal */
204 #define F_FORWUDP 4 /* remote machine via UDP */
205 #define F_USERS 5 /* list of users */
206 #define F_WALL 6 /* everyone logged on */
207 #define F_MEMBUF 7 /* memory buffer */
208 #define F_PIPE 8 /* pipe to external program */
209 #define F_FORWTCP 9 /* remote machine via TCP */
210 #define F_FORWTLS 10 /* remote machine via TLS */
211
212 char *TypeNames[] = {
213 "UNUSED", "FILE", "TTY", "CONSOLE",
214 "FORWUDP", "USERS", "WALL", "MEMBUF",
215 "PIPE", "FORWTCP", "FORWTLS",
216 };
217
218 SIMPLEQ_HEAD(filed_list, filed) Files;
219 struct filed consfile;
220
221 int Debug; /* debug flag */
222 int Foreground; /* run in foreground, instead of daemonizing */
223 char LocalHostName[HOST_NAME_MAX+1]; /* our hostname */
224 int Started = 0; /* set after privsep */
225 int Initialized = 0; /* set when we have initialized ourselves */
226
227 int MarkInterval = 20 * 60; /* interval between marks in seconds */
228 int MarkSeq = 0; /* mark sequence number */
229 int PrivChild = 0; /* Exec the privileged parent process */
230 int Repeat = 0; /* 0 msg repeated, 1 in files only, 2 never */
231 int SecureMode = 1; /* when true, speak only unix domain socks */
232 int NoDNS = 0; /* when true, refrain from doing DNS lookups */
233 int ZuluTime = 0; /* display date and time in UTC ISO format */
234 int IncludeHostname = 0; /* include RFC 3164 hostnames when forwarding */
235 int Family = PF_UNSPEC; /* protocol family, may disable IPv4 or IPv6 */
236
237 struct tls *server_ctx;
238 struct tls_config *client_config, *server_config;
239 const char *CAfile = "/etc/ssl/cert.pem"; /* file containing CA certificates */
240 int NoVerify = 0; /* do not verify TLS server x509 certificate */
241 const char *ClientCertfile = NULL;
242 const char *ClientKeyfile = NULL;
243 const char *ServerCAfile = NULL;
244 int udpsend_dropped = 0; /* messages dropped due to UDP not ready */
245 int tcpbuf_dropped = 0; /* count messages dropped from TCP or TLS */
246 int file_dropped = 0; /* messages dropped due to file system full */
247 int init_dropped = 0; /* messages dropped during initialization */
248
249 #define CTL_READING_CMD 1
250 #define CTL_WRITING_REPLY 2
251 #define CTL_WRITING_CONT_REPLY 3
252 int ctl_state = 0; /* What the control socket is up to */
253 int membuf_drop = 0; /* logs dropped in continuous membuf read */
254
255 /*
256 * Client protocol NB. all numeric fields in network byte order
257 */
258 #define CTL_VERSION 2
259
260 /* Request */
261 struct {
262 u_int32_t version;
263 #define CMD_READ 1 /* Read out log */
264 #define CMD_READ_CLEAR 2 /* Read and clear log */
265 #define CMD_CLEAR 3 /* Clear log */
266 #define CMD_LIST 4 /* List available logs */
267 #define CMD_FLAGS 5 /* Query flags only */
268 #define CMD_READ_CONT 6 /* Read out log continuously */
269 u_int32_t cmd;
270 u_int32_t lines;
271 char logname[MAX_MEMBUF_NAME];
272 } ctl_cmd;
273
274 size_t ctl_cmd_bytes = 0; /* number of bytes of ctl_cmd read */
275
276 /* Reply */
277 struct ctl_reply_hdr {
278 u_int32_t version;
279 #define CTL_HDR_FLAG_OVERFLOW 0x01
280 u_int32_t flags;
281 /* Reply text follows, up to MAX_MEMBUF long */
282 };
283
284 #define CTL_HDR_LEN (sizeof(struct ctl_reply_hdr))
285 #define CTL_REPLY_MAXSIZE (CTL_HDR_LEN + MAX_MEMBUF)
286 #define CTL_REPLY_SIZE (strlen(reply_text) + CTL_HDR_LEN)
287
288 char *ctl_reply = NULL; /* Buffer for control connection reply */
289 char *reply_text; /* Start of reply text in buffer */
290 size_t ctl_reply_size = 0; /* Number of bytes used in reply */
291 size_t ctl_reply_offset = 0; /* Number of bytes of reply written so far */
292
293 char *linebuf;
294 int linesize;
295
296 int fd_ctlconn, fd_udp, fd_udp6, send_udp, send_udp6;
297 struct event *ev_ctlaccept, *ev_ctlread, *ev_ctlwrite;
298
299 struct peer {
300 struct buffertls p_buftls;
301 struct bufferevent *p_bufev;
302 struct tls *p_ctx;
303 char *p_peername;
304 char *p_hostname;
305 int p_fd;
306 };
307 char hostname_unknown[] = "???";
308
309 void klog_readcb(int, short, void *);
310 void udp_readcb(int, short, void *);
311 void unix_readcb(int, short, void *);
312 int reserve_accept4(int, int, struct event *,
313 void (*)(int, short, void *), struct sockaddr *, socklen_t *, int);
314 void tcp_acceptcb(int, short, void *);
315 void tls_acceptcb(int, short, void *);
316 void acceptcb(int, short, void *, int);
317 void tls_handshakecb(struct bufferevent *, void *);
318 int octet_counting(struct evbuffer *, char **, int);
319 int non_transparent_framing(struct evbuffer *, char **);
320 void tcp_readcb(struct bufferevent *, void *);
321 void tcp_closecb(struct bufferevent *, short, void *);
322 int tcp_socket(struct filed *);
323 void tcp_dropcb(struct bufferevent *, void *);
324 void tcp_writecb(struct bufferevent *, void *);
325 void tcp_errorcb(struct bufferevent *, short, void *);
326 void tcp_connectcb(int, short, void *);
327 int loghost_resolve(struct filed *);
328 void loghost_retry(struct filed *);
329 void udp_resolvecb(int, short, void *);
330 int tcpbuf_countmsg(struct bufferevent *bufev);
331 void die_signalcb(int, short, void *);
332 void mark_timercb(int, short, void *);
333 void init_signalcb(int, short, void *);
334 void ctlsock_acceptcb(int, short, void *);
335 void ctlconn_readcb(int, short, void *);
336 void ctlconn_writecb(int, short, void *);
337 void ctlconn_logto(char *);
338 void ctlconn_cleanup(void);
339
340 struct filed *cfline(char *, char *, char *);
341 void cvthname(struct sockaddr *, char *, size_t);
342 int decode(const char *, const CODE *);
343 void markit(void);
344 void fprintlog(struct filed *, int, char *);
345 void dropped_warn(int *, const char *);
346 void init(void);
347 void logevent(int, const char *);
348 void logmsg(struct msg *, int, char *);
349 struct filed *find_dup(struct filed *);
350 void printline(char *, char *);
351 void printsys(char *);
352 void current_time(char *);
353 void usage(void);
354 void wallmsg(struct filed *, struct iovec *);
355 int loghost_parse(char *, char **, char **, char **);
356 int getmsgbufsize(void);
357 void address_alloc(const char *, const char *, char ***, char ***, int *);
358 int socket_bind(const char *, const char *, const char *, int,
359 int *, int *);
360 int unix_socket(char *, int, mode_t);
361 void double_sockbuf(int, int, int);
362 void set_sockbuf(int);
363 void set_keepalive(int);
364 void tailify_replytext(char *, int);
365
366 int
main(int argc,char * argv[])367 main(int argc, char *argv[])
368 {
369 struct timeval to;
370 struct event *ev_klog, *ev_sendsys, *ev_udp, *ev_udp6,
371 *ev_bind, *ev_listen, *ev_tls, *ev_unix,
372 *ev_hup, *ev_int, *ev_quit, *ev_term, *ev_mark;
373 sigset_t sigmask;
374 const char *errstr;
375 char *p;
376 int ch, i;
377 int lockpipe[2] = { -1, -1}, pair[2], nullfd, fd;
378 int fd_ctlsock, fd_klog, fd_sendsys, *fd_bind, *fd_listen;
379 int *fd_tls, *fd_unix, nunix, nbind, nlisten, ntls;
380 char **path_unix, *path_ctlsock;
381 char **bind_host, **bind_port, **listen_host, **listen_port;
382 char *tls_hostport, **tls_host, **tls_port;
383
384 /* block signal until handler is set up */
385 sigemptyset(&sigmask);
386 sigaddset(&sigmask, SIGHUP);
387 if (sigprocmask(SIG_SETMASK, &sigmask, NULL) == -1)
388 err(1, "sigprocmask block");
389
390 if ((path_unix = malloc(sizeof(*path_unix))) == NULL)
391 err(1, "malloc %s", _PATH_LOG);
392 path_unix[0] = _PATH_LOG;
393 nunix = 1;
394 path_ctlsock = NULL;
395
396 bind_host = listen_host = tls_host = NULL;
397 bind_port = listen_port = tls_port = NULL;
398 tls_hostport = NULL;
399 nbind = nlisten = ntls = 0;
400
401 while ((ch = getopt(argc, argv,
402 "46a:C:c:dFf:hK:k:m:nP:p:rS:s:T:U:uVZ")) != -1) {
403 switch (ch) {
404 case '4': /* disable IPv6 */
405 Family = PF_INET;
406 break;
407 case '6': /* disable IPv4 */
408 Family = PF_INET6;
409 break;
410 case 'a':
411 if ((path_unix = reallocarray(path_unix, nunix + 1,
412 sizeof(*path_unix))) == NULL)
413 err(1, "unix path %s", optarg);
414 path_unix[nunix++] = optarg;
415 break;
416 case 'C': /* file containing CA certificates */
417 CAfile = optarg;
418 break;
419 case 'c': /* file containing client certificate */
420 ClientCertfile = optarg;
421 break;
422 case 'd': /* debug */
423 Debug++;
424 break;
425 case 'F': /* foreground */
426 Foreground = 1;
427 break;
428 case 'f': /* configuration file */
429 ConfFile = optarg;
430 break;
431 case 'h': /* RFC 3164 hostnames */
432 IncludeHostname = 1;
433 break;
434 case 'K': /* verify client with CA file */
435 ServerCAfile = optarg;
436 break;
437 case 'k': /* file containing client key */
438 ClientKeyfile = optarg;
439 break;
440 case 'm': /* mark interval */
441 MarkInterval = strtonum(optarg, 0, 365*24*60, &errstr);
442 if (errstr)
443 errx(1, "mark_interval %s: %s", errstr, optarg);
444 MarkInterval *= 60;
445 break;
446 case 'n': /* don't do DNS lookups */
447 NoDNS = 1;
448 break;
449 case 'P': /* used internally, exec the parent */
450 PrivChild = strtonum(optarg, 2, INT_MAX, &errstr);
451 if (errstr)
452 errx(1, "priv child %s: %s", errstr, optarg);
453 break;
454 case 'p': /* path */
455 path_unix[0] = optarg;
456 break;
457 case 'r':
458 Repeat++;
459 break;
460 case 'S': /* allow tls and listen on address */
461 if (tls_hostport == NULL)
462 tls_hostport = optarg;
463 address_alloc("tls", optarg, &tls_host, &tls_port,
464 &ntls);
465 break;
466 case 's':
467 path_ctlsock = optarg;
468 break;
469 case 'T': /* allow tcp and listen on address */
470 address_alloc("listen", optarg, &listen_host,
471 &listen_port, &nlisten);
472 break;
473 case 'U': /* allow udp only from address */
474 address_alloc("bind", optarg, &bind_host, &bind_port,
475 &nbind);
476 break;
477 case 'u': /* allow udp input port */
478 SecureMode = 0;
479 break;
480 case 'V': /* do not verify certificates */
481 NoVerify = 1;
482 break;
483 case 'Z': /* time stamps in UTC ISO format */
484 ZuluTime = 1;
485 break;
486 default:
487 usage();
488 }
489 }
490 if (argc != optind)
491 usage();
492
493 log_init(Debug, LOG_SYSLOG);
494 log_procinit("syslogd");
495 if (Debug)
496 setvbuf(stdout, NULL, _IOLBF, 0);
497
498 if ((nullfd = open(_PATH_DEVNULL, O_RDWR)) == -1)
499 fatal("open %s", _PATH_DEVNULL);
500 for (fd = nullfd + 1; fd <= STDERR_FILENO; fd++) {
501 if (fcntl(fd, F_GETFL) == -1 && errno == EBADF)
502 if (dup2(nullfd, fd) == -1)
503 fatal("dup2 null");
504 }
505
506 if (PrivChild > 1)
507 priv_exec(ConfFile, NoDNS, PrivChild, argc, argv);
508
509 consfile.f_type = F_CONSOLE;
510 (void)strlcpy(consfile.f_un.f_fname, ctty,
511 sizeof(consfile.f_un.f_fname));
512 consfile.f_file = open(consfile.f_un.f_fname, O_WRONLY|O_NONBLOCK);
513 if (consfile.f_file == -1)
514 log_warn("open %s", consfile.f_un.f_fname);
515
516 if (gethostname(LocalHostName, sizeof(LocalHostName)) == -1 ||
517 LocalHostName[0] == '\0')
518 strlcpy(LocalHostName, "-", sizeof(LocalHostName));
519 else if ((p = strchr(LocalHostName, '.')) != NULL)
520 *p = '\0';
521
522 /* Reserve space for kernel message buffer plus buffer full message. */
523 linesize = getmsgbufsize() + 64;
524 if (linesize < LOG_MAXLINE)
525 linesize = LOG_MAXLINE;
526 linesize++;
527 if ((linebuf = malloc(linesize)) == NULL)
528 fatal("allocate line buffer");
529
530 if (socket_bind("udp", NULL, "syslog", SecureMode,
531 &fd_udp, &fd_udp6) == -1)
532 log_warnx("socket bind * failed");
533 if ((fd_bind = reallocarray(NULL, nbind, sizeof(*fd_bind))) == NULL)
534 fatal("allocate bind fd");
535 for (i = 0; i < nbind; i++) {
536 if (socket_bind("udp", bind_host[i], bind_port[i], 0,
537 &fd_bind[i], &fd_bind[i]) == -1)
538 log_warnx("socket bind udp failed");
539 }
540 if ((fd_listen = reallocarray(NULL, nlisten, sizeof(*fd_listen)))
541 == NULL)
542 fatal("allocate listen fd");
543 for (i = 0; i < nlisten; i++) {
544 if (socket_bind("tcp", listen_host[i], listen_port[i], 0,
545 &fd_listen[i], &fd_listen[i]) == -1)
546 log_warnx("socket listen tcp failed");
547 }
548 if ((fd_tls = reallocarray(NULL, ntls, sizeof(*fd_tls))) == NULL)
549 fatal("allocate tls fd");
550 for (i = 0; i < ntls; i++) {
551 if (socket_bind("tls", tls_host[i], tls_port[i], 0,
552 &fd_tls[i], &fd_tls[i]) == -1)
553 log_warnx("socket listen tls failed");
554 }
555
556 if ((fd_unix = reallocarray(NULL, nunix, sizeof(*fd_unix))) == NULL)
557 fatal("allocate unix fd");
558 for (i = 0; i < nunix; i++) {
559 fd_unix[i] = unix_socket(path_unix[i], SOCK_DGRAM, 0666);
560 if (fd_unix[i] == -1) {
561 if (i == 0)
562 log_warnx("log socket %s failed", path_unix[i]);
563 continue;
564 }
565 double_sockbuf(fd_unix[i], SO_RCVBUF, 0);
566 }
567
568 if (socketpair(AF_UNIX, SOCK_DGRAM, PF_UNSPEC, pair) == -1) {
569 log_warn("socketpair sendsyslog");
570 fd_sendsys = -1;
571 } else {
572 /*
573 * Avoid to lose messages from sendsyslog(2). A larger
574 * 1 MB socket buffer compensates bursts.
575 */
576 double_sockbuf(pair[0], SO_RCVBUF, 1<<20);
577 double_sockbuf(pair[1], SO_SNDBUF, 1<<20);
578 fd_sendsys = pair[0];
579 }
580
581 fd_ctlsock = fd_ctlconn = -1;
582 if (path_ctlsock != NULL) {
583 fd_ctlsock = unix_socket(path_ctlsock, SOCK_STREAM, 0600);
584 if (fd_ctlsock == -1) {
585 log_warnx("control socket %s failed", path_ctlsock);
586 } else {
587 if (listen(fd_ctlsock, 5) == -1) {
588 log_warn("listen control socket");
589 close(fd_ctlsock);
590 fd_ctlsock = -1;
591 }
592 }
593 }
594
595 if ((fd_klog = open(_PATH_KLOG, O_RDONLY)) == -1) {
596 log_warn("open %s", _PATH_KLOG);
597 } else if (fd_sendsys != -1) {
598 /* Use /dev/klog to register sendsyslog(2) receiver. */
599 if (ioctl(fd_klog, LIOCSFD, &pair[1]) == -1)
600 log_warn("ioctl klog LIOCSFD sendsyslog");
601 }
602 if (fd_sendsys != -1)
603 close(pair[1]);
604
605 if ((client_config = tls_config_new()) == NULL)
606 log_warn("tls_config_new client");
607 if (tls_hostport) {
608 if ((server_config = tls_config_new()) == NULL)
609 log_warn("tls_config_new server");
610 if ((server_ctx = tls_server()) == NULL) {
611 log_warn("tls_server");
612 for (i = 0; i < ntls; i++)
613 close(fd_tls[i]);
614 free(fd_tls);
615 fd_tls = NULL;
616 free(tls_host);
617 free(tls_port);
618 tls_host = tls_port = NULL;
619 ntls = 0;
620 }
621 }
622
623 if (client_config) {
624 if (NoVerify) {
625 tls_config_insecure_noverifycert(client_config);
626 tls_config_insecure_noverifyname(client_config);
627 } else {
628 if (tls_config_set_ca_file(client_config,
629 CAfile) == -1) {
630 log_warnx("load client TLS CA: %s",
631 tls_config_error(client_config));
632 /* avoid reading default certs in chroot */
633 tls_config_set_ca_mem(client_config, "", 0);
634 } else
635 log_debug("CAfile %s", CAfile);
636 }
637 if (ClientCertfile && ClientKeyfile) {
638 if (tls_config_set_cert_file(client_config,
639 ClientCertfile) == -1)
640 log_warnx("load client TLS cert: %s",
641 tls_config_error(client_config));
642 else
643 log_debug("ClientCertfile %s", ClientCertfile);
644
645 if (tls_config_set_key_file(client_config,
646 ClientKeyfile) == -1)
647 log_warnx("load client TLS key: %s",
648 tls_config_error(client_config));
649 else
650 log_debug("ClientKeyfile %s", ClientKeyfile);
651 } else if (ClientCertfile || ClientKeyfile) {
652 log_warnx("options -c and -k must be used together");
653 }
654 if (tls_config_set_protocols(client_config,
655 TLS_PROTOCOLS_ALL) != 0)
656 log_warnx("set client TLS protocols: %s",
657 tls_config_error(client_config));
658 if (tls_config_set_ciphers(client_config, "all") != 0)
659 log_warnx("set client TLS ciphers: %s",
660 tls_config_error(client_config));
661 }
662 if (server_config && server_ctx) {
663 const char *names[2];
664
665 names[0] = tls_hostport;
666 names[1] = tls_host[0];
667
668 for (i = 0; i < 2; i++) {
669 if (asprintf(&p, "/etc/ssl/private/%s.key", names[i])
670 == -1)
671 continue;
672 if (tls_config_set_key_file(server_config, p) == -1) {
673 log_warnx("load server TLS key: %s",
674 tls_config_error(server_config));
675 free(p);
676 continue;
677 }
678 log_debug("Keyfile %s", p);
679 free(p);
680 if (asprintf(&p, "/etc/ssl/%s.crt", names[i]) == -1)
681 continue;
682 if (tls_config_set_cert_file(server_config, p) == -1) {
683 log_warnx("load server TLS cert: %s",
684 tls_config_error(server_config));
685 free(p);
686 continue;
687 }
688 log_debug("Certfile %s", p);
689 free(p);
690 break;
691 }
692
693 if (ServerCAfile) {
694 if (tls_config_set_ca_file(server_config,
695 ServerCAfile) == -1) {
696 log_warnx("load server TLS CA: %s",
697 tls_config_error(server_config));
698 /* avoid reading default certs in chroot */
699 tls_config_set_ca_mem(server_config, "", 0);
700 } else
701 log_debug("Server CAfile %s", ServerCAfile);
702 tls_config_verify_client(server_config);
703 }
704 if (tls_config_set_protocols(server_config,
705 TLS_PROTOCOLS_ALL) != 0)
706 log_warnx("set server TLS protocols: %s",
707 tls_config_error(server_config));
708 if (tls_config_set_ciphers(server_config, "compat") != 0)
709 log_warnx("Set server TLS ciphers: %s",
710 tls_config_error(server_config));
711 if (tls_configure(server_ctx, server_config) != 0) {
712 log_warnx("tls_configure server: %s",
713 tls_error(server_ctx));
714 tls_free(server_ctx);
715 server_ctx = NULL;
716 for (i = 0; i < ntls; i++)
717 close(fd_tls[i]);
718 free(fd_tls);
719 fd_tls = NULL;
720 free(tls_host);
721 free(tls_port);
722 tls_host = tls_port = NULL;
723 ntls = 0;
724 }
725 }
726
727 log_debug("off & running....");
728
729 if (!Debug && !Foreground) {
730 char c;
731
732 pipe(lockpipe);
733
734 switch(fork()) {
735 case -1:
736 err(1, "fork");
737 case 0:
738 setsid();
739 close(lockpipe[0]);
740 break;
741 default:
742 close(lockpipe[1]);
743 read(lockpipe[0], &c, 1);
744 _exit(0);
745 }
746 }
747
748 /* tuck my process id away */
749 if (!Debug) {
750 FILE *fp;
751
752 fp = fopen(_PATH_LOGPID, "w");
753 if (fp != NULL) {
754 fprintf(fp, "%ld\n", (long)getpid());
755 (void) fclose(fp);
756 }
757 }
758
759 /* Privilege separation begins here */
760 priv_init(lockpipe[1], nullfd, argc, argv);
761
762 if (pledge("stdio unix inet recvfd", NULL) == -1)
763 err(1, "pledge");
764
765 Started = 1;
766
767 /* Process is now unprivileged and inside a chroot */
768 if (Debug)
769 event_set_log_callback(logevent);
770 event_init();
771
772 if ((ev_ctlaccept = malloc(sizeof(struct event))) == NULL ||
773 (ev_ctlread = malloc(sizeof(struct event))) == NULL ||
774 (ev_ctlwrite = malloc(sizeof(struct event))) == NULL ||
775 (ev_klog = malloc(sizeof(struct event))) == NULL ||
776 (ev_sendsys = malloc(sizeof(struct event))) == NULL ||
777 (ev_udp = malloc(sizeof(struct event))) == NULL ||
778 (ev_udp6 = malloc(sizeof(struct event))) == NULL ||
779 (ev_bind = reallocarray(NULL, nbind, sizeof(struct event)))
780 == NULL ||
781 (ev_listen = reallocarray(NULL, nlisten, sizeof(struct event)))
782 == NULL ||
783 (ev_tls = reallocarray(NULL, ntls, sizeof(struct event)))
784 == NULL ||
785 (ev_unix = reallocarray(NULL, nunix, sizeof(struct event)))
786 == NULL ||
787 (ev_hup = malloc(sizeof(struct event))) == NULL ||
788 (ev_int = malloc(sizeof(struct event))) == NULL ||
789 (ev_quit = malloc(sizeof(struct event))) == NULL ||
790 (ev_term = malloc(sizeof(struct event))) == NULL ||
791 (ev_mark = malloc(sizeof(struct event))) == NULL)
792 err(1, "malloc");
793
794 event_set(ev_ctlaccept, fd_ctlsock, EV_READ|EV_PERSIST,
795 ctlsock_acceptcb, ev_ctlaccept);
796 event_set(ev_ctlread, fd_ctlconn, EV_READ|EV_PERSIST,
797 ctlconn_readcb, ev_ctlread);
798 event_set(ev_ctlwrite, fd_ctlconn, EV_WRITE|EV_PERSIST,
799 ctlconn_writecb, ev_ctlwrite);
800 event_set(ev_klog, fd_klog, EV_READ|EV_PERSIST, klog_readcb, ev_klog);
801 event_set(ev_sendsys, fd_sendsys, EV_READ|EV_PERSIST, unix_readcb,
802 ev_sendsys);
803 event_set(ev_udp, fd_udp, EV_READ|EV_PERSIST, udp_readcb, ev_udp);
804 event_set(ev_udp6, fd_udp6, EV_READ|EV_PERSIST, udp_readcb, ev_udp6);
805 for (i = 0; i < nbind; i++)
806 event_set(&ev_bind[i], fd_bind[i], EV_READ|EV_PERSIST,
807 udp_readcb, &ev_bind[i]);
808 for (i = 0; i < nlisten; i++)
809 event_set(&ev_listen[i], fd_listen[i], EV_READ|EV_PERSIST,
810 tcp_acceptcb, &ev_listen[i]);
811 for (i = 0; i < ntls; i++)
812 event_set(&ev_tls[i], fd_tls[i], EV_READ|EV_PERSIST,
813 tls_acceptcb, &ev_tls[i]);
814 for (i = 0; i < nunix; i++)
815 event_set(&ev_unix[i], fd_unix[i], EV_READ|EV_PERSIST,
816 unix_readcb, &ev_unix[i]);
817
818 signal_set(ev_hup, SIGHUP, init_signalcb, ev_hup);
819 signal_set(ev_int, SIGINT, die_signalcb, ev_int);
820 signal_set(ev_quit, SIGQUIT, die_signalcb, ev_quit);
821 signal_set(ev_term, SIGTERM, die_signalcb, ev_term);
822
823 evtimer_set(ev_mark, mark_timercb, ev_mark);
824
825 init();
826
827 /* Allocate ctl socket reply buffer if we have a ctl socket */
828 if (fd_ctlsock != -1 &&
829 (ctl_reply = malloc(CTL_REPLY_MAXSIZE)) == NULL)
830 fatal("allocate control socket reply buffer");
831 reply_text = ctl_reply + CTL_HDR_LEN;
832
833 if (!Debug) {
834 close(lockpipe[1]);
835 dup2(nullfd, STDIN_FILENO);
836 dup2(nullfd, STDOUT_FILENO);
837 dup2(nullfd, STDERR_FILENO);
838 }
839 if (nullfd > 2)
840 close(nullfd);
841
842 /*
843 * Signal to the priv process that the initial config parsing is done
844 * so that it will reject any future attempts to open more files
845 */
846 priv_config_parse_done();
847
848 if (fd_ctlsock != -1)
849 event_add(ev_ctlaccept, NULL);
850 if (fd_klog != -1)
851 event_add(ev_klog, NULL);
852 if (fd_sendsys != -1)
853 event_add(ev_sendsys, NULL);
854 if (!SecureMode) {
855 if (fd_udp != -1)
856 event_add(ev_udp, NULL);
857 if (fd_udp6 != -1)
858 event_add(ev_udp6, NULL);
859 }
860 for (i = 0; i < nbind; i++)
861 if (fd_bind[i] != -1)
862 event_add(&ev_bind[i], NULL);
863 for (i = 0; i < nlisten; i++)
864 if (fd_listen[i] != -1)
865 event_add(&ev_listen[i], NULL);
866 for (i = 0; i < ntls; i++)
867 if (fd_tls[i] != -1)
868 event_add(&ev_tls[i], NULL);
869 for (i = 0; i < nunix; i++)
870 if (fd_unix[i] != -1)
871 event_add(&ev_unix[i], NULL);
872
873 signal_add(ev_hup, NULL);
874 signal_add(ev_term, NULL);
875 if (Debug || Foreground) {
876 signal_add(ev_int, NULL);
877 signal_add(ev_quit, NULL);
878 } else {
879 (void)signal(SIGINT, SIG_IGN);
880 (void)signal(SIGQUIT, SIG_IGN);
881 }
882 (void)signal(SIGCHLD, SIG_IGN);
883 (void)signal(SIGPIPE, SIG_IGN);
884
885 to.tv_sec = TIMERINTVL;
886 to.tv_usec = 0;
887 evtimer_add(ev_mark, &to);
888
889 log_info(LOG_INFO, "start");
890 log_debug("syslogd: started");
891
892 sigemptyset(&sigmask);
893 if (sigprocmask(SIG_SETMASK, &sigmask, NULL) == -1)
894 err(1, "sigprocmask unblock");
895
896 /* Send message via libc, flushes log stash in kernel. */
897 openlog("syslogd", LOG_PID, LOG_SYSLOG);
898 syslog(LOG_DEBUG, "running");
899
900 event_dispatch();
901 /* NOTREACHED */
902 return (0);
903 }
904
905 void
address_alloc(const char * name,const char * address,char *** host,char *** port,int * num)906 address_alloc(const char *name, const char *address, char ***host,
907 char ***port, int *num)
908 {
909 char *p;
910
911 /* do not care about memory leak, argv has to be preserved */
912 if ((p = strdup(address)) == NULL)
913 err(1, "%s address %s", name, address);
914 if ((*host = reallocarray(*host, *num + 1, sizeof(**host))) == NULL)
915 err(1, "%s host %s", name, address);
916 if ((*port = reallocarray(*port, *num + 1, sizeof(**port))) == NULL)
917 err(1, "%s port %s", name, address);
918 if (loghost_parse(p, NULL, *host + *num, *port + *num) == -1)
919 errx(1, "bad %s address: %s", name, address);
920 (*num)++;
921 }
922
923 int
socket_bind(const char * proto,const char * host,const char * port,int shutread,int * fd,int * fd6)924 socket_bind(const char *proto, const char *host, const char *port,
925 int shutread, int *fd, int *fd6)
926 {
927 struct addrinfo hints, *res, *res0;
928 char hostname[NI_MAXHOST], servname[NI_MAXSERV];
929 int *fdp, error, reuseaddr;
930
931 *fd = *fd6 = -1;
932 if (proto == NULL)
933 proto = "udp";
934 if (port == NULL)
935 port = strcmp(proto, "tls") == 0 ? "syslog-tls" : "syslog";
936
937 memset(&hints, 0, sizeof(hints));
938 hints.ai_family = Family;
939 if (strcmp(proto, "udp") == 0) {
940 hints.ai_socktype = SOCK_DGRAM;
941 hints.ai_protocol = IPPROTO_UDP;
942 } else {
943 hints.ai_socktype = SOCK_STREAM;
944 hints.ai_protocol = IPPROTO_TCP;
945 }
946 hints.ai_flags = AI_PASSIVE;
947
948 if ((error = getaddrinfo(host, port, &hints, &res0))) {
949 log_warnx("getaddrinfo proto %s, host %s, port %s: %s",
950 proto, host ? host : "*", port, gai_strerror(error));
951 return (-1);
952 }
953
954 for (res = res0; res; res = res->ai_next) {
955 switch (res->ai_family) {
956 case AF_INET:
957 fdp = fd;
958 break;
959 case AF_INET6:
960 fdp = fd6;
961 break;
962 default:
963 continue;
964 }
965 if (*fdp >= 0)
966 continue;
967
968 if ((*fdp = socket(res->ai_family,
969 res->ai_socktype | SOCK_NONBLOCK, res->ai_protocol)) == -1)
970 continue;
971
972 error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname,
973 sizeof(hostname), servname, sizeof(servname),
974 NI_NUMERICHOST | NI_NUMERICSERV |
975 (res->ai_socktype == SOCK_DGRAM ? NI_DGRAM : 0));
976 if (error) {
977 log_warnx("malformed bind address host \"%s\": %s",
978 host, gai_strerror(error));
979 strlcpy(hostname, hostname_unknown, sizeof(hostname));
980 strlcpy(servname, hostname_unknown, sizeof(servname));
981 }
982 if (shutread && shutdown(*fdp, SHUT_RD) == -1) {
983 log_warn("shutdown SHUT_RD "
984 "protocol %d, address %s, portnum %s",
985 res->ai_protocol, hostname, servname);
986 close(*fdp);
987 *fdp = -1;
988 continue;
989 }
990 if (!shutread && res->ai_protocol == IPPROTO_UDP)
991 double_sockbuf(*fdp, SO_RCVBUF, 0);
992 else if (res->ai_protocol == IPPROTO_TCP) {
993 set_sockbuf(*fdp);
994 set_keepalive(*fdp);
995 }
996 reuseaddr = 1;
997 if (setsockopt(*fdp, SOL_SOCKET, SO_REUSEADDR, &reuseaddr,
998 sizeof(reuseaddr)) == -1) {
999 log_warn("setsockopt SO_REUSEADDR "
1000 "protocol %d, address %s, portnum %s",
1001 res->ai_protocol, hostname, servname);
1002 close(*fdp);
1003 *fdp = -1;
1004 continue;
1005 }
1006 if (bind(*fdp, res->ai_addr, res->ai_addrlen) == -1) {
1007 log_warn("bind protocol %d, address %s, portnum %s",
1008 res->ai_protocol, hostname, servname);
1009 close(*fdp);
1010 *fdp = -1;
1011 continue;
1012 }
1013 if (!shutread && res->ai_protocol == IPPROTO_TCP &&
1014 listen(*fdp, 10) == -1) {
1015 log_warn("listen protocol %d, address %s, portnum %s",
1016 res->ai_protocol, hostname, servname);
1017 close(*fdp);
1018 *fdp = -1;
1019 continue;
1020 }
1021 }
1022
1023 freeaddrinfo(res0);
1024
1025 if (*fd == -1 && *fd6 == -1)
1026 return (-1);
1027 return (0);
1028 }
1029
1030 void
klog_readcb(int fd,short event,void * arg)1031 klog_readcb(int fd, short event, void *arg)
1032 {
1033 struct event *ev = arg;
1034 ssize_t n;
1035
1036 n = read(fd, linebuf, linesize - 1);
1037 if (n > 0) {
1038 linebuf[n] = '\0';
1039 printsys(linebuf);
1040 } else if (n == -1 && errno != EINTR) {
1041 log_warn("read klog");
1042 event_del(ev);
1043 }
1044 }
1045
1046 void
udp_readcb(int fd,short event,void * arg)1047 udp_readcb(int fd, short event, void *arg)
1048 {
1049 struct sockaddr_storage sa;
1050 socklen_t salen;
1051 ssize_t n;
1052
1053 salen = sizeof(sa);
1054 n = recvfrom(fd, linebuf, LOG_MAXLINE, 0, (struct sockaddr *)&sa,
1055 &salen);
1056 if (n > 0) {
1057 char resolve[NI_MAXHOST];
1058
1059 linebuf[n] = '\0';
1060 cvthname((struct sockaddr *)&sa, resolve, sizeof(resolve));
1061 log_debug("cvthname res: %s", resolve);
1062 printline(resolve, linebuf);
1063 } else if (n == -1 && errno != EINTR && errno != EWOULDBLOCK)
1064 log_warn("recvfrom udp");
1065 }
1066
1067 void
unix_readcb(int fd,short event,void * arg)1068 unix_readcb(int fd, short event, void *arg)
1069 {
1070 struct sockaddr_un sa;
1071 socklen_t salen;
1072 ssize_t n;
1073
1074 salen = sizeof(sa);
1075 n = recvfrom(fd, linebuf, LOG_MAXLINE, 0, (struct sockaddr *)&sa,
1076 &salen);
1077 if (n > 0) {
1078 linebuf[n] = '\0';
1079 printline(LocalHostName, linebuf);
1080 } else if (n == -1 && errno != EINTR && errno != EWOULDBLOCK)
1081 log_warn("recvfrom unix");
1082 }
1083
1084 int
reserve_accept4(int lfd,int event,struct event * ev,void (* cb)(int,short,void *),struct sockaddr * sa,socklen_t * salen,int flags)1085 reserve_accept4(int lfd, int event, struct event *ev,
1086 void (*cb)(int, short, void *),
1087 struct sockaddr *sa, socklen_t *salen, int flags)
1088 {
1089 struct timeval to = { 1, 0 };
1090 int afd;
1091
1092 if (event & EV_TIMEOUT) {
1093 log_debug("Listen again");
1094 /* Enable the listen event, there is no timeout anymore. */
1095 event_set(ev, lfd, EV_READ|EV_PERSIST, cb, ev);
1096 event_add(ev, NULL);
1097 errno = EWOULDBLOCK;
1098 return (-1);
1099 }
1100
1101 if (getdtablecount() + FD_RESERVE >= getdtablesize()) {
1102 afd = -1;
1103 errno = EMFILE;
1104 } else
1105 afd = accept4(lfd, sa, salen, flags);
1106
1107 if (afd == -1 && (errno == ENFILE || errno == EMFILE)) {
1108 log_info(LOG_WARNING, "accept deferred: %s", strerror(errno));
1109 /*
1110 * Disable the listen event and convert it to a timeout.
1111 * Pass the listen file descriptor to the callback.
1112 */
1113 event_del(ev);
1114 event_set(ev, lfd, 0, cb, ev);
1115 event_add(ev, &to);
1116 return (-1);
1117 }
1118
1119 return (afd);
1120 }
1121
1122 void
tcp_acceptcb(int lfd,short event,void * arg)1123 tcp_acceptcb(int lfd, short event, void *arg)
1124 {
1125 acceptcb(lfd, event, arg, 0);
1126 }
1127
1128 void
tls_acceptcb(int lfd,short event,void * arg)1129 tls_acceptcb(int lfd, short event, void *arg)
1130 {
1131 acceptcb(lfd, event, arg, 1);
1132 }
1133
1134 void
acceptcb(int lfd,short event,void * arg,int usetls)1135 acceptcb(int lfd, short event, void *arg, int usetls)
1136 {
1137 struct event *ev = arg;
1138 struct peer *p;
1139 struct sockaddr_storage ss;
1140 socklen_t sslen;
1141 char hostname[NI_MAXHOST], servname[NI_MAXSERV];
1142 char *peername;
1143 int fd, error;
1144
1145 sslen = sizeof(ss);
1146 if ((fd = reserve_accept4(lfd, event, ev, tcp_acceptcb,
1147 (struct sockaddr *)&ss, &sslen, SOCK_NONBLOCK)) == -1) {
1148 if (errno != ENFILE && errno != EMFILE &&
1149 errno != EINTR && errno != EWOULDBLOCK &&
1150 errno != ECONNABORTED)
1151 log_warn("accept tcp socket");
1152 return;
1153 }
1154 log_debug("Accepting tcp connection");
1155
1156 error = getnameinfo((struct sockaddr *)&ss, sslen, hostname,
1157 sizeof(hostname), servname, sizeof(servname),
1158 NI_NUMERICHOST | NI_NUMERICSERV);
1159 if (error) {
1160 log_warnx("malformed TCP accept address: %s",
1161 gai_strerror(error));
1162 peername = hostname_unknown;
1163 } else if (asprintf(&peername, ss.ss_family == AF_INET6 ?
1164 "[%s]:%s" : "%s:%s", hostname, servname) == -1) {
1165 log_warn("allocate hostname \"%s\"", hostname);
1166 peername = hostname_unknown;
1167 }
1168 log_debug("Peer address and port %s", peername);
1169 if ((p = malloc(sizeof(*p))) == NULL) {
1170 log_warn("allocate peername \"%s\"", peername);
1171 close(fd);
1172 return;
1173 }
1174 p->p_fd = fd;
1175 if ((p->p_bufev = bufferevent_new(fd, tcp_readcb,
1176 usetls ? tls_handshakecb : NULL, tcp_closecb, p)) == NULL) {
1177 log_warn("bufferevent \"%s\"", peername);
1178 free(p);
1179 close(fd);
1180 return;
1181 }
1182 p->p_ctx = NULL;
1183 if (usetls) {
1184 if (tls_accept_socket(server_ctx, &p->p_ctx, fd) == -1) {
1185 log_warnx("tls_accept_socket \"%s\": %s",
1186 peername, tls_error(server_ctx));
1187 bufferevent_free(p->p_bufev);
1188 free(p);
1189 close(fd);
1190 return;
1191 }
1192 buffertls_set(&p->p_buftls, p->p_bufev, p->p_ctx, fd);
1193 buffertls_accept(&p->p_buftls, fd);
1194 log_debug("tcp accept callback: tls context success");
1195 }
1196 if (!NoDNS && peername != hostname_unknown &&
1197 priv_getnameinfo((struct sockaddr *)&ss, ss.ss_len, hostname,
1198 sizeof(hostname)) != 0) {
1199 log_debug("Host name for accept address (%s) unknown",
1200 hostname);
1201 }
1202 if (peername == hostname_unknown ||
1203 (p->p_hostname = strdup(hostname)) == NULL)
1204 p->p_hostname = hostname_unknown;
1205 log_debug("Peer hostname %s", hostname);
1206 p->p_peername = peername;
1207 bufferevent_enable(p->p_bufev, EV_READ);
1208
1209 log_info(LOG_DEBUG, "%s logger \"%s\" accepted",
1210 p->p_ctx ? "tls" : "tcp", peername);
1211 }
1212
1213 void
tls_handshakecb(struct bufferevent * bufev,void * arg)1214 tls_handshakecb(struct bufferevent *bufev, void *arg)
1215 {
1216 struct peer *p = arg;
1217 const char *cn;
1218 char *cntmp;
1219
1220 log_debug("Completed tls handshake");
1221
1222 if (tls_peer_cert_provided(p->p_ctx)) {
1223 if ((cn = tls_peer_cert_common_name(p->p_ctx)) != NULL &&
1224 strlen(cn) > 0) {
1225 if (stravis(&cntmp, cn, VIS_WHITE) == -1)
1226 log_warn("tls_handshakecb stravis");
1227 else {
1228 log_info(LOG_INFO, "%s using hostname \"%s\" "
1229 "from certificate", p->p_hostname, cntmp);
1230 free(p->p_hostname);
1231 p->p_hostname = cntmp;
1232 }
1233 } else
1234 log_info(LOG_NOTICE,
1235 "cannot get hostname from peer certificate");
1236 }
1237
1238 bufferevent_setcb(bufev, tcp_readcb, NULL, tcp_closecb, p);
1239 }
1240
1241 /*
1242 * Syslog over TCP RFC 6587 3.4.1. Octet Counting
1243 */
1244 int
octet_counting(struct evbuffer * evbuf,char ** msg,int drain)1245 octet_counting(struct evbuffer *evbuf, char **msg, int drain)
1246 {
1247 char *p, *buf, *end;
1248 int len;
1249
1250 buf = EVBUFFER_DATA(evbuf);
1251 end = buf + EVBUFFER_LENGTH(evbuf);
1252 /*
1253 * It can be assumed that octet-counting framing is used if a syslog
1254 * frame starts with a digit.
1255 */
1256 if (buf >= end || !isdigit((unsigned char)*buf))
1257 return (-1);
1258 /*
1259 * SYSLOG-FRAME = MSG-LEN SP SYSLOG-MSG
1260 * MSG-LEN is the octet count of the SYSLOG-MSG in the SYSLOG-FRAME.
1261 * We support up to 5 digits in MSG-LEN, so the maximum is 99999.
1262 */
1263 for (p = buf; p < end && p < buf + 5; p++) {
1264 if (!isdigit((unsigned char)*p))
1265 break;
1266 }
1267 if (buf >= p || p >= end || *p != ' ')
1268 return (-1);
1269 p++;
1270 /* Using atoi() is safe as buf starts with 1 to 5 digits and a space. */
1271 len = atoi(buf);
1272 if (drain)
1273 log_debugadd(" octet counting %d", len);
1274 if (p + len > end)
1275 return (0);
1276 if (drain)
1277 evbuffer_drain(evbuf, p - buf);
1278 if (msg)
1279 *msg = p;
1280 return (len);
1281 }
1282
1283 /*
1284 * Syslog over TCP RFC 6587 3.4.2. Non-Transparent-Framing
1285 */
1286 int
non_transparent_framing(struct evbuffer * evbuf,char ** msg)1287 non_transparent_framing(struct evbuffer *evbuf, char **msg)
1288 {
1289 char *p, *buf, *end;
1290
1291 buf = EVBUFFER_DATA(evbuf);
1292 end = buf + EVBUFFER_LENGTH(evbuf);
1293 /*
1294 * The TRAILER has usually been a single character and most often
1295 * is ASCII LF (%d10). However, other characters have also been
1296 * seen, with ASCII NUL (%d00) being a prominent example.
1297 */
1298 for (p = buf; p < end; p++) {
1299 if (*p == '\0' || *p == '\n')
1300 break;
1301 }
1302 if (p + 1 - buf >= INT_MAX)
1303 return (-1);
1304 log_debugadd(" non transparent framing");
1305 if (p >= end)
1306 return (0);
1307 /*
1308 * Some devices have also been seen to emit a two-character
1309 * TRAILER, which is usually CR and LF.
1310 */
1311 if (buf < p && p[0] == '\n' && p[-1] == '\r')
1312 p[-1] = '\0';
1313 if (msg)
1314 *msg = buf;
1315 return (p + 1 - buf);
1316 }
1317
1318 void
tcp_readcb(struct bufferevent * bufev,void * arg)1319 tcp_readcb(struct bufferevent *bufev, void *arg)
1320 {
1321 struct peer *p = arg;
1322 char *msg;
1323 int len;
1324
1325 while (EVBUFFER_LENGTH(bufev->input) > 0) {
1326 log_debugadd("%s logger \"%s\"", p->p_ctx ? "tls" : "tcp",
1327 p->p_peername);
1328 msg = NULL;
1329 len = octet_counting(bufev->input, &msg, 1);
1330 if (len < 0)
1331 len = non_transparent_framing(bufev->input, &msg);
1332 if (len < 0)
1333 log_debugadd("unknown method");
1334 if (msg == NULL) {
1335 log_debugadd(", incomplete frame");
1336 break;
1337 }
1338 log_debug(", use %d bytes", len);
1339 if (len > 0 && msg[len-1] == '\n')
1340 msg[len-1] = '\0';
1341 if (len == 0 || msg[len-1] != '\0') {
1342 memcpy(linebuf, msg, MINIMUM(len, LOG_MAXLINE));
1343 linebuf[MINIMUM(len, LOG_MAXLINE)] = '\0';
1344 msg = linebuf;
1345 }
1346 printline(p->p_hostname, msg);
1347 evbuffer_drain(bufev->input, len);
1348 }
1349 /* Maximum frame has 5 digits, 1 space, MAXLINE chars, 1 new line. */
1350 if (EVBUFFER_LENGTH(bufev->input) >= 5 + 1 + LOG_MAXLINE + 1) {
1351 log_debug(", use %zu bytes", EVBUFFER_LENGTH(bufev->input));
1352 EVBUFFER_DATA(bufev->input)[5 + 1 + LOG_MAXLINE] = '\0';
1353 printline(p->p_hostname, EVBUFFER_DATA(bufev->input));
1354 evbuffer_drain(bufev->input, -1);
1355 } else if (EVBUFFER_LENGTH(bufev->input) > 0)
1356 log_debug(", buffer %zu bytes", EVBUFFER_LENGTH(bufev->input));
1357 }
1358
1359 void
tcp_closecb(struct bufferevent * bufev,short event,void * arg)1360 tcp_closecb(struct bufferevent *bufev, short event, void *arg)
1361 {
1362 struct peer *p = arg;
1363
1364 if (event & EVBUFFER_EOF) {
1365 log_info(LOG_DEBUG, "%s logger \"%s\" connection close",
1366 p->p_ctx ? "tls" : "tcp", p->p_peername);
1367 } else {
1368 log_info(LOG_NOTICE, "%s logger \"%s\" connection error: %s",
1369 p->p_ctx ? "tls" : "tcp", p->p_peername,
1370 p->p_ctx ? tls_error(p->p_ctx) : strerror(errno));
1371 }
1372
1373 if (p->p_peername != hostname_unknown)
1374 free(p->p_peername);
1375 if (p->p_hostname != hostname_unknown)
1376 free(p->p_hostname);
1377 bufferevent_free(p->p_bufev);
1378 close(p->p_fd);
1379 free(p);
1380 }
1381
1382 int
tcp_socket(struct filed * f)1383 tcp_socket(struct filed *f)
1384 {
1385 int s;
1386
1387 if ((s = socket(f->f_un.f_forw.f_addr.ss_family,
1388 SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP)) == -1) {
1389 log_warn("socket \"%s\"", f->f_un.f_forw.f_loghost);
1390 return (-1);
1391 }
1392 set_sockbuf(s);
1393 if (connect(s, (struct sockaddr *)&f->f_un.f_forw.f_addr,
1394 f->f_un.f_forw.f_addr.ss_len) == -1 && errno != EINPROGRESS) {
1395 log_warn("connect \"%s\"", f->f_un.f_forw.f_loghost);
1396 close(s);
1397 return (-1);
1398 }
1399 return (s);
1400 }
1401
1402 void
tcp_dropcb(struct bufferevent * bufev,void * arg)1403 tcp_dropcb(struct bufferevent *bufev, void *arg)
1404 {
1405 struct filed *f = arg;
1406
1407 /*
1408 * Drop data received from the forward log server.
1409 */
1410 log_debug("loghost \"%s\" did send %zu bytes back",
1411 f->f_un.f_forw.f_loghost, EVBUFFER_LENGTH(bufev->input));
1412 evbuffer_drain(bufev->input, -1);
1413 }
1414
1415 void
tcp_writecb(struct bufferevent * bufev,void * arg)1416 tcp_writecb(struct bufferevent *bufev, void *arg)
1417 {
1418 struct filed *f = arg;
1419 char ebuf[ERRBUFSIZE];
1420
1421 /*
1422 * Successful write, connection to server is good, reset wait time.
1423 */
1424 log_debug("loghost \"%s\" successful write", f->f_un.f_forw.f_loghost);
1425 f->f_un.f_forw.f_retrywait = 0;
1426
1427 if (f->f_dropped > 0 &&
1428 EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) < MAX_TCPBUF) {
1429 snprintf(ebuf, sizeof(ebuf), "to loghost \"%s\"",
1430 f->f_un.f_forw.f_loghost);
1431 dropped_warn(&f->f_dropped, ebuf);
1432 }
1433 }
1434
1435 void
tcp_errorcb(struct bufferevent * bufev,short event,void * arg)1436 tcp_errorcb(struct bufferevent *bufev, short event, void *arg)
1437 {
1438 struct filed *f = arg;
1439 char *p, *buf, *end;
1440 int l;
1441 char ebuf[ERRBUFSIZE];
1442
1443 if (event & EVBUFFER_EOF)
1444 snprintf(ebuf, sizeof(ebuf), "loghost \"%s\" connection close",
1445 f->f_un.f_forw.f_loghost);
1446 else
1447 snprintf(ebuf, sizeof(ebuf),
1448 "loghost \"%s\" connection error: %s",
1449 f->f_un.f_forw.f_loghost, f->f_un.f_forw.f_ctx ?
1450 tls_error(f->f_un.f_forw.f_ctx) : strerror(errno));
1451 log_debug("%s", ebuf);
1452
1453 /* The SIGHUP handler may also close the socket, so invalidate it. */
1454 if (f->f_un.f_forw.f_ctx) {
1455 tls_close(f->f_un.f_forw.f_ctx);
1456 tls_free(f->f_un.f_forw.f_ctx);
1457 f->f_un.f_forw.f_ctx = NULL;
1458 }
1459 bufferevent_disable(bufev, EV_READ|EV_WRITE);
1460 close(f->f_file);
1461 f->f_file = -1;
1462
1463 /*
1464 * The messages in the output buffer may be out of sync.
1465 * Check that the buffer starts with "1234 <1234 octets>\n".
1466 * Otherwise remove the partial message from the beginning.
1467 */
1468 buf = EVBUFFER_DATA(bufev->output);
1469 end = buf + EVBUFFER_LENGTH(bufev->output);
1470 if (buf < end && !((l = octet_counting(bufev->output, &p, 0)) > 0 &&
1471 p[l-1] == '\n')) {
1472 for (p = buf; p < end; p++) {
1473 if (*p == '\n') {
1474 evbuffer_drain(bufev->output, p - buf + 1);
1475 break;
1476 }
1477 }
1478 /* Without '\n' discard everything. */
1479 if (p == end)
1480 evbuffer_drain(bufev->output, -1);
1481 log_debug("loghost \"%s\" dropped partial message",
1482 f->f_un.f_forw.f_loghost);
1483 f->f_dropped++;
1484 }
1485
1486 loghost_retry(f);
1487
1488 /* Log the connection error to the fresh buffer after reconnecting. */
1489 log_info(LOG_WARNING, "%s", ebuf);
1490 }
1491
1492 void
tcp_connectcb(int fd,short event,void * arg)1493 tcp_connectcb(int fd, short event, void *arg)
1494 {
1495 struct filed *f = arg;
1496 struct bufferevent *bufev = f->f_un.f_forw.f_bufev;
1497 int s;
1498
1499 if (f->f_un.f_forw.f_addr.ss_family == AF_UNSPEC) {
1500 if (loghost_resolve(f) != 0) {
1501 loghost_retry(f);
1502 return;
1503 }
1504 }
1505
1506 if ((s = tcp_socket(f)) == -1) {
1507 loghost_retry(f);
1508 return;
1509 }
1510 log_debug("tcp connect callback: socket success, event %#x", event);
1511 f->f_file = s;
1512
1513 bufferevent_setfd(bufev, s);
1514 bufferevent_setcb(bufev, tcp_dropcb, tcp_writecb, tcp_errorcb, f);
1515 /*
1516 * Although syslog is a write only protocol, enable reading from
1517 * the socket to detect connection close and errors.
1518 */
1519 bufferevent_enable(bufev, EV_READ|EV_WRITE);
1520
1521 if (f->f_type == F_FORWTLS) {
1522 if ((f->f_un.f_forw.f_ctx = tls_client()) == NULL) {
1523 log_warn("tls_client \"%s\"", f->f_un.f_forw.f_loghost);
1524 goto error;
1525 }
1526 if (client_config &&
1527 tls_configure(f->f_un.f_forw.f_ctx, client_config) == -1) {
1528 log_warnx("tls_configure \"%s\": %s",
1529 f->f_un.f_forw.f_loghost,
1530 tls_error(f->f_un.f_forw.f_ctx));
1531 goto error;
1532 }
1533 if (tls_connect_socket(f->f_un.f_forw.f_ctx, s,
1534 f->f_un.f_forw.f_host) == -1) {
1535 log_warnx("tls_connect_socket \"%s\": %s",
1536 f->f_un.f_forw.f_loghost,
1537 tls_error(f->f_un.f_forw.f_ctx));
1538 goto error;
1539 }
1540 log_debug("tcp connect callback: tls context success");
1541
1542 buffertls_set(&f->f_un.f_forw.f_buftls, bufev,
1543 f->f_un.f_forw.f_ctx, s);
1544 buffertls_connect(&f->f_un.f_forw.f_buftls, s);
1545 }
1546
1547 return;
1548
1549 error:
1550 if (f->f_un.f_forw.f_ctx) {
1551 tls_free(f->f_un.f_forw.f_ctx);
1552 f->f_un.f_forw.f_ctx = NULL;
1553 }
1554 bufferevent_disable(bufev, EV_READ|EV_WRITE);
1555 close(f->f_file);
1556 f->f_file = -1;
1557 loghost_retry(f);
1558 }
1559
1560 int
loghost_resolve(struct filed * f)1561 loghost_resolve(struct filed *f)
1562 {
1563 char hostname[NI_MAXHOST];
1564 int error;
1565
1566 error = priv_getaddrinfo(f->f_un.f_forw.f_ipproto,
1567 f->f_un.f_forw.f_host, f->f_un.f_forw.f_port,
1568 (struct sockaddr *)&f->f_un.f_forw.f_addr,
1569 sizeof(f->f_un.f_forw.f_addr));
1570 if (error) {
1571 log_warnx("bad hostname \"%s\"", f->f_un.f_forw.f_loghost);
1572 f->f_un.f_forw.f_addr.ss_family = AF_UNSPEC;
1573 return (error);
1574 }
1575
1576 error = getnameinfo((struct sockaddr *)&f->f_un.f_forw.f_addr,
1577 f->f_un.f_forw.f_addr.ss_len, hostname, sizeof(hostname), NULL, 0,
1578 NI_NUMERICHOST | NI_NUMERICSERV |
1579 (strncmp(f->f_un.f_forw.f_ipproto, "udp", 3) == 0 ? NI_DGRAM : 0));
1580 if (error) {
1581 log_warnx("malformed UDP address loghost \"%s\": %s",
1582 f->f_un.f_forw.f_loghost, gai_strerror(error));
1583 strlcpy(hostname, hostname_unknown, sizeof(hostname));
1584 }
1585
1586 log_debug("resolved loghost \"%s\" address %s",
1587 f->f_un.f_forw.f_loghost, hostname);
1588 return (0);
1589 }
1590
1591 void
loghost_retry(struct filed * f)1592 loghost_retry(struct filed *f)
1593 {
1594 struct timeval to;
1595
1596 if (f->f_un.f_forw.f_retrywait == 0)
1597 f->f_un.f_forw.f_retrywait = 1;
1598 else
1599 f->f_un.f_forw.f_retrywait <<= 1;
1600 if (f->f_un.f_forw.f_retrywait > 600)
1601 f->f_un.f_forw.f_retrywait = 600;
1602 to.tv_sec = f->f_un.f_forw.f_retrywait;
1603 to.tv_usec = 0;
1604 evtimer_add(&f->f_un.f_forw.f_ev, &to);
1605
1606 log_debug("retry loghost \"%s\" wait %d",
1607 f->f_un.f_forw.f_loghost, f->f_un.f_forw.f_retrywait);
1608 }
1609
1610 void
udp_resolvecb(int fd,short event,void * arg)1611 udp_resolvecb(int fd, short event, void *arg)
1612 {
1613 struct filed *f = arg;
1614
1615 if (loghost_resolve(f) != 0) {
1616 loghost_retry(f);
1617 return;
1618 }
1619
1620 switch (f->f_un.f_forw.f_addr.ss_family) {
1621 case AF_INET:
1622 f->f_file = fd_udp;
1623 break;
1624 case AF_INET6:
1625 f->f_file = fd_udp6;
1626 break;
1627 }
1628 f->f_un.f_forw.f_retrywait = 0;
1629
1630 if (f->f_dropped > 0) {
1631 char ebuf[ERRBUFSIZE];
1632
1633 snprintf(ebuf, sizeof(ebuf), "to udp loghost \"%s\"",
1634 f->f_un.f_forw.f_loghost);
1635 dropped_warn(&f->f_dropped, ebuf);
1636 }
1637 }
1638
1639 int
tcpbuf_countmsg(struct bufferevent * bufev)1640 tcpbuf_countmsg(struct bufferevent *bufev)
1641 {
1642 char *p, *buf, *end;
1643 int i = 0;
1644
1645 buf = EVBUFFER_DATA(bufev->output);
1646 end = buf + EVBUFFER_LENGTH(bufev->output);
1647 for (p = buf; p < end; p++) {
1648 if (*p == '\n')
1649 i++;
1650 }
1651 return (i);
1652 }
1653
1654 void
usage(void)1655 usage(void)
1656 {
1657
1658 (void)fprintf(stderr,
1659 "usage: syslogd [-46dFhnruVZ] [-a path] [-C CAfile]\n"
1660 "\t[-c cert_file] [-f config_file] [-K CAfile] [-k key_file]\n"
1661 "\t[-m mark_interval] [-p log_socket] [-S listen_address]\n"
1662 "\t[-s reporting_socket] [-T listen_address] [-U bind_address]\n");
1663 exit(1);
1664 }
1665
1666 /*
1667 * Take a raw input line, decode the message, and print the message
1668 * on the appropriate log files.
1669 */
1670 void
printline(char * hname,char * msgstr)1671 printline(char *hname, char *msgstr)
1672 {
1673 struct msg msg;
1674 char *p, *q, line[LOG_MAXLINE + 4 + 1]; /* message, encoding, NUL */
1675
1676 p = msgstr;
1677 for (q = line; *p && q < &line[LOG_MAXLINE]; p++) {
1678 if (*p == '\n')
1679 *q++ = ' ';
1680 else
1681 q = vis(q, *p, VIS_NOSLASH, 0);
1682 }
1683 line[LOG_MAXLINE] = *q = '\0';
1684
1685 parsemsg(line, &msg);
1686 if (msg.m_pri == -1)
1687 msg.m_pri = DEFUPRI;
1688 /*
1689 * Don't allow users to log kernel messages.
1690 * NOTE: since LOG_KERN == 0 this will also match
1691 * messages with no facility specified.
1692 */
1693 if (LOG_FAC(msg.m_pri) == LOG_KERN)
1694 msg.m_pri = LOG_USER | LOG_PRI(msg.m_pri);
1695
1696 if (msg.m_timestamp[0] == '\0')
1697 current_time(msg.m_timestamp);
1698
1699 logmsg(&msg, 0, hname);
1700 }
1701
1702 /*
1703 * Take a raw input line from /dev/klog, split and format similar to syslog().
1704 */
1705 void
printsys(char * msgstr)1706 printsys(char *msgstr)
1707 {
1708 struct msg msg;
1709 int c, flags;
1710 char *lp, *p, *q;
1711 size_t prilen;
1712 int l;
1713
1714 current_time(msg.m_timestamp);
1715 strlcpy(msg.m_prog, _PATH_UNIX, sizeof(msg.m_prog));
1716 l = snprintf(msg.m_msg, sizeof(msg.m_msg), "%s: ", _PATH_UNIX);
1717 if (l < 0 || l >= sizeof(msg.m_msg)) {
1718 msg.m_msg[0] = '\0';
1719 l = 0;
1720 }
1721 lp = msg.m_msg + l;
1722 for (p = msgstr; *p != '\0'; ) {
1723 flags = SYNC_FILE; /* fsync file after write */
1724 msg.m_pri = DEFSPRI;
1725 prilen = parsemsg_priority(p, &msg.m_pri);
1726 p += prilen;
1727 if (prilen == 0) {
1728 /* kernel printf's come out on console */
1729 flags |= IGN_CONS;
1730 }
1731 if (msg.m_pri &~ (LOG_FACMASK|LOG_PRIMASK))
1732 msg.m_pri = DEFSPRI;
1733
1734 q = lp;
1735 while (*p && (c = *p++) != '\n' &&
1736 q < &msg.m_msg[sizeof(msg.m_msg) - 4])
1737 q = vis(q, c, VIS_NOSLASH, 0);
1738
1739 logmsg(&msg, flags, LocalHostName);
1740 }
1741 }
1742
1743 void
vlogmsg(int pri,const char * prog,const char * fmt,va_list ap)1744 vlogmsg(int pri, const char *prog, const char *fmt, va_list ap)
1745 {
1746 struct msg msg;
1747 int l;
1748
1749 msg.m_pri = pri;
1750 current_time(msg.m_timestamp);
1751 strlcpy(msg.m_prog, prog, sizeof(msg.m_prog));
1752 l = snprintf(msg.m_msg, sizeof(msg.m_msg), "%s[%d]: ", prog, getpid());
1753 if (l < 0 || l >= sizeof(msg.m_msg))
1754 l = 0;
1755 l = vsnprintf(msg.m_msg + l, sizeof(msg.m_msg) - l, fmt, ap);
1756 if (l < 0)
1757 strlcpy(msg.m_msg, fmt, sizeof(msg.m_msg));
1758
1759 if (!Started) {
1760 fprintf(stderr, "%s\n", msg.m_msg);
1761 init_dropped++;
1762 return;
1763 }
1764 logmsg(&msg, 0, LocalHostName);
1765 }
1766
1767 struct timeval now;
1768
1769 void
current_time(char * timestamp)1770 current_time(char *timestamp)
1771 {
1772 (void)gettimeofday(&now, NULL);
1773
1774 if (ZuluTime) {
1775 struct tm *tm;
1776 size_t l;
1777
1778 tm = gmtime(&now.tv_sec);
1779 l = strftime(timestamp, 33, "%FT%T", tm);
1780 /*
1781 * Use only millisecond precision as some time has
1782 * passed since syslog(3) was called.
1783 */
1784 snprintf(timestamp + l, 33 - l, ".%03ldZ", now.tv_usec / 1000);
1785 } else
1786 strlcpy(timestamp, ctime(&now.tv_sec) + 4, 16);
1787 }
1788
1789 /*
1790 * Log a message to the appropriate log files, users, etc. based on
1791 * the priority.
1792 */
1793 void
logmsg(struct msg * msg,int flags,char * from)1794 logmsg(struct msg *msg, int flags, char *from)
1795 {
1796 struct filed *f;
1797 int fac, msglen, prilev;
1798
1799 (void)gettimeofday(&now, NULL);
1800 log_debug("logmsg: pri 0%o, flags 0x%x, from %s, prog %s, msg %s",
1801 msg->m_pri, flags, from, msg->m_prog, msg->m_msg);
1802
1803 /* extract facility and priority level */
1804 if (flags & MARK)
1805 fac = LOG_NFACILITIES;
1806 else
1807 fac = LOG_FAC(msg->m_pri);
1808 prilev = LOG_PRI(msg->m_pri);
1809
1810 /* log the message to the particular outputs */
1811 if (!Initialized) {
1812 f = &consfile;
1813 if (f->f_type == F_CONSOLE) {
1814 strlcpy(f->f_lasttime, msg->m_timestamp,
1815 sizeof(f->f_lasttime));
1816 strlcpy(f->f_prevhost, from,
1817 sizeof(f->f_prevhost));
1818 fprintlog(f, flags, msg->m_msg);
1819 /* May be set to F_UNUSED, try again next time. */
1820 f->f_type = F_CONSOLE;
1821 }
1822 init_dropped++;
1823 return;
1824 }
1825 /* log the message to the particular outputs */
1826 msglen = strlen(msg->m_msg);
1827 SIMPLEQ_FOREACH(f, &Files, f_next) {
1828 /* skip messages that are incorrect priority */
1829 if (f->f_pmask[fac] < prilev ||
1830 f->f_pmask[fac] == INTERNAL_NOPRI)
1831 continue;
1832
1833 /* skip messages with the incorrect program or hostname */
1834 if (f->f_program && fnmatch(f->f_program, msg->m_prog, 0) != 0)
1835 continue;
1836 if (f->f_hostname && fnmatch(f->f_hostname, from, 0) != 0)
1837 continue;
1838
1839 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1840 continue;
1841
1842 /* don't output marks to recently written files */
1843 if ((flags & MARK) &&
1844 (now.tv_sec - f->f_time) < MarkInterval / 2)
1845 continue;
1846
1847 /*
1848 * suppress duplicate lines to this file
1849 */
1850 if ((Repeat == 0 || (Repeat == 1 &&
1851 (f->f_type != F_PIPE && f->f_type != F_FORWUDP &&
1852 f->f_type != F_FORWTCP && f->f_type != F_FORWTLS))) &&
1853 (flags & MARK) == 0 && msglen == f->f_prevlen &&
1854 f->f_dropped == 0 &&
1855 !strcmp(msg->m_msg, f->f_prevline) &&
1856 !strcmp(from, f->f_prevhost)) {
1857 strlcpy(f->f_lasttime, msg->m_timestamp,
1858 sizeof(f->f_lasttime));
1859 f->f_prevcount++;
1860 log_debug("msg repeated %d times, %ld sec of %d",
1861 f->f_prevcount, (long)(now.tv_sec - f->f_time),
1862 repeatinterval[f->f_repeatcount]);
1863 /*
1864 * If domark would have logged this by now,
1865 * flush it now (so we don't hold isolated messages),
1866 * but back off so we'll flush less often
1867 * in the future.
1868 */
1869 if (now.tv_sec > REPEATTIME(f)) {
1870 fprintlog(f, flags, (char *)NULL);
1871 BACKOFF(f);
1872 }
1873 } else {
1874 /* new line, save it */
1875 if (f->f_prevcount)
1876 fprintlog(f, 0, (char *)NULL);
1877 f->f_repeatcount = 0;
1878 f->f_prevpri = msg->m_pri;
1879 strlcpy(f->f_lasttime, msg->m_timestamp,
1880 sizeof(f->f_lasttime));
1881 strlcpy(f->f_prevhost, from,
1882 sizeof(f->f_prevhost));
1883 if (msglen < MAXSVLINE) {
1884 f->f_prevlen = msglen;
1885 strlcpy(f->f_prevline, msg->m_msg,
1886 sizeof(f->f_prevline));
1887 fprintlog(f, flags, (char *)NULL);
1888 } else {
1889 f->f_prevline[0] = 0;
1890 f->f_prevlen = 0;
1891 fprintlog(f, flags, msg->m_msg);
1892 }
1893 }
1894
1895 if (f->f_quick)
1896 break;
1897 }
1898 }
1899
1900 void
fprintlog(struct filed * f,int flags,char * msg)1901 fprintlog(struct filed *f, int flags, char *msg)
1902 {
1903 struct iovec iov[IOVCNT], *v;
1904 struct msghdr msghdr;
1905 int l, retryonce;
1906 char line[LOG_MAXLINE + 1], pribuf[13], greetings[500], repbuf[80];
1907 char ebuf[ERRBUFSIZE];
1908
1909 v = iov;
1910 switch (f->f_type) {
1911 case F_FORWUDP:
1912 case F_FORWTCP:
1913 case F_FORWTLS:
1914 l = snprintf(pribuf, sizeof(pribuf), "<%d>", f->f_prevpri);
1915 if (l < 0)
1916 l = strlcpy(pribuf, "<13>", sizeof(pribuf));
1917 if (l >= sizeof(pribuf))
1918 l = sizeof(pribuf) - 1;
1919 v->iov_base = pribuf;
1920 v->iov_len = l;
1921 break;
1922 case F_WALL:
1923 l = snprintf(greetings, sizeof(greetings),
1924 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1925 f->f_prevhost, ctime(&now.tv_sec));
1926 if (l < 0)
1927 l = strlcpy(greetings,
1928 "\r\n\7Message from syslogd ...\r\n",
1929 sizeof(greetings));
1930 if (l >= sizeof(greetings))
1931 l = sizeof(greetings) - 1;
1932 v->iov_base = greetings;
1933 v->iov_len = l;
1934 break;
1935 default:
1936 v->iov_base = "";
1937 v->iov_len = 0;
1938 break;
1939 }
1940 v++;
1941
1942 if (f->f_lasttime[0] != '\0') {
1943 v->iov_base = f->f_lasttime;
1944 v->iov_len = strlen(f->f_lasttime);
1945 v++;
1946 v->iov_base = " ";
1947 v->iov_len = 1;
1948 } else {
1949 v->iov_base = "";
1950 v->iov_len = 0;
1951 v++;
1952 v->iov_base = "";
1953 v->iov_len = 0;
1954 }
1955 v++;
1956
1957 switch (f->f_type) {
1958 case F_FORWUDP:
1959 case F_FORWTCP:
1960 case F_FORWTLS:
1961 if (IncludeHostname) {
1962 v->iov_base = LocalHostName;
1963 v->iov_len = strlen(LocalHostName);
1964 v++;
1965 v->iov_base = " ";
1966 v->iov_len = 1;
1967 } else {
1968 /* XXX RFC requires to include host name */
1969 v->iov_base = "";
1970 v->iov_len = 0;
1971 v++;
1972 v->iov_base = "";
1973 v->iov_len = 0;
1974 }
1975 break;
1976 default:
1977 if (f->f_prevhost[0] != '\0') {
1978 v->iov_base = f->f_prevhost;
1979 v->iov_len = strlen(v->iov_base);
1980 v++;
1981 v->iov_base = " ";
1982 v->iov_len = 1;
1983 } else {
1984 v->iov_base = "";
1985 v->iov_len = 0;
1986 v++;
1987 v->iov_base = "";
1988 v->iov_len = 0;
1989 }
1990 break;
1991 }
1992 v++;
1993
1994 if (msg) {
1995 v->iov_base = msg;
1996 v->iov_len = strlen(msg);
1997 } else if (f->f_prevcount > 1) {
1998 l = snprintf(repbuf, sizeof(repbuf),
1999 "last message repeated %d times", f->f_prevcount);
2000 if (l < 0)
2001 l = strlcpy(repbuf, "last message repeated",
2002 sizeof(repbuf));
2003 if (l >= sizeof(repbuf))
2004 l = sizeof(repbuf) - 1;
2005 v->iov_base = repbuf;
2006 v->iov_len = l;
2007 } else {
2008 v->iov_base = f->f_prevline;
2009 v->iov_len = f->f_prevlen;
2010 }
2011 v++;
2012
2013 switch (f->f_type) {
2014 case F_CONSOLE:
2015 case F_TTY:
2016 case F_USERS:
2017 case F_WALL:
2018 v->iov_base = "\r\n";
2019 v->iov_len = 2;
2020 break;
2021 case F_FILE:
2022 case F_PIPE:
2023 case F_FORWTCP:
2024 case F_FORWTLS:
2025 v->iov_base = "\n";
2026 v->iov_len = 1;
2027 break;
2028 default:
2029 v->iov_base = "";
2030 v->iov_len = 0;
2031 break;
2032 }
2033 v = NULL;
2034
2035 log_debugadd("Logging to %s", TypeNames[f->f_type]);
2036 f->f_time = now.tv_sec;
2037
2038 switch (f->f_type) {
2039 case F_UNUSED:
2040 log_debug("");
2041 break;
2042
2043 case F_FORWUDP:
2044 log_debugadd(" %s", f->f_un.f_forw.f_loghost);
2045 if (f->f_un.f_forw.f_addr.ss_family == AF_UNSPEC) {
2046 log_debug(" (dropped not resolved)");
2047 f->f_dropped++;
2048 break;
2049 }
2050 l = iov[0].iov_len + iov[1].iov_len + iov[2].iov_len +
2051 iov[3].iov_len + iov[4].iov_len + iov[5].iov_len +
2052 iov[6].iov_len;
2053 if (l > MAX_UDPMSG) {
2054 l -= MAX_UDPMSG;
2055 if (iov[5].iov_len > l)
2056 iov[5].iov_len -= l;
2057 else
2058 iov[5].iov_len = 0;
2059 }
2060 memset(&msghdr, 0, sizeof(msghdr));
2061 msghdr.msg_name = &f->f_un.f_forw.f_addr;
2062 msghdr.msg_namelen = f->f_un.f_forw.f_addr.ss_len;
2063 msghdr.msg_iov = iov;
2064 msghdr.msg_iovlen = IOVCNT;
2065 if (sendmsg(f->f_file, &msghdr, 0) == -1) {
2066 switch (errno) {
2067 case EACCES:
2068 case EADDRNOTAVAIL:
2069 case EHOSTDOWN:
2070 case EHOSTUNREACH:
2071 case ENETDOWN:
2072 case ENETUNREACH:
2073 case ENOBUFS:
2074 case EWOULDBLOCK:
2075 log_debug(" (dropped send error)");
2076 f->f_dropped++;
2077 /* silently dropped */
2078 break;
2079 default:
2080 log_debug(" (dropped permanent send error)");
2081 f->f_dropped++;
2082 f->f_type = F_UNUSED;
2083 snprintf(ebuf, sizeof(ebuf),
2084 "to udp loghost \"%s\"",
2085 f->f_un.f_forw.f_loghost);
2086 dropped_warn(&f->f_dropped, ebuf);
2087 log_warn("loghost \"%s\" disabled, sendmsg",
2088 f->f_un.f_forw.f_loghost);
2089 break;
2090 }
2091 } else {
2092 log_debug("");
2093 if (f->f_dropped > 0) {
2094 snprintf(ebuf, sizeof(ebuf),
2095 "to udp loghost \"%s\"",
2096 f->f_un.f_forw.f_loghost);
2097 dropped_warn(&f->f_dropped, ebuf);
2098 }
2099 }
2100 break;
2101
2102 case F_FORWTCP:
2103 case F_FORWTLS:
2104 log_debugadd(" %s", f->f_un.f_forw.f_loghost);
2105 if (EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) >=
2106 MAX_TCPBUF) {
2107 log_debug(" (dropped tcpbuf full)");
2108 f->f_dropped++;
2109 break;
2110 }
2111 /*
2112 * Syslog over TLS RFC 5425 4.3. Sending Data
2113 * Syslog over TCP RFC 6587 3.4.1. Octet Counting
2114 * Use an additional '\n' to split messages. This allows
2115 * buffer synchronisation, helps legacy implementations,
2116 * and makes line based testing easier.
2117 */
2118 l = evbuffer_add_printf(f->f_un.f_forw.f_bufev->output,
2119 "%zu %s%s%s%s%s%s%s", iov[0].iov_len +
2120 iov[1].iov_len + iov[2].iov_len +
2121 iov[3].iov_len + iov[4].iov_len +
2122 iov[5].iov_len + iov[6].iov_len,
2123 (char *)iov[0].iov_base,
2124 (char *)iov[1].iov_base, (char *)iov[2].iov_base,
2125 (char *)iov[3].iov_base, (char *)iov[4].iov_base,
2126 (char *)iov[5].iov_base, (char *)iov[6].iov_base);
2127 if (l < 0) {
2128 log_debug(" (dropped evbuffer add)");
2129 f->f_dropped++;
2130 break;
2131 }
2132 bufferevent_enable(f->f_un.f_forw.f_bufev, EV_WRITE);
2133 log_debug("");
2134 break;
2135
2136 case F_CONSOLE:
2137 if (flags & IGN_CONS) {
2138 log_debug(" (ignored)");
2139 break;
2140 }
2141 /* FALLTHROUGH */
2142 case F_TTY:
2143 case F_FILE:
2144 case F_PIPE:
2145 log_debug(" %s", f->f_un.f_fname);
2146 retryonce = 0;
2147 again:
2148 if (writev(f->f_file, iov, IOVCNT) == -1) {
2149 int e = errno;
2150
2151 /* allow to recover from file system full */
2152 if (e == ENOSPC && f->f_type == F_FILE) {
2153 if (f->f_dropped++ == 0) {
2154 f->f_type = F_UNUSED;
2155 errno = e;
2156 log_warn("write to file \"%s\"",
2157 f->f_un.f_fname);
2158 f->f_type = F_FILE;
2159 }
2160 break;
2161 }
2162
2163 /* pipe is non-blocking. log and drop message if full */
2164 if (e == EAGAIN && f->f_type == F_PIPE) {
2165 if (now.tv_sec - f->f_lasterrtime > 120) {
2166 f->f_lasterrtime = now.tv_sec;
2167 log_warn("write to pipe \"%s\"",
2168 f->f_un.f_fname);
2169 }
2170 break;
2171 }
2172
2173 /*
2174 * Check for errors on TTY's or program pipes.
2175 * Errors happen due to loss of tty or died programs.
2176 */
2177 if (e == EAGAIN) {
2178 /*
2179 * Silently drop messages on blocked write.
2180 * This can happen when logging to a locked tty.
2181 */
2182 break;
2183 }
2184
2185 (void)close(f->f_file);
2186 if ((e == EIO || e == EBADF) &&
2187 f->f_type != F_FILE && f->f_type != F_PIPE &&
2188 !retryonce) {
2189 f->f_file = priv_open_tty(f->f_un.f_fname);
2190 retryonce = 1;
2191 if (f->f_file < 0) {
2192 f->f_type = F_UNUSED;
2193 log_warn("priv_open_tty \"%s\"",
2194 f->f_un.f_fname);
2195 } else
2196 goto again;
2197 } else if ((e == EPIPE || e == EBADF) &&
2198 f->f_type == F_PIPE && !retryonce) {
2199 f->f_file = priv_open_log(f->f_un.f_fname);
2200 retryonce = 1;
2201 if (f->f_file < 0) {
2202 f->f_type = F_UNUSED;
2203 log_warn("priv_open_log \"%s\"",
2204 f->f_un.f_fname);
2205 } else
2206 goto again;
2207 } else {
2208 f->f_type = F_UNUSED;
2209 f->f_file = -1;
2210 errno = e;
2211 log_warn("writev \"%s\"", f->f_un.f_fname);
2212 }
2213 } else {
2214 if (flags & SYNC_FILE)
2215 (void)fsync(f->f_file);
2216 if (f->f_dropped > 0 && f->f_type == F_FILE) {
2217 snprintf(ebuf, sizeof(ebuf), "to file \"%s\"",
2218 f->f_un.f_fname);
2219 dropped_warn(&f->f_dropped, ebuf);
2220 }
2221 }
2222 break;
2223
2224 case F_USERS:
2225 case F_WALL:
2226 log_debug("");
2227 wallmsg(f, iov);
2228 break;
2229
2230 case F_MEMBUF:
2231 log_debug("");
2232 l = snprintf(line, sizeof(line),
2233 "%s%s%s%s%s%s%s", (char *)iov[0].iov_base,
2234 (char *)iov[1].iov_base, (char *)iov[2].iov_base,
2235 (char *)iov[3].iov_base, (char *)iov[4].iov_base,
2236 (char *)iov[5].iov_base, (char *)iov[6].iov_base);
2237 if (l < 0)
2238 l = strlcpy(line, iov[5].iov_base, sizeof(line));
2239 if (ringbuf_append_line(f->f_un.f_mb.f_rb, line) == 1)
2240 f->f_un.f_mb.f_overflow = 1;
2241 if (f->f_un.f_mb.f_attached)
2242 ctlconn_logto(line);
2243 break;
2244 }
2245 f->f_prevcount = 0;
2246 }
2247
2248 /*
2249 * WALLMSG -- Write a message to the world at large
2250 *
2251 * Write the specified message to either the entire
2252 * world, or a list of approved users.
2253 */
2254 void
wallmsg(struct filed * f,struct iovec * iov)2255 wallmsg(struct filed *f, struct iovec *iov)
2256 {
2257 struct utmp ut;
2258 char utline[sizeof(ut.ut_line) + 1];
2259 static int reenter; /* avoid calling ourselves */
2260 FILE *uf;
2261 int i;
2262
2263 if (reenter++)
2264 return;
2265 if ((uf = priv_open_utmp()) == NULL) {
2266 log_warn("priv_open_utmp");
2267 reenter = 0;
2268 return;
2269 }
2270 while (fread(&ut, sizeof(ut), 1, uf) == 1) {
2271 if (ut.ut_name[0] == '\0')
2272 continue;
2273 /* must use strncpy since ut_* may not be NUL terminated */
2274 strncpy(utline, ut.ut_line, sizeof(utline) - 1);
2275 utline[sizeof(utline) - 1] = '\0';
2276 if (f->f_type == F_WALL) {
2277 ttymsg(utline, iov);
2278 continue;
2279 }
2280 /* should we send the message to this user? */
2281 for (i = 0; i < MAXUNAMES; i++) {
2282 if (!f->f_un.f_uname[i][0])
2283 break;
2284 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
2285 UT_NAMESIZE)) {
2286 ttymsg(utline, iov);
2287 break;
2288 }
2289 }
2290 }
2291 (void)fclose(uf);
2292 reenter = 0;
2293 }
2294
2295 /*
2296 * Return a printable representation of a host address.
2297 */
2298 void
cvthname(struct sockaddr * f,char * result,size_t res_len)2299 cvthname(struct sockaddr *f, char *result, size_t res_len)
2300 {
2301 int error;
2302
2303 error = getnameinfo(f, f->sa_len, result, res_len, NULL, 0,
2304 NI_NUMERICHOST | NI_NUMERICSERV | NI_DGRAM);
2305 if (error) {
2306 log_warnx("malformed UDP from address: %s",
2307 gai_strerror(error));
2308 strlcpy(result, hostname_unknown, res_len);
2309 return;
2310 }
2311 log_debug("cvthname(%s)", result);
2312 if (NoDNS)
2313 return;
2314
2315 if (priv_getnameinfo(f, f->sa_len, result, res_len) != 0)
2316 log_debug("Host name for from address (%s) unknown", result);
2317 }
2318
2319 void
die_signalcb(int signum,short event,void * arg)2320 die_signalcb(int signum, short event, void *arg)
2321 {
2322 die(signum);
2323 }
2324
2325 void
mark_timercb(int unused,short event,void * arg)2326 mark_timercb(int unused, short event, void *arg)
2327 {
2328 struct event *ev = arg;
2329 struct timeval to;
2330
2331 markit();
2332
2333 to.tv_sec = TIMERINTVL;
2334 to.tv_usec = 0;
2335 evtimer_add(ev, &to);
2336 }
2337
2338 void
init_signalcb(int signum,short event,void * arg)2339 init_signalcb(int signum, short event, void *arg)
2340 {
2341 init();
2342 log_info(LOG_INFO, "restart");
2343
2344 dropped_warn(&udpsend_dropped, "to udp loghost");
2345 dropped_warn(&tcpbuf_dropped, "to remote loghost");
2346 dropped_warn(&file_dropped, "to file");
2347 log_debug("syslogd: restarted");
2348 }
2349
2350 void
logevent(int severity,const char * msg)2351 logevent(int severity, const char *msg)
2352 {
2353 log_debug("libevent: [%d] %s", severity, msg);
2354 }
2355
2356 void
dropped_warn(int * count,const char * what)2357 dropped_warn(int *count, const char *what)
2358 {
2359 int dropped;
2360
2361 if (*count == 0)
2362 return;
2363
2364 dropped = *count;
2365 *count = 0;
2366 log_info(LOG_WARNING, "dropped %d message%s %s",
2367 dropped, dropped == 1 ? "" : "s", what);
2368 }
2369
2370 __dead void
die(int signo)2371 die(int signo)
2372 {
2373 struct filed *f;
2374
2375 SIMPLEQ_FOREACH(f, &Files, f_next) {
2376 /* flush any pending output */
2377 if (f->f_prevcount)
2378 fprintlog(f, 0, (char *)NULL);
2379 if (f->f_type == F_FORWUDP) {
2380 udpsend_dropped += f->f_dropped;
2381 f->f_dropped = 0;
2382 }
2383 if (f->f_type == F_FORWTLS || f->f_type == F_FORWTCP) {
2384 tcpbuf_dropped += f->f_dropped +
2385 tcpbuf_countmsg(f->f_un.f_forw.f_bufev);
2386 f->f_dropped = 0;
2387 }
2388 if (f->f_type == F_FILE) {
2389 file_dropped += f->f_dropped;
2390 f->f_dropped = 0;
2391 }
2392 }
2393 dropped_warn(&init_dropped, "during initialization");
2394 dropped_warn(&udpsend_dropped, "to udp loghost");
2395 dropped_warn(&tcpbuf_dropped, "to remote loghost");
2396 dropped_warn(&file_dropped, "to file");
2397
2398 if (signo)
2399 log_info(LOG_ERR, "exiting on signal %d", signo);
2400 log_debug("syslogd: exited");
2401 exit(0);
2402 }
2403
2404 /*
2405 * INIT -- Initialize syslogd from configuration table
2406 */
2407 void
init(void)2408 init(void)
2409 {
2410 char progblock[NAME_MAX+1], hostblock[NAME_MAX+1], *cline, *p, *q;
2411 struct filed_list mb;
2412 struct filed *f, *m;
2413 FILE *cf;
2414 int i;
2415 size_t s;
2416
2417 log_debug("init");
2418
2419 /* If config file has been modified, then just die to restart */
2420 if (priv_config_modified()) {
2421 log_debug("config file changed: dying");
2422 die(0);
2423 }
2424
2425 /*
2426 * Close all open log files.
2427 */
2428 Initialized = 0;
2429 SIMPLEQ_INIT(&mb);
2430 while (!SIMPLEQ_EMPTY(&Files)) {
2431 f = SIMPLEQ_FIRST(&Files);
2432 SIMPLEQ_REMOVE_HEAD(&Files, f_next);
2433 /* flush any pending output */
2434 if (f->f_prevcount)
2435 fprintlog(f, 0, (char *)NULL);
2436
2437 switch (f->f_type) {
2438 case F_FORWUDP:
2439 evtimer_del(&f->f_un.f_forw.f_ev);
2440 udpsend_dropped += f->f_dropped;
2441 f->f_dropped = 0;
2442 free(f->f_un.f_forw.f_ipproto);
2443 free(f->f_un.f_forw.f_host);
2444 free(f->f_un.f_forw.f_port);
2445 break;
2446 case F_FORWTLS:
2447 if (f->f_un.f_forw.f_ctx) {
2448 tls_close(f->f_un.f_forw.f_ctx);
2449 tls_free(f->f_un.f_forw.f_ctx);
2450 }
2451 /* FALLTHROUGH */
2452 case F_FORWTCP:
2453 evtimer_del(&f->f_un.f_forw.f_ev);
2454 tcpbuf_dropped += f->f_dropped;
2455 if (f->f_un.f_forw.f_bufev) {
2456 bufferevent_disable(f->f_un.f_forw.f_bufev,
2457 EV_READ|EV_WRITE);
2458 tcpbuf_dropped +=
2459 tcpbuf_countmsg(f->f_un.f_forw.f_bufev);
2460 bufferevent_free(f->f_un.f_forw.f_bufev);
2461 }
2462 free(f->f_un.f_forw.f_ipproto);
2463 free(f->f_un.f_forw.f_host);
2464 free(f->f_un.f_forw.f_port);
2465 /* FALLTHROUGH */
2466 case F_FILE:
2467 if (f->f_type == F_FILE)
2468 file_dropped += f->f_dropped;
2469 f->f_dropped = 0;
2470 /* FALLTHROUGH */
2471 case F_TTY:
2472 case F_CONSOLE:
2473 case F_PIPE:
2474 (void)close(f->f_file);
2475 break;
2476 }
2477 free(f->f_program);
2478 free(f->f_hostname);
2479 if (f->f_type == F_MEMBUF) {
2480 f->f_program = NULL;
2481 f->f_hostname = NULL;
2482 log_debug("add %p to mb", f);
2483 SIMPLEQ_INSERT_HEAD(&mb, f, f_next);
2484 } else
2485 free(f);
2486 }
2487 SIMPLEQ_INIT(&Files);
2488
2489 /* open the configuration file */
2490 if ((cf = priv_open_config()) == NULL) {
2491 log_debug("cannot open %s", ConfFile);
2492 SIMPLEQ_INSERT_TAIL(&Files,
2493 cfline("*.ERR\t/dev/console", "*", "*"), f_next);
2494 SIMPLEQ_INSERT_TAIL(&Files,
2495 cfline("*.PANIC\t*", "*", "*"), f_next);
2496 Initialized = 1;
2497 dropped_warn(&init_dropped, "during initialization");
2498 return;
2499 }
2500
2501 /*
2502 * Foreach line in the conf table, open that file.
2503 */
2504 cline = NULL;
2505 s = 0;
2506 strlcpy(progblock, "*", sizeof(progblock));
2507 strlcpy(hostblock, "*", sizeof(hostblock));
2508 send_udp = send_udp6 = 0;
2509 while (getline(&cline, &s, cf) != -1) {
2510 /*
2511 * check for end-of-section, comments, strip off trailing
2512 * spaces and newline character. !progblock and +hostblock
2513 * are treated specially: the following lines apply only to
2514 * that program.
2515 */
2516 for (p = cline; isspace((unsigned char)*p); ++p)
2517 continue;
2518 if (*p == '\0' || *p == '#')
2519 continue;
2520 if (*p == '!' || *p == '+') {
2521 q = (*p == '!') ? progblock : hostblock;
2522 p++;
2523 while (isspace((unsigned char)*p))
2524 p++;
2525 if (*p == '\0' || (*p == '*' && (p[1] == '\0' ||
2526 isspace((unsigned char)p[1])))) {
2527 strlcpy(q, "*", NAME_MAX+1);
2528 continue;
2529 }
2530 for (i = 0; i < NAME_MAX; i++) {
2531 if (*p == '\0' || isspace((unsigned char)*p))
2532 break;
2533 *q++ = *p++;
2534 }
2535 *q = '\0';
2536 continue;
2537 }
2538
2539 p = cline + strlen(cline);
2540 while (p > cline)
2541 if (!isspace((unsigned char)*--p)) {
2542 p++;
2543 break;
2544 }
2545 *p = '\0';
2546 f = cfline(cline, progblock, hostblock);
2547 if (f != NULL)
2548 SIMPLEQ_INSERT_TAIL(&Files, f, f_next);
2549 }
2550 free(cline);
2551 if (!feof(cf))
2552 fatal("read config file");
2553
2554 /* Match and initialize the memory buffers */
2555 SIMPLEQ_FOREACH(f, &Files, f_next) {
2556 if (f->f_type != F_MEMBUF)
2557 continue;
2558 log_debug("Initialize membuf %s at %p",
2559 f->f_un.f_mb.f_mname, f);
2560
2561 SIMPLEQ_FOREACH(m, &mb, f_next) {
2562 if (m->f_un.f_mb.f_rb == NULL)
2563 continue;
2564 if (strcmp(m->f_un.f_mb.f_mname,
2565 f->f_un.f_mb.f_mname) == 0)
2566 break;
2567 }
2568 if (m == NULL) {
2569 log_debug("Membuf no match");
2570 f->f_un.f_mb.f_rb = ringbuf_init(f->f_un.f_mb.f_len);
2571 if (f->f_un.f_mb.f_rb == NULL) {
2572 f->f_type = F_UNUSED;
2573 log_warn("allocate membuf");
2574 }
2575 } else {
2576 log_debug("Membuf match f:%p, m:%p", f, m);
2577 f->f_un = m->f_un;
2578 m->f_un.f_mb.f_rb = NULL;
2579 }
2580 }
2581
2582 /* make sure remaining buffers are freed */
2583 while (!SIMPLEQ_EMPTY(&mb)) {
2584 m = SIMPLEQ_FIRST(&mb);
2585 SIMPLEQ_REMOVE_HEAD(&mb, f_next);
2586 if (m->f_un.f_mb.f_rb != NULL) {
2587 log_warnx("mismatched membuf");
2588 ringbuf_free(m->f_un.f_mb.f_rb);
2589 }
2590 log_debug("Freeing membuf %p", m);
2591
2592 free(m);
2593 }
2594
2595 /* close the configuration file */
2596 (void)fclose(cf);
2597
2598 Initialized = 1;
2599 dropped_warn(&init_dropped, "during initialization");
2600
2601 if (SecureMode) {
2602 /*
2603 * If generic UDP file descriptors are used neither
2604 * for receiving nor for sending, close them. Then
2605 * there is no useless *.514 in netstat.
2606 */
2607 if (fd_udp != -1 && !send_udp) {
2608 close(fd_udp);
2609 fd_udp = -1;
2610 }
2611 if (fd_udp6 != -1 && !send_udp6) {
2612 close(fd_udp6);
2613 fd_udp6 = -1;
2614 }
2615 }
2616
2617 if (Debug) {
2618 SIMPLEQ_FOREACH(f, &Files, f_next) {
2619 for (i = 0; i <= LOG_NFACILITIES; i++)
2620 if (f->f_pmask[i] == INTERNAL_NOPRI)
2621 printf("X ");
2622 else
2623 printf("%d ", f->f_pmask[i]);
2624 printf("%s: ", TypeNames[f->f_type]);
2625 switch (f->f_type) {
2626 case F_FILE:
2627 case F_TTY:
2628 case F_CONSOLE:
2629 case F_PIPE:
2630 printf("%s", f->f_un.f_fname);
2631 break;
2632
2633 case F_FORWUDP:
2634 case F_FORWTCP:
2635 case F_FORWTLS:
2636 printf("%s", f->f_un.f_forw.f_loghost);
2637 break;
2638
2639 case F_USERS:
2640 for (i = 0; i < MAXUNAMES &&
2641 *f->f_un.f_uname[i]; i++)
2642 printf("%s, ", f->f_un.f_uname[i]);
2643 break;
2644
2645 case F_MEMBUF:
2646 printf("%s", f->f_un.f_mb.f_mname);
2647 break;
2648
2649 }
2650 if (f->f_program || f->f_hostname)
2651 printf(" (%s, %s)",
2652 f->f_program ? f->f_program : "*",
2653 f->f_hostname ? f->f_hostname : "*");
2654 printf("\n");
2655 }
2656 }
2657 }
2658
2659 #define progmatches(p1, p2) \
2660 (p1 == p2 || (p1 != NULL && p2 != NULL && strcmp(p1, p2) == 0))
2661
2662 /*
2663 * Spot a line with a duplicate file, pipe, console, tty, or membuf target.
2664 */
2665 struct filed *
find_dup(struct filed * f)2666 find_dup(struct filed *f)
2667 {
2668 struct filed *list;
2669
2670 SIMPLEQ_FOREACH(list, &Files, f_next) {
2671 if (list->f_quick || f->f_quick)
2672 continue;
2673 switch (list->f_type) {
2674 case F_FILE:
2675 case F_TTY:
2676 case F_CONSOLE:
2677 case F_PIPE:
2678 if (strcmp(list->f_un.f_fname, f->f_un.f_fname) == 0 &&
2679 progmatches(list->f_program, f->f_program) &&
2680 progmatches(list->f_hostname, f->f_hostname)) {
2681 log_debug("duplicate %s", f->f_un.f_fname);
2682 return (list);
2683 }
2684 break;
2685 case F_MEMBUF:
2686 if (strcmp(list->f_un.f_mb.f_mname,
2687 f->f_un.f_mb.f_mname) == 0 &&
2688 progmatches(list->f_program, f->f_program) &&
2689 progmatches(list->f_hostname, f->f_hostname)) {
2690 log_debug("duplicate membuf %s",
2691 f->f_un.f_mb.f_mname);
2692 return (list);
2693 }
2694 break;
2695 }
2696 }
2697 return (NULL);
2698 }
2699
2700 /*
2701 * Crack a configuration file line
2702 */
2703 struct filed *
cfline(char * line,char * progblock,char * hostblock)2704 cfline(char *line, char *progblock, char *hostblock)
2705 {
2706 int i, pri;
2707 size_t rb_len;
2708 char *bp, *p, *q, *proto, *host, *port, *ipproto;
2709 char buf[LOG_MAXLINE];
2710 struct filed *xf, *f, *d;
2711 struct timeval to;
2712
2713 log_debug("cfline(\"%s\", f, \"%s\", \"%s\")",
2714 line, progblock, hostblock);
2715
2716 if ((f = calloc(1, sizeof(*f))) == NULL)
2717 fatal("allocate struct filed");
2718 for (i = 0; i <= LOG_NFACILITIES; i++)
2719 f->f_pmask[i] = INTERNAL_NOPRI;
2720
2721 /* save program name if any */
2722 f->f_quick = 0;
2723 if (*progblock == '!') {
2724 progblock++;
2725 f->f_quick = 1;
2726 }
2727 if (*hostblock == '+') {
2728 hostblock++;
2729 f->f_quick = 1;
2730 }
2731 if (strcmp(progblock, "*") != 0)
2732 f->f_program = strdup(progblock);
2733 if (strcmp(hostblock, "*") != 0)
2734 f->f_hostname = strdup(hostblock);
2735
2736 /* scan through the list of selectors */
2737 for (p = line; *p && *p != '\t' && *p != ' ';) {
2738
2739 /* find the end of this facility name list */
2740 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2741 continue;
2742
2743 /* collect priority name */
2744 for (bp = buf; *q && !strchr("\t,; ", *q); )
2745 *bp++ = *q++;
2746 *bp = '\0';
2747
2748 /* skip cruft */
2749 while (*q && strchr(",;", *q))
2750 q++;
2751
2752 /* decode priority name */
2753 if (*buf == '*')
2754 pri = LOG_PRIMASK + 1;
2755 else {
2756 /* ignore trailing spaces */
2757 for (i=strlen(buf)-1; i >= 0 && buf[i] == ' '; i--) {
2758 buf[i]='\0';
2759 }
2760
2761 pri = decode(buf, prioritynames);
2762 if (pri < 0) {
2763 log_warnx("unknown priority name \"%s\"", buf);
2764 free(f);
2765 return (NULL);
2766 }
2767 }
2768
2769 /* scan facilities */
2770 while (*p && !strchr("\t.; ", *p)) {
2771 for (bp = buf; *p && !strchr("\t,;. ", *p); )
2772 *bp++ = *p++;
2773 *bp = '\0';
2774 if (*buf == '*')
2775 for (i = 0; i < LOG_NFACILITIES; i++)
2776 f->f_pmask[i] = pri;
2777 else {
2778 i = decode(buf, facilitynames);
2779 if (i < 0) {
2780 log_warnx("unknown facility name "
2781 "\"%s\"", buf);
2782 free(f);
2783 return (NULL);
2784 }
2785 f->f_pmask[i >> 3] = pri;
2786 }
2787 while (*p == ',' || *p == ' ')
2788 p++;
2789 }
2790
2791 p = q;
2792 }
2793
2794 /* skip to action part */
2795 while (*p == '\t' || *p == ' ')
2796 p++;
2797
2798 switch (*p) {
2799 case '@':
2800 if ((strlcpy(f->f_un.f_forw.f_loghost, p,
2801 sizeof(f->f_un.f_forw.f_loghost)) >=
2802 sizeof(f->f_un.f_forw.f_loghost))) {
2803 log_warnx("loghost too long \"%s\"", p);
2804 break;
2805 }
2806 if (loghost_parse(++p, &proto, &host, &port) == -1) {
2807 log_warnx("bad loghost \"%s\"",
2808 f->f_un.f_forw.f_loghost);
2809 break;
2810 }
2811 if (proto == NULL)
2812 proto = "udp";
2813 if (strcmp(proto, "udp") == 0) {
2814 if (fd_udp == -1)
2815 proto = "udp6";
2816 if (fd_udp6 == -1)
2817 proto = "udp4";
2818 }
2819 ipproto = proto;
2820 if (strcmp(proto, "udp") == 0) {
2821 send_udp = send_udp6 = 1;
2822 } else if (strcmp(proto, "udp4") == 0) {
2823 send_udp = 1;
2824 if (fd_udp == -1) {
2825 log_warnx("no udp4 \"%s\"",
2826 f->f_un.f_forw.f_loghost);
2827 break;
2828 }
2829 } else if (strcmp(proto, "udp6") == 0) {
2830 send_udp6 = 1;
2831 if (fd_udp6 == -1) {
2832 log_warnx("no udp6 \"%s\"",
2833 f->f_un.f_forw.f_loghost);
2834 break;
2835 }
2836 } else if (strcmp(proto, "tcp") == 0 ||
2837 strcmp(proto, "tcp4") == 0 || strcmp(proto, "tcp6") == 0) {
2838 ;
2839 } else if (strcmp(proto, "tls") == 0) {
2840 ipproto = "tcp";
2841 } else if (strcmp(proto, "tls4") == 0) {
2842 ipproto = "tcp4";
2843 } else if (strcmp(proto, "tls6") == 0) {
2844 ipproto = "tcp6";
2845 } else {
2846 log_warnx("bad protocol \"%s\"",
2847 f->f_un.f_forw.f_loghost);
2848 break;
2849 }
2850 if (strlen(host) >= NI_MAXHOST) {
2851 log_warnx("host too long \"%s\"",
2852 f->f_un.f_forw.f_loghost);
2853 break;
2854 }
2855 if (port == NULL)
2856 port = strncmp(proto, "tls", 3) == 0 ?
2857 "syslog-tls" : "syslog";
2858 if (strlen(port) >= NI_MAXSERV) {
2859 log_warnx("port too long \"%s\"",
2860 f->f_un.f_forw.f_loghost);
2861 break;
2862 }
2863 f->f_un.f_forw.f_ipproto = strdup(ipproto);
2864 f->f_un.f_forw.f_host = strdup(host);
2865 f->f_un.f_forw.f_port = strdup(port);
2866 if (f->f_un.f_forw.f_ipproto == NULL ||
2867 f->f_un.f_forw.f_host == NULL ||
2868 f->f_un.f_forw.f_port == NULL) {
2869 log_warnx("strdup ipproto host port \"%s\"",
2870 f->f_un.f_forw.f_loghost);
2871 free(f->f_un.f_forw.f_ipproto);
2872 free(f->f_un.f_forw.f_host);
2873 free(f->f_un.f_forw.f_port);
2874 break;
2875 }
2876 f->f_file = -1;
2877 loghost_resolve(f);
2878 if (strncmp(proto, "udp", 3) == 0) {
2879 evtimer_set(&f->f_un.f_forw.f_ev, udp_resolvecb, f);
2880 switch (f->f_un.f_forw.f_addr.ss_family) {
2881 case AF_UNSPEC:
2882 log_debug("resolve \"%s\" delayed",
2883 f->f_un.f_forw.f_loghost);
2884 to.tv_sec = 0;
2885 to.tv_usec = 1;
2886 evtimer_add(&f->f_un.f_forw.f_ev, &to);
2887 break;
2888 case AF_INET:
2889 f->f_file = fd_udp;
2890 break;
2891 case AF_INET6:
2892 f->f_file = fd_udp6;
2893 break;
2894 }
2895 f->f_type = F_FORWUDP;
2896 } else if (strncmp(ipproto, "tcp", 3) == 0) {
2897 if ((f->f_un.f_forw.f_bufev = bufferevent_new(-1,
2898 tcp_dropcb, tcp_writecb, tcp_errorcb, f)) == NULL) {
2899 log_warn("bufferevent \"%s\"",
2900 f->f_un.f_forw.f_loghost);
2901 free(f->f_un.f_forw.f_ipproto);
2902 free(f->f_un.f_forw.f_host);
2903 free(f->f_un.f_forw.f_port);
2904 break;
2905 }
2906 /*
2907 * If we try to connect to a TLS server immediately
2908 * syslogd gets an SIGPIPE as the signal handlers have
2909 * not been set up. Delay the connection until the
2910 * event loop is started.
2911 */
2912 evtimer_set(&f->f_un.f_forw.f_ev, tcp_connectcb, f);
2913 to.tv_sec = 0;
2914 to.tv_usec = 1;
2915 evtimer_add(&f->f_un.f_forw.f_ev, &to);
2916 f->f_type = (strncmp(proto, "tls", 3) == 0) ?
2917 F_FORWTLS : F_FORWTCP;
2918 }
2919 break;
2920
2921 case '/':
2922 case '|':
2923 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2924 d = find_dup(f);
2925 if (d != NULL) {
2926 for (i = 0; i <= LOG_NFACILITIES; i++)
2927 if (f->f_pmask[i] != INTERNAL_NOPRI)
2928 d->f_pmask[i] = f->f_pmask[i];
2929 free(f);
2930 return (NULL);
2931 }
2932 if (strcmp(p, ctty) == 0) {
2933 f->f_file = priv_open_tty(p);
2934 if (f->f_file < 0)
2935 log_warn("priv_open_tty \"%s\"", p);
2936 } else {
2937 f->f_file = priv_open_log(p);
2938 if (f->f_file < 0)
2939 log_warn("priv_open_log \"%s\"", p);
2940 }
2941 if (f->f_file < 0) {
2942 f->f_type = F_UNUSED;
2943 break;
2944 }
2945 if (isatty(f->f_file)) {
2946 if (strcmp(p, ctty) == 0)
2947 f->f_type = F_CONSOLE;
2948 else
2949 f->f_type = F_TTY;
2950 } else {
2951 if (*p == '|')
2952 f->f_type = F_PIPE;
2953 else {
2954 f->f_type = F_FILE;
2955
2956 /* Clear O_NONBLOCK flag on f->f_file */
2957 if ((i = fcntl(f->f_file, F_GETFL)) != -1) {
2958 i &= ~O_NONBLOCK;
2959 fcntl(f->f_file, F_SETFL, i);
2960 }
2961 }
2962 }
2963 break;
2964
2965 case '*':
2966 f->f_type = F_WALL;
2967 break;
2968
2969 case ':':
2970 f->f_type = F_MEMBUF;
2971
2972 /* Parse buffer size (in kb) */
2973 errno = 0;
2974 rb_len = strtoul(++p, &q, 0);
2975 if (*p == '\0' || (errno == ERANGE && rb_len == ULONG_MAX) ||
2976 *q != ':' || rb_len == 0) {
2977 f->f_type = F_UNUSED;
2978 log_warnx("strtoul \"%s\"", p);
2979 break;
2980 }
2981 q++;
2982 rb_len *= 1024;
2983
2984 /* Copy buffer name */
2985 for(i = 0; (size_t)i < sizeof(f->f_un.f_mb.f_mname) - 1; i++) {
2986 if (!isalnum((unsigned char)q[i]))
2987 break;
2988 f->f_un.f_mb.f_mname[i] = q[i];
2989 }
2990
2991 /* Make sure buffer name is unique */
2992 xf = find_dup(f);
2993
2994 /* Error on missing or non-unique name, or bad buffer length */
2995 if (i == 0 || rb_len > MAX_MEMBUF || xf != NULL) {
2996 f->f_type = F_UNUSED;
2997 log_warnx("find_dup \"%s\"", p);
2998 break;
2999 }
3000
3001 /* Set buffer length */
3002 rb_len = MAXIMUM(rb_len, MIN_MEMBUF);
3003 f->f_un.f_mb.f_len = rb_len;
3004 f->f_un.f_mb.f_overflow = 0;
3005 f->f_un.f_mb.f_attached = 0;
3006 break;
3007
3008 default:
3009 for (i = 0; i < MAXUNAMES && *p; i++) {
3010 for (q = p; *q && *q != ','; )
3011 q++;
3012 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
3013 if ((q - p) > UT_NAMESIZE)
3014 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
3015 else
3016 f->f_un.f_uname[i][q - p] = '\0';
3017 while (*q == ',' || *q == ' ')
3018 q++;
3019 p = q;
3020 }
3021 f->f_type = F_USERS;
3022 break;
3023 }
3024 return (f);
3025 }
3026
3027 /*
3028 * Parse the host and port parts from a loghost string.
3029 */
3030 int
loghost_parse(char * str,char ** proto,char ** host,char ** port)3031 loghost_parse(char *str, char **proto, char **host, char **port)
3032 {
3033 char *prefix = NULL;
3034
3035 if ((*host = strchr(str, ':')) &&
3036 (*host)[1] == '/' && (*host)[2] == '/') {
3037 prefix = str;
3038 **host = '\0';
3039 str = *host + 3;
3040 }
3041 if (proto)
3042 *proto = prefix;
3043 else if (prefix)
3044 return (-1);
3045
3046 *host = str;
3047 if (**host == '[') {
3048 (*host)++;
3049 str = strchr(*host, ']');
3050 if (str == NULL)
3051 return (-1);
3052 *str++ = '\0';
3053 }
3054 *port = strrchr(str, ':');
3055 if (*port != NULL)
3056 *(*port)++ = '\0';
3057
3058 return (0);
3059 }
3060
3061 /*
3062 * Retrieve the size of the kernel message buffer, via sysctl.
3063 */
3064 int
getmsgbufsize(void)3065 getmsgbufsize(void)
3066 {
3067 int msgbufsize, mib[2];
3068 size_t size;
3069
3070 mib[0] = CTL_KERN;
3071 mib[1] = KERN_MSGBUFSIZE;
3072 size = sizeof msgbufsize;
3073 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
3074 log_debug("couldn't get kern.msgbufsize");
3075 return (0);
3076 }
3077 return (msgbufsize);
3078 }
3079
3080 /*
3081 * Decode a symbolic name to a numeric value
3082 */
3083 int
decode(const char * name,const CODE * codetab)3084 decode(const char *name, const CODE *codetab)
3085 {
3086 const CODE *c;
3087 char *p, buf[40];
3088
3089 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3090 if (isupper((unsigned char)*name))
3091 *p = tolower((unsigned char)*name);
3092 else
3093 *p = *name;
3094 }
3095 *p = '\0';
3096 for (c = codetab; c->c_name; c++)
3097 if (!strcmp(buf, c->c_name))
3098 return (c->c_val);
3099
3100 return (-1);
3101 }
3102
3103 void
markit(void)3104 markit(void)
3105 {
3106 struct msg msg;
3107 struct filed *f;
3108
3109 msg.m_pri = LOG_INFO;
3110 current_time(msg.m_timestamp);
3111 msg.m_prog[0] = '\0';
3112 strlcpy(msg.m_msg, "-- MARK --", sizeof(msg.m_msg));
3113 MarkSeq += TIMERINTVL;
3114 if (MarkSeq >= MarkInterval) {
3115 logmsg(&msg, MARK, LocalHostName);
3116 MarkSeq = 0;
3117 }
3118
3119 SIMPLEQ_FOREACH(f, &Files, f_next) {
3120 if (f->f_prevcount && now.tv_sec >= REPEATTIME(f)) {
3121 log_debug("flush %s: repeated %d times, %d sec",
3122 TypeNames[f->f_type], f->f_prevcount,
3123 repeatinterval[f->f_repeatcount]);
3124 fprintlog(f, 0, (char *)NULL);
3125 BACKOFF(f);
3126 }
3127 }
3128 }
3129
3130 int
unix_socket(char * path,int type,mode_t mode)3131 unix_socket(char *path, int type, mode_t mode)
3132 {
3133 struct sockaddr_un s_un;
3134 int fd, optval;
3135 mode_t old_umask;
3136
3137 memset(&s_un, 0, sizeof(s_un));
3138 s_un.sun_family = AF_UNIX;
3139 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
3140 sizeof(s_un.sun_path)) {
3141 log_warnx("socket path too long \"%s\"", path);
3142 return (-1);
3143 }
3144
3145 if ((fd = socket(AF_UNIX, type, 0)) == -1) {
3146 log_warn("socket unix \"%s\"", path);
3147 return (-1);
3148 }
3149
3150 if (Debug) {
3151 if (connect(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == 0 ||
3152 errno == EPROTOTYPE) {
3153 close(fd);
3154 errno = EISCONN;
3155 log_warn("connect unix \"%s\"", path);
3156 return (-1);
3157 }
3158 }
3159
3160 old_umask = umask(0177);
3161
3162 unlink(path);
3163 if (bind(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == -1) {
3164 log_warn("bind unix \"%s\"", path);
3165 umask(old_umask);
3166 close(fd);
3167 return (-1);
3168 }
3169
3170 umask(old_umask);
3171
3172 if (chmod(path, mode) == -1) {
3173 log_warn("chmod unix \"%s\"", path);
3174 close(fd);
3175 unlink(path);
3176 return (-1);
3177 }
3178
3179 optval = LOG_MAXLINE + PATH_MAX;
3180 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval))
3181 == -1)
3182 log_warn("setsockopt unix \"%s\"", path);
3183
3184 return (fd);
3185 }
3186
3187 /*
3188 * Increase socket buffer size in small steps to get partial success
3189 * if we hit a kernel limit. Allow an optional final step.
3190 */
3191 void
double_sockbuf(int fd,int optname,int bigsize)3192 double_sockbuf(int fd, int optname, int bigsize)
3193 {
3194 socklen_t len;
3195 int i, newsize, oldsize = 0;
3196
3197 len = sizeof(oldsize);
3198 if (getsockopt(fd, SOL_SOCKET, optname, &oldsize, &len) == -1)
3199 log_warn("getsockopt bufsize");
3200 len = sizeof(newsize);
3201 newsize = LOG_MAXLINE + 128; /* data + control */
3202 /* allow 8 full length messages, that is 66560 bytes */
3203 for (i = 0; i < 4; i++, newsize *= 2) {
3204 if (newsize <= oldsize)
3205 continue;
3206 if (setsockopt(fd, SOL_SOCKET, optname, &newsize, len) == -1)
3207 log_warn("setsockopt bufsize %d", newsize);
3208 else
3209 oldsize = newsize;
3210 }
3211 if (bigsize && bigsize > oldsize) {
3212 if (setsockopt(fd, SOL_SOCKET, optname, &bigsize, len) == -1)
3213 log_warn("setsockopt bufsize %d", bigsize);
3214 }
3215 }
3216
3217 void
set_sockbuf(int fd)3218 set_sockbuf(int fd)
3219 {
3220 int size = 65536;
3221
3222 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) == -1)
3223 log_warn("setsockopt sndbufsize %d", size);
3224 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) == -1)
3225 log_warn("setsockopt rcvbufsize %d", size);
3226 }
3227
3228 void
set_keepalive(int fd)3229 set_keepalive(int fd)
3230 {
3231 int val = 1;
3232
3233 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1)
3234 log_warn("setsockopt keepalive %d", val);
3235 }
3236
3237 void
ctlconn_cleanup(void)3238 ctlconn_cleanup(void)
3239 {
3240 struct filed *f;
3241
3242 close(fd_ctlconn);
3243 fd_ctlconn = -1;
3244 event_del(ev_ctlread);
3245 event_del(ev_ctlwrite);
3246 event_add(ev_ctlaccept, NULL);
3247
3248 if (ctl_state == CTL_WRITING_CONT_REPLY)
3249 SIMPLEQ_FOREACH(f, &Files, f_next)
3250 if (f->f_type == F_MEMBUF)
3251 f->f_un.f_mb.f_attached = 0;
3252
3253 ctl_state = ctl_cmd_bytes = ctl_reply_offset = ctl_reply_size = 0;
3254 }
3255
3256 void
ctlsock_acceptcb(int fd,short event,void * arg)3257 ctlsock_acceptcb(int fd, short event, void *arg)
3258 {
3259 struct event *ev = arg;
3260
3261 if ((fd = reserve_accept4(fd, event, ev, ctlsock_acceptcb,
3262 NULL, NULL, SOCK_NONBLOCK)) == -1) {
3263 if (errno != ENFILE && errno != EMFILE &&
3264 errno != EINTR && errno != EWOULDBLOCK &&
3265 errno != ECONNABORTED)
3266 log_warn("accept control socket");
3267 return;
3268 }
3269 log_debug("Accepting control connection");
3270
3271 if (fd_ctlconn != -1)
3272 ctlconn_cleanup();
3273
3274 /* Only one connection at a time */
3275 event_del(ev);
3276
3277 fd_ctlconn = fd;
3278 /* file descriptor has changed, reset event */
3279 event_set(ev_ctlread, fd_ctlconn, EV_READ|EV_PERSIST,
3280 ctlconn_readcb, ev_ctlread);
3281 event_set(ev_ctlwrite, fd_ctlconn, EV_WRITE|EV_PERSIST,
3282 ctlconn_writecb, ev_ctlwrite);
3283 event_add(ev_ctlread, NULL);
3284 ctl_state = CTL_READING_CMD;
3285 ctl_cmd_bytes = 0;
3286 }
3287
3288 static struct filed
find_membuf_log(const char * name)3289 *find_membuf_log(const char *name)
3290 {
3291 struct filed *f;
3292
3293 SIMPLEQ_FOREACH(f, &Files, f_next) {
3294 if (f->f_type == F_MEMBUF &&
3295 strcmp(f->f_un.f_mb.f_mname, name) == 0)
3296 break;
3297 }
3298 return (f);
3299 }
3300
3301 void
ctlconn_readcb(int fd,short event,void * arg)3302 ctlconn_readcb(int fd, short event, void *arg)
3303 {
3304 struct filed *f;
3305 struct ctl_reply_hdr *reply_hdr = (struct ctl_reply_hdr *)ctl_reply;
3306 ssize_t n;
3307 u_int32_t flags = 0;
3308
3309 if (ctl_state == CTL_WRITING_REPLY ||
3310 ctl_state == CTL_WRITING_CONT_REPLY) {
3311 /* client has closed the connection */
3312 ctlconn_cleanup();
3313 return;
3314 }
3315
3316 retry:
3317 n = read(fd, (char*)&ctl_cmd + ctl_cmd_bytes,
3318 sizeof(ctl_cmd) - ctl_cmd_bytes);
3319 switch (n) {
3320 case -1:
3321 if (errno == EINTR)
3322 goto retry;
3323 if (errno == EWOULDBLOCK)
3324 return;
3325 log_warn("read control socket");
3326 /* FALLTHROUGH */
3327 case 0:
3328 ctlconn_cleanup();
3329 return;
3330 default:
3331 ctl_cmd_bytes += n;
3332 }
3333 if (ctl_cmd_bytes < sizeof(ctl_cmd))
3334 return;
3335
3336 if (ntohl(ctl_cmd.version) != CTL_VERSION) {
3337 log_warnx("unknown client protocol version");
3338 ctlconn_cleanup();
3339 return;
3340 }
3341
3342 /* Ensure that logname is \0 terminated */
3343 if (memchr(ctl_cmd.logname, '\0', sizeof(ctl_cmd.logname)) == NULL) {
3344 log_warnx("corrupt control socket command");
3345 ctlconn_cleanup();
3346 return;
3347 }
3348
3349 *reply_text = '\0';
3350
3351 ctl_reply_size = ctl_reply_offset = 0;
3352 memset(reply_hdr, '\0', sizeof(*reply_hdr));
3353
3354 ctl_cmd.cmd = ntohl(ctl_cmd.cmd);
3355 log_debug("ctlcmd %x logname \"%s\"", ctl_cmd.cmd, ctl_cmd.logname);
3356
3357 switch (ctl_cmd.cmd) {
3358 case CMD_READ:
3359 case CMD_READ_CLEAR:
3360 case CMD_READ_CONT:
3361 case CMD_FLAGS:
3362 f = find_membuf_log(ctl_cmd.logname);
3363 if (f == NULL) {
3364 strlcpy(reply_text, "No such log\n", MAX_MEMBUF);
3365 } else {
3366 if (ctl_cmd.cmd != CMD_FLAGS) {
3367 ringbuf_to_string(reply_text, MAX_MEMBUF,
3368 f->f_un.f_mb.f_rb);
3369 }
3370 if (f->f_un.f_mb.f_overflow)
3371 flags |= CTL_HDR_FLAG_OVERFLOW;
3372 if (ctl_cmd.cmd == CMD_READ_CLEAR) {
3373 ringbuf_clear(f->f_un.f_mb.f_rb);
3374 f->f_un.f_mb.f_overflow = 0;
3375 }
3376 if (ctl_cmd.cmd == CMD_READ_CONT) {
3377 f->f_un.f_mb.f_attached = 1;
3378 tailify_replytext(reply_text,
3379 ctl_cmd.lines > 0 ? ctl_cmd.lines : 10);
3380 } else if (ctl_cmd.lines > 0) {
3381 tailify_replytext(reply_text, ctl_cmd.lines);
3382 }
3383 }
3384 break;
3385 case CMD_CLEAR:
3386 f = find_membuf_log(ctl_cmd.logname);
3387 if (f == NULL) {
3388 strlcpy(reply_text, "No such log\n", MAX_MEMBUF);
3389 } else {
3390 ringbuf_clear(f->f_un.f_mb.f_rb);
3391 if (f->f_un.f_mb.f_overflow)
3392 flags |= CTL_HDR_FLAG_OVERFLOW;
3393 f->f_un.f_mb.f_overflow = 0;
3394 strlcpy(reply_text, "Log cleared\n", MAX_MEMBUF);
3395 }
3396 break;
3397 case CMD_LIST:
3398 SIMPLEQ_FOREACH(f, &Files, f_next) {
3399 if (f->f_type == F_MEMBUF) {
3400 strlcat(reply_text, f->f_un.f_mb.f_mname,
3401 MAX_MEMBUF);
3402 if (f->f_un.f_mb.f_overflow) {
3403 strlcat(reply_text, "*", MAX_MEMBUF);
3404 flags |= CTL_HDR_FLAG_OVERFLOW;
3405 }
3406 strlcat(reply_text, " ", MAX_MEMBUF);
3407 }
3408 }
3409 strlcat(reply_text, "\n", MAX_MEMBUF);
3410 break;
3411 default:
3412 log_warnx("unsupported control socket command");
3413 ctlconn_cleanup();
3414 return;
3415 }
3416 reply_hdr->version = htonl(CTL_VERSION);
3417 reply_hdr->flags = htonl(flags);
3418
3419 ctl_reply_size = CTL_REPLY_SIZE;
3420 log_debug("ctlcmd reply length %lu", (u_long)ctl_reply_size);
3421
3422 /* Otherwise, set up to write out reply */
3423 ctl_state = (ctl_cmd.cmd == CMD_READ_CONT) ?
3424 CTL_WRITING_CONT_REPLY : CTL_WRITING_REPLY;
3425
3426 event_add(ev_ctlwrite, NULL);
3427
3428 /* another syslogc can kick us out */
3429 if (ctl_state == CTL_WRITING_CONT_REPLY)
3430 event_add(ev_ctlaccept, NULL);
3431 }
3432
3433 void
ctlconn_writecb(int fd,short event,void * arg)3434 ctlconn_writecb(int fd, short event, void *arg)
3435 {
3436 struct event *ev = arg;
3437 ssize_t n;
3438
3439 if (!(ctl_state == CTL_WRITING_REPLY ||
3440 ctl_state == CTL_WRITING_CONT_REPLY)) {
3441 /* Shouldn't be here! */
3442 log_warnx("control socket write with bad state");
3443 ctlconn_cleanup();
3444 return;
3445 }
3446
3447 retry:
3448 n = write(fd, ctl_reply + ctl_reply_offset,
3449 ctl_reply_size - ctl_reply_offset);
3450 switch (n) {
3451 case -1:
3452 if (errno == EINTR)
3453 goto retry;
3454 if (errno == EWOULDBLOCK)
3455 return;
3456 if (errno != EPIPE)
3457 log_warn("write control socket");
3458 /* FALLTHROUGH */
3459 case 0:
3460 ctlconn_cleanup();
3461 return;
3462 default:
3463 ctl_reply_offset += n;
3464 }
3465 if (ctl_reply_offset < ctl_reply_size)
3466 return;
3467
3468 if (ctl_state != CTL_WRITING_CONT_REPLY) {
3469 ctlconn_cleanup();
3470 return;
3471 }
3472
3473 /*
3474 * Make space in the buffer for continuous writes.
3475 * Set offset behind reply header to skip it
3476 */
3477 *reply_text = '\0';
3478 ctl_reply_offset = ctl_reply_size = CTL_REPLY_SIZE;
3479
3480 /* Now is a good time to report dropped lines */
3481 if (membuf_drop) {
3482 strlcat(reply_text, "<ENOBUFS>\n", MAX_MEMBUF);
3483 ctl_reply_size = CTL_REPLY_SIZE;
3484 membuf_drop = 0;
3485 } else {
3486 /* Nothing left to write */
3487 event_del(ev);
3488 }
3489 }
3490
3491 /* Shorten replytext to number of lines */
3492 void
tailify_replytext(char * replytext,int lines)3493 tailify_replytext(char *replytext, int lines)
3494 {
3495 char *start, *nl;
3496 int count = 0;
3497 start = nl = replytext;
3498
3499 while ((nl = strchr(nl, '\n')) != NULL) {
3500 nl++;
3501 if (++count > lines) {
3502 start = strchr(start, '\n');
3503 start++;
3504 }
3505 }
3506 if (start != replytext) {
3507 int len = strlen(start);
3508 memmove(replytext, start, len);
3509 *(replytext + len) = '\0';
3510 }
3511 }
3512
3513 void
ctlconn_logto(char * line)3514 ctlconn_logto(char *line)
3515 {
3516 size_t l;
3517
3518 if (membuf_drop)
3519 return;
3520
3521 l = strlen(line);
3522 if (l + 2 > (CTL_REPLY_MAXSIZE - ctl_reply_size)) {
3523 /* remember line drops for later report */
3524 membuf_drop = 1;
3525 return;
3526 }
3527 memcpy(ctl_reply + ctl_reply_size, line, l);
3528 memcpy(ctl_reply + ctl_reply_size + l, "\n", 2);
3529 ctl_reply_size += l + 1;
3530 event_add(ev_ctlwrite, NULL);
3531 }
3532