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