[core] use buffer_eq_icase* funcs
[lighttpd.git] / src / server.c
blobb7086b07a0d565ef1249fc3d4387094b34ccba3a
1 #include "first.h"
3 #include "base.h"
4 #include "buffer.h"
5 #include "burl.h"
6 #include "network.h"
7 #include "log.h"
8 #include "rand.h"
9 #include "chunk.h"
10 #include "http_auth.h"
11 #include "http_vhostdb.h"
12 #include "fdevent.h"
13 #include "connections.h"
14 #include "sock_addr.h"
15 #include "stat_cache.h"
16 #include "configfile.h"
17 #include "plugin.h"
18 #include "joblist.h"
19 #include "network_write.h"
21 #ifdef HAVE_VERSIONSTAMP_H
22 # include "versionstamp.h"
23 #else
24 # define REPO_VERSION ""
25 #endif
27 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
29 #include <sys/types.h>
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
34 #include <string.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #include <time.h>
40 #include <signal.h>
41 #include <locale.h>
43 #include <stdio.h>
45 #ifdef HAVE_GETOPT_H
46 # include <getopt.h>
47 #endif
49 #ifdef HAVE_VALGRIND_VALGRIND_H
50 # include <valgrind/valgrind.h>
51 #endif
53 #ifdef HAVE_SYS_WAIT_H
54 # include <sys/wait.h>
55 #endif
57 #ifdef HAVE_PWD_H
58 # include <grp.h>
59 # include <pwd.h>
60 #endif
62 #ifdef HAVE_SYSLOG_H
63 # include <syslog.h>
64 #endif
66 #ifdef HAVE_SYS_RESOURCE_H
67 # include <sys/resource.h>
68 #endif
70 #ifdef HAVE_SYS_PRCTL_H
71 # include <sys/prctl.h>
72 #endif
74 #include "sys-crypto.h"
75 #ifdef USE_OPENSSL_CRYPTO
76 #define USE_SSL
77 #define TEXT_SSL " (ssl)"
78 #else
79 #define TEXT_SSL
80 #endif
82 #ifndef __sgi
83 /* IRIX doesn't like the alarm based time() optimization */
84 /* #define USE_ALARM */
85 #endif
87 static int oneshot_fd = 0;
88 static volatile int pid_fd = -2;
89 static server_socket_array graceful_sockets;
90 static server_socket_array inherited_sockets;
91 static volatile sig_atomic_t graceful_restart = 0;
92 static volatile sig_atomic_t graceful_shutdown = 0;
93 static volatile sig_atomic_t srv_shutdown = 0;
94 static volatile sig_atomic_t handle_sig_child = 0;
95 static volatile sig_atomic_t handle_sig_alarm = 1;
96 static volatile sig_atomic_t handle_sig_hup = 0;
97 static time_t idle_limit = 0;
99 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
100 static volatile siginfo_t last_sigterm_info;
101 static volatile siginfo_t last_sighup_info;
103 static void sigaction_handler(int sig, siginfo_t *si, void *context) {
104 static const siginfo_t empty_siginfo;
105 UNUSED(context);
107 if (!si) *(const siginfo_t **)&si = &empty_siginfo;
109 switch (sig) {
110 case SIGTERM:
111 srv_shutdown = 1;
112 last_sigterm_info = *si;
113 break;
114 case SIGUSR1:
115 if (!graceful_shutdown) {
116 graceful_restart = 1;
117 graceful_shutdown = 1;
118 last_sigterm_info = *si;
120 break;
121 case SIGINT:
122 if (graceful_shutdown) {
123 if (2 == graceful_restart)
124 graceful_restart = 1;
125 else
126 srv_shutdown = 1;
127 } else {
128 graceful_shutdown = 1;
130 last_sigterm_info = *si;
132 break;
133 case SIGALRM:
134 handle_sig_alarm = 1;
135 break;
136 case SIGHUP:
137 handle_sig_hup = 1;
138 last_sighup_info = *si;
139 break;
140 case SIGCHLD:
141 handle_sig_child = 1;
142 break;
145 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
146 static void signal_handler(int sig) {
147 switch (sig) {
148 case SIGTERM: srv_shutdown = 1; break;
149 case SIGUSR1:
150 if (!graceful_shutdown) {
151 graceful_restart = 1;
152 graceful_shutdown = 1;
154 break;
155 case SIGINT:
156 if (graceful_shutdown) {
157 if (2 == graceful_restart)
158 graceful_restart = 1;
159 else
160 srv_shutdown = 1;
161 } else {
162 graceful_shutdown = 1;
164 break;
165 case SIGALRM: handle_sig_alarm = 1; break;
166 case SIGHUP: handle_sig_hup = 1; break;
167 case SIGCHLD: handle_sig_child = 1; break;
170 #endif
172 #ifdef HAVE_FORK
173 static int daemonize(void) {
174 int pipefd[2];
175 pid_t pid;
176 #ifdef SIGTTOU
177 signal(SIGTTOU, SIG_IGN);
178 #endif
179 #ifdef SIGTTIN
180 signal(SIGTTIN, SIG_IGN);
181 #endif
182 #ifdef SIGTSTP
183 signal(SIGTSTP, SIG_IGN);
184 #endif
186 if (pipe(pipefd) < 0) exit(-1);
188 if (0 > (pid = fork())) exit(-1);
190 if (0 < pid) {
191 char buf;
192 ssize_t bytes;
194 close(pipefd[1]);
195 /* parent waits for grandchild to be ready */
196 do {
197 bytes = read(pipefd[0], &buf, sizeof(buf));
198 } while (bytes < 0 && EINTR == errno);
199 close(pipefd[0]);
201 if (bytes <= 0) {
202 /* closed fd (without writing) == failure in grandchild */
203 fputs("daemonized server failed to start; check error log for details\n", stderr);
204 exit(-1);
207 exit(0);
210 close(pipefd[0]);
212 if (-1 == setsid()) exit(0);
214 signal(SIGHUP, SIG_IGN);
216 if (0 != fork()) exit(0);
218 if (0 != chdir("/")) exit(0);
220 fdevent_setfd_cloexec(pipefd[1]);
221 return pipefd[1];
223 #endif
225 __attribute_cold__
226 static server *server_init(void) {
227 int i;
228 server *srv = calloc(1, sizeof(*srv));
229 force_assert(srv);
230 #define CLEAN(x) \
231 srv->x = buffer_init();
233 CLEAN(response_header);
234 CLEAN(parse_full_path);
235 CLEAN(ts_date_str);
236 CLEAN(response_range);
237 CLEAN(tmp_buf);
238 srv->empty_string = buffer_init_string("");
239 CLEAN(cond_check_buf);
241 CLEAN(srvconf.errorlog_file);
242 CLEAN(srvconf.breakagelog_file);
243 CLEAN(srvconf.groupname);
244 CLEAN(srvconf.username);
245 CLEAN(srvconf.changeroot);
246 CLEAN(srvconf.bindhost);
247 CLEAN(srvconf.event_handler);
248 CLEAN(srvconf.pid_file);
249 CLEAN(srvconf.syslog_facility);
251 CLEAN(tmp_chunk_len);
252 #undef CLEAN
254 #define CLEAN(x) \
255 srv->x = array_init();
257 CLEAN(config_context);
258 CLEAN(config_touched);
259 CLEAN(status);
260 #undef CLEAN
262 for (i = 0; i < FILE_CACHE_MAX; i++) {
263 srv->mtime_cache[i].mtime = (time_t)-1;
264 srv->mtime_cache[i].str = buffer_init();
267 li_rand_reseed();
269 srv->cur_ts = time(NULL);
270 srv->startup_ts = srv->cur_ts;
272 srv->conns = calloc(1, sizeof(*srv->conns));
273 force_assert(srv->conns);
275 srv->joblist = calloc(1, sizeof(*srv->joblist));
276 force_assert(srv->joblist);
278 srv->fdwaitqueue = calloc(1, sizeof(*srv->fdwaitqueue));
279 force_assert(srv->fdwaitqueue);
281 srv->errh = log_error_st_init(&srv->cur_ts, &srv->last_generated_debug_ts);
283 srv->srvconf.modules = array_init();
284 srv->srvconf.modules_dir = buffer_init_string(LIBRARY_DIR);
285 srv->srvconf.network_backend = buffer_init();
286 srv->srvconf.upload_tempdirs = array_init();
287 srv->srvconf.reject_expect_100_with_417 = 1;
288 srv->srvconf.xattr_name = buffer_init_string("Content-Type");
289 srv->srvconf.http_header_strict = 1;
290 srv->srvconf.http_host_strict = 1; /*(implies http_host_normalize)*/
291 srv->srvconf.http_host_normalize = 0;
292 srv->srvconf.http_url_normalize = HTTP_PARSEOPT_URL_NORMALIZE
293 | HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED
294 | HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT
295 | HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
296 | HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
297 srv->srvconf.high_precision_timestamps = 0;
298 srv->srvconf.max_request_field_size = 8192;
299 srv->srvconf.loadavg[0] = 0.0;
300 srv->srvconf.loadavg[1] = 0.0;
301 srv->srvconf.loadavg[2] = 0.0;
302 srv->srvconf.compat_module_load = 1;
303 srv->srvconf.systemd_socket_activation = 0;
305 srv->split_vals = array_init();
306 srv->request_env = plugins_call_handle_request_env;
308 return srv;
311 __attribute_cold__
312 static void server_free(server *srv) {
313 size_t i;
315 for (i = 0; i < FILE_CACHE_MAX; i++) {
316 buffer_free(srv->mtime_cache[i].str);
319 if (oneshot_fd > 0) {
320 close(oneshot_fd);
323 #define CLEAN(x) \
324 buffer_free(srv->x);
326 CLEAN(response_header);
327 CLEAN(parse_full_path);
328 CLEAN(ts_date_str);
329 CLEAN(response_range);
330 CLEAN(tmp_buf);
331 CLEAN(empty_string);
332 CLEAN(cond_check_buf);
334 CLEAN(srvconf.errorlog_file);
335 CLEAN(srvconf.breakagelog_file);
336 CLEAN(srvconf.groupname);
337 CLEAN(srvconf.username);
338 CLEAN(srvconf.changeroot);
339 CLEAN(srvconf.bindhost);
340 CLEAN(srvconf.event_handler);
341 CLEAN(srvconf.pid_file);
342 CLEAN(srvconf.modules_dir);
343 CLEAN(srvconf.network_backend);
344 CLEAN(srvconf.xattr_name);
345 CLEAN(srvconf.syslog_facility);
347 CLEAN(tmp_chunk_len);
348 #undef CLEAN
350 fdevent_free(srv->ev);
352 free(srv->conns);
354 if (srv->config_storage) {
355 for (i = 0; i < srv->config_context->used; i++) {
356 specific_config *s = srv->config_storage[i];
358 if (!s) continue;
360 buffer_free(s->document_root);
361 buffer_free(s->server_name);
362 buffer_free(s->server_tag);
363 buffer_free(s->error_handler);
364 buffer_free(s->error_handler_404);
365 buffer_free(s->errorfile_prefix);
366 buffer_free(s->socket_perms);
367 array_free(s->mimetypes);
368 free(s);
370 free(srv->config_storage);
371 srv->config_storage = NULL;
374 #define CLEAN(x) \
375 array_free(srv->x);
377 CLEAN(config_context);
378 CLEAN(config_touched);
379 CLEAN(status);
380 CLEAN(srvconf.upload_tempdirs);
381 #undef CLEAN
383 joblist_free(srv, srv->joblist);
384 fdwaitqueue_free(srv, srv->fdwaitqueue);
386 if (srv->stat_cache) {
387 stat_cache_free(srv->stat_cache);
390 array_free(srv->srvconf.modules);
391 array_free(srv->split_vals);
393 li_rand_cleanup();
394 chunkqueue_chunk_pool_free();
396 log_error_st_free(srv->errh);
397 free(srv);
400 __attribute_cold__
401 static void remove_pid_file(server *srv) {
402 if (pid_fd <= -2) return;
403 if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= pid_fd) {
404 if (0 != ftruncate(pid_fd, 0)) {
405 log_error_write(srv, __FILE__, __LINE__, "sbds",
406 "ftruncate failed for:",
407 srv->srvconf.pid_file,
408 errno,
409 strerror(errno));
412 if (0 <= pid_fd) {
413 close(pid_fd);
414 pid_fd = -1;
416 if (!buffer_string_is_empty(srv->srvconf.pid_file) &&
417 buffer_string_is_empty(srv->srvconf.changeroot)) {
418 if (0 != unlink(srv->srvconf.pid_file->ptr)) {
419 if (errno != EACCES && errno != EPERM) {
420 log_error_write(srv, __FILE__, __LINE__, "sbds",
421 "unlink failed for:",
422 srv->srvconf.pid_file,
423 errno,
424 strerror(errno));
431 __attribute_cold__
432 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) {
433 server_socket *srv_socket, *srv_socket_wild = NULL;
434 size_t i;
435 for (i = 0; i < srv->srv_sockets.used; ++i) {
436 srv_socket = srv->srv_sockets.ptr[i];
437 if (!sock_addr_is_port_eq(&srv_socket->addr,cnt_addr)) continue;
438 if (sock_addr_is_addr_eq(&srv_socket->addr,cnt_addr)) return srv_socket;
440 if (NULL != srv_socket_wild) continue;
441 if (sock_addr_is_addr_wildcard(&srv_socket->addr)) {
442 srv_socket_wild = srv_socket;
446 if (NULL != srv_socket_wild) {
447 return srv_socket_wild;
448 } else if (srv->srv_sockets.used) {
449 return srv->srv_sockets.ptr[0];
450 } else {
451 log_error_write(srv, __FILE__, __LINE__, "s", "no sockets configured");
452 return NULL;
457 __attribute_cold__
458 static int server_oneshot_init(server *srv, int fd) {
459 /* Note: does not work with netcat due to requirement that fd be socket.
460 * STDOUT_FILENO was not saved earlier in startup, and that is to where
461 * netcat expects output to be sent. Since lighttpd expects connections
462 * to be sockets, con->fd is where output is sent; separate fds are not
463 * stored for input and output, but netcat has different fds for stdin
464 * and * stdout. To support netcat, would additionally need to avoid
465 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
466 * addresses from environment variables:
467 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
468 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
469 * NCAT_PROTO
471 connection *con;
472 server_socket *srv_socket;
473 sock_addr cnt_addr;
474 socklen_t cnt_len;
475 struct stat st;
477 if (0 != fstat(fd, &st)) {
478 log_error_write(srv, __FILE__, __LINE__, "ss", "fstat:", strerror(errno));
479 return 0;
482 if (!S_ISSOCK(st.st_mode)) {
483 /* require that fd is a socket
484 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
485 log_error_write(srv, __FILE__, __LINE__, "s", "lighttpd -1 stdin is not a socket");
486 return 0;
489 cnt_len = sizeof(cnt_addr);
490 if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
491 log_error_write(srv, __FILE__, __LINE__, "ss", "getsockname:", strerror(errno));
492 return 0;
495 srv_socket = server_oneshot_getsock(srv, &cnt_addr);
496 if (NULL == srv_socket) return 0;
498 cnt_len = sizeof(cnt_addr);
499 if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
500 log_error_write(srv, __FILE__, __LINE__, "ss", "getpeername:", strerror(errno));
501 return 0;
504 /*(must set flags; fd did not pass through fdevent accept() logic)*/
505 if (-1 == fdevent_fcntl_set_nb_cloexec(srv->ev, fd)) {
506 log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl:", strerror(errno));
507 return 0;
510 if (sock_addr_get_family(&cnt_addr) != AF_UNIX) {
511 network_accept_tcp_nagle_disable(fd);
514 con = connection_accepted(srv, srv_socket, &cnt_addr, fd);
515 if (NULL == con) return 0;
517 connection_state_machine(srv, con);
518 return 1;
522 __attribute_cold__
523 static void show_version (void) {
524 char *b = PACKAGE_DESC TEXT_SSL \
525 " - a light and fast webserver\n"
526 #ifdef NONREPRODUCIBLE_BUILD
527 "Build-Date: " __DATE__ " " __TIME__ "\n";
528 #endif
530 write_all(STDOUT_FILENO, b, strlen(b));
533 __attribute_cold__
534 static void show_features (void) {
535 static const char features[] =
536 "\nFeatures:\n\n"
537 #ifdef HAVE_IPV6
538 "\t+ IPv6 support\n"
539 #else
540 "\t- IPv6 support\n"
541 #endif
542 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
543 "\t+ zlib support\n"
544 #else
545 "\t- zlib support\n"
546 #endif
547 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
548 "\t+ bzip2 support\n"
549 #else
550 "\t- bzip2 support\n"
551 #endif
552 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
553 "\t+ crypt support\n"
554 #else
555 "\t- crypt support\n"
556 #endif
557 #ifdef USE_SSL
558 "\t+ SSL support\n"
559 #else
560 "\t- SSL support\n"
561 #endif
562 #ifdef HAVE_LIBPCRE
563 "\t+ PCRE support\n"
564 #else
565 "\t- PCRE support\n"
566 #endif
567 #ifdef HAVE_MYSQL
568 "\t+ MySQL support\n"
569 #else
570 "\t- MySQL support\n"
571 #endif
572 #ifdef HAVE_PGSQL
573 "\t+ PgSQL support\n"
574 #else
575 "\t- PgSQL support\n"
576 #endif
577 #ifdef HAVE_DBI
578 "\t+ DBI support\n"
579 #else
580 "\t- DBI support\n"
581 #endif
582 #ifdef HAVE_KRB5
583 "\t+ Kerberos support\n"
584 #else
585 "\t- Kerberos support\n"
586 #endif
587 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
588 "\t+ LDAP support\n"
589 #else
590 "\t- LDAP support\n"
591 #endif
592 #ifdef HAVE_PAM
593 "\t+ PAM support\n"
594 #else
595 "\t- PAM support\n"
596 #endif
597 #ifdef USE_MEMCACHED
598 "\t+ memcached support\n"
599 #else
600 "\t- memcached support\n"
601 #endif
602 #ifdef HAVE_FAM_H
603 "\t+ FAM support\n"
604 #else
605 "\t- FAM support\n"
606 #endif
607 #ifdef HAVE_LUA_H
608 "\t+ LUA support\n"
609 #else
610 "\t- LUA support\n"
611 #endif
612 #ifdef HAVE_LIBXML_H
613 "\t+ xml support\n"
614 #else
615 "\t- xml support\n"
616 #endif
617 #ifdef HAVE_SQLITE3_H
618 "\t+ SQLite support\n"
619 #else
620 "\t- SQLite support\n"
621 #endif
622 #ifdef HAVE_GDBM_H
623 "\t+ GDBM support\n"
624 #else
625 "\t- GDBM support\n"
626 #endif
628 show_version();
629 printf("%s%s%s\n", fdevent_show_event_handlers(), network_write_show_handlers(), features);
632 __attribute_cold__
633 static void show_help (void) {
634 char *b = PACKAGE_DESC TEXT_SSL
635 #ifdef NONREPRODUCIBLE_BUILD
636 " ("__DATE__ " " __TIME__ ")"
637 #endif
638 " - a light and fast webserver\n" \
639 "usage:\n" \
640 " -f <name> filename of the config-file\n" \
641 " -m <name> module directory (default: "LIBRARY_DIR")\n" \
642 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
643 " -1 process single (one) request on stdin socket, then exit\n" \
644 " -p print the parsed config-file in internal form, and exit\n" \
645 " -t test config-file syntax, then exit\n" \
646 " -tt test config-file syntax, load and init modules, then exit\n" \
647 " -D don't go to background (default: go to background)\n" \
648 " -v show version\n" \
649 " -V show compile-time features\n" \
650 " -h show this help\n" \
651 "\n"
653 write_all(STDOUT_FILENO, b, strlen(b));
657 * open the errorlog
659 * we have 4 possibilities:
660 * - stderr (default)
661 * - syslog
662 * - logfile
663 * - pipe
667 static int log_error_open(server *srv) {
668 log_error_st *errh = srv->errh;
669 int errfd;
670 #ifdef HAVE_SYSLOG_H
671 /* perhaps someone wants to use syslog() */
672 int facility = -1;
673 if (!buffer_string_is_empty(srv->srvconf.syslog_facility)) {
674 static const struct facility_name_st {
675 const char *name;
676 int val;
677 } facility_names[] = {
678 { "auth", LOG_AUTH }
679 #ifdef LOG_AUTHPRIV
680 ,{ "authpriv", LOG_AUTHPRIV }
681 #endif
682 #ifdef LOG_CRON
683 ,{ "cron", LOG_CRON }
684 #endif
685 ,{ "daemon", LOG_DAEMON }
686 #ifdef LOG_FTP
687 ,{ "ftp", LOG_FTP }
688 #endif
689 #ifdef LOG_KERN
690 ,{ "kern", LOG_KERN }
691 #endif
692 #ifdef LOG_LPR
693 ,{ "lpr", LOG_LPR }
694 #endif
695 #ifdef LOG_MAIL
696 ,{ "mail", LOG_MAIL }
697 #endif
698 #ifdef LOG_NEWS
699 ,{ "news", LOG_NEWS }
700 #endif
701 ,{ "security", LOG_AUTH } /* DEPRECATED */
702 #ifdef LOG_SYSLOG
703 ,{ "syslog", LOG_SYSLOG }
704 #endif
705 #ifdef LOG_USER
706 ,{ "user", LOG_USER }
707 #endif
708 #ifdef LOG_UUCP
709 ,{ "uucp", LOG_UUCP }
710 #endif
711 ,{ "local0", LOG_LOCAL0 }
712 ,{ "local1", LOG_LOCAL1 }
713 ,{ "local2", LOG_LOCAL2 }
714 ,{ "local3", LOG_LOCAL3 }
715 ,{ "local4", LOG_LOCAL4 }
716 ,{ "local5", LOG_LOCAL5 }
717 ,{ "local6", LOG_LOCAL6 }
718 ,{ "local7", LOG_LOCAL7 }
720 unsigned int i;
721 for (i = 0; i < sizeof(facility_names)/sizeof(facility_names[0]); ++i) {
722 const struct facility_name_st *f = facility_names+i;
723 if (0 == strcmp(srv->srvconf.syslog_facility->ptr, f->name)) {
724 facility = f->val;
725 break;
728 if (-1 == facility) {
729 log_error_write(srv, __FILE__, __LINE__, "SBS",
730 "unrecognized server.syslog-facility: \"",
731 srv->srvconf.syslog_facility,
732 "\"; defaulting to \"daemon\" facility");
735 openlog("lighttpd", LOG_CONS|LOG_PID, -1==facility ? LOG_DAEMON : facility);
736 #endif
738 errh->errorlog_mode = ERRORLOG_FD;
739 errh->errorlog_fd = STDERR_FILENO;
741 if (srv->srvconf.errorlog_use_syslog) {
742 errh->errorlog_mode = ERRORLOG_SYSLOG;
744 else if (!buffer_string_is_empty(srv->srvconf.errorlog_file)) {
745 const char *logfile = srv->srvconf.errorlog_file->ptr;
746 int fd = fdevent_open_logger(logfile);
747 if (-1 == fd) {
748 log_error_write(srv, __FILE__, __LINE__, "SSSS",
749 "opening errorlog '", logfile,
750 "' failed: ", strerror(errno));
751 return -1;
753 errh->errorlog_fd = fd;
754 errh->errorlog_mode = logfile[0] == '|' ? ERRORLOG_PIPE : ERRORLOG_FILE;
757 if (errh->errorlog_mode == ERRORLOG_FD && !srv->srvconf.dont_daemonize) {
758 /* We can only log to stderr in dont-daemonize mode;
759 * if we do daemonize and no errorlog file is specified,
760 * we log into /dev/null
762 errh->errorlog_fd = -1;
765 if (!buffer_string_is_empty(srv->srvconf.breakagelog_file)) {
766 const char *logfile = srv->srvconf.breakagelog_file->ptr;
768 if (errh->errorlog_mode == ERRORLOG_FD) {
769 errh->errorlog_fd = dup(STDERR_FILENO);
770 fdevent_setfd_cloexec(errh->errorlog_fd);
773 if (-1 == (errfd = fdevent_open_logger(logfile))) {
774 log_error_write(srv, __FILE__, __LINE__, "SSSS",
775 "opening errorlog '", logfile,
776 "' failed: ", strerror(errno));
777 return -1;
780 if (*logfile == '|') fdevent_breakagelog_logger_pipe(errfd);
782 else if (!srv->srvconf.dont_daemonize) {
783 /* move STDERR_FILENO to /dev/null */
784 if (-1 == (errfd = fdevent_open_devnull())) {
785 log_error_write(srv, __FILE__, __LINE__, "ss",
786 "opening /dev/null failed:", strerror(errno));
787 return -1;
790 else {
791 /*(leave STDERR_FILENO as-is)*/
792 errfd = -1;
795 if (0 != fdevent_set_stdin_stdout_stderr(-1, -1, errfd)) {
796 log_error_write(srv, __FILE__, __LINE__, "ss",
797 "setting stderr failed:", strerror(errno));
798 #ifdef FD_CLOEXEC
799 if (-1 != errfd) close(errfd);
800 #endif
801 return -1;
803 #ifdef FD_CLOEXEC
804 if (-1 != errfd) close(errfd);
805 #endif
807 return 0;
811 * cycle the errorlog
815 static int log_error_cycle(server *srv) {
816 /* cycle only if the error log is a file */
818 log_error_st *errh = srv->errh;
819 if (errh->errorlog_mode == ERRORLOG_FILE) {
820 const char *logfile = srv->srvconf.errorlog_file->ptr;
821 if (-1 == fdevent_cycle_logger(logfile, &errh->errorlog_fd)) {
822 /* write to old log */
823 log_error_write(srv, __FILE__, __LINE__, "SSSS",
824 "cycling errorlog '", logfile,
825 "' failed: ", strerror(errno));
829 return 0;
832 __attribute_cold__
833 static int log_error_close(server *srv) {
834 log_error_st *errh = srv->errh;
835 switch(errh->errorlog_mode) {
836 case ERRORLOG_PIPE:
837 case ERRORLOG_FILE:
838 case ERRORLOG_FD:
839 if (-1 != errh->errorlog_fd) {
840 /* don't close STDERR */
841 /* fdevent_close_logger_pipes() closes ERRORLOG_PIPE */
842 if (STDERR_FILENO != errh->errorlog_fd
843 && ERRORLOG_PIPE != errh->errorlog_mode) {
844 close(errh->errorlog_fd);
846 errh->errorlog_fd = -1;
848 break;
849 case ERRORLOG_SYSLOG:
850 #ifdef HAVE_SYSLOG_H
851 closelog();
852 #endif
853 break;
856 return 0;
859 __attribute_cold__
860 static void server_sockets_save (server *srv) { /* graceful_restart */
861 memcpy(&graceful_sockets, &srv->srv_sockets, sizeof(server_socket_array));
862 memset(&srv->srv_sockets, 0, sizeof(server_socket_array));
863 memcpy(&inherited_sockets, &srv->srv_sockets_inherited, sizeof(server_socket_array));
864 memset(&srv->srv_sockets_inherited, 0, sizeof(server_socket_array));
867 __attribute_cold__
868 static void server_sockets_restore (server *srv) { /* graceful_restart */
869 memcpy(&srv->srv_sockets, &graceful_sockets, sizeof(server_socket_array));
870 memset(&graceful_sockets, 0, sizeof(server_socket_array));
871 memcpy(&srv->srv_sockets_inherited, &inherited_sockets, sizeof(server_socket_array));
872 memset(&inherited_sockets, 0, sizeof(server_socket_array));
875 __attribute_cold__
876 static int server_sockets_set_nb_cloexec (server *srv) {
877 if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */
878 for (size_t i = 0; i < srv->srv_sockets.used; ++i) {
879 server_socket *srv_socket = srv->srv_sockets.ptr[i];
880 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv->ev, srv_socket->fd)) {
881 log_error_write(srv, __FILE__, __LINE__, "ss",
882 "fcntl failed:", strerror(errno));
883 return -1;
886 return 0;
889 __attribute_cold__
890 static void server_sockets_set_event (server *srv, int event) {
891 for (size_t i = 0; i < srv->srv_sockets.used; ++i) {
892 server_socket *srv_socket = srv->srv_sockets.ptr[i];
893 fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event);
897 __attribute_cold__
898 static void server_sockets_unregister (server *srv) {
899 if (2 == srv->sockets_disabled) return;
900 srv->sockets_disabled = 2;
901 for (size_t i = 0; i < srv->srv_sockets.used; ++i)
902 network_unregister_sock(srv, srv->srv_sockets.ptr[i]);
905 __attribute_cold__
906 static void server_sockets_close (server *srv) {
907 /* closing socket right away will make it possible for the next lighttpd
908 * to take over (old-style graceful restart), but only if backends
909 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
910 * than started by lighttpd via "bin-path")
912 if (3 == srv->sockets_disabled) return;
913 for (size_t i = 0; i < srv->srv_sockets.used; ++i) {
914 server_socket *srv_socket = srv->srv_sockets.ptr[i];
915 if (-1 == srv_socket->fd) continue;
916 if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket);
917 close(srv_socket->fd);
918 srv_socket->fd = -1;
919 /* network_close() will cleanup after us */
921 srv->sockets_disabled = 3;
924 __attribute_cold__
925 static void server_graceful_shutdown_maint (server *srv) {
926 connections *conns = srv->conns;
927 for (size_t ndx = 0; ndx < conns->used; ++ndx) {
928 connection * const con = conns->ptr[ndx];
929 int changed = 0;
931 if (con->state == CON_STATE_CLOSE) {
932 /* reduce remaining linger timeout to be
933 * (from zero) *up to* one more second, but no more */
934 if (HTTP_LINGER_TIMEOUT > 1)
935 con->close_timeout_ts -= (HTTP_LINGER_TIMEOUT - 1);
936 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT)
937 changed = 1;
939 else if (con->state == CON_STATE_READ && con->request_count > 1
940 && chunkqueue_is_empty(con->read_queue)) {
941 /* close connections in keep-alive waiting for next request */
942 connection_set_state(srv, con, CON_STATE_ERROR);
943 changed = 1;
946 con->keep_alive = 0; /* disable keep-alive */
948 con->conf.kbytes_per_second = 0; /* disable rate limit */
949 con->conf.global_kbytes_per_second = 0; /* disable rate limit */
950 if (con->traffic_limit_reached) {
951 con->traffic_limit_reached = 0;
952 changed = 1;
955 if (changed) {
956 connection_state_machine(srv, con);
961 __attribute_cold__
962 static void server_graceful_state (server *srv) {
964 if (!srv_shutdown) server_graceful_shutdown_maint(srv);
966 if (!oneshot_fd
967 && (2 == srv->sockets_disabled || 3 == srv->sockets_disabled)) return;
969 log_error_write(srv, __FILE__, __LINE__, "s",
970 "[note] graceful shutdown started");
972 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
973 if (!buffer_string_is_empty(srv->srvconf.changeroot)
974 || oneshot_fd || 2 == graceful_shutdown)
975 graceful_restart = 0;
977 if (graceful_restart) {
978 server_sockets_unregister(srv);
979 if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/
981 else {
982 server_sockets_close(srv);
983 remove_pid_file(srv);
984 buffer_clear(srv->srvconf.pid_file); /*(prevent more removal attempts)*/
988 __attribute_cold__
989 static void server_sockets_enable (server *srv) {
990 server_sockets_set_event(srv, FDEVENT_IN);
991 srv->sockets_disabled = 0;
992 log_error_write(srv, __FILE__, __LINE__, "s",
993 "[note] sockets enabled again");
996 __attribute_cold__
997 static void server_sockets_disable (server *srv) {
998 server_sockets_set_event(srv, 0);
999 srv->sockets_disabled = 1;
1000 log_error_write(srv, __FILE__, __LINE__, "s",
1001 (srv->conns->used >= srv->max_conns)
1002 ? "[note] sockets disabled, connection limit reached"
1003 : "[note] sockets disabled, out-of-fds");
1006 __attribute_cold__
1007 static void server_overload_check (server *srv) {
1008 if (srv->cur_fds + srv->want_fds < srv->max_fds_lowat
1009 && srv->conns->used <= srv->max_conns * 9 / 10) {
1011 server_sockets_enable(srv);
1015 static void server_load_check (server *srv) {
1016 if (srv->cur_fds + srv->want_fds > srv->max_fds_hiwat /* out of fds */
1017 || srv->conns->used >= srv->max_conns) { /* out of connections */
1019 server_sockets_disable(srv);
1023 __attribute_cold__
1024 static void server_process_want_fds (server *srv) {
1025 for (int n = srv->max_fds - srv->cur_fds - 16; n > 0; --n) {
1026 connection *con = fdwaitqueue_unshift(srv, srv->fdwaitqueue);
1027 if (NULL == con) break;
1028 connection_state_machine(srv, con);
1029 --srv->want_fds;
1033 __attribute_cold__
1034 static int server_main (server * const srv, int argc, char **argv) {
1035 int print_config = 0;
1036 int test_config = 0;
1037 int i_am_root = 0;
1038 int o;
1039 #ifdef HAVE_FORK
1040 int num_childs = 0;
1041 #endif
1042 size_t i;
1043 #ifdef HAVE_SIGACTION
1044 struct sigaction act;
1045 #endif
1047 #ifdef HAVE_FORK
1048 int parent_pipe_fd = -1;
1049 #endif
1050 int stdin_fd = -1;
1052 #ifdef HAVE_GETUID
1053 i_am_root = (0 == getuid());
1054 #endif
1056 /* initialize globals (including file-scoped static globals) */
1057 oneshot_fd = 0;
1058 srv_shutdown = 0;
1059 graceful_shutdown = 0;
1060 handle_sig_alarm = 1;
1061 handle_sig_hup = 0;
1062 idle_limit = 0;
1063 chunkqueue_set_tempdirs_default_reset();
1064 http_auth_dumbdata_reset();
1065 http_vhostdb_dumbdata_reset();
1066 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1067 /*(intentionally preserved)*/
1068 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1069 /*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/
1070 /*pid_fd = -1;*/
1072 srv->srvconf.port = 0;
1073 srv->srvconf.dont_daemonize = 0;
1074 srv->srvconf.preflight_check = 0;
1076 while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) {
1077 switch(o) {
1078 case 'f':
1079 if (srv->config_storage) {
1080 log_error_write(srv, __FILE__, __LINE__, "s",
1081 "Can only read one config file. Use the include command to use multiple config files.");
1082 return -1;
1084 if (config_read(srv, optarg)) {
1085 return -1;
1087 break;
1088 case 'm':
1089 buffer_copy_string(srv->srvconf.modules_dir, optarg);
1090 break;
1091 case 'i': {
1092 char *endptr;
1093 long timeout = strtol(optarg, &endptr, 0);
1094 if (!*optarg || *endptr || timeout < 0) {
1095 log_error_write(srv, __FILE__, __LINE__, "ss",
1096 "Invalid idle timeout value:", optarg);
1097 return -1;
1099 idle_limit = (time_t)timeout;
1100 break;
1102 case 'p': print_config = 1; break;
1103 case 't': ++test_config; break;
1104 case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO);
1105 break;
1106 case 'D': srv->srvconf.dont_daemonize = 1; break;
1107 case 'v': show_version(); return 0;
1108 case 'V': show_features(); return 0;
1109 case 'h': show_help(); return 0;
1110 default:
1111 show_help();
1112 return -1;
1116 #ifdef __CYGWIN__
1117 if (!srv->config_storage && NULL != getenv("NSSM_SERVICE_NAME")) {
1118 char *dir = getenv("NSSM_SERVICE_DIR");
1119 if (NULL != dir && 0 != chdir(dir)) {
1120 log_error_write(srv, __FILE__, __LINE__, "sss", "chdir failed:", dir, strerror(errno));
1121 return -1;
1123 srv->srvconf.dont_daemonize = 1;
1124 buffer_copy_string_len(srv->srvconf.modules_dir, CONST_STR_LEN("modules"));
1125 if (config_read(srv, "conf/lighttpd.conf")) return -1;
1127 #endif
1129 if (!srv->config_storage) {
1130 log_error_write(srv, __FILE__, __LINE__, "s",
1131 "No configuration available. Try using -f option.");
1132 return -1;
1135 if (print_config) {
1136 data_unset *dc = srv->config_context->data[0];
1137 if (dc) {
1138 dc->fn->print(dc, 0);
1139 fprintf(stdout, "\n");
1140 } else {
1141 /* shouldn't happend */
1142 fprintf(stderr, "global config not found\n");
1146 if (test_config) {
1147 buffer_clear(srv->srvconf.pid_file);
1148 if (1 == test_config) {
1149 printf("Syntax OK\n");
1150 } else { /*(test_config > 1)*/
1151 test_config = 0;
1152 srv->srvconf.preflight_check = 1;
1153 srv->srvconf.dont_daemonize = 1;
1157 if (test_config || print_config) {
1158 return 0;
1161 if (oneshot_fd) {
1162 if (oneshot_fd <= STDERR_FILENO) {
1163 log_error_write(srv, __FILE__, __LINE__, "s",
1164 "Invalid fds at startup with lighttpd -1");
1165 return -1;
1167 graceful_shutdown = 1;
1168 srv->sockets_disabled = 1;
1169 srv->srvconf.dont_daemonize = 1;
1170 buffer_clear(srv->srvconf.pid_file);
1171 if (srv->srvconf.max_worker) {
1172 srv->srvconf.max_worker = 0;
1173 log_error_write(srv, __FILE__, __LINE__, "s",
1174 "server one-shot command line option disables server.max-worker config file option.");
1178 if (buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) {
1179 stdin_fd = dup(STDIN_FILENO);
1180 if (stdin_fd <= STDERR_FILENO) {
1181 log_error_write(srv, __FILE__, __LINE__, "s",
1182 "Invalid fds at startup");
1183 return -1;
1187 /* close stdin and stdout, as they are not needed */
1189 struct stat st;
1190 int devnull;
1191 int errfd;
1192 do {
1193 /* coverity[overwrite_var : FALSE] */
1194 devnull = fdevent_open_devnull();
1195 #ifdef __COVERITY__
1196 __coverity_escape__(devnull);
1197 #endif
1198 } while (-1 != devnull && devnull <= STDERR_FILENO);
1199 if (-1 == devnull) {
1200 log_error_write(srv, __FILE__, __LINE__, "ss",
1201 "opening /dev/null failed:", strerror(errno));
1202 return -1;
1204 errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull;
1205 if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) {
1206 log_error_write(srv, __FILE__, __LINE__, "ss",
1207 "setting default fds failed:", strerror(errno));
1208 #ifdef FD_CLOEXEC
1209 if (-1 != errfd) close(errfd);
1210 if (devnull != errfd) close(devnull);
1211 #endif
1212 return -1;
1214 #ifdef FD_CLOEXEC
1215 if (-1 != errfd) close(errfd);
1216 if (devnull != errfd) close(devnull);
1217 #endif
1220 if (0 != config_set_defaults(srv)) {
1221 log_error_write(srv, __FILE__, __LINE__, "s",
1222 "setting default values failed");
1223 return -1;
1226 /* check document-root */
1227 if (buffer_string_is_empty(srv->config_storage[0]->document_root)) {
1228 log_error_write(srv, __FILE__, __LINE__, "s",
1229 "document-root is not set\n");
1230 return -1;
1233 if (plugins_load(srv)) {
1234 log_error_write(srv, __FILE__, __LINE__, "s",
1235 "loading plugins finally failed");
1236 return -1;
1239 if (HANDLER_GO_ON != plugins_call_init(srv)) {
1240 log_error_write(srv, __FILE__, __LINE__, "s", "Initialization of plugins failed. Going down.");
1241 return -1;
1244 /* mod_indexfile should be listed in server.modules prior to dynamic handlers */
1245 i = 0;
1246 for (buffer *pname = NULL; i < srv->plugins.used; ++i) {
1247 plugin *p = ((plugin **)srv->plugins.ptr)[i];
1248 if (buffer_is_equal_string(p->name, CONST_STR_LEN("indexfile"))) {
1249 if (pname) {
1250 log_error_write(srv, __FILE__, __LINE__, "SB",
1251 "Warning: mod_indexfile should be listed in server.modules prior to mod_", pname);
1253 break;
1255 if (p->handle_subrequest_start && p->handle_subrequest) {
1256 if (!pname) pname = p->name;
1260 /* open pid file BEFORE chroot */
1261 if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/
1262 if (-1 == pid_fd && !buffer_string_is_empty(srv->srvconf.pid_file)) {
1263 if (-1 == (pid_fd = fdevent_open_cloexec(srv->srvconf.pid_file->ptr, 0, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
1264 struct stat st;
1265 if (errno != EEXIST) {
1266 log_error_write(srv, __FILE__, __LINE__, "sbs",
1267 "opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
1268 return -1;
1271 if (0 != stat(srv->srvconf.pid_file->ptr, &st)) {
1272 log_error_write(srv, __FILE__, __LINE__, "sbs",
1273 "stating existing pid-file failed:", srv->srvconf.pid_file, strerror(errno));
1276 if (!S_ISREG(st.st_mode)) {
1277 log_error_write(srv, __FILE__, __LINE__, "sb",
1278 "pid-file exists and isn't regular file:", srv->srvconf.pid_file);
1279 return -1;
1282 if (-1 == (pid_fd = fdevent_open_cloexec(srv->srvconf.pid_file->ptr, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
1283 log_error_write(srv, __FILE__, __LINE__, "sbs",
1284 "opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
1285 return -1;
1291 #ifdef HAVE_GETRLIMIT
1292 struct rlimit rlim;
1293 int use_rlimit = 1;
1294 #ifdef HAVE_VALGRIND_VALGRIND_H
1295 if (RUNNING_ON_VALGRIND) use_rlimit = 0;
1296 #endif
1298 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
1299 log_error_write(srv, __FILE__, __LINE__,
1300 "ss", "couldn't get 'max filedescriptors'",
1301 strerror(errno));
1302 return -1;
1306 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1308 if (use_rlimit && srv->srvconf.max_fds
1309 && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) {
1310 /* set rlimits */
1312 rlim.rlim_cur = srv->srvconf.max_fds;
1313 if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds;
1315 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
1316 log_error_write(srv, __FILE__, __LINE__,
1317 "ss", "couldn't set 'max filedescriptors'",
1318 strerror(errno));
1319 return -1;
1323 srv->max_fds = rlim.rlim_cur;
1324 /*(default upper limit of 4k if server.max-fds not specified)*/
1325 if (i_am_root && 0 == srv->srvconf.max_fds && rlim.rlim_cur > 4096)
1326 srv->max_fds = 4096;
1328 /* set core file rlimit, if enable_cores is set */
1329 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
1330 rlim.rlim_cur = rlim.rlim_max;
1331 setrlimit(RLIMIT_CORE, &rlim);
1333 #endif
1336 /* we need root-perms for port < 1024 */
1337 if (0 != network_init(srv, stdin_fd)) {
1338 return -1;
1341 if (i_am_root) {
1342 #ifdef HAVE_PWD_H
1343 /* set user and group */
1344 struct group *grp = NULL;
1345 struct passwd *pwd = NULL;
1347 if (!buffer_string_is_empty(srv->srvconf.groupname)) {
1348 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
1349 log_error_write(srv, __FILE__, __LINE__, "sb",
1350 "can't find groupname", srv->srvconf.groupname);
1351 return -1;
1355 if (!buffer_string_is_empty(srv->srvconf.username)) {
1356 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
1357 log_error_write(srv, __FILE__, __LINE__, "sb",
1358 "can't find username", srv->srvconf.username);
1359 return -1;
1362 if (pwd->pw_uid == 0) {
1363 log_error_write(srv, __FILE__, __LINE__, "s",
1364 "I will not set uid to 0\n");
1365 return -1;
1368 if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) {
1369 log_error_write(srv, __FILE__, __LINE__, "sd",
1370 "can't find group id", pwd->pw_gid);
1371 return -1;
1375 if (NULL != grp) {
1376 if (grp->gr_gid == 0) {
1377 log_error_write(srv, __FILE__, __LINE__, "s",
1378 "I will not set gid to 0\n");
1379 return -1;
1384 * Change group before chroot, when we have access
1385 * to /etc/group
1386 * */
1387 if (NULL != grp) {
1388 if (-1 == setgid(grp->gr_gid)) {
1389 log_error_write(srv, __FILE__, __LINE__, "ss", "setgid failed: ", strerror(errno));
1390 return -1;
1392 if (-1 == setgroups(0, NULL)) {
1393 log_error_write(srv, __FILE__, __LINE__, "ss", "setgroups failed: ", strerror(errno));
1394 return -1;
1396 if (!buffer_string_is_empty(srv->srvconf.username)) {
1397 initgroups(srv->srvconf.username->ptr, grp->gr_gid);
1400 #endif
1401 #ifdef HAVE_CHROOT
1402 if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
1403 tzset();
1405 if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
1406 log_error_write(srv, __FILE__, __LINE__, "ss", "chroot failed: ", strerror(errno));
1407 return -1;
1409 if (-1 == chdir("/")) {
1410 log_error_write(srv, __FILE__, __LINE__, "ss", "chdir failed: ", strerror(errno));
1411 return -1;
1414 #endif
1415 #ifdef HAVE_PWD_H
1416 /* drop root privs */
1417 if (NULL != pwd) {
1418 if (-1 == setuid(pwd->pw_uid)) {
1419 log_error_write(srv, __FILE__, __LINE__, "ss", "setuid failed: ", strerror(errno));
1420 return -1;
1423 #endif
1424 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1426 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1428 if (srv->srvconf.enable_cores) {
1429 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1431 #endif
1434 /* set max-conns */
1435 if (srv->srvconf.max_conns > srv->max_fds/2) {
1436 /* we can't have more connections than max-fds/2 */
1437 log_error_write(srv, __FILE__, __LINE__, "sdd", "can't have more connections than fds/2: ", srv->srvconf.max_conns, srv->max_fds);
1438 srv->max_conns = srv->max_fds/2;
1439 } else if (srv->srvconf.max_conns) {
1440 /* otherwise respect the wishes of the user */
1441 srv->max_conns = srv->srvconf.max_conns;
1442 } else {
1443 /* or use the default: we really don't want to hit max-fds */
1444 srv->max_conns = srv->max_fds/3;
1447 #ifdef HAVE_FORK
1448 /* network is up, let's daemonize ourself */
1449 if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) {
1450 parent_pipe_fd = daemonize();
1452 #endif
1453 graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/
1454 if (0 == oneshot_fd) graceful_shutdown = 0;
1457 #ifdef HAVE_SIGACTION
1458 memset(&act, 0, sizeof(act));
1459 act.sa_handler = SIG_IGN;
1460 sigaction(SIGPIPE, &act, NULL);
1461 # if defined(SA_SIGINFO)
1462 last_sighup_info.si_uid = 0,
1463 last_sighup_info.si_pid = 0;
1464 last_sigterm_info.si_uid = 0,
1465 last_sigterm_info.si_pid = 0;
1466 act.sa_sigaction = sigaction_handler;
1467 sigemptyset(&act.sa_mask);
1468 act.sa_flags = SA_SIGINFO;
1469 # else
1470 act.sa_handler = signal_handler;
1471 sigemptyset(&act.sa_mask);
1472 act.sa_flags = 0;
1473 # endif
1474 sigaction(SIGINT, &act, NULL);
1475 sigaction(SIGTERM, &act, NULL);
1476 sigaction(SIGHUP, &act, NULL);
1477 sigaction(SIGALRM, &act, NULL);
1478 sigaction(SIGUSR1, &act, NULL);
1480 /* it should be safe to restart syscalls after SIGCHLD */
1481 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
1482 sigaction(SIGCHLD, &act, NULL);
1484 #elif defined(HAVE_SIGNAL)
1485 /* ignore the SIGPIPE from sendfile() */
1486 signal(SIGPIPE, SIG_IGN);
1487 signal(SIGALRM, signal_handler);
1488 signal(SIGTERM, signal_handler);
1489 signal(SIGHUP, signal_handler);
1490 signal(SIGCHLD, signal_handler);
1491 signal(SIGINT, signal_handler);
1492 signal(SIGUSR1, signal_handler);
1493 #endif
1496 srv->gid = getgid();
1497 srv->uid = getuid();
1498 srv->pid = getpid();
1500 /* write pid file */
1501 if (pid_fd > 2) {
1502 buffer_copy_int(srv->tmp_buf, srv->pid);
1503 buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\n"));
1504 if (-1 == write_all(pid_fd, CONST_BUF_LEN(srv->tmp_buf))) {
1505 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't write pid file:", strerror(errno));
1506 close(pid_fd);
1507 pid_fd = -1;
1508 return -1;
1510 } else if (pid_fd < -2) {
1511 pid_fd = -pid_fd;
1514 /* Close stderr ASAP in the child process to make sure that nothing
1515 * is being written to that fd which may not be valid anymore. */
1516 if (!srv->srvconf.preflight_check) {
1517 if (-1 == log_error_open(srv)) {
1518 log_error_write(srv, __FILE__, __LINE__, "s", "Opening errorlog failed. Going down.");
1519 return -1;
1521 log_error_write(srv, __FILE__, __LINE__, "s", "server started (" PACKAGE_DESC ")");
1524 if (buffer_is_empty(srv->config_storage[0]->server_tag)) {
1525 buffer_copy_string_len(srv->config_storage[0]->server_tag, CONST_STR_LEN(PACKAGE_DESC));
1528 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1529 log_error_write(srv, __FILE__, __LINE__, "s", "Configuration of plugins failed. Going down.");
1530 return -1;
1533 /* settings might be enabled during module config set defaults */
1534 srv->config_storage[0]->high_precision_timestamps = srv->srvconf.high_precision_timestamps;
1536 /* dump unused config-keys */
1537 for (i = 0; i < srv->config_context->used; i++) {
1538 array *config = ((data_config *)srv->config_context->data[i])->value;
1539 size_t j;
1541 for (j = 0; config && j < config->used; j++) {
1542 data_unset *du = config->data[j];
1544 /* all var.* is known as user defined variable */
1545 if (strncmp(du->key->ptr, "var.", sizeof("var.") - 1) == 0) {
1546 continue;
1549 if (NULL == array_get_element_klen(srv->config_touched, CONST_BUF_LEN(du->key))) {
1550 log_error_write(srv, __FILE__, __LINE__, "sbs",
1551 "WARNING: unknown config-key:",
1552 du->key,
1553 "(ignored)");
1558 if (srv->config_unsupported) {
1559 log_error_write(srv, __FILE__, __LINE__, "s",
1560 "Configuration contains unsupported keys. Going down.");
1563 if (srv->config_deprecated) {
1564 log_error_write(srv, __FILE__, __LINE__, "s",
1565 "Configuration contains deprecated keys. Going down.");
1568 if (srv->config_unsupported || srv->config_deprecated) {
1569 return -1;
1572 if (srv->srvconf.preflight_check) {
1573 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1574 return 0;
1578 #ifdef HAVE_FORK
1580 * notify daemonize-grandparent of successful startup
1581 * do this before any further forking is done (workers)
1583 if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) {
1584 if (0 > write(parent_pipe_fd, "", 1)) return -1;
1585 close(parent_pipe_fd);
1588 if (idle_limit && srv->srvconf.max_worker) {
1589 srv->srvconf.max_worker = 0;
1590 log_error_write(srv, __FILE__, __LINE__, "s",
1591 "server idle time limit command line option disables server.max-worker config file option.");
1594 /* start watcher and workers */
1595 num_childs = srv->srvconf.max_worker;
1596 if (num_childs > 0) {
1597 pid_t pids[num_childs];
1598 pid_t pid;
1599 const int npids = num_childs;
1600 int child = 0;
1601 unsigned int timer = 0;
1602 for (int n = 0; n < npids; ++n) pids[n] = -1;
1603 while (!child && !srv_shutdown && !graceful_shutdown) {
1604 if (num_childs > 0) {
1605 switch ((pid = fork())) {
1606 case -1:
1607 return -1;
1608 case 0:
1609 child = 1;
1610 alarm(0);
1611 break;
1612 default:
1613 num_childs--;
1614 for (int n = 0; n < npids; ++n) {
1615 if (-1 == pids[n]) {
1616 pids[n] = pid;
1617 break;
1620 break;
1622 } else {
1623 int status;
1625 if (-1 != (pid = wait(&status))) {
1626 srv->cur_ts = time(NULL);
1627 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1628 if (!timer) alarm((timer = 5));
1629 continue;
1631 switch (fdevent_reaped_logger_pipe(pid)) {
1632 default: break;
1633 case -1: if (!timer) alarm((timer = 5));
1634 /* fall through */
1635 case 1: continue;
1637 /**
1638 * check if one of our workers went away
1640 for (int n = 0; n < npids; ++n) {
1641 if (pid == pids[n]) {
1642 pids[n] = -1;
1643 num_childs++;
1644 break;
1647 } else {
1648 switch (errno) {
1649 case EINTR:
1650 srv->cur_ts = time(NULL);
1652 * if we receive a SIGHUP we have to close our logs ourself as we don't
1653 * have the mainloop who can help us here
1655 if (handle_sig_hup) {
1656 handle_sig_hup = 0;
1658 log_error_cycle(srv);
1660 /* forward SIGHUP to workers */
1661 for (int n = 0; n < npids; ++n) {
1662 if (pids[n] > 0) kill(pids[n], SIGHUP);
1665 if (handle_sig_alarm) {
1666 handle_sig_alarm = 0;
1667 timer = 0;
1668 plugins_call_handle_trigger(srv);
1669 fdevent_restart_logger_pipes(srv->cur_ts);
1671 break;
1672 default:
1673 break;
1680 * for the parent this is the exit-point
1682 if (!child) {
1683 /**
1684 * kill all children too
1686 if (graceful_shutdown || graceful_restart) {
1687 /* flag to ignore one SIGINT if graceful_restart */
1688 if (graceful_restart) graceful_restart = 2;
1689 kill(0, SIGINT);
1690 server_graceful_state(srv);
1691 } else if (srv_shutdown) {
1692 kill(0, SIGTERM);
1695 return 0;
1698 /* ignore SIGUSR1 in workers; only parent directs graceful restart */
1699 #ifdef HAVE_SIGACTION
1701 struct sigaction actignore;
1702 memset(&actignore, 0, sizeof(actignore));
1703 actignore.sa_handler = SIG_IGN;
1704 sigaction(SIGUSR1, &actignore, NULL);
1706 #elif defined(HAVE_SIGNAL)
1707 signal(SIGUSR1, SIG_IGN);
1708 #endif
1711 * make sure workers do not muck with pid-file
1713 if (0 <= pid_fd) {
1714 close(pid_fd);
1715 pid_fd = -1;
1717 buffer_clear(srv->srvconf.pid_file);
1719 fdevent_clr_logger_pipe_pids();
1720 srv->pid = getpid();
1721 li_rand_reseed();
1723 #endif
1725 if (NULL == (srv->ev = fdevent_init(srv))) {
1726 log_error_write(srv, __FILE__, __LINE__,
1727 "s", "fdevent_init failed");
1728 return -1;
1731 srv->max_fds_lowat = srv->max_fds * 8 / 10;
1732 srv->max_fds_hiwat = srv->max_fds * 9 / 10;
1734 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1735 #ifdef HAVE_SIGACTION
1736 sigaction(SIGCHLD, &act, NULL);
1737 #elif defined(HAVE_SIGNAL)
1738 signal(SIGCHLD, signal_handler);
1739 #endif
1742 * kqueue() is called here, select resets its internals,
1743 * all server sockets get their handlers
1745 * */
1746 if (0 != network_register_fdevents(srv)) {
1747 return -1;
1750 /* might fail if user is using fam (not gamin) and famd isn't running */
1751 if (NULL == (srv->stat_cache = stat_cache_init(srv))) {
1752 log_error_write(srv, __FILE__, __LINE__, "s",
1753 "stat-cache could not be setup, dieing.");
1754 return -1;
1757 #ifdef USE_ALARM
1759 /* setup periodic timer (1 second) */
1760 struct itimerval interval;
1761 interval.it_interval.tv_sec = 1;
1762 interval.it_interval.tv_usec = 0;
1763 interval.it_value.tv_sec = 1;
1764 interval.it_value.tv_usec = 0;
1765 if (setitimer(ITIMER_REAL, &interval, NULL)) {
1766 log_error_write(srv, __FILE__, __LINE__, "s", "setting timer failed");
1767 return -1;
1770 #endif
1773 /* get the current number of FDs */
1775 int fd = fdevent_open_devnull();
1776 if (fd >= 0) {
1777 srv->cur_fds = fd;
1778 close(fd);
1782 if (0 != server_sockets_set_nb_cloexec(srv)) {
1783 return -1;
1786 /* plugin hook for worker_init */
1787 if (HANDLER_GO_ON != plugins_call_worker_init(srv))
1788 return -1;
1790 if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) {
1791 oneshot_fd = -1;
1794 return 1;
1797 __attribute_cold__
1798 __attribute_noinline__
1799 static int server_handle_sighup (server * const srv) {
1800 handler_t r;
1802 /* cycle logfiles */
1804 switch(r = plugins_call_handle_sighup(srv)) {
1805 case HANDLER_GO_ON:
1806 break;
1807 default:
1808 log_error_write(srv, __FILE__, __LINE__, "sd", "sighup-handler return with an error", r);
1809 break;
1812 if (-1 == log_error_cycle(srv)) {
1813 log_error_write(srv, __FILE__, __LINE__, "s", "cycling errorlog failed, dying");
1815 return -1;
1816 } else {
1817 #ifdef HAVE_SIGACTION
1818 log_error_write(srv, __FILE__, __LINE__, "sdsd",
1819 "logfiles cycled UID =",
1820 last_sighup_info.si_uid,
1821 "PID =",
1822 last_sighup_info.si_pid);
1823 #else
1824 log_error_write(srv, __FILE__, __LINE__, "s",
1825 "logfiles cycled");
1826 #endif
1829 return 0;
1832 __attribute_noinline__
1833 static void server_handle_sigalrm (server * const srv, time_t min_ts, time_t last_active_ts) {
1834 connections *conns = srv->conns;
1835 handler_t r;
1837 switch(r = plugins_call_handle_trigger(srv)) {
1838 case HANDLER_GO_ON:
1839 break;
1840 case HANDLER_ERROR:
1841 log_error_write(srv, __FILE__, __LINE__, "s", "one of the triggers failed");
1842 break;
1843 default:
1844 log_error_write(srv, __FILE__, __LINE__, "d", r);
1845 break;
1848 srv->cur_ts = min_ts;
1850 /* check idle time limit, if enabled */
1851 if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) {
1852 log_error_write(srv, __FILE__, __LINE__, "sDs", "[note] idle timeout", (int)idle_limit,
1853 "s exceeded, initiating graceful shutdown");
1854 graceful_shutdown = 2; /* value 2 indicates idle timeout */
1855 if (graceful_restart) {
1856 graceful_restart = 0;
1857 if (pid_fd < -2) pid_fd = -pid_fd;
1858 server_sockets_close(srv);
1862 #ifdef HAVE_GETLOADAVG
1863 /* refresh loadavg data every 30 seconds */
1864 if (srv->srvconf.loadts + 30 < min_ts) {
1865 if (-1 != getloadavg(srv->srvconf.loadavg, 3)) {
1866 srv->srvconf.loadts = min_ts;
1869 #endif
1871 /* free excess chunkqueue buffers every 64 seconds */
1872 if (0 == (min_ts & 0x3f)) chunkqueue_chunk_pool_clear();
1873 /* cleanup stat-cache */
1874 stat_cache_trigger_cleanup(srv);
1875 /* reset global/aggregate rate limit counters */
1876 for (size_t i = 0; i < srv->config_context->used; ++i) {
1877 srv->config_storage[i]->global_bytes_per_second_cnt = 0;
1879 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1880 if (graceful_shutdown && !srv_shutdown) server_graceful_shutdown_maint(srv);
1882 * check all connections for timeouts
1885 for (size_t ndx = 0; ndx < conns->used; ++ndx) {
1886 connection * const con = conns->ptr[ndx];
1887 const int waitevents = fdevent_fdnode_interest(con->fdn);
1888 int changed = 0;
1889 int t_diff;
1891 if (con->state == CON_STATE_CLOSE) {
1892 if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
1893 changed = 1;
1895 } else if (waitevents & FDEVENT_IN) {
1896 if (con->request_count == 1 || con->state != CON_STATE_READ) { /* e.g. CON_STATE_READ_POST || CON_STATE_WRITE */
1897 if (srv->cur_ts - con->read_idle_ts > con->conf.max_read_idle) {
1898 /* time - out */
1899 if (con->conf.log_request_handling) {
1900 log_error_write(srv, __FILE__, __LINE__, "sd",
1901 "connection closed - read timeout:", con->fd);
1904 connection_set_state(srv, con, CON_STATE_ERROR);
1905 changed = 1;
1907 } else {
1908 if (srv->cur_ts - con->read_idle_ts > con->keep_alive_idle) {
1909 /* time - out */
1910 if (con->conf.log_request_handling) {
1911 log_error_write(srv, __FILE__, __LINE__, "sd",
1912 "connection closed - keep-alive timeout:", con->fd);
1915 connection_set_state(srv, con, CON_STATE_ERROR);
1916 changed = 1;
1921 /* max_write_idle timeout currently functions as backend timeout,
1922 * too, after response has been started.
1923 * future: have separate backend timeout, and then change this
1924 * to check for write interest before checking for timeout */
1925 /*if (waitevents & FDEVENT_OUT)*/
1926 if ((con->state == CON_STATE_WRITE) &&
1927 (con->write_request_ts != 0)) {
1928 #if 0
1929 if (srv->cur_ts - con->write_request_ts > 60) {
1930 log_error_write(srv, __FILE__, __LINE__, "sdd",
1931 "connection closed - pre-write-request-timeout:", con->fd, srv->cur_ts - con->write_request_ts);
1933 #endif
1935 if (srv->cur_ts - con->write_request_ts > con->conf.max_write_idle) {
1936 /* time - out */
1937 if (con->conf.log_timeouts) {
1938 log_error_write(srv, __FILE__, __LINE__, "sbsbsosds",
1939 "NOTE: a request from",
1940 con->dst_addr_buf,
1941 "for",
1942 con->request.uri,
1943 "timed out after writing",
1944 con->bytes_written,
1945 "bytes. We waited",
1946 (int)con->conf.max_write_idle,
1947 "seconds. If this a problem increase server.max-write-idle");
1949 connection_set_state(srv, con, CON_STATE_ERROR);
1950 changed = 1;
1954 /* we don't like div by zero */
1955 if (0 == (t_diff = srv->cur_ts - con->connection_start)) t_diff = 1;
1957 if (con->traffic_limit_reached &&
1958 (con->conf.kbytes_per_second == 0 ||
1959 ((con->bytes_written / t_diff) < con->conf.kbytes_per_second * 1024))) {
1960 /* enable connection again */
1961 con->traffic_limit_reached = 0;
1963 changed = 1;
1966 con->bytes_written_cur_second = 0;
1968 if (changed) {
1969 connection_state_machine(srv, con);
1974 __attribute_noinline__
1975 static void server_handle_sigchld (server * const srv) {
1976 pid_t pid;
1977 do {
1978 int status;
1979 pid = waitpid(-1, &status, WNOHANG);
1980 if (pid > 0) {
1981 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1982 continue;
1984 if (0 == srv->srvconf.max_worker) {
1985 /* check piped-loggers and restart, even if shutting down */
1986 if (fdevent_waitpid_logger_pipe_pid(pid, srv->cur_ts)) {
1987 continue;
1991 } while (pid > 0 || (-1 == pid && errno == EINTR));
1994 __attribute_hot__
1995 __attribute_noinline__
1996 static int server_main_loop (server * const srv) {
1997 connections * const joblist = srv->joblist;
1998 time_t last_active_ts = time(NULL);
2000 while (!srv_shutdown) {
2002 if (handle_sig_hup) {
2003 handle_sig_hup = 0;
2004 if (server_handle_sighup(srv)) return -1;
2007 if (handle_sig_alarm) {
2008 time_t min_ts = time(NULL);
2009 #ifdef USE_ALARM
2010 handle_sig_alarm = 0;
2011 #endif
2012 if (min_ts != srv->cur_ts) {
2013 server_handle_sigalrm(srv, min_ts, last_active_ts);
2017 if (handle_sig_child) {
2018 handle_sig_child = 0;
2019 server_handle_sigchld(srv);
2022 if (graceful_shutdown) {
2023 server_graceful_state(srv);
2024 if (srv->conns->used == 0) {
2025 /* we are in graceful shutdown phase and all connections are closed
2026 * we are ready to terminate without harming anyone */
2027 srv_shutdown = 1;
2028 break;
2030 } else if (srv->sockets_disabled) {
2031 server_overload_check(srv);
2032 } else {
2033 server_load_check(srv);
2036 if (srv->want_fds) {
2037 server_process_want_fds(srv);
2040 if (fdevent_poll(srv->ev, 1000) > 0) {
2041 last_active_ts = srv->cur_ts;
2044 for (size_t ndx = 0; ndx < joblist->used; ++ndx) {
2045 connection *con = joblist->ptr[ndx];
2046 connection_state_machine(srv, con);
2048 joblist->used = 0;
2051 return 0;
2054 __attribute_cold__
2055 int main (int argc, char **argv) {
2056 int rc;
2058 #ifdef HAVE_GETUID
2059 #ifndef HAVE_ISSETUGID
2060 #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2061 #endif
2062 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2063 fprintf(stderr,
2064 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2065 return -1;
2067 #endif
2069 /* for nice %b handling in strftime() */
2070 setlocale(LC_TIME, "C");
2072 do {
2073 server * const srv = server_init();
2075 if (graceful_restart) {
2076 server_sockets_restore(srv);
2077 optind = 1;
2080 rc = server_main(srv, argc, argv);
2081 if (rc > 0 && 0 == (rc = server_main_loop(srv))) {
2082 if (graceful_shutdown || graceful_restart) {
2083 server_graceful_state(srv);
2086 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */
2087 log_error_write(srv, __FILE__, __LINE__, "s",
2088 "server stopped after idle timeout");
2089 } else {
2090 #ifdef HAVE_SIGACTION
2091 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2092 "server stopped by UID =",
2093 last_sigterm_info.si_uid,
2094 "PID =",
2095 last_sigterm_info.si_pid);
2096 #else
2097 log_error_write(srv, __FILE__, __LINE__, "s",
2098 "server stopped");
2099 #endif
2103 /* clean-up */
2104 remove_pid_file(srv);
2105 log_error_close(srv);
2106 fdevent_close_logger_pipes();
2107 if (graceful_restart)
2108 server_sockets_save(srv);
2109 else
2110 network_close(srv);
2111 connections_free(srv);
2112 plugins_free(srv);
2113 server_free(srv);
2115 if (0 != rc || !graceful_restart) break;
2117 /* wait for all children to exit before graceful restart */
2118 while (waitpid(-1, NULL, 0) > 0) ;
2119 } while (graceful_restart);
2121 return rc;