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