1 #include "first.h" 2 3 #include "base.h" 4 #include "buffer.h" 5 #include "network.h" 6 #include "log.h" 7 #include "rand.h" 8 #include "chunk.h" 9 #include "h2.h" /* h2_send_1xx() */ 10 #include "fdevent.h" 11 #include "fdlog.h" 12 #include "connections.h" 13 #include "sock_addr.h" 14 #include "stat_cache.h" 15 #include "plugin.h" 16 #include "plugin_config.h" /* config_plugin_value_tobool() */ 17 #include "network_write.h" /* network_write_show_handlers() */ 18 #include "reqpool.h" /* request_pool_init() request_pool_free() */ 19 #include "response.h" /* http_response_send_1xx_cb_set() strftime_cache_reset() */ 20 21 #ifdef HAVE_VERSIONSTAMP_H 22 # include "versionstamp.h" 23 #else 24 # define REPO_VERSION "" 25 #endif 26 27 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION 28 static const buffer default_server_tag = { CONST_STR_LEN(PACKAGE_DESC)+1, 0 }; 29 30 #include <sys/types.h> 31 #include <sys/stat.h> 32 #include "sys-time.h" 33 34 #include <string.h> 35 #include <errno.h> 36 #include <fcntl.h> 37 #include <unistd.h> 38 #include <stdlib.h> 39 #include <signal.h> 40 #include <locale.h> 41 42 #include <stdio.h> 43 44 #ifdef HAVE_GETOPT_H 45 # include <getopt.h> 46 #endif 47 48 #ifdef HAVE_VALGRIND_VALGRIND_H 49 # include <valgrind/valgrind.h> 50 #endif 51 52 #ifdef HAVE_PWD_H 53 # include <grp.h> 54 # include <pwd.h> 55 #endif 56 57 #ifdef HAVE_SYS_LOADAVG_H 58 # include <sys/loadavg.h> 59 #endif 60 61 #ifdef HAVE_SYS_RESOURCE_H 62 # include <sys/resource.h> 63 #endif 64 65 #ifdef HAVE_SYS_PRCTL_H 66 # include <sys/prctl.h> 67 #endif 68 69 #ifdef HAVE_MALLOC_H 70 #ifndef LIGHTTPD_STATIC 71 #ifdef HAVE_DLFCN_H 72 #include <dlfcn.h> 73 #endif 74 #endif 75 #include <malloc.h> 76 #if defined(HAVE_MALLOC_TRIM) 77 static int(*malloc_trim_fn)(size_t); 78 static size_t malloc_top_pad; 79 #endif 80 #endif 81 82 #include "sys-crypto.h" 83 #if defined(USE_OPENSSL_CRYPTO) \ 84 || defined(USE_MBEDTLS_CRYPTO) \ 85 || defined(USE_NSS_CRYPTO) \ 86 || defined(USE_GNUTLS_CRYPTO) \ 87 || defined(USE_WOLFTLS_CRYPTO) 88 #define TEXT_SSL " (ssl)" 89 #else 90 #define TEXT_SSL 91 #endif 92 93 #ifndef __sgi 94 /* IRIX doesn't like the alarm based time() optimization */ 95 /* #define USE_ALARM */ 96 #endif 97 98 static int oneshot_fd = 0; 99 static int oneshot_fdout = -1; 100 static fdnode *oneshot_fdn = NULL; 101 static int (*oneshot_read_cq)(connection *con, chunkqueue *cq, off_t max_bytes); 102 static volatile int pid_fd = -2; 103 static server_socket_array graceful_sockets; 104 static server_socket_array inherited_sockets; 105 static volatile sig_atomic_t graceful_restart = 0; 106 static volatile sig_atomic_t graceful_shutdown = 0; 107 static volatile sig_atomic_t srv_shutdown = 0; 108 static volatile sig_atomic_t handle_sig_child = 0; 109 static volatile sig_atomic_t handle_sig_alarm = 1; 110 static volatile sig_atomic_t handle_sig_hup = 0; 111 static int idle_limit = 0; 112 113 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO) 114 static volatile siginfo_t last_sigterm_info; 115 static volatile siginfo_t last_sighup_info; 116 117 static void sigaction_handler(int sig, siginfo_t *si, void *context) { 118 static const siginfo_t empty_siginfo; 119 UNUSED(context); 120 121 if (!si) *(const siginfo_t **)&si = &empty_siginfo; 122 123 switch (sig) { 124 case SIGTERM: 125 srv_shutdown = 1; 126 last_sigterm_info = *si; 127 break; 128 case SIGUSR1: 129 if (!graceful_shutdown) { 130 graceful_restart = 1; 131 graceful_shutdown = 1; 132 last_sigterm_info = *si; 133 } 134 break; 135 case SIGINT: 136 if (graceful_shutdown) { 137 if (2 == graceful_restart) 138 graceful_restart = 1; 139 else 140 srv_shutdown = 1; 141 } else { 142 graceful_shutdown = 1; 143 } 144 last_sigterm_info = *si; 145 146 break; 147 case SIGALRM: 148 handle_sig_alarm = 1; 149 break; 150 case SIGHUP: 151 handle_sig_hup = 1; 152 last_sighup_info = *si; 153 break; 154 case SIGCHLD: 155 handle_sig_child = 1; 156 break; 157 } 158 } 159 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION) 160 static void signal_handler(int sig) { 161 switch (sig) { 162 case SIGTERM: srv_shutdown = 1; break; 163 case SIGUSR1: 164 if (!graceful_shutdown) { 165 graceful_restart = 1; 166 graceful_shutdown = 1; 167 } 168 break; 169 case SIGINT: 170 if (graceful_shutdown) { 171 if (2 == graceful_restart) 172 graceful_restart = 1; 173 else 174 srv_shutdown = 1; 175 } else { 176 graceful_shutdown = 1; 177 } 178 break; 179 case SIGALRM: handle_sig_alarm = 1; break; 180 case SIGHUP: handle_sig_hup = 1; break; 181 case SIGCHLD: handle_sig_child = 1; break; 182 } 183 } 184 #endif 185 186 #ifdef HAVE_FORK 187 static int daemonize(void) { 188 int pipefd[2]; 189 pid_t pid; 190 #ifdef SIGTTOU 191 signal(SIGTTOU, SIG_IGN); 192 #endif 193 #ifdef SIGTTIN 194 signal(SIGTTIN, SIG_IGN); 195 #endif 196 #ifdef SIGTSTP 197 signal(SIGTSTP, SIG_IGN); 198 #endif 199 200 if (fdevent_pipe_cloexec(pipefd, 64) < 0) exit(-1); 201 202 if (0 > (pid = fork())) exit(-1); 203 204 if (0 < pid) { 205 char buf; 206 ssize_t bytes; 207 208 close(pipefd[1]); 209 /* parent waits for grandchild to be ready */ 210 do { 211 bytes = read(pipefd[0], &buf, sizeof(buf)); 212 } while (bytes < 0 && EINTR == errno); 213 close(pipefd[0]); 214 215 if (bytes <= 0) { 216 /* closed fd (without writing) == failure in grandchild */ 217 fputs("daemonized server failed to start; check error log for details\n", stderr); 218 exit(-1); 219 } 220 221 exit(0); 222 } 223 224 close(pipefd[0]); 225 226 if (-1 == setsid()) exit(0); 227 228 signal(SIGHUP, SIG_IGN); 229 230 if (0 != fork()) exit(0); 231 232 if (0 != chdir("/")) exit(0); 233 234 return pipefd[1]; 235 } 236 #endif 237 238 static int clockid_mono_coarse = 0; 239 240 static unix_time64_t 241 server_monotonic_secs (void) 242 { 243 unix_timespec64_t ts; 244 return (0 == log_clock_gettime(clockid_mono_coarse, &ts)) 245 ? ts.tv_sec 246 : log_monotonic_secs; 247 } 248 249 static unix_time64_t 250 server_epoch_secs (server * const srv, unix_time64_t mono_ts_delta) 251 { 252 const unix_time64_t cur_ts = log_epoch_secs; 253 const unix_time64_t new_ts = TIME64_CAST(time(NULL)); 254 const unix_time64_t new_ts_adj = new_ts - mono_ts_delta; 255 /* attempt to detect large clock jump */ 256 if (new_ts_adj < cur_ts || new_ts_adj - cur_ts > 300) { /*(5 mins)*/ 257 log_error(srv->errh, __FILE__, __LINE__, 258 "warning: clock jumped %lld secs", 259 (long long)((int64_t)new_ts_adj - (int64_t)cur_ts)); 260 int delta = /*(30 mins default)*/ 261 config_feature_int(srv, "server.clock-jump-restart", 1800); 262 if (delta && (new_ts_adj > cur_ts 263 ? new_ts_adj-cur_ts 264 : cur_ts-new_ts_adj) > delta) { 265 log_error(srv->errh, __FILE__, __LINE__, 266 "attempting graceful restart in < ~5 seconds, else hard restart"); 267 srv->graceful_expire_ts = log_monotonic_secs + 5; 268 raise(SIGUSR1); 269 } 270 } 271 return new_ts; 272 } 273 274 __attribute_cold__ 275 __attribute_noinline__ 276 __attribute_returns_nonnull__ 277 static server *server_init(void) { 278 server *srv = calloc(1, sizeof(*srv)); 279 force_assert(srv); 280 281 srv->tmp_buf = buffer_init(); 282 283 strftime_cache_reset(); 284 285 li_rand_reseed(); 286 287 srv->startup_ts = log_epoch_secs = TIME64_CAST(time(NULL)); 288 #ifdef HAVE_CLOCK_GETTIME 289 unix_timespec64_t ts; 290 UNUSED(&ts); 291 #ifdef CLOCK_MONOTONIC_COARSE 292 if (0 == log_clock_gettime(CLOCK_MONOTONIC_COARSE, &ts)) 293 clockid_mono_coarse = CLOCK_MONOTONIC_COARSE; 294 else 295 #endif 296 #ifdef CLOCK_MONOTONIC_RAW_APPROX 297 if (0 == log_clock_gettime(CLOCK_MONOTONIC_RAW_APPROX, &ts)) 298 clockid_mono_coarse = CLOCK_MONOTONIC_RAW_APPROX; 299 else 300 #endif 301 #ifdef CLOCK_MONOTONIC_RAW 302 if (0 == log_clock_gettime(CLOCK_MONOTONIC_RAW, &ts)) 303 clockid_mono_coarse = CLOCK_MONOTONIC_RAW; 304 else 305 #endif 306 clockid_mono_coarse = CLOCK_MONOTONIC; 307 #endif 308 log_monotonic_secs = server_monotonic_secs(); 309 310 srv->errh = log_set_global_errh(NULL, 0); 311 312 config_init(srv); 313 314 srv->request_env = plugins_call_handle_request_env; 315 316 srv->loadavg[0] = 0.0; 317 srv->loadavg[1] = 0.0; 318 srv->loadavg[2] = 0.0; 319 srv->stdin_fd = -1; 320 321 log_con_jqueue = (connection *)(uintptr_t)&log_con_jqueue;/*(sentinel)*/ 322 323 return srv; 324 } 325 326 __attribute_cold__ 327 __attribute_noinline__ 328 static void server_free(server *srv) { 329 if (oneshot_fd > 0) { 330 if (oneshot_fdn) { 331 fdevent_fdnode_event_del(srv->ev, oneshot_fdn); 332 fdevent_unregister(srv->ev, oneshot_fd); 333 oneshot_fdn = NULL; 334 } 335 close(oneshot_fd); 336 } 337 if (oneshot_fdout >= 0) { 338 close(oneshot_fdout); 339 } 340 if (srv->stdin_fd >= 0) { 341 close(srv->stdin_fd); 342 } 343 344 buffer_free(srv->tmp_buf); 345 346 fdevent_free(srv->ev); 347 348 config_free(srv); 349 350 stat_cache_free(); 351 352 li_rand_cleanup(); 353 chunkqueue_chunk_pool_free(); 354 355 if (srv->errh != log_set_global_errh(NULL, 0)) 356 fdlog_free(srv->errh); 357 free(srv); 358 } 359 360 __attribute_cold__ 361 __attribute_noinline__ 362 static void remove_pid_file(server *srv) { 363 if (pid_fd <= -2) return; 364 if (srv->srvconf.pid_file && 0 <= pid_fd) { 365 if (0 != ftruncate(pid_fd, 0)) { 366 log_perror(srv->errh, __FILE__, __LINE__, 367 "ftruncate failed for: %s", srv->srvconf.pid_file->ptr); 368 } 369 } 370 if (0 <= pid_fd) { 371 close(pid_fd); 372 pid_fd = -1; 373 } 374 if (srv->srvconf.pid_file && !srv->srvconf.changeroot) { 375 if (0 != unlink(srv->srvconf.pid_file->ptr)) { 376 if (errno != EACCES && errno != EPERM) { 377 log_perror(srv->errh, __FILE__, __LINE__, 378 "unlink failed for: %s", srv->srvconf.pid_file->ptr); 379 } 380 } 381 } 382 } 383 384 385 __attribute_cold__ 386 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) { 387 server_socket *srv_socket, *srv_socket_wild = NULL; 388 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 389 srv_socket = srv->srv_sockets.ptr[i]; 390 if (!sock_addr_is_port_eq(&srv_socket->addr,cnt_addr)) continue; 391 if (sock_addr_is_addr_eq(&srv_socket->addr,cnt_addr)) return srv_socket; 392 393 if (NULL != srv_socket_wild) continue; 394 if (sock_addr_is_addr_wildcard(&srv_socket->addr)) { 395 srv_socket_wild = srv_socket; 396 } 397 } 398 399 if (NULL != srv_socket_wild) { 400 return srv_socket_wild; 401 } else if (srv->srv_sockets.used) { 402 return srv->srv_sockets.ptr[0]; 403 } else { 404 log_error(srv->errh, __FILE__, __LINE__, "no sockets configured"); 405 return NULL; 406 } 407 } 408 409 410 static int server_oneshot_read_cq(connection *con, chunkqueue *cq, off_t max_bytes) { 411 /* temporary set con->fd to oneshot_fd (fd input) rather than outshot_fdout 412 * (lighttpd generally assumes operation on sockets, so this is a kludge) */ 413 int fd = con->fd; 414 con->fd = oneshot_fdn->fd; 415 int rc = oneshot_read_cq(con, cq, max_bytes); 416 con->fd = fd; 417 418 /* note: optimistic reads (elsewhere) may or may not be enough to re-enable 419 * read interest after FDEVENT_IN interest was paused for other reasons */ 420 421 const int events = fdevent_fdnode_interest(oneshot_fdn); 422 int n = con->is_readable > 0 ? 0 : FDEVENT_IN; 423 if (events & FDEVENT_RDHUP) 424 n |= FDEVENT_RDHUP; 425 fdevent_fdnode_event_set(con->srv->ev, oneshot_fdn, n); 426 return rc; 427 } 428 429 430 static handler_t server_oneshot_handle_fdevent(void *context, int revents) { 431 connection *con = context; 432 433 /* note: not sync'd with con->fdn or connection_set_fdevent_interest() */ 434 int rdhup = 0; 435 int n = fdevent_fdnode_interest(oneshot_fdn); 436 if (revents & FDEVENT_IN) 437 n &= ~FDEVENT_IN; 438 request_st * const r = &con->request; 439 if (r->state != CON_STATE_ERROR && (revents & (FDEVENT_HUP|FDEVENT_RDHUP))){ 440 revents &= ~(FDEVENT_HUP|FDEVENT_RDHUP); 441 /* copied and modified from connection_handle_fdevent() 442 * fdevent_is_tcp_half_closed() will fail on pipe 443 * and, besides, read end of pipes should treat POLLHUP as POLLRDHUP */ 444 n &= ~(FDEVENT_IN|FDEVENT_RDHUP); 445 rdhup = 1; 446 } 447 fdevent_fdnode_event_set(con->srv->ev, oneshot_fdn, n); 448 449 fdnode * const fdn = con->fdn; /* fdn->ctx == con */ 450 handler_t rc = (fdn && (fdevent_handler)NULL != fdn->handler) 451 ? (*fdn->handler)(con, revents) 452 : HANDLER_FINISHED; 453 454 if (rdhup) { 455 r->conf.stream_request_body &= 456 ~(FDEVENT_STREAM_REQUEST_BUFMIN|FDEVENT_STREAM_REQUEST_POLLIN); 457 r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLRDHUP; 458 r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_TCP_FIN; 459 con->is_readable = 1; /*(can read 0 for end-of-stream)*/ 460 if (chunkqueue_is_empty(con->read_queue)) r->keep_alive = 0; 461 if (r->reqbody_length < -1) /*(transparent proxy mode; no more data)*/ 462 r->reqbody_length = r->reqbody_queue.bytes_in; 463 } 464 465 return rc; 466 } 467 468 469 __attribute_cold__ 470 static int server_oneshot_init_pipe(server *srv, int fdin, int fdout) { 471 /* Note: attempt to work with netcat pipes though other code expects socket. 472 * netcat has different fds (pipes) for stdin and stdout. To support 473 * netcat, need to avoid S_ISSOCK(), getsockname(), and getpeername(), 474 * reconstructing addresses from environment variables: 475 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT 476 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT 477 * NCAT_PROTO (TCP, UDP, SCTP) 478 */ 479 connection *con; 480 const server_socket *srv_socket; 481 sock_addr cnt_addr; 482 483 /* detect if called from netcat or else fabricate localhost addrs */ 484 const char * const ncat = 485 getenv("NCAT_LOCAL_ADDR"); 486 const char * const ncat_local_addr = 487 ncat ? ncat : "127.0.0.1"; /*(fabricated)*/ 488 const char * const ncat_local_port = 489 ncat ? getenv("NCAT_LOCAL_PORT") : "80"; /*(fabricated)*/ 490 const char * const ncat_remote_addr = 491 ncat ? getenv("NCAT_REMOTE_ADDR") : "127.0.0.1"; /*(fabricated)*/ 492 const char * const ncat_remote_port = 493 ncat ? getenv("NCAT_REMOTE_PORT") : "48080"; /*(fabricated)*/ 494 if (NULL == ncat_local_addr || NULL == ncat_local_port) return 0; 495 if (NULL == ncat_remote_addr || NULL == ncat_remote_port) return 0; 496 497 const int family = ncat && strchr(ncat_local_addr,':') ? AF_INET6 : AF_INET; 498 unsigned short port; 499 500 port = (unsigned short)strtol(ncat_local_port, NULL, 10); 501 if (1 != sock_addr_inet_pton(&cnt_addr, ncat_local_addr, family, port)) { 502 log_error(srv->errh, __FILE__, __LINE__, "invalid local addr"); 503 return 0; 504 } 505 506 srv_socket = server_oneshot_getsock(srv, &cnt_addr); 507 if (NULL == srv_socket) return 0; 508 509 port = (unsigned short)strtol(ncat_remote_port, NULL, 10); 510 if (1 != sock_addr_inet_pton(&cnt_addr, ncat_remote_addr, family, port)) { 511 log_error(srv->errh, __FILE__, __LINE__, "invalid remote addr"); 512 return 0; 513 } 514 515 /*(must set flags; fd did not pass through fdevent accept() logic)*/ 516 if (-1 == fdevent_fcntl_set_nb_cloexec(fdin)) { 517 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 518 return 0; 519 } 520 if (-1 == fdevent_fcntl_set_nb_cloexec(fdout)) { 521 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 522 return 0; 523 } 524 525 con = connection_accepted(srv, srv_socket, &cnt_addr, fdout); 526 if (NULL == con) return 0; 527 528 /* note: existing routines assume socket, not pipe 529 * connections.c:connection_read_cq() 530 * uses recv() ifdef __WIN32 531 * passes S_IFSOCK to fdevent_ioctl_fionread() 532 * (The routine could be copied and modified, if required) 533 * This is unlikely to work if TLS is used over pipe since the SSL_CTX 534 * is associated with the other end of the pipe. However, if using 535 * pipes, using TLS is unexpected behavior. 536 */ 537 538 /*assert(oneshot_fd == fdin);*/ 539 oneshot_read_cq = con->network_read; 540 con->network_read = server_oneshot_read_cq; 541 oneshot_fdn = 542 fdevent_register(srv->ev, fdin, server_oneshot_handle_fdevent, con); 543 fdevent_fdnode_event_set(srv->ev, oneshot_fdn, FDEVENT_RDHUP); 544 545 connection_state_machine(con); 546 return 1; 547 } 548 549 550 __attribute_cold__ 551 static int server_oneshot_init(server *srv, int fd) { 552 connection *con; 553 const server_socket *srv_socket; 554 sock_addr cnt_addr; 555 socklen_t cnt_len; 556 557 cnt_len = sizeof(cnt_addr); 558 if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 559 log_perror(srv->errh, __FILE__, __LINE__, "getsockname()"); 560 return 0; 561 } 562 563 srv_socket = server_oneshot_getsock(srv, &cnt_addr); 564 if (NULL == srv_socket) return 0; 565 566 #ifdef __clang_analyzer__ 567 memset(&cnt_addr, 0, sizeof(cnt_addr)); 568 #endif 569 cnt_len = sizeof(cnt_addr); 570 if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 571 log_perror(srv->errh, __FILE__, __LINE__, "getpeername()"); 572 return 0; 573 } 574 575 /*(must set flags; fd did not pass through fdevent accept() logic)*/ 576 if (-1 == fdevent_fcntl_set_nb_cloexec(fd)) { 577 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 578 return 0; 579 } 580 581 if (sock_addr_get_family(&cnt_addr) != AF_UNIX) { 582 network_accept_tcp_nagle_disable(fd); 583 } 584 585 con = connection_accepted(srv, srv_socket, &cnt_addr, fd); 586 if (NULL == con) return 0; 587 588 connection_state_machine(con); 589 return 1; 590 } 591 592 593 __attribute_cold__ 594 static void show_version (void) { 595 char *b = PACKAGE_DESC TEXT_SSL \ 596 " - a light and fast webserver\n" 597 #ifdef NONREPRODUCIBLE_BUILD 598 "Build-Date: " __DATE__ " " __TIME__ "\n"; 599 #endif 600 ; 601 write_all(STDOUT_FILENO, b, strlen(b)); 602 } 603 604 __attribute_cold__ 605 static void show_features (void) { 606 static const char features[] = 607 "\nFeatures:\n\n" 608 #ifdef HAVE_IPV6 609 "\t+ IPv6 support\n" 610 #else 611 "\t- IPv6 support\n" 612 #endif 613 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ 614 "\t+ zlib support\n" 615 #else 616 "\t- zlib support\n" 617 #endif 618 #if defined HAVE_ZSTD_H && defined HAVE_ZSTD 619 "\t+ zstd support\n" 620 #else 621 "\t- zstd support\n" 622 #endif 623 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2 624 "\t+ bzip2 support\n" 625 #else 626 "\t- bzip2 support\n" 627 #endif 628 #if defined HAVE_BROTLI_ENCODE_H && defined HAVE_BROTLI 629 "\t+ brotli support\n" 630 #else 631 "\t- brotli support\n" 632 #endif 633 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT) 634 "\t+ crypt support\n" 635 #else 636 "\t- crypt support\n" 637 #endif 638 #ifdef USE_OPENSSL_CRYPTO 639 "\t+ OpenSSL support\n" 640 #else 641 "\t- OpenSSL support\n" 642 #endif 643 #ifdef USE_MBEDTLS_CRYPTO 644 "\t+ mbedTLS support\n" 645 #else 646 "\t- mbedTLS support\n" 647 #endif 648 #ifdef USE_NSS_CRYPTO 649 "\t+ NSS crypto support\n" 650 #else 651 "\t- NSS crypto support\n" 652 #endif 653 #ifdef USE_GNUTLS_CRYPTO 654 "\t+ GnuTLS support\n" 655 #else 656 "\t- GnuTLS support\n" 657 #endif 658 #ifdef USE_WOLFSSL_CRYPTO 659 "\t+ WolfSSL support\n" 660 #else 661 "\t- WolfSSL support\n" 662 #endif 663 #ifdef USE_NETTLE_CRYPTO 664 "\t+ Nettle support\n" 665 #else 666 "\t- Nettle support\n" 667 #endif 668 #ifdef HAVE_PCRE 669 "\t+ PCRE support\n" 670 #else 671 "\t- PCRE support\n" 672 #endif 673 #ifdef HAVE_MYSQL 674 "\t+ MySQL support\n" 675 #else 676 "\t- MySQL support\n" 677 #endif 678 #ifdef HAVE_PGSQL 679 "\t+ PgSQL support\n" 680 #else 681 "\t- PgSQL support\n" 682 #endif 683 #ifdef HAVE_DBI 684 "\t+ DBI support\n" 685 #else 686 "\t- DBI support\n" 687 #endif 688 #ifdef HAVE_KRB5 689 "\t+ Kerberos support\n" 690 #else 691 "\t- Kerberos support\n" 692 #endif 693 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER) 694 "\t+ LDAP support\n" 695 #else 696 "\t- LDAP support\n" 697 #endif 698 #ifdef HAVE_PAM 699 "\t+ PAM support\n" 700 #else 701 "\t- PAM support\n" 702 #endif 703 #ifdef USE_MEMCACHED 704 "\t+ memcached support\n" 705 #else 706 "\t- memcached support\n" 707 #endif 708 #ifdef HAVE_FAM_H 709 "\t+ FAM support\n" 710 #else 711 "\t- FAM support\n" 712 #endif 713 #ifdef HAVE_LUA_H 714 "\t+ LUA support\n" 715 #else 716 "\t- LUA support\n" 717 #endif 718 #ifdef HAVE_LIBXML_H 719 "\t+ xml support\n" 720 #else 721 "\t- xml support\n" 722 #endif 723 #ifdef HAVE_SQLITE3_H 724 "\t+ SQLite support\n" 725 #else 726 "\t- SQLite support\n" 727 #endif 728 #ifdef HAVE_GDBM_H 729 "\t+ GDBM support\n" 730 #else 731 "\t- GDBM support\n" 732 #endif 733 ; 734 show_version(); 735 printf("%s%s%s%s\n", 736 fdevent_show_event_handlers(), 737 network_write_show_handlers(), 738 features, 739 sizeof(time_t) > 4 || (sizeof(time_t) == 4 && (time_t)-1 > (time_t)1) 740 ? "\t+ Y2038 support\n" 741 : "\t- Y2038 support (unsafe 32-bit signed time_t)\n"); 742 } 743 744 __attribute_cold__ 745 static void show_help (void) { 746 char *b = PACKAGE_DESC TEXT_SSL 747 #ifdef NONREPRODUCIBLE_BUILD 748 " ("__DATE__ " " __TIME__ ")" 749 #endif 750 " - a light and fast webserver\n" \ 751 "usage:\n" \ 752 " -f <name> filename of the config-file\n" \ 753 " -m <name> module directory (default: "LIBRARY_DIR")\n" \ 754 " -i <secs> graceful shutdown after <secs> of inactivity\n" \ 755 " -1 process single (one) request on stdin socket, then exit\n" \ 756 " -p print the parsed config-file in internal form, and exit\n" \ 757 " -t test config-file syntax, then exit\n" \ 758 " -tt test config-file syntax, load and init modules, then exit\n" \ 759 " -D don't go to background (default: go to background)\n" \ 760 " -v show version\n" \ 761 " -V show compile-time features\n" \ 762 " -h show this help\n" \ 763 "\n" 764 ; 765 write_all(STDOUT_FILENO, b, strlen(b)); 766 } 767 768 __attribute_cold__ 769 __attribute_noinline__ 770 static void server_sockets_save (server *srv) { /* graceful_restart */ 771 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) 772 srv->srv_sockets.ptr[i]->srv = NULL; /* srv will shortly be invalid */ 773 for (uint32_t i = 0; i < srv->srv_sockets_inherited.used; ++i) 774 srv->srv_sockets_inherited.ptr[i]->srv = NULL; /* srv to be invalid */ 775 memcpy(&graceful_sockets, &srv->srv_sockets, sizeof(server_socket_array)); 776 memset(&srv->srv_sockets, 0, sizeof(server_socket_array)); 777 memcpy(&inherited_sockets, &srv->srv_sockets_inherited, sizeof(server_socket_array)); 778 memset(&srv->srv_sockets_inherited, 0, sizeof(server_socket_array)); 779 } 780 781 __attribute_cold__ 782 __attribute_noinline__ 783 static void server_sockets_restore (server *srv) { /* graceful_restart */ 784 memcpy(&srv->srv_sockets, &graceful_sockets, sizeof(server_socket_array)); 785 memset(&graceful_sockets, 0, sizeof(server_socket_array)); 786 memcpy(&srv->srv_sockets_inherited, &inherited_sockets, sizeof(server_socket_array)); 787 memset(&inherited_sockets, 0, sizeof(server_socket_array)); 788 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) 789 srv->srv_sockets.ptr[i]->srv = srv; /* update ptr */ 790 for (uint32_t i = 0; i < srv->srv_sockets_inherited.used; ++i) 791 srv->srv_sockets_inherited.ptr[i]->srv = srv; /* update ptr */ 792 } 793 794 __attribute_cold__ 795 static int server_sockets_set_nb_cloexec (server *srv) { 796 if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */ 797 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 798 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 799 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv_socket->fd)) { 800 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 801 return -1; 802 } 803 } 804 return 0; 805 } 806 807 __attribute_cold__ 808 static void server_sockets_set_event (server *srv, int event) { 809 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 810 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 811 fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event); 812 } 813 } 814 815 __attribute_cold__ 816 static void server_sockets_unregister (server *srv) { 817 if (2 == srv->sockets_disabled) return; 818 srv->sockets_disabled = 2; 819 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) 820 network_unregister_sock(srv, srv->srv_sockets.ptr[i]); 821 } 822 823 __attribute_cold__ 824 static void server_sockets_close (server *srv) { 825 /* closing socket right away will make it possible for the next lighttpd 826 * to take over (old-style graceful restart), but only if backends 827 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather 828 * than started by lighttpd via "bin-path") 829 */ 830 if (3 == srv->sockets_disabled) return; 831 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 832 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 833 if (-1 == srv_socket->fd) continue; 834 if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket); 835 close(srv_socket->fd); 836 srv_socket->fd = -1; 837 /* network_close() will cleanup after us */ 838 } 839 srv->sockets_disabled = 3; 840 } 841 842 __attribute_cold__ 843 static void server_graceful_signal_prev_generation (void) 844 { 845 const char * const prev_gen = getenv("LIGHTTPD_PREV_GEN"); 846 if (NULL == prev_gen) return; 847 pid_t pid = (pid_t)strtol(prev_gen, NULL, 10); 848 unsetenv("LIGHTTPD_PREV_GEN"); 849 if (pid <= 0) return; /*(should not happen)*/ 850 if (pid == fdevent_waitpid(pid,NULL,1)) return; /*(pid exited; unexpected)*/ 851 kill(pid, SIGINT); /* signal previous generation for graceful shutdown */ 852 } 853 854 __attribute_cold__ 855 static int server_graceful_state_bg (server *srv) { 856 /*assert(graceful_restart);*/ 857 /*(SIGUSR1 set to SIG_IGN in workers, so should not reach here if worker)*/ 858 if (srv_shutdown) return 0; 859 860 /* check if server should fork and background (bg) itself 861 * to continue processing requests already in progress */ 862 if (!config_feature_bool(srv, "server.graceful-restart-bg", 0)) return 0; 863 864 /*(set flag to false to avoid repeating)*/ 865 data_unset * const du = 866 array_get_data_unset(srv->srvconf.feature_flags, 867 CONST_STR_LEN("server.graceful-restart-bg")); 868 if (du->type == TYPE_STRING) 869 buffer_copy_string_len(&((data_string *)du)->value, 870 CONST_STR_LEN("false")); 871 else /* (du->type == TYPE_INTEGER) */ 872 ((data_integer *)du)->value = 0; 873 874 /* require exec'd via absolute path or daemon in foreground 875 * and exec'd with path containing '/' (e.g. "./xxxxx") */ 876 char ** const argv = srv->argv; 877 if (0 == srv->srvconf.dont_daemonize 878 ? argv[0][0] != '/' 879 : NULL == strchr(argv[0], '/')) return 0; 880 881 #if 0 882 /* disabled; not fully implemented 883 * srv->srvconf.systemd_socket_activation might be cleared in network_init() 884 * leading to issuing a false warning 885 */ 886 /* warn if server.systemd-socket-activation not enabled 887 * (While this warns on existing config rather than new config, 888 * it is probably a decent predictor for presence in new config) */ 889 if (!srv->srvconf.systemd_socket_activation) 890 log_error(srv->errh, __FILE__, __LINE__, 891 "[note] server.systemd-socket-activation not enabled; " 892 "listen sockets will be closed and reopened"); 893 #endif 894 895 /* flush log buffers to avoid potential duplication of entries 896 * server_handle_sighup(srv) does the following, but skip logging */ 897 plugins_call_handle_sighup(srv); 898 fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */ 899 900 /* backgrounding to continue processing requests in progress */ 901 /* re-exec lighttpd in original process 902 * Note: using path in re-exec is portable and allows lighttpd upgrade. 903 * OTOH, getauxval() AT_EXECFD and fexecve() could be used on Linux to 904 * re-exec without access to original executable on disk, which might be 905 * desirable in some situations, but is not implemented here. 906 * Alternatively, if argv[] was not available, could use readlink() on 907 * /proc/self/exe (Linux-specific), though there are ways on many other 908 * platforms to achieve the same: 909 * https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe 910 */ 911 #if defined(HAVE_KQUEUE) 912 #if defined(__FreeBSD__) || defined(__DragonFly__) 913 /*(must *exclude* rfork RFFDG flag for kqueue to work across rfork)*/ 914 pid_t pid = rfork(RFPROC); 915 #else 916 pid_t pid = -1; 917 if (pid < 0) { 918 /* kqueue is not inherited across fork 919 * future: fdevent kqueue and stat_cache kqueue would need to be closed, 920 * re-opened, and active fds re-registered. Not current done. 921 * Need to create some routines like fdevent_reinit_after_fork*/ 922 log_error(srv->errh, __FILE__, __LINE__, 923 "server.graceful-restart-bg ignored on OpenBSD and NetBSD " 924 "due to limitation in kqueue inheritance and lacking rfork"); 925 return 0; 926 } 927 #endif 928 #else 929 pid_t pid = fork(); 930 #endif 931 if (pid) { /* original process */ 932 if (pid < 0) return 0; 933 network_socket_activation_to_env(srv); 934 /* save pid of original server in environment so that it can be 935 * signalled by restarted server once restarted server is ready 936 * to accept new connections */ 937 server_graceful_signal_prev_generation();/*(expect no prev gen active)*/ 938 if (0 == srv->srvconf.max_worker) { 939 buffer * const tb = srv->tmp_buf; 940 buffer_clear(tb); 941 buffer_append_int(tb, pid); 942 setenv("LIGHTTPD_PREV_GEN", tb->ptr, 1); 943 } 944 /*fdevent_waitpid(pid, NULL, 0);*//* detach? */ 945 execv(argv[0], argv); 946 _exit(1); 947 } 948 /* else child/grandchild */ 949 950 /*if (-1 == setsid()) _exit(1);*//* should we detach? */ 951 /* Note: restarted server will fail with socket-in-use error if 952 * server.systemd-socket-activation not enabled in restarted server */ 953 if (0 != srv->srvconf.max_worker) 954 server_sockets_close(srv);/*(close before parent reaps pid in waitpid)*/ 955 /*if (0 != fork()) _exit(0);*//* should we detach? */ 956 /*(grandchild is now backgrounded and detached from original process)*/ 957 958 /* XXX: might extend code to have new server.feature-flags param specify 959 * max lifetime before aborting remaining connections */ 960 961 /* (reached if lighttpd workers or if sole process w/o workers) 962 * use same code as comment elsewhere in server.c: 963 * make sure workers do not muck with pid-file */ 964 if (0 <= pid_fd) { 965 close(pid_fd); 966 pid_fd = -1; 967 } 968 srv->srvconf.pid_file = NULL; 969 970 /* (original process is backgrounded -- even if no active connections -- 971 * to allow graceful shutdown tasks to be run by server and by modules) */ 972 log_error(srv->errh, __FILE__, __LINE__, 973 "[note] pid %lld continuing to handle %u connection(s) in progress", 974 (long long)getpid(), srv->srvconf.max_conns - srv->lim_conns); 975 976 if (0 == srv->srvconf.max_worker) { 977 /* reset graceful_shutdown; wait for signal from restarted server */ 978 srv->graceful_expire_ts = 0; 979 graceful_shutdown = 0; 980 } 981 graceful_restart = 0; 982 return 1; 983 } 984 985 __attribute_cold__ 986 __attribute_noinline__ 987 static void server_graceful_shutdown_maint (server *srv) { 988 if (oneshot_fd) { 989 /* permit keep-alive on one-shot connections until graceful_expire_ts */ 990 if (!srv->graceful_expire_ts) return; 991 if (srv->graceful_expire_ts >= log_monotonic_secs) return; 992 } 993 connection_graceful_shutdown_maint(srv); 994 } 995 996 __attribute_cold__ 997 __attribute_noinline__ 998 static void server_graceful_state (server *srv) { 999 1000 if (!srv_shutdown) { 1001 if (0 == srv->graceful_expire_ts) { 1002 srv->graceful_expire_ts = 1003 config_feature_int(srv, "server.graceful-shutdown-timeout", 0); 1004 if (srv->graceful_expire_ts) 1005 srv->graceful_expire_ts += log_monotonic_secs; 1006 } 1007 server_graceful_shutdown_maint(srv); 1008 } 1009 1010 if (2 == srv->sockets_disabled || 3 == srv->sockets_disabled) { 1011 if (oneshot_fd) graceful_restart = 0; 1012 return; 1013 } 1014 1015 log_error(srv->errh,__FILE__,__LINE__,"[note] graceful shutdown started"); 1016 1017 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */ 1018 if (srv->srvconf.changeroot || oneshot_fd || 2 == graceful_shutdown) 1019 graceful_restart = 0; 1020 1021 if (graceful_restart) { 1022 if (!server_graceful_state_bg(srv)) 1023 server_sockets_unregister(srv); 1024 if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/ 1025 } 1026 else { 1027 server_sockets_close(srv); 1028 remove_pid_file(srv); 1029 /*(prevent more removal attempts)*/ 1030 srv->srvconf.pid_file = NULL; 1031 } 1032 } 1033 1034 __attribute_cold__ 1035 __attribute_noinline__ 1036 static void server_sockets_enable (server *srv) { 1037 server_sockets_set_event(srv, FDEVENT_IN); 1038 srv->sockets_disabled = 0; 1039 log_error(srv->errh, __FILE__, __LINE__, "[note] sockets enabled again"); 1040 } 1041 1042 __attribute_cold__ 1043 __attribute_noinline__ 1044 static void server_sockets_disable (server *srv) { 1045 server_sockets_set_event(srv, 0); 1046 srv->sockets_disabled = 1; 1047 log_error(srv->errh, __FILE__, __LINE__, 1048 (0 == srv->lim_conns) 1049 ? "[note] sockets disabled, connection limit reached" 1050 : "[note] sockets disabled, out-of-fds"); 1051 } 1052 1053 __attribute_cold__ 1054 static void server_overload_check (server *srv) { 1055 if (srv->cur_fds < srv->max_fds_lowat && 0 != srv->lim_conns) 1056 server_sockets_enable(srv); 1057 } 1058 1059 static void server_load_check (server *srv) { 1060 /* check if hit limits for num fds used or num connections */ 1061 if (srv->cur_fds > srv->max_fds_hiwat || 0 == srv->lim_conns) 1062 server_sockets_disable(srv); 1063 } 1064 1065 __attribute_cold__ 1066 __attribute_noinline__ 1067 static int server_main_setup (server * const srv, int argc, char **argv) { 1068 int print_config = 0; 1069 int test_config = 0; 1070 int i_am_root = 0; 1071 int o; 1072 #ifdef HAVE_FORK 1073 int num_childs = 0; 1074 #endif 1075 uint32_t i; 1076 #ifdef HAVE_SIGACTION 1077 struct sigaction act; 1078 #endif 1079 1080 #ifdef HAVE_FORK 1081 int parent_pipe_fd = -1; 1082 #endif 1083 1084 #ifdef HAVE_GETUID 1085 i_am_root = (0 == getuid()); 1086 #endif 1087 1088 /* initialize globals (including file-scoped static globals) */ 1089 oneshot_fd = 0; 1090 oneshot_fdout = -1; 1091 srv_shutdown = 0; 1092 graceful_shutdown = 0; 1093 handle_sig_alarm = 1; 1094 handle_sig_hup = 0; 1095 idle_limit = 0; 1096 chunkqueue_set_tempdirs_default_reset(); 1097 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/ 1098 /*(intentionally preserved)*/ 1099 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/ 1100 /*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/ 1101 /*pid_fd = -1;*/ 1102 srv->argv = argv; 1103 1104 while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) { 1105 switch(o) { 1106 case 'f': 1107 if (srv->config_data_base) { 1108 log_error(srv->errh, __FILE__, __LINE__, 1109 "Can only read one config file. Use the include command to use multiple config files."); 1110 return -1; 1111 } 1112 if (config_read(srv, optarg)) { 1113 return -1; 1114 } 1115 break; 1116 case 'm': 1117 buffer_copy_string(srv->srvconf.modules_dir, optarg); 1118 break; 1119 case 'i': { 1120 char *endptr; 1121 long timeout = strtol(optarg, &endptr, 0); 1122 if (!*optarg || *endptr || timeout < 0) { 1123 log_error(srv->errh, __FILE__, __LINE__, 1124 "Invalid idle timeout value: %s", optarg); 1125 return -1; 1126 } 1127 idle_limit = (int)timeout; 1128 break; 1129 } 1130 case 'p': print_config = 1; break; 1131 case 't': ++test_config; break; 1132 case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO); 1133 break; 1134 case 'D': srv->srvconf.dont_daemonize = 1; break; 1135 case 'v': show_version(); return 0; 1136 case 'V': show_features(); return 0; 1137 case 'h': show_help(); return 0; 1138 default: 1139 show_help(); 1140 return -1; 1141 } 1142 } 1143 1144 #ifdef __CYGWIN__ 1145 if (!srv->config_data_base && NULL != getenv("NSSM_SERVICE_NAME")) { 1146 char *dir = getenv("NSSM_SERVICE_DIR"); 1147 if (NULL != dir && 0 != chdir(dir)) { 1148 log_perror(srv->errh, __FILE__, __LINE__, "chdir %s failed", dir); 1149 return -1; 1150 } 1151 srv->srvconf.dont_daemonize = 1; 1152 buffer_copy_string_len(srv->srvconf.modules_dir, CONST_STR_LEN("modules")); 1153 if (config_read(srv, "conf/lighttpd.conf")) return -1; 1154 } 1155 #endif 1156 1157 if (!srv->config_data_base) { 1158 log_error(srv->errh, __FILE__, __LINE__, 1159 "No configuration available. Try using -f option."); 1160 return -1; 1161 } 1162 1163 if (print_config) { 1164 config_print(srv); 1165 puts(srv->tmp_buf->ptr); 1166 } 1167 1168 if (test_config) { 1169 srv->srvconf.pid_file = NULL; 1170 if (1 == test_config) { 1171 printf("Syntax OK\n"); 1172 } else { /*(test_config > 1)*/ 1173 test_config = 0; 1174 srv->srvconf.preflight_check = 1; 1175 srv->srvconf.dont_daemonize = 1; 1176 } 1177 } 1178 1179 if (test_config || print_config) { 1180 return 0; 1181 } 1182 1183 if (oneshot_fd) { 1184 if (oneshot_fd <= STDERR_FILENO) { 1185 log_error(srv->errh, __FILE__, __LINE__, 1186 "Invalid fds at startup with lighttpd -1"); 1187 return -1; 1188 } 1189 graceful_shutdown = 1; 1190 srv->sockets_disabled = 2; 1191 srv->srvconf.dont_daemonize = 1; 1192 srv->srvconf.pid_file = NULL; 1193 if (srv->srvconf.max_worker) { 1194 srv->srvconf.max_worker = 0; 1195 log_error(srv->errh, __FILE__, __LINE__, 1196 "server one-shot command line option disables server.max-worker config file option."); 1197 } 1198 1199 struct stat st; 1200 if (0 != fstat(oneshot_fd, &st)) { 1201 log_perror(srv->errh, __FILE__, __LINE__, "fstat()"); 1202 return -1; 1203 } 1204 1205 if (S_ISFIFO(st.st_mode)) { 1206 oneshot_fdout = dup(STDOUT_FILENO); 1207 if (oneshot_fdout <= STDERR_FILENO) { 1208 log_perror(srv->errh, __FILE__, __LINE__, "dup()"); 1209 return -1; 1210 } 1211 } 1212 else if (!S_ISSOCK(st.st_mode)) { 1213 /* require that fd is a socket 1214 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */ 1215 log_error(srv->errh, __FILE__, __LINE__, 1216 "lighttpd -1 stdin is not a socket"); 1217 return -1; 1218 } 1219 } 1220 1221 if (srv->srvconf.bindhost && buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) { 1222 if (-1 == srv->stdin_fd) 1223 srv->stdin_fd = dup(STDIN_FILENO); 1224 if (srv->stdin_fd <= STDERR_FILENO) { 1225 log_error(srv->errh, __FILE__, __LINE__, 1226 "Invalid fds at startup"); 1227 return -1; 1228 } 1229 } 1230 1231 /* close stdin and stdout, as they are not needed */ 1232 { 1233 struct stat st; 1234 int devnull; 1235 int errfd; 1236 do { 1237 /* coverity[overwrite_var : FALSE] */ 1238 devnull = fdevent_open_devnull(); 1239 #ifdef __COVERITY__ 1240 __coverity_escape__(devnull); 1241 #endif 1242 } while (-1 != devnull && devnull <= STDERR_FILENO); 1243 if (-1 == devnull) { 1244 log_perror(srv->errh, __FILE__, __LINE__, 1245 "opening /dev/null failed"); 1246 return -1; 1247 } 1248 errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull; 1249 if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) { 1250 log_perror(srv->errh, __FILE__, __LINE__, 1251 "setting default fds failed"); 1252 #ifdef FD_CLOEXEC 1253 if (-1 != errfd) close(errfd); 1254 if (devnull != errfd) close(devnull); 1255 #endif 1256 return -1; 1257 } 1258 #ifdef FD_CLOEXEC 1259 if (-1 != errfd) close(errfd); 1260 if (devnull != errfd) close(devnull); 1261 #endif 1262 } 1263 1264 http_response_send_1xx_cb_set(NULL, HTTP_VERSION_2); 1265 if (!config_feature_bool(srv, "server.h2-discard-backend-1xx", 0)) 1266 http_response_send_1xx_cb_set(h2_send_1xx, HTTP_VERSION_2); 1267 1268 http_response_send_1xx_cb_set(NULL, HTTP_VERSION_1_1); 1269 if (!config_feature_bool(srv, "server.h1-discard-backend-1xx", 0)) 1270 http_response_send_1xx_cb_set(connection_send_1xx, HTTP_VERSION_1_1); 1271 1272 if (0 != config_set_defaults(srv)) { 1273 log_error(srv->errh, __FILE__, __LINE__, 1274 "setting default values failed"); 1275 return -1; 1276 } 1277 1278 if (plugins_load(srv)) { 1279 log_error(srv->errh, __FILE__, __LINE__, 1280 "loading plugins finally failed"); 1281 return -1; 1282 } 1283 1284 if (HANDLER_GO_ON != plugins_call_init(srv)) { 1285 log_error(srv->errh, __FILE__, __LINE__, 1286 "Initialization of plugins failed. Going down."); 1287 return -1; 1288 } 1289 1290 /* mod_indexfile should be listed in server.modules prior to dynamic handlers */ 1291 i = 0; 1292 for (const char *pname = NULL; i < srv->plugins.used; ++i) { 1293 plugin *p = ((plugin **)srv->plugins.ptr)[i]; 1294 if (NULL != pname && 0 == strcmp(p->name, "indexfile")) { 1295 log_error(srv->errh, __FILE__, __LINE__, 1296 "Warning: mod_indexfile should be listed in server.modules prior to mod_%s", pname); 1297 break; 1298 } 1299 if (p->handle_subrequest_start && p->handle_subrequest) { 1300 if (!pname) pname = p->name; 1301 } 1302 } 1303 1304 /* open pid file BEFORE chroot */ 1305 if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/ 1306 if (-1 == pid_fd && srv->srvconf.pid_file) { 1307 const char *pidfile = srv->srvconf.pid_file->ptr; 1308 if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) { 1309 struct stat st; 1310 if (errno != EEXIST) { 1311 log_perror(srv->errh, __FILE__, __LINE__, 1312 "opening pid-file failed: %s", pidfile); 1313 return -1; 1314 } 1315 1316 if (0 != stat(pidfile, &st)) { 1317 log_perror(srv->errh, __FILE__, __LINE__, 1318 "stating existing pid-file failed: %s", pidfile); 1319 } 1320 1321 if (!S_ISREG(st.st_mode)) { 1322 log_error(srv->errh, __FILE__, __LINE__, 1323 "pid-file exists and isn't regular file: %s", pidfile); 1324 return -1; 1325 } 1326 1327 if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) { 1328 log_perror(srv->errh, __FILE__, __LINE__, 1329 "opening pid-file failed: %s", pidfile); 1330 return -1; 1331 } 1332 } 1333 } 1334 1335 { 1336 #ifdef HAVE_GETRLIMIT 1337 struct rlimit rlim = { 4096, 4096 }; 1338 int use_rlimit = 1; 1339 #ifdef HAVE_VALGRIND_VALGRIND_H 1340 if (RUNNING_ON_VALGRIND) use_rlimit = 0; 1341 #endif 1342 1343 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) { 1344 log_perror(srv->errh, __FILE__, __LINE__, "getrlimit()"); 1345 use_rlimit = 0; 1346 } 1347 1348 /** 1349 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it 1350 */ 1351 if (use_rlimit && srv->srvconf.max_fds 1352 && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) { 1353 /* set rlimits */ 1354 1355 rlim.rlim_cur = srv->srvconf.max_fds; 1356 if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds; 1357 1358 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) { 1359 log_perror(srv->errh, __FILE__, __LINE__, "setrlimit()"); 1360 log_error(srv->errh, __FILE__, __LINE__, "setrlimit() may need root to run once: setsebool -P httpd_setrlimit on"); 1361 use_rlimit = 0; 1362 } 1363 } 1364 1365 /*(default upper limit of 4k if server.max-fds not specified)*/ 1366 if (0 == srv->srvconf.max_fds) 1367 srv->srvconf.max_fds = (rlim.rlim_cur <= 4096) 1368 ? (unsigned short)rlim.rlim_cur 1369 : 4096; 1370 1371 /* set core file rlimit, if enable_cores is set */ 1372 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) { 1373 rlim.rlim_cur = rlim.rlim_max; 1374 setrlimit(RLIMIT_CORE, &rlim); 1375 } 1376 #endif 1377 } 1378 1379 /* we need root-perms for port < 1024 */ 1380 if (0 != network_init(srv, srv->stdin_fd)) { 1381 return -1; 1382 } 1383 srv->stdin_fd = -1; 1384 1385 if (i_am_root) { 1386 #ifdef HAVE_PWD_H 1387 /* set user and group */ 1388 struct group *grp = NULL; 1389 struct passwd *pwd = NULL; 1390 1391 if (srv->srvconf.groupname) { 1392 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) { 1393 log_error(srv->errh, __FILE__, __LINE__, 1394 "can't find groupname %s", srv->srvconf.groupname->ptr); 1395 return -1; 1396 } 1397 } 1398 1399 if (srv->srvconf.username) { 1400 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) { 1401 log_error(srv->errh, __FILE__, __LINE__, 1402 "can't find username %s", srv->srvconf.username->ptr); 1403 return -1; 1404 } 1405 1406 if (pwd->pw_uid == 0) { 1407 log_error(srv->errh, __FILE__, __LINE__, 1408 "I will not set uid to 0\n"); 1409 return -1; 1410 } 1411 1412 if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) { 1413 log_error(srv->errh, __FILE__, __LINE__, 1414 "can't find group id %d", (int)pwd->pw_gid); 1415 return -1; 1416 } 1417 } 1418 1419 if (NULL != grp) { 1420 if (grp->gr_gid == 0) { 1421 log_error(srv->errh, __FILE__, __LINE__, 1422 "I will not set gid to 0\n"); 1423 return -1; 1424 } 1425 } 1426 1427 /* 1428 * Change group before chroot, when we have access 1429 * to /etc/group 1430 * */ 1431 if (NULL != grp) { 1432 if (-1 == setgid(grp->gr_gid)) { 1433 log_perror(srv->errh, __FILE__, __LINE__, "setgid()"); 1434 return -1; 1435 } 1436 if (-1 == setgroups(0, NULL)) { 1437 log_perror(srv->errh, __FILE__, __LINE__, "setgroups()"); 1438 return -1; 1439 } 1440 if (srv->srvconf.username) { 1441 initgroups(srv->srvconf.username->ptr, grp->gr_gid); 1442 } 1443 } 1444 #endif 1445 #ifdef HAVE_CHROOT 1446 if (srv->srvconf.changeroot) { 1447 tzset(); 1448 1449 if (-1 == chroot(srv->srvconf.changeroot->ptr)) { 1450 log_perror(srv->errh, __FILE__, __LINE__, "chroot()"); 1451 return -1; 1452 } 1453 if (-1 == chdir("/")) { 1454 log_perror(srv->errh, __FILE__, __LINE__, "chdir()"); 1455 return -1; 1456 } 1457 } 1458 #endif 1459 #ifdef HAVE_PWD_H 1460 /* drop root privs */ 1461 if (NULL != pwd) { 1462 if (-1 == setuid(pwd->pw_uid)) { 1463 log_perror(srv->errh, __FILE__, __LINE__, "setuid()"); 1464 return -1; 1465 } 1466 } 1467 #endif 1468 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE) 1469 /** 1470 * on IRIX 6.5.30 they have prctl() but no DUMPABLE 1471 */ 1472 if (srv->srvconf.enable_cores) { 1473 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); 1474 } 1475 #endif 1476 } 1477 1478 #ifdef HAVE_FORK 1479 /* network is up, let's daemonize ourself */ 1480 if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) { 1481 parent_pipe_fd = daemonize(); 1482 } 1483 #endif 1484 graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/ 1485 if (0 == oneshot_fd) graceful_shutdown = 0; 1486 1487 1488 #ifdef HAVE_SIGACTION 1489 memset(&act, 0, sizeof(act)); 1490 act.sa_handler = SIG_IGN; 1491 sigaction(SIGPIPE, &act, NULL); 1492 # if defined(SA_SIGINFO) 1493 last_sighup_info.si_uid = 0, 1494 last_sighup_info.si_pid = 0; 1495 last_sigterm_info.si_uid = 0, 1496 last_sigterm_info.si_pid = 0; 1497 act.sa_sigaction = sigaction_handler; 1498 sigemptyset(&act.sa_mask); 1499 act.sa_flags = SA_SIGINFO; 1500 # else 1501 act.sa_handler = signal_handler; 1502 sigemptyset(&act.sa_mask); 1503 act.sa_flags = 0; 1504 # endif 1505 sigaction(SIGINT, &act, NULL); 1506 sigaction(SIGTERM, &act, NULL); 1507 sigaction(SIGHUP, &act, NULL); 1508 sigaction(SIGALRM, &act, NULL); 1509 sigaction(SIGUSR1, &act, NULL); 1510 1511 /* it should be safe to restart syscalls after SIGCHLD */ 1512 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP; 1513 sigaction(SIGCHLD, &act, NULL); 1514 1515 #elif defined(HAVE_SIGNAL) 1516 /* ignore the SIGPIPE from sendfile() */ 1517 signal(SIGPIPE, SIG_IGN); 1518 signal(SIGALRM, signal_handler); 1519 signal(SIGTERM, signal_handler); 1520 signal(SIGHUP, signal_handler); 1521 signal(SIGCHLD, signal_handler); 1522 signal(SIGINT, signal_handler); 1523 signal(SIGUSR1, signal_handler); 1524 #endif 1525 1526 1527 srv->gid = getgid(); 1528 srv->uid = getuid(); 1529 srv->pid = getpid(); 1530 1531 /* write pid file */ 1532 if (pid_fd > 2) { 1533 buffer * const tb = srv->tmp_buf; 1534 buffer_clear(tb); 1535 buffer_append_int(tb, srv->pid); 1536 buffer_append_string_len(tb, CONST_STR_LEN("\n")); 1537 if (-1 == write_all(pid_fd, BUF_PTR_LEN(tb))) { 1538 log_perror(srv->errh, __FILE__, __LINE__, "Couldn't write pid file"); 1539 close(pid_fd); 1540 pid_fd = -1; 1541 return -1; 1542 } 1543 } else if (pid_fd < -2) { 1544 pid_fd = -pid_fd; 1545 } 1546 1547 /* Close stderr ASAP in the child process to make sure that nothing 1548 * is being written to that fd which may not be valid anymore. */ 1549 if (!srv->srvconf.preflight_check) { 1550 if (-1 == config_log_error_open(srv)) { 1551 log_error(srv->errh, __FILE__, __LINE__, "Opening errorlog failed. Going down."); 1552 return -1; 1553 } 1554 if (!oneshot_fd) 1555 log_error(srv->errh, __FILE__, __LINE__, "server started (" PACKAGE_DESC ")"); 1556 } 1557 1558 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) { 1559 log_error(srv->errh, __FILE__, __LINE__, "Configuration of plugins failed. Going down."); 1560 return -1; 1561 } 1562 1563 if (!config_finalize(srv, &default_server_tag)) { 1564 return -1; 1565 } 1566 1567 if (srv->srvconf.preflight_check) { 1568 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/ 1569 return 0; 1570 } 1571 1572 1573 #ifdef HAVE_FORK 1574 /** 1575 * notify daemonize-grandparent of successful startup 1576 * do this before any further forking is done (workers) 1577 */ 1578 if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) { 1579 if (0 > write(parent_pipe_fd, "", 1)) return -1; 1580 close(parent_pipe_fd); 1581 } 1582 1583 if (idle_limit && srv->srvconf.max_worker) { 1584 srv->srvconf.max_worker = 0; 1585 log_error(srv->errh, __FILE__, __LINE__, 1586 "server idle time limit command line option disables server.max-worker config file option."); 1587 } 1588 1589 /* start watcher and workers */ 1590 num_childs = srv->srvconf.max_worker; 1591 if (num_childs > 0) { 1592 pid_t pids[num_childs]; 1593 pid_t pid; 1594 const int npids = num_childs; 1595 int child = 0; 1596 unsigned int timer = 0; 1597 for (int n = 0; n < npids; ++n) pids[n] = -1; 1598 server_graceful_signal_prev_generation(); 1599 while (!child && !srv_shutdown && !graceful_shutdown) { 1600 if (num_childs > 0) { 1601 switch ((pid = fork())) { 1602 case -1: 1603 return -1; 1604 case 0: 1605 child = 1; 1606 alarm(0); 1607 break; 1608 default: 1609 num_childs--; 1610 for (int n = 0; n < npids; ++n) { 1611 if (-1 == pids[n]) { 1612 pids[n] = pid; 1613 break; 1614 } 1615 } 1616 break; 1617 } 1618 } else { 1619 int status; 1620 unix_time64_t mono_ts; 1621 1622 if (-1 != (pid = fdevent_waitpid_intr(-1, &status))) { 1623 mono_ts = log_monotonic_secs; 1624 log_monotonic_secs = server_monotonic_secs(); 1625 log_epoch_secs = server_epoch_secs(srv, log_monotonic_secs - mono_ts); 1626 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) { 1627 if (!timer) alarm((timer = 5)); 1628 continue; 1629 } 1630 switch (fdlog_pipes_waitpid_cb(pid)) { 1631 default: break; 1632 case -1: if (!timer) alarm((timer = 5)); 1633 __attribute_fallthrough__ 1634 case 1: continue; 1635 } 1636 /** 1637 * check if one of our workers went away 1638 */ 1639 for (int n = 0; n < npids; ++n) { 1640 if (pid == pids[n]) { 1641 pids[n] = -1; 1642 num_childs++; 1643 break; 1644 } 1645 } 1646 } else { 1647 switch (errno) { 1648 case EINTR: 1649 mono_ts = log_monotonic_secs; 1650 log_monotonic_secs = server_monotonic_secs(); 1651 log_epoch_secs = server_epoch_secs(srv, log_monotonic_secs - mono_ts); 1652 /** 1653 * if we receive a SIGHUP we have to close our logs ourself as we don't 1654 * have the mainloop who can help us here 1655 */ 1656 if (handle_sig_hup) { 1657 handle_sig_hup = 0; 1658 fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */ 1659 1660 /* forward SIGHUP to workers */ 1661 for (int n = 0; n < npids; ++n) { 1662 if (pids[n] > 0) kill(pids[n], SIGHUP); 1663 } 1664 } 1665 if (handle_sig_alarm) { 1666 handle_sig_alarm = 0; 1667 timer = 0; 1668 plugins_call_handle_trigger(srv); 1669 fdlog_pipes_restart(log_monotonic_secs); 1670 } 1671 break; 1672 default: 1673 break; 1674 } 1675 } 1676 } 1677 } 1678 1679 /** 1680 * for the parent this is the exit-point 1681 */ 1682 if (!child) { 1683 /** 1684 * kill all children too 1685 */ 1686 if (graceful_shutdown || graceful_restart) { 1687 /* flag to ignore one SIGINT if graceful_restart */ 1688 if (graceful_restart) graceful_restart = 2; 1689 kill(0, SIGINT); 1690 server_graceful_state(srv); 1691 } else if (srv_shutdown) { 1692 kill(0, SIGTERM); 1693 } 1694 1695 return 0; 1696 } 1697 1698 /* ignore SIGUSR1 in workers; only parent directs graceful restart */ 1699 #ifdef HAVE_SIGACTION 1700 { 1701 struct sigaction actignore; 1702 memset(&actignore, 0, sizeof(actignore)); 1703 actignore.sa_handler = SIG_IGN; 1704 sigaction(SIGUSR1, &actignore, NULL); 1705 } 1706 #elif defined(HAVE_SIGNAL) 1707 signal(SIGUSR1, SIG_IGN); 1708 #endif 1709 1710 /** 1711 * make sure workers do not muck with pid-file 1712 */ 1713 if (0 <= pid_fd) { 1714 close(pid_fd); 1715 pid_fd = -1; 1716 } 1717 srv->srvconf.pid_file = NULL; 1718 1719 fdlog_pipes_abandon_pids(); 1720 srv->pid = getpid(); 1721 li_rand_reseed(); 1722 } 1723 #endif 1724 1725 srv->max_fds = (int)srv->srvconf.max_fds; 1726 if (srv->max_fds < 32) /*(sanity check; not expected)*/ 1727 srv->max_fds = 32; /*(server load checks will fail if too low)*/ 1728 srv->ev = fdevent_init(srv->srvconf.event_handler, &srv->max_fds, &srv->cur_fds, srv->errh); 1729 if (NULL == srv->ev) { 1730 log_error(srv->errh, __FILE__, __LINE__, "fdevent_init failed"); 1731 return -1; 1732 } 1733 1734 srv->max_fds_lowat = srv->max_fds * 8 / 10; 1735 srv->max_fds_hiwat = srv->max_fds * 9 / 10; 1736 1737 /* set max-conns */ 1738 if (srv->srvconf.max_conns > srv->max_fds/2) { 1739 /* we can't have more connections than max-fds/2 */ 1740 log_error(srv->errh, __FILE__, __LINE__, 1741 "can't have more connections than fds/2: %hu %d", 1742 srv->srvconf.max_conns, srv->max_fds); 1743 srv->lim_conns = srv->srvconf.max_conns = srv->max_fds/2; 1744 } else if (srv->srvconf.max_conns) { 1745 /* otherwise respect the wishes of the user */ 1746 srv->lim_conns = srv->srvconf.max_conns; 1747 } else { 1748 /* or use the default: we really don't want to hit max-fds */ 1749 srv->lim_conns = srv->srvconf.max_conns = srv->max_fds/3; 1750 } 1751 1752 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */ 1753 #ifdef HAVE_SIGACTION 1754 sigaction(SIGCHLD, &act, NULL); 1755 #elif defined(HAVE_SIGNAL) 1756 signal(SIGCHLD, signal_handler); 1757 #endif 1758 1759 /* 1760 * kqueue() is called here, select resets its internals, 1761 * all server sockets get their handlers 1762 * 1763 * */ 1764 if (0 != network_register_fdevents(srv)) { 1765 return -1; 1766 } 1767 1768 chunkqueue_internal_pipes(config_feature_bool(srv, "chunkqueue.splice", 1)); 1769 1770 /* might fail if user is using fam (not gamin) and famd isn't running */ 1771 if (!stat_cache_init(srv->ev, srv->errh)) { 1772 log_error(srv->errh, __FILE__, __LINE__, 1773 "stat-cache could not be setup, dying."); 1774 return -1; 1775 } 1776 1777 #ifdef USE_ALARM 1778 { 1779 /* setup periodic timer (1 second) */ 1780 struct itimerval interval; 1781 interval.it_interval.tv_sec = 1; 1782 interval.it_interval.tv_usec = 0; 1783 interval.it_value.tv_sec = 1; 1784 interval.it_value.tv_usec = 0; 1785 if (setitimer(ITIMER_REAL, &interval, NULL)) { 1786 log_perror(srv->errh, __FILE__, __LINE__, "setitimer()"); 1787 return -1; 1788 } 1789 } 1790 #endif 1791 1792 /* get the current number of FDs */ 1793 { 1794 int fd = fdevent_open_devnull(); 1795 if (fd >= 0) { 1796 srv->cur_fds = fd; 1797 close(fd); 1798 } 1799 } 1800 1801 if (0 != server_sockets_set_nb_cloexec(srv)) { 1802 return -1; 1803 } 1804 1805 /* plugin hook for worker_init */ 1806 if (HANDLER_GO_ON != plugins_call_worker_init(srv)) 1807 return -1; 1808 1809 if (oneshot_fdout > 0) { 1810 if (server_oneshot_init_pipe(srv, oneshot_fd, oneshot_fdout)) { 1811 oneshot_fd = -1; 1812 oneshot_fdout = -1; 1813 } 1814 } 1815 else if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) { 1816 oneshot_fd = -1; 1817 } 1818 1819 if (0 == srv->srvconf.max_worker) 1820 server_graceful_signal_prev_generation(); 1821 1822 return 1; 1823 } 1824 1825 __attribute_cold__ 1826 __attribute_noinline__ 1827 static void server_handle_sighup (server * const srv) { 1828 1829 /* cycle logfiles */ 1830 1831 plugins_call_handle_sighup(srv); 1832 fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */ 1833 #ifdef HAVE_SIGACTION 1834 log_error(srv->errh, __FILE__, __LINE__, 1835 "logfiles cycled UID = %d PID = %d", 1836 (int)last_sighup_info.si_uid, 1837 (int)last_sighup_info.si_pid); 1838 #else 1839 log_error(srv->errh, __FILE__, __LINE__, 1840 "logfiles cycled"); 1841 #endif 1842 } 1843 1844 __attribute_noinline__ 1845 static void server_handle_sigalrm (server * const srv, unix_time64_t mono_ts, unix_time64_t last_active_ts) { 1846 1847 plugins_call_handle_trigger(srv); 1848 1849 log_monotonic_secs = mono_ts; 1850 log_epoch_secs = server_epoch_secs(srv, 0); 1851 1852 /* check idle time limit, if enabled */ 1853 if (idle_limit && idle_limit < mono_ts - last_active_ts && !graceful_shutdown) { 1854 log_error(srv->errh, __FILE__, __LINE__, 1855 "[note] idle timeout %ds exceeded, " 1856 "initiating graceful shutdown", (int)idle_limit); 1857 graceful_shutdown = 2; /* value 2 indicates idle timeout */ 1858 if (graceful_restart) { 1859 graceful_restart = 0; 1860 if (pid_fd < -2) pid_fd = -pid_fd; 1861 server_sockets_close(srv); 1862 } 1863 } 1864 1865 #ifdef HAVE_GETLOADAVG 1866 /* refresh loadavg data every 30 seconds */ 1867 if (srv->loadts + 30 < mono_ts) { 1868 if (-1 != getloadavg(srv->loadavg, 3)) { 1869 srv->loadts = mono_ts; 1870 } 1871 } 1872 #endif 1873 1874 if (0 == (mono_ts & 0x3f)) { /*(once every 64 secs)*/ 1875 /* free logger buffers every 64 secs */ 1876 fdlog_flushall(srv->errh); 1877 /* free excess chunkqueue buffers every 64 secs */ 1878 chunkqueue_chunk_pool_clear(); 1879 /* clear request and connection pools every 64 secs */ 1880 request_pool_free(); 1881 connections_pool_clear(srv); 1882 #if defined(HAVE_MALLOC_TRIM) 1883 if (malloc_trim_fn) malloc_trim_fn(malloc_top_pad); 1884 #endif 1885 /* attempt to restart dead piped loggers every 64 secs */ 1886 if (0 == srv->srvconf.max_worker) 1887 fdlog_pipes_restart(mono_ts); 1888 } 1889 /* cleanup stat-cache */ 1890 stat_cache_trigger_cleanup(); 1891 /* reset global/aggregate rate limit counters */ 1892 config_reset_config_bytes_sec(srv->config_data_base); 1893 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */ 1894 if (graceful_shutdown && !srv_shutdown) 1895 server_graceful_shutdown_maint(srv); 1896 connection_periodic_maint(srv, mono_ts); 1897 } 1898 1899 __attribute_noinline__ 1900 static void server_handle_sigchld (server * const srv) { 1901 pid_t pid; 1902 do { 1903 int status; 1904 pid = fdevent_waitpid(-1, &status, 1); 1905 if (pid > 0) { 1906 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) { 1907 continue; 1908 } 1909 if (0 == srv->srvconf.max_worker) { 1910 /* check piped-loggers and restart, even if shutting down */ 1911 if (fdlog_pipes_waitpid_cb(pid)) { 1912 continue; 1913 } 1914 } 1915 } 1916 } while (pid > 0 || (-1 == pid && errno == EINTR)); 1917 } 1918 1919 __attribute_hot__ 1920 __attribute_nonnull__() 1921 static void server_run_con_queue (connection * const restrict joblist, const connection * const sentinel) { 1922 for (connection *con = joblist, *jqnext; con != sentinel; con = jqnext) { 1923 jqnext = con->jqnext; 1924 con->jqnext = NULL; 1925 connection_state_machine(con); 1926 } 1927 } 1928 1929 __attribute_hot__ 1930 __attribute_noinline__ 1931 static void server_main_loop (server * const srv) { 1932 unix_time64_t last_active_ts = server_monotonic_secs(); 1933 log_epoch_secs = server_epoch_secs(srv, 0); 1934 1935 while (!srv_shutdown) { 1936 1937 if (handle_sig_hup) { 1938 handle_sig_hup = 0; 1939 server_handle_sighup(srv); 1940 } 1941 1942 /*(USE_ALARM not used; fdevent_poll() is effective periodic timer)*/ 1943 #ifdef USE_ALARM 1944 if (handle_sig_alarm) { 1945 handle_sig_alarm = 0; 1946 #endif 1947 unix_time64_t mono_ts = server_monotonic_secs(); 1948 if (mono_ts != log_monotonic_secs) { 1949 server_handle_sigalrm(srv, mono_ts, last_active_ts); 1950 } 1951 #ifdef USE_ALARM 1952 } 1953 #endif 1954 1955 if (handle_sig_child) { 1956 handle_sig_child = 0; 1957 server_handle_sigchld(srv); 1958 } 1959 1960 if (graceful_shutdown) { 1961 server_graceful_state(srv); 1962 if (NULL == srv->conns && graceful_shutdown) { 1963 /* we are in graceful shutdown phase and all connections are closed 1964 * we are ready to terminate without harming anyone */ 1965 srv_shutdown = 1; 1966 break; 1967 } 1968 } else if (srv->sockets_disabled) { 1969 server_overload_check(srv); 1970 } else { 1971 server_load_check(srv); 1972 } 1973 1974 static connection * const sentinel = 1975 (connection *)(uintptr_t)&log_con_jqueue; 1976 connection * const joblist = log_con_jqueue; 1977 log_con_jqueue = sentinel; 1978 server_run_con_queue(joblist, sentinel); 1979 1980 if (fdevent_poll(srv->ev, log_con_jqueue != sentinel ? 0 : 1000) > 0) 1981 last_active_ts = log_monotonic_secs; 1982 } 1983 } 1984 1985 __attribute_cold__ 1986 __attribute_noinline__ 1987 static int main_init_once (void) { 1988 #ifdef HAVE_GETUID 1989 #ifndef HAVE_ISSETUGID 1990 #define issetugid() (geteuid() != getuid() || getegid() != getgid()) 1991 #endif 1992 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/ 1993 fprintf(stderr, 1994 "Are you nuts ? Don't apply a SUID bit to this binary\n"); 1995 return 0; 1996 } 1997 #endif 1998 1999 #if defined(HAVE_MALLOPT) && defined(M_ARENA_MAX) 2000 #ifdef LIGHTTPD_STATIC 2001 mallopt(M_ARENA_MAX, 2); /*(ignore error, if any)*/ 2002 #else 2003 { 2004 int (*mallopt_fn)(int, int); 2005 mallopt_fn = (int (*)(int, int))(intptr_t)dlsym(RTLD_DEFAULT,"mallopt"); 2006 if (mallopt_fn) mallopt_fn(M_ARENA_MAX, 2); /*(ignore error, if any)*/ 2007 } 2008 #endif 2009 #endif 2010 2011 #if defined(HAVE_MALLOC_TRIM) 2012 malloc_top_pad = 524288; 2013 { 2014 const char * const top_pad_str = getenv("MALLOC_TOP_PAD_"); 2015 if (top_pad_str) { 2016 unsigned long top_pad = strtoul(top_pad_str, NULL, 10); 2017 if (top_pad != ULONG_MAX) malloc_top_pad = (size_t)top_pad; 2018 } 2019 } 2020 #ifdef LIGHTTPD_STATIC 2021 malloc_trim_fn = malloc_trim; 2022 #else 2023 malloc_trim_fn = 2024 (int (*)(size_t))(intptr_t)dlsym(RTLD_DEFAULT,"malloc_trim"); 2025 #endif 2026 #endif 2027 2028 /* for nice %b handling in strftime() */ 2029 setlocale(LC_TIME, "C"); 2030 tzset(); 2031 2032 return 1; 2033 } 2034 2035 __attribute_cold__ 2036 int main (int argc, char ** argv) { 2037 if (!main_init_once()) return -1; 2038 2039 int rc; 2040 2041 do { 2042 server * const srv = server_init(); 2043 2044 if (graceful_restart) { 2045 server_sockets_restore(srv); 2046 optind = 1; 2047 } 2048 2049 rc = server_main_setup(srv, argc, argv); 2050 if (rc > 0) { 2051 2052 server_main_loop(srv); 2053 2054 if (graceful_shutdown || graceful_restart) { 2055 server_graceful_state(srv); 2056 } 2057 2058 if (NULL == srv->conns) rc = 0; 2059 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */ 2060 log_error(srv->errh, __FILE__, __LINE__, 2061 "server stopped after idle timeout"); 2062 } else if (!oneshot_fd) { 2063 #ifdef HAVE_SIGACTION 2064 log_error(srv->errh, __FILE__, __LINE__, 2065 "server stopped by UID = %d PID = %d", 2066 (int)last_sigterm_info.si_uid, 2067 (int)last_sigterm_info.si_pid); 2068 #else 2069 log_error(srv->errh, __FILE__, __LINE__, 2070 "server stopped"); 2071 #endif 2072 } 2073 } 2074 2075 /* clean-up */ 2076 chunkqueue_internal_pipes(0); 2077 remove_pid_file(srv); 2078 config_log_error_close(srv); 2079 if (graceful_restart) 2080 server_sockets_save(srv); 2081 else 2082 network_close(srv); 2083 request_pool_free(); 2084 connections_free(srv); 2085 plugins_free(srv); 2086 server_free(srv); 2087 2088 if (rc < 0 || !graceful_restart) break; 2089 2090 /* wait for all children to exit before graceful restart */ 2091 while (fdevent_waitpid(-1, NULL, 0) > 0) ; 2092 } while (graceful_restart); 2093 2094 return rc; 2095 } 2096