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