12 #include "http_auth.h"
13 #include "http_chunk.h"
14 #include "http_vhostdb.h"
16 #include "connections.h"
17 #include "sock_addr.h"
18 #include "stat_cache.h"
21 #include "network_write.h"
23 #ifdef HAVE_VERSIONSTAMP_H
24 # include "versionstamp.h"
26 # define REPO_VERSION ""
29 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
31 #include <sys/types.h>
51 #ifdef HAVE_VALGRIND_VALGRIND_H
52 # include <valgrind/valgrind.h>
55 #ifdef HAVE_SYS_WAIT_H
56 # include <sys/wait.h>
68 #ifdef HAVE_SYS_RESOURCE_H
69 # include <sys/resource.h>
72 #ifdef HAVE_SYS_PRCTL_H
73 # include <sys/prctl.h>
76 #if defined HAVE_LIBSSL && defined HAVE_OPENSSL_SSL_H
78 #define TEXT_SSL " (ssl)"
84 /* IRIX doesn't like the alarm based time() optimization */
85 /* #define USE_ALARM */
88 static int oneshot_fd
= 0;
89 static volatile int pid_fd
= -2;
90 static server_socket_array graceful_sockets
;
91 static volatile sig_atomic_t graceful_restart
= 0;
92 static volatile sig_atomic_t graceful_shutdown
= 0;
93 static volatile sig_atomic_t srv_shutdown
= 0;
94 static volatile sig_atomic_t handle_sig_child
= 0;
95 static volatile sig_atomic_t handle_sig_alarm
= 1;
96 static volatile sig_atomic_t handle_sig_hup
= 0;
98 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
99 static volatile siginfo_t last_sigterm_info
;
100 static volatile siginfo_t last_sighup_info
;
102 static void sigaction_handler(int sig
, siginfo_t
*si
, void *context
) {
103 static const siginfo_t empty_siginfo
;
106 if (!si
) *(const siginfo_t
**)&si
= &empty_siginfo
;
111 last_sigterm_info
= *si
;
114 if (!graceful_shutdown
) {
115 graceful_restart
= 1;
116 graceful_shutdown
= 1;
117 last_sigterm_info
= *si
;
121 if (graceful_shutdown
) {
122 if (2 == graceful_restart
)
123 graceful_restart
= 1;
127 graceful_shutdown
= 1;
129 last_sigterm_info
= *si
;
133 handle_sig_alarm
= 1;
137 last_sighup_info
= *si
;
140 handle_sig_child
= 1;
144 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
145 static void signal_handler(int sig
) {
147 case SIGTERM
: srv_shutdown
= 1; break;
149 if (!graceful_shutdown
) {
150 graceful_restart
= 1;
151 graceful_shutdown
= 1;
155 if (graceful_shutdown
) {
156 if (2 == graceful_restart
)
157 graceful_restart
= 1;
161 graceful_shutdown
= 1;
164 case SIGALRM
: handle_sig_alarm
= 1; break;
165 case SIGHUP
: handle_sig_hup
= 1; break;
166 case SIGCHLD
: handle_sig_child
= 1; break;
172 static int daemonize(void) {
176 signal(SIGTTOU
, SIG_IGN
);
179 signal(SIGTTIN
, SIG_IGN
);
182 signal(SIGTSTP
, SIG_IGN
);
185 if (pipe(pipefd
) < 0) exit(-1);
187 if (0 > (pid
= fork())) exit(-1);
194 /* parent waits for grandchild to be ready */
196 bytes
= read(pipefd
[0], &buf
, sizeof(buf
));
197 } while (bytes
< 0 && EINTR
== errno
);
201 /* closed fd (without writing) == failure in grandchild */
202 fputs("daemonized server failed to start; check error log for details\n", stderr
);
211 if (-1 == setsid()) exit(0);
213 signal(SIGHUP
, SIG_IGN
);
215 if (0 != fork()) exit(0);
217 if (0 != chdir("/")) exit(0);
219 fdevent_setfd_cloexec(pipefd
[1]);
224 static server
*server_init(void) {
226 server
*srv
= calloc(1, sizeof(*srv
));
229 srv->x = buffer_init();
231 CLEAN(response_header
);
232 CLEAN(parse_full_path
);
236 CLEAN(response_range
);
238 srv
->empty_string
= buffer_init_string("");
239 CLEAN(cond_check_buf
);
241 CLEAN(srvconf
.errorlog_file
);
242 CLEAN(srvconf
.breakagelog_file
);
243 CLEAN(srvconf
.groupname
);
244 CLEAN(srvconf
.username
);
245 CLEAN(srvconf
.changeroot
);
246 CLEAN(srvconf
.bindhost
);
247 CLEAN(srvconf
.event_handler
);
248 CLEAN(srvconf
.pid_file
);
249 CLEAN(srvconf
.syslog_facility
);
251 CLEAN(tmp_chunk_len
);
255 srv->x = array_init();
257 CLEAN(config_context
);
258 CLEAN(config_touched
);
262 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
263 srv
->mtime_cache
[i
].mtime
= (time_t)-1;
264 srv
->mtime_cache
[i
].str
= buffer_init();
269 srv
->cur_ts
= time(NULL
);
270 srv
->startup_ts
= srv
->cur_ts
;
272 srv
->conns
= calloc(1, sizeof(*srv
->conns
));
273 force_assert(srv
->conns
);
275 srv
->joblist
= calloc(1, sizeof(*srv
->joblist
));
276 force_assert(srv
->joblist
);
278 srv
->fdwaitqueue
= calloc(1, sizeof(*srv
->fdwaitqueue
));
279 force_assert(srv
->fdwaitqueue
);
281 srv
->srvconf
.modules
= array_init();
282 srv
->srvconf
.modules_dir
= buffer_init_string(LIBRARY_DIR
);
283 srv
->srvconf
.network_backend
= buffer_init();
284 srv
->srvconf
.upload_tempdirs
= array_init();
285 srv
->srvconf
.reject_expect_100_with_417
= 1;
286 srv
->srvconf
.xattr_name
= buffer_init_string("Content-Type");
287 srv
->srvconf
.http_header_strict
= 1;
288 srv
->srvconf
.http_host_strict
= 1; /*(implies http_host_normalize)*/
289 srv
->srvconf
.http_host_normalize
= 0;
290 srv
->srvconf
.high_precision_timestamps
= 0;
291 srv
->srvconf
.max_request_field_size
= 8192;
292 srv
->srvconf
.loadavg
[0] = 0.0;
293 srv
->srvconf
.loadavg
[1] = 0.0;
294 srv
->srvconf
.loadavg
[2] = 0.0;
297 srv
->errorlog_fd
= STDERR_FILENO
;
298 srv
->errorlog_mode
= ERRORLOG_FD
;
300 srv
->split_vals
= array_init();
301 srv
->request_env
= plugins_call_handle_request_env
;
306 static void server_free(server
*srv
) {
309 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
310 buffer_free(srv
->mtime_cache
[i
].str
);
313 if (oneshot_fd
> 0) {
320 CLEAN(response_header
);
321 CLEAN(parse_full_path
);
325 CLEAN(response_range
);
328 CLEAN(cond_check_buf
);
330 CLEAN(srvconf
.errorlog_file
);
331 CLEAN(srvconf
.breakagelog_file
);
332 CLEAN(srvconf
.groupname
);
333 CLEAN(srvconf
.username
);
334 CLEAN(srvconf
.changeroot
);
335 CLEAN(srvconf
.bindhost
);
336 CLEAN(srvconf
.event_handler
);
337 CLEAN(srvconf
.pid_file
);
338 CLEAN(srvconf
.modules_dir
);
339 CLEAN(srvconf
.network_backend
);
340 CLEAN(srvconf
.xattr_name
);
341 CLEAN(srvconf
.syslog_facility
);
343 CLEAN(tmp_chunk_len
);
347 fdevent_unregister(srv
->ev
, srv
->fd
);
349 fdevent_free(srv
->ev
);
353 if (srv
->config_storage
) {
354 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
355 specific_config
*s
= srv
->config_storage
[i
];
359 buffer_free(s
->document_root
);
360 buffer_free(s
->server_name
);
361 buffer_free(s
->server_tag
);
362 buffer_free(s
->error_handler
);
363 buffer_free(s
->error_handler_404
);
364 buffer_free(s
->errorfile_prefix
);
365 buffer_free(s
->socket_perms
);
366 array_free(s
->mimetypes
);
369 free(srv
->config_storage
);
370 srv
->config_storage
= NULL
;
376 CLEAN(config_context
);
377 CLEAN(config_touched
);
379 CLEAN(srvconf
.upload_tempdirs
);
382 joblist_free(srv
, srv
->joblist
);
383 fdwaitqueue_free(srv
, srv
->fdwaitqueue
);
385 if (srv
->stat_cache
) {
386 stat_cache_free(srv
->stat_cache
);
389 array_free(srv
->srvconf
.modules
);
390 array_free(srv
->split_vals
);
397 static void remove_pid_file(server
*srv
) {
398 if (pid_fd
<= -2) return;
399 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) && 0 <= pid_fd
) {
400 if (0 != ftruncate(pid_fd
, 0)) {
401 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
402 "ftruncate failed for:",
403 srv
->srvconf
.pid_file
,
412 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) &&
413 buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
414 if (0 != unlink(srv
->srvconf
.pid_file
->ptr
)) {
415 if (errno
!= EACCES
&& errno
!= EPERM
) {
416 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
417 "unlink failed for:",
418 srv
->srvconf
.pid_file
,
427 static server_socket
* server_oneshot_getsock(server
*srv
, sock_addr
*cnt_addr
) {
428 server_socket
*srv_socket
, *srv_socket_wild
= NULL
;
430 for (i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
431 srv_socket
= srv
->srv_sockets
.ptr
[i
];
432 if (!sock_addr_is_port_eq(&srv_socket
->addr
,cnt_addr
)) continue;
433 if (sock_addr_is_addr_eq(&srv_socket
->addr
,cnt_addr
)) return srv_socket
;
435 if (NULL
!= srv_socket_wild
) continue;
436 if (sock_addr_is_addr_wildcard(&srv_socket
->addr
)) {
437 srv_socket_wild
= srv_socket
;
441 if (NULL
!= srv_socket_wild
) {
442 return srv_socket_wild
;
443 } else if (srv
->srv_sockets
.used
) {
444 return srv
->srv_sockets
.ptr
[0];
446 log_error_write(srv
, __FILE__
, __LINE__
, "s", "no sockets configured");
452 static int server_oneshot_init(server
*srv
, int fd
) {
453 /* Note: does not work with netcat due to requirement that fd be socket.
454 * STDOUT_FILENO was not saved earlier in startup, and that is to where
455 * netcat expects output to be sent. Since lighttpd expects connections
456 * to be sockets, con->fd is where output is sent; separate fds are not
457 * stored for input and output, but netcat has different fds for stdin
458 * and * stdout. To support netcat, would additionally need to avoid
459 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
460 * addresses from environment variables:
461 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
462 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
466 server_socket
*srv_socket
;
471 if (0 != fstat(fd
, &st
)) {
472 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fstat:", strerror(errno
));
476 if (!S_ISSOCK(st
.st_mode
)) {
477 /* require that fd is a socket
478 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
479 log_error_write(srv
, __FILE__
, __LINE__
, "s", "lighttpd -1 stdin is not a socket");
483 cnt_len
= sizeof(cnt_addr
);
484 if (0 != getsockname(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
485 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getsockname:", strerror(errno
));
489 srv_socket
= server_oneshot_getsock(srv
, &cnt_addr
);
490 if (NULL
== srv_socket
) return 0;
492 cnt_len
= sizeof(cnt_addr
);
493 if (0 != getpeername(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
494 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getpeername:", strerror(errno
));
498 /*(must set flags; fd did not pass through fdevent accept() logic)*/
499 if (-1 == fdevent_fcntl_set_nb_cloexec(srv
->ev
, fd
)) {
500 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl:", strerror(errno
));
504 if (sock_addr_get_family(&cnt_addr
) != AF_UNIX
) {
505 network_accept_tcp_nagle_disable(fd
);
508 con
= connection_accepted(srv
, srv_socket
, &cnt_addr
, fd
);
509 if (NULL
== con
) return 0;
511 connection_state_machine(srv
, con
);
516 static void show_version (void) {
517 char *b
= PACKAGE_DESC TEXT_SSL \
518 " - a light and fast webserver\n"
519 #ifdef NONREPRODUCIBLE_BUILD
520 "Build-Date: " __DATE__
" " __TIME__
"\n";
523 write_all(STDOUT_FILENO
, b
, strlen(b
));
526 static void show_features (void) {
527 static const char event_handlers
[] = ""
528 "\nEvent Handlers:\n\n"
530 "\t+ select (generic)\n"
532 "\t- select (generic)\n"
539 #ifdef USE_LINUX_EPOLL
540 "\t+ epoll (Linux 2.6)\n"
542 "\t- epoll (Linux 2.6)\n"
544 #ifdef USE_SOLARIS_DEVPOLL
545 "\t+ /dev/poll (Solaris)\n"
547 "\t- /dev/poll (Solaris)\n"
549 #ifdef USE_SOLARIS_PORT
550 "\t+ eventports (Solaris)\n"
552 "\t- eventports (Solaris)\n"
554 #ifdef USE_FREEBSD_KQUEUE
555 "\t+ kqueue (FreeBSD)\n"
557 "\t- kqueue (FreeBSD)\n"
560 "\t+ libev (generic)\n"
562 "\t- libev (generic)\n"
566 static const char features
[] =
573 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
578 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
579 "\t+ bzip2 support\n"
581 "\t- bzip2 support\n"
583 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
584 "\t+ crypt support\n"
586 "\t- crypt support\n"
599 "\t+ MySQL support\n"
601 "\t- MySQL support\n"
604 "\t+ PgSQL support\n"
606 "\t- PgSQL support\n"
614 "\t+ Kerberos support\n"
616 "\t- Kerberos support\n"
618 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
624 "\t+ memcached support\n"
626 "\t- memcached support\n"
643 #ifdef HAVE_SQLITE3_H
644 "\t+ SQLite support\n"
646 "\t- SQLite support\n"
655 printf("%s%s%s\n", event_handlers
, network_write_show_handlers(), features
);
658 static void show_help (void) {
659 char *b
= PACKAGE_DESC TEXT_SSL
660 #ifdef NONREPRODUCIBLE_BUILD
661 " ("__DATE__
" " __TIME__
")"
663 " - a light and fast webserver\n" \
665 " -f <name> filename of the config-file\n" \
666 " -m <name> module directory (default: "LIBRARY_DIR
")\n" \
667 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
668 " -1 process single (one) request on stdin socket, then exit\n" \
669 " -p print the parsed config-file in internal form, and exit\n" \
670 " -t test config-file syntax, then exit\n" \
671 " -tt test config-file syntax, load and init modules, then exit\n" \
672 " -D don't go to background (default: go to background)\n" \
673 " -v show version\n" \
674 " -V show compile-time features\n" \
675 " -h show this help\n" \
678 write_all(STDOUT_FILENO
, b
, strlen(b
));
684 * we have 4 possibilities:
692 static int log_error_open(server
*srv
) {
695 /* perhaps someone wants to use syslog() */
697 if (!buffer_string_is_empty(srv
->srvconf
.syslog_facility
)) {
698 static const struct facility_name_st
{
701 } facility_names
[] = {
704 ,{ "authpriv", LOG_AUTHPRIV
}
707 ,{ "cron", LOG_CRON
}
709 ,{ "daemon", LOG_DAEMON
}
714 ,{ "kern", LOG_KERN
}
720 ,{ "mail", LOG_MAIL
}
723 ,{ "news", LOG_NEWS
}
725 ,{ "security", LOG_AUTH
} /* DEPRECATED */
727 ,{ "syslog", LOG_SYSLOG
}
730 ,{ "user", LOG_USER
}
733 ,{ "uucp", LOG_UUCP
}
735 ,{ "local0", LOG_LOCAL0
}
736 ,{ "local1", LOG_LOCAL1
}
737 ,{ "local2", LOG_LOCAL2
}
738 ,{ "local3", LOG_LOCAL3
}
739 ,{ "local4", LOG_LOCAL4
}
740 ,{ "local5", LOG_LOCAL5
}
741 ,{ "local6", LOG_LOCAL6
}
742 ,{ "local7", LOG_LOCAL7
}
745 for (i
= 0; i
< sizeof(facility_names
)/sizeof(facility_names
[0]); ++i
) {
746 const struct facility_name_st
*f
= facility_names
+i
;
747 if (0 == strcmp(srv
->srvconf
.syslog_facility
->ptr
, f
->name
)) {
752 if (-1 == facility
) {
753 log_error_write(srv
, __FILE__
, __LINE__
, "SBS",
754 "unrecognized server.syslog-facility: \"",
755 srv
->srvconf
.syslog_facility
,
756 "\"; defaulting to \"daemon\" facility");
759 openlog("lighttpd", LOG_CONS
|LOG_PID
, -1==facility
? LOG_DAEMON
: facility
);
762 srv
->errorlog_mode
= ERRORLOG_FD
;
763 srv
->errorlog_fd
= STDERR_FILENO
;
765 if (srv
->srvconf
.errorlog_use_syslog
) {
766 srv
->errorlog_mode
= ERRORLOG_SYSLOG
;
768 else if (!buffer_string_is_empty(srv
->srvconf
.errorlog_file
)) {
769 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
771 if (-1 == (srv
->errorlog_fd
= fdevent_open_logger(logfile
))) {
772 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
773 "opening errorlog '", logfile
,
774 "' failed: ", strerror(errno
));
777 srv
->errorlog_mode
= logfile
[0] == '|' ? ERRORLOG_PIPE
: ERRORLOG_FILE
;
780 if (srv
->errorlog_mode
== ERRORLOG_FD
&& !srv
->srvconf
.dont_daemonize
) {
781 /* We can only log to stderr in dont-daemonize mode;
782 * if we do daemonize and no errorlog file is specified,
783 * we log into /dev/null
785 srv
->errorlog_fd
= -1;
788 if (!buffer_string_is_empty(srv
->srvconf
.breakagelog_file
)) {
789 const char *logfile
= srv
->srvconf
.breakagelog_file
->ptr
;
791 if (srv
->errorlog_mode
== ERRORLOG_FD
) {
792 srv
->errorlog_fd
= dup(STDERR_FILENO
);
793 fdevent_setfd_cloexec(srv
->errorlog_fd
);
796 if (-1 == (errfd
= fdevent_open_logger(logfile
))) {
797 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
798 "opening errorlog '", logfile
,
799 "' failed: ", strerror(errno
));
803 if (*logfile
== '|') fdevent_breakagelog_logger_pipe(errfd
);
805 else if (!srv
->srvconf
.dont_daemonize
) {
806 /* move STDERR_FILENO to /dev/null */
807 if (-1 == (errfd
= fdevent_open_devnull())) {
808 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
809 "opening /dev/null failed:", strerror(errno
));
814 /*(leave STDERR_FILENO as-is)*/
818 if (0 != fdevent_set_stdin_stdout_stderr(-1, -1, errfd
)) {
819 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
820 "setting stderr failed:", strerror(errno
));
822 if (-1 != errfd
) close(errfd
);
827 if (-1 != errfd
) close(errfd
);
838 static int log_error_cycle(server
*srv
) {
839 /* cycle only if the error log is a file */
841 if (srv
->errorlog_mode
== ERRORLOG_FILE
) {
842 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
843 if (-1 == fdevent_cycle_logger(logfile
, &srv
->errorlog_fd
)) {
844 /* write to old log */
845 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
846 "cycling errorlog '", logfile
,
847 "' failed: ", strerror(errno
));
854 static int log_error_close(server
*srv
) {
855 switch(srv
->errorlog_mode
) {
859 if (-1 != srv
->errorlog_fd
) {
860 /* don't close STDERR */
861 /* fdevent_close_logger_pipes() closes ERRORLOG_PIPE */
862 if (STDERR_FILENO
!= srv
->errorlog_fd
863 && srv
->errorlog_mode
!= ERRORLOG_PIPE
) {
864 close(srv
->errorlog_fd
);
866 srv
->errorlog_fd
= -1;
869 case ERRORLOG_SYSLOG
:
879 static void server_sockets_save (server
*srv
) { /* graceful_restart */
880 memcpy(&graceful_sockets
, &srv
->srv_sockets
, sizeof(server_socket_array
));
881 memset(&srv
->srv_sockets
, 0, sizeof(server_socket_array
));
884 static void server_sockets_restore (server
*srv
) { /* graceful_restart */
885 memcpy(&srv
->srv_sockets
, &graceful_sockets
, sizeof(server_socket_array
));
886 memset(&graceful_sockets
, 0, sizeof(server_socket_array
));
889 static int server_sockets_set_nb_cloexec (server
*srv
) {
890 if (srv
->sockets_disabled
) return 0; /* lighttpd -1 (one-shot mode) */
891 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
892 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
893 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv
->ev
, srv_socket
->fd
)) {
894 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
895 "fcntl failed:", strerror(errno
));
902 static void server_sockets_set_event (server
*srv
, int event
) {
903 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
904 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
905 fdevent_event_set(srv
->ev
,&(srv_socket
->fde_ndx
),srv_socket
->fd
,event
);
909 static void server_sockets_unregister (server
*srv
) {
910 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
)
911 network_unregister_sock(srv
, srv
->srv_sockets
.ptr
[i
]);
914 static void server_sockets_close (server
*srv
) {
915 /* closing socket right away will make it possible for the next lighttpd
916 * to take over (old-style graceful restart), but only if backends
917 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
918 * than started by lighttpd via "bin-path")
920 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
921 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
922 if (-1 == srv_socket
->fd
) continue;
923 network_unregister_sock(srv
, srv_socket
);
924 close(srv_socket
->fd
);
926 /* network_close() will cleanup after us */
930 static void server_graceful_shutdown_maint (server
*srv
) {
931 connections
*conns
= srv
->conns
;
932 for (size_t ndx
= 0; ndx
< conns
->used
; ++ndx
) {
933 connection
* const con
= conns
->ptr
[ndx
];
936 if (con
->state
== CON_STATE_CLOSE
) {
937 /* reduce remaining linger timeout to be
938 * (from zero) *up to* one more second, but no more */
939 if (HTTP_LINGER_TIMEOUT
> 1)
940 con
->close_timeout_ts
-= (HTTP_LINGER_TIMEOUT
- 1);
941 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
)
944 else if (con
->state
== CON_STATE_READ
&& con
->request_count
> 1
945 && chunkqueue_is_empty(con
->read_queue
)) {
946 /* close connections in keep-alive waiting for next request */
947 connection_set_state(srv
, con
, CON_STATE_ERROR
);
951 con
->keep_alive
= 0; /* disable keep-alive */
953 con
->conf
.kbytes_per_second
= 0; /* disable rate limit */
954 con
->conf
.global_kbytes_per_second
= 0; /* disable rate limit */
955 if (con
->traffic_limit_reached
) {
956 con
->traffic_limit_reached
= 0;
961 connection_state_machine(srv
, con
);
966 static void server_graceful_state (server
*srv
) {
968 if (!srv_shutdown
) server_graceful_shutdown_maint(srv
);
971 if (0==srv
->srv_sockets
.used
|| -1 == srv
->srv_sockets
.ptr
[0]->fde_ndx
)
975 log_error_write(srv
, __FILE__
, __LINE__
, "s",
976 "[note] graceful shutdown started");
978 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
979 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)
980 || oneshot_fd
|| 2 == graceful_shutdown
)
981 graceful_restart
= 0;
983 if (graceful_restart
) {
984 server_sockets_unregister(srv
);
985 if (pid_fd
> 0) pid_fd
= -pid_fd
; /*(flag to skip removing pid file)*/
988 server_sockets_close(srv
);
989 remove_pid_file(srv
);
990 buffer_reset(srv
->srvconf
.pid_file
); /*(prevent more removal attempts)*/
994 static int server_main (server
* const srv
, int argc
, char **argv
) {
995 int print_config
= 0;
1003 time_t idle_limit
= 0, last_active_ts
= time(NULL
);
1004 #ifdef HAVE_SIGACTION
1005 struct sigaction act
;
1009 int parent_pipe_fd
= -1;
1014 i_am_root
= (0 == getuid());
1017 /* initialize globals (including file-scoped static globals) */
1020 graceful_shutdown
= 0;
1021 handle_sig_alarm
= 1;
1023 chunkqueue_set_tempdirs_default_reset();
1024 http_auth_dumbdata_reset();
1025 http_vhostdb_dumbdata_reset();
1026 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1027 /*(intentionally preserved)*/
1028 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1031 srv
->srvconf
.port
= 0;
1032 srv
->srvconf
.dont_daemonize
= 0;
1033 srv
->srvconf
.preflight_check
= 0;
1035 while(-1 != (o
= getopt(argc
, argv
, "f:m:i:hvVD1pt"))) {
1038 if (srv
->config_storage
) {
1039 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1040 "Can only read one config file. Use the include command to use multiple config files.");
1043 if (config_read(srv
, optarg
)) {
1048 buffer_copy_string(srv
->srvconf
.modules_dir
, optarg
);
1052 long timeout
= strtol(optarg
, &endptr
, 0);
1053 if (!*optarg
|| *endptr
|| timeout
< 0) {
1054 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1055 "Invalid idle timeout value:", optarg
);
1058 idle_limit
= (time_t)timeout
;
1061 case 'p': print_config
= 1; break;
1062 case 't': ++test_config
; break;
1063 case '1': if (0 == oneshot_fd
) oneshot_fd
= dup(STDIN_FILENO
);
1065 case 'D': srv
->srvconf
.dont_daemonize
= 1; break;
1066 case 'v': show_version(); return 0;
1067 case 'V': show_features(); return 0;
1068 case 'h': show_help(); return 0;
1075 if (!srv
->config_storage
) {
1076 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1077 "No configuration available. Try using -f option.");
1082 data_unset
*dc
= srv
->config_context
->data
[0];
1085 fprintf(stdout
, "\n");
1087 /* shouldn't happend */
1088 fprintf(stderr
, "global config not found\n");
1093 buffer_reset(srv
->srvconf
.pid_file
);
1094 if (1 == test_config
) {
1095 printf("Syntax OK\n");
1096 } else { /*(test_config > 1)*/
1098 srv
->srvconf
.preflight_check
= 1;
1099 srv
->srvconf
.dont_daemonize
= 1;
1103 if (test_config
|| print_config
) {
1108 if (oneshot_fd
<= STDERR_FILENO
) {
1109 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1110 "Invalid fds at startup with lighttpd -1");
1113 graceful_shutdown
= 1;
1114 srv
->sockets_disabled
= 1;
1115 srv
->srvconf
.dont_daemonize
= 1;
1116 buffer_reset(srv
->srvconf
.pid_file
);
1117 if (srv
->srvconf
.max_worker
) {
1118 srv
->srvconf
.max_worker
= 0;
1119 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1120 "server one-shot command line option disables server.max-worker config file option.");
1124 if (buffer_is_equal_string(srv
->srvconf
.bindhost
, CONST_STR_LEN("/dev/stdin"))) {
1125 stdin_fd
= dup(STDIN_FILENO
);
1126 if (stdin_fd
<= STDERR_FILENO
) {
1127 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1128 "Invalid fds at startup");
1133 /* close stdin and stdout, as they are not needed */
1139 /* coverity[overwrite_var : FALSE] */
1140 devnull
= fdevent_open_devnull();
1142 __coverity_escape__(devnull
);
1144 } while (-1 != devnull
&& devnull
<= STDERR_FILENO
);
1145 if (-1 == devnull
) {
1146 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1147 "opening /dev/null failed:", strerror(errno
));
1150 errfd
= (0 == fstat(STDERR_FILENO
, &st
)) ? -1 : devnull
;
1151 if (0 != fdevent_set_stdin_stdout_stderr(devnull
, devnull
, errfd
)) {
1152 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1153 "setting default fds failed:", strerror(errno
));
1155 if (-1 != errfd
) close(errfd
);
1156 if (devnull
!= errfd
) close(devnull
);
1161 if (-1 != errfd
) close(errfd
);
1162 if (devnull
!= errfd
) close(devnull
);
1166 if (0 != config_set_defaults(srv
)) {
1167 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1168 "setting default values failed");
1172 /* check document-root */
1173 if (buffer_string_is_empty(srv
->config_storage
[0]->document_root
)) {
1174 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1175 "document-root is not set\n");
1179 if (plugins_load(srv
)) {
1180 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1181 "loading plugins finally failed");
1185 if (HANDLER_GO_ON
!= plugins_call_init(srv
)) {
1186 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Initialization of plugins failed. Going down.");
1190 /* open pid file BEFORE chroot */
1191 if (-2 == pid_fd
) pid_fd
= -1; /*(initial startup state)*/
1192 if (-1 == pid_fd
&& !buffer_string_is_empty(srv
->srvconf
.pid_file
)) {
1193 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
))) {
1195 if (errno
!= EEXIST
) {
1196 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1197 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1201 if (0 != stat(srv
->srvconf
.pid_file
->ptr
, &st
)) {
1202 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1203 "stating existing pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1206 if (!S_ISREG(st
.st_mode
)) {
1207 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1208 "pid-file exists and isn't regular file:", srv
->srvconf
.pid_file
);
1212 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
))) {
1213 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1214 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1220 if (srv
->event_handler
== FDEVENT_HANDLER_SELECT
) {
1221 /* select limits itself
1223 * as it is a hard limit and will lead to a segfault we add some safety
1225 srv
->max_fds
= FD_SETSIZE
- 200;
1227 srv
->max_fds
= 4096;
1231 #ifdef HAVE_GETRLIMIT
1234 #ifdef HAVE_VALGRIND_VALGRIND_H
1235 if (RUNNING_ON_VALGRIND
) use_rlimit
= 0;
1238 if (0 != getrlimit(RLIMIT_NOFILE
, &rlim
)) {
1239 log_error_write(srv
, __FILE__
, __LINE__
,
1240 "ss", "couldn't get 'max filedescriptors'",
1246 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1248 if (use_rlimit
&& srv
->srvconf
.max_fds
1249 && (i_am_root
|| srv
->srvconf
.max_fds
<= rlim
.rlim_max
)) {
1252 rlim
.rlim_cur
= srv
->srvconf
.max_fds
;
1253 if (i_am_root
) rlim
.rlim_max
= srv
->srvconf
.max_fds
;
1255 if (0 != setrlimit(RLIMIT_NOFILE
, &rlim
)) {
1256 log_error_write(srv
, __FILE__
, __LINE__
,
1257 "ss", "couldn't set 'max filedescriptors'",
1263 if (srv
->event_handler
== FDEVENT_HANDLER_SELECT
) {
1264 srv
->max_fds
= rlim
.rlim_cur
< (rlim_t
)FD_SETSIZE
- 200 ? (int)rlim
.rlim_cur
: (int)FD_SETSIZE
- 200;
1266 srv
->max_fds
= rlim
.rlim_cur
;
1267 /*(default upper limit of 4k if server.max-fds not specified)*/
1268 if (i_am_root
&& 0 == srv
->srvconf
.max_fds
&& rlim
.rlim_cur
> 4096)
1269 srv
->max_fds
= 4096;
1272 /* set core file rlimit, if enable_cores is set */
1273 if (use_rlimit
&& srv
->srvconf
.enable_cores
&& getrlimit(RLIMIT_CORE
, &rlim
) == 0) {
1274 rlim
.rlim_cur
= rlim
.rlim_max
;
1275 setrlimit(RLIMIT_CORE
, &rlim
);
1278 if (srv
->event_handler
== FDEVENT_HANDLER_SELECT
) {
1279 /* don't raise the limit above FD_SET_SIZE */
1280 if (srv
->max_fds
> ((int)FD_SETSIZE
) - 200) {
1281 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1282 "can't raise max filedescriptors above", FD_SETSIZE
- 200,
1283 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
1289 /* we need root-perms for port < 1024 */
1290 if (0 != network_init(srv
, stdin_fd
)) {
1296 /* set user and group */
1297 struct group
*grp
= NULL
;
1298 struct passwd
*pwd
= NULL
;
1300 if (!buffer_string_is_empty(srv
->srvconf
.groupname
)) {
1301 if (NULL
== (grp
= getgrnam(srv
->srvconf
.groupname
->ptr
))) {
1302 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1303 "can't find groupname", srv
->srvconf
.groupname
);
1308 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1309 if (NULL
== (pwd
= getpwnam(srv
->srvconf
.username
->ptr
))) {
1310 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1311 "can't find username", srv
->srvconf
.username
);
1315 if (pwd
->pw_uid
== 0) {
1316 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1317 "I will not set uid to 0\n");
1321 if (NULL
== grp
&& NULL
== (grp
= getgrgid(pwd
->pw_gid
))) {
1322 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1323 "can't find group id", pwd
->pw_gid
);
1329 if (grp
->gr_gid
== 0) {
1330 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1331 "I will not set gid to 0\n");
1337 * Change group before chroot, when we have access
1341 if (-1 == setgid(grp
->gr_gid
)) {
1342 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgid failed: ", strerror(errno
));
1345 if (-1 == setgroups(0, NULL
)) {
1346 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgroups failed: ", strerror(errno
));
1349 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1350 initgroups(srv
->srvconf
.username
->ptr
, grp
->gr_gid
);
1355 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
1358 if (-1 == chroot(srv
->srvconf
.changeroot
->ptr
)) {
1359 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chroot failed: ", strerror(errno
));
1362 if (-1 == chdir("/")) {
1363 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chdir failed: ", strerror(errno
));
1369 /* drop root privs */
1371 if (-1 == setuid(pwd
->pw_uid
)) {
1372 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setuid failed: ", strerror(errno
));
1377 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1379 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1381 if (srv
->srvconf
.enable_cores
) {
1382 prctl(PR_SET_DUMPABLE
, 1, 0, 0, 0);
1388 if (srv
->srvconf
.max_conns
> srv
->max_fds
/2) {
1389 /* we can't have more connections than max-fds/2 */
1390 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", "can't have more connections than fds/2: ", srv
->srvconf
.max_conns
, srv
->max_fds
);
1391 srv
->max_conns
= srv
->max_fds
/2;
1392 } else if (srv
->srvconf
.max_conns
) {
1393 /* otherwise respect the wishes of the user */
1394 srv
->max_conns
= srv
->srvconf
.max_conns
;
1396 /* or use the default: we really don't want to hit max-fds */
1397 srv
->max_conns
= srv
->max_fds
/3;
1401 /* network is up, let's daemonize ourself */
1402 if (0 == srv
->srvconf
.dont_daemonize
&& 0 == graceful_restart
) {
1403 parent_pipe_fd
= daemonize();
1406 graceful_restart
= 0;/*(reset here after avoiding further daemonizing)*/
1407 graceful_shutdown
= 0;
1410 #ifdef HAVE_SIGACTION
1411 memset(&act
, 0, sizeof(act
));
1412 act
.sa_handler
= SIG_IGN
;
1413 sigaction(SIGPIPE
, &act
, NULL
);
1414 # if defined(SA_SIGINFO)
1415 last_sighup_info
.si_uid
= 0,
1416 last_sighup_info
.si_pid
= 0;
1417 last_sigterm_info
.si_uid
= 0,
1418 last_sigterm_info
.si_pid
= 0;
1419 act
.sa_sigaction
= sigaction_handler
;
1420 sigemptyset(&act
.sa_mask
);
1421 act
.sa_flags
= SA_SIGINFO
;
1423 act
.sa_handler
= signal_handler
;
1424 sigemptyset(&act
.sa_mask
);
1427 sigaction(SIGINT
, &act
, NULL
);
1428 sigaction(SIGTERM
, &act
, NULL
);
1429 sigaction(SIGHUP
, &act
, NULL
);
1430 sigaction(SIGALRM
, &act
, NULL
);
1431 sigaction(SIGUSR1
, &act
, NULL
);
1433 /* it should be safe to restart syscalls after SIGCHLD */
1434 act
.sa_flags
|= SA_RESTART
| SA_NOCLDSTOP
;
1435 sigaction(SIGCHLD
, &act
, NULL
);
1437 #elif defined(HAVE_SIGNAL)
1438 /* ignore the SIGPIPE from sendfile() */
1439 signal(SIGPIPE
, SIG_IGN
);
1440 signal(SIGALRM
, signal_handler
);
1441 signal(SIGTERM
, signal_handler
);
1442 signal(SIGHUP
, signal_handler
);
1443 signal(SIGCHLD
, signal_handler
);
1444 signal(SIGINT
, signal_handler
);
1445 signal(SIGUSR1
, signal_handler
);
1449 srv
->gid
= getgid();
1450 srv
->uid
= getuid();
1451 srv
->pid
= getpid();
1453 /* write pid file */
1455 buffer_copy_int(srv
->tmp_buf
, srv
->pid
);
1456 buffer_append_string_len(srv
->tmp_buf
, CONST_STR_LEN("\n"));
1457 if (-1 == write_all(pid_fd
, CONST_BUF_LEN(srv
->tmp_buf
))) {
1458 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't write pid file:", strerror(errno
));
1463 } else if (pid_fd
< -2) {
1467 /* Close stderr ASAP in the child process to make sure that nothing
1468 * is being written to that fd which may not be valid anymore. */
1469 if (!srv
->srvconf
.preflight_check
) {
1470 if (-1 == log_error_open(srv
)) {
1471 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Opening errorlog failed. Going down.");
1474 log_error_write(srv
, __FILE__
, __LINE__
, "s", "server started (" PACKAGE_DESC
")");
1477 if (buffer_is_empty(srv
->config_storage
[0]->server_tag
)) {
1478 buffer_copy_string_len(srv
->config_storage
[0]->server_tag
, CONST_STR_LEN(PACKAGE_DESC
));
1481 if (HANDLER_GO_ON
!= plugins_call_set_defaults(srv
)) {
1482 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Configuration of plugins failed. Going down.");
1486 /* settings might be enabled during module config set defaults */
1487 srv
->config_storage
[0]->high_precision_timestamps
= srv
->srvconf
.high_precision_timestamps
;
1489 /* dump unused config-keys */
1490 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1491 array
*config
= ((data_config
*)srv
->config_context
->data
[i
])->value
;
1494 for (j
= 0; config
&& j
< config
->used
; j
++) {
1495 data_unset
*du
= config
->data
[j
];
1497 /* all var.* is known as user defined variable */
1498 if (strncmp(du
->key
->ptr
, "var.", sizeof("var.") - 1) == 0) {
1502 if (NULL
== array_get_element_klen(srv
->config_touched
, CONST_BUF_LEN(du
->key
))) {
1503 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1504 "WARNING: unknown config-key:",
1511 if (srv
->config_unsupported
) {
1512 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1513 "Configuration contains unsupported keys. Going down.");
1516 if (srv
->config_deprecated
) {
1517 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1518 "Configuration contains deprecated keys. Going down.");
1521 if (srv
->config_unsupported
|| srv
->config_deprecated
) {
1525 if (srv
->srvconf
.preflight_check
) {
1526 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1533 * notify daemonize-grandparent of successful startup
1534 * do this before any further forking is done (workers)
1536 if (0 == srv
->srvconf
.dont_daemonize
&& -1 != parent_pipe_fd
) {
1537 if (0 > write(parent_pipe_fd
, "", 1)) return -1;
1538 close(parent_pipe_fd
);
1541 if (idle_limit
&& srv
->srvconf
.max_worker
) {
1542 srv
->srvconf
.max_worker
= 0;
1543 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1544 "server idle time limit command line option disables server.max-worker config file option.");
1547 /* start watcher and workers */
1548 num_childs
= srv
->srvconf
.max_worker
;
1549 if (num_childs
> 0) {
1550 pid_t pids
[num_childs
];
1552 const int npids
= num_childs
;
1554 unsigned int timer
= 0;
1555 for (int n
= 0; n
< npids
; ++n
) pids
[n
] = -1;
1556 while (!child
&& !srv_shutdown
&& !graceful_shutdown
) {
1557 if (num_childs
> 0) {
1558 switch ((pid
= fork())) {
1567 for (int n
= 0; n
< npids
; ++n
) {
1568 if (-1 == pids
[n
]) {
1578 if (-1 != (pid
= wait(&status
))) {
1579 srv
->cur_ts
= time(NULL
);
1580 if (plugins_call_handle_waitpid(srv
, pid
, status
) != HANDLER_GO_ON
) {
1581 if (!timer
) alarm((timer
= 5));
1584 switch (fdevent_reaped_logger_pipe(pid
)) {
1586 case -1: if (!timer
) alarm((timer
= 5));
1591 * check if one of our workers went away
1593 for (int n
= 0; n
< npids
; ++n
) {
1594 if (pid
== pids
[n
]) {
1603 srv
->cur_ts
= time(NULL
);
1605 * if we receive a SIGHUP we have to close our logs ourself as we don't
1606 * have the mainloop who can help us here
1608 if (handle_sig_hup
) {
1611 log_error_cycle(srv
);
1613 /* forward SIGHUP to workers */
1614 for (int n
= 0; n
< npids
; ++n
) {
1615 if (pids
[n
] > 0) kill(pids
[n
], SIGHUP
);
1618 if (handle_sig_alarm
) {
1619 handle_sig_alarm
= 0;
1621 plugins_call_handle_trigger(srv
);
1622 fdevent_restart_logger_pipes(srv
->cur_ts
);
1633 * for the parent this is the exit-point
1637 * kill all children too
1639 if (graceful_shutdown
|| graceful_restart
) {
1640 /* flag to ignore one SIGINT if graceful_restart */
1641 if (graceful_restart
) graceful_restart
= 2;
1643 server_graceful_state(srv
);
1644 } else if (srv_shutdown
) {
1651 /* ignore SIGUSR1 in workers; only parent directs graceful restart */
1652 #ifdef HAVE_SIGACTION
1654 struct sigaction actignore
;
1655 memset(&actignore
, 0, sizeof(actignore
));
1656 actignore
.sa_handler
= SIG_IGN
;
1657 sigaction(SIGUSR1
, &actignore
, NULL
);
1659 #elif defined(HAVE_SIGNAL)
1660 signal(SIGUSR1
, SIG_IGN
);
1664 * make sure workers do not muck with pid-file
1670 buffer_reset(srv
->srvconf
.pid_file
);
1672 fdevent_clr_logger_pipe_pids();
1673 srv
->pid
= getpid();
1678 if (NULL
== (srv
->ev
= fdevent_init(srv
, srv
->max_fds
+ 1, srv
->event_handler
))) {
1679 log_error_write(srv
, __FILE__
, __LINE__
,
1680 "s", "fdevent_init failed");
1684 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1685 #ifdef HAVE_SIGACTION
1686 sigaction(SIGCHLD
, &act
, NULL
);
1687 #elif defined(HAVE_SIGNAL)
1688 signal(SIGCHLD
, signal_handler
);
1692 * kqueue() is called here, select resets its internals,
1693 * all server sockets get their handlers
1696 if (0 != network_register_fdevents(srv
)) {
1700 /* might fail if user is using fam (not gamin) and famd isn't running */
1701 if (NULL
== (srv
->stat_cache
= stat_cache_init(srv
))) {
1702 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1703 "stat-cache could not be setup, dieing.");
1709 /* setup periodic timer (1 second) */
1710 struct itimerval interval
;
1711 interval
.it_interval
.tv_sec
= 1;
1712 interval
.it_interval
.tv_usec
= 0;
1713 interval
.it_value
.tv_sec
= 1;
1714 interval
.it_value
.tv_usec
= 0;
1715 if (setitimer(ITIMER_REAL
, &interval
, NULL
)) {
1716 log_error_write(srv
, __FILE__
, __LINE__
, "s", "setting timer failed");
1723 /* get the current number of FDs */
1725 int fd
= fdevent_open_devnull();
1732 if (0 != server_sockets_set_nb_cloexec(srv
)) {
1736 if (oneshot_fd
&& server_oneshot_init(srv
, oneshot_fd
)) {
1741 while (!srv_shutdown
) {
1746 if (handle_sig_hup
) {
1749 /* reset notification */
1753 /* cycle logfiles */
1755 switch(r
= plugins_call_handle_sighup(srv
)) {
1759 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "sighup-handler return with an error", r
);
1763 if (-1 == log_error_cycle(srv
)) {
1764 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cycling errorlog failed, dying");
1768 #ifdef HAVE_SIGACTION
1769 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
1770 "logfiles cycled UID =",
1771 last_sighup_info
.si_uid
,
1773 last_sighup_info
.si_pid
);
1775 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1781 if (handle_sig_alarm
) {
1785 /* reset notification */
1786 handle_sig_alarm
= 0;
1789 /* get current time */
1790 min_ts
= time(NULL
);
1792 if (min_ts
!= srv
->cur_ts
) {
1793 #ifdef DEBUG_CONNECTION_STATES
1796 connections
*conns
= srv
->conns
;
1799 switch(r
= plugins_call_handle_trigger(srv
)) {
1803 log_error_write(srv
, __FILE__
, __LINE__
, "s", "one of the triggers failed");
1806 log_error_write(srv
, __FILE__
, __LINE__
, "d", r
);
1810 srv
->cur_ts
= min_ts
;
1812 /* check idle time limit, if enabled */
1813 if (idle_limit
&& idle_limit
< min_ts
- last_active_ts
&& !graceful_shutdown
) {
1814 log_error_write(srv
, __FILE__
, __LINE__
, "sDs", "[note] idle timeout", (int)idle_limit
,
1815 "s exceeded, initiating graceful shutdown");
1816 graceful_shutdown
= 2; /* value 2 indicates idle timeout */
1817 if (graceful_restart
) {
1818 graceful_restart
= 0;
1819 if (pid_fd
< -2) pid_fd
= -pid_fd
;
1820 server_sockets_close(srv
);
1824 #ifdef HAVE_GETLOADAVG
1825 /* refresh loadavg data every 30 seconds */
1826 if (srv
->srvconf
.loadts
+ 30 < min_ts
) {
1827 if (-1 != getloadavg(srv
->srvconf
.loadavg
, 3)) {
1828 srv
->srvconf
.loadts
= min_ts
;
1833 /* cleanup stat-cache */
1834 stat_cache_trigger_cleanup(srv
);
1835 /* reset global/aggregate rate limit counters */
1836 for (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 (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
);
1932 #if DEBUG_CONNECTION_STATES
1934 fprintf(stderr
, "connection-state: ");
1938 fprintf(stderr
, "c[%d,%d]: %s ",
1941 connection_get_state(con
->state
));
1945 #ifdef DEBUG_CONNECTION_STATES
1946 if (cs
== 1) fprintf(stderr
, "\n");
1951 if (handle_sig_child
) {
1953 handle_sig_child
= 0;
1956 pid
= waitpid(-1, &status
, WNOHANG
);
1958 if (plugins_call_handle_waitpid(srv
, pid
, status
) != HANDLER_GO_ON
) {
1961 if (0 == srv
->srvconf
.max_worker
) {
1962 /* check piped-loggers and restart, even if shutting down */
1963 if (fdevent_waitpid_logger_pipe_pid(pid
, srv
->cur_ts
)) {
1968 } while (pid
> 0 || (-1 == pid
&& errno
== EINTR
));
1971 if (graceful_shutdown
) {
1972 server_graceful_state(srv
);
1973 srv
->sockets_disabled
= 1;
1974 } else if (srv
->sockets_disabled
) {
1975 /* our server sockets are disabled, why ? */
1977 if ((srv
->cur_fds
+ srv
->want_fds
< srv
->max_fds
* 8 / 10) && /* we have enough unused fds */
1978 (srv
->conns
->used
<= srv
->max_conns
* 9 / 10)) {
1979 server_sockets_set_event(srv
, FDEVENT_IN
);
1980 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets enabled again");
1982 srv
->sockets_disabled
= 0;
1985 if ((srv
->cur_fds
+ srv
->want_fds
> srv
->max_fds
* 9 / 10) || /* out of fds */
1986 (srv
->conns
->used
>= srv
->max_conns
)) { /* out of connections */
1987 /* disable server-fds */
1988 server_sockets_set_event(srv
, 0);
1990 if (srv
->conns
->used
>= srv
->max_conns
) {
1991 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets disabled, connection limit reached");
1993 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets disabled, out-of-fds");
1996 srv
->sockets_disabled
= 1;
2000 if (graceful_shutdown
&& srv
->conns
->used
== 0) {
2001 /* we are in graceful shutdown phase and all connections are closed
2002 * we are ready to terminate without harming anyone */
2007 /* we still have some fds to share */
2008 if (srv
->want_fds
) {
2009 /* check the fdwaitqueue for waiting fds */
2010 int free_fds
= srv
->max_fds
- srv
->cur_fds
- 16;
2013 for (; free_fds
> 0 && NULL
!= (con
= fdwaitqueue_unshift(srv
, srv
->fdwaitqueue
)); free_fds
--) {
2014 connection_state_machine(srv
, con
);
2020 if ((n
= fdevent_poll(srv
->ev
, 1000)) > 0) {
2021 /* n is the number of events */
2025 last_active_ts
= srv
->cur_ts
;
2028 fdevent_handler handler
;
2031 fd_ndx
= fdevent_event_next_fdndx (srv
->ev
, fd_ndx
);
2032 if (-1 == fd_ndx
) break; /* not all fdevent handlers know how many fds got an event */
2034 revents
= fdevent_event_get_revent (srv
->ev
, fd_ndx
);
2035 fd
= fdevent_event_get_fd (srv
->ev
, fd_ndx
);
2036 handler
= fdevent_get_handler(srv
->ev
, fd
);
2037 context
= fdevent_get_context(srv
->ev
, fd
);
2038 if (NULL
!= handler
) {
2039 (*handler
)(srv
, context
, revents
);
2042 } else if (n
< 0 && errno
!= EINTR
) {
2043 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2044 "fdevent_poll failed:",
2048 if (n
>= 0) fdevent_sched_run(srv
, srv
->ev
);
2050 for (ndx
= 0; ndx
< srv
->joblist
->used
; ndx
++) {
2051 connection
*con
= srv
->joblist
->ptr
[ndx
];
2052 connection_state_machine(srv
, con
);
2055 srv
->joblist
->used
= 0;
2058 if (graceful_shutdown
|| graceful_restart
) {
2059 server_graceful_state(srv
);
2062 if (2 == graceful_shutdown
) { /* value 2 indicates idle timeout */
2063 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2064 "server stopped after idle timeout");
2066 #ifdef HAVE_SIGACTION
2067 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2068 "server stopped by UID =",
2069 last_sigterm_info
.si_uid
,
2071 last_sigterm_info
.si_pid
);
2073 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2081 int main (int argc
, char **argv
) {
2085 #ifndef HAVE_ISSETUGID
2086 #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2088 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2090 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2095 /* for nice %b handling in strftime() */
2096 setlocale(LC_TIME
, "C");
2099 server
* const srv
= server_init();
2101 if (graceful_restart
) {
2102 server_sockets_restore(srv
);
2106 rc
= server_main(srv
, argc
, argv
);
2109 remove_pid_file(srv
);
2110 log_error_close(srv
);
2111 fdevent_close_logger_pipes();
2112 if (graceful_restart
)
2113 server_sockets_save(srv
);
2116 connections_free(srv
);
2120 if (0 != rc
|| !graceful_restart
) break;
2122 /* wait for all children to exit before graceful restart */
2123 while (waitpid(-1, NULL
, 0) > 0) ;
2124 } while (graceful_restart
);