xref: /lighttpd1.4/src/server.c (revision 4933a225)
1 #include "first.h"
2 
3 #include "base.h"
4 #include "buffer.h"
5 #include "network.h"
6 #include "log.h"
7 #include "rand.h"
8 #include "chunk.h"
9 #include "h2.h"             /* h2_send_1xx() */
10 #include "http_auth.h"      /* http_auth_dumbdata_reset() */
11 #include "http_vhostdb.h"   /* http_vhostdb_dumbdata_reset() */
12 #include "fdevent.h"
13 #include "connections.h"
14 #include "sock_addr.h"
15 #include "stat_cache.h"
16 #include "plugin.h"
17 #include "plugin_config.h"  /* config_plugin_value_tobool() */
18 #include "network_write.h"  /* network_write_show_handlers() */
19 #include "reqpool.h"        /* request_pool_init() request_pool_free() */
20 #include "response.h"       /* http_response_send_1xx_cb_set() strftime_cache_reset() */
21 
22 #ifdef HAVE_VERSIONSTAMP_H
23 # include "versionstamp.h"
24 #else
25 # define REPO_VERSION ""
26 #endif
27 
28 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
29 static const buffer default_server_tag = { CONST_STR_LEN(PACKAGE_DESC)+1, 0 };
30 
31 #include <sys/types.h>
32 #include <sys/time.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 
36 #include <string.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <unistd.h>
40 #include <stdlib.h>
41 #include <time.h>
42 #include <signal.h>
43 #include <locale.h>
44 
45 #include <stdio.h>
46 
47 #ifdef HAVE_GETOPT_H
48 # include <getopt.h>
49 #endif
50 
51 #ifdef HAVE_VALGRIND_VALGRIND_H
52 # include <valgrind/valgrind.h>
53 #endif
54 
55 #ifdef HAVE_SYS_WAIT_H
56 # include <sys/wait.h>
57 #endif
58 
59 #ifdef HAVE_PWD_H
60 # include <grp.h>
61 # include <pwd.h>
62 #endif
63 
64 #ifdef HAVE_SYS_LOADAVG_H
65 # include <sys/loadavg.h>
66 #endif
67 
68 #ifdef HAVE_SYS_RESOURCE_H
69 # include <sys/resource.h>
70 #endif
71 
72 #ifdef HAVE_SYS_PRCTL_H
73 # include <sys/prctl.h>
74 #endif
75 
76 #include "sys-crypto.h"
77 #if defined(USE_OPENSSL_CRYPTO) \
78  || defined(USE_MBEDTLS_CRYPTO) \
79  || defined(USE_NSS_CRYPTO) \
80  || defined(USE_GNUTLS_CRYPTO) \
81  || defined(USE_WOLFTLS_CRYPTO)
82 #define TEXT_SSL " (ssl)"
83 #else
84 #define TEXT_SSL
85 #endif
86 
87 #ifndef __sgi
88 /* IRIX doesn't like the alarm based time() optimization */
89 /* #define USE_ALARM */
90 #endif
91 
92 static int oneshot_fd = 0;
93 static int oneshot_fdout = -1;
94 static fdnode *oneshot_fdn = NULL;
95 static int (*oneshot_read_cq)(connection *con, chunkqueue *cq, off_t max_bytes);
96 static volatile int pid_fd = -2;
97 static server_socket_array graceful_sockets;
98 static server_socket_array inherited_sockets;
99 static volatile sig_atomic_t graceful_restart = 0;
100 static volatile sig_atomic_t graceful_shutdown = 0;
101 static volatile sig_atomic_t srv_shutdown = 0;
102 static volatile sig_atomic_t handle_sig_child = 0;
103 static volatile sig_atomic_t handle_sig_alarm = 1;
104 static volatile sig_atomic_t handle_sig_hup = 0;
105 static time_t idle_limit = 0;
106 
107 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
108 static volatile siginfo_t last_sigterm_info;
109 static volatile siginfo_t last_sighup_info;
110 
111 static void sigaction_handler(int sig, siginfo_t *si, void *context) {
112 	static const siginfo_t empty_siginfo;
113 	UNUSED(context);
114 
115 	if (!si) *(const siginfo_t **)&si = &empty_siginfo;
116 
117 	switch (sig) {
118 	case SIGTERM:
119 		srv_shutdown = 1;
120 		last_sigterm_info = *si;
121 		break;
122 	case SIGUSR1:
123 		if (!graceful_shutdown) {
124 			graceful_restart = 1;
125 			graceful_shutdown = 1;
126 			last_sigterm_info = *si;
127 		}
128 		break;
129 	case SIGINT:
130 		if (graceful_shutdown) {
131 			if (2 == graceful_restart)
132 				graceful_restart = 1;
133 			else
134 				srv_shutdown = 1;
135 		} else {
136 			graceful_shutdown = 1;
137 		}
138 		last_sigterm_info = *si;
139 
140 		break;
141 	case SIGALRM:
142 		handle_sig_alarm = 1;
143 		break;
144 	case SIGHUP:
145 		handle_sig_hup = 1;
146 		last_sighup_info = *si;
147 		break;
148 	case SIGCHLD:
149 		handle_sig_child = 1;
150 		break;
151 	}
152 }
153 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
154 static void signal_handler(int sig) {
155 	switch (sig) {
156 	case SIGTERM: srv_shutdown = 1; break;
157 	case SIGUSR1:
158 		if (!graceful_shutdown) {
159 			graceful_restart = 1;
160 			graceful_shutdown = 1;
161 		}
162 		break;
163 	case SIGINT:
164 		if (graceful_shutdown) {
165 			if (2 == graceful_restart)
166 				graceful_restart = 1;
167 			else
168 				srv_shutdown = 1;
169 		} else {
170 			graceful_shutdown = 1;
171 		}
172 		break;
173 	case SIGALRM: handle_sig_alarm = 1; break;
174 	case SIGHUP:  handle_sig_hup = 1; break;
175 	case SIGCHLD: handle_sig_child = 1; break;
176 	}
177 }
178 #endif
179 
180 #ifdef HAVE_FORK
181 static int daemonize(void) {
182 	int pipefd[2];
183 	pid_t pid;
184 #ifdef SIGTTOU
185 	signal(SIGTTOU, SIG_IGN);
186 #endif
187 #ifdef SIGTTIN
188 	signal(SIGTTIN, SIG_IGN);
189 #endif
190 #ifdef SIGTSTP
191 	signal(SIGTSTP, SIG_IGN);
192 #endif
193 
194 	if (pipe(pipefd) < 0) exit(-1);
195 
196 	if (0 > (pid = fork())) exit(-1);
197 
198 	if (0 < pid) {
199 		char buf;
200 		ssize_t bytes;
201 
202 		close(pipefd[1]);
203 		/* parent waits for grandchild to be ready */
204 		do {
205 			bytes = read(pipefd[0], &buf, sizeof(buf));
206 		} while (bytes < 0 && EINTR == errno);
207 		close(pipefd[0]);
208 
209 		if (bytes <= 0) {
210 			/* closed fd (without writing) == failure in grandchild */
211 			fputs("daemonized server failed to start; check error log for details\n", stderr);
212 			exit(-1);
213 		}
214 
215 		exit(0);
216 	}
217 
218 	close(pipefd[0]);
219 
220 	if (-1 == setsid()) exit(0);
221 
222 	signal(SIGHUP, SIG_IGN);
223 
224 	if (0 != fork()) exit(0);
225 
226 	if (0 != chdir("/")) exit(0);
227 
228 	fdevent_setfd_cloexec(pipefd[1]);
229 	return pipefd[1];
230 }
231 #endif
232 
233 __attribute_cold__
234 static server *server_init(void) {
235 	server *srv = calloc(1, sizeof(*srv));
236 	force_assert(srv);
237 #define CLEAN(x) \
238 	srv->x = buffer_init();
239 
240 	CLEAN(tmp_buf);
241 #undef CLEAN
242 	connection_joblist = &srv->joblist_A;
243 
244 	strftime_cache_reset();
245 
246 	li_rand_reseed();
247 
248 	srv->startup_ts = log_epoch_secs = time(NULL);
249 
250 	srv->errh = log_error_st_init();
251 
252 	config_init(srv);
253 
254 	srv->request_env = plugins_call_handle_request_env;
255 
256 	srv->loadavg[0] = 0.0;
257 	srv->loadavg[1] = 0.0;
258 	srv->loadavg[2] = 0.0;
259 	srv->stdin_fd = -1;
260 
261 	return srv;
262 }
263 
264 __attribute_cold__
265 static void server_free(server *srv) {
266 	if (oneshot_fd > 0) {
267 		if (oneshot_fdn) {
268 			fdevent_fdnode_event_del(srv->ev, oneshot_fdn);
269 			fdevent_unregister(srv->ev, oneshot_fd);
270 			oneshot_fdn = NULL;
271 		}
272 		close(oneshot_fd);
273 	}
274 	if (oneshot_fdout >= 0) {
275 		close(oneshot_fdout);
276 	}
277 	if (srv->stdin_fd >= 0) {
278 		close(srv->stdin_fd);
279 	}
280 
281 #define CLEAN(x) \
282 	buffer_free(srv->x);
283 
284 	CLEAN(tmp_buf);
285 
286 #undef CLEAN
287 
288 	fdevent_free(srv->ev);
289 
290 	config_free(srv);
291 
292 	free(srv->joblist_A.ptr);
293 	free(srv->joblist_B.ptr);
294 	free(srv->fdwaitqueue.ptr);
295 
296 	stat_cache_free();
297 
298 	li_rand_cleanup();
299 	chunkqueue_chunk_pool_free();
300 
301 	log_error_st_free(srv->errh);
302 	free(srv);
303 }
304 
305 __attribute_cold__
306 static void remove_pid_file(server *srv) {
307 	if (pid_fd <= -2) return;
308 	if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= pid_fd) {
309 		if (0 != ftruncate(pid_fd, 0)) {
310 			log_perror(srv->errh, __FILE__, __LINE__,
311 			  "ftruncate failed for: %s", srv->srvconf.pid_file->ptr);
312 		}
313 	}
314 	if (0 <= pid_fd) {
315 		close(pid_fd);
316 		pid_fd = -1;
317 	}
318 	if (!buffer_string_is_empty(srv->srvconf.pid_file) &&
319 	    buffer_string_is_empty(srv->srvconf.changeroot)) {
320 		if (0 != unlink(srv->srvconf.pid_file->ptr)) {
321 			if (errno != EACCES && errno != EPERM) {
322 				log_perror(srv->errh, __FILE__, __LINE__,
323 				  "unlink failed for: %s", srv->srvconf.pid_file->ptr);
324 			}
325 		}
326 	}
327 }
328 
329 
330 __attribute_cold__
331 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) {
332 	server_socket *srv_socket, *srv_socket_wild = NULL;
333 	for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
334 		srv_socket = srv->srv_sockets.ptr[i];
335 		if (!sock_addr_is_port_eq(&srv_socket->addr,cnt_addr)) continue;
336 		if (sock_addr_is_addr_eq(&srv_socket->addr,cnt_addr)) return srv_socket;
337 
338 		if (NULL != srv_socket_wild) continue;
339 		if (sock_addr_is_addr_wildcard(&srv_socket->addr)) {
340 			srv_socket_wild = srv_socket;
341 		}
342 	}
343 
344 	if (NULL != srv_socket_wild) {
345 		return srv_socket_wild;
346 	} else if (srv->srv_sockets.used) {
347 		return srv->srv_sockets.ptr[0];
348 	} else {
349 		log_error(srv->errh, __FILE__, __LINE__, "no sockets configured");
350 		return NULL;
351 	}
352 }
353 
354 
355 static int server_oneshot_read_cq(connection *con, chunkqueue *cq, off_t max_bytes) {
356     /* temporary set con->fd to oneshot_fd (fd input) rather than outshot_fdout
357      * (lighttpd generally assumes operation on sockets, so this is a kludge) */
358     int fd = con->fd;
359     con->fd = oneshot_fdn->fd;
360     int rc = oneshot_read_cq(con, cq, max_bytes);
361     con->fd = fd;
362 
363     /* note: optimistic reads (elsewhere) may or may not be enough to re-enable
364      * read interest after FDEVENT_IN interest was paused for other reasons */
365 
366     const int events = fdevent_fdnode_interest(oneshot_fdn);
367     int n = con->is_readable ? 0 : FDEVENT_IN;
368     if (events & FDEVENT_RDHUP)
369         n |= FDEVENT_RDHUP;
370     fdevent_fdnode_event_set(con->srv->ev, oneshot_fdn, n);
371     return rc;
372 }
373 
374 
375 static handler_t server_oneshot_handle_fdevent(void *context, int revents) {
376     connection *con = context;
377 
378     /* note: not sync'd with con->fdn or connection_set_fdevent_interest() */
379     int rdhup = 0;
380     int n = fdevent_fdnode_interest(oneshot_fdn);
381     if (revents & FDEVENT_IN)
382         n &= ~FDEVENT_IN;
383     request_st * const r = &con->request;
384     if (r->state != CON_STATE_ERROR && (revents & (FDEVENT_HUP|FDEVENT_RDHUP))){
385         revents &= ~(FDEVENT_HUP|FDEVENT_RDHUP);
386         /* copied and modified from connection_handle_fdevent()
387          * fdevent_is_tcp_half_closed() will fail on pipe
388          * and, besides, read end of pipes should treat POLLHUP as POLLRDHUP */
389         n &= ~(FDEVENT_IN|FDEVENT_RDHUP);
390         rdhup = 1;
391     }
392     fdevent_fdnode_event_set(con->srv->ev, oneshot_fdn, n);
393 
394     fdnode * const fdn = con->fdn; /* fdn->ctx == con */
395     handler_t rc = ((fdevent_handler)NULL != fdn->handler)
396       ? (*fdn->handler)(con, revents)
397       : HANDLER_FINISHED;
398 
399     if (rdhup) {
400         r->conf.stream_request_body &=
401           ~(FDEVENT_STREAM_REQUEST_BUFMIN|FDEVENT_STREAM_REQUEST_POLLIN);
402         r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLRDHUP;
403         r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_TCP_FIN;
404         con->is_readable = 1; /*(can read 0 for end-of-stream)*/
405         if (chunkqueue_is_empty(con->read_queue)) r->keep_alive = 0;
406         if (r->reqbody_length < -1) /*(transparent proxy mode; no more data)*/
407             r->reqbody_length = r->reqbody_queue.bytes_in;
408     }
409 
410     return rc;
411 }
412 
413 
414 __attribute_cold__
415 static int server_oneshot_init_pipe(server *srv, int fdin, int fdout) {
416     /* Note: attempt to work with netcat pipes though other code expects socket.
417      * netcat has different fds (pipes) for stdin and stdout.  To support
418      * netcat, need to avoid S_ISSOCK(), getsockname(), and getpeername(),
419      * reconstructing addresses from environment variables:
420      *   NCAT_LOCAL_ADDR   NCAT_LOCAL_PORT
421      *   NCAT_REMOTE_ADDR  NCAT_REMOTE_PORT
422      *   NCAT_PROTO (TCP, UDP, SCTP)
423      */
424     connection *con;
425     server_socket *srv_socket;
426     sock_addr cnt_addr;
427 
428     /* detect if called from netcat or else fabricate localhost addrs */
429     const char * const ncat =
430              getenv("NCAT_LOCAL_ADDR");
431     const char * const ncat_local_addr  =
432       ncat ? ncat                       : "127.0.0.1"; /*(fabricated)*/
433     const char * const ncat_local_port  =
434       ncat ? getenv("NCAT_LOCAL_PORT")  : "80";        /*(fabricated)*/
435     const char * const ncat_remote_addr =
436       ncat ? getenv("NCAT_REMOTE_ADDR") : "127.0.0.1"; /*(fabricated)*/
437     const char * const ncat_remote_port =
438       ncat ? getenv("NCAT_REMOTE_PORT") : "48080";     /*(fabricated)*/
439     if (NULL == ncat_local_addr  || NULL == ncat_local_port)  return 0;
440     if (NULL == ncat_remote_addr || NULL == ncat_remote_port) return 0;
441 
442     const int family = ncat && strchr(ncat_local_addr,':') ? AF_INET6 : AF_INET;
443     unsigned short port;
444 
445     port = (unsigned short)strtol(ncat_local_port, NULL, 10);
446     if (1 != sock_addr_inet_pton(&cnt_addr, ncat_local_addr, family, port)) {
447         log_error(srv->errh, __FILE__, __LINE__, "invalid local addr");
448         return 0;
449     }
450 
451     srv_socket = server_oneshot_getsock(srv, &cnt_addr);
452     if (NULL == srv_socket) return 0;
453 
454     port = (unsigned short)strtol(ncat_remote_port, NULL, 10);
455     if (1 != sock_addr_inet_pton(&cnt_addr, ncat_remote_addr, family, port)) {
456         log_error(srv->errh, __FILE__, __LINE__, "invalid remote addr");
457         return 0;
458     }
459 
460     /*(must set flags; fd did not pass through fdevent accept() logic)*/
461     if (-1 == fdevent_fcntl_set_nb_cloexec(fdin)) {
462         log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
463         return 0;
464     }
465     if (-1 == fdevent_fcntl_set_nb_cloexec(fdout)) {
466         log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
467         return 0;
468     }
469 
470     con = connection_accepted(srv, srv_socket, &cnt_addr, fdout);
471     if (NULL == con) return 0;
472 
473     /* note: existing routines assume socket, not pipe
474      * connections.c:connection_read_cq()
475      *   uses recv() ifdef __WIN32
476      *   passes S_IFSOCK to fdevent_ioctl_fionread()
477      *   (The routine could be copied and modified, if required)
478      * This is unlikely to work if TLS is used over pipe since the SSL_CTX
479      * is associated with the other end of the pipe.  However, if using
480      * pipes, using TLS is unexpected behavior.
481      */
482 
483     /*assert(oneshot_fd == fdin);*/
484     oneshot_read_cq = con->network_read;
485     con->network_read = server_oneshot_read_cq;
486     oneshot_fdn =
487       fdevent_register(srv->ev, fdin, server_oneshot_handle_fdevent, con);
488     fdevent_fdnode_event_set(srv->ev, oneshot_fdn, FDEVENT_RDHUP);
489 
490     connection_state_machine(con);
491     return 1;
492 }
493 
494 
495 __attribute_cold__
496 static int server_oneshot_init(server *srv, int fd) {
497 	connection *con;
498 	server_socket *srv_socket;
499 	sock_addr cnt_addr;
500 	socklen_t cnt_len;
501 
502 	cnt_len = sizeof(cnt_addr);
503 	if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
504 		log_perror(srv->errh, __FILE__, __LINE__, "getsockname()");
505 		return 0;
506 	}
507 
508 	srv_socket = server_oneshot_getsock(srv, &cnt_addr);
509 	if (NULL == srv_socket) return 0;
510 
511       #ifdef __clang_analyzer__
512         memset(&cnt_addr, 0, sizeof(cnt_addr));
513       #endif
514 	cnt_len = sizeof(cnt_addr);
515 	if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
516 		log_perror(srv->errh, __FILE__, __LINE__, "getpeername()");
517 		return 0;
518 	}
519 
520 	/*(must set flags; fd did not pass through fdevent accept() logic)*/
521 	if (-1 == fdevent_fcntl_set_nb_cloexec(fd)) {
522 		log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
523 		return 0;
524 	}
525 
526 	if (sock_addr_get_family(&cnt_addr) != AF_UNIX) {
527 		network_accept_tcp_nagle_disable(fd);
528 	}
529 
530 	con = connection_accepted(srv, srv_socket, &cnt_addr, fd);
531 	if (NULL == con) return 0;
532 
533 	connection_state_machine(con);
534 	return 1;
535 }
536 
537 
538 __attribute_cold__
539 static void show_version (void) {
540 	char *b = PACKAGE_DESC TEXT_SSL \
541 " - a light and fast webserver\n"
542 #ifdef NONREPRODUCIBLE_BUILD
543 "Build-Date: " __DATE__ " " __TIME__ "\n";
544 #endif
545 ;
546 	write_all(STDOUT_FILENO, b, strlen(b));
547 }
548 
549 __attribute_cold__
550 static void show_features (void) {
551   static const char features[] =
552       "\nFeatures:\n\n"
553 #ifdef HAVE_IPV6
554       "\t+ IPv6 support\n"
555 #else
556       "\t- IPv6 support\n"
557 #endif
558 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
559       "\t+ zlib support\n"
560 #else
561       "\t- zlib support\n"
562 #endif
563 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
564       "\t+ bzip2 support\n"
565 #else
566       "\t- bzip2 support\n"
567 #endif
568 #if defined HAVE_BROTLI_ENCODE_H && defined HAVE_BROTLI
569       "\t+ brotli support\n"
570 #else
571       "\t- brotli support\n"
572 #endif
573 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
574       "\t+ crypt support\n"
575 #else
576       "\t- crypt support\n"
577 #endif
578 #ifdef USE_OPENSSL_CRYPTO
579       "\t+ OpenSSL support\n"
580 #else
581       "\t- OpenSSL support\n"
582 #endif
583 #ifdef USE_MBEDTLS_CRYPTO
584       "\t+ mbedTLS support\n"
585 #else
586       "\t- mbedTLS support\n"
587 #endif
588 #ifdef USE_NSS_CRYPTO
589       "\t+ NSS crypto support\n"
590 #else
591       "\t- NSS crypto support\n"
592 #endif
593 #ifdef USE_GNUTLS_CRYPTO
594       "\t+ GnuTLS support\n"
595 #else
596       "\t- GnuTLS support\n"
597 #endif
598 #ifdef USE_WOLFSSL_CRYPTO
599       "\t+ WolfSSL support\n"
600 #else
601       "\t- WolfSSL support\n"
602 #endif
603 #ifdef USE_NETTLE_CRYPTO
604       "\t+ Nettle support\n"
605 #else
606       "\t- Nettle support\n"
607 #endif
608 #ifdef HAVE_LIBPCRE
609       "\t+ PCRE support\n"
610 #else
611       "\t- PCRE support\n"
612 #endif
613 #ifdef HAVE_MYSQL
614       "\t+ MySQL support\n"
615 #else
616       "\t- MySQL support\n"
617 #endif
618 #ifdef HAVE_PGSQL
619       "\t+ PgSQL support\n"
620 #else
621       "\t- PgSQL support\n"
622 #endif
623 #ifdef HAVE_DBI
624       "\t+ DBI support\n"
625 #else
626       "\t- DBI support\n"
627 #endif
628 #ifdef HAVE_KRB5
629       "\t+ Kerberos support\n"
630 #else
631       "\t- Kerberos support\n"
632 #endif
633 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
634       "\t+ LDAP support\n"
635 #else
636       "\t- LDAP support\n"
637 #endif
638 #ifdef HAVE_PAM
639       "\t+ PAM support\n"
640 #else
641       "\t- PAM support\n"
642 #endif
643 #ifdef USE_MEMCACHED
644       "\t+ memcached support\n"
645 #else
646       "\t- memcached support\n"
647 #endif
648 #ifdef HAVE_FAM_H
649       "\t+ FAM support\n"
650 #else
651       "\t- FAM support\n"
652 #endif
653 #ifdef HAVE_LUA_H
654       "\t+ LUA support\n"
655 #else
656       "\t- LUA support\n"
657 #endif
658 #ifdef HAVE_LIBXML_H
659       "\t+ xml support\n"
660 #else
661       "\t- xml support\n"
662 #endif
663 #ifdef HAVE_SQLITE3_H
664       "\t+ SQLite support\n"
665 #else
666       "\t- SQLite support\n"
667 #endif
668 #ifdef HAVE_GDBM_H
669       "\t+ GDBM support\n"
670 #else
671       "\t- GDBM support\n"
672 #endif
673       ;
674   show_version();
675   printf("%s%s%s\n", fdevent_show_event_handlers(), network_write_show_handlers(), features);
676 }
677 
678 __attribute_cold__
679 static void show_help (void) {
680 	char *b = PACKAGE_DESC TEXT_SSL
681 #ifdef NONREPRODUCIBLE_BUILD
682 " ("__DATE__ " " __TIME__ ")"
683 #endif
684 " - a light and fast webserver\n" \
685 "usage:\n" \
686 " -f <name>  filename of the config-file\n" \
687 " -m <name>  module directory (default: "LIBRARY_DIR")\n" \
688 " -i <secs>  graceful shutdown after <secs> of inactivity\n" \
689 " -1         process single (one) request on stdin socket, then exit\n" \
690 " -p         print the parsed config-file in internal form, and exit\n" \
691 " -t         test config-file syntax, then exit\n" \
692 " -tt        test config-file syntax, load and init modules, then exit\n" \
693 " -D         don't go to background (default: go to background)\n" \
694 " -v         show version\n" \
695 " -V         show compile-time features\n" \
696 " -h         show this help\n" \
697 "\n"
698 ;
699 	write_all(STDOUT_FILENO, b, strlen(b));
700 }
701 
702 __attribute_cold__
703 static void server_sockets_save (server *srv) {    /* graceful_restart */
704     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i)
705         srv->srv_sockets.ptr[i]->srv = NULL; /* srv will shortly be invalid */
706     for (uint32_t i = 0; i < srv->srv_sockets_inherited.used; ++i)
707         srv->srv_sockets_inherited.ptr[i]->srv = NULL; /* srv to be invalid */
708     memcpy(&graceful_sockets, &srv->srv_sockets, sizeof(server_socket_array));
709     memset(&srv->srv_sockets, 0, sizeof(server_socket_array));
710     memcpy(&inherited_sockets, &srv->srv_sockets_inherited, sizeof(server_socket_array));
711     memset(&srv->srv_sockets_inherited, 0, sizeof(server_socket_array));
712 }
713 
714 __attribute_cold__
715 static void server_sockets_restore (server *srv) { /* graceful_restart */
716     memcpy(&srv->srv_sockets, &graceful_sockets, sizeof(server_socket_array));
717     memset(&graceful_sockets, 0, sizeof(server_socket_array));
718     memcpy(&srv->srv_sockets_inherited, &inherited_sockets, sizeof(server_socket_array));
719     memset(&inherited_sockets, 0, sizeof(server_socket_array));
720     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i)
721         srv->srv_sockets.ptr[i]->srv = srv;           /* update ptr */
722     for (uint32_t i = 0; i < srv->srv_sockets_inherited.used; ++i)
723         srv->srv_sockets_inherited.ptr[i]->srv = srv; /* update ptr */
724 }
725 
726 __attribute_cold__
727 static int server_sockets_set_nb_cloexec (server *srv) {
728     if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */
729     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
730         server_socket *srv_socket = srv->srv_sockets.ptr[i];
731         if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv_socket->fd)) {
732             log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
733             return -1;
734         }
735     }
736     return 0;
737 }
738 
739 __attribute_cold__
740 static void server_sockets_set_event (server *srv, int event) {
741     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
742         server_socket *srv_socket = srv->srv_sockets.ptr[i];
743         fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event);
744     }
745 }
746 
747 __attribute_cold__
748 static void server_sockets_unregister (server *srv) {
749     if (2 == srv->sockets_disabled) return;
750     srv->sockets_disabled = 2;
751     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i)
752         network_unregister_sock(srv, srv->srv_sockets.ptr[i]);
753 }
754 
755 __attribute_cold__
756 static void server_sockets_close (server *srv) {
757     /* closing socket right away will make it possible for the next lighttpd
758      * to take over (old-style graceful restart), but only if backends
759      * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
760      * than started by lighttpd via "bin-path")
761      */
762     if (3 == srv->sockets_disabled) return;
763     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
764         server_socket *srv_socket = srv->srv_sockets.ptr[i];
765         if (-1 == srv_socket->fd) continue;
766         if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket);
767         close(srv_socket->fd);
768         srv_socket->fd = -1;
769         /* network_close() will cleanup after us */
770     }
771     srv->sockets_disabled = 3;
772 }
773 
774 __attribute_cold__
775 static void server_graceful_signal_prev_generation (void)
776 {
777     const char * const prev_gen = getenv("LIGHTTPD_PREV_GEN");
778     if (NULL == prev_gen) return;
779     pid_t pid = (pid_t)strtol(prev_gen, NULL, 10);
780     unsetenv("LIGHTTPD_PREV_GEN");
781     if (pid <= 0) return; /*(should not happen)*/
782     if (pid == waitpid(pid, NULL, WNOHANG)) return; /*(pid exited; unexpected)*/
783     kill(pid, SIGINT); /* signal previous generation for graceful shutdown */
784 }
785 
786 __attribute_cold__
787 static int server_graceful_state_bg (server *srv) {
788     /*assert(graceful_restart);*/
789     /*(SIGUSR1 set to SIG_IGN in workers, so should not reach here if worker)*/
790     if (srv_shutdown) return 0;
791     if (NULL == srv->srvconf.feature_flags) return 0;
792 
793     /* check if server should fork and background (bg) itself
794      * to continue processing requests already in progress */
795     data_unset * const du =
796       array_get_element_klen(srv->srvconf.feature_flags,
797                              CONST_STR_LEN("server.graceful-restart-bg"));
798     if (!config_plugin_value_tobool(du, 0)) return 0;
799 
800     /*(set flag to false to avoid repeating)*/
801     if (du->type == TYPE_STRING)
802         buffer_copy_string_len(&((data_string *)du)->value,
803                                CONST_STR_LEN("false"));
804     else /* (du->type == TYPE_INTEGER) */
805         ((data_integer *)du)->value = 0;
806 
807     /* require exec'd via absolute path or daemon in foreground
808      * and exec'd with path containing '/' (e.g. "./xxxxx") */
809     char ** const argv = srv->argv;
810     if (0 == srv->srvconf.dont_daemonize
811         ? argv[0][0] != '/'
812         : NULL == strchr(argv[0], '/')) return 0;
813 
814   #if 0
815     /* disabled; not fully implemented
816      * srv->srvconf.systemd_socket_activation might be cleared in network_init()
817      * leading to issuing a false warning
818      */
819     /* warn if server.systemd-socket-activation not enabled
820      * (While this warns on existing config rather than new config,
821      *  it is probably a decent predictor for presence in new config) */
822     if (!srv->srvconf.systemd_socket_activation)
823         log_error(srv->errh, __FILE__, __LINE__,
824           "[note] server.systemd-socket-activation not enabled; "
825           "listen sockets will be closed and reopened");
826   #endif
827 
828     /* flush log buffers to avoid potential duplication of entries
829      * server_handle_sighup(srv) does the following, but skip logging */
830     plugins_call_handle_sighup(srv);
831     config_log_error_cycle(srv);
832 
833     /* backgrounding to continue processing requests in progress */
834     /* re-exec lighttpd in original process
835      *   Note: using path in re-exec is portable and allows lighttpd upgrade.
836      *   OTOH, getauxval() AT_EXECFD and fexecve() could be used on Linux to
837      *   re-exec without access to original executable on disk, which might be
838      *   desirable in some situations, but is not implemented here.
839      *   Alternatively, if argv[] was not available, could use readlink() on
840      *   /proc/self/exe (Linux-specific), though there are ways on many other
841      *   platforms to achieve the same:
842      *   https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
843      */
844   #if defined(HAVE_KQUEUE)
845    #if defined(__FreeBSD__) || defined(__DragonFly__)
846     /*(must *exclude* rfork RFFDG flag for kqueue to work across rfork)*/
847     pid_t pid = rfork(RFPROC);
848    #else
849     pid_t pid = -1;
850     if (pid < 0) {
851         /* kqueue is not inherited across fork
852          * future: fdevent kqueue and stat_cache kqueue would need to be closed,
853          *         re-opened, and active fds re-registered.  Not current done.
854          *         Need to create some routines like fdevent_reinit_after_fork*/
855         log_error(srv->errh, __FILE__, __LINE__,
856           "server.graceful-restart-bg ignored on OpenBSD and NetBSD "
857           "due to limitation in kqueue inheritance and lacking rfork");
858         return 0;
859     }
860    #endif
861   #else
862     pid_t pid = fork();
863   #endif
864     if (pid) { /* original process */
865         if (pid < 0) return 0;
866         network_socket_activation_to_env(srv);
867         /* save pid of original server in environment so that it can be
868          * signalled by restarted server once restarted server is ready
869          * to accept new connections */
870         server_graceful_signal_prev_generation();/*(expect no prev gen active)*/
871         if (0 == srv->srvconf.max_worker) {
872             buffer * const tb = srv->tmp_buf;
873             buffer_clear(tb);
874             buffer_append_int(tb, pid);
875             setenv("LIGHTTPD_PREV_GEN", tb->ptr, 1);
876         }
877         /*while (waitpid(pid, NULL, 0) < 0 && errno == EINTR) ;*//* detach? */
878         execv(argv[0], argv);
879         _exit(1);
880     }
881     /* else child/grandchild */
882 
883     /*if (-1 == setsid()) _exit(1);*//* should we detach? */
884     /* Note: restarted server will fail with socket-in-use error if
885      *       server.systemd-socket-activation not enabled in restarted server */
886     if (0 != srv->srvconf.max_worker)
887         server_sockets_close(srv);/*(close before parent reaps pid in waitpid)*/
888     /*if (0 != fork())    _exit(0);*//* should we detach? */
889     /*(grandchild is now backgrounded and detached from original process)*/
890 
891     /* XXX: might extend code to have new server.feature-flags param specify
892      *      max lifetime before aborting remaining connections */
893 
894     /* (reached if lighttpd workers or if sole process w/o workers)
895      * use same code as comment elsewhere in server.c:
896      *   make sure workers do not muck with pid-file */
897     if (0 <= pid_fd) {
898             close(pid_fd);
899             pid_fd = -1;
900     }
901     if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file);
902 
903     /* (original process is backgrounded -- even if no active connections --
904      *  to allow graceful shutdown tasks to be run by server and by modules) */
905     log_error(srv->errh, __FILE__, __LINE__,
906       "[note] pid %lld continuing to handle %u connection(s) in progress",
907       (long long)getpid(), srv->conns.used);
908 
909     if (0 == srv->srvconf.max_worker) {
910         /* reset graceful_shutdown; wait for signal from restarted server */
911         srv->graceful_expire_ts = 0;
912         graceful_shutdown = 0;
913     }
914     graceful_restart = 0;
915     return 1;
916 }
917 
918 __attribute_cold__
919 __attribute_noinline__
920 static void server_graceful_shutdown_maint (server *srv) {
921     if (oneshot_fd) {
922         /* permit keep-alive on one-shot connections until graceful_expire_ts */
923         if (!srv->graceful_expire_ts) return;
924         if (srv->graceful_expire_ts >= log_epoch_secs) return;
925     }
926     connection_graceful_shutdown_maint(srv);
927 }
928 
929 __attribute_cold__
930 static void server_graceful_state (server *srv) {
931 
932     if (!srv_shutdown) {
933         if (0 == srv->graceful_expire_ts && srv->srvconf.feature_flags) {
934             data_unset * const du =
935               array_get_element_klen(srv->srvconf.feature_flags,
936                 CONST_STR_LEN("server.graceful-shutdown-timeout"));
937             srv->graceful_expire_ts = config_plugin_value_to_int32(du, 0);
938             if (srv->graceful_expire_ts)
939                 srv->graceful_expire_ts += log_epoch_secs;
940         }
941         server_graceful_shutdown_maint(srv);
942     }
943 
944     if (2 == srv->sockets_disabled || 3 == srv->sockets_disabled) {
945         if (oneshot_fd) graceful_restart = 0;
946         return;
947     }
948 
949     log_error(srv->errh,__FILE__,__LINE__,"[note] graceful shutdown started");
950 
951     /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
952     if (!buffer_string_is_empty(srv->srvconf.changeroot)
953         || oneshot_fd || 2 == graceful_shutdown)
954         graceful_restart = 0;
955 
956     if (graceful_restart) {
957         if (!server_graceful_state_bg(srv))
958             server_sockets_unregister(srv);
959         if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/
960     }
961     else {
962         server_sockets_close(srv);
963         remove_pid_file(srv);
964         /*(prevent more removal attempts)*/
965         if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file);
966     }
967 }
968 
969 __attribute_cold__
970 static void server_sockets_enable (server *srv) {
971     server_sockets_set_event(srv, FDEVENT_IN);
972     srv->sockets_disabled = 0;
973     log_error(srv->errh, __FILE__, __LINE__, "[note] sockets enabled again");
974 }
975 
976 __attribute_cold__
977 static void server_sockets_disable (server *srv) {
978     server_sockets_set_event(srv, 0);
979     srv->sockets_disabled = 1;
980     log_error(srv->errh, __FILE__, __LINE__,
981       (srv->conns.used >= srv->max_conns)
982         ? "[note] sockets disabled, connection limit reached"
983         : "[note] sockets disabled, out-of-fds");
984 }
985 
986 __attribute_cold__
987 static void server_overload_check (server *srv) {
988     if (srv->cur_fds + (int)srv->fdwaitqueue.used < srv->max_fds_lowat
989         && srv->conns.used < srv->max_conns) {
990 
991         server_sockets_enable(srv);
992     }
993 }
994 
995 static void server_load_check (server *srv) {
996     /* check if hit limits for num fds used or num connections */
997     if (srv->cur_fds > srv->max_fds_hiwat || srv->conns.used >= srv->max_conns)
998         server_sockets_disable(srv);
999 }
1000 
1001 __attribute_cold__
1002 __attribute_noinline__
1003 static void server_process_fdwaitqueue (server *srv) {
1004     connections * const fdwaitqueue = &srv->fdwaitqueue;
1005     uint32_t i = 0;
1006     for (int n = srv->max_fds - srv->cur_fds - 16; n > 0; --n) {
1007         if (i == fdwaitqueue->used) break;
1008         connection_state_machine(fdwaitqueue->ptr[i++]);
1009     }
1010     if (i > 0 && 0 != (fdwaitqueue->used -= i)) {
1011 	memmove(fdwaitqueue->ptr, fdwaitqueue->ptr+i, fdwaitqueue->used * sizeof(*(fdwaitqueue->ptr)));
1012     }
1013 }
1014 
1015 __attribute_cold__
1016 static int server_main_setup (server * const srv, int argc, char **argv) {
1017 	int print_config = 0;
1018 	int test_config = 0;
1019 	int i_am_root = 0;
1020 	int o;
1021 #ifdef HAVE_FORK
1022 	int num_childs = 0;
1023 #endif
1024 	uint32_t i;
1025 #ifdef HAVE_SIGACTION
1026 	struct sigaction act;
1027 #endif
1028 
1029 #ifdef HAVE_FORK
1030 	int parent_pipe_fd = -1;
1031 #endif
1032 
1033 #ifdef HAVE_GETUID
1034 	i_am_root = (0 == getuid());
1035 #endif
1036 
1037 	/* initialize globals (including file-scoped static globals) */
1038 	oneshot_fd = 0;
1039 	oneshot_fdout = -1;
1040 	srv_shutdown = 0;
1041 	graceful_shutdown = 0;
1042 	handle_sig_alarm = 1;
1043 	handle_sig_hup = 0;
1044 	idle_limit = 0;
1045 	chunkqueue_set_tempdirs_default_reset();
1046 	http_auth_dumbdata_reset();
1047 	http_vhostdb_dumbdata_reset();
1048 	/*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1049 	/*(intentionally preserved)*/
1050 	/*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1051 	/*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/
1052 	/*pid_fd = -1;*/
1053 	srv->argv = argv;
1054 
1055 	while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) {
1056 		switch(o) {
1057 		case 'f':
1058 			if (srv->config_data_base) {
1059 				log_error(srv->errh, __FILE__, __LINE__,
1060 				  "Can only read one config file. Use the include command to use multiple config files.");
1061 				return -1;
1062 			}
1063 			if (config_read(srv, optarg)) {
1064 				return -1;
1065 			}
1066 			break;
1067 		case 'm':
1068 			buffer_copy_string(srv->srvconf.modules_dir, optarg);
1069 			break;
1070 		case 'i': {
1071 			char *endptr;
1072 			long timeout = strtol(optarg, &endptr, 0);
1073 			if (!*optarg || *endptr || timeout < 0) {
1074 				log_error(srv->errh, __FILE__, __LINE__,
1075 				  "Invalid idle timeout value: %s", optarg);
1076 				return -1;
1077 			}
1078 			idle_limit = (time_t)timeout;
1079 			break;
1080 		}
1081 		case 'p': print_config = 1; break;
1082 		case 't': ++test_config; break;
1083 		case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO);
1084 			  break;
1085 		case 'D': srv->srvconf.dont_daemonize = 1; break;
1086 		case 'v': show_version(); return 0;
1087 		case 'V': show_features(); return 0;
1088 		case 'h': show_help(); return 0;
1089 		default:
1090 			show_help();
1091 			return -1;
1092 		}
1093 	}
1094 
1095       #ifdef __CYGWIN__
1096 	if (!srv->config_data_base && NULL != getenv("NSSM_SERVICE_NAME")) {
1097 		char *dir = getenv("NSSM_SERVICE_DIR");
1098 		if (NULL != dir && 0 != chdir(dir)) {
1099 			log_perror(srv->errh, __FILE__, __LINE__, "chdir %s failed", dir);
1100 			return -1;
1101 		}
1102 		srv->srvconf.dont_daemonize = 1;
1103 		buffer_copy_string_len(srv->srvconf.modules_dir, CONST_STR_LEN("modules"));
1104 		if (config_read(srv, "conf/lighttpd.conf")) return -1;
1105 	}
1106       #endif
1107 
1108 	if (!srv->config_data_base) {
1109 		log_error(srv->errh, __FILE__, __LINE__,
1110 		  "No configuration available. Try using -f option.");
1111 		return -1;
1112 	}
1113 
1114 	if (print_config) {
1115 		config_print(srv);
1116 		fprintf(stdout, "\n");
1117 	}
1118 
1119 	if (test_config) {
1120 		if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file);
1121 		if (1 == test_config) {
1122 			printf("Syntax OK\n");
1123 		} else { /*(test_config > 1)*/
1124 			test_config = 0;
1125 			srv->srvconf.preflight_check = 1;
1126 			srv->srvconf.dont_daemonize = 1;
1127 		}
1128 	}
1129 
1130 	if (test_config || print_config) {
1131 		return 0;
1132 	}
1133 
1134 	if (oneshot_fd) {
1135 		if (oneshot_fd <= STDERR_FILENO) {
1136 			log_error(srv->errh, __FILE__, __LINE__,
1137 			  "Invalid fds at startup with lighttpd -1");
1138 			return -1;
1139 		}
1140 		graceful_shutdown = 1;
1141 		srv->sockets_disabled = 2;
1142 		srv->srvconf.dont_daemonize = 1;
1143 		if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file);
1144 		if (srv->srvconf.max_worker) {
1145 			srv->srvconf.max_worker = 0;
1146 			log_error(srv->errh, __FILE__, __LINE__,
1147 			  "server one-shot command line option disables server.max-worker config file option.");
1148 		}
1149 
1150 		struct stat st;
1151 		if (0 != fstat(oneshot_fd, &st)) {
1152 			log_perror(srv->errh, __FILE__, __LINE__, "fstat()");
1153 			return -1;
1154 		}
1155 
1156 		if (S_ISFIFO(st.st_mode)) {
1157 			oneshot_fdout = dup(STDOUT_FILENO);
1158 			if (oneshot_fdout <= STDERR_FILENO) {
1159 				log_perror(srv->errh, __FILE__, __LINE__, "dup()");
1160 				return -1;
1161 			}
1162 		}
1163 		else if (!S_ISSOCK(st.st_mode)) {
1164 			/* require that fd is a socket
1165 			 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
1166 			log_error(srv->errh, __FILE__, __LINE__,
1167 			  "lighttpd -1 stdin is not a socket");
1168 			return -1;
1169 		}
1170 	}
1171 
1172 	if (srv->srvconf.bindhost && buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) {
1173 		if (-1 == srv->stdin_fd)
1174 			srv->stdin_fd = dup(STDIN_FILENO);
1175 		if (srv->stdin_fd <= STDERR_FILENO) {
1176 			log_error(srv->errh, __FILE__, __LINE__,
1177 			  "Invalid fds at startup");
1178 			return -1;
1179 		}
1180 	}
1181 
1182 	/* close stdin and stdout, as they are not needed */
1183 	{
1184 		struct stat st;
1185 		int devnull;
1186 		int errfd;
1187 		do {
1188 			/* coverity[overwrite_var : FALSE] */
1189 			devnull = fdevent_open_devnull();
1190 		      #ifdef __COVERITY__
1191 			__coverity_escape__(devnull);
1192 		      #endif
1193 		} while (-1 != devnull && devnull <= STDERR_FILENO);
1194 		if (-1 == devnull) {
1195 			log_perror(srv->errh, __FILE__, __LINE__,
1196 			  "opening /dev/null failed");
1197 			return -1;
1198 		}
1199 		errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull;
1200 		if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) {
1201 			log_perror(srv->errh, __FILE__, __LINE__,
1202 			  "setting default fds failed");
1203 		      #ifdef FD_CLOEXEC
1204 			if (-1 != errfd) close(errfd);
1205 			if (devnull != errfd) close(devnull);
1206 		      #endif
1207 			return -1;
1208 		}
1209 	      #ifdef FD_CLOEXEC
1210 		if (-1 != errfd) close(errfd);
1211 		if (devnull != errfd) close(devnull);
1212 	      #endif
1213 	}
1214 
1215 	http_response_send_1xx_cb_set(NULL, HTTP_VERSION_2);
1216 	if (srv->srvconf.feature_flags
1217 	    && !config_plugin_value_tobool(
1218 	          array_get_element_klen(srv->srvconf.feature_flags,
1219 	            CONST_STR_LEN("server.h2-discard-backend-1xx")), 0))
1220 		http_response_send_1xx_cb_set(h2_send_1xx,
1221 		                              HTTP_VERSION_2);
1222 
1223 	http_response_send_1xx_cb_set(NULL, HTTP_VERSION_1_1);
1224 	if (srv->srvconf.feature_flags
1225 	    && !config_plugin_value_tobool(
1226 	          array_get_element_klen(srv->srvconf.feature_flags,
1227 	            CONST_STR_LEN("server.h1-discard-backend-1xx")), 0))
1228 		http_response_send_1xx_cb_set(connection_send_1xx,
1229 		                              HTTP_VERSION_1_1);
1230 
1231 	if (0 != config_set_defaults(srv)) {
1232 		log_error(srv->errh, __FILE__, __LINE__,
1233 		  "setting default values failed");
1234 		return -1;
1235 	}
1236 
1237 	if (plugins_load(srv)) {
1238 		log_error(srv->errh, __FILE__, __LINE__,
1239 		  "loading plugins finally failed");
1240 		return -1;
1241 	}
1242 
1243 	if (HANDLER_GO_ON != plugins_call_init(srv)) {
1244 		log_error(srv->errh, __FILE__, __LINE__,
1245 		  "Initialization of plugins failed. Going down.");
1246 		return -1;
1247 	}
1248 
1249 	/* mod_indexfile should be listed in server.modules prior to dynamic handlers */
1250 	i = 0;
1251 	for (const char *pname = NULL; i < srv->plugins.used; ++i) {
1252 		plugin *p = ((plugin **)srv->plugins.ptr)[i];
1253 		if (NULL != pname && 0 == strcmp(p->name, "indexfile")) {
1254 			log_error(srv->errh, __FILE__, __LINE__,
1255 			  "Warning: mod_indexfile should be listed in server.modules prior to mod_%s", pname);
1256 			break;
1257 		}
1258 		if (p->handle_subrequest_start && p->handle_subrequest) {
1259 			if (!pname) pname = p->name;
1260 		}
1261 	}
1262 
1263 	/* open pid file BEFORE chroot */
1264 	if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/
1265 	if (-1 == pid_fd && !buffer_string_is_empty(srv->srvconf.pid_file)) {
1266 		const char *pidfile = srv->srvconf.pid_file->ptr;
1267 		if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
1268 			struct stat st;
1269 			if (errno != EEXIST) {
1270 				log_perror(srv->errh, __FILE__, __LINE__,
1271 				  "opening pid-file failed: %s", pidfile);
1272 				return -1;
1273 			}
1274 
1275 			if (0 != stat(pidfile, &st)) {
1276 				log_perror(srv->errh, __FILE__, __LINE__,
1277 				  "stating existing pid-file failed: %s", pidfile);
1278 			}
1279 
1280 			if (!S_ISREG(st.st_mode)) {
1281 				log_error(srv->errh, __FILE__, __LINE__,
1282 				  "pid-file exists and isn't regular file: %s", pidfile);
1283 				return -1;
1284 			}
1285 
1286 			if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
1287 				log_perror(srv->errh, __FILE__, __LINE__,
1288 				  "opening pid-file failed: %s", pidfile);
1289 				return -1;
1290 			}
1291 		}
1292 	}
1293 
1294 	{
1295 #ifdef HAVE_GETRLIMIT
1296 		struct rlimit rlim = { 4096, 4096 };
1297 		int use_rlimit = 1;
1298 #ifdef HAVE_VALGRIND_VALGRIND_H
1299 		if (RUNNING_ON_VALGRIND) use_rlimit = 0;
1300 #endif
1301 
1302 		if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
1303 			log_perror(srv->errh, __FILE__, __LINE__, "getrlimit()");
1304 			use_rlimit = 0;
1305 		}
1306 
1307 		/**
1308 		 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1309 		 */
1310 		if (use_rlimit && srv->srvconf.max_fds
1311 		    && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) {
1312 			/* set rlimits */
1313 
1314 			rlim.rlim_cur = srv->srvconf.max_fds;
1315 			if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds;
1316 
1317 			if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
1318 				log_perror(srv->errh, __FILE__, __LINE__, "setrlimit()");
1319 				return -1;
1320 			}
1321 		}
1322 
1323 		/*(default upper limit of 4k if server.max-fds not specified)*/
1324 		if (0 == srv->srvconf.max_fds)
1325 			srv->srvconf.max_fds = (rlim.rlim_cur <= 4096)
1326 			  ? (unsigned short)rlim.rlim_cur
1327 			  : 4096;
1328 
1329 		/* set core file rlimit, if enable_cores is set */
1330 		if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
1331 			rlim.rlim_cur = rlim.rlim_max;
1332 			setrlimit(RLIMIT_CORE, &rlim);
1333 		}
1334 #endif
1335 	}
1336 
1337 	/* we need root-perms for port < 1024 */
1338 	if (0 != network_init(srv, srv->stdin_fd)) {
1339 		return -1;
1340 	}
1341 	srv->stdin_fd = -1;
1342 
1343 	if (i_am_root) {
1344 #ifdef HAVE_PWD_H
1345 		/* set user and group */
1346 		struct group *grp = NULL;
1347 		struct passwd *pwd = NULL;
1348 
1349 		if (!buffer_string_is_empty(srv->srvconf.groupname)) {
1350 			if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
1351 				log_error(srv->errh, __FILE__, __LINE__,
1352 				  "can't find groupname %s", srv->srvconf.groupname->ptr);
1353 				return -1;
1354 			}
1355 		}
1356 
1357 		if (!buffer_string_is_empty(srv->srvconf.username)) {
1358 			if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
1359 				log_error(srv->errh, __FILE__, __LINE__,
1360 				  "can't find username %s", srv->srvconf.username->ptr);
1361 				return -1;
1362 			}
1363 
1364 			if (pwd->pw_uid == 0) {
1365 				log_error(srv->errh, __FILE__, __LINE__,
1366 				  "I will not set uid to 0\n");
1367 				return -1;
1368 			}
1369 
1370 			if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) {
1371 				log_error(srv->errh, __FILE__, __LINE__,
1372 				  "can't find group id %d", (int)pwd->pw_gid);
1373 				return -1;
1374 			}
1375 		}
1376 
1377 		if (NULL != grp) {
1378 			if (grp->gr_gid == 0) {
1379 				log_error(srv->errh, __FILE__, __LINE__,
1380 				  "I will not set gid to 0\n");
1381 				return -1;
1382 			}
1383 		}
1384 
1385 		/*
1386 		 * Change group before chroot, when we have access
1387 		 * to /etc/group
1388 		 * */
1389 		if (NULL != grp) {
1390 			if (-1 == setgid(grp->gr_gid)) {
1391 				log_perror(srv->errh, __FILE__, __LINE__, "setgid()");
1392 				return -1;
1393 			}
1394 			if (-1 == setgroups(0, NULL)) {
1395 				log_perror(srv->errh, __FILE__, __LINE__, "setgroups()");
1396 				return -1;
1397 			}
1398 			if (!buffer_string_is_empty(srv->srvconf.username)) {
1399 				initgroups(srv->srvconf.username->ptr, grp->gr_gid);
1400 			}
1401 		}
1402 #endif
1403 #ifdef HAVE_CHROOT
1404 		if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
1405 			tzset();
1406 
1407 			if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
1408 				log_perror(srv->errh, __FILE__, __LINE__, "chroot()");
1409 				return -1;
1410 			}
1411 			if (-1 == chdir("/")) {
1412 				log_perror(srv->errh, __FILE__, __LINE__, "chdir()");
1413 				return -1;
1414 			}
1415 		}
1416 #endif
1417 #ifdef HAVE_PWD_H
1418 		/* drop root privs */
1419 		if (NULL != pwd) {
1420 			if (-1 == setuid(pwd->pw_uid)) {
1421 				log_perror(srv->errh, __FILE__, __LINE__, "setuid()");
1422 				return -1;
1423 			}
1424 		}
1425 #endif
1426 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1427 		/**
1428 		 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1429 		 */
1430 		if (srv->srvconf.enable_cores) {
1431 			prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1432 		}
1433 #endif
1434 	}
1435 
1436 #ifdef HAVE_FORK
1437 	/* network is up, let's daemonize ourself */
1438 	if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) {
1439 		parent_pipe_fd = daemonize();
1440 	}
1441 #endif
1442 	graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/
1443 	if (0 == oneshot_fd) graceful_shutdown = 0;
1444 
1445 
1446 #ifdef HAVE_SIGACTION
1447 	memset(&act, 0, sizeof(act));
1448 	act.sa_handler = SIG_IGN;
1449 	sigaction(SIGPIPE, &act, NULL);
1450 # if defined(SA_SIGINFO)
1451 	last_sighup_info.si_uid = 0,
1452 	last_sighup_info.si_pid = 0;
1453 	last_sigterm_info.si_uid = 0,
1454 	last_sigterm_info.si_pid = 0;
1455 	act.sa_sigaction = sigaction_handler;
1456 	sigemptyset(&act.sa_mask);
1457 	act.sa_flags = SA_SIGINFO;
1458 # else
1459 	act.sa_handler = signal_handler;
1460 	sigemptyset(&act.sa_mask);
1461 	act.sa_flags = 0;
1462 # endif
1463 	sigaction(SIGINT,  &act, NULL);
1464 	sigaction(SIGTERM, &act, NULL);
1465 	sigaction(SIGHUP,  &act, NULL);
1466 	sigaction(SIGALRM, &act, NULL);
1467 	sigaction(SIGUSR1, &act, NULL);
1468 
1469 	/* it should be safe to restart syscalls after SIGCHLD */
1470 	act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
1471 	sigaction(SIGCHLD, &act, NULL);
1472 
1473 #elif defined(HAVE_SIGNAL)
1474 	/* ignore the SIGPIPE from sendfile() */
1475 	signal(SIGPIPE, SIG_IGN);
1476 	signal(SIGALRM, signal_handler);
1477 	signal(SIGTERM, signal_handler);
1478 	signal(SIGHUP,  signal_handler);
1479 	signal(SIGCHLD,  signal_handler);
1480 	signal(SIGINT,  signal_handler);
1481 	signal(SIGUSR1, signal_handler);
1482 #endif
1483 
1484 
1485 	srv->gid = getgid();
1486 	srv->uid = getuid();
1487 	srv->pid = getpid();
1488 
1489 	/* write pid file */
1490 	if (pid_fd > 2) {
1491 		buffer * const tb = srv->tmp_buf;
1492 		buffer_clear(tb);
1493 		buffer_append_int(tb, srv->pid);
1494 		buffer_append_string_len(tb, CONST_STR_LEN("\n"));
1495 		if (-1 == write_all(pid_fd, CONST_BUF_LEN(tb))) {
1496 			log_perror(srv->errh, __FILE__, __LINE__, "Couldn't write pid file");
1497 			close(pid_fd);
1498 			pid_fd = -1;
1499 			return -1;
1500 		}
1501 	} else if (pid_fd < -2) {
1502 		pid_fd = -pid_fd;
1503 	}
1504 
1505 	/* Close stderr ASAP in the child process to make sure that nothing
1506 	 * is being written to that fd which may not be valid anymore. */
1507 	if (!srv->srvconf.preflight_check) {
1508 		if (-1 == config_log_error_open(srv)) {
1509 			log_error(srv->errh, __FILE__, __LINE__, "Opening errorlog failed. Going down.");
1510 			return -1;
1511 		}
1512 		if (!oneshot_fd)
1513 			log_error(srv->errh, __FILE__, __LINE__, "server started (" PACKAGE_DESC ")");
1514 	}
1515 
1516 	if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1517 		log_error(srv->errh, __FILE__, __LINE__, "Configuration of plugins failed. Going down.");
1518 		return -1;
1519 	}
1520 
1521 	if (!config_finalize(srv, &default_server_tag)) {
1522 		return -1;
1523 	}
1524 
1525 	if (srv->srvconf.preflight_check) {
1526 		/*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1527 		return 0;
1528 	}
1529 
1530 
1531 #ifdef HAVE_FORK
1532 	/**
1533 	 * notify daemonize-grandparent of successful startup
1534 	 * do this before any further forking is done (workers)
1535 	 */
1536 	if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) {
1537 		if (0 > write(parent_pipe_fd, "", 1)) return -1;
1538 		close(parent_pipe_fd);
1539 	}
1540 
1541 	if (idle_limit && srv->srvconf.max_worker) {
1542 		srv->srvconf.max_worker = 0;
1543 		log_error(srv->errh, __FILE__, __LINE__,
1544 		  "server idle time limit command line option disables server.max-worker config file option.");
1545 	}
1546 
1547 	/* start watcher and workers */
1548 	num_childs = srv->srvconf.max_worker;
1549 	if (num_childs > 0) {
1550 		pid_t pids[num_childs];
1551 		pid_t pid;
1552 		const int npids = num_childs;
1553 		int child = 0;
1554 		unsigned int timer = 0;
1555 		for (int n = 0; n < npids; ++n) pids[n] = -1;
1556 		server_graceful_signal_prev_generation();
1557 		while (!child && !srv_shutdown && !graceful_shutdown) {
1558 			if (num_childs > 0) {
1559 				switch ((pid = fork())) {
1560 				case -1:
1561 					return -1;
1562 				case 0:
1563 					child = 1;
1564 					alarm(0);
1565 					break;
1566 				default:
1567 					num_childs--;
1568 					for (int n = 0; n < npids; ++n) {
1569 						if (-1 == pids[n]) {
1570 							pids[n] = pid;
1571 							break;
1572 						}
1573 					}
1574 					break;
1575 				}
1576 			} else {
1577 				int status;
1578 
1579 				if (-1 != (pid = wait(&status))) {
1580 					log_epoch_secs = time(NULL);
1581 					if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1582 						if (!timer) alarm((timer = 5));
1583 						continue;
1584 					}
1585 					switch (fdevent_reaped_logger_pipe(pid)) {
1586 					  default: break;
1587 					  case -1: if (!timer) alarm((timer = 5));
1588 						   /* fall through */
1589 					  case  1: continue;
1590 					}
1591 					/**
1592 					 * check if one of our workers went away
1593 					 */
1594 					for (int n = 0; n < npids; ++n) {
1595 						if (pid == pids[n]) {
1596 							pids[n] = -1;
1597 							num_childs++;
1598 							break;
1599 						}
1600 					}
1601 				} else {
1602 					switch (errno) {
1603 					case EINTR:
1604 						log_epoch_secs = time(NULL);
1605 						/**
1606 						 * if we receive a SIGHUP we have to close our logs ourself as we don't
1607 						 * have the mainloop who can help us here
1608 						 */
1609 						if (handle_sig_hup) {
1610 							handle_sig_hup = 0;
1611 
1612 							config_log_error_cycle(srv);
1613 
1614 							/* forward SIGHUP to workers */
1615 							for (int n = 0; n < npids; ++n) {
1616 								if (pids[n] > 0) kill(pids[n], SIGHUP);
1617 							}
1618 						}
1619 						if (handle_sig_alarm) {
1620 							handle_sig_alarm = 0;
1621 							timer = 0;
1622 							plugins_call_handle_trigger(srv);
1623 							fdevent_restart_logger_pipes(log_epoch_secs);
1624 						}
1625 						break;
1626 					default:
1627 						break;
1628 					}
1629 				}
1630 			}
1631 		}
1632 
1633 		/**
1634 		 * for the parent this is the exit-point
1635 		 */
1636 		if (!child) {
1637 			/**
1638 			 * kill all children too
1639 			 */
1640 			if (graceful_shutdown || graceful_restart) {
1641 				/* flag to ignore one SIGINT if graceful_restart */
1642 				if (graceful_restart) graceful_restart = 2;
1643 				kill(0, SIGINT);
1644 				server_graceful_state(srv);
1645 			} else if (srv_shutdown) {
1646 				kill(0, SIGTERM);
1647 			}
1648 
1649 			return 0;
1650 		}
1651 
1652 		/* ignore SIGUSR1 in workers; only parent directs graceful restart */
1653 	      #ifdef HAVE_SIGACTION
1654 		{
1655 			struct sigaction actignore;
1656 			memset(&actignore, 0, sizeof(actignore));
1657 			actignore.sa_handler = SIG_IGN;
1658 			sigaction(SIGUSR1, &actignore, NULL);
1659 		}
1660 	      #elif defined(HAVE_SIGNAL)
1661 			signal(SIGUSR1, SIG_IGN);
1662 	      #endif
1663 
1664 		/**
1665 		 * make sure workers do not muck with pid-file
1666 		 */
1667 		if (0 <= pid_fd) {
1668 			close(pid_fd);
1669 			pid_fd = -1;
1670 		}
1671 		if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file);
1672 
1673 		fdevent_clr_logger_pipe_pids();
1674 		srv->pid = getpid();
1675 		li_rand_reseed();
1676 	}
1677 #endif
1678 
1679 	srv->max_fds = (int)srv->srvconf.max_fds;
1680 	srv->ev = fdevent_init(srv->srvconf.event_handler, &srv->max_fds, &srv->cur_fds, srv->errh);
1681 	if (NULL == srv->ev) {
1682 		log_error(srv->errh, __FILE__, __LINE__, "fdevent_init failed");
1683 		return -1;
1684 	}
1685 
1686 	srv->max_fds_lowat = srv->max_fds * 8 / 10;
1687 	srv->max_fds_hiwat = srv->max_fds * 9 / 10;
1688 
1689 	/* set max-conns */
1690 	if (srv->srvconf.max_conns > srv->max_fds/2) {
1691 		/* we can't have more connections than max-fds/2 */
1692 		log_error(srv->errh, __FILE__, __LINE__,
1693 		  "can't have more connections than fds/2: %hu %d",
1694 		  srv->srvconf.max_conns, srv->max_fds);
1695 		srv->max_conns = srv->max_fds/2;
1696 	} else if (srv->srvconf.max_conns) {
1697 		/* otherwise respect the wishes of the user */
1698 		srv->max_conns = srv->srvconf.max_conns;
1699 	} else {
1700 		/* or use the default: we really don't want to hit max-fds */
1701 		srv->max_conns = srv->max_fds/3;
1702 	}
1703 
1704 	request_pool_init(srv->max_conns);
1705 
1706 	/* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1707 #ifdef HAVE_SIGACTION
1708 	sigaction(SIGCHLD, &act, NULL);
1709 #elif defined(HAVE_SIGNAL)
1710 	signal(SIGCHLD,  signal_handler);
1711 #endif
1712 
1713 	/*
1714 	 * kqueue() is called here, select resets its internals,
1715 	 * all server sockets get their handlers
1716 	 *
1717 	 * */
1718 	if (0 != network_register_fdevents(srv)) {
1719 		return -1;
1720 	}
1721 
1722 	/* might fail if user is using fam (not gamin) and famd isn't running */
1723 	if (!stat_cache_init(srv->ev, srv->errh)) {
1724 		log_error(srv->errh, __FILE__, __LINE__,
1725 		  "stat-cache could not be setup, dying.");
1726 		return -1;
1727 	}
1728 
1729 #ifdef USE_ALARM
1730 	{
1731 		/* setup periodic timer (1 second) */
1732 		struct itimerval interval;
1733 		interval.it_interval.tv_sec = 1;
1734 		interval.it_interval.tv_usec = 0;
1735 		interval.it_value.tv_sec = 1;
1736 		interval.it_value.tv_usec = 0;
1737 		if (setitimer(ITIMER_REAL, &interval, NULL)) {
1738 			log_perror(srv->errh, __FILE__, __LINE__, "setitimer()");
1739 			return -1;
1740 		}
1741 	}
1742 #endif
1743 
1744 	/* get the current number of FDs */
1745 	{
1746 		int fd = fdevent_open_devnull();
1747 		if (fd >= 0) {
1748 			srv->cur_fds = fd;
1749 			close(fd);
1750 		}
1751 	}
1752 
1753 	if (0 != server_sockets_set_nb_cloexec(srv)) {
1754 		return -1;
1755 	}
1756 
1757 	/* plugin hook for worker_init */
1758 	if (HANDLER_GO_ON != plugins_call_worker_init(srv))
1759 		return -1;
1760 
1761 	if (oneshot_fdout > 0) {
1762 		if (server_oneshot_init_pipe(srv, oneshot_fd, oneshot_fdout)) {
1763 			oneshot_fd = -1;
1764 			oneshot_fdout = -1;
1765 		}
1766 	}
1767 	else if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) {
1768 		oneshot_fd = -1;
1769 	}
1770 
1771 	if (0 == srv->srvconf.max_worker)
1772 		server_graceful_signal_prev_generation();
1773 
1774 	return 1;
1775 }
1776 
1777 __attribute_cold__
1778 __attribute_noinline__
1779 static void server_handle_sighup (server * const srv) {
1780 
1781 			/* cycle logfiles */
1782 
1783 			plugins_call_handle_sighup(srv);
1784 
1785 			config_log_error_cycle(srv);
1786 #ifdef HAVE_SIGACTION
1787 				log_error(srv->errh, __FILE__, __LINE__,
1788 				  "logfiles cycled UID = %d PID = %d",
1789 				  (int)last_sighup_info.si_uid,
1790 				  (int)last_sighup_info.si_pid);
1791 #else
1792 				log_error(srv->errh, __FILE__, __LINE__,
1793 				  "logfiles cycled");
1794 #endif
1795 }
1796 
1797 __attribute_noinline__
1798 static void server_handle_sigalrm (server * const srv, time_t min_ts, time_t last_active_ts) {
1799 
1800 				plugins_call_handle_trigger(srv);
1801 
1802 				log_epoch_secs = min_ts;
1803 
1804 				/* check idle time limit, if enabled */
1805 				if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) {
1806 					log_error(srv->errh, __FILE__, __LINE__,
1807 					  "[note] idle timeout %ds exceeded, "
1808 					  "initiating graceful shutdown", (int)idle_limit);
1809 					graceful_shutdown = 2; /* value 2 indicates idle timeout */
1810 					if (graceful_restart) {
1811 						graceful_restart = 0;
1812 						if (pid_fd < -2) pid_fd = -pid_fd;
1813 						server_sockets_close(srv);
1814 					}
1815 				}
1816 
1817 			      #ifdef HAVE_GETLOADAVG
1818 				/* refresh loadavg data every 30 seconds */
1819 				if (srv->loadts + 30 < min_ts) {
1820 					if (-1 != getloadavg(srv->loadavg, 3)) {
1821 						srv->loadts = min_ts;
1822 					}
1823 				}
1824 			      #endif
1825 
1826 				if (0 == (min_ts & 0x3f)) { /*(once every 64 secs)*/
1827 					/* free excess chunkqueue buffers every 64 secs */
1828 					chunkqueue_chunk_pool_clear();
1829 					/* attempt to restart dead piped loggers every 64 secs */
1830 					if (0 == srv->srvconf.max_worker)
1831 						fdevent_restart_logger_pipes(min_ts);
1832 				}
1833 				/* cleanup stat-cache */
1834 				stat_cache_trigger_cleanup();
1835 				/* reset global/aggregate rate limit counters */
1836 				config_reset_config_bytes_sec(srv->config_data_base);
1837 				/* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1838 				if (graceful_shutdown && !srv_shutdown)
1839 					server_graceful_shutdown_maint(srv);
1840 				connection_periodic_maint(srv, min_ts);
1841 }
1842 
1843 __attribute_noinline__
1844 static void server_handle_sigchld (server * const srv) {
1845 			pid_t pid;
1846 			do {
1847 				int status;
1848 				pid = waitpid(-1, &status, WNOHANG);
1849 				if (pid > 0) {
1850 					if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1851 						continue;
1852 					}
1853 					if (0 == srv->srvconf.max_worker) {
1854 						/* check piped-loggers and restart, even if shutting down */
1855 						if (fdevent_waitpid_logger_pipe_pid(pid, log_epoch_secs)) {
1856 							continue;
1857 						}
1858 					}
1859 				}
1860 			} while (pid > 0 || (-1 == pid && errno == EINTR));
1861 }
1862 
1863 __attribute_hot__
1864 static void server_run_con_queue (connections * const restrict joblist) {
1865     connection * const * const restrict conlist = joblist->ptr;
1866     const uint32_t used = joblist->used;
1867     joblist->used = 0;
1868     for (uint32_t i = 0; i < used; ++i) {
1869         connection_state_machine(conlist[i]);
1870     }
1871 }
1872 
1873 __attribute_hot__
1874 __attribute_noinline__
1875 static void server_main_loop (server * const srv) {
1876 	time_t last_active_ts = time(NULL);
1877 
1878 	while (!srv_shutdown) {
1879 
1880 		if (handle_sig_hup) {
1881 			handle_sig_hup = 0;
1882 			server_handle_sighup(srv);
1883 		}
1884 
1885 		/*(USE_ALARM not used; fdevent_poll() is effective periodic timer)*/
1886 	      #ifdef USE_ALARM
1887 		if (handle_sig_alarm) {
1888 			handle_sig_alarm = 0;
1889 	      #endif
1890 			time_t min_ts = time(NULL);
1891 			if (min_ts != log_epoch_secs) {
1892 				server_handle_sigalrm(srv, min_ts, last_active_ts);
1893 			}
1894 	      #ifdef USE_ALARM
1895 		}
1896 	      #endif
1897 
1898 		if (handle_sig_child) {
1899 			handle_sig_child = 0;
1900 			server_handle_sigchld(srv);
1901 		}
1902 
1903 		if (graceful_shutdown) {
1904 			server_graceful_state(srv);
1905 			if (0 == srv->conns.used && graceful_shutdown) {
1906 				/* we are in graceful shutdown phase and all connections are closed
1907 				 * we are ready to terminate without harming anyone */
1908 				srv_shutdown = 1;
1909 				break;
1910 			}
1911 		} else if (srv->sockets_disabled) {
1912 			server_overload_check(srv);
1913 		} else {
1914 			server_load_check(srv);
1915 		}
1916 
1917 		if (srv->fdwaitqueue.used) {
1918 			server_process_fdwaitqueue(srv);
1919 		}
1920 
1921 		connections * const joblist = connection_joblist;
1922 
1923 		if (fdevent_poll(srv->ev, joblist->used ? 0 : 1000) > 0) {
1924 			last_active_ts = log_epoch_secs;
1925 		}
1926 
1927 		connection_joblist = (joblist == &srv->joblist_A)
1928 		  ? &srv->joblist_B
1929 		  : &srv->joblist_A;
1930 
1931 		server_run_con_queue(joblist);
1932 	}
1933 }
1934 
1935 __attribute_cold__
1936 int main (int argc, char **argv) {
1937     int rc;
1938 
1939   #ifdef HAVE_GETUID
1940   #ifndef HAVE_ISSETUGID
1941   #define issetugid() (geteuid() != getuid() || getegid() != getgid())
1942   #endif
1943     if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
1944         fprintf(stderr,
1945                 "Are you nuts ? Don't apply a SUID bit to this binary\n");
1946         return -1;
1947     }
1948   #endif
1949 
1950     /* for nice %b handling in strftime() */
1951     setlocale(LC_TIME, "C");
1952 
1953     do {
1954         server * const srv = server_init();
1955 
1956         if (graceful_restart) {
1957             server_sockets_restore(srv);
1958             optind = 1;
1959         }
1960 
1961         rc = server_main_setup(srv, argc, argv);
1962         if (rc > 0) {
1963 
1964             server_main_loop(srv);
1965 
1966             if (graceful_shutdown || graceful_restart) {
1967                 server_graceful_state(srv);
1968             }
1969 
1970             if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */
1971                 log_error(srv->errh, __FILE__, __LINE__,
1972                   "server stopped after idle timeout");
1973             } else if (!oneshot_fd) {
1974               #ifdef HAVE_SIGACTION
1975                 log_error(srv->errh, __FILE__, __LINE__,
1976                   "server stopped by UID = %d PID = %d",
1977                   (int)last_sigterm_info.si_uid,
1978                   (int)last_sigterm_info.si_pid);
1979               #else
1980                 log_error(srv->errh, __FILE__, __LINE__,
1981                   "server stopped");
1982               #endif
1983             }
1984         }
1985 
1986         /* clean-up */
1987         remove_pid_file(srv);
1988         config_log_error_close(srv);
1989         if (graceful_restart)
1990             server_sockets_save(srv);
1991         else
1992             network_close(srv);
1993         request_pool_free();
1994         connections_free(srv);
1995         plugins_free(srv);
1996         server_free(srv);
1997 
1998         if (rc < 0 || !graceful_restart) break;
1999 
2000         /* wait for all children to exit before graceful restart */
2001         while (waitpid(-1, NULL, 0) > 0) ;
2002     } while (graceful_restart);
2003 
2004     return rc;
2005 }
2006