[mod_openssl] move openssl config into mod_openssl
[lighttpd.git] / src / server.c
blobf0df8d521515c53bb196d3dac94aaa6df0fc371f
1 #include "first.h"
3 #include "server.h"
4 #include "buffer.h"
5 #include "network.h"
6 #include "log.h"
7 #include "keyvalue.h"
8 #include "rand.h"
9 #include "response.h"
10 #include "request.h"
11 #include "chunk.h"
12 #include "http_chunk.h"
13 #include "fdevent.h"
14 #include "connections.h"
15 #include "stat_cache.h"
16 #include "plugin.h"
17 #include "joblist.h"
18 #include "network_backends.h"
19 #include "version.h"
21 #include <sys/types.h>
22 #include <sys/time.h>
23 #include <sys/stat.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <time.h>
31 #include <signal.h>
32 #include <assert.h>
33 #include <locale.h>
35 #include <stdio.h>
37 #ifdef HAVE_GETOPT_H
38 # include <getopt.h>
39 #endif
41 #ifdef HAVE_VALGRIND_VALGRIND_H
42 # include <valgrind/valgrind.h>
43 #endif
45 #ifdef HAVE_SYS_WAIT_H
46 # include <sys/wait.h>
47 #endif
49 #ifdef HAVE_PWD_H
50 # include <grp.h>
51 # include <pwd.h>
52 #endif
54 #ifdef HAVE_SYS_RESOURCE_H
55 # include <sys/resource.h>
56 #endif
58 #ifdef HAVE_SYS_PRCTL_H
59 # include <sys/prctl.h>
60 #endif
62 #if defined HAVE_LIBSSL && defined HAVE_OPENSSL_SSL_H
63 #define USE_SSL
64 #define TEXT_SSL " (ssl)"
65 #else
66 #define TEXT_SSL
67 #endif
69 #ifndef __sgi
70 /* IRIX doesn't like the alarm based time() optimization */
71 /* #define USE_ALARM */
72 #endif
74 #ifdef HAVE_GETUID
75 # ifndef HAVE_ISSETUGID
77 static int l_issetugid(void) {
78 return (geteuid() != getuid() || getegid() != getgid());
81 # define issetugid l_issetugid
82 # endif
83 #endif
85 static int oneshot_fd = 0;
86 static volatile sig_atomic_t srv_shutdown = 0;
87 static volatile sig_atomic_t graceful_shutdown = 0;
88 static volatile sig_atomic_t handle_sig_alarm = 1;
89 static volatile sig_atomic_t handle_sig_hup = 0;
90 static volatile sig_atomic_t forwarded_sig_hup = 0;
92 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
93 static volatile siginfo_t last_sigterm_info;
94 static volatile siginfo_t last_sighup_info;
96 static void sigaction_handler(int sig, siginfo_t *si, void *context) {
97 static siginfo_t empty_siginfo;
98 UNUSED(context);
100 if (!si) si = &empty_siginfo;
102 switch (sig) {
103 case SIGTERM:
104 srv_shutdown = 1;
105 last_sigterm_info = *si;
106 break;
107 case SIGINT:
108 if (graceful_shutdown) {
109 srv_shutdown = 1;
110 } else {
111 graceful_shutdown = 1;
113 last_sigterm_info = *si;
115 break;
116 case SIGALRM:
117 handle_sig_alarm = 1;
118 break;
119 case SIGHUP:
120 /**
121 * we send the SIGHUP to all procs in the process-group
122 * this includes ourself
124 * make sure we only send it once and don't create a
125 * infinite loop
127 if (!forwarded_sig_hup) {
128 handle_sig_hup = 1;
129 last_sighup_info = *si;
130 } else {
131 forwarded_sig_hup = 0;
133 break;
134 case SIGCHLD:
135 break;
138 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
139 static void signal_handler(int sig) {
140 switch (sig) {
141 case SIGTERM: srv_shutdown = 1; break;
142 case SIGINT:
143 if (graceful_shutdown) srv_shutdown = 1;
144 else graceful_shutdown = 1;
146 break;
147 case SIGALRM: handle_sig_alarm = 1; break;
148 case SIGHUP: handle_sig_hup = 1; break;
149 case SIGCHLD: break;
152 #endif
154 #ifdef HAVE_FORK
155 static int daemonize(void) {
156 int pipefd[2];
157 pid_t pid;
158 #ifdef SIGTTOU
159 signal(SIGTTOU, SIG_IGN);
160 #endif
161 #ifdef SIGTTIN
162 signal(SIGTTIN, SIG_IGN);
163 #endif
164 #ifdef SIGTSTP
165 signal(SIGTSTP, SIG_IGN);
166 #endif
168 if (pipe(pipefd) < 0) exit(-1);
170 if (0 > (pid = fork())) exit(-1);
172 if (0 < pid) {
173 char buf;
174 ssize_t bytes;
176 close(pipefd[1]);
177 /* parent waits for grandchild to be ready */
178 do {
179 bytes = read(pipefd[0], &buf, sizeof(buf));
180 } while (bytes < 0 && EINTR == errno);
181 close(pipefd[0]);
183 if (bytes <= 0) {
184 /* closed fd (without writing) == failure in grandchild */
185 fputs("daemonized server failed to start; check error log for details\n", stderr);
186 exit(-1);
189 exit(0);
192 close(pipefd[0]);
194 if (-1 == setsid()) exit(0);
196 signal(SIGHUP, SIG_IGN);
198 if (0 != fork()) exit(0);
200 if (0 != chdir("/")) exit(0);
202 fd_close_on_exec(pipefd[1]);
203 return pipefd[1];
205 #endif
207 static server *server_init(void) {
208 int i;
209 server *srv = calloc(1, sizeof(*srv));
210 force_assert(srv);
211 #define CLEAN(x) \
212 srv->x = buffer_init();
214 CLEAN(response_header);
215 CLEAN(parse_full_path);
216 CLEAN(ts_debug_str);
217 CLEAN(ts_date_str);
218 CLEAN(errorlog_buf);
219 CLEAN(response_range);
220 CLEAN(tmp_buf);
221 srv->empty_string = buffer_init_string("");
222 CLEAN(cond_check_buf);
224 CLEAN(srvconf.errorlog_file);
225 CLEAN(srvconf.breakagelog_file);
226 CLEAN(srvconf.groupname);
227 CLEAN(srvconf.username);
228 CLEAN(srvconf.changeroot);
229 CLEAN(srvconf.bindhost);
230 CLEAN(srvconf.event_handler);
231 CLEAN(srvconf.pid_file);
233 CLEAN(tmp_chunk_len);
234 #undef CLEAN
236 #define CLEAN(x) \
237 srv->x = array_init();
239 CLEAN(config_context);
240 CLEAN(config_touched);
241 CLEAN(status);
242 #undef CLEAN
244 for (i = 0; i < FILE_CACHE_MAX; i++) {
245 srv->mtime_cache[i].mtime = (time_t)-1;
246 srv->mtime_cache[i].str = buffer_init();
249 li_rand_reseed();
251 srv->cur_ts = time(NULL);
252 srv->startup_ts = srv->cur_ts;
254 srv->conns = calloc(1, sizeof(*srv->conns));
255 force_assert(srv->conns);
257 srv->joblist = calloc(1, sizeof(*srv->joblist));
258 force_assert(srv->joblist);
260 srv->fdwaitqueue = calloc(1, sizeof(*srv->fdwaitqueue));
261 force_assert(srv->fdwaitqueue);
263 srv->srvconf.modules = array_init();
264 srv->srvconf.modules_dir = buffer_init_string(LIBRARY_DIR);
265 srv->srvconf.network_backend = buffer_init();
266 srv->srvconf.upload_tempdirs = array_init();
267 srv->srvconf.reject_expect_100_with_417 = 1;
268 srv->srvconf.xattr_name = buffer_init_string("Content-Type");
269 srv->srvconf.http_header_strict = 1;
270 srv->srvconf.http_host_strict = 1; /*(implies http_host_normalize)*/
271 srv->srvconf.http_host_normalize = 0;
272 srv->srvconf.high_precision_timestamps = 0;
273 srv->srvconf.max_request_field_size = 8192;
274 srv->srvconf.loadavg[0] = 0.0;
275 srv->srvconf.loadavg[1] = 0.0;
276 srv->srvconf.loadavg[2] = 0.0;
278 /* use syslog */
279 srv->errorlog_fd = STDERR_FILENO;
280 srv->errorlog_mode = ERRORLOG_FD;
282 srv->split_vals = array_init();
283 srv->request_env = plugins_call_handle_request_env;
285 return srv;
288 static void server_free(server *srv) {
289 size_t i;
291 for (i = 0; i < FILE_CACHE_MAX; i++) {
292 buffer_free(srv->mtime_cache[i].str);
295 if (oneshot_fd > 0) {
296 close(oneshot_fd);
299 #define CLEAN(x) \
300 buffer_free(srv->x);
302 CLEAN(response_header);
303 CLEAN(parse_full_path);
304 CLEAN(ts_debug_str);
305 CLEAN(ts_date_str);
306 CLEAN(errorlog_buf);
307 CLEAN(response_range);
308 CLEAN(tmp_buf);
309 CLEAN(empty_string);
310 CLEAN(cond_check_buf);
312 CLEAN(srvconf.errorlog_file);
313 CLEAN(srvconf.breakagelog_file);
314 CLEAN(srvconf.groupname);
315 CLEAN(srvconf.username);
316 CLEAN(srvconf.changeroot);
317 CLEAN(srvconf.bindhost);
318 CLEAN(srvconf.event_handler);
319 CLEAN(srvconf.pid_file);
320 CLEAN(srvconf.modules_dir);
321 CLEAN(srvconf.network_backend);
322 CLEAN(srvconf.xattr_name);
324 CLEAN(tmp_chunk_len);
325 #undef CLEAN
327 #if 0
328 fdevent_unregister(srv->ev, srv->fd);
329 #endif
330 fdevent_free(srv->ev);
332 free(srv->conns);
334 if (srv->config_storage) {
335 for (i = 0; i < srv->config_context->used; i++) {
336 specific_config *s = srv->config_storage[i];
338 if (!s) continue;
340 buffer_free(s->document_root);
341 buffer_free(s->server_name);
342 buffer_free(s->server_tag);
343 buffer_free(s->error_handler);
344 buffer_free(s->error_handler_404);
345 buffer_free(s->errorfile_prefix);
346 array_free(s->mimetypes);
347 free(s);
349 free(srv->config_storage);
350 srv->config_storage = NULL;
353 #define CLEAN(x) \
354 array_free(srv->x);
356 CLEAN(config_context);
357 CLEAN(config_touched);
358 CLEAN(status);
359 CLEAN(srvconf.upload_tempdirs);
360 #undef CLEAN
362 joblist_free(srv, srv->joblist);
363 fdwaitqueue_free(srv, srv->fdwaitqueue);
365 if (srv->stat_cache) {
366 stat_cache_free(srv->stat_cache);
369 array_free(srv->srvconf.modules);
370 array_free(srv->split_vals);
372 li_rand_cleanup();
374 free(srv);
377 static void remove_pid_file(server *srv, int *pid_fd) {
378 if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= *pid_fd) {
379 if (0 != ftruncate(*pid_fd, 0)) {
380 log_error_write(srv, __FILE__, __LINE__, "sbds",
381 "ftruncate failed for:",
382 srv->srvconf.pid_file,
383 errno,
384 strerror(errno));
387 if (0 <= *pid_fd) {
388 close(*pid_fd);
389 *pid_fd = -1;
391 if (!buffer_string_is_empty(srv->srvconf.pid_file) &&
392 buffer_string_is_empty(srv->srvconf.changeroot)) {
393 if (0 != unlink(srv->srvconf.pid_file->ptr)) {
394 if (errno != EACCES && errno != EPERM) {
395 log_error_write(srv, __FILE__, __LINE__, "sbds",
396 "unlink failed for:",
397 srv->srvconf.pid_file,
398 errno,
399 strerror(errno));
406 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) {
407 server_socket *srv_socket, *srv_socket_wild = NULL;
408 size_t i;
409 for (i = 0; i < srv->srv_sockets.used; ++i) {
410 srv_socket = srv->srv_sockets.ptr[i];
411 if (cnt_addr->plain.sa_family != srv_socket->addr.plain.sa_family) continue;
412 switch (cnt_addr->plain.sa_family) {
413 case AF_INET:
414 if (srv_socket->addr.ipv4.sin_port != cnt_addr->ipv4.sin_port) continue;
415 if (srv_socket->addr.ipv4.sin_addr.s_addr == cnt_addr->ipv4.sin_addr.s_addr) {
416 return srv_socket;
418 if (srv_socket->addr.ipv4.sin_addr.s_addr == htonl(INADDR_ANY)) {
419 srv_socket_wild = srv_socket;
421 continue;
422 #ifdef HAVE_IPV6
423 case AF_INET6:
424 if (srv_socket->addr.ipv6.sin6_port != cnt_addr->ipv6.sin6_port) continue;
425 if (0 == memcmp(&srv_socket->addr.ipv6.sin6_addr, &cnt_addr->ipv6.sin6_addr, sizeof(struct in6_addr))) {
426 return srv_socket;
428 if (0 == memcmp(&srv_socket->addr.ipv6.sin6_addr, &in6addr_any, sizeof(struct in6_addr))) {
429 srv_socket_wild = srv_socket;
431 continue;
432 #endif
433 #ifdef HAVE_SYS_UN_H
434 case AF_UNIX:
435 if (0 == strcmp(srv_socket->addr.un.sun_path, cnt_addr->un.sun_path)) {
436 return srv_socket;
438 continue;
439 #endif
440 default: continue;
444 if (NULL != srv_socket_wild) {
445 return srv_socket_wild;
446 } else if (srv->srv_sockets.used) {
447 return srv->srv_sockets.ptr[0];
448 } else {
449 log_error_write(srv, __FILE__, __LINE__, "s", "no sockets configured");
450 return NULL;
455 static int server_oneshot_init(server *srv, int fd) {
456 /* Note: does not work with netcat due to requirement that fd be socket.
457 * STDOUT_FILENO was not saved earlier in startup, and that is to where
458 * netcat expects output to be sent. Since lighttpd expects connections
459 * to be sockets, con->fd is where output is sent; separate fds are not
460 * stored for input and output, but netcat has different fds for stdin
461 * and * stdout. To support netcat, would additionally need to avoid
462 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
463 * addresses from environment variables:
464 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
465 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
466 * NCAT_PROTO
468 connection *con;
469 server_socket *srv_socket;
470 sock_addr cnt_addr;
471 socklen_t cnt_len;
472 struct stat st;
474 if (0 != fstat(fd, &st)) {
475 log_error_write(srv, __FILE__, __LINE__, "ss", "fstat:", strerror(errno));
476 return 0;
479 if (!S_ISSOCK(st.st_mode)) {
480 /* require that fd is a socket
481 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
482 log_error_write(srv, __FILE__, __LINE__, "s", "lighttpd -1 stdin is not a socket");
483 return 0;
486 cnt_len = sizeof(cnt_addr);
487 if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
488 log_error_write(srv, __FILE__, __LINE__, "ss", "getsockname:", strerror(errno));
489 return 0;
492 srv_socket = server_oneshot_getsock(srv, &cnt_addr);
493 if (NULL == srv_socket) return 0;
495 cnt_len = sizeof(cnt_addr);
496 if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
497 log_error_write(srv, __FILE__, __LINE__, "ss", "getpeername:", strerror(errno));
498 return 0;
501 if (cnt_addr.plain.sa_family != AF_UNIX) {
502 network_accept_tcp_nagle_disable(fd);
505 con = connection_accepted(srv, srv_socket, &cnt_addr, fd);
506 if (NULL == con) return 0;
508 connection_state_machine(srv, con);
509 return 1;
513 static void show_version (void) {
514 char *b = PACKAGE_DESC TEXT_SSL \
515 " - a light and fast webserver\n" \
516 "Build-Date: " __DATE__ " " __TIME__ "\n";
518 write_all(STDOUT_FILENO, b, strlen(b));
521 static void show_features (void) {
522 const char features[] = ""
523 #ifdef USE_SELECT
524 "\t+ select (generic)\n"
525 #else
526 "\t- select (generic)\n"
527 #endif
528 #ifdef USE_POLL
529 "\t+ poll (Unix)\n"
530 #else
531 "\t- poll (Unix)\n"
532 #endif
533 #ifdef USE_LINUX_EPOLL
534 "\t+ epoll (Linux 2.6)\n"
535 #else
536 "\t- epoll (Linux 2.6)\n"
537 #endif
538 #ifdef USE_SOLARIS_DEVPOLL
539 "\t+ /dev/poll (Solaris)\n"
540 #else
541 "\t- /dev/poll (Solaris)\n"
542 #endif
543 #ifdef USE_SOLARIS_PORT
544 "\t+ eventports (Solaris)\n"
545 #else
546 "\t- eventports (Solaris)\n"
547 #endif
548 #ifdef USE_FREEBSD_KQUEUE
549 "\t+ kqueue (FreeBSD)\n"
550 #else
551 "\t- kqueue (FreeBSD)\n"
552 #endif
553 #ifdef USE_LIBEV
554 "\t+ libev (generic)\n"
555 #else
556 "\t- libev (generic)\n"
557 #endif
558 "\nNetwork handler:\n\n"
559 #if defined USE_LINUX_SENDFILE
560 "\t+ linux-sendfile\n"
561 #else
562 "\t- linux-sendfile\n"
563 #endif
564 #if defined USE_FREEBSD_SENDFILE
565 "\t+ freebsd-sendfile\n"
566 #else
567 "\t- freebsd-sendfile\n"
568 #endif
569 #if defined USE_DARWIN_SENDFILE
570 "\t+ darwin-sendfile\n"
571 #else
572 "\t- darwin-sendfile\n"
573 #endif
574 #if defined USE_SOLARIS_SENDFILEV
575 "\t+ solaris-sendfilev\n"
576 #else
577 "\t- solaris-sendfilev\n"
578 #endif
579 #if defined USE_WRITEV
580 "\t+ writev\n"
581 #else
582 "\t- writev\n"
583 #endif
584 "\t+ write\n"
585 #ifdef USE_MMAP
586 "\t+ mmap support\n"
587 #else
588 "\t- mmap support\n"
589 #endif
590 "\nFeatures:\n\n"
591 #ifdef HAVE_IPV6
592 "\t+ IPv6 support\n"
593 #else
594 "\t- IPv6 support\n"
595 #endif
596 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
597 "\t+ zlib support\n"
598 #else
599 "\t- zlib support\n"
600 #endif
601 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
602 "\t+ bzip2 support\n"
603 #else
604 "\t- bzip2 support\n"
605 #endif
606 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
607 "\t+ crypt support\n"
608 #else
609 "\t- crypt support\n"
610 #endif
611 #ifdef USE_SSL
612 "\t+ SSL support\n"
613 #else
614 "\t- SSL support\n"
615 #endif
616 #ifdef HAVE_LIBPCRE
617 "\t+ PCRE support\n"
618 #else
619 "\t- PCRE support\n"
620 #endif
621 #ifdef HAVE_MYSQL
622 "\t+ MySQL support\n"
623 #else
624 "\t- MySQL support\n"
625 #endif
626 #ifdef HAVE_KRB5
627 "\t+ Kerberos support\n"
628 #else
629 "\t- Kerberos support\n"
630 #endif
631 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
632 "\t+ LDAP support\n"
633 #else
634 "\t- LDAP support\n"
635 #endif
636 #ifdef USE_MEMCACHED
637 "\t+ memcached support\n"
638 #else
639 "\t- memcached support\n"
640 #endif
641 #ifdef HAVE_FAM_H
642 "\t+ FAM support\n"
643 #else
644 "\t- FAM support\n"
645 #endif
646 #ifdef HAVE_LUA_H
647 "\t+ LUA support\n"
648 #else
649 "\t- LUA support\n"
650 #endif
651 #ifdef HAVE_LIBXML_H
652 "\t+ xml support\n"
653 #else
654 "\t- xml support\n"
655 #endif
656 #ifdef HAVE_SQLITE3_H
657 "\t+ SQLite support\n"
658 #else
659 "\t- SQLite support\n"
660 #endif
661 #ifdef HAVE_GDBM_H
662 "\t+ GDBM support\n"
663 #else
664 "\t- GDBM support\n"
665 #endif
666 "\n";
667 show_version();
668 printf("\nEvent Handlers:\n\n%s", features);
671 static void show_help (void) {
672 char *b = PACKAGE_DESC TEXT_SSL " ("__DATE__ " " __TIME__ ")" \
673 " - a light and fast webserver\n" \
674 "usage:\n" \
675 " -f <name> filename of the config-file\n" \
676 " -m <name> module directory (default: "LIBRARY_DIR")\n" \
677 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
678 " -1 process single (one) request on stdin socket, then exit\n" \
679 " -p print the parsed config-file in internal form, and exit\n" \
680 " -t test config-file syntax, then exit\n" \
681 " -tt test config-file syntax, load and init modules, then exit\n" \
682 " -D don't go to background (default: go to background)\n" \
683 " -v show version\n" \
684 " -V show compile-time features\n" \
685 " -h show this help\n" \
686 "\n"
688 write_all(STDOUT_FILENO, b, strlen(b));
691 int main (int argc, char **argv) {
692 server *srv = NULL;
693 int print_config = 0;
694 int test_config = 0;
695 int i_am_root;
696 int o;
697 int num_childs = 0;
698 int pid_fd = -1, fd;
699 size_t i;
700 time_t idle_limit = 0, last_active_ts = time(NULL);
701 #ifdef HAVE_SIGACTION
702 struct sigaction act;
703 #endif
704 #ifdef HAVE_GETRLIMIT
705 struct rlimit rlim;
706 #endif
708 #ifdef HAVE_FORK
709 int parent_pipe_fd = -1;
710 #endif
712 #ifdef USE_ALARM
713 struct itimerval interval;
715 interval.it_interval.tv_sec = 1;
716 interval.it_interval.tv_usec = 0;
717 interval.it_value.tv_sec = 1;
718 interval.it_value.tv_usec = 0;
719 #endif
721 /* for nice %b handling in strfime() */
722 setlocale(LC_TIME, "C");
724 if (NULL == (srv = server_init())) {
725 fprintf(stderr, "did this really happen?\n");
726 return -1;
729 /* init structs done */
731 srv->srvconf.port = 0;
732 #ifdef HAVE_GETUID
733 i_am_root = (getuid() == 0);
734 #else
735 i_am_root = 0;
736 #endif
737 srv->srvconf.dont_daemonize = 0;
738 srv->srvconf.preflight_check = 0;
740 while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) {
741 switch(o) {
742 case 'f':
743 if (srv->config_storage) {
744 log_error_write(srv, __FILE__, __LINE__, "s",
745 "Can only read one config file. Use the include command to use multiple config files.");
747 server_free(srv);
748 return -1;
750 if (config_read(srv, optarg)) {
751 server_free(srv);
752 return -1;
754 break;
755 case 'm':
756 buffer_copy_string(srv->srvconf.modules_dir, optarg);
757 break;
758 case 'i': {
759 char *endptr;
760 long timeout = strtol(optarg, &endptr, 0);
761 if (!*optarg || *endptr || timeout < 0) {
762 log_error_write(srv, __FILE__, __LINE__, "ss",
763 "Invalid idle timeout value:", optarg);
764 server_free(srv);
765 return -1;
767 idle_limit = (time_t)timeout;
768 break;
770 case 'p': print_config = 1; break;
771 case 't': ++test_config; break;
772 case '1': oneshot_fd = dup(STDIN_FILENO); break;
773 case 'D': srv->srvconf.dont_daemonize = 1; break;
774 case 'v': show_version(); server_free(srv); return 0;
775 case 'V': show_features(); server_free(srv); return 0;
776 case 'h': show_help(); server_free(srv); return 0;
777 default:
778 show_help();
779 server_free(srv);
780 return -1;
784 if (!srv->config_storage) {
785 log_error_write(srv, __FILE__, __LINE__, "s",
786 "No configuration available. Try using -f option.");
788 server_free(srv);
789 return -1;
792 if (print_config) {
793 data_unset *dc = srv->config_context->data[0];
794 if (dc) {
795 dc->print(dc, 0);
796 fprintf(stdout, "\n");
797 } else {
798 /* shouldn't happend */
799 fprintf(stderr, "global config not found\n");
803 if (test_config) {
804 if (1 == test_config) {
805 printf("Syntax OK\n");
806 } else { /*(test_config > 1)*/
807 test_config = 0;
808 srv->srvconf.preflight_check = 1;
809 srv->srvconf.dont_daemonize = 1;
810 buffer_reset(srv->srvconf.pid_file);
814 if (test_config || print_config) {
815 server_free(srv);
816 return 0;
819 if (oneshot_fd) {
820 if (oneshot_fd <= STDERR_FILENO) {
821 log_error_write(srv, __FILE__, __LINE__, "s",
822 "Invalid fds at startup with lighttpd -1");
823 server_free(srv);
824 return -1;
826 graceful_shutdown = 1;
827 srv->sockets_disabled = 1;
828 srv->srvconf.dont_daemonize = 1;
829 buffer_reset(srv->srvconf.pid_file);
830 if (srv->srvconf.max_worker) {
831 srv->srvconf.max_worker = 0;
832 log_error_write(srv, __FILE__, __LINE__, "s",
833 "server one-shot command line option disables server.max-worker config file option.");
837 /* close stdin and stdout, as they are not needed */
838 openDevNull(STDIN_FILENO);
839 openDevNull(STDOUT_FILENO);
841 if (0 != config_set_defaults(srv)) {
842 log_error_write(srv, __FILE__, __LINE__, "s",
843 "setting default values failed");
844 server_free(srv);
845 return -1;
848 /* UID handling */
849 #ifdef HAVE_GETUID
850 if (!i_am_root && issetugid()) {
851 /* we are setuid-root */
853 log_error_write(srv, __FILE__, __LINE__, "s",
854 "Are you nuts ? Don't apply a SUID bit to this binary");
856 server_free(srv);
857 return -1;
859 #endif
861 /* check document-root */
862 if (buffer_string_is_empty(srv->config_storage[0]->document_root)) {
863 log_error_write(srv, __FILE__, __LINE__, "s",
864 "document-root is not set\n");
866 server_free(srv);
868 return -1;
871 if (plugins_load(srv)) {
872 log_error_write(srv, __FILE__, __LINE__, "s",
873 "loading plugins finally failed");
875 plugins_free(srv);
876 server_free(srv);
878 return -1;
881 /* open pid file BEFORE chroot */
882 if (!buffer_string_is_empty(srv->srvconf.pid_file)) {
883 if (-1 == (pid_fd = fdevent_open_cloexec(srv->srvconf.pid_file->ptr, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
884 struct stat st;
885 if (errno != EEXIST) {
886 log_error_write(srv, __FILE__, __LINE__, "sbs",
887 "opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
888 return -1;
891 if (0 != stat(srv->srvconf.pid_file->ptr, &st)) {
892 log_error_write(srv, __FILE__, __LINE__, "sbs",
893 "stating existing pid-file failed:", srv->srvconf.pid_file, strerror(errno));
896 if (!S_ISREG(st.st_mode)) {
897 log_error_write(srv, __FILE__, __LINE__, "sb",
898 "pid-file exists and isn't regular file:", srv->srvconf.pid_file);
899 return -1;
902 if (-1 == (pid_fd = open(srv->srvconf.pid_file->ptr, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
903 log_error_write(srv, __FILE__, __LINE__, "sbs",
904 "opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
905 return -1;
910 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
911 /* select limits itself
913 * as it is a hard limit and will lead to a segfault we add some safety
914 * */
915 srv->max_fds = FD_SETSIZE - 200;
916 } else {
917 srv->max_fds = 4096;
920 if (i_am_root) {
921 struct group *grp = NULL;
922 struct passwd *pwd = NULL;
923 int use_rlimit = 1;
925 #ifdef HAVE_VALGRIND_VALGRIND_H
926 if (RUNNING_ON_VALGRIND) use_rlimit = 0;
927 #endif
929 #ifdef HAVE_GETRLIMIT
930 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
931 log_error_write(srv, __FILE__, __LINE__,
932 "ss", "couldn't get 'max filedescriptors'",
933 strerror(errno));
934 return -1;
937 if (use_rlimit && srv->srvconf.max_fds) {
938 /* set rlimits */
940 rlim.rlim_cur = srv->srvconf.max_fds;
941 rlim.rlim_max = srv->srvconf.max_fds;
943 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
944 log_error_write(srv, __FILE__, __LINE__,
945 "ss", "couldn't set 'max filedescriptors'",
946 strerror(errno));
947 return -1;
951 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
952 srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200;
953 } else {
954 srv->max_fds = rlim.rlim_cur;
957 /* set core file rlimit, if enable_cores is set */
958 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
959 rlim.rlim_cur = rlim.rlim_max;
960 setrlimit(RLIMIT_CORE, &rlim);
962 #endif
963 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
964 /* don't raise the limit above FD_SET_SIZE */
965 if (srv->max_fds > ((int)FD_SETSIZE) - 200) {
966 log_error_write(srv, __FILE__, __LINE__, "sd",
967 "can't raise max filedescriptors above", FD_SETSIZE - 200,
968 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
969 return -1;
974 #ifdef HAVE_PWD_H
975 /* set user and group */
976 if (!buffer_string_is_empty(srv->srvconf.groupname)) {
977 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
978 log_error_write(srv, __FILE__, __LINE__, "sb",
979 "can't find groupname", srv->srvconf.groupname);
980 return -1;
984 if (!buffer_string_is_empty(srv->srvconf.username)) {
985 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
986 log_error_write(srv, __FILE__, __LINE__, "sb",
987 "can't find username", srv->srvconf.username);
988 return -1;
991 if (pwd->pw_uid == 0) {
992 log_error_write(srv, __FILE__, __LINE__, "s",
993 "I will not set uid to 0\n");
994 return -1;
997 if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) {
998 log_error_write(srv, __FILE__, __LINE__, "sd",
999 "can't find group id", pwd->pw_gid);
1000 return -1;
1004 if (NULL != grp) {
1005 if (grp->gr_gid == 0) {
1006 log_error_write(srv, __FILE__, __LINE__, "s",
1007 "I will not set gid to 0\n");
1008 return -1;
1011 #endif
1012 /* we need root-perms for port < 1024 */
1013 if (0 != network_init(srv)) {
1014 plugins_free(srv);
1015 server_free(srv);
1017 return -1;
1019 #ifdef HAVE_PWD_H
1021 * Change group before chroot, when we have access
1022 * to /etc/group
1023 * */
1024 if (NULL != grp) {
1025 if (-1 == setgid(grp->gr_gid)) {
1026 log_error_write(srv, __FILE__, __LINE__, "ss", "setgid failed: ", strerror(errno));
1027 return -1;
1029 if (-1 == setgroups(0, NULL)) {
1030 log_error_write(srv, __FILE__, __LINE__, "ss", "setgroups failed: ", strerror(errno));
1031 return -1;
1033 if (!buffer_string_is_empty(srv->srvconf.username)) {
1034 initgroups(srv->srvconf.username->ptr, grp->gr_gid);
1037 #endif
1038 #ifdef HAVE_CHROOT
1039 if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
1040 tzset();
1042 if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
1043 log_error_write(srv, __FILE__, __LINE__, "ss", "chroot failed: ", strerror(errno));
1044 return -1;
1046 if (-1 == chdir("/")) {
1047 log_error_write(srv, __FILE__, __LINE__, "ss", "chdir failed: ", strerror(errno));
1048 return -1;
1051 #endif
1052 #ifdef HAVE_PWD_H
1053 /* drop root privs */
1054 if (NULL != pwd) {
1055 if (-1 == setuid(pwd->pw_uid)) {
1056 log_error_write(srv, __FILE__, __LINE__, "ss", "setuid failed: ", strerror(errno));
1057 return -1;
1060 #endif
1061 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1063 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1065 if (srv->srvconf.enable_cores) {
1066 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1068 #endif
1069 } else {
1071 #ifdef HAVE_GETRLIMIT
1072 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
1073 log_error_write(srv, __FILE__, __LINE__,
1074 "ss", "couldn't get 'max filedescriptors'",
1075 strerror(errno));
1076 return -1;
1080 * we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1082 if (srv->srvconf.max_fds && srv->srvconf.max_fds <= rlim.rlim_max) {
1083 /* set rlimits */
1085 rlim.rlim_cur = srv->srvconf.max_fds;
1087 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
1088 log_error_write(srv, __FILE__, __LINE__,
1089 "ss", "couldn't set 'max filedescriptors'",
1090 strerror(errno));
1091 return -1;
1095 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
1096 srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200;
1097 } else {
1098 srv->max_fds = rlim.rlim_cur;
1101 /* set core file rlimit, if enable_cores is set */
1102 if (srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
1103 rlim.rlim_cur = rlim.rlim_max;
1104 setrlimit(RLIMIT_CORE, &rlim);
1107 #endif
1108 if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
1109 /* don't raise the limit above FD_SET_SIZE */
1110 if (srv->max_fds > ((int)FD_SETSIZE) - 200) {
1111 log_error_write(srv, __FILE__, __LINE__, "sd",
1112 "can't raise max filedescriptors above", FD_SETSIZE - 200,
1113 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
1114 return -1;
1118 if (0 != network_init(srv)) {
1119 plugins_free(srv);
1120 server_free(srv);
1122 return -1;
1126 /* set max-conns */
1127 if (srv->srvconf.max_conns > srv->max_fds/2) {
1128 /* we can't have more connections than max-fds/2 */
1129 log_error_write(srv, __FILE__, __LINE__, "sdd", "can't have more connections than fds/2: ", srv->srvconf.max_conns, srv->max_fds);
1130 srv->max_conns = srv->max_fds/2;
1131 } else if (srv->srvconf.max_conns) {
1132 /* otherwise respect the wishes of the user */
1133 srv->max_conns = srv->srvconf.max_conns;
1134 } else {
1135 /* or use the default: we really don't want to hit max-fds */
1136 srv->max_conns = srv->max_fds/3;
1139 if (HANDLER_GO_ON != plugins_call_init(srv)) {
1140 log_error_write(srv, __FILE__, __LINE__, "s", "Initialization of plugins failed. Going down.");
1142 plugins_free(srv);
1143 network_close(srv);
1144 server_free(srv);
1146 return -1;
1149 #ifdef HAVE_FORK
1150 /* network is up, let's deamonize ourself */
1151 if (srv->srvconf.dont_daemonize == 0) {
1152 parent_pipe_fd = daemonize();
1154 #endif
1157 #ifdef HAVE_SIGACTION
1158 memset(&act, 0, sizeof(act));
1159 act.sa_handler = SIG_IGN;
1160 sigaction(SIGPIPE, &act, NULL);
1161 sigaction(SIGUSR1, &act, NULL);
1162 # if defined(SA_SIGINFO)
1163 act.sa_sigaction = sigaction_handler;
1164 sigemptyset(&act.sa_mask);
1165 act.sa_flags = SA_SIGINFO;
1166 # else
1167 act.sa_handler = signal_handler;
1168 sigemptyset(&act.sa_mask);
1169 act.sa_flags = 0;
1170 # endif
1171 sigaction(SIGINT, &act, NULL);
1172 sigaction(SIGTERM, &act, NULL);
1173 sigaction(SIGHUP, &act, NULL);
1174 sigaction(SIGALRM, &act, NULL);
1176 /* it should be safe to restart syscalls after SIGCHLD */
1177 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
1178 sigaction(SIGCHLD, &act, NULL);
1180 #elif defined(HAVE_SIGNAL)
1181 /* ignore the SIGPIPE from sendfile() */
1182 signal(SIGPIPE, SIG_IGN);
1183 signal(SIGUSR1, SIG_IGN);
1184 signal(SIGALRM, signal_handler);
1185 signal(SIGTERM, signal_handler);
1186 signal(SIGHUP, signal_handler);
1187 signal(SIGCHLD, signal_handler);
1188 signal(SIGINT, signal_handler);
1189 #endif
1191 #ifdef USE_ALARM
1192 signal(SIGALRM, signal_handler);
1194 /* setup periodic timer (1 second) */
1195 if (setitimer(ITIMER_REAL, &interval, NULL)) {
1196 log_error_write(srv, __FILE__, __LINE__, "s", "setting timer failed");
1197 return -1;
1200 getitimer(ITIMER_REAL, &interval);
1201 #endif
1204 srv->gid = getgid();
1205 srv->uid = getuid();
1207 /* write pid file */
1208 if (pid_fd != -1) {
1209 buffer_copy_int(srv->tmp_buf, getpid());
1210 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\n"));
1211 if (-1 == write_all(pid_fd, CONST_BUF_LEN(srv->tmp_buf))) {
1212 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't write pid file:", strerror(errno));
1213 close(pid_fd);
1214 return -1;
1218 /* Close stderr ASAP in the child process to make sure that nothing
1219 * is being written to that fd which may not be valid anymore. */
1220 if (!srv->srvconf.preflight_check && -1 == log_error_open(srv)) {
1221 log_error_write(srv, __FILE__, __LINE__, "s", "Opening errorlog failed. Going down.");
1223 plugins_free(srv);
1224 network_close(srv);
1225 server_free(srv);
1226 return -1;
1229 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1230 log_error_write(srv, __FILE__, __LINE__, "s", "Configuration of plugins failed. Going down.");
1232 plugins_free(srv);
1233 network_close(srv);
1234 server_free(srv);
1236 return -1;
1239 /* settings might be enabled during module config set defaults */
1240 srv->config_storage[0]->high_precision_timestamps = srv->srvconf.high_precision_timestamps;
1242 /* dump unused config-keys */
1243 for (i = 0; i < srv->config_context->used; i++) {
1244 array *config = ((data_config *)srv->config_context->data[i])->value;
1245 size_t j;
1247 for (j = 0; config && j < config->used; j++) {
1248 data_unset *du = config->data[j];
1250 /* all var.* is known as user defined variable */
1251 if (strncmp(du->key->ptr, "var.", sizeof("var.") - 1) == 0) {
1252 continue;
1255 if (NULL == array_get_element(srv->config_touched, du->key->ptr)) {
1256 log_error_write(srv, __FILE__, __LINE__, "sbs",
1257 "WARNING: unknown config-key:",
1258 du->key,
1259 "(ignored)");
1264 if (srv->config_unsupported) {
1265 log_error_write(srv, __FILE__, __LINE__, "s",
1266 "Configuration contains unsupported keys. Going down.");
1269 if (srv->config_deprecated) {
1270 log_error_write(srv, __FILE__, __LINE__, "s",
1271 "Configuration contains deprecated keys. Going down.");
1274 if (srv->config_unsupported || srv->config_deprecated) {
1275 plugins_free(srv);
1276 network_close(srv);
1277 server_free(srv);
1279 return -1;
1282 if (srv->srvconf.preflight_check) {
1283 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1284 plugins_free(srv);
1285 network_close(srv);
1286 server_free(srv);
1288 exit(0);
1292 #ifdef HAVE_FORK
1294 * notify daemonize-grandparent of successful startup
1295 * do this before any further forking is done (workers)
1297 if (srv->srvconf.dont_daemonize == 0) {
1298 if (0 > write(parent_pipe_fd, "", 1)) return -1;
1299 close(parent_pipe_fd);
1302 if (idle_limit && srv->srvconf.max_worker) {
1303 srv->srvconf.max_worker = 0;
1304 log_error_write(srv, __FILE__, __LINE__, "s",
1305 "server idle time limit command line option disables server.max-worker config file option.");
1308 /* start watcher and workers */
1309 num_childs = srv->srvconf.max_worker;
1310 if (num_childs > 0) {
1311 int child = 0;
1312 while (!child && !srv_shutdown && !graceful_shutdown) {
1313 if (num_childs > 0) {
1314 switch (fork()) {
1315 case -1:
1316 return -1;
1317 case 0:
1318 child = 1;
1319 break;
1320 default:
1321 num_childs--;
1322 break;
1324 } else {
1325 int status;
1327 if (-1 != wait(&status)) {
1328 /**
1329 * one of our workers went away
1331 num_childs++;
1332 } else {
1333 switch (errno) {
1334 case EINTR:
1336 * if we receive a SIGHUP we have to close our logs ourself as we don't
1337 * have the mainloop who can help us here
1339 if (handle_sig_hup) {
1340 handle_sig_hup = 0;
1342 log_error_cycle(srv);
1345 * forward to all procs in the process-group
1347 * we also send it ourself
1349 if (!forwarded_sig_hup && 0 != srv->srvconf.max_worker) {
1350 forwarded_sig_hup = 1;
1351 kill(0, SIGHUP);
1354 break;
1355 default:
1356 break;
1363 * for the parent this is the exit-point
1365 if (!child) {
1366 /**
1367 * kill all children too
1369 if (graceful_shutdown) {
1370 kill(0, SIGINT);
1371 } else if (srv_shutdown) {
1372 kill(0, SIGTERM);
1375 remove_pid_file(srv, &pid_fd);
1376 log_error_close(srv);
1377 network_close(srv);
1378 connections_free(srv);
1379 plugins_free(srv);
1380 server_free(srv);
1381 return 0;
1385 * make sure workers do not muck with pid-file
1387 if (0 <= pid_fd) {
1388 close(pid_fd);
1389 pid_fd = -1;
1391 buffer_reset(srv->srvconf.pid_file);
1393 li_rand_reseed();
1395 #endif
1397 if (NULL == (srv->ev = fdevent_init(srv, srv->max_fds + 1, srv->event_handler))) {
1398 log_error_write(srv, __FILE__, __LINE__,
1399 "s", "fdevent_init failed");
1400 return -1;
1403 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1404 #ifdef HAVE_SIGACTION
1405 sigaction(SIGCHLD, &act, NULL);
1406 #elif defined(HAVE_SIGNAL)
1407 signal(SIGCHLD, signal_handler);
1408 #endif
1411 * kqueue() is called here, select resets its internals,
1412 * all server sockets get their handlers
1414 * */
1415 if (0 != network_register_fdevents(srv)) {
1416 plugins_free(srv);
1417 network_close(srv);
1418 server_free(srv);
1420 return -1;
1423 /* might fail if user is using fam (not gamin) and famd isn't running */
1424 if (NULL == (srv->stat_cache = stat_cache_init())) {
1425 log_error_write(srv, __FILE__, __LINE__, "s",
1426 "stat-cache could not be setup, dieing.");
1427 return -1;
1430 #ifdef HAVE_FAM_H
1431 /* setup FAM */
1432 if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_FAM) {
1433 if (0 != FAMOpen2(&srv->stat_cache->fam, "lighttpd")) {
1434 log_error_write(srv, __FILE__, __LINE__, "s",
1435 "could not open a fam connection, dieing.");
1436 return -1;
1438 #ifdef HAVE_FAMNOEXISTS
1439 FAMNoExists(&srv->stat_cache->fam);
1440 #endif
1442 fd_close_on_exec(FAMCONNECTION_GETFD(&srv->stat_cache->fam));
1443 fdevent_register(srv->ev, FAMCONNECTION_GETFD(&srv->stat_cache->fam), stat_cache_handle_fdevent, NULL);
1444 fdevent_event_set(srv->ev, &(srv->stat_cache->fam_fcce_ndx), FAMCONNECTION_GETFD(&srv->stat_cache->fam), FDEVENT_IN);
1446 #endif
1449 /* get the current number of FDs */
1450 srv->cur_fds = open("/dev/null", O_RDONLY);
1451 close(srv->cur_fds);
1453 for (i = 0; i < srv->srv_sockets.used; i++) {
1454 server_socket *srv_socket = srv->srv_sockets.ptr[i];
1455 if (srv->sockets_disabled) continue; /* lighttpd -1 (one-shot mode) */
1456 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv->ev, srv_socket->fd)) {
1457 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed:", strerror(errno));
1458 return -1;
1462 if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) {
1463 oneshot_fd = -1;
1466 /* main-loop */
1467 while (!srv_shutdown) {
1468 int n;
1469 size_t ndx;
1470 time_t min_ts;
1472 if (handle_sig_hup) {
1473 handler_t r;
1475 /* reset notification */
1476 handle_sig_hup = 0;
1479 /* cycle logfiles */
1481 switch(r = plugins_call_handle_sighup(srv)) {
1482 case HANDLER_GO_ON:
1483 break;
1484 default:
1485 log_error_write(srv, __FILE__, __LINE__, "sd", "sighup-handler return with an error", r);
1486 break;
1489 if (-1 == log_error_cycle(srv)) {
1490 log_error_write(srv, __FILE__, __LINE__, "s", "cycling errorlog failed, dying");
1492 return -1;
1493 } else {
1494 #ifdef HAVE_SIGACTION
1495 log_error_write(srv, __FILE__, __LINE__, "sdsd",
1496 "logfiles cycled UID =",
1497 last_sighup_info.si_uid,
1498 "PID =",
1499 last_sighup_info.si_pid);
1500 #else
1501 log_error_write(srv, __FILE__, __LINE__, "s",
1502 "logfiles cycled");
1503 #endif
1507 if (handle_sig_alarm) {
1508 /* a new second */
1510 #ifdef USE_ALARM
1511 /* reset notification */
1512 handle_sig_alarm = 0;
1513 #endif
1515 /* get current time */
1516 min_ts = time(NULL);
1518 if (min_ts != srv->cur_ts) {
1519 #ifdef DEBUG_CONNECTION_STATES
1520 int cs = 0;
1521 #endif
1522 connections *conns = srv->conns;
1523 handler_t r;
1525 switch(r = plugins_call_handle_trigger(srv)) {
1526 case HANDLER_GO_ON:
1527 break;
1528 case HANDLER_ERROR:
1529 log_error_write(srv, __FILE__, __LINE__, "s", "one of the triggers failed");
1530 break;
1531 default:
1532 log_error_write(srv, __FILE__, __LINE__, "d", r);
1533 break;
1536 /* trigger waitpid */
1537 srv->cur_ts = min_ts;
1539 /* check idle time limit, if enabled */
1540 if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) {
1541 log_error_write(srv, __FILE__, __LINE__, "sDs", "[note] idle timeout", (int)idle_limit,
1542 "s exceeded, initiating graceful shutdown");
1543 graceful_shutdown = 2; /* value 2 indicates idle timeout */
1546 #ifdef HAVE_GETLOADAVG
1547 /* refresh loadavg data every 30 seconds */
1548 if (srv->srvconf.loadts + 30 < min_ts) {
1549 if (-1 != getloadavg(srv->srvconf.loadavg, 3)) {
1550 srv->srvconf.loadts = min_ts;
1553 #endif
1555 /* cleanup stat-cache */
1556 stat_cache_trigger_cleanup(srv);
1558 * check all connections for timeouts
1561 for (ndx = 0; ndx < conns->used; ndx++) {
1562 connection * const con = conns->ptr[ndx];
1563 const int waitevents = fdevent_event_get_interest(srv->ev, con->fd);
1564 int changed = 0;
1565 int t_diff;
1567 if (con->state == CON_STATE_CLOSE) {
1568 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
1569 changed = 1;
1571 } else if (waitevents & FDEVENT_IN) {
1572 if (con->request_count == 1 || con->state != CON_STATE_READ) { /* e.g. CON_STATE_READ_POST || CON_STATE_WRITE */
1573 if (srv->cur_ts - con->read_idle_ts > con->conf.max_read_idle) {
1574 /* time - out */
1575 if (con->conf.log_request_handling) {
1576 log_error_write(srv, __FILE__, __LINE__, "sd",
1577 "connection closed - read timeout:", con->fd);
1580 connection_set_state(srv, con, CON_STATE_ERROR);
1581 changed = 1;
1583 } else {
1584 if (srv->cur_ts - con->read_idle_ts > con->keep_alive_idle) {
1585 /* time - out */
1586 if (con->conf.log_request_handling) {
1587 log_error_write(srv, __FILE__, __LINE__, "sd",
1588 "connection closed - keep-alive timeout:", con->fd);
1591 connection_set_state(srv, con, CON_STATE_ERROR);
1592 changed = 1;
1597 /* max_write_idle timeout currently functions as backend timeout,
1598 * too, after response has been started.
1599 * future: have separate backend timeout, and then change this
1600 * to check for write interest before checking for timeout */
1601 /*if (waitevents & FDEVENT_OUT)*/
1602 if ((con->state == CON_STATE_WRITE) &&
1603 (con->write_request_ts != 0)) {
1604 #if 0
1605 if (srv->cur_ts - con->write_request_ts > 60) {
1606 log_error_write(srv, __FILE__, __LINE__, "sdd",
1607 "connection closed - pre-write-request-timeout:", con->fd, srv->cur_ts - con->write_request_ts);
1609 #endif
1611 if (srv->cur_ts - con->write_request_ts > con->conf.max_write_idle) {
1612 /* time - out */
1613 if (con->conf.log_timeouts) {
1614 log_error_write(srv, __FILE__, __LINE__, "sbsbsosds",
1615 "NOTE: a request from",
1616 con->dst_addr_buf,
1617 "for",
1618 con->request.uri,
1619 "timed out after writing",
1620 con->bytes_written,
1621 "bytes. We waited",
1622 (int)con->conf.max_write_idle,
1623 "seconds. If this a problem increase server.max-write-idle");
1625 connection_set_state(srv, con, CON_STATE_ERROR);
1626 changed = 1;
1630 /* we don't like div by zero */
1631 if (0 == (t_diff = srv->cur_ts - con->connection_start)) t_diff = 1;
1633 if (con->traffic_limit_reached &&
1634 (con->conf.kbytes_per_second == 0 ||
1635 ((con->bytes_written / t_diff) < con->conf.kbytes_per_second * 1024))) {
1636 /* enable connection again */
1637 con->traffic_limit_reached = 0;
1639 changed = 1;
1642 if (changed) {
1643 connection_state_machine(srv, con);
1645 con->bytes_written_cur_second = 0;
1646 *(con->conf.global_bytes_per_second_cnt_ptr) = 0;
1648 #if DEBUG_CONNECTION_STATES
1649 if (cs == 0) {
1650 fprintf(stderr, "connection-state: ");
1651 cs = 1;
1654 fprintf(stderr, "c[%d,%d]: %s ",
1655 con->fd,
1656 con->fcgi.fd,
1657 connection_get_state(con->state));
1658 #endif
1661 #ifdef DEBUG_CONNECTION_STATES
1662 if (cs == 1) fprintf(stderr, "\n");
1663 #endif
1667 if (srv->sockets_disabled) {
1668 /* our server sockets are disabled, why ? */
1670 if ((srv->cur_fds + srv->want_fds < srv->max_fds * 8 / 10) && /* we have enough unused fds */
1671 (srv->conns->used <= srv->max_conns * 9 / 10) &&
1672 (0 == graceful_shutdown)) {
1673 for (i = 0; i < srv->srv_sockets.used; i++) {
1674 server_socket *srv_socket = srv->srv_sockets.ptr[i];
1675 fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, FDEVENT_IN);
1678 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets enabled again");
1680 srv->sockets_disabled = 0;
1682 } else {
1683 if ((srv->cur_fds + srv->want_fds > srv->max_fds * 9 / 10) || /* out of fds */
1684 (srv->conns->used >= srv->max_conns) || /* out of connections */
1685 (graceful_shutdown)) { /* graceful_shutdown */
1687 /* disable server-fds */
1689 for (i = 0; i < srv->srv_sockets.used; i++) {
1690 server_socket *srv_socket = srv->srv_sockets.ptr[i];
1692 if (graceful_shutdown) {
1693 /* we don't want this socket anymore,
1695 * closing it right away will make it possible for
1696 * the next lighttpd to take over (graceful restart)
1697 * */
1699 fdevent_event_del(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd);
1700 fdevent_unregister(srv->ev, srv_socket->fd);
1701 close(srv_socket->fd);
1702 srv_socket->fd = -1;
1704 /* network_close() will cleanup after us */
1705 } else {
1706 fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, 0);
1710 if (graceful_shutdown) {
1711 remove_pid_file(srv, &pid_fd);
1712 log_error_write(srv, __FILE__, __LINE__, "s", "[note] graceful shutdown started");
1713 } else if (srv->conns->used >= srv->max_conns) {
1714 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, connection limit reached");
1715 } else {
1716 log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, out-of-fds");
1719 srv->sockets_disabled = 1;
1723 if (graceful_shutdown && srv->conns->used == 0) {
1724 /* we are in graceful shutdown phase and all connections are closed
1725 * we are ready to terminate without harming anyone */
1726 srv_shutdown = 1;
1727 break;
1730 /* we still have some fds to share */
1731 if (srv->want_fds) {
1732 /* check the fdwaitqueue for waiting fds */
1733 int free_fds = srv->max_fds - srv->cur_fds - 16;
1734 connection *con;
1736 for (; free_fds > 0 && NULL != (con = fdwaitqueue_unshift(srv, srv->fdwaitqueue)); free_fds--) {
1737 connection_state_machine(srv, con);
1739 srv->want_fds--;
1743 if ((n = fdevent_poll(srv->ev, 1000)) > 0) {
1744 /* n is the number of events */
1745 int revents;
1746 int fd_ndx;
1747 last_active_ts = srv->cur_ts;
1748 fd_ndx = -1;
1749 do {
1750 fdevent_handler handler;
1751 void *context;
1753 fd_ndx = fdevent_event_next_fdndx (srv->ev, fd_ndx);
1754 if (-1 == fd_ndx) break; /* not all fdevent handlers know how many fds got an event */
1756 revents = fdevent_event_get_revent (srv->ev, fd_ndx);
1757 fd = fdevent_event_get_fd (srv->ev, fd_ndx);
1758 handler = fdevent_get_handler(srv->ev, fd);
1759 context = fdevent_get_context(srv->ev, fd);
1760 if (NULL != handler) {
1761 (*handler)(srv, context, revents);
1763 } while (--n > 0);
1764 fdevent_sched_run(srv, srv->ev);
1765 } else if (n < 0 && errno != EINTR) {
1766 log_error_write(srv, __FILE__, __LINE__, "ss",
1767 "fdevent_poll failed:",
1768 strerror(errno));
1771 for (ndx = 0; ndx < srv->joblist->used; ndx++) {
1772 connection *con = srv->joblist->ptr[ndx];
1773 connection_state_machine(srv, con);
1774 con->in_joblist = 0;
1777 srv->joblist->used = 0;
1780 if (0 == graceful_shutdown) {
1781 remove_pid_file(srv, &pid_fd);
1784 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */
1785 log_error_write(srv, __FILE__, __LINE__, "s",
1786 "server stopped after idle timeout");
1787 } else {
1788 #ifdef HAVE_SIGACTION
1789 log_error_write(srv, __FILE__, __LINE__, "sdsd",
1790 "server stopped by UID =",
1791 last_sigterm_info.si_uid,
1792 "PID =",
1793 last_sigterm_info.si_pid);
1794 #else
1795 log_error_write(srv, __FILE__, __LINE__, "s",
1796 "server stopped");
1797 #endif
1800 /* clean-up */
1801 log_error_close(srv);
1802 network_close(srv);
1803 connections_free(srv);
1804 plugins_free(srv);
1805 server_free(srv);
1807 return 0;