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