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
);
238 CLEAN(response_range
);
240 srv
->empty_string
= buffer_init_string("");
241 CLEAN(cond_check_buf
);
243 CLEAN(srvconf
.errorlog_file
);
244 CLEAN(srvconf
.breakagelog_file
);
245 CLEAN(srvconf
.groupname
);
246 CLEAN(srvconf
.username
);
247 CLEAN(srvconf
.changeroot
);
248 CLEAN(srvconf
.bindhost
);
249 CLEAN(srvconf
.event_handler
);
250 CLEAN(srvconf
.pid_file
);
251 CLEAN(srvconf
.syslog_facility
);
253 CLEAN(tmp_chunk_len
);
257 srv->x = array_init();
259 CLEAN(config_context
);
260 CLEAN(config_touched
);
264 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
265 srv
->mtime_cache
[i
].mtime
= (time_t)-1;
266 srv
->mtime_cache
[i
].str
= buffer_init();
271 srv
->cur_ts
= time(NULL
);
272 srv
->startup_ts
= srv
->cur_ts
;
274 srv
->conns
= calloc(1, sizeof(*srv
->conns
));
275 force_assert(srv
->conns
);
277 srv
->joblist
= calloc(1, sizeof(*srv
->joblist
));
278 force_assert(srv
->joblist
);
280 srv
->fdwaitqueue
= calloc(1, sizeof(*srv
->fdwaitqueue
));
281 force_assert(srv
->fdwaitqueue
);
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;
293 srv
->srvconf
.http_url_normalize
= HTTP_PARSEOPT_URL_NORMALIZE
294 | HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED
295 | HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT
296 | HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS
297 | HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
298 | HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE
;
300 srv
->srvconf
.http_url_normalize
= 0; /* temporary; change in future */
301 srv
->srvconf
.high_precision_timestamps
= 0;
302 srv
->srvconf
.max_request_field_size
= 8192;
303 srv
->srvconf
.loadavg
[0] = 0.0;
304 srv
->srvconf
.loadavg
[1] = 0.0;
305 srv
->srvconf
.loadavg
[2] = 0.0;
306 srv
->srvconf
.compat_module_load
= 1;
307 srv
->srvconf
.systemd_socket_activation
= 0;
310 srv
->errorlog_fd
= STDERR_FILENO
;
311 srv
->errorlog_mode
= ERRORLOG_FD
;
313 srv
->split_vals
= array_init();
314 srv
->request_env
= plugins_call_handle_request_env
;
320 static void server_free(server
*srv
) {
323 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
324 buffer_free(srv
->mtime_cache
[i
].str
);
327 if (oneshot_fd
> 0) {
334 CLEAN(response_header
);
335 CLEAN(parse_full_path
);
339 CLEAN(response_range
);
342 CLEAN(cond_check_buf
);
344 CLEAN(srvconf
.errorlog_file
);
345 CLEAN(srvconf
.breakagelog_file
);
346 CLEAN(srvconf
.groupname
);
347 CLEAN(srvconf
.username
);
348 CLEAN(srvconf
.changeroot
);
349 CLEAN(srvconf
.bindhost
);
350 CLEAN(srvconf
.event_handler
);
351 CLEAN(srvconf
.pid_file
);
352 CLEAN(srvconf
.modules_dir
);
353 CLEAN(srvconf
.network_backend
);
354 CLEAN(srvconf
.xattr_name
);
355 CLEAN(srvconf
.syslog_facility
);
357 CLEAN(tmp_chunk_len
);
361 fdevent_unregister(srv
->ev
, srv
->fd
);
363 fdevent_free(srv
->ev
);
367 if (srv
->config_storage
) {
368 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
369 specific_config
*s
= srv
->config_storage
[i
];
373 buffer_free(s
->document_root
);
374 buffer_free(s
->server_name
);
375 buffer_free(s
->server_tag
);
376 buffer_free(s
->error_handler
);
377 buffer_free(s
->error_handler_404
);
378 buffer_free(s
->errorfile_prefix
);
379 buffer_free(s
->socket_perms
);
380 array_free(s
->mimetypes
);
383 free(srv
->config_storage
);
384 srv
->config_storage
= NULL
;
390 CLEAN(config_context
);
391 CLEAN(config_touched
);
393 CLEAN(srvconf
.upload_tempdirs
);
396 joblist_free(srv
, srv
->joblist
);
397 fdwaitqueue_free(srv
, srv
->fdwaitqueue
);
399 if (srv
->stat_cache
) {
400 stat_cache_free(srv
->stat_cache
);
403 array_free(srv
->srvconf
.modules
);
404 array_free(srv
->split_vals
);
407 chunkqueue_chunk_pool_free();
413 static void remove_pid_file(server
*srv
) {
414 if (pid_fd
<= -2) return;
415 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) && 0 <= pid_fd
) {
416 if (0 != ftruncate(pid_fd
, 0)) {
417 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
418 "ftruncate failed for:",
419 srv
->srvconf
.pid_file
,
428 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) &&
429 buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
430 if (0 != unlink(srv
->srvconf
.pid_file
->ptr
)) {
431 if (errno
!= EACCES
&& errno
!= EPERM
) {
432 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
433 "unlink failed for:",
434 srv
->srvconf
.pid_file
,
444 static server_socket
* server_oneshot_getsock(server
*srv
, sock_addr
*cnt_addr
) {
445 server_socket
*srv_socket
, *srv_socket_wild
= NULL
;
447 for (i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
448 srv_socket
= srv
->srv_sockets
.ptr
[i
];
449 if (!sock_addr_is_port_eq(&srv_socket
->addr
,cnt_addr
)) continue;
450 if (sock_addr_is_addr_eq(&srv_socket
->addr
,cnt_addr
)) return srv_socket
;
452 if (NULL
!= srv_socket_wild
) continue;
453 if (sock_addr_is_addr_wildcard(&srv_socket
->addr
)) {
454 srv_socket_wild
= srv_socket
;
458 if (NULL
!= srv_socket_wild
) {
459 return srv_socket_wild
;
460 } else if (srv
->srv_sockets
.used
) {
461 return srv
->srv_sockets
.ptr
[0];
463 log_error_write(srv
, __FILE__
, __LINE__
, "s", "no sockets configured");
470 static int server_oneshot_init(server
*srv
, int fd
) {
471 /* Note: does not work with netcat due to requirement that fd be socket.
472 * STDOUT_FILENO was not saved earlier in startup, and that is to where
473 * netcat expects output to be sent. Since lighttpd expects connections
474 * to be sockets, con->fd is where output is sent; separate fds are not
475 * stored for input and output, but netcat has different fds for stdin
476 * and * stdout. To support netcat, would additionally need to avoid
477 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
478 * addresses from environment variables:
479 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
480 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
484 server_socket
*srv_socket
;
489 if (0 != fstat(fd
, &st
)) {
490 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fstat:", strerror(errno
));
494 if (!S_ISSOCK(st
.st_mode
)) {
495 /* require that fd is a socket
496 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
497 log_error_write(srv
, __FILE__
, __LINE__
, "s", "lighttpd -1 stdin is not a socket");
501 cnt_len
= sizeof(cnt_addr
);
502 if (0 != getsockname(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
503 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getsockname:", strerror(errno
));
507 srv_socket
= server_oneshot_getsock(srv
, &cnt_addr
);
508 if (NULL
== srv_socket
) return 0;
510 cnt_len
= sizeof(cnt_addr
);
511 if (0 != getpeername(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
512 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getpeername:", strerror(errno
));
516 /*(must set flags; fd did not pass through fdevent accept() logic)*/
517 if (-1 == fdevent_fcntl_set_nb_cloexec(srv
->ev
, fd
)) {
518 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl:", strerror(errno
));
522 if (sock_addr_get_family(&cnt_addr
) != AF_UNIX
) {
523 network_accept_tcp_nagle_disable(fd
);
526 con
= connection_accepted(srv
, srv_socket
, &cnt_addr
, fd
);
527 if (NULL
== con
) return 0;
529 connection_state_machine(srv
, con
);
535 static void show_version (void) {
536 char *b
= PACKAGE_DESC TEXT_SSL \
537 " - a light and fast webserver\n"
538 #ifdef NONREPRODUCIBLE_BUILD
539 "Build-Date: " __DATE__
" " __TIME__
"\n";
542 write_all(STDOUT_FILENO
, b
, strlen(b
));
546 static void show_features (void) {
547 static const char features
[] =
554 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
559 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
560 "\t+ bzip2 support\n"
562 "\t- bzip2 support\n"
564 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
565 "\t+ crypt support\n"
567 "\t- crypt support\n"
580 "\t+ MySQL support\n"
582 "\t- MySQL support\n"
585 "\t+ PgSQL support\n"
587 "\t- PgSQL support\n"
595 "\t+ Kerberos support\n"
597 "\t- Kerberos support\n"
599 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
610 "\t+ memcached support\n"
612 "\t- memcached support\n"
629 #ifdef HAVE_SQLITE3_H
630 "\t+ SQLite support\n"
632 "\t- SQLite support\n"
641 printf("%s%s%s\n", fdevent_show_event_handlers(), network_write_show_handlers(), features
);
645 static void show_help (void) {
646 char *b
= PACKAGE_DESC TEXT_SSL
647 #ifdef NONREPRODUCIBLE_BUILD
648 " ("__DATE__
" " __TIME__
")"
650 " - a light and fast webserver\n" \
652 " -f <name> filename of the config-file\n" \
653 " -m <name> module directory (default: "LIBRARY_DIR
")\n" \
654 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
655 " -1 process single (one) request on stdin socket, then exit\n" \
656 " -p print the parsed config-file in internal form, and exit\n" \
657 " -t test config-file syntax, then exit\n" \
658 " -tt test config-file syntax, load and init modules, then exit\n" \
659 " -D don't go to background (default: go to background)\n" \
660 " -v show version\n" \
661 " -V show compile-time features\n" \
662 " -h show this help\n" \
665 write_all(STDOUT_FILENO
, b
, strlen(b
));
671 * we have 4 possibilities:
679 static int log_error_open(server
*srv
) {
682 /* perhaps someone wants to use syslog() */
684 if (!buffer_string_is_empty(srv
->srvconf
.syslog_facility
)) {
685 static const struct facility_name_st
{
688 } facility_names
[] = {
691 ,{ "authpriv", LOG_AUTHPRIV
}
694 ,{ "cron", LOG_CRON
}
696 ,{ "daemon", LOG_DAEMON
}
701 ,{ "kern", LOG_KERN
}
707 ,{ "mail", LOG_MAIL
}
710 ,{ "news", LOG_NEWS
}
712 ,{ "security", LOG_AUTH
} /* DEPRECATED */
714 ,{ "syslog", LOG_SYSLOG
}
717 ,{ "user", LOG_USER
}
720 ,{ "uucp", LOG_UUCP
}
722 ,{ "local0", LOG_LOCAL0
}
723 ,{ "local1", LOG_LOCAL1
}
724 ,{ "local2", LOG_LOCAL2
}
725 ,{ "local3", LOG_LOCAL3
}
726 ,{ "local4", LOG_LOCAL4
}
727 ,{ "local5", LOG_LOCAL5
}
728 ,{ "local6", LOG_LOCAL6
}
729 ,{ "local7", LOG_LOCAL7
}
732 for (i
= 0; i
< sizeof(facility_names
)/sizeof(facility_names
[0]); ++i
) {
733 const struct facility_name_st
*f
= facility_names
+i
;
734 if (0 == strcmp(srv
->srvconf
.syslog_facility
->ptr
, f
->name
)) {
739 if (-1 == facility
) {
740 log_error_write(srv
, __FILE__
, __LINE__
, "SBS",
741 "unrecognized server.syslog-facility: \"",
742 srv
->srvconf
.syslog_facility
,
743 "\"; defaulting to \"daemon\" facility");
746 openlog("lighttpd", LOG_CONS
|LOG_PID
, -1==facility
? LOG_DAEMON
: facility
);
749 srv
->errorlog_mode
= ERRORLOG_FD
;
750 srv
->errorlog_fd
= STDERR_FILENO
;
752 if (srv
->srvconf
.errorlog_use_syslog
) {
753 srv
->errorlog_mode
= ERRORLOG_SYSLOG
;
755 else if (!buffer_string_is_empty(srv
->srvconf
.errorlog_file
)) {
756 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
757 int fd
= fdevent_open_logger(logfile
);
759 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
760 "opening errorlog '", logfile
,
761 "' failed: ", strerror(errno
));
764 srv
->errorlog_fd
= fd
;
765 srv
->errorlog_mode
= logfile
[0] == '|' ? ERRORLOG_PIPE
: ERRORLOG_FILE
;
768 if (srv
->errorlog_mode
== ERRORLOG_FD
&& !srv
->srvconf
.dont_daemonize
) {
769 /* We can only log to stderr in dont-daemonize mode;
770 * if we do daemonize and no errorlog file is specified,
771 * we log into /dev/null
773 srv
->errorlog_fd
= -1;
776 if (!buffer_string_is_empty(srv
->srvconf
.breakagelog_file
)) {
777 const char *logfile
= srv
->srvconf
.breakagelog_file
->ptr
;
779 if (srv
->errorlog_mode
== ERRORLOG_FD
) {
780 srv
->errorlog_fd
= dup(STDERR_FILENO
);
781 fdevent_setfd_cloexec(srv
->errorlog_fd
);
784 if (-1 == (errfd
= fdevent_open_logger(logfile
))) {
785 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
786 "opening errorlog '", logfile
,
787 "' failed: ", strerror(errno
));
791 if (*logfile
== '|') fdevent_breakagelog_logger_pipe(errfd
);
793 else if (!srv
->srvconf
.dont_daemonize
) {
794 /* move STDERR_FILENO to /dev/null */
795 if (-1 == (errfd
= fdevent_open_devnull())) {
796 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
797 "opening /dev/null failed:", strerror(errno
));
802 /*(leave STDERR_FILENO as-is)*/
806 if (0 != fdevent_set_stdin_stdout_stderr(-1, -1, errfd
)) {
807 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
808 "setting stderr failed:", strerror(errno
));
810 if (-1 != errfd
) close(errfd
);
815 if (-1 != errfd
) close(errfd
);
826 static int log_error_cycle(server
*srv
) {
827 /* cycle only if the error log is a file */
829 if (srv
->errorlog_mode
== ERRORLOG_FILE
) {
830 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
831 if (-1 == fdevent_cycle_logger(logfile
, &srv
->errorlog_fd
)) {
832 /* write to old log */
833 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
834 "cycling errorlog '", logfile
,
835 "' failed: ", strerror(errno
));
843 static int log_error_close(server
*srv
) {
844 switch(srv
->errorlog_mode
) {
848 if (-1 != srv
->errorlog_fd
) {
849 /* don't close STDERR */
850 /* fdevent_close_logger_pipes() closes ERRORLOG_PIPE */
851 if (STDERR_FILENO
!= srv
->errorlog_fd
852 && srv
->errorlog_mode
!= ERRORLOG_PIPE
) {
853 close(srv
->errorlog_fd
);
855 srv
->errorlog_fd
= -1;
858 case ERRORLOG_SYSLOG
:
869 static void server_sockets_save (server
*srv
) { /* graceful_restart */
870 memcpy(&graceful_sockets
, &srv
->srv_sockets
, sizeof(server_socket_array
));
871 memset(&srv
->srv_sockets
, 0, sizeof(server_socket_array
));
872 memcpy(&inherited_sockets
, &srv
->srv_sockets_inherited
, sizeof(server_socket_array
));
873 memset(&srv
->srv_sockets_inherited
, 0, sizeof(server_socket_array
));
877 static void server_sockets_restore (server
*srv
) { /* graceful_restart */
878 memcpy(&srv
->srv_sockets
, &graceful_sockets
, sizeof(server_socket_array
));
879 memset(&graceful_sockets
, 0, sizeof(server_socket_array
));
880 memcpy(&srv
->srv_sockets_inherited
, &inherited_sockets
, sizeof(server_socket_array
));
881 memset(&inherited_sockets
, 0, sizeof(server_socket_array
));
885 static int server_sockets_set_nb_cloexec (server
*srv
) {
886 if (srv
->sockets_disabled
) return 0; /* lighttpd -1 (one-shot mode) */
887 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
888 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
889 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv
->ev
, srv_socket
->fd
)) {
890 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
891 "fcntl failed:", strerror(errno
));
899 static void server_sockets_set_event (server
*srv
, int event
) {
900 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
901 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
902 fdevent_event_set(srv
->ev
, srv_socket
->fd
, event
);
907 static void server_sockets_unregister (server
*srv
) {
908 if (2 == srv
->sockets_disabled
) return;
909 srv
->sockets_disabled
= 2;
910 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
)
911 network_unregister_sock(srv
, srv
->srv_sockets
.ptr
[i
]);
915 static void server_sockets_close (server
*srv
) {
916 /* closing socket right away will make it possible for the next lighttpd
917 * to take over (old-style graceful restart), but only if backends
918 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
919 * than started by lighttpd via "bin-path")
921 if (3 == srv
->sockets_disabled
) return;
922 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
923 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
924 if (-1 == srv_socket
->fd
) continue;
925 if (2 != srv
->sockets_disabled
) network_unregister_sock(srv
,srv_socket
);
926 close(srv_socket
->fd
);
928 /* network_close() will cleanup after us */
930 srv
->sockets_disabled
= 3;
934 static void server_graceful_shutdown_maint (server
*srv
) {
935 connections
*conns
= srv
->conns
;
936 for (size_t ndx
= 0; ndx
< conns
->used
; ++ndx
) {
937 connection
* const con
= conns
->ptr
[ndx
];
940 if (con
->state
== CON_STATE_CLOSE
) {
941 /* reduce remaining linger timeout to be
942 * (from zero) *up to* one more second, but no more */
943 if (HTTP_LINGER_TIMEOUT
> 1)
944 con
->close_timeout_ts
-= (HTTP_LINGER_TIMEOUT
- 1);
945 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
)
948 else if (con
->state
== CON_STATE_READ
&& con
->request_count
> 1
949 && chunkqueue_is_empty(con
->read_queue
)) {
950 /* close connections in keep-alive waiting for next request */
951 connection_set_state(srv
, con
, CON_STATE_ERROR
);
955 con
->keep_alive
= 0; /* disable keep-alive */
957 con
->conf
.kbytes_per_second
= 0; /* disable rate limit */
958 con
->conf
.global_kbytes_per_second
= 0; /* disable rate limit */
959 if (con
->traffic_limit_reached
) {
960 con
->traffic_limit_reached
= 0;
965 connection_state_machine(srv
, con
);
971 static void server_graceful_state (server
*srv
) {
973 if (!srv_shutdown
) server_graceful_shutdown_maint(srv
);
976 && (2 == srv
->sockets_disabled
|| 3 == srv
->sockets_disabled
)) return;
978 log_error_write(srv
, __FILE__
, __LINE__
, "s",
979 "[note] graceful shutdown started");
981 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
982 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)
983 || oneshot_fd
|| 2 == graceful_shutdown
)
984 graceful_restart
= 0;
986 if (graceful_restart
) {
987 server_sockets_unregister(srv
);
988 if (pid_fd
> 0) pid_fd
= -pid_fd
; /*(flag to skip removing pid file)*/
991 server_sockets_close(srv
);
992 remove_pid_file(srv
);
993 buffer_clear(srv
->srvconf
.pid_file
); /*(prevent more removal attempts)*/
998 static int server_main (server
* const srv
, int argc
, char **argv
) {
999 int print_config
= 0;
1000 int test_config
= 0;
1007 #ifdef HAVE_SIGACTION
1008 struct sigaction act
;
1012 int parent_pipe_fd
= -1;
1017 i_am_root
= (0 == getuid());
1020 /* initialize globals (including file-scoped static globals) */
1023 graceful_shutdown
= 0;
1024 handle_sig_alarm
= 1;
1027 chunkqueue_set_tempdirs_default_reset();
1028 http_auth_dumbdata_reset();
1029 http_vhostdb_dumbdata_reset();
1030 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1031 /*(intentionally preserved)*/
1032 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1033 /*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/
1036 srv
->srvconf
.port
= 0;
1037 srv
->srvconf
.dont_daemonize
= 0;
1038 srv
->srvconf
.preflight_check
= 0;
1040 while(-1 != (o
= getopt(argc
, argv
, "f:m:i:hvVD1pt"))) {
1043 if (srv
->config_storage
) {
1044 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1045 "Can only read one config file. Use the include command to use multiple config files.");
1048 if (config_read(srv
, optarg
)) {
1053 buffer_copy_string(srv
->srvconf
.modules_dir
, optarg
);
1057 long timeout
= strtol(optarg
, &endptr
, 0);
1058 if (!*optarg
|| *endptr
|| timeout
< 0) {
1059 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1060 "Invalid idle timeout value:", optarg
);
1063 idle_limit
= (time_t)timeout
;
1066 case 'p': print_config
= 1; break;
1067 case 't': ++test_config
; break;
1068 case '1': if (0 == oneshot_fd
) oneshot_fd
= dup(STDIN_FILENO
);
1070 case 'D': srv
->srvconf
.dont_daemonize
= 1; break;
1071 case 'v': show_version(); return 0;
1072 case 'V': show_features(); return 0;
1073 case 'h': show_help(); return 0;
1081 if (!srv
->config_storage
&& NULL
!= getenv("NSSM_SERVICE_NAME")) {
1082 char *dir
= getenv("NSSM_SERVICE_DIR");
1083 if (NULL
!= dir
&& 0 != chdir(dir
)) {
1084 log_error_write(srv
, __FILE__
, __LINE__
, "sss", "chdir failed:", dir
, strerror(errno
));
1087 srv
->srvconf
.dont_daemonize
= 1;
1088 buffer_copy_string_len(srv
->srvconf
.modules_dir
, CONST_STR_LEN("modules"));
1089 if (config_read(srv
, "conf/lighttpd.conf")) return -1;
1093 if (!srv
->config_storage
) {
1094 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1095 "No configuration available. Try using -f option.");
1100 data_unset
*dc
= srv
->config_context
->data
[0];
1102 dc
->fn
->print(dc
, 0);
1103 fprintf(stdout
, "\n");
1105 /* shouldn't happend */
1106 fprintf(stderr
, "global config not found\n");
1111 buffer_clear(srv
->srvconf
.pid_file
);
1112 if (1 == test_config
) {
1113 printf("Syntax OK\n");
1114 } else { /*(test_config > 1)*/
1116 srv
->srvconf
.preflight_check
= 1;
1117 srv
->srvconf
.dont_daemonize
= 1;
1121 if (test_config
|| print_config
) {
1126 if (oneshot_fd
<= STDERR_FILENO
) {
1127 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1128 "Invalid fds at startup with lighttpd -1");
1131 graceful_shutdown
= 1;
1132 srv
->sockets_disabled
= 1;
1133 srv
->srvconf
.dont_daemonize
= 1;
1134 buffer_clear(srv
->srvconf
.pid_file
);
1135 if (srv
->srvconf
.max_worker
) {
1136 srv
->srvconf
.max_worker
= 0;
1137 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1138 "server one-shot command line option disables server.max-worker config file option.");
1142 if (buffer_is_equal_string(srv
->srvconf
.bindhost
, CONST_STR_LEN("/dev/stdin"))) {
1143 stdin_fd
= dup(STDIN_FILENO
);
1144 if (stdin_fd
<= STDERR_FILENO
) {
1145 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1146 "Invalid fds at startup");
1151 /* close stdin and stdout, as they are not needed */
1157 /* coverity[overwrite_var : FALSE] */
1158 devnull
= fdevent_open_devnull();
1160 __coverity_escape__(devnull
);
1162 } while (-1 != devnull
&& devnull
<= STDERR_FILENO
);
1163 if (-1 == devnull
) {
1164 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1165 "opening /dev/null failed:", strerror(errno
));
1168 errfd
= (0 == fstat(STDERR_FILENO
, &st
)) ? -1 : devnull
;
1169 if (0 != fdevent_set_stdin_stdout_stderr(devnull
, devnull
, errfd
)) {
1170 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1171 "setting default fds failed:", strerror(errno
));
1173 if (-1 != errfd
) close(errfd
);
1174 if (devnull
!= errfd
) close(devnull
);
1179 if (-1 != errfd
) close(errfd
);
1180 if (devnull
!= errfd
) close(devnull
);
1184 if (0 != config_set_defaults(srv
)) {
1185 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1186 "setting default values failed");
1190 /* check document-root */
1191 if (buffer_string_is_empty(srv
->config_storage
[0]->document_root
)) {
1192 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1193 "document-root is not set\n");
1197 if (plugins_load(srv
)) {
1198 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1199 "loading plugins finally failed");
1203 if (HANDLER_GO_ON
!= plugins_call_init(srv
)) {
1204 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Initialization of plugins failed. Going down.");
1208 /* mod_indexfile should be listed in server.modules prior to dynamic handlers */
1210 for (buffer
*pname
= NULL
; i
< srv
->plugins
.used
; ++i
) {
1211 plugin
*p
= ((plugin
**)srv
->plugins
.ptr
)[i
];
1212 if (buffer_is_equal_string(p
->name
, CONST_STR_LEN("indexfile"))) {
1214 log_error_write(srv
, __FILE__
, __LINE__
, "SB",
1215 "Warning: mod_indexfile should be listed in server.modules prior to mod_", pname
);
1219 if (p
->handle_subrequest_start
&& p
->handle_subrequest
) {
1220 if (!pname
) pname
= p
->name
;
1224 /* open pid file BEFORE chroot */
1225 if (-2 == pid_fd
) pid_fd
= -1; /*(initial startup state)*/
1226 if (-1 == pid_fd
&& !buffer_string_is_empty(srv
->srvconf
.pid_file
)) {
1227 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
))) {
1229 if (errno
!= EEXIST
) {
1230 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1231 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1235 if (0 != stat(srv
->srvconf
.pid_file
->ptr
, &st
)) {
1236 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1237 "stating existing pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1240 if (!S_ISREG(st
.st_mode
)) {
1241 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1242 "pid-file exists and isn't regular file:", srv
->srvconf
.pid_file
);
1246 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
))) {
1247 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1248 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1255 #ifdef HAVE_GETRLIMIT
1258 #ifdef HAVE_VALGRIND_VALGRIND_H
1259 if (RUNNING_ON_VALGRIND
) use_rlimit
= 0;
1262 if (0 != getrlimit(RLIMIT_NOFILE
, &rlim
)) {
1263 log_error_write(srv
, __FILE__
, __LINE__
,
1264 "ss", "couldn't get 'max filedescriptors'",
1270 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1272 if (use_rlimit
&& srv
->srvconf
.max_fds
1273 && (i_am_root
|| srv
->srvconf
.max_fds
<= rlim
.rlim_max
)) {
1276 rlim
.rlim_cur
= srv
->srvconf
.max_fds
;
1277 if (i_am_root
) rlim
.rlim_max
= srv
->srvconf
.max_fds
;
1279 if (0 != setrlimit(RLIMIT_NOFILE
, &rlim
)) {
1280 log_error_write(srv
, __FILE__
, __LINE__
,
1281 "ss", "couldn't set 'max filedescriptors'",
1287 srv
->max_fds
= rlim
.rlim_cur
;
1288 /*(default upper limit of 4k if server.max-fds not specified)*/
1289 if (i_am_root
&& 0 == srv
->srvconf
.max_fds
&& rlim
.rlim_cur
> 4096)
1290 srv
->max_fds
= 4096;
1292 /* set core file rlimit, if enable_cores is set */
1293 if (use_rlimit
&& srv
->srvconf
.enable_cores
&& getrlimit(RLIMIT_CORE
, &rlim
) == 0) {
1294 rlim
.rlim_cur
= rlim
.rlim_max
;
1295 setrlimit(RLIMIT_CORE
, &rlim
);
1300 /* we need root-perms for port < 1024 */
1301 if (0 != network_init(srv
, stdin_fd
)) {
1307 /* set user and group */
1308 struct group
*grp
= NULL
;
1309 struct passwd
*pwd
= NULL
;
1311 if (!buffer_string_is_empty(srv
->srvconf
.groupname
)) {
1312 if (NULL
== (grp
= getgrnam(srv
->srvconf
.groupname
->ptr
))) {
1313 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1314 "can't find groupname", srv
->srvconf
.groupname
);
1319 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1320 if (NULL
== (pwd
= getpwnam(srv
->srvconf
.username
->ptr
))) {
1321 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1322 "can't find username", srv
->srvconf
.username
);
1326 if (pwd
->pw_uid
== 0) {
1327 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1328 "I will not set uid to 0\n");
1332 if (NULL
== grp
&& NULL
== (grp
= getgrgid(pwd
->pw_gid
))) {
1333 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1334 "can't find group id", pwd
->pw_gid
);
1340 if (grp
->gr_gid
== 0) {
1341 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1342 "I will not set gid to 0\n");
1348 * Change group before chroot, when we have access
1352 if (-1 == setgid(grp
->gr_gid
)) {
1353 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgid failed: ", strerror(errno
));
1356 if (-1 == setgroups(0, NULL
)) {
1357 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgroups failed: ", strerror(errno
));
1360 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1361 initgroups(srv
->srvconf
.username
->ptr
, grp
->gr_gid
);
1366 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
1369 if (-1 == chroot(srv
->srvconf
.changeroot
->ptr
)) {
1370 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chroot failed: ", strerror(errno
));
1373 if (-1 == chdir("/")) {
1374 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chdir failed: ", strerror(errno
));
1380 /* drop root privs */
1382 if (-1 == setuid(pwd
->pw_uid
)) {
1383 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setuid failed: ", strerror(errno
));
1388 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1390 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1392 if (srv
->srvconf
.enable_cores
) {
1393 prctl(PR_SET_DUMPABLE
, 1, 0, 0, 0);
1399 if (srv
->srvconf
.max_conns
> srv
->max_fds
/2) {
1400 /* we can't have more connections than max-fds/2 */
1401 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", "can't have more connections than fds/2: ", srv
->srvconf
.max_conns
, srv
->max_fds
);
1402 srv
->max_conns
= srv
->max_fds
/2;
1403 } else if (srv
->srvconf
.max_conns
) {
1404 /* otherwise respect the wishes of the user */
1405 srv
->max_conns
= srv
->srvconf
.max_conns
;
1407 /* or use the default: we really don't want to hit max-fds */
1408 srv
->max_conns
= srv
->max_fds
/3;
1412 /* network is up, let's daemonize ourself */
1413 if (0 == srv
->srvconf
.dont_daemonize
&& 0 == graceful_restart
) {
1414 parent_pipe_fd
= daemonize();
1417 graceful_restart
= 0;/*(reset here after avoiding further daemonizing)*/
1418 if (0 == oneshot_fd
) graceful_shutdown
= 0;
1421 #ifdef HAVE_SIGACTION
1422 memset(&act
, 0, sizeof(act
));
1423 act
.sa_handler
= SIG_IGN
;
1424 sigaction(SIGPIPE
, &act
, NULL
);
1425 # if defined(SA_SIGINFO)
1426 last_sighup_info
.si_uid
= 0,
1427 last_sighup_info
.si_pid
= 0;
1428 last_sigterm_info
.si_uid
= 0,
1429 last_sigterm_info
.si_pid
= 0;
1430 act
.sa_sigaction
= sigaction_handler
;
1431 sigemptyset(&act
.sa_mask
);
1432 act
.sa_flags
= SA_SIGINFO
;
1434 act
.sa_handler
= signal_handler
;
1435 sigemptyset(&act
.sa_mask
);
1438 sigaction(SIGINT
, &act
, NULL
);
1439 sigaction(SIGTERM
, &act
, NULL
);
1440 sigaction(SIGHUP
, &act
, NULL
);
1441 sigaction(SIGALRM
, &act
, NULL
);
1442 sigaction(SIGUSR1
, &act
, NULL
);
1444 /* it should be safe to restart syscalls after SIGCHLD */
1445 act
.sa_flags
|= SA_RESTART
| SA_NOCLDSTOP
;
1446 sigaction(SIGCHLD
, &act
, NULL
);
1448 #elif defined(HAVE_SIGNAL)
1449 /* ignore the SIGPIPE from sendfile() */
1450 signal(SIGPIPE
, SIG_IGN
);
1451 signal(SIGALRM
, signal_handler
);
1452 signal(SIGTERM
, signal_handler
);
1453 signal(SIGHUP
, signal_handler
);
1454 signal(SIGCHLD
, signal_handler
);
1455 signal(SIGINT
, signal_handler
);
1456 signal(SIGUSR1
, signal_handler
);
1460 srv
->gid
= getgid();
1461 srv
->uid
= getuid();
1462 srv
->pid
= getpid();
1464 /* write pid file */
1466 buffer_copy_int(srv
->tmp_buf
, srv
->pid
);
1467 buffer_append_string_len(srv
->tmp_buf
, CONST_STR_LEN("\n"));
1468 if (-1 == write_all(pid_fd
, CONST_BUF_LEN(srv
->tmp_buf
))) {
1469 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't write pid file:", strerror(errno
));
1474 } else if (pid_fd
< -2) {
1478 /* Close stderr ASAP in the child process to make sure that nothing
1479 * is being written to that fd which may not be valid anymore. */
1480 if (!srv
->srvconf
.preflight_check
) {
1481 if (-1 == log_error_open(srv
)) {
1482 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Opening errorlog failed. Going down.");
1485 log_error_write(srv
, __FILE__
, __LINE__
, "s", "server started (" PACKAGE_DESC
")");
1488 if (buffer_is_empty(srv
->config_storage
[0]->server_tag
)) {
1489 buffer_copy_string_len(srv
->config_storage
[0]->server_tag
, CONST_STR_LEN(PACKAGE_DESC
));
1492 if (HANDLER_GO_ON
!= plugins_call_set_defaults(srv
)) {
1493 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Configuration of plugins failed. Going down.");
1497 /* settings might be enabled during module config set defaults */
1498 srv
->config_storage
[0]->high_precision_timestamps
= srv
->srvconf
.high_precision_timestamps
;
1500 /* dump unused config-keys */
1501 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1502 array
*config
= ((data_config
*)srv
->config_context
->data
[i
])->value
;
1505 for (j
= 0; config
&& j
< config
->used
; j
++) {
1506 data_unset
*du
= config
->data
[j
];
1508 /* all var.* is known as user defined variable */
1509 if (strncmp(du
->key
->ptr
, "var.", sizeof("var.") - 1) == 0) {
1513 if (NULL
== array_get_element_klen(srv
->config_touched
, CONST_BUF_LEN(du
->key
))) {
1514 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1515 "WARNING: unknown config-key:",
1522 if (srv
->config_unsupported
) {
1523 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1524 "Configuration contains unsupported keys. Going down.");
1527 if (srv
->config_deprecated
) {
1528 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1529 "Configuration contains deprecated keys. Going down.");
1532 if (srv
->config_unsupported
|| srv
->config_deprecated
) {
1536 if (srv
->srvconf
.preflight_check
) {
1537 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1544 * notify daemonize-grandparent of successful startup
1545 * do this before any further forking is done (workers)
1547 if (0 == srv
->srvconf
.dont_daemonize
&& -1 != parent_pipe_fd
) {
1548 if (0 > write(parent_pipe_fd
, "", 1)) return -1;
1549 close(parent_pipe_fd
);
1552 if (idle_limit
&& srv
->srvconf
.max_worker
) {
1553 srv
->srvconf
.max_worker
= 0;
1554 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1555 "server idle time limit command line option disables server.max-worker config file option.");
1558 /* start watcher and workers */
1559 num_childs
= srv
->srvconf
.max_worker
;
1560 if (num_childs
> 0) {
1561 pid_t pids
[num_childs
];
1563 const int npids
= num_childs
;
1565 unsigned int timer
= 0;
1566 for (int n
= 0; n
< npids
; ++n
) pids
[n
] = -1;
1567 while (!child
&& !srv_shutdown
&& !graceful_shutdown
) {
1568 if (num_childs
> 0) {
1569 switch ((pid
= fork())) {
1578 for (int n
= 0; n
< npids
; ++n
) {
1579 if (-1 == pids
[n
]) {
1589 if (-1 != (pid
= wait(&status
))) {
1590 srv
->cur_ts
= time(NULL
);
1591 if (plugins_call_handle_waitpid(srv
, pid
, status
) != HANDLER_GO_ON
) {
1592 if (!timer
) alarm((timer
= 5));
1595 switch (fdevent_reaped_logger_pipe(pid
)) {
1597 case -1: if (!timer
) alarm((timer
= 5));
1602 * check if one of our workers went away
1604 for (int n
= 0; n
< npids
; ++n
) {
1605 if (pid
== pids
[n
]) {
1614 srv
->cur_ts
= time(NULL
);
1616 * if we receive a SIGHUP we have to close our logs ourself as we don't
1617 * have the mainloop who can help us here
1619 if (handle_sig_hup
) {
1622 log_error_cycle(srv
);
1624 /* forward SIGHUP to workers */
1625 for (int n
= 0; n
< npids
; ++n
) {
1626 if (pids
[n
] > 0) kill(pids
[n
], SIGHUP
);
1629 if (handle_sig_alarm
) {
1630 handle_sig_alarm
= 0;
1632 plugins_call_handle_trigger(srv
);
1633 fdevent_restart_logger_pipes(srv
->cur_ts
);
1644 * for the parent this is the exit-point
1648 * kill all children too
1650 if (graceful_shutdown
|| graceful_restart
) {
1651 /* flag to ignore one SIGINT if graceful_restart */
1652 if (graceful_restart
) graceful_restart
= 2;
1654 server_graceful_state(srv
);
1655 } else if (srv_shutdown
) {
1662 /* ignore SIGUSR1 in workers; only parent directs graceful restart */
1663 #ifdef HAVE_SIGACTION
1665 struct sigaction actignore
;
1666 memset(&actignore
, 0, sizeof(actignore
));
1667 actignore
.sa_handler
= SIG_IGN
;
1668 sigaction(SIGUSR1
, &actignore
, NULL
);
1670 #elif defined(HAVE_SIGNAL)
1671 signal(SIGUSR1
, SIG_IGN
);
1675 * make sure workers do not muck with pid-file
1681 buffer_clear(srv
->srvconf
.pid_file
);
1683 fdevent_clr_logger_pipe_pids();
1684 srv
->pid
= getpid();
1689 if (NULL
== (srv
->ev
= fdevent_init(srv
))) {
1690 log_error_write(srv
, __FILE__
, __LINE__
,
1691 "s", "fdevent_init failed");
1695 srv
->max_fds_lowat
= srv
->max_fds
* 8 / 10;
1696 srv
->max_fds_hiwat
= srv
->max_fds
* 9 / 10;
1698 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1699 #ifdef HAVE_SIGACTION
1700 sigaction(SIGCHLD
, &act
, NULL
);
1701 #elif defined(HAVE_SIGNAL)
1702 signal(SIGCHLD
, signal_handler
);
1706 * kqueue() is called here, select resets its internals,
1707 * all server sockets get their handlers
1710 if (0 != network_register_fdevents(srv
)) {
1714 /* might fail if user is using fam (not gamin) and famd isn't running */
1715 if (NULL
== (srv
->stat_cache
= stat_cache_init(srv
))) {
1716 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1717 "stat-cache could not be setup, dieing.");
1723 /* setup periodic timer (1 second) */
1724 struct itimerval interval
;
1725 interval
.it_interval
.tv_sec
= 1;
1726 interval
.it_interval
.tv_usec
= 0;
1727 interval
.it_value
.tv_sec
= 1;
1728 interval
.it_value
.tv_usec
= 0;
1729 if (setitimer(ITIMER_REAL
, &interval
, NULL
)) {
1730 log_error_write(srv
, __FILE__
, __LINE__
, "s", "setting timer failed");
1737 /* get the current number of FDs */
1739 int fd
= fdevent_open_devnull();
1746 if (0 != server_sockets_set_nb_cloexec(srv
)) {
1750 if (oneshot_fd
&& server_oneshot_init(srv
, oneshot_fd
)) {
1758 __attribute_noinline__
1759 static int server_handle_sighup (server
* const srv
) {
1762 /* cycle logfiles */
1764 switch(r
= plugins_call_handle_sighup(srv
)) {
1768 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "sighup-handler return with an error", r
);
1772 if (-1 == log_error_cycle(srv
)) {
1773 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cycling errorlog failed, dying");
1777 #ifdef HAVE_SIGACTION
1778 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
1779 "logfiles cycled UID =",
1780 last_sighup_info
.si_uid
,
1782 last_sighup_info
.si_pid
);
1784 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1792 __attribute_noinline__
1793 static void server_handle_sigalrm (server
* const srv
, time_t min_ts
, time_t last_active_ts
) {
1794 connections
*conns
= srv
->conns
;
1797 switch(r
= plugins_call_handle_trigger(srv
)) {
1801 log_error_write(srv
, __FILE__
, __LINE__
, "s", "one of the triggers failed");
1804 log_error_write(srv
, __FILE__
, __LINE__
, "d", r
);
1808 srv
->cur_ts
= min_ts
;
1810 /* check idle time limit, if enabled */
1811 if (idle_limit
&& idle_limit
< min_ts
- last_active_ts
&& !graceful_shutdown
) {
1812 log_error_write(srv
, __FILE__
, __LINE__
, "sDs", "[note] idle timeout", (int)idle_limit
,
1813 "s exceeded, initiating graceful shutdown");
1814 graceful_shutdown
= 2; /* value 2 indicates idle timeout */
1815 if (graceful_restart
) {
1816 graceful_restart
= 0;
1817 if (pid_fd
< -2) pid_fd
= -pid_fd
;
1818 server_sockets_close(srv
);
1822 #ifdef HAVE_GETLOADAVG
1823 /* refresh loadavg data every 30 seconds */
1824 if (srv
->srvconf
.loadts
+ 30 < min_ts
) {
1825 if (-1 != getloadavg(srv
->srvconf
.loadavg
, 3)) {
1826 srv
->srvconf
.loadts
= min_ts
;
1831 /* free excess chunkqueue buffers every 64 seconds */
1832 if (0 == (min_ts
& 0x3f)) chunkqueue_chunk_pool_clear();
1833 /* cleanup stat-cache */
1834 stat_cache_trigger_cleanup(srv
);
1835 /* reset global/aggregate rate limit counters */
1836 for (size_t i
= 0; i
< srv
->config_context
->used
; ++i
) {
1837 srv
->config_storage
[i
]->global_bytes_per_second_cnt
= 0;
1839 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1840 if (graceful_shutdown
&& !srv_shutdown
) server_graceful_shutdown_maint(srv
);
1842 * check all connections for timeouts
1845 for (size_t ndx
= 0; ndx
< conns
->used
; ++ndx
) {
1846 connection
* const con
= conns
->ptr
[ndx
];
1847 const int waitevents
= fdevent_event_get_interest(srv
->ev
, con
->fd
);
1851 if (con
->state
== CON_STATE_CLOSE
) {
1852 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
) {
1855 } else if (waitevents
& FDEVENT_IN
) {
1856 if (con
->request_count
== 1 || con
->state
!= CON_STATE_READ
) { /* e.g. CON_STATE_READ_POST || CON_STATE_WRITE */
1857 if (srv
->cur_ts
- con
->read_idle_ts
> con
->conf
.max_read_idle
) {
1859 if (con
->conf
.log_request_handling
) {
1860 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1861 "connection closed - read timeout:", con
->fd
);
1864 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1868 if (srv
->cur_ts
- con
->read_idle_ts
> con
->keep_alive_idle
) {
1870 if (con
->conf
.log_request_handling
) {
1871 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1872 "connection closed - keep-alive timeout:", con
->fd
);
1875 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1881 /* max_write_idle timeout currently functions as backend timeout,
1882 * too, after response has been started.
1883 * future: have separate backend timeout, and then change this
1884 * to check for write interest before checking for timeout */
1885 /*if (waitevents & FDEVENT_OUT)*/
1886 if ((con
->state
== CON_STATE_WRITE
) &&
1887 (con
->write_request_ts
!= 0)) {
1889 if (srv
->cur_ts
- con
->write_request_ts
> 60) {
1890 log_error_write(srv
, __FILE__
, __LINE__
, "sdd",
1891 "connection closed - pre-write-request-timeout:", con
->fd
, srv
->cur_ts
- con
->write_request_ts
);
1895 if (srv
->cur_ts
- con
->write_request_ts
> con
->conf
.max_write_idle
) {
1897 if (con
->conf
.log_timeouts
) {
1898 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsosds",
1899 "NOTE: a request from",
1903 "timed out after writing",
1906 (int)con
->conf
.max_write_idle
,
1907 "seconds. If this a problem increase server.max-write-idle");
1909 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1914 /* we don't like div by zero */
1915 if (0 == (t_diff
= srv
->cur_ts
- con
->connection_start
)) t_diff
= 1;
1917 if (con
->traffic_limit_reached
&&
1918 (con
->conf
.kbytes_per_second
== 0 ||
1919 ((con
->bytes_written
/ t_diff
) < con
->conf
.kbytes_per_second
* 1024))) {
1920 /* enable connection again */
1921 con
->traffic_limit_reached
= 0;
1926 con
->bytes_written_cur_second
= 0;
1929 connection_state_machine(srv
, con
);
1934 __attribute_noinline__
1935 static void server_handle_sigchld (server
* const srv
) {
1939 pid
= waitpid(-1, &status
, WNOHANG
);
1941 if (plugins_call_handle_waitpid(srv
, pid
, status
) != HANDLER_GO_ON
) {
1944 if (0 == srv
->srvconf
.max_worker
) {
1945 /* check piped-loggers and restart, even if shutting down */
1946 if (fdevent_waitpid_logger_pipe_pid(pid
, srv
->cur_ts
)) {
1951 } while (pid
> 0 || (-1 == pid
&& errno
== EINTR
));
1955 __attribute_noinline__
1956 static int server_main_loop (server
* const srv
) {
1957 connections
* const joblist
= srv
->joblist
;
1958 time_t last_active_ts
= time(NULL
);
1960 while (!srv_shutdown
) {
1963 if (handle_sig_hup
) {
1965 if (server_handle_sighup(srv
)) return -1;
1968 if (handle_sig_alarm
) {
1969 time_t min_ts
= time(NULL
);
1971 handle_sig_alarm
= 0;
1973 if (min_ts
!= srv
->cur_ts
) {
1974 server_handle_sigalrm(srv
, min_ts
, last_active_ts
);
1978 if (handle_sig_child
) {
1979 handle_sig_child
= 0;
1980 server_handle_sigchld(srv
);
1983 if (graceful_shutdown
) {
1984 server_graceful_state(srv
);
1985 if (srv
->conns
->used
== 0) {
1986 /* we are in graceful shutdown phase and all connections are closed
1987 * we are ready to terminate without harming anyone */
1991 } else if (srv
->sockets_disabled
) {
1992 /* our server sockets are disabled, why ? */
1994 if ((srv
->cur_fds
+ srv
->want_fds
< srv
->max_fds_lowat
) && /* we have enough unused fds */
1995 (srv
->conns
->used
<= srv
->max_conns
* 9 / 10)) {
1996 server_sockets_set_event(srv
, FDEVENT_IN
);
1997 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets enabled again");
1999 srv
->sockets_disabled
= 0;
2002 if ((srv
->cur_fds
+ srv
->want_fds
> srv
->max_fds_hiwat
) || /* out of fds */
2003 (srv
->conns
->used
>= srv
->max_conns
)) { /* out of connections */
2004 /* disable server-fds */
2005 server_sockets_set_event(srv
, 0);
2007 if (srv
->conns
->used
>= srv
->max_conns
) {
2008 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets disabled, connection limit reached");
2010 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets disabled, out-of-fds");
2013 srv
->sockets_disabled
= 1;
2017 /* we still have some fds to share */
2018 if (srv
->want_fds
) {
2019 /* check the fdwaitqueue for waiting fds */
2020 int free_fds
= srv
->max_fds
- srv
->cur_fds
- 16;
2023 for (; free_fds
> 0 && NULL
!= (con
= fdwaitqueue_unshift(srv
, srv
->fdwaitqueue
)); free_fds
--) {
2024 connection_state_machine(srv
, con
);
2030 if ((n
= fdevent_poll(srv
->ev
, 1000)) >= 0) {
2031 if (n
> 0) last_active_ts
= srv
->cur_ts
;
2032 fdevent_sched_run(srv
, srv
->ev
);
2033 } else if (errno
!= EINTR
) {
2034 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2035 "fdevent_poll failed:",
2039 for (size_t ndx
= 0; ndx
< joblist
->used
; ++ndx
) {
2040 connection
*con
= joblist
->ptr
[ndx
];
2041 connection_state_machine(srv
, con
);
2050 int main (int argc
, char **argv
) {
2054 #ifndef HAVE_ISSETUGID
2055 #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2057 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2059 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2064 /* for nice %b handling in strftime() */
2065 setlocale(LC_TIME
, "C");
2068 server
* const srv
= server_init();
2070 if (graceful_restart
) {
2071 server_sockets_restore(srv
);
2075 rc
= server_main(srv
, argc
, argv
);
2076 if (rc
> 0 && 0 == (rc
= server_main_loop(srv
))) {
2077 if (graceful_shutdown
|| graceful_restart
) {
2078 server_graceful_state(srv
);
2081 if (2 == graceful_shutdown
) { /* value 2 indicates idle timeout */
2082 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2083 "server stopped after idle timeout");
2085 #ifdef HAVE_SIGACTION
2086 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2087 "server stopped by UID =",
2088 last_sigterm_info
.si_uid
,
2090 last_sigterm_info
.si_pid
);
2092 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2099 remove_pid_file(srv
);
2100 log_error_close(srv
);
2101 fdevent_close_logger_pipes();
2102 if (graceful_restart
)
2103 server_sockets_save(srv
);
2106 connections_free(srv
);
2110 if (0 != rc
|| !graceful_restart
) break;
2112 /* wait for all children to exit before graceful restart */
2113 while (waitpid(-1, NULL
, 0) > 0) ;
2114 } while (graceful_restart
);