1 /* $OpenBSD: syslogd.c,v 1.283 2024/11/07 10:12:18 bluhm 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 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 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 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 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 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 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 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 1123 tcp_acceptcb(int lfd, short event, void *arg) 1124 { 1125 acceptcb(lfd, event, arg, 0); 1126 } 1127 1128 void 1129 tls_acceptcb(int lfd, short event, void *arg) 1130 { 1131 acceptcb(lfd, event, arg, 1); 1132 } 1133 1134 void 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 1214 tls_handshakecb(struct bufferevent *bufev, void *arg) 1215 { 1216 struct peer *p = arg; 1217 1218 log_debug("Completed tls handshake"); 1219 1220 bufferevent_setcb(bufev, tcp_readcb, NULL, tcp_closecb, p); 1221 } 1222 1223 /* 1224 * Syslog over TCP RFC 6587 3.4.1. Octet Counting 1225 */ 1226 int 1227 octet_counting(struct evbuffer *evbuf, char **msg, int drain) 1228 { 1229 char *p, *buf, *end; 1230 int len; 1231 1232 buf = EVBUFFER_DATA(evbuf); 1233 end = buf + EVBUFFER_LENGTH(evbuf); 1234 /* 1235 * It can be assumed that octet-counting framing is used if a syslog 1236 * frame starts with a digit. 1237 */ 1238 if (buf >= end || !isdigit((unsigned char)*buf)) 1239 return (-1); 1240 /* 1241 * SYSLOG-FRAME = MSG-LEN SP SYSLOG-MSG 1242 * MSG-LEN is the octet count of the SYSLOG-MSG in the SYSLOG-FRAME. 1243 * We support up to 5 digits in MSG-LEN, so the maximum is 99999. 1244 */ 1245 for (p = buf; p < end && p < buf + 5; p++) { 1246 if (!isdigit((unsigned char)*p)) 1247 break; 1248 } 1249 if (buf >= p || p >= end || *p != ' ') 1250 return (-1); 1251 p++; 1252 /* Using atoi() is safe as buf starts with 1 to 5 digits and a space. */ 1253 len = atoi(buf); 1254 if (drain) 1255 log_debugadd(" octet counting %d", len); 1256 if (p + len > end) 1257 return (0); 1258 if (drain) 1259 evbuffer_drain(evbuf, p - buf); 1260 if (msg) 1261 *msg = p; 1262 return (len); 1263 } 1264 1265 /* 1266 * Syslog over TCP RFC 6587 3.4.2. Non-Transparent-Framing 1267 */ 1268 int 1269 non_transparent_framing(struct evbuffer *evbuf, char **msg) 1270 { 1271 char *p, *buf, *end; 1272 1273 buf = EVBUFFER_DATA(evbuf); 1274 end = buf + EVBUFFER_LENGTH(evbuf); 1275 /* 1276 * The TRAILER has usually been a single character and most often 1277 * is ASCII LF (%d10). However, other characters have also been 1278 * seen, with ASCII NUL (%d00) being a prominent example. 1279 */ 1280 for (p = buf; p < end; p++) { 1281 if (*p == '\0' || *p == '\n') 1282 break; 1283 } 1284 if (p + 1 - buf >= INT_MAX) 1285 return (-1); 1286 log_debugadd(" non transparent framing"); 1287 if (p >= end) 1288 return (0); 1289 /* 1290 * Some devices have also been seen to emit a two-character 1291 * TRAILER, which is usually CR and LF. 1292 */ 1293 if (buf < p && p[0] == '\n' && p[-1] == '\r') 1294 p[-1] = '\0'; 1295 if (msg) 1296 *msg = buf; 1297 return (p + 1 - buf); 1298 } 1299 1300 void 1301 tcp_readcb(struct bufferevent *bufev, void *arg) 1302 { 1303 struct peer *p = arg; 1304 char *msg; 1305 int len; 1306 1307 while (EVBUFFER_LENGTH(bufev->input) > 0) { 1308 log_debugadd("%s logger \"%s\"", p->p_ctx ? "tls" : "tcp", 1309 p->p_peername); 1310 msg = NULL; 1311 len = octet_counting(bufev->input, &msg, 1); 1312 if (len < 0) 1313 len = non_transparent_framing(bufev->input, &msg); 1314 if (len < 0) 1315 log_debugadd("unknown method"); 1316 if (msg == NULL) { 1317 log_debugadd(", incomplete frame"); 1318 break; 1319 } 1320 log_debug(", use %d bytes", len); 1321 if (len > 0 && msg[len-1] == '\n') 1322 msg[len-1] = '\0'; 1323 if (len == 0 || msg[len-1] != '\0') { 1324 memcpy(linebuf, msg, MINIMUM(len, LOG_MAXLINE)); 1325 linebuf[MINIMUM(len, LOG_MAXLINE)] = '\0'; 1326 msg = linebuf; 1327 } 1328 printline(p->p_hostname, msg); 1329 evbuffer_drain(bufev->input, len); 1330 } 1331 /* Maximum frame has 5 digits, 1 space, MAXLINE chars, 1 new line. */ 1332 if (EVBUFFER_LENGTH(bufev->input) >= 5 + 1 + LOG_MAXLINE + 1) { 1333 log_debug(", use %zu bytes", EVBUFFER_LENGTH(bufev->input)); 1334 EVBUFFER_DATA(bufev->input)[5 + 1 + LOG_MAXLINE] = '\0'; 1335 printline(p->p_hostname, EVBUFFER_DATA(bufev->input)); 1336 evbuffer_drain(bufev->input, -1); 1337 } else if (EVBUFFER_LENGTH(bufev->input) > 0) 1338 log_debug(", buffer %zu bytes", EVBUFFER_LENGTH(bufev->input)); 1339 } 1340 1341 void 1342 tcp_closecb(struct bufferevent *bufev, short event, void *arg) 1343 { 1344 struct peer *p = arg; 1345 1346 if (event & EVBUFFER_EOF) { 1347 log_info(LOG_DEBUG, "%s logger \"%s\" connection close", 1348 p->p_ctx ? "tls" : "tcp", p->p_peername); 1349 } else { 1350 log_info(LOG_NOTICE, "%s logger \"%s\" connection error: %s", 1351 p->p_ctx ? "tls" : "tcp", p->p_peername, 1352 p->p_ctx ? tls_error(p->p_ctx) : strerror(errno)); 1353 } 1354 1355 if (p->p_peername != hostname_unknown) 1356 free(p->p_peername); 1357 if (p->p_hostname != hostname_unknown) 1358 free(p->p_hostname); 1359 bufferevent_free(p->p_bufev); 1360 close(p->p_fd); 1361 free(p); 1362 } 1363 1364 int 1365 tcp_socket(struct filed *f) 1366 { 1367 int s; 1368 1369 if ((s = socket(f->f_un.f_forw.f_addr.ss_family, 1370 SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP)) == -1) { 1371 log_warn("socket \"%s\"", f->f_un.f_forw.f_loghost); 1372 return (-1); 1373 } 1374 set_sockbuf(s); 1375 if (connect(s, (struct sockaddr *)&f->f_un.f_forw.f_addr, 1376 f->f_un.f_forw.f_addr.ss_len) == -1 && errno != EINPROGRESS) { 1377 log_warn("connect \"%s\"", f->f_un.f_forw.f_loghost); 1378 close(s); 1379 return (-1); 1380 } 1381 return (s); 1382 } 1383 1384 void 1385 tcp_dropcb(struct bufferevent *bufev, void *arg) 1386 { 1387 struct filed *f = arg; 1388 1389 /* 1390 * Drop data received from the forward log server. 1391 */ 1392 log_debug("loghost \"%s\" did send %zu bytes back", 1393 f->f_un.f_forw.f_loghost, EVBUFFER_LENGTH(bufev->input)); 1394 evbuffer_drain(bufev->input, -1); 1395 } 1396 1397 void 1398 tcp_writecb(struct bufferevent *bufev, void *arg) 1399 { 1400 struct filed *f = arg; 1401 char ebuf[ERRBUFSIZE]; 1402 1403 /* 1404 * Successful write, connection to server is good, reset wait time. 1405 */ 1406 log_debug("loghost \"%s\" successful write", f->f_un.f_forw.f_loghost); 1407 f->f_un.f_forw.f_retrywait = 0; 1408 1409 if (f->f_dropped > 0 && 1410 EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) < MAX_TCPBUF) { 1411 snprintf(ebuf, sizeof(ebuf), "to loghost \"%s\"", 1412 f->f_un.f_forw.f_loghost); 1413 dropped_warn(&f->f_dropped, ebuf); 1414 } 1415 } 1416 1417 void 1418 tcp_errorcb(struct bufferevent *bufev, short event, void *arg) 1419 { 1420 struct filed *f = arg; 1421 char *p, *buf, *end; 1422 int l; 1423 char ebuf[ERRBUFSIZE]; 1424 1425 if (event & EVBUFFER_EOF) 1426 snprintf(ebuf, sizeof(ebuf), "loghost \"%s\" connection close", 1427 f->f_un.f_forw.f_loghost); 1428 else 1429 snprintf(ebuf, sizeof(ebuf), 1430 "loghost \"%s\" connection error: %s", 1431 f->f_un.f_forw.f_loghost, f->f_un.f_forw.f_ctx ? 1432 tls_error(f->f_un.f_forw.f_ctx) : strerror(errno)); 1433 log_debug("%s", ebuf); 1434 1435 /* The SIGHUP handler may also close the socket, so invalidate it. */ 1436 if (f->f_un.f_forw.f_ctx) { 1437 tls_close(f->f_un.f_forw.f_ctx); 1438 tls_free(f->f_un.f_forw.f_ctx); 1439 f->f_un.f_forw.f_ctx = NULL; 1440 } 1441 bufferevent_disable(bufev, EV_READ|EV_WRITE); 1442 close(f->f_file); 1443 f->f_file = -1; 1444 1445 /* 1446 * The messages in the output buffer may be out of sync. 1447 * Check that the buffer starts with "1234 <1234 octets>\n". 1448 * Otherwise remove the partial message from the beginning. 1449 */ 1450 buf = EVBUFFER_DATA(bufev->output); 1451 end = buf + EVBUFFER_LENGTH(bufev->output); 1452 if (buf < end && !((l = octet_counting(bufev->output, &p, 0)) > 0 && 1453 p[l-1] == '\n')) { 1454 for (p = buf; p < end; p++) { 1455 if (*p == '\n') { 1456 evbuffer_drain(bufev->output, p - buf + 1); 1457 break; 1458 } 1459 } 1460 /* Without '\n' discard everything. */ 1461 if (p == end) 1462 evbuffer_drain(bufev->output, -1); 1463 log_debug("loghost \"%s\" dropped partial message", 1464 f->f_un.f_forw.f_loghost); 1465 f->f_dropped++; 1466 } 1467 1468 loghost_retry(f); 1469 1470 /* Log the connection error to the fresh buffer after reconnecting. */ 1471 log_info(LOG_WARNING, "%s", ebuf); 1472 } 1473 1474 void 1475 tcp_connectcb(int fd, short event, void *arg) 1476 { 1477 struct filed *f = arg; 1478 struct bufferevent *bufev = f->f_un.f_forw.f_bufev; 1479 int s; 1480 1481 if (f->f_un.f_forw.f_addr.ss_family == AF_UNSPEC) { 1482 if (loghost_resolve(f) != 0) { 1483 loghost_retry(f); 1484 return; 1485 } 1486 } 1487 1488 if ((s = tcp_socket(f)) == -1) { 1489 loghost_retry(f); 1490 return; 1491 } 1492 log_debug("tcp connect callback: socket success, event %#x", event); 1493 f->f_file = s; 1494 1495 bufferevent_setfd(bufev, s); 1496 bufferevent_setcb(bufev, tcp_dropcb, tcp_writecb, tcp_errorcb, f); 1497 /* 1498 * Although syslog is a write only protocol, enable reading from 1499 * the socket to detect connection close and errors. 1500 */ 1501 bufferevent_enable(bufev, EV_READ|EV_WRITE); 1502 1503 if (f->f_type == F_FORWTLS) { 1504 if ((f->f_un.f_forw.f_ctx = tls_client()) == NULL) { 1505 log_warn("tls_client \"%s\"", f->f_un.f_forw.f_loghost); 1506 goto error; 1507 } 1508 if (client_config && 1509 tls_configure(f->f_un.f_forw.f_ctx, client_config) == -1) { 1510 log_warnx("tls_configure \"%s\": %s", 1511 f->f_un.f_forw.f_loghost, 1512 tls_error(f->f_un.f_forw.f_ctx)); 1513 goto error; 1514 } 1515 if (tls_connect_socket(f->f_un.f_forw.f_ctx, s, 1516 f->f_un.f_forw.f_host) == -1) { 1517 log_warnx("tls_connect_socket \"%s\": %s", 1518 f->f_un.f_forw.f_loghost, 1519 tls_error(f->f_un.f_forw.f_ctx)); 1520 goto error; 1521 } 1522 log_debug("tcp connect callback: tls context success"); 1523 1524 buffertls_set(&f->f_un.f_forw.f_buftls, bufev, 1525 f->f_un.f_forw.f_ctx, s); 1526 buffertls_connect(&f->f_un.f_forw.f_buftls, s); 1527 } 1528 1529 return; 1530 1531 error: 1532 if (f->f_un.f_forw.f_ctx) { 1533 tls_free(f->f_un.f_forw.f_ctx); 1534 f->f_un.f_forw.f_ctx = NULL; 1535 } 1536 bufferevent_disable(bufev, EV_READ|EV_WRITE); 1537 close(f->f_file); 1538 f->f_file = -1; 1539 loghost_retry(f); 1540 } 1541 1542 int 1543 loghost_resolve(struct filed *f) 1544 { 1545 char hostname[NI_MAXHOST]; 1546 int error; 1547 1548 error = priv_getaddrinfo(f->f_un.f_forw.f_ipproto, 1549 f->f_un.f_forw.f_host, f->f_un.f_forw.f_port, 1550 (struct sockaddr *)&f->f_un.f_forw.f_addr, 1551 sizeof(f->f_un.f_forw.f_addr)); 1552 if (error) { 1553 log_warnx("bad hostname \"%s\"", f->f_un.f_forw.f_loghost); 1554 f->f_un.f_forw.f_addr.ss_family = AF_UNSPEC; 1555 return (error); 1556 } 1557 1558 error = getnameinfo((struct sockaddr *)&f->f_un.f_forw.f_addr, 1559 f->f_un.f_forw.f_addr.ss_len, hostname, sizeof(hostname), NULL, 0, 1560 NI_NUMERICHOST | NI_NUMERICSERV | 1561 (strncmp(f->f_un.f_forw.f_ipproto, "udp", 3) == 0 ? NI_DGRAM : 0)); 1562 if (error) { 1563 log_warnx("malformed UDP address loghost \"%s\": %s", 1564 f->f_un.f_forw.f_loghost, gai_strerror(error)); 1565 strlcpy(hostname, hostname_unknown, sizeof(hostname)); 1566 } 1567 1568 log_debug("resolved loghost \"%s\" address %s", 1569 f->f_un.f_forw.f_loghost, hostname); 1570 return (0); 1571 } 1572 1573 void 1574 loghost_retry(struct filed *f) 1575 { 1576 struct timeval to; 1577 1578 if (f->f_un.f_forw.f_retrywait == 0) 1579 f->f_un.f_forw.f_retrywait = 1; 1580 else 1581 f->f_un.f_forw.f_retrywait <<= 1; 1582 if (f->f_un.f_forw.f_retrywait > 600) 1583 f->f_un.f_forw.f_retrywait = 600; 1584 to.tv_sec = f->f_un.f_forw.f_retrywait; 1585 to.tv_usec = 0; 1586 evtimer_add(&f->f_un.f_forw.f_ev, &to); 1587 1588 log_debug("retry loghost \"%s\" wait %d", 1589 f->f_un.f_forw.f_loghost, f->f_un.f_forw.f_retrywait); 1590 } 1591 1592 void 1593 udp_resolvecb(int fd, short event, void *arg) 1594 { 1595 struct filed *f = arg; 1596 1597 if (loghost_resolve(f) != 0) { 1598 loghost_retry(f); 1599 return; 1600 } 1601 1602 switch (f->f_un.f_forw.f_addr.ss_family) { 1603 case AF_INET: 1604 f->f_file = fd_udp; 1605 break; 1606 case AF_INET6: 1607 f->f_file = fd_udp6; 1608 break; 1609 } 1610 f->f_un.f_forw.f_retrywait = 0; 1611 1612 if (f->f_dropped > 0) { 1613 char ebuf[ERRBUFSIZE]; 1614 1615 snprintf(ebuf, sizeof(ebuf), "to udp loghost \"%s\"", 1616 f->f_un.f_forw.f_loghost); 1617 dropped_warn(&f->f_dropped, ebuf); 1618 } 1619 } 1620 1621 int 1622 tcpbuf_countmsg(struct bufferevent *bufev) 1623 { 1624 char *p, *buf, *end; 1625 int i = 0; 1626 1627 buf = EVBUFFER_DATA(bufev->output); 1628 end = buf + EVBUFFER_LENGTH(bufev->output); 1629 for (p = buf; p < end; p++) { 1630 if (*p == '\n') 1631 i++; 1632 } 1633 return (i); 1634 } 1635 1636 void 1637 usage(void) 1638 { 1639 1640 (void)fprintf(stderr, 1641 "usage: syslogd [-46dFhnruVZ] [-a path] [-C CAfile]\n" 1642 "\t[-c cert_file] [-f config_file] [-K CAfile] [-k key_file]\n" 1643 "\t[-m mark_interval] [-p log_socket] [-S listen_address]\n" 1644 "\t[-s reporting_socket] [-T listen_address] [-U bind_address]\n"); 1645 exit(1); 1646 } 1647 1648 /* 1649 * Take a raw input line, decode the message, and print the message 1650 * on the appropriate log files. 1651 */ 1652 void 1653 printline(char *hname, char *msgstr) 1654 { 1655 struct msg msg; 1656 char *p, *q, line[LOG_MAXLINE + 4 + 1]; /* message, encoding, NUL */ 1657 1658 p = msgstr; 1659 for (q = line; *p && q < &line[LOG_MAXLINE]; p++) { 1660 if (*p == '\n') 1661 *q++ = ' '; 1662 else 1663 q = vis(q, *p, VIS_NOSLASH, 0); 1664 } 1665 line[LOG_MAXLINE] = *q = '\0'; 1666 1667 parsemsg(line, &msg); 1668 if (msg.m_pri == -1) 1669 msg.m_pri = DEFUPRI; 1670 /* 1671 * Don't allow users to log kernel messages. 1672 * NOTE: since LOG_KERN == 0 this will also match 1673 * messages with no facility specified. 1674 */ 1675 if (LOG_FAC(msg.m_pri) == LOG_KERN) 1676 msg.m_pri = LOG_USER | LOG_PRI(msg.m_pri); 1677 1678 if (msg.m_timestamp[0] == '\0') 1679 current_time(msg.m_timestamp); 1680 1681 logmsg(&msg, 0, hname); 1682 } 1683 1684 /* 1685 * Take a raw input line from /dev/klog, split and format similar to syslog(). 1686 */ 1687 void 1688 printsys(char *msgstr) 1689 { 1690 struct msg msg; 1691 int c, flags; 1692 char *lp, *p, *q; 1693 size_t prilen; 1694 int l; 1695 1696 current_time(msg.m_timestamp); 1697 strlcpy(msg.m_prog, _PATH_UNIX, sizeof(msg.m_prog)); 1698 l = snprintf(msg.m_msg, sizeof(msg.m_msg), "%s: ", _PATH_UNIX); 1699 if (l < 0 || l >= sizeof(msg.m_msg)) { 1700 msg.m_msg[0] = '\0'; 1701 l = 0; 1702 } 1703 lp = msg.m_msg + l; 1704 for (p = msgstr; *p != '\0'; ) { 1705 flags = SYNC_FILE; /* fsync file after write */ 1706 msg.m_pri = DEFSPRI; 1707 prilen = parsemsg_priority(p, &msg.m_pri); 1708 p += prilen; 1709 if (prilen == 0) { 1710 /* kernel printf's come out on console */ 1711 flags |= IGN_CONS; 1712 } 1713 if (msg.m_pri &~ (LOG_FACMASK|LOG_PRIMASK)) 1714 msg.m_pri = DEFSPRI; 1715 1716 q = lp; 1717 while (*p && (c = *p++) != '\n' && 1718 q < &msg.m_msg[sizeof(msg.m_msg) - 4]) 1719 q = vis(q, c, VIS_NOSLASH, 0); 1720 1721 logmsg(&msg, flags, LocalHostName); 1722 } 1723 } 1724 1725 void 1726 vlogmsg(int pri, const char *prog, const char *fmt, va_list ap) 1727 { 1728 struct msg msg; 1729 int l; 1730 1731 msg.m_pri = pri; 1732 current_time(msg.m_timestamp); 1733 strlcpy(msg.m_prog, prog, sizeof(msg.m_prog)); 1734 l = snprintf(msg.m_msg, sizeof(msg.m_msg), "%s[%d]: ", prog, getpid()); 1735 if (l < 0 || l >= sizeof(msg.m_msg)) 1736 l = 0; 1737 l = vsnprintf(msg.m_msg + l, sizeof(msg.m_msg) - l, fmt, ap); 1738 if (l < 0) 1739 strlcpy(msg.m_msg, fmt, sizeof(msg.m_msg)); 1740 1741 if (!Started) { 1742 fprintf(stderr, "%s\n", msg.m_msg); 1743 init_dropped++; 1744 return; 1745 } 1746 logmsg(&msg, 0, LocalHostName); 1747 } 1748 1749 struct timeval now; 1750 1751 void 1752 current_time(char *timestamp) 1753 { 1754 (void)gettimeofday(&now, NULL); 1755 1756 if (ZuluTime) { 1757 struct tm *tm; 1758 size_t l; 1759 1760 tm = gmtime(&now.tv_sec); 1761 l = strftime(timestamp, 33, "%FT%T", tm); 1762 /* 1763 * Use only millisecond precision as some time has 1764 * passed since syslog(3) was called. 1765 */ 1766 snprintf(timestamp + l, 33 - l, ".%03ldZ", now.tv_usec / 1000); 1767 } else 1768 strlcpy(timestamp, ctime(&now.tv_sec) + 4, 16); 1769 } 1770 1771 /* 1772 * Log a message to the appropriate log files, users, etc. based on 1773 * the priority. 1774 */ 1775 void 1776 logmsg(struct msg *msg, int flags, char *from) 1777 { 1778 struct filed *f; 1779 int fac, msglen, prilev; 1780 1781 (void)gettimeofday(&now, NULL); 1782 log_debug("logmsg: pri 0%o, flags 0x%x, from %s, prog %s, msg %s", 1783 msg->m_pri, flags, from, msg->m_prog, msg->m_msg); 1784 1785 /* extract facility and priority level */ 1786 if (flags & MARK) 1787 fac = LOG_NFACILITIES; 1788 else 1789 fac = LOG_FAC(msg->m_pri); 1790 prilev = LOG_PRI(msg->m_pri); 1791 1792 /* log the message to the particular outputs */ 1793 if (!Initialized) { 1794 f = &consfile; 1795 if (f->f_type == F_CONSOLE) { 1796 strlcpy(f->f_lasttime, msg->m_timestamp, 1797 sizeof(f->f_lasttime)); 1798 strlcpy(f->f_prevhost, from, 1799 sizeof(f->f_prevhost)); 1800 fprintlog(f, flags, msg->m_msg); 1801 /* May be set to F_UNUSED, try again next time. */ 1802 f->f_type = F_CONSOLE; 1803 } 1804 init_dropped++; 1805 return; 1806 } 1807 /* log the message to the particular outputs */ 1808 msglen = strlen(msg->m_msg); 1809 SIMPLEQ_FOREACH(f, &Files, f_next) { 1810 /* skip messages that are incorrect priority */ 1811 if (f->f_pmask[fac] < prilev || 1812 f->f_pmask[fac] == INTERNAL_NOPRI) 1813 continue; 1814 1815 /* skip messages with the incorrect program or hostname */ 1816 if (f->f_program && fnmatch(f->f_program, msg->m_prog, 0) != 0) 1817 continue; 1818 if (f->f_hostname && fnmatch(f->f_hostname, from, 0) != 0) 1819 continue; 1820 1821 if (f->f_type == F_CONSOLE && (flags & IGN_CONS)) 1822 continue; 1823 1824 /* don't output marks to recently written files */ 1825 if ((flags & MARK) && 1826 (now.tv_sec - f->f_time) < MarkInterval / 2) 1827 continue; 1828 1829 /* 1830 * suppress duplicate lines to this file 1831 */ 1832 if ((Repeat == 0 || (Repeat == 1 && 1833 (f->f_type != F_PIPE && f->f_type != F_FORWUDP && 1834 f->f_type != F_FORWTCP && f->f_type != F_FORWTLS))) && 1835 (flags & MARK) == 0 && msglen == f->f_prevlen && 1836 f->f_dropped == 0 && 1837 !strcmp(msg->m_msg, f->f_prevline) && 1838 !strcmp(from, f->f_prevhost)) { 1839 strlcpy(f->f_lasttime, msg->m_timestamp, 1840 sizeof(f->f_lasttime)); 1841 f->f_prevcount++; 1842 log_debug("msg repeated %d times, %ld sec of %d", 1843 f->f_prevcount, (long)(now.tv_sec - f->f_time), 1844 repeatinterval[f->f_repeatcount]); 1845 /* 1846 * If domark would have logged this by now, 1847 * flush it now (so we don't hold isolated messages), 1848 * but back off so we'll flush less often 1849 * in the future. 1850 */ 1851 if (now.tv_sec > REPEATTIME(f)) { 1852 fprintlog(f, flags, (char *)NULL); 1853 BACKOFF(f); 1854 } 1855 } else { 1856 /* new line, save it */ 1857 if (f->f_prevcount) 1858 fprintlog(f, 0, (char *)NULL); 1859 f->f_repeatcount = 0; 1860 f->f_prevpri = msg->m_pri; 1861 strlcpy(f->f_lasttime, msg->m_timestamp, 1862 sizeof(f->f_lasttime)); 1863 strlcpy(f->f_prevhost, from, 1864 sizeof(f->f_prevhost)); 1865 if (msglen < MAXSVLINE) { 1866 f->f_prevlen = msglen; 1867 strlcpy(f->f_prevline, msg->m_msg, 1868 sizeof(f->f_prevline)); 1869 fprintlog(f, flags, (char *)NULL); 1870 } else { 1871 f->f_prevline[0] = 0; 1872 f->f_prevlen = 0; 1873 fprintlog(f, flags, msg->m_msg); 1874 } 1875 } 1876 1877 if (f->f_quick) 1878 break; 1879 } 1880 } 1881 1882 void 1883 fprintlog(struct filed *f, int flags, char *msg) 1884 { 1885 struct iovec iov[IOVCNT], *v; 1886 struct msghdr msghdr; 1887 int l, retryonce; 1888 char line[LOG_MAXLINE + 1], pribuf[13], greetings[500], repbuf[80]; 1889 char ebuf[ERRBUFSIZE]; 1890 1891 v = iov; 1892 switch (f->f_type) { 1893 case F_FORWUDP: 1894 case F_FORWTCP: 1895 case F_FORWTLS: 1896 l = snprintf(pribuf, sizeof(pribuf), "<%d>", f->f_prevpri); 1897 if (l < 0) 1898 l = strlcpy(pribuf, "<13>", sizeof(pribuf)); 1899 if (l >= sizeof(pribuf)) 1900 l = sizeof(pribuf) - 1; 1901 v->iov_base = pribuf; 1902 v->iov_len = l; 1903 break; 1904 case F_WALL: 1905 l = snprintf(greetings, sizeof(greetings), 1906 "\r\n\7Message from syslogd@%s at %.24s ...\r\n", 1907 f->f_prevhost, ctime(&now.tv_sec)); 1908 if (l < 0) 1909 l = strlcpy(greetings, 1910 "\r\n\7Message from syslogd ...\r\n", 1911 sizeof(greetings)); 1912 if (l >= sizeof(greetings)) 1913 l = sizeof(greetings) - 1; 1914 v->iov_base = greetings; 1915 v->iov_len = l; 1916 break; 1917 default: 1918 v->iov_base = ""; 1919 v->iov_len = 0; 1920 break; 1921 } 1922 v++; 1923 1924 if (f->f_lasttime[0] != '\0') { 1925 v->iov_base = f->f_lasttime; 1926 v->iov_len = strlen(f->f_lasttime); 1927 v++; 1928 v->iov_base = " "; 1929 v->iov_len = 1; 1930 } else { 1931 v->iov_base = ""; 1932 v->iov_len = 0; 1933 v++; 1934 v->iov_base = ""; 1935 v->iov_len = 0; 1936 } 1937 v++; 1938 1939 switch (f->f_type) { 1940 case F_FORWUDP: 1941 case F_FORWTCP: 1942 case F_FORWTLS: 1943 if (IncludeHostname) { 1944 v->iov_base = LocalHostName; 1945 v->iov_len = strlen(LocalHostName); 1946 v++; 1947 v->iov_base = " "; 1948 v->iov_len = 1; 1949 } else { 1950 /* XXX RFC requires to include host name */ 1951 v->iov_base = ""; 1952 v->iov_len = 0; 1953 v++; 1954 v->iov_base = ""; 1955 v->iov_len = 0; 1956 } 1957 break; 1958 default: 1959 if (f->f_prevhost[0] != '\0') { 1960 v->iov_base = f->f_prevhost; 1961 v->iov_len = strlen(v->iov_base); 1962 v++; 1963 v->iov_base = " "; 1964 v->iov_len = 1; 1965 } else { 1966 v->iov_base = ""; 1967 v->iov_len = 0; 1968 v++; 1969 v->iov_base = ""; 1970 v->iov_len = 0; 1971 } 1972 break; 1973 } 1974 v++; 1975 1976 if (msg) { 1977 v->iov_base = msg; 1978 v->iov_len = strlen(msg); 1979 } else if (f->f_prevcount > 1) { 1980 l = snprintf(repbuf, sizeof(repbuf), 1981 "last message repeated %d times", f->f_prevcount); 1982 if (l < 0) 1983 l = strlcpy(repbuf, "last message repeated", 1984 sizeof(repbuf)); 1985 if (l >= sizeof(repbuf)) 1986 l = sizeof(repbuf) - 1; 1987 v->iov_base = repbuf; 1988 v->iov_len = l; 1989 } else { 1990 v->iov_base = f->f_prevline; 1991 v->iov_len = f->f_prevlen; 1992 } 1993 v++; 1994 1995 switch (f->f_type) { 1996 case F_CONSOLE: 1997 case F_TTY: 1998 case F_USERS: 1999 case F_WALL: 2000 v->iov_base = "\r\n"; 2001 v->iov_len = 2; 2002 break; 2003 case F_FILE: 2004 case F_PIPE: 2005 case F_FORWTCP: 2006 case F_FORWTLS: 2007 v->iov_base = "\n"; 2008 v->iov_len = 1; 2009 break; 2010 default: 2011 v->iov_base = ""; 2012 v->iov_len = 0; 2013 break; 2014 } 2015 v = NULL; 2016 2017 log_debugadd("Logging to %s", TypeNames[f->f_type]); 2018 f->f_time = now.tv_sec; 2019 2020 switch (f->f_type) { 2021 case F_UNUSED: 2022 log_debug(""); 2023 break; 2024 2025 case F_FORWUDP: 2026 log_debugadd(" %s", f->f_un.f_forw.f_loghost); 2027 if (f->f_un.f_forw.f_addr.ss_family == AF_UNSPEC) { 2028 log_debug(" (dropped not resolved)"); 2029 f->f_dropped++; 2030 break; 2031 } 2032 l = iov[0].iov_len + iov[1].iov_len + iov[2].iov_len + 2033 iov[3].iov_len + iov[4].iov_len + iov[5].iov_len + 2034 iov[6].iov_len; 2035 if (l > MAX_UDPMSG) { 2036 l -= MAX_UDPMSG; 2037 if (iov[5].iov_len > l) 2038 iov[5].iov_len -= l; 2039 else 2040 iov[5].iov_len = 0; 2041 } 2042 memset(&msghdr, 0, sizeof(msghdr)); 2043 msghdr.msg_name = &f->f_un.f_forw.f_addr; 2044 msghdr.msg_namelen = f->f_un.f_forw.f_addr.ss_len; 2045 msghdr.msg_iov = iov; 2046 msghdr.msg_iovlen = IOVCNT; 2047 if (sendmsg(f->f_file, &msghdr, 0) == -1) { 2048 switch (errno) { 2049 case EACCES: 2050 case EADDRNOTAVAIL: 2051 case EHOSTDOWN: 2052 case EHOSTUNREACH: 2053 case ENETDOWN: 2054 case ENETUNREACH: 2055 case ENOBUFS: 2056 case EWOULDBLOCK: 2057 log_debug(" (dropped send error)"); 2058 f->f_dropped++; 2059 /* silently dropped */ 2060 break; 2061 default: 2062 log_debug(" (dropped permanent send error)"); 2063 f->f_dropped++; 2064 f->f_type = F_UNUSED; 2065 snprintf(ebuf, sizeof(ebuf), 2066 "to udp loghost \"%s\"", 2067 f->f_un.f_forw.f_loghost); 2068 dropped_warn(&f->f_dropped, ebuf); 2069 log_warn("loghost \"%s\" disabled, sendmsg", 2070 f->f_un.f_forw.f_loghost); 2071 break; 2072 } 2073 } else { 2074 log_debug(""); 2075 if (f->f_dropped > 0) { 2076 snprintf(ebuf, sizeof(ebuf), 2077 "to udp loghost \"%s\"", 2078 f->f_un.f_forw.f_loghost); 2079 dropped_warn(&f->f_dropped, ebuf); 2080 } 2081 } 2082 break; 2083 2084 case F_FORWTCP: 2085 case F_FORWTLS: 2086 log_debugadd(" %s", f->f_un.f_forw.f_loghost); 2087 if (EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) >= 2088 MAX_TCPBUF) { 2089 log_debug(" (dropped tcpbuf full)"); 2090 f->f_dropped++; 2091 break; 2092 } 2093 /* 2094 * Syslog over TLS RFC 5425 4.3. Sending Data 2095 * Syslog over TCP RFC 6587 3.4.1. Octet Counting 2096 * Use an additional '\n' to split messages. This allows 2097 * buffer synchronisation, helps legacy implementations, 2098 * and makes line based testing easier. 2099 */ 2100 l = evbuffer_add_printf(f->f_un.f_forw.f_bufev->output, 2101 "%zu %s%s%s%s%s%s%s", iov[0].iov_len + 2102 iov[1].iov_len + iov[2].iov_len + 2103 iov[3].iov_len + iov[4].iov_len + 2104 iov[5].iov_len + iov[6].iov_len, 2105 (char *)iov[0].iov_base, 2106 (char *)iov[1].iov_base, (char *)iov[2].iov_base, 2107 (char *)iov[3].iov_base, (char *)iov[4].iov_base, 2108 (char *)iov[5].iov_base, (char *)iov[6].iov_base); 2109 if (l < 0) { 2110 log_debug(" (dropped evbuffer add)"); 2111 f->f_dropped++; 2112 break; 2113 } 2114 bufferevent_enable(f->f_un.f_forw.f_bufev, EV_WRITE); 2115 log_debug(""); 2116 break; 2117 2118 case F_CONSOLE: 2119 if (flags & IGN_CONS) { 2120 log_debug(" (ignored)"); 2121 break; 2122 } 2123 /* FALLTHROUGH */ 2124 case F_TTY: 2125 case F_FILE: 2126 case F_PIPE: 2127 log_debug(" %s", f->f_un.f_fname); 2128 retryonce = 0; 2129 again: 2130 if (writev(f->f_file, iov, IOVCNT) == -1) { 2131 int e = errno; 2132 2133 /* allow to recover from file system full */ 2134 if (e == ENOSPC && f->f_type == F_FILE) { 2135 if (f->f_dropped++ == 0) { 2136 f->f_type = F_UNUSED; 2137 errno = e; 2138 log_warn("write to file \"%s\"", 2139 f->f_un.f_fname); 2140 f->f_type = F_FILE; 2141 } 2142 break; 2143 } 2144 2145 /* pipe is non-blocking. log and drop message if full */ 2146 if (e == EAGAIN && f->f_type == F_PIPE) { 2147 if (now.tv_sec - f->f_lasterrtime > 120) { 2148 f->f_lasterrtime = now.tv_sec; 2149 log_warn("write to pipe \"%s\"", 2150 f->f_un.f_fname); 2151 } 2152 break; 2153 } 2154 2155 /* 2156 * Check for errors on TTY's or program pipes. 2157 * Errors happen due to loss of tty or died programs. 2158 */ 2159 if (e == EAGAIN) { 2160 /* 2161 * Silently drop messages on blocked write. 2162 * This can happen when logging to a locked tty. 2163 */ 2164 break; 2165 } 2166 2167 (void)close(f->f_file); 2168 if ((e == EIO || e == EBADF) && 2169 f->f_type != F_FILE && f->f_type != F_PIPE && 2170 !retryonce) { 2171 f->f_file = priv_open_tty(f->f_un.f_fname); 2172 retryonce = 1; 2173 if (f->f_file < 0) { 2174 f->f_type = F_UNUSED; 2175 log_warn("priv_open_tty \"%s\"", 2176 f->f_un.f_fname); 2177 } else 2178 goto again; 2179 } else if ((e == EPIPE || e == EBADF) && 2180 f->f_type == F_PIPE && !retryonce) { 2181 f->f_file = priv_open_log(f->f_un.f_fname); 2182 retryonce = 1; 2183 if (f->f_file < 0) { 2184 f->f_type = F_UNUSED; 2185 log_warn("priv_open_log \"%s\"", 2186 f->f_un.f_fname); 2187 } else 2188 goto again; 2189 } else { 2190 f->f_type = F_UNUSED; 2191 f->f_file = -1; 2192 errno = e; 2193 log_warn("writev \"%s\"", f->f_un.f_fname); 2194 } 2195 } else { 2196 if (flags & SYNC_FILE) 2197 (void)fsync(f->f_file); 2198 if (f->f_dropped > 0 && f->f_type == F_FILE) { 2199 snprintf(ebuf, sizeof(ebuf), "to file \"%s\"", 2200 f->f_un.f_fname); 2201 dropped_warn(&f->f_dropped, ebuf); 2202 } 2203 } 2204 break; 2205 2206 case F_USERS: 2207 case F_WALL: 2208 log_debug(""); 2209 wallmsg(f, iov); 2210 break; 2211 2212 case F_MEMBUF: 2213 log_debug(""); 2214 l = snprintf(line, sizeof(line), 2215 "%s%s%s%s%s%s%s", (char *)iov[0].iov_base, 2216 (char *)iov[1].iov_base, (char *)iov[2].iov_base, 2217 (char *)iov[3].iov_base, (char *)iov[4].iov_base, 2218 (char *)iov[5].iov_base, (char *)iov[6].iov_base); 2219 if (l < 0) 2220 l = strlcpy(line, iov[5].iov_base, sizeof(line)); 2221 if (ringbuf_append_line(f->f_un.f_mb.f_rb, line) == 1) 2222 f->f_un.f_mb.f_overflow = 1; 2223 if (f->f_un.f_mb.f_attached) 2224 ctlconn_logto(line); 2225 break; 2226 } 2227 f->f_prevcount = 0; 2228 } 2229 2230 /* 2231 * WALLMSG -- Write a message to the world at large 2232 * 2233 * Write the specified message to either the entire 2234 * world, or a list of approved users. 2235 */ 2236 void 2237 wallmsg(struct filed *f, struct iovec *iov) 2238 { 2239 struct utmp ut; 2240 char utline[sizeof(ut.ut_line) + 1]; 2241 static int reenter; /* avoid calling ourselves */ 2242 FILE *uf; 2243 int i; 2244 2245 if (reenter++) 2246 return; 2247 if ((uf = priv_open_utmp()) == NULL) { 2248 log_warn("priv_open_utmp"); 2249 reenter = 0; 2250 return; 2251 } 2252 while (fread(&ut, sizeof(ut), 1, uf) == 1) { 2253 if (ut.ut_name[0] == '\0') 2254 continue; 2255 /* must use strncpy since ut_* may not be NUL terminated */ 2256 strncpy(utline, ut.ut_line, sizeof(utline) - 1); 2257 utline[sizeof(utline) - 1] = '\0'; 2258 if (f->f_type == F_WALL) { 2259 ttymsg(utline, iov); 2260 continue; 2261 } 2262 /* should we send the message to this user? */ 2263 for (i = 0; i < MAXUNAMES; i++) { 2264 if (!f->f_un.f_uname[i][0]) 2265 break; 2266 if (!strncmp(f->f_un.f_uname[i], ut.ut_name, 2267 UT_NAMESIZE)) { 2268 ttymsg(utline, iov); 2269 break; 2270 } 2271 } 2272 } 2273 (void)fclose(uf); 2274 reenter = 0; 2275 } 2276 2277 /* 2278 * Return a printable representation of a host address. 2279 */ 2280 void 2281 cvthname(struct sockaddr *f, char *result, size_t res_len) 2282 { 2283 int error; 2284 2285 error = getnameinfo(f, f->sa_len, result, res_len, NULL, 0, 2286 NI_NUMERICHOST | NI_NUMERICSERV | NI_DGRAM); 2287 if (error) { 2288 log_warnx("malformed UDP from address: %s", 2289 gai_strerror(error)); 2290 strlcpy(result, hostname_unknown, res_len); 2291 return; 2292 } 2293 log_debug("cvthname(%s)", result); 2294 if (NoDNS) 2295 return; 2296 2297 if (priv_getnameinfo(f, f->sa_len, result, res_len) != 0) 2298 log_debug("Host name for from address (%s) unknown", result); 2299 } 2300 2301 void 2302 die_signalcb(int signum, short event, void *arg) 2303 { 2304 die(signum); 2305 } 2306 2307 void 2308 mark_timercb(int unused, short event, void *arg) 2309 { 2310 struct event *ev = arg; 2311 struct timeval to; 2312 2313 markit(); 2314 2315 to.tv_sec = TIMERINTVL; 2316 to.tv_usec = 0; 2317 evtimer_add(ev, &to); 2318 } 2319 2320 void 2321 init_signalcb(int signum, short event, void *arg) 2322 { 2323 init(); 2324 log_info(LOG_INFO, "restart"); 2325 2326 dropped_warn(&udpsend_dropped, "to udp loghost"); 2327 dropped_warn(&tcpbuf_dropped, "to remote loghost"); 2328 dropped_warn(&file_dropped, "to file"); 2329 log_debug("syslogd: restarted"); 2330 } 2331 2332 void 2333 logevent(int severity, const char *msg) 2334 { 2335 log_debug("libevent: [%d] %s", severity, msg); 2336 } 2337 2338 void 2339 dropped_warn(int *count, const char *what) 2340 { 2341 int dropped; 2342 2343 if (*count == 0) 2344 return; 2345 2346 dropped = *count; 2347 *count = 0; 2348 log_info(LOG_WARNING, "dropped %d message%s %s", 2349 dropped, dropped == 1 ? "" : "s", what); 2350 } 2351 2352 __dead void 2353 die(int signo) 2354 { 2355 struct filed *f; 2356 2357 SIMPLEQ_FOREACH(f, &Files, f_next) { 2358 /* flush any pending output */ 2359 if (f->f_prevcount) 2360 fprintlog(f, 0, (char *)NULL); 2361 if (f->f_type == F_FORWUDP) { 2362 udpsend_dropped += f->f_dropped; 2363 f->f_dropped = 0; 2364 } 2365 if (f->f_type == F_FORWTLS || f->f_type == F_FORWTCP) { 2366 tcpbuf_dropped += f->f_dropped + 2367 tcpbuf_countmsg(f->f_un.f_forw.f_bufev); 2368 f->f_dropped = 0; 2369 } 2370 if (f->f_type == F_FILE) { 2371 file_dropped += f->f_dropped; 2372 f->f_dropped = 0; 2373 } 2374 } 2375 dropped_warn(&init_dropped, "during initialization"); 2376 dropped_warn(&udpsend_dropped, "to udp loghost"); 2377 dropped_warn(&tcpbuf_dropped, "to remote loghost"); 2378 dropped_warn(&file_dropped, "to file"); 2379 2380 if (signo) 2381 log_info(LOG_ERR, "exiting on signal %d", signo); 2382 log_debug("syslogd: exited"); 2383 exit(0); 2384 } 2385 2386 /* 2387 * INIT -- Initialize syslogd from configuration table 2388 */ 2389 void 2390 init(void) 2391 { 2392 char progblock[NAME_MAX+1], hostblock[NAME_MAX+1], *cline, *p, *q; 2393 struct filed_list mb; 2394 struct filed *f, *m; 2395 FILE *cf; 2396 int i; 2397 size_t s; 2398 2399 log_debug("init"); 2400 2401 /* If config file has been modified, then just die to restart */ 2402 if (priv_config_modified()) { 2403 log_debug("config file changed: dying"); 2404 die(0); 2405 } 2406 2407 /* 2408 * Close all open log files. 2409 */ 2410 Initialized = 0; 2411 SIMPLEQ_INIT(&mb); 2412 while (!SIMPLEQ_EMPTY(&Files)) { 2413 f = SIMPLEQ_FIRST(&Files); 2414 SIMPLEQ_REMOVE_HEAD(&Files, f_next); 2415 /* flush any pending output */ 2416 if (f->f_prevcount) 2417 fprintlog(f, 0, (char *)NULL); 2418 2419 switch (f->f_type) { 2420 case F_FORWUDP: 2421 evtimer_del(&f->f_un.f_forw.f_ev); 2422 udpsend_dropped += f->f_dropped; 2423 f->f_dropped = 0; 2424 free(f->f_un.f_forw.f_ipproto); 2425 free(f->f_un.f_forw.f_host); 2426 free(f->f_un.f_forw.f_port); 2427 break; 2428 case F_FORWTLS: 2429 if (f->f_un.f_forw.f_ctx) { 2430 tls_close(f->f_un.f_forw.f_ctx); 2431 tls_free(f->f_un.f_forw.f_ctx); 2432 } 2433 /* FALLTHROUGH */ 2434 case F_FORWTCP: 2435 evtimer_del(&f->f_un.f_forw.f_ev); 2436 tcpbuf_dropped += f->f_dropped; 2437 if (f->f_un.f_forw.f_bufev) { 2438 bufferevent_disable(f->f_un.f_forw.f_bufev, 2439 EV_READ|EV_WRITE); 2440 tcpbuf_dropped += 2441 tcpbuf_countmsg(f->f_un.f_forw.f_bufev); 2442 bufferevent_free(f->f_un.f_forw.f_bufev); 2443 } 2444 free(f->f_un.f_forw.f_ipproto); 2445 free(f->f_un.f_forw.f_host); 2446 free(f->f_un.f_forw.f_port); 2447 /* FALLTHROUGH */ 2448 case F_FILE: 2449 if (f->f_type == F_FILE) 2450 file_dropped += f->f_dropped; 2451 f->f_dropped = 0; 2452 /* FALLTHROUGH */ 2453 case F_TTY: 2454 case F_CONSOLE: 2455 case F_PIPE: 2456 (void)close(f->f_file); 2457 break; 2458 } 2459 free(f->f_program); 2460 free(f->f_hostname); 2461 if (f->f_type == F_MEMBUF) { 2462 f->f_program = NULL; 2463 f->f_hostname = NULL; 2464 log_debug("add %p to mb", f); 2465 SIMPLEQ_INSERT_HEAD(&mb, f, f_next); 2466 } else 2467 free(f); 2468 } 2469 SIMPLEQ_INIT(&Files); 2470 2471 /* open the configuration file */ 2472 if ((cf = priv_open_config()) == NULL) { 2473 log_debug("cannot open %s", ConfFile); 2474 SIMPLEQ_INSERT_TAIL(&Files, 2475 cfline("*.ERR\t/dev/console", "*", "*"), f_next); 2476 SIMPLEQ_INSERT_TAIL(&Files, 2477 cfline("*.PANIC\t*", "*", "*"), f_next); 2478 Initialized = 1; 2479 dropped_warn(&init_dropped, "during initialization"); 2480 return; 2481 } 2482 2483 /* 2484 * Foreach line in the conf table, open that file. 2485 */ 2486 cline = NULL; 2487 s = 0; 2488 strlcpy(progblock, "*", sizeof(progblock)); 2489 strlcpy(hostblock, "*", sizeof(hostblock)); 2490 send_udp = send_udp6 = 0; 2491 while (getline(&cline, &s, cf) != -1) { 2492 /* 2493 * check for end-of-section, comments, strip off trailing 2494 * spaces and newline character. !progblock and +hostblock 2495 * are treated specially: the following lines apply only to 2496 * that program. 2497 */ 2498 for (p = cline; isspace((unsigned char)*p); ++p) 2499 continue; 2500 if (*p == '\0' || *p == '#') 2501 continue; 2502 if (*p == '!' || *p == '+') { 2503 q = (*p == '!') ? progblock : hostblock; 2504 p++; 2505 while (isspace((unsigned char)*p)) 2506 p++; 2507 if (*p == '\0' || (*p == '*' && (p[1] == '\0' || 2508 isspace((unsigned char)p[1])))) { 2509 strlcpy(q, "*", NAME_MAX+1); 2510 continue; 2511 } 2512 for (i = 0; i < NAME_MAX; i++) { 2513 if (*p == '\0' || isspace((unsigned char)*p)) 2514 break; 2515 *q++ = *p++; 2516 } 2517 *q = '\0'; 2518 continue; 2519 } 2520 2521 p = cline + strlen(cline); 2522 while (p > cline) 2523 if (!isspace((unsigned char)*--p)) { 2524 p++; 2525 break; 2526 } 2527 *p = '\0'; 2528 f = cfline(cline, progblock, hostblock); 2529 if (f != NULL) 2530 SIMPLEQ_INSERT_TAIL(&Files, f, f_next); 2531 } 2532 free(cline); 2533 if (!feof(cf)) 2534 fatal("read config file"); 2535 2536 /* Match and initialize the memory buffers */ 2537 SIMPLEQ_FOREACH(f, &Files, f_next) { 2538 if (f->f_type != F_MEMBUF) 2539 continue; 2540 log_debug("Initialize membuf %s at %p", 2541 f->f_un.f_mb.f_mname, f); 2542 2543 SIMPLEQ_FOREACH(m, &mb, f_next) { 2544 if (m->f_un.f_mb.f_rb == NULL) 2545 continue; 2546 if (strcmp(m->f_un.f_mb.f_mname, 2547 f->f_un.f_mb.f_mname) == 0) 2548 break; 2549 } 2550 if (m == NULL) { 2551 log_debug("Membuf no match"); 2552 f->f_un.f_mb.f_rb = ringbuf_init(f->f_un.f_mb.f_len); 2553 if (f->f_un.f_mb.f_rb == NULL) { 2554 f->f_type = F_UNUSED; 2555 log_warn("allocate membuf"); 2556 } 2557 } else { 2558 log_debug("Membuf match f:%p, m:%p", f, m); 2559 f->f_un = m->f_un; 2560 m->f_un.f_mb.f_rb = NULL; 2561 } 2562 } 2563 2564 /* make sure remaining buffers are freed */ 2565 while (!SIMPLEQ_EMPTY(&mb)) { 2566 m = SIMPLEQ_FIRST(&mb); 2567 SIMPLEQ_REMOVE_HEAD(&mb, f_next); 2568 if (m->f_un.f_mb.f_rb != NULL) { 2569 log_warnx("mismatched membuf"); 2570 ringbuf_free(m->f_un.f_mb.f_rb); 2571 } 2572 log_debug("Freeing membuf %p", m); 2573 2574 free(m); 2575 } 2576 2577 /* close the configuration file */ 2578 (void)fclose(cf); 2579 2580 Initialized = 1; 2581 dropped_warn(&init_dropped, "during initialization"); 2582 2583 if (SecureMode) { 2584 /* 2585 * If generic UDP file descriptors are used neither 2586 * for receiving nor for sending, close them. Then 2587 * there is no useless *.514 in netstat. 2588 */ 2589 if (fd_udp != -1 && !send_udp) { 2590 close(fd_udp); 2591 fd_udp = -1; 2592 } 2593 if (fd_udp6 != -1 && !send_udp6) { 2594 close(fd_udp6); 2595 fd_udp6 = -1; 2596 } 2597 } 2598 2599 if (Debug) { 2600 SIMPLEQ_FOREACH(f, &Files, f_next) { 2601 for (i = 0; i <= LOG_NFACILITIES; i++) 2602 if (f->f_pmask[i] == INTERNAL_NOPRI) 2603 printf("X "); 2604 else 2605 printf("%d ", f->f_pmask[i]); 2606 printf("%s: ", TypeNames[f->f_type]); 2607 switch (f->f_type) { 2608 case F_FILE: 2609 case F_TTY: 2610 case F_CONSOLE: 2611 case F_PIPE: 2612 printf("%s", f->f_un.f_fname); 2613 break; 2614 2615 case F_FORWUDP: 2616 case F_FORWTCP: 2617 case F_FORWTLS: 2618 printf("%s", f->f_un.f_forw.f_loghost); 2619 break; 2620 2621 case F_USERS: 2622 for (i = 0; i < MAXUNAMES && 2623 *f->f_un.f_uname[i]; i++) 2624 printf("%s, ", f->f_un.f_uname[i]); 2625 break; 2626 2627 case F_MEMBUF: 2628 printf("%s", f->f_un.f_mb.f_mname); 2629 break; 2630 2631 } 2632 if (f->f_program || f->f_hostname) 2633 printf(" (%s, %s)", 2634 f->f_program ? f->f_program : "*", 2635 f->f_hostname ? f->f_hostname : "*"); 2636 printf("\n"); 2637 } 2638 } 2639 } 2640 2641 #define progmatches(p1, p2) \ 2642 (p1 == p2 || (p1 != NULL && p2 != NULL && strcmp(p1, p2) == 0)) 2643 2644 /* 2645 * Spot a line with a duplicate file, pipe, console, tty, or membuf target. 2646 */ 2647 struct filed * 2648 find_dup(struct filed *f) 2649 { 2650 struct filed *list; 2651 2652 SIMPLEQ_FOREACH(list, &Files, f_next) { 2653 if (list->f_quick || f->f_quick) 2654 continue; 2655 switch (list->f_type) { 2656 case F_FILE: 2657 case F_TTY: 2658 case F_CONSOLE: 2659 case F_PIPE: 2660 if (strcmp(list->f_un.f_fname, f->f_un.f_fname) == 0 && 2661 progmatches(list->f_program, f->f_program) && 2662 progmatches(list->f_hostname, f->f_hostname)) { 2663 log_debug("duplicate %s", f->f_un.f_fname); 2664 return (list); 2665 } 2666 break; 2667 case F_MEMBUF: 2668 if (strcmp(list->f_un.f_mb.f_mname, 2669 f->f_un.f_mb.f_mname) == 0 && 2670 progmatches(list->f_program, f->f_program) && 2671 progmatches(list->f_hostname, f->f_hostname)) { 2672 log_debug("duplicate membuf %s", 2673 f->f_un.f_mb.f_mname); 2674 return (list); 2675 } 2676 break; 2677 } 2678 } 2679 return (NULL); 2680 } 2681 2682 /* 2683 * Crack a configuration file line 2684 */ 2685 struct filed * 2686 cfline(char *line, char *progblock, char *hostblock) 2687 { 2688 int i, pri; 2689 size_t rb_len; 2690 char *bp, *p, *q, *proto, *host, *port, *ipproto; 2691 char buf[LOG_MAXLINE]; 2692 struct filed *xf, *f, *d; 2693 struct timeval to; 2694 2695 log_debug("cfline(\"%s\", f, \"%s\", \"%s\")", 2696 line, progblock, hostblock); 2697 2698 if ((f = calloc(1, sizeof(*f))) == NULL) 2699 fatal("allocate struct filed"); 2700 for (i = 0; i <= LOG_NFACILITIES; i++) 2701 f->f_pmask[i] = INTERNAL_NOPRI; 2702 2703 /* save program name if any */ 2704 f->f_quick = 0; 2705 if (*progblock == '!') { 2706 progblock++; 2707 f->f_quick = 1; 2708 } 2709 if (*hostblock == '+') { 2710 hostblock++; 2711 f->f_quick = 1; 2712 } 2713 if (strcmp(progblock, "*") != 0) 2714 f->f_program = strdup(progblock); 2715 if (strcmp(hostblock, "*") != 0) 2716 f->f_hostname = strdup(hostblock); 2717 2718 /* scan through the list of selectors */ 2719 for (p = line; *p && *p != '\t' && *p != ' ';) { 2720 2721 /* find the end of this facility name list */ 2722 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; ) 2723 continue; 2724 2725 /* collect priority name */ 2726 for (bp = buf; *q && !strchr("\t,; ", *q); ) 2727 *bp++ = *q++; 2728 *bp = '\0'; 2729 2730 /* skip cruft */ 2731 while (*q && strchr(",;", *q)) 2732 q++; 2733 2734 /* decode priority name */ 2735 if (*buf == '*') 2736 pri = LOG_PRIMASK + 1; 2737 else { 2738 /* ignore trailing spaces */ 2739 for (i=strlen(buf)-1; i >= 0 && buf[i] == ' '; i--) { 2740 buf[i]='\0'; 2741 } 2742 2743 pri = decode(buf, prioritynames); 2744 if (pri < 0) { 2745 log_warnx("unknown priority name \"%s\"", buf); 2746 free(f); 2747 return (NULL); 2748 } 2749 } 2750 2751 /* scan facilities */ 2752 while (*p && !strchr("\t.; ", *p)) { 2753 for (bp = buf; *p && !strchr("\t,;. ", *p); ) 2754 *bp++ = *p++; 2755 *bp = '\0'; 2756 if (*buf == '*') 2757 for (i = 0; i < LOG_NFACILITIES; i++) 2758 f->f_pmask[i] = pri; 2759 else { 2760 i = decode(buf, facilitynames); 2761 if (i < 0) { 2762 log_warnx("unknown facility name " 2763 "\"%s\"", buf); 2764 free(f); 2765 return (NULL); 2766 } 2767 f->f_pmask[i >> 3] = pri; 2768 } 2769 while (*p == ',' || *p == ' ') 2770 p++; 2771 } 2772 2773 p = q; 2774 } 2775 2776 /* skip to action part */ 2777 while (*p == '\t' || *p == ' ') 2778 p++; 2779 2780 switch (*p) { 2781 case '@': 2782 if ((strlcpy(f->f_un.f_forw.f_loghost, p, 2783 sizeof(f->f_un.f_forw.f_loghost)) >= 2784 sizeof(f->f_un.f_forw.f_loghost))) { 2785 log_warnx("loghost too long \"%s\"", p); 2786 break; 2787 } 2788 if (loghost_parse(++p, &proto, &host, &port) == -1) { 2789 log_warnx("bad loghost \"%s\"", 2790 f->f_un.f_forw.f_loghost); 2791 break; 2792 } 2793 if (proto == NULL) 2794 proto = "udp"; 2795 if (strcmp(proto, "udp") == 0) { 2796 if (fd_udp == -1) 2797 proto = "udp6"; 2798 if (fd_udp6 == -1) 2799 proto = "udp4"; 2800 } 2801 ipproto = proto; 2802 if (strcmp(proto, "udp") == 0) { 2803 send_udp = send_udp6 = 1; 2804 } else if (strcmp(proto, "udp4") == 0) { 2805 send_udp = 1; 2806 if (fd_udp == -1) { 2807 log_warnx("no udp4 \"%s\"", 2808 f->f_un.f_forw.f_loghost); 2809 break; 2810 } 2811 } else if (strcmp(proto, "udp6") == 0) { 2812 send_udp6 = 1; 2813 if (fd_udp6 == -1) { 2814 log_warnx("no udp6 \"%s\"", 2815 f->f_un.f_forw.f_loghost); 2816 break; 2817 } 2818 } else if (strcmp(proto, "tcp") == 0 || 2819 strcmp(proto, "tcp4") == 0 || strcmp(proto, "tcp6") == 0) { 2820 ; 2821 } else if (strcmp(proto, "tls") == 0) { 2822 ipproto = "tcp"; 2823 } else if (strcmp(proto, "tls4") == 0) { 2824 ipproto = "tcp4"; 2825 } else if (strcmp(proto, "tls6") == 0) { 2826 ipproto = "tcp6"; 2827 } else { 2828 log_warnx("bad protocol \"%s\"", 2829 f->f_un.f_forw.f_loghost); 2830 break; 2831 } 2832 if (strlen(host) >= NI_MAXHOST) { 2833 log_warnx("host too long \"%s\"", 2834 f->f_un.f_forw.f_loghost); 2835 break; 2836 } 2837 if (port == NULL) 2838 port = strncmp(proto, "tls", 3) == 0 ? 2839 "syslog-tls" : "syslog"; 2840 if (strlen(port) >= NI_MAXSERV) { 2841 log_warnx("port too long \"%s\"", 2842 f->f_un.f_forw.f_loghost); 2843 break; 2844 } 2845 f->f_un.f_forw.f_ipproto = strdup(ipproto); 2846 f->f_un.f_forw.f_host = strdup(host); 2847 f->f_un.f_forw.f_port = strdup(port); 2848 if (f->f_un.f_forw.f_ipproto == NULL || 2849 f->f_un.f_forw.f_host == NULL || 2850 f->f_un.f_forw.f_port == NULL) { 2851 log_warnx("strdup ipproto host port \"%s\"", 2852 f->f_un.f_forw.f_loghost); 2853 free(f->f_un.f_forw.f_ipproto); 2854 free(f->f_un.f_forw.f_host); 2855 free(f->f_un.f_forw.f_port); 2856 break; 2857 } 2858 f->f_file = -1; 2859 loghost_resolve(f); 2860 if (strncmp(proto, "udp", 3) == 0) { 2861 evtimer_set(&f->f_un.f_forw.f_ev, udp_resolvecb, f); 2862 switch (f->f_un.f_forw.f_addr.ss_family) { 2863 case AF_UNSPEC: 2864 log_debug("resolve \"%s\" delayed", 2865 f->f_un.f_forw.f_loghost); 2866 to.tv_sec = 0; 2867 to.tv_usec = 1; 2868 evtimer_add(&f->f_un.f_forw.f_ev, &to); 2869 break; 2870 case AF_INET: 2871 f->f_file = fd_udp; 2872 break; 2873 case AF_INET6: 2874 f->f_file = fd_udp6; 2875 break; 2876 } 2877 f->f_type = F_FORWUDP; 2878 } else if (strncmp(ipproto, "tcp", 3) == 0) { 2879 if ((f->f_un.f_forw.f_bufev = bufferevent_new(-1, 2880 tcp_dropcb, tcp_writecb, tcp_errorcb, f)) == NULL) { 2881 log_warn("bufferevent \"%s\"", 2882 f->f_un.f_forw.f_loghost); 2883 free(f->f_un.f_forw.f_ipproto); 2884 free(f->f_un.f_forw.f_host); 2885 free(f->f_un.f_forw.f_port); 2886 break; 2887 } 2888 /* 2889 * If we try to connect to a TLS server immediately 2890 * syslogd gets an SIGPIPE as the signal handlers have 2891 * not been set up. Delay the connection until the 2892 * event loop is started. 2893 */ 2894 evtimer_set(&f->f_un.f_forw.f_ev, tcp_connectcb, f); 2895 to.tv_sec = 0; 2896 to.tv_usec = 1; 2897 evtimer_add(&f->f_un.f_forw.f_ev, &to); 2898 f->f_type = (strncmp(proto, "tls", 3) == 0) ? 2899 F_FORWTLS : F_FORWTCP; 2900 } 2901 break; 2902 2903 case '/': 2904 case '|': 2905 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname)); 2906 d = find_dup(f); 2907 if (d != NULL) { 2908 for (i = 0; i <= LOG_NFACILITIES; i++) 2909 if (f->f_pmask[i] != INTERNAL_NOPRI) 2910 d->f_pmask[i] = f->f_pmask[i]; 2911 free(f); 2912 return (NULL); 2913 } 2914 if (strcmp(p, ctty) == 0) { 2915 f->f_file = priv_open_tty(p); 2916 if (f->f_file < 0) 2917 log_warn("priv_open_tty \"%s\"", p); 2918 } else { 2919 f->f_file = priv_open_log(p); 2920 if (f->f_file < 0) 2921 log_warn("priv_open_log \"%s\"", p); 2922 } 2923 if (f->f_file < 0) { 2924 f->f_type = F_UNUSED; 2925 break; 2926 } 2927 if (isatty(f->f_file)) { 2928 if (strcmp(p, ctty) == 0) 2929 f->f_type = F_CONSOLE; 2930 else 2931 f->f_type = F_TTY; 2932 } else { 2933 if (*p == '|') 2934 f->f_type = F_PIPE; 2935 else { 2936 f->f_type = F_FILE; 2937 2938 /* Clear O_NONBLOCK flag on f->f_file */ 2939 if ((i = fcntl(f->f_file, F_GETFL)) != -1) { 2940 i &= ~O_NONBLOCK; 2941 fcntl(f->f_file, F_SETFL, i); 2942 } 2943 } 2944 } 2945 break; 2946 2947 case '*': 2948 f->f_type = F_WALL; 2949 break; 2950 2951 case ':': 2952 f->f_type = F_MEMBUF; 2953 2954 /* Parse buffer size (in kb) */ 2955 errno = 0; 2956 rb_len = strtoul(++p, &q, 0); 2957 if (*p == '\0' || (errno == ERANGE && rb_len == ULONG_MAX) || 2958 *q != ':' || rb_len == 0) { 2959 f->f_type = F_UNUSED; 2960 log_warnx("strtoul \"%s\"", p); 2961 break; 2962 } 2963 q++; 2964 rb_len *= 1024; 2965 2966 /* Copy buffer name */ 2967 for(i = 0; (size_t)i < sizeof(f->f_un.f_mb.f_mname) - 1; i++) { 2968 if (!isalnum((unsigned char)q[i])) 2969 break; 2970 f->f_un.f_mb.f_mname[i] = q[i]; 2971 } 2972 2973 /* Make sure buffer name is unique */ 2974 xf = find_dup(f); 2975 2976 /* Error on missing or non-unique name, or bad buffer length */ 2977 if (i == 0 || rb_len > MAX_MEMBUF || xf != NULL) { 2978 f->f_type = F_UNUSED; 2979 log_warnx("find_dup \"%s\"", p); 2980 break; 2981 } 2982 2983 /* Set buffer length */ 2984 rb_len = MAXIMUM(rb_len, MIN_MEMBUF); 2985 f->f_un.f_mb.f_len = rb_len; 2986 f->f_un.f_mb.f_overflow = 0; 2987 f->f_un.f_mb.f_attached = 0; 2988 break; 2989 2990 default: 2991 for (i = 0; i < MAXUNAMES && *p; i++) { 2992 for (q = p; *q && *q != ','; ) 2993 q++; 2994 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE); 2995 if ((q - p) > UT_NAMESIZE) 2996 f->f_un.f_uname[i][UT_NAMESIZE] = '\0'; 2997 else 2998 f->f_un.f_uname[i][q - p] = '\0'; 2999 while (*q == ',' || *q == ' ') 3000 q++; 3001 p = q; 3002 } 3003 f->f_type = F_USERS; 3004 break; 3005 } 3006 return (f); 3007 } 3008 3009 /* 3010 * Parse the host and port parts from a loghost string. 3011 */ 3012 int 3013 loghost_parse(char *str, char **proto, char **host, char **port) 3014 { 3015 char *prefix = NULL; 3016 3017 if ((*host = strchr(str, ':')) && 3018 (*host)[1] == '/' && (*host)[2] == '/') { 3019 prefix = str; 3020 **host = '\0'; 3021 str = *host + 3; 3022 } 3023 if (proto) 3024 *proto = prefix; 3025 else if (prefix) 3026 return (-1); 3027 3028 *host = str; 3029 if (**host == '[') { 3030 (*host)++; 3031 str = strchr(*host, ']'); 3032 if (str == NULL) 3033 return (-1); 3034 *str++ = '\0'; 3035 } 3036 *port = strrchr(str, ':'); 3037 if (*port != NULL) 3038 *(*port)++ = '\0'; 3039 3040 return (0); 3041 } 3042 3043 /* 3044 * Retrieve the size of the kernel message buffer, via sysctl. 3045 */ 3046 int 3047 getmsgbufsize(void) 3048 { 3049 int msgbufsize, mib[2]; 3050 size_t size; 3051 3052 mib[0] = CTL_KERN; 3053 mib[1] = KERN_MSGBUFSIZE; 3054 size = sizeof msgbufsize; 3055 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) { 3056 log_debug("couldn't get kern.msgbufsize"); 3057 return (0); 3058 } 3059 return (msgbufsize); 3060 } 3061 3062 /* 3063 * Decode a symbolic name to a numeric value 3064 */ 3065 int 3066 decode(const char *name, const CODE *codetab) 3067 { 3068 const CODE *c; 3069 char *p, buf[40]; 3070 3071 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) { 3072 if (isupper((unsigned char)*name)) 3073 *p = tolower((unsigned char)*name); 3074 else 3075 *p = *name; 3076 } 3077 *p = '\0'; 3078 for (c = codetab; c->c_name; c++) 3079 if (!strcmp(buf, c->c_name)) 3080 return (c->c_val); 3081 3082 return (-1); 3083 } 3084 3085 void 3086 markit(void) 3087 { 3088 struct msg msg; 3089 struct filed *f; 3090 3091 msg.m_pri = LOG_INFO; 3092 current_time(msg.m_timestamp); 3093 msg.m_prog[0] = '\0'; 3094 strlcpy(msg.m_msg, "-- MARK --", sizeof(msg.m_msg)); 3095 MarkSeq += TIMERINTVL; 3096 if (MarkSeq >= MarkInterval) { 3097 logmsg(&msg, MARK, LocalHostName); 3098 MarkSeq = 0; 3099 } 3100 3101 SIMPLEQ_FOREACH(f, &Files, f_next) { 3102 if (f->f_prevcount && now.tv_sec >= REPEATTIME(f)) { 3103 log_debug("flush %s: repeated %d times, %d sec", 3104 TypeNames[f->f_type], f->f_prevcount, 3105 repeatinterval[f->f_repeatcount]); 3106 fprintlog(f, 0, (char *)NULL); 3107 BACKOFF(f); 3108 } 3109 } 3110 } 3111 3112 int 3113 unix_socket(char *path, int type, mode_t mode) 3114 { 3115 struct sockaddr_un s_un; 3116 int fd, optval; 3117 mode_t old_umask; 3118 3119 memset(&s_un, 0, sizeof(s_un)); 3120 s_un.sun_family = AF_UNIX; 3121 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >= 3122 sizeof(s_un.sun_path)) { 3123 log_warnx("socket path too long \"%s\"", path); 3124 return (-1); 3125 } 3126 3127 if ((fd = socket(AF_UNIX, type, 0)) == -1) { 3128 log_warn("socket unix \"%s\"", path); 3129 return (-1); 3130 } 3131 3132 if (Debug) { 3133 if (connect(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == 0 || 3134 errno == EPROTOTYPE) { 3135 close(fd); 3136 errno = EISCONN; 3137 log_warn("connect unix \"%s\"", path); 3138 return (-1); 3139 } 3140 } 3141 3142 old_umask = umask(0177); 3143 3144 unlink(path); 3145 if (bind(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == -1) { 3146 log_warn("bind unix \"%s\"", path); 3147 umask(old_umask); 3148 close(fd); 3149 return (-1); 3150 } 3151 3152 umask(old_umask); 3153 3154 if (chmod(path, mode) == -1) { 3155 log_warn("chmod unix \"%s\"", path); 3156 close(fd); 3157 unlink(path); 3158 return (-1); 3159 } 3160 3161 optval = LOG_MAXLINE + PATH_MAX; 3162 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval)) 3163 == -1) 3164 log_warn("setsockopt unix \"%s\"", path); 3165 3166 return (fd); 3167 } 3168 3169 /* 3170 * Increase socket buffer size in small steps to get partial success 3171 * if we hit a kernel limit. Allow an optional final step. 3172 */ 3173 void 3174 double_sockbuf(int fd, int optname, int bigsize) 3175 { 3176 socklen_t len; 3177 int i, newsize, oldsize = 0; 3178 3179 len = sizeof(oldsize); 3180 if (getsockopt(fd, SOL_SOCKET, optname, &oldsize, &len) == -1) 3181 log_warn("getsockopt bufsize"); 3182 len = sizeof(newsize); 3183 newsize = LOG_MAXLINE + 128; /* data + control */ 3184 /* allow 8 full length messages, that is 66560 bytes */ 3185 for (i = 0; i < 4; i++, newsize *= 2) { 3186 if (newsize <= oldsize) 3187 continue; 3188 if (setsockopt(fd, SOL_SOCKET, optname, &newsize, len) == -1) 3189 log_warn("setsockopt bufsize %d", newsize); 3190 else 3191 oldsize = newsize; 3192 } 3193 if (bigsize && bigsize > oldsize) { 3194 if (setsockopt(fd, SOL_SOCKET, optname, &bigsize, len) == -1) 3195 log_warn("setsockopt bufsize %d", bigsize); 3196 } 3197 } 3198 3199 void 3200 set_sockbuf(int fd) 3201 { 3202 int size = 65536; 3203 3204 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) == -1) 3205 log_warn("setsockopt sndbufsize %d", size); 3206 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) == -1) 3207 log_warn("setsockopt rcvbufsize %d", size); 3208 } 3209 3210 void 3211 set_keepalive(int fd) 3212 { 3213 int val = 1; 3214 3215 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1) 3216 log_warn("setsockopt keepalive %d", val); 3217 } 3218 3219 void 3220 ctlconn_cleanup(void) 3221 { 3222 struct filed *f; 3223 3224 close(fd_ctlconn); 3225 fd_ctlconn = -1; 3226 event_del(ev_ctlread); 3227 event_del(ev_ctlwrite); 3228 event_add(ev_ctlaccept, NULL); 3229 3230 if (ctl_state == CTL_WRITING_CONT_REPLY) 3231 SIMPLEQ_FOREACH(f, &Files, f_next) 3232 if (f->f_type == F_MEMBUF) 3233 f->f_un.f_mb.f_attached = 0; 3234 3235 ctl_state = ctl_cmd_bytes = ctl_reply_offset = ctl_reply_size = 0; 3236 } 3237 3238 void 3239 ctlsock_acceptcb(int fd, short event, void *arg) 3240 { 3241 struct event *ev = arg; 3242 3243 if ((fd = reserve_accept4(fd, event, ev, ctlsock_acceptcb, 3244 NULL, NULL, SOCK_NONBLOCK)) == -1) { 3245 if (errno != ENFILE && errno != EMFILE && 3246 errno != EINTR && errno != EWOULDBLOCK && 3247 errno != ECONNABORTED) 3248 log_warn("accept control socket"); 3249 return; 3250 } 3251 log_debug("Accepting control connection"); 3252 3253 if (fd_ctlconn != -1) 3254 ctlconn_cleanup(); 3255 3256 /* Only one connection at a time */ 3257 event_del(ev); 3258 3259 fd_ctlconn = fd; 3260 /* file descriptor has changed, reset event */ 3261 event_set(ev_ctlread, fd_ctlconn, EV_READ|EV_PERSIST, 3262 ctlconn_readcb, ev_ctlread); 3263 event_set(ev_ctlwrite, fd_ctlconn, EV_WRITE|EV_PERSIST, 3264 ctlconn_writecb, ev_ctlwrite); 3265 event_add(ev_ctlread, NULL); 3266 ctl_state = CTL_READING_CMD; 3267 ctl_cmd_bytes = 0; 3268 } 3269 3270 static struct filed 3271 *find_membuf_log(const char *name) 3272 { 3273 struct filed *f; 3274 3275 SIMPLEQ_FOREACH(f, &Files, f_next) { 3276 if (f->f_type == F_MEMBUF && 3277 strcmp(f->f_un.f_mb.f_mname, name) == 0) 3278 break; 3279 } 3280 return (f); 3281 } 3282 3283 void 3284 ctlconn_readcb(int fd, short event, void *arg) 3285 { 3286 struct filed *f; 3287 struct ctl_reply_hdr *reply_hdr = (struct ctl_reply_hdr *)ctl_reply; 3288 ssize_t n; 3289 u_int32_t flags = 0; 3290 3291 if (ctl_state == CTL_WRITING_REPLY || 3292 ctl_state == CTL_WRITING_CONT_REPLY) { 3293 /* client has closed the connection */ 3294 ctlconn_cleanup(); 3295 return; 3296 } 3297 3298 retry: 3299 n = read(fd, (char*)&ctl_cmd + ctl_cmd_bytes, 3300 sizeof(ctl_cmd) - ctl_cmd_bytes); 3301 switch (n) { 3302 case -1: 3303 if (errno == EINTR) 3304 goto retry; 3305 if (errno == EWOULDBLOCK) 3306 return; 3307 log_warn("read control socket"); 3308 /* FALLTHROUGH */ 3309 case 0: 3310 ctlconn_cleanup(); 3311 return; 3312 default: 3313 ctl_cmd_bytes += n; 3314 } 3315 if (ctl_cmd_bytes < sizeof(ctl_cmd)) 3316 return; 3317 3318 if (ntohl(ctl_cmd.version) != CTL_VERSION) { 3319 log_warnx("unknown client protocol version"); 3320 ctlconn_cleanup(); 3321 return; 3322 } 3323 3324 /* Ensure that logname is \0 terminated */ 3325 if (memchr(ctl_cmd.logname, '\0', sizeof(ctl_cmd.logname)) == NULL) { 3326 log_warnx("corrupt control socket command"); 3327 ctlconn_cleanup(); 3328 return; 3329 } 3330 3331 *reply_text = '\0'; 3332 3333 ctl_reply_size = ctl_reply_offset = 0; 3334 memset(reply_hdr, '\0', sizeof(*reply_hdr)); 3335 3336 ctl_cmd.cmd = ntohl(ctl_cmd.cmd); 3337 log_debug("ctlcmd %x logname \"%s\"", ctl_cmd.cmd, ctl_cmd.logname); 3338 3339 switch (ctl_cmd.cmd) { 3340 case CMD_READ: 3341 case CMD_READ_CLEAR: 3342 case CMD_READ_CONT: 3343 case CMD_FLAGS: 3344 f = find_membuf_log(ctl_cmd.logname); 3345 if (f == NULL) { 3346 strlcpy(reply_text, "No such log\n", MAX_MEMBUF); 3347 } else { 3348 if (ctl_cmd.cmd != CMD_FLAGS) { 3349 ringbuf_to_string(reply_text, MAX_MEMBUF, 3350 f->f_un.f_mb.f_rb); 3351 } 3352 if (f->f_un.f_mb.f_overflow) 3353 flags |= CTL_HDR_FLAG_OVERFLOW; 3354 if (ctl_cmd.cmd == CMD_READ_CLEAR) { 3355 ringbuf_clear(f->f_un.f_mb.f_rb); 3356 f->f_un.f_mb.f_overflow = 0; 3357 } 3358 if (ctl_cmd.cmd == CMD_READ_CONT) { 3359 f->f_un.f_mb.f_attached = 1; 3360 tailify_replytext(reply_text, 3361 ctl_cmd.lines > 0 ? ctl_cmd.lines : 10); 3362 } else if (ctl_cmd.lines > 0) { 3363 tailify_replytext(reply_text, ctl_cmd.lines); 3364 } 3365 } 3366 break; 3367 case CMD_CLEAR: 3368 f = find_membuf_log(ctl_cmd.logname); 3369 if (f == NULL) { 3370 strlcpy(reply_text, "No such log\n", MAX_MEMBUF); 3371 } else { 3372 ringbuf_clear(f->f_un.f_mb.f_rb); 3373 if (f->f_un.f_mb.f_overflow) 3374 flags |= CTL_HDR_FLAG_OVERFLOW; 3375 f->f_un.f_mb.f_overflow = 0; 3376 strlcpy(reply_text, "Log cleared\n", MAX_MEMBUF); 3377 } 3378 break; 3379 case CMD_LIST: 3380 SIMPLEQ_FOREACH(f, &Files, f_next) { 3381 if (f->f_type == F_MEMBUF) { 3382 strlcat(reply_text, f->f_un.f_mb.f_mname, 3383 MAX_MEMBUF); 3384 if (f->f_un.f_mb.f_overflow) { 3385 strlcat(reply_text, "*", MAX_MEMBUF); 3386 flags |= CTL_HDR_FLAG_OVERFLOW; 3387 } 3388 strlcat(reply_text, " ", MAX_MEMBUF); 3389 } 3390 } 3391 strlcat(reply_text, "\n", MAX_MEMBUF); 3392 break; 3393 default: 3394 log_warnx("unsupported control socket command"); 3395 ctlconn_cleanup(); 3396 return; 3397 } 3398 reply_hdr->version = htonl(CTL_VERSION); 3399 reply_hdr->flags = htonl(flags); 3400 3401 ctl_reply_size = CTL_REPLY_SIZE; 3402 log_debug("ctlcmd reply length %lu", (u_long)ctl_reply_size); 3403 3404 /* Otherwise, set up to write out reply */ 3405 ctl_state = (ctl_cmd.cmd == CMD_READ_CONT) ? 3406 CTL_WRITING_CONT_REPLY : CTL_WRITING_REPLY; 3407 3408 event_add(ev_ctlwrite, NULL); 3409 3410 /* another syslogc can kick us out */ 3411 if (ctl_state == CTL_WRITING_CONT_REPLY) 3412 event_add(ev_ctlaccept, NULL); 3413 } 3414 3415 void 3416 ctlconn_writecb(int fd, short event, void *arg) 3417 { 3418 struct event *ev = arg; 3419 ssize_t n; 3420 3421 if (!(ctl_state == CTL_WRITING_REPLY || 3422 ctl_state == CTL_WRITING_CONT_REPLY)) { 3423 /* Shouldn't be here! */ 3424 log_warnx("control socket write with bad state"); 3425 ctlconn_cleanup(); 3426 return; 3427 } 3428 3429 retry: 3430 n = write(fd, ctl_reply + ctl_reply_offset, 3431 ctl_reply_size - ctl_reply_offset); 3432 switch (n) { 3433 case -1: 3434 if (errno == EINTR) 3435 goto retry; 3436 if (errno == EWOULDBLOCK) 3437 return; 3438 if (errno != EPIPE) 3439 log_warn("write control socket"); 3440 /* FALLTHROUGH */ 3441 case 0: 3442 ctlconn_cleanup(); 3443 return; 3444 default: 3445 ctl_reply_offset += n; 3446 } 3447 if (ctl_reply_offset < ctl_reply_size) 3448 return; 3449 3450 if (ctl_state != CTL_WRITING_CONT_REPLY) { 3451 ctlconn_cleanup(); 3452 return; 3453 } 3454 3455 /* 3456 * Make space in the buffer for continuous writes. 3457 * Set offset behind reply header to skip it 3458 */ 3459 *reply_text = '\0'; 3460 ctl_reply_offset = ctl_reply_size = CTL_REPLY_SIZE; 3461 3462 /* Now is a good time to report dropped lines */ 3463 if (membuf_drop) { 3464 strlcat(reply_text, "<ENOBUFS>\n", MAX_MEMBUF); 3465 ctl_reply_size = CTL_REPLY_SIZE; 3466 membuf_drop = 0; 3467 } else { 3468 /* Nothing left to write */ 3469 event_del(ev); 3470 } 3471 } 3472 3473 /* Shorten replytext to number of lines */ 3474 void 3475 tailify_replytext(char *replytext, int lines) 3476 { 3477 char *start, *nl; 3478 int count = 0; 3479 start = nl = replytext; 3480 3481 while ((nl = strchr(nl, '\n')) != NULL) { 3482 nl++; 3483 if (++count > lines) { 3484 start = strchr(start, '\n'); 3485 start++; 3486 } 3487 } 3488 if (start != replytext) { 3489 int len = strlen(start); 3490 memmove(replytext, start, len); 3491 *(replytext + len) = '\0'; 3492 } 3493 } 3494 3495 void 3496 ctlconn_logto(char *line) 3497 { 3498 size_t l; 3499 3500 if (membuf_drop) 3501 return; 3502 3503 l = strlen(line); 3504 if (l + 2 > (CTL_REPLY_MAXSIZE - ctl_reply_size)) { 3505 /* remember line drops for later report */ 3506 membuf_drop = 1; 3507 return; 3508 } 3509 memcpy(ctl_reply + ctl_reply_size, line, l); 3510 memcpy(ctl_reply + ctl_reply_size + l, "\n", 2); 3511 ctl_reply_size += l + 1; 3512 event_add(ev_ctlwrite, NULL); 3513 } 3514