xref: /lighttpd1.4/src/server.c (revision dbdab5db)
1 #include "first.h"
2 
3 #include "server.h"
4 #include "buffer.h"
5 #include "network.h"
6 #include "log.h"
7 #include "keyvalue.h"
8 #include "response.h"
9 #include "request.h"
10 #include "chunk.h"
11 #include "http_chunk.h"
12 #include "fdevent.h"
13 #include "connections.h"
14 #include "stat_cache.h"
15 #include "plugin.h"
16 #include "joblist.h"
17 #include "network_backends.h"
18 #include "version.h"
19 
20 #include <sys/types.h>
21 #include <sys/time.h>
22 #include <sys/stat.h>
23 
24 #include <string.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <stdlib.h>
29 #include <time.h>
30 #include <signal.h>
31 #include <assert.h>
32 #include <locale.h>
33 
34 #include <stdio.h>
35 
36 #ifdef HAVE_GETOPT_H
37 # include <getopt.h>
38 #endif
39 
40 #ifdef HAVE_VALGRIND_VALGRIND_H
41 # include <valgrind/valgrind.h>
42 #endif
43 
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
46 #endif
47 
48 #ifdef HAVE_PWD_H
49 # include <grp.h>
50 # include <pwd.h>
51 #endif
52 
53 #ifdef HAVE_SYS_RESOURCE_H
54 # include <sys/resource.h>
55 #endif
56 
57 #ifdef HAVE_SYS_PRCTL_H
58 # include <sys/prctl.h>
59 #endif
60 
61 #ifdef USE_OPENSSL
62 # include <openssl/err.h>
63 #endif
64 
65 #ifndef __sgi
66 /* IRIX doesn't like the alarm based time() optimization */
67 /* #define USE_ALARM */
68 #endif
69 
70 #ifdef HAVE_GETUID
71 # ifndef HAVE_ISSETUGID
72 
73 static int l_issetugid(void) {
74 	return (geteuid() != getuid() || getegid() != getgid());
75 }
76 
77 #  define issetugid l_issetugid
78 # endif
79 #endif
80 
81 static volatile sig_atomic_t srv_shutdown = 0;
82 static volatile sig_atomic_t graceful_shutdown = 0;
83 static volatile sig_atomic_t handle_sig_alarm = 1;
84 static volatile sig_atomic_t handle_sig_hup = 0;
85 static volatile sig_atomic_t forwarded_sig_hup = 0;
86 
87 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
88 static volatile siginfo_t last_sigterm_info;
89 static volatile siginfo_t last_sighup_info;
90 
91 static void sigaction_handler(int sig, siginfo_t *si, void *context) {
92 	static siginfo_t empty_siginfo;
93 	UNUSED(context);
94 
95 	if (!si) si = &empty_siginfo;
96 
97 	switch (sig) {
98 	case SIGTERM:
99 		srv_shutdown = 1;
100 		last_sigterm_info = *si;
101 		break;
102 	case SIGINT:
103 		if (graceful_shutdown) {
104 			srv_shutdown = 1;
105 		} else {
106 			graceful_shutdown = 1;
107 		}
108 		last_sigterm_info = *si;
109 
110 		break;
111 	case SIGALRM:
112 		handle_sig_alarm = 1;
113 		break;
114 	case SIGHUP:
115 		/**
116 		 * we send the SIGHUP to all procs in the process-group
117 		 * this includes ourself
118 		 *
119 		 * make sure we only send it once and don't create a
120 		 * infinite loop
121 		 */
122 		if (!forwarded_sig_hup) {
123 			handle_sig_hup = 1;
124 			last_sighup_info = *si;
125 		} else {
126 			forwarded_sig_hup = 0;
127 		}
128 		break;
129 	case SIGCHLD:
130 		break;
131 	}
132 }
133 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
134 static void signal_handler(int sig) {
135 	switch (sig) {
136 	case SIGTERM: srv_shutdown = 1; break;
137 	case SIGINT:
138 	     if (graceful_shutdown) srv_shutdown = 1;
139 	     else graceful_shutdown = 1;
140 
141 	     break;
142 	case SIGALRM: handle_sig_alarm = 1; break;
143 	case SIGHUP:  handle_sig_hup = 1; break;
144 	case SIGCHLD:  break;
145 	}
146 }
147 #endif
148 
149 #ifdef HAVE_FORK
150 static int daemonize(void) {
151 	int pipefd[2];
152 	pid_t pid;
153 #ifdef SIGTTOU
154 	signal(SIGTTOU, SIG_IGN);
155 #endif
156 #ifdef SIGTTIN
157 	signal(SIGTTIN, SIG_IGN);
158 #endif
159 #ifdef SIGTSTP
160 	signal(SIGTSTP, SIG_IGN);
161 #endif
162 
163 	if (pipe(pipefd) < 0) exit(-1);
164 
165 	if (0 > (pid = fork())) exit(-1);
166 
167 	if (0 < pid) {
168 		char buf;
169 		ssize_t bytes;
170 
171 		close(pipefd[1]);
172 		/* parent waits for grandchild to be ready */
173 		do {
174 			bytes = read(pipefd[0], &buf, sizeof(buf));
175 		} while (bytes < 0 && EINTR == errno);
176 		close(pipefd[0]);
177 
178 		if (bytes <= 0) {
179 			/* closed fd (without writing) == failure in grandchild */
180 			fputs("daemonized server failed to start; check error log for details\n", stderr);
181 			exit(-1);
182 		}
183 
184 		exit(0);
185 	}
186 
187 	close(pipefd[0]);
188 
189 	if (-1 == setsid()) exit(0);
190 
191 	signal(SIGHUP, SIG_IGN);
192 
193 	if (0 != fork()) exit(0);
194 
195 	if (0 != chdir("/")) exit(0);
196 
197 	fd_close_on_exec(pipefd[1]);
198 	return pipefd[1];
199 }
200 #endif
201 
202 static server *server_init(void) {
203 	int i;
204 	FILE *frandom = NULL;
205 
206 	server *srv = calloc(1, sizeof(*srv));
207 	force_assert(srv);
208 #define CLEAN(x) \
209 	srv->x = buffer_init();
210 
211 	CLEAN(response_header);
212 	CLEAN(parse_full_path);
213 	CLEAN(ts_debug_str);
214 	CLEAN(ts_date_str);
215 	CLEAN(errorlog_buf);
216 	CLEAN(response_range);
217 	CLEAN(tmp_buf);
218 	srv->empty_string = buffer_init_string("");
219 	CLEAN(cond_check_buf);
220 
221 	CLEAN(srvconf.errorlog_file);
222 	CLEAN(srvconf.breakagelog_file);
223 	CLEAN(srvconf.groupname);
224 	CLEAN(srvconf.username);
225 	CLEAN(srvconf.changeroot);
226 	CLEAN(srvconf.bindhost);
227 	CLEAN(srvconf.event_handler);
228 	CLEAN(srvconf.pid_file);
229 
230 	CLEAN(tmp_chunk_len);
231 #undef CLEAN
232 
233 #define CLEAN(x) \
234 	srv->x = array_init();
235 
236 	CLEAN(config_context);
237 	CLEAN(config_touched);
238 	CLEAN(status);
239 #undef CLEAN
240 
241 	for (i = 0; i < FILE_CACHE_MAX; i++) {
242 		srv->mtime_cache[i].mtime = (time_t)-1;
243 		srv->mtime_cache[i].str = buffer_init();
244 	}
245 
246 	if ((NULL != (frandom = fopen("/dev/urandom", "rb")) || NULL != (frandom = fopen("/dev/random", "rb")))
247 	            && 1 == fread(srv->entropy, sizeof(srv->entropy), 1, frandom)) {
248 		unsigned int e;
249 		memcpy(&e, srv->entropy, sizeof(e) < sizeof(srv->entropy) ? sizeof(e) : sizeof(srv->entropy));
250 		srand(e);
251 		srv->is_real_entropy = 1;
252 	} else {
253 		unsigned int j;
254 		srand(time(NULL) ^ getpid());
255 		srv->is_real_entropy = 0;
256 		for (j = 0; j < sizeof(srv->entropy); j++)
257 			srv->entropy[j] = rand();
258 	}
259 	if (frandom) fclose(frandom);
260 
261 	srv->cur_ts = time(NULL);
262 	srv->startup_ts = srv->cur_ts;
263 
264 	srv->conns = calloc(1, sizeof(*srv->conns));
265 	force_assert(srv->conns);
266 
267 	srv->joblist = calloc(1, sizeof(*srv->joblist));
268 	force_assert(srv->joblist);
269 
270 	srv->fdwaitqueue = calloc(1, sizeof(*srv->fdwaitqueue));
271 	force_assert(srv->fdwaitqueue);
272 
273 	srv->srvconf.modules = array_init();
274 	srv->srvconf.modules_dir = buffer_init_string(LIBRARY_DIR);
275 	srv->srvconf.network_backend = buffer_init();
276 	srv->srvconf.upload_tempdirs = array_init();
277 	srv->srvconf.reject_expect_100_with_417 = 1;
278 	srv->srvconf.xattr_name = buffer_init_string("Content-Type");
279 
280 	/* use syslog */
281 	srv->errorlog_fd = STDERR_FILENO;
282 	srv->errorlog_mode = ERRORLOG_FD;
283 
284 	srv->split_vals = array_init();
285 
286 	return srv;
287 }
288 
289 static void server_free(server *srv) {
290 	size_t i;
291 
292 	for (i = 0; i < FILE_CACHE_MAX; i++) {
293 		buffer_free(srv->mtime_cache[i].str);
294 	}
295 
296 #define CLEAN(x) \
297 	buffer_free(srv->x);
298 
299 	CLEAN(response_header);
300 	CLEAN(parse_full_path);
301 	CLEAN(ts_debug_str);
302 	CLEAN(ts_date_str);
303 	CLEAN(errorlog_buf);
304 	CLEAN(response_range);
305 	CLEAN(tmp_buf);
306 	CLEAN(empty_string);
307 	CLEAN(cond_check_buf);
308 
309 	CLEAN(srvconf.errorlog_file);
310 	CLEAN(srvconf.breakagelog_file);
311 	CLEAN(srvconf.groupname);
312 	CLEAN(srvconf.username);
313 	CLEAN(srvconf.changeroot);
314 	CLEAN(srvconf.bindhost);
315 	CLEAN(srvconf.event_handler);
316 	CLEAN(srvconf.pid_file);
317 	CLEAN(srvconf.modules_dir);
318 	CLEAN(srvconf.network_backend);
319 	CLEAN(srvconf.xattr_name);
320 
321 	CLEAN(tmp_chunk_len);
322 #undef CLEAN
323 
324 #if 0
325 	fdevent_unregister(srv->ev, srv->fd);
326 #endif
327 	fdevent_free(srv->ev);
328 
329 	free(srv->conns);
330 
331 	if (srv->config_storage) {
332 		for (i = 0; i < srv->config_context->used; i++) {
333 			specific_config *s = srv->config_storage[i];
334 
335 			if (!s) continue;
336 
337 			buffer_free(s->document_root);
338 			buffer_free(s->server_name);
339 			buffer_free(s->server_tag);
340 			buffer_free(s->ssl_pemfile);
341 			buffer_free(s->ssl_ca_file);
342 			buffer_free(s->ssl_cipher_list);
343 			buffer_free(s->ssl_dh_file);
344 			buffer_free(s->ssl_ec_curve);
345 			buffer_free(s->error_handler);
346 			buffer_free(s->error_handler_404);
347 			buffer_free(s->errorfile_prefix);
348 			array_free(s->mimetypes);
349 			buffer_free(s->ssl_verifyclient_username);
350 #ifdef USE_OPENSSL
351 			SSL_CTX_free(s->ssl_ctx);
352 			EVP_PKEY_free(s->ssl_pemfile_pkey);
353 			X509_free(s->ssl_pemfile_x509);
354 			if (NULL != s->ssl_ca_file_cert_names) sk_X509_NAME_pop_free(s->ssl_ca_file_cert_names, X509_NAME_free);
355 #endif
356 			free(s);
357 		}
358 		free(srv->config_storage);
359 		srv->config_storage = NULL;
360 	}
361 
362 #define CLEAN(x) \
363 	array_free(srv->x);
364 
365 	CLEAN(config_context);
366 	CLEAN(config_touched);
367 	CLEAN(status);
368 	CLEAN(srvconf.upload_tempdirs);
369 #undef CLEAN
370 
371 	joblist_free(srv, srv->joblist);
372 	fdwaitqueue_free(srv, srv->fdwaitqueue);
373 
374 	if (srv->stat_cache) {
375 		stat_cache_free(srv->stat_cache);
376 	}
377 
378 	array_free(srv->srvconf.modules);
379 	array_free(srv->split_vals);
380 
381 #ifdef USE_OPENSSL
382 	if (srv->ssl_is_init) {
383 		CRYPTO_cleanup_all_ex_data();
384 		ERR_free_strings();
385 	      #if   OPENSSL_VERSION_NUMBER >= 0x10100000L
386 		ERR_remove_thread_state();
387 	      #elif OPENSSL_VERSION_NUMBER >= 0x10000000L
388 		ERR_remove_thread_state(NULL);
389 	      #else
390 		ERR_remove_state(0);
391 	      #endif
392 		EVP_cleanup();
393 	}
394 #endif
395 
396 	free(srv);
397 }
398 
399 static void remove_pid_file(server *srv, int *pid_fd) {
400 	if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= *pid_fd) {
401 		if (0 != ftruncate(*pid_fd, 0)) {
402 			log_error_write(srv, __FILE__, __LINE__, "sbds",
403 					"ftruncate failed for:",
404 					srv->srvconf.pid_file,
405 					errno,
406 					strerror(errno));
407 		}
408 	}
409 	if (0 <= *pid_fd) {
410 		close(*pid_fd);
411 		*pid_fd = -1;
412 	}
413 	if (!buffer_string_is_empty(srv->srvconf.pid_file) &&
414 	    buffer_string_is_empty(srv->srvconf.changeroot)) {
415 		if (0 != unlink(srv->srvconf.pid_file->ptr)) {
416 			if (errno != EACCES && errno != EPERM) {
417 				log_error_write(srv, __FILE__, __LINE__, "sbds",
418 						"unlink failed for:",
419 						srv->srvconf.pid_file,
420 						errno,
421 						strerror(errno));
422 			}
423 		}
424 	}
425 }
426 
427 static void show_version (void) {
428 #ifdef USE_OPENSSL
429 # define TEXT_SSL " (ssl)"
430 #else
431 # define TEXT_SSL
432 #endif
433 	char *b = PACKAGE_DESC TEXT_SSL \
434 " - a light and fast webserver\n" \
435 "Build-Date: " __DATE__ " " __TIME__ "\n";
436 ;
437 #undef TEXT_SSL
438 	write_all(STDOUT_FILENO, b, strlen(b));
439 }
440 
441 static void show_features (void) {
442   const char features[] = ""
443 #ifdef USE_SELECT
444       "\t+ select (generic)\n"
445 #else
446       "\t- select (generic)\n"
447 #endif
448 #ifdef USE_POLL
449       "\t+ poll (Unix)\n"
450 #else
451       "\t- poll (Unix)\n"
452 #endif
453 #ifdef USE_LINUX_SIGIO
454       "\t+ rt-signals (Linux 2.4+)\n"
455 #else
456       "\t- rt-signals (Linux 2.4+)\n"
457 #endif
458 #ifdef USE_LINUX_EPOLL
459       "\t+ epoll (Linux 2.6)\n"
460 #else
461       "\t- epoll (Linux 2.6)\n"
462 #endif
463 #ifdef USE_SOLARIS_DEVPOLL
464       "\t+ /dev/poll (Solaris)\n"
465 #else
466       "\t- /dev/poll (Solaris)\n"
467 #endif
468 #ifdef USE_SOLARIS_PORT
469       "\t+ eventports (Solaris)\n"
470 #else
471       "\t- eventports (Solaris)\n"
472 #endif
473 #ifdef USE_FREEBSD_KQUEUE
474       "\t+ kqueue (FreeBSD)\n"
475 #else
476       "\t- kqueue (FreeBSD)\n"
477 #endif
478 #ifdef USE_LIBEV
479       "\t+ libev (generic)\n"
480 #else
481       "\t- libev (generic)\n"
482 #endif
483       "\nNetwork handler:\n\n"
484 #if defined USE_LINUX_SENDFILE
485       "\t+ linux-sendfile\n"
486 #else
487       "\t- linux-sendfile\n"
488 #endif
489 #if defined USE_FREEBSD_SENDFILE
490       "\t+ freebsd-sendfile\n"
491 #else
492       "\t- freebsd-sendfile\n"
493 #endif
494 #if defined USE_DARWIN_SENDFILE
495       "\t+ darwin-sendfile\n"
496 #else
497       "\t- darwin-sendfile\n"
498 #endif
499 #if defined USE_SOLARIS_SENDFILEV
500       "\t+ solaris-sendfilev\n"
501 #else
502       "\t- solaris-sendfilev\n"
503 #endif
504 #if defined USE_WRITEV
505       "\t+ writev\n"
506 #else
507       "\t- writev\n"
508 #endif
509       "\t+ write\n"
510 #ifdef USE_MMAP
511       "\t+ mmap support\n"
512 #else
513       "\t- mmap support\n"
514 #endif
515       "\nFeatures:\n\n"
516 #ifdef HAVE_IPV6
517       "\t+ IPv6 support\n"
518 #else
519       "\t- IPv6 support\n"
520 #endif
521 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
522       "\t+ zlib support\n"
523 #else
524       "\t- zlib support\n"
525 #endif
526 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
527       "\t+ bzip2 support\n"
528 #else
529       "\t- bzip2 support\n"
530 #endif
531 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT)
532       "\t+ crypt support\n"
533 #else
534       "\t- crypt support\n"
535 #endif
536 #ifdef USE_OPENSSL
537       "\t+ SSL Support\n"
538 #else
539       "\t- SSL Support\n"
540 #endif
541 #ifdef HAVE_LIBPCRE
542       "\t+ PCRE support\n"
543 #else
544       "\t- PCRE support\n"
545 #endif
546 #ifdef HAVE_MYSQL
547       "\t+ mySQL support\n"
548 #else
549       "\t- mySQL support\n"
550 #endif
551 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
552       "\t+ LDAP support\n"
553 #else
554       "\t- LDAP support\n"
555 #endif
556 #ifdef USE_MEMCACHED
557       "\t+ memcached support\n"
558 #else
559       "\t- memcached support\n"
560 #endif
561 #ifdef HAVE_FAM_H
562       "\t+ FAM support\n"
563 #else
564       "\t- FAM support\n"
565 #endif
566 #ifdef HAVE_LUA_H
567       "\t+ LUA support\n"
568 #else
569       "\t- LUA support\n"
570 #endif
571 #ifdef HAVE_LIBXML_H
572       "\t+ xml support\n"
573 #else
574       "\t- xml support\n"
575 #endif
576 #ifdef HAVE_SQLITE3_H
577       "\t+ SQLite support\n"
578 #else
579       "\t- SQLite support\n"
580 #endif
581 #ifdef HAVE_GDBM_H
582       "\t+ GDBM support\n"
583 #else
584       "\t- GDBM support\n"
585 #endif
586       "\n";
587   show_version();
588   printf("\nEvent Handlers:\n\n%s", features);
589 }
590 
591 static void show_help (void) {
592 #ifdef USE_OPENSSL
593 # define TEXT_SSL " (ssl)"
594 #else
595 # define TEXT_SSL
596 #endif
597 	char *b = PACKAGE_DESC TEXT_SSL " ("__DATE__ " " __TIME__ ")" \
598 " - a light and fast webserver\n" \
599 "usage:\n" \
600 " -f <name>  filename of the config-file\n" \
601 " -m <name>  module directory (default: "LIBRARY_DIR")\n" \
602 " -p         print the parsed config-file in internal form, and exit\n" \
603 " -t         test the config-file, and exit\n" \
604 " -D         don't go to background (default: go to background)\n" \
605 " -v         show version\n" \
606 " -V         show compile-time features\n" \
607 " -h         show this help\n" \
608 "\n"
609 ;
610 #undef TEXT_SSL
611 #undef TEXT_IPV6
612 	write_all(STDOUT_FILENO, b, strlen(b));
613 }
614 
615 int main (int argc, char **argv) {
616 	server *srv = NULL;
617 	int print_config = 0;
618 	int test_config = 0;
619 	int i_am_root;
620 	int o;
621 	int num_childs = 0;
622 	int pid_fd = -1, fd;
623 	size_t i;
624 #ifdef HAVE_SIGACTION
625 	struct sigaction act;
626 #endif
627 #ifdef HAVE_GETRLIMIT
628 	struct rlimit rlim;
629 #endif
630 
631 #ifdef HAVE_FORK
632 	int parent_pipe_fd = -1;
633 #endif
634 
635 #ifdef USE_ALARM
636 	struct itimerval interval;
637 
638 	interval.it_interval.tv_sec = 1;
639 	interval.it_interval.tv_usec = 0;
640 	interval.it_value.tv_sec = 1;
641 	interval.it_value.tv_usec = 0;
642 #endif
643 
644 	/* for nice %b handling in strfime() */
645 	setlocale(LC_TIME, "C");
646 
647 	if (NULL == (srv = server_init())) {
648 		fprintf(stderr, "did this really happen?\n");
649 		return -1;
650 	}
651 
652 	/* init structs done */
653 
654 	srv->srvconf.port = 0;
655 #ifdef HAVE_GETUID
656 	i_am_root = (getuid() == 0);
657 #else
658 	i_am_root = 0;
659 #endif
660 	srv->srvconf.dont_daemonize = 0;
661 	srv->srvconf.preflight_check = 0;
662 
663 	while(-1 != (o = getopt(argc, argv, "f:m:hvVDpt"))) {
664 		switch(o) {
665 		case 'f':
666 			if (srv->config_storage) {
667 				log_error_write(srv, __FILE__, __LINE__, "s",
668 						"Can only read one config file. Use the include command to use multiple config files.");
669 
670 				server_free(srv);
671 				return -1;
672 			}
673 			if (config_read(srv, optarg)) {
674 				server_free(srv);
675 				return -1;
676 			}
677 			break;
678 		case 'm':
679 			buffer_copy_string(srv->srvconf.modules_dir, optarg);
680 			break;
681 		case 'p': print_config = 1; break;
682 		case 't': ++test_config; break;
683 		case 'D': srv->srvconf.dont_daemonize = 1; break;
684 		case 'v': show_version(); server_free(srv); return 0;
685 		case 'V': show_features(); server_free(srv); return 0;
686 		case 'h': show_help(); server_free(srv); return 0;
687 		default:
688 			show_help();
689 			server_free(srv);
690 			return -1;
691 		}
692 	}
693 
694 	if (!srv->config_storage) {
695 		log_error_write(srv, __FILE__, __LINE__, "s",
696 				"No configuration available. Try using -f option.");
697 
698 		server_free(srv);
699 		return -1;
700 	}
701 
702 	if (print_config) {
703 		data_unset *dc = srv->config_context->data[0];
704 		if (dc) {
705 			dc->print(dc, 0);
706 			fprintf(stdout, "\n");
707 		} else {
708 			/* shouldn't happend */
709 			fprintf(stderr, "global config not found\n");
710 		}
711 	}
712 
713 	if (test_config) {
714 		if (1 == test_config) {
715 			printf("Syntax OK\n");
716 		} else { /*(test_config > 1)*/
717 			test_config = 0;
718 			srv->srvconf.preflight_check = 1;
719 			srv->srvconf.dont_daemonize = 1;
720 			buffer_reset(srv->srvconf.pid_file);
721 		}
722 	}
723 
724 	if (test_config || print_config) {
725 		server_free(srv);
726 		return 0;
727 	}
728 
729 	/* close stdin and stdout, as they are not needed */
730 	openDevNull(STDIN_FILENO);
731 	openDevNull(STDOUT_FILENO);
732 
733 	if (0 != config_set_defaults(srv)) {
734 		log_error_write(srv, __FILE__, __LINE__, "s",
735 				"setting default values failed");
736 		server_free(srv);
737 		return -1;
738 	}
739 
740 	/* UID handling */
741 #ifdef HAVE_GETUID
742 	if (!i_am_root && issetugid()) {
743 		/* we are setuid-root */
744 
745 		log_error_write(srv, __FILE__, __LINE__, "s",
746 				"Are you nuts ? Don't apply a SUID bit to this binary");
747 
748 		server_free(srv);
749 		return -1;
750 	}
751 #endif
752 
753 	/* check document-root */
754 	if (buffer_string_is_empty(srv->config_storage[0]->document_root)) {
755 		log_error_write(srv, __FILE__, __LINE__, "s",
756 				"document-root is not set\n");
757 
758 		server_free(srv);
759 
760 		return -1;
761 	}
762 
763 	if (plugins_load(srv)) {
764 		log_error_write(srv, __FILE__, __LINE__, "s",
765 				"loading plugins finally failed");
766 
767 		plugins_free(srv);
768 		server_free(srv);
769 
770 		return -1;
771 	}
772 
773 	/* open pid file BEFORE chroot */
774 	if (!buffer_string_is_empty(srv->srvconf.pid_file)) {
775 		if (-1 == (pid_fd = open(srv->srvconf.pid_file->ptr, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
776 			struct stat st;
777 			if (errno != EEXIST) {
778 				log_error_write(srv, __FILE__, __LINE__, "sbs",
779 					"opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
780 				return -1;
781 			}
782 
783 			if (0 != stat(srv->srvconf.pid_file->ptr, &st)) {
784 				log_error_write(srv, __FILE__, __LINE__, "sbs",
785 						"stating existing pid-file failed:", srv->srvconf.pid_file, strerror(errno));
786 			}
787 
788 			if (!S_ISREG(st.st_mode)) {
789 				log_error_write(srv, __FILE__, __LINE__, "sb",
790 						"pid-file exists and isn't regular file:", srv->srvconf.pid_file);
791 				return -1;
792 			}
793 
794 			if (-1 == (pid_fd = open(srv->srvconf.pid_file->ptr, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
795 				log_error_write(srv, __FILE__, __LINE__, "sbs",
796 						"opening pid-file failed:", srv->srvconf.pid_file, strerror(errno));
797 				return -1;
798 			}
799 		}
800 		fd_close_on_exec(pid_fd);
801 	}
802 
803 	if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
804 		/* select limits itself
805 		 *
806 		 * as it is a hard limit and will lead to a segfault we add some safety
807 		 * */
808 		srv->max_fds = FD_SETSIZE - 200;
809 	} else {
810 		srv->max_fds = 4096;
811 	}
812 
813 	if (i_am_root) {
814 		struct group *grp = NULL;
815 		struct passwd *pwd = NULL;
816 		int use_rlimit = 1;
817 
818 #ifdef HAVE_VALGRIND_VALGRIND_H
819 		if (RUNNING_ON_VALGRIND) use_rlimit = 0;
820 #endif
821 
822 #ifdef HAVE_GETRLIMIT
823 		if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
824 			log_error_write(srv, __FILE__, __LINE__,
825 					"ss", "couldn't get 'max filedescriptors'",
826 					strerror(errno));
827 			return -1;
828 		}
829 
830 		if (use_rlimit && srv->srvconf.max_fds) {
831 			/* set rlimits */
832 
833 			rlim.rlim_cur = srv->srvconf.max_fds;
834 			rlim.rlim_max = srv->srvconf.max_fds;
835 
836 			if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
837 				log_error_write(srv, __FILE__, __LINE__,
838 						"ss", "couldn't set 'max filedescriptors'",
839 						strerror(errno));
840 				return -1;
841 			}
842 		}
843 
844 		if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
845 			srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200;
846 		} else {
847 			srv->max_fds = rlim.rlim_cur;
848 		}
849 
850 		/* set core file rlimit, if enable_cores is set */
851 		if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
852 			rlim.rlim_cur = rlim.rlim_max;
853 			setrlimit(RLIMIT_CORE, &rlim);
854 		}
855 #endif
856 		if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
857 			/* don't raise the limit above FD_SET_SIZE */
858 			if (srv->max_fds > ((int)FD_SETSIZE) - 200) {
859 				log_error_write(srv, __FILE__, __LINE__, "sd",
860 						"can't raise max filedescriptors above",  FD_SETSIZE - 200,
861 						"if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
862 				return -1;
863 			}
864 		}
865 
866 
867 #ifdef HAVE_PWD_H
868 		/* set user and group */
869 		if (!buffer_string_is_empty(srv->srvconf.username)) {
870 			if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
871 				log_error_write(srv, __FILE__, __LINE__, "sb",
872 						"can't find username", srv->srvconf.username);
873 				return -1;
874 			}
875 
876 			if (pwd->pw_uid == 0) {
877 				log_error_write(srv, __FILE__, __LINE__, "s",
878 						"I will not set uid to 0\n");
879 				return -1;
880 			}
881 		}
882 
883 		if (!buffer_string_is_empty(srv->srvconf.groupname)) {
884 			if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
885 				log_error_write(srv, __FILE__, __LINE__, "sb",
886 					"can't find groupname", srv->srvconf.groupname);
887 				return -1;
888 			}
889 			if (grp->gr_gid == 0) {
890 				log_error_write(srv, __FILE__, __LINE__, "s",
891 						"I will not set gid to 0\n");
892 				return -1;
893 			}
894 		}
895 #endif
896 		/* we need root-perms for port < 1024 */
897 		if (0 != network_init(srv)) {
898 			plugins_free(srv);
899 			server_free(srv);
900 
901 			return -1;
902 		}
903 #ifdef HAVE_PWD_H
904 		/*
905 		 * Change group before chroot, when we have access
906 		 * to /etc/group
907 		 * */
908 		if (NULL != grp) {
909 			if (-1 == setgid(grp->gr_gid)) {
910 				log_error_write(srv, __FILE__, __LINE__, "ss", "setgid failed: ", strerror(errno));
911 				return -1;
912 			}
913 			if (-1 == setgroups(0, NULL)) {
914 				log_error_write(srv, __FILE__, __LINE__, "ss", "setgroups failed: ", strerror(errno));
915 				return -1;
916 			}
917 			if (!buffer_string_is_empty(srv->srvconf.username)) {
918 				initgroups(srv->srvconf.username->ptr, grp->gr_gid);
919 			}
920 		}
921 #endif
922 #ifdef HAVE_CHROOT
923 		if (!buffer_string_is_empty(srv->srvconf.changeroot)) {
924 			tzset();
925 
926 			if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
927 				log_error_write(srv, __FILE__, __LINE__, "ss", "chroot failed: ", strerror(errno));
928 				return -1;
929 			}
930 			if (-1 == chdir("/")) {
931 				log_error_write(srv, __FILE__, __LINE__, "ss", "chdir failed: ", strerror(errno));
932 				return -1;
933 			}
934 		}
935 #endif
936 #ifdef HAVE_PWD_H
937 		/* drop root privs */
938 		if (NULL != pwd) {
939 			if (-1 == setuid(pwd->pw_uid)) {
940 				log_error_write(srv, __FILE__, __LINE__, "ss", "setuid failed: ", strerror(errno));
941 				return -1;
942 			}
943 		}
944 #endif
945 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
946 		/**
947 		 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
948 		 */
949 		if (srv->srvconf.enable_cores) {
950 			prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
951 		}
952 #endif
953 	} else {
954 
955 #ifdef HAVE_GETRLIMIT
956 		if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
957 			log_error_write(srv, __FILE__, __LINE__,
958 					"ss", "couldn't get 'max filedescriptors'",
959 					strerror(errno));
960 			return -1;
961 		}
962 
963 		/**
964 		 * we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
965 		 */
966 		if (srv->srvconf.max_fds && srv->srvconf.max_fds <= rlim.rlim_max) {
967 			/* set rlimits */
968 
969 			rlim.rlim_cur = srv->srvconf.max_fds;
970 
971 			if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
972 				log_error_write(srv, __FILE__, __LINE__,
973 						"ss", "couldn't set 'max filedescriptors'",
974 						strerror(errno));
975 				return -1;
976 			}
977 		}
978 
979 		if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
980 			srv->max_fds = rlim.rlim_cur < (rlim_t)FD_SETSIZE - 200 ? (int)rlim.rlim_cur : (int)FD_SETSIZE - 200;
981 		} else {
982 			srv->max_fds = rlim.rlim_cur;
983 		}
984 
985 		/* set core file rlimit, if enable_cores is set */
986 		if (srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
987 			rlim.rlim_cur = rlim.rlim_max;
988 			setrlimit(RLIMIT_CORE, &rlim);
989 		}
990 
991 #endif
992 		if (srv->event_handler == FDEVENT_HANDLER_SELECT) {
993 			/* don't raise the limit above FD_SET_SIZE */
994 			if (srv->max_fds > ((int)FD_SETSIZE) - 200) {
995 				log_error_write(srv, __FILE__, __LINE__, "sd",
996 						"can't raise max filedescriptors above",  FD_SETSIZE - 200,
997 						"if event-handler is 'select'. Use 'poll' or something else or reduce server.max-fds.");
998 				return -1;
999 			}
1000 		}
1001 
1002 		if (0 != network_init(srv)) {
1003 			plugins_free(srv);
1004 			server_free(srv);
1005 
1006 			return -1;
1007 		}
1008 	}
1009 
1010 	/* set max-conns */
1011 	if (srv->srvconf.max_conns > srv->max_fds/2) {
1012 		/* we can't have more connections than max-fds/2 */
1013 		log_error_write(srv, __FILE__, __LINE__, "sdd", "can't have more connections than fds/2: ", srv->srvconf.max_conns, srv->max_fds);
1014 		srv->max_conns = srv->max_fds/2;
1015 	} else if (srv->srvconf.max_conns) {
1016 		/* otherwise respect the wishes of the user */
1017 		srv->max_conns = srv->srvconf.max_conns;
1018 	} else {
1019 		/* or use the default: we really don't want to hit max-fds */
1020 		srv->max_conns = srv->max_fds/3;
1021 	}
1022 
1023 	if (HANDLER_GO_ON != plugins_call_init(srv)) {
1024 		log_error_write(srv, __FILE__, __LINE__, "s", "Initialization of plugins failed. Going down.");
1025 
1026 		plugins_free(srv);
1027 		network_close(srv);
1028 		server_free(srv);
1029 
1030 		return -1;
1031 	}
1032 
1033 #ifdef HAVE_FORK
1034 	/* network is up, let's deamonize ourself */
1035 	if (srv->srvconf.dont_daemonize == 0) {
1036 		parent_pipe_fd = daemonize();
1037 	}
1038 #endif
1039 
1040 
1041 #ifdef HAVE_SIGACTION
1042 	memset(&act, 0, sizeof(act));
1043 	act.sa_handler = SIG_IGN;
1044 	sigaction(SIGPIPE, &act, NULL);
1045 	sigaction(SIGUSR1, &act, NULL);
1046 # if defined(SA_SIGINFO)
1047 	act.sa_sigaction = sigaction_handler;
1048 	sigemptyset(&act.sa_mask);
1049 	act.sa_flags = SA_SIGINFO;
1050 # else
1051 	act.sa_handler = signal_handler;
1052 	sigemptyset(&act.sa_mask);
1053 	act.sa_flags = 0;
1054 # endif
1055 	sigaction(SIGINT,  &act, NULL);
1056 	sigaction(SIGTERM, &act, NULL);
1057 	sigaction(SIGHUP,  &act, NULL);
1058 	sigaction(SIGALRM, &act, NULL);
1059 
1060 	/* it should be safe to restart syscalls after SIGCHLD */
1061 	act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
1062 	sigaction(SIGCHLD, &act, NULL);
1063 
1064 #elif defined(HAVE_SIGNAL)
1065 	/* ignore the SIGPIPE from sendfile() */
1066 	signal(SIGPIPE, SIG_IGN);
1067 	signal(SIGUSR1, SIG_IGN);
1068 	signal(SIGALRM, signal_handler);
1069 	signal(SIGTERM, signal_handler);
1070 	signal(SIGHUP,  signal_handler);
1071 	signal(SIGCHLD,  signal_handler);
1072 	signal(SIGINT,  signal_handler);
1073 #endif
1074 
1075 #ifdef USE_ALARM
1076 	signal(SIGALRM, signal_handler);
1077 
1078 	/* setup periodic timer (1 second) */
1079 	if (setitimer(ITIMER_REAL, &interval, NULL)) {
1080 		log_error_write(srv, __FILE__, __LINE__, "s", "setting timer failed");
1081 		return -1;
1082 	}
1083 
1084 	getitimer(ITIMER_REAL, &interval);
1085 #endif
1086 
1087 
1088 	srv->gid = getgid();
1089 	srv->uid = getuid();
1090 
1091 	/* write pid file */
1092 	if (pid_fd != -1) {
1093 		buffer_copy_int(srv->tmp_buf, getpid());
1094 		buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("\n"));
1095 		if (-1 == write_all(pid_fd, CONST_BUF_LEN(srv->tmp_buf))) {
1096 			log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't write pid file:", strerror(errno));
1097 			close(pid_fd);
1098 			return -1;
1099 		}
1100 	}
1101 
1102 	/* Close stderr ASAP in the child process to make sure that nothing
1103 	 * is being written to that fd which may not be valid anymore. */
1104 	if (!srv->srvconf.preflight_check && -1 == log_error_open(srv)) {
1105 		log_error_write(srv, __FILE__, __LINE__, "s", "Opening errorlog failed. Going down.");
1106 
1107 		plugins_free(srv);
1108 		network_close(srv);
1109 		server_free(srv);
1110 		return -1;
1111 	}
1112 
1113 	if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1114 		log_error_write(srv, __FILE__, __LINE__, "s", "Configuration of plugins failed. Going down.");
1115 
1116 		plugins_free(srv);
1117 		network_close(srv);
1118 		server_free(srv);
1119 
1120 		return -1;
1121 	}
1122 
1123 	/* dump unused config-keys */
1124 	for (i = 0; i < srv->config_context->used; i++) {
1125 		array *config = ((data_config *)srv->config_context->data[i])->value;
1126 		size_t j;
1127 
1128 		for (j = 0; config && j < config->used; j++) {
1129 			data_unset *du = config->data[j];
1130 
1131 			/* all var.* is known as user defined variable */
1132 			if (strncmp(du->key->ptr, "var.", sizeof("var.") - 1) == 0) {
1133 				continue;
1134 			}
1135 
1136 			if (NULL == array_get_element(srv->config_touched, du->key->ptr)) {
1137 				log_error_write(srv, __FILE__, __LINE__, "sbs",
1138 						"WARNING: unknown config-key:",
1139 						du->key,
1140 						"(ignored)");
1141 			}
1142 		}
1143 	}
1144 
1145 	if (srv->config_unsupported) {
1146 		log_error_write(srv, __FILE__, __LINE__, "s",
1147 				"Configuration contains unsupported keys. Going down.");
1148 	}
1149 
1150 	if (srv->config_deprecated) {
1151 		log_error_write(srv, __FILE__, __LINE__, "s",
1152 				"Configuration contains deprecated keys. Going down.");
1153 	}
1154 
1155 	if (srv->config_unsupported || srv->config_deprecated) {
1156 		plugins_free(srv);
1157 		network_close(srv);
1158 		server_free(srv);
1159 
1160 		return -1;
1161 	}
1162 
1163 	if (srv->srvconf.preflight_check) {
1164 		/*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1165 		plugins_free(srv);
1166 		network_close(srv);
1167 		server_free(srv);
1168 
1169 		exit(0);
1170 	}
1171 
1172 
1173 #ifdef HAVE_FORK
1174 	/**
1175 	 * notify daemonize-grandparent of successful startup
1176 	 * do this before any further forking is done (workers)
1177 	 */
1178 	if (srv->srvconf.dont_daemonize == 0) {
1179 		if (0 > write(parent_pipe_fd, "", 1)) return -1;
1180 		close(parent_pipe_fd);
1181 	}
1182 
1183 	/* start watcher and workers */
1184 	num_childs = srv->srvconf.max_worker;
1185 	if (num_childs > 0) {
1186 		int child = 0;
1187 		while (!child && !srv_shutdown && !graceful_shutdown) {
1188 			if (num_childs > 0) {
1189 				switch (fork()) {
1190 				case -1:
1191 					return -1;
1192 				case 0:
1193 					child = 1;
1194 					break;
1195 				default:
1196 					num_childs--;
1197 					break;
1198 				}
1199 			} else {
1200 				int status;
1201 
1202 				if (-1 != wait(&status)) {
1203 					/**
1204 					 * one of our workers went away
1205 					 */
1206 					num_childs++;
1207 				} else {
1208 					switch (errno) {
1209 					case EINTR:
1210 						/**
1211 						 * if we receive a SIGHUP we have to close our logs ourself as we don't
1212 						 * have the mainloop who can help us here
1213 						 */
1214 						if (handle_sig_hup) {
1215 							handle_sig_hup = 0;
1216 
1217 							log_error_cycle(srv);
1218 
1219 							/**
1220 							 * forward to all procs in the process-group
1221 							 *
1222 							 * we also send it ourself
1223 							 */
1224 							if (!forwarded_sig_hup && 0 != srv->srvconf.max_worker) {
1225 								forwarded_sig_hup = 1;
1226 								kill(0, SIGHUP);
1227 							}
1228 						}
1229 						break;
1230 					default:
1231 						break;
1232 					}
1233 				}
1234 			}
1235 		}
1236 
1237 		/**
1238 		 * for the parent this is the exit-point
1239 		 */
1240 		if (!child) {
1241 			/**
1242 			 * kill all children too
1243 			 */
1244 			if (graceful_shutdown) {
1245 				kill(0, SIGINT);
1246 			} else if (srv_shutdown) {
1247 				kill(0, SIGTERM);
1248 			}
1249 
1250 			remove_pid_file(srv, &pid_fd);
1251 			log_error_close(srv);
1252 			network_close(srv);
1253 			connections_free(srv);
1254 			plugins_free(srv);
1255 			server_free(srv);
1256 			return 0;
1257 		}
1258 
1259 		/**
1260 		 * make sure workers do not muck with pid-file
1261 		 */
1262 		if (0 <= pid_fd) {
1263 			close(pid_fd);
1264 			pid_fd = -1;
1265 		}
1266 		buffer_reset(srv->srvconf.pid_file);
1267 	}
1268 #endif
1269 
1270 	if (NULL == (srv->ev = fdevent_init(srv, srv->max_fds + 1, srv->event_handler))) {
1271 		log_error_write(srv, __FILE__, __LINE__,
1272 				"s", "fdevent_init failed");
1273 		return -1;
1274 	}
1275 
1276 	/* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */
1277 #ifdef HAVE_SIGACTION
1278 	sigaction(SIGCHLD, &act, NULL);
1279 #elif defined(HAVE_SIGNAL)
1280 	signal(SIGCHLD,  signal_handler);
1281 #endif
1282 
1283 	/*
1284 	 * kqueue() is called here, select resets its internals,
1285 	 * all server sockets get their handlers
1286 	 *
1287 	 * */
1288 	if (0 != network_register_fdevents(srv)) {
1289 		plugins_free(srv);
1290 		network_close(srv);
1291 		server_free(srv);
1292 
1293 		return -1;
1294 	}
1295 
1296 	/* might fail if user is using fam (not gamin) and famd isn't running */
1297 	if (NULL == (srv->stat_cache = stat_cache_init())) {
1298 		log_error_write(srv, __FILE__, __LINE__, "s",
1299 			"stat-cache could not be setup, dieing.");
1300 		return -1;
1301 	}
1302 
1303 #ifdef HAVE_FAM_H
1304 	/* setup FAM */
1305 	if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_FAM) {
1306 		if (0 != FAMOpen2(&srv->stat_cache->fam, "lighttpd")) {
1307 			log_error_write(srv, __FILE__, __LINE__, "s",
1308 					 "could not open a fam connection, dieing.");
1309 			return -1;
1310 		}
1311 #ifdef HAVE_FAMNOEXISTS
1312 		FAMNoExists(&srv->stat_cache->fam);
1313 #endif
1314 
1315 		fdevent_register(srv->ev, FAMCONNECTION_GETFD(&srv->stat_cache->fam), stat_cache_handle_fdevent, NULL);
1316 		fdevent_event_set(srv->ev, &(srv->stat_cache->fam_fcce_ndx), FAMCONNECTION_GETFD(&srv->stat_cache->fam), FDEVENT_IN);
1317 	}
1318 #endif
1319 
1320 
1321 	/* get the current number of FDs */
1322 	srv->cur_fds = open("/dev/null", O_RDONLY);
1323 	close(srv->cur_fds);
1324 
1325 	for (i = 0; i < srv->srv_sockets.used; i++) {
1326 		server_socket *srv_socket = srv->srv_sockets.ptr[i];
1327 		if (-1 == fdevent_fcntl_set(srv->ev, srv_socket->fd)) {
1328 			log_error_write(srv, __FILE__, __LINE__, "ss", "fcntl failed:", strerror(errno));
1329 			return -1;
1330 		}
1331 	}
1332 
1333 	/* main-loop */
1334 	while (!srv_shutdown) {
1335 		int n;
1336 		size_t ndx;
1337 		time_t min_ts;
1338 
1339 		if (handle_sig_hup) {
1340 			handler_t r;
1341 
1342 			/* reset notification */
1343 			handle_sig_hup = 0;
1344 
1345 
1346 			/* cycle logfiles */
1347 
1348 			switch(r = plugins_call_handle_sighup(srv)) {
1349 			case HANDLER_GO_ON:
1350 				break;
1351 			default:
1352 				log_error_write(srv, __FILE__, __LINE__, "sd", "sighup-handler return with an error", r);
1353 				break;
1354 			}
1355 
1356 			if (-1 == log_error_cycle(srv)) {
1357 				log_error_write(srv, __FILE__, __LINE__, "s", "cycling errorlog failed, dying");
1358 
1359 				return -1;
1360 			} else {
1361 #ifdef HAVE_SIGACTION
1362 				log_error_write(srv, __FILE__, __LINE__, "sdsd",
1363 					"logfiles cycled UID =",
1364 					last_sighup_info.si_uid,
1365 					"PID =",
1366 					last_sighup_info.si_pid);
1367 #else
1368 				log_error_write(srv, __FILE__, __LINE__, "s",
1369 					"logfiles cycled");
1370 #endif
1371 			}
1372 		}
1373 
1374 		if (handle_sig_alarm) {
1375 			/* a new second */
1376 
1377 #ifdef USE_ALARM
1378 			/* reset notification */
1379 			handle_sig_alarm = 0;
1380 #endif
1381 
1382 			/* get current time */
1383 			min_ts = time(NULL);
1384 
1385 			if (min_ts != srv->cur_ts) {
1386 #ifdef DEBUG_CONNECTION_STATES
1387 				int cs = 0;
1388 #endif
1389 				connections *conns = srv->conns;
1390 				handler_t r;
1391 
1392 				switch(r = plugins_call_handle_trigger(srv)) {
1393 				case HANDLER_GO_ON:
1394 					break;
1395 				case HANDLER_ERROR:
1396 					log_error_write(srv, __FILE__, __LINE__, "s", "one of the triggers failed");
1397 					break;
1398 				default:
1399 					log_error_write(srv, __FILE__, __LINE__, "d", r);
1400 					break;
1401 				}
1402 
1403 				/* trigger waitpid */
1404 				srv->cur_ts = min_ts;
1405 
1406 				/* cleanup stat-cache */
1407 				stat_cache_trigger_cleanup(srv);
1408 				/**
1409 				 * check all connections for timeouts
1410 				 *
1411 				 */
1412 				for (ndx = 0; ndx < conns->used; ndx++) {
1413 					int changed = 0;
1414 					connection *con;
1415 					int t_diff;
1416 
1417 					con = conns->ptr[ndx];
1418 
1419 					if (con->state == CON_STATE_READ ||
1420 					    con->state == CON_STATE_READ_POST) {
1421 						if (con->request_count == 1 || con->state == CON_STATE_READ_POST) {
1422 							if (srv->cur_ts - con->read_idle_ts > con->conf.max_read_idle) {
1423 								/* time - out */
1424 								if (con->conf.log_request_handling) {
1425 									log_error_write(srv, __FILE__, __LINE__, "sd",
1426 										"connection closed - read timeout:", con->fd);
1427 								}
1428 
1429 								connection_set_state(srv, con, CON_STATE_ERROR);
1430 								changed = 1;
1431 							}
1432 						} else {
1433 							if (srv->cur_ts - con->read_idle_ts > con->keep_alive_idle) {
1434 								/* time - out */
1435 								if (con->conf.log_request_handling) {
1436 									log_error_write(srv, __FILE__, __LINE__, "sd",
1437 										"connection closed - keep-alive timeout:", con->fd);
1438 								}
1439 
1440 								connection_set_state(srv, con, CON_STATE_ERROR);
1441 								changed = 1;
1442 							}
1443 						}
1444 					}
1445 
1446 					if ((con->state == CON_STATE_WRITE) &&
1447 					    (con->write_request_ts != 0)) {
1448 #if 0
1449 						if (srv->cur_ts - con->write_request_ts > 60) {
1450 							log_error_write(srv, __FILE__, __LINE__, "sdd",
1451 									"connection closed - pre-write-request-timeout:", con->fd, srv->cur_ts - con->write_request_ts);
1452 						}
1453 #endif
1454 
1455 						if (srv->cur_ts - con->write_request_ts > con->conf.max_write_idle) {
1456 							/* time - out */
1457 							if (con->conf.log_timeouts) {
1458 								log_error_write(srv, __FILE__, __LINE__, "sbsbsosds",
1459 									"NOTE: a request from",
1460 									con->dst_addr_buf,
1461 									"for",
1462 									con->request.uri,
1463 									"timed out after writing",
1464 									con->bytes_written,
1465 									"bytes. We waited",
1466 									(int)con->conf.max_write_idle,
1467 									"seconds. If this a problem increase server.max-write-idle");
1468 							}
1469 							connection_set_state(srv, con, CON_STATE_ERROR);
1470 							changed = 1;
1471 						}
1472 					}
1473 
1474 					if (con->state == CON_STATE_CLOSE && (srv->cur_ts - con->close_timeout_ts > HTTP_LINGER_TIMEOUT)) {
1475 						changed = 1;
1476 					}
1477 
1478 					/* we don't like div by zero */
1479 					if (0 == (t_diff = srv->cur_ts - con->connection_start)) t_diff = 1;
1480 
1481 					if (con->traffic_limit_reached &&
1482 					    (con->conf.kbytes_per_second == 0 ||
1483 					     ((con->bytes_written / t_diff) < con->conf.kbytes_per_second * 1024))) {
1484 						/* enable connection again */
1485 						con->traffic_limit_reached = 0;
1486 
1487 						changed = 1;
1488 					}
1489 
1490 					if (changed) {
1491 						connection_state_machine(srv, con);
1492 					}
1493 					con->bytes_written_cur_second = 0;
1494 					*(con->conf.global_bytes_per_second_cnt_ptr) = 0;
1495 
1496 #if DEBUG_CONNECTION_STATES
1497 					if (cs == 0) {
1498 						fprintf(stderr, "connection-state: ");
1499 						cs = 1;
1500 					}
1501 
1502 					fprintf(stderr, "c[%d,%d]: %s ",
1503 						con->fd,
1504 						con->fcgi.fd,
1505 						connection_get_state(con->state));
1506 #endif
1507 				}
1508 
1509 #ifdef DEBUG_CONNECTION_STATES
1510 				if (cs == 1) fprintf(stderr, "\n");
1511 #endif
1512 			}
1513 		}
1514 
1515 		if (srv->sockets_disabled) {
1516 			/* our server sockets are disabled, why ? */
1517 
1518 			if ((srv->cur_fds + srv->want_fds < srv->max_fds * 8 / 10) && /* we have enough unused fds */
1519 			    (srv->conns->used <= srv->max_conns * 9 / 10) &&
1520 			    (0 == graceful_shutdown)) {
1521 				for (i = 0; i < srv->srv_sockets.used; i++) {
1522 					server_socket *srv_socket = srv->srv_sockets.ptr[i];
1523 					fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, FDEVENT_IN);
1524 				}
1525 
1526 				log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets enabled again");
1527 
1528 				srv->sockets_disabled = 0;
1529 			}
1530 		} else {
1531 			if ((srv->cur_fds + srv->want_fds > srv->max_fds * 9 / 10) || /* out of fds */
1532 			    (srv->conns->used >= srv->max_conns) || /* out of connections */
1533 			    (graceful_shutdown)) { /* graceful_shutdown */
1534 
1535 				/* disable server-fds */
1536 
1537 				for (i = 0; i < srv->srv_sockets.used; i++) {
1538 					server_socket *srv_socket = srv->srv_sockets.ptr[i];
1539 
1540 					if (graceful_shutdown) {
1541 						/* we don't want this socket anymore,
1542 						 *
1543 						 * closing it right away will make it possible for
1544 						 * the next lighttpd to take over (graceful restart)
1545 						 *  */
1546 
1547 						fdevent_event_del(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd);
1548 						fdevent_unregister(srv->ev, srv_socket->fd);
1549 						close(srv_socket->fd);
1550 						srv_socket->fd = -1;
1551 
1552 						/* network_close() will cleanup after us */
1553 					} else {
1554 						fdevent_event_set(srv->ev, &(srv_socket->fde_ndx), srv_socket->fd, 0);
1555 					}
1556 				}
1557 
1558 				if (graceful_shutdown) {
1559 					remove_pid_file(srv, &pid_fd);
1560 					log_error_write(srv, __FILE__, __LINE__, "s", "[note] graceful shutdown started");
1561 				} else if (srv->conns->used >= srv->max_conns) {
1562 					log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, connection limit reached");
1563 				} else {
1564 					log_error_write(srv, __FILE__, __LINE__, "s", "[note] sockets disabled, out-of-fds");
1565 				}
1566 
1567 				srv->sockets_disabled = 1;
1568 			}
1569 		}
1570 
1571 		if (graceful_shutdown && srv->conns->used == 0) {
1572 			/* we are in graceful shutdown phase and all connections are closed
1573 			 * we are ready to terminate without harming anyone */
1574 			srv_shutdown = 1;
1575 		}
1576 
1577 		/* we still have some fds to share */
1578 		if (srv->want_fds) {
1579 			/* check the fdwaitqueue for waiting fds */
1580 			int free_fds = srv->max_fds - srv->cur_fds - 16;
1581 			connection *con;
1582 
1583 			for (; free_fds > 0 && NULL != (con = fdwaitqueue_unshift(srv, srv->fdwaitqueue)); free_fds--) {
1584 				connection_state_machine(srv, con);
1585 
1586 				srv->want_fds--;
1587 			}
1588 		}
1589 
1590 		if ((n = fdevent_poll(srv->ev, 1000)) > 0) {
1591 			/* n is the number of events */
1592 			int revents;
1593 			int fd_ndx;
1594 #if 0
1595 			if (n > 0) {
1596 				log_error_write(srv, __FILE__, __LINE__, "sd",
1597 						"polls:", n);
1598 			}
1599 #endif
1600 			fd_ndx = -1;
1601 			do {
1602 				fdevent_handler handler;
1603 				void *context;
1604 				handler_t r;
1605 
1606 				fd_ndx  = fdevent_event_next_fdndx (srv->ev, fd_ndx);
1607 				if (-1 == fd_ndx) break; /* not all fdevent handlers know how many fds got an event */
1608 
1609 				revents = fdevent_event_get_revent (srv->ev, fd_ndx);
1610 				fd      = fdevent_event_get_fd     (srv->ev, fd_ndx);
1611 				handler = fdevent_get_handler(srv->ev, fd);
1612 				context = fdevent_get_context(srv->ev, fd);
1613 
1614 				/* connection_handle_fdevent needs a joblist_append */
1615 #if 0
1616 				log_error_write(srv, __FILE__, __LINE__, "sdd",
1617 						"event for", fd, revents);
1618 #endif
1619 				switch (r = (*handler)(srv, context, revents)) {
1620 				case HANDLER_FINISHED:
1621 				case HANDLER_GO_ON:
1622 				case HANDLER_WAIT_FOR_EVENT:
1623 				case HANDLER_WAIT_FOR_FD:
1624 					break;
1625 				case HANDLER_ERROR:
1626 					/* should never happen */
1627 					SEGFAULT();
1628 					break;
1629 				default:
1630 					log_error_write(srv, __FILE__, __LINE__, "d", r);
1631 					break;
1632 				}
1633 			} while (--n > 0);
1634 		} else if (n < 0 && errno != EINTR) {
1635 			log_error_write(srv, __FILE__, __LINE__, "ss",
1636 					"fdevent_poll failed:",
1637 					strerror(errno));
1638 		}
1639 
1640 		for (ndx = 0; ndx < srv->joblist->used; ndx++) {
1641 			connection *con = srv->joblist->ptr[ndx];
1642 			connection_state_machine(srv, con);
1643 			con->in_joblist = 0;
1644 		}
1645 
1646 		srv->joblist->used = 0;
1647 	}
1648 
1649 	if (0 == graceful_shutdown) {
1650 		remove_pid_file(srv, &pid_fd);
1651 	}
1652 
1653 #ifdef HAVE_SIGACTION
1654 	log_error_write(srv, __FILE__, __LINE__, "sdsd",
1655 			"server stopped by UID =",
1656 			last_sigterm_info.si_uid,
1657 			"PID =",
1658 			last_sigterm_info.si_pid);
1659 #else
1660 	log_error_write(srv, __FILE__, __LINE__, "s",
1661 			"server stopped");
1662 #endif
1663 
1664 	/* clean-up */
1665 	log_error_close(srv);
1666 	network_close(srv);
1667 	connections_free(srv);
1668 	plugins_free(srv);
1669 	server_free(srv);
1670 
1671 	return 0;
1672 }
1673