xref: /lighttpd1.4/src/server.c (revision 672891a7)
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 "http_auth.h"      /* http_auth_dumbdata_reset() */
10 #include "http_vhostdb.h"   /* http_vhostdb_dumbdata_reset() */
11 #include "fdevent.h"
12 #include "connections.h"
13 #include "sock_addr.h"
14 #include "stat_cache.h"
15 #include "plugin.h"
16 #include "network_write.h"  /* network_write_show_handlers() */
17 #include "response.h"       /* strftime_cache_reset() */
18 
19 #ifdef HAVE_VERSIONSTAMP_H
20 # include "versionstamp.h"
21 #else
22 # define REPO_VERSION ""
23 #endif
24 
25 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
26 static const buffer default_server_tag = { CONST_STR_LEN(PACKAGE_DESC), 0 };
27 
28 #include <sys/types.h>
29 #include <sys/time.h>
30 #include <sys/stat.h>
31 #include <sys/wait.h>
32 
33 #include <string.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <unistd.h>
37 #include <stdlib.h>
38 #include <time.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_SYS_WAIT_H
53 # include <sys/wait.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 
73 #include "sys-crypto.h"
74 #if defined(USE_OPENSSL_CRYPTO) \
75  || defined(USE_MBEDTLS_CRYPTO) \
76  || defined(USE_NSS_CRYPTO) \
77  || defined(USE_GNUTLS_CRYPTO) \
78  || defined(USE_WOLFTLS_CRYPTO)
79 #define TEXT_SSL " (ssl)"
80 #else
81 #define TEXT_SSL
82 #endif
83 
84 #ifndef __sgi
85 /* IRIX doesn't like the alarm based time() optimization */
86 /* #define USE_ALARM */
87 #endif
88 
89 static int oneshot_fd = 0;
90 static volatile int pid_fd = -2;
91 static server_socket_array graceful_sockets;
92 static server_socket_array inherited_sockets;
93 static volatile sig_atomic_t graceful_restart = 0;
94 static volatile sig_atomic_t graceful_shutdown = 0;
95 static volatile sig_atomic_t srv_shutdown = 0;
96 static volatile sig_atomic_t handle_sig_child = 0;
97 static volatile sig_atomic_t handle_sig_alarm = 1;
98 static volatile sig_atomic_t handle_sig_hup = 0;
99 static time_t idle_limit = 0;
100 
101 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
102 static volatile siginfo_t last_sigterm_info;
103 static volatile siginfo_t last_sighup_info;
104 
105 static void sigaction_handler(int sig, siginfo_t *si, void *context) {
106 	static const siginfo_t empty_siginfo;
107 	UNUSED(context);
108 
109 	if (!si) *(const siginfo_t **)&si = &empty_siginfo;
110 
111 	switch (sig) {
112 	case SIGTERM:
113 		srv_shutdown = 1;
114 		last_sigterm_info = *si;
115 		break;
116 	case SIGUSR1:
117 		if (!graceful_shutdown) {
118 			graceful_restart = 1;
119 			graceful_shutdown = 1;
120 			last_sigterm_info = *si;
121 		}
122 		break;
123 	case SIGINT:
124 		if (graceful_shutdown) {
125 			if (2 == graceful_restart)
126 				graceful_restart = 1;
127 			else
128 				srv_shutdown = 1;
129 		} else {
130 			graceful_shutdown = 1;
131 		}
132 		last_sigterm_info = *si;
133 
134 		break;
135 	case SIGALRM:
136 		handle_sig_alarm = 1;
137 		break;
138 	case SIGHUP:
139 		handle_sig_hup = 1;
140 		last_sighup_info = *si;
141 		break;
142 	case SIGCHLD:
143 		handle_sig_child = 1;
144 		break;
145 	}
146 }
147 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
148 static void signal_handler(int sig) {
149 	switch (sig) {
150 	case SIGTERM: srv_shutdown = 1; break;
151 	case SIGUSR1:
152 		if (!graceful_shutdown) {
153 			graceful_restart = 1;
154 			graceful_shutdown = 1;
155 		}
156 		break;
157 	case SIGINT:
158 		if (graceful_shutdown) {
159 			if (2 == graceful_restart)
160 				graceful_restart = 1;
161 			else
162 				srv_shutdown = 1;
163 		} else {
164 			graceful_shutdown = 1;
165 		}
166 		break;
167 	case SIGALRM: handle_sig_alarm = 1; break;
168 	case SIGHUP:  handle_sig_hup = 1; break;
169 	case SIGCHLD: handle_sig_child = 1; break;
170 	}
171 }
172 #endif
173 
174 #ifdef HAVE_FORK
175 static int daemonize(void) {
176 	int pipefd[2];
177 	pid_t pid;
178 #ifdef SIGTTOU
179 	signal(SIGTTOU, SIG_IGN);
180 #endif
181 #ifdef SIGTTIN
182 	signal(SIGTTIN, SIG_IGN);
183 #endif
184 #ifdef SIGTSTP
185 	signal(SIGTSTP, SIG_IGN);
186 #endif
187 
188 	if (pipe(pipefd) < 0) exit(-1);
189 
190 	if (0 > (pid = fork())) exit(-1);
191 
192 	if (0 < pid) {
193 		char buf;
194 		ssize_t bytes;
195 
196 		close(pipefd[1]);
197 		/* parent waits for grandchild to be ready */
198 		do {
199 			bytes = read(pipefd[0], &buf, sizeof(buf));
200 		} while (bytes < 0 && EINTR == errno);
201 		close(pipefd[0]);
202 
203 		if (bytes <= 0) {
204 			/* closed fd (without writing) == failure in grandchild */
205 			fputs("daemonized server failed to start; check error log for details\n", stderr);
206 			exit(-1);
207 		}
208 
209 		exit(0);
210 	}
211 
212 	close(pipefd[0]);
213 
214 	if (-1 == setsid()) exit(0);
215 
216 	signal(SIGHUP, SIG_IGN);
217 
218 	if (0 != fork()) exit(0);
219 
220 	if (0 != chdir("/")) exit(0);
221 
222 	fdevent_setfd_cloexec(pipefd[1]);
223 	return pipefd[1];
224 }
225 #endif
226 
227 __attribute_cold__
228 static server *server_init(void) {
229 	server *srv = calloc(1, sizeof(*srv));
230 	force_assert(srv);
231 #define CLEAN(x) \
232 	srv->x = buffer_init();
233 
234 	CLEAN(tmp_buf);
235 #undef CLEAN
236 
237 	strftime_cache_reset();
238 
239 	li_rand_reseed();
240 
241 	srv->startup_ts = log_epoch_secs = time(NULL);
242 
243 	srv->errh = log_error_st_init();
244 
245 	config_init(srv);
246 
247 	srv->request_env = plugins_call_handle_request_env;
248 
249 	srv->loadavg[0] = 0.0;
250 	srv->loadavg[1] = 0.0;
251 	srv->loadavg[2] = 0.0;
252 	srv->stdin_fd = -1;
253 
254 	return srv;
255 }
256 
257 __attribute_cold__
258 static void server_free(server *srv) {
259 	if (oneshot_fd > 0) {
260 		close(oneshot_fd);
261 	}
262 	if (srv->stdin_fd >= 0) {
263 		close(srv->stdin_fd);
264 	}
265 
266 #define CLEAN(x) \
267 	buffer_free(srv->x);
268 
269 	CLEAN(tmp_buf);
270 
271 #undef CLEAN
272 
273 	fdevent_free(srv->ev);
274 
275 	config_free(srv);
276 
277 	free(srv->joblist.ptr);
278 	free(srv->fdwaitqueue.ptr);
279 
280 	stat_cache_free();
281 
282 	li_rand_cleanup();
283 	chunkqueue_chunk_pool_free();
284 
285 	log_error_st_free(srv->errh);
286 	free(srv);
287 }
288 
289 __attribute_cold__
290 static void remove_pid_file(server *srv) {
291 	if (pid_fd <= -2) return;
292 	if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= pid_fd) {
293 		if (0 != ftruncate(pid_fd, 0)) {
294 			log_perror(srv->errh, __FILE__, __LINE__,
295 			  "ftruncate failed for: %s", srv->srvconf.pid_file->ptr);
296 		}
297 	}
298 	if (0 <= pid_fd) {
299 		close(pid_fd);
300 		pid_fd = -1;
301 	}
302 	if (!buffer_string_is_empty(srv->srvconf.pid_file) &&
303 	    buffer_string_is_empty(srv->srvconf.changeroot)) {
304 		if (0 != unlink(srv->srvconf.pid_file->ptr)) {
305 			if (errno != EACCES && errno != EPERM) {
306 				log_perror(srv->errh, __FILE__, __LINE__,
307 				  "unlink failed for: %s", srv->srvconf.pid_file->ptr);
308 			}
309 		}
310 	}
311 }
312 
313 
314 __attribute_cold__
315 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) {
316 	server_socket *srv_socket, *srv_socket_wild = NULL;
317 	for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
318 		srv_socket = srv->srv_sockets.ptr[i];
319 		if (!sock_addr_is_port_eq(&srv_socket->addr,cnt_addr)) continue;
320 		if (sock_addr_is_addr_eq(&srv_socket->addr,cnt_addr)) return srv_socket;
321 
322 		if (NULL != srv_socket_wild) continue;
323 		if (sock_addr_is_addr_wildcard(&srv_socket->addr)) {
324 			srv_socket_wild = srv_socket;
325 		}
326 	}
327 
328 	if (NULL != srv_socket_wild) {
329 		return srv_socket_wild;
330 	} else if (srv->srv_sockets.used) {
331 		return srv->srv_sockets.ptr[0];
332 	} else {
333 		log_error(srv->errh, __FILE__, __LINE__, "no sockets configured");
334 		return NULL;
335 	}
336 }
337 
338 
339 __attribute_cold__
340 static int server_oneshot_init(server *srv, int fd) {
341 	/* Note: does not work with netcat due to requirement that fd be socket.
342 	 * STDOUT_FILENO was not saved earlier in startup, and that is to where
343 	 * netcat expects output to be sent.  Since lighttpd expects connections
344 	 * to be sockets, con->fd is where output is sent; separate fds are not
345 	 * stored for input and output, but netcat has different fds for stdin
346 	 * and * stdout.  To support netcat, would additionally need to avoid
347 	 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
348 	 * addresses from environment variables:
349 	 *   NCAT_LOCAL_ADDR   NCAT_LOCAL_PORT
350 	 *   NCAT_REMOTE_ADDR  NCAT_REMOTE_PORT
351 	 *   NCAT_PROTO
352 	 */
353 	connection *con;
354 	server_socket *srv_socket;
355 	sock_addr cnt_addr;
356 	socklen_t cnt_len;
357 	struct stat st;
358 
359 	if (0 != fstat(fd, &st)) {
360 		log_perror(srv->errh, __FILE__, __LINE__, "fstat()");
361 		return 0;
362 	}
363 
364 	if (!S_ISSOCK(st.st_mode)) {
365 		/* require that fd is a socket
366 		 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
367 		log_error(srv->errh, __FILE__, __LINE__,
368 		  "lighttpd -1 stdin is not a socket");
369 		return 0;
370 	}
371 
372 	cnt_len = sizeof(cnt_addr);
373 	if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
374 		log_perror(srv->errh, __FILE__, __LINE__, "getsockname()");
375 		return 0;
376 	}
377 
378 	srv_socket = server_oneshot_getsock(srv, &cnt_addr);
379 	if (NULL == srv_socket) return 0;
380 
381       #ifdef __clang_analyzer__
382         memset(&cnt_addr, 0, sizeof(cnt_addr));
383       #endif
384 	cnt_len = sizeof(cnt_addr);
385 	if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
386 		log_perror(srv->errh, __FILE__, __LINE__, "getpeername()");
387 		return 0;
388 	}
389 
390 	/*(must set flags; fd did not pass through fdevent accept() logic)*/
391 	if (-1 == fdevent_fcntl_set_nb_cloexec(fd)) {
392 		log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
393 		return 0;
394 	}
395 
396 	if (sock_addr_get_family(&cnt_addr) != AF_UNIX) {
397 		network_accept_tcp_nagle_disable(fd);
398 	}
399 
400 	con = connection_accepted(srv, srv_socket, &cnt_addr, fd);
401 	if (NULL == con) return 0;
402 
403 	connection_state_machine(con);
404 	return 1;
405 }
406 
407 
408 __attribute_cold__
409 static void show_version (void) {
410 	char *b = PACKAGE_DESC TEXT_SSL \
411 " - a light and fast webserver\n"
412 #ifdef NONREPRODUCIBLE_BUILD
413 "Build-Date: " __DATE__ " " __TIME__ "\n";
414 #endif
415 ;
416 	write_all(STDOUT_FILENO, b, strlen(b));
417 }
418 
419 __attribute_cold__
420 static void show_features (void) {
421   static const char features[] =
422       "\nFeatures:\n\n"
423 #ifdef HAVE_IPV6
424       "\t+ IPv6 support\n"
425 #else
426       "\t- IPv6 support\n"
427 #endif
428 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
429       "\t+ zlib support\n"
430 #else
431       "\t- zlib support\n"
432 #endif
433 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
434       "\t+ bzip2 support\n"
435 #else
436       "\t- bzip2 support\n"
437 #endif
438 #if defined HAVE_BROTLI_ENCODE_H && defined HAVE_BROTLI
439       "\t+ brotli support\n"
440 #else
441       "\t- brotli support\n"
442 #endif
443 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
444       "\t+ crypt support\n"
445 #else
446       "\t- crypt support\n"
447 #endif
448 #ifdef USE_OPENSSL_CRYPTO
449       "\t+ OpenSSL support\n"
450 #else
451       "\t- OpenSSL support\n"
452 #endif
453 #ifdef USE_MBEDTLS_CRYPTO
454       "\t+ mbedTLS support\n"
455 #else
456       "\t- mbedTLS support\n"
457 #endif
458 #ifdef USE_NSS_CRYPTO
459       "\t+ NSS crypto support\n"
460 #else
461       "\t- NSS crypto support\n"
462 #endif
463 #ifdef USE_GNUTLS_CRYPTO
464       "\t+ GnuTLS support\n"
465 #else
466       "\t- GnuTLS support\n"
467 #endif
468 #ifdef USE_WOLFSSL_CRYPTO
469       "\t+ WolfSSL support\n"
470 #else
471       "\t- WolfSSL support\n"
472 #endif
473 #ifdef USE_NETTLE_CRYPTO
474       "\t+ Nettle support\n"
475 #else
476       "\t- Nettle support\n"
477 #endif
478 #ifdef HAVE_LIBPCRE
479       "\t+ PCRE support\n"
480 #else
481       "\t- PCRE support\n"
482 #endif
483 #ifdef HAVE_MYSQL
484       "\t+ MySQL support\n"
485 #else
486       "\t- MySQL support\n"
487 #endif
488 #ifdef HAVE_PGSQL
489       "\t+ PgSQL support\n"
490 #else
491       "\t- PgSQL support\n"
492 #endif
493 #ifdef HAVE_DBI
494       "\t+ DBI support\n"
495 #else
496       "\t- DBI support\n"
497 #endif
498 #ifdef HAVE_KRB5
499       "\t+ Kerberos support\n"
500 #else
501       "\t- Kerberos support\n"
502 #endif
503 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
504       "\t+ LDAP support\n"
505 #else
506       "\t- LDAP support\n"
507 #endif
508 #ifdef HAVE_PAM
509       "\t+ PAM support\n"
510 #else
511       "\t- PAM support\n"
512 #endif
513 #ifdef USE_MEMCACHED
514       "\t+ memcached support\n"
515 #else
516       "\t- memcached support\n"
517 #endif
518 #ifdef HAVE_FAM_H
519       "\t+ FAM support\n"
520 #else
521       "\t- FAM support\n"
522 #endif
523 #ifdef HAVE_LUA_H
524       "\t+ LUA support\n"
525 #else
526       "\t- LUA support\n"
527 #endif
528 #ifdef HAVE_LIBXML_H
529       "\t+ xml support\n"
530 #else
531       "\t- xml support\n"
532 #endif
533 #ifdef HAVE_SQLITE3_H
534       "\t+ SQLite support\n"
535 #else
536       "\t- SQLite support\n"
537 #endif
538 #ifdef HAVE_GDBM_H
539       "\t+ GDBM support\n"
540 #else
541       "\t- GDBM support\n"
542 #endif
543       ;
544   show_version();
545   printf("%s%s%s\n", fdevent_show_event_handlers(), network_write_show_handlers(), features);
546 }
547 
548 __attribute_cold__
549 static void show_help (void) {
550 	char *b = PACKAGE_DESC TEXT_SSL
551 #ifdef NONREPRODUCIBLE_BUILD
552 " ("__DATE__ " " __TIME__ ")"
553 #endif
554 " - a light and fast webserver\n" \
555 "usage:\n" \
556 " -f <name>  filename of the config-file\n" \
557 " -m <name>  module directory (default: "LIBRARY_DIR")\n" \
558 " -i <secs>  graceful shutdown after <secs> of inactivity\n" \
559 " -1         process single (one) request on stdin socket, then exit\n" \
560 " -p         print the parsed config-file in internal form, and exit\n" \
561 " -t         test config-file syntax, then exit\n" \
562 " -tt        test config-file syntax, load and init modules, then exit\n" \
563 " -D         don't go to background (default: go to background)\n" \
564 " -v         show version\n" \
565 " -V         show compile-time features\n" \
566 " -h         show this help\n" \
567 "\n"
568 ;
569 	write_all(STDOUT_FILENO, b, strlen(b));
570 }
571 
572 __attribute_cold__
573 static void server_sockets_save (server *srv) {    /* graceful_restart */
574     memcpy(&graceful_sockets, &srv->srv_sockets, sizeof(server_socket_array));
575     memset(&srv->srv_sockets, 0, sizeof(server_socket_array));
576     memcpy(&inherited_sockets, &srv->srv_sockets_inherited, sizeof(server_socket_array));
577     memset(&srv->srv_sockets_inherited, 0, sizeof(server_socket_array));
578 }
579 
580 __attribute_cold__
581 static void server_sockets_restore (server *srv) { /* graceful_restart */
582     memcpy(&srv->srv_sockets, &graceful_sockets, sizeof(server_socket_array));
583     memset(&graceful_sockets, 0, sizeof(server_socket_array));
584     memcpy(&srv->srv_sockets_inherited, &inherited_sockets, sizeof(server_socket_array));
585     memset(&inherited_sockets, 0, sizeof(server_socket_array));
586 }
587 
588 __attribute_cold__
589 static int server_sockets_set_nb_cloexec (server *srv) {
590     if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */
591     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
592         server_socket *srv_socket = srv->srv_sockets.ptr[i];
593         if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv_socket->fd)) {
594             log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
595             return -1;
596         }
597     }
598     return 0;
599 }
600 
601 __attribute_cold__
602 static void server_sockets_set_event (server *srv, int event) {
603     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
604         server_socket *srv_socket = srv->srv_sockets.ptr[i];
605         fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event);
606     }
607 }
608 
609 __attribute_cold__
610 static void server_sockets_unregister (server *srv) {
611     if (2 == srv->sockets_disabled) return;
612     srv->sockets_disabled = 2;
613     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i)
614         network_unregister_sock(srv, srv->srv_sockets.ptr[i]);
615 }
616 
617 __attribute_cold__
618 static void server_sockets_close (server *srv) {
619     /* closing socket right away will make it possible for the next lighttpd
620      * to take over (old-style graceful restart), but only if backends
621      * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
622      * than started by lighttpd via "bin-path")
623      */
624     if (3 == srv->sockets_disabled) return;
625     for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
626         server_socket *srv_socket = srv->srv_sockets.ptr[i];
627         if (-1 == srv_socket->fd) continue;
628         if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket);
629         close(srv_socket->fd);
630         srv_socket->fd = -1;
631         /* network_close() will cleanup after us */
632     }
633     srv->sockets_disabled = 3;
634 }
635 
636 __attribute_cold__
637 static void server_graceful_state (server *srv) {
638 
639     if (!srv_shutdown) connection_graceful_shutdown_maint(srv);
640 
641     if (!oneshot_fd
642         && (2 == srv->sockets_disabled || 3 == srv->sockets_disabled)) return;
643 
644     log_error(srv->errh,__FILE__,__LINE__,"[note] graceful shutdown started");
645 
646     /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
647     if (!buffer_string_is_empty(srv->srvconf.changeroot)
648         || oneshot_fd || 2 == graceful_shutdown)
649         graceful_restart = 0;
650 
651     if (graceful_restart) {
652         server_sockets_unregister(srv);
653         if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/
654     }
655     else {
656         server_sockets_close(srv);
657         remove_pid_file(srv);
658         /*(prevent more removal attempts)*/
659         if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file);
660     }
661 }
662 
663 __attribute_cold__
664 static void server_sockets_enable (server *srv) {
665     server_sockets_set_event(srv, FDEVENT_IN);
666     srv->sockets_disabled = 0;
667     log_error(srv->errh, __FILE__, __LINE__, "[note] sockets enabled again");
668 }
669 
670 __attribute_cold__
671 static void server_sockets_disable (server *srv) {
672     server_sockets_set_event(srv, 0);
673     srv->sockets_disabled = 1;
674     log_error(srv->errh, __FILE__, __LINE__,
675       (srv->conns.used >= srv->max_conns)
676         ? "[note] sockets disabled, connection limit reached"
677         : "[note] sockets disabled, out-of-fds");
678 }
679 
680 __attribute_cold__
681 static void server_overload_check (server *srv) {
682     if (srv->cur_fds + (int)srv->fdwaitqueue.used < srv->max_fds_lowat
683         && srv->conns.used < srv->max_conns) {
684 
685         server_sockets_enable(srv);
686     }
687 }
688 
689 static void server_load_check (server *srv) {
690     /* check if hit limits for num fds used or num connections */
691     if (srv->cur_fds > srv->max_fds_hiwat || srv->conns.used >= srv->max_conns)
692         server_sockets_disable(srv);
693 }
694 
695 __attribute_cold__
696 __attribute_noinline__
697 static void server_process_fdwaitqueue (server *srv) {
698     connections * const fdwaitqueue = &srv->fdwaitqueue;
699     uint32_t i = 0;
700     for (int n = srv->max_fds - srv->cur_fds - 16; n > 0; --n) {
701         if (i == fdwaitqueue->used) break;
702         connection_state_machine(fdwaitqueue->ptr[i++]);
703     }
704     if (i > 0 && 0 != (fdwaitqueue->used -= i)) {
705 	memmove(fdwaitqueue->ptr, fdwaitqueue->ptr+i, fdwaitqueue->used * sizeof(*(fdwaitqueue->ptr)));
706     }
707 }
708 
709 __attribute_cold__
710 static int server_main_setup (server * const srv, int argc, char **argv) {
711 	int print_config = 0;
712 	int test_config = 0;
713 	int i_am_root = 0;
714 	int o;
715 #ifdef HAVE_FORK
716 	int num_childs = 0;
717 #endif
718 	uint32_t i;
719 #ifdef HAVE_SIGACTION
720 	struct sigaction act;
721 #endif
722 
723 #ifdef HAVE_FORK
724 	int parent_pipe_fd = -1;
725 #endif
726 
727 #ifdef HAVE_GETUID
728 	i_am_root = (0 == getuid());
729 #endif
730 
731 	/* initialize globals (including file-scoped static globals) */
732 	oneshot_fd = 0;
733 	srv_shutdown = 0;
734 	graceful_shutdown = 0;
735 	handle_sig_alarm = 1;
736 	handle_sig_hup = 0;
737 	idle_limit = 0;
738 	chunkqueue_set_tempdirs_default_reset();
739 	http_auth_dumbdata_reset();
740 	http_vhostdb_dumbdata_reset();
741 	/*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
742 	/*(intentionally preserved)*/
743 	/*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
744 	/*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/
745 	/*pid_fd = -1;*/
746 
747 	while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) {
748 		switch(o) {
749 		case 'f':
750 			if (srv->config_data_base) {
751 				log_error(srv->errh, __FILE__, __LINE__,
752 				  "Can only read one config file. Use the include command to use multiple config files.");
753 				return -1;
754 			}
755 			if (config_read(srv, optarg)) {
756 				return -1;
757 			}
758 			break;
759 		case 'm':
760 			buffer_copy_string(srv->srvconf.modules_dir, optarg);
761 			break;
762 		case 'i': {
763 			char *endptr;
764 			long timeout = strtol(optarg, &endptr, 0);
765 			if (!*optarg || *endptr || timeout < 0) {
766 				log_error(srv->errh, __FILE__, __LINE__,
767 				  "Invalid idle timeout value: %s", optarg);
768 				return -1;
769 			}
770 			idle_limit = (time_t)timeout;
771 			break;
772 		}
773 		case 'p': print_config = 1; break;
774 		case 't': ++test_config; break;
775 		case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO);
776 			  break;
777 		case 'D': srv->srvconf.dont_daemonize = 1; break;
778 		case 'v': show_version(); return 0;
779 		case 'V': show_features(); return 0;
780 		case 'h': show_help(); return 0;
781 		default:
782 			show_help();
783 			return -1;
784 		}
785 	}
786 
787       #ifdef __CYGWIN__
788 	if (!srv->config_data_base && NULL != getenv("NSSM_SERVICE_NAME")) {
789 		char *dir = getenv("NSSM_SERVICE_DIR");
790 		if (NULL != dir && 0 != chdir(dir)) {
791 			log_perror(srv->errh, __FILE__, __LINE__, "chdir %s failed", dir);
792 			return -1;
793 		}
794 		srv->srvconf.dont_daemonize = 1;
795 		buffer_copy_string_len(srv->srvconf.modules_dir, CONST_STR_LEN("modules"));
796 		if (config_read(srv, "conf/lighttpd.conf")) return -1;
797 	}
798       #endif
799 
800 	if (!srv->config_data_base) {
801 		log_error(srv->errh, __FILE__, __LINE__,
802 		  "No configuration available. Try using -f option.");
803 		return -1;
804 	}
805 
806 	if (print_config) {
807 		config_print(srv);
808 		fprintf(stdout, "\n");
809 	}
810 
811 	if (test_config) {
812 		if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file);
813 		if (1 == test_config) {
814 			printf("Syntax OK\n");
815 		} else { /*(test_config > 1)*/
816 			test_config = 0;
817 			srv->srvconf.preflight_check = 1;
818 			srv->srvconf.dont_daemonize = 1;
819 		}
820 	}
821 
822 	if (test_config || print_config) {
823 		return 0;
824 	}
825 
826 	if (oneshot_fd) {
827 		if (oneshot_fd <= STDERR_FILENO) {
828 			log_error(srv->errh, __FILE__, __LINE__,
829 			  "Invalid fds at startup with lighttpd -1");
830 			return -1;
831 		}
832 		graceful_shutdown = 1;
833 		srv->sockets_disabled = 1;
834 		srv->srvconf.dont_daemonize = 1;
835 		if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file);
836 		if (srv->srvconf.max_worker) {
837 			srv->srvconf.max_worker = 0;
838 			log_error(srv->errh, __FILE__, __LINE__,
839 			  "server one-shot command line option disables server.max-worker config file option.");
840 		}
841 	}
842 
843 	if (srv->srvconf.bindhost && buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) {
844 		if (-1 == srv->stdin_fd)
845 			srv->stdin_fd = dup(STDIN_FILENO);
846 		if (srv->stdin_fd <= STDERR_FILENO) {
847 			log_error(srv->errh, __FILE__, __LINE__,
848 			  "Invalid fds at startup");
849 			return -1;
850 		}
851 	}
852 
853 	/* close stdin and stdout, as they are not needed */
854 	{
855 		struct stat st;
856 		int devnull;
857 		int errfd;
858 		do {
859 			/* coverity[overwrite_var : FALSE] */
860 			devnull = fdevent_open_devnull();
861 		      #ifdef __COVERITY__
862 			__coverity_escape__(devnull);
863 		      #endif
864 		} while (-1 != devnull && devnull <= STDERR_FILENO);
865 		if (-1 == devnull) {
866 			log_perror(srv->errh, __FILE__, __LINE__,
867 			  "opening /dev/null failed");
868 			return -1;
869 		}
870 		errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull;
871 		if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) {
872 			log_perror(srv->errh, __FILE__, __LINE__,
873 			  "setting default fds failed");
874 		      #ifdef FD_CLOEXEC
875 			if (-1 != errfd) close(errfd);
876 			if (devnull != errfd) close(devnull);
877 		      #endif
878 			return -1;
879 		}
880 	      #ifdef FD_CLOEXEC
881 		if (-1 != errfd) close(errfd);
882 		if (devnull != errfd) close(devnull);
883 	      #endif
884 	}
885 
886 	if (0 != config_set_defaults(srv)) {
887 		log_error(srv->errh, __FILE__, __LINE__,
888 		  "setting default values failed");
889 		return -1;
890 	}
891 
892 	if (plugins_load(srv)) {
893 		log_error(srv->errh, __FILE__, __LINE__,
894 		  "loading plugins finally failed");
895 		return -1;
896 	}
897 
898 	if (HANDLER_GO_ON != plugins_call_init(srv)) {
899 		log_error(srv->errh, __FILE__, __LINE__,
900 		  "Initialization of plugins failed. Going down.");
901 		return -1;
902 	}
903 
904 	/* mod_indexfile should be listed in server.modules prior to dynamic handlers */
905 	i = 0;
906 	for (const char *pname = NULL; i < srv->plugins.used; ++i) {
907 		plugin *p = ((plugin **)srv->plugins.ptr)[i];
908 		if (NULL != pname && 0 == strcmp(p->name, "indexfile")) {
909 			log_error(srv->errh, __FILE__, __LINE__,
910 			  "Warning: mod_indexfile should be listed in server.modules prior to mod_%s", pname);
911 			break;
912 		}
913 		if (p->handle_subrequest_start && p->handle_subrequest) {
914 			if (!pname) pname = p->name;
915 		}
916 	}
917 
918 	/* open pid file BEFORE chroot */
919 	if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/
920 	if (-1 == pid_fd && !buffer_string_is_empty(srv->srvconf.pid_file)) {
921 		const char *pidfile = srv->srvconf.pid_file->ptr;
922 		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))) {
923 			struct stat st;
924 			if (errno != EEXIST) {
925 				log_perror(srv->errh, __FILE__, __LINE__,
926 				  "opening pid-file failed: %s", pidfile);
927 				return -1;
928 			}
929 
930 			if (0 != stat(pidfile, &st)) {
931 				log_perror(srv->errh, __FILE__, __LINE__,
932 				  "stating existing pid-file failed: %s", pidfile);
933 			}
934 
935 			if (!S_ISREG(st.st_mode)) {
936 				log_error(srv->errh, __FILE__, __LINE__,
937 				  "pid-file exists and isn't regular file: %s", pidfile);
938 				return -1;
939 			}
940 
941 			if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
942 				log_perror(srv->errh, __FILE__, __LINE__,
943 				  "opening pid-file failed: %s", pidfile);
944 				return -1;
945 			}
946 		}
947 	}
948 
949 	{
950 #ifdef HAVE_GETRLIMIT
951 		struct rlimit rlim;
952 		int use_rlimit = 1;
953 #ifdef HAVE_VALGRIND_VALGRIND_H
954 		if (RUNNING_ON_VALGRIND) use_rlimit = 0;
955 #endif
956 
957 		if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
958 			log_perror(srv->errh, __FILE__, __LINE__, "getrlimit()");
959 			return -1;
960 		}
961 
962 		/**
963 		 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
964 		 */
965 		if (use_rlimit && srv->srvconf.max_fds
966 		    && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) {
967 			/* set rlimits */
968 
969 			rlim.rlim_cur = srv->srvconf.max_fds;
970 			if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds;
971 
972 			if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
973 				log_perror(srv->errh, __FILE__, __LINE__, "setrlimit()");
974 				return -1;
975 			}
976 		}
977 
978 		/*(default upper limit of 4k if server.max-fds not specified)*/
979 		if (0 == srv->srvconf.max_fds)
980 			srv->srvconf.max_fds = (rlim.rlim_cur <= 4096)
981 			  ? (unsigned short)rlim.rlim_cur
982 			  : 4096;
983 
984 		/* set core file rlimit, if enable_cores is set */
985 		if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
986 			rlim.rlim_cur = rlim.rlim_max;
987 			setrlimit(RLIMIT_CORE, &rlim);
988 		}
989 #endif
990 	}
991 
992 	/* we need root-perms for port < 1024 */
993 	if (0 != network_init(srv, srv->stdin_fd)) {
994 		return -1;
995 	}
996 	srv->stdin_fd = -1;
997 
998 	if (i_am_root) {
999 #ifdef HAVE_PWD_H
1000 		/* set user and group */
1001 		struct group *grp = NULL;
1002 		struct passwd *pwd = NULL;
1003 
1004 		if (!buffer_string_is_empty(srv->srvconf.groupname)) {
1005 			if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
1006 				log_error(srv->errh, __FILE__, __LINE__,
1007 				  "can't find groupname %s", srv->srvconf.groupname->ptr);
1008 				return -1;
1009 			}
1010 		}
1011 
1012 		if (!buffer_string_is_empty(srv->srvconf.username)) {
1013 			if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
1014 				log_error(srv->errh, __FILE__, __LINE__,
1015 				  "can't find username %s", srv->srvconf.username->ptr);
1016 				return -1;
1017 			}
1018 
1019 			if (pwd->pw_uid == 0) {
1020 				log_error(srv->errh, __FILE__, __LINE__,
1021 				  "I will not set uid to 0\n");
1022 				return -1;
1023 			}
1024 
1025 			if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) {
1026 				log_error(srv->errh, __FILE__, __LINE__,
1027 				  "can't find group id %d", (int)pwd->pw_gid);
1028 				return -1;
1029 			}
1030 		}
1031 
1032 		if (NULL != grp) {
1033 			if (grp->gr_gid == 0) {
1034 				log_error(srv->errh, __FILE__, __LINE__,
1035 				  "I will not set gid to 0\n");
1036 				return -1;
1037 			}
1038 		}
1039 
1040 		/*
1041 		 * Change group before chroot, when we have access
1042 		 * to /etc/group
1043 		 * */
1044 		if (NULL != grp) {
1045 			if (-1 == setgid(grp->gr_gid)) {
1046 				log_perror(srv->errh, __FILE__, __LINE__, "setgid()");
1047 				return -1;
1048 			}
1049 			if (-1 == setgroups(0, NULL)) {
1050 				log_perror(srv->errh, __FILE__, __LINE__, "setgroups()");
1051 				return -1;
1052 			}
1053 			if (!buffer_string_is_empty(srv->srvconf.username)) {
1054 				initgroups(srv->srvconf.username->ptr, grp->gr_gid);
1055 			}
1056 		}
1057 #endif
1058 #ifdef HAVE_CHROOT
1059 		if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
1060 			tzset();
1061 
1062 			if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
1063 				log_perror(srv->errh, __FILE__, __LINE__, "chroot()");
1064 				return -1;
1065 			}
1066 			if (-1 == chdir("/")) {
1067 				log_perror(srv->errh, __FILE__, __LINE__, "chdir()");
1068 				return -1;
1069 			}
1070 		}
1071 #endif
1072 #ifdef HAVE_PWD_H
1073 		/* drop root privs */
1074 		if (NULL != pwd) {
1075 			if (-1 == setuid(pwd->pw_uid)) {
1076 				log_perror(srv->errh, __FILE__, __LINE__, "setuid()");
1077 				return -1;
1078 			}
1079 		}
1080 #endif
1081 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1082 		/**
1083 		 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1084 		 */
1085 		if (srv->srvconf.enable_cores) {
1086 			prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1087 		}
1088 #endif
1089 	}
1090 
1091 #ifdef HAVE_FORK
1092 	/* network is up, let's daemonize ourself */
1093 	if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) {
1094 		parent_pipe_fd = daemonize();
1095 	}
1096 #endif
1097 	graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/
1098 	if (0 == oneshot_fd) graceful_shutdown = 0;
1099 
1100 
1101 #ifdef HAVE_SIGACTION
1102 	memset(&act, 0, sizeof(act));
1103 	act.sa_handler = SIG_IGN;
1104 	sigaction(SIGPIPE, &act, NULL);
1105 # if defined(SA_SIGINFO)
1106 	last_sighup_info.si_uid = 0,
1107 	last_sighup_info.si_pid = 0;
1108 	last_sigterm_info.si_uid = 0,
1109 	last_sigterm_info.si_pid = 0;
1110 	act.sa_sigaction = sigaction_handler;
1111 	sigemptyset(&act.sa_mask);
1112 	act.sa_flags = SA_SIGINFO;
1113 # else
1114 	act.sa_handler = signal_handler;
1115 	sigemptyset(&act.sa_mask);
1116 	act.sa_flags = 0;
1117 # endif
1118 	sigaction(SIGINT,  &act, NULL);
1119 	sigaction(SIGTERM, &act, NULL);
1120 	sigaction(SIGHUP,  &act, NULL);
1121 	sigaction(SIGALRM, &act, NULL);
1122 	sigaction(SIGUSR1, &act, NULL);
1123 
1124 	/* it should be safe to restart syscalls after SIGCHLD */
1125 	act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
1126 	sigaction(SIGCHLD, &act, NULL);
1127 
1128 #elif defined(HAVE_SIGNAL)
1129 	/* ignore the SIGPIPE from sendfile() */
1130 	signal(SIGPIPE, SIG_IGN);
1131 	signal(SIGALRM, signal_handler);
1132 	signal(SIGTERM, signal_handler);
1133 	signal(SIGHUP,  signal_handler);
1134 	signal(SIGCHLD,  signal_handler);
1135 	signal(SIGINT,  signal_handler);
1136 	signal(SIGUSR1, signal_handler);
1137 #endif
1138 
1139 
1140 	srv->gid = getgid();
1141 	srv->uid = getuid();
1142 	srv->pid = getpid();
1143 
1144 	/* write pid file */
1145 	if (pid_fd > 2) {
1146 		buffer * const tb = srv->tmp_buf;
1147 		buffer_clear(tb);
1148 		buffer_append_int(tb, srv->pid);
1149 		buffer_append_string_len(tb, CONST_STR_LEN("\n"));
1150 		if (-1 == write_all(pid_fd, CONST_BUF_LEN(tb))) {
1151 			log_perror(srv->errh, __FILE__, __LINE__, "Couldn't write pid file");
1152 			close(pid_fd);
1153 			pid_fd = -1;
1154 			return -1;
1155 		}
1156 	} else if (pid_fd < -2) {
1157 		pid_fd = -pid_fd;
1158 	}
1159 
1160 	/* Close stderr ASAP in the child process to make sure that nothing
1161 	 * is being written to that fd which may not be valid anymore. */
1162 	if (!srv->srvconf.preflight_check) {
1163 		if (-1 == config_log_error_open(srv)) {
1164 			log_error(srv->errh, __FILE__, __LINE__, "Opening errorlog failed. Going down.");
1165 			return -1;
1166 		}
1167 		log_error(srv->errh, __FILE__, __LINE__, "server started (" PACKAGE_DESC ")");
1168 	}
1169 
1170 	if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1171 		log_error(srv->errh, __FILE__, __LINE__, "Configuration of plugins failed. Going down.");
1172 		return -1;
1173 	}
1174 
1175 	if (!config_finalize(srv, &default_server_tag)) {
1176 		return -1;
1177 	}
1178 
1179 	if (srv->srvconf.preflight_check) {
1180 		/*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1181 		return 0;
1182 	}
1183 
1184 
1185 #ifdef HAVE_FORK
1186 	/**
1187 	 * notify daemonize-grandparent of successful startup
1188 	 * do this before any further forking is done (workers)
1189 	 */
1190 	if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) {
1191 		if (0 > write(parent_pipe_fd, "", 1)) return -1;
1192 		close(parent_pipe_fd);
1193 	}
1194 
1195 	if (idle_limit && srv->srvconf.max_worker) {
1196 		srv->srvconf.max_worker = 0;
1197 		log_error(srv->errh, __FILE__, __LINE__,
1198 		  "server idle time limit command line option disables server.max-worker config file option.");
1199 	}
1200 
1201 	/* start watcher and workers */
1202 	num_childs = srv->srvconf.max_worker;
1203 	if (num_childs > 0) {
1204 		pid_t pids[num_childs];
1205 		pid_t pid;
1206 		const int npids = num_childs;
1207 		int child = 0;
1208 		unsigned int timer = 0;
1209 		for (int n = 0; n < npids; ++n) pids[n] = -1;
1210 		while (!child && !srv_shutdown && !graceful_shutdown) {
1211 			if (num_childs > 0) {
1212 				switch ((pid = fork())) {
1213 				case -1:
1214 					return -1;
1215 				case 0:
1216 					child = 1;
1217 					alarm(0);
1218 					break;
1219 				default:
1220 					num_childs--;
1221 					for (int n = 0; n < npids; ++n) {
1222 						if (-1 == pids[n]) {
1223 							pids[n] = pid;
1224 							break;
1225 						}
1226 					}
1227 					break;
1228 				}
1229 			} else {
1230 				int status;
1231 
1232 				if (-1 != (pid = wait(&status))) {
1233 					log_epoch_secs = time(NULL);
1234 					if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1235 						if (!timer) alarm((timer = 5));
1236 						continue;
1237 					}
1238 					switch (fdevent_reaped_logger_pipe(pid)) {
1239 					  default: break;
1240 					  case -1: if (!timer) alarm((timer = 5));
1241 						   /* fall through */
1242 					  case  1: continue;
1243 					}
1244 					/**
1245 					 * check if one of our workers went away
1246 					 */
1247 					for (int n = 0; n < npids; ++n) {
1248 						if (pid == pids[n]) {
1249 							pids[n] = -1;
1250 							num_childs++;
1251 							break;
1252 						}
1253 					}
1254 				} else {
1255 					switch (errno) {
1256 					case EINTR:
1257 						log_epoch_secs = time(NULL);
1258 						/**
1259 						 * if we receive a SIGHUP we have to close our logs ourself as we don't
1260 						 * have the mainloop who can help us here
1261 						 */
1262 						if (handle_sig_hup) {
1263 							handle_sig_hup = 0;
1264 
1265 							config_log_error_cycle(srv);
1266 
1267 							/* forward SIGHUP to workers */
1268 							for (int n = 0; n < npids; ++n) {
1269 								if (pids[n] > 0) kill(pids[n], SIGHUP);
1270 							}
1271 						}
1272 						if (handle_sig_alarm) {
1273 							handle_sig_alarm = 0;
1274 							timer = 0;
1275 							plugins_call_handle_trigger(srv);
1276 							fdevent_restart_logger_pipes(log_epoch_secs);
1277 						}
1278 						break;
1279 					default:
1280 						break;
1281 					}
1282 				}
1283 			}
1284 		}
1285 
1286 		/**
1287 		 * for the parent this is the exit-point
1288 		 */
1289 		if (!child) {
1290 			/**
1291 			 * kill all children too
1292 			 */
1293 			if (graceful_shutdown || graceful_restart) {
1294 				/* flag to ignore one SIGINT if graceful_restart */
1295 				if (graceful_restart) graceful_restart = 2;
1296 				kill(0, SIGINT);
1297 				server_graceful_state(srv);
1298 			} else if (srv_shutdown) {
1299 				kill(0, SIGTERM);
1300 			}
1301 
1302 			return 0;
1303 		}
1304 
1305 		/* ignore SIGUSR1 in workers; only parent directs graceful restart */
1306 	      #ifdef HAVE_SIGACTION
1307 		{
1308 			struct sigaction actignore;
1309 			memset(&actignore, 0, sizeof(actignore));
1310 			actignore.sa_handler = SIG_IGN;
1311 			sigaction(SIGUSR1, &actignore, NULL);
1312 		}
1313 	      #elif defined(HAVE_SIGNAL)
1314 			signal(SIGUSR1, SIG_IGN);
1315 	      #endif
1316 
1317 		/**
1318 		 * make sure workers do not muck with pid-file
1319 		 */
1320 		if (0 <= pid_fd) {
1321 			close(pid_fd);
1322 			pid_fd = -1;
1323 		}
1324 		if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file);
1325 
1326 		fdevent_clr_logger_pipe_pids();
1327 		srv->pid = getpid();
1328 		li_rand_reseed();
1329 	}
1330 #endif
1331 
1332 	srv->max_fds = (int)srv->srvconf.max_fds;
1333 	srv->ev = fdevent_init(srv->srvconf.event_handler, &srv->max_fds, &srv->cur_fds, srv->errh);
1334 	if (NULL == srv->ev) {
1335 		log_error(srv->errh, __FILE__, __LINE__, "fdevent_init failed");
1336 		return -1;
1337 	}
1338 
1339 	srv->max_fds_lowat = srv->max_fds * 8 / 10;
1340 	srv->max_fds_hiwat = srv->max_fds * 9 / 10;
1341 
1342 	/* set max-conns */
1343 	if (srv->srvconf.max_conns > srv->max_fds/2) {
1344 		/* we can't have more connections than max-fds/2 */
1345 		log_error(srv->errh, __FILE__, __LINE__,
1346 		  "can't have more connections than fds/2: %hu %d",
1347 		  srv->srvconf.max_conns, srv->max_fds);
1348 		srv->max_conns = srv->max_fds/2;
1349 	} else if (srv->srvconf.max_conns) {
1350 		/* otherwise respect the wishes of the user */
1351 		srv->max_conns = srv->srvconf.max_conns;
1352 	} else {
1353 		/* or use the default: we really don't want to hit max-fds */
1354 		srv->max_conns = srv->max_fds/3;
1355 	}
1356 
1357 	/* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1358 #ifdef HAVE_SIGACTION
1359 	sigaction(SIGCHLD, &act, NULL);
1360 #elif defined(HAVE_SIGNAL)
1361 	signal(SIGCHLD,  signal_handler);
1362 #endif
1363 
1364 	/*
1365 	 * kqueue() is called here, select resets its internals,
1366 	 * all server sockets get their handlers
1367 	 *
1368 	 * */
1369 	if (0 != network_register_fdevents(srv)) {
1370 		return -1;
1371 	}
1372 
1373 	/* might fail if user is using fam (not gamin) and famd isn't running */
1374 	if (!stat_cache_init(srv->ev, srv->errh)) {
1375 		log_error(srv->errh, __FILE__, __LINE__,
1376 		  "stat-cache could not be setup, dying.");
1377 		return -1;
1378 	}
1379 
1380 #ifdef USE_ALARM
1381 	{
1382 		/* setup periodic timer (1 second) */
1383 		struct itimerval interval;
1384 		interval.it_interval.tv_sec = 1;
1385 		interval.it_interval.tv_usec = 0;
1386 		interval.it_value.tv_sec = 1;
1387 		interval.it_value.tv_usec = 0;
1388 		if (setitimer(ITIMER_REAL, &interval, NULL)) {
1389 			log_perror(srv->errh, __FILE__, __LINE__, "setitimer()");
1390 			return -1;
1391 		}
1392 	}
1393 #endif
1394 
1395 	/* get the current number of FDs */
1396 	{
1397 		int fd = fdevent_open_devnull();
1398 		if (fd >= 0) {
1399 			srv->cur_fds = fd;
1400 			close(fd);
1401 		}
1402 	}
1403 
1404 	if (0 != server_sockets_set_nb_cloexec(srv)) {
1405 		return -1;
1406 	}
1407 
1408 	/* plugin hook for worker_init */
1409 	if (HANDLER_GO_ON != plugins_call_worker_init(srv))
1410 		return -1;
1411 
1412 	if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) {
1413 		oneshot_fd = -1;
1414 	}
1415 
1416 	return 1;
1417 }
1418 
1419 __attribute_cold__
1420 __attribute_noinline__
1421 static void server_handle_sighup (server * const srv) {
1422 
1423 			/* cycle logfiles */
1424 
1425 			plugins_call_handle_sighup(srv);
1426 
1427 			config_log_error_cycle(srv);
1428 #ifdef HAVE_SIGACTION
1429 				log_error(srv->errh, __FILE__, __LINE__,
1430 				  "logfiles cycled UID = %d PID = %d",
1431 				  (int)last_sighup_info.si_uid,
1432 				  (int)last_sighup_info.si_pid);
1433 #else
1434 				log_error(srv->errh, __FILE__, __LINE__,
1435 				  "logfiles cycled");
1436 #endif
1437 }
1438 
1439 __attribute_noinline__
1440 static void server_handle_sigalrm (server * const srv, time_t min_ts, time_t last_active_ts) {
1441 
1442 				plugins_call_handle_trigger(srv);
1443 
1444 				log_epoch_secs = min_ts;
1445 
1446 				/* check idle time limit, if enabled */
1447 				if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) {
1448 					log_error(srv->errh, __FILE__, __LINE__,
1449 					  "[note] idle timeout %ds exceeded, "
1450 					  "initiating graceful shutdown", (int)idle_limit);
1451 					graceful_shutdown = 2; /* value 2 indicates idle timeout */
1452 					if (graceful_restart) {
1453 						graceful_restart = 0;
1454 						if (pid_fd < -2) pid_fd = -pid_fd;
1455 						server_sockets_close(srv);
1456 					}
1457 				}
1458 
1459 			      #ifdef HAVE_GETLOADAVG
1460 				/* refresh loadavg data every 30 seconds */
1461 				if (srv->loadts + 30 < min_ts) {
1462 					if (-1 != getloadavg(srv->loadavg, 3)) {
1463 						srv->loadts = min_ts;
1464 					}
1465 				}
1466 			      #endif
1467 
1468 				if (0 == (min_ts & 0x3f)) { /*(once every 64 secs)*/
1469 					/* free excess chunkqueue buffers every 64 secs */
1470 					chunkqueue_chunk_pool_clear();
1471 					/* attempt to restart dead piped loggers every 64 secs */
1472 					if (0 == srv->srvconf.max_worker)
1473 						fdevent_restart_logger_pipes(min_ts);
1474 				}
1475 				/* cleanup stat-cache */
1476 				stat_cache_trigger_cleanup();
1477 				/* reset global/aggregate rate limit counters */
1478 				config_reset_config_bytes_sec(srv->config_data_base);
1479 				/* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1480 				if (graceful_shutdown && !srv_shutdown) connection_graceful_shutdown_maint(srv);
1481 				connection_periodic_maint(srv, min_ts);
1482 }
1483 
1484 __attribute_noinline__
1485 static void server_handle_sigchld (server * const srv) {
1486 			pid_t pid;
1487 			do {
1488 				int status;
1489 				pid = waitpid(-1, &status, WNOHANG);
1490 				if (pid > 0) {
1491 					if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1492 						continue;
1493 					}
1494 					if (0 == srv->srvconf.max_worker) {
1495 						/* check piped-loggers and restart, even if shutting down */
1496 						if (fdevent_waitpid_logger_pipe_pid(pid, log_epoch_secs)) {
1497 							continue;
1498 						}
1499 					}
1500 				}
1501 			} while (pid > 0 || (-1 == pid && errno == EINTR));
1502 }
1503 
1504 __attribute_hot__
1505 __attribute_noinline__
1506 static void server_main_loop (server * const srv) {
1507 	connections * const joblist = &srv->joblist;
1508 	time_t last_active_ts = time(NULL);
1509 
1510 	while (!srv_shutdown) {
1511 
1512 		if (handle_sig_hup) {
1513 			handle_sig_hup = 0;
1514 			server_handle_sighup(srv);
1515 		}
1516 
1517 		/*(USE_ALARM not used; fdevent_poll() is effective periodic timer)*/
1518 	      #ifdef USE_ALARM
1519 		if (handle_sig_alarm) {
1520 			handle_sig_alarm = 0;
1521 	      #endif
1522 			time_t min_ts = time(NULL);
1523 			if (min_ts != log_epoch_secs) {
1524 				server_handle_sigalrm(srv, min_ts, last_active_ts);
1525 			}
1526 	      #ifdef USE_ALARM
1527 		}
1528 	      #endif
1529 
1530 		if (handle_sig_child) {
1531 			handle_sig_child = 0;
1532 			server_handle_sigchld(srv);
1533 		}
1534 
1535 		if (graceful_shutdown) {
1536 			server_graceful_state(srv);
1537 			if (0 == srv->conns.used) {
1538 				/* we are in graceful shutdown phase and all connections are closed
1539 				 * we are ready to terminate without harming anyone */
1540 				srv_shutdown = 1;
1541 				break;
1542 			}
1543 		} else if (srv->sockets_disabled) {
1544 			server_overload_check(srv);
1545 		} else {
1546 			server_load_check(srv);
1547 		}
1548 
1549 		if (srv->fdwaitqueue.used) {
1550 			server_process_fdwaitqueue(srv);
1551 		}
1552 
1553 		if (fdevent_poll(srv->ev, 1000) > 0) {
1554 			last_active_ts = log_epoch_secs;
1555 		}
1556 
1557 		for (uint32_t ndx = 0; ndx < joblist->used; ++ndx) {
1558 			connection *con = joblist->ptr[ndx];
1559 			connection_state_machine(con);
1560 		}
1561 		joblist->used = 0;
1562 	}
1563 }
1564 
1565 __attribute_cold__
1566 int main (int argc, char **argv) {
1567     int rc;
1568 
1569   #ifdef HAVE_GETUID
1570   #ifndef HAVE_ISSETUGID
1571   #define issetugid() (geteuid() != getuid() || getegid() != getgid())
1572   #endif
1573     if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
1574         fprintf(stderr,
1575                 "Are you nuts ? Don't apply a SUID bit to this binary\n");
1576         return -1;
1577     }
1578   #endif
1579 
1580     /* for nice %b handling in strftime() */
1581     setlocale(LC_TIME, "C");
1582 
1583     do {
1584         server * const srv = server_init();
1585 
1586         if (graceful_restart) {
1587             server_sockets_restore(srv);
1588             optind = 1;
1589         }
1590 
1591         rc = server_main_setup(srv, argc, argv);
1592         if (rc > 0) {
1593 
1594             server_main_loop(srv);
1595 
1596             if (graceful_shutdown || graceful_restart) {
1597                 server_graceful_state(srv);
1598             }
1599 
1600             if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */
1601                 log_error(srv->errh, __FILE__, __LINE__,
1602                   "server stopped after idle timeout");
1603             } else {
1604               #ifdef HAVE_SIGACTION
1605                 log_error(srv->errh, __FILE__, __LINE__,
1606                   "server stopped by UID = %d PID = %d",
1607                   (int)last_sigterm_info.si_uid,
1608                   (int)last_sigterm_info.si_pid);
1609               #else
1610                 log_error(srv->errh, __FILE__, __LINE__,
1611                   "server stopped");
1612               #endif
1613             }
1614         }
1615 
1616         /* clean-up */
1617         remove_pid_file(srv);
1618         config_log_error_close(srv);
1619         if (graceful_restart)
1620             server_sockets_save(srv);
1621         else
1622             network_close(srv);
1623         connections_free(srv);
1624         plugins_free(srv);
1625         server_free(srv);
1626 
1627         if (rc < 0 || !graceful_restart) break;
1628 
1629         /* wait for all children to exit before graceful restart */
1630         while (waitpid(-1, NULL, 0) > 0) ;
1631     } while (graceful_restart);
1632 
1633     return rc;
1634 }
1635