xref: /lighttpd1.4/src/mod_fastcgi.c (revision 4eeeb8fc)
1 #include "first.h"
2 
3 #include "buffer.h"
4 #include "server.h"
5 #include "keyvalue.h"
6 #include "log.h"
7 
8 #include "http_chunk.h"
9 #include "fdevent.h"
10 #include "connections.h"
11 #include "response.h"
12 #include "joblist.h"
13 
14 #include "plugin.h"
15 
16 #include "inet_ntop_cache.h"
17 #include "stat_cache.h"
18 #include "status_counter.h"
19 
20 #include <sys/types.h>
21 #include <unistd.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
27 #include <assert.h>
28 #include <signal.h>
29 
30 #ifdef HAVE_FASTCGI_FASTCGI_H
31 # include <fastcgi/fastcgi.h>
32 #else
33 # ifdef HAVE_FASTCGI_H
34 #  include <fastcgi.h>
35 # else
36 #  include "fastcgi.h"
37 # endif
38 #endif /* HAVE_FASTCGI_FASTCGI_H */
39 
40 #include <stdio.h>
41 
42 #include "sys-socket.h"
43 
44 #ifdef HAVE_SYS_UIO_H
45 #include <sys/uio.h>
46 #endif
47 #ifdef HAVE_SYS_WAIT_H
48 #include <sys/wait.h>
49 #endif
50 
51 #include "version.h"
52 
53 /*
54  *
55  * TODO:
56  *
57  * - add timeout for a connect to a non-fastcgi process
58  *   (use state_timestamp + state)
59  *
60  */
61 
62 typedef struct fcgi_proc {
63 	size_t id; /* id will be between 1 and max_procs */
64 	buffer *unixsocket; /* config.socket + "-" + id */
65 	unsigned port;  /* config.port + pno */
66 
67 	buffer *connection_name; /* either tcp:<host>:<port> or unix:<socket> for debugging purposes */
68 
69 	pid_t pid;   /* PID of the spawned process (0 if not spawned locally) */
70 
71 
72 	size_t load; /* number of requests waiting on this process */
73 
74 	size_t requests;  /* see max_requests */
75 	struct fcgi_proc *prev, *next; /* see first */
76 
77 	time_t disabled_until; /* this proc is disabled until, use something else until then */
78 
79 	int is_local;
80 
81 	enum {
82 		PROC_STATE_UNSET,    /* init-phase */
83 		PROC_STATE_RUNNING,  /* alive */
84 		PROC_STATE_OVERLOADED, /* listen-queue is full,
85 					  don't send anything to this proc for the next 2 seconds */
86 		PROC_STATE_DIED_WAIT_FOR_PID, /* */
87 		PROC_STATE_DIED,     /* marked as dead, should be restarted */
88 		PROC_STATE_KILLED    /* was killed as we don't have the load anymore */
89 	} state;
90 } fcgi_proc;
91 
92 typedef struct {
93 	/* the key that is used to reference this value */
94 	buffer *id;
95 
96 	/* list of processes handling this extension
97 	 * sorted by lowest load
98 	 *
99 	 * whenever a job is done move it up in the list
100 	 * until it is sorted, move it down as soon as the
101 	 * job is started
102 	 */
103 	fcgi_proc *first;
104 	fcgi_proc *unused_procs;
105 
106 	/*
107 	 * spawn at least min_procs, at max_procs.
108 	 *
109 	 * as soon as the load of the first entry
110 	 * is max_load_per_proc we spawn a new one
111 	 * and add it to the first entry and give it
112 	 * the load
113 	 *
114 	 */
115 
116 	unsigned short max_procs;
117 	size_t num_procs;    /* how many procs are started */
118 	size_t active_procs; /* how many of them are really running, i.e. state = PROC_STATE_RUNNING */
119 
120 	/*
121 	 * time after a disabled remote connection is tried to be re-enabled
122 	 *
123 	 *
124 	 */
125 
126 	unsigned short disable_time;
127 
128 	/*
129 	 * some fastcgi processes get a little bit larger
130 	 * than wanted. max_requests_per_proc kills a
131 	 * process after a number of handled requests.
132 	 *
133 	 */
134 	size_t max_requests_per_proc;
135 
136 
137 	/* config */
138 
139 	/*
140 	 * host:port
141 	 *
142 	 * if host is one of the local IP adresses the
143 	 * whole connection is local
144 	 *
145 	 * if port is not 0, and host is not specified,
146 	 * "localhost" (INADDR_LOOPBACK) is assumed.
147 	 *
148 	 */
149 	buffer *host;
150 	unsigned short port;
151 	sa_family_t family;
152 
153 	/*
154 	 * Unix Domain Socket
155 	 *
156 	 * instead of TCP/IP we can use Unix Domain Sockets
157 	 * - more secure (you have fileperms to play with)
158 	 * - more control (on locally)
159 	 * - more speed (no extra overhead)
160 	 */
161 	buffer *unixsocket;
162 
163 	/* if socket is local we can start the fastcgi
164 	 * process ourself
165 	 *
166 	 * bin-path is the path to the binary
167 	 *
168 	 * check min_procs and max_procs for the number
169 	 * of process to start up
170 	 */
171 	buffer *bin_path;
172 
173 	/* bin-path is set bin-environment is taken to
174 	 * create the environement before starting the
175 	 * FastCGI process
176 	 *
177 	 */
178 	array *bin_env;
179 
180 	array *bin_env_copy;
181 
182 	/*
183 	 * docroot-translation between URL->phys and the
184 	 * remote host
185 	 *
186 	 * reasons:
187 	 * - different dir-layout if remote
188 	 * - chroot if local
189 	 *
190 	 */
191 	buffer *docroot;
192 
193 	/*
194 	 * fastcgi-mode:
195 	 * - responser
196 	 * - authorizer
197 	 *
198 	 */
199 	unsigned short mode;
200 
201 	/*
202 	 * check_local tells you if the phys file is stat()ed
203 	 * or not. FastCGI doesn't care if the service is
204 	 * remote. If the web-server side doesn't contain
205 	 * the fastcgi-files we should not stat() for them
206 	 * and say '404 not found'.
207 	 */
208 	unsigned short check_local;
209 
210 	/*
211 	 * append PATH_INFO to SCRIPT_FILENAME
212 	 *
213 	 * php needs this if cgi.fix_pathinfo is provided
214 	 *
215 	 */
216 
217 	unsigned short break_scriptfilename_for_php;
218 
219 	/*
220 	 * workaround for program when prefix="/"
221 	 *
222 	 * rule to build PATH_INFO is hardcoded for when check_local is disabled
223 	 * enable this option to use the workaround
224 	 *
225 	 */
226 
227 	unsigned short fix_root_path_name;
228 
229 	/*
230 	 * If the backend includes X-Sendfile in the response
231 	 * we use the value as filename and ignore the content.
232 	 *
233 	 */
234 	unsigned short xsendfile_allow;
235 	array *xsendfile_docroot;
236 
237 	ssize_t load; /* replace by host->load */
238 
239 	size_t max_id; /* corresponds most of the time to
240 	num_procs.
241 
242 	only if a process is killed max_id waits for the process itself
243 	to die and decrements it afterwards */
244 
245 	buffer *strip_request_uri;
246 
247 	unsigned short kill_signal; /* we need a setting for this as libfcgi
248 				       applications prefer SIGUSR1 while the
249 				       rest of the world would use SIGTERM
250 				       *sigh* */
251 
252 	int listen_backlog;
253 } fcgi_extension_host;
254 
255 /*
256  * one extension can have multiple hosts assigned
257  * one host can spawn additional processes on the same
258  *   socket (if we control it)
259  *
260  * ext -> host -> procs
261  *    1:n     1:n
262  *
263  * if the fastcgi process is remote that whole goes down
264  * to
265  *
266  * ext -> host -> procs
267  *    1:n     1:1
268  *
269  * in case of PHP and FCGI_CHILDREN we have again a procs
270  * but we don't control it directly.
271  *
272  */
273 
274 typedef struct {
275 	buffer *key; /* like .php */
276 
277 	int note_is_sent;
278 	int last_used_ndx;
279 
280 	fcgi_extension_host **hosts;
281 
282 	size_t used;
283 	size_t size;
284 } fcgi_extension;
285 
286 typedef struct {
287 	fcgi_extension **exts;
288 
289 	size_t used;
290 	size_t size;
291 } fcgi_exts;
292 
293 
294 typedef struct {
295 	fcgi_exts *exts;
296 
297 	array *ext_mapping;
298 
299 	unsigned int debug;
300 } plugin_config;
301 
302 typedef struct {
303 	char **ptr;
304 
305 	size_t size;
306 	size_t used;
307 } char_array;
308 
309 /* generic plugin data, shared between all connections */
310 typedef struct {
311 	PLUGIN_DATA;
312 
313 	buffer *fcgi_env;
314 
315 	buffer *path;
316 
317 	buffer *statuskey;
318 
319 	plugin_config **config_storage;
320 
321 	plugin_config conf; /* this is only used as long as no handler_ctx is setup */
322 } plugin_data;
323 
324 /* connection specific data */
325 typedef enum {
326 	FCGI_STATE_INIT,
327 	FCGI_STATE_CONNECT_DELAYED,
328 	FCGI_STATE_PREPARE_WRITE,
329 	FCGI_STATE_WRITE,
330 	FCGI_STATE_READ
331 } fcgi_connection_state_t;
332 
333 typedef struct {
334 	fcgi_proc *proc;
335 	fcgi_extension_host *host;
336 	fcgi_extension *ext;
337 
338 	fcgi_connection_state_t state;
339 	time_t   state_timestamp;
340 
341 	int      reconnects; /* number of reconnect attempts */
342 
343 	chunkqueue *rb; /* read queue */
344 	chunkqueue *wb; /* write queue */
345 
346 	buffer   *response_header;
347 
348 	size_t    request_id;
349 	int       fd;        /* fd to the fastcgi process */
350 	int       fde_ndx;   /* index into the fd-event buffer */
351 
352 	pid_t     pid;
353 	int       got_proc;
354 
355 	int       send_content_body;
356 
357 	plugin_config conf;
358 
359 	connection *remote_conn;  /* dumb pointer */
360 	plugin_data *plugin_data; /* dumb pointer */
361 } handler_ctx;
362 
363 
364 /* ok, we need a prototype */
365 static handler_t fcgi_handle_fdevent(server *srv, void *ctx, int revents);
366 
367 static void reset_signals(void) {
368 #ifdef SIGTTOU
369 	signal(SIGTTOU, SIG_DFL);
370 #endif
371 #ifdef SIGTTIN
372 	signal(SIGTTIN, SIG_DFL);
373 #endif
374 #ifdef SIGTSTP
375 	signal(SIGTSTP, SIG_DFL);
376 #endif
377 	signal(SIGHUP, SIG_DFL);
378 	signal(SIGPIPE, SIG_DFL);
379 	signal(SIGUSR1, SIG_DFL);
380 }
381 
382 static void fastcgi_status_copy_procname(buffer *b, fcgi_extension_host *host, fcgi_proc *proc) {
383 	buffer_copy_string_len(b, CONST_STR_LEN("fastcgi.backend."));
384 	buffer_append_string_buffer(b, host->id);
385 	if (proc) {
386 		buffer_append_string_len(b, CONST_STR_LEN("."));
387 		buffer_append_int(b, proc->id);
388 	}
389 }
390 
391 static void fcgi_proc_load_inc(server *srv, handler_ctx *hctx) {
392 	plugin_data *p = hctx->plugin_data;
393 	hctx->proc->load++;
394 
395 	status_counter_inc(srv, CONST_STR_LEN("fastcgi.active-requests"));
396 
397 	fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
398 	buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
399 
400 	status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->proc->load);
401 }
402 
403 static void fcgi_proc_load_dec(server *srv, handler_ctx *hctx) {
404 	plugin_data *p = hctx->plugin_data;
405 	hctx->proc->load--;
406 
407 	status_counter_dec(srv, CONST_STR_LEN("fastcgi.active-requests"));
408 
409 	fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
410 	buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
411 
412 	status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->proc->load);
413 }
414 
415 static void fcgi_host_assign(server *srv, handler_ctx *hctx, fcgi_extension_host *host) {
416 	plugin_data *p = hctx->plugin_data;
417 	hctx->host = host;
418 	hctx->host->load++;
419 
420 	fastcgi_status_copy_procname(p->statuskey, hctx->host, NULL);
421 	buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
422 
423 	status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->host->load);
424 }
425 
426 static void fcgi_host_reset(server *srv, handler_ctx *hctx) {
427 	plugin_data *p = hctx->plugin_data;
428 	hctx->host->load--;
429 
430 	fastcgi_status_copy_procname(p->statuskey, hctx->host, NULL);
431 	buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
432 
433 	status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->host->load);
434 
435 	hctx->host = NULL;
436 }
437 
438 static void fcgi_host_disable(server *srv, handler_ctx *hctx) {
439 	plugin_data *p    = hctx->plugin_data;
440 
441 	if (hctx->host->disable_time || hctx->proc->is_local) {
442 		if (hctx->proc->state == PROC_STATE_RUNNING) hctx->host->active_procs--;
443 		hctx->proc->disabled_until = srv->cur_ts + hctx->host->disable_time;
444 		hctx->proc->state = hctx->proc->is_local ? PROC_STATE_DIED_WAIT_FOR_PID : PROC_STATE_DIED;
445 
446 		if (p->conf.debug) {
447 			log_error_write(srv, __FILE__, __LINE__, "sds",
448 				"backend disabled for", hctx->host->disable_time, "seconds");
449 		}
450 	}
451 }
452 
453 static int fastcgi_status_init(server *srv, buffer *b, fcgi_extension_host *host, fcgi_proc *proc) {
454 #define CLEAN(x) \
455 	fastcgi_status_copy_procname(b, host, proc); \
456 	buffer_append_string_len(b, CONST_STR_LEN(x)); \
457 	status_counter_set(srv, CONST_BUF_LEN(b), 0);
458 
459 	CLEAN(".disabled");
460 	CLEAN(".died");
461 	CLEAN(".overloaded");
462 	CLEAN(".connected");
463 	CLEAN(".load");
464 
465 #undef CLEAN
466 
467 #define CLEAN(x) \
468 	fastcgi_status_copy_procname(b, host, NULL); \
469 	buffer_append_string_len(b, CONST_STR_LEN(x)); \
470 	status_counter_set(srv, CONST_BUF_LEN(b), 0);
471 
472 	CLEAN(".load");
473 
474 #undef CLEAN
475 
476 	return 0;
477 }
478 
479 static handler_ctx * handler_ctx_init(void) {
480 	handler_ctx * hctx;
481 
482 	hctx = calloc(1, sizeof(*hctx));
483 	force_assert(hctx);
484 
485 	hctx->fde_ndx = -1;
486 
487 	hctx->response_header = buffer_init();
488 
489 	hctx->request_id = 0;
490 	hctx->state = FCGI_STATE_INIT;
491 	hctx->proc = NULL;
492 
493 	hctx->fd = -1;
494 
495 	hctx->reconnects = 0;
496 	hctx->send_content_body = 1;
497 
498 	hctx->rb = chunkqueue_init();
499 	hctx->wb = chunkqueue_init();
500 
501 	return hctx;
502 }
503 
504 static void handler_ctx_free(server *srv, handler_ctx *hctx) {
505 	if (hctx->host) {
506 		fcgi_host_reset(srv, hctx);
507 	}
508 
509 	buffer_free(hctx->response_header);
510 
511 	chunkqueue_free(hctx->rb);
512 	chunkqueue_free(hctx->wb);
513 
514 	free(hctx);
515 }
516 
517 static fcgi_proc *fastcgi_process_init(void) {
518 	fcgi_proc *f;
519 
520 	f = calloc(1, sizeof(*f));
521 	f->unixsocket = buffer_init();
522 	f->connection_name = buffer_init();
523 
524 	f->prev = NULL;
525 	f->next = NULL;
526 
527 	return f;
528 }
529 
530 static void fastcgi_process_free(fcgi_proc *f) {
531 	if (!f) return;
532 
533 	fastcgi_process_free(f->next);
534 
535 	buffer_free(f->unixsocket);
536 	buffer_free(f->connection_name);
537 
538 	free(f);
539 }
540 
541 static fcgi_extension_host *fastcgi_host_init(void) {
542 	fcgi_extension_host *f;
543 
544 	f = calloc(1, sizeof(*f));
545 
546 	f->id = buffer_init();
547 	f->host = buffer_init();
548 	f->unixsocket = buffer_init();
549 	f->docroot = buffer_init();
550 	f->bin_path = buffer_init();
551 	f->bin_env = array_init();
552 	f->bin_env_copy = array_init();
553 	f->strip_request_uri = buffer_init();
554 	f->xsendfile_docroot = array_init();
555 
556 	return f;
557 }
558 
559 static void fastcgi_host_free(fcgi_extension_host *h) {
560 	if (!h) return;
561 
562 	buffer_free(h->id);
563 	buffer_free(h->host);
564 	buffer_free(h->unixsocket);
565 	buffer_free(h->docroot);
566 	buffer_free(h->bin_path);
567 	buffer_free(h->strip_request_uri);
568 	array_free(h->bin_env);
569 	array_free(h->bin_env_copy);
570 	array_free(h->xsendfile_docroot);
571 
572 	fastcgi_process_free(h->first);
573 	fastcgi_process_free(h->unused_procs);
574 
575 	free(h);
576 
577 }
578 
579 static fcgi_exts *fastcgi_extensions_init(void) {
580 	fcgi_exts *f;
581 
582 	f = calloc(1, sizeof(*f));
583 
584 	return f;
585 }
586 
587 static void fastcgi_extensions_free(fcgi_exts *f) {
588 	size_t i;
589 
590 	if (!f) return;
591 
592 	for (i = 0; i < f->used; i++) {
593 		fcgi_extension *fe;
594 		size_t j;
595 
596 		fe = f->exts[i];
597 
598 		for (j = 0; j < fe->used; j++) {
599 			fcgi_extension_host *h;
600 
601 			h = fe->hosts[j];
602 
603 			fastcgi_host_free(h);
604 		}
605 
606 		buffer_free(fe->key);
607 		free(fe->hosts);
608 
609 		free(fe);
610 	}
611 
612 	free(f->exts);
613 
614 	free(f);
615 }
616 
617 static int fastcgi_extension_insert(fcgi_exts *ext, buffer *key, fcgi_extension_host *fh) {
618 	fcgi_extension *fe;
619 	size_t i;
620 
621 	/* there is something */
622 
623 	for (i = 0; i < ext->used; i++) {
624 		if (buffer_is_equal(key, ext->exts[i]->key)) {
625 			break;
626 		}
627 	}
628 
629 	if (i == ext->used) {
630 		/* filextension is new */
631 		fe = calloc(1, sizeof(*fe));
632 		force_assert(fe);
633 		fe->key = buffer_init();
634 		fe->last_used_ndx = -1;
635 		buffer_copy_buffer(fe->key, key);
636 
637 		/* */
638 
639 		if (ext->size == 0) {
640 			ext->size = 8;
641 			ext->exts = malloc(ext->size * sizeof(*(ext->exts)));
642 			force_assert(ext->exts);
643 		} else if (ext->used == ext->size) {
644 			ext->size += 8;
645 			ext->exts = realloc(ext->exts, ext->size * sizeof(*(ext->exts)));
646 			force_assert(ext->exts);
647 		}
648 		ext->exts[ext->used++] = fe;
649 	} else {
650 		fe = ext->exts[i];
651 	}
652 
653 	if (fe->size == 0) {
654 		fe->size = 4;
655 		fe->hosts = malloc(fe->size * sizeof(*(fe->hosts)));
656 		force_assert(fe->hosts);
657 	} else if (fe->size == fe->used) {
658 		fe->size += 4;
659 		fe->hosts = realloc(fe->hosts, fe->size * sizeof(*(fe->hosts)));
660 		force_assert(fe->hosts);
661 	}
662 
663 	fe->hosts[fe->used++] = fh;
664 
665 	return 0;
666 
667 }
668 
669 INIT_FUNC(mod_fastcgi_init) {
670 	plugin_data *p;
671 
672 	p = calloc(1, sizeof(*p));
673 
674 	p->fcgi_env = buffer_init();
675 
676 	p->path = buffer_init();
677 
678 	p->statuskey = buffer_init();
679 
680 	return p;
681 }
682 
683 
684 FREE_FUNC(mod_fastcgi_free) {
685 	plugin_data *p = p_d;
686 
687 	UNUSED(srv);
688 
689 	buffer_free(p->fcgi_env);
690 	buffer_free(p->path);
691 	buffer_free(p->statuskey);
692 
693 	if (p->config_storage) {
694 		size_t i, j, n;
695 		for (i = 0; i < srv->config_context->used; i++) {
696 			plugin_config *s = p->config_storage[i];
697 			fcgi_exts *exts;
698 
699 			if (NULL == s) continue;
700 
701 			exts = s->exts;
702 
703 			for (j = 0; j < exts->used; j++) {
704 				fcgi_extension *ex;
705 
706 				ex = exts->exts[j];
707 
708 				for (n = 0; n < ex->used; n++) {
709 					fcgi_proc *proc;
710 					fcgi_extension_host *host;
711 
712 					host = ex->hosts[n];
713 
714 					for (proc = host->first; proc; proc = proc->next) {
715 						if (proc->pid != 0) {
716 							kill(proc->pid, host->kill_signal);
717 						}
718 
719 						if (proc->is_local &&
720 						    !buffer_string_is_empty(proc->unixsocket)) {
721 							unlink(proc->unixsocket->ptr);
722 						}
723 					}
724 
725 					for (proc = host->unused_procs; proc; proc = proc->next) {
726 						if (proc->pid != 0) {
727 							kill(proc->pid, host->kill_signal);
728 						}
729 						if (proc->is_local &&
730 						    !buffer_string_is_empty(proc->unixsocket)) {
731 							unlink(proc->unixsocket->ptr);
732 						}
733 					}
734 				}
735 			}
736 
737 			fastcgi_extensions_free(s->exts);
738 			array_free(s->ext_mapping);
739 
740 			free(s);
741 		}
742 		free(p->config_storage);
743 	}
744 
745 	free(p);
746 
747 	return HANDLER_GO_ON;
748 }
749 
750 static int env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) {
751 	char *dst;
752 	size_t i;
753 
754 	if (!key || !val) return -1;
755 
756 	dst = malloc(key_len + val_len + 3);
757 	memcpy(dst, key, key_len);
758 	dst[key_len] = '=';
759 	memcpy(dst + key_len + 1, val, val_len);
760 	dst[key_len + 1 + val_len] = '\0';
761 
762 	for (i = 0; i < env->used; i++) {
763 		if (0 == strncmp(dst, env->ptr[i], key_len + 1)) {
764 			/* don't care about free as we are in a forked child which is going to exec(...) */
765 			/* free(env->ptr[i]); */
766 			env->ptr[i] = dst;
767 			return 0;
768 		}
769 	}
770 
771 	if (env->size == 0) {
772 		env->size = 16;
773 		env->ptr = malloc(env->size * sizeof(*env->ptr));
774 	} else if (env->size == env->used + 1) {
775 		env->size += 16;
776 		env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
777 	}
778 
779 	env->ptr[env->used++] = dst;
780 
781 	return 0;
782 }
783 
784 static int parse_binpath(char_array *env, buffer *b) {
785 	char *start;
786 	size_t i;
787 	/* search for spaces */
788 
789 	start = b->ptr;
790 	for (i = 0; i < buffer_string_length(b); i++) {
791 		switch(b->ptr[i]) {
792 		case ' ':
793 		case '\t':
794 			/* a WS, stop here and copy the argument */
795 
796 			if (env->size == 0) {
797 				env->size = 16;
798 				env->ptr = malloc(env->size * sizeof(*env->ptr));
799 			} else if (env->size == env->used) {
800 				env->size += 16;
801 				env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
802 			}
803 
804 			b->ptr[i] = '\0';
805 
806 			env->ptr[env->used++] = start;
807 
808 			start = b->ptr + i + 1;
809 			break;
810 		default:
811 			break;
812 		}
813 	}
814 
815 	if (env->size == 0) {
816 		env->size = 16;
817 		env->ptr = malloc(env->size * sizeof(*env->ptr));
818 	} else if (env->size == env->used) { /* we need one extra for the terminating NULL */
819 		env->size += 16;
820 		env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
821 	}
822 
823 	/* the rest */
824 	env->ptr[env->used++] = start;
825 
826 	if (env->size == 0) {
827 		env->size = 16;
828 		env->ptr = malloc(env->size * sizeof(*env->ptr));
829 	} else if (env->size == env->used) { /* we need one extra for the terminating NULL */
830 		env->size += 16;
831 		env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
832 	}
833 
834 	/* terminate */
835 	env->ptr[env->used++] = NULL;
836 
837 	return 0;
838 }
839 
840 #if !defined(HAVE_FORK)
841 static int fcgi_spawn_connection(server *srv,
842                                  plugin_data *p,
843                                  fcgi_extension_host *host,
844                                  fcgi_proc *proc) {
845 	UNUSED(srv);
846 	UNUSED(p);
847 	UNUSED(host);
848 	UNUSED(proc);
849 	return -1;
850 }
851 
852 #else /* -> defined(HAVE_FORK) */
853 
854 static int fcgi_spawn_connection(server *srv,
855                                  plugin_data *p,
856                                  fcgi_extension_host *host,
857                                  fcgi_proc *proc) {
858 	int fcgi_fd;
859 	int status;
860 	struct timeval tv = { 0, 100 * 1000 };
861 #ifdef HAVE_SYS_UN_H
862 	struct sockaddr_un fcgi_addr_un;
863 #endif
864 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
865 	struct sockaddr_in6 fcgi_addr_in6;
866 #endif
867 	struct sockaddr_in fcgi_addr_in;
868 	struct sockaddr *fcgi_addr;
869 
870 	socklen_t servlen;
871 
872 	if (p->conf.debug) {
873 		log_error_write(srv, __FILE__, __LINE__, "sdb",
874 				"new proc, socket:", proc->port, proc->unixsocket);
875 	}
876 
877 	if (!buffer_string_is_empty(proc->unixsocket)) {
878 #ifdef HAVE_SYS_UN_H
879 		memset(&fcgi_addr_un, 0, sizeof(fcgi_addr_un));
880 		fcgi_addr_un.sun_family = AF_UNIX;
881 		if (buffer_string_length(proc->unixsocket) + 1 > sizeof(fcgi_addr_un.sun_path)) {
882 			log_error_write(srv, __FILE__, __LINE__, "sB",
883 					"ERROR: Unix Domain socket filename too long:",
884 					proc->unixsocket);
885 			return -1;
886 		}
887 		memcpy(fcgi_addr_un.sun_path, proc->unixsocket->ptr, buffer_string_length(proc->unixsocket) + 1);
888 
889 #ifdef SUN_LEN
890 		servlen = SUN_LEN(&fcgi_addr_un);
891 #else
892 		/* stevens says: */
893 		servlen = buffer_string_length(proc->unixsocket) + 1 + sizeof(fcgi_addr_un.sun_family);
894 #endif
895 		fcgi_addr = (struct sockaddr *) &fcgi_addr_un;
896 
897 		buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("unix:"));
898 		buffer_append_string_buffer(proc->connection_name, proc->unixsocket);
899 
900 #else
901 		log_error_write(srv, __FILE__, __LINE__, "s",
902 				"ERROR: Unix Domain sockets are not supported.");
903 		return -1;
904 #endif
905 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
906 	} else if (host->family == AF_INET6 && !buffer_string_is_empty(host->host)) {
907 		memset(&fcgi_addr_in6, 0, sizeof(fcgi_addr_in6));
908 		fcgi_addr_in6.sin6_family = AF_INET6;
909 		inet_pton(AF_INET6, host->host->ptr, (char *) &fcgi_addr_in6.sin6_addr);
910 		fcgi_addr_in6.sin6_port = htons(proc->port);
911 		servlen = sizeof(fcgi_addr_in6);
912 		fcgi_addr = (struct sockaddr *) &fcgi_addr_in6;
913 #endif
914 	} else {
915 		memset(&fcgi_addr_in, 0, sizeof(fcgi_addr_in));
916 		fcgi_addr_in.sin_family = AF_INET;
917 
918 		if (buffer_string_is_empty(host->host)) {
919 			fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
920 		} else {
921 			struct hostent *he;
922 
923 			/* set a useful default */
924 			fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
925 
926 
927 			if (NULL == (he = gethostbyname(host->host->ptr))) {
928 				log_error_write(srv, __FILE__, __LINE__,
929 						"sdb", "gethostbyname failed: ",
930 						h_errno, host->host);
931 				return -1;
932 			}
933 
934 			if (he->h_addrtype != AF_INET) {
935 				log_error_write(srv, __FILE__, __LINE__, "sd", "addr-type != AF_INET: ", he->h_addrtype);
936 				return -1;
937 			}
938 
939 			if (he->h_length != sizeof(struct in_addr)) {
940 				log_error_write(srv, __FILE__, __LINE__, "sd", "addr-length != sizeof(in_addr): ", he->h_length);
941 				return -1;
942 			}
943 
944 			memcpy(&(fcgi_addr_in.sin_addr.s_addr), he->h_addr_list[0], he->h_length);
945 
946 		}
947 		fcgi_addr_in.sin_port = htons(proc->port);
948 		servlen = sizeof(fcgi_addr_in);
949 
950 		fcgi_addr = (struct sockaddr *) &fcgi_addr_in;
951 	}
952 
953 	if (buffer_string_is_empty(proc->unixsocket)) {
954 		buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("tcp:"));
955 		if (!buffer_string_is_empty(host->host)) {
956 			buffer_append_string_buffer(proc->connection_name, host->host);
957 		} else {
958 			buffer_append_string_len(proc->connection_name, CONST_STR_LEN("localhost"));
959 		}
960 		buffer_append_string_len(proc->connection_name, CONST_STR_LEN(":"));
961 		buffer_append_int(proc->connection_name, proc->port);
962 	}
963 
964 	if (-1 == (fcgi_fd = socket(fcgi_addr->sa_family, SOCK_STREAM, 0))) {
965 		log_error_write(srv, __FILE__, __LINE__, "ss",
966 				"failed:", strerror(errno));
967 		return -1;
968 	}
969 
970 	if (-1 == connect(fcgi_fd, fcgi_addr, servlen)) {
971 		/* server is not up, spawn it  */
972 		pid_t child;
973 		int val;
974 
975 		if (errno != ENOENT &&
976 		    !buffer_string_is_empty(proc->unixsocket)) {
977 			unlink(proc->unixsocket->ptr);
978 		}
979 
980 		close(fcgi_fd);
981 
982 		/* reopen socket */
983 		if (-1 == (fcgi_fd = socket(fcgi_addr->sa_family, SOCK_STREAM, 0))) {
984 			log_error_write(srv, __FILE__, __LINE__, "ss",
985 				"socket failed:", strerror(errno));
986 			return -1;
987 		}
988 
989 		val = 1;
990 		if (setsockopt(fcgi_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) {
991 			log_error_write(srv, __FILE__, __LINE__, "ss",
992 					"socketsockopt failed:", strerror(errno));
993 			close(fcgi_fd);
994 			return -1;
995 		}
996 
997 		/* create socket */
998 		if (-1 == bind(fcgi_fd, fcgi_addr, servlen)) {
999 			log_error_write(srv, __FILE__, __LINE__, "sbs",
1000 				"bind failed for:",
1001 				proc->connection_name,
1002 				strerror(errno));
1003 			close(fcgi_fd);
1004 			return -1;
1005 		}
1006 
1007 		if (-1 == listen(fcgi_fd, host->listen_backlog)) {
1008 			log_error_write(srv, __FILE__, __LINE__, "ss",
1009 				"listen failed:", strerror(errno));
1010 			close(fcgi_fd);
1011 			return -1;
1012 		}
1013 
1014 		switch ((child = fork())) {
1015 		case 0: {
1016 			size_t i = 0;
1017 			char *c;
1018 			char_array env;
1019 			char_array arg;
1020 
1021 			/* create environment */
1022 			env.ptr = NULL;
1023 			env.size = 0;
1024 			env.used = 0;
1025 
1026 			arg.ptr = NULL;
1027 			arg.size = 0;
1028 			arg.used = 0;
1029 
1030 			if(fcgi_fd != FCGI_LISTENSOCK_FILENO) {
1031 				close(FCGI_LISTENSOCK_FILENO);
1032 				dup2(fcgi_fd, FCGI_LISTENSOCK_FILENO);
1033 				close(fcgi_fd);
1034 			}
1035 
1036 			/* we don't need the client socket */
1037 			for (i = 3; i < 256; i++) {
1038 				close(i);
1039 			}
1040 
1041 			/* build clean environment */
1042 			if (host->bin_env_copy->used) {
1043 				for (i = 0; i < host->bin_env_copy->used; i++) {
1044 					data_string *ds = (data_string *)host->bin_env_copy->data[i];
1045 					char *ge;
1046 
1047 					if (NULL != (ge = getenv(ds->value->ptr))) {
1048 						env_add(&env, CONST_BUF_LEN(ds->value), ge, strlen(ge));
1049 					}
1050 				}
1051 			} else {
1052 				char ** const e = environ;
1053 				for (i = 0; e[i]; ++i) {
1054 					char *eq;
1055 
1056 					if (NULL != (eq = strchr(e[i], '='))) {
1057 						env_add(&env, e[i], eq - e[i], eq+1, strlen(eq+1));
1058 					}
1059 				}
1060 			}
1061 
1062 			/* create environment */
1063 			for (i = 0; i < host->bin_env->used; i++) {
1064 				data_string *ds = (data_string *)host->bin_env->data[i];
1065 
1066 				env_add(&env, CONST_BUF_LEN(ds->key), CONST_BUF_LEN(ds->value));
1067 			}
1068 
1069 			for (i = 0; i < env.used; i++) {
1070 				/* search for PHP_FCGI_CHILDREN */
1071 				if (0 == strncmp(env.ptr[i], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
1072 			}
1073 
1074 			/* not found, add a default */
1075 			if (i == env.used) {
1076 				env_add(&env, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
1077 			}
1078 
1079 			env.ptr[env.used] = NULL;
1080 
1081 			parse_binpath(&arg, host->bin_path);
1082 
1083 			/* chdir into the base of the bin-path,
1084 			 * search for the last / */
1085 			if (NULL != (c = strrchr(arg.ptr[0], '/'))) {
1086 				*c = '\0';
1087 
1088 				/* change to the physical directory */
1089 				if (-1 == chdir(arg.ptr[0])) {
1090 					*c = '/';
1091 					log_error_write(srv, __FILE__, __LINE__, "sss", "chdir failed:", strerror(errno), arg.ptr[0]);
1092 				}
1093 				*c = '/';
1094 			}
1095 
1096 			reset_signals();
1097 
1098 			/* exec the cgi */
1099 			execve(arg.ptr[0], arg.ptr, env.ptr);
1100 
1101 			/* log_error_write(srv, __FILE__, __LINE__, "sbs",
1102 					"execve failed for:", host->bin_path, strerror(errno)); */
1103 
1104 			_exit(errno);
1105 
1106 			break;
1107 		}
1108 		case -1:
1109 			/* error */
1110 			close(fcgi_fd);
1111 			break;
1112 		default:
1113 			/* father */
1114 			close(fcgi_fd);
1115 
1116 			/* wait */
1117 			select(0, NULL, NULL, NULL, &tv);
1118 
1119 			switch (waitpid(child, &status, WNOHANG)) {
1120 			case 0:
1121 				/* child still running after timeout, good */
1122 				break;
1123 			case -1:
1124 				/* no PID found ? should never happen */
1125 				log_error_write(srv, __FILE__, __LINE__, "ss",
1126 						"pid not found:", strerror(errno));
1127 				return -1;
1128 			default:
1129 				log_error_write(srv, __FILE__, __LINE__, "sbs",
1130 						"the fastcgi-backend", host->bin_path, "failed to start:");
1131 				/* the child should not terminate at all */
1132 				if (WIFEXITED(status)) {
1133 					log_error_write(srv, __FILE__, __LINE__, "sdb",
1134 							"child exited with status",
1135 							WEXITSTATUS(status), host->bin_path);
1136 					log_error_write(srv, __FILE__, __LINE__, "s",
1137 							"If you're trying to run your app as a FastCGI backend, make sure you're using the FastCGI-enabled version.\n"
1138 							"If this is PHP on Gentoo, add 'fastcgi' to the USE flags.");
1139 				} else if (WIFSIGNALED(status)) {
1140 					log_error_write(srv, __FILE__, __LINE__, "sd",
1141 							"terminated by signal:",
1142 							WTERMSIG(status));
1143 
1144 					if (WTERMSIG(status) == 11) {
1145 						log_error_write(srv, __FILE__, __LINE__, "s",
1146 								"to be exact: it segfaulted, crashed, died, ... you get the idea." );
1147 						log_error_write(srv, __FILE__, __LINE__, "s",
1148 								"If this is PHP, try removing the bytecode caches for now and try again.");
1149 					}
1150 				} else {
1151 					log_error_write(srv, __FILE__, __LINE__, "sd",
1152 							"child died somehow:",
1153 							status);
1154 				}
1155 				return -1;
1156 			}
1157 
1158 			/* register process */
1159 			proc->pid = child;
1160 			proc->is_local = 1;
1161 
1162 			break;
1163 		}
1164 	} else {
1165 		close(fcgi_fd);
1166 		proc->is_local = 0;
1167 		proc->pid = 0;
1168 
1169 		if (p->conf.debug) {
1170 			log_error_write(srv, __FILE__, __LINE__, "sb",
1171 					"(debug) socket is already used; won't spawn:",
1172 					proc->connection_name);
1173 		}
1174 	}
1175 
1176 	proc->state = PROC_STATE_RUNNING;
1177 	host->active_procs++;
1178 
1179 	return 0;
1180 }
1181 
1182 #endif /* HAVE_FORK */
1183 
1184 static int unixsocket_is_dup(plugin_data *p, size_t used, buffer *unixsocket) {
1185 	size_t i, j, n;
1186 	for (i = 0; i < used; ++i) {
1187 		fcgi_exts *exts = p->config_storage[i]->exts;
1188 		for (j = 0; j < exts->used; ++j) {
1189 			fcgi_extension *ex = exts->exts[j];
1190 			for (n = 0; n < ex->used; ++n) {
1191 				fcgi_extension_host *host = ex->hosts[n];
1192 				if (!buffer_string_is_empty(host->unixsocket)
1193 				    && buffer_is_equal(host->unixsocket, unixsocket))
1194 					return 1;
1195 			}
1196 		}
1197 	}
1198 
1199 	return 0;
1200 }
1201 
1202 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults) {
1203 	plugin_data *p = p_d;
1204 	data_unset *du;
1205 	size_t i = 0;
1206 	buffer *fcgi_mode = buffer_init();
1207 	fcgi_extension_host *host = NULL;
1208 
1209 	config_values_t cv[] = {
1210 		{ "fastcgi.server",              NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION },       /* 0 */
1211 		{ "fastcgi.debug",               NULL, T_CONFIG_INT  , T_CONFIG_SCOPE_CONNECTION },       /* 1 */
1212 		{ "fastcgi.map-extensions",      NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION },       /* 2 */
1213 		{ NULL,                          NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1214 	};
1215 
1216 	p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
1217 
1218 	for (i = 0; i < srv->config_context->used; i++) {
1219 		data_config const* config = (data_config const*)srv->config_context->data[i];
1220 		plugin_config *s;
1221 
1222 		s = malloc(sizeof(plugin_config));
1223 		s->exts          = fastcgi_extensions_init();
1224 		s->debug         = 0;
1225 		s->ext_mapping   = array_init();
1226 
1227 		cv[0].destination = s->exts;
1228 		cv[1].destination = &(s->debug);
1229 		cv[2].destination = s->ext_mapping;
1230 
1231 		p->config_storage[i] = s;
1232 
1233 		if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
1234 			goto error;
1235 		}
1236 
1237 		/*
1238 		 * <key> = ( ... )
1239 		 */
1240 
1241 		if (NULL != (du = array_get_element(config->value, "fastcgi.server"))) {
1242 			size_t j;
1243 			data_array *da = (data_array *)du;
1244 
1245 			if (du->type != TYPE_ARRAY) {
1246 				log_error_write(srv, __FILE__, __LINE__, "sss",
1247 						"unexpected type for key: ", "fastcgi.server", "expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1248 
1249 				goto error;
1250 			}
1251 
1252 
1253 			/*
1254 			 * fastcgi.server = ( "<ext>" => ( ... ),
1255 			 *                    "<ext>" => ( ... ) )
1256 			 */
1257 
1258 			for (j = 0; j < da->value->used; j++) {
1259 				size_t n;
1260 				data_array *da_ext = (data_array *)da->value->data[j];
1261 
1262 				if (da->value->data[j]->type != TYPE_ARRAY) {
1263 					log_error_write(srv, __FILE__, __LINE__, "sssbs",
1264 							"unexpected type for key: ", "fastcgi.server",
1265 							"[", da->value->data[j]->key, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1266 
1267 					goto error;
1268 				}
1269 
1270 				/*
1271 				 * da_ext->key == name of the extension
1272 				 */
1273 
1274 				/*
1275 				 * fastcgi.server = ( "<ext>" =>
1276 				 *                     ( "<host>" => ( ... ),
1277 				 *                       "<host>" => ( ... )
1278 				 *                     ),
1279 				 *                    "<ext>" => ... )
1280 				 */
1281 
1282 				for (n = 0; n < da_ext->value->used; n++) {
1283 					data_array *da_host = (data_array *)da_ext->value->data[n];
1284 
1285 					config_values_t fcv[] = {
1286 						{ "host",              NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },       /* 0 */
1287 						{ "docroot",           NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },       /* 1 */
1288 						{ "mode",              NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },       /* 2 */
1289 						{ "socket",            NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },       /* 3 */
1290 						{ "bin-path",          NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },       /* 4 */
1291 
1292 						{ "check-local",       NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION },      /* 5 */
1293 						{ "port",              NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },        /* 6 */
1294 						{ "max-procs",         NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },        /* 7 */
1295 						{ "disable-time",      NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },        /* 8 */
1296 
1297 						{ "bin-environment",   NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION },        /* 9 */
1298 						{ "bin-copy-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION },     /* 10 */
1299 
1300 						{ "broken-scriptfilename", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION },  /* 11 */
1301 						{ "allow-x-send-file",  NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION },     /* 12 */
1302 						{ "strip-request-uri",  NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },      /* 13 */
1303 						{ "kill-signal",        NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },       /* 14 */
1304 						{ "fix-root-scriptname",   NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION },  /* 15 */
1305 						{ "listen-backlog",    NULL, T_CONFIG_INT,   T_CONFIG_SCOPE_CONNECTION },        /* 16 */
1306 						{ "x-sendfile",        NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION },      /* 17 */
1307 						{ "x-sendfile-docroot",NULL, T_CONFIG_ARRAY,  T_CONFIG_SCOPE_CONNECTION },      /* 18 */
1308 
1309 						{ NULL,                NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1310 					};
1311 
1312 					if (da_host->type != TYPE_ARRAY) {
1313 						log_error_write(srv, __FILE__, __LINE__, "ssSBS",
1314 								"unexpected type for key:",
1315 								"fastcgi.server",
1316 								"[", da_host->key, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1317 
1318 						goto error;
1319 					}
1320 
1321 					host = fastcgi_host_init();
1322 					buffer_reset(fcgi_mode);
1323 
1324 					buffer_copy_buffer(host->id, da_host->key);
1325 
1326 					host->check_local  = 1;
1327 					host->max_procs    = 4;
1328 					host->mode = FCGI_RESPONDER;
1329 					host->disable_time = 1;
1330 					host->break_scriptfilename_for_php = 0;
1331 					host->xsendfile_allow = 0;
1332 					host->kill_signal = SIGTERM;
1333 					host->fix_root_path_name = 0;
1334 					host->listen_backlog = 1024;
1335 
1336 					fcv[0].destination = host->host;
1337 					fcv[1].destination = host->docroot;
1338 					fcv[2].destination = fcgi_mode;
1339 					fcv[3].destination = host->unixsocket;
1340 					fcv[4].destination = host->bin_path;
1341 
1342 					fcv[5].destination = &(host->check_local);
1343 					fcv[6].destination = &(host->port);
1344 					fcv[7].destination = &(host->max_procs);
1345 					fcv[8].destination = &(host->disable_time);
1346 
1347 					fcv[9].destination = host->bin_env;
1348 					fcv[10].destination = host->bin_env_copy;
1349 					fcv[11].destination = &(host->break_scriptfilename_for_php);
1350 					fcv[12].destination = &(host->xsendfile_allow);
1351 					fcv[13].destination = host->strip_request_uri;
1352 					fcv[14].destination = &(host->kill_signal);
1353 					fcv[15].destination = &(host->fix_root_path_name);
1354 					fcv[16].destination = &(host->listen_backlog);
1355 					fcv[17].destination = &(host->xsendfile_allow);
1356 					fcv[18].destination = host->xsendfile_docroot;
1357 
1358 					if (0 != config_insert_values_internal(srv, da_host->value, fcv, T_CONFIG_SCOPE_CONNECTION)) {
1359 						goto error;
1360 					}
1361 
1362 					if ((!buffer_string_is_empty(host->host) || host->port) &&
1363 					    !buffer_string_is_empty(host->unixsocket)) {
1364 						log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1365 								"either host/port or socket have to be set in:",
1366 								da->key, "= (",
1367 								da_ext->key, " => (",
1368 								da_host->key, " ( ...");
1369 
1370 						goto error;
1371 					}
1372 
1373 					if (!buffer_string_is_empty(host->unixsocket)) {
1374 						/* unix domain socket */
1375 						struct sockaddr_un un;
1376 
1377 						if (buffer_string_length(host->unixsocket) + 1 > sizeof(un.sun_path) - 2) {
1378 							log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1379 									"unixsocket is too long in:",
1380 									da->key, "= (",
1381 									da_ext->key, " => (",
1382 									da_host->key, " ( ...");
1383 
1384 							goto error;
1385 						}
1386 
1387 						if (!buffer_string_is_empty(host->bin_path)
1388 						    && unixsocket_is_dup(p, i+1, host->unixsocket)) {
1389 							log_error_write(srv, __FILE__, __LINE__, "sb",
1390 									"duplicate unixsocket path:",
1391 									host->unixsocket);
1392 							goto error;
1393 						}
1394 
1395 						host->family = AF_UNIX;
1396 					} else {
1397 						/* tcp/ip */
1398 
1399 						if (buffer_string_is_empty(host->host) &&
1400 						    buffer_string_is_empty(host->bin_path)) {
1401 							log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1402 									"host or binpath have to be set in:",
1403 									da->key, "= (",
1404 									da_ext->key, " => (",
1405 									da_host->key, " ( ...");
1406 
1407 							goto error;
1408 						} else if (host->port == 0) {
1409 							log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1410 									"port has to be set in:",
1411 									da->key, "= (",
1412 									da_ext->key, " => (",
1413 									da_host->key, " ( ...");
1414 
1415 							goto error;
1416 						}
1417 
1418 						host->family = (!buffer_string_is_empty(host->host) && NULL != strchr(host->host->ptr, ':')) ? AF_INET6 : AF_INET;
1419 					}
1420 
1421 					if (!buffer_string_is_empty(host->bin_path)) {
1422 						/* a local socket + self spawning */
1423 						size_t pno;
1424 
1425 						if (s->debug) {
1426 							log_error_write(srv, __FILE__, __LINE__, "ssbsdsbsd",
1427 									"--- fastcgi spawning local",
1428 									"\n\tproc:", host->bin_path,
1429 									"\n\tport:", host->port,
1430 									"\n\tsocket", host->unixsocket,
1431 									"\n\tmax-procs:", host->max_procs);
1432 						}
1433 
1434 						for (pno = 0; pno < host->max_procs; pno++) {
1435 							fcgi_proc *proc;
1436 
1437 							proc = fastcgi_process_init();
1438 							proc->id = host->num_procs++;
1439 							host->max_id++;
1440 
1441 							if (buffer_string_is_empty(host->unixsocket)) {
1442 								proc->port = host->port + pno;
1443 							} else {
1444 								buffer_copy_buffer(proc->unixsocket, host->unixsocket);
1445 								buffer_append_string_len(proc->unixsocket, CONST_STR_LEN("-"));
1446 								buffer_append_int(proc->unixsocket, pno);
1447 							}
1448 
1449 							if (s->debug) {
1450 								log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
1451 										"--- fastcgi spawning",
1452 										"\n\tport:", host->port,
1453 										"\n\tsocket", host->unixsocket,
1454 										"\n\tcurrent:", pno, "/", host->max_procs);
1455 							}
1456 
1457 							if (!srv->srvconf.preflight_check
1458 							    && fcgi_spawn_connection(srv, p, host, proc)) {
1459 								log_error_write(srv, __FILE__, __LINE__, "s",
1460 										"[ERROR]: spawning fcgi failed.");
1461 								fastcgi_process_free(proc);
1462 								goto error;
1463 							}
1464 
1465 							fastcgi_status_init(srv, p->statuskey, host, proc);
1466 
1467 							proc->next = host->first;
1468 							if (host->first) host->first->prev = proc;
1469 
1470 							host->first = proc;
1471 						}
1472 					} else {
1473 						fcgi_proc *proc;
1474 
1475 						proc = fastcgi_process_init();
1476 						proc->id = host->num_procs++;
1477 						host->max_id++;
1478 						host->active_procs++;
1479 						proc->state = PROC_STATE_RUNNING;
1480 
1481 						if (buffer_string_is_empty(host->unixsocket)) {
1482 							proc->port = host->port;
1483 						} else {
1484 							buffer_copy_buffer(proc->unixsocket, host->unixsocket);
1485 						}
1486 
1487 						fastcgi_status_init(srv, p->statuskey, host, proc);
1488 
1489 						host->first = proc;
1490 
1491 						host->max_procs = 1;
1492 					}
1493 
1494 					if (!buffer_string_is_empty(fcgi_mode)) {
1495 						if (strcmp(fcgi_mode->ptr, "responder") == 0) {
1496 							host->mode = FCGI_RESPONDER;
1497 						} else if (strcmp(fcgi_mode->ptr, "authorizer") == 0) {
1498 							host->mode = FCGI_AUTHORIZER;
1499 							if (buffer_string_is_empty(host->docroot)) {
1500 								log_error_write(srv, __FILE__, __LINE__, "s",
1501 										"ERROR: docroot is required for authorizer mode.");
1502 								goto error;
1503 							}
1504 						} else {
1505 							log_error_write(srv, __FILE__, __LINE__, "sbs",
1506 									"WARNING: unknown fastcgi mode:",
1507 									fcgi_mode, "(ignored, mode set to responder)");
1508 						}
1509 					}
1510 
1511 					if (host->xsendfile_docroot->used) {
1512 						size_t k;
1513 						for (k = 0; k < host->xsendfile_docroot->used; ++k) {
1514 							data_string *ds = (data_string *)host->xsendfile_docroot->data[k];
1515 							if (ds->type != TYPE_STRING) {
1516 								log_error_write(srv, __FILE__, __LINE__, "s",
1517 									"unexpected type for x-sendfile-docroot; expected: \"x-sendfile-docroot\" => ( \"/allowed/path\", ... )");
1518 								goto error;
1519 							}
1520 							if (ds->value->ptr[0] != '/') {
1521 								log_error_write(srv, __FILE__, __LINE__, "SBs",
1522 									"x-sendfile-docroot paths must begin with '/'; invalid: \"", ds->value, "\"");
1523 								goto error;
1524 							}
1525 							buffer_path_simplify(ds->value, ds->value);
1526 							buffer_append_slash(ds->value);
1527 						}
1528 					}
1529 
1530 					/* if extension already exists, take it */
1531 					fastcgi_extension_insert(s->exts, da_ext->key, host);
1532 					host = NULL;
1533 				}
1534 			}
1535 		}
1536 	}
1537 
1538 	buffer_free(fcgi_mode);
1539 	return HANDLER_GO_ON;
1540 
1541 error:
1542 	if (NULL != host) fastcgi_host_free(host);
1543 	buffer_free(fcgi_mode);
1544 	return HANDLER_ERROR;
1545 }
1546 
1547 static int fcgi_set_state(server *srv, handler_ctx *hctx, fcgi_connection_state_t state) {
1548 	hctx->state = state;
1549 	hctx->state_timestamp = srv->cur_ts;
1550 
1551 	return 0;
1552 }
1553 
1554 
1555 static void fcgi_connection_close(server *srv, handler_ctx *hctx) {
1556 	plugin_data *p;
1557 	connection  *con;
1558 
1559 	p    = hctx->plugin_data;
1560 	con  = hctx->remote_conn;
1561 
1562 	if (hctx->fd != -1) {
1563 		fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1564 		fdevent_unregister(srv->ev, hctx->fd);
1565 		close(hctx->fd);
1566 		srv->cur_fds--;
1567 	}
1568 
1569 	if (hctx->host && hctx->proc) {
1570 		if (hctx->got_proc) {
1571 			/* after the connect the process gets a load */
1572 			fcgi_proc_load_dec(srv, hctx);
1573 
1574 			if (p->conf.debug) {
1575 				log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
1576 						"released proc:",
1577 						"pid:", hctx->proc->pid,
1578 						"socket:", hctx->proc->connection_name,
1579 						"load:", hctx->proc->load);
1580 			}
1581 		}
1582 	}
1583 
1584 
1585 	handler_ctx_free(srv, hctx);
1586 	con->plugin_ctx[p->id] = NULL;
1587 
1588 	/* finish response (if not already finished) */
1589 	if (con->mode == p->id
1590 	    && (con->state == CON_STATE_HANDLE_REQUEST || con->state == CON_STATE_READ_POST)) {
1591 		/* (not CON_STATE_ERROR and not CON_STATE_RESPONSE_END,
1592 		 *  i.e. not called from fcgi_connection_reset()) */
1593 
1594 		/* Send an error if we haven't sent any data yet */
1595 		if (0 == con->file_started) {
1596 			con->http_status = 500;
1597 			con->mode = DIRECT;
1598 		}
1599 		else if (!con->file_finished) {
1600 			http_chunk_close(srv, con);
1601 			con->file_finished = 1;
1602 		}
1603 	}
1604 }
1605 
1606 static int fcgi_reconnect(server *srv, handler_ctx *hctx) {
1607 	plugin_data *p    = hctx->plugin_data;
1608 
1609 	/* child died
1610 	 *
1611 	 * 1.
1612 	 *
1613 	 * connect was ok, connection was accepted
1614 	 * but the php accept loop checks after the accept if it should die or not.
1615 	 *
1616 	 * if yes we can only detect it at a write()
1617 	 *
1618 	 * next step is resetting this attemp and setup a connection again
1619 	 *
1620 	 * if we have more than 5 reconnects for the same request, die
1621 	 *
1622 	 * 2.
1623 	 *
1624 	 * we have a connection but the child died by some other reason
1625 	 *
1626 	 */
1627 
1628 	if (hctx->fd != -1) {
1629 		fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1630 		fdevent_unregister(srv->ev, hctx->fd);
1631 		close(hctx->fd);
1632 		srv->cur_fds--;
1633 		hctx->fd = -1;
1634 	}
1635 
1636 	fcgi_set_state(srv, hctx, FCGI_STATE_INIT);
1637 
1638 	hctx->request_id = 0;
1639 	hctx->reconnects++;
1640 
1641 	if (p->conf.debug > 2) {
1642 		if (hctx->proc) {
1643 			log_error_write(srv, __FILE__, __LINE__, "sdb",
1644 					"release proc for reconnect:",
1645 					hctx->proc->pid, hctx->proc->connection_name);
1646 		} else {
1647 			log_error_write(srv, __FILE__, __LINE__, "sb",
1648 					"release proc for reconnect:",
1649 					hctx->host->unixsocket);
1650 		}
1651 	}
1652 
1653 	if (hctx->proc && hctx->got_proc) {
1654 		fcgi_proc_load_dec(srv, hctx);
1655 	}
1656 
1657 	/* perhaps another host gives us more luck */
1658 	fcgi_host_reset(srv, hctx);
1659 
1660 	return 0;
1661 }
1662 
1663 
1664 static handler_t fcgi_connection_reset(server *srv, connection *con, void *p_d) {
1665 	plugin_data *p = p_d;
1666 	handler_ctx *hctx = con->plugin_ctx[p->id];
1667 	if (hctx) fcgi_connection_close(srv, hctx);
1668 
1669 	return HANDLER_GO_ON;
1670 }
1671 
1672 
1673 static int fcgi_env_add(buffer *env, const char *key, size_t key_len, const char *val, size_t val_len) {
1674 	size_t len;
1675 	char len_enc[8];
1676 	size_t len_enc_len = 0;
1677 
1678 	if (!key || !val) return -1;
1679 
1680 	len = key_len + val_len;
1681 
1682 	len += key_len > 127 ? 4 : 1;
1683 	len += val_len > 127 ? 4 : 1;
1684 
1685 	if (buffer_string_length(env) + len >= FCGI_MAX_LENGTH) {
1686 		/**
1687 		 * we can't append more headers, ignore it
1688 		 */
1689 		return -1;
1690 	}
1691 
1692 	/**
1693 	 * field length can be 31bit max
1694 	 *
1695 	 * HINT: this can't happen as FCGI_MAX_LENGTH is only 16bit
1696 	 */
1697 	force_assert(key_len < 0x7fffffffu);
1698 	force_assert(val_len < 0x7fffffffu);
1699 
1700 	buffer_string_prepare_append(env, len);
1701 
1702 	if (key_len > 127) {
1703 		len_enc[len_enc_len++] = ((key_len >> 24) & 0xff) | 0x80;
1704 		len_enc[len_enc_len++] = (key_len >> 16) & 0xff;
1705 		len_enc[len_enc_len++] = (key_len >> 8) & 0xff;
1706 		len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1707 	} else {
1708 		len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1709 	}
1710 
1711 	if (val_len > 127) {
1712 		len_enc[len_enc_len++] = ((val_len >> 24) & 0xff) | 0x80;
1713 		len_enc[len_enc_len++] = (val_len >> 16) & 0xff;
1714 		len_enc[len_enc_len++] = (val_len >> 8) & 0xff;
1715 		len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1716 	} else {
1717 		len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1718 	}
1719 
1720 	buffer_append_string_len(env, len_enc, len_enc_len);
1721 	buffer_append_string_len(env, key, key_len);
1722 	buffer_append_string_len(env, val, val_len);
1723 
1724 	return 0;
1725 }
1726 
1727 static int fcgi_header(FCGI_Header * header, unsigned char type, size_t request_id, int contentLength, unsigned char paddingLength) {
1728 	force_assert(contentLength <= FCGI_MAX_LENGTH);
1729 
1730 	header->version = FCGI_VERSION_1;
1731 	header->type = type;
1732 	header->requestIdB0 = request_id & 0xff;
1733 	header->requestIdB1 = (request_id >> 8) & 0xff;
1734 	header->contentLengthB0 = contentLength & 0xff;
1735 	header->contentLengthB1 = (contentLength >> 8) & 0xff;
1736 	header->paddingLength = paddingLength;
1737 	header->reserved = 0;
1738 
1739 	return 0;
1740 }
1741 
1742 typedef enum {
1743 	CONNECTION_OK,
1744 	CONNECTION_DELAYED, /* retry after event, take same host */
1745 	CONNECTION_OVERLOADED, /* disable for 1 second, take another backend */
1746 	CONNECTION_DEAD /* disable for 60 seconds, take another backend */
1747 } connection_result_t;
1748 
1749 static connection_result_t fcgi_establish_connection(server *srv, handler_ctx *hctx) {
1750 	struct sockaddr *fcgi_addr;
1751 	struct sockaddr_in fcgi_addr_in;
1752 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1753 	struct sockaddr_in6 fcgi_addr_in6;
1754 #endif
1755 #ifdef HAVE_SYS_UN_H
1756 	struct sockaddr_un fcgi_addr_un;
1757 #endif
1758 	socklen_t servlen;
1759 
1760 	fcgi_extension_host *host = hctx->host;
1761 	fcgi_proc *proc   = hctx->proc;
1762 	int fcgi_fd       = hctx->fd;
1763 
1764 	if (!buffer_string_is_empty(proc->unixsocket)) {
1765 #ifdef HAVE_SYS_UN_H
1766 		/* use the unix domain socket */
1767 		memset(&fcgi_addr_un, 0, sizeof(fcgi_addr_un));
1768 		fcgi_addr_un.sun_family = AF_UNIX;
1769 		if (buffer_string_length(proc->unixsocket) + 1 > sizeof(fcgi_addr_un.sun_path)) {
1770 			log_error_write(srv, __FILE__, __LINE__, "sB",
1771 					"ERROR: Unix Domain socket filename too long:",
1772 					proc->unixsocket);
1773 			return -1;
1774 		}
1775 		memcpy(fcgi_addr_un.sun_path, proc->unixsocket->ptr, buffer_string_length(proc->unixsocket) + 1);
1776 
1777 #ifdef SUN_LEN
1778 		servlen = SUN_LEN(&fcgi_addr_un);
1779 #else
1780 		/* stevens says: */
1781 		servlen = buffer_string_length(proc->unixsocket) + 1 + sizeof(fcgi_addr_un.sun_family);
1782 #endif
1783 		fcgi_addr = (struct sockaddr *) &fcgi_addr_un;
1784 
1785 		if (buffer_string_is_empty(proc->connection_name)) {
1786 			/* on remote spawing we have to set the connection-name now */
1787 			buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("unix:"));
1788 			buffer_append_string_buffer(proc->connection_name, proc->unixsocket);
1789 		}
1790 #else
1791 		return CONNECTION_DEAD;
1792 #endif
1793 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1794 	} else if (host->family == AF_INET6 && !buffer_string_is_empty(host->host)) {
1795 		memset(&fcgi_addr_in6, 0, sizeof(fcgi_addr_in6));
1796 		fcgi_addr_in6.sin6_family = AF_INET6;
1797 		inet_pton(AF_INET6, host->host->ptr, (char *) &fcgi_addr_in6.sin6_addr);
1798 		fcgi_addr_in6.sin6_port = htons(proc->port);
1799 		servlen = sizeof(fcgi_addr_in6);
1800 		fcgi_addr = (struct sockaddr *) &fcgi_addr_in6;
1801 #endif
1802 	} else {
1803 		memset(&fcgi_addr_in, 0, sizeof(fcgi_addr_in));
1804 		fcgi_addr_in.sin_family = AF_INET;
1805 		if (!buffer_string_is_empty(host->host)) {
1806 			if (0 == inet_aton(host->host->ptr, &(fcgi_addr_in.sin_addr))) {
1807 				log_error_write(srv, __FILE__, __LINE__, "sbs",
1808 						"converting IP address failed for", host->host,
1809 						"\nBe sure to specify an IP address here");
1810 
1811 				return CONNECTION_DEAD;
1812 			}
1813 		} else {
1814 			fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1815 		}
1816 		fcgi_addr_in.sin_port = htons(proc->port);
1817 		servlen = sizeof(fcgi_addr_in);
1818 
1819 		fcgi_addr = (struct sockaddr *) &fcgi_addr_in;
1820 	}
1821 
1822 	if (buffer_string_is_empty(proc->unixsocket)) {
1823 		if (buffer_string_is_empty(proc->connection_name)) {
1824 			/* on remote spawing we have to set the connection-name now */
1825 			buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("tcp:"));
1826 			if (!buffer_string_is_empty(host->host)) {
1827 				buffer_append_string_buffer(proc->connection_name, host->host);
1828 			} else {
1829 				buffer_append_string_len(proc->connection_name, CONST_STR_LEN("localhost"));
1830 			}
1831 			buffer_append_string_len(proc->connection_name, CONST_STR_LEN(":"));
1832 			buffer_append_int(proc->connection_name, proc->port);
1833 		}
1834 	}
1835 
1836 	if (-1 == connect(fcgi_fd, fcgi_addr, servlen)) {
1837 		if (errno == EINPROGRESS ||
1838 		    errno == EALREADY ||
1839 		    errno == EINTR) {
1840 			if (hctx->conf.debug > 2) {
1841 				log_error_write(srv, __FILE__, __LINE__, "sb",
1842 					"connect delayed; will continue later:", proc->connection_name);
1843 			}
1844 
1845 			return CONNECTION_DELAYED;
1846 		} else if (errno == EAGAIN) {
1847 			if (hctx->conf.debug) {
1848 				log_error_write(srv, __FILE__, __LINE__, "sbsd",
1849 					"This means that you have more incoming requests than your FastCGI backend can handle in parallel."
1850 					"It might help to spawn more FastCGI backends or PHP children; if not, decrease server.max-connections."
1851 					"The load for this FastCGI backend", proc->connection_name, "is", proc->load);
1852 			}
1853 
1854 			return CONNECTION_OVERLOADED;
1855 		} else {
1856 			log_error_write(srv, __FILE__, __LINE__, "sssb",
1857 					"connect failed:",
1858 					strerror(errno), "on",
1859 					proc->connection_name);
1860 
1861 			return CONNECTION_DEAD;
1862 		}
1863 	}
1864 
1865 	hctx->reconnects = 0;
1866 	if (hctx->conf.debug > 1) {
1867 		log_error_write(srv, __FILE__, __LINE__, "sd",
1868 				"connect succeeded: ", fcgi_fd);
1869 	}
1870 
1871 	return CONNECTION_OK;
1872 }
1873 
1874 #define FCGI_ENV_ADD_CHECK(ret, con) \
1875 	if (ret == -1) { \
1876 		con->http_status = 400; \
1877 		con->file_finished = 1; \
1878 		return -1; \
1879 	};
1880 static int fcgi_env_add_request_headers(server *srv, connection *con, plugin_data *p) {
1881 	size_t i;
1882 
1883 	for (i = 0; i < con->request.headers->used; i++) {
1884 		data_string *ds;
1885 
1886 		ds = (data_string *)con->request.headers->data[i];
1887 
1888 		if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1889 			buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 1);
1890 
1891 			FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value)),con);
1892 		}
1893 	}
1894 
1895 	for (i = 0; i < con->environment->used; i++) {
1896 		data_string *ds;
1897 
1898 		ds = (data_string *)con->environment->data[i];
1899 
1900 		if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1901 			buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 0);
1902 
1903 			FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value)), con);
1904 		}
1905 	}
1906 
1907 	return 0;
1908 }
1909 
1910 static int fcgi_create_env(server *srv, handler_ctx *hctx, size_t request_id) {
1911 	FCGI_BeginRequestRecord beginRecord;
1912 	FCGI_Header header;
1913 
1914 	char buf[LI_ITOSTRING_LENGTH];
1915 	const char *s;
1916 #ifdef HAVE_IPV6
1917 	char b2[INET6_ADDRSTRLEN + 1];
1918 #endif
1919 
1920 	plugin_data *p    = hctx->plugin_data;
1921 	fcgi_extension_host *host= hctx->host;
1922 
1923 	connection *con   = hctx->remote_conn;
1924 	buffer * const req_uri = (con->error_handler_saved_status >= 0) ? con->request.uri : con->request.orig_uri;
1925 	server_socket *srv_sock = con->srv_socket;
1926 
1927 	sock_addr our_addr;
1928 	socklen_t our_addr_len;
1929 
1930 	/* send FCGI_BEGIN_REQUEST */
1931 
1932 	fcgi_header(&(beginRecord.header), FCGI_BEGIN_REQUEST, request_id, sizeof(beginRecord.body), 0);
1933 	beginRecord.body.roleB0 = host->mode;
1934 	beginRecord.body.roleB1 = 0;
1935 	beginRecord.body.flags = 0;
1936 	memset(beginRecord.body.reserved, 0, sizeof(beginRecord.body.reserved));
1937 
1938 	/* send FCGI_PARAMS */
1939 	buffer_string_prepare_copy(p->fcgi_env, 1023);
1940 
1941 
1942 	if (buffer_is_empty(con->conf.server_tag)) {
1943 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_DESC)),con)
1944 	} else {
1945 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con->conf.server_tag)),con)
1946 	}
1947 
1948 	if (!buffer_is_empty(con->server_name)) {
1949 		size_t len = buffer_string_length(con->server_name);
1950 
1951 		if (con->server_name->ptr[0] == '[') {
1952 			const char *colon = strstr(con->server_name->ptr, "]:");
1953 			if (colon) len = (colon + 1) - con->server_name->ptr;
1954 		} else {
1955 			const char *colon = strchr(con->server_name->ptr, ':');
1956 			if (colon) len = colon - con->server_name->ptr;
1957 		}
1958 
1959 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_NAME"), con->server_name->ptr, len),con)
1960 	} else {
1961 #ifdef HAVE_IPV6
1962 		s = inet_ntop(srv_sock->addr.plain.sa_family,
1963 			      srv_sock->addr.plain.sa_family == AF_INET6 ?
1964 			      (const void *) &(srv_sock->addr.ipv6.sin6_addr) :
1965 			      (const void *) &(srv_sock->addr.ipv4.sin_addr),
1966 			      b2, sizeof(b2)-1);
1967 #else
1968 		s = inet_ntoa(srv_sock->addr.ipv4.sin_addr);
1969 #endif
1970 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_NAME"), s, strlen(s)),con)
1971 	}
1972 
1973 	FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1")),con)
1974 
1975 	li_utostrn(buf, sizeof(buf),
1976 #ifdef HAVE_IPV6
1977 	       ntohs(srv_sock->addr.plain.sa_family ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port)
1978 #else
1979 	       ntohs(srv_sock->addr.ipv4.sin_port)
1980 #endif
1981 	       );
1982 
1983 	FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf)),con)
1984 
1985 	/* get the server-side of the connection to the client */
1986 	our_addr_len = sizeof(our_addr);
1987 
1988 	if (-1 == getsockname(con->fd, (struct sockaddr *)&our_addr, &our_addr_len)
1989 	    || our_addr_len > sizeof(our_addr)) {
1990 		s = inet_ntop_cache_get_ip(srv, &(srv_sock->addr));
1991 	} else {
1992 		s = inet_ntop_cache_get_ip(srv, &(our_addr));
1993 	}
1994 	FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s)),con)
1995 
1996 	li_utostrn(buf, sizeof(buf),
1997 #ifdef HAVE_IPV6
1998 	       ntohs(con->dst_addr.plain.sa_family ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port)
1999 #else
2000 	       ntohs(con->dst_addr.ipv4.sin_port)
2001 #endif
2002 	       );
2003 
2004 	FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf)),con)
2005 
2006 	s = inet_ntop_cache_get_ip(srv, &(con->dst_addr));
2007 	FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s)),con)
2008 
2009 	if (con->request.content_length > 0 && host->mode != FCGI_AUTHORIZER) {
2010 		/* CGI-SPEC 6.1.2 and FastCGI spec 6.3 */
2011 
2012 		li_itostrn(buf, sizeof(buf), con->request.content_length);
2013 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf)),con)
2014 	}
2015 
2016 	if (host->mode != FCGI_AUTHORIZER) {
2017 		/*
2018 		 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
2019 		 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
2020 		 * (6.1.14, 6.1.6, 6.1.7)
2021 		 * For AUTHORIZER mode these headers should be omitted.
2022 		 */
2023 
2024 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path)),con)
2025 
2026 		if (!buffer_string_is_empty(con->request.pathinfo)) {
2027 			FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo)),con)
2028 
2029 			/* PATH_TRANSLATED is only defined if PATH_INFO is set */
2030 
2031 			if (!buffer_string_is_empty(host->docroot)) {
2032 				buffer_copy_buffer(p->path, host->docroot);
2033 			} else {
2034 				buffer_copy_buffer(p->path, con->physical.basedir);
2035 			}
2036 			buffer_append_string_buffer(p->path, con->request.pathinfo);
2037 			FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p->path)),con)
2038 		} else {
2039 			FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN("")),con)
2040 		}
2041 	}
2042 
2043 	/*
2044 	 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
2045 	 * http://www.php.net/manual/en/reserved.variables.php
2046 	 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
2047 	 * TODO: this code should be checked against cgi.fix_pathinfo php
2048 	 * parameter.
2049 	 */
2050 
2051 	if (!buffer_string_is_empty(host->docroot)) {
2052 		/*
2053 		 * rewrite SCRIPT_FILENAME
2054 		 *
2055 		 */
2056 
2057 		buffer_copy_buffer(p->path, host->docroot);
2058 		buffer_append_string_buffer(p->path, con->uri.path);
2059 
2060 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path)),con)
2061 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host->docroot)),con)
2062 	} else {
2063 		buffer_copy_buffer(p->path, con->physical.path);
2064 
2065 		/* cgi.fix_pathinfo need a broken SCRIPT_FILENAME to find out what PATH_INFO is itself
2066 		 *
2067 		 * see src/sapi/cgi_main.c, init_request_info()
2068 		 */
2069 		if (host->break_scriptfilename_for_php) {
2070 			buffer_append_string_buffer(p->path, con->request.pathinfo);
2071 		}
2072 
2073 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path)),con)
2074 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.basedir)),con)
2075 	}
2076 
2077 	if (!buffer_string_is_empty(host->strip_request_uri)) {
2078 		/* we need at least one char to strip off */
2079 		/**
2080 		 * /app1/index/list
2081 		 *
2082 		 * stripping /app1 or /app1/ should lead to
2083 		 *
2084 		 * /index/list
2085 		 *
2086 		 */
2087 
2088 		if ('/' != host->strip_request_uri->ptr[buffer_string_length(host->strip_request_uri) - 1]) {
2089 			/* fix the user-input to have / as last char */
2090 			buffer_append_string_len(host->strip_request_uri, CONST_STR_LEN("/"));
2091 		}
2092 
2093 		if (buffer_string_length(req_uri) >= buffer_string_length(host->strip_request_uri) &&
2094 		    0 == strncmp(req_uri->ptr, host->strip_request_uri->ptr, buffer_string_length(host->strip_request_uri))) {
2095 			/* the left is the same */
2096 
2097 			FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_URI"),
2098 					req_uri->ptr + (buffer_string_length(host->strip_request_uri) - 1),
2099 					buffer_string_length(req_uri) - (buffer_string_length(host->strip_request_uri) - 1)), con)
2100 		} else {
2101 			FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(req_uri)),con)
2102 		}
2103 	} else {
2104 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(req_uri)),con)
2105 	}
2106 	if (!buffer_string_is_empty(con->uri.query)) {
2107 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query)),con)
2108 	} else {
2109 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN("")),con)
2110 	}
2111 
2112 	s = get_http_method_name(con->request.http_method);
2113 	force_assert(s);
2114 	FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s)),con)
2115 	/* set REDIRECT_STATUS for php compiled with --force-redirect
2116 	 * (if REDIRECT_STATUS has not already been set by error handler) */
2117 	if (0 == con->error_handler_saved_status) {
2118 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")), con);
2119 	}
2120 	s = get_http_version_name(con->request.http_version);
2121 	force_assert(s);
2122 	FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s)),con)
2123 
2124 	if (buffer_is_equal_caseless_string(con->uri.scheme, CONST_STR_LEN("https"))) {
2125 		FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on")),con)
2126 	}
2127 
2128 	FCGI_ENV_ADD_CHECK(fcgi_env_add_request_headers(srv, con, p), con);
2129 
2130 	{
2131 		buffer *b = buffer_init();
2132 
2133 		buffer_copy_string_len(b, (const char *)&beginRecord, sizeof(beginRecord));
2134 
2135 		fcgi_header(&(header), FCGI_PARAMS, request_id, buffer_string_length(p->fcgi_env), 0);
2136 		buffer_append_string_len(b, (const char *)&header, sizeof(header));
2137 		buffer_append_string_buffer(b, p->fcgi_env);
2138 
2139 		fcgi_header(&(header), FCGI_PARAMS, request_id, 0, 0);
2140 		buffer_append_string_len(b, (const char *)&header, sizeof(header));
2141 
2142 		chunkqueue_append_buffer(hctx->wb, b);
2143 		buffer_free(b);
2144 	}
2145 
2146 	if (con->request.content_length) {
2147 		chunkqueue *req_cq = con->request_content_queue;
2148 		off_t offset;
2149 
2150 		/* something to send ? */
2151 		for (offset = 0; offset != req_cq->bytes_in; ) {
2152 			off_t weWant = req_cq->bytes_in - offset > FCGI_MAX_LENGTH ? FCGI_MAX_LENGTH : req_cq->bytes_in - offset;
2153 
2154 			/* we announce toWrite octets
2155 			 * now take all the request_content chunks that we need to fill this request
2156 			 * */
2157 
2158 			fcgi_header(&(header), FCGI_STDIN, request_id, weWant, 0);
2159 			chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
2160 
2161 			if (p->conf.debug > 10) {
2162 				log_error_write(srv, __FILE__, __LINE__, "soso", "tosend:", offset, "/", req_cq->bytes_in);
2163 			}
2164 
2165 			chunkqueue_steal(hctx->wb, req_cq, weWant);
2166 
2167 			offset += weWant;
2168 		}
2169 	}
2170 
2171 	/* terminate STDIN */
2172 	fcgi_header(&(header), FCGI_STDIN, request_id, 0, 0);
2173 	chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
2174 
2175 	return 0;
2176 }
2177 
2178 static int fcgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in) {
2179 	char *s, *ns;
2180 
2181 	handler_ctx *hctx = con->plugin_ctx[p->id];
2182 	fcgi_extension_host *host= hctx->host;
2183 	int have_sendfile2 = 0;
2184 	off_t sendfile2_content_length = 0;
2185 
2186 	UNUSED(srv);
2187 
2188 	/* search for \n */
2189 	for (s = in->ptr; NULL != (ns = strchr(s, '\n')); s = ns + 1) {
2190 		char *key, *value;
2191 		int key_len;
2192 
2193 		/* a good day. Someone has read the specs and is sending a \r\n to us */
2194 
2195 		if (ns > in->ptr &&
2196 		    *(ns-1) == '\r') {
2197 			*(ns-1) = '\0';
2198 		}
2199 
2200 		ns[0] = '\0';
2201 
2202 		key = s;
2203 		if (NULL == (value = strchr(s, ':'))) {
2204 			/* we expect: "<key>: <value>\n" */
2205 			continue;
2206 		}
2207 
2208 		key_len = value - key;
2209 
2210 		value++;
2211 		/* strip WS */
2212 		while (*value == ' ' || *value == '\t') value++;
2213 
2214 		if (host->mode != FCGI_AUTHORIZER ||
2215 		    !(con->http_status == 0 ||
2216 		      con->http_status == 200)) {
2217 			/* authorizers shouldn't affect the response headers sent back to the client */
2218 
2219 			/* don't forward Status: */
2220 			if (0 != strncasecmp(key, "Status", key_len)) {
2221 				data_string *ds;
2222 				if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2223 					ds = data_response_init();
2224 				}
2225 				buffer_copy_string_len(ds->key, key, key_len);
2226 				buffer_copy_string(ds->value, value);
2227 
2228 				array_insert_unique(con->response.headers, (data_unset *)ds);
2229 			}
2230 		}
2231 
2232 		switch(key_len) {
2233 		case 4:
2234 			if (0 == strncasecmp(key, "Date", key_len)) {
2235 				con->parsed_response |= HTTP_DATE;
2236 			}
2237 			break;
2238 		case 6:
2239 			if (0 == strncasecmp(key, "Status", key_len)) {
2240 				int status = strtol(value, NULL, 10);
2241 				if (status >= 100 && status < 1000) {
2242 					con->http_status = status;
2243 					con->parsed_response |= HTTP_STATUS;
2244 				} else {
2245 					con->http_status = 502;
2246 				}
2247 			}
2248 			break;
2249 		case 8:
2250 			if (0 == strncasecmp(key, "Location", key_len)) {
2251 				con->parsed_response |= HTTP_LOCATION;
2252 			}
2253 			break;
2254 		case 10:
2255 			if (0 == strncasecmp(key, "Connection", key_len)) {
2256 				con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
2257 				con->parsed_response |= HTTP_CONNECTION;
2258 			}
2259 			break;
2260 		case 11:
2261 			if (host->xsendfile_allow && 0 == strncasecmp(key, "X-Sendfile2", key_len) && hctx->send_content_body) {
2262 				char *pos = value;
2263 				have_sendfile2 = 1;
2264 
2265 				while (*pos) {
2266 					char *filename, *range;
2267 					stat_cache_entry *sce;
2268 					off_t begin_range, end_range, range_len;
2269 
2270 					while (' ' == *pos) pos++;
2271 					if (!*pos) break;
2272 
2273 					filename = pos;
2274 					if (NULL == (range = strchr(pos, ' '))) {
2275 						/* missing range */
2276 						if (p->conf.debug) {
2277 							log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't find range after filename:", filename);
2278 						}
2279 						return 502;
2280 					}
2281 					buffer_copy_string_len(srv->tmp_buf, filename, range - filename);
2282 
2283 					/* find end of range */
2284 					for (pos = ++range; *pos && *pos != ' ' && *pos != ','; pos++) ;
2285 
2286 					buffer_urldecode_path(srv->tmp_buf);
2287 					buffer_path_simplify(srv->tmp_buf, srv->tmp_buf);
2288 					if (con->conf.force_lowercase_filenames) {
2289 						buffer_to_lower(srv->tmp_buf);
2290 					}
2291 					if (host->xsendfile_docroot->used) {
2292 						size_t i, xlen = buffer_string_length(srv->tmp_buf);
2293 						for (i = 0; i < host->xsendfile_docroot->used; ++i) {
2294 							data_string *ds = (data_string *)host->xsendfile_docroot->data[i];
2295 							size_t dlen = buffer_string_length(ds->value);
2296 							if (dlen <= xlen
2297 							    && (!con->conf.force_lowercase_filenames
2298 								? 0 == memcmp(srv->tmp_buf->ptr, ds->value->ptr, dlen)
2299 								: 0 == strncasecmp(srv->tmp_buf->ptr, ds->value->ptr, dlen))) {
2300 								break;
2301 							}
2302 						}
2303 						if (i == host->xsendfile_docroot->used) {
2304 							log_error_write(srv, __FILE__, __LINE__, "SBs",
2305 									"X-Sendfile2 (", srv->tmp_buf,
2306 									") not under configured x-sendfile-docroot(s)");
2307 							return 403;
2308 						}
2309 					}
2310 
2311 					if (HANDLER_ERROR == stat_cache_get_entry(srv, con, srv->tmp_buf, &sce)) {
2312 						if (p->conf.debug) {
2313 							log_error_write(srv, __FILE__, __LINE__, "sb",
2314 								"send-file error: couldn't get stat_cache entry for X-Sendfile2:",
2315 								srv->tmp_buf);
2316 						}
2317 						return 404;
2318 					} else if (!S_ISREG(sce->st.st_mode)) {
2319 						if (p->conf.debug) {
2320 							log_error_write(srv, __FILE__, __LINE__, "sb",
2321 								"send-file error: wrong filetype for X-Sendfile2:",
2322 								srv->tmp_buf);
2323 						}
2324 						return 502;
2325 					}
2326 					/* found the file */
2327 
2328 					/* parse range */
2329 					begin_range = 0; end_range = sce->st.st_size - 1;
2330 					{
2331 						char *rpos = NULL;
2332 						errno = 0;
2333 						begin_range = strtoll(range, &rpos, 10);
2334 						if (errno != 0 || begin_range < 0 || rpos == range) goto range_failed;
2335 						if ('-' != *rpos++) goto range_failed;
2336 						if (rpos != pos) {
2337 							range = rpos;
2338 							end_range = strtoll(range, &rpos, 10);
2339 							if (errno != 0 || end_range < 0 || rpos == range) goto range_failed;
2340 						}
2341 						if (rpos != pos) goto range_failed;
2342 
2343 						goto range_success;
2344 
2345 range_failed:
2346 						if (p->conf.debug) {
2347 							log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't decode range after filename:", filename);
2348 						}
2349 						return 502;
2350 
2351 range_success: ;
2352 					}
2353 
2354 					/* no parameters accepted */
2355 
2356 					while (*pos == ' ') pos++;
2357 					if (*pos != '\0' && *pos != ',') return 502;
2358 
2359 					range_len = end_range - begin_range + 1;
2360 					if (range_len < 0) return 502;
2361 					if (range_len != 0) {
2362 						if (0 != http_chunk_append_file_range(srv, con, srv->tmp_buf, begin_range, range_len)) {
2363 							return 502;
2364 						}
2365 					}
2366 					sendfile2_content_length += range_len;
2367 
2368 					if (*pos == ',') pos++;
2369 				}
2370 			}
2371 			break;
2372 		case 14:
2373 			if (0 == strncasecmp(key, "Content-Length", key_len)) {
2374 				con->response.content_length = strtoul(value, NULL, 10);
2375 				con->parsed_response |= HTTP_CONTENT_LENGTH;
2376 
2377 				if (con->response.content_length < 0) con->response.content_length = 0;
2378 			}
2379 			break;
2380 		default:
2381 			break;
2382 		}
2383 	}
2384 
2385 	if (have_sendfile2) {
2386 		data_string *dcls;
2387 
2388 		hctx->send_content_body = 0;
2389 		joblist_append(srv, con);
2390 
2391 		/* fix content-length */
2392 		if (NULL == (dcls = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2393 			dcls = data_response_init();
2394 		}
2395 
2396 		buffer_copy_string_len(dcls->key, "Content-Length", sizeof("Content-Length")-1);
2397 		buffer_copy_int(dcls->value, sendfile2_content_length);
2398 		array_replace(con->response.headers, (data_unset *)dcls);
2399 
2400 		con->parsed_response |= HTTP_CONTENT_LENGTH;
2401 		con->response.content_length = sendfile2_content_length;
2402 	}
2403 
2404 	/* CGI/1.1 rev 03 - 7.2.1.2 */
2405 	if ((con->parsed_response & HTTP_LOCATION) &&
2406 	    !(con->parsed_response & HTTP_STATUS)) {
2407 		con->http_status = 302;
2408 	}
2409 
2410 	return 0;
2411 }
2412 
2413 typedef struct {
2414 	buffer  *b;
2415 	size_t   len;
2416 	int      type;
2417 	int      padding;
2418 	size_t   request_id;
2419 } fastcgi_response_packet;
2420 
2421 static int fastcgi_get_packet(server *srv, handler_ctx *hctx, fastcgi_response_packet *packet) {
2422 	chunk *c;
2423 	size_t offset;
2424 	size_t toread;
2425 	FCGI_Header *header;
2426 
2427 	if (!hctx->rb->first) return -1;
2428 
2429 	packet->b = buffer_init();
2430 	packet->len = 0;
2431 	packet->type = 0;
2432 	packet->padding = 0;
2433 	packet->request_id = 0;
2434 
2435 	offset = 0; toread = 8;
2436 	/* get at least the FastCGI header */
2437 	for (c = hctx->rb->first; c; c = c->next) {
2438 		size_t weHave = buffer_string_length(c->mem) - c->offset;
2439 
2440 		if (weHave > toread) weHave = toread;
2441 
2442 		buffer_append_string_len(packet->b, c->mem->ptr + c->offset, weHave);
2443 		toread -= weHave;
2444 		offset = weHave; /* skip offset bytes in chunk for "real" data */
2445 
2446 		if (0 == toread) break;
2447 	}
2448 
2449 	if (buffer_string_length(packet->b) < sizeof(FCGI_Header)) {
2450 		/* no header */
2451 		if (hctx->plugin_data->conf.debug) {
2452 			log_error_write(srv, __FILE__, __LINE__, "sdsds", "FastCGI: header too small:", buffer_string_length(packet->b), "bytes <", sizeof(FCGI_Header), "bytes, waiting for more data");
2453 		}
2454 
2455 		buffer_free(packet->b);
2456 
2457 		return -1;
2458 	}
2459 
2460 	/* we have at least a header, now check how much me have to fetch */
2461 	header = (FCGI_Header *)(packet->b->ptr);
2462 
2463 	packet->len = (header->contentLengthB0 | (header->contentLengthB1 << 8)) + header->paddingLength;
2464 	packet->request_id = (header->requestIdB0 | (header->requestIdB1 << 8));
2465 	packet->type = header->type;
2466 	packet->padding = header->paddingLength;
2467 
2468 	/* ->b should only be the content */
2469 	buffer_string_set_length(packet->b, 0);
2470 
2471 	if (packet->len) {
2472 		/* copy the content */
2473 		for (; c && (buffer_string_length(packet->b) < packet->len); c = c->next) {
2474 			size_t weWant = packet->len - buffer_string_length(packet->b);
2475 			size_t weHave = buffer_string_length(c->mem) - c->offset - offset;
2476 
2477 			if (weHave > weWant) weHave = weWant;
2478 
2479 			buffer_append_string_len(packet->b, c->mem->ptr + c->offset + offset, weHave);
2480 
2481 			/* we only skipped the first bytes as they belonged to the fcgi header */
2482 			offset = 0;
2483 		}
2484 
2485 		if (buffer_string_length(packet->b) < packet->len) {
2486 			/* we didn't get the full packet */
2487 
2488 			buffer_free(packet->b);
2489 			return -1;
2490 		}
2491 
2492 		buffer_string_set_length(packet->b, buffer_string_length(packet->b) - packet->padding);
2493 	}
2494 
2495 	chunkqueue_mark_written(hctx->rb, packet->len + sizeof(FCGI_Header));
2496 
2497 	return 0;
2498 }
2499 
2500 static int fcgi_demux_response(server *srv, handler_ctx *hctx) {
2501 	int fin = 0;
2502 	int toread, ret;
2503 	ssize_t r;
2504 
2505 	plugin_data *p    = hctx->plugin_data;
2506 	connection *con   = hctx->remote_conn;
2507 	int fcgi_fd       = hctx->fd;
2508 	fcgi_extension_host *host= hctx->host;
2509 	fcgi_proc *proc   = hctx->proc;
2510 
2511 	/*
2512 	 * check how much we have to read
2513 	 */
2514 	if (ioctl(hctx->fd, FIONREAD, &toread)) {
2515 		if (errno == EAGAIN) return 0;
2516 		log_error_write(srv, __FILE__, __LINE__, "sd",
2517 				"unexpected end-of-file (perhaps the fastcgi process died):",
2518 				fcgi_fd);
2519 		return -1;
2520 	}
2521 
2522 	if (toread > 0) {
2523 		char *mem;
2524 		size_t mem_len;
2525 
2526 		chunkqueue_get_memory(hctx->rb, &mem, &mem_len, 0, toread);
2527 		r = read(hctx->fd, mem, mem_len);
2528 		chunkqueue_use_memory(hctx->rb, r > 0 ? r : 0);
2529 
2530 		if (-1 == r) {
2531 			if (errno == EAGAIN) return 0;
2532 			log_error_write(srv, __FILE__, __LINE__, "sds",
2533 					"unexpected end-of-file (perhaps the fastcgi process died):",
2534 					fcgi_fd, strerror(errno));
2535 			return -1;
2536 		}
2537 	} else {
2538 		log_error_write(srv, __FILE__, __LINE__, "ssdsb",
2539 				"unexpected end-of-file (perhaps the fastcgi process died):",
2540 				"pid:", proc->pid,
2541 				"socket:", proc->connection_name);
2542 
2543 		return -1;
2544 	}
2545 
2546 	/*
2547 	 * parse the fastcgi packets and forward the content to the write-queue
2548 	 *
2549 	 */
2550 	while (fin == 0) {
2551 		fastcgi_response_packet packet;
2552 
2553 		/* check if we have at least one packet */
2554 		if (0 != fastcgi_get_packet(srv, hctx, &packet)) {
2555 			/* no full packet */
2556 			break;
2557 		}
2558 
2559 		switch(packet.type) {
2560 		case FCGI_STDOUT:
2561 			if (packet.len == 0) break;
2562 
2563 			/* is the header already finished */
2564 			if (0 == con->file_started) {
2565 				char *c;
2566 				data_string *ds;
2567 
2568 				/* search for header terminator
2569 				 *
2570 				 * if we start with \r\n check if last packet terminated with \r\n
2571 				 * if we start with \n check if last packet terminated with \n
2572 				 * search for \r\n\r\n
2573 				 * search for \n\n
2574 				 */
2575 
2576 				buffer_append_string_buffer(hctx->response_header, packet.b);
2577 
2578 				if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\r\n\r\n")))) {
2579 					char *hend = c + 4; /* header end == body start */
2580 					size_t hlen = hend - hctx->response_header->ptr;
2581 					buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2582 					buffer_string_set_length(hctx->response_header, hlen);
2583 				} else if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\n\n")))) {
2584 					char *hend = c + 2; /* header end == body start */
2585 					size_t hlen = hend - hctx->response_header->ptr;
2586 					buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2587 					buffer_string_set_length(hctx->response_header, hlen);
2588 				} else {
2589 					/* no luck, no header found */
2590 					break;
2591 				}
2592 
2593 				/* parse the response header */
2594 				if ((ret = fcgi_response_parse(srv, con, p, hctx->response_header))) {
2595 					con->http_status = ret;
2596 					hctx->send_content_body = 0;
2597 					con->file_started = 1;
2598 					break;
2599 				}
2600 
2601 				con->file_started = 1;
2602 
2603 				if (host->mode == FCGI_AUTHORIZER &&
2604 				    (con->http_status == 0 ||
2605 				     con->http_status == 200)) {
2606 					/* a authorizer with approved the static request, ignore the content here */
2607 					hctx->send_content_body = 0;
2608 				}
2609 
2610 				if (host->xsendfile_allow && hctx->send_content_body &&
2611 				    (NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-LIGHTTPD-send-file"))
2612 					  || NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-Sendfile")))) {
2613 					http_response_xsendfile(srv, con, ds->value, host->xsendfile_docroot);
2614 					if (con->mode == DIRECT) {
2615 						fin = 1;
2616 					}
2617 
2618 					hctx->send_content_body = 0; /* ignore the content */
2619 					break;
2620 				}
2621 
2622 				/* enable chunked-transfer-encoding */
2623 				if (con->request.http_version == HTTP_VERSION_1_1 &&
2624 				    !(con->parsed_response & HTTP_CONTENT_LENGTH)) {
2625 					con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
2626 				}
2627 			}
2628 
2629 			if (hctx->send_content_body && !buffer_string_is_empty(packet.b)) {
2630 				http_chunk_append_buffer(srv, con, packet.b);
2631 			}
2632 			break;
2633 		case FCGI_STDERR:
2634 			if (packet.len == 0) break;
2635 
2636 			log_error_write_multiline_buffer(srv, __FILE__, __LINE__, packet.b, "s",
2637 					"FastCGI-stderr:");
2638 
2639 			break;
2640 		case FCGI_END_REQUEST:
2641 			con->file_finished = 1;
2642 
2643 			if (host->mode != FCGI_AUTHORIZER ||
2644 			    !(con->http_status == 0 ||
2645 			      con->http_status == 200)) {
2646 				/* send chunk-end if necessary */
2647 				http_chunk_close(srv, con);
2648 			}
2649 
2650 			fin = 1;
2651 			break;
2652 		default:
2653 			log_error_write(srv, __FILE__, __LINE__, "sd",
2654 					"FastCGI: header.type not handled: ", packet.type);
2655 			break;
2656 		}
2657 		buffer_free(packet.b);
2658 	}
2659 
2660 	return fin;
2661 }
2662 
2663 static int fcgi_restart_dead_procs(server *srv, plugin_data *p, fcgi_extension_host *host) {
2664 	fcgi_proc *proc;
2665 
2666 	for (proc = host->first; proc; proc = proc->next) {
2667 		int status;
2668 
2669 		if (p->conf.debug > 2) {
2670 			log_error_write(srv, __FILE__, __LINE__,  "sbdddd",
2671 					"proc:",
2672 					proc->connection_name,
2673 					proc->state,
2674 					proc->is_local,
2675 					proc->load,
2676 					proc->pid);
2677 		}
2678 
2679 		/*
2680 		 * if the remote side is overloaded, we check back after <n> seconds
2681 		 *
2682 		 */
2683 		switch (proc->state) {
2684 		case PROC_STATE_KILLED:
2685 		case PROC_STATE_UNSET:
2686 			/* this should never happen as long as adaptive spawing is disabled */
2687 			force_assert(0);
2688 
2689 			break;
2690 		case PROC_STATE_RUNNING:
2691 			break;
2692 		case PROC_STATE_OVERLOADED:
2693 			if (srv->cur_ts <= proc->disabled_until) break;
2694 
2695 			proc->state = PROC_STATE_RUNNING;
2696 			host->active_procs++;
2697 
2698 			log_error_write(srv, __FILE__, __LINE__,  "sbdb",
2699 					"fcgi-server re-enabled:",
2700 					host->host, host->port,
2701 					host->unixsocket);
2702 			break;
2703 		case PROC_STATE_DIED_WAIT_FOR_PID:
2704 			/* non-local procs don't have PIDs to wait for */
2705 			if (!proc->is_local) {
2706 				proc->state = PROC_STATE_DIED;
2707 			} else {
2708 				/* the child should not terminate at all */
2709 
2710 				for ( ;; ) {
2711 					switch(waitpid(proc->pid, &status, WNOHANG)) {
2712 					case 0:
2713 						/* child is still alive */
2714 						if (srv->cur_ts <= proc->disabled_until) break;
2715 
2716 						proc->state = PROC_STATE_RUNNING;
2717 						host->active_procs++;
2718 
2719 						log_error_write(srv, __FILE__, __LINE__,  "sbdb",
2720 							"fcgi-server re-enabled:",
2721 							host->host, host->port,
2722 							host->unixsocket);
2723 						break;
2724 					case -1:
2725 						if (errno == EINTR) continue;
2726 
2727 						log_error_write(srv, __FILE__, __LINE__, "sd",
2728 							"child died somehow, waitpid failed:",
2729 							errno);
2730 						proc->state = PROC_STATE_DIED;
2731 						break;
2732 					default:
2733 						if (WIFEXITED(status)) {
2734 #if 0
2735 							log_error_write(srv, __FILE__, __LINE__, "sdsd",
2736 								"child exited, pid:", proc->pid,
2737 								"status:", WEXITSTATUS(status));
2738 #endif
2739 						} else if (WIFSIGNALED(status)) {
2740 							log_error_write(srv, __FILE__, __LINE__, "sd",
2741 								"child signaled:",
2742 								WTERMSIG(status));
2743 						} else {
2744 							log_error_write(srv, __FILE__, __LINE__, "sd",
2745 								"child died somehow:",
2746 								status);
2747 						}
2748 
2749 						proc->state = PROC_STATE_DIED;
2750 						break;
2751 					}
2752 					break;
2753 				}
2754 			}
2755 
2756 			/* fall through if we have a dead proc now */
2757 			if (proc->state != PROC_STATE_DIED) break;
2758 
2759 		case PROC_STATE_DIED:
2760 			/* local procs get restarted by us,
2761 			 * remote ones hopefully by the admin */
2762 
2763 			if (!buffer_string_is_empty(host->bin_path)) {
2764 				/* we still have connections bound to this proc,
2765 				 * let them terminate first */
2766 				if (proc->load != 0) break;
2767 
2768 				/* restart the child */
2769 
2770 				if (p->conf.debug) {
2771 					log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
2772 							"--- fastcgi spawning",
2773 							"\n\tsocket", proc->connection_name,
2774 							"\n\tcurrent:", 1, "/", host->max_procs);
2775 				}
2776 
2777 				if (fcgi_spawn_connection(srv, p, host, proc)) {
2778 					log_error_write(srv, __FILE__, __LINE__, "s",
2779 							"ERROR: spawning fcgi failed.");
2780 					return HANDLER_ERROR;
2781 				}
2782 			} else {
2783 				if (srv->cur_ts <= proc->disabled_until) break;
2784 
2785 				proc->state = PROC_STATE_RUNNING;
2786 				host->active_procs++;
2787 
2788 				log_error_write(srv, __FILE__, __LINE__,  "sb",
2789 						"fcgi-server re-enabled:",
2790 						proc->connection_name);
2791 			}
2792 			break;
2793 		}
2794 	}
2795 
2796 	return 0;
2797 }
2798 
2799 static handler_t fcgi_write_request(server *srv, handler_ctx *hctx) {
2800 	plugin_data *p    = hctx->plugin_data;
2801 	fcgi_extension_host *host= hctx->host;
2802 	connection *con   = hctx->remote_conn;
2803 	fcgi_proc  *proc;
2804 
2805 	int ret;
2806 
2807 	/* sanity check:
2808 	 *  - host != NULL
2809 	 *  - either:
2810 	 *     - tcp socket (do not check host->host->uses, as it may be not set which means INADDR_LOOPBACK)
2811 	 *     - unix socket
2812 	 */
2813 	if (!host) {
2814 		log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: host = NULL");
2815 		return HANDLER_ERROR;
2816 	}
2817 	if ((!host->port && buffer_string_is_empty(host->unixsocket))) {
2818 		log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: neither host->port nor host->unixsocket is set");
2819 		return HANDLER_ERROR;
2820 	}
2821 
2822 	/* we can't handle this in the switch as we have to fall through in it */
2823 	if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
2824 		int socket_error;
2825 		socklen_t socket_error_len = sizeof(socket_error);
2826 
2827 		/* try to finish the connect() */
2828 		if (0 != getsockopt(hctx->fd, SOL_SOCKET, SO_ERROR, &socket_error, &socket_error_len)) {
2829 			log_error_write(srv, __FILE__, __LINE__, "ss",
2830 					"getsockopt failed:", strerror(errno));
2831 
2832 			fcgi_host_disable(srv, hctx);
2833 
2834 			return HANDLER_ERROR;
2835 		}
2836 		if (socket_error != 0) {
2837 			if (!hctx->proc->is_local || p->conf.debug) {
2838 				/* local procs get restarted */
2839 
2840 				log_error_write(srv, __FILE__, __LINE__, "sssb",
2841 						"establishing connection failed:", strerror(socket_error),
2842 						"socket:", hctx->proc->connection_name);
2843 			}
2844 
2845 			fcgi_host_disable(srv, hctx);
2846 			log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2847 				"backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2848 				"reconnects:", hctx->reconnects,
2849 				"load:", host->load);
2850 
2851 			fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2852 			buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2853 
2854 			status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2855 
2856 			return HANDLER_ERROR;
2857 		}
2858 		/* go on with preparing the request */
2859 		hctx->state = FCGI_STATE_PREPARE_WRITE;
2860 	}
2861 
2862 
2863 	switch(hctx->state) {
2864 	case FCGI_STATE_CONNECT_DELAYED:
2865 		/* should never happen */
2866 		return HANDLER_WAIT_FOR_EVENT;
2867 	case FCGI_STATE_INIT:
2868 		/* do we have a running process for this host (max-procs) ? */
2869 		hctx->proc = NULL;
2870 
2871 		for (proc = hctx->host->first;
2872 		     proc && proc->state != PROC_STATE_RUNNING;
2873 		     proc = proc->next);
2874 
2875 		/* all children are dead */
2876 		if (proc == NULL) {
2877 			hctx->fde_ndx = -1;
2878 
2879 			return HANDLER_ERROR;
2880 		}
2881 
2882 		hctx->proc = proc;
2883 
2884 		/* check the other procs if they have a lower load */
2885 		for (proc = proc->next; proc; proc = proc->next) {
2886 			if (proc->state != PROC_STATE_RUNNING) continue;
2887 			if (proc->load < hctx->proc->load) hctx->proc = proc;
2888 		}
2889 
2890 		if (-1 == (hctx->fd = socket(host->family, SOCK_STREAM, 0))) {
2891 			if (errno == EMFILE ||
2892 			    errno == EINTR) {
2893 				log_error_write(srv, __FILE__, __LINE__, "sd",
2894 						"wait for fd at connection:", con->fd);
2895 
2896 				return HANDLER_WAIT_FOR_FD;
2897 			}
2898 
2899 			log_error_write(srv, __FILE__, __LINE__, "ssdd",
2900 					"socket failed:", strerror(errno), srv->cur_fds, srv->max_fds);
2901 			return HANDLER_ERROR;
2902 		}
2903 		hctx->fde_ndx = -1;
2904 
2905 		srv->cur_fds++;
2906 
2907 		fdevent_register(srv->ev, hctx->fd, fcgi_handle_fdevent, hctx);
2908 
2909 		if (-1 == fdevent_fcntl_set(srv->ev, hctx->fd)) {
2910 			log_error_write(srv, __FILE__, __LINE__, "ss",
2911 					"fcntl failed:", strerror(errno));
2912 
2913 			return HANDLER_ERROR;
2914 		}
2915 
2916 		if (hctx->proc->is_local) {
2917 			hctx->pid = hctx->proc->pid;
2918 		}
2919 
2920 		switch (fcgi_establish_connection(srv, hctx)) {
2921 		case CONNECTION_DELAYED:
2922 			/* connection is in progress, wait for an event and call getsockopt() below */
2923 
2924 			fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2925 
2926 			fcgi_set_state(srv, hctx, FCGI_STATE_CONNECT_DELAYED);
2927 			return HANDLER_WAIT_FOR_EVENT;
2928 		case CONNECTION_OVERLOADED:
2929 			/* cool down the backend, it is overloaded
2930 			 * -> EAGAIN */
2931 
2932 			if (hctx->host->disable_time) {
2933 				log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2934 					"backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2935 					"reconnects:", hctx->reconnects,
2936 					"load:", host->load);
2937 
2938 				hctx->proc->disabled_until = srv->cur_ts + hctx->host->disable_time;
2939 				if (hctx->proc->state == PROC_STATE_RUNNING) hctx->host->active_procs--;
2940 				hctx->proc->state = PROC_STATE_OVERLOADED;
2941 			}
2942 
2943 			fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2944 			buffer_append_string_len(p->statuskey, CONST_STR_LEN(".overloaded"));
2945 
2946 			status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2947 
2948 			return HANDLER_ERROR;
2949 		case CONNECTION_DEAD:
2950 			/* we got a hard error from the backend like
2951 			 * - ECONNREFUSED for tcp-ip sockets
2952 			 * - ENOENT for unix-domain-sockets
2953 			 *
2954 			 * for check if the host is back in hctx->host->disable_time seconds
2955 			 *  */
2956 
2957 			fcgi_host_disable(srv, hctx);
2958 
2959 			log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2960 				"backend died; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2961 				"reconnects:", hctx->reconnects,
2962 				"load:", host->load);
2963 
2964 			fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2965 			buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2966 
2967 			status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2968 
2969 			return HANDLER_ERROR;
2970 		case CONNECTION_OK:
2971 			/* everything is ok, go on */
2972 
2973 			fcgi_set_state(srv, hctx, FCGI_STATE_PREPARE_WRITE);
2974 
2975 			break;
2976 		}
2977 		/* fallthrough */
2978 	case FCGI_STATE_PREPARE_WRITE:
2979 		/* ok, we have the connection */
2980 
2981 		fcgi_proc_load_inc(srv, hctx);
2982 		hctx->got_proc = 1;
2983 
2984 		status_counter_inc(srv, CONST_STR_LEN("fastcgi.requests"));
2985 
2986 		fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2987 		buffer_append_string_len(p->statuskey, CONST_STR_LEN(".connected"));
2988 
2989 		status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2990 
2991 		if (p->conf.debug) {
2992 			log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
2993 				"got proc:",
2994 				"pid:", hctx->proc->pid,
2995 				"socket:", hctx->proc->connection_name,
2996 				"load:", hctx->proc->load);
2997 		}
2998 
2999 		/* move the proc-list entry down the list */
3000 		if (hctx->request_id == 0) {
3001 			hctx->request_id = 1; /* always use id 1 as we don't use multiplexing */
3002 		} else {
3003 			log_error_write(srv, __FILE__, __LINE__, "sd",
3004 					"fcgi-request is already in use:", hctx->request_id);
3005 		}
3006 
3007 		if (-1 == fcgi_create_env(srv, hctx, hctx->request_id)) return HANDLER_ERROR;
3008 
3009 		fcgi_set_state(srv, hctx, FCGI_STATE_WRITE);
3010 		/* fall through */
3011 	case FCGI_STATE_WRITE:
3012 		ret = srv->network_backend_write(srv, con, hctx->fd, hctx->wb, MAX_WRITE_LIMIT);
3013 
3014 		chunkqueue_remove_finished_chunks(hctx->wb);
3015 
3016 		if (ret < 0) {
3017 			switch(errno) {
3018 			case EPIPE:
3019 			case ENOTCONN:
3020 			case ECONNRESET:
3021 				/* the connection got dropped after accept()
3022 				 * we don't care about that - if you accept() it, you have to handle it.
3023 				 */
3024 
3025 				log_error_write(srv, __FILE__, __LINE__, "ssosb",
3026 							"connection was dropped after accept() (perhaps the fastcgi process died),",
3027 						"write-offset:", hctx->wb->bytes_out,
3028 						"socket:", hctx->proc->connection_name);
3029 
3030 				return HANDLER_ERROR;
3031 			default:
3032 				log_error_write(srv, __FILE__, __LINE__, "ssd",
3033 						"write failed:", strerror(errno), errno);
3034 
3035 				return HANDLER_ERROR;
3036 			}
3037 		}
3038 
3039 		if (hctx->wb->bytes_out == hctx->wb->bytes_in) {
3040 			fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
3041 			fcgi_set_state(srv, hctx, FCGI_STATE_READ);
3042 		} else {
3043 			fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN|FDEVENT_OUT);
3044 		}
3045 
3046 		return HANDLER_WAIT_FOR_EVENT;
3047 	case FCGI_STATE_READ:
3048 		/* waiting for a response */
3049 		return HANDLER_WAIT_FOR_EVENT;
3050 	default:
3051 		log_error_write(srv, __FILE__, __LINE__, "s", "(debug) unknown state");
3052 		return HANDLER_ERROR;
3053 	}
3054 }
3055 
3056 
3057 /* might be called on fdevent after a connect() is delay too
3058  * */
3059 static handler_t fcgi_send_request(server *srv, handler_ctx *hctx) {
3060 	fcgi_extension_host *host;
3061 	handler_t rc;
3062 
3063 	/* we don't have a host yet, choose one
3064 	 * -> this happens in the first round
3065 	 *    and when the host died and we have to select a new one */
3066 	if (hctx->host == NULL) {
3067 		size_t k;
3068 		int ndx, used = -1;
3069 
3070 		/* check if the next server has no load. */
3071 		ndx = hctx->ext->last_used_ndx + 1;
3072 		if(ndx >= (int) hctx->ext->used || ndx < 0) ndx = 0;
3073 		host = hctx->ext->hosts[ndx];
3074 		if (host->load > 0) {
3075 			/* get backend with the least load. */
3076 			for (k = 0, ndx = -1; k < hctx->ext->used; k++) {
3077 				host = hctx->ext->hosts[k];
3078 
3079 				/* we should have at least one proc that can do something */
3080 				if (host->active_procs == 0) continue;
3081 
3082 				if (used == -1 || host->load < used) {
3083 					used = host->load;
3084 
3085 					ndx = k;
3086 				}
3087 			}
3088 		}
3089 
3090 		/* found a server */
3091 		if (ndx == -1) {
3092 			/* all hosts are down */
3093 
3094 			fcgi_connection_close(srv, hctx);
3095 
3096 			return HANDLER_FINISHED;
3097 		}
3098 
3099 		hctx->ext->last_used_ndx = ndx;
3100 		host = hctx->ext->hosts[ndx];
3101 
3102 		/*
3103 		 * if check-local is disabled, use the uri.path handler
3104 		 *
3105 		 */
3106 
3107 		/* init handler-context */
3108 
3109 		/* we put a connection on this host, move the other new connections to other hosts
3110 		 *
3111 		 * as soon as hctx->host is unassigned, decrease the load again */
3112 		fcgi_host_assign(srv, hctx, host);
3113 		hctx->proc = NULL;
3114 	} else {
3115 		host = hctx->host;
3116 	}
3117 
3118 	/* ok, create the request */
3119 	rc = fcgi_write_request(srv, hctx);
3120 	if (HANDLER_ERROR != rc) {
3121 		return rc;
3122 	} else {
3123 		plugin_data *p  = hctx->plugin_data;
3124 		connection *con = hctx->remote_conn;
3125 
3126 		if (hctx->state == FCGI_STATE_INIT ||
3127 		    hctx->state == FCGI_STATE_CONNECT_DELAYED) {
3128 			fcgi_restart_dead_procs(srv, p, host);
3129 
3130 			/* cleanup this request and let the request handler start this request again */
3131 			if (hctx->reconnects < 5) {
3132 				fcgi_reconnect(srv, hctx);
3133 
3134 				return HANDLER_COMEBACK;
3135 			} else {
3136 				fcgi_connection_close(srv, hctx);
3137 				con->http_status = 503;
3138 
3139 				return HANDLER_FINISHED;
3140 			}
3141 		} else {
3142 			int status = con->http_status;
3143 			fcgi_connection_close(srv, hctx);
3144 			con->http_status = (status == 400) ? 400 : 503; /* see FCGI_ENV_ADD_CHECK() for 400 error */
3145 
3146 			return HANDLER_FINISHED;
3147 		}
3148 	}
3149 }
3150 
3151 
3152 SUBREQUEST_FUNC(mod_fastcgi_handle_subrequest) {
3153 	plugin_data *p = p_d;
3154 
3155 	handler_ctx *hctx = con->plugin_ctx[p->id];
3156 
3157 	if (NULL == hctx) return HANDLER_GO_ON;
3158 
3159 	/* not my job */
3160 	if (con->mode != p->id) return HANDLER_GO_ON;
3161 
3162 	if (con->state == CON_STATE_READ_POST) {
3163 		handler_t r = connection_handle_read_post_state(srv, con);
3164 		if (r != HANDLER_GO_ON) return r;
3165 	}
3166 
3167 	return (hctx->state != FCGI_STATE_READ)
3168 	  ? fcgi_send_request(srv, hctx)
3169 	  : HANDLER_WAIT_FOR_EVENT;
3170 }
3171 
3172 static handler_t fcgi_handle_fdevent(server *srv, void *ctx, int revents) {
3173 	handler_ctx *hctx = ctx;
3174 	connection  *con  = hctx->remote_conn;
3175 	plugin_data *p    = hctx->plugin_data;
3176 
3177 	fcgi_proc *proc   = hctx->proc;
3178 	fcgi_extension_host *host= hctx->host;
3179 
3180 	joblist_append(srv, con);
3181 
3182 	if ((revents & FDEVENT_IN) &&
3183 	    hctx->state == FCGI_STATE_READ) {
3184 		switch (fcgi_demux_response(srv, hctx)) {
3185 		case 0:
3186 			break;
3187 		case 1:
3188 
3189 			if (host->mode == FCGI_AUTHORIZER &&
3190 		   	    (con->http_status == 200 ||
3191 			     con->http_status == 0)) {
3192 				/*
3193 				 * If we are here in AUTHORIZER mode then a request for authorizer
3194 				 * was processed already, and status 200 has been returned. We need
3195 				 * now to handle authorized request.
3196 				 */
3197 
3198 				buffer_copy_buffer(con->physical.doc_root, host->docroot);
3199 				buffer_copy_buffer(con->physical.basedir, host->docroot);
3200 
3201 				buffer_copy_buffer(con->physical.path, host->docroot);
3202 				buffer_append_string_buffer(con->physical.path, con->uri.path);
3203 
3204 				con->mode = DIRECT;/*(avoid changing con->state, con->http_status)*/
3205 				fcgi_connection_close(srv, hctx);
3206 				con->http_status = 0;
3207 				con->file_started = 1; /* fcgi_extension won't touch the request afterwards */
3208 			} else {
3209 				/* we are done */
3210 				fcgi_connection_close(srv, hctx);
3211 			}
3212 
3213 			return HANDLER_FINISHED;
3214 		case -1:
3215 			if (proc->pid && proc->state != PROC_STATE_DIED) {
3216 				int status;
3217 
3218 				/* only fetch the zombie if it is not already done */
3219 
3220 				switch(waitpid(proc->pid, &status, WNOHANG)) {
3221 				case 0:
3222 					/* child is still alive */
3223 					break;
3224 				case -1:
3225 					break;
3226 				default:
3227 					/* the child should not terminate at all */
3228 					if (WIFEXITED(status)) {
3229 						log_error_write(srv, __FILE__, __LINE__, "sdsd",
3230 								"child exited, pid:", proc->pid,
3231 								"status:", WEXITSTATUS(status));
3232 					} else if (WIFSIGNALED(status)) {
3233 						log_error_write(srv, __FILE__, __LINE__, "sd",
3234 								"child signaled:",
3235 								WTERMSIG(status));
3236 					} else {
3237 						log_error_write(srv, __FILE__, __LINE__, "sd",
3238 								"child died somehow:",
3239 								status);
3240 					}
3241 
3242 					if (p->conf.debug) {
3243 						log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
3244 								"--- fastcgi spawning",
3245 								"\n\tsocket", proc->connection_name,
3246 								"\n\tcurrent:", 1, "/", host->max_procs);
3247 					}
3248 
3249 					if (fcgi_spawn_connection(srv, p, host, proc)) {
3250 						/* respawning failed, retry later */
3251 						proc->state = PROC_STATE_DIED;
3252 
3253 						log_error_write(srv, __FILE__, __LINE__, "s",
3254 								"respawning failed, will retry later");
3255 					}
3256 
3257 					break;
3258 				}
3259 			}
3260 
3261 			if (con->file_started == 0) {
3262 				/* nothing has been sent out yet, try to use another child */
3263 
3264 				if (hctx->wb->bytes_out == 0 &&
3265 				    hctx->reconnects < 5) {
3266 
3267 					log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3268 						"response not received, request not sent",
3269 						"on socket:", proc->connection_name,
3270 						"for", con->uri.path, "?", con->uri.query, ", reconnecting");
3271 
3272 					fcgi_reconnect(srv, hctx);
3273 
3274 					return HANDLER_COMEBACK;
3275 				}
3276 
3277 				log_error_write(srv, __FILE__, __LINE__, "sosbsBSBs",
3278 						"response not received, request sent:", hctx->wb->bytes_out,
3279 						"on socket:", proc->connection_name,
3280 						"for", con->uri.path, "?", con->uri.query, ", closing connection");
3281 
3282 				fcgi_connection_close(srv, hctx);
3283 			} else {
3284 				/* response might have been already started, kill the connection */
3285 				log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3286 						"response already sent out, but backend returned error",
3287 						"on socket:", proc->connection_name,
3288 						"for", con->uri.path, "?", con->uri.query, ", terminating connection");
3289 
3290 				con->keep_alive = 0;
3291 				con->file_finished = 1;
3292 				con->mode = DIRECT; /*(avoid sending final chunked block)*/
3293 				fcgi_connection_close(srv, hctx);
3294 			}
3295 
3296 			return HANDLER_FINISHED;
3297 		}
3298 	}
3299 
3300 	if (revents & FDEVENT_OUT) {
3301 		if (hctx->state == FCGI_STATE_CONNECT_DELAYED ||
3302 		    hctx->state == FCGI_STATE_WRITE) {
3303 			/* we are allowed to send something out
3304 			 *
3305 			 * 1. in an unfinished connect() call
3306 			 * 2. in an unfinished write() call (long POST request)
3307 			 */
3308 			return fcgi_send_request(srv, hctx); /*(might invalidate hctx)*/
3309 		} else {
3310 			log_error_write(srv, __FILE__, __LINE__, "sd",
3311 					"got a FDEVENT_OUT and didn't know why:",
3312 					hctx->state);
3313 		}
3314 	}
3315 
3316 	/* perhaps this issue is already handled */
3317 	if (revents & FDEVENT_HUP) {
3318 		if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
3319 			/* getoptsock will catch this one (right ?)
3320 			 *
3321 			 * if we are in connect we might get an EINPROGRESS
3322 			 * in the first call and an FDEVENT_HUP in the
3323 			 * second round
3324 			 *
3325 			 * FIXME: as it is a bit ugly.
3326 			 *
3327 			 */
3328 			fcgi_send_request(srv, hctx);
3329 		} else if (hctx->state == FCGI_STATE_READ &&
3330 			   hctx->proc->port == 0) {
3331 			/* FIXME:
3332 			 *
3333 			 * ioctl says 8192 bytes to read from PHP and we receive directly a HUP for the socket
3334 			 * even if the FCGI_FIN packet is not received yet
3335 			 */
3336 		} else {
3337 			log_error_write(srv, __FILE__, __LINE__, "sBSbsbsd",
3338 					"error: unexpected close of fastcgi connection for",
3339 					con->uri.path, "?", con->uri.query,
3340 					"(no fastcgi process on socket:", proc->connection_name, "?)",
3341 					hctx->state);
3342 
3343 			fcgi_connection_close(srv, hctx);
3344 		}
3345 	} else if (revents & FDEVENT_ERR) {
3346 		log_error_write(srv, __FILE__, __LINE__, "s",
3347 				"fcgi: got a FDEVENT_ERR. Don't know why.");
3348 
3349 		if (con->file_started) {
3350 			con->keep_alive = 0;
3351 			con->file_finished = 1;
3352 			con->mode = DIRECT; /*(avoid sending final chunked block)*/
3353 		}
3354 		fcgi_connection_close(srv, hctx);
3355 	}
3356 
3357 	return HANDLER_FINISHED;
3358 }
3359 
3360 #define PATCH(x) \
3361 	p->conf.x = s->x;
3362 static int fcgi_patch_connection(server *srv, connection *con, plugin_data *p) {
3363 	size_t i, j;
3364 	plugin_config *s = p->config_storage[0];
3365 
3366 	PATCH(exts);
3367 	PATCH(debug);
3368 	PATCH(ext_mapping);
3369 
3370 	/* skip the first, the global context */
3371 	for (i = 1; i < srv->config_context->used; i++) {
3372 		data_config *dc = (data_config *)srv->config_context->data[i];
3373 		s = p->config_storage[i];
3374 
3375 		/* condition didn't match */
3376 		if (!config_check_cond(srv, con, dc)) continue;
3377 
3378 		/* merge config */
3379 		for (j = 0; j < dc->value->used; j++) {
3380 			data_unset *du = dc->value->data[j];
3381 
3382 			if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.server"))) {
3383 				PATCH(exts);
3384 			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.debug"))) {
3385 				PATCH(debug);
3386 			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.map-extensions"))) {
3387 				PATCH(ext_mapping);
3388 			}
3389 		}
3390 	}
3391 
3392 	return 0;
3393 }
3394 #undef PATCH
3395 
3396 
3397 static handler_t fcgi_check_extension(server *srv, connection *con, void *p_d, int uri_path_handler) {
3398 	plugin_data *p = p_d;
3399 	size_t s_len;
3400 	size_t k;
3401 	buffer *fn;
3402 	fcgi_extension *extension = NULL;
3403 	fcgi_extension_host *host = NULL;
3404 
3405 	if (con->mode != DIRECT) return HANDLER_GO_ON;
3406 
3407 	/* Possibly, we processed already this request */
3408 	if (con->file_started == 1) return HANDLER_GO_ON;
3409 
3410 	fn = uri_path_handler ? con->uri.path : con->physical.path;
3411 
3412 	if (buffer_string_is_empty(fn)) return HANDLER_GO_ON;
3413 
3414 	s_len = buffer_string_length(fn);
3415 
3416 	fcgi_patch_connection(srv, con, p);
3417 
3418 	/* fastcgi.map-extensions maps extensions to existing fastcgi.server entries
3419 	 *
3420 	 * fastcgi.map-extensions = ( ".php3" => ".php" )
3421 	 *
3422 	 * fastcgi.server = ( ".php" => ... )
3423 	 *
3424 	 * */
3425 
3426 	/* check if extension-mapping matches */
3427 	for (k = 0; k < p->conf.ext_mapping->used; k++) {
3428 		data_string *ds = (data_string *)p->conf.ext_mapping->data[k];
3429 		size_t ct_len; /* length of the config entry */
3430 
3431 		if (buffer_is_empty(ds->key)) continue;
3432 
3433 		ct_len = buffer_string_length(ds->key);
3434 
3435 		if (s_len < ct_len) continue;
3436 
3437 		/* found a mapping */
3438 		if (0 == strncmp(fn->ptr + s_len - ct_len, ds->key->ptr, ct_len)) {
3439 			/* check if we know the extension */
3440 
3441 			/* we can reuse k here */
3442 			for (k = 0; k < p->conf.exts->used; k++) {
3443 				extension = p->conf.exts->exts[k];
3444 
3445 				if (buffer_is_equal(ds->value, extension->key)) {
3446 					break;
3447 				}
3448 			}
3449 
3450 			if (k == p->conf.exts->used) {
3451 				/* found nothign */
3452 				extension = NULL;
3453 			}
3454 			break;
3455 		}
3456 	}
3457 
3458 	if (extension == NULL) {
3459 		size_t uri_path_len = buffer_string_length(con->uri.path);
3460 
3461 		/* check if extension matches */
3462 		for (k = 0; k < p->conf.exts->used; k++) {
3463 			size_t ct_len; /* length of the config entry */
3464 			fcgi_extension *ext = p->conf.exts->exts[k];
3465 
3466 			if (buffer_is_empty(ext->key)) continue;
3467 
3468 			ct_len = buffer_string_length(ext->key);
3469 
3470 			/* check _url_ in the form "/fcgi_pattern" */
3471 			if (ext->key->ptr[0] == '/') {
3472 				if ((ct_len <= uri_path_len) &&
3473 				    (strncmp(con->uri.path->ptr, ext->key->ptr, ct_len) == 0)) {
3474 					extension = ext;
3475 					break;
3476 				}
3477 			} else if ((ct_len <= s_len) && (0 == strncmp(fn->ptr + s_len - ct_len, ext->key->ptr, ct_len))) {
3478 				/* check extension in the form ".fcg" */
3479 				extension = ext;
3480 				break;
3481 			}
3482 		}
3483 		/* extension doesn't match */
3484 		if (NULL == extension) {
3485 			return HANDLER_GO_ON;
3486 		}
3487 	}
3488 
3489 	/* check if we have at least one server for this extension up and running */
3490 	for (k = 0; k < extension->used; k++) {
3491 		fcgi_extension_host *h = extension->hosts[k];
3492 
3493 		/* we should have at least one proc that can do something */
3494 		if (h->active_procs == 0) {
3495 			continue;
3496 		}
3497 
3498 		/* we found one host that is alive */
3499 		host = h;
3500 		break;
3501 	}
3502 
3503 	if (!host) {
3504 		/* sorry, we don't have a server alive for this ext */
3505 		con->http_status = 500;
3506 		con->mode = DIRECT;
3507 
3508 		/* only send the 'no handler' once */
3509 		if (!extension->note_is_sent) {
3510 			extension->note_is_sent = 1;
3511 
3512 			log_error_write(srv, __FILE__, __LINE__, "sBSbsbs",
3513 					"all handlers for", con->uri.path, "?", con->uri.query,
3514 					"on", extension->key,
3515 					"are down.");
3516 		}
3517 
3518 		return HANDLER_FINISHED;
3519 	}
3520 
3521 	/* a note about no handler is not sent yet */
3522 	extension->note_is_sent = 0;
3523 
3524 	/*
3525 	 * if check-local is disabled, use the uri.path handler
3526 	 *
3527 	 */
3528 
3529 	/* init handler-context */
3530 	if (uri_path_handler) {
3531 		if (host->check_local == 0) {
3532 			handler_ctx *hctx;
3533 			char *pathinfo;
3534 
3535 			hctx = handler_ctx_init();
3536 
3537 			hctx->remote_conn      = con;
3538 			hctx->plugin_data      = p;
3539 			hctx->proc	       = NULL;
3540 			hctx->ext              = extension;
3541 
3542 
3543 			hctx->conf.exts        = p->conf.exts;
3544 			hctx->conf.debug       = p->conf.debug;
3545 
3546 			con->plugin_ctx[p->id] = hctx;
3547 
3548 			con->mode = p->id;
3549 
3550 			if (con->conf.log_request_handling) {
3551 				log_error_write(srv, __FILE__, __LINE__, "s",
3552 				"handling it in mod_fastcgi");
3553 			}
3554 
3555 			/* do not split path info for authorizer */
3556 			if (host->mode != FCGI_AUTHORIZER) {
3557 				/* the prefix is the SCRIPT_NAME,
3558 				* everything from start to the next slash
3559 				* this is important for check-local = "disable"
3560 				*
3561 				* if prefix = /admin.fcgi
3562 				*
3563 				* /admin.fcgi/foo/bar
3564 				*
3565 				* SCRIPT_NAME = /admin.fcgi
3566 				* PATH_INFO   = /foo/bar
3567 				*
3568 				* if prefix = /fcgi-bin/
3569 				*
3570 				* /fcgi-bin/foo/bar
3571 				*
3572 				* SCRIPT_NAME = /fcgi-bin/foo
3573 				* PATH_INFO   = /bar
3574 				*
3575 				* if prefix = /, and fix-root-path-name is enable
3576 				*
3577 				* /fcgi-bin/foo/bar
3578 				*
3579 				* SCRIPT_NAME = /fcgi-bin/foo
3580 				* PATH_INFO   = /bar
3581 				*
3582 				*/
3583 
3584 				/* the rewrite is only done for /prefix/? matches */
3585 				if (host->fix_root_path_name && extension->key->ptr[0] == '/' && extension->key->ptr[1] == '\0') {
3586 					buffer_copy_string(con->request.pathinfo, con->uri.path->ptr);
3587 					buffer_string_set_length(con->uri.path, 0);
3588 				} else if (extension->key->ptr[0] == '/' &&
3589 					buffer_string_length(con->uri.path) > buffer_string_length(extension->key) &&
3590 					NULL != (pathinfo = strchr(con->uri.path->ptr + buffer_string_length(extension->key), '/'))) {
3591 					/* rewrite uri.path and pathinfo */
3592 
3593 					buffer_copy_string(con->request.pathinfo, pathinfo);
3594 					buffer_string_set_length(con->uri.path, buffer_string_length(con->uri.path) - buffer_string_length(con->request.pathinfo));
3595 				}
3596 			}
3597 		}
3598 	} else {
3599 		handler_ctx *hctx;
3600 		hctx = handler_ctx_init();
3601 
3602 		hctx->remote_conn      = con;
3603 		hctx->plugin_data      = p;
3604 		hctx->proc             = NULL;
3605 		hctx->ext              = extension;
3606 
3607 		hctx->conf.exts        = p->conf.exts;
3608 		hctx->conf.debug       = p->conf.debug;
3609 
3610 		con->plugin_ctx[p->id] = hctx;
3611 
3612 		con->mode = p->id;
3613 
3614 		if (con->conf.log_request_handling) {
3615 			log_error_write(srv, __FILE__, __LINE__, "s", "handling it in mod_fastcgi");
3616 		}
3617 	}
3618 
3619 	return HANDLER_GO_ON;
3620 }
3621 
3622 /* uri-path handler */
3623 static handler_t fcgi_check_extension_1(server *srv, connection *con, void *p_d) {
3624 	return fcgi_check_extension(srv, con, p_d, 1);
3625 }
3626 
3627 /* start request handler */
3628 static handler_t fcgi_check_extension_2(server *srv, connection *con, void *p_d) {
3629 	return fcgi_check_extension(srv, con, p_d, 0);
3630 }
3631 
3632 
3633 TRIGGER_FUNC(mod_fastcgi_handle_trigger) {
3634 	plugin_data *p = p_d;
3635 	size_t i, j, n;
3636 
3637 
3638 	/* perhaps we should kill a connect attempt after 10-15 seconds
3639 	 *
3640 	 * currently we wait for the TCP timeout which is 180 seconds on Linux
3641 	 *
3642 	 *
3643 	 *
3644 	 */
3645 
3646 	/* check all children if they are still up */
3647 
3648 	for (i = 0; i < srv->config_context->used; i++) {
3649 		plugin_config *conf;
3650 		fcgi_exts *exts;
3651 
3652 		conf = p->config_storage[i];
3653 
3654 		exts = conf->exts;
3655 
3656 		for (j = 0; j < exts->used; j++) {
3657 			fcgi_extension *ex;
3658 
3659 			ex = exts->exts[j];
3660 
3661 			for (n = 0; n < ex->used; n++) {
3662 
3663 				fcgi_proc *proc;
3664 				fcgi_extension_host *host;
3665 
3666 				host = ex->hosts[n];
3667 
3668 				fcgi_restart_dead_procs(srv, p, host);
3669 
3670 				for (proc = host->unused_procs; proc; proc = proc->next) {
3671 					int status;
3672 
3673 					if (proc->pid == 0) continue;
3674 
3675 					switch (waitpid(proc->pid, &status, WNOHANG)) {
3676 					case 0:
3677 						/* child still running after timeout, good */
3678 						break;
3679 					case -1:
3680 						if (errno != EINTR) {
3681 							/* no PID found ? should never happen */
3682 							log_error_write(srv, __FILE__, __LINE__, "sddss",
3683 									"pid ", proc->pid, proc->state,
3684 									"not found:", strerror(errno));
3685 
3686 #if 0
3687 							if (errno == ECHILD) {
3688 								/* someone else has cleaned up for us */
3689 								proc->pid = 0;
3690 								proc->state = PROC_STATE_UNSET;
3691 							}
3692 #endif
3693 						}
3694 						break;
3695 					default:
3696 						/* the child should not terminate at all */
3697 						if (WIFEXITED(status)) {
3698 							if (proc->state != PROC_STATE_KILLED) {
3699 								log_error_write(srv, __FILE__, __LINE__, "sdb",
3700 										"child exited:",
3701 										WEXITSTATUS(status), proc->connection_name);
3702 							}
3703 						} else if (WIFSIGNALED(status)) {
3704 							if (WTERMSIG(status) != SIGTERM) {
3705 								log_error_write(srv, __FILE__, __LINE__, "sd",
3706 										"child signaled:",
3707 										WTERMSIG(status));
3708 							}
3709 						} else {
3710 							log_error_write(srv, __FILE__, __LINE__, "sd",
3711 									"child died somehow:",
3712 									status);
3713 						}
3714 						proc->pid = 0;
3715 						if (proc->state == PROC_STATE_RUNNING) host->active_procs--;
3716 						proc->state = PROC_STATE_UNSET;
3717 						host->max_id--;
3718 					}
3719 				}
3720 			}
3721 		}
3722 	}
3723 
3724 	return HANDLER_GO_ON;
3725 }
3726 
3727 
3728 int mod_fastcgi_plugin_init(plugin *p);
3729 int mod_fastcgi_plugin_init(plugin *p) {
3730 	p->version      = LIGHTTPD_VERSION_ID;
3731 	p->name         = buffer_init_string("fastcgi");
3732 
3733 	p->init         = mod_fastcgi_init;
3734 	p->cleanup      = mod_fastcgi_free;
3735 	p->set_defaults = mod_fastcgi_set_defaults;
3736 	p->connection_reset        = fcgi_connection_reset;
3737 	p->handle_connection_close = fcgi_connection_reset;
3738 	p->handle_uri_clean        = fcgi_check_extension_1;
3739 	p->handle_subrequest_start = fcgi_check_extension_2;
3740 	p->handle_subrequest       = mod_fastcgi_handle_subrequest;
3741 	p->handle_trigger          = mod_fastcgi_handle_trigger;
3742 
3743 	p->data         = NULL;
3744 
3745 	return 0;
3746 }
3747