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
= -2;
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;
96 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
97 static volatile siginfo_t last_sigterm_info
;
98 static volatile siginfo_t last_sighup_info
;
100 static void sigaction_handler(int sig
, siginfo_t
*si
, void *context
) {
101 static const siginfo_t empty_siginfo
;
104 if (!si
) *(const siginfo_t
**)&si
= &empty_siginfo
;
109 last_sigterm_info
= *si
;
112 if (!graceful_shutdown
) {
113 graceful_restart
= 1;
114 graceful_shutdown
= 1;
115 last_sigterm_info
= *si
;
119 if (graceful_shutdown
) {
120 if (2 == graceful_restart
)
121 graceful_restart
= 1;
125 graceful_shutdown
= 1;
127 last_sigterm_info
= *si
;
131 handle_sig_alarm
= 1;
135 last_sighup_info
= *si
;
141 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
142 static void signal_handler(int sig
) {
144 case SIGTERM
: srv_shutdown
= 1; break;
146 if (!graceful_shutdown
) {
147 graceful_restart
= 1;
148 graceful_shutdown
= 1;
152 if (graceful_shutdown
) {
153 if (2 == graceful_restart
)
154 graceful_restart
= 1;
158 graceful_shutdown
= 1;
161 case SIGALRM
: handle_sig_alarm
= 1; break;
162 case SIGHUP
: handle_sig_hup
= 1; break;
169 static int daemonize(void) {
173 signal(SIGTTOU
, SIG_IGN
);
176 signal(SIGTTIN
, SIG_IGN
);
179 signal(SIGTSTP
, SIG_IGN
);
182 if (pipe(pipefd
) < 0) exit(-1);
184 if (0 > (pid
= fork())) exit(-1);
191 /* parent waits for grandchild to be ready */
193 bytes
= read(pipefd
[0], &buf
, sizeof(buf
));
194 } while (bytes
< 0 && EINTR
== errno
);
198 /* closed fd (without writing) == failure in grandchild */
199 fputs("daemonized server failed to start; check error log for details\n", stderr
);
208 if (-1 == setsid()) exit(0);
210 signal(SIGHUP
, SIG_IGN
);
212 if (0 != fork()) exit(0);
214 if (0 != chdir("/")) exit(0);
216 fdevent_setfd_cloexec(pipefd
[1]);
221 static server
*server_init(void) {
223 server
*srv
= calloc(1, sizeof(*srv
));
226 srv->x = buffer_init();
228 CLEAN(response_header
);
229 CLEAN(parse_full_path
);
233 CLEAN(response_range
);
235 srv
->empty_string
= buffer_init_string("");
236 CLEAN(cond_check_buf
);
238 CLEAN(srvconf
.errorlog_file
);
239 CLEAN(srvconf
.breakagelog_file
);
240 CLEAN(srvconf
.groupname
);
241 CLEAN(srvconf
.username
);
242 CLEAN(srvconf
.changeroot
);
243 CLEAN(srvconf
.bindhost
);
244 CLEAN(srvconf
.event_handler
);
245 CLEAN(srvconf
.pid_file
);
246 CLEAN(srvconf
.syslog_facility
);
248 CLEAN(tmp_chunk_len
);
252 srv->x = array_init();
254 CLEAN(config_context
);
255 CLEAN(config_touched
);
259 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
260 srv
->mtime_cache
[i
].mtime
= (time_t)-1;
261 srv
->mtime_cache
[i
].str
= buffer_init();
266 srv
->cur_ts
= time(NULL
);
267 srv
->startup_ts
= srv
->cur_ts
;
269 srv
->conns
= calloc(1, sizeof(*srv
->conns
));
270 force_assert(srv
->conns
);
272 srv
->joblist
= calloc(1, sizeof(*srv
->joblist
));
273 force_assert(srv
->joblist
);
275 srv
->fdwaitqueue
= calloc(1, sizeof(*srv
->fdwaitqueue
));
276 force_assert(srv
->fdwaitqueue
);
278 srv
->srvconf
.modules
= array_init();
279 srv
->srvconf
.modules_dir
= buffer_init_string(LIBRARY_DIR
);
280 srv
->srvconf
.network_backend
= buffer_init();
281 srv
->srvconf
.upload_tempdirs
= array_init();
282 srv
->srvconf
.reject_expect_100_with_417
= 1;
283 srv
->srvconf
.xattr_name
= buffer_init_string("Content-Type");
284 srv
->srvconf
.http_header_strict
= 1;
285 srv
->srvconf
.http_host_strict
= 1; /*(implies http_host_normalize)*/
286 srv
->srvconf
.http_host_normalize
= 0;
287 srv
->srvconf
.high_precision_timestamps
= 0;
288 srv
->srvconf
.max_request_field_size
= 8192;
289 srv
->srvconf
.loadavg
[0] = 0.0;
290 srv
->srvconf
.loadavg
[1] = 0.0;
291 srv
->srvconf
.loadavg
[2] = 0.0;
294 srv
->errorlog_fd
= STDERR_FILENO
;
295 srv
->errorlog_mode
= ERRORLOG_FD
;
297 srv
->split_vals
= array_init();
298 srv
->request_env
= plugins_call_handle_request_env
;
303 static void server_free(server
*srv
) {
306 for (i
= 0; i
< FILE_CACHE_MAX
; i
++) {
307 buffer_free(srv
->mtime_cache
[i
].str
);
310 if (oneshot_fd
> 0) {
317 CLEAN(response_header
);
318 CLEAN(parse_full_path
);
322 CLEAN(response_range
);
325 CLEAN(cond_check_buf
);
327 CLEAN(srvconf
.errorlog_file
);
328 CLEAN(srvconf
.breakagelog_file
);
329 CLEAN(srvconf
.groupname
);
330 CLEAN(srvconf
.username
);
331 CLEAN(srvconf
.changeroot
);
332 CLEAN(srvconf
.bindhost
);
333 CLEAN(srvconf
.event_handler
);
334 CLEAN(srvconf
.pid_file
);
335 CLEAN(srvconf
.modules_dir
);
336 CLEAN(srvconf
.network_backend
);
337 CLEAN(srvconf
.xattr_name
);
338 CLEAN(srvconf
.syslog_facility
);
340 CLEAN(tmp_chunk_len
);
344 fdevent_unregister(srv
->ev
, srv
->fd
);
346 fdevent_free(srv
->ev
);
350 if (srv
->config_storage
) {
351 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
352 specific_config
*s
= srv
->config_storage
[i
];
356 buffer_free(s
->document_root
);
357 buffer_free(s
->server_name
);
358 buffer_free(s
->server_tag
);
359 buffer_free(s
->error_handler
);
360 buffer_free(s
->error_handler_404
);
361 buffer_free(s
->errorfile_prefix
);
362 buffer_free(s
->socket_perms
);
363 array_free(s
->mimetypes
);
366 free(srv
->config_storage
);
367 srv
->config_storage
= NULL
;
373 CLEAN(config_context
);
374 CLEAN(config_touched
);
376 CLEAN(srvconf
.upload_tempdirs
);
379 joblist_free(srv
, srv
->joblist
);
380 fdwaitqueue_free(srv
, srv
->fdwaitqueue
);
382 if (srv
->stat_cache
) {
383 stat_cache_free(srv
->stat_cache
);
386 array_free(srv
->srvconf
.modules
);
387 array_free(srv
->split_vals
);
394 static void remove_pid_file(server
*srv
) {
395 if (pid_fd
<= -2) return;
396 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) && 0 <= pid_fd
) {
397 if (0 != ftruncate(pid_fd
, 0)) {
398 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
399 "ftruncate failed for:",
400 srv
->srvconf
.pid_file
,
409 if (!buffer_string_is_empty(srv
->srvconf
.pid_file
) &&
410 buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
411 if (0 != unlink(srv
->srvconf
.pid_file
->ptr
)) {
412 if (errno
!= EACCES
&& errno
!= EPERM
) {
413 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
414 "unlink failed for:",
415 srv
->srvconf
.pid_file
,
424 static server_socket
* server_oneshot_getsock(server
*srv
, sock_addr
*cnt_addr
) {
425 server_socket
*srv_socket
, *srv_socket_wild
= NULL
;
427 for (i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
428 srv_socket
= srv
->srv_sockets
.ptr
[i
];
429 if (cnt_addr
->plain
.sa_family
!= srv_socket
->addr
.plain
.sa_family
) continue;
430 switch (cnt_addr
->plain
.sa_family
) {
432 if (srv_socket
->addr
.ipv4
.sin_port
!= cnt_addr
->ipv4
.sin_port
) continue;
433 if (srv_socket
->addr
.ipv4
.sin_addr
.s_addr
== cnt_addr
->ipv4
.sin_addr
.s_addr
) {
436 if (srv_socket
->addr
.ipv4
.sin_addr
.s_addr
== htonl(INADDR_ANY
)) {
437 srv_socket_wild
= srv_socket
;
442 if (srv_socket
->addr
.ipv6
.sin6_port
!= cnt_addr
->ipv6
.sin6_port
) continue;
443 if (0 == memcmp(&srv_socket
->addr
.ipv6
.sin6_addr
, &cnt_addr
->ipv6
.sin6_addr
, sizeof(struct in6_addr
))) {
446 if (0 == memcmp(&srv_socket
->addr
.ipv6
.sin6_addr
, &in6addr_any
, sizeof(struct in6_addr
))) {
447 srv_socket_wild
= srv_socket
;
453 if (0 == strcmp(srv_socket
->addr
.un
.sun_path
, cnt_addr
->un
.sun_path
)) {
462 if (NULL
!= srv_socket_wild
) {
463 return srv_socket_wild
;
464 } else if (srv
->srv_sockets
.used
) {
465 return srv
->srv_sockets
.ptr
[0];
467 log_error_write(srv
, __FILE__
, __LINE__
, "s", "no sockets configured");
473 static int server_oneshot_init(server
*srv
, int fd
) {
474 /* Note: does not work with netcat due to requirement that fd be socket.
475 * STDOUT_FILENO was not saved earlier in startup, and that is to where
476 * netcat expects output to be sent. Since lighttpd expects connections
477 * to be sockets, con->fd is where output is sent; separate fds are not
478 * stored for input and output, but netcat has different fds for stdin
479 * and * stdout. To support netcat, would additionally need to avoid
480 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
481 * addresses from environment variables:
482 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
483 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
487 server_socket
*srv_socket
;
492 if (0 != fstat(fd
, &st
)) {
493 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fstat:", strerror(errno
));
497 if (!S_ISSOCK(st
.st_mode
)) {
498 /* require that fd is a socket
499 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
500 log_error_write(srv
, __FILE__
, __LINE__
, "s", "lighttpd -1 stdin is not a socket");
504 cnt_len
= sizeof(cnt_addr
);
505 if (0 != getsockname(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
506 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getsockname:", strerror(errno
));
510 srv_socket
= server_oneshot_getsock(srv
, &cnt_addr
);
511 if (NULL
== srv_socket
) return 0;
513 cnt_len
= sizeof(cnt_addr
);
514 if (0 != getpeername(fd
, (struct sockaddr
*)&cnt_addr
, &cnt_len
)) {
515 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "getpeername:", strerror(errno
));
519 /*(must set flags; fd did not pass through fdevent accept() logic)*/
520 if (-1 == fdevent_fcntl_set_nb_cloexec(srv
->ev
, fd
)) {
521 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "fcntl:", 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 if (*logfile
== '|') fdevent_breakagelog_logger_pipe(errfd
);
849 else if (!srv
->srvconf
.dont_daemonize
) {
850 /* move STDERR_FILENO to /dev/null */
851 if (-1 == (errfd
= fdevent_open_devnull())) {
852 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
853 "opening /dev/null failed:", strerror(errno
));
858 /*(leave STDERR_FILENO as-is)*/
862 if (0 != fdevent_set_stdin_stdout_stderr(-1, -1, errfd
)) {
863 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
864 "setting stderr failed:", strerror(errno
));
866 if (-1 != errfd
) close(errfd
);
871 if (-1 != errfd
) close(errfd
);
882 static int log_error_cycle(server
*srv
) {
883 /* cycle only if the error log is a file */
885 if (srv
->errorlog_mode
== ERRORLOG_FILE
) {
886 const char *logfile
= srv
->srvconf
.errorlog_file
->ptr
;
887 if (-1 == fdevent_cycle_logger(logfile
, &srv
->errorlog_fd
)) {
888 /* write to old log */
889 log_error_write(srv
, __FILE__
, __LINE__
, "SSSS",
890 "cycling errorlog '", logfile
,
891 "' failed: ", strerror(errno
));
898 static int log_error_close(server
*srv
) {
899 switch(srv
->errorlog_mode
) {
903 if (-1 != srv
->errorlog_fd
) {
904 /* don't close STDERR */
905 /* fdevent_close_logger_pipes() closes ERRORLOG_PIPE */
906 if (STDERR_FILENO
!= srv
->errorlog_fd
907 && srv
->errorlog_mode
!= ERRORLOG_PIPE
) {
908 close(srv
->errorlog_fd
);
910 srv
->errorlog_fd
= -1;
913 case ERRORLOG_SYSLOG
:
923 static void server_sockets_save (server
*srv
) { /* graceful_restart */
924 memcpy(&graceful_sockets
, &srv
->srv_sockets
, sizeof(server_socket_array
));
925 memset(&srv
->srv_sockets
, 0, sizeof(server_socket_array
));
928 static void server_sockets_restore (server
*srv
) { /* graceful_restart */
929 memcpy(&srv
->srv_sockets
, &graceful_sockets
, sizeof(server_socket_array
));
930 memset(&graceful_sockets
, 0, sizeof(server_socket_array
));
933 static int server_sockets_set_nb_cloexec (server
*srv
) {
934 if (srv
->sockets_disabled
) return 0; /* lighttpd -1 (one-shot mode) */
935 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
936 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
937 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv
->ev
, srv_socket
->fd
)) {
938 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
939 "fcntl failed:", strerror(errno
));
946 static void server_sockets_set_event (server
*srv
, int event
) {
947 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
948 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
949 fdevent_event_set(srv
->ev
,&(srv_socket
->fde_ndx
),srv_socket
->fd
,event
);
953 static void server_sockets_unregister (server
*srv
) {
954 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
)
955 network_unregister_sock(srv
, srv
->srv_sockets
.ptr
[i
]);
958 static void server_sockets_close (server
*srv
) {
959 /* closing socket right away will make it possible for the next lighttpd
960 * to take over (old-style graceful restart), but only if backends
961 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
962 * than started by lighttpd via "bin-path")
964 for (size_t i
= 0; i
< srv
->srv_sockets
.used
; ++i
) {
965 server_socket
*srv_socket
= srv
->srv_sockets
.ptr
[i
];
966 if (-1 == srv_socket
->fd
) continue;
967 network_unregister_sock(srv
, srv_socket
);
968 close(srv_socket
->fd
);
970 /* network_close() will cleanup after us */
974 static void server_graceful_shutdown_maint (server
*srv
) {
975 connections
*conns
= srv
->conns
;
976 for (size_t ndx
= 0; ndx
< conns
->used
; ++ndx
) {
977 connection
* const con
= conns
->ptr
[ndx
];
980 if (con
->state
== CON_STATE_CLOSE
) {
981 /* reduce remaining linger timeout to be
982 * (from zero) *up to* one more second, but no more */
983 if (HTTP_LINGER_TIMEOUT
> 1)
984 con
->close_timeout_ts
-= (HTTP_LINGER_TIMEOUT
- 1);
985 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
)
988 else if (con
->state
== CON_STATE_READ
&& con
->request_count
> 1
989 && chunkqueue_is_empty(con
->read_queue
)) {
990 /* close connections in keep-alive waiting for next request */
991 connection_set_state(srv
, con
, CON_STATE_ERROR
);
995 con
->keep_alive
= 0; /* disable keep-alive */
997 con
->conf
.kbytes_per_second
= 0; /* disable rate limit */
998 con
->conf
.global_kbytes_per_second
= 0; /* disable rate limit */
999 if (con
->traffic_limit_reached
) {
1000 con
->traffic_limit_reached
= 0;
1005 connection_state_machine(srv
, con
);
1010 static void server_graceful_state (server
*srv
) {
1012 if (!srv_shutdown
) server_graceful_shutdown_maint(srv
);
1015 if (0==srv
->srv_sockets
.used
|| -1 == srv
->srv_sockets
.ptr
[0]->fde_ndx
)
1019 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1020 "[note] graceful shutdown started");
1022 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
1023 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)
1024 || oneshot_fd
|| 2 == graceful_shutdown
)
1025 graceful_restart
= 0;
1027 if (graceful_restart
) {
1028 server_sockets_unregister(srv
);
1029 if (pid_fd
> 0) pid_fd
= -pid_fd
; /*(flag to skip removing pid file)*/
1032 server_sockets_close(srv
);
1033 remove_pid_file(srv
);
1034 buffer_reset(srv
->srvconf
.pid_file
); /*(prevent more removal attempts)*/
1038 static int server_main (server
* const srv
, int argc
, char **argv
) {
1039 int print_config
= 0;
1040 int test_config
= 0;
1047 time_t idle_limit
= 0, last_active_ts
= time(NULL
);
1048 #ifdef HAVE_SIGACTION
1049 struct sigaction act
;
1053 int parent_pipe_fd
= -1;
1057 i_am_root
= (0 == getuid());
1060 /* initialize globals (including file-scoped static globals) */
1063 graceful_shutdown
= 0;
1064 handle_sig_alarm
= 1;
1066 chunkqueue_set_tempdirs_default_reset();
1067 http_auth_dumbdata_reset();
1068 http_vhostdb_dumbdata_reset();
1069 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1070 /*(intentionally preserved)*/
1071 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1074 srv
->srvconf
.port
= 0;
1075 srv
->srvconf
.dont_daemonize
= 0;
1076 srv
->srvconf
.preflight_check
= 0;
1078 while(-1 != (o
= getopt(argc
, argv
, "f:m:i:hvVD1pt"))) {
1081 if (srv
->config_storage
) {
1082 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1083 "Can only read one config file. Use the include command to use multiple config files.");
1086 if (config_read(srv
, optarg
)) {
1091 buffer_copy_string(srv
->srvconf
.modules_dir
, optarg
);
1095 long timeout
= strtol(optarg
, &endptr
, 0);
1096 if (!*optarg
|| *endptr
|| timeout
< 0) {
1097 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1098 "Invalid idle timeout value:", optarg
);
1101 idle_limit
= (time_t)timeout
;
1104 case 'p': print_config
= 1; break;
1105 case 't': ++test_config
; break;
1106 case '1': if (0 == oneshot_fd
) oneshot_fd
= dup(STDIN_FILENO
);
1108 case 'D': srv
->srvconf
.dont_daemonize
= 1; break;
1109 case 'v': show_version(); return 0;
1110 case 'V': show_features(); return 0;
1111 case 'h': show_help(); return 0;
1118 if (!srv
->config_storage
) {
1119 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1120 "No configuration available. Try using -f option.");
1125 data_unset
*dc
= srv
->config_context
->data
[0];
1128 fprintf(stdout
, "\n");
1130 /* shouldn't happend */
1131 fprintf(stderr
, "global config not found\n");
1136 buffer_reset(srv
->srvconf
.pid_file
);
1137 if (1 == test_config
) {
1138 printf("Syntax OK\n");
1139 } else { /*(test_config > 1)*/
1141 srv
->srvconf
.preflight_check
= 1;
1142 srv
->srvconf
.dont_daemonize
= 1;
1146 if (test_config
|| print_config
) {
1151 if (oneshot_fd
<= STDERR_FILENO
) {
1152 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1153 "Invalid fds at startup with lighttpd -1");
1156 graceful_shutdown
= 1;
1157 srv
->sockets_disabled
= 1;
1158 srv
->srvconf
.dont_daemonize
= 1;
1159 buffer_reset(srv
->srvconf
.pid_file
);
1160 if (srv
->srvconf
.max_worker
) {
1161 srv
->srvconf
.max_worker
= 0;
1162 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1163 "server one-shot command line option disables server.max-worker config file option.");
1167 /* close stdin and stdout, as they are not needed */
1173 /* coverity[overwrite_var : FALSE] */
1174 devnull
= fdevent_open_devnull();
1175 } while (-1 != devnull
&& devnull
<= STDERR_FILENO
);
1176 if (-1 == devnull
) {
1177 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1178 "opening /dev/null failed:", strerror(errno
));
1181 errfd
= (0 == fstat(STDERR_FILENO
, &st
)) ? -1 : devnull
;
1182 if (0 != fdevent_set_stdin_stdout_stderr(devnull
, devnull
, errfd
)) {
1183 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1184 "setting default fds failed:", strerror(errno
));
1186 if (-1 != errfd
) close(errfd
);
1187 if (devnull
!= errfd
) close(devnull
);
1192 if (-1 != errfd
) close(errfd
);
1193 if (devnull
!= errfd
) close(devnull
);
1197 if (0 != config_set_defaults(srv
)) {
1198 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1199 "setting default values failed");
1203 /* check document-root */
1204 if (buffer_string_is_empty(srv
->config_storage
[0]->document_root
)) {
1205 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1206 "document-root is not set\n");
1210 if (plugins_load(srv
)) {
1211 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1212 "loading plugins finally failed");
1216 if (HANDLER_GO_ON
!= plugins_call_init(srv
)) {
1217 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Initialization of plugins failed. Going down.");
1221 /* open pid file BEFORE chroot */
1222 if (-2 == pid_fd
) pid_fd
= -1; /*(initial startup state)*/
1223 if (-1 == pid_fd
&& !buffer_string_is_empty(srv
->srvconf
.pid_file
)) {
1224 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
))) {
1226 if (errno
!= EEXIST
) {
1227 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1228 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1232 if (0 != stat(srv
->srvconf
.pid_file
->ptr
, &st
)) {
1233 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1234 "stating existing pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1237 if (!S_ISREG(st
.st_mode
)) {
1238 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1239 "pid-file exists and isn't regular file:", srv
->srvconf
.pid_file
);
1243 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
))) {
1244 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1245 "opening pid-file failed:", srv
->srvconf
.pid_file
, strerror(errno
));
1251 if (srv
->event_handler
== FDEVENT_HANDLER_SELECT
) {
1252 /* select limits itself
1254 * as it is a hard limit and will lead to a segfault we add some safety
1256 srv
->max_fds
= FD_SETSIZE
- 200;
1258 srv
->max_fds
= 4096;
1262 #ifdef HAVE_GETRLIMIT
1265 #ifdef HAVE_VALGRIND_VALGRIND_H
1266 if (RUNNING_ON_VALGRIND
) use_rlimit
= 0;
1269 if (0 != getrlimit(RLIMIT_NOFILE
, &rlim
)) {
1270 log_error_write(srv
, __FILE__
, __LINE__
,
1271 "ss", "couldn't get 'max filedescriptors'",
1277 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1279 if (use_rlimit
&& srv
->srvconf
.max_fds
1280 && (i_am_root
|| srv
->srvconf
.max_fds
<= rlim
.rlim_max
)) {
1283 rlim
.rlim_cur
= srv
->srvconf
.max_fds
;
1284 if (i_am_root
) rlim
.rlim_max
= srv
->srvconf
.max_fds
;
1286 if (0 != setrlimit(RLIMIT_NOFILE
, &rlim
)) {
1287 log_error_write(srv
, __FILE__
, __LINE__
,
1288 "ss", "couldn't set 'max filedescriptors'",
1294 if (srv
->event_handler
== FDEVENT_HANDLER_SELECT
) {
1295 srv
->max_fds
= rlim
.rlim_cur
< (rlim_t
)FD_SETSIZE
- 200 ? (int)rlim
.rlim_cur
: (int)FD_SETSIZE
- 200;
1297 srv
->max_fds
= rlim
.rlim_cur
;
1298 /*(default upper limit of 4k if server.max-fds not specified)*/
1299 if (i_am_root
&& 0 == srv
->srvconf
.max_fds
&& rlim
.rlim_cur
> 4096)
1300 srv
->max_fds
= 4096;
1303 /* set core file rlimit, if enable_cores is set */
1304 if (use_rlimit
&& srv
->srvconf
.enable_cores
&& getrlimit(RLIMIT_CORE
, &rlim
) == 0) {
1305 rlim
.rlim_cur
= rlim
.rlim_max
;
1306 setrlimit(RLIMIT_CORE
, &rlim
);
1309 if (srv
->event_handler
== FDEVENT_HANDLER_SELECT
) {
1310 /* don't raise the limit above FD_SET_SIZE */
1311 if (srv
->max_fds
> ((int)FD_SETSIZE
) - 200) {
1312 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1313 "can't raise max filedescriptors above", FD_SETSIZE
- 200,
1314 "if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
1320 /* we need root-perms for port < 1024 */
1321 if (0 != network_init(srv
)) {
1327 /* set user and group */
1328 struct group
*grp
= NULL
;
1329 struct passwd
*pwd
= NULL
;
1331 if (!buffer_string_is_empty(srv
->srvconf
.groupname
)) {
1332 if (NULL
== (grp
= getgrnam(srv
->srvconf
.groupname
->ptr
))) {
1333 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1334 "can't find groupname", srv
->srvconf
.groupname
);
1339 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1340 if (NULL
== (pwd
= getpwnam(srv
->srvconf
.username
->ptr
))) {
1341 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1342 "can't find username", srv
->srvconf
.username
);
1346 if (pwd
->pw_uid
== 0) {
1347 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1348 "I will not set uid to 0\n");
1352 if (NULL
== grp
&& NULL
== (grp
= getgrgid(pwd
->pw_gid
))) {
1353 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1354 "can't find group id", pwd
->pw_gid
);
1360 if (grp
->gr_gid
== 0) {
1361 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1362 "I will not set gid to 0\n");
1368 * Change group before chroot, when we have access
1372 if (-1 == setgid(grp
->gr_gid
)) {
1373 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgid failed: ", strerror(errno
));
1376 if (-1 == setgroups(0, NULL
)) {
1377 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setgroups failed: ", strerror(errno
));
1380 if (!buffer_string_is_empty(srv
->srvconf
.username
)) {
1381 initgroups(srv
->srvconf
.username
->ptr
, grp
->gr_gid
);
1386 if (!buffer_string_is_empty(srv
->srvconf
.changeroot
)) {
1389 if (-1 == chroot(srv
->srvconf
.changeroot
->ptr
)) {
1390 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chroot failed: ", strerror(errno
));
1393 if (-1 == chdir("/")) {
1394 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "chdir failed: ", strerror(errno
));
1400 /* drop root privs */
1402 if (-1 == setuid(pwd
->pw_uid
)) {
1403 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "setuid failed: ", strerror(errno
));
1408 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1410 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1412 if (srv
->srvconf
.enable_cores
) {
1413 prctl(PR_SET_DUMPABLE
, 1, 0, 0, 0);
1419 if (srv
->srvconf
.max_conns
> srv
->max_fds
/2) {
1420 /* we can't have more connections than max-fds/2 */
1421 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", "can't have more connections than fds/2: ", srv
->srvconf
.max_conns
, srv
->max_fds
);
1422 srv
->max_conns
= srv
->max_fds
/2;
1423 } else if (srv
->srvconf
.max_conns
) {
1424 /* otherwise respect the wishes of the user */
1425 srv
->max_conns
= srv
->srvconf
.max_conns
;
1427 /* or use the default: we really don't want to hit max-fds */
1428 srv
->max_conns
= srv
->max_fds
/3;
1432 /* network is up, let's daemonize ourself */
1433 if (0 == srv
->srvconf
.dont_daemonize
&& 0 == graceful_restart
) {
1434 parent_pipe_fd
= daemonize();
1437 graceful_restart
= 0;/*(reset here after avoiding further daemonizing)*/
1438 graceful_shutdown
= 0;
1441 #ifdef HAVE_SIGACTION
1442 memset(&act
, 0, sizeof(act
));
1443 act
.sa_handler
= SIG_IGN
;
1444 sigaction(SIGPIPE
, &act
, NULL
);
1445 # if defined(SA_SIGINFO)
1446 last_sighup_info
.si_uid
= 0,
1447 last_sighup_info
.si_pid
= 0;
1448 last_sigterm_info
.si_uid
= 0,
1449 last_sigterm_info
.si_pid
= 0;
1450 act
.sa_sigaction
= sigaction_handler
;
1451 sigemptyset(&act
.sa_mask
);
1452 act
.sa_flags
= SA_SIGINFO
;
1454 act
.sa_handler
= signal_handler
;
1455 sigemptyset(&act
.sa_mask
);
1458 sigaction(SIGINT
, &act
, NULL
);
1459 sigaction(SIGTERM
, &act
, NULL
);
1460 sigaction(SIGHUP
, &act
, NULL
);
1461 sigaction(SIGALRM
, &act
, NULL
);
1462 sigaction(SIGUSR1
, &act
, NULL
);
1464 /* it should be safe to restart syscalls after SIGCHLD */
1465 act
.sa_flags
|= SA_RESTART
| SA_NOCLDSTOP
;
1466 sigaction(SIGCHLD
, &act
, NULL
);
1468 #elif defined(HAVE_SIGNAL)
1469 /* ignore the SIGPIPE from sendfile() */
1470 signal(SIGPIPE
, SIG_IGN
);
1471 signal(SIGALRM
, signal_handler
);
1472 signal(SIGTERM
, signal_handler
);
1473 signal(SIGHUP
, signal_handler
);
1474 signal(SIGCHLD
, signal_handler
);
1475 signal(SIGINT
, signal_handler
);
1476 signal(SIGUSR1
, signal_handler
);
1480 srv
->gid
= getgid();
1481 srv
->uid
= getuid();
1483 /* write pid file */
1485 buffer_copy_int(srv
->tmp_buf
, getpid());
1486 buffer_append_string_len(srv
->tmp_buf
, CONST_STR_LEN("\n"));
1487 if (-1 == write_all(pid_fd
, CONST_BUF_LEN(srv
->tmp_buf
))) {
1488 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't write pid file:", strerror(errno
));
1493 } else if (pid_fd
< -2) {
1497 /* Close stderr ASAP in the child process to make sure that nothing
1498 * is being written to that fd which may not be valid anymore. */
1499 if (!srv
->srvconf
.preflight_check
) {
1500 if (-1 == log_error_open(srv
)) {
1501 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Opening errorlog failed. Going down.");
1504 log_error_write(srv
, __FILE__
, __LINE__
, "s", "server started (" PACKAGE_DESC
")");
1507 if (buffer_is_empty(srv
->config_storage
[0]->server_tag
)) {
1508 buffer_copy_string_len(srv
->config_storage
[0]->server_tag
, CONST_STR_LEN(PACKAGE_DESC
));
1511 if (HANDLER_GO_ON
!= plugins_call_set_defaults(srv
)) {
1512 log_error_write(srv
, __FILE__
, __LINE__
, "s", "Configuration of plugins failed. Going down.");
1516 /* settings might be enabled during module config set defaults */
1517 srv
->config_storage
[0]->high_precision_timestamps
= srv
->srvconf
.high_precision_timestamps
;
1519 /* dump unused config-keys */
1520 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1521 array
*config
= ((data_config
*)srv
->config_context
->data
[i
])->value
;
1524 for (j
= 0; config
&& j
< config
->used
; j
++) {
1525 data_unset
*du
= config
->data
[j
];
1527 /* all var.* is known as user defined variable */
1528 if (strncmp(du
->key
->ptr
, "var.", sizeof("var.") - 1) == 0) {
1532 if (NULL
== array_get_element_klen(srv
->config_touched
, CONST_BUF_LEN(du
->key
))) {
1533 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1534 "WARNING: unknown config-key:",
1541 if (srv
->config_unsupported
) {
1542 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1543 "Configuration contains unsupported keys. Going down.");
1546 if (srv
->config_deprecated
) {
1547 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1548 "Configuration contains deprecated keys. Going down.");
1551 if (srv
->config_unsupported
|| srv
->config_deprecated
) {
1555 if (srv
->srvconf
.preflight_check
) {
1556 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1563 * notify daemonize-grandparent of successful startup
1564 * do this before any further forking is done (workers)
1566 if (0 == srv
->srvconf
.dont_daemonize
&& -1 != parent_pipe_fd
) {
1567 if (0 > write(parent_pipe_fd
, "", 1)) return -1;
1568 close(parent_pipe_fd
);
1571 if (idle_limit
&& srv
->srvconf
.max_worker
) {
1572 srv
->srvconf
.max_worker
= 0;
1573 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1574 "server idle time limit command line option disables server.max-worker config file option.");
1577 /* start watcher and workers */
1578 num_childs
= srv
->srvconf
.max_worker
;
1579 if (num_childs
> 0) {
1580 pid_t pids
[num_childs
];
1582 const int npids
= num_childs
;
1584 for (int n
= 0; n
< npids
; ++n
) pids
[n
] = -1;
1585 while (!child
&& !srv_shutdown
&& !graceful_shutdown
) {
1586 if (num_childs
> 0) {
1587 switch ((pid
= fork())) {
1595 for (int n
= 0; n
< npids
; ++n
) {
1596 if (-1 == pids
[n
]) {
1606 if (-1 != (pid
= wait(&status
))) {
1607 switch (fdevent_reaped_logger_pipe(pid
)) {
1609 case -1: alarm(5); /* fall through */
1613 * check if one of our workers went away
1615 for (int n
= 0; n
< npids
; ++n
) {
1616 if (pid
== pids
[n
]) {
1626 * if we receive a SIGHUP we have to close our logs ourself as we don't
1627 * have the mainloop who can help us here
1629 if (handle_sig_hup
) {
1632 log_error_cycle(srv
);
1634 /* forward SIGHUP to workers */
1635 for (int n
= 0; n
< npids
; ++n
) {
1636 if (pids
[n
] > 0) kill(pids
[n
], SIGHUP
);
1639 if (handle_sig_alarm
) {
1640 handle_sig_alarm
= 0;
1641 fdevent_waitpid_logger_pipes(time(NULL
));
1652 * for the parent this is the exit-point
1656 * kill all children too
1658 if (graceful_shutdown
|| graceful_restart
) {
1659 /* flag to ignore one SIGINT if graceful_restart */
1660 if (graceful_restart
) graceful_restart
= 2;
1662 server_graceful_state(srv
);
1663 } else if (srv_shutdown
) {
1670 /* ignore SIGUSR1 in workers; only parent directs graceful restart */
1671 #ifdef HAVE_SIGACTION
1673 struct sigaction actignore
;
1674 memset(&actignore
, 0, sizeof(actignore
));
1675 actignore
.sa_handler
= SIG_IGN
;
1676 sigaction(SIGUSR1
, &actignore
, NULL
);
1678 #elif defined(HAVE_SIGNAL)
1679 signal(SIGUSR1
, SIG_IGN
);
1683 * make sure workers do not muck with pid-file
1689 buffer_reset(srv
->srvconf
.pid_file
);
1695 if (NULL
== (srv
->ev
= fdevent_init(srv
, srv
->max_fds
+ 1, srv
->event_handler
))) {
1696 log_error_write(srv
, __FILE__
, __LINE__
,
1697 "s", "fdevent_init failed");
1701 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1702 #ifdef HAVE_SIGACTION
1703 sigaction(SIGCHLD
, &act
, NULL
);
1704 #elif defined(HAVE_SIGNAL)
1705 signal(SIGCHLD
, signal_handler
);
1709 * kqueue() is called here, select resets its internals,
1710 * all server sockets get their handlers
1713 if (0 != network_register_fdevents(srv
)) {
1717 /* might fail if user is using fam (not gamin) and famd isn't running */
1718 if (NULL
== (srv
->stat_cache
= stat_cache_init(srv
))) {
1719 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1720 "stat-cache could not be setup, dieing.");
1726 /* setup periodic timer (1 second) */
1727 struct itimerval interval
;
1728 interval
.it_interval
.tv_sec
= 1;
1729 interval
.it_interval
.tv_usec
= 0;
1730 interval
.it_value
.tv_sec
= 1;
1731 interval
.it_value
.tv_usec
= 0;
1732 if (setitimer(ITIMER_REAL
, &interval
, NULL
)) {
1733 log_error_write(srv
, __FILE__
, __LINE__
, "s", "setting timer failed");
1740 /* get the current number of FDs */
1742 int fd
= fdevent_open_devnull();
1749 if (0 != server_sockets_set_nb_cloexec(srv
)) {
1753 if (oneshot_fd
&& server_oneshot_init(srv
, oneshot_fd
)) {
1758 while (!srv_shutdown
) {
1763 if (handle_sig_hup
) {
1766 /* reset notification */
1770 /* cycle logfiles */
1772 switch(r
= plugins_call_handle_sighup(srv
)) {
1776 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "sighup-handler return with an error", r
);
1780 if (-1 == log_error_cycle(srv
)) {
1781 log_error_write(srv
, __FILE__
, __LINE__
, "s", "cycling errorlog failed, dying");
1785 #ifdef HAVE_SIGACTION
1786 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
1787 "logfiles cycled UID =",
1788 last_sighup_info
.si_uid
,
1790 last_sighup_info
.si_pid
);
1792 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1798 if (handle_sig_alarm
) {
1802 /* reset notification */
1803 handle_sig_alarm
= 0;
1806 /* get current time */
1807 min_ts
= time(NULL
);
1809 if (min_ts
!= srv
->cur_ts
) {
1810 #ifdef DEBUG_CONNECTION_STATES
1813 connections
*conns
= srv
->conns
;
1816 switch(r
= plugins_call_handle_trigger(srv
)) {
1820 log_error_write(srv
, __FILE__
, __LINE__
, "s", "one of the triggers failed");
1823 log_error_write(srv
, __FILE__
, __LINE__
, "d", r
);
1827 /* trigger waitpid */
1828 srv
->cur_ts
= min_ts
;
1830 /* check idle time limit, if enabled */
1831 if (idle_limit
&& idle_limit
< min_ts
- last_active_ts
&& !graceful_shutdown
) {
1832 log_error_write(srv
, __FILE__
, __LINE__
, "sDs", "[note] idle timeout", (int)idle_limit
,
1833 "s exceeded, initiating graceful shutdown");
1834 graceful_shutdown
= 2; /* value 2 indicates idle timeout */
1835 if (graceful_restart
) {
1836 graceful_restart
= 0;
1837 if (pid_fd
< -2) pid_fd
= -pid_fd
;
1838 server_sockets_close(srv
);
1842 #ifdef HAVE_GETLOADAVG
1843 /* refresh loadavg data every 30 seconds */
1844 if (srv
->srvconf
.loadts
+ 30 < min_ts
) {
1845 if (-1 != getloadavg(srv
->srvconf
.loadavg
, 3)) {
1846 srv
->srvconf
.loadts
= min_ts
;
1851 /* cleanup stat-cache */
1852 stat_cache_trigger_cleanup(srv
);
1853 /* reset global/aggregate rate limit counters */
1854 for (i
= 0; i
< srv
->config_context
->used
; ++i
) {
1855 srv
->config_storage
[i
]->global_bytes_per_second_cnt
= 0;
1857 /* check piped-loggers and restart, unless shutting down */
1858 if (!graceful_shutdown
&& !srv_shutdown
&& 0 == srv
->srvconf
.max_worker
) fdevent_waitpid_logger_pipes(min_ts
);
1859 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1860 if (graceful_shutdown
&& !srv_shutdown
) server_graceful_shutdown_maint(srv
);
1862 * check all connections for timeouts
1865 for (ndx
= 0; ndx
< conns
->used
; ndx
++) {
1866 connection
* const con
= conns
->ptr
[ndx
];
1867 const int waitevents
= fdevent_event_get_interest(srv
->ev
, con
->fd
);
1871 if (con
->state
== CON_STATE_CLOSE
) {
1872 if (srv
->cur_ts
- con
->close_timeout_ts
> HTTP_LINGER_TIMEOUT
) {
1875 } else if (waitevents
& FDEVENT_IN
) {
1876 if (con
->request_count
== 1 || con
->state
!= CON_STATE_READ
) { /* e.g. CON_STATE_READ_POST || CON_STATE_WRITE */
1877 if (srv
->cur_ts
- con
->read_idle_ts
> con
->conf
.max_read_idle
) {
1879 if (con
->conf
.log_request_handling
) {
1880 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1881 "connection closed - read timeout:", con
->fd
);
1884 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1888 if (srv
->cur_ts
- con
->read_idle_ts
> con
->keep_alive_idle
) {
1890 if (con
->conf
.log_request_handling
) {
1891 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1892 "connection closed - keep-alive timeout:", con
->fd
);
1895 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1901 /* max_write_idle timeout currently functions as backend timeout,
1902 * too, after response has been started.
1903 * future: have separate backend timeout, and then change this
1904 * to check for write interest before checking for timeout */
1905 /*if (waitevents & FDEVENT_OUT)*/
1906 if ((con
->state
== CON_STATE_WRITE
) &&
1907 (con
->write_request_ts
!= 0)) {
1909 if (srv
->cur_ts
- con
->write_request_ts
> 60) {
1910 log_error_write(srv
, __FILE__
, __LINE__
, "sdd",
1911 "connection closed - pre-write-request-timeout:", con
->fd
, srv
->cur_ts
- con
->write_request_ts
);
1915 if (srv
->cur_ts
- con
->write_request_ts
> con
->conf
.max_write_idle
) {
1917 if (con
->conf
.log_timeouts
) {
1918 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsosds",
1919 "NOTE: a request from",
1923 "timed out after writing",
1926 (int)con
->conf
.max_write_idle
,
1927 "seconds. If this a problem increase server.max-write-idle");
1929 connection_set_state(srv
, con
, CON_STATE_ERROR
);
1934 /* we don't like div by zero */
1935 if (0 == (t_diff
= srv
->cur_ts
- con
->connection_start
)) t_diff
= 1;
1937 if (con
->traffic_limit_reached
&&
1938 (con
->conf
.kbytes_per_second
== 0 ||
1939 ((con
->bytes_written
/ t_diff
) < con
->conf
.kbytes_per_second
* 1024))) {
1940 /* enable connection again */
1941 con
->traffic_limit_reached
= 0;
1946 con
->bytes_written_cur_second
= 0;
1949 connection_state_machine(srv
, con
);
1952 #if DEBUG_CONNECTION_STATES
1954 fprintf(stderr
, "connection-state: ");
1958 fprintf(stderr
, "c[%d,%d]: %s ",
1961 connection_get_state(con
->state
));
1965 #ifdef DEBUG_CONNECTION_STATES
1966 if (cs
== 1) fprintf(stderr
, "\n");
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 fdevent_sched_run(srv
, srv
->ev
);
2043 } else if (n
< 0 && errno
!= EINTR
) {
2044 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2045 "fdevent_poll failed:",
2049 for (ndx
= 0; ndx
< srv
->joblist
->used
; ndx
++) {
2050 connection
*con
= srv
->joblist
->ptr
[ndx
];
2051 connection_state_machine(srv
, con
);
2054 srv
->joblist
->used
= 0;
2057 if (graceful_shutdown
|| graceful_restart
) {
2058 server_graceful_state(srv
);
2061 if (2 == graceful_shutdown
) { /* value 2 indicates idle timeout */
2062 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2063 "server stopped after idle timeout");
2065 #ifdef HAVE_SIGACTION
2066 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2067 "server stopped by UID =",
2068 last_sigterm_info
.si_uid
,
2070 last_sigterm_info
.si_pid
);
2072 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2080 int main (int argc
, char **argv
) {
2084 #ifndef HAVE_ISSETUGID
2085 #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2087 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2089 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2094 /* for nice %b handling in strftime() */
2095 setlocale(LC_TIME
, "C");
2098 server
* const srv
= server_init();
2100 if (graceful_restart
) {
2101 server_sockets_restore(srv
);
2105 rc
= server_main(srv
, argc
, argv
);
2108 remove_pid_file(srv
);
2109 log_error_close(srv
);
2110 fdevent_close_logger_pipes();
2111 if (graceful_restart
)
2112 server_sockets_save(srv
);
2115 connections_free(srv
);
2119 if (0 != rc
|| !graceful_restart
) break;
2121 /* wait for all children to exit before graceful restart */
2122 while (waitpid(-1, NULL
, 0) > 0) ;
2123 } while (graceful_restart
);