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