xref: /lighttpd1.4/src/server.c (revision fcf0dc3e)
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         srv->srv_sockets.ptr[i]->sidx= (unsigned short)~0u;
793     }
794     for (uint32_t i = 0; i < srv->srv_sockets_inherited.used; ++i)
795         srv->srv_sockets_inherited.ptr[i]->srv = srv; /* update ptr */
796 }
797 
798 __attribute_cold__
799 static int server_sockets_set_nb_cloexec (server *srv) {
800     if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */
801     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
802         server_socket *srv_socket = srv->srv_sockets.ptr[i];
803         if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv_socket->fd)) {
804             log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
805             return -1;
806         }
807     }
808     return 0;
809 }
810 
811 __attribute_cold__
812 static void server_sockets_set_event (server *srv, int event) {
813     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
814         server_socket *srv_socket = srv->srv_sockets.ptr[i];
815         fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event);
816     }
817 }
818 
819 __attribute_cold__
820 static void server_sockets_unregister (server *srv) {
821     if (2 == srv->sockets_disabled) return;
822     srv->sockets_disabled = 2;
823     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i)
824         network_unregister_sock(srv, srv->srv_sockets.ptr[i]);
825 }
826 
827 __attribute_cold__
828 static void server_sockets_close (server *srv) {
829     /* closing socket right away will make it possible for the next lighttpd
830      * to take over (old-style graceful restart), but only if backends
831      * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
832      * than started by lighttpd via "bin-path")
833      */
834     if (3 == srv->sockets_disabled) return;
835     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
836         server_socket *srv_socket = srv->srv_sockets.ptr[i];
837         if (-1 == srv_socket->fd) continue;
838         if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket);
839         close(srv_socket->fd);
840         srv_socket->fd = -1;
841         /* network_close() will cleanup after us */
842     }
843     srv->sockets_disabled = 3;
844 }
845 
846 __attribute_cold__
847 static void server_graceful_signal_prev_generation (void)
848 {
849     const char * const prev_gen = getenv("LIGHTTPD_PREV_GEN");
850     if (NULL == prev_gen) return;
851     pid_t pid = (pid_t)strtol(prev_gen, NULL, 10);
852     unsetenv("LIGHTTPD_PREV_GEN");
853     if (pid <= 0) return; /*(should not happen)*/
854     if (pid == fdevent_waitpid(pid,NULL,1)) return; /*(pid exited; unexpected)*/
855     kill(pid, SIGINT); /* signal previous generation for graceful shutdown */
856 }
857 
858 __attribute_cold__
859 static int server_graceful_state_bg (server *srv) {
860     /*assert(graceful_restart);*/
861     /*(SIGUSR1 set to SIG_IGN in workers, so should not reach here if worker)*/
862     if (srv_shutdown) return 0;
863 
864     /* check if server should fork and background (bg) itself
865      * to continue processing requests already in progress */
866     if (!config_feature_bool(srv, "server.graceful-restart-bg", 0)) return 0;
867 
868     /*(set flag to false to avoid repeating)*/
869     data_unset * const du =
870       array_get_data_unset(srv->srvconf.feature_flags,
871                            CONST_STR_LEN("server.graceful-restart-bg"));
872     if (du->type == TYPE_STRING)
873         buffer_copy_string_len(&((data_string *)du)->value,
874                                CONST_STR_LEN("false"));
875     else /* (du->type == TYPE_INTEGER) */
876         ((data_integer *)du)->value = 0;
877 
878     /* require exec'd via absolute path or daemon in foreground
879      * and exec'd with path containing '/' (e.g. "./xxxxx") */
880     char ** const argv = srv->argv;
881     if (0 == srv->srvconf.dont_daemonize
882         ? argv[0][0] != '/'
883         : NULL == strchr(argv[0], '/')) return 0;
884 
885     /* flush log buffers to avoid potential duplication of entries
886      * server_handle_sighup(srv) does the following, but skip logging */
887     plugins_call_handle_sighup(srv);
888     fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */
889 
890     /* backgrounding to continue processing requests in progress */
891     /* re-exec lighttpd in original process
892      *   Note: using path in re-exec is portable and allows lighttpd upgrade.
893      *   OTOH, getauxval() AT_EXECFD and fexecve() could be used on Linux to
894      *   re-exec without access to original executable on disk, which might be
895      *   desirable in some situations, but is not implemented here.
896      *   Alternatively, if argv[] was not available, could use readlink() on
897      *   /proc/self/exe (Linux-specific), though there are ways on many other
898      *   platforms to achieve the same:
899      *   https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
900      */
901   #if defined(HAVE_KQUEUE)
902    #if defined(__FreeBSD__) || defined(__DragonFly__)
903     /*(must *exclude* rfork RFFDG flag for kqueue to work across rfork)*/
904     pid_t pid = rfork(RFPROC);
905    #else
906     pid_t pid = -1;
907     if (pid < 0) {
908         /* kqueue is not inherited across fork
909          * future: fdevent kqueue and stat_cache kqueue would need to be closed,
910          *         re-opened, and active fds re-registered.  Not current done.
911          *         Need to create some routines like fdevent_reinit_after_fork*/
912         log_error(srv->errh, __FILE__, __LINE__,
913           "server.graceful-restart-bg ignored on OpenBSD and NetBSD "
914           "due to limitation in kqueue inheritance and lacking rfork");
915         return 0;
916     }
917    #endif
918   #else
919     pid_t pid = fork();
920   #endif
921     if (pid) { /* original process */
922         if (pid < 0) return 0;
923         network_socket_activation_to_env(srv);
924         /* save pid of original server in environment so that it can be
925          * signalled by restarted server once restarted server is ready
926          * to accept new connections */
927         server_graceful_signal_prev_generation();/*(expect no prev gen active)*/
928         if (0 == srv->srvconf.max_worker) {
929             buffer * const tb = srv->tmp_buf;
930             buffer_clear(tb);
931             buffer_append_int(tb, pid);
932             setenv("LIGHTTPD_PREV_GEN", tb->ptr, 1);
933         }
934         /*fdevent_waitpid(pid, NULL, 0);*//* detach? */
935         execv(argv[0], argv);
936         _exit(1);
937     }
938     /* else child/grandchild */
939 
940     /*if (-1 == setsid()) _exit(1);*//* should we detach? */
941     /* Note: restarted server will fail with socket-in-use error if
942      *       server.systemd-socket-activation not enabled in restarted server */
943     if (0 != srv->srvconf.max_worker)
944         server_sockets_close(srv);/*(close before parent reaps pid in waitpid)*/
945     /*if (0 != fork())    _exit(0);*//* should we detach? */
946     /*(grandchild is now backgrounded and detached from original process)*/
947 
948     /* XXX: might extend code to have new server.feature-flags param specify
949      *      max lifetime before aborting remaining connections */
950 
951     /* (reached if lighttpd workers or if sole process w/o workers)
952      * use same code as comment elsewhere in server.c:
953      *   make sure workers do not muck with pid-file */
954     if (0 <= pid_fd) {
955             close(pid_fd);
956             pid_fd = -1;
957     }
958     srv->srvconf.pid_file = NULL;
959 
960     /* (original process is backgrounded -- even if no active connections --
961      *  to allow graceful shutdown tasks to be run by server and by modules) */
962     log_error(srv->errh, __FILE__, __LINE__,
963       "[note] pid %lld continuing to handle %u connection(s) in progress",
964       (long long)getpid(), srv->srvconf.max_conns - srv->lim_conns);
965 
966     if (0 == srv->srvconf.max_worker) {
967         /* reset graceful_shutdown; wait for signal from restarted server */
968         srv->graceful_expire_ts = 0;
969         graceful_shutdown = 0;
970     }
971     graceful_restart = 0;
972     return 1;
973 }
974 
975 __attribute_cold__
976 __attribute_noinline__
977 static void server_graceful_shutdown_maint (server *srv) {
978     if (oneshot_fd) {
979         /* permit keep-alive on one-shot connections until graceful_expire_ts */
980         if (!srv->graceful_expire_ts) return;
981         if (srv->graceful_expire_ts >= log_monotonic_secs) return;
982     }
983     connection_graceful_shutdown_maint(srv);
984 }
985 
986 __attribute_cold__
987 __attribute_noinline__
988 static void server_graceful_state (server *srv) {
989 
990     if (!srv_shutdown) {
991         if (0 == srv->graceful_expire_ts) {
992             srv->graceful_expire_ts =
993               config_feature_int(srv, "server.graceful-shutdown-timeout", 8);
994             if (srv->graceful_expire_ts)
995                 srv->graceful_expire_ts += log_monotonic_secs;
996         }
997         server_graceful_shutdown_maint(srv);
998     }
999 
1000     if (2 == srv->sockets_disabled || 3 == srv->sockets_disabled) {
1001         if (oneshot_fd) graceful_restart = 0;
1002         return;
1003     }
1004 
1005     log_error(srv->errh,__FILE__,__LINE__,"[note] graceful shutdown started");
1006 
1007     /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
1008     if (srv->srvconf.changeroot || oneshot_fd || 2 == graceful_shutdown)
1009         graceful_restart = 0;
1010 
1011     if (graceful_restart) {
1012         if (!server_graceful_state_bg(srv))
1013             server_sockets_unregister(srv);
1014         if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/
1015     }
1016     else {
1017         server_sockets_close(srv);
1018         remove_pid_file(srv);
1019         /*(prevent more removal attempts)*/
1020         srv->srvconf.pid_file = NULL;
1021     }
1022 }
1023 
1024 __attribute_cold__
1025 __attribute_noinline__
1026 static void server_sockets_enable (server *srv) {
1027     server_sockets_set_event(srv, FDEVENT_IN);
1028     srv->sockets_disabled = 0;
1029     log_error(srv->errh, __FILE__, __LINE__, "[note] sockets enabled again");
1030 }
1031 
1032 __attribute_cold__
1033 __attribute_noinline__
1034 static void server_sockets_disable (server *srv) {
1035     server_sockets_set_event(srv, 0);
1036     srv->sockets_disabled = 1;
1037     log_error(srv->errh, __FILE__, __LINE__,
1038       (0 == srv->lim_conns)
1039         ? "[note] sockets disabled, connection limit reached"
1040         : "[note] sockets disabled, out-of-fds");
1041 }
1042 
1043 __attribute_cold__
1044 static void server_overload_check (server *srv) {
1045     if (srv->cur_fds < srv->max_fds_lowat && 0 != srv->lim_conns)
1046         server_sockets_enable(srv);
1047 }
1048 
1049 static void server_load_check (server *srv) {
1050     /* check if hit limits for num fds used or num connections */
1051     if (srv->cur_fds > srv->max_fds_hiwat || 0 == srv->lim_conns)
1052         server_sockets_disable(srv);
1053 }
1054 
1055 __attribute_cold__
1056 __attribute_noinline__
1057 static int server_main_setup (server * const srv, int argc, char **argv) {
1058 	int print_config = 0;
1059 	int test_config = 0;
1060 	int i_am_root = 0;
1061 	int o;
1062 #ifdef HAVE_FORK
1063 	int num_childs = 0;
1064 #endif
1065 	uint32_t i;
1066 #ifdef HAVE_SIGACTION
1067 	struct sigaction act;
1068 #endif
1069 
1070 #ifdef HAVE_FORK
1071 	int parent_pipe_fd = -1;
1072 #endif
1073 
1074 #ifdef HAVE_GETUID
1075 	i_am_root = (0 == getuid());
1076 #endif
1077 
1078 	/* initialize globals (including file-scoped static globals) */
1079 	oneshot_fd = 0;
1080 	oneshot_fdout = -1;
1081 	srv_shutdown = 0;
1082 	graceful_shutdown = 0;
1083 	handle_sig_alarm = 1;
1084 	handle_sig_hup = 0;
1085 	idle_limit = 0;
1086 	chunkqueue_set_tempdirs_default_reset();
1087 	/*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1088 	/*(intentionally preserved)*/
1089 	/*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1090 	/*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/
1091 	/*pid_fd = -1;*/
1092 	srv->argv = argv;
1093 
1094 	while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) {
1095 		switch(o) {
1096 		case 'f':
1097 			if (srv->config_data_base) {
1098 				log_error(srv->errh, __FILE__, __LINE__,
1099 				  "Can only read one config file. Use the include command to use multiple config files.");
1100 				return -1;
1101 			}
1102 			if (config_read(srv, optarg)) {
1103 				return -1;
1104 			}
1105 			break;
1106 		case 'm':
1107 			srv->srvconf.modules_dir = optarg;
1108 			break;
1109 		case 'i': {
1110 			char *endptr;
1111 			long timeout = strtol(optarg, &endptr, 0);
1112 			if (!*optarg || *endptr || timeout < 0) {
1113 				log_error(srv->errh, __FILE__, __LINE__,
1114 				  "Invalid idle timeout value: %s", optarg);
1115 				return -1;
1116 			}
1117 			idle_limit = (int)timeout;
1118 			break;
1119 		}
1120 		case 'p': print_config = 1; break;
1121 		case 't': ++test_config; break;
1122 		case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO);
1123 			  break;
1124 		case 'D': srv->srvconf.dont_daemonize = 1; break;
1125 		case 'v': show_version(); return 0;
1126 		case 'V': show_features(); return 0;
1127 		case 'h': show_help(); return 0;
1128 		default:
1129 			show_help();
1130 			return -1;
1131 		}
1132 	}
1133 
1134       #ifdef __CYGWIN__
1135 	if (!srv->config_data_base && NULL != getenv("NSSM_SERVICE_NAME")) {
1136 		char *dir = getenv("NSSM_SERVICE_DIR");
1137 		if (NULL != dir && 0 != chdir(dir)) {
1138 			log_perror(srv->errh, __FILE__, __LINE__, "chdir %s failed", dir);
1139 			return -1;
1140 		}
1141 		srv->srvconf.dont_daemonize = 1;
1142 		srv->srvconf.modules_dir = "modules";
1143 		if (config_read(srv, "conf/lighttpd.conf")) return -1;
1144 	}
1145       #endif
1146 
1147 	if (!srv->config_data_base) {
1148 		log_error(srv->errh, __FILE__, __LINE__,
1149 		  "No configuration available. Try using -f option.");
1150 		return -1;
1151 	}
1152 
1153 	if (1 == srv->srvconf.max_worker)
1154 		srv->srvconf.max_worker = 0;
1155 
1156 	if (print_config) {
1157 		config_print(srv);
1158 		puts(srv->tmp_buf->ptr);
1159 	}
1160 
1161 	if (test_config) {
1162 		srv->srvconf.pid_file = NULL;
1163 		if (1 == test_config) {
1164 			printf("Syntax OK\n");
1165 		} else { /*(test_config > 1)*/
1166 			test_config = 0;
1167 			srv->srvconf.preflight_check = 1;
1168 			srv->srvconf.dont_daemonize = 1;
1169 		}
1170 	}
1171 
1172 	if (test_config || print_config) {
1173 		return 0;
1174 	}
1175 
1176 	if (oneshot_fd) {
1177 		if (oneshot_fd <= STDERR_FILENO) {
1178 			log_error(srv->errh, __FILE__, __LINE__,
1179 			  "Invalid fds at startup with lighttpd -1");
1180 			return -1;
1181 		}
1182 		graceful_shutdown = 1;
1183 		srv->sockets_disabled = 2;
1184 		srv->srvconf.dont_daemonize = 1;
1185 		srv->srvconf.pid_file = NULL;
1186 		if (srv->srvconf.max_worker) {
1187 			srv->srvconf.max_worker = 0;
1188 			log_error(srv->errh, __FILE__, __LINE__,
1189 			  "server one-shot command line option disables server.max-worker config file option.");
1190 		}
1191 
1192 		struct stat st;
1193 		if (0 != fstat(oneshot_fd, &st)) {
1194 			log_perror(srv->errh, __FILE__, __LINE__, "fstat()");
1195 			return -1;
1196 		}
1197 
1198 		if (S_ISFIFO(st.st_mode)) {
1199 			oneshot_fdout = dup(STDOUT_FILENO);
1200 			if (oneshot_fdout <= STDERR_FILENO) {
1201 				log_perror(srv->errh, __FILE__, __LINE__, "dup()");
1202 				return -1;
1203 			}
1204 		}
1205 		else if (!S_ISSOCK(st.st_mode)) {
1206 			/* require that fd is a socket
1207 			 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
1208 			log_error(srv->errh, __FILE__, __LINE__,
1209 			  "lighttpd -1 stdin is not a socket");
1210 			return -1;
1211 		}
1212 	}
1213 
1214 	if (srv->srvconf.bindhost && buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) {
1215 		if (-1 == srv->stdin_fd)
1216 			srv->stdin_fd = dup(STDIN_FILENO);
1217 		if (srv->stdin_fd <= STDERR_FILENO) {
1218 			log_error(srv->errh, __FILE__, __LINE__,
1219 			  "Invalid fds at startup");
1220 			return -1;
1221 		}
1222 	}
1223 
1224 	/* close stdin and stdout, as they are not needed */
1225 	{
1226 		struct stat st;
1227 		int devnull;
1228 		int errfd;
1229 		do {
1230 			/* coverity[overwrite_var : FALSE] */
1231 			devnull = fdevent_open_devnull();
1232 		      #ifdef __COVERITY__
1233 			__coverity_escape__(devnull);
1234 		      #endif
1235 		} while (-1 != devnull && devnull <= STDERR_FILENO);
1236 		if (-1 == devnull) {
1237 			log_perror(srv->errh, __FILE__, __LINE__,
1238 			  "opening /dev/null failed");
1239 			return -1;
1240 		}
1241 		errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull;
1242 		if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) {
1243 			log_perror(srv->errh, __FILE__, __LINE__,
1244 			  "setting default fds failed");
1245 		      #ifdef FD_CLOEXEC
1246 			if (-1 != errfd) close(errfd);
1247 			if (devnull != errfd) close(devnull);
1248 		      #endif
1249 			return -1;
1250 		}
1251 	      #ifdef FD_CLOEXEC
1252 		if (-1 != errfd) close(errfd);
1253 		if (devnull != errfd) close(devnull);
1254 	      #endif
1255 	}
1256 
1257 	http_response_send_1xx_cb_set(NULL, HTTP_VERSION_2);
1258 	if (!config_feature_bool(srv, "server.h2-discard-backend-1xx", 0))
1259 		http_response_send_1xx_cb_set(h2_send_1xx, HTTP_VERSION_2);
1260 
1261 	http_response_send_1xx_cb_set(NULL, HTTP_VERSION_1_1);
1262 	if (!config_feature_bool(srv, "server.h1-discard-backend-1xx", 0))
1263 		http_response_send_1xx_cb_set(connection_send_1xx, HTTP_VERSION_1_1);
1264 
1265 	http_range_config_allow_http10(config_feature_bool(srv, "http10.range", 0));
1266 
1267 	if (0 != config_set_defaults(srv)) {
1268 		log_error(srv->errh, __FILE__, __LINE__,
1269 		  "setting default values failed");
1270 		return -1;
1271 	}
1272 
1273 	if (plugins_load(srv)) {
1274 		log_error(srv->errh, __FILE__, __LINE__,
1275 		  "loading plugins finally failed");
1276 		return -1;
1277 	}
1278 
1279 	if (HANDLER_GO_ON != plugins_call_init(srv)) {
1280 		log_error(srv->errh, __FILE__, __LINE__,
1281 		  "Initialization of plugins failed. Going down.");
1282 		return -1;
1283 	}
1284 
1285 	/* mod_indexfile should be listed in server.modules prior to dynamic handlers */
1286 	i = 0;
1287 	for (const char *pname = NULL; i < srv->plugins.used; ++i) {
1288 		plugin *p = ((plugin **)srv->plugins.ptr)[i];
1289 		if (NULL != pname && 0 == strcmp(p->name, "indexfile")) {
1290 			log_error(srv->errh, __FILE__, __LINE__,
1291 			  "Warning: mod_indexfile should be listed in server.modules prior to mod_%s", pname);
1292 			break;
1293 		}
1294 		if (p->handle_subrequest_start && p->handle_subrequest) {
1295 			if (!pname) pname = p->name;
1296 		}
1297 	}
1298 
1299 	/* open pid file BEFORE chroot */
1300 	if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/
1301 	if (-1 == pid_fd && srv->srvconf.pid_file) {
1302 		const char *pidfile = srv->srvconf.pid_file->ptr;
1303 		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))) {
1304 			struct stat st;
1305 			if (errno != EEXIST) {
1306 				log_perror(srv->errh, __FILE__, __LINE__,
1307 				  "opening pid-file failed: %s", pidfile);
1308 				return -1;
1309 			}
1310 
1311 			if (0 != stat(pidfile, &st)) {
1312 				log_perror(srv->errh, __FILE__, __LINE__,
1313 				  "stating existing pid-file failed: %s", pidfile);
1314 			}
1315 
1316 			if (!S_ISREG(st.st_mode)) {
1317 				log_error(srv->errh, __FILE__, __LINE__,
1318 				  "pid-file exists and isn't regular file: %s", pidfile);
1319 				return -1;
1320 			}
1321 
1322 			if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
1323 				log_perror(srv->errh, __FILE__, __LINE__,
1324 				  "opening pid-file failed: %s", pidfile);
1325 				return -1;
1326 			}
1327 		}
1328 	}
1329 
1330 	{
1331 #ifdef HAVE_GETRLIMIT
1332 		struct rlimit rlim = { 4096, 4096 };
1333 		int use_rlimit = 1;
1334 #ifdef HAVE_VALGRIND_VALGRIND_H
1335 		if (RUNNING_ON_VALGRIND) use_rlimit = 0;
1336 #endif
1337 
1338 		if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
1339 			log_perror(srv->errh, __FILE__, __LINE__, "getrlimit()");
1340 			use_rlimit = 0;
1341 		}
1342 
1343 		/**
1344 		 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1345 		 */
1346 		if (use_rlimit && srv->srvconf.max_fds
1347 		    && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) {
1348 			/* set rlimits */
1349 
1350 			rlim_t rlim_cur = rlim.rlim_cur;
1351 			rlim.rlim_cur = srv->srvconf.max_fds;
1352 			if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds;
1353 
1354 			if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
1355 				log_perror(srv->errh, __FILE__, __LINE__, "setrlimit()");
1356 				log_error(srv->errh, __FILE__, __LINE__, "setrlimit() may need root to run once: setsebool -P httpd_setrlimit on");
1357 				use_rlimit = 0;
1358 				if (srv->srvconf.max_fds > rlim_cur)
1359 					srv->srvconf.max_fds = rlim_cur;
1360 			}
1361 		}
1362 
1363 		/*(default upper limit of 4k if server.max-fds not specified)*/
1364 		if (0 == srv->srvconf.max_fds)
1365 			srv->srvconf.max_fds = (rlim.rlim_cur <= 4096)
1366 			  ? (unsigned short)rlim.rlim_cur
1367 			  : 4096;
1368 
1369 		/* set core file rlimit, if enable_cores is set */
1370 		if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
1371 			rlim.rlim_cur = rlim.rlim_max;
1372 			setrlimit(RLIMIT_CORE, &rlim);
1373 		}
1374 #endif
1375 	}
1376 
1377 	/* we need root-perms for port < 1024 */
1378 	if (0 != network_init(srv, srv->stdin_fd)) {
1379 		return -1;
1380 	}
1381 	srv->stdin_fd = -1;
1382 
1383 	if (i_am_root) {
1384 #ifdef HAVE_PWD_H
1385 		/* set user and group */
1386 		struct group *grp = NULL;
1387 		struct passwd *pwd = NULL;
1388 
1389 		if (srv->srvconf.groupname) {
1390 			if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
1391 				log_error(srv->errh, __FILE__, __LINE__,
1392 				  "can't find groupname %s", srv->srvconf.groupname->ptr);
1393 				return -1;
1394 			}
1395 		}
1396 
1397 		if (srv->srvconf.username) {
1398 			if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
1399 				log_error(srv->errh, __FILE__, __LINE__,
1400 				  "can't find username %s", srv->srvconf.username->ptr);
1401 				return -1;
1402 			}
1403 
1404 			if (pwd->pw_uid == 0) {
1405 				log_error(srv->errh, __FILE__, __LINE__,
1406 				  "I will not set uid to 0.  Perhaps you should comment out server.username in lighttpd.conf\n");
1407 				return -1;
1408 			}
1409 
1410 			if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) {
1411 				log_error(srv->errh, __FILE__, __LINE__,
1412 				  "can't find group id %d", (int)pwd->pw_gid);
1413 				return -1;
1414 			}
1415 		}
1416 
1417 		if (NULL != grp) {
1418 			if (grp->gr_gid == 0) {
1419 				log_error(srv->errh, __FILE__, __LINE__,
1420 				  "I will not set gid to 0.  Perhaps you should comment out server.groupname in lighttpd.conf\n");
1421 				return -1;
1422 			}
1423 		}
1424 
1425 		/*
1426 		 * Change group before chroot, when we have access
1427 		 * to /etc/group
1428 		 * */
1429 		if (NULL != grp) {
1430 			if (-1 == setgid(grp->gr_gid)) {
1431 				log_perror(srv->errh, __FILE__, __LINE__, "setgid()");
1432 				return -1;
1433 			}
1434 			if (-1 == setgroups(0, NULL)) {
1435 				log_perror(srv->errh, __FILE__, __LINE__, "setgroups()");
1436 				return -1;
1437 			}
1438 			if (srv->srvconf.username) {
1439 				initgroups(srv->srvconf.username->ptr, grp->gr_gid);
1440 			}
1441 		}
1442 #endif
1443 #ifdef HAVE_CHROOT
1444 		if (srv->srvconf.changeroot) {
1445 			tzset();
1446 
1447 			if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
1448 				log_perror(srv->errh, __FILE__, __LINE__, "chroot()");
1449 				return -1;
1450 			}
1451 			if (-1 == chdir("/")) {
1452 				log_perror(srv->errh, __FILE__, __LINE__, "chdir()");
1453 				return -1;
1454 			}
1455 		}
1456 #endif
1457 #ifdef HAVE_PWD_H
1458 		/* drop root privs */
1459 		if (NULL != pwd) {
1460 			if (-1 == setuid(pwd->pw_uid)) {
1461 				log_perror(srv->errh, __FILE__, __LINE__, "setuid()");
1462 				return -1;
1463 			}
1464 		}
1465 #endif
1466 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1467 		/**
1468 		 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1469 		 */
1470 		if (srv->srvconf.enable_cores) {
1471 			prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1472 		}
1473 #elif defined(HAVE_SYS_PROCCTL_H) && defined(PROC_TRACE_CTL_ENABLE)
1474 		/* (DragonFlyBSD has procctl(), but not PROC_TRACE_CTL_ENABLE) */
1475 		if (srv->srvconf.enable_cores) {
1476 			int dumpable = PROC_TRACE_CTL_ENABLE;
1477 			procctl(P_PID, 0, PROC_TRACE_CTL, &dumpable);
1478 		}
1479 #elif defined(HAVE_SETPFLAGS) && defined(__PROC_PROTECT)
1480 		/**
1481 		 * setpflags seems uniquely a solaris/illumos feature
1482 		 * but just taking extra precautions clearing __PROC_PROTECT option
1483 		 */
1484 		if (srv->srvconf.enable_cores) {
1485 			setpflags(__PROC_PROTECT, 0);
1486 		}
1487 #endif
1488 	}
1489 
1490 #ifdef HAVE_FORK
1491 	/* network is up, let's daemonize ourself */
1492 	if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) {
1493 		parent_pipe_fd = daemonize();
1494 	}
1495 #endif
1496 	graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/
1497 	if (0 == oneshot_fd) graceful_shutdown = 0;
1498 
1499 
1500 #ifdef HAVE_SIGACTION
1501 	memset(&act, 0, sizeof(act));
1502 	sigemptyset(&act.sa_mask);
1503 
1504 	act.sa_handler = SIG_IGN;
1505 	sigaction(SIGPIPE, &act, NULL);
1506 
1507 #ifndef _MSC_VER
1508 	act.sa_flags = SA_NODEFER;
1509 	act.sa_handler = sys_setjmp_sigbus;
1510 	sigaction(SIGBUS, &act, NULL);
1511 	act.sa_flags = 0;
1512 #endif
1513 
1514 # if defined(SA_SIGINFO)
1515 	last_sighup_info.si_uid = 0,
1516 	last_sighup_info.si_pid = 0;
1517 	last_sigterm_info.si_uid = 0,
1518 	last_sigterm_info.si_pid = 0;
1519 	act.sa_sigaction = sigaction_handler;
1520 	act.sa_flags = SA_SIGINFO;
1521 # else
1522 	act.sa_handler = signal_handler;
1523 	act.sa_flags = 0;
1524 # endif
1525 	sigaction(SIGINT,  &act, NULL);
1526 	sigaction(SIGTERM, &act, NULL);
1527 	sigaction(SIGHUP,  &act, NULL);
1528 	sigaction(SIGALRM, &act, NULL);
1529 	sigaction(SIGUSR1, &act, NULL);
1530 
1531 	/* it should be safe to restart syscalls after SIGCHLD */
1532 	act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
1533 	sigaction(SIGCHLD, &act, NULL);
1534 #elif defined(HAVE_SIGNAL)
1535 	/* ignore the SIGPIPE from sendfile() */
1536 	signal(SIGPIPE, SIG_IGN);
1537 	signal(SIGALRM, signal_handler);
1538 	signal(SIGTERM, signal_handler);
1539 	signal(SIGHUP,  signal_handler);
1540 	signal(SIGCHLD,  signal_handler);
1541 	signal(SIGINT,  signal_handler);
1542 	signal(SIGUSR1, signal_handler);
1543 #ifndef _MSC_VER
1544 	signal(SIGBUS,  sys_setjmp_sigbus);
1545 #endif
1546 #endif
1547 
1548 
1549 	srv->gid = getgid();
1550 	srv->uid = getuid();
1551 	srv->pid = getpid();
1552 
1553 	/* write pid file */
1554 	if (pid_fd > 2) {
1555 		buffer * const tb = srv->tmp_buf;
1556 		buffer_clear(tb);
1557 		buffer_append_int(tb, srv->pid);
1558 		buffer_append_char(tb, '\n');
1559 		if (-1 == write_all(pid_fd, BUF_PTR_LEN(tb))) {
1560 			log_perror(srv->errh, __FILE__, __LINE__, "Couldn't write pid file");
1561 			close(pid_fd);
1562 			pid_fd = -1;
1563 			return -1;
1564 		}
1565 	} else if (pid_fd < -2) {
1566 		pid_fd = -pid_fd;
1567 	}
1568 
1569 	/* Close stderr ASAP in the child process to make sure that nothing
1570 	 * is being written to that fd which may not be valid anymore. */
1571 	if (!srv->srvconf.preflight_check) {
1572 		if (-1 == config_log_error_open(srv)) {
1573 			log_error(srv->errh, __FILE__, __LINE__, "Opening errorlog failed. Going down.");
1574 			return -1;
1575 		}
1576 		if (!oneshot_fd)
1577 			log_error(srv->errh, __FILE__, __LINE__, "server started (" PACKAGE_DESC ")");
1578 	}
1579 
1580 	if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1581 		log_error(srv->errh, __FILE__, __LINE__, "Configuration of plugins failed. Going down.");
1582 		return -1;
1583 	}
1584 
1585 	if (!config_finalize(srv, &default_server_tag)) {
1586 		return -1;
1587 	}
1588 
1589 	if (srv->srvconf.preflight_check) {
1590 		/*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1591 		return 0;
1592 	}
1593 
1594 
1595 #ifdef HAVE_FORK
1596 	/**
1597 	 * notify daemonize-grandparent of successful startup
1598 	 * do this before any further forking is done (workers)
1599 	 */
1600 	if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) {
1601 		if (0 > write(parent_pipe_fd, "", 1)) return -1;
1602 		close(parent_pipe_fd);
1603 	}
1604 
1605 	if (idle_limit && srv->srvconf.max_worker) {
1606 		srv->srvconf.max_worker = 0;
1607 		log_error(srv->errh, __FILE__, __LINE__,
1608 		  "server idle time limit command line option disables server.max-worker config file option.");
1609 	}
1610 
1611 	/* start watcher and workers */
1612 	num_childs = srv->srvconf.max_worker;
1613 	if (num_childs > 0) {
1614 		pid_t pids[num_childs];
1615 		pid_t pid;
1616 		const int npids = num_childs;
1617 		int child = 0;
1618 		unsigned int timer = 0;
1619 		for (int n = 0; n < npids; ++n) pids[n] = -1;
1620 		server_graceful_signal_prev_generation();
1621 		while (!child && !srv_shutdown && !graceful_shutdown) {
1622 			if (num_childs > 0) {
1623 				switch ((pid = fork())) {
1624 				case -1:
1625 					return -1;
1626 				case 0:
1627 					child = 1;
1628 					alarm(0);
1629 					break;
1630 				default:
1631 					num_childs--;
1632 					for (int n = 0; n < npids; ++n) {
1633 						if (-1 == pids[n]) {
1634 							pids[n] = pid;
1635 							break;
1636 						}
1637 					}
1638 					break;
1639 				}
1640 			} else {
1641 				int status;
1642 				unix_time64_t mono_ts;
1643 
1644 				if (-1 != (pid = fdevent_waitpid_intr(-1, &status))) {
1645 					mono_ts = log_monotonic_secs;
1646 					log_monotonic_secs = server_monotonic_secs();
1647 					log_epoch_secs = server_epoch_secs(srv, log_monotonic_secs - mono_ts);
1648 					if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1649 						if (!timer) alarm((timer = 5));
1650 						continue;
1651 					}
1652 					switch (fdlog_pipes_waitpid_cb(pid)) {
1653 					  default: break;
1654 					  case -1: if (!timer) alarm((timer = 5));
1655 						   __attribute_fallthrough__
1656 					  case  1: continue;
1657 					}
1658 					/**
1659 					 * check if one of our workers went away
1660 					 */
1661 					for (int n = 0; n < npids; ++n) {
1662 						if (pid == pids[n]) {
1663 							pids[n] = -1;
1664 							num_childs++;
1665 							break;
1666 						}
1667 					}
1668 				} else {
1669 					switch (errno) {
1670 					case EINTR:
1671 						mono_ts = log_monotonic_secs;
1672 						log_monotonic_secs = server_monotonic_secs();
1673 						log_epoch_secs = server_epoch_secs(srv, log_monotonic_secs - mono_ts);
1674 						/**
1675 						 * if we receive a SIGHUP we have to close our logs ourself as we don't
1676 						 * have the mainloop who can help us here
1677 						 */
1678 						if (handle_sig_hup) {
1679 							handle_sig_hup = 0;
1680 							fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */
1681 
1682 							/* forward SIGHUP to workers */
1683 							for (int n = 0; n < npids; ++n) {
1684 								if (pids[n] > 0) kill(pids[n], SIGHUP);
1685 							}
1686 						}
1687 						if (handle_sig_alarm) {
1688 							handle_sig_alarm = 0;
1689 							timer = 0;
1690 							plugins_call_handle_trigger(srv);
1691 							fdlog_pipes_restart(log_monotonic_secs);
1692 						}
1693 						break;
1694 					default:
1695 						break;
1696 					}
1697 				}
1698 			}
1699 		}
1700 
1701 		/**
1702 		 * for the parent this is the exit-point
1703 		 */
1704 		if (!child) {
1705 			/**
1706 			 * kill all children too
1707 			 */
1708 			if (graceful_shutdown || graceful_restart) {
1709 				/* flag to ignore one SIGINT if graceful_restart */
1710 				if (graceful_restart) graceful_restart = 2;
1711 				kill(0, SIGINT);
1712 				server_graceful_state(srv);
1713 			} else if (srv_shutdown) {
1714 				kill(0, SIGTERM);
1715 			}
1716 
1717 			return 0;
1718 		}
1719 
1720 		/* ignore SIGUSR1 in workers; only parent directs graceful restart */
1721 	      #ifdef HAVE_SIGACTION
1722 		{
1723 			struct sigaction actignore;
1724 			memset(&actignore, 0, sizeof(actignore));
1725 			actignore.sa_handler = SIG_IGN;
1726 			sigaction(SIGUSR1, &actignore, NULL);
1727 		}
1728 	      #elif defined(HAVE_SIGNAL)
1729 			signal(SIGUSR1, SIG_IGN);
1730 	      #endif
1731 
1732 		/**
1733 		 * make sure workers do not muck with pid-file
1734 		 */
1735 		if (0 <= pid_fd) {
1736 			close(pid_fd);
1737 			pid_fd = -1;
1738 		}
1739 		srv->srvconf.pid_file = NULL;
1740 
1741 		fdlog_pipes_abandon_pids();
1742 		srv->pid = getpid();
1743 		li_rand_reseed();
1744 	}
1745 #endif
1746 
1747 	srv->max_fds = (int)srv->srvconf.max_fds;
1748         if (srv->max_fds < 32) /*(sanity check; not expected)*/
1749             srv->max_fds = 32; /*(server load checks will fail if too low)*/
1750 	srv->ev = fdevent_init(srv->srvconf.event_handler, &srv->max_fds, &srv->cur_fds, srv->errh);
1751 	if (NULL == srv->ev) {
1752 		log_error(srv->errh, __FILE__, __LINE__, "fdevent_init failed");
1753 		return -1;
1754 	}
1755 
1756 	srv->max_fds_lowat = srv->max_fds * 8 / 10;
1757 	srv->max_fds_hiwat = srv->max_fds * 9 / 10;
1758 
1759 	/* set max-conns */
1760 	if (srv->srvconf.max_conns > srv->max_fds/2) {
1761 		/* we can't have more connections than max-fds/2 */
1762 		log_error(srv->errh, __FILE__, __LINE__,
1763 		  "can't have more connections than fds/2: %hu %d",
1764 		  srv->srvconf.max_conns, srv->max_fds);
1765 		srv->lim_conns = srv->srvconf.max_conns = srv->max_fds/2;
1766 	} else if (srv->srvconf.max_conns) {
1767 		/* otherwise respect the wishes of the user */
1768 		srv->lim_conns = srv->srvconf.max_conns;
1769 	} else {
1770 		/* or use the default: we really don't want to hit max-fds */
1771 		srv->lim_conns = srv->srvconf.max_conns = srv->max_fds/3;
1772 	}
1773 
1774 	/* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1775 #ifdef HAVE_SIGACTION
1776 	sigaction(SIGCHLD, &act, NULL);
1777 #elif defined(HAVE_SIGNAL)
1778 	signal(SIGCHLD,  signal_handler);
1779 #endif
1780 
1781 	/*
1782 	 * kqueue() is called here, select resets its internals,
1783 	 * all server sockets get their handlers
1784 	 *
1785 	 * */
1786 	if (0 != network_register_fdevents(srv)) {
1787 		return -1;
1788 	}
1789 
1790 	chunkqueue_internal_pipes(config_feature_bool(srv, "chunkqueue.splice", 1));
1791 
1792 	/* might fail if user is using fam (not gamin) and famd isn't running */
1793 	if (!stat_cache_init(srv->ev, srv->errh)) {
1794 		log_error(srv->errh, __FILE__, __LINE__,
1795 		  "stat-cache could not be setup, dying.");
1796 		return -1;
1797 	}
1798 
1799 #ifdef USE_ALARM
1800 	{
1801 		/* setup periodic timer (1 second) */
1802 		struct itimerval interval;
1803 		interval.it_interval.tv_sec = 1;
1804 		interval.it_interval.tv_usec = 0;
1805 		interval.it_value.tv_sec = 1;
1806 		interval.it_value.tv_usec = 0;
1807 		if (setitimer(ITIMER_REAL, &interval, NULL)) {
1808 			log_perror(srv->errh, __FILE__, __LINE__, "setitimer()");
1809 			return -1;
1810 		}
1811 	}
1812 #endif
1813 
1814 	/* get the current number of FDs */
1815 	{
1816 		int fd = fdevent_open_devnull();
1817 		if (fd >= 0) {
1818 			srv->cur_fds = fd;
1819 			close(fd);
1820 		}
1821 	}
1822 
1823 	if (0 != server_sockets_set_nb_cloexec(srv)) {
1824 		return -1;
1825 	}
1826 
1827 	/* plugin hook for worker_init */
1828 	if (HANDLER_GO_ON != plugins_call_worker_init(srv))
1829 		return -1;
1830 
1831 	if (oneshot_fdout > 0) {
1832 		if (server_oneshot_init_pipe(srv, oneshot_fd, oneshot_fdout)) {
1833 			oneshot_fd = -1;
1834 			oneshot_fdout = -1;
1835 		}
1836 	}
1837 	else if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) {
1838 		oneshot_fd = -1;
1839 	}
1840 
1841 	if (0 == srv->srvconf.max_worker)
1842 		server_graceful_signal_prev_generation();
1843 
1844 	return 1;
1845 }
1846 
1847 __attribute_cold__
1848 __attribute_noinline__
1849 static void server_handle_sighup (server * const srv) {
1850 
1851 			/* cycle logfiles */
1852 
1853 			plugins_call_handle_sighup(srv);
1854 			fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */
1855 #ifdef HAVE_SIGACTION
1856 				log_error(srv->errh, __FILE__, __LINE__,
1857 				  "logfiles cycled UID = %d PID = %d",
1858 				  (int)last_sighup_info.si_uid,
1859 				  (int)last_sighup_info.si_pid);
1860 #else
1861 				log_error(srv->errh, __FILE__, __LINE__,
1862 				  "logfiles cycled");
1863 #endif
1864 }
1865 
1866 __attribute_noinline__
1867 static void server_handle_sigalrm (server * const srv, unix_time64_t mono_ts, unix_time64_t last_active_ts) {
1868 
1869 				plugins_call_handle_trigger(srv);
1870 
1871 				log_monotonic_secs = mono_ts;
1872 				log_epoch_secs = server_epoch_secs(srv, 0);
1873 
1874 				/* check idle time limit, if enabled */
1875 				if (idle_limit && idle_limit < mono_ts - last_active_ts && !graceful_shutdown) {
1876 					log_error(srv->errh, __FILE__, __LINE__,
1877 					  "[note] idle timeout %ds exceeded, "
1878 					  "initiating graceful shutdown", (int)idle_limit);
1879 					graceful_shutdown = 2; /* value 2 indicates idle timeout */
1880 					if (graceful_restart) {
1881 						graceful_restart = 0;
1882 						if (pid_fd < -2) pid_fd = -pid_fd;
1883 						server_sockets_close(srv);
1884 					}
1885 				}
1886 
1887 			      #ifdef HAVE_GETLOADAVG
1888 				/* refresh loadavg data every 30 seconds */
1889 				if (srv->loadts + 30 < mono_ts) {
1890 					if (-1 != getloadavg(srv->loadavg, 3)) {
1891 						srv->loadts = mono_ts;
1892 					}
1893 				}
1894 			      #endif
1895 
1896 				if (0 == (mono_ts & 0x3f)) { /*(once every 64 secs)*/
1897 					/* free logger buffers every 64 secs */
1898 					fdlog_flushall(srv->errh);
1899 					/* free excess chunkqueue buffers every 64 secs */
1900 					chunkqueue_chunk_pool_clear();
1901 					/* clear request and connection pools every 64 secs */
1902 					request_pool_free();
1903 					connections_pool_clear(srv);
1904 				  #if defined(HAVE_MALLOC_TRIM)
1905 					if (malloc_trim_fn) malloc_trim_fn(malloc_top_pad);
1906 				  #endif
1907 					/* attempt to restart dead piped loggers every 64 secs */
1908 					if (0 == srv->srvconf.max_worker)
1909 						fdlog_pipes_restart(mono_ts);
1910 				}
1911 				/* cleanup stat-cache */
1912 				stat_cache_trigger_cleanup();
1913 				/* reset global/aggregate rate limit counters */
1914 				config_reset_config_bytes_sec(srv->config_data_base);
1915 				/* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1916 				if (graceful_shutdown && !srv_shutdown)
1917 					server_graceful_shutdown_maint(srv);
1918 				connection_periodic_maint(srv, mono_ts);
1919 }
1920 
1921 __attribute_noinline__
1922 static void server_handle_sigchld (server * const srv) {
1923 			pid_t pid;
1924 			do {
1925 				int status;
1926 				pid = fdevent_waitpid(-1, &status, 1);
1927 				if (pid > 0) {
1928 					if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1929 						continue;
1930 					}
1931 					if (0 == srv->srvconf.max_worker) {
1932 						/* check piped-loggers and restart, even if shutting down */
1933 						if (fdlog_pipes_waitpid_cb(pid)) {
1934 							continue;
1935 						}
1936 					}
1937 				}
1938 			} while (pid > 0 || (-1 == pid && errno == EINTR));
1939 }
1940 
1941 __attribute_hot__
1942 __attribute_nonnull__()
1943 static void server_run_con_queue (connection * const restrict joblist, const connection * const sentinel) {
1944     for (connection *con = joblist, *jqnext; con != sentinel; con = jqnext) {
1945         jqnext = con->jqnext;
1946         con->jqnext = NULL;
1947         connection_state_machine(con);
1948     }
1949 }
1950 
1951 __attribute_hot__
1952 __attribute_noinline__
1953 static void server_main_loop (server * const srv) {
1954 	unix_time64_t last_active_ts = server_monotonic_secs();
1955 	log_epoch_secs = server_epoch_secs(srv, 0);
1956 
1957 	while (!srv_shutdown) {
1958 
1959 		if (handle_sig_hup) {
1960 			handle_sig_hup = 0;
1961 			server_handle_sighup(srv);
1962 		}
1963 
1964 		/*(USE_ALARM not used; fdevent_poll() is effective periodic timer)*/
1965 	      #ifdef USE_ALARM
1966 		if (handle_sig_alarm) {
1967 			handle_sig_alarm = 0;
1968 	      #endif
1969 			unix_time64_t mono_ts = server_monotonic_secs();
1970 			if (mono_ts != log_monotonic_secs) {
1971 				server_handle_sigalrm(srv, mono_ts, last_active_ts);
1972 			}
1973 	      #ifdef USE_ALARM
1974 		}
1975 	      #endif
1976 
1977 		if (handle_sig_child) {
1978 			handle_sig_child = 0;
1979 			server_handle_sigchld(srv);
1980 		}
1981 
1982 		if (graceful_shutdown) {
1983 			server_graceful_state(srv);
1984 			if (NULL == srv->conns && graceful_shutdown) {
1985 				/* we are in graceful shutdown phase and all connections are closed
1986 				 * we are ready to terminate without harming anyone */
1987 				srv_shutdown = 1;
1988 				break;
1989 			}
1990 		} else if (srv->sockets_disabled) {
1991 			server_overload_check(srv);
1992 		} else {
1993 			server_load_check(srv);
1994 		}
1995 
1996 		static connection * const sentinel =
1997 		  (connection *)(uintptr_t)&log_con_jqueue;
1998 		connection * const joblist = log_con_jqueue;
1999 		log_con_jqueue = sentinel;
2000 		server_run_con_queue(joblist, sentinel);
2001 
2002 		if (fdevent_poll(srv->ev, log_con_jqueue != sentinel ? 0 : 1000) > 0)
2003 			last_active_ts = log_monotonic_secs;
2004 	}
2005 }
2006 
2007 __attribute_cold__
2008 __attribute_noinline__
2009 static int main_init_once (void) {
2010   #ifdef HAVE_GETUID
2011   #ifndef HAVE_ISSETUGID
2012   #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2013   #endif
2014     if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2015         fprintf(stderr,
2016                 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2017         return 0;
2018     }
2019   #endif
2020 
2021   #if defined(HAVE_MALLOPT) && defined(M_ARENA_MAX)
2022   #ifdef LIGHTTPD_STATIC
2023     mallopt(M_ARENA_MAX, 2); /*(ignore error, if any)*/
2024   #else
2025     {
2026         int (*mallopt_fn)(int, int);
2027         mallopt_fn = (int (*)(int, int))(intptr_t)dlsym(RTLD_DEFAULT,"mallopt");
2028         if (mallopt_fn) mallopt_fn(M_ARENA_MAX, 2); /*(ignore error, if any)*/
2029     }
2030   #endif
2031   #endif
2032 
2033   #if defined(HAVE_MALLOC_TRIM)
2034     malloc_top_pad = 524288;
2035     {
2036         const char * const top_pad_str = getenv("MALLOC_TOP_PAD_");
2037         if (top_pad_str) {
2038             unsigned long top_pad = strtoul(top_pad_str, NULL, 10);
2039             if (top_pad != ULONG_MAX) malloc_top_pad = (size_t)top_pad;
2040         }
2041     }
2042   #ifdef LIGHTTPD_STATIC
2043     malloc_trim_fn = malloc_trim;
2044   #else
2045     malloc_trim_fn =
2046       (int (*)(size_t))(intptr_t)dlsym(RTLD_DEFAULT,"malloc_trim");
2047   #endif
2048   #endif
2049 
2050     /* for nice %b handling in strftime() */
2051     setlocale(LC_TIME, "C");
2052     tzset();
2053 
2054     return 1;
2055 }
2056 
2057 __attribute_cold__
2058 int main (int argc, char ** argv) {
2059     if (!main_init_once()) return -1;
2060 
2061     int rc;
2062 
2063     do {
2064         server * const srv = server_init();
2065 
2066         if (graceful_restart) {
2067             server_sockets_restore(srv);
2068             optind = 1;
2069         }
2070 
2071         rc = server_main_setup(srv, argc, argv);
2072         if (rc > 0) {
2073 
2074             server_main_loop(srv);
2075 
2076             if (graceful_shutdown || graceful_restart) {
2077                 server_graceful_state(srv);
2078             }
2079 
2080             if (NULL == srv->conns) rc = 0;
2081             if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */
2082                 log_error(srv->errh, __FILE__, __LINE__,
2083                   "server stopped after idle timeout");
2084             } else if (!oneshot_fd) {
2085               #ifdef HAVE_SIGACTION
2086                 log_error(srv->errh, __FILE__, __LINE__,
2087                   "server stopped by UID = %d PID = %d",
2088                   (int)last_sigterm_info.si_uid,
2089                   (int)last_sigterm_info.si_pid);
2090               #else
2091                 log_error(srv->errh, __FILE__, __LINE__,
2092                   "server stopped");
2093               #endif
2094             }
2095         }
2096 
2097         /* clean-up */
2098         chunkqueue_internal_pipes(0);
2099         remove_pid_file(srv);
2100         config_log_error_close(srv);
2101         if (graceful_restart)
2102             server_sockets_save(srv);
2103         else
2104             network_close(srv);
2105         request_pool_free();
2106         connections_free(srv);
2107         plugins_free(srv);
2108         server_free(srv);
2109 
2110         if (rc < 0 || !graceful_restart) break;
2111 
2112         /* wait for all children to exit before graceful restart */
2113         while (fdevent_waitpid(-1, NULL, 0) > 0) ;
2114     } while (graceful_restart);
2115 
2116     return rc;
2117 }
2118