12 #include "http_auth.h"
13 #include "http_chunk.h"
14 #include "http_vhostdb.h"
16 #include "connections.h"
17 #include "sock_addr.h"
18 #include "stat_cache.h"
21 #include "network_write.h"
23 #ifdef HAVE_VERSIONSTAMP_H
24 # include "versionstamp.h"
26 # define REPO_VERSION ""
29 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
31 #include <sys/types.h>
51 #ifdef HAVE_VALGRIND_VALGRIND_H
52 # include <valgrind/valgrind.h>
55 #ifdef HAVE_SYS_WAIT_H
56 # include <sys/wait.h>
68 #ifdef HAVE_SYS_RESOURCE_H
69 # include <sys/resource.h>
72 #ifdef HAVE_SYS_PRCTL_H
73 # include <sys/prctl.h>
76 #if defined HAVE_LIBSSL && defined HAVE_OPENSSL_SSL_H
78 #define TEXT_SSL " (ssl)"
84 /* IRIX doesn't like the alarm based time() optimization */
85 /* #define USE_ALARM */
88 static int oneshot_fd
= 0;
89 static volatile int pid_fd
= -2;
90 static server_socket_array graceful_sockets
;
91 static volatile sig_atomic_t graceful_restart
= 0;
92 static volatile sig_atomic_t graceful_shutdown
= 0;
93 static volatile sig_atomic_t srv_shutdown
= 0;
94 static volatile sig_atomic_t handle_sig_child
= 0;
95 static volatile sig_atomic_t handle_sig_alarm
= 1;
96 static volatile sig_atomic_t handle_sig_hup
= 0;
98 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
99 static volatile siginfo_t last_sigterm_info
;
100 static volatile siginfo_t last_sighup_info
;
102 static void sigaction_handler(int sig
, siginfo_t
*si
, void *context
) {
103 static const siginfo_t empty_siginfo
;
106 if (!si
) *(const siginfo_t
**)&si
= &empty_siginfo
;
111 last_sigterm_info
= *si
;
114 if (!graceful_shutdown
) {
115 graceful_restart
= 1;
116 graceful_shutdown
= 1;
117 last_sigterm_info
= *si
;
121 if (graceful_shutdown
) {
122 if (2 == graceful_restart
)
123 graceful_restart
= 1;
127 graceful_shutdown
= 1;
129 last_sigterm_info
= *si
;
133 handle_sig_alarm
= 1;
137 last_sighup_info
= *si
;
140 handle_sig_child
= 1;
144 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
145 static void signal_handler(int sig
) {
147 case SIGTERM
: srv_shutdown
= 1; break;
149 if (!graceful_shutdown
) {
150 graceful_restart
= 1;
151 graceful_shutdown
= 1;
155 if (graceful_shutdown
) {
156 if (2 == graceful_restart
)
157 graceful_restart
= 1;
161 graceful_shutdown
= 1;
164 case SIGALRM
: handle_sig_alarm
= 1; break;
165 case SIGHUP
: handle_sig_hup
= 1; break;
166 case SIGCHLD
: handle_sig_child
= 1; break;
172 static int daemonize(void) {
176 signal(SIGTTOU
, SIG_IGN
);
179 signal(SIGTTIN
, SIG_IGN
);
182 signal(SIGTSTP
, SIG_IGN
);
185 if (pipe(pipefd
) < 0) exit(-1);
187 if (0 > (pid
= fork())) exit(-1);
194 /* parent waits for grandchild to be ready */
196 bytes
= read(pipefd
[0], &buf
, sizeof(buf
));
197 } while (bytes
< 0 && EINTR
== errno
);
201 /* closed fd (without writing) == failure in grandchild */
202 fputs("daemonized server failed to start; check error log for details\n", stderr
);
211 if (-1 == setsid()) exit(0);
213 signal(SIGHUP
, SIG_IGN
);
215 if (0 != fork()) exit(0);
217 if (0 != chdir("/")) exit(0);
219 fdevent_setfd_cloexec(pipefd
[1]);
224 static server
*server_init(void) {
226 server
*srv
= calloc(1, sizeof(*srv
));
229 srv->x = buffer_init();
231 CLEAN(response_header
);
232 CLEAN(parse_full_path
);
236 CLEAN(response_range
);
238 srv
->empty_string
= buffer_init_string("");
239 CLEAN(cond_check_buf
);
241 CLEAN(srvconf
.errorlog_file
);
242 CLEAN(srvconf
.breakagelog_file
);
243 CLEAN(srvconf
.groupname
);
244 CLEAN(srvconf
.username
);
245 CLEAN(srvconf
.changeroot
);
246 CLEAN(srvconf
.bindhost
);
247 CLEAN(srvconf
.event_handler
);
248 CLEAN(srvconf
.pid_file
);
249 CLEAN(srvconf
.syslog_facility
);
251 CLEAN(tmp_chunk_len
);
255 srv->x = array_init();
257 CLEAN(config_context
);
258 CLEAN(config_touched
);
262 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
263 srv
->mtime_cache
[i
].mtime
= (time_t)-1;
264 srv
->mtime_cache
[i
].str
= buffer_init();
269 srv
->cur_ts
= time(NULL
);
270 srv
->startup_ts
= srv
->cur_ts
;
272 srv
->conns
= calloc(1, sizeof(*srv
->conns
));
273 force_assert(srv
->conns
);
275 srv
->joblist
= calloc(1, sizeof(*srv
->joblist
));
276 force_assert(srv
->joblist
);
278 srv
->fdwaitqueue
= calloc(1, sizeof(*srv
->fdwaitqueue
));
279 force_assert(srv
->fdwaitqueue
);
281 srv
->srvconf
.modules
= array_init();
282 srv
->srvconf
.modules_dir
= buffer_init_string(LIBRARY_DIR
);
283 srv
->srvconf
.network_backend
= buffer_init();
284 srv
->srvconf
.upload_tempdirs
= array_init();
285 srv
->srvconf
.reject_expect_100_with_417
= 1;
286 srv
->srvconf
.xattr_name
= buffer_init_string("Content-Type");
287 srv
->srvconf
.http_header_strict
= 1;
288 srv
->srvconf
.http_host_strict
= 1; /*(implies http_host_normalize)*/
289 srv
->srvconf
.http_host_normalize
= 0;
290 srv
->srvconf
.high_precision_timestamps
= 0;
291 srv
->srvconf
.max_request_field_size
= 8192;
292 srv
->srvconf
.loadavg
[0] = 0.0;
293 srv
->srvconf
.loadavg
[1] = 0.0;
294 srv
->srvconf
.loadavg
[2] = 0.0;
297 srv
->errorlog_fd
= STDERR_FILENO
;
298 srv
->errorlog_mode
= ERRORLOG_FD
;
300 srv
->split_vals
= array_init();
301 srv
->request_env
= plugins_call_handle_request_env
;
306 static void server_free(server
*srv
) {
309 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
310 buffer_free(srv
->mtime_cache
[i
].str
);
313 if (oneshot_fd
> 0) {
320 CLEAN(response_header
);
321 CLEAN(parse_full_path
);
325 CLEAN(response_range
);
328 CLEAN(cond_check_buf
);
330 CLEAN(srvconf
.errorlog_file
);
331 CLEAN(srvconf
.breakagelog_file
);
332 CLEAN(srvconf
.groupname
);
333 CLEAN(srvconf
.username
);
334 CLEAN(srvconf
.changeroot
);
335 CLEAN(srvconf
.bindhost
);
336 CLEAN(srvconf
.event_handler
);
337 CLEAN(srvconf
.pid_file
);
338 CLEAN(srvconf
.modules_dir
);
339 CLEAN(srvconf
.network_backend
);
340 CLEAN(srvconf
.xattr_name
);
341 CLEAN(srvconf
.syslog_facility
);
343 CLEAN(tmp_chunk_len
);
347 fdevent_unregister(srv
->ev
, srv
->fd
);
349 fdevent_free(srv
->ev
);
353 if (srv
->config_storage
) {
354 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
355 specific_config
*s
= srv
->config_storage
[i
];
359 buffer_free(s
->document_root
);
360 buffer_free(s
->server_name
);
361 buffer_free(s
->server_tag
);
362 buffer_free(s
->error_handler
);
363 buffer_free(s
->error_handler_404
);
364 buffer_free(s
->errorfile_prefix
);
365 buffer_free(s
->socket_perms
);
366 array_free(s
->mimetypes
);
369 free(srv
->config_storage
);
370 srv
->config_storage
= NULL
;
376 CLEAN(config_context
);
377 CLEAN(config_touched
);
379 CLEAN(srvconf
.upload_tempdirs
);
382 joblist_free(srv
, srv
->joblist
);
383 fdwaitqueue_free(srv
, srv
->fdwaitqueue
);
385 if (srv
->stat_cache
) {
386 stat_cache_free(srv
->stat_cache
);
389 array_free(srv
->srvconf
.modules
);
390 array_free(srv
->split_vals
);
397 static void remove_pid_file(server
*srv
) {
398 if (pid_fd
<= -2) return;
399 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) && 0 <= pid_fd
) {
400 if (0 != ftruncate(pid_fd
, 0)) {
401 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
402 "ftruncate failed for:",
403 srv
->srvconf
.pid_file
,
412 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) &&
413 buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
414 if (0 != unlink(srv
->srvconf
.pid_file
->ptr
)) {
415 if (errno
!= EACCES
&& errno
!= EPERM
) {
416 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
417 "unlink failed for:",
418 srv
->srvconf
.pid_file
,
427 static server_socket
* server_oneshot_getsock(server
*srv
, sock_addr
*cnt_addr
) {
428 server_socket
*srv_socket
, *srv_socket_wild
= NULL
;
430 for (i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
431 srv_socket
= srv
->srv_sockets
.ptr
[i
];
432 if (!sock_addr_is_port_eq(&srv_socket
->addr
,cnt_addr
)) continue;
433 if (sock_addr_is_addr_eq(&srv_socket
->addr
,cnt_addr
)) return srv_socket
;
435 if (NULL
!= srv_socket_wild
) continue;
436 if (sock_addr_is_addr_wildcard(&srv_socket
->addr
)) {
437 srv_socket_wild
= srv_socket
;
441 if (NULL
!= srv_socket_wild
) {
442 return srv_socket_wild
;
443 } else if (srv
->srv_sockets
.used
) {
444 return srv
->srv_sockets
.ptr
[0];
446 log_error_write(srv
, __FILE__
, __LINE__
, "s", "no sockets configured");
452 static int server_oneshot_init(server
*srv
, int fd
) {
453 /* Note: does not work with netcat due to requirement that fd be socket.
454 * STDOUT_FILENO was not saved earlier in startup, and that is to where
455 * netcat expects output to be sent. Since lighttpd expects connections
456 * to be sockets, con->fd is where output is sent; separate fds are not
457 * stored for input and output, but netcat has different fds for stdin
458 * and * stdout. To support netcat, would additionally need to avoid
459 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
460 * addresses from environment variables:
461 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
462 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
466 server_socket
*srv_socket
;
471 if (0 != fstat(fd
, &st
)) {
472 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fstat:", strerror(errno
));
476 if (!S_ISSOCK(st
.st_mode
)) {
477 /* require that fd is a socket
478 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
479 log_error_write(srv
, __FILE__
, __LINE__
, "s", "lighttpd -1 stdin is not a socket");
483 cnt_len
= sizeof(cnt_addr
);
484 if (0 != getsockname(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
485 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getsockname:", strerror(errno
));
489 srv_socket
= server_oneshot_getsock(srv
, &cnt_addr
);
490 if (NULL
== srv_socket
) return 0;
492 cnt_len
= sizeof(cnt_addr
);
493 if (0 != getpeername(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
494 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getpeername:", strerror(errno
));
498 /*(must set flags; fd did not pass through fdevent accept() logic)*/
499 if (-1 == fdevent_fcntl_set_nb_cloexec(srv
->ev
, fd
)) {
500 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl:", strerror(errno
));
504 if (sock_addr_get_family(&cnt_addr
) != AF_UNIX
) {
505 network_accept_tcp_nagle_disable(fd
);
508 con
= connection_accepted(srv
, srv_socket
, &cnt_addr
, fd
);
509 if (NULL
== con
) return 0;
511 connection_state_machine(srv
, con
);
516 static void show_version (void) {
517 char *b
= PACKAGE_DESC TEXT_SSL \
518 " - a light and fast webserver\n"
519 #ifdef NONREPRODUCIBLE_BUILD
520 "Build-Date: " __DATE__
" " __TIME__
"\n";
523 write_all(STDOUT_FILENO
, b
, strlen(b
));
526 static void show_features (void) {
527 static const char features
[] =
534 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
539 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
540 "\t+ bzip2 support\n"
542 "\t- bzip2 support\n"
544 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
545 "\t+ crypt support\n"
547 "\t- crypt support\n"
560 "\t+ MySQL support\n"
562 "\t- MySQL support\n"
565 "\t+ PgSQL support\n"
567 "\t- PgSQL support\n"
575 "\t+ Kerberos support\n"
577 "\t- Kerberos support\n"
579 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
585 "\t+ memcached support\n"
587 "\t- memcached support\n"
604 #ifdef HAVE_SQLITE3_H
605 "\t+ SQLite support\n"
607 "\t- SQLite support\n"
616 printf("%s%s%s\n", fdevent_show_event_handlers(), network_write_show_handlers(), features
);
619 static void show_help (void) {
620 char *b
= PACKAGE_DESC TEXT_SSL
621 #ifdef NONREPRODUCIBLE_BUILD
622 " ("__DATE__
" " __TIME__
")"
624 " - a light and fast webserver\n" \
626 " -f <name> filename of the config-file\n" \
627 " -m <name> module directory (default: "LIBRARY_DIR
")\n" \
628 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
629 " -1 process single (one) request on stdin socket, then exit\n" \
630 " -p print the parsed config-file in internal form, and exit\n" \
631 " -t test config-file syntax, then exit\n" \
632 " -tt test config-file syntax, load and init modules, then exit\n" \
633 " -D don't go to background (default: go to background)\n" \
634 " -v show version\n" \
635 " -V show compile-time features\n" \
636 " -h show this help\n" \
639 write_all(STDOUT_FILENO
, b
, strlen(b
));
645 * we have 4 possibilities:
653 static int log_error_open(server
*srv
) {
656 /* perhaps someone wants to use syslog() */
658 if (!buffer_string_is_empty(srv
->srvconf
.syslog_facility
)) {
659 static const struct facility_name_st
{
662 } facility_names
[] = {
665 ,{ "authpriv", LOG_AUTHPRIV
}
668 ,{ "cron", LOG_CRON
}
670 ,{ "daemon", LOG_DAEMON
}
675 ,{ "kern", LOG_KERN
}
681 ,{ "mail", LOG_MAIL
}
684 ,{ "news", LOG_NEWS
}
686 ,{ "security", LOG_AUTH
} /* DEPRECATED */
688 ,{ "syslog", LOG_SYSLOG
}
691 ,{ "user", LOG_USER
}
694 ,{ "uucp", LOG_UUCP
}
696 ,{ "local0", LOG_LOCAL0
}
697 ,{ "local1", LOG_LOCAL1
}
698 ,{ "local2", LOG_LOCAL2
}
699 ,{ "local3", LOG_LOCAL3
}
700 ,{ "local4", LOG_LOCAL4
}
701 ,{ "local5", LOG_LOCAL5
}
702 ,{ "local6", LOG_LOCAL6
}
703 ,{ "local7", LOG_LOCAL7
}
706 for (i
= 0; i
< sizeof(facility_names
)/sizeof(facility_names
[0]); ++i
) {
707 const struct facility_name_st
*f
= facility_names
+i
;
708 if (0 == strcmp(srv
->srvconf
.syslog_facility
->ptr
, f
->name
)) {
713 if (-1 == facility
) {
714 log_error_write(srv
, __FILE__
, __LINE__
, "SBS",
715 "unrecognized server.syslog-facility: \"",
716 srv
->srvconf
.syslog_facility
,
717 "\"; defaulting to \"daemon\" facility");
720 openlog("lighttpd", LOG_CONS
|LOG_PID
, -1==facility
? LOG_DAEMON
: facility
);
723 srv
->errorlog_mode
= ERRORLOG_FD
;
724 srv
->errorlog_fd
= STDERR_FILENO
;
726 if (srv
->srvconf
.errorlog_use_syslog
) {
727 srv
->errorlog_mode
= ERRORLOG_SYSLOG
;
729 else if (!buffer_string_is_empty(srv
->srvconf
.errorlog_file
)) {
730 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
732 if (-1 == (srv
->errorlog_fd
= fdevent_open_logger(logfile
))) {
733 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
734 "opening errorlog '", logfile
,
735 "' failed: ", strerror(errno
));
738 srv
->errorlog_mode
= logfile
[0] == '|' ? ERRORLOG_PIPE
: ERRORLOG_FILE
;
741 if (srv
->errorlog_mode
== ERRORLOG_FD
&& !srv
->srvconf
.dont_daemonize
) {
742 /* We can only log to stderr in dont-daemonize mode;
743 * if we do daemonize and no errorlog file is specified,
744 * we log into /dev/null
746 srv
->errorlog_fd
= -1;
749 if (!buffer_string_is_empty(srv
->srvconf
.breakagelog_file
)) {
750 const char *logfile
= srv
->srvconf
.breakagelog_file
->ptr
;
752 if (srv
->errorlog_mode
== ERRORLOG_FD
) {
753 srv
->errorlog_fd
= dup(STDERR_FILENO
);
754 fdevent_setfd_cloexec(srv
->errorlog_fd
);
757 if (-1 == (errfd
= fdevent_open_logger(logfile
))) {
758 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
759 "opening errorlog '", logfile
,
760 "' failed: ", strerror(errno
));
764 if (*logfile
== '|') fdevent_breakagelog_logger_pipe(errfd
);
766 else if (!srv
->srvconf
.dont_daemonize
) {
767 /* move STDERR_FILENO to /dev/null */
768 if (-1 == (errfd
= fdevent_open_devnull())) {
769 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
770 "opening /dev/null failed:", strerror(errno
));
775 /*(leave STDERR_FILENO as-is)*/
779 if (0 != fdevent_set_stdin_stdout_stderr(-1, -1, errfd
)) {
780 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
781 "setting stderr failed:", strerror(errno
));
783 if (-1 != errfd
) close(errfd
);
788 if (-1 != errfd
) close(errfd
);
799 static int log_error_cycle(server
*srv
) {
800 /* cycle only if the error log is a file */
802 if (srv
->errorlog_mode
== ERRORLOG_FILE
) {
803 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
804 if (-1 == fdevent_cycle_logger(logfile
, &srv
->errorlog_fd
)) {
805 /* write to old log */
806 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
807 "cycling errorlog '", logfile
,
808 "' failed: ", strerror(errno
));
815 static int log_error_close(server
*srv
) {
816 switch(srv
->errorlog_mode
) {
820 if (-1 != srv
->errorlog_fd
) {
821 /* don't close STDERR */
822 /* fdevent_close_logger_pipes() closes ERRORLOG_PIPE */
823 if (STDERR_FILENO
!= srv
->errorlog_fd
824 && srv
->errorlog_mode
!= ERRORLOG_PIPE
) {
825 close(srv
->errorlog_fd
);
827 srv
->errorlog_fd
= -1;
830 case ERRORLOG_SYSLOG
:
840 static void server_sockets_save (server
*srv
) { /* graceful_restart */
841 memcpy(&graceful_sockets
, &srv
->srv_sockets
, sizeof(server_socket_array
));
842 memset(&srv
->srv_sockets
, 0, sizeof(server_socket_array
));
845 static void server_sockets_restore (server
*srv
) { /* graceful_restart */
846 memcpy(&srv
->srv_sockets
, &graceful_sockets
, sizeof(server_socket_array
));
847 memset(&graceful_sockets
, 0, sizeof(server_socket_array
));
850 static int server_sockets_set_nb_cloexec (server
*srv
) {
851 if (srv
->sockets_disabled
) return 0; /* lighttpd -1 (one-shot mode) */
852 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
853 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
854 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv
->ev
, srv_socket
->fd
)) {
855 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
856 "fcntl failed:", strerror(errno
));
863 static void server_sockets_set_event (server
*srv
, int event
) {
864 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
865 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
866 fdevent_event_set(srv
->ev
,&(srv_socket
->fde_ndx
),srv_socket
->fd
,event
);
870 static void server_sockets_unregister (server
*srv
) {
871 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
)
872 network_unregister_sock(srv
, srv
->srv_sockets
.ptr
[i
]);
875 static void server_sockets_close (server
*srv
) {
876 /* closing socket right away will make it possible for the next lighttpd
877 * to take over (old-style graceful restart), but only if backends
878 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
879 * than started by lighttpd via "bin-path")
881 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
882 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
883 if (-1 == srv_socket
->fd
) continue;
884 network_unregister_sock(srv
, srv_socket
);
885 close(srv_socket
->fd
);
887 /* network_close() will cleanup after us */
891 static void server_graceful_shutdown_maint (server
*srv
) {
892 connections
*conns
= srv
->conns
;
893 for (size_t ndx
= 0; ndx
< conns
->used
; ++ndx
) {
894 connection
* const con
= conns
->ptr
[ndx
];
897 if (con
->state
== CON_STATE_CLOSE
) {
898 /* reduce remaining linger timeout to be
899 * (from zero) *up to* one more second, but no more */
900 if (HTTP_LINGER_TIMEOUT
> 1)
901 con
->close_timeout_ts
-= (HTTP_LINGER_TIMEOUT
- 1);
902 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
)
905 else if (con
->state
== CON_STATE_READ
&& con
->request_count
> 1
906 && chunkqueue_is_empty(con
->read_queue
)) {
907 /* close connections in keep-alive waiting for next request */
908 connection_set_state(srv
, con
, CON_STATE_ERROR
);
912 con
->keep_alive
= 0; /* disable keep-alive */
914 con
->conf
.kbytes_per_second
= 0; /* disable rate limit */
915 con
->conf
.global_kbytes_per_second
= 0; /* disable rate limit */
916 if (con
->traffic_limit_reached
) {
917 con
->traffic_limit_reached
= 0;
922 connection_state_machine(srv
, con
);
927 static void server_graceful_state (server
*srv
) {
929 if (!srv_shutdown
) server_graceful_shutdown_maint(srv
);
932 if (0==srv
->srv_sockets
.used
|| -1 == srv
->srv_sockets
.ptr
[0]->fde_ndx
)
936 log_error_write(srv
, __FILE__
, __LINE__
, "s",
937 "[note] graceful shutdown started");
939 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
940 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)
941 || oneshot_fd
|| 2 == graceful_shutdown
)
942 graceful_restart
= 0;
944 if (graceful_restart
) {
945 server_sockets_unregister(srv
);
946 if (pid_fd
> 0) pid_fd
= -pid_fd
; /*(flag to skip removing pid file)*/
949 server_sockets_close(srv
);
950 remove_pid_file(srv
);
951 buffer_reset(srv
->srvconf
.pid_file
); /*(prevent more removal attempts)*/
955 static int server_main (server
* const srv
, int argc
, char **argv
) {
956 int print_config
= 0;
964 time_t idle_limit
= 0, last_active_ts
= time(NULL
);
965 #ifdef HAVE_SIGACTION
966 struct sigaction act
;
970 int parent_pipe_fd
= -1;
975 i_am_root
= (0 == getuid());
978 /* initialize globals (including file-scoped static globals) */
981 graceful_shutdown
= 0;
982 handle_sig_alarm
= 1;
984 chunkqueue_set_tempdirs_default_reset();
985 http_auth_dumbdata_reset();
986 http_vhostdb_dumbdata_reset();
987 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
988 /*(intentionally preserved)*/
989 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
992 srv
->srvconf
.port
= 0;
993 srv
->srvconf
.dont_daemonize
= 0;
994 srv
->srvconf
.preflight_check
= 0;
996 while(-1 != (o
= getopt(argc
, argv
, "f:m:i:hvVD1pt"))) {
999 if (srv
->config_storage
) {
1000 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1001 "Can only read one config file. Use the include command to use multiple config files.");
1004 if (config_read(srv
, optarg
)) {
1009 buffer_copy_string(srv
->srvconf
.modules_dir
, optarg
);
1013 long timeout
= strtol(optarg
, &endptr
, 0);
1014 if (!*optarg
|| *endptr
|| timeout
< 0) {
1015 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1016 "Invalid idle timeout value:", optarg
);
1019 idle_limit
= (time_t)timeout
;
1022 case 'p': print_config
= 1; break;
1023 case 't': ++test_config
; break;
1024 case '1': if (0 == oneshot_fd
) oneshot_fd
= dup(STDIN_FILENO
);
1026 case 'D': srv
->srvconf
.dont_daemonize
= 1; break;
1027 case 'v': show_version(); return 0;
1028 case 'V': show_features(); return 0;
1029 case 'h': show_help(); return 0;
1036 if (!srv
->config_storage
) {
1037 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1038 "No configuration available. Try using -f option.");
1043 data_unset
*dc
= srv
->config_context
->data
[0];
1046 fprintf(stdout
, "\n");
1048 /* shouldn't happend */
1049 fprintf(stderr
, "global config not found\n");
1054 buffer_reset(srv
->srvconf
.pid_file
);
1055 if (1 == test_config
) {
1056 printf("Syntax OK\n");
1057 } else { /*(test_config > 1)*/
1059 srv
->srvconf
.preflight_check
= 1;
1060 srv
->srvconf
.dont_daemonize
= 1;
1064 if (test_config
|| print_config
) {
1069 if (oneshot_fd
<= STDERR_FILENO
) {
1070 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1071 "Invalid fds at startup with lighttpd -1");
1074 graceful_shutdown
= 1;
1075 srv
->sockets_disabled
= 1;
1076 srv
->srvconf
.dont_daemonize
= 1;
1077 buffer_reset(srv
->srvconf
.pid_file
);
1078 if (srv
->srvconf
.max_worker
) {
1079 srv
->srvconf
.max_worker
= 0;
1080 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1081 "server one-shot command line option disables server.max-worker config file option.");
1085 if (buffer_is_equal_string(srv
->srvconf
.bindhost
, CONST_STR_LEN("/dev/stdin"))) {
1086 stdin_fd
= dup(STDIN_FILENO
);
1087 if (stdin_fd
<= STDERR_FILENO
) {
1088 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1089 "Invalid fds at startup");
1094 /* close stdin and stdout, as they are not needed */
1100 /* coverity[overwrite_var : FALSE] */
1101 devnull
= fdevent_open_devnull();
1103 __coverity_escape__(devnull
);
1105 } while (-1 != devnull
&& devnull
<= STDERR_FILENO
);
1106 if (-1 == devnull
) {
1107 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1108 "opening /dev/null failed:", strerror(errno
));
1111 errfd
= (0 == fstat(STDERR_FILENO
, &st
)) ? -1 : devnull
;
1112 if (0 != fdevent_set_stdin_stdout_stderr(devnull
, devnull
, errfd
)) {
1113 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1114 "setting default fds failed:", strerror(errno
));
1116 if (-1 != errfd
) close(errfd
);
1117 if (devnull
!= errfd
) close(devnull
);
1122 if (-1 != errfd
) close(errfd
);
1123 if (devnull
!= errfd
) close(devnull
);
1127 if (0 != config_set_defaults(srv
)) {
1128 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1129 "setting default values failed");
1133 /* check document-root */
1134 if (buffer_string_is_empty(srv
->config_storage
[0]->document_root
)) {
1135 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1136 "document-root is not set\n");
1140 if (plugins_load(srv
)) {
1141 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1142 "loading plugins finally failed");
1146 if (HANDLER_GO_ON
!= plugins_call_init(srv
)) {
1147 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Initialization of plugins failed. Going down.");
1151 /* open pid file BEFORE chroot */
1152 if (-2 == pid_fd
) pid_fd
= -1; /*(initial startup state)*/
1153 if (-1 == pid_fd
&& !buffer_string_is_empty(srv
->srvconf
.pid_file
)) {
1154 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
))) {
1156 if (errno
!= EEXIST
) {
1157 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1158 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1162 if (0 != stat(srv
->srvconf
.pid_file
->ptr
, &st
)) {
1163 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1164 "stating existing pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1167 if (!S_ISREG(st
.st_mode
)) {
1168 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1169 "pid-file exists and isn't regular file:", srv
->srvconf
.pid_file
);
1173 if (-1 == (pid_fd
= fdevent_open_cloexec(srv
->srvconf
.pid_file
->ptr
, O_WRONLY
| O_CREAT
| O_TRUNC
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
))) {
1174 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1175 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1182 #ifdef HAVE_GETRLIMIT
1185 #ifdef HAVE_VALGRIND_VALGRIND_H
1186 if (RUNNING_ON_VALGRIND
) use_rlimit
= 0;
1189 if (0 != getrlimit(RLIMIT_NOFILE
, &rlim
)) {
1190 log_error_write(srv
, __FILE__
, __LINE__
,
1191 "ss", "couldn't get 'max filedescriptors'",
1197 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1199 if (use_rlimit
&& srv
->srvconf
.max_fds
1200 && (i_am_root
|| srv
->srvconf
.max_fds
<= rlim
.rlim_max
)) {
1203 rlim
.rlim_cur
= srv
->srvconf
.max_fds
;
1204 if (i_am_root
) rlim
.rlim_max
= srv
->srvconf
.max_fds
;
1206 if (0 != setrlimit(RLIMIT_NOFILE
, &rlim
)) {
1207 log_error_write(srv
, __FILE__
, __LINE__
,
1208 "ss", "couldn't set 'max filedescriptors'",
1214 srv
->max_fds
= rlim
.rlim_cur
;
1215 /*(default upper limit of 4k if server.max-fds not specified)*/
1216 if (i_am_root
&& 0 == srv
->srvconf
.max_fds
&& rlim
.rlim_cur
> 4096)
1217 srv
->max_fds
= 4096;
1219 /* set core file rlimit, if enable_cores is set */
1220 if (use_rlimit
&& srv
->srvconf
.enable_cores
&& getrlimit(RLIMIT_CORE
, &rlim
) == 0) {
1221 rlim
.rlim_cur
= rlim
.rlim_max
;
1222 setrlimit(RLIMIT_CORE
, &rlim
);
1227 /* we need root-perms for port < 1024 */
1228 if (0 != network_init(srv
, stdin_fd
)) {
1234 /* set user and group */
1235 struct group
*grp
= NULL
;
1236 struct passwd
*pwd
= NULL
;
1238 if (!buffer_string_is_empty(srv
->srvconf
.groupname
)) {
1239 if (NULL
== (grp
= getgrnam(srv
->srvconf
.groupname
->ptr
))) {
1240 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1241 "can't find groupname", srv
->srvconf
.groupname
);
1246 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1247 if (NULL
== (pwd
= getpwnam(srv
->srvconf
.username
->ptr
))) {
1248 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1249 "can't find username", srv
->srvconf
.username
);
1253 if (pwd
->pw_uid
== 0) {
1254 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1255 "I will not set uid to 0\n");
1259 if (NULL
== grp
&& NULL
== (grp
= getgrgid(pwd
->pw_gid
))) {
1260 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1261 "can't find group id", pwd
->pw_gid
);
1267 if (grp
->gr_gid
== 0) {
1268 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1269 "I will not set gid to 0\n");
1275 * Change group before chroot, when we have access
1279 if (-1 == setgid(grp
->gr_gid
)) {
1280 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgid failed: ", strerror(errno
));
1283 if (-1 == setgroups(0, NULL
)) {
1284 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgroups failed: ", strerror(errno
));
1287 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1288 initgroups(srv
->srvconf
.username
->ptr
, grp
->gr_gid
);
1293 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
1296 if (-1 == chroot(srv
->srvconf
.changeroot
->ptr
)) {
1297 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chroot failed: ", strerror(errno
));
1300 if (-1 == chdir("/")) {
1301 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chdir failed: ", strerror(errno
));
1307 /* drop root privs */
1309 if (-1 == setuid(pwd
->pw_uid
)) {
1310 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setuid failed: ", strerror(errno
));
1315 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1317 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1319 if (srv
->srvconf
.enable_cores
) {
1320 prctl(PR_SET_DUMPABLE
, 1, 0, 0, 0);
1326 if (srv
->srvconf
.max_conns
> srv
->max_fds
/2) {
1327 /* we can't have more connections than max-fds/2 */
1328 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", "can't have more connections than fds/2: ", srv
->srvconf
.max_conns
, srv
->max_fds
);
1329 srv
->max_conns
= srv
->max_fds
/2;
1330 } else if (srv
->srvconf
.max_conns
) {
1331 /* otherwise respect the wishes of the user */
1332 srv
->max_conns
= srv
->srvconf
.max_conns
;
1334 /* or use the default: we really don't want to hit max-fds */
1335 srv
->max_conns
= srv
->max_fds
/3;
1339 /* network is up, let's daemonize ourself */
1340 if (0 == srv
->srvconf
.dont_daemonize
&& 0 == graceful_restart
) {
1341 parent_pipe_fd
= daemonize();
1344 graceful_restart
= 0;/*(reset here after avoiding further daemonizing)*/
1345 graceful_shutdown
= 0;
1348 #ifdef HAVE_SIGACTION
1349 memset(&act
, 0, sizeof(act
));
1350 act
.sa_handler
= SIG_IGN
;
1351 sigaction(SIGPIPE
, &act
, NULL
);
1352 # if defined(SA_SIGINFO)
1353 last_sighup_info
.si_uid
= 0,
1354 last_sighup_info
.si_pid
= 0;
1355 last_sigterm_info
.si_uid
= 0,
1356 last_sigterm_info
.si_pid
= 0;
1357 act
.sa_sigaction
= sigaction_handler
;
1358 sigemptyset(&act
.sa_mask
);
1359 act
.sa_flags
= SA_SIGINFO
;
1361 act
.sa_handler
= signal_handler
;
1362 sigemptyset(&act
.sa_mask
);
1365 sigaction(SIGINT
, &act
, NULL
);
1366 sigaction(SIGTERM
, &act
, NULL
);
1367 sigaction(SIGHUP
, &act
, NULL
);
1368 sigaction(SIGALRM
, &act
, NULL
);
1369 sigaction(SIGUSR1
, &act
, NULL
);
1371 /* it should be safe to restart syscalls after SIGCHLD */
1372 act
.sa_flags
|= SA_RESTART
| SA_NOCLDSTOP
;
1373 sigaction(SIGCHLD
, &act
, NULL
);
1375 #elif defined(HAVE_SIGNAL)
1376 /* ignore the SIGPIPE from sendfile() */
1377 signal(SIGPIPE
, SIG_IGN
);
1378 signal(SIGALRM
, signal_handler
);
1379 signal(SIGTERM
, signal_handler
);
1380 signal(SIGHUP
, signal_handler
);
1381 signal(SIGCHLD
, signal_handler
);
1382 signal(SIGINT
, signal_handler
);
1383 signal(SIGUSR1
, signal_handler
);
1387 srv
->gid
= getgid();
1388 srv
->uid
= getuid();
1389 srv
->pid
= getpid();
1391 /* write pid file */
1393 buffer_copy_int(srv
->tmp_buf
, srv
->pid
);
1394 buffer_append_string_len(srv
->tmp_buf
, CONST_STR_LEN("\n"));
1395 if (-1 == write_all(pid_fd
, CONST_BUF_LEN(srv
->tmp_buf
))) {
1396 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't write pid file:", strerror(errno
));
1401 } else if (pid_fd
< -2) {
1405 /* Close stderr ASAP in the child process to make sure that nothing
1406 * is being written to that fd which may not be valid anymore. */
1407 if (!srv
->srvconf
.preflight_check
) {
1408 if (-1 == log_error_open(srv
)) {
1409 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Opening errorlog failed. Going down.");
1412 log_error_write(srv
, __FILE__
, __LINE__
, "s", "server started (" PACKAGE_DESC
")");
1415 if (buffer_is_empty(srv
->config_storage
[0]->server_tag
)) {
1416 buffer_copy_string_len(srv
->config_storage
[0]->server_tag
, CONST_STR_LEN(PACKAGE_DESC
));
1419 if (HANDLER_GO_ON
!= plugins_call_set_defaults(srv
)) {
1420 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Configuration of plugins failed. Going down.");
1424 /* settings might be enabled during module config set defaults */
1425 srv
->config_storage
[0]->high_precision_timestamps
= srv
->srvconf
.high_precision_timestamps
;
1427 /* dump unused config-keys */
1428 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1429 array
*config
= ((data_config
*)srv
->config_context
->data
[i
])->value
;
1432 for (j
= 0; config
&& j
< config
->used
; j
++) {
1433 data_unset
*du
= config
->data
[j
];
1435 /* all var.* is known as user defined variable */
1436 if (strncmp(du
->key
->ptr
, "var.", sizeof("var.") - 1) == 0) {
1440 if (NULL
== array_get_element_klen(srv
->config_touched
, CONST_BUF_LEN(du
->key
))) {
1441 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1442 "WARNING: unknown config-key:",
1449 if (srv
->config_unsupported
) {
1450 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1451 "Configuration contains unsupported keys. Going down.");
1454 if (srv
->config_deprecated
) {
1455 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1456 "Configuration contains deprecated keys. Going down.");
1459 if (srv
->config_unsupported
|| srv
->config_deprecated
) {
1463 if (srv
->srvconf
.preflight_check
) {
1464 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1471 * notify daemonize-grandparent of successful startup
1472 * do this before any further forking is done (workers)
1474 if (0 == srv
->srvconf
.dont_daemonize
&& -1 != parent_pipe_fd
) {
1475 if (0 > write(parent_pipe_fd
, "", 1)) return -1;
1476 close(parent_pipe_fd
);
1479 if (idle_limit
&& srv
->srvconf
.max_worker
) {
1480 srv
->srvconf
.max_worker
= 0;
1481 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1482 "server idle time limit command line option disables server.max-worker config file option.");
1485 /* start watcher and workers */
1486 num_childs
= srv
->srvconf
.max_worker
;
1487 if (num_childs
> 0) {
1488 pid_t pids
[num_childs
];
1490 const int npids
= num_childs
;
1492 unsigned int timer
= 0;
1493 for (int n
= 0; n
< npids
; ++n
) pids
[n
] = -1;
1494 while (!child
&& !srv_shutdown
&& !graceful_shutdown
) {
1495 if (num_childs
> 0) {
1496 switch ((pid
= fork())) {
1505 for (int n
= 0; n
< npids
; ++n
) {
1506 if (-1 == pids
[n
]) {
1516 if (-1 != (pid
= wait(&status
))) {
1517 srv
->cur_ts
= time(NULL
);
1518 if (plugins_call_handle_waitpid(srv
, pid
, status
) != HANDLER_GO_ON
) {
1519 if (!timer
) alarm((timer
= 5));
1522 switch (fdevent_reaped_logger_pipe(pid
)) {
1524 case -1: if (!timer
) alarm((timer
= 5));
1529 * check if one of our workers went away
1531 for (int n
= 0; n
< npids
; ++n
) {
1532 if (pid
== pids
[n
]) {
1541 srv
->cur_ts
= time(NULL
);
1543 * if we receive a SIGHUP we have to close our logs ourself as we don't
1544 * have the mainloop who can help us here
1546 if (handle_sig_hup
) {
1549 log_error_cycle(srv
);
1551 /* forward SIGHUP to workers */
1552 for (int n
= 0; n
< npids
; ++n
) {
1553 if (pids
[n
] > 0) kill(pids
[n
], SIGHUP
);
1556 if (handle_sig_alarm
) {
1557 handle_sig_alarm
= 0;
1559 plugins_call_handle_trigger(srv
);
1560 fdevent_restart_logger_pipes(srv
->cur_ts
);
1571 * for the parent this is the exit-point
1575 * kill all children too
1577 if (graceful_shutdown
|| graceful_restart
) {
1578 /* flag to ignore one SIGINT if graceful_restart */
1579 if (graceful_restart
) graceful_restart
= 2;
1581 server_graceful_state(srv
);
1582 } else if (srv_shutdown
) {
1589 /* ignore SIGUSR1 in workers; only parent directs graceful restart */
1590 #ifdef HAVE_SIGACTION
1592 struct sigaction actignore
;
1593 memset(&actignore
, 0, sizeof(actignore
));
1594 actignore
.sa_handler
= SIG_IGN
;
1595 sigaction(SIGUSR1
, &actignore
, NULL
);
1597 #elif defined(HAVE_SIGNAL)
1598 signal(SIGUSR1
, SIG_IGN
);
1602 * make sure workers do not muck with pid-file
1608 buffer_reset(srv
->srvconf
.pid_file
);
1610 fdevent_clr_logger_pipe_pids();
1611 srv
->pid
= getpid();
1616 if (NULL
== (srv
->ev
= fdevent_init(srv
))) {
1617 log_error_write(srv
, __FILE__
, __LINE__
,
1618 "s", "fdevent_init failed");
1622 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1623 #ifdef HAVE_SIGACTION
1624 sigaction(SIGCHLD
, &act
, NULL
);
1625 #elif defined(HAVE_SIGNAL)
1626 signal(SIGCHLD
, signal_handler
);
1630 * kqueue() is called here, select resets its internals,
1631 * all server sockets get their handlers
1634 if (0 != network_register_fdevents(srv
)) {
1638 /* might fail if user is using fam (not gamin) and famd isn't running */
1639 if (NULL
== (srv
->stat_cache
= stat_cache_init(srv
))) {
1640 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1641 "stat-cache could not be setup, dieing.");
1647 /* setup periodic timer (1 second) */
1648 struct itimerval interval
;
1649 interval
.it_interval
.tv_sec
= 1;
1650 interval
.it_interval
.tv_usec
= 0;
1651 interval
.it_value
.tv_sec
= 1;
1652 interval
.it_value
.tv_usec
= 0;
1653 if (setitimer(ITIMER_REAL
, &interval
, NULL
)) {
1654 log_error_write(srv
, __FILE__
, __LINE__
, "s", "setting timer failed");
1661 /* get the current number of FDs */
1663 int fd
= fdevent_open_devnull();
1670 if (0 != server_sockets_set_nb_cloexec(srv
)) {
1674 if (oneshot_fd
&& server_oneshot_init(srv
, oneshot_fd
)) {
1679 while (!srv_shutdown
) {
1684 if (handle_sig_hup
) {
1687 /* reset notification */
1691 /* cycle logfiles */
1693 switch(r
= plugins_call_handle_sighup(srv
)) {
1697 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "sighup-handler return with an error", r
);
1701 if (-1 == log_error_cycle(srv
)) {
1702 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cycling errorlog failed, dying");
1706 #ifdef HAVE_SIGACTION
1707 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
1708 "logfiles cycled UID =",
1709 last_sighup_info
.si_uid
,
1711 last_sighup_info
.si_pid
);
1713 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1719 if (handle_sig_alarm
) {
1723 /* reset notification */
1724 handle_sig_alarm
= 0;
1727 /* get current time */
1728 min_ts
= time(NULL
);
1730 if (min_ts
!= srv
->cur_ts
) {
1731 #ifdef DEBUG_CONNECTION_STATES
1734 connections
*conns
= srv
->conns
;
1737 switch(r
= plugins_call_handle_trigger(srv
)) {
1741 log_error_write(srv
, __FILE__
, __LINE__
, "s", "one of the triggers failed");
1744 log_error_write(srv
, __FILE__
, __LINE__
, "d", r
);
1748 srv
->cur_ts
= min_ts
;
1750 /* check idle time limit, if enabled */
1751 if (idle_limit
&& idle_limit
< min_ts
- last_active_ts
&& !graceful_shutdown
) {
1752 log_error_write(srv
, __FILE__
, __LINE__
, "sDs", "[note] idle timeout", (int)idle_limit
,
1753 "s exceeded, initiating graceful shutdown");
1754 graceful_shutdown
= 2; /* value 2 indicates idle timeout */
1755 if (graceful_restart
) {
1756 graceful_restart
= 0;
1757 if (pid_fd
< -2) pid_fd
= -pid_fd
;
1758 server_sockets_close(srv
);
1762 #ifdef HAVE_GETLOADAVG
1763 /* refresh loadavg data every 30 seconds */
1764 if (srv
->srvconf
.loadts
+ 30 < min_ts
) {
1765 if (-1 != getloadavg(srv
->srvconf
.loadavg
, 3)) {
1766 srv
->srvconf
.loadts
= min_ts
;
1771 /* cleanup stat-cache */
1772 stat_cache_trigger_cleanup(srv
);
1773 /* reset global/aggregate rate limit counters */
1774 for (i
= 0; i
< srv
->config_context
->used
; ++i
) {
1775 srv
->config_storage
[i
]->global_bytes_per_second_cnt
= 0;
1777 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1778 if (graceful_shutdown
&& !srv_shutdown
) server_graceful_shutdown_maint(srv
);
1780 * check all connections for timeouts
1783 for (ndx
= 0; ndx
< conns
->used
; ndx
++) {
1784 connection
* const con
= conns
->ptr
[ndx
];
1785 const int waitevents
= fdevent_event_get_interest(srv
->ev
, con
->fd
);
1789 if (con
->state
== CON_STATE_CLOSE
) {
1790 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
) {
1793 } else if (waitevents
& FDEVENT_IN
) {
1794 if (con
->request_count
== 1 || con
->state
!= CON_STATE_READ
) { /* e.g. CON_STATE_READ_POST || CON_STATE_WRITE */
1795 if (srv
->cur_ts
- con
->read_idle_ts
> con
->conf
.max_read_idle
) {
1797 if (con
->conf
.log_request_handling
) {
1798 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1799 "connection closed - read timeout:", con
->fd
);
1802 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1806 if (srv
->cur_ts
- con
->read_idle_ts
> con
->keep_alive_idle
) {
1808 if (con
->conf
.log_request_handling
) {
1809 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1810 "connection closed - keep-alive timeout:", con
->fd
);
1813 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1819 /* max_write_idle timeout currently functions as backend timeout,
1820 * too, after response has been started.
1821 * future: have separate backend timeout, and then change this
1822 * to check for write interest before checking for timeout */
1823 /*if (waitevents & FDEVENT_OUT)*/
1824 if ((con
->state
== CON_STATE_WRITE
) &&
1825 (con
->write_request_ts
!= 0)) {
1827 if (srv
->cur_ts
- con
->write_request_ts
> 60) {
1828 log_error_write(srv
, __FILE__
, __LINE__
, "sdd",
1829 "connection closed - pre-write-request-timeout:", con
->fd
, srv
->cur_ts
- con
->write_request_ts
);
1833 if (srv
->cur_ts
- con
->write_request_ts
> con
->conf
.max_write_idle
) {
1835 if (con
->conf
.log_timeouts
) {
1836 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsosds",
1837 "NOTE: a request from",
1841 "timed out after writing",
1844 (int)con
->conf
.max_write_idle
,
1845 "seconds. If this a problem increase server.max-write-idle");
1847 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1852 /* we don't like div by zero */
1853 if (0 == (t_diff
= srv
->cur_ts
- con
->connection_start
)) t_diff
= 1;
1855 if (con
->traffic_limit_reached
&&
1856 (con
->conf
.kbytes_per_second
== 0 ||
1857 ((con
->bytes_written
/ t_diff
) < con
->conf
.kbytes_per_second
* 1024))) {
1858 /* enable connection again */
1859 con
->traffic_limit_reached
= 0;
1864 con
->bytes_written_cur_second
= 0;
1867 connection_state_machine(srv
, con
);
1870 #if DEBUG_CONNECTION_STATES
1872 fprintf(stderr
, "connection-state: ");
1876 fprintf(stderr
, "c[%d,%d]: %s ",
1879 connection_get_state(con
->state
));
1883 #ifdef DEBUG_CONNECTION_STATES
1884 if (cs
== 1) fprintf(stderr
, "\n");
1889 if (handle_sig_child
) {
1891 handle_sig_child
= 0;
1894 pid
= waitpid(-1, &status
, WNOHANG
);
1896 if (plugins_call_handle_waitpid(srv
, pid
, status
) != HANDLER_GO_ON
) {
1899 if (0 == srv
->srvconf
.max_worker
) {
1900 /* check piped-loggers and restart, even if shutting down */
1901 if (fdevent_waitpid_logger_pipe_pid(pid
, srv
->cur_ts
)) {
1906 } while (pid
> 0 || (-1 == pid
&& errno
== EINTR
));
1909 if (graceful_shutdown
) {
1910 server_graceful_state(srv
);
1911 srv
->sockets_disabled
= 1;
1912 } else if (srv
->sockets_disabled
) {
1913 /* our server sockets are disabled, why ? */
1915 if ((srv
->cur_fds
+ srv
->want_fds
< srv
->max_fds
* 8 / 10) && /* we have enough unused fds */
1916 (srv
->conns
->used
<= srv
->max_conns
* 9 / 10)) {
1917 server_sockets_set_event(srv
, FDEVENT_IN
);
1918 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets enabled again");
1920 srv
->sockets_disabled
= 0;
1923 if ((srv
->cur_fds
+ srv
->want_fds
> srv
->max_fds
* 9 / 10) || /* out of fds */
1924 (srv
->conns
->used
>= srv
->max_conns
)) { /* out of connections */
1925 /* disable server-fds */
1926 server_sockets_set_event(srv
, 0);
1928 if (srv
->conns
->used
>= srv
->max_conns
) {
1929 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets disabled, connection limit reached");
1931 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets disabled, out-of-fds");
1934 srv
->sockets_disabled
= 1;
1938 if (graceful_shutdown
&& srv
->conns
->used
== 0) {
1939 /* we are in graceful shutdown phase and all connections are closed
1940 * we are ready to terminate without harming anyone */
1945 /* we still have some fds to share */
1946 if (srv
->want_fds
) {
1947 /* check the fdwaitqueue for waiting fds */
1948 int free_fds
= srv
->max_fds
- srv
->cur_fds
- 16;
1951 for (; free_fds
> 0 && NULL
!= (con
= fdwaitqueue_unshift(srv
, srv
->fdwaitqueue
)); free_fds
--) {
1952 connection_state_machine(srv
, con
);
1958 if ((n
= fdevent_poll(srv
->ev
, 1000)) > 0) {
1959 /* n is the number of events */
1963 last_active_ts
= srv
->cur_ts
;
1966 fdevent_handler handler
;
1969 fd_ndx
= fdevent_event_next_fdndx (srv
->ev
, fd_ndx
);
1970 if (-1 == fd_ndx
) break; /* not all fdevent handlers know how many fds got an event */
1972 revents
= fdevent_event_get_revent (srv
->ev
, fd_ndx
);
1973 fd
= fdevent_event_get_fd (srv
->ev
, fd_ndx
);
1974 handler
= fdevent_get_handler(srv
->ev
, fd
);
1975 context
= fdevent_get_context(srv
->ev
, fd
);
1976 if (NULL
!= handler
) {
1977 (*handler
)(srv
, context
, revents
);
1980 } else if (n
< 0 && errno
!= EINTR
) {
1981 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1982 "fdevent_poll failed:",
1986 if (n
>= 0) fdevent_sched_run(srv
, srv
->ev
);
1988 for (ndx
= 0; ndx
< srv
->joblist
->used
; ndx
++) {
1989 connection
*con
= srv
->joblist
->ptr
[ndx
];
1990 connection_state_machine(srv
, con
);
1993 srv
->joblist
->used
= 0;
1996 if (graceful_shutdown
|| graceful_restart
) {
1997 server_graceful_state(srv
);
2000 if (2 == graceful_shutdown
) { /* value 2 indicates idle timeout */
2001 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2002 "server stopped after idle timeout");
2004 #ifdef HAVE_SIGACTION
2005 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2006 "server stopped by UID =",
2007 last_sigterm_info
.si_uid
,
2009 last_sigterm_info
.si_pid
);
2011 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2019 int main (int argc
, char **argv
) {
2023 #ifndef HAVE_ISSETUGID
2024 #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2026 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2028 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2033 /* for nice %b handling in strftime() */
2034 setlocale(LC_TIME
, "C");
2037 server
* const srv
= server_init();
2039 if (graceful_restart
) {
2040 server_sockets_restore(srv
);
2044 rc
= server_main(srv
, argc
, argv
);
2047 remove_pid_file(srv
);
2048 log_error_close(srv
);
2049 fdevent_close_logger_pipes();
2050 if (graceful_restart
)
2051 server_sockets_save(srv
);
2054 connections_free(srv
);
2058 if (0 != rc
|| !graceful_restart
) break;
2060 /* wait for all children to exit before graceful restart */
2061 while (waitpid(-1, NULL
, 0) > 0) ;
2062 } while (graceful_restart
);