xref: /lighttpd1.4/src/server.c (revision 49e9f0ac)
1 #include "first.h"
2 
3 #include "base.h"
4 #include "buffer.h"
5 #include "burl.h"
6 #include "network.h"
7 #include "log.h"
8 #include "rand.h"
9 #include "chunk.h"
10 #include "http_auth.h"
11 #include "http_vhostdb.h"
12 #include "fdevent.h"
13 #include "connections.h"
14 #include "sock_addr.h"
15 #include "stat_cache.h"
16 #include "configfile.h"
17 #include "plugin.h"
18 #include "joblist.h"
19 #include "network_write.h"
20 
21 #ifdef HAVE_VERSIONSTAMP_H
22 # include "versionstamp.h"
23 #else
24 # define REPO_VERSION ""
25 #endif
26 
27 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
28 
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_SYSLOG_H
63 # include <syslog.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 #ifdef USE_OPENSSL_CRYPTO
76 #define USE_SSL
77 #define TEXT_SSL " (ssl)"
78 #else
79 #define TEXT_SSL
80 #endif
81 
82 #ifndef __sgi
83 /* IRIX doesn't like the alarm based time() optimization */
84 /* #define USE_ALARM */
85 #endif
86 
87 static int oneshot_fd = 0;
88 static volatile int pid_fd = -2;
89 static server_socket_array graceful_sockets;
90 static server_socket_array inherited_sockets;
91 static volatile sig_atomic_t graceful_restart = 0;
92 static volatile sig_atomic_t graceful_shutdown = 0;
93 static volatile sig_atomic_t srv_shutdown = 0;
94 static volatile sig_atomic_t handle_sig_child = 0;
95 static volatile sig_atomic_t handle_sig_alarm = 1;
96 static volatile sig_atomic_t handle_sig_hup = 0;
97 static time_t idle_limit = 0;
98 
99 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
100 static volatile siginfo_t last_sigterm_info;
101 static volatile siginfo_t last_sighup_info;
102 
103 static void sigaction_handler(int sig, siginfo_t *si, void *context) {
104 	static const siginfo_t empty_siginfo;
105 	UNUSED(context);
106 
107 	if (!si) *(const siginfo_t **)&si = &empty_siginfo;
108 
109 	switch (sig) {
110 	case SIGTERM:
111 		srv_shutdown = 1;
112 		last_sigterm_info = *si;
113 		break;
114 	case SIGUSR1:
115 		if (!graceful_shutdown) {
116 			graceful_restart = 1;
117 			graceful_shutdown = 1;
118 			last_sigterm_info = *si;
119 		}
120 		break;
121 	case SIGINT:
122 		if (graceful_shutdown) {
123 			if (2 == graceful_restart)
124 				graceful_restart = 1;
125 			else
126 				srv_shutdown = 1;
127 		} else {
128 			graceful_shutdown = 1;
129 		}
130 		last_sigterm_info = *si;
131 
132 		break;
133 	case SIGALRM:
134 		handle_sig_alarm = 1;
135 		break;
136 	case SIGHUP:
137 		handle_sig_hup = 1;
138 		last_sighup_info = *si;
139 		break;
140 	case SIGCHLD:
141 		handle_sig_child = 1;
142 		break;
143 	}
144 }
145 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
146 static void signal_handler(int sig) {
147 	switch (sig) {
148 	case SIGTERM: srv_shutdown = 1; break;
149 	case SIGUSR1:
150 		if (!graceful_shutdown) {
151 			graceful_restart = 1;
152 			graceful_shutdown = 1;
153 		}
154 		break;
155 	case SIGINT:
156 		if (graceful_shutdown) {
157 			if (2 == graceful_restart)
158 				graceful_restart = 1;
159 			else
160 				srv_shutdown = 1;
161 		} else {
162 			graceful_shutdown = 1;
163 		}
164 		break;
165 	case SIGALRM: handle_sig_alarm = 1; break;
166 	case SIGHUP:  handle_sig_hup = 1; break;
167 	case SIGCHLD: handle_sig_child = 1; break;
168 	}
169 }
170 #endif
171 
172 #ifdef HAVE_FORK
173 static int daemonize(void) {
174 	int pipefd[2];
175 	pid_t pid;
176 #ifdef SIGTTOU
177 	signal(SIGTTOU, SIG_IGN);
178 #endif
179 #ifdef SIGTTIN
180 	signal(SIGTTIN, SIG_IGN);
181 #endif
182 #ifdef SIGTSTP
183 	signal(SIGTSTP, SIG_IGN);
184 #endif
185 
186 	if (pipe(pipefd) < 0) exit(-1);
187 
188 	if (0 > (pid = fork())) exit(-1);
189 
190 	if (0 < pid) {
191 		char buf;
192 		ssize_t bytes;
193 
194 		close(pipefd[1]);
195 		/* parent waits for grandchild to be ready */
196 		do {
197 			bytes = read(pipefd[0], &buf, sizeof(buf));
198 		} while (bytes < 0 && EINTR == errno);
199 		close(pipefd[0]);
200 
201 		if (bytes <= 0) {
202 			/* closed fd (without writing) == failure in grandchild */
203 			fputs("daemonized server failed to start; check error log for details\n", stderr);
204 			exit(-1);
205 		}
206 
207 		exit(0);
208 	}
209 
210 	close(pipefd[0]);
211 
212 	if (-1 == setsid()) exit(0);
213 
214 	signal(SIGHUP, SIG_IGN);
215 
216 	if (0 != fork()) exit(0);
217 
218 	if (0 != chdir("/")) exit(0);
219 
220 	fdevent_setfd_cloexec(pipefd[1]);
221 	return pipefd[1];
222 }
223 #endif
224 
225 __attribute_cold__
226 static server *server_init(void) {
227 	int i;
228 	server *srv = calloc(1, sizeof(*srv));
229 	force_assert(srv);
230 #define CLEAN(x) \
231 	srv->x = buffer_init();
232 
233 	CLEAN(response_header);
234 	CLEAN(parse_full_path);
235 	CLEAN(ts_date_str);
236 	CLEAN(response_range);
237 	CLEAN(tmp_buf);
238 	srv->empty_string = buffer_init_string("");
239 	CLEAN(cond_check_buf);
240 
241 	CLEAN(srvconf.errorlog_file);
242 	CLEAN(srvconf.breakagelog_file);
243 	CLEAN(srvconf.groupname);
244 	CLEAN(srvconf.username);
245 	CLEAN(srvconf.changeroot);
246 	CLEAN(srvconf.bindhost);
247 	CLEAN(srvconf.event_handler);
248 	CLEAN(srvconf.pid_file);
249 	CLEAN(srvconf.syslog_facility);
250 
251 	CLEAN(tmp_chunk_len);
252 #undef CLEAN
253 
254 #define CLEAN(x) \
255 	srv->x = array_init();
256 
257 	CLEAN(config_context);
258 	CLEAN(config_touched);
259 	CLEAN(status);
260 #undef CLEAN
261 
262 	for (i = 0; i < FILE_CACHE_MAX; i++) {
263 		srv->mtime_cache[i].mtime = (time_t)-1;
264 		srv->mtime_cache[i].str = buffer_init();
265 	}
266 
267 	li_rand_reseed();
268 
269 	srv->cur_ts = time(NULL);
270 	srv->startup_ts = srv->cur_ts;
271 
272 	srv->conns = calloc(1, sizeof(*srv->conns));
273 	force_assert(srv->conns);
274 
275 	srv->joblist = calloc(1, sizeof(*srv->joblist));
276 	force_assert(srv->joblist);
277 
278 	srv->fdwaitqueue = calloc(1, sizeof(*srv->fdwaitqueue));
279 	force_assert(srv->fdwaitqueue);
280 
281 	srv->errh = log_error_st_init(&srv->cur_ts, &srv->last_generated_debug_ts);
282 
283 	srv->srvconf.modules = array_init();
284 	srv->srvconf.modules_dir = buffer_init_string(LIBRARY_DIR);
285 	srv->srvconf.network_backend = buffer_init();
286 	srv->srvconf.upload_tempdirs = array_init();
287 	srv->srvconf.reject_expect_100_with_417 = 1;
288 	srv->srvconf.xattr_name = buffer_init_string("Content-Type");
289 	srv->srvconf.http_header_strict  = 1;
290 	srv->srvconf.http_host_strict    = 1; /*(implies http_host_normalize)*/
291 	srv->srvconf.http_host_normalize = 0;
292       #if 0
293 	srv->srvconf.http_url_normalize = HTTP_PARSEOPT_URL_NORMALIZE
294 					| HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED
295 					| HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT
296 					| HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS
297 					| HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE
298 					| HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
299       #endif
300 	srv->srvconf.http_url_normalize = 0; /* temporary; change in future */
301 	srv->srvconf.high_precision_timestamps = 0;
302 	srv->srvconf.max_request_field_size = 8192;
303 	srv->srvconf.loadavg[0] = 0.0;
304 	srv->srvconf.loadavg[1] = 0.0;
305 	srv->srvconf.loadavg[2] = 0.0;
306 	srv->srvconf.compat_module_load = 1;
307 	srv->srvconf.systemd_socket_activation = 0;
308 
309 	srv->split_vals = array_init();
310 	srv->request_env = plugins_call_handle_request_env;
311 
312 	return srv;
313 }
314 
315 __attribute_cold__
316 static void server_free(server *srv) {
317 	size_t i;
318 
319 	for (i = 0; i < FILE_CACHE_MAX; i++) {
320 		buffer_free(srv->mtime_cache[i].str);
321 	}
322 
323 	if (oneshot_fd > 0) {
324 		close(oneshot_fd);
325 	}
326 
327 #define CLEAN(x) \
328 	buffer_free(srv->x);
329 
330 	CLEAN(response_header);
331 	CLEAN(parse_full_path);
332 	CLEAN(ts_date_str);
333 	CLEAN(response_range);
334 	CLEAN(tmp_buf);
335 	CLEAN(empty_string);
336 	CLEAN(cond_check_buf);
337 
338 	CLEAN(srvconf.errorlog_file);
339 	CLEAN(srvconf.breakagelog_file);
340 	CLEAN(srvconf.groupname);
341 	CLEAN(srvconf.username);
342 	CLEAN(srvconf.changeroot);
343 	CLEAN(srvconf.bindhost);
344 	CLEAN(srvconf.event_handler);
345 	CLEAN(srvconf.pid_file);
346 	CLEAN(srvconf.modules_dir);
347 	CLEAN(srvconf.network_backend);
348 	CLEAN(srvconf.xattr_name);
349 	CLEAN(srvconf.syslog_facility);
350 
351 	CLEAN(tmp_chunk_len);
352 #undef CLEAN
353 
354 	fdevent_free(srv->ev);
355 
356 	free(srv->conns);
357 
358 	if (srv->config_storage) {
359 		for (i = 0; i < srv->config_context->used; i++) {
360 			specific_config *s = srv->config_storage[i];
361 
362 			if (!s) continue;
363 
364 			buffer_free(s->document_root);
365 			buffer_free(s->server_name);
366 			buffer_free(s->server_tag);
367 			buffer_free(s->error_handler);
368 			buffer_free(s->error_handler_404);
369 			buffer_free(s->errorfile_prefix);
370 			buffer_free(s->socket_perms);
371 			array_free(s->mimetypes);
372 			free(s);
373 		}
374 		free(srv->config_storage);
375 		srv->config_storage = NULL;
376 	}
377 
378 #define CLEAN(x) \
379 	array_free(srv->x);
380 
381 	CLEAN(config_context);
382 	CLEAN(config_touched);
383 	CLEAN(status);
384 	CLEAN(srvconf.upload_tempdirs);
385 #undef CLEAN
386 
387 	joblist_free(srv, srv->joblist);
388 	fdwaitqueue_free(srv, srv->fdwaitqueue);
389 
390 	if (srv->stat_cache) {
391 		stat_cache_free(srv->stat_cache);
392 	}
393 
394 	array_free(srv->srvconf.modules);
395 	array_free(srv->split_vals);
396 
397 	li_rand_cleanup();
398 	chunkqueue_chunk_pool_free();
399 
400 	log_error_st_free(srv->errh);
401 	free(srv);
402 }
403 
404 __attribute_cold__
405 static void remove_pid_file(server *srv) {
406 	if (pid_fd <= -2) return;
407 	if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= pid_fd) {
408 		if (0 != ftruncate(pid_fd, 0)) {
409 			log_error_write(srv, __FILE__, __LINE__, "sbds",
410 					"ftruncate failed for:",
411 					srv->srvconf.pid_file,
412 					errno,
413 					strerror(errno));
414 		}
415 	}
416 	if (0 <= pid_fd) {
417 		close(pid_fd);
418 		pid_fd = -1;
419 	}
420 	if (!buffer_string_is_empty(srv->srvconf.pid_file) &&
421 	    buffer_string_is_empty(srv->srvconf.changeroot)) {
422 		if (0 != unlink(srv->srvconf.pid_file->ptr)) {
423 			if (errno != EACCES && errno != EPERM) {
424 				log_error_write(srv, __FILE__, __LINE__, "sbds",
425 						"unlink failed for:",
426 						srv->srvconf.pid_file,
427 						errno,
428 						strerror(errno));
429 			}
430 		}
431 	}
432 }
433 
434 
435 __attribute_cold__
436 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) {
437 	server_socket *srv_socket, *srv_socket_wild = NULL;
438 	size_t i;
439 	for (i = 0; i < srv->srv_sockets.used; ++i) {
440 		srv_socket = srv->srv_sockets.ptr[i];
441 		if (!sock_addr_is_port_eq(&srv_socket->addr,cnt_addr)) continue;
442 		if (sock_addr_is_addr_eq(&srv_socket->addr,cnt_addr)) return srv_socket;
443 
444 		if (NULL != srv_socket_wild) continue;
445 		if (sock_addr_is_addr_wildcard(&srv_socket->addr)) {
446 			srv_socket_wild = srv_socket;
447 		}
448 	}
449 
450 	if (NULL != srv_socket_wild) {
451 		return srv_socket_wild;
452 	} else if (srv->srv_sockets.used) {
453 		return srv->srv_sockets.ptr[0];
454 	} else {
455 		log_error_write(srv, __FILE__, __LINE__, "s", "no sockets configured");
456 		return NULL;
457 	}
458 }
459 
460 
461 __attribute_cold__
462 static int server_oneshot_init(server *srv, int fd) {
463 	/* Note: does not work with netcat due to requirement that fd be socket.
464 	 * STDOUT_FILENO was not saved earlier in startup, and that is to where
465 	 * netcat expects output to be sent.  Since lighttpd expects connections
466 	 * to be sockets, con->fd is where output is sent; separate fds are not
467 	 * stored for input and output, but netcat has different fds for stdin
468 	 * and * stdout.  To support netcat, would additionally need to avoid
469 	 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing
470 	 * addresses from environment variables:
471 	 *   NCAT_LOCAL_ADDR   NCAT_LOCAL_PORT
472 	 *   NCAT_REMOTE_ADDR  NCAT_REMOTE_PORT
473 	 *   NCAT_PROTO
474 	 */
475 	connection *con;
476 	server_socket *srv_socket;
477 	sock_addr cnt_addr;
478 	socklen_t cnt_len;
479 	struct stat st;
480 
481 	if (0 != fstat(fd, &st)) {
482 		log_error_write(srv, __FILE__, __LINE__, "ss", "fstat:", strerror(errno));
483 		return 0;
484 	}
485 
486 	if (!S_ISSOCK(st.st_mode)) {
487 		/* require that fd is a socket
488 		 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
489 		log_error_write(srv, __FILE__, __LINE__, "s", "lighttpd -1 stdin is not a socket");
490 		return 0;
491 	}
492 
493 	cnt_len = sizeof(cnt_addr);
494 	if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
495 		log_error_write(srv, __FILE__, __LINE__, "ss", "getsockname:", strerror(errno));
496 		return 0;
497 	}
498 
499 	srv_socket = server_oneshot_getsock(srv, &cnt_addr);
500 	if (NULL == srv_socket) return 0;
501 
502 	cnt_len = sizeof(cnt_addr);
503 	if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
504 		log_error_write(srv, __FILE__, __LINE__, "ss", "getpeername:", strerror(errno));
505 		return 0;
506 	}
507 
508 	/*(must set flags; fd did not pass through fdevent accept() logic)*/
509 	if (-1 == fdevent_fcntl_set_nb_cloexec(srv->ev, fd)) {
510 		log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl:", strerror(errno));
511 		return 0;
512 	}
513 
514 	if (sock_addr_get_family(&cnt_addr) != AF_UNIX) {
515 		network_accept_tcp_nagle_disable(fd);
516 	}
517 
518 	con = connection_accepted(srv, srv_socket, &cnt_addr, fd);
519 	if (NULL == con) return 0;
520 
521 	connection_state_machine(srv, con);
522 	return 1;
523 }
524 
525 
526 __attribute_cold__
527 static void show_version (void) {
528 	char *b = PACKAGE_DESC TEXT_SSL \
529 " - a light and fast webserver\n"
530 #ifdef NONREPRODUCIBLE_BUILD
531 "Build-Date: " __DATE__ " " __TIME__ "\n";
532 #endif
533 ;
534 	write_all(STDOUT_FILENO, b, strlen(b));
535 }
536 
537 __attribute_cold__
538 static void show_features (void) {
539   static const char features[] =
540       "\nFeatures:\n\n"
541 #ifdef HAVE_IPV6
542       "\t+ IPv6 support\n"
543 #else
544       "\t- IPv6 support\n"
545 #endif
546 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
547       "\t+ zlib support\n"
548 #else
549       "\t- zlib support\n"
550 #endif
551 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
552       "\t+ bzip2 support\n"
553 #else
554       "\t- bzip2 support\n"
555 #endif
556 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
557       "\t+ crypt support\n"
558 #else
559       "\t- crypt support\n"
560 #endif
561 #ifdef USE_SSL
562       "\t+ SSL support\n"
563 #else
564       "\t- SSL support\n"
565 #endif
566 #ifdef HAVE_LIBPCRE
567       "\t+ PCRE support\n"
568 #else
569       "\t- PCRE support\n"
570 #endif
571 #ifdef HAVE_MYSQL
572       "\t+ MySQL support\n"
573 #else
574       "\t- MySQL support\n"
575 #endif
576 #ifdef HAVE_PGSQL
577       "\t+ PgSQL support\n"
578 #else
579       "\t- PgSQL support\n"
580 #endif
581 #ifdef HAVE_DBI
582       "\t+ DBI support\n"
583 #else
584       "\t- DBI support\n"
585 #endif
586 #ifdef HAVE_KRB5
587       "\t+ Kerberos support\n"
588 #else
589       "\t- Kerberos support\n"
590 #endif
591 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
592       "\t+ LDAP support\n"
593 #else
594       "\t- LDAP support\n"
595 #endif
596 #ifdef HAVE_PAM
597       "\t+ PAM support\n"
598 #else
599       "\t- PAM support\n"
600 #endif
601 #ifdef USE_MEMCACHED
602       "\t+ memcached support\n"
603 #else
604       "\t- memcached support\n"
605 #endif
606 #ifdef HAVE_FAM_H
607       "\t+ FAM support\n"
608 #else
609       "\t- FAM support\n"
610 #endif
611 #ifdef HAVE_LUA_H
612       "\t+ LUA support\n"
613 #else
614       "\t- LUA support\n"
615 #endif
616 #ifdef HAVE_LIBXML_H
617       "\t+ xml support\n"
618 #else
619       "\t- xml support\n"
620 #endif
621 #ifdef HAVE_SQLITE3_H
622       "\t+ SQLite support\n"
623 #else
624       "\t- SQLite support\n"
625 #endif
626 #ifdef HAVE_GDBM_H
627       "\t+ GDBM support\n"
628 #else
629       "\t- GDBM support\n"
630 #endif
631       ;
632   show_version();
633   printf("%s%s%s\n", fdevent_show_event_handlers(), network_write_show_handlers(), features);
634 }
635 
636 __attribute_cold__
637 static void show_help (void) {
638 	char *b = PACKAGE_DESC TEXT_SSL
639 #ifdef NONREPRODUCIBLE_BUILD
640 " ("__DATE__ " " __TIME__ ")"
641 #endif
642 " - a light and fast webserver\n" \
643 "usage:\n" \
644 " -f <name>  filename of the config-file\n" \
645 " -m <name>  module directory (default: "LIBRARY_DIR")\n" \
646 " -i <secs>  graceful shutdown after <secs> of inactivity\n" \
647 " -1         process single (one) request on stdin socket, then exit\n" \
648 " -p         print the parsed config-file in internal form, and exit\n" \
649 " -t         test config-file syntax, then exit\n" \
650 " -tt        test config-file syntax, load and init modules, then exit\n" \
651 " -D         don't go to background (default: go to background)\n" \
652 " -v         show version\n" \
653 " -V         show compile-time features\n" \
654 " -h         show this help\n" \
655 "\n"
656 ;
657 	write_all(STDOUT_FILENO, b, strlen(b));
658 }
659 
660 /**
661  * open the errorlog
662  *
663  * we have 4 possibilities:
664  * - stderr (default)
665  * - syslog
666  * - logfile
667  * - pipe
668  *
669  */
670 
671 static int log_error_open(server *srv) {
672     log_error_st *errh = srv->errh;
673     int errfd;
674   #ifdef HAVE_SYSLOG_H
675     /* perhaps someone wants to use syslog() */
676     int facility = -1;
677     if (!buffer_string_is_empty(srv->srvconf.syslog_facility)) {
678         static const struct facility_name_st {
679           const char *name;
680           int val;
681         } facility_names[] = {
682             { "auth",     LOG_AUTH }
683           #ifdef LOG_AUTHPRIV
684            ,{ "authpriv", LOG_AUTHPRIV }
685           #endif
686           #ifdef LOG_CRON
687            ,{ "cron",     LOG_CRON }
688           #endif
689            ,{ "daemon",   LOG_DAEMON }
690           #ifdef LOG_FTP
691            ,{ "ftp",      LOG_FTP }
692           #endif
693           #ifdef LOG_KERN
694            ,{ "kern",     LOG_KERN }
695           #endif
696           #ifdef LOG_LPR
697            ,{ "lpr",      LOG_LPR }
698           #endif
699           #ifdef LOG_MAIL
700            ,{ "mail",     LOG_MAIL }
701           #endif
702           #ifdef LOG_NEWS
703            ,{ "news",     LOG_NEWS }
704           #endif
705            ,{ "security", LOG_AUTH }           /* DEPRECATED */
706           #ifdef LOG_SYSLOG
707            ,{ "syslog",   LOG_SYSLOG }
708           #endif
709           #ifdef LOG_USER
710            ,{ "user",     LOG_USER }
711           #endif
712           #ifdef LOG_UUCP
713            ,{ "uucp",     LOG_UUCP }
714           #endif
715            ,{ "local0",   LOG_LOCAL0 }
716            ,{ "local1",   LOG_LOCAL1 }
717            ,{ "local2",   LOG_LOCAL2 }
718            ,{ "local3",   LOG_LOCAL3 }
719            ,{ "local4",   LOG_LOCAL4 }
720            ,{ "local5",   LOG_LOCAL5 }
721            ,{ "local6",   LOG_LOCAL6 }
722            ,{ "local7",   LOG_LOCAL7 }
723         };
724         unsigned int i;
725         for (i = 0; i < sizeof(facility_names)/sizeof(facility_names[0]); ++i) {
726             const struct facility_name_st *f = facility_names+i;
727             if (0 == strcmp(srv->srvconf.syslog_facility->ptr, f->name)) {
728                 facility = f->val;
729                 break;
730             }
731         }
732         if (-1 == facility) {
733             log_error_write(srv, __FILE__, __LINE__, "SBS",
734                             "unrecognized server.syslog-facility: \"",
735                             srv->srvconf.syslog_facility,
736                             "\"; defaulting to \"daemon\" facility");
737         }
738     }
739     openlog("lighttpd", LOG_CONS|LOG_PID, -1==facility ? LOG_DAEMON : facility);
740   #endif
741 
742     errh->errorlog_mode = ERRORLOG_FD;
743     errh->errorlog_fd = STDERR_FILENO;
744 
745     if (srv->srvconf.errorlog_use_syslog) {
746         errh->errorlog_mode = ERRORLOG_SYSLOG;
747     }
748     else if (!buffer_string_is_empty(srv->srvconf.errorlog_file)) {
749         const char *logfile = srv->srvconf.errorlog_file->ptr;
750         int fd = fdevent_open_logger(logfile);
751         if (-1 == fd) {
752             log_error_write(srv, __FILE__, __LINE__, "SSSS",
753                             "opening errorlog '", logfile,
754                             "' failed: ", strerror(errno));
755             return -1;
756         }
757         errh->errorlog_fd = fd;
758         errh->errorlog_mode = logfile[0] == '|' ? ERRORLOG_PIPE : ERRORLOG_FILE;
759     }
760 
761     if (errh->errorlog_mode == ERRORLOG_FD && !srv->srvconf.dont_daemonize) {
762         /* We can only log to stderr in dont-daemonize mode;
763          * if we do daemonize and no errorlog file is specified,
764          * we log into /dev/null
765          */
766         errh->errorlog_fd = -1;
767     }
768 
769     if (!buffer_string_is_empty(srv->srvconf.breakagelog_file)) {
770         const char *logfile = srv->srvconf.breakagelog_file->ptr;
771 
772         if (errh->errorlog_mode == ERRORLOG_FD) {
773             errh->errorlog_fd = dup(STDERR_FILENO);
774             fdevent_setfd_cloexec(errh->errorlog_fd);
775         }
776 
777         if (-1 == (errfd = fdevent_open_logger(logfile))) {
778             log_error_write(srv, __FILE__, __LINE__, "SSSS",
779                             "opening errorlog '", logfile,
780                             "' failed: ", strerror(errno));
781             return -1;
782         }
783 
784         if (*logfile == '|') fdevent_breakagelog_logger_pipe(errfd);
785     }
786     else if (!srv->srvconf.dont_daemonize) {
787         /* move STDERR_FILENO to /dev/null */
788         if (-1 == (errfd = fdevent_open_devnull())) {
789             log_error_write(srv, __FILE__, __LINE__, "ss",
790                             "opening /dev/null failed:", strerror(errno));
791             return -1;
792         }
793     }
794     else {
795         /*(leave STDERR_FILENO as-is)*/
796         errfd = -1;
797     }
798 
799     if (0 != fdevent_set_stdin_stdout_stderr(-1, -1, errfd)) {
800         log_error_write(srv, __FILE__, __LINE__, "ss",
801                         "setting stderr failed:", strerror(errno));
802       #ifdef FD_CLOEXEC
803         if (-1 != errfd) close(errfd);
804       #endif
805         return -1;
806     }
807   #ifdef FD_CLOEXEC
808     if (-1 != errfd) close(errfd);
809   #endif
810 
811     return 0;
812 }
813 
814 /**
815  * cycle the errorlog
816  *
817  */
818 
819 static int log_error_cycle(server *srv) {
820     /* cycle only if the error log is a file */
821 
822     log_error_st *errh = srv->errh;
823     if (errh->errorlog_mode == ERRORLOG_FILE) {
824         const char *logfile = srv->srvconf.errorlog_file->ptr;
825         if (-1 == fdevent_cycle_logger(logfile, &errh->errorlog_fd)) {
826             /* write to old log */
827             log_error_write(srv, __FILE__, __LINE__, "SSSS",
828                             "cycling errorlog '", logfile,
829                             "' failed: ", strerror(errno));
830         }
831     }
832 
833     return 0;
834 }
835 
836 __attribute_cold__
837 static int log_error_close(server *srv) {
838     log_error_st *errh = srv->errh;
839     switch(errh->errorlog_mode) {
840     case ERRORLOG_PIPE:
841     case ERRORLOG_FILE:
842     case ERRORLOG_FD:
843         if (-1 != errh->errorlog_fd) {
844             /* don't close STDERR */
845             /* fdevent_close_logger_pipes() closes ERRORLOG_PIPE */
846             if (STDERR_FILENO != errh->errorlog_fd
847                 && ERRORLOG_PIPE != errh->errorlog_mode) {
848                 close(errh->errorlog_fd);
849             }
850             errh->errorlog_fd = -1;
851         }
852         break;
853     case ERRORLOG_SYSLOG:
854       #ifdef HAVE_SYSLOG_H
855         closelog();
856       #endif
857         break;
858     }
859 
860     return 0;
861 }
862 
863 __attribute_cold__
864 static void server_sockets_save (server *srv) {    /* graceful_restart */
865     memcpy(&graceful_sockets, &srv->srv_sockets, sizeof(server_socket_array));
866     memset(&srv->srv_sockets, 0, sizeof(server_socket_array));
867     memcpy(&inherited_sockets, &srv->srv_sockets_inherited, sizeof(server_socket_array));
868     memset(&srv->srv_sockets_inherited, 0, sizeof(server_socket_array));
869 }
870 
871 __attribute_cold__
872 static void server_sockets_restore (server *srv) { /* graceful_restart */
873     memcpy(&srv->srv_sockets, &graceful_sockets, sizeof(server_socket_array));
874     memset(&graceful_sockets, 0, sizeof(server_socket_array));
875     memcpy(&srv->srv_sockets_inherited, &inherited_sockets, sizeof(server_socket_array));
876     memset(&inherited_sockets, 0, sizeof(server_socket_array));
877 }
878 
879 __attribute_cold__
880 static int server_sockets_set_nb_cloexec (server *srv) {
881     if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */
882     for (size_t i = 0; i < srv->srv_sockets.used; ++i) {
883         server_socket *srv_socket = srv->srv_sockets.ptr[i];
884         if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv->ev, srv_socket->fd)) {
885             log_error_write(srv, __FILE__, __LINE__, "ss",
886                             "fcntl failed:", strerror(errno));
887             return -1;
888         }
889     }
890     return 0;
891 }
892 
893 __attribute_cold__
894 static void server_sockets_set_event (server *srv, int event) {
895     for (size_t i = 0; i < srv->srv_sockets.used; ++i) {
896         server_socket *srv_socket = srv->srv_sockets.ptr[i];
897         fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event);
898     }
899 }
900 
901 __attribute_cold__
902 static void server_sockets_unregister (server *srv) {
903     if (2 == srv->sockets_disabled) return;
904     srv->sockets_disabled = 2;
905     for (size_t i = 0; i < srv->srv_sockets.used; ++i)
906         network_unregister_sock(srv, srv->srv_sockets.ptr[i]);
907 }
908 
909 __attribute_cold__
910 static void server_sockets_close (server *srv) {
911     /* closing socket right away will make it possible for the next lighttpd
912      * to take over (old-style graceful restart), but only if backends
913      * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
914      * than started by lighttpd via "bin-path")
915      */
916     if (3 == srv->sockets_disabled) return;
917     for (size_t i = 0; i < srv->srv_sockets.used; ++i) {
918         server_socket *srv_socket = srv->srv_sockets.ptr[i];
919         if (-1 == srv_socket->fd) continue;
920         if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket);
921         close(srv_socket->fd);
922         srv_socket->fd = -1;
923         /* network_close() will cleanup after us */
924     }
925     srv->sockets_disabled = 3;
926 }
927 
928 __attribute_cold__
929 static void server_graceful_shutdown_maint (server *srv) {
930     connections *conns = srv->conns;
931     for (size_t ndx = 0; ndx < conns->used; ++ndx) {
932         connection * const con = conns->ptr[ndx];
933         int changed = 0;
934 
935         if (con->state == CON_STATE_CLOSE) {
936             /* reduce remaining linger timeout to be
937              * (from zero) *up to* one more second, but no more */
938             if (HTTP_LINGER_TIMEOUT > 1)
939                 con->close_timeout_ts -= (HTTP_LINGER_TIMEOUT - 1);
940             if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT)
941                 changed = 1;
942         }
943         else if (con->state == CON_STATE_READ && con->request_count > 1
944                  && chunkqueue_is_empty(con->read_queue)) {
945             /* close connections in keep-alive waiting for next request */
946             connection_set_state(srv, con, CON_STATE_ERROR);
947             changed = 1;
948         }
949 
950         con->keep_alive = 0;                    /* disable keep-alive */
951 
952         con->conf.kbytes_per_second = 0;        /* disable rate limit */
953         con->conf.global_kbytes_per_second = 0; /* disable rate limit */
954         if (con->traffic_limit_reached) {
955             con->traffic_limit_reached = 0;
956             changed = 1;
957         }
958 
959         if (changed) {
960             connection_state_machine(srv, con);
961         }
962     }
963 }
964 
965 __attribute_cold__
966 static void server_graceful_state (server *srv) {
967 
968     if (!srv_shutdown) server_graceful_shutdown_maint(srv);
969 
970     if (!oneshot_fd
971         && (2 == srv->sockets_disabled || 3 == srv->sockets_disabled)) return;
972 
973     log_error_write(srv, __FILE__, __LINE__, "s",
974                     "[note] graceful shutdown started");
975 
976     /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
977     if (!buffer_string_is_empty(srv->srvconf.changeroot)
978         || oneshot_fd || 2 == graceful_shutdown)
979         graceful_restart = 0;
980 
981     if (graceful_restart) {
982         server_sockets_unregister(srv);
983         if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/
984     }
985     else {
986         server_sockets_close(srv);
987         remove_pid_file(srv);
988         buffer_clear(srv->srvconf.pid_file); /*(prevent more removal attempts)*/
989     }
990 }
991 
992 __attribute_cold__
993 static void server_sockets_enable (server *srv) {
994     server_sockets_set_event(srv, FDEVENT_IN);
995     srv->sockets_disabled = 0;
996     log_error_write(srv, __FILE__, __LINE__, "s",
997                     "[note] sockets enabled again");
998 }
999 
1000 __attribute_cold__
1001 static void server_sockets_disable (server *srv) {
1002     server_sockets_set_event(srv, 0);
1003     srv->sockets_disabled = 1;
1004     log_error_write(srv, __FILE__, __LINE__, "s",
1005                     (srv->conns->used >= srv->max_conns)
1006                     ? "[note] sockets disabled, connection limit reached"
1007                     : "[note] sockets disabled, out-of-fds");
1008 }
1009 
1010 __attribute_cold__
1011 static void server_overload_check (server *srv) {
1012     if (srv->cur_fds + srv->want_fds < srv->max_fds_lowat
1013         && srv->conns->used <= srv->max_conns * 9 / 10) {
1014 
1015         server_sockets_enable(srv);
1016     }
1017 }
1018 
1019 static void server_load_check (server *srv) {
1020     if (srv->cur_fds + srv->want_fds > srv->max_fds_hiwat  /* out of fds */
1021         || srv->conns->used >= srv->max_conns) {   /* out of connections */
1022 
1023         server_sockets_disable(srv);
1024     }
1025 }
1026 
1027 __attribute_cold__
1028 static void server_process_want_fds (server *srv) {
1029     for (int n = srv->max_fds - srv->cur_fds - 16; n > 0; --n) {
1030         connection *con = fdwaitqueue_unshift(srv, srv->fdwaitqueue);
1031         if (NULL == con) break;
1032         connection_state_machine(srv, con);
1033         --srv->want_fds;
1034     }
1035 }
1036 
1037 __attribute_cold__
1038 static int server_main (server * const srv, int argc, char **argv) {
1039 	int print_config = 0;
1040 	int test_config = 0;
1041 	int i_am_root = 0;
1042 	int o;
1043 #ifdef HAVE_FORK
1044 	int num_childs = 0;
1045 #endif
1046 	size_t i;
1047 #ifdef HAVE_SIGACTION
1048 	struct sigaction act;
1049 #endif
1050 
1051 #ifdef HAVE_FORK
1052 	int parent_pipe_fd = -1;
1053 #endif
1054 	int stdin_fd = -1;
1055 
1056 #ifdef HAVE_GETUID
1057 	i_am_root = (0 == getuid());
1058 #endif
1059 
1060 	/* initialize globals (including file-scoped static globals) */
1061 	oneshot_fd = 0;
1062 	srv_shutdown = 0;
1063 	graceful_shutdown = 0;
1064 	handle_sig_alarm = 1;
1065 	handle_sig_hup = 0;
1066 	idle_limit = 0;
1067 	chunkqueue_set_tempdirs_default_reset();
1068 	http_auth_dumbdata_reset();
1069 	http_vhostdb_dumbdata_reset();
1070 	/*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1071 	/*(intentionally preserved)*/
1072 	/*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1073 	/*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/
1074 	/*pid_fd = -1;*/
1075 
1076 	srv->srvconf.port = 0;
1077 	srv->srvconf.dont_daemonize = 0;
1078 	srv->srvconf.preflight_check = 0;
1079 
1080 	while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) {
1081 		switch(o) {
1082 		case 'f':
1083 			if (srv->config_storage) {
1084 				log_error_write(srv, __FILE__, __LINE__, "s",
1085 						"Can only read one config file. Use the include command to use multiple config files.");
1086 				return -1;
1087 			}
1088 			if (config_read(srv, optarg)) {
1089 				return -1;
1090 			}
1091 			break;
1092 		case 'm':
1093 			buffer_copy_string(srv->srvconf.modules_dir, optarg);
1094 			break;
1095 		case 'i': {
1096 			char *endptr;
1097 			long timeout = strtol(optarg, &endptr, 0);
1098 			if (!*optarg || *endptr || timeout < 0) {
1099 				log_error_write(srv, __FILE__, __LINE__, "ss",
1100 						"Invalid idle timeout value:", optarg);
1101 				return -1;
1102 			}
1103 			idle_limit = (time_t)timeout;
1104 			break;
1105 		}
1106 		case 'p': print_config = 1; break;
1107 		case 't': ++test_config; break;
1108 		case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO);
1109 			  break;
1110 		case 'D': srv->srvconf.dont_daemonize = 1; break;
1111 		case 'v': show_version(); return 0;
1112 		case 'V': show_features(); return 0;
1113 		case 'h': show_help(); return 0;
1114 		default:
1115 			show_help();
1116 			return -1;
1117 		}
1118 	}
1119 
1120       #ifdef __CYGWIN__
1121 	if (!srv->config_storage && NULL != getenv("NSSM_SERVICE_NAME")) {
1122 		char *dir = getenv("NSSM_SERVICE_DIR");
1123 		if (NULL != dir && 0 != chdir(dir)) {
1124 			log_error_write(srv, __FILE__, __LINE__, "sss", "chdir failed:", dir, strerror(errno));
1125 			return -1;
1126 		}
1127 		srv->srvconf.dont_daemonize = 1;
1128 		buffer_copy_string_len(srv->srvconf.modules_dir, CONST_STR_LEN("modules"));
1129 		if (config_read(srv, "conf/lighttpd.conf")) return -1;
1130 	}
1131       #endif
1132 
1133 	if (!srv->config_storage) {
1134 		log_error_write(srv, __FILE__, __LINE__, "s",
1135 				"No configuration available. Try using -f option.");
1136 		return -1;
1137 	}
1138 
1139 	if (print_config) {
1140 		data_unset *dc = srv->config_context->data[0];
1141 		if (dc) {
1142 			dc->fn->print(dc, 0);
1143 			fprintf(stdout, "\n");
1144 		} else {
1145 			/* shouldn't happend */
1146 			fprintf(stderr, "global config not found\n");
1147 		}
1148 	}
1149 
1150 	if (test_config) {
1151 		buffer_clear(srv->srvconf.pid_file);
1152 		if (1 == test_config) {
1153 			printf("Syntax OK\n");
1154 		} else { /*(test_config > 1)*/
1155 			test_config = 0;
1156 			srv->srvconf.preflight_check = 1;
1157 			srv->srvconf.dont_daemonize = 1;
1158 		}
1159 	}
1160 
1161 	if (test_config || print_config) {
1162 		return 0;
1163 	}
1164 
1165 	if (oneshot_fd) {
1166 		if (oneshot_fd <= STDERR_FILENO) {
1167 			log_error_write(srv, __FILE__, __LINE__, "s",
1168 					"Invalid fds at startup with lighttpd -1");
1169 			return -1;
1170 		}
1171 		graceful_shutdown = 1;
1172 		srv->sockets_disabled = 1;
1173 		srv->srvconf.dont_daemonize = 1;
1174 		buffer_clear(srv->srvconf.pid_file);
1175 		if (srv->srvconf.max_worker) {
1176 			srv->srvconf.max_worker = 0;
1177 			log_error_write(srv, __FILE__, __LINE__, "s",
1178 					"server one-shot command line option disables server.max-worker config file option.");
1179 		}
1180 	}
1181 
1182 	if (buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) {
1183 		stdin_fd = dup(STDIN_FILENO);
1184 		if (stdin_fd <= STDERR_FILENO) {
1185 			log_error_write(srv, __FILE__, __LINE__, "s",
1186 					"Invalid fds at startup");
1187 			return -1;
1188 		}
1189 	}
1190 
1191 	/* close stdin and stdout, as they are not needed */
1192 	{
1193 		struct stat st;
1194 		int devnull;
1195 		int errfd;
1196 		do {
1197 			/* coverity[overwrite_var : FALSE] */
1198 			devnull = fdevent_open_devnull();
1199 		      #ifdef __COVERITY__
1200 			__coverity_escape__(devnull);
1201 		      #endif
1202 		} while (-1 != devnull && devnull <= STDERR_FILENO);
1203 		if (-1 == devnull) {
1204 			log_error_write(srv, __FILE__, __LINE__, "ss",
1205 					"opening /dev/null failed:", strerror(errno));
1206 			return -1;
1207 		}
1208 		errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull;
1209 		if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) {
1210 			log_error_write(srv, __FILE__, __LINE__, "ss",
1211 					"setting default fds failed:", strerror(errno));
1212 		      #ifdef FD_CLOEXEC
1213 			if (-1 != errfd) close(errfd);
1214 			if (devnull != errfd) close(devnull);
1215 		      #endif
1216 			return -1;
1217 		}
1218 	      #ifdef FD_CLOEXEC
1219 		if (-1 != errfd) close(errfd);
1220 		if (devnull != errfd) close(devnull);
1221 	      #endif
1222 	}
1223 
1224 	if (0 != config_set_defaults(srv)) {
1225 		log_error_write(srv, __FILE__, __LINE__, "s",
1226 				"setting default values failed");
1227 		return -1;
1228 	}
1229 
1230 	/* check document-root */
1231 	if (buffer_string_is_empty(srv->config_storage[0]->document_root)) {
1232 		log_error_write(srv, __FILE__, __LINE__, "s",
1233 				"document-root is not set\n");
1234 		return -1;
1235 	}
1236 
1237 	if (plugins_load(srv)) {
1238 		log_error_write(srv, __FILE__, __LINE__, "s",
1239 				"loading plugins finally failed");
1240 		return -1;
1241 	}
1242 
1243 	if (HANDLER_GO_ON != plugins_call_init(srv)) {
1244 		log_error_write(srv, __FILE__, __LINE__, "s", "Initialization of plugins failed. Going down.");
1245 		return -1;
1246 	}
1247 
1248 	/* mod_indexfile should be listed in server.modules prior to dynamic handlers */
1249 	i = 0;
1250 	for (buffer *pname = NULL; i < srv->plugins.used; ++i) {
1251 		plugin *p = ((plugin **)srv->plugins.ptr)[i];
1252 		if (buffer_is_equal_string(p->name, CONST_STR_LEN("indexfile"))) {
1253 			if (pname) {
1254 				log_error_write(srv, __FILE__, __LINE__, "SB",
1255 						"Warning: mod_indexfile should be listed in server.modules prior to mod_", pname);
1256 			}
1257 			break;
1258 		}
1259 		if (p->handle_subrequest_start && p->handle_subrequest) {
1260 			if (!pname) pname = p->name;
1261 		}
1262 	}
1263 
1264 	/* open pid file BEFORE chroot */
1265 	if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/
1266 	if (-1 == pid_fd && !buffer_string_is_empty(srv->srvconf.pid_file)) {
1267 		if (-1 == (pid_fd = fdevent_open_cloexec(srv->srvconf.pid_file->ptr, 0, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
1268 			struct stat st;
1269 			if (errno != EEXIST) {
1270 				log_error_write(srv, __FILE__, __LINE__, "sbs",
1271 					"opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
1272 				return -1;
1273 			}
1274 
1275 			if (0 != stat(srv->srvconf.pid_file->ptr, &st)) {
1276 				log_error_write(srv, __FILE__, __LINE__, "sbs",
1277 						"stating existing pid-file failed:", srv->srvconf.pid_file, strerror(errno));
1278 			}
1279 
1280 			if (!S_ISREG(st.st_mode)) {
1281 				log_error_write(srv, __FILE__, __LINE__, "sb",
1282 						"pid-file exists and isn't regular file:", srv->srvconf.pid_file);
1283 				return -1;
1284 			}
1285 
1286 			if (-1 == (pid_fd = fdevent_open_cloexec(srv->srvconf.pid_file->ptr, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
1287 				log_error_write(srv, __FILE__, __LINE__, "sbs",
1288 						"opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
1289 				return -1;
1290 			}
1291 		}
1292 	}
1293 
1294 	{
1295 #ifdef HAVE_GETRLIMIT
1296 		struct rlimit rlim;
1297 		int use_rlimit = 1;
1298 #ifdef HAVE_VALGRIND_VALGRIND_H
1299 		if (RUNNING_ON_VALGRIND) use_rlimit = 0;
1300 #endif
1301 
1302 		if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
1303 			log_error_write(srv, __FILE__, __LINE__,
1304 					"ss", "couldn't get 'max filedescriptors'",
1305 					strerror(errno));
1306 			return -1;
1307 		}
1308 
1309 		/**
1310 		 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1311 		 */
1312 		if (use_rlimit && srv->srvconf.max_fds
1313 		    && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) {
1314 			/* set rlimits */
1315 
1316 			rlim.rlim_cur = srv->srvconf.max_fds;
1317 			if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds;
1318 
1319 			if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
1320 				log_error_write(srv, __FILE__, __LINE__,
1321 						"ss", "couldn't set 'max filedescriptors'",
1322 						strerror(errno));
1323 				return -1;
1324 			}
1325 		}
1326 
1327 			srv->max_fds = rlim.rlim_cur;
1328 			/*(default upper limit of 4k if server.max-fds not specified)*/
1329 			if (i_am_root && 0 == srv->srvconf.max_fds && rlim.rlim_cur > 4096)
1330 				srv->max_fds = 4096;
1331 
1332 		/* set core file rlimit, if enable_cores is set */
1333 		if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
1334 			rlim.rlim_cur = rlim.rlim_max;
1335 			setrlimit(RLIMIT_CORE, &rlim);
1336 		}
1337 #endif
1338 	}
1339 
1340 	/* we need root-perms for port < 1024 */
1341 	if (0 != network_init(srv, stdin_fd)) {
1342 		return -1;
1343 	}
1344 
1345 	if (i_am_root) {
1346 #ifdef HAVE_PWD_H
1347 		/* set user and group */
1348 		struct group *grp = NULL;
1349 		struct passwd *pwd = NULL;
1350 
1351 		if (!buffer_string_is_empty(srv->srvconf.groupname)) {
1352 			if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
1353 				log_error_write(srv, __FILE__, __LINE__, "sb",
1354 					"can't find groupname", srv->srvconf.groupname);
1355 				return -1;
1356 			}
1357 		}
1358 
1359 		if (!buffer_string_is_empty(srv->srvconf.username)) {
1360 			if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
1361 				log_error_write(srv, __FILE__, __LINE__, "sb",
1362 						"can't find username", srv->srvconf.username);
1363 				return -1;
1364 			}
1365 
1366 			if (pwd->pw_uid == 0) {
1367 				log_error_write(srv, __FILE__, __LINE__, "s",
1368 						"I will not set uid to 0\n");
1369 				return -1;
1370 			}
1371 
1372 			if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) {
1373 				log_error_write(srv, __FILE__, __LINE__, "sd",
1374 					"can't find group id", pwd->pw_gid);
1375 				return -1;
1376 			}
1377 		}
1378 
1379 		if (NULL != grp) {
1380 			if (grp->gr_gid == 0) {
1381 				log_error_write(srv, __FILE__, __LINE__, "s",
1382 						"I will not set gid to 0\n");
1383 				return -1;
1384 			}
1385 		}
1386 
1387 		/*
1388 		 * Change group before chroot, when we have access
1389 		 * to /etc/group
1390 		 * */
1391 		if (NULL != grp) {
1392 			if (-1 == setgid(grp->gr_gid)) {
1393 				log_error_write(srv, __FILE__, __LINE__, "ss", "setgid failed: ", strerror(errno));
1394 				return -1;
1395 			}
1396 			if (-1 == setgroups(0, NULL)) {
1397 				log_error_write(srv, __FILE__, __LINE__, "ss", "setgroups failed: ", strerror(errno));
1398 				return -1;
1399 			}
1400 			if (!buffer_string_is_empty(srv->srvconf.username)) {
1401 				initgroups(srv->srvconf.username->ptr, grp->gr_gid);
1402 			}
1403 		}
1404 #endif
1405 #ifdef HAVE_CHROOT
1406 		if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
1407 			tzset();
1408 
1409 			if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
1410 				log_error_write(srv, __FILE__, __LINE__, "ss", "chroot failed: ", strerror(errno));
1411 				return -1;
1412 			}
1413 			if (-1 == chdir("/")) {
1414 				log_error_write(srv, __FILE__, __LINE__, "ss", "chdir failed: ", strerror(errno));
1415 				return -1;
1416 			}
1417 		}
1418 #endif
1419 #ifdef HAVE_PWD_H
1420 		/* drop root privs */
1421 		if (NULL != pwd) {
1422 			if (-1 == setuid(pwd->pw_uid)) {
1423 				log_error_write(srv, __FILE__, __LINE__, "ss", "setuid failed: ", strerror(errno));
1424 				return -1;
1425 			}
1426 		}
1427 #endif
1428 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1429 		/**
1430 		 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1431 		 */
1432 		if (srv->srvconf.enable_cores) {
1433 			prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1434 		}
1435 #endif
1436 	}
1437 
1438 	/* set max-conns */
1439 	if (srv->srvconf.max_conns > srv->max_fds/2) {
1440 		/* we can't have more connections than max-fds/2 */
1441 		log_error_write(srv, __FILE__, __LINE__, "sdd", "can't have more connections than fds/2: ", srv->srvconf.max_conns, srv->max_fds);
1442 		srv->max_conns = srv->max_fds/2;
1443 	} else if (srv->srvconf.max_conns) {
1444 		/* otherwise respect the wishes of the user */
1445 		srv->max_conns = srv->srvconf.max_conns;
1446 	} else {
1447 		/* or use the default: we really don't want to hit max-fds */
1448 		srv->max_conns = srv->max_fds/3;
1449 	}
1450 
1451 #ifdef HAVE_FORK
1452 	/* network is up, let's daemonize ourself */
1453 	if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) {
1454 		parent_pipe_fd = daemonize();
1455 	}
1456 #endif
1457 	graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/
1458 	if (0 == oneshot_fd) graceful_shutdown = 0;
1459 
1460 
1461 #ifdef HAVE_SIGACTION
1462 	memset(&act, 0, sizeof(act));
1463 	act.sa_handler = SIG_IGN;
1464 	sigaction(SIGPIPE, &act, NULL);
1465 # if defined(SA_SIGINFO)
1466 	last_sighup_info.si_uid = 0,
1467 	last_sighup_info.si_pid = 0;
1468 	last_sigterm_info.si_uid = 0,
1469 	last_sigterm_info.si_pid = 0;
1470 	act.sa_sigaction = sigaction_handler;
1471 	sigemptyset(&act.sa_mask);
1472 	act.sa_flags = SA_SIGINFO;
1473 # else
1474 	act.sa_handler = signal_handler;
1475 	sigemptyset(&act.sa_mask);
1476 	act.sa_flags = 0;
1477 # endif
1478 	sigaction(SIGINT,  &act, NULL);
1479 	sigaction(SIGTERM, &act, NULL);
1480 	sigaction(SIGHUP,  &act, NULL);
1481 	sigaction(SIGALRM, &act, NULL);
1482 	sigaction(SIGUSR1, &act, NULL);
1483 
1484 	/* it should be safe to restart syscalls after SIGCHLD */
1485 	act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
1486 	sigaction(SIGCHLD, &act, NULL);
1487 
1488 #elif defined(HAVE_SIGNAL)
1489 	/* ignore the SIGPIPE from sendfile() */
1490 	signal(SIGPIPE, SIG_IGN);
1491 	signal(SIGALRM, signal_handler);
1492 	signal(SIGTERM, signal_handler);
1493 	signal(SIGHUP,  signal_handler);
1494 	signal(SIGCHLD,  signal_handler);
1495 	signal(SIGINT,  signal_handler);
1496 	signal(SIGUSR1, signal_handler);
1497 #endif
1498 
1499 
1500 	srv->gid = getgid();
1501 	srv->uid = getuid();
1502 	srv->pid = getpid();
1503 
1504 	/* write pid file */
1505 	if (pid_fd > 2) {
1506 		buffer_copy_int(srv->tmp_buf, srv->pid);
1507 		buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\n"));
1508 		if (-1 == write_all(pid_fd, CONST_BUF_LEN(srv->tmp_buf))) {
1509 			log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't write pid file:", strerror(errno));
1510 			close(pid_fd);
1511 			pid_fd = -1;
1512 			return -1;
1513 		}
1514 	} else if (pid_fd < -2) {
1515 		pid_fd = -pid_fd;
1516 	}
1517 
1518 	/* Close stderr ASAP in the child process to make sure that nothing
1519 	 * is being written to that fd which may not be valid anymore. */
1520 	if (!srv->srvconf.preflight_check) {
1521 		if (-1 == log_error_open(srv)) {
1522 			log_error_write(srv, __FILE__, __LINE__, "s", "Opening errorlog failed. Going down.");
1523 			return -1;
1524 		}
1525 		log_error_write(srv, __FILE__, __LINE__, "s", "server started (" PACKAGE_DESC ")");
1526 	}
1527 
1528 	if (buffer_is_empty(srv->config_storage[0]->server_tag)) {
1529 		buffer_copy_string_len(srv->config_storage[0]->server_tag, CONST_STR_LEN(PACKAGE_DESC));
1530 	}
1531 
1532 	if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1533 		log_error_write(srv, __FILE__, __LINE__, "s", "Configuration of plugins failed. Going down.");
1534 		return -1;
1535 	}
1536 
1537 	/* settings might be enabled during module config set defaults */
1538 	srv->config_storage[0]->high_precision_timestamps = srv->srvconf.high_precision_timestamps;
1539 
1540 	/* dump unused config-keys */
1541 	for (i = 0; i < srv->config_context->used; i++) {
1542 		array *config = ((data_config *)srv->config_context->data[i])->value;
1543 		size_t j;
1544 
1545 		for (j = 0; config && j < config->used; j++) {
1546 			data_unset *du = config->data[j];
1547 
1548 			/* all var.* is known as user defined variable */
1549 			if (strncmp(du->key->ptr, "var.", sizeof("var.") - 1) == 0) {
1550 				continue;
1551 			}
1552 
1553 			if (NULL == array_get_element_klen(srv->config_touched, CONST_BUF_LEN(du->key))) {
1554 				log_error_write(srv, __FILE__, __LINE__, "sbs",
1555 						"WARNING: unknown config-key:",
1556 						du->key,
1557 						"(ignored)");
1558 			}
1559 		}
1560 	}
1561 
1562 	if (srv->config_unsupported) {
1563 		log_error_write(srv, __FILE__, __LINE__, "s",
1564 				"Configuration contains unsupported keys. Going down.");
1565 	}
1566 
1567 	if (srv->config_deprecated) {
1568 		log_error_write(srv, __FILE__, __LINE__, "s",
1569 				"Configuration contains deprecated keys. Going down.");
1570 	}
1571 
1572 	if (srv->config_unsupported || srv->config_deprecated) {
1573 		return -1;
1574 	}
1575 
1576 	if (srv->srvconf.preflight_check) {
1577 		/*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1578 		return 0;
1579 	}
1580 
1581 
1582 #ifdef HAVE_FORK
1583 	/**
1584 	 * notify daemonize-grandparent of successful startup
1585 	 * do this before any further forking is done (workers)
1586 	 */
1587 	if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) {
1588 		if (0 > write(parent_pipe_fd, "", 1)) return -1;
1589 		close(parent_pipe_fd);
1590 	}
1591 
1592 	if (idle_limit && srv->srvconf.max_worker) {
1593 		srv->srvconf.max_worker = 0;
1594 		log_error_write(srv, __FILE__, __LINE__, "s",
1595 				"server idle time limit command line option disables server.max-worker config file option.");
1596 	}
1597 
1598 	/* start watcher and workers */
1599 	num_childs = srv->srvconf.max_worker;
1600 	if (num_childs > 0) {
1601 		pid_t pids[num_childs];
1602 		pid_t pid;
1603 		const int npids = num_childs;
1604 		int child = 0;
1605 		unsigned int timer = 0;
1606 		for (int n = 0; n < npids; ++n) pids[n] = -1;
1607 		while (!child && !srv_shutdown && !graceful_shutdown) {
1608 			if (num_childs > 0) {
1609 				switch ((pid = fork())) {
1610 				case -1:
1611 					return -1;
1612 				case 0:
1613 					child = 1;
1614 					alarm(0);
1615 					break;
1616 				default:
1617 					num_childs--;
1618 					for (int n = 0; n < npids; ++n) {
1619 						if (-1 == pids[n]) {
1620 							pids[n] = pid;
1621 							break;
1622 						}
1623 					}
1624 					break;
1625 				}
1626 			} else {
1627 				int status;
1628 
1629 				if (-1 != (pid = wait(&status))) {
1630 					srv->cur_ts = time(NULL);
1631 					if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1632 						if (!timer) alarm((timer = 5));
1633 						continue;
1634 					}
1635 					switch (fdevent_reaped_logger_pipe(pid)) {
1636 					  default: break;
1637 					  case -1: if (!timer) alarm((timer = 5));
1638 						   /* fall through */
1639 					  case  1: continue;
1640 					}
1641 					/**
1642 					 * check if one of our workers went away
1643 					 */
1644 					for (int n = 0; n < npids; ++n) {
1645 						if (pid == pids[n]) {
1646 							pids[n] = -1;
1647 							num_childs++;
1648 							break;
1649 						}
1650 					}
1651 				} else {
1652 					switch (errno) {
1653 					case EINTR:
1654 						srv->cur_ts = time(NULL);
1655 						/**
1656 						 * if we receive a SIGHUP we have to close our logs ourself as we don't
1657 						 * have the mainloop who can help us here
1658 						 */
1659 						if (handle_sig_hup) {
1660 							handle_sig_hup = 0;
1661 
1662 							log_error_cycle(srv);
1663 
1664 							/* forward SIGHUP to workers */
1665 							for (int n = 0; n < npids; ++n) {
1666 								if (pids[n] > 0) kill(pids[n], SIGHUP);
1667 							}
1668 						}
1669 						if (handle_sig_alarm) {
1670 							handle_sig_alarm = 0;
1671 							timer = 0;
1672 							plugins_call_handle_trigger(srv);
1673 							fdevent_restart_logger_pipes(srv->cur_ts);
1674 						}
1675 						break;
1676 					default:
1677 						break;
1678 					}
1679 				}
1680 			}
1681 		}
1682 
1683 		/**
1684 		 * for the parent this is the exit-point
1685 		 */
1686 		if (!child) {
1687 			/**
1688 			 * kill all children too
1689 			 */
1690 			if (graceful_shutdown || graceful_restart) {
1691 				/* flag to ignore one SIGINT if graceful_restart */
1692 				if (graceful_restart) graceful_restart = 2;
1693 				kill(0, SIGINT);
1694 				server_graceful_state(srv);
1695 			} else if (srv_shutdown) {
1696 				kill(0, SIGTERM);
1697 			}
1698 
1699 			return 0;
1700 		}
1701 
1702 		/* ignore SIGUSR1 in workers; only parent directs graceful restart */
1703 	      #ifdef HAVE_SIGACTION
1704 		{
1705 			struct sigaction actignore;
1706 			memset(&actignore, 0, sizeof(actignore));
1707 			actignore.sa_handler = SIG_IGN;
1708 			sigaction(SIGUSR1, &actignore, NULL);
1709 		}
1710 	      #elif defined(HAVE_SIGNAL)
1711 			signal(SIGUSR1, SIG_IGN);
1712 	      #endif
1713 
1714 		/**
1715 		 * make sure workers do not muck with pid-file
1716 		 */
1717 		if (0 <= pid_fd) {
1718 			close(pid_fd);
1719 			pid_fd = -1;
1720 		}
1721 		buffer_clear(srv->srvconf.pid_file);
1722 
1723 		fdevent_clr_logger_pipe_pids();
1724 		srv->pid = getpid();
1725 		li_rand_reseed();
1726 	}
1727 #endif
1728 
1729 	if (NULL == (srv->ev = fdevent_init(srv))) {
1730 		log_error_write(srv, __FILE__, __LINE__,
1731 				"s", "fdevent_init failed");
1732 		return -1;
1733 	}
1734 
1735 	srv->max_fds_lowat = srv->max_fds * 8 / 10;
1736 	srv->max_fds_hiwat = srv->max_fds * 9 / 10;
1737 
1738 	/* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1739 #ifdef HAVE_SIGACTION
1740 	sigaction(SIGCHLD, &act, NULL);
1741 #elif defined(HAVE_SIGNAL)
1742 	signal(SIGCHLD,  signal_handler);
1743 #endif
1744 
1745 	/*
1746 	 * kqueue() is called here, select resets its internals,
1747 	 * all server sockets get their handlers
1748 	 *
1749 	 * */
1750 	if (0 != network_register_fdevents(srv)) {
1751 		return -1;
1752 	}
1753 
1754 	/* might fail if user is using fam (not gamin) and famd isn't running */
1755 	if (NULL == (srv->stat_cache = stat_cache_init(srv))) {
1756 		log_error_write(srv, __FILE__, __LINE__, "s",
1757 			"stat-cache could not be setup, dieing.");
1758 		return -1;
1759 	}
1760 
1761 #ifdef USE_ALARM
1762 	{
1763 		/* setup periodic timer (1 second) */
1764 		struct itimerval interval;
1765 		interval.it_interval.tv_sec = 1;
1766 		interval.it_interval.tv_usec = 0;
1767 		interval.it_value.tv_sec = 1;
1768 		interval.it_value.tv_usec = 0;
1769 		if (setitimer(ITIMER_REAL, &interval, NULL)) {
1770 			log_error_write(srv, __FILE__, __LINE__, "s", "setting timer failed");
1771 			return -1;
1772 		}
1773 	}
1774 #endif
1775 
1776 
1777 	/* get the current number of FDs */
1778 	{
1779 		int fd = fdevent_open_devnull();
1780 		if (fd >= 0) {
1781 			srv->cur_fds = fd;
1782 			close(fd);
1783 		}
1784 	}
1785 
1786 	if (0 != server_sockets_set_nb_cloexec(srv)) {
1787 		return -1;
1788 	}
1789 
1790 	/* plugin hook for worker_init */
1791 	if (HANDLER_GO_ON != plugins_call_worker_init(srv))
1792 		return -1;
1793 
1794 	if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) {
1795 		oneshot_fd = -1;
1796 	}
1797 
1798 	return 1;
1799 }
1800 
1801 __attribute_cold__
1802 __attribute_noinline__
1803 static int server_handle_sighup (server * const srv) {
1804 			handler_t r;
1805 
1806 			/* cycle logfiles */
1807 
1808 			switch(r = plugins_call_handle_sighup(srv)) {
1809 			case HANDLER_GO_ON:
1810 				break;
1811 			default:
1812 				log_error_write(srv, __FILE__, __LINE__, "sd", "sighup-handler return with an error", r);
1813 				break;
1814 			}
1815 
1816 			if (-1 == log_error_cycle(srv)) {
1817 				log_error_write(srv, __FILE__, __LINE__, "s", "cycling errorlog failed, dying");
1818 
1819 				return -1;
1820 			} else {
1821 #ifdef HAVE_SIGACTION
1822 				log_error_write(srv, __FILE__, __LINE__, "sdsd",
1823 					"logfiles cycled UID =",
1824 					last_sighup_info.si_uid,
1825 					"PID =",
1826 					last_sighup_info.si_pid);
1827 #else
1828 				log_error_write(srv, __FILE__, __LINE__, "s",
1829 					"logfiles cycled");
1830 #endif
1831 			}
1832 
1833 			return 0;
1834 }
1835 
1836 __attribute_noinline__
1837 static void server_handle_sigalrm (server * const srv, time_t min_ts, time_t last_active_ts) {
1838 				connections *conns = srv->conns;
1839 				handler_t r;
1840 
1841 				switch(r = plugins_call_handle_trigger(srv)) {
1842 				case HANDLER_GO_ON:
1843 					break;
1844 				case HANDLER_ERROR:
1845 					log_error_write(srv, __FILE__, __LINE__, "s", "one of the triggers failed");
1846 					break;
1847 				default:
1848 					log_error_write(srv, __FILE__, __LINE__, "d", r);
1849 					break;
1850 				}
1851 
1852 				srv->cur_ts = min_ts;
1853 
1854 				/* check idle time limit, if enabled */
1855 				if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) {
1856 					log_error_write(srv, __FILE__, __LINE__, "sDs", "[note] idle timeout", (int)idle_limit,
1857 							"s exceeded, initiating graceful shutdown");
1858 					graceful_shutdown = 2; /* value 2 indicates idle timeout */
1859 					if (graceful_restart) {
1860 						graceful_restart = 0;
1861 						if (pid_fd < -2) pid_fd = -pid_fd;
1862 						server_sockets_close(srv);
1863 					}
1864 				}
1865 
1866 			      #ifdef HAVE_GETLOADAVG
1867 				/* refresh loadavg data every 30 seconds */
1868 				if (srv->srvconf.loadts + 30 < min_ts) {
1869 					if (-1 != getloadavg(srv->srvconf.loadavg, 3)) {
1870 						srv->srvconf.loadts = min_ts;
1871 					}
1872 				}
1873 			      #endif
1874 
1875 				/* free excess chunkqueue buffers every 64 seconds */
1876 				if (0 == (min_ts & 0x3f)) chunkqueue_chunk_pool_clear();
1877 				/* cleanup stat-cache */
1878 				stat_cache_trigger_cleanup(srv);
1879 				/* reset global/aggregate rate limit counters */
1880 				for (size_t i = 0; i < srv->config_context->used; ++i) {
1881 					srv->config_storage[i]->global_bytes_per_second_cnt = 0;
1882 				}
1883 				/* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1884 				if (graceful_shutdown && !srv_shutdown) server_graceful_shutdown_maint(srv);
1885 				/**
1886 				 * check all connections for timeouts
1887 				 *
1888 				 */
1889 				for (size_t ndx = 0; ndx < conns->used; ++ndx) {
1890 					connection * const con = conns->ptr[ndx];
1891 					const int waitevents = fdevent_fdnode_interest(con->fdn);
1892 					int changed = 0;
1893 					int t_diff;
1894 
1895 					if (con->state == CON_STATE_CLOSE) {
1896 						if (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT) {
1897 							changed = 1;
1898 						}
1899 					} else if (waitevents & FDEVENT_IN) {
1900 						if (con->request_count == 1 || con->state != CON_STATE_READ) { /* e.g. CON_STATE_READ_POST || CON_STATE_WRITE */
1901 							if (srv->cur_ts - con->read_idle_ts > con->conf.max_read_idle) {
1902 								/* time - out */
1903 								if (con->conf.log_request_handling) {
1904 									log_error_write(srv, __FILE__, __LINE__, "sd",
1905 										"connection closed - read timeout:", con->fd);
1906 								}
1907 
1908 								connection_set_state(srv, con, CON_STATE_ERROR);
1909 								changed = 1;
1910 							}
1911 						} else {
1912 							if (srv->cur_ts - con->read_idle_ts > con->keep_alive_idle) {
1913 								/* time - out */
1914 								if (con->conf.log_request_handling) {
1915 									log_error_write(srv, __FILE__, __LINE__, "sd",
1916 										"connection closed - keep-alive timeout:", con->fd);
1917 								}
1918 
1919 								connection_set_state(srv, con, CON_STATE_ERROR);
1920 								changed = 1;
1921 							}
1922 						}
1923 					}
1924 
1925 					/* max_write_idle timeout currently functions as backend timeout,
1926 					 * too, after response has been started.
1927 					 * future: have separate backend timeout, and then change this
1928 					 * to check for write interest before checking for timeout */
1929 					/*if (waitevents & FDEVENT_OUT)*/
1930 					if ((con->state == CON_STATE_WRITE) &&
1931 					    (con->write_request_ts != 0)) {
1932 #if 0
1933 						if (srv->cur_ts - con->write_request_ts > 60) {
1934 							log_error_write(srv, __FILE__, __LINE__, "sdd",
1935 									"connection closed - pre-write-request-timeout:", con->fd, srv->cur_ts - con->write_request_ts);
1936 						}
1937 #endif
1938 
1939 						if (srv->cur_ts - con->write_request_ts > con->conf.max_write_idle) {
1940 							/* time - out */
1941 							if (con->conf.log_timeouts) {
1942 								log_error_write(srv, __FILE__, __LINE__, "sbsbsosds",
1943 									"NOTE: a request from",
1944 									con->dst_addr_buf,
1945 									"for",
1946 									con->request.uri,
1947 									"timed out after writing",
1948 									con->bytes_written,
1949 									"bytes. We waited",
1950 									(int)con->conf.max_write_idle,
1951 									"seconds. If this a problem increase server.max-write-idle");
1952 							}
1953 							connection_set_state(srv, con, CON_STATE_ERROR);
1954 							changed = 1;
1955 						}
1956 					}
1957 
1958 					/* we don't like div by zero */
1959 					if (0 == (t_diff = srv->cur_ts - con->connection_start)) t_diff = 1;
1960 
1961 					if (con->traffic_limit_reached &&
1962 					    (con->conf.kbytes_per_second == 0 ||
1963 					     ((con->bytes_written / t_diff) < con->conf.kbytes_per_second * 1024))) {
1964 						/* enable connection again */
1965 						con->traffic_limit_reached = 0;
1966 
1967 						changed = 1;
1968 					}
1969 
1970 					con->bytes_written_cur_second = 0;
1971 
1972 					if (changed) {
1973 						connection_state_machine(srv, con);
1974 					}
1975 				}
1976 }
1977 
1978 __attribute_noinline__
1979 static void server_handle_sigchld (server * const srv) {
1980 			pid_t pid;
1981 			do {
1982 				int status;
1983 				pid = waitpid(-1, &status, WNOHANG);
1984 				if (pid > 0) {
1985 					if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1986 						continue;
1987 					}
1988 					if (0 == srv->srvconf.max_worker) {
1989 						/* check piped-loggers and restart, even if shutting down */
1990 						if (fdevent_waitpid_logger_pipe_pid(pid, srv->cur_ts)) {
1991 							continue;
1992 						}
1993 					}
1994 				}
1995 			} while (pid > 0 || (-1 == pid && errno == EINTR));
1996 }
1997 
1998 __attribute_hot__
1999 __attribute_noinline__
2000 static int server_main_loop (server * const srv) {
2001 	connections * const joblist = srv->joblist;
2002 	time_t last_active_ts = time(NULL);
2003 
2004 	while (!srv_shutdown) {
2005 
2006 		if (handle_sig_hup) {
2007 			handle_sig_hup = 0;
2008 			if (server_handle_sighup(srv)) return -1;
2009 		}
2010 
2011 		if (handle_sig_alarm) {
2012 			time_t min_ts = time(NULL);
2013 		      #ifdef USE_ALARM
2014 			handle_sig_alarm = 0;
2015 		      #endif
2016 			if (min_ts != srv->cur_ts) {
2017 				server_handle_sigalrm(srv, min_ts, last_active_ts);
2018 			}
2019 		}
2020 
2021 		if (handle_sig_child) {
2022 			handle_sig_child = 0;
2023 			server_handle_sigchld(srv);
2024 		}
2025 
2026 		if (graceful_shutdown) {
2027 			server_graceful_state(srv);
2028 			if (srv->conns->used == 0) {
2029 				/* we are in graceful shutdown phase and all connections are closed
2030 				 * we are ready to terminate without harming anyone */
2031 				srv_shutdown = 1;
2032 				break;
2033 			}
2034 		} else if (srv->sockets_disabled) {
2035 			server_overload_check(srv);
2036 		} else {
2037 			server_load_check(srv);
2038 		}
2039 
2040 		if (srv->want_fds) {
2041 			server_process_want_fds(srv);
2042 		}
2043 
2044 		if (fdevent_poll(srv->ev, 1000) > 0) {
2045 			last_active_ts = srv->cur_ts;
2046 		}
2047 
2048 		for (size_t ndx = 0; ndx < joblist->used; ++ndx) {
2049 			connection *con = joblist->ptr[ndx];
2050 			connection_state_machine(srv, con);
2051 		}
2052 		joblist->used = 0;
2053 	}
2054 
2055 	return 0;
2056 }
2057 
2058 __attribute_cold__
2059 int main (int argc, char **argv) {
2060     int rc;
2061 
2062   #ifdef HAVE_GETUID
2063   #ifndef HAVE_ISSETUGID
2064   #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2065   #endif
2066     if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2067         fprintf(stderr,
2068                 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2069         return -1;
2070     }
2071   #endif
2072 
2073     /* for nice %b handling in strftime() */
2074     setlocale(LC_TIME, "C");
2075 
2076     do {
2077         server * const srv = server_init();
2078 
2079         if (graceful_restart) {
2080             server_sockets_restore(srv);
2081             optind = 1;
2082         }
2083 
2084         rc = server_main(srv, argc, argv);
2085         if (rc > 0 && 0 == (rc = server_main_loop(srv))) {
2086             if (graceful_shutdown || graceful_restart) {
2087                 server_graceful_state(srv);
2088             }
2089 
2090             if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */
2091                 log_error_write(srv, __FILE__, __LINE__, "s",
2092                                 "server stopped after idle timeout");
2093             } else {
2094               #ifdef HAVE_SIGACTION
2095                 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2096                                 "server stopped by UID =",
2097                                 last_sigterm_info.si_uid,
2098                                 "PID =",
2099                                 last_sigterm_info.si_pid);
2100               #else
2101                 log_error_write(srv, __FILE__, __LINE__, "s",
2102                                 "server stopped");
2103               #endif
2104             }
2105         }
2106 
2107         /* clean-up */
2108         remove_pid_file(srv);
2109         log_error_close(srv);
2110         fdevent_close_logger_pipes();
2111         if (graceful_restart)
2112             server_sockets_save(srv);
2113         else
2114             network_close(srv);
2115         connections_free(srv);
2116         plugins_free(srv);
2117         server_free(srv);
2118 
2119         if (0 != rc || !graceful_restart) break;
2120 
2121         /* wait for all children to exit before graceful restart */
2122         while (waitpid(-1, NULL, 0) > 0) ;
2123     } while (graceful_restart);
2124 
2125     return rc;
2126 }
2127