1 #include "first.h" 2 3 #include "server.h" 4 #include "buffer.h" 5 #include "network.h" 6 #include "log.h" 7 #include "keyvalue.h" 8 #include "response.h" 9 #include "request.h" 10 #include "chunk.h" 11 #include "http_chunk.h" 12 #include "fdevent.h" 13 #include "connections.h" 14 #include "stat_cache.h" 15 #include "plugin.h" 16 #include "joblist.h" 17 #include "network_backends.h" 18 #include "version.h" 19 20 #include <sys/types.h> 21 #include <sys/time.h> 22 #include <sys/stat.h> 23 24 #include <string.h> 25 #include <errno.h> 26 #include <fcntl.h> 27 #include <unistd.h> 28 #include <stdlib.h> 29 #include <time.h> 30 #include <signal.h> 31 #include <assert.h> 32 #include <locale.h> 33 34 #include <stdio.h> 35 36 #ifdef HAVE_GETOPT_H 37 # include <getopt.h> 38 #endif 39 40 #ifdef HAVE_VALGRIND_VALGRIND_H 41 # include <valgrind/valgrind.h> 42 #endif 43 44 #ifdef HAVE_SYS_WAIT_H 45 # include <sys/wait.h> 46 #endif 47 48 #ifdef HAVE_PWD_H 49 # include <grp.h> 50 # include <pwd.h> 51 #endif 52 53 #ifdef HAVE_SYS_RESOURCE_H 54 # include <sys/resource.h> 55 #endif 56 57 #ifdef HAVE_SYS_PRCTL_H 58 # include <sys/prctl.h> 59 #endif 60 61 #ifdef USE_OPENSSL 62 # include <openssl/err.h> 63 #endif 64 65 #ifndef __sgi 66 /* IRIX doesn't like the alarm based time() optimization */ 67 /* #define USE_ALARM */ 68 #endif 69 70 #ifdef HAVE_GETUID 71 # ifndef HAVE_ISSETUGID 72 73 static int l_issetugid(void) { 74 return (geteuid() != getuid() || getegid() != getgid()); 75 } 76 77 # define issetugid l_issetugid 78 # endif 79 #endif 80 81 static int oneshot_fd = 0; 82 static volatile sig_atomic_t srv_shutdown = 0; 83 static volatile sig_atomic_t graceful_shutdown = 0; 84 static volatile sig_atomic_t handle_sig_alarm = 1; 85 static volatile sig_atomic_t handle_sig_hup = 0; 86 static volatile sig_atomic_t forwarded_sig_hup = 0; 87 88 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO) 89 static volatile siginfo_t last_sigterm_info; 90 static volatile siginfo_t last_sighup_info; 91 92 static void sigaction_handler(int sig, siginfo_t *si, void *context) { 93 static siginfo_t empty_siginfo; 94 UNUSED(context); 95 96 if (!si) si = &empty_siginfo; 97 98 switch (sig) { 99 case SIGTERM: 100 srv_shutdown = 1; 101 last_sigterm_info = *si; 102 break; 103 case SIGINT: 104 if (graceful_shutdown) { 105 srv_shutdown = 1; 106 } else { 107 graceful_shutdown = 1; 108 } 109 last_sigterm_info = *si; 110 111 break; 112 case SIGALRM: 113 handle_sig_alarm = 1; 114 break; 115 case SIGHUP: 116 /** 117 * we send the SIGHUP to all procs in the process-group 118 * this includes ourself 119 * 120 * make sure we only send it once and don't create a 121 * infinite loop 122 */ 123 if (!forwarded_sig_hup) { 124 handle_sig_hup = 1; 125 last_sighup_info = *si; 126 } else { 127 forwarded_sig_hup = 0; 128 } 129 break; 130 case SIGCHLD: 131 break; 132 } 133 } 134 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION) 135 static void signal_handler(int sig) { 136 switch (sig) { 137 case SIGTERM: srv_shutdown = 1; break; 138 case SIGINT: 139 if (graceful_shutdown) srv_shutdown = 1; 140 else graceful_shutdown = 1; 141 142 break; 143 case SIGALRM: handle_sig_alarm = 1; break; 144 case SIGHUP: handle_sig_hup = 1; break; 145 case SIGCHLD: break; 146 } 147 } 148 #endif 149 150 #ifdef HAVE_FORK 151 static int daemonize(void) { 152 int pipefd[2]; 153 pid_t pid; 154 #ifdef SIGTTOU 155 signal(SIGTTOU, SIG_IGN); 156 #endif 157 #ifdef SIGTTIN 158 signal(SIGTTIN, SIG_IGN); 159 #endif 160 #ifdef SIGTSTP 161 signal(SIGTSTP, SIG_IGN); 162 #endif 163 164 if (pipe(pipefd) < 0) exit(-1); 165 166 if (0 > (pid = fork())) exit(-1); 167 168 if (0 < pid) { 169 char buf; 170 ssize_t bytes; 171 172 close(pipefd[1]); 173 /* parent waits for grandchild to be ready */ 174 do { 175 bytes = read(pipefd[0], &buf, sizeof(buf)); 176 } while (bytes < 0 && EINTR == errno); 177 close(pipefd[0]); 178 179 if (bytes <= 0) { 180 /* closed fd (without writing) == failure in grandchild */ 181 fputs("daemonized server failed to start; check error log for details\n", stderr); 182 exit(-1); 183 } 184 185 exit(0); 186 } 187 188 close(pipefd[0]); 189 190 if (-1 == setsid()) exit(0); 191 192 signal(SIGHUP, SIG_IGN); 193 194 if (0 != fork()) exit(0); 195 196 if (0 != chdir("/")) exit(0); 197 198 fd_close_on_exec(pipefd[1]); 199 return pipefd[1]; 200 } 201 #endif 202 203 static server *server_init(void) { 204 int i; 205 FILE *frandom = NULL; 206 207 server *srv = calloc(1, sizeof(*srv)); 208 force_assert(srv); 209 #define CLEAN(x) \ 210 srv->x = buffer_init(); 211 212 CLEAN(response_header); 213 CLEAN(parse_full_path); 214 CLEAN(ts_debug_str); 215 CLEAN(ts_date_str); 216 CLEAN(errorlog_buf); 217 CLEAN(response_range); 218 CLEAN(tmp_buf); 219 srv->empty_string = buffer_init_string(""); 220 CLEAN(cond_check_buf); 221 222 CLEAN(srvconf.errorlog_file); 223 CLEAN(srvconf.breakagelog_file); 224 CLEAN(srvconf.groupname); 225 CLEAN(srvconf.username); 226 CLEAN(srvconf.changeroot); 227 CLEAN(srvconf.bindhost); 228 CLEAN(srvconf.event_handler); 229 CLEAN(srvconf.pid_file); 230 231 CLEAN(tmp_chunk_len); 232 #undef CLEAN 233 234 #define CLEAN(x) \ 235 srv->x = array_init(); 236 237 CLEAN(config_context); 238 CLEAN(config_touched); 239 CLEAN(status); 240 #undef CLEAN 241 242 for (i = 0; i < FILE_CACHE_MAX; i++) { 243 srv->mtime_cache[i].mtime = (time_t)-1; 244 srv->mtime_cache[i].str = buffer_init(); 245 } 246 247 if ((NULL != (frandom = fopen("/dev/urandom", "rb")) || NULL != (frandom = fopen("/dev/random", "rb"))) 248 && 1 == fread(srv->entropy, sizeof(srv->entropy), 1, frandom)) { 249 unsigned int e; 250 memcpy(&e, srv->entropy, sizeof(e) < sizeof(srv->entropy) ? sizeof(e) : sizeof(srv->entropy)); 251 srand(e); 252 srv->is_real_entropy = 1; 253 } else { 254 unsigned int j; 255 srand(time(NULL) ^ getpid()); 256 srv->is_real_entropy = 0; 257 for (j = 0; j < sizeof(srv->entropy); j++) 258 srv->entropy[j] = rand(); 259 } 260 if (frandom) fclose(frandom); 261 262 srv->cur_ts = time(NULL); 263 srv->startup_ts = srv->cur_ts; 264 265 srv->conns = calloc(1, sizeof(*srv->conns)); 266 force_assert(srv->conns); 267 268 srv->joblist = calloc(1, sizeof(*srv->joblist)); 269 force_assert(srv->joblist); 270 271 srv->fdwaitqueue = calloc(1, sizeof(*srv->fdwaitqueue)); 272 force_assert(srv->fdwaitqueue); 273 274 srv->srvconf.modules = array_init(); 275 srv->srvconf.modules_dir = buffer_init_string(LIBRARY_DIR); 276 srv->srvconf.network_backend = buffer_init(); 277 srv->srvconf.upload_tempdirs = array_init(); 278 srv->srvconf.reject_expect_100_with_417 = 1; 279 srv->srvconf.xattr_name = buffer_init_string("Content-Type"); 280 srv->srvconf.http_header_strict = 1; 281 srv->srvconf.http_host_strict = 1; /*(implies http_host_normalize)*/ 282 srv->srvconf.http_host_normalize = 0; 283 284 /* use syslog */ 285 srv->errorlog_fd = STDERR_FILENO; 286 srv->errorlog_mode = ERRORLOG_FD; 287 288 srv->split_vals = array_init(); 289 290 return srv; 291 } 292 293 static void server_free(server *srv) { 294 size_t i; 295 296 for (i = 0; i < FILE_CACHE_MAX; i++) { 297 buffer_free(srv->mtime_cache[i].str); 298 } 299 300 if (oneshot_fd > 0) { 301 close(oneshot_fd); 302 } 303 304 #define CLEAN(x) \ 305 buffer_free(srv->x); 306 307 CLEAN(response_header); 308 CLEAN(parse_full_path); 309 CLEAN(ts_debug_str); 310 CLEAN(ts_date_str); 311 CLEAN(errorlog_buf); 312 CLEAN(response_range); 313 CLEAN(tmp_buf); 314 CLEAN(empty_string); 315 CLEAN(cond_check_buf); 316 317 CLEAN(srvconf.errorlog_file); 318 CLEAN(srvconf.breakagelog_file); 319 CLEAN(srvconf.groupname); 320 CLEAN(srvconf.username); 321 CLEAN(srvconf.changeroot); 322 CLEAN(srvconf.bindhost); 323 CLEAN(srvconf.event_handler); 324 CLEAN(srvconf.pid_file); 325 CLEAN(srvconf.modules_dir); 326 CLEAN(srvconf.network_backend); 327 CLEAN(srvconf.xattr_name); 328 329 CLEAN(tmp_chunk_len); 330 #undef CLEAN 331 332 #if 0 333 fdevent_unregister(srv->ev, srv->fd); 334 #endif 335 fdevent_free(srv->ev); 336 337 free(srv->conns); 338 339 if (srv->config_storage) { 340 for (i = 0; i < srv->config_context->used; i++) { 341 specific_config *s = srv->config_storage[i]; 342 343 if (!s) continue; 344 345 buffer_free(s->document_root); 346 buffer_free(s->server_name); 347 buffer_free(s->server_tag); 348 buffer_free(s->ssl_pemfile); 349 buffer_free(s->ssl_ca_file); 350 buffer_free(s->ssl_cipher_list); 351 buffer_free(s->ssl_dh_file); 352 buffer_free(s->ssl_ec_curve); 353 buffer_free(s->error_handler); 354 buffer_free(s->error_handler_404); 355 buffer_free(s->errorfile_prefix); 356 array_free(s->mimetypes); 357 buffer_free(s->ssl_verifyclient_username); 358 #ifdef USE_OPENSSL 359 SSL_CTX_free(s->ssl_ctx); 360 EVP_PKEY_free(s->ssl_pemfile_pkey); 361 X509_free(s->ssl_pemfile_x509); 362 if (NULL != s->ssl_ca_file_cert_names) sk_X509_NAME_pop_free(s->ssl_ca_file_cert_names, X509_NAME_free); 363 #endif 364 free(s); 365 } 366 free(srv->config_storage); 367 srv->config_storage = NULL; 368 } 369 370 #define CLEAN(x) \ 371 array_free(srv->x); 372 373 CLEAN(config_context); 374 CLEAN(config_touched); 375 CLEAN(status); 376 CLEAN(srvconf.upload_tempdirs); 377 #undef CLEAN 378 379 joblist_free(srv, srv->joblist); 380 fdwaitqueue_free(srv, srv->fdwaitqueue); 381 382 if (srv->stat_cache) { 383 stat_cache_free(srv->stat_cache); 384 } 385 386 array_free(srv->srvconf.modules); 387 array_free(srv->split_vals); 388 389 #ifdef USE_OPENSSL 390 if (srv->ssl_is_init) { 391 CRYPTO_cleanup_all_ex_data(); 392 ERR_free_strings(); 393 #if OPENSSL_VERSION_NUMBER >= 0x10100000L \ 394 && !defined(LIBRESSL_VERSION_NUMBER) 395 /*(OpenSSL libraries handle thread init and deinit) 396 * https://github.com/openssl/openssl/pull/1048 */ 397 #elif OPENSSL_VERSION_NUMBER >= 0x10000000L 398 ERR_remove_thread_state(NULL); 399 #else 400 ERR_remove_state(0); 401 #endif 402 EVP_cleanup(); 403 } 404 #endif 405 406 free(srv); 407 } 408 409 static void remove_pid_file(server *srv, int *pid_fd) { 410 if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= *pid_fd) { 411 if (0 != ftruncate(*pid_fd, 0)) { 412 log_error_write(srv, __FILE__, __LINE__, "sbds", 413 "ftruncate failed for:", 414 srv->srvconf.pid_file, 415 errno, 416 strerror(errno)); 417 } 418 } 419 if (0 <= *pid_fd) { 420 close(*pid_fd); 421 *pid_fd = -1; 422 } 423 if (!buffer_string_is_empty(srv->srvconf.pid_file) && 424 buffer_string_is_empty(srv->srvconf.changeroot)) { 425 if (0 != unlink(srv->srvconf.pid_file->ptr)) { 426 if (errno != EACCES && errno != EPERM) { 427 log_error_write(srv, __FILE__, __LINE__, "sbds", 428 "unlink failed for:", 429 srv->srvconf.pid_file, 430 errno, 431 strerror(errno)); 432 } 433 } 434 } 435 } 436 437 438 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) { 439 server_socket *srv_socket, *srv_socket_wild = NULL; 440 size_t i; 441 for (i = 0; i < srv->srv_sockets.used; ++i) { 442 srv_socket = srv->srv_sockets.ptr[i]; 443 if (cnt_addr->plain.sa_family != srv_socket->addr.plain.sa_family) continue; 444 switch (cnt_addr->plain.sa_family) { 445 case AF_INET: 446 if (srv_socket->addr.ipv4.sin_port != cnt_addr->ipv4.sin_port) continue; 447 if (srv_socket->addr.ipv4.sin_addr.s_addr == cnt_addr->ipv4.sin_addr.s_addr) { 448 return srv_socket; 449 } 450 if (srv_socket->addr.ipv4.sin_addr.s_addr == htonl(INADDR_ANY)) { 451 srv_socket_wild = srv_socket; 452 } 453 continue; 454 #ifdef HAVE_IPV6 455 case AF_INET6: 456 if (srv_socket->addr.ipv6.sin6_port != cnt_addr->ipv6.sin6_port) continue; 457 if (0 == memcmp(&srv_socket->addr.ipv6.sin6_addr, &cnt_addr->ipv6.sin6_addr, sizeof(struct in6_addr))) { 458 return srv_socket; 459 } 460 if (0 == memcmp(&srv_socket->addr.ipv6.sin6_addr, &in6addr_any, sizeof(struct in6_addr))) { 461 srv_socket_wild = srv_socket; 462 } 463 continue; 464 #endif 465 #ifdef HAVE_SYS_UN_H 466 case AF_UNIX: 467 if (0 == strcmp(srv_socket->addr.un.sun_path, cnt_addr->un.sun_path)) { 468 return srv_socket; 469 } 470 continue; 471 #endif 472 default: continue; 473 } 474 } 475 476 if (NULL != srv_socket_wild) { 477 return srv_socket_wild; 478 } else if (srv->srv_sockets.used) { 479 return srv->srv_sockets.ptr[0]; 480 } else { 481 log_error_write(srv, __FILE__, __LINE__, "s", "no sockets configured"); 482 return NULL; 483 } 484 } 485 486 487 static int server_oneshot_init(server *srv, int fd) { 488 /* Note: does not work with netcat due to requirement that fd be socket. 489 * STDOUT_FILENO was not saved earlier in startup, and that is to where 490 * netcat expects output to be sent. Since lighttpd expects connections 491 * to be sockets, con->fd is where output is sent; separate fds are not 492 * stored for input and output, but netcat has different fds for stdin 493 * and * stdout. To support netcat, would additionally need to avoid 494 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing 495 * addresses from environment variables: 496 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT 497 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT 498 * NCAT_PROTO 499 */ 500 connection *con; 501 server_socket *srv_socket; 502 sock_addr cnt_addr; 503 socklen_t cnt_len; 504 struct stat st; 505 506 if (0 != fstat(fd, &st)) { 507 log_error_write(srv, __FILE__, __LINE__, "ss", "fstat:", strerror(errno)); 508 return 0; 509 } 510 511 if (!S_ISSOCK(st.st_mode)) { 512 /* require that fd is a socket 513 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */ 514 log_error_write(srv, __FILE__, __LINE__, "s", "lighttpd -1 stdin is not a socket"); 515 return 0; 516 } 517 518 cnt_len = sizeof(cnt_addr); 519 if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 520 log_error_write(srv, __FILE__, __LINE__, "ss", "getsockname:", strerror(errno)); 521 return 0; 522 } 523 524 srv_socket = server_oneshot_getsock(srv, &cnt_addr); 525 if (NULL == srv_socket) return 0; 526 527 cnt_len = sizeof(cnt_addr); 528 if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 529 log_error_write(srv, __FILE__, __LINE__, "ss", "getpeername:", strerror(errno)); 530 return 0; 531 } 532 533 con = connection_accepted(srv, srv_socket, &cnt_addr, fd); 534 if (NULL == con) return 0; 535 536 connection_state_machine(srv, con); 537 return 1; 538 } 539 540 541 static void show_version (void) { 542 #ifdef USE_OPENSSL 543 # define TEXT_SSL " (ssl)" 544 #else 545 # define TEXT_SSL 546 #endif 547 char *b = PACKAGE_DESC TEXT_SSL \ 548 " - a light and fast webserver\n" \ 549 "Build-Date: " __DATE__ " " __TIME__ "\n"; 550 ; 551 #undef TEXT_SSL 552 write_all(STDOUT_FILENO, b, strlen(b)); 553 } 554 555 static void show_features (void) { 556 const char features[] = "" 557 #ifdef USE_SELECT 558 "\t+ select (generic)\n" 559 #else 560 "\t- select (generic)\n" 561 #endif 562 #ifdef USE_POLL 563 "\t+ poll (Unix)\n" 564 #else 565 "\t- poll (Unix)\n" 566 #endif 567 #ifdef USE_LINUX_SIGIO 568 "\t+ rt-signals (Linux 2.4+)\n" 569 #else 570 "\t- rt-signals (Linux 2.4+)\n" 571 #endif 572 #ifdef USE_LINUX_EPOLL 573 "\t+ epoll (Linux 2.6)\n" 574 #else 575 "\t- epoll (Linux 2.6)\n" 576 #endif 577 #ifdef USE_SOLARIS_DEVPOLL 578 "\t+ /dev/poll (Solaris)\n" 579 #else 580 "\t- /dev/poll (Solaris)\n" 581 #endif 582 #ifdef USE_SOLARIS_PORT 583 "\t+ eventports (Solaris)\n" 584 #else 585 "\t- eventports (Solaris)\n" 586 #endif 587 #ifdef USE_FREEBSD_KQUEUE 588 "\t+ kqueue (FreeBSD)\n" 589 #else 590 "\t- kqueue (FreeBSD)\n" 591 #endif 592 #ifdef USE_LIBEV 593 "\t+ libev (generic)\n" 594 #else 595 "\t- libev (generic)\n" 596 #endif 597 "\nNetwork handler:\n\n" 598 #if defined USE_LINUX_SENDFILE 599 "\t+ linux-sendfile\n" 600 #else 601 "\t- linux-sendfile\n" 602 #endif 603 #if defined USE_FREEBSD_SENDFILE 604 "\t+ freebsd-sendfile\n" 605 #else 606 "\t- freebsd-sendfile\n" 607 #endif 608 #if defined USE_DARWIN_SENDFILE 609 "\t+ darwin-sendfile\n" 610 #else 611 "\t- darwin-sendfile\n" 612 #endif 613 #if defined USE_SOLARIS_SENDFILEV 614 "\t+ solaris-sendfilev\n" 615 #else 616 "\t- solaris-sendfilev\n" 617 #endif 618 #if defined USE_WRITEV 619 "\t+ writev\n" 620 #else 621 "\t- writev\n" 622 #endif 623 "\t+ write\n" 624 #ifdef USE_MMAP 625 "\t+ mmap support\n" 626 #else 627 "\t- mmap support\n" 628 #endif 629 "\nFeatures:\n\n" 630 #ifdef HAVE_IPV6 631 "\t+ IPv6 support\n" 632 #else 633 "\t- IPv6 support\n" 634 #endif 635 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ 636 "\t+ zlib support\n" 637 #else 638 "\t- zlib support\n" 639 #endif 640 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2 641 "\t+ bzip2 support\n" 642 #else 643 "\t- bzip2 support\n" 644 #endif 645 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT) 646 "\t+ crypt support\n" 647 #else 648 "\t- crypt support\n" 649 #endif 650 #ifdef USE_OPENSSL 651 "\t+ SSL Support\n" 652 #else 653 "\t- SSL Support\n" 654 #endif 655 #ifdef HAVE_LIBPCRE 656 "\t+ PCRE support\n" 657 #else 658 "\t- PCRE support\n" 659 #endif 660 #ifdef HAVE_MYSQL 661 "\t+ mySQL support\n" 662 #else 663 "\t- mySQL support\n" 664 #endif 665 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER) 666 "\t+ LDAP support\n" 667 #else 668 "\t- LDAP support\n" 669 #endif 670 #ifdef USE_MEMCACHED 671 "\t+ memcached support\n" 672 #else 673 "\t- memcached support\n" 674 #endif 675 #ifdef HAVE_FAM_H 676 "\t+ FAM support\n" 677 #else 678 "\t- FAM support\n" 679 #endif 680 #ifdef HAVE_LUA_H 681 "\t+ LUA support\n" 682 #else 683 "\t- LUA support\n" 684 #endif 685 #ifdef HAVE_LIBXML_H 686 "\t+ xml support\n" 687 #else 688 "\t- xml support\n" 689 #endif 690 #ifdef HAVE_SQLITE3_H 691 "\t+ SQLite support\n" 692 #else 693 "\t- SQLite support\n" 694 #endif 695 #ifdef HAVE_GDBM_H 696 "\t+ GDBM support\n" 697 #else 698 "\t- GDBM support\n" 699 #endif 700 "\n"; 701 show_version(); 702 printf("\nEvent Handlers:\n\n%s", features); 703 } 704 705 static void show_help (void) { 706 #ifdef USE_OPENSSL 707 # define TEXT_SSL " (ssl)" 708 #else 709 # define TEXT_SSL 710 #endif 711 char *b = PACKAGE_DESC TEXT_SSL " ("__DATE__ " " __TIME__ ")" \ 712 " - a light and fast webserver\n" \ 713 "usage:\n" \ 714 " -f <name> filename of the config-file\n" \ 715 " -m <name> module directory (default: "LIBRARY_DIR")\n" \ 716 " -i <secs> graceful shutdown after <secs> of inactivity\n" \ 717 " -1 process single (one) request on stdin socket, then exit\n" \ 718 " -p print the parsed config-file in internal form, and exit\n" \ 719 " -t test the config-file, and exit\n" \ 720 " -D don't go to background (default: go to background)\n" \ 721 " -v show version\n" \ 722 " -V show compile-time features\n" \ 723 " -h show this help\n" \ 724 "\n" 725 ; 726 #undef TEXT_SSL 727 #undef TEXT_IPV6 728 write_all(STDOUT_FILENO, b, strlen(b)); 729 } 730 731 int main (int argc, char **argv) { 732 server *srv = NULL; 733 int print_config = 0; 734 int test_config = 0; 735 int i_am_root; 736 int o; 737 int num_childs = 0; 738 int pid_fd = -1, fd; 739 size_t i; 740 time_t idle_limit = 0, last_active_ts = time(NULL); 741 #ifdef HAVE_SIGACTION 742 struct sigaction act; 743 #endif 744 #ifdef HAVE_GETRLIMIT 745 struct rlimit rlim; 746 #endif 747 748 #ifdef HAVE_FORK 749 int parent_pipe_fd = -1; 750 #endif 751 752 #ifdef USE_ALARM 753 struct itimerval interval; 754 755 interval.it_interval.tv_sec = 1; 756 interval.it_interval.tv_usec = 0; 757 interval.it_value.tv_sec = 1; 758 interval.it_value.tv_usec = 0; 759 #endif 760 761 /* for nice %b handling in strfime() */ 762 setlocale(LC_TIME, "C"); 763 764 if (NULL == (srv = server_init())) { 765 fprintf(stderr, "did this really happen?\n"); 766 return -1; 767 } 768 769 /* init structs done */ 770 771 srv->srvconf.port = 0; 772 #ifdef HAVE_GETUID 773 i_am_root = (getuid() == 0); 774 #else 775 i_am_root = 0; 776 #endif 777 srv->srvconf.dont_daemonize = 0; 778 srv->srvconf.preflight_check = 0; 779 780 while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) { 781 switch(o) { 782 case 'f': 783 if (srv->config_storage) { 784 log_error_write(srv, __FILE__, __LINE__, "s", 785 "Can only read one config file. Use the include command to use multiple config files."); 786 787 server_free(srv); 788 return -1; 789 } 790 if (config_read(srv, optarg)) { 791 server_free(srv); 792 return -1; 793 } 794 break; 795 case 'm': 796 buffer_copy_string(srv->srvconf.modules_dir, optarg); 797 break; 798 case 'i': { 799 char *endptr; 800 long timeout = strtol(optarg, &endptr, 0); 801 if (!*optarg || *endptr || timeout < 0) { 802 log_error_write(srv, __FILE__, __LINE__, "ss", 803 "Invalid idle timeout value:", optarg); 804 server_free(srv); 805 return -1; 806 } 807 idle_limit = (time_t)timeout; 808 break; 809 } 810 case 'p': print_config = 1; break; 811 case 't': ++test_config; break; 812 case '1': oneshot_fd = dup(STDIN_FILENO); break; 813 case 'D': srv->srvconf.dont_daemonize = 1; break; 814 case 'v': show_version(); server_free(srv); return 0; 815 case 'V': show_features(); server_free(srv); return 0; 816 case 'h': show_help(); server_free(srv); return 0; 817 default: 818 show_help(); 819 server_free(srv); 820 return -1; 821 } 822 } 823 824 if (!srv->config_storage) { 825 log_error_write(srv, __FILE__, __LINE__, "s", 826 "No configuration available. Try using -f option."); 827 828 server_free(srv); 829 return -1; 830 } 831 832 if (print_config) { 833 data_unset *dc = srv->config_context->data[0]; 834 if (dc) { 835 dc->print(dc, 0); 836 fprintf(stdout, "\n"); 837 } else { 838 /* shouldn't happend */ 839 fprintf(stderr, "global config not found\n"); 840 } 841 } 842 843 if (test_config) { 844 if (1 == test_config) { 845 printf("Syntax OK\n"); 846 } else { /*(test_config > 1)*/ 847 test_config = 0; 848 srv->srvconf.preflight_check = 1; 849 srv->srvconf.dont_daemonize = 1; 850 buffer_reset(srv->srvconf.pid_file); 851 } 852 } 853 854 if (test_config || print_config) { 855 server_free(srv); 856 return 0; 857 } 858 859 if (oneshot_fd) { 860 if (oneshot_fd <= STDERR_FILENO) { 861 log_error_write(srv, __FILE__, __LINE__, "s", 862 "Invalid fds at startup with lighttpd -1"); 863 server_free(srv); 864 return -1; 865 } 866 graceful_shutdown = 1; 867 srv->sockets_disabled = 1; 868 srv->srvconf.dont_daemonize = 1; 869 buffer_reset(srv->srvconf.pid_file); 870 if (srv->srvconf.max_worker) { 871 srv->srvconf.max_worker = 0; 872 log_error_write(srv, __FILE__, __LINE__, "s", 873 "server one-shot command line option disables server.max-worker config file option."); 874 } 875 } 876 877 /* close stdin and stdout, as they are not needed */ 878 openDevNull(STDIN_FILENO); 879 openDevNull(STDOUT_FILENO); 880 881 if (0 != config_set_defaults(srv)) { 882 log_error_write(srv, __FILE__, __LINE__, "s", 883 "setting default values failed"); 884 server_free(srv); 885 return -1; 886 } 887 888 /* UID handling */ 889 #ifdef HAVE_GETUID 890 if (!i_am_root && issetugid()) { 891 /* we are setuid-root */ 892 893 log_error_write(srv, __FILE__, __LINE__, "s", 894 "Are you nuts ? Don't apply a SUID bit to this binary"); 895 896 server_free(srv); 897 return -1; 898 } 899 #endif 900 901 /* check document-root */ 902 if (buffer_string_is_empty(srv->config_storage[0]->document_root)) { 903 log_error_write(srv, __FILE__, __LINE__, "s", 904 "document-root is not set\n"); 905 906 server_free(srv); 907 908 return -1; 909 } 910 911 if (plugins_load(srv)) { 912 log_error_write(srv, __FILE__, __LINE__, "s", 913 "loading plugins finally failed"); 914 915 plugins_free(srv); 916 server_free(srv); 917 918 return -1; 919 } 920 921 /* open pid file BEFORE chroot */ 922 if (!buffer_string_is_empty(srv->srvconf.pid_file)) { 923 if (-1 == (pid_fd = open(srv->srvconf.pid_file->ptr, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) { 924 struct stat st; 925 if (errno != EEXIST) { 926 log_error_write(srv, __FILE__, __LINE__, "sbs", 927 "opening pid-file failed:", srv->srvconf.pid_file, strerror(errno)); 928 return -1; 929 } 930 931 if (0 != stat(srv->srvconf.pid_file->ptr, &st)) { 932 log_error_write(srv, __FILE__, __LINE__, "sbs", 933 "stating existing pid-file failed:", srv->srvconf.pid_file, strerror(errno)); 934 } 935 936 if (!S_ISREG(st.st_mode)) { 937 log_error_write(srv, __FILE__, __LINE__, "sb", 938 "pid-file exists and isn't regular file:", srv->srvconf.pid_file); 939 return -1; 940 } 941 942 if (-1 == (pid_fd = open(srv->srvconf.pid_file->ptr, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) { 943 log_error_write(srv, __FILE__, __LINE__, "sbs", 944 "opening pid-file failed:", srv->srvconf.pid_file, strerror(errno)); 945 return -1; 946 } 947 } 948 fd_close_on_exec(pid_fd); 949 } 950 951 if (srv->event_handler == FDEVENT_HANDLER_SELECT) { 952 /* select limits itself 953 * 954 * as it is a hard limit and will lead to a segfault we add some safety 955 * */ 956 srv->max_fds = FD_SETSIZE - 200; 957 } else { 958 srv->max_fds = 4096; 959 } 960 961 if (i_am_root) { 962 struct group *grp = NULL; 963 struct passwd *pwd = NULL; 964 int use_rlimit = 1; 965 966 #ifdef HAVE_VALGRIND_VALGRIND_H 967 if (RUNNING_ON_VALGRIND) use_rlimit = 0; 968 #endif 969 970 #ifdef HAVE_GETRLIMIT 971 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) { 972 log_error_write(srv, __FILE__, __LINE__, 973 "ss", "couldn't get 'max filedescriptors'", 974 strerror(errno)); 975 return -1; 976 } 977 978 if (use_rlimit && srv->srvconf.max_fds) { 979 /* set rlimits */ 980 981 rlim.rlim_cur = srv->srvconf.max_fds; 982 rlim.rlim_max = srv->srvconf.max_fds; 983 984 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) { 985 log_error_write(srv, __FILE__, __LINE__, 986 "ss", "couldn't set 'max filedescriptors'", 987 strerror(errno)); 988 return -1; 989 } 990 } 991 992 if (srv->event_handler == FDEVENT_HANDLER_SELECT) { 993 srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200; 994 } else { 995 srv->max_fds = rlim.rlim_cur; 996 } 997 998 /* set core file rlimit, if enable_cores is set */ 999 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) { 1000 rlim.rlim_cur = rlim.rlim_max; 1001 setrlimit(RLIMIT_CORE, &rlim); 1002 } 1003 #endif 1004 if (srv->event_handler == FDEVENT_HANDLER_SELECT) { 1005 /* don't raise the limit above FD_SET_SIZE */ 1006 if (srv->max_fds > ((int)FD_SETSIZE) - 200) { 1007 log_error_write(srv, __FILE__, __LINE__, "sd", 1008 "can't raise max filedescriptors above", FD_SETSIZE - 200, 1009 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds."); 1010 return -1; 1011 } 1012 } 1013 1014 1015 #ifdef HAVE_PWD_H 1016 /* set user and group */ 1017 if (!buffer_string_is_empty(srv->srvconf.username)) { 1018 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) { 1019 log_error_write(srv, __FILE__, __LINE__, "sb", 1020 "can't find username", srv->srvconf.username); 1021 return -1; 1022 } 1023 1024 if (pwd->pw_uid == 0) { 1025 log_error_write(srv, __FILE__, __LINE__, "s", 1026 "I will not set uid to 0\n"); 1027 return -1; 1028 } 1029 } 1030 1031 if (!buffer_string_is_empty(srv->srvconf.groupname)) { 1032 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) { 1033 log_error_write(srv, __FILE__, __LINE__, "sb", 1034 "can't find groupname", srv->srvconf.groupname); 1035 return -1; 1036 } 1037 if (grp->gr_gid == 0) { 1038 log_error_write(srv, __FILE__, __LINE__, "s", 1039 "I will not set gid to 0\n"); 1040 return -1; 1041 } 1042 } 1043 #endif 1044 /* we need root-perms for port < 1024 */ 1045 if (0 != network_init(srv)) { 1046 plugins_free(srv); 1047 server_free(srv); 1048 1049 return -1; 1050 } 1051 #ifdef HAVE_PWD_H 1052 /* 1053 * Change group before chroot, when we have access 1054 * to /etc/group 1055 * */ 1056 if (NULL != grp) { 1057 if (-1 == setgid(grp->gr_gid)) { 1058 log_error_write(srv, __FILE__, __LINE__, "ss", "setgid failed: ", strerror(errno)); 1059 return -1; 1060 } 1061 if (-1 == setgroups(0, NULL)) { 1062 log_error_write(srv, __FILE__, __LINE__, "ss", "setgroups failed: ", strerror(errno)); 1063 return -1; 1064 } 1065 if (!buffer_string_is_empty(srv->srvconf.username)) { 1066 initgroups(srv->srvconf.username->ptr, grp->gr_gid); 1067 } 1068 } 1069 #endif 1070 #ifdef HAVE_CHROOT 1071 if (!buffer_string_is_empty(srv->srvconf.changeroot)) { 1072 tzset(); 1073 1074 if (-1 == chroot(srv->srvconf.changeroot->ptr)) { 1075 log_error_write(srv, __FILE__, __LINE__, "ss", "chroot failed: ", strerror(errno)); 1076 return -1; 1077 } 1078 if (-1 == chdir("/")) { 1079 log_error_write(srv, __FILE__, __LINE__, "ss", "chdir failed: ", strerror(errno)); 1080 return -1; 1081 } 1082 } 1083 #endif 1084 #ifdef HAVE_PWD_H 1085 /* drop root privs */ 1086 if (NULL != pwd) { 1087 if (-1 == setuid(pwd->pw_uid)) { 1088 log_error_write(srv, __FILE__, __LINE__, "ss", "setuid failed: ", strerror(errno)); 1089 return -1; 1090 } 1091 } 1092 #endif 1093 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE) 1094 /** 1095 * on IRIX 6.5.30 they have prctl() but no DUMPABLE 1096 */ 1097 if (srv->srvconf.enable_cores) { 1098 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); 1099 } 1100 #endif 1101 } else { 1102 1103 #ifdef HAVE_GETRLIMIT 1104 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) { 1105 log_error_write(srv, __FILE__, __LINE__, 1106 "ss", "couldn't get 'max filedescriptors'", 1107 strerror(errno)); 1108 return -1; 1109 } 1110 1111 /** 1112 * we are not root can can't increase the fd-limit above rlim_max, but we can reduce it 1113 */ 1114 if (srv->srvconf.max_fds && srv->srvconf.max_fds <= rlim.rlim_max) { 1115 /* set rlimits */ 1116 1117 rlim.rlim_cur = srv->srvconf.max_fds; 1118 1119 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) { 1120 log_error_write(srv, __FILE__, __LINE__, 1121 "ss", "couldn't set 'max filedescriptors'", 1122 strerror(errno)); 1123 return -1; 1124 } 1125 } 1126 1127 if (srv->event_handler == FDEVENT_HANDLER_SELECT) { 1128 srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200; 1129 } else { 1130 srv->max_fds = rlim.rlim_cur; 1131 } 1132 1133 /* set core file rlimit, if enable_cores is set */ 1134 if (srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) { 1135 rlim.rlim_cur = rlim.rlim_max; 1136 setrlimit(RLIMIT_CORE, &rlim); 1137 } 1138 1139 #endif 1140 if (srv->event_handler == FDEVENT_HANDLER_SELECT) { 1141 /* don't raise the limit above FD_SET_SIZE */ 1142 if (srv->max_fds > ((int)FD_SETSIZE) - 200) { 1143 log_error_write(srv, __FILE__, __LINE__, "sd", 1144 "can't raise max filedescriptors above", FD_SETSIZE - 200, 1145 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds."); 1146 return -1; 1147 } 1148 } 1149 1150 if (0 != network_init(srv)) { 1151 plugins_free(srv); 1152 server_free(srv); 1153 1154 return -1; 1155 } 1156 } 1157 1158 /* set max-conns */ 1159 if (srv->srvconf.max_conns > srv->max_fds/2) { 1160 /* we can't have more connections than max-fds/2 */ 1161 log_error_write(srv, __FILE__, __LINE__, "sdd", "can't have more connections than fds/2: ", srv->srvconf.max_conns, srv->max_fds); 1162 srv->max_conns = srv->max_fds/2; 1163 } else if (srv->srvconf.max_conns) { 1164 /* otherwise respect the wishes of the user */ 1165 srv->max_conns = srv->srvconf.max_conns; 1166 } else { 1167 /* or use the default: we really don't want to hit max-fds */ 1168 srv->max_conns = srv->max_fds/3; 1169 } 1170 1171 if (HANDLER_GO_ON != plugins_call_init(srv)) { 1172 log_error_write(srv, __FILE__, __LINE__, "s", "Initialization of plugins failed. Going down."); 1173 1174 plugins_free(srv); 1175 network_close(srv); 1176 server_free(srv); 1177 1178 return -1; 1179 } 1180 1181 #ifdef HAVE_FORK 1182 /* network is up, let's deamonize ourself */ 1183 if (srv->srvconf.dont_daemonize == 0) { 1184 parent_pipe_fd = daemonize(); 1185 } 1186 #endif 1187 1188 1189 #ifdef HAVE_SIGACTION 1190 memset(&act, 0, sizeof(act)); 1191 act.sa_handler = SIG_IGN; 1192 sigaction(SIGPIPE, &act, NULL); 1193 sigaction(SIGUSR1, &act, NULL); 1194 # if defined(SA_SIGINFO) 1195 act.sa_sigaction = sigaction_handler; 1196 sigemptyset(&act.sa_mask); 1197 act.sa_flags = SA_SIGINFO; 1198 # else 1199 act.sa_handler = signal_handler; 1200 sigemptyset(&act.sa_mask); 1201 act.sa_flags = 0; 1202 # endif 1203 sigaction(SIGINT, &act, NULL); 1204 sigaction(SIGTERM, &act, NULL); 1205 sigaction(SIGHUP, &act, NULL); 1206 sigaction(SIGALRM, &act, NULL); 1207 1208 /* it should be safe to restart syscalls after SIGCHLD */ 1209 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP; 1210 sigaction(SIGCHLD, &act, NULL); 1211 1212 #elif defined(HAVE_SIGNAL) 1213 /* ignore the SIGPIPE from sendfile() */ 1214 signal(SIGPIPE, SIG_IGN); 1215 signal(SIGUSR1, SIG_IGN); 1216 signal(SIGALRM, signal_handler); 1217 signal(SIGTERM, signal_handler); 1218 signal(SIGHUP, signal_handler); 1219 signal(SIGCHLD, signal_handler); 1220 signal(SIGINT, signal_handler); 1221 #endif 1222 1223 #ifdef USE_ALARM 1224 signal(SIGALRM, signal_handler); 1225 1226 /* setup periodic timer (1 second) */ 1227 if (setitimer(ITIMER_REAL, &interval, NULL)) { 1228 log_error_write(srv, __FILE__, __LINE__, "s", "setting timer failed"); 1229 return -1; 1230 } 1231 1232 getitimer(ITIMER_REAL, &interval); 1233 #endif 1234 1235 1236 srv->gid = getgid(); 1237 srv->uid = getuid(); 1238 1239 /* write pid file */ 1240 if (pid_fd != -1) { 1241 buffer_copy_int(srv->tmp_buf, getpid()); 1242 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\n")); 1243 if (-1 == write_all(pid_fd, CONST_BUF_LEN(srv->tmp_buf))) { 1244 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't write pid file:", strerror(errno)); 1245 close(pid_fd); 1246 return -1; 1247 } 1248 } 1249 1250 /* Close stderr ASAP in the child process to make sure that nothing 1251 * is being written to that fd which may not be valid anymore. */ 1252 if (!srv->srvconf.preflight_check && -1 == log_error_open(srv)) { 1253 log_error_write(srv, __FILE__, __LINE__, "s", "Opening errorlog failed. Going down."); 1254 1255 plugins_free(srv); 1256 network_close(srv); 1257 server_free(srv); 1258 return -1; 1259 } 1260 1261 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) { 1262 log_error_write(srv, __FILE__, __LINE__, "s", "Configuration of plugins failed. Going down."); 1263 1264 plugins_free(srv); 1265 network_close(srv); 1266 server_free(srv); 1267 1268 return -1; 1269 } 1270 1271 /* dump unused config-keys */ 1272 for (i = 0; i < srv->config_context->used; i++) { 1273 array *config = ((data_config *)srv->config_context->data[i])->value; 1274 size_t j; 1275 1276 for (j = 0; config && j < config->used; j++) { 1277 data_unset *du = config->data[j]; 1278 1279 /* all var.* is known as user defined variable */ 1280 if (strncmp(du->key->ptr, "var.", sizeof("var.") - 1) == 0) { 1281 continue; 1282 } 1283 1284 if (NULL == array_get_element(srv->config_touched, du->key->ptr)) { 1285 log_error_write(srv, __FILE__, __LINE__, "sbs", 1286 "WARNING: unknown config-key:", 1287 du->key, 1288 "(ignored)"); 1289 } 1290 } 1291 } 1292 1293 if (srv->config_unsupported) { 1294 log_error_write(srv, __FILE__, __LINE__, "s", 1295 "Configuration contains unsupported keys. Going down."); 1296 } 1297 1298 if (srv->config_deprecated) { 1299 log_error_write(srv, __FILE__, __LINE__, "s", 1300 "Configuration contains deprecated keys. Going down."); 1301 } 1302 1303 if (srv->config_unsupported || srv->config_deprecated) { 1304 plugins_free(srv); 1305 network_close(srv); 1306 server_free(srv); 1307 1308 return -1; 1309 } 1310 1311 if (srv->srvconf.preflight_check) { 1312 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/ 1313 plugins_free(srv); 1314 network_close(srv); 1315 server_free(srv); 1316 1317 exit(0); 1318 } 1319 1320 1321 #ifdef HAVE_FORK 1322 /** 1323 * notify daemonize-grandparent of successful startup 1324 * do this before any further forking is done (workers) 1325 */ 1326 if (srv->srvconf.dont_daemonize == 0) { 1327 if (0 > write(parent_pipe_fd, "", 1)) return -1; 1328 close(parent_pipe_fd); 1329 } 1330 1331 if (idle_limit && srv->srvconf.max_worker) { 1332 srv->srvconf.max_worker = 0; 1333 log_error_write(srv, __FILE__, __LINE__, "s", 1334 "server idle time limit command line option disables server.max-worker config file option."); 1335 } 1336 1337 /* start watcher and workers */ 1338 num_childs = srv->srvconf.max_worker; 1339 if (num_childs > 0) { 1340 int child = 0; 1341 while (!child && !srv_shutdown && !graceful_shutdown) { 1342 if (num_childs > 0) { 1343 switch (fork()) { 1344 case -1: 1345 return -1; 1346 case 0: 1347 child = 1; 1348 break; 1349 default: 1350 num_childs--; 1351 break; 1352 } 1353 } else { 1354 int status; 1355 1356 if (-1 != wait(&status)) { 1357 /** 1358 * one of our workers went away 1359 */ 1360 num_childs++; 1361 } else { 1362 switch (errno) { 1363 case EINTR: 1364 /** 1365 * if we receive a SIGHUP we have to close our logs ourself as we don't 1366 * have the mainloop who can help us here 1367 */ 1368 if (handle_sig_hup) { 1369 handle_sig_hup = 0; 1370 1371 log_error_cycle(srv); 1372 1373 /** 1374 * forward to all procs in the process-group 1375 * 1376 * we also send it ourself 1377 */ 1378 if (!forwarded_sig_hup && 0 != srv->srvconf.max_worker) { 1379 forwarded_sig_hup = 1; 1380 kill(0, SIGHUP); 1381 } 1382 } 1383 break; 1384 default: 1385 break; 1386 } 1387 } 1388 } 1389 } 1390 1391 /** 1392 * for the parent this is the exit-point 1393 */ 1394 if (!child) { 1395 /** 1396 * kill all children too 1397 */ 1398 if (graceful_shutdown) { 1399 kill(0, SIGINT); 1400 } else if (srv_shutdown) { 1401 kill(0, SIGTERM); 1402 } 1403 1404 remove_pid_file(srv, &pid_fd); 1405 log_error_close(srv); 1406 network_close(srv); 1407 connections_free(srv); 1408 plugins_free(srv); 1409 server_free(srv); 1410 return 0; 1411 } 1412 1413 /** 1414 * make sure workers do not muck with pid-file 1415 */ 1416 if (0 <= pid_fd) { 1417 close(pid_fd); 1418 pid_fd = -1; 1419 } 1420 buffer_reset(srv->srvconf.pid_file); 1421 } 1422 #endif 1423 1424 if (NULL == (srv->ev = fdevent_init(srv, srv->max_fds + 1, srv->event_handler))) { 1425 log_error_write(srv, __FILE__, __LINE__, 1426 "s", "fdevent_init failed"); 1427 return -1; 1428 } 1429 1430 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */ 1431 #ifdef HAVE_SIGACTION 1432 sigaction(SIGCHLD, &act, NULL); 1433 #elif defined(HAVE_SIGNAL) 1434 signal(SIGCHLD, signal_handler); 1435 #endif 1436 1437 /* 1438 * kqueue() is called here, select resets its internals, 1439 * all server sockets get their handlers 1440 * 1441 * */ 1442 if (0 != network_register_fdevents(srv)) { 1443 plugins_free(srv); 1444 network_close(srv); 1445 server_free(srv); 1446 1447 return -1; 1448 } 1449 1450 /* might fail if user is using fam (not gamin) and famd isn't running */ 1451 if (NULL == (srv->stat_cache = stat_cache_init())) { 1452 log_error_write(srv, __FILE__, __LINE__, "s", 1453 "stat-cache could not be setup, dieing."); 1454 return -1; 1455 } 1456 1457 #ifdef HAVE_FAM_H 1458 /* setup FAM */ 1459 if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_FAM) { 1460 if (0 != FAMOpen2(&srv->stat_cache->fam, "lighttpd")) { 1461 log_error_write(srv, __FILE__, __LINE__, "s", 1462 "could not open a fam connection, dieing."); 1463 return -1; 1464 } 1465 #ifdef HAVE_FAMNOEXISTS 1466 FAMNoExists(&srv->stat_cache->fam); 1467 #endif 1468 1469 fdevent_register(srv->ev, FAMCONNECTION_GETFD(&srv->stat_cache->fam), stat_cache_handle_fdevent, NULL); 1470 fdevent_event_set(srv->ev, &(srv->stat_cache->fam_fcce_ndx), FAMCONNECTION_GETFD(&srv->stat_cache->fam), FDEVENT_IN); 1471 } 1472 #endif 1473 1474 1475 /* get the current number of FDs */ 1476 srv->cur_fds = open("/dev/null", O_RDONLY); 1477 close(srv->cur_fds); 1478 1479 for (i = 0; i < srv->srv_sockets.used; i++) { 1480 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 1481 if (srv->sockets_disabled) continue; /* lighttpd -1 (one-shot mode) */ 1482 if (-1 == fdevent_fcntl_set(srv->ev, srv_socket->fd)) { 1483 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed:", strerror(errno)); 1484 return -1; 1485 } 1486 } 1487 1488 if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) { 1489 oneshot_fd = -1; 1490 } 1491 1492 /* main-loop */ 1493 while (!srv_shutdown) { 1494 int n; 1495 size_t ndx; 1496 time_t min_ts; 1497 1498 if (handle_sig_hup) { 1499 handler_t r; 1500 1501 /* reset notification */ 1502 handle_sig_hup = 0; 1503 1504 1505 /* cycle logfiles */ 1506 1507 switch(r = plugins_call_handle_sighup(srv)) { 1508 case HANDLER_GO_ON: 1509 break; 1510 default: 1511 log_error_write(srv, __FILE__, __LINE__, "sd", "sighup-handler return with an error", r); 1512 break; 1513 } 1514 1515 if (-1 == log_error_cycle(srv)) { 1516 log_error_write(srv, __FILE__, __LINE__, "s", "cycling errorlog failed, dying"); 1517 1518 return -1; 1519 } else { 1520 #ifdef HAVE_SIGACTION 1521 log_error_write(srv, __FILE__, __LINE__, "sdsd", 1522 "logfiles cycled UID =", 1523 last_sighup_info.si_uid, 1524 "PID =", 1525 last_sighup_info.si_pid); 1526 #else 1527 log_error_write(srv, __FILE__, __LINE__, "s", 1528 "logfiles cycled"); 1529 #endif 1530 } 1531 } 1532 1533 if (handle_sig_alarm) { 1534 /* a new second */ 1535 1536 #ifdef USE_ALARM 1537 /* reset notification */ 1538 handle_sig_alarm = 0; 1539 #endif 1540 1541 /* get current time */ 1542 min_ts = time(NULL); 1543 1544 if (min_ts != srv->cur_ts) { 1545 #ifdef DEBUG_CONNECTION_STATES 1546 int cs = 0; 1547 #endif 1548 connections *conns = srv->conns; 1549 handler_t r; 1550 1551 switch(r = plugins_call_handle_trigger(srv)) { 1552 case HANDLER_GO_ON: 1553 break; 1554 case HANDLER_ERROR: 1555 log_error_write(srv, __FILE__, __LINE__, "s", "one of the triggers failed"); 1556 break; 1557 default: 1558 log_error_write(srv, __FILE__, __LINE__, "d", r); 1559 break; 1560 } 1561 1562 /* trigger waitpid */ 1563 srv->cur_ts = min_ts; 1564 1565 /* check idle time limit, if enabled */ 1566 if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) { 1567 log_error_write(srv, __FILE__, __LINE__, "sDs", "[note] idle timeout", (int)idle_limit, 1568 "s exceeded, initiating graceful shutdown"); 1569 graceful_shutdown = 2; /* value 2 indicates idle timeout */ 1570 } 1571 1572 /* cleanup stat-cache */ 1573 stat_cache_trigger_cleanup(srv); 1574 /** 1575 * check all connections for timeouts 1576 * 1577 */ 1578 for (ndx = 0; ndx < conns->used; ndx++) { 1579 int changed = 0; 1580 connection *con; 1581 int t_diff; 1582 1583 con = conns->ptr[ndx]; 1584 1585 if (con->state == CON_STATE_READ || 1586 con->state == CON_STATE_READ_POST) { 1587 if (con->request_count == 1 || con->state == CON_STATE_READ_POST) { 1588 if (srv->cur_ts - con->read_idle_ts > con->conf.max_read_idle) { 1589 /* time - out */ 1590 if (con->conf.log_request_handling) { 1591 log_error_write(srv, __FILE__, __LINE__, "sd", 1592 "connection closed - read timeout:", con->fd); 1593 } 1594 1595 connection_set_state(srv, con, CON_STATE_ERROR); 1596 changed = 1; 1597 } 1598 } else { 1599 if (srv->cur_ts - con->read_idle_ts > con->keep_alive_idle) { 1600 /* time - out */ 1601 if (con->conf.log_request_handling) { 1602 log_error_write(srv, __FILE__, __LINE__, "sd", 1603 "connection closed - keep-alive timeout:", con->fd); 1604 } 1605 1606 connection_set_state(srv, con, CON_STATE_ERROR); 1607 changed = 1; 1608 } 1609 } 1610 } 1611 1612 if ((con->state == CON_STATE_WRITE) && 1613 (con->write_request_ts != 0)) { 1614 #if 0 1615 if (srv->cur_ts - con->write_request_ts > 60) { 1616 log_error_write(srv, __FILE__, __LINE__, "sdd", 1617 "connection closed - pre-write-request-timeout:", con->fd, srv->cur_ts - con->write_request_ts); 1618 } 1619 #endif 1620 1621 if (srv->cur_ts - con->write_request_ts > con->conf.max_write_idle) { 1622 /* time - out */ 1623 if (con->conf.log_timeouts) { 1624 log_error_write(srv, __FILE__, __LINE__, "sbsbsosds", 1625 "NOTE: a request from", 1626 con->dst_addr_buf, 1627 "for", 1628 con->request.uri, 1629 "timed out after writing", 1630 con->bytes_written, 1631 "bytes. We waited", 1632 (int)con->conf.max_write_idle, 1633 "seconds. If this a problem increase server.max-write-idle"); 1634 } 1635 connection_set_state(srv, con, CON_STATE_ERROR); 1636 changed = 1; 1637 } 1638 } 1639 1640 if (con->state == CON_STATE_CLOSE && (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT)) { 1641 changed = 1; 1642 } 1643 1644 /* we don't like div by zero */ 1645 if (0 == (t_diff = srv->cur_ts - con->connection_start)) t_diff = 1; 1646 1647 if (con->traffic_limit_reached && 1648 (con->conf.kbytes_per_second == 0 || 1649 ((con->bytes_written / t_diff) < con->conf.kbytes_per_second * 1024))) { 1650 /* enable connection again */ 1651 con->traffic_limit_reached = 0; 1652 1653 changed = 1; 1654 } 1655 1656 if (changed) { 1657 connection_state_machine(srv, con); 1658 } 1659 con->bytes_written_cur_second = 0; 1660 *(con->conf.global_bytes_per_second_cnt_ptr) = 0; 1661 1662 #if DEBUG_CONNECTION_STATES 1663 if (cs == 0) { 1664 fprintf(stderr, "connection-state: "); 1665 cs = 1; 1666 } 1667 1668 fprintf(stderr, "c[%d,%d]: %s ", 1669 con->fd, 1670 con->fcgi.fd, 1671 connection_get_state(con->state)); 1672 #endif 1673 } 1674 1675 #ifdef DEBUG_CONNECTION_STATES 1676 if (cs == 1) fprintf(stderr, "\n"); 1677 #endif 1678 } 1679 } 1680 1681 if (srv->sockets_disabled) { 1682 /* our server sockets are disabled, why ? */ 1683 1684 if ((srv->cur_fds + srv->want_fds < srv->max_fds * 8 / 10) && /* we have enough unused fds */ 1685 (srv->conns->used <= srv->max_conns * 9 / 10) && 1686 (0 == graceful_shutdown)) { 1687 for (i = 0; i < srv->srv_sockets.used; i++) { 1688 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 1689 fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, FDEVENT_IN); 1690 } 1691 1692 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets enabled again"); 1693 1694 srv->sockets_disabled = 0; 1695 } 1696 } else { 1697 if ((srv->cur_fds + srv->want_fds > srv->max_fds * 9 / 10) || /* out of fds */ 1698 (srv->conns->used >= srv->max_conns) || /* out of connections */ 1699 (graceful_shutdown)) { /* graceful_shutdown */ 1700 1701 /* disable server-fds */ 1702 1703 for (i = 0; i < srv->srv_sockets.used; i++) { 1704 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 1705 1706 if (graceful_shutdown) { 1707 /* we don't want this socket anymore, 1708 * 1709 * closing it right away will make it possible for 1710 * the next lighttpd to take over (graceful restart) 1711 * */ 1712 1713 fdevent_event_del(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd); 1714 fdevent_unregister(srv->ev, srv_socket->fd); 1715 close(srv_socket->fd); 1716 srv_socket->fd = -1; 1717 1718 /* network_close() will cleanup after us */ 1719 } else { 1720 fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, 0); 1721 } 1722 } 1723 1724 if (graceful_shutdown) { 1725 remove_pid_file(srv, &pid_fd); 1726 log_error_write(srv, __FILE__, __LINE__, "s", "[note] graceful shutdown started"); 1727 } else if (srv->conns->used >= srv->max_conns) { 1728 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, connection limit reached"); 1729 } else { 1730 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, out-of-fds"); 1731 } 1732 1733 srv->sockets_disabled = 1; 1734 } 1735 } 1736 1737 if (graceful_shutdown && srv->conns->used == 0) { 1738 /* we are in graceful shutdown phase and all connections are closed 1739 * we are ready to terminate without harming anyone */ 1740 srv_shutdown = 1; 1741 } 1742 1743 /* we still have some fds to share */ 1744 if (srv->want_fds) { 1745 /* check the fdwaitqueue for waiting fds */ 1746 int free_fds = srv->max_fds - srv->cur_fds - 16; 1747 connection *con; 1748 1749 for (; free_fds > 0 && NULL != (con = fdwaitqueue_unshift(srv, srv->fdwaitqueue)); free_fds--) { 1750 connection_state_machine(srv, con); 1751 1752 srv->want_fds--; 1753 } 1754 } 1755 1756 if ((n = fdevent_poll(srv->ev, 1000)) > 0) { 1757 /* n is the number of events */ 1758 int revents; 1759 int fd_ndx; 1760 #if 0 1761 if (n > 0) { 1762 log_error_write(srv, __FILE__, __LINE__, "sd", 1763 "polls:", n); 1764 } 1765 #endif 1766 last_active_ts = srv->cur_ts; 1767 fd_ndx = -1; 1768 do { 1769 fdevent_handler handler; 1770 void *context; 1771 handler_t r; 1772 1773 fd_ndx = fdevent_event_next_fdndx (srv->ev, fd_ndx); 1774 if (-1 == fd_ndx) break; /* not all fdevent handlers know how many fds got an event */ 1775 1776 revents = fdevent_event_get_revent (srv->ev, fd_ndx); 1777 fd = fdevent_event_get_fd (srv->ev, fd_ndx); 1778 handler = fdevent_get_handler(srv->ev, fd); 1779 context = fdevent_get_context(srv->ev, fd); 1780 1781 /* connection_handle_fdevent needs a joblist_append */ 1782 #if 0 1783 log_error_write(srv, __FILE__, __LINE__, "sdd", 1784 "event for", fd, revents); 1785 #endif 1786 switch (r = (*handler)(srv, context, revents)) { 1787 case HANDLER_FINISHED: 1788 case HANDLER_GO_ON: 1789 case HANDLER_WAIT_FOR_EVENT: 1790 case HANDLER_WAIT_FOR_FD: 1791 break; 1792 case HANDLER_ERROR: 1793 /* should never happen */ 1794 SEGFAULT(); 1795 break; 1796 default: 1797 log_error_write(srv, __FILE__, __LINE__, "d", r); 1798 break; 1799 } 1800 } while (--n > 0); 1801 } else if (n < 0 && errno != EINTR) { 1802 log_error_write(srv, __FILE__, __LINE__, "ss", 1803 "fdevent_poll failed:", 1804 strerror(errno)); 1805 } 1806 1807 for (ndx = 0; ndx < srv->joblist->used; ndx++) { 1808 connection *con = srv->joblist->ptr[ndx]; 1809 connection_state_machine(srv, con); 1810 con->in_joblist = 0; 1811 } 1812 1813 srv->joblist->used = 0; 1814 } 1815 1816 if (0 == graceful_shutdown) { 1817 remove_pid_file(srv, &pid_fd); 1818 } 1819 1820 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */ 1821 log_error_write(srv, __FILE__, __LINE__, "s", 1822 "server stopped after idle timeout"); 1823 } else { 1824 #ifdef HAVE_SIGACTION 1825 log_error_write(srv, __FILE__, __LINE__, "sdsd", 1826 "server stopped by UID =", 1827 last_sigterm_info.si_uid, 1828 "PID =", 1829 last_sigterm_info.si_pid); 1830 #else 1831 log_error_write(srv, __FILE__, __LINE__, "s", 1832 "server stopped"); 1833 #endif 1834 } 1835 1836 /* clean-up */ 1837 log_error_close(srv); 1838 network_close(srv); 1839 connections_free(srv); 1840 plugins_free(srv); 1841 server_free(srv); 1842 1843 return 0; 1844 } 1845