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