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