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