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 "http_auth.h" /* http_auth_dumbdata_reset() */ 10 #include "http_vhostdb.h" /* http_vhostdb_dumbdata_reset() */ 11 #include "fdevent.h" 12 #include "connections.h" 13 #include "sock_addr.h" 14 #include "stat_cache.h" 15 #include "plugin.h" 16 #include "network_write.h" /* network_write_show_handlers() */ 17 #include "response.h" /* strftime_cache_reset() */ 18 19 #ifdef HAVE_VERSIONSTAMP_H 20 # include "versionstamp.h" 21 #else 22 # define REPO_VERSION "" 23 #endif 24 25 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION 26 static const buffer default_server_tag = { CONST_STR_LEN(PACKAGE_DESC), 0 }; 27 28 #include <sys/types.h> 29 #include <sys/time.h> 30 #include <sys/stat.h> 31 #include <sys/wait.h> 32 33 #include <string.h> 34 #include <errno.h> 35 #include <fcntl.h> 36 #include <unistd.h> 37 #include <stdlib.h> 38 #include <time.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_SYS_WAIT_H 53 # include <sys/wait.h> 54 #endif 55 56 #ifdef HAVE_PWD_H 57 # include <grp.h> 58 # include <pwd.h> 59 #endif 60 61 #ifdef HAVE_SYS_LOADAVG_H 62 # include <sys/loadavg.h> 63 #endif 64 65 #ifdef HAVE_SYS_RESOURCE_H 66 # include <sys/resource.h> 67 #endif 68 69 #ifdef HAVE_SYS_PRCTL_H 70 # include <sys/prctl.h> 71 #endif 72 73 #include "sys-crypto.h" 74 #ifdef USE_OPENSSL_CRYPTO 75 #define USE_SSL 76 #define TEXT_SSL " (ssl)" 77 #else 78 #define TEXT_SSL 79 #endif 80 81 #ifndef __sgi 82 /* IRIX doesn't like the alarm based time() optimization */ 83 /* #define USE_ALARM */ 84 #endif 85 86 static int oneshot_fd = 0; 87 static volatile int pid_fd = -2; 88 static server_socket_array graceful_sockets; 89 static server_socket_array inherited_sockets; 90 static volatile sig_atomic_t graceful_restart = 0; 91 static volatile sig_atomic_t graceful_shutdown = 0; 92 static volatile sig_atomic_t srv_shutdown = 0; 93 static volatile sig_atomic_t handle_sig_child = 0; 94 static volatile sig_atomic_t handle_sig_alarm = 1; 95 static volatile sig_atomic_t handle_sig_hup = 0; 96 static time_t idle_limit = 0; 97 98 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO) 99 static volatile siginfo_t last_sigterm_info; 100 static volatile siginfo_t last_sighup_info; 101 102 static void sigaction_handler(int sig, siginfo_t *si, void *context) { 103 static const siginfo_t empty_siginfo; 104 UNUSED(context); 105 106 if (!si) *(const siginfo_t **)&si = &empty_siginfo; 107 108 switch (sig) { 109 case SIGTERM: 110 srv_shutdown = 1; 111 last_sigterm_info = *si; 112 break; 113 case SIGUSR1: 114 if (!graceful_shutdown) { 115 graceful_restart = 1; 116 graceful_shutdown = 1; 117 last_sigterm_info = *si; 118 } 119 break; 120 case SIGINT: 121 if (graceful_shutdown) { 122 if (2 == graceful_restart) 123 graceful_restart = 1; 124 else 125 srv_shutdown = 1; 126 } else { 127 graceful_shutdown = 1; 128 } 129 last_sigterm_info = *si; 130 131 break; 132 case SIGALRM: 133 handle_sig_alarm = 1; 134 break; 135 case SIGHUP: 136 handle_sig_hup = 1; 137 last_sighup_info = *si; 138 break; 139 case SIGCHLD: 140 handle_sig_child = 1; 141 break; 142 } 143 } 144 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION) 145 static void signal_handler(int sig) { 146 switch (sig) { 147 case SIGTERM: srv_shutdown = 1; break; 148 case SIGUSR1: 149 if (!graceful_shutdown) { 150 graceful_restart = 1; 151 graceful_shutdown = 1; 152 } 153 break; 154 case SIGINT: 155 if (graceful_shutdown) { 156 if (2 == graceful_restart) 157 graceful_restart = 1; 158 else 159 srv_shutdown = 1; 160 } else { 161 graceful_shutdown = 1; 162 } 163 break; 164 case SIGALRM: handle_sig_alarm = 1; break; 165 case SIGHUP: handle_sig_hup = 1; break; 166 case SIGCHLD: handle_sig_child = 1; break; 167 } 168 } 169 #endif 170 171 #ifdef HAVE_FORK 172 static int daemonize(void) { 173 int pipefd[2]; 174 pid_t pid; 175 #ifdef SIGTTOU 176 signal(SIGTTOU, SIG_IGN); 177 #endif 178 #ifdef SIGTTIN 179 signal(SIGTTIN, SIG_IGN); 180 #endif 181 #ifdef SIGTSTP 182 signal(SIGTSTP, SIG_IGN); 183 #endif 184 185 if (pipe(pipefd) < 0) exit(-1); 186 187 if (0 > (pid = fork())) exit(-1); 188 189 if (0 < pid) { 190 char buf; 191 ssize_t bytes; 192 193 close(pipefd[1]); 194 /* parent waits for grandchild to be ready */ 195 do { 196 bytes = read(pipefd[0], &buf, sizeof(buf)); 197 } while (bytes < 0 && EINTR == errno); 198 close(pipefd[0]); 199 200 if (bytes <= 0) { 201 /* closed fd (without writing) == failure in grandchild */ 202 fputs("daemonized server failed to start; check error log for details\n", stderr); 203 exit(-1); 204 } 205 206 exit(0); 207 } 208 209 close(pipefd[0]); 210 211 if (-1 == setsid()) exit(0); 212 213 signal(SIGHUP, SIG_IGN); 214 215 if (0 != fork()) exit(0); 216 217 if (0 != chdir("/")) exit(0); 218 219 fdevent_setfd_cloexec(pipefd[1]); 220 return pipefd[1]; 221 } 222 #endif 223 224 __attribute_cold__ 225 static server *server_init(void) { 226 server *srv = calloc(1, sizeof(*srv)); 227 force_assert(srv); 228 #define CLEAN(x) \ 229 srv->x = buffer_init(); 230 231 CLEAN(tmp_buf); 232 #undef CLEAN 233 234 strftime_cache_reset(); 235 236 li_rand_reseed(); 237 238 srv->startup_ts = log_epoch_secs = time(NULL); 239 240 srv->errh = log_error_st_init(); 241 242 config_init(srv); 243 244 srv->request_env = plugins_call_handle_request_env; 245 246 srv->loadavg[0] = 0.0; 247 srv->loadavg[1] = 0.0; 248 srv->loadavg[2] = 0.0; 249 250 return srv; 251 } 252 253 __attribute_cold__ 254 static void server_free(server *srv) { 255 if (oneshot_fd > 0) { 256 close(oneshot_fd); 257 } 258 259 #define CLEAN(x) \ 260 buffer_free(srv->x); 261 262 CLEAN(tmp_buf); 263 264 #undef CLEAN 265 266 fdevent_free(srv->ev); 267 268 config_free(srv); 269 270 free(srv->joblist.ptr); 271 free(srv->fdwaitqueue.ptr); 272 273 stat_cache_free(); 274 275 li_rand_cleanup(); 276 chunkqueue_chunk_pool_free(); 277 278 log_error_st_free(srv->errh); 279 free(srv); 280 } 281 282 __attribute_cold__ 283 static void remove_pid_file(server *srv) { 284 if (pid_fd <= -2) return; 285 if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= pid_fd) { 286 if (0 != ftruncate(pid_fd, 0)) { 287 log_perror(srv->errh, __FILE__, __LINE__, 288 "ftruncate failed for: %s", srv->srvconf.pid_file->ptr); 289 } 290 } 291 if (0 <= pid_fd) { 292 close(pid_fd); 293 pid_fd = -1; 294 } 295 if (!buffer_string_is_empty(srv->srvconf.pid_file) && 296 buffer_string_is_empty(srv->srvconf.changeroot)) { 297 if (0 != unlink(srv->srvconf.pid_file->ptr)) { 298 if (errno != EACCES && errno != EPERM) { 299 log_perror(srv->errh, __FILE__, __LINE__, 300 "unlink failed for: %s", srv->srvconf.pid_file->ptr); 301 } 302 } 303 } 304 } 305 306 307 __attribute_cold__ 308 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) { 309 server_socket *srv_socket, *srv_socket_wild = NULL; 310 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 311 srv_socket = srv->srv_sockets.ptr[i]; 312 if (!sock_addr_is_port_eq(&srv_socket->addr,cnt_addr)) continue; 313 if (sock_addr_is_addr_eq(&srv_socket->addr,cnt_addr)) return srv_socket; 314 315 if (NULL != srv_socket_wild) continue; 316 if (sock_addr_is_addr_wildcard(&srv_socket->addr)) { 317 srv_socket_wild = srv_socket; 318 } 319 } 320 321 if (NULL != srv_socket_wild) { 322 return srv_socket_wild; 323 } else if (srv->srv_sockets.used) { 324 return srv->srv_sockets.ptr[0]; 325 } else { 326 log_error(srv->errh, __FILE__, __LINE__, "no sockets configured"); 327 return NULL; 328 } 329 } 330 331 332 __attribute_cold__ 333 static int server_oneshot_init(server *srv, int fd) { 334 /* Note: does not work with netcat due to requirement that fd be socket. 335 * STDOUT_FILENO was not saved earlier in startup, and that is to where 336 * netcat expects output to be sent. Since lighttpd expects connections 337 * to be sockets, con->fd is where output is sent; separate fds are not 338 * stored for input and output, but netcat has different fds for stdin 339 * and * stdout. To support netcat, would additionally need to avoid 340 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing 341 * addresses from environment variables: 342 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT 343 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT 344 * NCAT_PROTO 345 */ 346 connection *con; 347 server_socket *srv_socket; 348 sock_addr cnt_addr; 349 socklen_t cnt_len; 350 struct stat st; 351 352 if (0 != fstat(fd, &st)) { 353 log_perror(srv->errh, __FILE__, __LINE__, "fstat()"); 354 return 0; 355 } 356 357 if (!S_ISSOCK(st.st_mode)) { 358 /* require that fd is a socket 359 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */ 360 log_error(srv->errh, __FILE__, __LINE__, 361 "lighttpd -1 stdin is not a socket"); 362 return 0; 363 } 364 365 cnt_len = sizeof(cnt_addr); 366 if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 367 log_perror(srv->errh, __FILE__, __LINE__, "getsockname()"); 368 return 0; 369 } 370 371 srv_socket = server_oneshot_getsock(srv, &cnt_addr); 372 if (NULL == srv_socket) return 0; 373 374 cnt_len = sizeof(cnt_addr); 375 if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 376 log_perror(srv->errh, __FILE__, __LINE__, "getpeername()"); 377 return 0; 378 } 379 380 /*(must set flags; fd did not pass through fdevent accept() logic)*/ 381 if (-1 == fdevent_fcntl_set_nb_cloexec(fd)) { 382 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 383 return 0; 384 } 385 386 if (sock_addr_get_family(&cnt_addr) != AF_UNIX) { 387 network_accept_tcp_nagle_disable(fd); 388 } 389 390 con = connection_accepted(srv, srv_socket, &cnt_addr, fd); 391 if (NULL == con) return 0; 392 393 connection_state_machine(con); 394 return 1; 395 } 396 397 398 __attribute_cold__ 399 static void show_version (void) { 400 char *b = PACKAGE_DESC TEXT_SSL \ 401 " - a light and fast webserver\n" 402 #ifdef NONREPRODUCIBLE_BUILD 403 "Build-Date: " __DATE__ " " __TIME__ "\n"; 404 #endif 405 ; 406 write_all(STDOUT_FILENO, b, strlen(b)); 407 } 408 409 __attribute_cold__ 410 static void show_features (void) { 411 static const char features[] = 412 "\nFeatures:\n\n" 413 #ifdef HAVE_IPV6 414 "\t+ IPv6 support\n" 415 #else 416 "\t- IPv6 support\n" 417 #endif 418 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ 419 "\t+ zlib support\n" 420 #else 421 "\t- zlib support\n" 422 #endif 423 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2 424 "\t+ bzip2 support\n" 425 #else 426 "\t- bzip2 support\n" 427 #endif 428 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT) 429 "\t+ crypt support\n" 430 #else 431 "\t- crypt support\n" 432 #endif 433 #ifdef USE_SSL 434 "\t+ SSL support\n" 435 #else 436 "\t- SSL support\n" 437 #endif 438 #ifdef HAVE_LIBPCRE 439 "\t+ PCRE support\n" 440 #else 441 "\t- PCRE support\n" 442 #endif 443 #ifdef HAVE_MYSQL 444 "\t+ MySQL support\n" 445 #else 446 "\t- MySQL support\n" 447 #endif 448 #ifdef HAVE_PGSQL 449 "\t+ PgSQL support\n" 450 #else 451 "\t- PgSQL support\n" 452 #endif 453 #ifdef HAVE_DBI 454 "\t+ DBI support\n" 455 #else 456 "\t- DBI support\n" 457 #endif 458 #ifdef HAVE_KRB5 459 "\t+ Kerberos support\n" 460 #else 461 "\t- Kerberos support\n" 462 #endif 463 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER) 464 "\t+ LDAP support\n" 465 #else 466 "\t- LDAP support\n" 467 #endif 468 #ifdef HAVE_PAM 469 "\t+ PAM support\n" 470 #else 471 "\t- PAM support\n" 472 #endif 473 #ifdef USE_MEMCACHED 474 "\t+ memcached support\n" 475 #else 476 "\t- memcached support\n" 477 #endif 478 #ifdef HAVE_FAM_H 479 "\t+ FAM support\n" 480 #else 481 "\t- FAM support\n" 482 #endif 483 #ifdef HAVE_LUA_H 484 "\t+ LUA support\n" 485 #else 486 "\t- LUA support\n" 487 #endif 488 #ifdef HAVE_LIBXML_H 489 "\t+ xml support\n" 490 #else 491 "\t- xml support\n" 492 #endif 493 #ifdef HAVE_SQLITE3_H 494 "\t+ SQLite support\n" 495 #else 496 "\t- SQLite support\n" 497 #endif 498 #ifdef HAVE_GDBM_H 499 "\t+ GDBM support\n" 500 #else 501 "\t- GDBM support\n" 502 #endif 503 ; 504 show_version(); 505 printf("%s%s%s\n", fdevent_show_event_handlers(), network_write_show_handlers(), features); 506 } 507 508 __attribute_cold__ 509 static void show_help (void) { 510 char *b = PACKAGE_DESC TEXT_SSL 511 #ifdef NONREPRODUCIBLE_BUILD 512 " ("__DATE__ " " __TIME__ ")" 513 #endif 514 " - a light and fast webserver\n" \ 515 "usage:\n" \ 516 " -f <name> filename of the config-file\n" \ 517 " -m <name> module directory (default: "LIBRARY_DIR")\n" \ 518 " -i <secs> graceful shutdown after <secs> of inactivity\n" \ 519 " -1 process single (one) request on stdin socket, then exit\n" \ 520 " -p print the parsed config-file in internal form, and exit\n" \ 521 " -t test config-file syntax, then exit\n" \ 522 " -tt test config-file syntax, load and init modules, then exit\n" \ 523 " -D don't go to background (default: go to background)\n" \ 524 " -v show version\n" \ 525 " -V show compile-time features\n" \ 526 " -h show this help\n" \ 527 "\n" 528 ; 529 write_all(STDOUT_FILENO, b, strlen(b)); 530 } 531 532 __attribute_cold__ 533 static void server_sockets_save (server *srv) { /* graceful_restart */ 534 memcpy(&graceful_sockets, &srv->srv_sockets, sizeof(server_socket_array)); 535 memset(&srv->srv_sockets, 0, sizeof(server_socket_array)); 536 memcpy(&inherited_sockets, &srv->srv_sockets_inherited, sizeof(server_socket_array)); 537 memset(&srv->srv_sockets_inherited, 0, sizeof(server_socket_array)); 538 } 539 540 __attribute_cold__ 541 static void server_sockets_restore (server *srv) { /* graceful_restart */ 542 memcpy(&srv->srv_sockets, &graceful_sockets, sizeof(server_socket_array)); 543 memset(&graceful_sockets, 0, sizeof(server_socket_array)); 544 memcpy(&srv->srv_sockets_inherited, &inherited_sockets, sizeof(server_socket_array)); 545 memset(&inherited_sockets, 0, sizeof(server_socket_array)); 546 } 547 548 __attribute_cold__ 549 static int server_sockets_set_nb_cloexec (server *srv) { 550 if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */ 551 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 552 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 553 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv_socket->fd)) { 554 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 555 return -1; 556 } 557 } 558 return 0; 559 } 560 561 __attribute_cold__ 562 static void server_sockets_set_event (server *srv, int event) { 563 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 564 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 565 fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event); 566 } 567 } 568 569 __attribute_cold__ 570 static void server_sockets_unregister (server *srv) { 571 if (2 == srv->sockets_disabled) return; 572 srv->sockets_disabled = 2; 573 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) 574 network_unregister_sock(srv, srv->srv_sockets.ptr[i]); 575 } 576 577 __attribute_cold__ 578 static void server_sockets_close (server *srv) { 579 /* closing socket right away will make it possible for the next lighttpd 580 * to take over (old-style graceful restart), but only if backends 581 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather 582 * than started by lighttpd via "bin-path") 583 */ 584 if (3 == srv->sockets_disabled) return; 585 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 586 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 587 if (-1 == srv_socket->fd) continue; 588 if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket); 589 close(srv_socket->fd); 590 srv_socket->fd = -1; 591 /* network_close() will cleanup after us */ 592 } 593 srv->sockets_disabled = 3; 594 } 595 596 __attribute_cold__ 597 static void server_graceful_state (server *srv) { 598 599 if (!srv_shutdown) connection_graceful_shutdown_maint(srv); 600 601 if (!oneshot_fd 602 && (2 == srv->sockets_disabled || 3 == srv->sockets_disabled)) return; 603 604 log_error(srv->errh,__FILE__,__LINE__,"[note] graceful shutdown started"); 605 606 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */ 607 if (!buffer_string_is_empty(srv->srvconf.changeroot) 608 || oneshot_fd || 2 == graceful_shutdown) 609 graceful_restart = 0; 610 611 if (graceful_restart) { 612 server_sockets_unregister(srv); 613 if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/ 614 } 615 else { 616 server_sockets_close(srv); 617 remove_pid_file(srv); 618 /*(prevent more removal attempts)*/ 619 if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file); 620 } 621 } 622 623 __attribute_cold__ 624 static void server_sockets_enable (server *srv) { 625 server_sockets_set_event(srv, FDEVENT_IN); 626 srv->sockets_disabled = 0; 627 log_error(srv->errh, __FILE__, __LINE__, "[note] sockets enabled again"); 628 } 629 630 __attribute_cold__ 631 static void server_sockets_disable (server *srv) { 632 server_sockets_set_event(srv, 0); 633 srv->sockets_disabled = 1; 634 log_error(srv->errh, __FILE__, __LINE__, 635 (srv->conns.used >= srv->max_conns) 636 ? "[note] sockets disabled, connection limit reached" 637 : "[note] sockets disabled, out-of-fds"); 638 } 639 640 __attribute_cold__ 641 static void server_overload_check (server *srv) { 642 if (srv->cur_fds + (int)srv->fdwaitqueue.used < srv->max_fds_lowat 643 && srv->conns.used < srv->max_conns) { 644 645 server_sockets_enable(srv); 646 } 647 } 648 649 static void server_load_check (server *srv) { 650 /* check if hit limits for num fds used or num connections */ 651 if (srv->cur_fds > srv->max_fds_hiwat || srv->conns.used >= srv->max_conns) 652 server_sockets_disable(srv); 653 } 654 655 __attribute_cold__ 656 __attribute_noinline__ 657 static void server_process_fdwaitqueue (server *srv) { 658 connections * const fdwaitqueue = &srv->fdwaitqueue; 659 uint32_t i = 0; 660 for (int n = srv->max_fds - srv->cur_fds - 16; n > 0; --n) { 661 if (i == fdwaitqueue->used) break; 662 connection_state_machine(fdwaitqueue->ptr[i++]); 663 } 664 if (i > 0 && 0 != (fdwaitqueue->used -= i)) { 665 memmove(fdwaitqueue->ptr, fdwaitqueue->ptr+i, fdwaitqueue->used * sizeof(*(fdwaitqueue->ptr))); 666 } 667 } 668 669 __attribute_cold__ 670 static int server_main_setup (server * const srv, int argc, char **argv) { 671 int print_config = 0; 672 int test_config = 0; 673 int i_am_root = 0; 674 int o; 675 #ifdef HAVE_FORK 676 int num_childs = 0; 677 #endif 678 uint32_t i; 679 #ifdef HAVE_SIGACTION 680 struct sigaction act; 681 #endif 682 683 #ifdef HAVE_FORK 684 int parent_pipe_fd = -1; 685 #endif 686 int stdin_fd = -1; 687 688 #ifdef HAVE_GETUID 689 i_am_root = (0 == getuid()); 690 #endif 691 692 /* initialize globals (including file-scoped static globals) */ 693 oneshot_fd = 0; 694 srv_shutdown = 0; 695 graceful_shutdown = 0; 696 handle_sig_alarm = 1; 697 handle_sig_hup = 0; 698 idle_limit = 0; 699 chunkqueue_set_tempdirs_default_reset(); 700 http_auth_dumbdata_reset(); 701 http_vhostdb_dumbdata_reset(); 702 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/ 703 /*(intentionally preserved)*/ 704 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/ 705 /*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/ 706 /*pid_fd = -1;*/ 707 708 while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) { 709 switch(o) { 710 case 'f': 711 if (srv->config_data_base) { 712 log_error(srv->errh, __FILE__, __LINE__, 713 "Can only read one config file. Use the include command to use multiple config files."); 714 return -1; 715 } 716 if (config_read(srv, optarg)) { 717 return -1; 718 } 719 break; 720 case 'm': 721 buffer_copy_string(srv->srvconf.modules_dir, optarg); 722 break; 723 case 'i': { 724 char *endptr; 725 long timeout = strtol(optarg, &endptr, 0); 726 if (!*optarg || *endptr || timeout < 0) { 727 log_error(srv->errh, __FILE__, __LINE__, 728 "Invalid idle timeout value: %s", optarg); 729 return -1; 730 } 731 idle_limit = (time_t)timeout; 732 break; 733 } 734 case 'p': print_config = 1; break; 735 case 't': ++test_config; break; 736 case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO); 737 break; 738 case 'D': srv->srvconf.dont_daemonize = 1; break; 739 case 'v': show_version(); return 0; 740 case 'V': show_features(); return 0; 741 case 'h': show_help(); return 0; 742 default: 743 show_help(); 744 return -1; 745 } 746 } 747 748 #ifdef __CYGWIN__ 749 if (!srv->config_data_base && NULL != getenv("NSSM_SERVICE_NAME")) { 750 char *dir = getenv("NSSM_SERVICE_DIR"); 751 if (NULL != dir && 0 != chdir(dir)) { 752 log_perror(srv->errh, __FILE__, __LINE__, "chdir %s failed", dir); 753 return -1; 754 } 755 srv->srvconf.dont_daemonize = 1; 756 buffer_copy_string_len(srv->srvconf.modules_dir, CONST_STR_LEN("modules")); 757 if (config_read(srv, "conf/lighttpd.conf")) return -1; 758 } 759 #endif 760 761 if (!srv->config_data_base) { 762 log_error(srv->errh, __FILE__, __LINE__, 763 "No configuration available. Try using -f option."); 764 return -1; 765 } 766 767 if (print_config) { 768 config_print(srv); 769 fprintf(stdout, "\n"); 770 } 771 772 if (test_config) { 773 if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file); 774 if (1 == test_config) { 775 printf("Syntax OK\n"); 776 } else { /*(test_config > 1)*/ 777 test_config = 0; 778 srv->srvconf.preflight_check = 1; 779 srv->srvconf.dont_daemonize = 1; 780 } 781 } 782 783 if (test_config || print_config) { 784 return 0; 785 } 786 787 if (oneshot_fd) { 788 if (oneshot_fd <= STDERR_FILENO) { 789 log_error(srv->errh, __FILE__, __LINE__, 790 "Invalid fds at startup with lighttpd -1"); 791 return -1; 792 } 793 graceful_shutdown = 1; 794 srv->sockets_disabled = 1; 795 srv->srvconf.dont_daemonize = 1; 796 if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file); 797 if (srv->srvconf.max_worker) { 798 srv->srvconf.max_worker = 0; 799 log_error(srv->errh, __FILE__, __LINE__, 800 "server one-shot command line option disables server.max-worker config file option."); 801 } 802 } 803 804 if (srv->srvconf.bindhost && buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) { 805 stdin_fd = dup(STDIN_FILENO); 806 if (stdin_fd <= STDERR_FILENO) { 807 log_error(srv->errh, __FILE__, __LINE__, 808 "Invalid fds at startup"); 809 return -1; 810 } 811 } 812 813 /* close stdin and stdout, as they are not needed */ 814 { 815 struct stat st; 816 int devnull; 817 int errfd; 818 do { 819 /* coverity[overwrite_var : FALSE] */ 820 devnull = fdevent_open_devnull(); 821 #ifdef __COVERITY__ 822 __coverity_escape__(devnull); 823 #endif 824 } while (-1 != devnull && devnull <= STDERR_FILENO); 825 if (-1 == devnull) { 826 log_perror(srv->errh, __FILE__, __LINE__, 827 "opening /dev/null failed"); 828 return -1; 829 } 830 errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull; 831 if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) { 832 log_perror(srv->errh, __FILE__, __LINE__, 833 "setting default fds failed"); 834 #ifdef FD_CLOEXEC 835 if (-1 != errfd) close(errfd); 836 if (devnull != errfd) close(devnull); 837 #endif 838 return -1; 839 } 840 #ifdef FD_CLOEXEC 841 if (-1 != errfd) close(errfd); 842 if (devnull != errfd) close(devnull); 843 #endif 844 } 845 846 if (0 != config_set_defaults(srv)) { 847 log_error(srv->errh, __FILE__, __LINE__, 848 "setting default values failed"); 849 return -1; 850 } 851 852 if (plugins_load(srv)) { 853 log_error(srv->errh, __FILE__, __LINE__, 854 "loading plugins finally failed"); 855 return -1; 856 } 857 858 if (HANDLER_GO_ON != plugins_call_init(srv)) { 859 log_error(srv->errh, __FILE__, __LINE__, 860 "Initialization of plugins failed. Going down."); 861 return -1; 862 } 863 864 /* mod_indexfile should be listed in server.modules prior to dynamic handlers */ 865 i = 0; 866 for (const char *pname = NULL; i < srv->plugins.used; ++i) { 867 plugin *p = ((plugin **)srv->plugins.ptr)[i]; 868 if (NULL != pname && 0 == strcmp(p->name, "indexfile")) { 869 log_error(srv->errh, __FILE__, __LINE__, 870 "Warning: mod_indexfile should be listed in server.modules prior to mod_%s", pname); 871 break; 872 } 873 if (p->handle_subrequest_start && p->handle_subrequest) { 874 if (!pname) pname = p->name; 875 } 876 } 877 878 /* open pid file BEFORE chroot */ 879 if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/ 880 if (-1 == pid_fd && !buffer_string_is_empty(srv->srvconf.pid_file)) { 881 const char *pidfile = srv->srvconf.pid_file->ptr; 882 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))) { 883 struct stat st; 884 if (errno != EEXIST) { 885 log_perror(srv->errh, __FILE__, __LINE__, 886 "opening pid-file failed: %s", pidfile); 887 return -1; 888 } 889 890 if (0 != stat(pidfile, &st)) { 891 log_perror(srv->errh, __FILE__, __LINE__, 892 "stating existing pid-file failed: %s", pidfile); 893 } 894 895 if (!S_ISREG(st.st_mode)) { 896 log_error(srv->errh, __FILE__, __LINE__, 897 "pid-file exists and isn't regular file: %s", pidfile); 898 return -1; 899 } 900 901 if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) { 902 log_perror(srv->errh, __FILE__, __LINE__, 903 "opening pid-file failed: %s", pidfile); 904 return -1; 905 } 906 } 907 } 908 909 { 910 #ifdef HAVE_GETRLIMIT 911 struct rlimit rlim; 912 int use_rlimit = 1; 913 #ifdef HAVE_VALGRIND_VALGRIND_H 914 if (RUNNING_ON_VALGRIND) use_rlimit = 0; 915 #endif 916 917 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) { 918 log_perror(srv->errh, __FILE__, __LINE__, "getrlimit()"); 919 return -1; 920 } 921 922 /** 923 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it 924 */ 925 if (use_rlimit && srv->srvconf.max_fds 926 && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) { 927 /* set rlimits */ 928 929 rlim.rlim_cur = srv->srvconf.max_fds; 930 if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds; 931 932 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) { 933 log_perror(srv->errh, __FILE__, __LINE__, "setrlimit()"); 934 return -1; 935 } 936 } 937 938 /*(default upper limit of 4k if server.max-fds not specified)*/ 939 if (0 == srv->srvconf.max_fds) 940 srv->srvconf.max_fds = (rlim.rlim_cur <= 4096) 941 ? (unsigned short)rlim.rlim_cur 942 : 4096; 943 944 /* set core file rlimit, if enable_cores is set */ 945 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) { 946 rlim.rlim_cur = rlim.rlim_max; 947 setrlimit(RLIMIT_CORE, &rlim); 948 } 949 #endif 950 } 951 952 /* we need root-perms for port < 1024 */ 953 if (0 != network_init(srv, stdin_fd)) { 954 return -1; 955 } 956 957 if (i_am_root) { 958 #ifdef HAVE_PWD_H 959 /* set user and group */ 960 struct group *grp = NULL; 961 struct passwd *pwd = NULL; 962 963 if (!buffer_string_is_empty(srv->srvconf.groupname)) { 964 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) { 965 log_error(srv->errh, __FILE__, __LINE__, 966 "can't find groupname %s", srv->srvconf.groupname->ptr); 967 return -1; 968 } 969 } 970 971 if (!buffer_string_is_empty(srv->srvconf.username)) { 972 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) { 973 log_error(srv->errh, __FILE__, __LINE__, 974 "can't find username %s", srv->srvconf.username->ptr); 975 return -1; 976 } 977 978 if (pwd->pw_uid == 0) { 979 log_error(srv->errh, __FILE__, __LINE__, 980 "I will not set uid to 0\n"); 981 return -1; 982 } 983 984 if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) { 985 log_error(srv->errh, __FILE__, __LINE__, 986 "can't find group id %d", (int)pwd->pw_gid); 987 return -1; 988 } 989 } 990 991 if (NULL != grp) { 992 if (grp->gr_gid == 0) { 993 log_error(srv->errh, __FILE__, __LINE__, 994 "I will not set gid to 0\n"); 995 return -1; 996 } 997 } 998 999 /* 1000 * Change group before chroot, when we have access 1001 * to /etc/group 1002 * */ 1003 if (NULL != grp) { 1004 if (-1 == setgid(grp->gr_gid)) { 1005 log_perror(srv->errh, __FILE__, __LINE__, "setgid()"); 1006 return -1; 1007 } 1008 if (-1 == setgroups(0, NULL)) { 1009 log_perror(srv->errh, __FILE__, __LINE__, "setgroups()"); 1010 return -1; 1011 } 1012 if (!buffer_string_is_empty(srv->srvconf.username)) { 1013 initgroups(srv->srvconf.username->ptr, grp->gr_gid); 1014 } 1015 } 1016 #endif 1017 #ifdef HAVE_CHROOT 1018 if (!buffer_string_is_empty(srv->srvconf.changeroot)) { 1019 tzset(); 1020 1021 if (-1 == chroot(srv->srvconf.changeroot->ptr)) { 1022 log_perror(srv->errh, __FILE__, __LINE__, "chroot()"); 1023 return -1; 1024 } 1025 if (-1 == chdir("/")) { 1026 log_perror(srv->errh, __FILE__, __LINE__, "chdir()"); 1027 return -1; 1028 } 1029 } 1030 #endif 1031 #ifdef HAVE_PWD_H 1032 /* drop root privs */ 1033 if (NULL != pwd) { 1034 if (-1 == setuid(pwd->pw_uid)) { 1035 log_perror(srv->errh, __FILE__, __LINE__, "setuid()"); 1036 return -1; 1037 } 1038 } 1039 #endif 1040 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE) 1041 /** 1042 * on IRIX 6.5.30 they have prctl() but no DUMPABLE 1043 */ 1044 if (srv->srvconf.enable_cores) { 1045 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); 1046 } 1047 #endif 1048 } 1049 1050 #ifdef HAVE_FORK 1051 /* network is up, let's daemonize ourself */ 1052 if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) { 1053 parent_pipe_fd = daemonize(); 1054 } 1055 #endif 1056 graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/ 1057 if (0 == oneshot_fd) graceful_shutdown = 0; 1058 1059 1060 #ifdef HAVE_SIGACTION 1061 memset(&act, 0, sizeof(act)); 1062 act.sa_handler = SIG_IGN; 1063 sigaction(SIGPIPE, &act, NULL); 1064 # if defined(SA_SIGINFO) 1065 last_sighup_info.si_uid = 0, 1066 last_sighup_info.si_pid = 0; 1067 last_sigterm_info.si_uid = 0, 1068 last_sigterm_info.si_pid = 0; 1069 act.sa_sigaction = sigaction_handler; 1070 sigemptyset(&act.sa_mask); 1071 act.sa_flags = SA_SIGINFO; 1072 # else 1073 act.sa_handler = signal_handler; 1074 sigemptyset(&act.sa_mask); 1075 act.sa_flags = 0; 1076 # endif 1077 sigaction(SIGINT, &act, NULL); 1078 sigaction(SIGTERM, &act, NULL); 1079 sigaction(SIGHUP, &act, NULL); 1080 sigaction(SIGALRM, &act, NULL); 1081 sigaction(SIGUSR1, &act, NULL); 1082 1083 /* it should be safe to restart syscalls after SIGCHLD */ 1084 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP; 1085 sigaction(SIGCHLD, &act, NULL); 1086 1087 #elif defined(HAVE_SIGNAL) 1088 /* ignore the SIGPIPE from sendfile() */ 1089 signal(SIGPIPE, SIG_IGN); 1090 signal(SIGALRM, signal_handler); 1091 signal(SIGTERM, signal_handler); 1092 signal(SIGHUP, signal_handler); 1093 signal(SIGCHLD, signal_handler); 1094 signal(SIGINT, signal_handler); 1095 signal(SIGUSR1, signal_handler); 1096 #endif 1097 1098 1099 srv->gid = getgid(); 1100 srv->uid = getuid(); 1101 srv->pid = getpid(); 1102 1103 /* write pid file */ 1104 if (pid_fd > 2) { 1105 buffer * const tb = srv->tmp_buf; 1106 buffer_clear(tb); 1107 buffer_append_int(tb, srv->pid); 1108 buffer_append_string_len(tb, CONST_STR_LEN("\n")); 1109 if (-1 == write_all(pid_fd, CONST_BUF_LEN(tb))) { 1110 log_perror(srv->errh, __FILE__, __LINE__, "Couldn't write pid file"); 1111 close(pid_fd); 1112 pid_fd = -1; 1113 return -1; 1114 } 1115 } else if (pid_fd < -2) { 1116 pid_fd = -pid_fd; 1117 } 1118 1119 /* Close stderr ASAP in the child process to make sure that nothing 1120 * is being written to that fd which may not be valid anymore. */ 1121 if (!srv->srvconf.preflight_check) { 1122 if (-1 == config_log_error_open(srv)) { 1123 log_error(srv->errh, __FILE__, __LINE__, "Opening errorlog failed. Going down."); 1124 return -1; 1125 } 1126 log_error(srv->errh, __FILE__, __LINE__, "server started (" PACKAGE_DESC ")"); 1127 } 1128 1129 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) { 1130 log_error(srv->errh, __FILE__, __LINE__, "Configuration of plugins failed. Going down."); 1131 return -1; 1132 } 1133 1134 if (!config_finalize(srv, &default_server_tag)) { 1135 return -1; 1136 } 1137 1138 if (srv->srvconf.preflight_check) { 1139 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/ 1140 return 0; 1141 } 1142 1143 1144 #ifdef HAVE_FORK 1145 /** 1146 * notify daemonize-grandparent of successful startup 1147 * do this before any further forking is done (workers) 1148 */ 1149 if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) { 1150 if (0 > write(parent_pipe_fd, "", 1)) return -1; 1151 close(parent_pipe_fd); 1152 } 1153 1154 if (idle_limit && srv->srvconf.max_worker) { 1155 srv->srvconf.max_worker = 0; 1156 log_error(srv->errh, __FILE__, __LINE__, 1157 "server idle time limit command line option disables server.max-worker config file option."); 1158 } 1159 1160 /* start watcher and workers */ 1161 num_childs = srv->srvconf.max_worker; 1162 if (num_childs > 0) { 1163 pid_t pids[num_childs]; 1164 pid_t pid; 1165 const int npids = num_childs; 1166 int child = 0; 1167 unsigned int timer = 0; 1168 for (int n = 0; n < npids; ++n) pids[n] = -1; 1169 while (!child && !srv_shutdown && !graceful_shutdown) { 1170 if (num_childs > 0) { 1171 switch ((pid = fork())) { 1172 case -1: 1173 return -1; 1174 case 0: 1175 child = 1; 1176 alarm(0); 1177 break; 1178 default: 1179 num_childs--; 1180 for (int n = 0; n < npids; ++n) { 1181 if (-1 == pids[n]) { 1182 pids[n] = pid; 1183 break; 1184 } 1185 } 1186 break; 1187 } 1188 } else { 1189 int status; 1190 1191 if (-1 != (pid = wait(&status))) { 1192 log_epoch_secs = time(NULL); 1193 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) { 1194 if (!timer) alarm((timer = 5)); 1195 continue; 1196 } 1197 switch (fdevent_reaped_logger_pipe(pid)) { 1198 default: break; 1199 case -1: if (!timer) alarm((timer = 5)); 1200 /* fall through */ 1201 case 1: continue; 1202 } 1203 /** 1204 * check if one of our workers went away 1205 */ 1206 for (int n = 0; n < npids; ++n) { 1207 if (pid == pids[n]) { 1208 pids[n] = -1; 1209 num_childs++; 1210 break; 1211 } 1212 } 1213 } else { 1214 switch (errno) { 1215 case EINTR: 1216 log_epoch_secs = time(NULL); 1217 /** 1218 * if we receive a SIGHUP we have to close our logs ourself as we don't 1219 * have the mainloop who can help us here 1220 */ 1221 if (handle_sig_hup) { 1222 handle_sig_hup = 0; 1223 1224 config_log_error_cycle(srv); 1225 1226 /* forward SIGHUP to workers */ 1227 for (int n = 0; n < npids; ++n) { 1228 if (pids[n] > 0) kill(pids[n], SIGHUP); 1229 } 1230 } 1231 if (handle_sig_alarm) { 1232 handle_sig_alarm = 0; 1233 timer = 0; 1234 plugins_call_handle_trigger(srv); 1235 fdevent_restart_logger_pipes(log_epoch_secs); 1236 } 1237 break; 1238 default: 1239 break; 1240 } 1241 } 1242 } 1243 } 1244 1245 /** 1246 * for the parent this is the exit-point 1247 */ 1248 if (!child) { 1249 /** 1250 * kill all children too 1251 */ 1252 if (graceful_shutdown || graceful_restart) { 1253 /* flag to ignore one SIGINT if graceful_restart */ 1254 if (graceful_restart) graceful_restart = 2; 1255 kill(0, SIGINT); 1256 server_graceful_state(srv); 1257 } else if (srv_shutdown) { 1258 kill(0, SIGTERM); 1259 } 1260 1261 return 0; 1262 } 1263 1264 /* ignore SIGUSR1 in workers; only parent directs graceful restart */ 1265 #ifdef HAVE_SIGACTION 1266 { 1267 struct sigaction actignore; 1268 memset(&actignore, 0, sizeof(actignore)); 1269 actignore.sa_handler = SIG_IGN; 1270 sigaction(SIGUSR1, &actignore, NULL); 1271 } 1272 #elif defined(HAVE_SIGNAL) 1273 signal(SIGUSR1, SIG_IGN); 1274 #endif 1275 1276 /** 1277 * make sure workers do not muck with pid-file 1278 */ 1279 if (0 <= pid_fd) { 1280 close(pid_fd); 1281 pid_fd = -1; 1282 } 1283 if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file); 1284 1285 fdevent_clr_logger_pipe_pids(); 1286 srv->pid = getpid(); 1287 li_rand_reseed(); 1288 } 1289 #endif 1290 1291 srv->max_fds = (int)srv->srvconf.max_fds; 1292 srv->ev = fdevent_init(srv->srvconf.event_handler, &srv->max_fds, &srv->cur_fds, srv->errh); 1293 if (NULL == srv->ev) { 1294 log_error(srv->errh, __FILE__, __LINE__, "fdevent_init failed"); 1295 return -1; 1296 } 1297 1298 srv->max_fds_lowat = srv->max_fds * 8 / 10; 1299 srv->max_fds_hiwat = srv->max_fds * 9 / 10; 1300 1301 /* set max-conns */ 1302 if (srv->srvconf.max_conns > srv->max_fds/2) { 1303 /* we can't have more connections than max-fds/2 */ 1304 log_error(srv->errh, __FILE__, __LINE__, 1305 "can't have more connections than fds/2: %hu %d", 1306 srv->srvconf.max_conns, srv->max_fds); 1307 srv->max_conns = srv->max_fds/2; 1308 } else if (srv->srvconf.max_conns) { 1309 /* otherwise respect the wishes of the user */ 1310 srv->max_conns = srv->srvconf.max_conns; 1311 } else { 1312 /* or use the default: we really don't want to hit max-fds */ 1313 srv->max_conns = srv->max_fds/3; 1314 } 1315 1316 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */ 1317 #ifdef HAVE_SIGACTION 1318 sigaction(SIGCHLD, &act, NULL); 1319 #elif defined(HAVE_SIGNAL) 1320 signal(SIGCHLD, signal_handler); 1321 #endif 1322 1323 /* 1324 * kqueue() is called here, select resets its internals, 1325 * all server sockets get their handlers 1326 * 1327 * */ 1328 if (0 != network_register_fdevents(srv)) { 1329 return -1; 1330 } 1331 1332 /* might fail if user is using fam (not gamin) and famd isn't running */ 1333 if (!stat_cache_init(srv->ev, srv->errh)) { 1334 log_error(srv->errh, __FILE__, __LINE__, 1335 "stat-cache could not be setup, dieing."); 1336 return -1; 1337 } 1338 1339 #ifdef USE_ALARM 1340 { 1341 /* setup periodic timer (1 second) */ 1342 struct itimerval interval; 1343 interval.it_interval.tv_sec = 1; 1344 interval.it_interval.tv_usec = 0; 1345 interval.it_value.tv_sec = 1; 1346 interval.it_value.tv_usec = 0; 1347 if (setitimer(ITIMER_REAL, &interval, NULL)) { 1348 log_perror(srv->errh, __FILE__, __LINE__, "setitimer()"); 1349 return -1; 1350 } 1351 } 1352 #endif 1353 1354 /* get the current number of FDs */ 1355 { 1356 int fd = fdevent_open_devnull(); 1357 if (fd >= 0) { 1358 srv->cur_fds = fd; 1359 close(fd); 1360 } 1361 } 1362 1363 if (0 != server_sockets_set_nb_cloexec(srv)) { 1364 return -1; 1365 } 1366 1367 /* plugin hook for worker_init */ 1368 if (HANDLER_GO_ON != plugins_call_worker_init(srv)) 1369 return -1; 1370 1371 if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) { 1372 oneshot_fd = -1; 1373 } 1374 1375 return 1; 1376 } 1377 1378 __attribute_cold__ 1379 __attribute_noinline__ 1380 static void server_handle_sighup (server * const srv) { 1381 1382 /* cycle logfiles */ 1383 1384 plugins_call_handle_sighup(srv); 1385 1386 config_log_error_cycle(srv); 1387 #ifdef HAVE_SIGACTION 1388 log_error(srv->errh, __FILE__, __LINE__, 1389 "logfiles cycled UID = %d PID = %d", 1390 (int)last_sighup_info.si_uid, 1391 (int)last_sighup_info.si_pid); 1392 #else 1393 log_error(srv->errh, __FILE__, __LINE__, 1394 "logfiles cycled"); 1395 #endif 1396 } 1397 1398 __attribute_noinline__ 1399 static void server_handle_sigalrm (server * const srv, time_t min_ts, time_t last_active_ts) { 1400 1401 plugins_call_handle_trigger(srv); 1402 1403 log_epoch_secs = min_ts; 1404 1405 /* check idle time limit, if enabled */ 1406 if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) { 1407 log_error(srv->errh, __FILE__, __LINE__, 1408 "[note] idle timeout %ds exceeded, " 1409 "initiating graceful shutdown", (int)idle_limit); 1410 graceful_shutdown = 2; /* value 2 indicates idle timeout */ 1411 if (graceful_restart) { 1412 graceful_restart = 0; 1413 if (pid_fd < -2) pid_fd = -pid_fd; 1414 server_sockets_close(srv); 1415 } 1416 } 1417 1418 #ifdef HAVE_GETLOADAVG 1419 /* refresh loadavg data every 30 seconds */ 1420 if (srv->loadts + 30 < min_ts) { 1421 if (-1 != getloadavg(srv->loadavg, 3)) { 1422 srv->loadts = min_ts; 1423 } 1424 } 1425 #endif 1426 1427 if (0 == (min_ts & 0x3f)) { /*(once every 64 secs)*/ 1428 /* free excess chunkqueue buffers every 64 secs */ 1429 chunkqueue_chunk_pool_clear(); 1430 /* attempt to restart dead piped loggers every 64 secs */ 1431 if (0 == srv->srvconf.max_worker) 1432 fdevent_restart_logger_pipes(min_ts); 1433 } 1434 /* cleanup stat-cache */ 1435 stat_cache_trigger_cleanup(); 1436 /* reset global/aggregate rate limit counters */ 1437 config_reset_config_bytes_sec(srv->config_data_base); 1438 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */ 1439 if (graceful_shutdown && !srv_shutdown) connection_graceful_shutdown_maint(srv); 1440 connection_periodic_maint(srv, min_ts); 1441 } 1442 1443 __attribute_noinline__ 1444 static void server_handle_sigchld (server * const srv) { 1445 pid_t pid; 1446 do { 1447 int status; 1448 pid = waitpid(-1, &status, WNOHANG); 1449 if (pid > 0) { 1450 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) { 1451 continue; 1452 } 1453 if (0 == srv->srvconf.max_worker) { 1454 /* check piped-loggers and restart, even if shutting down */ 1455 if (fdevent_waitpid_logger_pipe_pid(pid, log_epoch_secs)) { 1456 continue; 1457 } 1458 } 1459 } 1460 } while (pid > 0 || (-1 == pid && errno == EINTR)); 1461 } 1462 1463 __attribute_hot__ 1464 __attribute_noinline__ 1465 static void server_main_loop (server * const srv) { 1466 connections * const joblist = &srv->joblist; 1467 time_t last_active_ts = time(NULL); 1468 1469 while (!srv_shutdown) { 1470 1471 if (handle_sig_hup) { 1472 handle_sig_hup = 0; 1473 server_handle_sighup(srv); 1474 } 1475 1476 /*(USE_ALARM not used; fdevent_poll() is effective periodic timer)*/ 1477 #ifdef USE_ALARM 1478 if (handle_sig_alarm) { 1479 handle_sig_alarm = 0; 1480 #endif 1481 time_t min_ts = time(NULL); 1482 if (min_ts != log_epoch_secs) { 1483 server_handle_sigalrm(srv, min_ts, last_active_ts); 1484 } 1485 #ifdef USE_ALARM 1486 } 1487 #endif 1488 1489 if (handle_sig_child) { 1490 handle_sig_child = 0; 1491 server_handle_sigchld(srv); 1492 } 1493 1494 if (graceful_shutdown) { 1495 server_graceful_state(srv); 1496 if (0 == srv->conns.used) { 1497 /* we are in graceful shutdown phase and all connections are closed 1498 * we are ready to terminate without harming anyone */ 1499 srv_shutdown = 1; 1500 break; 1501 } 1502 } else if (srv->sockets_disabled) { 1503 server_overload_check(srv); 1504 } else { 1505 server_load_check(srv); 1506 } 1507 1508 if (srv->fdwaitqueue.used) { 1509 server_process_fdwaitqueue(srv); 1510 } 1511 1512 if (fdevent_poll(srv->ev, 1000) > 0) { 1513 last_active_ts = log_epoch_secs; 1514 } 1515 1516 for (uint32_t ndx = 0; ndx < joblist->used; ++ndx) { 1517 connection *con = joblist->ptr[ndx]; 1518 connection_state_machine(con); 1519 } 1520 joblist->used = 0; 1521 } 1522 } 1523 1524 __attribute_cold__ 1525 int main (int argc, char **argv) { 1526 int rc; 1527 1528 #ifdef HAVE_GETUID 1529 #ifndef HAVE_ISSETUGID 1530 #define issetugid() (geteuid() != getuid() || getegid() != getgid()) 1531 #endif 1532 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/ 1533 fprintf(stderr, 1534 "Are you nuts ? Don't apply a SUID bit to this binary\n"); 1535 return -1; 1536 } 1537 #endif 1538 1539 /* for nice %b handling in strftime() */ 1540 setlocale(LC_TIME, "C"); 1541 1542 do { 1543 server * const srv = server_init(); 1544 1545 if (graceful_restart) { 1546 server_sockets_restore(srv); 1547 optind = 1; 1548 } 1549 1550 rc = server_main_setup(srv, argc, argv); 1551 if (rc > 0) { 1552 1553 server_main_loop(srv); 1554 1555 if (graceful_shutdown || graceful_restart) { 1556 server_graceful_state(srv); 1557 } 1558 1559 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */ 1560 log_error(srv->errh, __FILE__, __LINE__, 1561 "server stopped after idle timeout"); 1562 } else { 1563 #ifdef HAVE_SIGACTION 1564 log_error(srv->errh, __FILE__, __LINE__, 1565 "server stopped by UID = %d PID = %d", 1566 (int)last_sigterm_info.si_uid, 1567 (int)last_sigterm_info.si_pid); 1568 #else 1569 log_error(srv->errh, __FILE__, __LINE__, 1570 "server stopped"); 1571 #endif 1572 } 1573 } 1574 1575 /* clean-up */ 1576 remove_pid_file(srv); 1577 config_log_error_close(srv); 1578 if (graceful_restart) 1579 server_sockets_save(srv); 1580 else 1581 network_close(srv); 1582 connections_free(srv); 1583 plugins_free(srv); 1584 server_free(srv); 1585 1586 if (rc < 0 || !graceful_restart) break; 1587 1588 /* wait for all children to exit before graceful restart */ 1589 while (waitpid(-1, NULL, 0) > 0) ; 1590 } while (graceful_restart); 1591 1592 return rc; 1593 } 1594