[mod_cgi] fix pipe_cloexec() when no O_CLOEXEC
[lighttpd.git] / src / server.c
blob01f10d87e59415c26725183249194035b2de3f42
1 #include "first.h"
3 #include "server.h"
4 #include "buffer.h"
5 #include "network.h"
6 #include "log.h"
7 #include "keyvalue.h"
8 #include "rand.h"
9 #include "response.h"
10 #include "request.h"
11 #include "chunk.h"
12 #include "http_chunk.h"
13 #include "fdevent.h"
14 #include "connections.h"
15 #include "stat_cache.h"
16 #include "plugin.h"
17 #include "joblist.h"
18 #include "network_backends.h"
19 #include "version.h"
21 #include <sys/types.h>
22 #include <sys/time.h>
23 #include <sys/stat.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <time.h>
31 #include <signal.h>
32 #include <assert.h>
33 #include <locale.h>
35 #include <stdio.h>
37 #ifdef HAVE_GETOPT_H
38 # include <getopt.h>
39 #endif
41 #ifdef HAVE_VALGRIND_VALGRIND_H
42 # include <valgrind/valgrind.h>
43 #endif
45 #ifdef HAVE_SYS_WAIT_H
46 # include <sys/wait.h>
47 #endif
49 #ifdef HAVE_PWD_H
50 # include <grp.h>
51 # include <pwd.h>
52 #endif
54 #ifdef HAVE_SYS_RESOURCE_H
55 # include <sys/resource.h>
56 #endif
58 #ifdef HAVE_SYS_PRCTL_H
59 # include <sys/prctl.h>
60 #endif
62 #ifdef USE_OPENSSL
63 # include <openssl/err.h>
64 #endif
66 #ifndef __sgi
67 /* IRIX doesn't like the alarm based time() optimization */
68 /* #define USE_ALARM */
69 #endif
71 #ifdef HAVE_GETUID
72 # ifndef HAVE_ISSETUGID
74 static int l_issetugid(void) {
75 return (geteuid() != getuid() || getegid() != getgid());
78 # define issetugid l_issetugid
79 # endif
80 #endif
82 static int oneshot_fd = 0;
83 static volatile sig_atomic_t srv_shutdown = 0;
84 static volatile sig_atomic_t graceful_shutdown = 0;
85 static volatile sig_atomic_t handle_sig_alarm = 1;
86 static volatile sig_atomic_t handle_sig_hup = 0;
87 static volatile sig_atomic_t forwarded_sig_hup = 0;
89 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
90 static volatile siginfo_t last_sigterm_info;
91 static volatile siginfo_t last_sighup_info;
93 static void sigaction_handler(int sig, siginfo_t *si, void *context) {
94 static siginfo_t empty_siginfo;
95 UNUSED(context);
97 if (!si) si = &empty_siginfo;
99 switch (sig) {
100 case SIGTERM:
101 srv_shutdown = 1;
102 last_sigterm_info = *si;
103 break;
104 case SIGINT:
105 if (graceful_shutdown) {
106 srv_shutdown = 1;
107 } else {
108 graceful_shutdown = 1;
110 last_sigterm_info = *si;
112 break;
113 case SIGALRM:
114 handle_sig_alarm = 1;
115 break;
116 case SIGHUP:
117 /**
118 * we send the SIGHUP to all procs in the process-group
119 * this includes ourself
121 * make sure we only send it once and don't create a
122 * infinite loop
124 if (!forwarded_sig_hup) {
125 handle_sig_hup = 1;
126 last_sighup_info = *si;
127 } else {
128 forwarded_sig_hup = 0;
130 break;
131 case SIGCHLD:
132 break;
135 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
136 static void signal_handler(int sig) {
137 switch (sig) {
138 case SIGTERM: srv_shutdown = 1; break;
139 case SIGINT:
140 if (graceful_shutdown) srv_shutdown = 1;
141 else graceful_shutdown = 1;
143 break;
144 case SIGALRM: handle_sig_alarm = 1; break;
145 case SIGHUP: handle_sig_hup = 1; break;
146 case SIGCHLD: break;
149 #endif
151 #ifdef HAVE_FORK
152 static int daemonize(void) {
153 int pipefd[2];
154 pid_t pid;
155 #ifdef SIGTTOU
156 signal(SIGTTOU, SIG_IGN);
157 #endif
158 #ifdef SIGTTIN
159 signal(SIGTTIN, SIG_IGN);
160 #endif
161 #ifdef SIGTSTP
162 signal(SIGTSTP, SIG_IGN);
163 #endif
165 if (pipe(pipefd) < 0) exit(-1);
167 if (0 > (pid = fork())) exit(-1);
169 if (0 < pid) {
170 char buf;
171 ssize_t bytes;
173 close(pipefd[1]);
174 /* parent waits for grandchild to be ready */
175 do {
176 bytes = read(pipefd[0], &buf, sizeof(buf));
177 } while (bytes < 0 && EINTR == errno);
178 close(pipefd[0]);
180 if (bytes <= 0) {
181 /* closed fd (without writing) == failure in grandchild */
182 fputs("daemonized server failed to start; check error log for details\n", stderr);
183 exit(-1);
186 exit(0);
189 close(pipefd[0]);
191 if (-1 == setsid()) exit(0);
193 signal(SIGHUP, SIG_IGN);
195 if (0 != fork()) exit(0);
197 if (0 != chdir("/")) exit(0);
199 fd_close_on_exec(pipefd[1]);
200 return pipefd[1];
202 #endif
204 static server *server_init(void) {
205 int i;
206 server *srv = calloc(1, sizeof(*srv));
207 force_assert(srv);
208 #define CLEAN(x) \
209 srv->x = buffer_init();
211 CLEAN(response_header);
212 CLEAN(parse_full_path);
213 CLEAN(ts_debug_str);
214 CLEAN(ts_date_str);
215 CLEAN(errorlog_buf);
216 CLEAN(response_range);
217 CLEAN(tmp_buf);
218 srv->empty_string = buffer_init_string("");
219 CLEAN(cond_check_buf);
221 CLEAN(srvconf.errorlog_file);
222 CLEAN(srvconf.breakagelog_file);
223 CLEAN(srvconf.groupname);
224 CLEAN(srvconf.username);
225 CLEAN(srvconf.changeroot);
226 CLEAN(srvconf.bindhost);
227 CLEAN(srvconf.event_handler);
228 CLEAN(srvconf.pid_file);
230 CLEAN(tmp_chunk_len);
231 #undef CLEAN
233 #define CLEAN(x) \
234 srv->x = array_init();
236 CLEAN(config_context);
237 CLEAN(config_touched);
238 CLEAN(status);
239 #undef CLEAN
241 for (i = 0; i < FILE_CACHE_MAX; i++) {
242 srv->mtime_cache[i].mtime = (time_t)-1;
243 srv->mtime_cache[i].str = buffer_init();
246 li_rand_reseed();
247 li_rand_bytes((unsigned char *)srv->entropy, (int)sizeof(srv->entropy));
249 srv->cur_ts = time(NULL);
250 srv->startup_ts = srv->cur_ts;
252 srv->conns = calloc(1, sizeof(*srv->conns));
253 force_assert(srv->conns);
255 srv->joblist = calloc(1, sizeof(*srv->joblist));
256 force_assert(srv->joblist);
258 srv->fdwaitqueue = calloc(1, sizeof(*srv->fdwaitqueue));
259 force_assert(srv->fdwaitqueue);
261 srv->srvconf.modules = array_init();
262 srv->srvconf.modules_dir = buffer_init_string(LIBRARY_DIR);
263 srv->srvconf.network_backend = buffer_init();
264 srv->srvconf.upload_tempdirs = array_init();
265 srv->srvconf.reject_expect_100_with_417 = 1;
266 srv->srvconf.xattr_name = buffer_init_string("Content-Type");
267 srv->srvconf.http_header_strict = 1;
268 srv->srvconf.http_host_strict = 1; /*(implies http_host_normalize)*/
269 srv->srvconf.http_host_normalize = 0;
270 srv->srvconf.high_precision_timestamps = 0;
271 srv->srvconf.max_request_field_size = 8192;
273 /* use syslog */
274 srv->errorlog_fd = STDERR_FILENO;
275 srv->errorlog_mode = ERRORLOG_FD;
277 srv->split_vals = array_init();
279 return srv;
282 static void server_free(server *srv) {
283 size_t i;
285 for (i = 0; i < FILE_CACHE_MAX; i++) {
286 buffer_free(srv->mtime_cache[i].str);
289 if (oneshot_fd > 0) {
290 close(oneshot_fd);
293 #define CLEAN(x) \
294 buffer_free(srv->x);
296 CLEAN(response_header);
297 CLEAN(parse_full_path);
298 CLEAN(ts_debug_str);
299 CLEAN(ts_date_str);
300 CLEAN(errorlog_buf);
301 CLEAN(response_range);
302 CLEAN(tmp_buf);
303 CLEAN(empty_string);
304 CLEAN(cond_check_buf);
306 CLEAN(srvconf.errorlog_file);
307 CLEAN(srvconf.breakagelog_file);
308 CLEAN(srvconf.groupname);
309 CLEAN(srvconf.username);
310 CLEAN(srvconf.changeroot);
311 CLEAN(srvconf.bindhost);
312 CLEAN(srvconf.event_handler);
313 CLEAN(srvconf.pid_file);
314 CLEAN(srvconf.modules_dir);
315 CLEAN(srvconf.network_backend);
316 CLEAN(srvconf.xattr_name);
318 CLEAN(tmp_chunk_len);
319 #undef CLEAN
321 #if 0
322 fdevent_unregister(srv->ev, srv->fd);
323 #endif
324 fdevent_free(srv->ev);
326 free(srv->conns);
328 if (srv->config_storage) {
329 for (i = 0; i < srv->config_context->used; i++) {
330 specific_config *s = srv->config_storage[i];
332 if (!s) continue;
334 buffer_free(s->document_root);
335 buffer_free(s->server_name);
336 buffer_free(s->server_tag);
337 buffer_free(s->ssl_pemfile);
338 buffer_free(s->ssl_ca_file);
339 buffer_free(s->ssl_cipher_list);
340 buffer_free(s->ssl_dh_file);
341 buffer_free(s->ssl_ec_curve);
342 buffer_free(s->error_handler);
343 buffer_free(s->error_handler_404);
344 buffer_free(s->errorfile_prefix);
345 array_free(s->mimetypes);
346 buffer_free(s->ssl_verifyclient_username);
347 #ifdef USE_OPENSSL
348 SSL_CTX_free(s->ssl_ctx);
349 EVP_PKEY_free(s->ssl_pemfile_pkey);
350 X509_free(s->ssl_pemfile_x509);
351 if (NULL != s->ssl_ca_file_cert_names) sk_X509_NAME_pop_free(s->ssl_ca_file_cert_names, X509_NAME_free);
352 #endif
353 free(s);
355 free(srv->config_storage);
356 srv->config_storage = NULL;
359 #define CLEAN(x) \
360 array_free(srv->x);
362 CLEAN(config_context);
363 CLEAN(config_touched);
364 CLEAN(status);
365 CLEAN(srvconf.upload_tempdirs);
366 #undef CLEAN
368 joblist_free(srv, srv->joblist);
369 fdwaitqueue_free(srv, srv->fdwaitqueue);
371 if (srv->stat_cache) {
372 stat_cache_free(srv->stat_cache);
375 array_free(srv->srvconf.modules);
376 array_free(srv->split_vals);
378 #ifdef USE_OPENSSL
379 if (srv->ssl_is_init) {
380 CRYPTO_cleanup_all_ex_data();
381 ERR_free_strings();
382 #if OPENSSL_VERSION_NUMBER >= 0x10100000L \
383 && !defined(LIBRESSL_VERSION_NUMBER)
384 /*(OpenSSL libraries handle thread init and deinit)
385 * https://github.com/openssl/openssl/pull/1048 */
386 #elif OPENSSL_VERSION_NUMBER >= 0x10000000L
387 ERR_remove_thread_state(NULL);
388 #else
389 ERR_remove_state(0);
390 #endif
391 EVP_cleanup();
393 #endif
394 li_rand_cleanup();
396 free(srv);
399 static void remove_pid_file(server *srv, int *pid_fd) {
400 if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= *pid_fd) {
401 if (0 != ftruncate(*pid_fd, 0)) {
402 log_error_write(srv, __FILE__, __LINE__, "sbds",
403 "ftruncate failed for:",
404 srv->srvconf.pid_file,
405 errno,
406 strerror(errno));
409 if (0 <= *pid_fd) {
410 close(*pid_fd);
411 *pid_fd = -1;
413 if (!buffer_string_is_empty(srv->srvconf.pid_file) &&
414 buffer_string_is_empty(srv->srvconf.changeroot)) {
415 if (0 != unlink(srv->srvconf.pid_file->ptr)) {
416 if (errno != EACCES && errno != EPERM) {
417 log_error_write(srv, __FILE__, __LINE__, "sbds",
418 "unlink failed for:",
419 srv->srvconf.pid_file,
420 errno,
421 strerror(errno));
428 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) {
429 server_socket *srv_socket, *srv_socket_wild = NULL;
430 size_t i;
431 for (i = 0; i < srv->srv_sockets.used; ++i) {
432 srv_socket = srv->srv_sockets.ptr[i];
433 if (cnt_addr->plain.sa_family != srv_socket->addr.plain.sa_family) continue;
434 switch (cnt_addr->plain.sa_family) {
435 case AF_INET:
436 if (srv_socket->addr.ipv4.sin_port != cnt_addr->ipv4.sin_port) continue;
437 if (srv_socket->addr.ipv4.sin_addr.s_addr == cnt_addr->ipv4.sin_addr.s_addr) {
438 return srv_socket;
440 if (srv_socket->addr.ipv4.sin_addr.s_addr == htonl(INADDR_ANY)) {
441 srv_socket_wild = srv_socket;
443 continue;
444 #ifdef HAVE_IPV6
445 case AF_INET6:
446 if (srv_socket->addr.ipv6.sin6_port != cnt_addr->ipv6.sin6_port) continue;
447 if (0 == memcmp(&srv_socket->addr.ipv6.sin6_addr, &cnt_addr->ipv6.sin6_addr, sizeof(struct in6_addr))) {
448 return srv_socket;
450 if (0 == memcmp(&srv_socket->addr.ipv6.sin6_addr, &in6addr_any, sizeof(struct in6_addr))) {
451 srv_socket_wild = srv_socket;
453 continue;
454 #endif
455 #ifdef HAVE_SYS_UN_H
456 case AF_UNIX:
457 if (0 == strcmp(srv_socket->addr.un.sun_path, cnt_addr->un.sun_path)) {
458 return srv_socket;
460 continue;
461 #endif
462 default: continue;
466 if (NULL != srv_socket_wild) {
467 return srv_socket_wild;
468 } else if (srv->srv_sockets.used) {
469 return srv->srv_sockets.ptr[0];
470 } else {
471 log_error_write(srv, __FILE__, __LINE__, "s", "no sockets configured");
472 return NULL;
477 static int server_oneshot_init(server *srv, int fd) {
478 /* Note: does not work with netcat due to requirement that fd be socket.
479 * STDOUT_FILENO was not saved earlier in startup, and that is to where
480 * netcat expects output to be sent. Since lighttpd expects connections
481 * to be sockets, con->fd is where output is sent; separate fds are not
482 * stored for input and output, but netcat has different fds for stdin
483 * and * stdout. To support netcat, would additionally need to avoid
484 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
485 * addresses from environment variables:
486 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
487 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
488 * NCAT_PROTO
490 connection *con;
491 server_socket *srv_socket;
492 sock_addr cnt_addr;
493 socklen_t cnt_len;
494 struct stat st;
496 if (0 != fstat(fd, &st)) {
497 log_error_write(srv, __FILE__, __LINE__, "ss", "fstat:", strerror(errno));
498 return 0;
501 if (!S_ISSOCK(st.st_mode)) {
502 /* require that fd is a socket
503 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
504 log_error_write(srv, __FILE__, __LINE__, "s", "lighttpd -1 stdin is not a socket");
505 return 0;
508 cnt_len = sizeof(cnt_addr);
509 if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
510 log_error_write(srv, __FILE__, __LINE__, "ss", "getsockname:", strerror(errno));
511 return 0;
514 srv_socket = server_oneshot_getsock(srv, &cnt_addr);
515 if (NULL == srv_socket) return 0;
517 cnt_len = sizeof(cnt_addr);
518 if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
519 log_error_write(srv, __FILE__, __LINE__, "ss", "getpeername:", strerror(errno));
520 return 0;
523 if (cnt_addr.plain.sa_family != AF_UNIX) {
524 network_accept_tcp_nagle_disable(fd);
527 con = connection_accepted(srv, srv_socket, &cnt_addr, fd);
528 if (NULL == con) return 0;
530 connection_state_machine(srv, con);
531 return 1;
535 static void show_version (void) {
536 #ifdef USE_OPENSSL
537 # define TEXT_SSL " (ssl)"
538 #else
539 # define TEXT_SSL
540 #endif
541 char *b = PACKAGE_DESC TEXT_SSL \
542 " - a light and fast webserver\n" \
543 "Build-Date: " __DATE__ " " __TIME__ "\n";
545 #undef TEXT_SSL
546 write_all(STDOUT_FILENO, b, strlen(b));
549 static void show_features (void) {
550 const char features[] = ""
551 #ifdef USE_SELECT
552 "\t+ select (generic)\n"
553 #else
554 "\t- select (generic)\n"
555 #endif
556 #ifdef USE_POLL
557 "\t+ poll (Unix)\n"
558 #else
559 "\t- poll (Unix)\n"
560 #endif
561 #ifdef USE_LINUX_SIGIO
562 "\t+ rt-signals (Linux 2.4+)\n"
563 #else
564 "\t- rt-signals (Linux 2.4+)\n"
565 #endif
566 #ifdef USE_LINUX_EPOLL
567 "\t+ epoll (Linux 2.6)\n"
568 #else
569 "\t- epoll (Linux 2.6)\n"
570 #endif
571 #ifdef USE_SOLARIS_DEVPOLL
572 "\t+ /dev/poll (Solaris)\n"
573 #else
574 "\t- /dev/poll (Solaris)\n"
575 #endif
576 #ifdef USE_SOLARIS_PORT
577 "\t+ eventports (Solaris)\n"
578 #else
579 "\t- eventports (Solaris)\n"
580 #endif
581 #ifdef USE_FREEBSD_KQUEUE
582 "\t+ kqueue (FreeBSD)\n"
583 #else
584 "\t- kqueue (FreeBSD)\n"
585 #endif
586 #ifdef USE_LIBEV
587 "\t+ libev (generic)\n"
588 #else
589 "\t- libev (generic)\n"
590 #endif
591 "\nNetwork handler:\n\n"
592 #if defined USE_LINUX_SENDFILE
593 "\t+ linux-sendfile\n"
594 #else
595 "\t- linux-sendfile\n"
596 #endif
597 #if defined USE_FREEBSD_SENDFILE
598 "\t+ freebsd-sendfile\n"
599 #else
600 "\t- freebsd-sendfile\n"
601 #endif
602 #if defined USE_DARWIN_SENDFILE
603 "\t+ darwin-sendfile\n"
604 #else
605 "\t- darwin-sendfile\n"
606 #endif
607 #if defined USE_SOLARIS_SENDFILEV
608 "\t+ solaris-sendfilev\n"
609 #else
610 "\t- solaris-sendfilev\n"
611 #endif
612 #if defined USE_WRITEV
613 "\t+ writev\n"
614 #else
615 "\t- writev\n"
616 #endif
617 "\t+ write\n"
618 #ifdef USE_MMAP
619 "\t+ mmap support\n"
620 #else
621 "\t- mmap support\n"
622 #endif
623 "\nFeatures:\n\n"
624 #ifdef HAVE_IPV6
625 "\t+ IPv6 support\n"
626 #else
627 "\t- IPv6 support\n"
628 #endif
629 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
630 "\t+ zlib support\n"
631 #else
632 "\t- zlib support\n"
633 #endif
634 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
635 "\t+ bzip2 support\n"
636 #else
637 "\t- bzip2 support\n"
638 #endif
639 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
640 "\t+ crypt support\n"
641 #else
642 "\t- crypt support\n"
643 #endif
644 #ifdef USE_OPENSSL
645 "\t+ SSL Support\n"
646 #else
647 "\t- SSL Support\n"
648 #endif
649 #ifdef HAVE_LIBPCRE
650 "\t+ PCRE support\n"
651 #else
652 "\t- PCRE support\n"
653 #endif
654 #ifdef HAVE_MYSQL
655 "\t+ MySQL support\n"
656 #else
657 "\t- MySQL support\n"
658 #endif
659 #ifdef HAVE_KRB5
660 "\t+ Kerberos support\n"
661 #else
662 "\t- Kerberos support\n"
663 #endif
664 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
665 "\t+ LDAP support\n"
666 #else
667 "\t- LDAP support\n"
668 #endif
669 #ifdef USE_MEMCACHED
670 "\t+ memcached support\n"
671 #else
672 "\t- memcached support\n"
673 #endif
674 #ifdef HAVE_FAM_H
675 "\t+ FAM support\n"
676 #else
677 "\t- FAM support\n"
678 #endif
679 #ifdef HAVE_LUA_H
680 "\t+ LUA support\n"
681 #else
682 "\t- LUA support\n"
683 #endif
684 #ifdef HAVE_LIBXML_H
685 "\t+ xml support\n"
686 #else
687 "\t- xml support\n"
688 #endif
689 #ifdef HAVE_SQLITE3_H
690 "\t+ SQLite support\n"
691 #else
692 "\t- SQLite support\n"
693 #endif
694 #ifdef HAVE_GDBM_H
695 "\t+ GDBM support\n"
696 #else
697 "\t- GDBM support\n"
698 #endif
699 "\n";
700 show_version();
701 printf("\nEvent Handlers:\n\n%s", features);
704 static void show_help (void) {
705 #ifdef USE_OPENSSL
706 # define TEXT_SSL " (ssl)"
707 #else
708 # define TEXT_SSL
709 #endif
710 char *b = PACKAGE_DESC TEXT_SSL " ("__DATE__ " " __TIME__ ")" \
711 " - a light and fast webserver\n" \
712 "usage:\n" \
713 " -f <name> filename of the config-file\n" \
714 " -m <name> module directory (default: "LIBRARY_DIR")\n" \
715 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
716 " -1 process single (one) request on stdin socket, then exit\n" \
717 " -p print the parsed config-file in internal form, and exit\n" \
718 " -t test config-file syntax, then exit\n" \
719 " -tt test config-file syntax, load and init modules, then 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"
726 #undef TEXT_SSL
727 #undef TEXT_IPV6
728 write_all(STDOUT_FILENO, b, strlen(b));
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
748 #ifdef HAVE_FORK
749 int parent_pipe_fd = -1;
750 #endif
752 #ifdef USE_ALARM
753 struct itimerval interval;
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
761 /* for nice %b handling in strfime() */
762 setlocale(LC_TIME, "C");
764 if (NULL == (srv = server_init())) {
765 fprintf(stderr, "did this really happen?\n");
766 return -1;
769 /* init structs done */
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;
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.");
787 server_free(srv);
788 return -1;
790 if (config_read(srv, optarg)) {
791 server_free(srv);
792 return -1;
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;
807 idle_limit = (time_t)timeout;
808 break;
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;
824 if (!srv->config_storage) {
825 log_error_write(srv, __FILE__, __LINE__, "s",
826 "No configuration available. Try using -f option.");
828 server_free(srv);
829 return -1;
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");
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);
854 if (test_config || print_config) {
855 server_free(srv);
856 return 0;
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;
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.");
877 /* close stdin and stdout, as they are not needed */
878 openDevNull(STDIN_FILENO);
879 openDevNull(STDOUT_FILENO);
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;
888 /* UID handling */
889 #ifdef HAVE_GETUID
890 if (!i_am_root && issetugid()) {
891 /* we are setuid-root */
893 log_error_write(srv, __FILE__, __LINE__, "s",
894 "Are you nuts ? Don't apply a SUID bit to this binary");
896 server_free(srv);
897 return -1;
899 #endif
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");
906 server_free(srv);
908 return -1;
911 if (plugins_load(srv)) {
912 log_error_write(srv, __FILE__, __LINE__, "s",
913 "loading plugins finally failed");
915 plugins_free(srv);
916 server_free(srv);
918 return -1;
921 /* open pid file BEFORE chroot */
922 if (!buffer_string_is_empty(srv->srvconf.pid_file)) {
923 if (-1 == (pid_fd = fdevent_open_cloexec(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;
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));
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;
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;
950 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
951 /* select limits itself
953 * as it is a hard limit and will lead to a segfault we add some safety
954 * */
955 srv->max_fds = FD_SETSIZE - 200;
956 } else {
957 srv->max_fds = 4096;
960 if (i_am_root) {
961 struct group *grp = NULL;
962 struct passwd *pwd = NULL;
963 int use_rlimit = 1;
965 #ifdef HAVE_VALGRIND_VALGRIND_H
966 if (RUNNING_ON_VALGRIND) use_rlimit = 0;
967 #endif
969 #ifdef HAVE_GETRLIMIT
970 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
971 log_error_write(srv, __FILE__, __LINE__,
972 "ss", "couldn't get 'max filedescriptors'",
973 strerror(errno));
974 return -1;
977 if (use_rlimit && srv->srvconf.max_fds) {
978 /* set rlimits */
980 rlim.rlim_cur = srv->srvconf.max_fds;
981 rlim.rlim_max = srv->srvconf.max_fds;
983 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
984 log_error_write(srv, __FILE__, __LINE__,
985 "ss", "couldn't set 'max filedescriptors'",
986 strerror(errno));
987 return -1;
991 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
992 srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200;
993 } else {
994 srv->max_fds = rlim.rlim_cur;
997 /* set core file rlimit, if enable_cores is set */
998 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
999 rlim.rlim_cur = rlim.rlim_max;
1000 setrlimit(RLIMIT_CORE, &rlim);
1002 #endif
1003 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
1004 /* don't raise the limit above FD_SET_SIZE */
1005 if (srv->max_fds > ((int)FD_SETSIZE) - 200) {
1006 log_error_write(srv, __FILE__, __LINE__, "sd",
1007 "can't raise max filedescriptors above", FD_SETSIZE - 200,
1008 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
1009 return -1;
1014 #ifdef HAVE_PWD_H
1015 /* set user and group */
1016 if (!buffer_string_is_empty(srv->srvconf.groupname)) {
1017 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
1018 log_error_write(srv, __FILE__, __LINE__, "sb",
1019 "can't find groupname", srv->srvconf.groupname);
1020 return -1;
1024 if (!buffer_string_is_empty(srv->srvconf.username)) {
1025 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
1026 log_error_write(srv, __FILE__, __LINE__, "sb",
1027 "can't find username", srv->srvconf.username);
1028 return -1;
1031 if (pwd->pw_uid == 0) {
1032 log_error_write(srv, __FILE__, __LINE__, "s",
1033 "I will not set uid to 0\n");
1034 return -1;
1037 if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) {
1038 log_error_write(srv, __FILE__, __LINE__, "sd",
1039 "can't find group id", pwd->pw_gid);
1040 return -1;
1044 if (NULL != grp) {
1045 if (grp->gr_gid == 0) {
1046 log_error_write(srv, __FILE__, __LINE__, "s",
1047 "I will not set gid to 0\n");
1048 return -1;
1051 #endif
1052 /* we need root-perms for port < 1024 */
1053 if (0 != network_init(srv)) {
1054 plugins_free(srv);
1055 server_free(srv);
1057 return -1;
1059 #ifdef HAVE_PWD_H
1061 * Change group before chroot, when we have access
1062 * to /etc/group
1063 * */
1064 if (NULL != grp) {
1065 if (-1 == setgid(grp->gr_gid)) {
1066 log_error_write(srv, __FILE__, __LINE__, "ss", "setgid failed: ", strerror(errno));
1067 return -1;
1069 if (-1 == setgroups(0, NULL)) {
1070 log_error_write(srv, __FILE__, __LINE__, "ss", "setgroups failed: ", strerror(errno));
1071 return -1;
1073 if (!buffer_string_is_empty(srv->srvconf.username)) {
1074 initgroups(srv->srvconf.username->ptr, grp->gr_gid);
1077 #endif
1078 #ifdef HAVE_CHROOT
1079 if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
1080 tzset();
1082 if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
1083 log_error_write(srv, __FILE__, __LINE__, "ss", "chroot failed: ", strerror(errno));
1084 return -1;
1086 if (-1 == chdir("/")) {
1087 log_error_write(srv, __FILE__, __LINE__, "ss", "chdir failed: ", strerror(errno));
1088 return -1;
1091 #endif
1092 #ifdef HAVE_PWD_H
1093 /* drop root privs */
1094 if (NULL != pwd) {
1095 if (-1 == setuid(pwd->pw_uid)) {
1096 log_error_write(srv, __FILE__, __LINE__, "ss", "setuid failed: ", strerror(errno));
1097 return -1;
1100 #endif
1101 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1103 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1105 if (srv->srvconf.enable_cores) {
1106 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1108 #endif
1109 } else {
1111 #ifdef HAVE_GETRLIMIT
1112 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
1113 log_error_write(srv, __FILE__, __LINE__,
1114 "ss", "couldn't get 'max filedescriptors'",
1115 strerror(errno));
1116 return -1;
1120 * we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1122 if (srv->srvconf.max_fds && srv->srvconf.max_fds <= rlim.rlim_max) {
1123 /* set rlimits */
1125 rlim.rlim_cur = srv->srvconf.max_fds;
1127 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
1128 log_error_write(srv, __FILE__, __LINE__,
1129 "ss", "couldn't set 'max filedescriptors'",
1130 strerror(errno));
1131 return -1;
1135 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
1136 srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200;
1137 } else {
1138 srv->max_fds = rlim.rlim_cur;
1141 /* set core file rlimit, if enable_cores is set */
1142 if (srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
1143 rlim.rlim_cur = rlim.rlim_max;
1144 setrlimit(RLIMIT_CORE, &rlim);
1147 #endif
1148 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
1149 /* don't raise the limit above FD_SET_SIZE */
1150 if (srv->max_fds > ((int)FD_SETSIZE) - 200) {
1151 log_error_write(srv, __FILE__, __LINE__, "sd",
1152 "can't raise max filedescriptors above", FD_SETSIZE - 200,
1153 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
1154 return -1;
1158 if (0 != network_init(srv)) {
1159 plugins_free(srv);
1160 server_free(srv);
1162 return -1;
1166 /* set max-conns */
1167 if (srv->srvconf.max_conns > srv->max_fds/2) {
1168 /* we can't have more connections than max-fds/2 */
1169 log_error_write(srv, __FILE__, __LINE__, "sdd", "can't have more connections than fds/2: ", srv->srvconf.max_conns, srv->max_fds);
1170 srv->max_conns = srv->max_fds/2;
1171 } else if (srv->srvconf.max_conns) {
1172 /* otherwise respect the wishes of the user */
1173 srv->max_conns = srv->srvconf.max_conns;
1174 } else {
1175 /* or use the default: we really don't want to hit max-fds */
1176 srv->max_conns = srv->max_fds/3;
1179 if (HANDLER_GO_ON != plugins_call_init(srv)) {
1180 log_error_write(srv, __FILE__, __LINE__, "s", "Initialization of plugins failed. Going down.");
1182 plugins_free(srv);
1183 network_close(srv);
1184 server_free(srv);
1186 return -1;
1189 #ifdef HAVE_FORK
1190 /* network is up, let's deamonize ourself */
1191 if (srv->srvconf.dont_daemonize == 0) {
1192 parent_pipe_fd = daemonize();
1194 #endif
1197 #ifdef HAVE_SIGACTION
1198 memset(&act, 0, sizeof(act));
1199 act.sa_handler = SIG_IGN;
1200 sigaction(SIGPIPE, &act, NULL);
1201 sigaction(SIGUSR1, &act, NULL);
1202 # if defined(SA_SIGINFO)
1203 act.sa_sigaction = sigaction_handler;
1204 sigemptyset(&act.sa_mask);
1205 act.sa_flags = SA_SIGINFO;
1206 # else
1207 act.sa_handler = signal_handler;
1208 sigemptyset(&act.sa_mask);
1209 act.sa_flags = 0;
1210 # endif
1211 sigaction(SIGINT, &act, NULL);
1212 sigaction(SIGTERM, &act, NULL);
1213 sigaction(SIGHUP, &act, NULL);
1214 sigaction(SIGALRM, &act, NULL);
1216 /* it should be safe to restart syscalls after SIGCHLD */
1217 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
1218 sigaction(SIGCHLD, &act, NULL);
1220 #elif defined(HAVE_SIGNAL)
1221 /* ignore the SIGPIPE from sendfile() */
1222 signal(SIGPIPE, SIG_IGN);
1223 signal(SIGUSR1, SIG_IGN);
1224 signal(SIGALRM, signal_handler);
1225 signal(SIGTERM, signal_handler);
1226 signal(SIGHUP, signal_handler);
1227 signal(SIGCHLD, signal_handler);
1228 signal(SIGINT, signal_handler);
1229 #endif
1231 #ifdef USE_ALARM
1232 signal(SIGALRM, signal_handler);
1234 /* setup periodic timer (1 second) */
1235 if (setitimer(ITIMER_REAL, &interval, NULL)) {
1236 log_error_write(srv, __FILE__, __LINE__, "s", "setting timer failed");
1237 return -1;
1240 getitimer(ITIMER_REAL, &interval);
1241 #endif
1244 srv->gid = getgid();
1245 srv->uid = getuid();
1247 /* write pid file */
1248 if (pid_fd != -1) {
1249 buffer_copy_int(srv->tmp_buf, getpid());
1250 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\n"));
1251 if (-1 == write_all(pid_fd, CONST_BUF_LEN(srv->tmp_buf))) {
1252 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't write pid file:", strerror(errno));
1253 close(pid_fd);
1254 return -1;
1258 /* Close stderr ASAP in the child process to make sure that nothing
1259 * is being written to that fd which may not be valid anymore. */
1260 if (!srv->srvconf.preflight_check && -1 == log_error_open(srv)) {
1261 log_error_write(srv, __FILE__, __LINE__, "s", "Opening errorlog failed. Going down.");
1263 plugins_free(srv);
1264 network_close(srv);
1265 server_free(srv);
1266 return -1;
1269 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1270 log_error_write(srv, __FILE__, __LINE__, "s", "Configuration of plugins failed. Going down.");
1272 plugins_free(srv);
1273 network_close(srv);
1274 server_free(srv);
1276 return -1;
1279 /* settings might be enabled during module config set defaults */
1280 srv->config_storage[0]->high_precision_timestamps = srv->srvconf.high_precision_timestamps;
1282 /* dump unused config-keys */
1283 for (i = 0; i < srv->config_context->used; i++) {
1284 array *config = ((data_config *)srv->config_context->data[i])->value;
1285 size_t j;
1287 for (j = 0; config && j < config->used; j++) {
1288 data_unset *du = config->data[j];
1290 /* all var.* is known as user defined variable */
1291 if (strncmp(du->key->ptr, "var.", sizeof("var.") - 1) == 0) {
1292 continue;
1295 if (NULL == array_get_element(srv->config_touched, du->key->ptr)) {
1296 log_error_write(srv, __FILE__, __LINE__, "sbs",
1297 "WARNING: unknown config-key:",
1298 du->key,
1299 "(ignored)");
1304 if (srv->config_unsupported) {
1305 log_error_write(srv, __FILE__, __LINE__, "s",
1306 "Configuration contains unsupported keys. Going down.");
1309 if (srv->config_deprecated) {
1310 log_error_write(srv, __FILE__, __LINE__, "s",
1311 "Configuration contains deprecated keys. Going down.");
1314 if (srv->config_unsupported || srv->config_deprecated) {
1315 plugins_free(srv);
1316 network_close(srv);
1317 server_free(srv);
1319 return -1;
1322 if (srv->srvconf.preflight_check) {
1323 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1324 plugins_free(srv);
1325 network_close(srv);
1326 server_free(srv);
1328 exit(0);
1332 #ifdef HAVE_FORK
1334 * notify daemonize-grandparent of successful startup
1335 * do this before any further forking is done (workers)
1337 if (srv->srvconf.dont_daemonize == 0) {
1338 if (0 > write(parent_pipe_fd, "", 1)) return -1;
1339 close(parent_pipe_fd);
1342 if (idle_limit && srv->srvconf.max_worker) {
1343 srv->srvconf.max_worker = 0;
1344 log_error_write(srv, __FILE__, __LINE__, "s",
1345 "server idle time limit command line option disables server.max-worker config file option.");
1348 /* start watcher and workers */
1349 num_childs = srv->srvconf.max_worker;
1350 if (num_childs > 0) {
1351 int child = 0;
1352 while (!child && !srv_shutdown && !graceful_shutdown) {
1353 if (num_childs > 0) {
1354 switch (fork()) {
1355 case -1:
1356 return -1;
1357 case 0:
1358 child = 1;
1359 break;
1360 default:
1361 num_childs--;
1362 break;
1364 } else {
1365 int status;
1367 if (-1 != wait(&status)) {
1368 /**
1369 * one of our workers went away
1371 num_childs++;
1372 } else {
1373 switch (errno) {
1374 case EINTR:
1376 * if we receive a SIGHUP we have to close our logs ourself as we don't
1377 * have the mainloop who can help us here
1379 if (handle_sig_hup) {
1380 handle_sig_hup = 0;
1382 log_error_cycle(srv);
1385 * forward to all procs in the process-group
1387 * we also send it ourself
1389 if (!forwarded_sig_hup && 0 != srv->srvconf.max_worker) {
1390 forwarded_sig_hup = 1;
1391 kill(0, SIGHUP);
1394 break;
1395 default:
1396 break;
1403 * for the parent this is the exit-point
1405 if (!child) {
1406 /**
1407 * kill all children too
1409 if (graceful_shutdown) {
1410 kill(0, SIGINT);
1411 } else if (srv_shutdown) {
1412 kill(0, SIGTERM);
1415 remove_pid_file(srv, &pid_fd);
1416 log_error_close(srv);
1417 network_close(srv);
1418 connections_free(srv);
1419 plugins_free(srv);
1420 server_free(srv);
1421 return 0;
1425 * make sure workers do not muck with pid-file
1427 if (0 <= pid_fd) {
1428 close(pid_fd);
1429 pid_fd = -1;
1431 buffer_reset(srv->srvconf.pid_file);
1433 li_rand_reseed();
1435 #endif
1437 if (NULL == (srv->ev = fdevent_init(srv, srv->max_fds + 1, srv->event_handler))) {
1438 log_error_write(srv, __FILE__, __LINE__,
1439 "s", "fdevent_init failed");
1440 return -1;
1443 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1444 #ifdef HAVE_SIGACTION
1445 sigaction(SIGCHLD, &act, NULL);
1446 #elif defined(HAVE_SIGNAL)
1447 signal(SIGCHLD, signal_handler);
1448 #endif
1451 * kqueue() is called here, select resets its internals,
1452 * all server sockets get their handlers
1454 * */
1455 if (0 != network_register_fdevents(srv)) {
1456 plugins_free(srv);
1457 network_close(srv);
1458 server_free(srv);
1460 return -1;
1463 /* might fail if user is using fam (not gamin) and famd isn't running */
1464 if (NULL == (srv->stat_cache = stat_cache_init())) {
1465 log_error_write(srv, __FILE__, __LINE__, "s",
1466 "stat-cache could not be setup, dieing.");
1467 return -1;
1470 #ifdef HAVE_FAM_H
1471 /* setup FAM */
1472 if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_FAM) {
1473 if (0 != FAMOpen2(&srv->stat_cache->fam, "lighttpd")) {
1474 log_error_write(srv, __FILE__, __LINE__, "s",
1475 "could not open a fam connection, dieing.");
1476 return -1;
1478 #ifdef HAVE_FAMNOEXISTS
1479 FAMNoExists(&srv->stat_cache->fam);
1480 #endif
1482 fd_close_on_exec(FAMCONNECTION_GETFD(&srv->stat_cache->fam));
1483 fdevent_register(srv->ev, FAMCONNECTION_GETFD(&srv->stat_cache->fam), stat_cache_handle_fdevent, NULL);
1484 fdevent_event_set(srv->ev, &(srv->stat_cache->fam_fcce_ndx), FAMCONNECTION_GETFD(&srv->stat_cache->fam), FDEVENT_IN);
1486 #endif
1489 /* get the current number of FDs */
1490 srv->cur_fds = open("/dev/null", O_RDONLY);
1491 close(srv->cur_fds);
1493 for (i = 0; i < srv->srv_sockets.used; i++) {
1494 server_socket *srv_socket = srv->srv_sockets.ptr[i];
1495 if (srv->sockets_disabled) continue; /* lighttpd -1 (one-shot mode) */
1496 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv->ev, srv_socket->fd)) {
1497 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed:", strerror(errno));
1498 return -1;
1502 if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) {
1503 oneshot_fd = -1;
1506 /* main-loop */
1507 while (!srv_shutdown) {
1508 int n;
1509 size_t ndx;
1510 time_t min_ts;
1512 if (handle_sig_hup) {
1513 handler_t r;
1515 /* reset notification */
1516 handle_sig_hup = 0;
1519 /* cycle logfiles */
1521 switch(r = plugins_call_handle_sighup(srv)) {
1522 case HANDLER_GO_ON:
1523 break;
1524 default:
1525 log_error_write(srv, __FILE__, __LINE__, "sd", "sighup-handler return with an error", r);
1526 break;
1529 if (-1 == log_error_cycle(srv)) {
1530 log_error_write(srv, __FILE__, __LINE__, "s", "cycling errorlog failed, dying");
1532 return -1;
1533 } else {
1534 #ifdef HAVE_SIGACTION
1535 log_error_write(srv, __FILE__, __LINE__, "sdsd",
1536 "logfiles cycled UID =",
1537 last_sighup_info.si_uid,
1538 "PID =",
1539 last_sighup_info.si_pid);
1540 #else
1541 log_error_write(srv, __FILE__, __LINE__, "s",
1542 "logfiles cycled");
1543 #endif
1547 if (handle_sig_alarm) {
1548 /* a new second */
1550 #ifdef USE_ALARM
1551 /* reset notification */
1552 handle_sig_alarm = 0;
1553 #endif
1555 /* get current time */
1556 min_ts = time(NULL);
1558 if (min_ts != srv->cur_ts) {
1559 #ifdef DEBUG_CONNECTION_STATES
1560 int cs = 0;
1561 #endif
1562 connections *conns = srv->conns;
1563 handler_t r;
1565 switch(r = plugins_call_handle_trigger(srv)) {
1566 case HANDLER_GO_ON:
1567 break;
1568 case HANDLER_ERROR:
1569 log_error_write(srv, __FILE__, __LINE__, "s", "one of the triggers failed");
1570 break;
1571 default:
1572 log_error_write(srv, __FILE__, __LINE__, "d", r);
1573 break;
1576 /* trigger waitpid */
1577 srv->cur_ts = min_ts;
1579 /* check idle time limit, if enabled */
1580 if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) {
1581 log_error_write(srv, __FILE__, __LINE__, "sDs", "[note] idle timeout", (int)idle_limit,
1582 "s exceeded, initiating graceful shutdown");
1583 graceful_shutdown = 2; /* value 2 indicates idle timeout */
1586 /* cleanup stat-cache */
1587 stat_cache_trigger_cleanup(srv);
1589 * check all connections for timeouts
1592 for (ndx = 0; ndx < conns->used; ndx++) {
1593 connection * const con = conns->ptr[ndx];
1594 const int waitevents = fdevent_event_get_interest(srv->ev, con->fd);
1595 int changed = 0;
1596 int t_diff;
1598 if (con->state == CON_STATE_CLOSE) {
1599 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
1600 changed = 1;
1602 } else if (waitevents & FDEVENT_IN) {
1603 if (con->request_count == 1 || con->state != CON_STATE_READ) { /* e.g. CON_STATE_READ_POST || CON_STATE_WRITE */
1604 if (srv->cur_ts - con->read_idle_ts > con->conf.max_read_idle) {
1605 /* time - out */
1606 if (con->conf.log_request_handling) {
1607 log_error_write(srv, __FILE__, __LINE__, "sd",
1608 "connection closed - read timeout:", con->fd);
1611 connection_set_state(srv, con, CON_STATE_ERROR);
1612 changed = 1;
1614 } else {
1615 if (srv->cur_ts - con->read_idle_ts > con->keep_alive_idle) {
1616 /* time - out */
1617 if (con->conf.log_request_handling) {
1618 log_error_write(srv, __FILE__, __LINE__, "sd",
1619 "connection closed - keep-alive timeout:", con->fd);
1622 connection_set_state(srv, con, CON_STATE_ERROR);
1623 changed = 1;
1628 /* max_write_idle timeout currently functions as backend timeout,
1629 * too, after response has been started.
1630 * future: have separate backend timeout, and then change this
1631 * to check for write interest before checking for timeout */
1632 /*if (waitevents & FDEVENT_OUT)*/
1633 if ((con->state == CON_STATE_WRITE) &&
1634 (con->write_request_ts != 0)) {
1635 #if 0
1636 if (srv->cur_ts - con->write_request_ts > 60) {
1637 log_error_write(srv, __FILE__, __LINE__, "sdd",
1638 "connection closed - pre-write-request-timeout:", con->fd, srv->cur_ts - con->write_request_ts);
1640 #endif
1642 if (srv->cur_ts - con->write_request_ts > con->conf.max_write_idle) {
1643 /* time - out */
1644 if (con->conf.log_timeouts) {
1645 log_error_write(srv, __FILE__, __LINE__, "sbsbsosds",
1646 "NOTE: a request from",
1647 con->dst_addr_buf,
1648 "for",
1649 con->request.uri,
1650 "timed out after writing",
1651 con->bytes_written,
1652 "bytes. We waited",
1653 (int)con->conf.max_write_idle,
1654 "seconds. If this a problem increase server.max-write-idle");
1656 connection_set_state(srv, con, CON_STATE_ERROR);
1657 changed = 1;
1661 /* we don't like div by zero */
1662 if (0 == (t_diff = srv->cur_ts - con->connection_start)) t_diff = 1;
1664 if (con->traffic_limit_reached &&
1665 (con->conf.kbytes_per_second == 0 ||
1666 ((con->bytes_written / t_diff) < con->conf.kbytes_per_second * 1024))) {
1667 /* enable connection again */
1668 con->traffic_limit_reached = 0;
1670 changed = 1;
1673 if (changed) {
1674 connection_state_machine(srv, con);
1676 con->bytes_written_cur_second = 0;
1677 *(con->conf.global_bytes_per_second_cnt_ptr) = 0;
1679 #if DEBUG_CONNECTION_STATES
1680 if (cs == 0) {
1681 fprintf(stderr, "connection-state: ");
1682 cs = 1;
1685 fprintf(stderr, "c[%d,%d]: %s ",
1686 con->fd,
1687 con->fcgi.fd,
1688 connection_get_state(con->state));
1689 #endif
1692 #ifdef DEBUG_CONNECTION_STATES
1693 if (cs == 1) fprintf(stderr, "\n");
1694 #endif
1698 if (srv->sockets_disabled) {
1699 /* our server sockets are disabled, why ? */
1701 if ((srv->cur_fds + srv->want_fds < srv->max_fds * 8 / 10) && /* we have enough unused fds */
1702 (srv->conns->used <= srv->max_conns * 9 / 10) &&
1703 (0 == graceful_shutdown)) {
1704 for (i = 0; i < srv->srv_sockets.used; i++) {
1705 server_socket *srv_socket = srv->srv_sockets.ptr[i];
1706 fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, FDEVENT_IN);
1709 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets enabled again");
1711 srv->sockets_disabled = 0;
1713 } else {
1714 if ((srv->cur_fds + srv->want_fds > srv->max_fds * 9 / 10) || /* out of fds */
1715 (srv->conns->used >= srv->max_conns) || /* out of connections */
1716 (graceful_shutdown)) { /* graceful_shutdown */
1718 /* disable server-fds */
1720 for (i = 0; i < srv->srv_sockets.used; i++) {
1721 server_socket *srv_socket = srv->srv_sockets.ptr[i];
1723 if (graceful_shutdown) {
1724 /* we don't want this socket anymore,
1726 * closing it right away will make it possible for
1727 * the next lighttpd to take over (graceful restart)
1728 * */
1730 fdevent_event_del(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd);
1731 fdevent_unregister(srv->ev, srv_socket->fd);
1732 close(srv_socket->fd);
1733 srv_socket->fd = -1;
1735 /* network_close() will cleanup after us */
1736 } else {
1737 fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, 0);
1741 if (graceful_shutdown) {
1742 remove_pid_file(srv, &pid_fd);
1743 log_error_write(srv, __FILE__, __LINE__, "s", "[note] graceful shutdown started");
1744 } else if (srv->conns->used >= srv->max_conns) {
1745 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, connection limit reached");
1746 } else {
1747 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, out-of-fds");
1750 srv->sockets_disabled = 1;
1754 if (graceful_shutdown && srv->conns->used == 0) {
1755 /* we are in graceful shutdown phase and all connections are closed
1756 * we are ready to terminate without harming anyone */
1757 srv_shutdown = 1;
1758 break;
1761 /* we still have some fds to share */
1762 if (srv->want_fds) {
1763 /* check the fdwaitqueue for waiting fds */
1764 int free_fds = srv->max_fds - srv->cur_fds - 16;
1765 connection *con;
1767 for (; free_fds > 0 && NULL != (con = fdwaitqueue_unshift(srv, srv->fdwaitqueue)); free_fds--) {
1768 connection_state_machine(srv, con);
1770 srv->want_fds--;
1774 if ((n = fdevent_poll(srv->ev, 1000)) > 0) {
1775 /* n is the number of events */
1776 int revents;
1777 int fd_ndx;
1778 last_active_ts = srv->cur_ts;
1779 fd_ndx = -1;
1780 do {
1781 fdevent_handler handler;
1782 void *context;
1784 fd_ndx = fdevent_event_next_fdndx (srv->ev, fd_ndx);
1785 if (-1 == fd_ndx) break; /* not all fdevent handlers know how many fds got an event */
1787 revents = fdevent_event_get_revent (srv->ev, fd_ndx);
1788 fd = fdevent_event_get_fd (srv->ev, fd_ndx);
1789 handler = fdevent_get_handler(srv->ev, fd);
1790 context = fdevent_get_context(srv->ev, fd);
1791 if (NULL != handler) {
1792 (*handler)(srv, context, revents);
1794 } while (--n > 0);
1795 fdevent_sched_run(srv, srv->ev);
1796 } else if (n < 0 && errno != EINTR) {
1797 log_error_write(srv, __FILE__, __LINE__, "ss",
1798 "fdevent_poll failed:",
1799 strerror(errno));
1802 for (ndx = 0; ndx < srv->joblist->used; ndx++) {
1803 connection *con = srv->joblist->ptr[ndx];
1804 connection_state_machine(srv, con);
1805 con->in_joblist = 0;
1808 srv->joblist->used = 0;
1811 if (0 == graceful_shutdown) {
1812 remove_pid_file(srv, &pid_fd);
1815 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */
1816 log_error_write(srv, __FILE__, __LINE__, "s",
1817 "server stopped after idle timeout");
1818 } else {
1819 #ifdef HAVE_SIGACTION
1820 log_error_write(srv, __FILE__, __LINE__, "sdsd",
1821 "server stopped by UID =",
1822 last_sigterm_info.si_uid,
1823 "PID =",
1824 last_sigterm_info.si_pid);
1825 #else
1826 log_error_write(srv, __FILE__, __LINE__, "s",
1827 "server stopped");
1828 #endif
1831 /* clean-up */
1832 log_error_close(srv);
1833 network_close(srv);
1834 connections_free(srv);
1835 plugins_free(srv);
1836 server_free(srv);
1838 return 0;