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