[core] lighttpd -1 handles single request on stdin socket (fixes #1584)
[lighttpd.git] / src / server.c
blob1119efd01c555ffc077a219f61407fefd11651c1
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 "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"
20 #include <sys/types.h>
21 #include <sys/time.h>
22 #include <sys/stat.h>
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>
34 #include <stdio.h>
36 #ifdef HAVE_GETOPT_H
37 # include <getopt.h>
38 #endif
40 #ifdef HAVE_VALGRIND_VALGRIND_H
41 # include <valgrind/valgrind.h>
42 #endif
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
46 #endif
48 #ifdef HAVE_PWD_H
49 # include <grp.h>
50 # include <pwd.h>
51 #endif
53 #ifdef HAVE_SYS_RESOURCE_H
54 # include <sys/resource.h>
55 #endif
57 #ifdef HAVE_SYS_PRCTL_H
58 # include <sys/prctl.h>
59 #endif
61 #ifdef USE_OPENSSL
62 # include <openssl/err.h>
63 #endif
65 #ifndef __sgi
66 /* IRIX doesn't like the alarm based time() optimization */
67 /* #define USE_ALARM */
68 #endif
70 #ifdef HAVE_GETUID
71 # ifndef HAVE_ISSETUGID
73 static int l_issetugid(void) {
74 return (geteuid() != getuid() || getegid() != getgid());
77 # define issetugid l_issetugid
78 # endif
79 #endif
81 static volatile sig_atomic_t srv_shutdown = 0;
82 static volatile sig_atomic_t graceful_shutdown = 0;
83 static volatile sig_atomic_t handle_sig_alarm = 1;
84 static volatile sig_atomic_t handle_sig_hup = 0;
85 static volatile sig_atomic_t forwarded_sig_hup = 0;
87 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
88 static volatile siginfo_t last_sigterm_info;
89 static volatile siginfo_t last_sighup_info;
91 static void sigaction_handler(int sig, siginfo_t *si, void *context) {
92 static siginfo_t empty_siginfo;
93 UNUSED(context);
95 if (!si) si = &empty_siginfo;
97 switch (sig) {
98 case SIGTERM:
99 srv_shutdown = 1;
100 last_sigterm_info = *si;
101 break;
102 case SIGINT:
103 if (graceful_shutdown) {
104 srv_shutdown = 1;
105 } else {
106 graceful_shutdown = 1;
108 last_sigterm_info = *si;
110 break;
111 case SIGALRM:
112 handle_sig_alarm = 1;
113 break;
114 case SIGHUP:
115 /**
116 * we send the SIGHUP to all procs in the process-group
117 * this includes ourself
119 * make sure we only send it once and don't create a
120 * infinite loop
122 if (!forwarded_sig_hup) {
123 handle_sig_hup = 1;
124 last_sighup_info = *si;
125 } else {
126 forwarded_sig_hup = 0;
128 break;
129 case SIGCHLD:
130 break;
133 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
134 static void signal_handler(int sig) {
135 switch (sig) {
136 case SIGTERM: srv_shutdown = 1; break;
137 case SIGINT:
138 if (graceful_shutdown) srv_shutdown = 1;
139 else graceful_shutdown = 1;
141 break;
142 case SIGALRM: handle_sig_alarm = 1; break;
143 case SIGHUP: handle_sig_hup = 1; break;
144 case SIGCHLD: break;
147 #endif
149 #ifdef HAVE_FORK
150 static int daemonize(void) {
151 int pipefd[2];
152 pid_t pid;
153 #ifdef SIGTTOU
154 signal(SIGTTOU, SIG_IGN);
155 #endif
156 #ifdef SIGTTIN
157 signal(SIGTTIN, SIG_IGN);
158 #endif
159 #ifdef SIGTSTP
160 signal(SIGTSTP, SIG_IGN);
161 #endif
163 if (pipe(pipefd) < 0) exit(-1);
165 if (0 > (pid = fork())) exit(-1);
167 if (0 < pid) {
168 char buf;
169 ssize_t bytes;
171 close(pipefd[1]);
172 /* parent waits for grandchild to be ready */
173 do {
174 bytes = read(pipefd[0], &buf, sizeof(buf));
175 } while (bytes < 0 && EINTR == errno);
176 close(pipefd[0]);
178 if (bytes <= 0) {
179 /* closed fd (without writing) == failure in grandchild */
180 fputs("daemonized server failed to start; check error log for details\n", stderr);
181 exit(-1);
184 exit(0);
187 close(pipefd[0]);
189 if (-1 == setsid()) exit(0);
191 signal(SIGHUP, SIG_IGN);
193 if (0 != fork()) exit(0);
195 if (0 != chdir("/")) exit(0);
197 fd_close_on_exec(pipefd[1]);
198 return pipefd[1];
200 #endif
202 static server *server_init(void) {
203 int i;
204 FILE *frandom = NULL;
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 if ((NULL != (frandom = fopen("/dev/urandom", "rb")) || NULL != (frandom = fopen("/dev/random", "rb")))
247 && 1 == fread(srv->entropy, sizeof(srv->entropy), 1, frandom)) {
248 unsigned int e;
249 memcpy(&e, srv->entropy, sizeof(e) < sizeof(srv->entropy) ? sizeof(e) : sizeof(srv->entropy));
250 srand(e);
251 srv->is_real_entropy = 1;
252 } else {
253 unsigned int j;
254 srand(time(NULL) ^ getpid());
255 srv->is_real_entropy = 0;
256 for (j = 0; j < sizeof(srv->entropy); j++)
257 srv->entropy[j] = rand();
259 if (frandom) fclose(frandom);
261 srv->cur_ts = time(NULL);
262 srv->startup_ts = srv->cur_ts;
264 srv->conns = calloc(1, sizeof(*srv->conns));
265 force_assert(srv->conns);
267 srv->joblist = calloc(1, sizeof(*srv->joblist));
268 force_assert(srv->joblist);
270 srv->fdwaitqueue = calloc(1, sizeof(*srv->fdwaitqueue));
271 force_assert(srv->fdwaitqueue);
273 srv->srvconf.modules = array_init();
274 srv->srvconf.modules_dir = buffer_init_string(LIBRARY_DIR);
275 srv->srvconf.network_backend = buffer_init();
276 srv->srvconf.upload_tempdirs = array_init();
277 srv->srvconf.reject_expect_100_with_417 = 1;
278 srv->srvconf.xattr_name = buffer_init_string("Content-Type");
280 /* use syslog */
281 srv->errorlog_fd = STDERR_FILENO;
282 srv->errorlog_mode = ERRORLOG_FD;
284 srv->split_vals = array_init();
286 return srv;
289 static void server_free(server *srv) {
290 size_t i;
292 for (i = 0; i < FILE_CACHE_MAX; i++) {
293 buffer_free(srv->mtime_cache[i].str);
296 #define CLEAN(x) \
297 buffer_free(srv->x);
299 CLEAN(response_header);
300 CLEAN(parse_full_path);
301 CLEAN(ts_debug_str);
302 CLEAN(ts_date_str);
303 CLEAN(errorlog_buf);
304 CLEAN(response_range);
305 CLEAN(tmp_buf);
306 CLEAN(empty_string);
307 CLEAN(cond_check_buf);
309 CLEAN(srvconf.errorlog_file);
310 CLEAN(srvconf.breakagelog_file);
311 CLEAN(srvconf.groupname);
312 CLEAN(srvconf.username);
313 CLEAN(srvconf.changeroot);
314 CLEAN(srvconf.bindhost);
315 CLEAN(srvconf.event_handler);
316 CLEAN(srvconf.pid_file);
317 CLEAN(srvconf.modules_dir);
318 CLEAN(srvconf.network_backend);
319 CLEAN(srvconf.xattr_name);
321 CLEAN(tmp_chunk_len);
322 #undef CLEAN
324 #if 0
325 fdevent_unregister(srv->ev, srv->fd);
326 #endif
327 fdevent_free(srv->ev);
329 free(srv->conns);
331 if (srv->config_storage) {
332 for (i = 0; i < srv->config_context->used; i++) {
333 specific_config *s = srv->config_storage[i];
335 if (!s) continue;
337 buffer_free(s->document_root);
338 buffer_free(s->server_name);
339 buffer_free(s->server_tag);
340 buffer_free(s->ssl_pemfile);
341 buffer_free(s->ssl_ca_file);
342 buffer_free(s->ssl_cipher_list);
343 buffer_free(s->ssl_dh_file);
344 buffer_free(s->ssl_ec_curve);
345 buffer_free(s->error_handler);
346 buffer_free(s->error_handler_404);
347 buffer_free(s->errorfile_prefix);
348 array_free(s->mimetypes);
349 buffer_free(s->ssl_verifyclient_username);
350 #ifdef USE_OPENSSL
351 SSL_CTX_free(s->ssl_ctx);
352 EVP_PKEY_free(s->ssl_pemfile_pkey);
353 X509_free(s->ssl_pemfile_x509);
354 if (NULL != s->ssl_ca_file_cert_names) sk_X509_NAME_pop_free(s->ssl_ca_file_cert_names, X509_NAME_free);
355 #endif
356 free(s);
358 free(srv->config_storage);
359 srv->config_storage = NULL;
362 #define CLEAN(x) \
363 array_free(srv->x);
365 CLEAN(config_context);
366 CLEAN(config_touched);
367 CLEAN(status);
368 CLEAN(srvconf.upload_tempdirs);
369 #undef CLEAN
371 joblist_free(srv, srv->joblist);
372 fdwaitqueue_free(srv, srv->fdwaitqueue);
374 if (srv->stat_cache) {
375 stat_cache_free(srv->stat_cache);
378 array_free(srv->srvconf.modules);
379 array_free(srv->split_vals);
381 #ifdef USE_OPENSSL
382 if (srv->ssl_is_init) {
383 CRYPTO_cleanup_all_ex_data();
384 ERR_free_strings();
385 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
386 ERR_remove_thread_state();
387 #elif OPENSSL_VERSION_NUMBER >= 0x10000000L
388 ERR_remove_thread_state(NULL);
389 #else
390 ERR_remove_state(0);
391 #endif
392 EVP_cleanup();
394 #endif
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 con = connection_accepted(srv, srv_socket, &cnt_addr, fd);
524 if (NULL == con) return 0;
526 connection_state_machine(srv, con);
527 return 1;
531 static void show_version (void) {
532 #ifdef USE_OPENSSL
533 # define TEXT_SSL " (ssl)"
534 #else
535 # define TEXT_SSL
536 #endif
537 char *b = PACKAGE_DESC TEXT_SSL \
538 " - a light and fast webserver\n" \
539 "Build-Date: " __DATE__ " " __TIME__ "\n";
541 #undef TEXT_SSL
542 write_all(STDOUT_FILENO, b, strlen(b));
545 static void show_features (void) {
546 const char features[] = ""
547 #ifdef USE_SELECT
548 "\t+ select (generic)\n"
549 #else
550 "\t- select (generic)\n"
551 #endif
552 #ifdef USE_POLL
553 "\t+ poll (Unix)\n"
554 #else
555 "\t- poll (Unix)\n"
556 #endif
557 #ifdef USE_LINUX_SIGIO
558 "\t+ rt-signals (Linux 2.4+)\n"
559 #else
560 "\t- rt-signals (Linux 2.4+)\n"
561 #endif
562 #ifdef USE_LINUX_EPOLL
563 "\t+ epoll (Linux 2.6)\n"
564 #else
565 "\t- epoll (Linux 2.6)\n"
566 #endif
567 #ifdef USE_SOLARIS_DEVPOLL
568 "\t+ /dev/poll (Solaris)\n"
569 #else
570 "\t- /dev/poll (Solaris)\n"
571 #endif
572 #ifdef USE_SOLARIS_PORT
573 "\t+ eventports (Solaris)\n"
574 #else
575 "\t- eventports (Solaris)\n"
576 #endif
577 #ifdef USE_FREEBSD_KQUEUE
578 "\t+ kqueue (FreeBSD)\n"
579 #else
580 "\t- kqueue (FreeBSD)\n"
581 #endif
582 #ifdef USE_LIBEV
583 "\t+ libev (generic)\n"
584 #else
585 "\t- libev (generic)\n"
586 #endif
587 "\nNetwork handler:\n\n"
588 #if defined USE_LINUX_SENDFILE
589 "\t+ linux-sendfile\n"
590 #else
591 "\t- linux-sendfile\n"
592 #endif
593 #if defined USE_FREEBSD_SENDFILE
594 "\t+ freebsd-sendfile\n"
595 #else
596 "\t- freebsd-sendfile\n"
597 #endif
598 #if defined USE_DARWIN_SENDFILE
599 "\t+ darwin-sendfile\n"
600 #else
601 "\t- darwin-sendfile\n"
602 #endif
603 #if defined USE_SOLARIS_SENDFILEV
604 "\t+ solaris-sendfilev\n"
605 #else
606 "\t- solaris-sendfilev\n"
607 #endif
608 #if defined USE_WRITEV
609 "\t+ writev\n"
610 #else
611 "\t- writev\n"
612 #endif
613 "\t+ write\n"
614 #ifdef USE_MMAP
615 "\t+ mmap support\n"
616 #else
617 "\t- mmap support\n"
618 #endif
619 "\nFeatures:\n\n"
620 #ifdef HAVE_IPV6
621 "\t+ IPv6 support\n"
622 #else
623 "\t- IPv6 support\n"
624 #endif
625 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
626 "\t+ zlib support\n"
627 #else
628 "\t- zlib support\n"
629 #endif
630 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
631 "\t+ bzip2 support\n"
632 #else
633 "\t- bzip2 support\n"
634 #endif
635 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
636 "\t+ crypt support\n"
637 #else
638 "\t- crypt support\n"
639 #endif
640 #ifdef USE_OPENSSL
641 "\t+ SSL Support\n"
642 #else
643 "\t- SSL Support\n"
644 #endif
645 #ifdef HAVE_LIBPCRE
646 "\t+ PCRE support\n"
647 #else
648 "\t- PCRE support\n"
649 #endif
650 #ifdef HAVE_MYSQL
651 "\t+ mySQL support\n"
652 #else
653 "\t- mySQL support\n"
654 #endif
655 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
656 "\t+ LDAP support\n"
657 #else
658 "\t- LDAP support\n"
659 #endif
660 #ifdef USE_MEMCACHED
661 "\t+ memcached support\n"
662 #else
663 "\t- memcached support\n"
664 #endif
665 #ifdef HAVE_FAM_H
666 "\t+ FAM support\n"
667 #else
668 "\t- FAM support\n"
669 #endif
670 #ifdef HAVE_LUA_H
671 "\t+ LUA support\n"
672 #else
673 "\t- LUA support\n"
674 #endif
675 #ifdef HAVE_LIBXML_H
676 "\t+ xml support\n"
677 #else
678 "\t- xml support\n"
679 #endif
680 #ifdef HAVE_SQLITE3_H
681 "\t+ SQLite support\n"
682 #else
683 "\t- SQLite support\n"
684 #endif
685 #ifdef HAVE_GDBM_H
686 "\t+ GDBM support\n"
687 #else
688 "\t- GDBM support\n"
689 #endif
690 "\n";
691 show_version();
692 printf("\nEvent Handlers:\n\n%s", features);
695 static void show_help (void) {
696 #ifdef USE_OPENSSL
697 # define TEXT_SSL " (ssl)"
698 #else
699 # define TEXT_SSL
700 #endif
701 char *b = PACKAGE_DESC TEXT_SSL " ("__DATE__ " " __TIME__ ")" \
702 " - a light and fast webserver\n" \
703 "usage:\n" \
704 " -f <name> filename of the config-file\n" \
705 " -m <name> module directory (default: "LIBRARY_DIR")\n" \
706 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
707 " -1 process single (one) request on stdin socket, then exit\n" \
708 " -p print the parsed config-file in internal form, and exit\n" \
709 " -t test the config-file, and exit\n" \
710 " -D don't go to background (default: go to background)\n" \
711 " -v show version\n" \
712 " -V show compile-time features\n" \
713 " -h show this help\n" \
714 "\n"
716 #undef TEXT_SSL
717 #undef TEXT_IPV6
718 write_all(STDOUT_FILENO, b, strlen(b));
721 int main (int argc, char **argv) {
722 server *srv = NULL;
723 int print_config = 0;
724 int test_config = 0;
725 int i_am_root;
726 int o;
727 int num_childs = 0;
728 int pid_fd = -1, fd;
729 size_t i;
730 time_t idle_limit = 0, last_active_ts = time(NULL);
731 #ifdef HAVE_SIGACTION
732 struct sigaction act;
733 #endif
734 #ifdef HAVE_GETRLIMIT
735 struct rlimit rlim;
736 #endif
738 #ifdef HAVE_FORK
739 int parent_pipe_fd = -1;
740 #endif
741 int oneshot_fd = 0;
743 #ifdef USE_ALARM
744 struct itimerval interval;
746 interval.it_interval.tv_sec = 1;
747 interval.it_interval.tv_usec = 0;
748 interval.it_value.tv_sec = 1;
749 interval.it_value.tv_usec = 0;
750 #endif
752 /* for nice %b handling in strfime() */
753 setlocale(LC_TIME, "C");
755 if (NULL == (srv = server_init())) {
756 fprintf(stderr, "did this really happen?\n");
757 return -1;
760 /* init structs done */
762 srv->srvconf.port = 0;
763 #ifdef HAVE_GETUID
764 i_am_root = (getuid() == 0);
765 #else
766 i_am_root = 0;
767 #endif
768 srv->srvconf.dont_daemonize = 0;
769 srv->srvconf.preflight_check = 0;
771 while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) {
772 switch(o) {
773 case 'f':
774 if (srv->config_storage) {
775 log_error_write(srv, __FILE__, __LINE__, "s",
776 "Can only read one config file. Use the include command to use multiple config files.");
778 server_free(srv);
779 return -1;
781 if (config_read(srv, optarg)) {
782 server_free(srv);
783 return -1;
785 break;
786 case 'm':
787 buffer_copy_string(srv->srvconf.modules_dir, optarg);
788 break;
789 case 'i': {
790 char *endptr;
791 long timeout = strtol(optarg, &endptr, 0);
792 if (!*optarg || *endptr || timeout < 0) {
793 log_error_write(srv, __FILE__, __LINE__, "ss",
794 "Invalid idle timeout value:", optarg);
795 server_free(srv);
796 return -1;
798 idle_limit = (time_t)timeout;
799 break;
801 case 'p': print_config = 1; break;
802 case 't': ++test_config; break;
803 case '1': oneshot_fd = dup(STDIN_FILENO); break;
804 case 'D': srv->srvconf.dont_daemonize = 1; break;
805 case 'v': show_version(); server_free(srv); return 0;
806 case 'V': show_features(); server_free(srv); return 0;
807 case 'h': show_help(); server_free(srv); return 0;
808 default:
809 show_help();
810 server_free(srv);
811 return -1;
815 if (!srv->config_storage) {
816 log_error_write(srv, __FILE__, __LINE__, "s",
817 "No configuration available. Try using -f option.");
819 server_free(srv);
820 return -1;
823 if (print_config) {
824 data_unset *dc = srv->config_context->data[0];
825 if (dc) {
826 dc->print(dc, 0);
827 fprintf(stdout, "\n");
828 } else {
829 /* shouldn't happend */
830 fprintf(stderr, "global config not found\n");
834 if (test_config) {
835 if (1 == test_config) {
836 printf("Syntax OK\n");
837 } else { /*(test_config > 1)*/
838 test_config = 0;
839 srv->srvconf.preflight_check = 1;
840 srv->srvconf.dont_daemonize = 1;
841 buffer_reset(srv->srvconf.pid_file);
845 if (test_config || print_config) {
846 server_free(srv);
847 return 0;
850 if (oneshot_fd) {
851 if (oneshot_fd <= STDERR_FILENO) {
852 log_error_write(srv, __FILE__, __LINE__, "s",
853 "Invalid fds at startup with lighttpd -1");
854 server_free(srv);
855 return -1;
857 graceful_shutdown = 1;
858 srv->sockets_disabled = 1;
859 srv->srvconf.dont_daemonize = 1;
860 buffer_reset(srv->srvconf.pid_file);
861 if (srv->srvconf.max_worker) {
862 srv->srvconf.max_worker = 0;
863 log_error_write(srv, __FILE__, __LINE__, "s",
864 "server one-shot command line option disables server.max-worker config file option.");
868 /* close stdin and stdout, as they are not needed */
869 openDevNull(STDIN_FILENO);
870 openDevNull(STDOUT_FILENO);
872 if (0 != config_set_defaults(srv)) {
873 log_error_write(srv, __FILE__, __LINE__, "s",
874 "setting default values failed");
875 server_free(srv);
876 return -1;
879 /* UID handling */
880 #ifdef HAVE_GETUID
881 if (!i_am_root && issetugid()) {
882 /* we are setuid-root */
884 log_error_write(srv, __FILE__, __LINE__, "s",
885 "Are you nuts ? Don't apply a SUID bit to this binary");
887 server_free(srv);
888 return -1;
890 #endif
892 /* check document-root */
893 if (buffer_string_is_empty(srv->config_storage[0]->document_root)) {
894 log_error_write(srv, __FILE__, __LINE__, "s",
895 "document-root is not set\n");
897 server_free(srv);
899 return -1;
902 if (plugins_load(srv)) {
903 log_error_write(srv, __FILE__, __LINE__, "s",
904 "loading plugins finally failed");
906 plugins_free(srv);
907 server_free(srv);
909 return -1;
912 /* open pid file BEFORE chroot */
913 if (!buffer_string_is_empty(srv->srvconf.pid_file)) {
914 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))) {
915 struct stat st;
916 if (errno != EEXIST) {
917 log_error_write(srv, __FILE__, __LINE__, "sbs",
918 "opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
919 return -1;
922 if (0 != stat(srv->srvconf.pid_file->ptr, &st)) {
923 log_error_write(srv, __FILE__, __LINE__, "sbs",
924 "stating existing pid-file failed:", srv->srvconf.pid_file, strerror(errno));
927 if (!S_ISREG(st.st_mode)) {
928 log_error_write(srv, __FILE__, __LINE__, "sb",
929 "pid-file exists and isn't regular file:", srv->srvconf.pid_file);
930 return -1;
933 if (-1 == (pid_fd = open(srv->srvconf.pid_file->ptr, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
934 log_error_write(srv, __FILE__, __LINE__, "sbs",
935 "opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
936 return -1;
939 fd_close_on_exec(pid_fd);
942 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
943 /* select limits itself
945 * as it is a hard limit and will lead to a segfault we add some safety
946 * */
947 srv->max_fds = FD_SETSIZE - 200;
948 } else {
949 srv->max_fds = 4096;
952 if (i_am_root) {
953 struct group *grp = NULL;
954 struct passwd *pwd = NULL;
955 int use_rlimit = 1;
957 #ifdef HAVE_VALGRIND_VALGRIND_H
958 if (RUNNING_ON_VALGRIND) use_rlimit = 0;
959 #endif
961 #ifdef HAVE_GETRLIMIT
962 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
963 log_error_write(srv, __FILE__, __LINE__,
964 "ss", "couldn't get 'max filedescriptors'",
965 strerror(errno));
966 return -1;
969 if (use_rlimit && srv->srvconf.max_fds) {
970 /* set rlimits */
972 rlim.rlim_cur = srv->srvconf.max_fds;
973 rlim.rlim_max = srv->srvconf.max_fds;
975 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
976 log_error_write(srv, __FILE__, __LINE__,
977 "ss", "couldn't set 'max filedescriptors'",
978 strerror(errno));
979 return -1;
983 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
984 srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200;
985 } else {
986 srv->max_fds = rlim.rlim_cur;
989 /* set core file rlimit, if enable_cores is set */
990 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
991 rlim.rlim_cur = rlim.rlim_max;
992 setrlimit(RLIMIT_CORE, &rlim);
994 #endif
995 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
996 /* don't raise the limit above FD_SET_SIZE */
997 if (srv->max_fds > ((int)FD_SETSIZE) - 200) {
998 log_error_write(srv, __FILE__, __LINE__, "sd",
999 "can't raise max filedescriptors above", FD_SETSIZE - 200,
1000 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
1001 return -1;
1006 #ifdef HAVE_PWD_H
1007 /* set user and group */
1008 if (!buffer_string_is_empty(srv->srvconf.username)) {
1009 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
1010 log_error_write(srv, __FILE__, __LINE__, "sb",
1011 "can't find username", srv->srvconf.username);
1012 return -1;
1015 if (pwd->pw_uid == 0) {
1016 log_error_write(srv, __FILE__, __LINE__, "s",
1017 "I will not set uid to 0\n");
1018 return -1;
1022 if (!buffer_string_is_empty(srv->srvconf.groupname)) {
1023 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
1024 log_error_write(srv, __FILE__, __LINE__, "sb",
1025 "can't find groupname", srv->srvconf.groupname);
1026 return -1;
1028 if (grp->gr_gid == 0) {
1029 log_error_write(srv, __FILE__, __LINE__, "s",
1030 "I will not set gid to 0\n");
1031 return -1;
1034 #endif
1035 /* we need root-perms for port < 1024 */
1036 if (0 != network_init(srv)) {
1037 plugins_free(srv);
1038 server_free(srv);
1040 return -1;
1042 #ifdef HAVE_PWD_H
1044 * Change group before chroot, when we have access
1045 * to /etc/group
1046 * */
1047 if (NULL != grp) {
1048 if (-1 == setgid(grp->gr_gid)) {
1049 log_error_write(srv, __FILE__, __LINE__, "ss", "setgid failed: ", strerror(errno));
1050 return -1;
1052 if (-1 == setgroups(0, NULL)) {
1053 log_error_write(srv, __FILE__, __LINE__, "ss", "setgroups failed: ", strerror(errno));
1054 return -1;
1056 if (!buffer_string_is_empty(srv->srvconf.username)) {
1057 initgroups(srv->srvconf.username->ptr, grp->gr_gid);
1060 #endif
1061 #ifdef HAVE_CHROOT
1062 if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
1063 tzset();
1065 if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
1066 log_error_write(srv, __FILE__, __LINE__, "ss", "chroot failed: ", strerror(errno));
1067 return -1;
1069 if (-1 == chdir("/")) {
1070 log_error_write(srv, __FILE__, __LINE__, "ss", "chdir failed: ", strerror(errno));
1071 return -1;
1074 #endif
1075 #ifdef HAVE_PWD_H
1076 /* drop root privs */
1077 if (NULL != pwd) {
1078 if (-1 == setuid(pwd->pw_uid)) {
1079 log_error_write(srv, __FILE__, __LINE__, "ss", "setuid failed: ", strerror(errno));
1080 return -1;
1083 #endif
1084 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1086 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1088 if (srv->srvconf.enable_cores) {
1089 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1091 #endif
1092 } else {
1094 #ifdef HAVE_GETRLIMIT
1095 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
1096 log_error_write(srv, __FILE__, __LINE__,
1097 "ss", "couldn't get 'max filedescriptors'",
1098 strerror(errno));
1099 return -1;
1103 * we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1105 if (srv->srvconf.max_fds && srv->srvconf.max_fds <= rlim.rlim_max) {
1106 /* set rlimits */
1108 rlim.rlim_cur = srv->srvconf.max_fds;
1110 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
1111 log_error_write(srv, __FILE__, __LINE__,
1112 "ss", "couldn't set 'max filedescriptors'",
1113 strerror(errno));
1114 return -1;
1118 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
1119 srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200;
1120 } else {
1121 srv->max_fds = rlim.rlim_cur;
1124 /* set core file rlimit, if enable_cores is set */
1125 if (srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
1126 rlim.rlim_cur = rlim.rlim_max;
1127 setrlimit(RLIMIT_CORE, &rlim);
1130 #endif
1131 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
1132 /* don't raise the limit above FD_SET_SIZE */
1133 if (srv->max_fds > ((int)FD_SETSIZE) - 200) {
1134 log_error_write(srv, __FILE__, __LINE__, "sd",
1135 "can't raise max filedescriptors above", FD_SETSIZE - 200,
1136 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
1137 return -1;
1141 if (0 != network_init(srv)) {
1142 plugins_free(srv);
1143 server_free(srv);
1145 return -1;
1149 /* set max-conns */
1150 if (srv->srvconf.max_conns > srv->max_fds/2) {
1151 /* we can't have more connections than max-fds/2 */
1152 log_error_write(srv, __FILE__, __LINE__, "sdd", "can't have more connections than fds/2: ", srv->srvconf.max_conns, srv->max_fds);
1153 srv->max_conns = srv->max_fds/2;
1154 } else if (srv->srvconf.max_conns) {
1155 /* otherwise respect the wishes of the user */
1156 srv->max_conns = srv->srvconf.max_conns;
1157 } else {
1158 /* or use the default: we really don't want to hit max-fds */
1159 srv->max_conns = srv->max_fds/3;
1162 if (HANDLER_GO_ON != plugins_call_init(srv)) {
1163 log_error_write(srv, __FILE__, __LINE__, "s", "Initialization of plugins failed. Going down.");
1165 plugins_free(srv);
1166 network_close(srv);
1167 server_free(srv);
1169 return -1;
1172 #ifdef HAVE_FORK
1173 /* network is up, let's deamonize ourself */
1174 if (srv->srvconf.dont_daemonize == 0) {
1175 parent_pipe_fd = daemonize();
1177 #endif
1180 #ifdef HAVE_SIGACTION
1181 memset(&act, 0, sizeof(act));
1182 act.sa_handler = SIG_IGN;
1183 sigaction(SIGPIPE, &act, NULL);
1184 sigaction(SIGUSR1, &act, NULL);
1185 # if defined(SA_SIGINFO)
1186 act.sa_sigaction = sigaction_handler;
1187 sigemptyset(&act.sa_mask);
1188 act.sa_flags = SA_SIGINFO;
1189 # else
1190 act.sa_handler = signal_handler;
1191 sigemptyset(&act.sa_mask);
1192 act.sa_flags = 0;
1193 # endif
1194 sigaction(SIGINT, &act, NULL);
1195 sigaction(SIGTERM, &act, NULL);
1196 sigaction(SIGHUP, &act, NULL);
1197 sigaction(SIGALRM, &act, NULL);
1199 /* it should be safe to restart syscalls after SIGCHLD */
1200 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
1201 sigaction(SIGCHLD, &act, NULL);
1203 #elif defined(HAVE_SIGNAL)
1204 /* ignore the SIGPIPE from sendfile() */
1205 signal(SIGPIPE, SIG_IGN);
1206 signal(SIGUSR1, SIG_IGN);
1207 signal(SIGALRM, signal_handler);
1208 signal(SIGTERM, signal_handler);
1209 signal(SIGHUP, signal_handler);
1210 signal(SIGCHLD, signal_handler);
1211 signal(SIGINT, signal_handler);
1212 #endif
1214 #ifdef USE_ALARM
1215 signal(SIGALRM, signal_handler);
1217 /* setup periodic timer (1 second) */
1218 if (setitimer(ITIMER_REAL, &interval, NULL)) {
1219 log_error_write(srv, __FILE__, __LINE__, "s", "setting timer failed");
1220 return -1;
1223 getitimer(ITIMER_REAL, &interval);
1224 #endif
1227 srv->gid = getgid();
1228 srv->uid = getuid();
1230 /* write pid file */
1231 if (pid_fd != -1) {
1232 buffer_copy_int(srv->tmp_buf, getpid());
1233 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\n"));
1234 if (-1 == write_all(pid_fd, CONST_BUF_LEN(srv->tmp_buf))) {
1235 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't write pid file:", strerror(errno));
1236 close(pid_fd);
1237 return -1;
1241 /* Close stderr ASAP in the child process to make sure that nothing
1242 * is being written to that fd which may not be valid anymore. */
1243 if (!srv->srvconf.preflight_check && -1 == log_error_open(srv)) {
1244 log_error_write(srv, __FILE__, __LINE__, "s", "Opening errorlog failed. Going down.");
1246 plugins_free(srv);
1247 network_close(srv);
1248 server_free(srv);
1249 return -1;
1252 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1253 log_error_write(srv, __FILE__, __LINE__, "s", "Configuration of plugins failed. Going down.");
1255 plugins_free(srv);
1256 network_close(srv);
1257 server_free(srv);
1259 return -1;
1262 /* dump unused config-keys */
1263 for (i = 0; i < srv->config_context->used; i++) {
1264 array *config = ((data_config *)srv->config_context->data[i])->value;
1265 size_t j;
1267 for (j = 0; config && j < config->used; j++) {
1268 data_unset *du = config->data[j];
1270 /* all var.* is known as user defined variable */
1271 if (strncmp(du->key->ptr, "var.", sizeof("var.") - 1) == 0) {
1272 continue;
1275 if (NULL == array_get_element(srv->config_touched, du->key->ptr)) {
1276 log_error_write(srv, __FILE__, __LINE__, "sbs",
1277 "WARNING: unknown config-key:",
1278 du->key,
1279 "(ignored)");
1284 if (srv->config_unsupported) {
1285 log_error_write(srv, __FILE__, __LINE__, "s",
1286 "Configuration contains unsupported keys. Going down.");
1289 if (srv->config_deprecated) {
1290 log_error_write(srv, __FILE__, __LINE__, "s",
1291 "Configuration contains deprecated keys. Going down.");
1294 if (srv->config_unsupported || srv->config_deprecated) {
1295 plugins_free(srv);
1296 network_close(srv);
1297 server_free(srv);
1299 return -1;
1302 if (srv->srvconf.preflight_check) {
1303 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1304 plugins_free(srv);
1305 network_close(srv);
1306 server_free(srv);
1308 exit(0);
1312 #ifdef HAVE_FORK
1314 * notify daemonize-grandparent of successful startup
1315 * do this before any further forking is done (workers)
1317 if (srv->srvconf.dont_daemonize == 0) {
1318 if (0 > write(parent_pipe_fd, "", 1)) return -1;
1319 close(parent_pipe_fd);
1322 if (idle_limit && srv->srvconf.max_worker) {
1323 srv->srvconf.max_worker = 0;
1324 log_error_write(srv, __FILE__, __LINE__, "s",
1325 "server idle time limit command line option disables server.max-worker config file option.");
1328 /* start watcher and workers */
1329 num_childs = srv->srvconf.max_worker;
1330 if (num_childs > 0) {
1331 int child = 0;
1332 while (!child && !srv_shutdown && !graceful_shutdown) {
1333 if (num_childs > 0) {
1334 switch (fork()) {
1335 case -1:
1336 return -1;
1337 case 0:
1338 child = 1;
1339 break;
1340 default:
1341 num_childs--;
1342 break;
1344 } else {
1345 int status;
1347 if (-1 != wait(&status)) {
1348 /**
1349 * one of our workers went away
1351 num_childs++;
1352 } else {
1353 switch (errno) {
1354 case EINTR:
1356 * if we receive a SIGHUP we have to close our logs ourself as we don't
1357 * have the mainloop who can help us here
1359 if (handle_sig_hup) {
1360 handle_sig_hup = 0;
1362 log_error_cycle(srv);
1365 * forward to all procs in the process-group
1367 * we also send it ourself
1369 if (!forwarded_sig_hup && 0 != srv->srvconf.max_worker) {
1370 forwarded_sig_hup = 1;
1371 kill(0, SIGHUP);
1374 break;
1375 default:
1376 break;
1383 * for the parent this is the exit-point
1385 if (!child) {
1386 /**
1387 * kill all children too
1389 if (graceful_shutdown) {
1390 kill(0, SIGINT);
1391 } else if (srv_shutdown) {
1392 kill(0, SIGTERM);
1395 remove_pid_file(srv, &pid_fd);
1396 log_error_close(srv);
1397 network_close(srv);
1398 connections_free(srv);
1399 plugins_free(srv);
1400 server_free(srv);
1401 return 0;
1405 * make sure workers do not muck with pid-file
1407 if (0 <= pid_fd) {
1408 close(pid_fd);
1409 pid_fd = -1;
1411 buffer_reset(srv->srvconf.pid_file);
1413 #endif
1415 if (NULL == (srv->ev = fdevent_init(srv, srv->max_fds + 1, srv->event_handler))) {
1416 log_error_write(srv, __FILE__, __LINE__,
1417 "s", "fdevent_init failed");
1418 return -1;
1421 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1422 #ifdef HAVE_SIGACTION
1423 sigaction(SIGCHLD, &act, NULL);
1424 #elif defined(HAVE_SIGNAL)
1425 signal(SIGCHLD, signal_handler);
1426 #endif
1429 * kqueue() is called here, select resets its internals,
1430 * all server sockets get their handlers
1432 * */
1433 if (0 != network_register_fdevents(srv)) {
1434 plugins_free(srv);
1435 network_close(srv);
1436 server_free(srv);
1438 return -1;
1441 /* might fail if user is using fam (not gamin) and famd isn't running */
1442 if (NULL == (srv->stat_cache = stat_cache_init())) {
1443 log_error_write(srv, __FILE__, __LINE__, "s",
1444 "stat-cache could not be setup, dieing.");
1445 return -1;
1448 #ifdef HAVE_FAM_H
1449 /* setup FAM */
1450 if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_FAM) {
1451 if (0 != FAMOpen2(&srv->stat_cache->fam, "lighttpd")) {
1452 log_error_write(srv, __FILE__, __LINE__, "s",
1453 "could not open a fam connection, dieing.");
1454 return -1;
1456 #ifdef HAVE_FAMNOEXISTS
1457 FAMNoExists(&srv->stat_cache->fam);
1458 #endif
1460 fdevent_register(srv->ev, FAMCONNECTION_GETFD(&srv->stat_cache->fam), stat_cache_handle_fdevent, NULL);
1461 fdevent_event_set(srv->ev, &(srv->stat_cache->fam_fcce_ndx), FAMCONNECTION_GETFD(&srv->stat_cache->fam), FDEVENT_IN);
1463 #endif
1466 /* get the current number of FDs */
1467 srv->cur_fds = open("/dev/null", O_RDONLY);
1468 close(srv->cur_fds);
1470 for (i = 0; i < srv->srv_sockets.used; i++) {
1471 server_socket *srv_socket = srv->srv_sockets.ptr[i];
1472 if (srv->sockets_disabled) continue; /* lighttpd -1 (one-shot mode) */
1473 if (-1 == fdevent_fcntl_set(srv->ev, srv_socket->fd)) {
1474 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed:", strerror(errno));
1475 return -1;
1479 if (oneshot_fd && !server_oneshot_init(srv, oneshot_fd)) {
1480 close(oneshot_fd);
1483 /* main-loop */
1484 while (!srv_shutdown) {
1485 int n;
1486 size_t ndx;
1487 time_t min_ts;
1489 if (handle_sig_hup) {
1490 handler_t r;
1492 /* reset notification */
1493 handle_sig_hup = 0;
1496 /* cycle logfiles */
1498 switch(r = plugins_call_handle_sighup(srv)) {
1499 case HANDLER_GO_ON:
1500 break;
1501 default:
1502 log_error_write(srv, __FILE__, __LINE__, "sd", "sighup-handler return with an error", r);
1503 break;
1506 if (-1 == log_error_cycle(srv)) {
1507 log_error_write(srv, __FILE__, __LINE__, "s", "cycling errorlog failed, dying");
1509 return -1;
1510 } else {
1511 #ifdef HAVE_SIGACTION
1512 log_error_write(srv, __FILE__, __LINE__, "sdsd",
1513 "logfiles cycled UID =",
1514 last_sighup_info.si_uid,
1515 "PID =",
1516 last_sighup_info.si_pid);
1517 #else
1518 log_error_write(srv, __FILE__, __LINE__, "s",
1519 "logfiles cycled");
1520 #endif
1524 if (handle_sig_alarm) {
1525 /* a new second */
1527 #ifdef USE_ALARM
1528 /* reset notification */
1529 handle_sig_alarm = 0;
1530 #endif
1532 /* get current time */
1533 min_ts = time(NULL);
1535 if (min_ts != srv->cur_ts) {
1536 #ifdef DEBUG_CONNECTION_STATES
1537 int cs = 0;
1538 #endif
1539 connections *conns = srv->conns;
1540 handler_t r;
1542 switch(r = plugins_call_handle_trigger(srv)) {
1543 case HANDLER_GO_ON:
1544 break;
1545 case HANDLER_ERROR:
1546 log_error_write(srv, __FILE__, __LINE__, "s", "one of the triggers failed");
1547 break;
1548 default:
1549 log_error_write(srv, __FILE__, __LINE__, "d", r);
1550 break;
1553 /* trigger waitpid */
1554 srv->cur_ts = min_ts;
1556 /* check idle time limit, if enabled */
1557 if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) {
1558 log_error_write(srv, __FILE__, __LINE__, "sDs", "[note] idle timeout", (int)idle_limit,
1559 "s exceeded, initiating graceful shutdown");
1560 graceful_shutdown = 2; /* value 2 indicates idle timeout */
1563 /* cleanup stat-cache */
1564 stat_cache_trigger_cleanup(srv);
1566 * check all connections for timeouts
1569 for (ndx = 0; ndx < conns->used; ndx++) {
1570 int changed = 0;
1571 connection *con;
1572 int t_diff;
1574 con = conns->ptr[ndx];
1576 if (con->state == CON_STATE_READ ||
1577 con->state == CON_STATE_READ_POST) {
1578 if (con->request_count == 1 || con->state == CON_STATE_READ_POST) {
1579 if (srv->cur_ts - con->read_idle_ts > con->conf.max_read_idle) {
1580 /* time - out */
1581 if (con->conf.log_request_handling) {
1582 log_error_write(srv, __FILE__, __LINE__, "sd",
1583 "connection closed - read timeout:", con->fd);
1586 connection_set_state(srv, con, CON_STATE_ERROR);
1587 changed = 1;
1589 } else {
1590 if (srv->cur_ts - con->read_idle_ts > con->keep_alive_idle) {
1591 /* time - out */
1592 if (con->conf.log_request_handling) {
1593 log_error_write(srv, __FILE__, __LINE__, "sd",
1594 "connection closed - keep-alive timeout:", con->fd);
1597 connection_set_state(srv, con, CON_STATE_ERROR);
1598 changed = 1;
1603 if ((con->state == CON_STATE_WRITE) &&
1604 (con->write_request_ts != 0)) {
1605 #if 0
1606 if (srv->cur_ts - con->write_request_ts > 60) {
1607 log_error_write(srv, __FILE__, __LINE__, "sdd",
1608 "connection closed - pre-write-request-timeout:", con->fd, srv->cur_ts - con->write_request_ts);
1610 #endif
1612 if (srv->cur_ts - con->write_request_ts > con->conf.max_write_idle) {
1613 /* time - out */
1614 if (con->conf.log_timeouts) {
1615 log_error_write(srv, __FILE__, __LINE__, "sbsbsosds",
1616 "NOTE: a request from",
1617 con->dst_addr_buf,
1618 "for",
1619 con->request.uri,
1620 "timed out after writing",
1621 con->bytes_written,
1622 "bytes. We waited",
1623 (int)con->conf.max_write_idle,
1624 "seconds. If this a problem increase server.max-write-idle");
1626 connection_set_state(srv, con, CON_STATE_ERROR);
1627 changed = 1;
1631 if (con->state == CON_STATE_CLOSE && (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT)) {
1632 changed = 1;
1635 /* we don't like div by zero */
1636 if (0 == (t_diff = srv->cur_ts - con->connection_start)) t_diff = 1;
1638 if (con->traffic_limit_reached &&
1639 (con->conf.kbytes_per_second == 0 ||
1640 ((con->bytes_written / t_diff) < con->conf.kbytes_per_second * 1024))) {
1641 /* enable connection again */
1642 con->traffic_limit_reached = 0;
1644 changed = 1;
1647 if (changed) {
1648 connection_state_machine(srv, con);
1650 con->bytes_written_cur_second = 0;
1651 *(con->conf.global_bytes_per_second_cnt_ptr) = 0;
1653 #if DEBUG_CONNECTION_STATES
1654 if (cs == 0) {
1655 fprintf(stderr, "connection-state: ");
1656 cs = 1;
1659 fprintf(stderr, "c[%d,%d]: %s ",
1660 con->fd,
1661 con->fcgi.fd,
1662 connection_get_state(con->state));
1663 #endif
1666 #ifdef DEBUG_CONNECTION_STATES
1667 if (cs == 1) fprintf(stderr, "\n");
1668 #endif
1672 if (srv->sockets_disabled) {
1673 /* our server sockets are disabled, why ? */
1675 if ((srv->cur_fds + srv->want_fds < srv->max_fds * 8 / 10) && /* we have enough unused fds */
1676 (srv->conns->used <= srv->max_conns * 9 / 10) &&
1677 (0 == graceful_shutdown)) {
1678 for (i = 0; i < srv->srv_sockets.used; i++) {
1679 server_socket *srv_socket = srv->srv_sockets.ptr[i];
1680 fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, FDEVENT_IN);
1683 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets enabled again");
1685 srv->sockets_disabled = 0;
1687 } else {
1688 if ((srv->cur_fds + srv->want_fds > srv->max_fds * 9 / 10) || /* out of fds */
1689 (srv->conns->used >= srv->max_conns) || /* out of connections */
1690 (graceful_shutdown)) { /* graceful_shutdown */
1692 /* disable server-fds */
1694 for (i = 0; i < srv->srv_sockets.used; i++) {
1695 server_socket *srv_socket = srv->srv_sockets.ptr[i];
1697 if (graceful_shutdown) {
1698 /* we don't want this socket anymore,
1700 * closing it right away will make it possible for
1701 * the next lighttpd to take over (graceful restart)
1702 * */
1704 fdevent_event_del(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd);
1705 fdevent_unregister(srv->ev, srv_socket->fd);
1706 close(srv_socket->fd);
1707 srv_socket->fd = -1;
1709 /* network_close() will cleanup after us */
1710 } else {
1711 fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, 0);
1715 if (graceful_shutdown) {
1716 remove_pid_file(srv, &pid_fd);
1717 log_error_write(srv, __FILE__, __LINE__, "s", "[note] graceful shutdown started");
1718 } else if (srv->conns->used >= srv->max_conns) {
1719 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, connection limit reached");
1720 } else {
1721 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, out-of-fds");
1724 srv->sockets_disabled = 1;
1728 if (graceful_shutdown && srv->conns->used == 0) {
1729 /* we are in graceful shutdown phase and all connections are closed
1730 * we are ready to terminate without harming anyone */
1731 srv_shutdown = 1;
1734 /* we still have some fds to share */
1735 if (srv->want_fds) {
1736 /* check the fdwaitqueue for waiting fds */
1737 int free_fds = srv->max_fds - srv->cur_fds - 16;
1738 connection *con;
1740 for (; free_fds > 0 && NULL != (con = fdwaitqueue_unshift(srv, srv->fdwaitqueue)); free_fds--) {
1741 connection_state_machine(srv, con);
1743 srv->want_fds--;
1747 if ((n = fdevent_poll(srv->ev, 1000)) > 0) {
1748 /* n is the number of events */
1749 int revents;
1750 int fd_ndx;
1751 #if 0
1752 if (n > 0) {
1753 log_error_write(srv, __FILE__, __LINE__, "sd",
1754 "polls:", n);
1756 #endif
1757 last_active_ts = srv->cur_ts;
1758 fd_ndx = -1;
1759 do {
1760 fdevent_handler handler;
1761 void *context;
1762 handler_t r;
1764 fd_ndx = fdevent_event_next_fdndx (srv->ev, fd_ndx);
1765 if (-1 == fd_ndx) break; /* not all fdevent handlers know how many fds got an event */
1767 revents = fdevent_event_get_revent (srv->ev, fd_ndx);
1768 fd = fdevent_event_get_fd (srv->ev, fd_ndx);
1769 handler = fdevent_get_handler(srv->ev, fd);
1770 context = fdevent_get_context(srv->ev, fd);
1772 /* connection_handle_fdevent needs a joblist_append */
1773 #if 0
1774 log_error_write(srv, __FILE__, __LINE__, "sdd",
1775 "event for", fd, revents);
1776 #endif
1777 switch (r = (*handler)(srv, context, revents)) {
1778 case HANDLER_FINISHED:
1779 case HANDLER_GO_ON:
1780 case HANDLER_WAIT_FOR_EVENT:
1781 case HANDLER_WAIT_FOR_FD:
1782 break;
1783 case HANDLER_ERROR:
1784 /* should never happen */
1785 SEGFAULT();
1786 break;
1787 default:
1788 log_error_write(srv, __FILE__, __LINE__, "d", r);
1789 break;
1791 } while (--n > 0);
1792 } else if (n < 0 && errno != EINTR) {
1793 log_error_write(srv, __FILE__, __LINE__, "ss",
1794 "fdevent_poll failed:",
1795 strerror(errno));
1798 for (ndx = 0; ndx < srv->joblist->used; ndx++) {
1799 connection *con = srv->joblist->ptr[ndx];
1800 connection_state_machine(srv, con);
1801 con->in_joblist = 0;
1804 srv->joblist->used = 0;
1807 if (0 == graceful_shutdown) {
1808 remove_pid_file(srv, &pid_fd);
1811 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */
1812 log_error_write(srv, __FILE__, __LINE__, "s",
1813 "server stopped after idle timeout");
1814 } else {
1815 #ifdef HAVE_SIGACTION
1816 log_error_write(srv, __FILE__, __LINE__, "sdsd",
1817 "server stopped by UID =",
1818 last_sigterm_info.si_uid,
1819 "PID =",
1820 last_sigterm_info.si_pid);
1821 #else
1822 log_error_write(srv, __FILE__, __LINE__, "s",
1823 "server stopped");
1824 #endif
1827 /* clean-up */
1828 log_error_close(srv);
1829 network_close(srv);
1830 connections_free(srv);
1831 plugins_free(srv);
1832 server_free(srv);
1834 return 0;