10 #include "http_auth.h"
11 #include "http_vhostdb.h"
13 #include "connections.h"
14 #include "sock_addr.h"
15 #include "stat_cache.h"
16 #include "configfile.h"
19 #include "network_write.h"
21 #ifdef HAVE_VERSIONSTAMP_H
22 # include "versionstamp.h"
24 # define REPO_VERSION ""
27 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
29 #include <sys/types.h>
49 #ifdef HAVE_VALGRIND_VALGRIND_H
50 # include <valgrind/valgrind.h>
53 #ifdef HAVE_SYS_WAIT_H
54 # include <sys/wait.h>
66 #ifdef HAVE_SYS_RESOURCE_H
67 # include <sys/resource.h>
70 #ifdef HAVE_SYS_PRCTL_H
71 # include <sys/prctl.h>
74 #include "sys-crypto.h"
75 #ifdef USE_OPENSSL_CRYPTO
77 #define TEXT_SSL " (ssl)"
83 /* IRIX doesn't like the alarm based time() optimization */
84 /* #define USE_ALARM */
87 static int oneshot_fd
= 0;
88 static volatile int pid_fd
= -2;
89 static server_socket_array graceful_sockets
;
90 static server_socket_array inherited_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;
97 static time_t idle_limit
= 0;
99 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
100 static volatile siginfo_t last_sigterm_info
;
101 static volatile siginfo_t last_sighup_info
;
103 static void sigaction_handler(int sig
, siginfo_t
*si
, void *context
) {
104 static const siginfo_t empty_siginfo
;
107 if (!si
) *(const siginfo_t
**)&si
= &empty_siginfo
;
112 last_sigterm_info
= *si
;
115 if (!graceful_shutdown
) {
116 graceful_restart
= 1;
117 graceful_shutdown
= 1;
118 last_sigterm_info
= *si
;
122 if (graceful_shutdown
) {
123 if (2 == graceful_restart
)
124 graceful_restart
= 1;
128 graceful_shutdown
= 1;
130 last_sigterm_info
= *si
;
134 handle_sig_alarm
= 1;
138 last_sighup_info
= *si
;
141 handle_sig_child
= 1;
145 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
146 static void signal_handler(int sig
) {
148 case SIGTERM
: srv_shutdown
= 1; break;
150 if (!graceful_shutdown
) {
151 graceful_restart
= 1;
152 graceful_shutdown
= 1;
156 if (graceful_shutdown
) {
157 if (2 == graceful_restart
)
158 graceful_restart
= 1;
162 graceful_shutdown
= 1;
165 case SIGALRM
: handle_sig_alarm
= 1; break;
166 case SIGHUP
: handle_sig_hup
= 1; break;
167 case SIGCHLD
: handle_sig_child
= 1; break;
173 static int daemonize(void) {
177 signal(SIGTTOU
, SIG_IGN
);
180 signal(SIGTTIN
, SIG_IGN
);
183 signal(SIGTSTP
, SIG_IGN
);
186 if (pipe(pipefd
) < 0) exit(-1);
188 if (0 > (pid
= fork())) exit(-1);
195 /* parent waits for grandchild to be ready */
197 bytes
= read(pipefd
[0], &buf
, sizeof(buf
));
198 } while (bytes
< 0 && EINTR
== errno
);
202 /* closed fd (without writing) == failure in grandchild */
203 fputs("daemonized server failed to start; check error log for details\n", stderr
);
212 if (-1 == setsid()) exit(0);
214 signal(SIGHUP
, SIG_IGN
);
216 if (0 != fork()) exit(0);
218 if (0 != chdir("/")) exit(0);
220 fdevent_setfd_cloexec(pipefd
[1]);
226 static server
*server_init(void) {
228 server
*srv
= calloc(1, sizeof(*srv
));
231 srv->x = buffer_init();
233 CLEAN(response_header
);
234 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
->errh
= log_error_st_init(&srv
->cur_ts
, &srv
->last_generated_debug_ts
);
283 srv
->srvconf
.modules
= array_init();
284 srv
->srvconf
.modules_dir
= buffer_init_string(LIBRARY_DIR
);
285 srv
->srvconf
.network_backend
= buffer_init();
286 srv
->srvconf
.upload_tempdirs
= array_init();
287 srv
->srvconf
.reject_expect_100_with_417
= 1;
288 srv
->srvconf
.xattr_name
= buffer_init_string("Content-Type");
289 srv
->srvconf
.http_header_strict
= 1;
290 srv
->srvconf
.http_host_strict
= 1; /*(implies http_host_normalize)*/
291 srv
->srvconf
.http_host_normalize
= 0;
292 srv
->srvconf
.http_url_normalize
= HTTP_PARSEOPT_URL_NORMALIZE
293 | HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED
294 | HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT
295 | HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
296 | HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE
;
297 srv
->srvconf
.high_precision_timestamps
= 0;
298 srv
->srvconf
.max_request_field_size
= 8192;
299 srv
->srvconf
.loadavg
[0] = 0.0;
300 srv
->srvconf
.loadavg
[1] = 0.0;
301 srv
->srvconf
.loadavg
[2] = 0.0;
302 srv
->srvconf
.compat_module_load
= 1;
303 srv
->srvconf
.systemd_socket_activation
= 0;
305 srv
->split_vals
= array_init();
306 srv
->request_env
= plugins_call_handle_request_env
;
312 static void server_free(server
*srv
) {
315 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
316 buffer_free(srv
->mtime_cache
[i
].str
);
319 if (oneshot_fd
> 0) {
326 CLEAN(response_header
);
327 CLEAN(parse_full_path
);
329 CLEAN(response_range
);
332 CLEAN(cond_check_buf
);
334 CLEAN(srvconf
.errorlog_file
);
335 CLEAN(srvconf
.breakagelog_file
);
336 CLEAN(srvconf
.groupname
);
337 CLEAN(srvconf
.username
);
338 CLEAN(srvconf
.changeroot
);
339 CLEAN(srvconf
.bindhost
);
340 CLEAN(srvconf
.event_handler
);
341 CLEAN(srvconf
.pid_file
);
342 CLEAN(srvconf
.modules_dir
);
343 CLEAN(srvconf
.network_backend
);
344 CLEAN(srvconf
.xattr_name
);
345 CLEAN(srvconf
.syslog_facility
);
347 CLEAN(tmp_chunk_len
);
350 fdevent_free(srv
->ev
);
354 if (srv
->config_storage
) {
355 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
356 specific_config
*s
= srv
->config_storage
[i
];
360 buffer_free(s
->document_root
);
361 buffer_free(s
->server_name
);
362 buffer_free(s
->server_tag
);
363 buffer_free(s
->error_handler
);
364 buffer_free(s
->error_handler_404
);
365 buffer_free(s
->errorfile_prefix
);
366 buffer_free(s
->socket_perms
);
367 array_free(s
->mimetypes
);
370 free(srv
->config_storage
);
371 srv
->config_storage
= NULL
;
377 CLEAN(config_context
);
378 CLEAN(config_touched
);
380 CLEAN(srvconf
.upload_tempdirs
);
383 joblist_free(srv
, srv
->joblist
);
384 fdwaitqueue_free(srv
, srv
->fdwaitqueue
);
386 if (srv
->stat_cache
) {
387 stat_cache_free(srv
->stat_cache
);
390 array_free(srv
->srvconf
.modules
);
391 array_free(srv
->split_vals
);
394 chunkqueue_chunk_pool_free();
396 log_error_st_free(srv
->errh
);
401 static void remove_pid_file(server
*srv
) {
402 if (pid_fd
<= -2) return;
403 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) && 0 <= pid_fd
) {
404 if (0 != ftruncate(pid_fd
, 0)) {
405 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
406 "ftruncate failed for:",
407 srv
->srvconf
.pid_file
,
416 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) &&
417 buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
418 if (0 != unlink(srv
->srvconf
.pid_file
->ptr
)) {
419 if (errno
!= EACCES
&& errno
!= EPERM
) {
420 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
421 "unlink failed for:",
422 srv
->srvconf
.pid_file
,
432 static server_socket
* server_oneshot_getsock(server
*srv
, sock_addr
*cnt_addr
) {
433 server_socket
*srv_socket
, *srv_socket_wild
= NULL
;
435 for (i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
436 srv_socket
= srv
->srv_sockets
.ptr
[i
];
437 if (!sock_addr_is_port_eq(&srv_socket
->addr
,cnt_addr
)) continue;
438 if (sock_addr_is_addr_eq(&srv_socket
->addr
,cnt_addr
)) return srv_socket
;
440 if (NULL
!= srv_socket_wild
) continue;
441 if (sock_addr_is_addr_wildcard(&srv_socket
->addr
)) {
442 srv_socket_wild
= srv_socket
;
446 if (NULL
!= srv_socket_wild
) {
447 return srv_socket_wild
;
448 } else if (srv
->srv_sockets
.used
) {
449 return srv
->srv_sockets
.ptr
[0];
451 log_error_write(srv
, __FILE__
, __LINE__
, "s", "no sockets configured");
458 static int server_oneshot_init(server
*srv
, int fd
) {
459 /* Note: does not work with netcat due to requirement that fd be socket.
460 * STDOUT_FILENO was not saved earlier in startup, and that is to where
461 * netcat expects output to be sent. Since lighttpd expects connections
462 * to be sockets, con->fd is where output is sent; separate fds are not
463 * stored for input and output, but netcat has different fds for stdin
464 * and * stdout. To support netcat, would additionally need to avoid
465 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
466 * addresses from environment variables:
467 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
468 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
472 server_socket
*srv_socket
;
477 if (0 != fstat(fd
, &st
)) {
478 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fstat:", strerror(errno
));
482 if (!S_ISSOCK(st
.st_mode
)) {
483 /* require that fd is a socket
484 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
485 log_error_write(srv
, __FILE__
, __LINE__
, "s", "lighttpd -1 stdin is not a socket");
489 cnt_len
= sizeof(cnt_addr
);
490 if (0 != getsockname(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
491 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getsockname:", strerror(errno
));
495 srv_socket
= server_oneshot_getsock(srv
, &cnt_addr
);
496 if (NULL
== srv_socket
) return 0;
498 cnt_len
= sizeof(cnt_addr
);
499 if (0 != getpeername(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
500 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getpeername:", strerror(errno
));
504 /*(must set flags; fd did not pass through fdevent accept() logic)*/
505 if (-1 == fdevent_fcntl_set_nb_cloexec(srv
->ev
, fd
)) {
506 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl:", strerror(errno
));
510 if (sock_addr_get_family(&cnt_addr
) != AF_UNIX
) {
511 network_accept_tcp_nagle_disable(fd
);
514 con
= connection_accepted(srv
, srv_socket
, &cnt_addr
, fd
);
515 if (NULL
== con
) return 0;
517 connection_state_machine(srv
, con
);
523 static void show_version (void) {
524 char *b
= PACKAGE_DESC TEXT_SSL \
525 " - a light and fast webserver\n"
526 #ifdef NONREPRODUCIBLE_BUILD
527 "Build-Date: " __DATE__
" " __TIME__
"\n";
530 write_all(STDOUT_FILENO
, b
, strlen(b
));
534 static void show_features (void) {
535 static const char features
[] =
542 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
547 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
548 "\t+ bzip2 support\n"
550 "\t- bzip2 support\n"
552 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
553 "\t+ crypt support\n"
555 "\t- crypt support\n"
568 "\t+ MySQL support\n"
570 "\t- MySQL support\n"
573 "\t+ PgSQL support\n"
575 "\t- PgSQL support\n"
583 "\t+ Kerberos support\n"
585 "\t- Kerberos support\n"
587 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
598 "\t+ memcached support\n"
600 "\t- memcached support\n"
617 #ifdef HAVE_SQLITE3_H
618 "\t+ SQLite support\n"
620 "\t- SQLite support\n"
629 printf("%s%s%s\n", fdevent_show_event_handlers(), network_write_show_handlers(), features
);
633 static void show_help (void) {
634 char *b
= PACKAGE_DESC TEXT_SSL
635 #ifdef NONREPRODUCIBLE_BUILD
636 " ("__DATE__
" " __TIME__
")"
638 " - a light and fast webserver\n" \
640 " -f <name> filename of the config-file\n" \
641 " -m <name> module directory (default: "LIBRARY_DIR
")\n" \
642 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
643 " -1 process single (one) request on stdin socket, then exit\n" \
644 " -p print the parsed config-file in internal form, and exit\n" \
645 " -t test config-file syntax, then exit\n" \
646 " -tt test config-file syntax, load and init modules, then exit\n" \
647 " -D don't go to background (default: go to background)\n" \
648 " -v show version\n" \
649 " -V show compile-time features\n" \
650 " -h show this help\n" \
653 write_all(STDOUT_FILENO
, b
, strlen(b
));
659 * we have 4 possibilities:
667 static int log_error_open(server
*srv
) {
668 log_error_st
*errh
= srv
->errh
;
671 /* perhaps someone wants to use syslog() */
673 if (!buffer_string_is_empty(srv
->srvconf
.syslog_facility
)) {
674 static const struct facility_name_st
{
677 } facility_names
[] = {
680 ,{ "authpriv", LOG_AUTHPRIV
}
683 ,{ "cron", LOG_CRON
}
685 ,{ "daemon", LOG_DAEMON
}
690 ,{ "kern", LOG_KERN
}
696 ,{ "mail", LOG_MAIL
}
699 ,{ "news", LOG_NEWS
}
701 ,{ "security", LOG_AUTH
} /* DEPRECATED */
703 ,{ "syslog", LOG_SYSLOG
}
706 ,{ "user", LOG_USER
}
709 ,{ "uucp", LOG_UUCP
}
711 ,{ "local0", LOG_LOCAL0
}
712 ,{ "local1", LOG_LOCAL1
}
713 ,{ "local2", LOG_LOCAL2
}
714 ,{ "local3", LOG_LOCAL3
}
715 ,{ "local4", LOG_LOCAL4
}
716 ,{ "local5", LOG_LOCAL5
}
717 ,{ "local6", LOG_LOCAL6
}
718 ,{ "local7", LOG_LOCAL7
}
721 for (i
= 0; i
< sizeof(facility_names
)/sizeof(facility_names
[0]); ++i
) {
722 const struct facility_name_st
*f
= facility_names
+i
;
723 if (0 == strcmp(srv
->srvconf
.syslog_facility
->ptr
, f
->name
)) {
728 if (-1 == facility
) {
729 log_error_write(srv
, __FILE__
, __LINE__
, "SBS",
730 "unrecognized server.syslog-facility: \"",
731 srv
->srvconf
.syslog_facility
,
732 "\"; defaulting to \"daemon\" facility");
735 openlog("lighttpd", LOG_CONS
|LOG_PID
, -1==facility
? LOG_DAEMON
: facility
);
738 errh
->errorlog_mode
= ERRORLOG_FD
;
739 errh
->errorlog_fd
= STDERR_FILENO
;
741 if (srv
->srvconf
.errorlog_use_syslog
) {
742 errh
->errorlog_mode
= ERRORLOG_SYSLOG
;
744 else if (!buffer_string_is_empty(srv
->srvconf
.errorlog_file
)) {
745 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
746 int fd
= fdevent_open_logger(logfile
);
748 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
749 "opening errorlog '", logfile
,
750 "' failed: ", strerror(errno
));
753 errh
->errorlog_fd
= fd
;
754 errh
->errorlog_mode
= logfile
[0] == '|' ? ERRORLOG_PIPE
: ERRORLOG_FILE
;
757 if (errh
->errorlog_mode
== ERRORLOG_FD
&& !srv
->srvconf
.dont_daemonize
) {
758 /* We can only log to stderr in dont-daemonize mode;
759 * if we do daemonize and no errorlog file is specified,
760 * we log into /dev/null
762 errh
->errorlog_fd
= -1;
765 if (!buffer_string_is_empty(srv
->srvconf
.breakagelog_file
)) {
766 const char *logfile
= srv
->srvconf
.breakagelog_file
->ptr
;
768 if (errh
->errorlog_mode
== ERRORLOG_FD
) {
769 errh
->errorlog_fd
= dup(STDERR_FILENO
);
770 fdevent_setfd_cloexec(errh
->errorlog_fd
);
773 if (-1 == (errfd
= fdevent_open_logger(logfile
))) {
774 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
775 "opening errorlog '", logfile
,
776 "' failed: ", strerror(errno
));
780 if (*logfile
== '|') fdevent_breakagelog_logger_pipe(errfd
);
782 else if (!srv
->srvconf
.dont_daemonize
) {
783 /* move STDERR_FILENO to /dev/null */
784 if (-1 == (errfd
= fdevent_open_devnull())) {
785 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
786 "opening /dev/null failed:", strerror(errno
));
791 /*(leave STDERR_FILENO as-is)*/
795 if (0 != fdevent_set_stdin_stdout_stderr(-1, -1, errfd
)) {
796 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
797 "setting stderr failed:", strerror(errno
));
799 if (-1 != errfd
) close(errfd
);
804 if (-1 != errfd
) close(errfd
);
815 static int log_error_cycle(server
*srv
) {
816 /* cycle only if the error log is a file */
818 log_error_st
*errh
= srv
->errh
;
819 if (errh
->errorlog_mode
== ERRORLOG_FILE
) {
820 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
821 if (-1 == fdevent_cycle_logger(logfile
, &errh
->errorlog_fd
)) {
822 /* write to old log */
823 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
824 "cycling errorlog '", logfile
,
825 "' failed: ", strerror(errno
));
833 static int log_error_close(server
*srv
) {
834 log_error_st
*errh
= srv
->errh
;
835 switch(errh
->errorlog_mode
) {
839 if (-1 != errh
->errorlog_fd
) {
840 /* don't close STDERR */
841 /* fdevent_close_logger_pipes() closes ERRORLOG_PIPE */
842 if (STDERR_FILENO
!= errh
->errorlog_fd
843 && ERRORLOG_PIPE
!= errh
->errorlog_mode
) {
844 close(errh
->errorlog_fd
);
846 errh
->errorlog_fd
= -1;
849 case ERRORLOG_SYSLOG
:
860 static void server_sockets_save (server
*srv
) { /* graceful_restart */
861 memcpy(&graceful_sockets
, &srv
->srv_sockets
, sizeof(server_socket_array
));
862 memset(&srv
->srv_sockets
, 0, sizeof(server_socket_array
));
863 memcpy(&inherited_sockets
, &srv
->srv_sockets_inherited
, sizeof(server_socket_array
));
864 memset(&srv
->srv_sockets_inherited
, 0, sizeof(server_socket_array
));
868 static void server_sockets_restore (server
*srv
) { /* graceful_restart */
869 memcpy(&srv
->srv_sockets
, &graceful_sockets
, sizeof(server_socket_array
));
870 memset(&graceful_sockets
, 0, sizeof(server_socket_array
));
871 memcpy(&srv
->srv_sockets_inherited
, &inherited_sockets
, sizeof(server_socket_array
));
872 memset(&inherited_sockets
, 0, sizeof(server_socket_array
));
876 static int server_sockets_set_nb_cloexec (server
*srv
) {
877 if (srv
->sockets_disabled
) return 0; /* lighttpd -1 (one-shot mode) */
878 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
879 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
880 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv
->ev
, srv_socket
->fd
)) {
881 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
882 "fcntl failed:", strerror(errno
));
890 static void server_sockets_set_event (server
*srv
, int event
) {
891 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
892 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
893 fdevent_fdnode_event_set(srv
->ev
, srv_socket
->fdn
, event
);
898 static void server_sockets_unregister (server
*srv
) {
899 if (2 == srv
->sockets_disabled
) return;
900 srv
->sockets_disabled
= 2;
901 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
)
902 network_unregister_sock(srv
, srv
->srv_sockets
.ptr
[i
]);
906 static void server_sockets_close (server
*srv
) {
907 /* closing socket right away will make it possible for the next lighttpd
908 * to take over (old-style graceful restart), but only if backends
909 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
910 * than started by lighttpd via "bin-path")
912 if (3 == srv
->sockets_disabled
) return;
913 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
914 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
915 if (-1 == srv_socket
->fd
) continue;
916 if (2 != srv
->sockets_disabled
) network_unregister_sock(srv
,srv_socket
);
917 close(srv_socket
->fd
);
919 /* network_close() will cleanup after us */
921 srv
->sockets_disabled
= 3;
925 static void server_graceful_shutdown_maint (server
*srv
) {
926 connections
*conns
= srv
->conns
;
927 for (size_t ndx
= 0; ndx
< conns
->used
; ++ndx
) {
928 connection
* const con
= conns
->ptr
[ndx
];
931 if (con
->state
== CON_STATE_CLOSE
) {
932 /* reduce remaining linger timeout to be
933 * (from zero) *up to* one more second, but no more */
934 if (HTTP_LINGER_TIMEOUT
> 1)
935 con
->close_timeout_ts
-= (HTTP_LINGER_TIMEOUT
- 1);
936 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
)
939 else if (con
->state
== CON_STATE_READ
&& con
->request_count
> 1
940 && chunkqueue_is_empty(con
->read_queue
)) {
941 /* close connections in keep-alive waiting for next request */
942 connection_set_state(srv
, con
, CON_STATE_ERROR
);
946 con
->keep_alive
= 0; /* disable keep-alive */
948 con
->conf
.kbytes_per_second
= 0; /* disable rate limit */
949 con
->conf
.global_kbytes_per_second
= 0; /* disable rate limit */
950 if (con
->traffic_limit_reached
) {
951 con
->traffic_limit_reached
= 0;
956 connection_state_machine(srv
, con
);
962 static void server_graceful_state (server
*srv
) {
964 if (!srv_shutdown
) server_graceful_shutdown_maint(srv
);
967 && (2 == srv
->sockets_disabled
|| 3 == srv
->sockets_disabled
)) return;
969 log_error_write(srv
, __FILE__
, __LINE__
, "s",
970 "[note] graceful shutdown started");
972 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
973 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)
974 || oneshot_fd
|| 2 == graceful_shutdown
)
975 graceful_restart
= 0;
977 if (graceful_restart
) {
978 server_sockets_unregister(srv
);
979 if (pid_fd
> 0) pid_fd
= -pid_fd
; /*(flag to skip removing pid file)*/
982 server_sockets_close(srv
);
983 remove_pid_file(srv
);
984 buffer_clear(srv
->srvconf
.pid_file
); /*(prevent more removal attempts)*/
989 static void server_sockets_enable (server
*srv
) {
990 server_sockets_set_event(srv
, FDEVENT_IN
);
991 srv
->sockets_disabled
= 0;
992 log_error_write(srv
, __FILE__
, __LINE__
, "s",
993 "[note] sockets enabled again");
997 static void server_sockets_disable (server
*srv
) {
998 server_sockets_set_event(srv
, 0);
999 srv
->sockets_disabled
= 1;
1000 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1001 (srv
->conns
->used
>= srv
->max_conns
)
1002 ? "[note] sockets disabled, connection limit reached"
1003 : "[note] sockets disabled, out-of-fds");
1007 static void server_overload_check (server
*srv
) {
1008 if (srv
->cur_fds
+ srv
->want_fds
< srv
->max_fds_lowat
1009 && srv
->conns
->used
<= srv
->max_conns
* 9 / 10) {
1011 server_sockets_enable(srv
);
1015 static void server_load_check (server
*srv
) {
1016 if (srv
->cur_fds
+ srv
->want_fds
> srv
->max_fds_hiwat
/* out of fds */
1017 || srv
->conns
->used
>= srv
->max_conns
) { /* out of connections */
1019 server_sockets_disable(srv
);
1024 static void server_process_want_fds (server
*srv
) {
1025 for (int n
= srv
->max_fds
- srv
->cur_fds
- 16; n
> 0; --n
) {
1026 connection
*con
= fdwaitqueue_unshift(srv
, srv
->fdwaitqueue
);
1027 if (NULL
== con
) break;
1028 connection_state_machine(srv
, con
);
1034 static int server_main (server
* const srv
, int argc
, char **argv
) {
1035 int print_config
= 0;
1036 int test_config
= 0;
1043 #ifdef HAVE_SIGACTION
1044 struct sigaction act
;
1048 int parent_pipe_fd
= -1;
1053 i_am_root
= (0 == getuid());
1056 /* initialize globals (including file-scoped static globals) */
1059 graceful_shutdown
= 0;
1060 handle_sig_alarm
= 1;
1063 chunkqueue_set_tempdirs_default_reset();
1064 http_auth_dumbdata_reset();
1065 http_vhostdb_dumbdata_reset();
1066 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1067 /*(intentionally preserved)*/
1068 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1069 /*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/
1072 srv
->srvconf
.port
= 0;
1073 srv
->srvconf
.dont_daemonize
= 0;
1074 srv
->srvconf
.preflight_check
= 0;
1076 while(-1 != (o
= getopt(argc
, argv
, "f:m:i:hvVD1pt"))) {
1079 if (srv
->config_storage
) {
1080 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1081 "Can only read one config file. Use the include command to use multiple config files.");
1084 if (config_read(srv
, optarg
)) {
1089 buffer_copy_string(srv
->srvconf
.modules_dir
, optarg
);
1093 long timeout
= strtol(optarg
, &endptr
, 0);
1094 if (!*optarg
|| *endptr
|| timeout
< 0) {
1095 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1096 "Invalid idle timeout value:", optarg
);
1099 idle_limit
= (time_t)timeout
;
1102 case 'p': print_config
= 1; break;
1103 case 't': ++test_config
; break;
1104 case '1': if (0 == oneshot_fd
) oneshot_fd
= dup(STDIN_FILENO
);
1106 case 'D': srv
->srvconf
.dont_daemonize
= 1; break;
1107 case 'v': show_version(); return 0;
1108 case 'V': show_features(); return 0;
1109 case 'h': show_help(); return 0;
1117 if (!srv
->config_storage
&& NULL
!= getenv("NSSM_SERVICE_NAME")) {
1118 char *dir
= getenv("NSSM_SERVICE_DIR");
1119 if (NULL
!= dir
&& 0 != chdir(dir
)) {
1120 log_error_write(srv
, __FILE__
, __LINE__
, "sss", "chdir failed:", dir
, strerror(errno
));
1123 srv
->srvconf
.dont_daemonize
= 1;
1124 buffer_copy_string_len(srv
->srvconf
.modules_dir
, CONST_STR_LEN("modules"));
1125 if (config_read(srv
, "conf/lighttpd.conf")) return -1;
1129 if (!srv
->config_storage
) {
1130 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1131 "No configuration available. Try using -f option.");
1136 data_unset
*dc
= srv
->config_context
->data
[0];
1138 dc
->fn
->print(dc
, 0);
1139 fprintf(stdout
, "\n");
1141 /* shouldn't happend */
1142 fprintf(stderr
, "global config not found\n");
1147 buffer_clear(srv
->srvconf
.pid_file
);
1148 if (1 == test_config
) {
1149 printf("Syntax OK\n");
1150 } else { /*(test_config > 1)*/
1152 srv
->srvconf
.preflight_check
= 1;
1153 srv
->srvconf
.dont_daemonize
= 1;
1157 if (test_config
|| print_config
) {
1162 if (oneshot_fd
<= STDERR_FILENO
) {
1163 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1164 "Invalid fds at startup with lighttpd -1");
1167 graceful_shutdown
= 1;
1168 srv
->sockets_disabled
= 1;
1169 srv
->srvconf
.dont_daemonize
= 1;
1170 buffer_clear(srv
->srvconf
.pid_file
);
1171 if (srv
->srvconf
.max_worker
) {
1172 srv
->srvconf
.max_worker
= 0;
1173 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1174 "server one-shot command line option disables server.max-worker config file option.");
1178 if (buffer_is_equal_string(srv
->srvconf
.bindhost
, CONST_STR_LEN("/dev/stdin"))) {
1179 stdin_fd
= dup(STDIN_FILENO
);
1180 if (stdin_fd
<= STDERR_FILENO
) {
1181 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1182 "Invalid fds at startup");
1187 /* close stdin and stdout, as they are not needed */
1193 /* coverity[overwrite_var : FALSE] */
1194 devnull
= fdevent_open_devnull();
1196 __coverity_escape__(devnull
);
1198 } while (-1 != devnull
&& devnull
<= STDERR_FILENO
);
1199 if (-1 == devnull
) {
1200 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1201 "opening /dev/null failed:", strerror(errno
));
1204 errfd
= (0 == fstat(STDERR_FILENO
, &st
)) ? -1 : devnull
;
1205 if (0 != fdevent_set_stdin_stdout_stderr(devnull
, devnull
, errfd
)) {
1206 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1207 "setting default fds failed:", strerror(errno
));
1209 if (-1 != errfd
) close(errfd
);
1210 if (devnull
!= errfd
) close(devnull
);
1215 if (-1 != errfd
) close(errfd
);
1216 if (devnull
!= errfd
) close(devnull
);
1220 if (0 != config_set_defaults(srv
)) {
1221 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1222 "setting default values failed");
1226 /* check document-root */
1227 if (buffer_string_is_empty(srv
->config_storage
[0]->document_root
)) {
1228 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1229 "document-root is not set\n");
1233 if (plugins_load(srv
)) {
1234 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1235 "loading plugins finally failed");
1239 if (HANDLER_GO_ON
!= plugins_call_init(srv
)) {
1240 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Initialization of plugins failed. Going down.");
1244 /* mod_indexfile should be listed in server.modules prior to dynamic handlers */
1246 for (buffer
*pname
= NULL
; i
< srv
->plugins
.used
; ++i
) {
1247 plugin
*p
= ((plugin
**)srv
->plugins
.ptr
)[i
];
1248 if (buffer_is_equal_string(p
->name
, CONST_STR_LEN("indexfile"))) {
1250 log_error_write(srv
, __FILE__
, __LINE__
, "SB",
1251 "Warning: mod_indexfile should be listed in server.modules prior to mod_", pname
);
1255 if (p
->handle_subrequest_start
&& p
->handle_subrequest
) {
1256 if (!pname
) pname
= p
->name
;
1260 /* open pid file BEFORE chroot */
1261 if (-2 == pid_fd
) pid_fd
= -1; /*(initial startup state)*/
1262 if (-1 == pid_fd
&& !buffer_string_is_empty(srv
->srvconf
.pid_file
)) {
1263 if (-1 == (pid_fd
= fdevent_open_cloexec(srv
->srvconf
.pid_file
->ptr
, 0, O_WRONLY
| O_CREAT
| O_EXCL
| O_TRUNC
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
))) {
1265 if (errno
!= EEXIST
) {
1266 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1267 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1271 if (0 != stat(srv
->srvconf
.pid_file
->ptr
, &st
)) {
1272 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1273 "stating existing pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1276 if (!S_ISREG(st
.st_mode
)) {
1277 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1278 "pid-file exists and isn't regular file:", srv
->srvconf
.pid_file
);
1282 if (-1 == (pid_fd
= fdevent_open_cloexec(srv
->srvconf
.pid_file
->ptr
, 0, O_WRONLY
| O_CREAT
| O_TRUNC
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
))) {
1283 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1284 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1291 #ifdef HAVE_GETRLIMIT
1294 #ifdef HAVE_VALGRIND_VALGRIND_H
1295 if (RUNNING_ON_VALGRIND
) use_rlimit
= 0;
1298 if (0 != getrlimit(RLIMIT_NOFILE
, &rlim
)) {
1299 log_error_write(srv
, __FILE__
, __LINE__
,
1300 "ss", "couldn't get 'max filedescriptors'",
1306 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1308 if (use_rlimit
&& srv
->srvconf
.max_fds
1309 && (i_am_root
|| srv
->srvconf
.max_fds
<= rlim
.rlim_max
)) {
1312 rlim
.rlim_cur
= srv
->srvconf
.max_fds
;
1313 if (i_am_root
) rlim
.rlim_max
= srv
->srvconf
.max_fds
;
1315 if (0 != setrlimit(RLIMIT_NOFILE
, &rlim
)) {
1316 log_error_write(srv
, __FILE__
, __LINE__
,
1317 "ss", "couldn't set 'max filedescriptors'",
1323 srv
->max_fds
= rlim
.rlim_cur
;
1324 /*(default upper limit of 4k if server.max-fds not specified)*/
1325 if (i_am_root
&& 0 == srv
->srvconf
.max_fds
&& rlim
.rlim_cur
> 4096)
1326 srv
->max_fds
= 4096;
1328 /* set core file rlimit, if enable_cores is set */
1329 if (use_rlimit
&& srv
->srvconf
.enable_cores
&& getrlimit(RLIMIT_CORE
, &rlim
) == 0) {
1330 rlim
.rlim_cur
= rlim
.rlim_max
;
1331 setrlimit(RLIMIT_CORE
, &rlim
);
1336 /* we need root-perms for port < 1024 */
1337 if (0 != network_init(srv
, stdin_fd
)) {
1343 /* set user and group */
1344 struct group
*grp
= NULL
;
1345 struct passwd
*pwd
= NULL
;
1347 if (!buffer_string_is_empty(srv
->srvconf
.groupname
)) {
1348 if (NULL
== (grp
= getgrnam(srv
->srvconf
.groupname
->ptr
))) {
1349 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1350 "can't find groupname", srv
->srvconf
.groupname
);
1355 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1356 if (NULL
== (pwd
= getpwnam(srv
->srvconf
.username
->ptr
))) {
1357 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1358 "can't find username", srv
->srvconf
.username
);
1362 if (pwd
->pw_uid
== 0) {
1363 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1364 "I will not set uid to 0\n");
1368 if (NULL
== grp
&& NULL
== (grp
= getgrgid(pwd
->pw_gid
))) {
1369 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1370 "can't find group id", pwd
->pw_gid
);
1376 if (grp
->gr_gid
== 0) {
1377 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1378 "I will not set gid to 0\n");
1384 * Change group before chroot, when we have access
1388 if (-1 == setgid(grp
->gr_gid
)) {
1389 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgid failed: ", strerror(errno
));
1392 if (-1 == setgroups(0, NULL
)) {
1393 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgroups failed: ", strerror(errno
));
1396 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1397 initgroups(srv
->srvconf
.username
->ptr
, grp
->gr_gid
);
1402 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
1405 if (-1 == chroot(srv
->srvconf
.changeroot
->ptr
)) {
1406 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chroot failed: ", strerror(errno
));
1409 if (-1 == chdir("/")) {
1410 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chdir failed: ", strerror(errno
));
1416 /* drop root privs */
1418 if (-1 == setuid(pwd
->pw_uid
)) {
1419 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setuid failed: ", strerror(errno
));
1424 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1426 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1428 if (srv
->srvconf
.enable_cores
) {
1429 prctl(PR_SET_DUMPABLE
, 1, 0, 0, 0);
1435 if (srv
->srvconf
.max_conns
> srv
->max_fds
/2) {
1436 /* we can't have more connections than max-fds/2 */
1437 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", "can't have more connections than fds/2: ", srv
->srvconf
.max_conns
, srv
->max_fds
);
1438 srv
->max_conns
= srv
->max_fds
/2;
1439 } else if (srv
->srvconf
.max_conns
) {
1440 /* otherwise respect the wishes of the user */
1441 srv
->max_conns
= srv
->srvconf
.max_conns
;
1443 /* or use the default: we really don't want to hit max-fds */
1444 srv
->max_conns
= srv
->max_fds
/3;
1448 /* network is up, let's daemonize ourself */
1449 if (0 == srv
->srvconf
.dont_daemonize
&& 0 == graceful_restart
) {
1450 parent_pipe_fd
= daemonize();
1453 graceful_restart
= 0;/*(reset here after avoiding further daemonizing)*/
1454 if (0 == oneshot_fd
) graceful_shutdown
= 0;
1457 #ifdef HAVE_SIGACTION
1458 memset(&act
, 0, sizeof(act
));
1459 act
.sa_handler
= SIG_IGN
;
1460 sigaction(SIGPIPE
, &act
, NULL
);
1461 # if defined(SA_SIGINFO)
1462 last_sighup_info
.si_uid
= 0,
1463 last_sighup_info
.si_pid
= 0;
1464 last_sigterm_info
.si_uid
= 0,
1465 last_sigterm_info
.si_pid
= 0;
1466 act
.sa_sigaction
= sigaction_handler
;
1467 sigemptyset(&act
.sa_mask
);
1468 act
.sa_flags
= SA_SIGINFO
;
1470 act
.sa_handler
= signal_handler
;
1471 sigemptyset(&act
.sa_mask
);
1474 sigaction(SIGINT
, &act
, NULL
);
1475 sigaction(SIGTERM
, &act
, NULL
);
1476 sigaction(SIGHUP
, &act
, NULL
);
1477 sigaction(SIGALRM
, &act
, NULL
);
1478 sigaction(SIGUSR1
, &act
, NULL
);
1480 /* it should be safe to restart syscalls after SIGCHLD */
1481 act
.sa_flags
|= SA_RESTART
| SA_NOCLDSTOP
;
1482 sigaction(SIGCHLD
, &act
, NULL
);
1484 #elif defined(HAVE_SIGNAL)
1485 /* ignore the SIGPIPE from sendfile() */
1486 signal(SIGPIPE
, SIG_IGN
);
1487 signal(SIGALRM
, signal_handler
);
1488 signal(SIGTERM
, signal_handler
);
1489 signal(SIGHUP
, signal_handler
);
1490 signal(SIGCHLD
, signal_handler
);
1491 signal(SIGINT
, signal_handler
);
1492 signal(SIGUSR1
, signal_handler
);
1496 srv
->gid
= getgid();
1497 srv
->uid
= getuid();
1498 srv
->pid
= getpid();
1500 /* write pid file */
1502 buffer_copy_int(srv
->tmp_buf
, srv
->pid
);
1503 buffer_append_string_len(srv
->tmp_buf
, CONST_STR_LEN("\n"));
1504 if (-1 == write_all(pid_fd
, CONST_BUF_LEN(srv
->tmp_buf
))) {
1505 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't write pid file:", strerror(errno
));
1510 } else if (pid_fd
< -2) {
1514 /* Close stderr ASAP in the child process to make sure that nothing
1515 * is being written to that fd which may not be valid anymore. */
1516 if (!srv
->srvconf
.preflight_check
) {
1517 if (-1 == log_error_open(srv
)) {
1518 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Opening errorlog failed. Going down.");
1521 log_error_write(srv
, __FILE__
, __LINE__
, "s", "server started (" PACKAGE_DESC
")");
1524 if (buffer_is_empty(srv
->config_storage
[0]->server_tag
)) {
1525 buffer_copy_string_len(srv
->config_storage
[0]->server_tag
, CONST_STR_LEN(PACKAGE_DESC
));
1528 if (HANDLER_GO_ON
!= plugins_call_set_defaults(srv
)) {
1529 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Configuration of plugins failed. Going down.");
1533 /* settings might be enabled during module config set defaults */
1534 srv
->config_storage
[0]->high_precision_timestamps
= srv
->srvconf
.high_precision_timestamps
;
1536 /* dump unused config-keys */
1537 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1538 array
*config
= ((data_config
*)srv
->config_context
->data
[i
])->value
;
1541 for (j
= 0; config
&& j
< config
->used
; j
++) {
1542 data_unset
*du
= config
->data
[j
];
1544 /* all var.* is known as user defined variable */
1545 if (strncmp(du
->key
->ptr
, "var.", sizeof("var.") - 1) == 0) {
1549 if (NULL
== array_get_element_klen(srv
->config_touched
, CONST_BUF_LEN(du
->key
))) {
1550 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1551 "WARNING: unknown config-key:",
1558 if (srv
->config_unsupported
) {
1559 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1560 "Configuration contains unsupported keys. Going down.");
1563 if (srv
->config_deprecated
) {
1564 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1565 "Configuration contains deprecated keys. Going down.");
1568 if (srv
->config_unsupported
|| srv
->config_deprecated
) {
1572 if (srv
->srvconf
.preflight_check
) {
1573 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1580 * notify daemonize-grandparent of successful startup
1581 * do this before any further forking is done (workers)
1583 if (0 == srv
->srvconf
.dont_daemonize
&& -1 != parent_pipe_fd
) {
1584 if (0 > write(parent_pipe_fd
, "", 1)) return -1;
1585 close(parent_pipe_fd
);
1588 if (idle_limit
&& srv
->srvconf
.max_worker
) {
1589 srv
->srvconf
.max_worker
= 0;
1590 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1591 "server idle time limit command line option disables server.max-worker config file option.");
1594 /* start watcher and workers */
1595 num_childs
= srv
->srvconf
.max_worker
;
1596 if (num_childs
> 0) {
1597 pid_t pids
[num_childs
];
1599 const int npids
= num_childs
;
1601 unsigned int timer
= 0;
1602 for (int n
= 0; n
< npids
; ++n
) pids
[n
] = -1;
1603 while (!child
&& !srv_shutdown
&& !graceful_shutdown
) {
1604 if (num_childs
> 0) {
1605 switch ((pid
= fork())) {
1614 for (int n
= 0; n
< npids
; ++n
) {
1615 if (-1 == pids
[n
]) {
1625 if (-1 != (pid
= wait(&status
))) {
1626 srv
->cur_ts
= time(NULL
);
1627 if (plugins_call_handle_waitpid(srv
, pid
, status
) != HANDLER_GO_ON
) {
1628 if (!timer
) alarm((timer
= 5));
1631 switch (fdevent_reaped_logger_pipe(pid
)) {
1633 case -1: if (!timer
) alarm((timer
= 5));
1638 * check if one of our workers went away
1640 for (int n
= 0; n
< npids
; ++n
) {
1641 if (pid
== pids
[n
]) {
1650 srv
->cur_ts
= time(NULL
);
1652 * if we receive a SIGHUP we have to close our logs ourself as we don't
1653 * have the mainloop who can help us here
1655 if (handle_sig_hup
) {
1658 log_error_cycle(srv
);
1660 /* forward SIGHUP to workers */
1661 for (int n
= 0; n
< npids
; ++n
) {
1662 if (pids
[n
] > 0) kill(pids
[n
], SIGHUP
);
1665 if (handle_sig_alarm
) {
1666 handle_sig_alarm
= 0;
1668 plugins_call_handle_trigger(srv
);
1669 fdevent_restart_logger_pipes(srv
->cur_ts
);
1680 * for the parent this is the exit-point
1684 * kill all children too
1686 if (graceful_shutdown
|| graceful_restart
) {
1687 /* flag to ignore one SIGINT if graceful_restart */
1688 if (graceful_restart
) graceful_restart
= 2;
1690 server_graceful_state(srv
);
1691 } else if (srv_shutdown
) {
1698 /* ignore SIGUSR1 in workers; only parent directs graceful restart */
1699 #ifdef HAVE_SIGACTION
1701 struct sigaction actignore
;
1702 memset(&actignore
, 0, sizeof(actignore
));
1703 actignore
.sa_handler
= SIG_IGN
;
1704 sigaction(SIGUSR1
, &actignore
, NULL
);
1706 #elif defined(HAVE_SIGNAL)
1707 signal(SIGUSR1
, SIG_IGN
);
1711 * make sure workers do not muck with pid-file
1717 buffer_clear(srv
->srvconf
.pid_file
);
1719 fdevent_clr_logger_pipe_pids();
1720 srv
->pid
= getpid();
1725 if (NULL
== (srv
->ev
= fdevent_init(srv
))) {
1726 log_error_write(srv
, __FILE__
, __LINE__
,
1727 "s", "fdevent_init failed");
1731 srv
->max_fds_lowat
= srv
->max_fds
* 8 / 10;
1732 srv
->max_fds_hiwat
= srv
->max_fds
* 9 / 10;
1734 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1735 #ifdef HAVE_SIGACTION
1736 sigaction(SIGCHLD
, &act
, NULL
);
1737 #elif defined(HAVE_SIGNAL)
1738 signal(SIGCHLD
, signal_handler
);
1742 * kqueue() is called here, select resets its internals,
1743 * all server sockets get their handlers
1746 if (0 != network_register_fdevents(srv
)) {
1750 /* might fail if user is using fam (not gamin) and famd isn't running */
1751 if (NULL
== (srv
->stat_cache
= stat_cache_init(srv
))) {
1752 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1753 "stat-cache could not be setup, dieing.");
1759 /* setup periodic timer (1 second) */
1760 struct itimerval interval
;
1761 interval
.it_interval
.tv_sec
= 1;
1762 interval
.it_interval
.tv_usec
= 0;
1763 interval
.it_value
.tv_sec
= 1;
1764 interval
.it_value
.tv_usec
= 0;
1765 if (setitimer(ITIMER_REAL
, &interval
, NULL
)) {
1766 log_error_write(srv
, __FILE__
, __LINE__
, "s", "setting timer failed");
1773 /* get the current number of FDs */
1775 int fd
= fdevent_open_devnull();
1782 if (0 != server_sockets_set_nb_cloexec(srv
)) {
1786 /* plugin hook for worker_init */
1787 if (HANDLER_GO_ON
!= plugins_call_worker_init(srv
))
1790 if (oneshot_fd
&& server_oneshot_init(srv
, oneshot_fd
)) {
1798 __attribute_noinline__
1799 static int server_handle_sighup (server
* const srv
) {
1802 /* cycle logfiles */
1804 switch(r
= plugins_call_handle_sighup(srv
)) {
1808 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "sighup-handler return with an error", r
);
1812 if (-1 == log_error_cycle(srv
)) {
1813 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cycling errorlog failed, dying");
1817 #ifdef HAVE_SIGACTION
1818 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
1819 "logfiles cycled UID =",
1820 last_sighup_info
.si_uid
,
1822 last_sighup_info
.si_pid
);
1824 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1832 __attribute_noinline__
1833 static void server_handle_sigalrm (server
* const srv
, time_t min_ts
, time_t last_active_ts
) {
1834 connections
*conns
= srv
->conns
;
1837 switch(r
= plugins_call_handle_trigger(srv
)) {
1841 log_error_write(srv
, __FILE__
, __LINE__
, "s", "one of the triggers failed");
1844 log_error_write(srv
, __FILE__
, __LINE__
, "d", r
);
1848 srv
->cur_ts
= min_ts
;
1850 /* check idle time limit, if enabled */
1851 if (idle_limit
&& idle_limit
< min_ts
- last_active_ts
&& !graceful_shutdown
) {
1852 log_error_write(srv
, __FILE__
, __LINE__
, "sDs", "[note] idle timeout", (int)idle_limit
,
1853 "s exceeded, initiating graceful shutdown");
1854 graceful_shutdown
= 2; /* value 2 indicates idle timeout */
1855 if (graceful_restart
) {
1856 graceful_restart
= 0;
1857 if (pid_fd
< -2) pid_fd
= -pid_fd
;
1858 server_sockets_close(srv
);
1862 #ifdef HAVE_GETLOADAVG
1863 /* refresh loadavg data every 30 seconds */
1864 if (srv
->srvconf
.loadts
+ 30 < min_ts
) {
1865 if (-1 != getloadavg(srv
->srvconf
.loadavg
, 3)) {
1866 srv
->srvconf
.loadts
= min_ts
;
1871 /* free excess chunkqueue buffers every 64 seconds */
1872 if (0 == (min_ts
& 0x3f)) chunkqueue_chunk_pool_clear();
1873 /* cleanup stat-cache */
1874 stat_cache_trigger_cleanup(srv
);
1875 /* reset global/aggregate rate limit counters */
1876 for (size_t i
= 0; i
< srv
->config_context
->used
; ++i
) {
1877 srv
->config_storage
[i
]->global_bytes_per_second_cnt
= 0;
1879 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1880 if (graceful_shutdown
&& !srv_shutdown
) server_graceful_shutdown_maint(srv
);
1882 * check all connections for timeouts
1885 for (size_t ndx
= 0; ndx
< conns
->used
; ++ndx
) {
1886 connection
* const con
= conns
->ptr
[ndx
];
1887 const int waitevents
= fdevent_fdnode_interest(con
->fdn
);
1891 if (con
->state
== CON_STATE_CLOSE
) {
1892 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
) {
1895 } else if (waitevents
& FDEVENT_IN
) {
1896 if (con
->request_count
== 1 || con
->state
!= CON_STATE_READ
) { /* e.g. CON_STATE_READ_POST || CON_STATE_WRITE */
1897 if (srv
->cur_ts
- con
->read_idle_ts
> con
->conf
.max_read_idle
) {
1899 if (con
->conf
.log_request_handling
) {
1900 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1901 "connection closed - read timeout:", con
->fd
);
1904 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1908 if (srv
->cur_ts
- con
->read_idle_ts
> con
->keep_alive_idle
) {
1910 if (con
->conf
.log_request_handling
) {
1911 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1912 "connection closed - keep-alive timeout:", con
->fd
);
1915 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1921 /* max_write_idle timeout currently functions as backend timeout,
1922 * too, after response has been started.
1923 * future: have separate backend timeout, and then change this
1924 * to check for write interest before checking for timeout */
1925 /*if (waitevents & FDEVENT_OUT)*/
1926 if ((con
->state
== CON_STATE_WRITE
) &&
1927 (con
->write_request_ts
!= 0)) {
1929 if (srv
->cur_ts
- con
->write_request_ts
> 60) {
1930 log_error_write(srv
, __FILE__
, __LINE__
, "sdd",
1931 "connection closed - pre-write-request-timeout:", con
->fd
, srv
->cur_ts
- con
->write_request_ts
);
1935 if (srv
->cur_ts
- con
->write_request_ts
> con
->conf
.max_write_idle
) {
1937 if (con
->conf
.log_timeouts
) {
1938 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsosds",
1939 "NOTE: a request from",
1943 "timed out after writing",
1946 (int)con
->conf
.max_write_idle
,
1947 "seconds. If this a problem increase server.max-write-idle");
1949 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1954 /* we don't like div by zero */
1955 if (0 == (t_diff
= srv
->cur_ts
- con
->connection_start
)) t_diff
= 1;
1957 if (con
->traffic_limit_reached
&&
1958 (con
->conf
.kbytes_per_second
== 0 ||
1959 ((con
->bytes_written
/ t_diff
) < con
->conf
.kbytes_per_second
* 1024))) {
1960 /* enable connection again */
1961 con
->traffic_limit_reached
= 0;
1966 con
->bytes_written_cur_second
= 0;
1969 connection_state_machine(srv
, con
);
1974 __attribute_noinline__
1975 static void server_handle_sigchld (server
* const srv
) {
1979 pid
= waitpid(-1, &status
, WNOHANG
);
1981 if (plugins_call_handle_waitpid(srv
, pid
, status
) != HANDLER_GO_ON
) {
1984 if (0 == srv
->srvconf
.max_worker
) {
1985 /* check piped-loggers and restart, even if shutting down */
1986 if (fdevent_waitpid_logger_pipe_pid(pid
, srv
->cur_ts
)) {
1991 } while (pid
> 0 || (-1 == pid
&& errno
== EINTR
));
1995 __attribute_noinline__
1996 static int server_main_loop (server
* const srv
) {
1997 connections
* const joblist
= srv
->joblist
;
1998 time_t last_active_ts
= time(NULL
);
2000 while (!srv_shutdown
) {
2002 if (handle_sig_hup
) {
2004 if (server_handle_sighup(srv
)) return -1;
2007 if (handle_sig_alarm
) {
2008 time_t min_ts
= time(NULL
);
2010 handle_sig_alarm
= 0;
2012 if (min_ts
!= srv
->cur_ts
) {
2013 server_handle_sigalrm(srv
, min_ts
, last_active_ts
);
2017 if (handle_sig_child
) {
2018 handle_sig_child
= 0;
2019 server_handle_sigchld(srv
);
2022 if (graceful_shutdown
) {
2023 server_graceful_state(srv
);
2024 if (srv
->conns
->used
== 0) {
2025 /* we are in graceful shutdown phase and all connections are closed
2026 * we are ready to terminate without harming anyone */
2030 } else if (srv
->sockets_disabled
) {
2031 server_overload_check(srv
);
2033 server_load_check(srv
);
2036 if (srv
->want_fds
) {
2037 server_process_want_fds(srv
);
2040 if (fdevent_poll(srv
->ev
, 1000) > 0) {
2041 last_active_ts
= srv
->cur_ts
;
2044 for (size_t ndx
= 0; ndx
< joblist
->used
; ++ndx
) {
2045 connection
*con
= joblist
->ptr
[ndx
];
2046 connection_state_machine(srv
, con
);
2055 int main (int argc
, char **argv
) {
2059 #ifndef HAVE_ISSETUGID
2060 #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2062 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2064 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2069 /* for nice %b handling in strftime() */
2070 setlocale(LC_TIME
, "C");
2073 server
* const srv
= server_init();
2075 if (graceful_restart
) {
2076 server_sockets_restore(srv
);
2080 rc
= server_main(srv
, argc
, argv
);
2081 if (rc
> 0 && 0 == (rc
= server_main_loop(srv
))) {
2082 if (graceful_shutdown
|| graceful_restart
) {
2083 server_graceful_state(srv
);
2086 if (2 == graceful_shutdown
) { /* value 2 indicates idle timeout */
2087 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2088 "server stopped after idle timeout");
2090 #ifdef HAVE_SIGACTION
2091 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2092 "server stopped by UID =",
2093 last_sigterm_info
.si_uid
,
2095 last_sigterm_info
.si_pid
);
2097 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2104 remove_pid_file(srv
);
2105 log_error_close(srv
);
2106 fdevent_close_logger_pipes();
2107 if (graceful_restart
)
2108 server_sockets_save(srv
);
2111 connections_free(srv
);
2115 if (0 != rc
|| !graceful_restart
) break;
2117 /* wait for all children to exit before graceful restart */
2118 while (waitpid(-1, NULL
, 0) > 0) ;
2119 } while (graceful_restart
);