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