12 #include "http_auth.h"
13 #include "http_chunk.h"
14 #include "http_vhostdb.h"
16 #include "connections.h"
17 #include "stat_cache.h"
20 #include "network_backends.h"
22 #ifdef HAVE_VERSIONSTAMP_H
23 # include "versionstamp.h"
25 # define REPO_VERSION ""
28 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
30 #include <sys/types.h>
50 #ifdef HAVE_VALGRIND_VALGRIND_H
51 # include <valgrind/valgrind.h>
54 #ifdef HAVE_SYS_WAIT_H
55 # include <sys/wait.h>
67 #ifdef HAVE_SYS_RESOURCE_H
68 # include <sys/resource.h>
71 #ifdef HAVE_SYS_PRCTL_H
72 # include <sys/prctl.h>
75 #if defined HAVE_LIBSSL && defined HAVE_OPENSSL_SSL_H
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
= -1;
89 static server_socket_array graceful_sockets
;
90 static volatile sig_atomic_t graceful_restart
= 0;
91 static volatile sig_atomic_t graceful_shutdown
= 0;
92 static volatile sig_atomic_t srv_shutdown
= 0;
93 static volatile sig_atomic_t handle_sig_alarm
= 1;
94 static volatile sig_atomic_t handle_sig_hup
= 0;
95 static volatile sig_atomic_t forwarded_sig_hup
= 0;
97 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
98 static volatile siginfo_t last_sigterm_info
;
99 static volatile siginfo_t last_sighup_info
;
101 static void sigaction_handler(int sig
, siginfo_t
*si
, void *context
) {
102 static siginfo_t empty_siginfo
;
105 if (!si
) si
= &empty_siginfo
;
110 last_sigterm_info
= *si
;
113 if (!graceful_shutdown
) {
114 graceful_restart
= 1;
115 graceful_shutdown
= 1;
116 last_sigterm_info
= *si
;
120 if (graceful_shutdown
) {
121 if (2 == graceful_restart
)
122 graceful_restart
= 1;
126 graceful_shutdown
= 1;
128 last_sigterm_info
= *si
;
132 handle_sig_alarm
= 1;
136 * we send the SIGHUP to all procs in the process-group
137 * this includes ourself
139 * make sure we only send it once and don't create a
142 if (!forwarded_sig_hup
) {
144 last_sighup_info
= *si
;
146 forwarded_sig_hup
= 0;
153 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
154 static void signal_handler(int sig
) {
156 case SIGTERM
: srv_shutdown
= 1; break;
158 if (graceful_shutdown
) {
159 if (2 == graceful_restart
)
160 graceful_restart
= 1;
164 graceful_shutdown
= 1;
167 case SIGALRM
: handle_sig_alarm
= 1; break;
168 case SIGHUP
: handle_sig_hup
= 1; break;
175 static int daemonize(void) {
179 signal(SIGTTOU
, SIG_IGN
);
182 signal(SIGTTIN
, SIG_IGN
);
185 signal(SIGTSTP
, SIG_IGN
);
188 if (pipe(pipefd
) < 0) exit(-1);
190 if (0 > (pid
= fork())) exit(-1);
197 /* parent waits for grandchild to be ready */
199 bytes
= read(pipefd
[0], &buf
, sizeof(buf
));
200 } while (bytes
< 0 && EINTR
== errno
);
204 /* closed fd (without writing) == failure in grandchild */
205 fputs("daemonized server failed to start; check error log for details\n", stderr
);
214 if (-1 == setsid()) exit(0);
216 signal(SIGHUP
, SIG_IGN
);
218 if (0 != fork()) exit(0);
220 if (0 != chdir("/")) exit(0);
222 fdevent_setfd_cloexec(pipefd
[1]);
227 static server
*server_init(void) {
229 server
*srv
= calloc(1, sizeof(*srv
));
232 srv->x = buffer_init();
234 CLEAN(response_header
);
235 CLEAN(parse_full_path
);
239 CLEAN(response_range
);
241 srv
->empty_string
= buffer_init_string("");
242 CLEAN(cond_check_buf
);
244 CLEAN(srvconf
.errorlog_file
);
245 CLEAN(srvconf
.breakagelog_file
);
246 CLEAN(srvconf
.groupname
);
247 CLEAN(srvconf
.username
);
248 CLEAN(srvconf
.changeroot
);
249 CLEAN(srvconf
.bindhost
);
250 CLEAN(srvconf
.event_handler
);
251 CLEAN(srvconf
.pid_file
);
252 CLEAN(srvconf
.syslog_facility
);
254 CLEAN(tmp_chunk_len
);
258 srv->x = array_init();
260 CLEAN(config_context
);
261 CLEAN(config_touched
);
265 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
266 srv
->mtime_cache
[i
].mtime
= (time_t)-1;
267 srv
->mtime_cache
[i
].str
= buffer_init();
272 srv
->cur_ts
= time(NULL
);
273 srv
->startup_ts
= srv
->cur_ts
;
275 srv
->conns
= calloc(1, sizeof(*srv
->conns
));
276 force_assert(srv
->conns
);
278 srv
->joblist
= calloc(1, sizeof(*srv
->joblist
));
279 force_assert(srv
->joblist
);
281 srv
->fdwaitqueue
= calloc(1, sizeof(*srv
->fdwaitqueue
));
282 force_assert(srv
->fdwaitqueue
);
284 srv
->srvconf
.modules
= array_init();
285 srv
->srvconf
.modules_dir
= buffer_init_string(LIBRARY_DIR
);
286 srv
->srvconf
.network_backend
= buffer_init();
287 srv
->srvconf
.upload_tempdirs
= array_init();
288 srv
->srvconf
.reject_expect_100_with_417
= 1;
289 srv
->srvconf
.xattr_name
= buffer_init_string("Content-Type");
290 srv
->srvconf
.http_header_strict
= 1;
291 srv
->srvconf
.http_host_strict
= 1; /*(implies http_host_normalize)*/
292 srv
->srvconf
.http_host_normalize
= 0;
293 srv
->srvconf
.high_precision_timestamps
= 0;
294 srv
->srvconf
.max_request_field_size
= 8192;
295 srv
->srvconf
.loadavg
[0] = 0.0;
296 srv
->srvconf
.loadavg
[1] = 0.0;
297 srv
->srvconf
.loadavg
[2] = 0.0;
300 srv
->errorlog_fd
= STDERR_FILENO
;
301 srv
->errorlog_mode
= ERRORLOG_FD
;
303 srv
->split_vals
= array_init();
304 srv
->request_env
= plugins_call_handle_request_env
;
309 static void server_free(server
*srv
) {
312 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
313 buffer_free(srv
->mtime_cache
[i
].str
);
316 if (oneshot_fd
> 0) {
323 CLEAN(response_header
);
324 CLEAN(parse_full_path
);
328 CLEAN(response_range
);
331 CLEAN(cond_check_buf
);
333 CLEAN(srvconf
.errorlog_file
);
334 CLEAN(srvconf
.breakagelog_file
);
335 CLEAN(srvconf
.groupname
);
336 CLEAN(srvconf
.username
);
337 CLEAN(srvconf
.changeroot
);
338 CLEAN(srvconf
.bindhost
);
339 CLEAN(srvconf
.event_handler
);
340 CLEAN(srvconf
.pid_file
);
341 CLEAN(srvconf
.modules_dir
);
342 CLEAN(srvconf
.network_backend
);
343 CLEAN(srvconf
.xattr_name
);
344 CLEAN(srvconf
.syslog_facility
);
346 CLEAN(tmp_chunk_len
);
350 fdevent_unregister(srv
->ev
, srv
->fd
);
352 fdevent_free(srv
->ev
);
356 if (srv
->config_storage
) {
357 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
358 specific_config
*s
= srv
->config_storage
[i
];
362 buffer_free(s
->document_root
);
363 buffer_free(s
->server_name
);
364 buffer_free(s
->server_tag
);
365 buffer_free(s
->error_handler
);
366 buffer_free(s
->error_handler_404
);
367 buffer_free(s
->errorfile_prefix
);
368 buffer_free(s
->socket_perms
);
369 array_free(s
->mimetypes
);
372 free(srv
->config_storage
);
373 srv
->config_storage
= NULL
;
379 CLEAN(config_context
);
380 CLEAN(config_touched
);
382 CLEAN(srvconf
.upload_tempdirs
);
385 joblist_free(srv
, srv
->joblist
);
386 fdwaitqueue_free(srv
, srv
->fdwaitqueue
);
388 if (srv
->stat_cache
) {
389 stat_cache_free(srv
->stat_cache
);
392 array_free(srv
->srvconf
.modules
);
393 array_free(srv
->split_vals
);
400 static void remove_pid_file(server
*srv
) {
401 if (pid_fd
< -2) return;
402 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) && 0 <= pid_fd
) {
403 if (0 != ftruncate(pid_fd
, 0)) {
404 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
405 "ftruncate failed for:",
406 srv
->srvconf
.pid_file
,
415 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) &&
416 buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
417 if (0 != unlink(srv
->srvconf
.pid_file
->ptr
)) {
418 if (errno
!= EACCES
&& errno
!= EPERM
) {
419 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
420 "unlink failed for:",
421 srv
->srvconf
.pid_file
,
430 static server_socket
* server_oneshot_getsock(server
*srv
, sock_addr
*cnt_addr
) {
431 server_socket
*srv_socket
, *srv_socket_wild
= NULL
;
433 for (i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
434 srv_socket
= srv
->srv_sockets
.ptr
[i
];
435 if (cnt_addr
->plain
.sa_family
!= srv_socket
->addr
.plain
.sa_family
) continue;
436 switch (cnt_addr
->plain
.sa_family
) {
438 if (srv_socket
->addr
.ipv4
.sin_port
!= cnt_addr
->ipv4
.sin_port
) continue;
439 if (srv_socket
->addr
.ipv4
.sin_addr
.s_addr
== cnt_addr
->ipv4
.sin_addr
.s_addr
) {
442 if (srv_socket
->addr
.ipv4
.sin_addr
.s_addr
== htonl(INADDR_ANY
)) {
443 srv_socket_wild
= srv_socket
;
448 if (srv_socket
->addr
.ipv6
.sin6_port
!= cnt_addr
->ipv6
.sin6_port
) continue;
449 if (0 == memcmp(&srv_socket
->addr
.ipv6
.sin6_addr
, &cnt_addr
->ipv6
.sin6_addr
, sizeof(struct in6_addr
))) {
452 if (0 == memcmp(&srv_socket
->addr
.ipv6
.sin6_addr
, &in6addr_any
, sizeof(struct in6_addr
))) {
453 srv_socket_wild
= srv_socket
;
459 if (0 == strcmp(srv_socket
->addr
.un
.sun_path
, cnt_addr
->un
.sun_path
)) {
468 if (NULL
!= srv_socket_wild
) {
469 return srv_socket_wild
;
470 } else if (srv
->srv_sockets
.used
) {
471 return srv
->srv_sockets
.ptr
[0];
473 log_error_write(srv
, __FILE__
, __LINE__
, "s", "no sockets configured");
479 static int server_oneshot_init(server
*srv
, int fd
) {
480 /* Note: does not work with netcat due to requirement that fd be socket.
481 * STDOUT_FILENO was not saved earlier in startup, and that is to where
482 * netcat expects output to be sent. Since lighttpd expects connections
483 * to be sockets, con->fd is where output is sent; separate fds are not
484 * stored for input and output, but netcat has different fds for stdin
485 * and * stdout. To support netcat, would additionally need to avoid
486 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
487 * addresses from environment variables:
488 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
489 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
493 server_socket
*srv_socket
;
498 if (0 != fstat(fd
, &st
)) {
499 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fstat:", strerror(errno
));
503 if (!S_ISSOCK(st
.st_mode
)) {
504 /* require that fd is a socket
505 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
506 log_error_write(srv
, __FILE__
, __LINE__
, "s", "lighttpd -1 stdin is not a socket");
510 cnt_len
= sizeof(cnt_addr
);
511 if (0 != getsockname(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
512 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getsockname:", strerror(errno
));
516 srv_socket
= server_oneshot_getsock(srv
, &cnt_addr
);
517 if (NULL
== srv_socket
) return 0;
519 cnt_len
= sizeof(cnt_addr
);
520 if (0 != getpeername(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
521 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getpeername:", strerror(errno
));
525 if (cnt_addr
.plain
.sa_family
!= AF_UNIX
) {
526 network_accept_tcp_nagle_disable(fd
);
529 con
= connection_accepted(srv
, srv_socket
, &cnt_addr
, fd
);
530 if (NULL
== con
) return 0;
532 connection_state_machine(srv
, con
);
537 static void show_version (void) {
538 char *b
= PACKAGE_DESC TEXT_SSL \
539 " - a light and fast webserver\n" \
540 "Build-Date: " __DATE__
" " __TIME__
"\n";
542 write_all(STDOUT_FILENO
, b
, strlen(b
));
545 static void show_features (void) {
546 const char features
[] = ""
548 "\t+ select (generic)\n"
550 "\t- select (generic)\n"
557 #ifdef USE_LINUX_EPOLL
558 "\t+ epoll (Linux 2.6)\n"
560 "\t- epoll (Linux 2.6)\n"
562 #ifdef USE_SOLARIS_DEVPOLL
563 "\t+ /dev/poll (Solaris)\n"
565 "\t- /dev/poll (Solaris)\n"
567 #ifdef USE_SOLARIS_PORT
568 "\t+ eventports (Solaris)\n"
570 "\t- eventports (Solaris)\n"
572 #ifdef USE_FREEBSD_KQUEUE
573 "\t+ kqueue (FreeBSD)\n"
575 "\t- kqueue (FreeBSD)\n"
578 "\t+ libev (generic)\n"
580 "\t- libev (generic)\n"
582 "\nNetwork handler:\n\n"
583 #if defined USE_LINUX_SENDFILE
584 "\t+ linux-sendfile\n"
586 "\t- linux-sendfile\n"
588 #if defined USE_FREEBSD_SENDFILE
589 "\t+ freebsd-sendfile\n"
591 "\t- freebsd-sendfile\n"
593 #if defined USE_DARWIN_SENDFILE
594 "\t+ darwin-sendfile\n"
596 "\t- darwin-sendfile\n"
598 #if defined USE_SOLARIS_SENDFILEV
599 "\t+ solaris-sendfilev\n"
601 "\t- solaris-sendfilev\n"
603 #if defined USE_WRITEV
620 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
625 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
626 "\t+ bzip2 support\n"
628 "\t- bzip2 support\n"
630 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
631 "\t+ crypt support\n"
633 "\t- crypt support\n"
646 "\t+ MySQL support\n"
648 "\t- MySQL support\n"
651 "\t+ PgSQL support\n"
653 "\t- PgSQL support\n"
661 "\t+ Kerberos support\n"
663 "\t- Kerberos support\n"
665 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
671 "\t+ memcached support\n"
673 "\t- memcached support\n"
690 #ifdef HAVE_SQLITE3_H
691 "\t+ SQLite support\n"
693 "\t- SQLite support\n"
702 printf("\nEvent Handlers:\n\n%s", features
);
705 static void show_help (void) {
706 char *b
= PACKAGE_DESC TEXT_SSL
" ("__DATE__
" " __TIME__
")" \
707 " - a light and fast webserver\n" \
709 " -f <name> filename of the config-file\n" \
710 " -m <name> module directory (default: "LIBRARY_DIR
")\n" \
711 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
712 " -1 process single (one) request on stdin socket, then exit\n" \
713 " -p print the parsed config-file in internal form, and exit\n" \
714 " -t test config-file syntax, then exit\n" \
715 " -tt test config-file syntax, load and init modules, then exit\n" \
716 " -D don't go to background (default: go to background)\n" \
717 " -v show version\n" \
718 " -V show compile-time features\n" \
719 " -h show this help\n" \
722 write_all(STDOUT_FILENO
, b
, strlen(b
));
728 * we have 4 possibilities:
736 static int log_error_open(server
*srv
) {
739 /* perhaps someone wants to use syslog() */
741 if (!buffer_string_is_empty(srv
->srvconf
.syslog_facility
)) {
742 static const struct facility_name_st
{
745 } facility_names
[] = {
748 ,{ "authpriv", LOG_AUTHPRIV
}
751 ,{ "cron", LOG_CRON
}
753 ,{ "daemon", LOG_DAEMON
}
758 ,{ "kern", LOG_KERN
}
764 ,{ "mail", LOG_MAIL
}
767 ,{ "news", LOG_NEWS
}
769 ,{ "security", LOG_AUTH
} /* DEPRECATED */
771 ,{ "syslog", LOG_SYSLOG
}
774 ,{ "user", LOG_USER
}
777 ,{ "uucp", LOG_UUCP
}
779 ,{ "local0", LOG_LOCAL0
}
780 ,{ "local1", LOG_LOCAL1
}
781 ,{ "local2", LOG_LOCAL2
}
782 ,{ "local3", LOG_LOCAL3
}
783 ,{ "local4", LOG_LOCAL4
}
784 ,{ "local5", LOG_LOCAL5
}
785 ,{ "local6", LOG_LOCAL6
}
786 ,{ "local7", LOG_LOCAL7
}
789 for (i
= 0; i
< sizeof(facility_names
)/sizeof(facility_names
[0]); ++i
) {
790 const struct facility_name_st
*f
= facility_names
+i
;
791 if (0 == strcmp(srv
->srvconf
.syslog_facility
->ptr
, f
->name
)) {
796 if (-1 == facility
) {
797 log_error_write(srv
, __FILE__
, __LINE__
, "SBS",
798 "unrecognized server.syslog-facility: \"",
799 srv
->srvconf
.syslog_facility
,
800 "\"; defaulting to \"daemon\" facility");
803 openlog("lighttpd", LOG_CONS
|LOG_PID
, -1==facility
? LOG_DAEMON
: facility
);
806 srv
->errorlog_mode
= ERRORLOG_FD
;
807 srv
->errorlog_fd
= STDERR_FILENO
;
809 if (srv
->srvconf
.errorlog_use_syslog
) {
810 srv
->errorlog_mode
= ERRORLOG_SYSLOG
;
812 else if (!buffer_string_is_empty(srv
->srvconf
.errorlog_file
)) {
813 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
815 if (-1 == (srv
->errorlog_fd
= fdevent_open_logger(logfile
))) {
816 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
817 "opening errorlog '", logfile
,
818 "' failed: ", strerror(errno
));
821 srv
->errorlog_mode
= logfile
[0] == '|' ? ERRORLOG_PIPE
: ERRORLOG_FILE
;
824 if (srv
->errorlog_mode
== ERRORLOG_FD
&& !srv
->srvconf
.dont_daemonize
) {
825 /* We can only log to stderr in dont-daemonize mode;
826 * if we do daemonize and no errorlog file is specified,
827 * we log into /dev/null
829 srv
->errorlog_fd
= -1;
832 if (!buffer_string_is_empty(srv
->srvconf
.breakagelog_file
)) {
833 const char *logfile
= srv
->srvconf
.breakagelog_file
->ptr
;
835 if (srv
->errorlog_mode
== ERRORLOG_FD
) {
836 srv
->errorlog_fd
= dup(STDERR_FILENO
);
837 fdevent_setfd_cloexec(srv
->errorlog_fd
);
840 if (-1 == (errfd
= fdevent_open_logger(logfile
))) {
841 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
842 "opening errorlog '", logfile
,
843 "' failed: ", strerror(errno
));
847 else if (!srv
->srvconf
.dont_daemonize
) {
848 /* move STDERR_FILENO to /dev/null */
849 if (-1 == (errfd
= fdevent_open_devnull())) {
850 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
851 "opening /dev/null failed:", strerror(errno
));
856 /*(leave STDERR_FILENO as-is)*/
860 if (0 != fdevent_set_stdin_stdout_stderr(-1, -1, errfd
)) {
861 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
862 "setting stderr failed:", strerror(errno
));
864 if (-1 != errfd
) close(errfd
);
869 if (-1 != errfd
) close(errfd
);
880 static int log_error_cycle(server
*srv
) {
881 /* cycle only if the error log is a file */
883 if (srv
->errorlog_mode
== ERRORLOG_FILE
) {
884 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
887 if (-1 == (new_fd
= fdevent_open_logger(logfile
))) {
888 /* write to old log */
889 log_error_write(srv
, __FILE__
, __LINE__
, "SSSSS",
890 "cycling errorlog '", logfile
,
891 "' failed: ", strerror(errno
),
892 ", falling back to syslog()");
894 close(srv
->errorlog_fd
);
895 srv
->errorlog_fd
= -1;
897 srv
->errorlog_mode
= ERRORLOG_SYSLOG
;
901 /* ok, new log is open, close the old one */
902 close(srv
->errorlog_fd
);
903 srv
->errorlog_fd
= new_fd
;
904 fdevent_setfd_cloexec(srv
->errorlog_fd
);
911 static int log_error_close(server
*srv
) {
912 switch(srv
->errorlog_mode
) {
916 if (-1 != srv
->errorlog_fd
) {
917 /* don't close STDERR */
918 if (STDERR_FILENO
!= srv
->errorlog_fd
)
919 close(srv
->errorlog_fd
);
920 srv
->errorlog_fd
= -1;
923 case ERRORLOG_SYSLOG
:
933 static void server_sockets_save (server
*srv
) { /* graceful_restart */
934 memcpy(&graceful_sockets
, &srv
->srv_sockets
, sizeof(server_socket_array
));
935 memset(&srv
->srv_sockets
, 0, sizeof(server_socket_array
));
938 static void server_sockets_restore (server
*srv
) { /* graceful_restart */
939 memcpy(&srv
->srv_sockets
, &graceful_sockets
, sizeof(server_socket_array
));
940 memset(&graceful_sockets
, 0, sizeof(server_socket_array
));
943 static int server_sockets_set_nb_cloexec (server
*srv
) {
944 if (srv
->sockets_disabled
) return 0; /* lighttpd -1 (one-shot mode) */
945 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
946 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
947 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv
->ev
, srv_socket
->fd
)) {
948 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
949 "fcntl failed:", strerror(errno
));
956 static void server_sockets_set_event (server
*srv
, int event
) {
957 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
958 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
959 fdevent_event_set(srv
->ev
,&(srv_socket
->fde_ndx
),srv_socket
->fd
,event
);
963 static void server_sockets_unregister (server
*srv
) {
964 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
)
965 network_unregister_sock(srv
, srv
->srv_sockets
.ptr
[i
]);
968 static void server_sockets_close (server
*srv
) {
969 /* closing socket right away will make it possible for the next lighttpd
970 * to take over (old-style graceful restart), but only if backends
971 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
972 * than started by lighttpd via "bin-path")
974 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
975 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
976 if (-1 == srv_socket
->fd
) continue;
977 network_unregister_sock(srv
, srv_socket
);
978 close(srv_socket
->fd
);
980 /* network_close() will cleanup after us */
984 static void server_graceful_shutdown_maint (server
*srv
) {
985 connections
*conns
= srv
->conns
;
986 for (size_t ndx
= 0; ndx
< conns
->used
; ++ndx
) {
987 connection
* const con
= conns
->ptr
[ndx
];
990 if (con
->state
== CON_STATE_CLOSE
) {
991 /* reduce remaining linger timeout to be
992 * (from zero) *up to* one more second, but no more */
993 if (HTTP_LINGER_TIMEOUT
> 1)
994 con
->close_timeout_ts
-= (HTTP_LINGER_TIMEOUT
- 1);
995 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
)
998 else if (con
->state
== CON_STATE_READ
&& con
->request_count
> 1
999 && chunkqueue_is_empty(con
->read_queue
)) {
1000 /* close connections in keep-alive waiting for next request */
1001 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1005 con
->keep_alive
= 0; /* disable keep-alive */
1007 con
->conf
.kbytes_per_second
= 0; /* disable rate limit */
1008 con
->conf
.global_kbytes_per_second
= 0; /* disable rate limit */
1009 if (con
->traffic_limit_reached
) {
1010 con
->traffic_limit_reached
= 0;
1015 connection_state_machine(srv
, con
);
1020 static void server_graceful_state (server
*srv
) {
1022 if (!srv_shutdown
) server_graceful_shutdown_maint(srv
);
1025 if (0==srv
->srv_sockets
.used
|| -1 == srv
->srv_sockets
.ptr
[0]->fde_ndx
)
1029 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1030 "[note] graceful shutdown started");
1032 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
1033 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)
1034 || oneshot_fd
|| 2 == graceful_shutdown
)
1035 graceful_restart
= 0;
1037 if (graceful_restart
) {
1038 server_sockets_unregister(srv
);
1039 if (pid_fd
> 0) pid_fd
= -pid_fd
; /*(flag to skip removing pid file)*/
1042 server_sockets_close(srv
);
1043 remove_pid_file(srv
);
1044 buffer_reset(srv
->srvconf
.pid_file
); /*(prevent more removal attempts)*/
1048 static int server_main (server
* const srv
, int argc
, char **argv
) {
1049 int print_config
= 0;
1050 int test_config
= 0;
1057 time_t idle_limit
= 0, last_active_ts
= time(NULL
);
1058 #ifdef HAVE_SIGACTION
1059 struct sigaction act
;
1063 int parent_pipe_fd
= -1;
1067 i_am_root
= (0 == getuid());
1070 /* initialize globals (including file-scoped static globals) */
1073 graceful_shutdown
= 0;
1074 handle_sig_alarm
= 1;
1076 forwarded_sig_hup
= 0;
1077 chunkqueue_set_tempdirs_default_reset();
1078 http_auth_dumbdata_reset();
1079 http_vhostdb_dumbdata_reset();
1080 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1081 /*(intentionally preserved)*/
1082 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1085 srv
->srvconf
.port
= 0;
1086 srv
->srvconf
.dont_daemonize
= 0;
1087 srv
->srvconf
.preflight_check
= 0;
1089 while(-1 != (o
= getopt(argc
, argv
, "f:m:i:hvVD1pt"))) {
1092 if (srv
->config_storage
) {
1093 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1094 "Can only read one config file. Use the include command to use multiple config files.");
1097 if (config_read(srv
, optarg
)) {
1102 buffer_copy_string(srv
->srvconf
.modules_dir
, optarg
);
1106 long timeout
= strtol(optarg
, &endptr
, 0);
1107 if (!*optarg
|| *endptr
|| timeout
< 0) {
1108 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1109 "Invalid idle timeout value:", optarg
);
1112 idle_limit
= (time_t)timeout
;
1115 case 'p': print_config
= 1; break;
1116 case 't': ++test_config
; break;
1117 case '1': if (0 == oneshot_fd
) oneshot_fd
= dup(STDIN_FILENO
);
1119 case 'D': srv
->srvconf
.dont_daemonize
= 1; break;
1120 case 'v': show_version(); return 0;
1121 case 'V': show_features(); return 0;
1122 case 'h': show_help(); return 0;
1129 if (!srv
->config_storage
) {
1130 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1131 "No configuration available. Try using -f option.");
1136 data_unset
*dc
= srv
->config_context
->data
[0];
1139 fprintf(stdout
, "\n");
1141 /* shouldn't happend */
1142 fprintf(stderr
, "global config not found\n");
1147 if (1 == test_config
) {
1148 printf("Syntax OK\n");
1149 } else { /*(test_config > 1)*/
1151 srv
->srvconf
.preflight_check
= 1;
1152 srv
->srvconf
.dont_daemonize
= 1;
1153 buffer_reset(srv
->srvconf
.pid_file
);
1157 if (test_config
|| print_config
) {
1162 if (oneshot_fd
<= STDERR_FILENO
) {
1163 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1164 "Invalid fds at startup with lighttpd -1");
1167 graceful_shutdown
= 1;
1168 srv
->sockets_disabled
= 1;
1169 srv
->srvconf
.dont_daemonize
= 1;
1170 buffer_reset(srv
->srvconf
.pid_file
);
1171 if (srv
->srvconf
.max_worker
) {
1172 srv
->srvconf
.max_worker
= 0;
1173 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1174 "server one-shot command line option disables server.max-worker config file option.");
1178 /* close stdin and stdout, as they are not needed */
1184 devnull
= fdevent_open_devnull();
1185 } while (-1 != devnull
&& devnull
<= STDERR_FILENO
);
1186 if (-1 == devnull
) {
1187 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1188 "opening /dev/null failed:", strerror(errno
));
1191 errfd
= (0 == fstat(STDERR_FILENO
, &st
)) ? -1 : devnull
;
1192 if (0 != fdevent_set_stdin_stdout_stderr(devnull
, devnull
, errfd
)) {
1193 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1194 "setting default fds failed:", strerror(errno
));
1196 if (-1 != errfd
) close(errfd
);
1197 if (devnull
!= errfd
) close(devnull
);
1202 if (-1 != errfd
) close(errfd
);
1203 if (devnull
!= errfd
) close(devnull
);
1207 if (0 != config_set_defaults(srv
)) {
1208 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1209 "setting default values failed");
1213 /* check document-root */
1214 if (buffer_string_is_empty(srv
->config_storage
[0]->document_root
)) {
1215 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1216 "document-root is not set\n");
1220 if (plugins_load(srv
)) {
1221 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1222 "loading plugins finally failed");
1226 if (HANDLER_GO_ON
!= plugins_call_init(srv
)) {
1227 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Initialization of plugins failed. Going down.");
1231 /* open pid file BEFORE chroot */
1232 if (-1 == pid_fd
&& !buffer_string_is_empty(srv
->srvconf
.pid_file
)) {
1233 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
))) {
1235 if (errno
!= EEXIST
) {
1236 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1237 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1241 if (0 != stat(srv
->srvconf
.pid_file
->ptr
, &st
)) {
1242 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1243 "stating existing pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1246 if (!S_ISREG(st
.st_mode
)) {
1247 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1248 "pid-file exists and isn't regular file:", srv
->srvconf
.pid_file
);
1252 if (-1 == (pid_fd
= open(srv
->srvconf
.pid_file
->ptr
, O_WRONLY
| O_CREAT
| O_TRUNC
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
))) {
1253 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1254 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1260 if (srv
->event_handler
== FDEVENT_HANDLER_SELECT
) {
1261 /* select limits itself
1263 * as it is a hard limit and will lead to a segfault we add some safety
1265 srv
->max_fds
= FD_SETSIZE
- 200;
1267 srv
->max_fds
= 4096;
1271 #ifdef HAVE_GETRLIMIT
1274 #ifdef HAVE_VALGRIND_VALGRIND_H
1275 if (RUNNING_ON_VALGRIND
) use_rlimit
= 0;
1278 if (0 != getrlimit(RLIMIT_NOFILE
, &rlim
)) {
1279 log_error_write(srv
, __FILE__
, __LINE__
,
1280 "ss", "couldn't get 'max filedescriptors'",
1286 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1288 if (use_rlimit
&& srv
->srvconf
.max_fds
1289 && (i_am_root
|| srv
->srvconf
.max_fds
<= rlim
.rlim_max
)) {
1292 rlim
.rlim_cur
= srv
->srvconf
.max_fds
;
1293 if (i_am_root
) rlim
.rlim_max
= srv
->srvconf
.max_fds
;
1295 if (0 != setrlimit(RLIMIT_NOFILE
, &rlim
)) {
1296 log_error_write(srv
, __FILE__
, __LINE__
,
1297 "ss", "couldn't set 'max filedescriptors'",
1303 if (srv
->event_handler
== FDEVENT_HANDLER_SELECT
) {
1304 srv
->max_fds
= rlim
.rlim_cur
< (rlim_t
)FD_SETSIZE
- 200 ? (int)rlim
.rlim_cur
: (int)FD_SETSIZE
- 200;
1306 srv
->max_fds
= rlim
.rlim_cur
;
1307 /*(default upper limit of 4k if server.max-fds not specified)*/
1308 if (i_am_root
&& 0 == srv
->srvconf
.max_fds
&& rlim
.rlim_cur
> 4096)
1309 srv
->max_fds
= 4096;
1312 /* set core file rlimit, if enable_cores is set */
1313 if (use_rlimit
&& srv
->srvconf
.enable_cores
&& getrlimit(RLIMIT_CORE
, &rlim
) == 0) {
1314 rlim
.rlim_cur
= rlim
.rlim_max
;
1315 setrlimit(RLIMIT_CORE
, &rlim
);
1318 if (srv
->event_handler
== FDEVENT_HANDLER_SELECT
) {
1319 /* don't raise the limit above FD_SET_SIZE */
1320 if (srv
->max_fds
> ((int)FD_SETSIZE
) - 200) {
1321 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1322 "can't raise max filedescriptors above", FD_SETSIZE
- 200,
1323 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
1329 /* we need root-perms for port < 1024 */
1330 if (0 != network_init(srv
)) {
1336 /* set user and group */
1337 struct group
*grp
= NULL
;
1338 struct passwd
*pwd
= NULL
;
1340 if (!buffer_string_is_empty(srv
->srvconf
.groupname
)) {
1341 if (NULL
== (grp
= getgrnam(srv
->srvconf
.groupname
->ptr
))) {
1342 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1343 "can't find groupname", srv
->srvconf
.groupname
);
1348 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1349 if (NULL
== (pwd
= getpwnam(srv
->srvconf
.username
->ptr
))) {
1350 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1351 "can't find username", srv
->srvconf
.username
);
1355 if (pwd
->pw_uid
== 0) {
1356 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1357 "I will not set uid to 0\n");
1361 if (NULL
== grp
&& NULL
== (grp
= getgrgid(pwd
->pw_gid
))) {
1362 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1363 "can't find group id", pwd
->pw_gid
);
1369 if (grp
->gr_gid
== 0) {
1370 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1371 "I will not set gid to 0\n");
1377 * Change group before chroot, when we have access
1381 if (-1 == setgid(grp
->gr_gid
)) {
1382 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgid failed: ", strerror(errno
));
1385 if (-1 == setgroups(0, NULL
)) {
1386 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgroups failed: ", strerror(errno
));
1389 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1390 initgroups(srv
->srvconf
.username
->ptr
, grp
->gr_gid
);
1395 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
1398 if (-1 == chroot(srv
->srvconf
.changeroot
->ptr
)) {
1399 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chroot failed: ", strerror(errno
));
1402 if (-1 == chdir("/")) {
1403 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chdir failed: ", strerror(errno
));
1409 /* drop root privs */
1411 if (-1 == setuid(pwd
->pw_uid
)) {
1412 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setuid failed: ", strerror(errno
));
1417 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1419 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1421 if (srv
->srvconf
.enable_cores
) {
1422 prctl(PR_SET_DUMPABLE
, 1, 0, 0, 0);
1428 if (srv
->srvconf
.max_conns
> srv
->max_fds
/2) {
1429 /* we can't have more connections than max-fds/2 */
1430 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", "can't have more connections than fds/2: ", srv
->srvconf
.max_conns
, srv
->max_fds
);
1431 srv
->max_conns
= srv
->max_fds
/2;
1432 } else if (srv
->srvconf
.max_conns
) {
1433 /* otherwise respect the wishes of the user */
1434 srv
->max_conns
= srv
->srvconf
.max_conns
;
1436 /* or use the default: we really don't want to hit max-fds */
1437 srv
->max_conns
= srv
->max_fds
/3;
1441 /* network is up, let's daemonize ourself */
1442 if (0 == srv
->srvconf
.dont_daemonize
&& 0 == graceful_restart
) {
1443 parent_pipe_fd
= daemonize();
1446 graceful_restart
= 0;/*(reset here after avoiding further daemonizing)*/
1447 graceful_shutdown
= 0;
1450 #ifdef HAVE_SIGACTION
1451 memset(&act
, 0, sizeof(act
));
1452 act
.sa_handler
= SIG_IGN
;
1453 sigaction(SIGPIPE
, &act
, NULL
);
1454 # if defined(SA_SIGINFO)
1455 last_sighup_info
.si_uid
= 0,
1456 last_sighup_info
.si_pid
= 0;
1457 last_sigterm_info
.si_uid
= 0,
1458 last_sigterm_info
.si_pid
= 0;
1459 act
.sa_sigaction
= sigaction_handler
;
1460 sigemptyset(&act
.sa_mask
);
1461 act
.sa_flags
= SA_SIGINFO
;
1463 act
.sa_handler
= signal_handler
;
1464 sigemptyset(&act
.sa_mask
);
1467 sigaction(SIGINT
, &act
, NULL
);
1468 sigaction(SIGTERM
, &act
, NULL
);
1469 sigaction(SIGHUP
, &act
, NULL
);
1470 sigaction(SIGALRM
, &act
, NULL
);
1471 sigaction(SIGUSR1
, &act
, NULL
);
1473 /* it should be safe to restart syscalls after SIGCHLD */
1474 act
.sa_flags
|= SA_RESTART
| SA_NOCLDSTOP
;
1475 sigaction(SIGCHLD
, &act
, NULL
);
1477 #elif defined(HAVE_SIGNAL)
1478 /* ignore the SIGPIPE from sendfile() */
1479 signal(SIGPIPE
, SIG_IGN
);
1480 signal(SIGALRM
, signal_handler
);
1481 signal(SIGTERM
, signal_handler
);
1482 signal(SIGHUP
, signal_handler
);
1483 signal(SIGCHLD
, signal_handler
);
1484 signal(SIGINT
, signal_handler
);
1485 signal(SIGUSR1
, signal_handler
);
1489 srv
->gid
= getgid();
1490 srv
->uid
= getuid();
1492 /* write pid file */
1494 buffer_copy_int(srv
->tmp_buf
, getpid());
1495 buffer_append_string_len(srv
->tmp_buf
, CONST_STR_LEN("\n"));
1496 if (-1 == write_all(pid_fd
, CONST_BUF_LEN(srv
->tmp_buf
))) {
1497 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't write pid file:", strerror(errno
));
1502 } else if (pid_fd
< -2) {
1506 /* Close stderr ASAP in the child process to make sure that nothing
1507 * is being written to that fd which may not be valid anymore. */
1508 if (!srv
->srvconf
.preflight_check
) {
1509 if (-1 == log_error_open(srv
)) {
1510 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Opening errorlog failed. Going down.");
1513 log_error_write(srv
, __FILE__
, __LINE__
, "s", "server started (" PACKAGE_DESC
")");
1516 if (buffer_is_empty(srv
->config_storage
[0]->server_tag
)) {
1517 buffer_copy_string_len(srv
->config_storage
[0]->server_tag
, CONST_STR_LEN(PACKAGE_DESC
));
1520 if (HANDLER_GO_ON
!= plugins_call_set_defaults(srv
)) {
1521 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Configuration of plugins failed. Going down.");
1525 /* settings might be enabled during module config set defaults */
1526 srv
->config_storage
[0]->high_precision_timestamps
= srv
->srvconf
.high_precision_timestamps
;
1528 /* dump unused config-keys */
1529 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1530 array
*config
= ((data_config
*)srv
->config_context
->data
[i
])->value
;
1533 for (j
= 0; config
&& j
< config
->used
; j
++) {
1534 data_unset
*du
= config
->data
[j
];
1536 /* all var.* is known as user defined variable */
1537 if (strncmp(du
->key
->ptr
, "var.", sizeof("var.") - 1) == 0) {
1541 if (NULL
== array_get_element_klen(srv
->config_touched
, CONST_BUF_LEN(du
->key
))) {
1542 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1543 "WARNING: unknown config-key:",
1550 if (srv
->config_unsupported
) {
1551 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1552 "Configuration contains unsupported keys. Going down.");
1555 if (srv
->config_deprecated
) {
1556 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1557 "Configuration contains deprecated keys. Going down.");
1560 if (srv
->config_unsupported
|| srv
->config_deprecated
) {
1564 if (srv
->srvconf
.preflight_check
) {
1565 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1572 * notify daemonize-grandparent of successful startup
1573 * do this before any further forking is done (workers)
1575 if (0 == srv
->srvconf
.dont_daemonize
&& -1 != parent_pipe_fd
) {
1576 if (0 > write(parent_pipe_fd
, "", 1)) return -1;
1577 close(parent_pipe_fd
);
1580 if (idle_limit
&& srv
->srvconf
.max_worker
) {
1581 srv
->srvconf
.max_worker
= 0;
1582 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1583 "server idle time limit command line option disables server.max-worker config file option.");
1586 /* start watcher and workers */
1587 num_childs
= srv
->srvconf
.max_worker
;
1588 if (num_childs
> 0) {
1590 while (!child
&& !srv_shutdown
&& !graceful_shutdown
) {
1591 if (num_childs
> 0) {
1605 if (-1 != wait(&status
)) {
1607 * one of our workers went away
1614 * if we receive a SIGHUP we have to close our logs ourself as we don't
1615 * have the mainloop who can help us here
1617 if (handle_sig_hup
) {
1620 log_error_cycle(srv
);
1623 * forward to all procs in the process-group
1625 * we also send it ourself
1627 if (!forwarded_sig_hup
&& 0 != srv
->srvconf
.max_worker
) {
1628 forwarded_sig_hup
= 1;
1641 * for the parent this is the exit-point
1645 * kill all children too
1647 if (graceful_shutdown
|| graceful_restart
) {
1648 /* flag to ignore one SIGINT if graceful_restart */
1649 if (graceful_restart
) graceful_restart
= 2;
1651 server_graceful_state(srv
);
1652 } else if (srv_shutdown
) {
1659 /* ignore SIGUSR1 in workers; only parent directs graceful restart */
1660 #ifdef HAVE_SIGACTION
1662 struct sigaction actignore
;
1663 memset(&actignore
, 0, sizeof(actignore
));
1664 actignore
.sa_handler
= SIG_IGN
;
1665 sigaction(SIGUSR1
, &actignore
, NULL
);
1667 #elif defined(HAVE_SIGNAL)
1668 signal(SIGUSR1
, SIG_IGN
);
1672 * make sure workers do not muck with pid-file
1678 buffer_reset(srv
->srvconf
.pid_file
);
1684 if (NULL
== (srv
->ev
= fdevent_init(srv
, srv
->max_fds
+ 1, srv
->event_handler
))) {
1685 log_error_write(srv
, __FILE__
, __LINE__
,
1686 "s", "fdevent_init failed");
1690 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1691 #ifdef HAVE_SIGACTION
1692 sigaction(SIGCHLD
, &act
, NULL
);
1693 #elif defined(HAVE_SIGNAL)
1694 signal(SIGCHLD
, signal_handler
);
1698 * kqueue() is called here, select resets its internals,
1699 * all server sockets get their handlers
1702 if (0 != network_register_fdevents(srv
)) {
1706 /* might fail if user is using fam (not gamin) and famd isn't running */
1707 if (NULL
== (srv
->stat_cache
= stat_cache_init(srv
))) {
1708 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1709 "stat-cache could not be setup, dieing.");
1715 /* setup periodic timer (1 second) */
1716 struct itimerval interval
;
1717 interval
.it_interval
.tv_sec
= 1;
1718 interval
.it_interval
.tv_usec
= 0;
1719 interval
.it_value
.tv_sec
= 1;
1720 interval
.it_value
.tv_usec
= 0;
1721 if (setitimer(ITIMER_REAL
, &interval
, NULL
)) {
1722 log_error_write(srv
, __FILE__
, __LINE__
, "s", "setting timer failed");
1729 /* get the current number of FDs */
1731 int fd
= fdevent_open_devnull();
1738 if (0 != server_sockets_set_nb_cloexec(srv
)) {
1742 if (oneshot_fd
&& server_oneshot_init(srv
, oneshot_fd
)) {
1747 while (!srv_shutdown
) {
1752 if (handle_sig_hup
) {
1755 /* reset notification */
1759 /* cycle logfiles */
1761 switch(r
= plugins_call_handle_sighup(srv
)) {
1765 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "sighup-handler return with an error", r
);
1769 if (-1 == log_error_cycle(srv
)) {
1770 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cycling errorlog failed, dying");
1774 #ifdef HAVE_SIGACTION
1775 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
1776 "logfiles cycled UID =",
1777 last_sighup_info
.si_uid
,
1779 last_sighup_info
.si_pid
);
1781 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1787 if (handle_sig_alarm
) {
1791 /* reset notification */
1792 handle_sig_alarm
= 0;
1795 /* get current time */
1796 min_ts
= time(NULL
);
1798 if (min_ts
!= srv
->cur_ts
) {
1799 #ifdef DEBUG_CONNECTION_STATES
1802 connections
*conns
= srv
->conns
;
1805 switch(r
= plugins_call_handle_trigger(srv
)) {
1809 log_error_write(srv
, __FILE__
, __LINE__
, "s", "one of the triggers failed");
1812 log_error_write(srv
, __FILE__
, __LINE__
, "d", r
);
1816 /* trigger waitpid */
1817 srv
->cur_ts
= min_ts
;
1819 /* check idle time limit, if enabled */
1820 if (idle_limit
&& idle_limit
< min_ts
- last_active_ts
&& !graceful_shutdown
) {
1821 log_error_write(srv
, __FILE__
, __LINE__
, "sDs", "[note] idle timeout", (int)idle_limit
,
1822 "s exceeded, initiating graceful shutdown");
1823 graceful_shutdown
= 2; /* value 2 indicates idle timeout */
1824 if (graceful_restart
) {
1825 graceful_restart
= 0;
1826 if (pid_fd
< -2) pid_fd
= -pid_fd
;
1827 server_sockets_close(srv
);
1831 #ifdef HAVE_GETLOADAVG
1832 /* refresh loadavg data every 30 seconds */
1833 if (srv
->srvconf
.loadts
+ 30 < min_ts
) {
1834 if (-1 != getloadavg(srv
->srvconf
.loadavg
, 3)) {
1835 srv
->srvconf
.loadts
= min_ts
;
1840 /* cleanup stat-cache */
1841 stat_cache_trigger_cleanup(srv
);
1842 /* reset global/aggregate rate limit counters */
1843 for (i
= 0; i
< srv
->config_context
->used
; ++i
) {
1844 srv
->config_storage
[i
]->global_bytes_per_second_cnt
= 0;
1846 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1847 if (graceful_shutdown
&& !srv_shutdown
) server_graceful_shutdown_maint(srv
);
1849 * check all connections for timeouts
1852 for (ndx
= 0; ndx
< conns
->used
; ndx
++) {
1853 connection
* const con
= conns
->ptr
[ndx
];
1854 const int waitevents
= fdevent_event_get_interest(srv
->ev
, con
->fd
);
1858 if (con
->state
== CON_STATE_CLOSE
) {
1859 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
) {
1862 } else if (waitevents
& FDEVENT_IN
) {
1863 if (con
->request_count
== 1 || con
->state
!= CON_STATE_READ
) { /* e.g. CON_STATE_READ_POST || CON_STATE_WRITE */
1864 if (srv
->cur_ts
- con
->read_idle_ts
> con
->conf
.max_read_idle
) {
1866 if (con
->conf
.log_request_handling
) {
1867 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1868 "connection closed - read timeout:", con
->fd
);
1871 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1875 if (srv
->cur_ts
- con
->read_idle_ts
> con
->keep_alive_idle
) {
1877 if (con
->conf
.log_request_handling
) {
1878 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1879 "connection closed - keep-alive timeout:", con
->fd
);
1882 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1888 /* max_write_idle timeout currently functions as backend timeout,
1889 * too, after response has been started.
1890 * future: have separate backend timeout, and then change this
1891 * to check for write interest before checking for timeout */
1892 /*if (waitevents & FDEVENT_OUT)*/
1893 if ((con
->state
== CON_STATE_WRITE
) &&
1894 (con
->write_request_ts
!= 0)) {
1896 if (srv
->cur_ts
- con
->write_request_ts
> 60) {
1897 log_error_write(srv
, __FILE__
, __LINE__
, "sdd",
1898 "connection closed - pre-write-request-timeout:", con
->fd
, srv
->cur_ts
- con
->write_request_ts
);
1902 if (srv
->cur_ts
- con
->write_request_ts
> con
->conf
.max_write_idle
) {
1904 if (con
->conf
.log_timeouts
) {
1905 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsosds",
1906 "NOTE: a request from",
1910 "timed out after writing",
1913 (int)con
->conf
.max_write_idle
,
1914 "seconds. If this a problem increase server.max-write-idle");
1916 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1921 /* we don't like div by zero */
1922 if (0 == (t_diff
= srv
->cur_ts
- con
->connection_start
)) t_diff
= 1;
1924 if (con
->traffic_limit_reached
&&
1925 (con
->conf
.kbytes_per_second
== 0 ||
1926 ((con
->bytes_written
/ t_diff
) < con
->conf
.kbytes_per_second
* 1024))) {
1927 /* enable connection again */
1928 con
->traffic_limit_reached
= 0;
1933 con
->bytes_written_cur_second
= 0;
1936 connection_state_machine(srv
, con
);
1939 #if DEBUG_CONNECTION_STATES
1941 fprintf(stderr
, "connection-state: ");
1945 fprintf(stderr
, "c[%d,%d]: %s ",
1948 connection_get_state(con
->state
));
1952 #ifdef DEBUG_CONNECTION_STATES
1953 if (cs
== 1) fprintf(stderr
, "\n");
1958 if (graceful_shutdown
) {
1959 server_graceful_state(srv
);
1960 srv
->sockets_disabled
= 1;
1961 } else if (srv
->sockets_disabled
) {
1962 /* our server sockets are disabled, why ? */
1964 if ((srv
->cur_fds
+ srv
->want_fds
< srv
->max_fds
* 8 / 10) && /* we have enough unused fds */
1965 (srv
->conns
->used
<= srv
->max_conns
* 9 / 10)) {
1966 server_sockets_set_event(srv
, FDEVENT_IN
);
1967 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets enabled again");
1969 srv
->sockets_disabled
= 0;
1972 if ((srv
->cur_fds
+ srv
->want_fds
> srv
->max_fds
* 9 / 10) || /* out of fds */
1973 (srv
->conns
->used
>= srv
->max_conns
)) { /* out of connections */
1974 /* disable server-fds */
1975 server_sockets_set_event(srv
, 0);
1977 if (srv
->conns
->used
>= srv
->max_conns
) {
1978 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets disabled, connection limit reached");
1980 log_error_write(srv
, __FILE__
, __LINE__
, "s", "[note] sockets disabled, out-of-fds");
1983 srv
->sockets_disabled
= 1;
1987 if (graceful_shutdown
&& srv
->conns
->used
== 0) {
1988 /* we are in graceful shutdown phase and all connections are closed
1989 * we are ready to terminate without harming anyone */
1994 /* we still have some fds to share */
1995 if (srv
->want_fds
) {
1996 /* check the fdwaitqueue for waiting fds */
1997 int free_fds
= srv
->max_fds
- srv
->cur_fds
- 16;
2000 for (; free_fds
> 0 && NULL
!= (con
= fdwaitqueue_unshift(srv
, srv
->fdwaitqueue
)); free_fds
--) {
2001 connection_state_machine(srv
, con
);
2007 if ((n
= fdevent_poll(srv
->ev
, 1000)) > 0) {
2008 /* n is the number of events */
2012 last_active_ts
= srv
->cur_ts
;
2015 fdevent_handler handler
;
2018 fd_ndx
= fdevent_event_next_fdndx (srv
->ev
, fd_ndx
);
2019 if (-1 == fd_ndx
) break; /* not all fdevent handlers know how many fds got an event */
2021 revents
= fdevent_event_get_revent (srv
->ev
, fd_ndx
);
2022 fd
= fdevent_event_get_fd (srv
->ev
, fd_ndx
);
2023 handler
= fdevent_get_handler(srv
->ev
, fd
);
2024 context
= fdevent_get_context(srv
->ev
, fd
);
2025 if (NULL
!= handler
) {
2026 (*handler
)(srv
, context
, revents
);
2029 fdevent_sched_run(srv
, srv
->ev
);
2030 } else if (n
< 0 && errno
!= EINTR
) {
2031 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2032 "fdevent_poll failed:",
2036 for (ndx
= 0; ndx
< srv
->joblist
->used
; ndx
++) {
2037 connection
*con
= srv
->joblist
->ptr
[ndx
];
2038 connection_state_machine(srv
, con
);
2041 srv
->joblist
->used
= 0;
2044 if (graceful_shutdown
|| graceful_restart
) {
2045 server_graceful_state(srv
);
2048 if (2 == graceful_shutdown
) { /* value 2 indicates idle timeout */
2049 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2050 "server stopped after idle timeout");
2052 #ifdef HAVE_SIGACTION
2053 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2054 "server stopped by UID =",
2055 last_sigterm_info
.si_uid
,
2057 last_sigterm_info
.si_pid
);
2059 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2067 int main (int argc
, char **argv
) {
2071 #ifndef HAVE_ISSETUGID
2072 #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2074 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2076 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2081 /* for nice %b handling in strftime() */
2082 setlocale(LC_TIME
, "C");
2085 server
* const srv
= server_init();
2087 if (graceful_restart
) {
2088 server_sockets_restore(srv
);
2092 rc
= server_main(srv
, argc
, argv
);
2095 remove_pid_file(srv
);
2096 log_error_close(srv
);
2097 if (graceful_restart
)
2098 server_sockets_save(srv
);
2101 connections_free(srv
);
2105 if (0 != rc
|| !graceful_restart
) break;
2107 /* wait for all children to exit before graceful restart */
2108 while (waitpid(-1, NULL
, 0) > 0) ;
2109 } while (graceful_restart
);