1 #include "buffer.h"
2 #include "server.h"
3 #include "keyvalue.h"
4 #include "log.h"
5 
6 #include "http_chunk.h"
7 #include "fdevent.h"
8 #include "connections.h"
9 #include "response.h"
10 #include "joblist.h"
11 
12 #include "plugin.h"
13 
14 #include "inet_ntop_cache.h"
15 
16 #include <sys/types.h>
17 #include <unistd.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <ctype.h>
23 #include <assert.h>
24 #include <signal.h>
25 
26 #include <stdio.h>
27 
28 #ifdef HAVE_SYS_FILIO_H
29 # include <sys/filio.h>
30 #endif
31 
32 #include "sys-socket.h"
33 
34 #ifdef HAVE_SYS_UIO_H
35 # include <sys/uio.h>
36 #endif
37 
38 #ifdef HAVE_SYS_WAIT_H
39 # include <sys/wait.h>
40 #endif
41 
42 #include "version.h"
43 
44 enum {EOL_UNSET, EOL_N, EOL_RN};
45 
46 /*
47  *
48  * TODO:
49  *
50  * - add timeout for a connect to a non-scgi process
51  *   (use state_timestamp + state)
52  *
53  */
54 
55 typedef struct scgi_proc {
56 	size_t id; /* id will be between 1 and max_procs */
57 	buffer *socket; /* config.socket + "-" + id */
58 	unsigned port;  /* config.port + pno */
59 
60 	pid_t pid;   /* PID of the spawned process (0 if not spawned locally) */
61 
62 
63 	size_t load; /* number of requests waiting on this process */
64 
65 	time_t last_used; /* see idle_timeout */
66 	size_t requests;  /* see max_requests */
67 	struct scgi_proc *prev, *next; /* see first */
68 
69 	time_t disable_ts; /* replace by host->something */
70 
71 	int is_local;
72 
73 	enum { PROC_STATE_UNSET,            /* init-phase */
74 			PROC_STATE_RUNNING, /* alive */
75 			PROC_STATE_DIED_WAIT_FOR_PID,
76 			PROC_STATE_KILLED,  /* was killed as we don't have the load anymore */
77 			PROC_STATE_DIED,    /* marked as dead, should be restarted */
78 			PROC_STATE_DISABLED /* proc disabled as it resulted in an error */
79 	} state;
80 } scgi_proc;
81 
82 typedef struct {
83 	/* list of processes handling this extension
84 	 * sorted by lowest load
85 	 *
86 	 * whenever a job is done move it up in the list
87 	 * until it is sorted, move it down as soon as the
88 	 * job is started
89 	 */
90 	scgi_proc *first;
91 	scgi_proc *unused_procs;
92 
93 	/*
94 	 * spawn at least min_procs, at max_procs.
95 	 *
96 	 * as soon as the load of the first entry
97 	 * is max_load_per_proc we spawn a new one
98 	 * and add it to the first entry and give it
99 	 * the load
100 	 *
101 	 */
102 
103 	unsigned short min_procs;
104 	unsigned short max_procs;
105 	size_t num_procs;    /* how many procs are started */
106 	size_t active_procs; /* how many of them are really running */
107 
108 	unsigned short max_load_per_proc;
109 
110 	/*
111 	 * kick the process from the list if it was not
112 	 * used for idle_timeout until min_procs is
113 	 * reached. this helps to get the processlist
114 	 * small again we had a small peak load.
115 	 *
116 	 */
117 
118 	unsigned short idle_timeout;
119 
120 	/*
121 	 * time after a disabled remote connection is tried to be re-enabled
122 	 *
123 	 *
124 	 */
125 
126 	unsigned short disable_time;
127 
128 	/*
129 	 * same scgi processes get a little bit larger
130 	 * than wanted. max_requests_per_proc kills a
131 	 * process after a number of handled requests.
132 	 *
133 	 */
134 	size_t max_requests_per_proc;
135 
136 
137 	/* config */
138 
139 	/*
140 	 * host:port
141 	 *
142 	 * if host is one of the local IP adresses the
143 	 * whole connection is local
144 	 *
145 	 * if tcp/ip should be used host AND port have
146 	 * to be specified
147 	 *
148 	 */
149 	buffer *host;
150 	unsigned short port;
151 
152 	/*
153 	 * Unix Domain Socket
154 	 *
155 	 * instead of TCP/IP we can use Unix Domain Sockets
156 	 * - more secure (you have fileperms to play with)
157 	 * - more control (on locally)
158 	 * - more speed (no extra overhead)
159 	 */
160 	buffer *unixsocket;
161 
162 	/* if socket is local we can start the scgi
163 	 * process ourself
164 	 *
165 	 * bin-path is the path to the binary
166 	 *
167 	 * check min_procs and max_procs for the number
168 	 * of process to start-up
169 	 */
170 	buffer *bin_path;
171 
172 	/* bin-path is set bin-environment is taken to
173 	 * create the environement before starting the
174 	 * FastCGI process
175 	 *
176 	 */
177 	array *bin_env;
178 
179 	array *bin_env_copy;
180 
181 	/*
182 	 * docroot-translation between URL->phys and the
183 	 * remote host
184 	 *
185 	 * reasons:
186 	 * - different dir-layout if remote
187 	 * - chroot if local
188 	 *
189 	 */
190 	buffer *docroot;
191 
192 	/*
193 	 * check_local tell you if the phys file is stat()ed
194 	 * or not. FastCGI doesn't care if the service is
195 	 * remote. If the web-server side doesn't contain
196 	 * the scgi-files we should not stat() for them
197 	 * and say '404 not found'.
198 	 */
199 	unsigned short check_local;
200 
201 	/*
202 	 * append PATH_INFO to SCRIPT_FILENAME
203 	 *
204 	 * php needs this if cgi.fix_pathinfo is provied
205 	 *
206 	 */
207 
208 	/*
209 	 * workaround for program when prefix="/"
210 	 *
211 	 * rule to build PATH_INFO is hardcoded for when check_local is disabled
212 	 * enable this option to use the workaround
213 	 *
214 	 */
215 
216 	unsigned short fix_root_path_name;
217 	ssize_t load; /* replace by host->load */
218 
219 	size_t max_id; /* corresponds most of the time to
220 	num_procs.
221 
222 	only if a process is killed max_id waits for the process itself
223 	to die and decrements its afterwards */
224 } scgi_extension_host;
225 
226 /*
227  * one extension can have multiple hosts assigned
228  * one host can spawn additional processes on the same
229  *   socket (if we control it)
230  *
231  * ext -> host -> procs
232  *    1:n     1:n
233  *
234  * if the scgi process is remote that whole goes down
235  * to
236  *
237  * ext -> host -> procs
238  *    1:n     1:1
239  *
240  * in case of PHP and FCGI_CHILDREN we have again a procs
241  * but we don't control it directly.
242  *
243  */
244 
245 typedef struct {
246 	buffer *key; /* like .php */
247 
248 	int note_is_sent;
249 	scgi_extension_host **hosts;
250 
251 	size_t used;
252 	size_t size;
253 } scgi_extension;
254 
255 typedef struct {
256 	scgi_extension **exts;
257 
258 	size_t used;
259 	size_t size;
260 } scgi_exts;
261 
262 
263 typedef struct {
264 	scgi_exts *exts;
265 
266 	int debug;
267 } plugin_config;
268 
269 typedef struct {
270 	char **ptr;
271 
272 	size_t size;
273 	size_t used;
274 } char_array;
275 
276 /* generic plugin data, shared between all connections */
277 typedef struct {
278 	PLUGIN_DATA;
279 
280 	buffer *scgi_env;
281 
282 	buffer *path;
283 	buffer *parse_response;
284 
285 	plugin_config **config_storage;
286 
287 	plugin_config conf; /* this is only used as long as no handler_ctx is setup */
288 } plugin_data;
289 
290 /* connection specific data */
291 typedef enum { FCGI_STATE_INIT, FCGI_STATE_CONNECT, FCGI_STATE_PREPARE_WRITE,
292 		FCGI_STATE_WRITE, FCGI_STATE_READ
293 } scgi_connection_state_t;
294 
295 typedef struct {
296 	buffer  *response;
297 	size_t   response_len;
298 	int      response_type;
299 	int      response_padding;
300 
301 	scgi_proc *proc;
302 	scgi_extension_host *host;
303 
304 	scgi_connection_state_t state;
305 	time_t   state_timestamp;
306 
307 	int      reconnects; /* number of reconnect attempts */
308 
309 	read_buffer *rb;
310 	chunkqueue *wb;
311 
312 	buffer   *response_header;
313 
314 	int       delayed;   /* flag to mark that the connect() is delayed */
315 
316 	size_t    request_id;
317 	int       fd;        /* fd to the scgi process */
318 	int       fde_ndx;   /* index into the fd-event buffer */
319 
320 	pid_t     pid;
321 	int       got_proc;
322 
323 	plugin_config conf;
324 
325 	connection *remote_conn;  /* dumb pointer */
326 	plugin_data *plugin_data; /* dumb pointer */
327 } handler_ctx;
328 
329 
330 /* ok, we need a prototype */
331 static handler_t scgi_handle_fdevent(server *srv, void *ctx, int revents);
332 
333 int scgi_proclist_sort_down(server *srv, scgi_extension_host *host, scgi_proc *proc);
334 
reset_signals(void)335 static void reset_signals(void) {
336 #ifdef SIGTTOU
337 	signal(SIGTTOU, SIG_DFL);
338 #endif
339 #ifdef SIGTTIN
340 	signal(SIGTTIN, SIG_DFL);
341 #endif
342 #ifdef SIGTSTP
343 	signal(SIGTSTP, SIG_DFL);
344 #endif
345 	signal(SIGHUP, SIG_DFL);
346 	signal(SIGPIPE, SIG_DFL);
347 	signal(SIGUSR1, SIG_DFL);
348 }
349 
handler_ctx_init(void)350 static handler_ctx * handler_ctx_init(void) {
351 	handler_ctx * hctx;
352 
353 	hctx = calloc(1, sizeof(*hctx));
354 	assert(hctx);
355 
356 	hctx->fde_ndx = -1;
357 
358 	hctx->response = buffer_init();
359 	hctx->response_header = buffer_init();
360 
361 	hctx->request_id = 0;
362 	hctx->state = FCGI_STATE_INIT;
363 	hctx->proc = NULL;
364 
365 	hctx->response_len = 0;
366 	hctx->response_type = 0;
367 	hctx->response_padding = 0;
368 	hctx->fd = -1;
369 
370 	hctx->reconnects = 0;
371 
372 	hctx->wb = chunkqueue_init();
373 
374 	return hctx;
375 }
376 
handler_ctx_free(handler_ctx * hctx)377 static void handler_ctx_free(handler_ctx *hctx) {
378 	buffer_free(hctx->response);
379 	buffer_free(hctx->response_header);
380 
381 	chunkqueue_free(hctx->wb);
382 
383 	if (hctx->rb) {
384 		if (hctx->rb->ptr) free(hctx->rb->ptr);
385 		free(hctx->rb);
386 	}
387 
388 	free(hctx);
389 }
390 
scgi_process_init(void)391 static scgi_proc *scgi_process_init(void) {
392 	scgi_proc *f;
393 
394 	f = calloc(1, sizeof(*f));
395 	f->socket = buffer_init();
396 
397 	f->prev = NULL;
398 	f->next = NULL;
399 
400 	return f;
401 }
402 
scgi_process_free(scgi_proc * f)403 static void scgi_process_free(scgi_proc *f) {
404 	if (!f) return;
405 
406 	scgi_process_free(f->next);
407 
408 	buffer_free(f->socket);
409 
410 	free(f);
411 }
412 
scgi_host_init(void)413 static scgi_extension_host *scgi_host_init(void) {
414 	scgi_extension_host *f;
415 
416 	f = calloc(1, sizeof(*f));
417 
418 	f->host = buffer_init();
419 	f->unixsocket = buffer_init();
420 	f->docroot = buffer_init();
421 	f->bin_path = buffer_init();
422 	f->bin_env = array_init();
423 	f->bin_env_copy = array_init();
424 
425 	return f;
426 }
427 
scgi_host_free(scgi_extension_host * h)428 static void scgi_host_free(scgi_extension_host *h) {
429 	if (!h) return;
430 
431 	buffer_free(h->host);
432 	buffer_free(h->unixsocket);
433 	buffer_free(h->docroot);
434 	buffer_free(h->bin_path);
435 	array_free(h->bin_env);
436 	array_free(h->bin_env_copy);
437 
438 	scgi_process_free(h->first);
439 	scgi_process_free(h->unused_procs);
440 
441 	free(h);
442 
443 }
444 
scgi_extensions_init(void)445 static scgi_exts *scgi_extensions_init(void) {
446 	scgi_exts *f;
447 
448 	f = calloc(1, sizeof(*f));
449 
450 	return f;
451 }
452 
scgi_extensions_free(scgi_exts * f)453 static void scgi_extensions_free(scgi_exts *f) {
454 	size_t i;
455 
456 	if (!f) return;
457 
458 	for (i = 0; i < f->used; i++) {
459 		scgi_extension *fe;
460 		size_t j;
461 
462 		fe = f->exts[i];
463 
464 		for (j = 0; j < fe->used; j++) {
465 			scgi_extension_host *h;
466 
467 			h = fe->hosts[j];
468 
469 			scgi_host_free(h);
470 		}
471 
472 		buffer_free(fe->key);
473 		free(fe->hosts);
474 
475 		free(fe);
476 	}
477 
478 	free(f->exts);
479 
480 	free(f);
481 }
482 
scgi_extension_insert(scgi_exts * ext,buffer * key,scgi_extension_host * fh)483 static int scgi_extension_insert(scgi_exts *ext, buffer *key, scgi_extension_host *fh) {
484 	scgi_extension *fe;
485 	size_t i;
486 
487 	/* there is something */
488 
489 	for (i = 0; i < ext->used; i++) {
490 		if (buffer_is_equal(key, ext->exts[i]->key)) {
491 			break;
492 		}
493 	}
494 
495 	if (i == ext->used) {
496 		/* filextension is new */
497 		fe = calloc(1, sizeof(*fe));
498 		assert(fe);
499 		fe->key = buffer_init();
500 		buffer_copy_string_buffer(fe->key, key);
501 
502 		/* */
503 
504 		if (ext->size == 0) {
505 			ext->size = 8;
506 			ext->exts = malloc(ext->size * sizeof(*(ext->exts)));
507 			assert(ext->exts);
508 		} else if (ext->used == ext->size) {
509 			ext->size += 8;
510 			ext->exts = realloc(ext->exts, ext->size * sizeof(*(ext->exts)));
511 			assert(ext->exts);
512 		}
513 		ext->exts[ext->used++] = fe;
514 	} else {
515 		fe = ext->exts[i];
516 	}
517 
518 	if (fe->size == 0) {
519 		fe->size = 4;
520 		fe->hosts = malloc(fe->size * sizeof(*(fe->hosts)));
521 		assert(fe->hosts);
522 	} else if (fe->size == fe->used) {
523 		fe->size += 4;
524 		fe->hosts = realloc(fe->hosts, fe->size * sizeof(*(fe->hosts)));
525 		assert(fe->hosts);
526 	}
527 
528 	fe->hosts[fe->used++] = fh;
529 
530 	return 0;
531 
532 }
533 
INIT_FUNC(mod_scgi_init)534 INIT_FUNC(mod_scgi_init) {
535 	plugin_data *p;
536 
537 	p = calloc(1, sizeof(*p));
538 
539 	p->scgi_env = buffer_init();
540 
541 	p->path = buffer_init();
542 	p->parse_response = buffer_init();
543 
544 	return p;
545 }
546 
547 
FREE_FUNC(mod_scgi_free)548 FREE_FUNC(mod_scgi_free) {
549 	plugin_data *p = p_d;
550 
551 	UNUSED(srv);
552 
553 	buffer_free(p->scgi_env);
554 	buffer_free(p->path);
555 	buffer_free(p->parse_response);
556 
557 	if (p->config_storage) {
558 		size_t i, j, n;
559 		for (i = 0; i < srv->config_context->used; i++) {
560 			plugin_config *s = p->config_storage[i];
561 			scgi_exts *exts;
562 
563 			if (!s) continue;
564 
565 			exts = s->exts;
566 
567 			for (j = 0; j < exts->used; j++) {
568 				scgi_extension *ex;
569 
570 				ex = exts->exts[j];
571 
572 				for (n = 0; n < ex->used; n++) {
573 					scgi_proc *proc;
574 					scgi_extension_host *host;
575 
576 					host = ex->hosts[n];
577 
578 					for (proc = host->first; proc; proc = proc->next) {
579 						if (proc->pid != 0) kill(proc->pid, SIGTERM);
580 
581 						if (proc->is_local &&
582 						    !buffer_is_empty(proc->socket)) {
583 							unlink(proc->socket->ptr);
584 						}
585 					}
586 
587 					for (proc = host->unused_procs; proc; proc = proc->next) {
588 						if (proc->pid != 0) kill(proc->pid, SIGTERM);
589 
590 						if (proc->is_local &&
591 						    !buffer_is_empty(proc->socket)) {
592 							unlink(proc->socket->ptr);
593 						}
594 					}
595 				}
596 			}
597 
598 			scgi_extensions_free(s->exts);
599 
600 			free(s);
601 		}
602 		free(p->config_storage);
603 	}
604 
605 	free(p);
606 
607 	return HANDLER_GO_ON;
608 }
609 
env_add(char_array * env,const char * key,size_t key_len,const char * val,size_t val_len)610 static int env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) {
611 	char *dst;
612 	size_t i;
613 
614 	if (!key || !val) return -1;
615 
616 	dst = malloc(key_len + val_len + 3);
617 	memcpy(dst, key, key_len);
618 	dst[key_len] = '=';
619 	/* add the \0 from the value */
620 	memcpy(dst + key_len + 1, val, val_len + 1);
621 
622 	for (i = 0; i < env->used; i++) {
623 		if (0 == strncmp(dst, env->ptr[i], key_len + 1)) {
624 			/* don't care about free as we are in a forked child which is going to exec(...) */
625 			/* free(env->ptr[i]); */
626 			env->ptr[i] = dst;
627 			return 0;
628 		}
629 	}
630 
631 	if (env->size == 0) {
632 		env->size = 16;
633 		env->ptr = malloc(env->size * sizeof(*env->ptr));
634 	} else if (env->size == env->used) {
635 		env->size += 16;
636 		env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
637 	}
638 
639 	env->ptr[env->used++] = dst;
640 
641 	return 0;
642 }
643 
scgi_spawn_connection(server * srv,plugin_data * p,scgi_extension_host * host,scgi_proc * proc)644 static int scgi_spawn_connection(server *srv,
645 				 plugin_data *p,
646 				 scgi_extension_host *host,
647 				 scgi_proc *proc) {
648 	int scgi_fd;
649 	int socket_type, status;
650 	struct timeval tv = { 0, 100 * 1000 };
651 #ifdef HAVE_SYS_UN_H
652 	struct sockaddr_un scgi_addr_un;
653 #endif
654 	struct sockaddr_in scgi_addr_in;
655 	struct sockaddr *scgi_addr;
656 
657 	socklen_t servlen;
658 
659 #ifndef HAVE_FORK
660 	return -1;
661 #endif
662 
663 	if (p->conf.debug) {
664 		log_error_write(srv, __FILE__, __LINE__, "sdb",
665 				"new proc, socket:", proc->port, proc->socket);
666 	}
667 
668 	if (!buffer_is_empty(proc->socket)) {
669 		memset(&scgi_addr, 0, sizeof(scgi_addr));
670 
671 #ifdef HAVE_SYS_UN_H
672 		scgi_addr_un.sun_family = AF_UNIX;
673 		strcpy(scgi_addr_un.sun_path, proc->socket->ptr);
674 
675 #ifdef SUN_LEN
676 		servlen = SUN_LEN(&scgi_addr_un);
677 #else
678 		/* stevens says: */
679 		servlen = proc->socket->used + sizeof(scgi_addr_un.sun_family);
680 #endif
681 		socket_type = AF_UNIX;
682 		scgi_addr = (struct sockaddr *) &scgi_addr_un;
683 #else
684 		log_error_write(srv, __FILE__, __LINE__, "s",
685 				"ERROR: Unix Domain sockets are not supported.");
686 		return -1;
687 #endif
688 	} else {
689 		scgi_addr_in.sin_family = AF_INET;
690 
691 		if (buffer_is_empty(host->host)) {
692 			scgi_addr_in.sin_addr.s_addr = htonl(INADDR_ANY);
693 		} else {
694 			struct hostent *he;
695 
696 			/* set a usefull default */
697 			scgi_addr_in.sin_addr.s_addr = htonl(INADDR_ANY);
698 
699 
700 			if (NULL == (he = gethostbyname(host->host->ptr))) {
701 				log_error_write(srv, __FILE__, __LINE__,
702 						"sdb", "gethostbyname failed: ",
703 						h_errno, host->host);
704 				return -1;
705 			}
706 
707 			if (he->h_addrtype != AF_INET) {
708 				log_error_write(srv, __FILE__, __LINE__, "sd", "addr-type != AF_INET: ", he->h_addrtype);
709 				return -1;
710 			}
711 
712 			if (he->h_length != sizeof(struct in_addr)) {
713 				log_error_write(srv, __FILE__, __LINE__, "sd", "addr-length != sizeof(in_addr): ", he->h_length);
714 				return -1;
715 			}
716 
717 			memcpy(&(scgi_addr_in.sin_addr.s_addr), he->h_addr_list[0], he->h_length);
718 
719 		}
720 		scgi_addr_in.sin_port = htons(proc->port);
721 		servlen = sizeof(scgi_addr_in);
722 
723 		socket_type = AF_INET;
724 		scgi_addr = (struct sockaddr *) &scgi_addr_in;
725 	}
726 
727 	if (-1 == (scgi_fd = socket(socket_type, SOCK_STREAM, 0))) {
728 		log_error_write(srv, __FILE__, __LINE__, "ss",
729 				"failed:", strerror(errno));
730 		return -1;
731 	}
732 
733 	if (-1 == connect(scgi_fd, scgi_addr, servlen)) {
734 		/* server is not up, spawn in  */
735 		pid_t child;
736 		int val;
737 
738 		if (!buffer_is_empty(proc->socket)) {
739 			unlink(proc->socket->ptr);
740 		}
741 
742 		close(scgi_fd);
743 
744 		/* reopen socket */
745 		if (-1 == (scgi_fd = socket(socket_type, SOCK_STREAM, 0))) {
746 			log_error_write(srv, __FILE__, __LINE__, "ss",
747 				"socket failed:", strerror(errno));
748 			return -1;
749 		}
750 
751 		val = 1;
752 		if (setsockopt(scgi_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) {
753 			log_error_write(srv, __FILE__, __LINE__, "ss",
754 					"socketsockopt failed:", strerror(errno));
755 			return -1;
756 		}
757 
758 		/* create socket */
759 		if (-1 == bind(scgi_fd, scgi_addr, servlen)) {
760 			log_error_write(srv, __FILE__, __LINE__, "sbds",
761 				"bind failed for:",
762 				proc->socket,
763 				proc->port,
764 				strerror(errno));
765 			return -1;
766 		}
767 
768 		if (-1 == listen(scgi_fd, 1024)) {
769 			log_error_write(srv, __FILE__, __LINE__, "ss",
770 				"listen failed:", strerror(errno));
771 			return -1;
772 		}
773 
774 #ifdef HAVE_FORK
775 		switch ((child = fork())) {
776 		case 0: {
777 			buffer *b;
778 			size_t i = 0;
779 			int fd = 0;
780 			char_array env;
781 
782 
783 			/* create environment */
784 			env.ptr = NULL;
785 			env.size = 0;
786 			env.used = 0;
787 
788 			if (scgi_fd != 0) {
789 				dup2(scgi_fd, 0);
790 				close(scgi_fd);
791 			}
792 
793 			/* we don't need the client socket */
794 			for (fd = 3; fd < 256; fd++) {
795 				close(fd);
796 			}
797 
798 			/* build clean environment */
799 			if (host->bin_env_copy->used) {
800 				for (i = 0; i < host->bin_env_copy->used; i++) {
801 					data_string *ds = (data_string *)host->bin_env_copy->data[i];
802 					char *ge;
803 
804 					if (NULL != (ge = getenv(ds->value->ptr))) {
805 						env_add(&env, CONST_BUF_LEN(ds->value), ge, strlen(ge));
806 					}
807 				}
808 			} else {
809 				for (i = 0; environ[i]; i++) {
810 					char *eq;
811 
812 					if (NULL != (eq = strchr(environ[i], '='))) {
813 						env_add(&env, environ[i], eq - environ[i], eq+1, strlen(eq+1));
814 					}
815 				}
816 			}
817 
818 			/* create environment */
819 			for (i = 0; i < host->bin_env->used; i++) {
820 				data_string *ds = (data_string *)host->bin_env->data[i];
821 
822 				env_add(&env, CONST_BUF_LEN(ds->key), CONST_BUF_LEN(ds->value));
823 			}
824 
825 			for (i = 0; i < env.used; i++) {
826 				/* search for PHP_FCGI_CHILDREN */
827 				if (0 == strncmp(env.ptr[i], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
828 			}
829 
830 			/* not found, add a default */
831 			if (i == env.used) {
832 				env_add(&env, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
833 			}
834 
835 			env.ptr[env.used] = NULL;
836 
837 			b = buffer_init();
838 			buffer_copy_string_len(b, CONST_STR_LEN("exec "));
839 			buffer_append_string_buffer(b, host->bin_path);
840 
841 			reset_signals();
842 
843 			/* exec the cgi */
844 			execle("/bin/sh", "sh", "-c", b->ptr, (char *)NULL, env.ptr);
845 
846 			log_error_write(srv, __FILE__, __LINE__, "sbs",
847 					"execl failed for:", host->bin_path, strerror(errno));
848 
849 			exit(errno);
850 
851 			break;
852 		}
853 		case -1:
854 			/* error */
855 			break;
856 		default:
857 			/* father */
858 
859 			/* wait */
860 			select(0, NULL, NULL, NULL, &tv);
861 
862 			switch (waitpid(child, &status, WNOHANG)) {
863 			case 0:
864 				/* child still running after timeout, good */
865 				break;
866 			case -1:
867 				/* no PID found ? should never happen */
868 				log_error_write(srv, __FILE__, __LINE__, "ss",
869 						"pid not found:", strerror(errno));
870 				return -1;
871 			default:
872 				/* the child should not terminate at all */
873 				if (WIFEXITED(status)) {
874 					log_error_write(srv, __FILE__, __LINE__, "sd",
875 							"child exited (is this a SCGI binary ?):",
876 							WEXITSTATUS(status));
877 				} else if (WIFSIGNALED(status)) {
878 					log_error_write(srv, __FILE__, __LINE__, "sd",
879 							"child signaled:",
880 							WTERMSIG(status));
881 				} else {
882 					log_error_write(srv, __FILE__, __LINE__, "sd",
883 							"child died somehow:",
884 							status);
885 				}
886 				return -1;
887 			}
888 
889 			/* register process */
890 			proc->pid = child;
891 			proc->last_used = srv->cur_ts;
892 			proc->is_local = 1;
893 
894 			break;
895 		}
896 #endif
897 	} else {
898 		proc->is_local = 0;
899 		proc->pid = 0;
900 
901 		if (p->conf.debug) {
902 			log_error_write(srv, __FILE__, __LINE__, "sb",
903 					"(debug) socket is already used, won't spawn:",
904 					proc->socket);
905 		}
906 	}
907 
908 	proc->state = PROC_STATE_RUNNING;
909 	host->active_procs++;
910 
911 	close(scgi_fd);
912 
913 	return 0;
914 }
915 
916 
SETDEFAULTS_FUNC(mod_scgi_set_defaults)917 SETDEFAULTS_FUNC(mod_scgi_set_defaults) {
918 	plugin_data *p = p_d;
919 	data_unset *du;
920 	size_t i = 0;
921 
922 	config_values_t cv[] = {
923 		{ "scgi.server",              NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION },       /* 0 */
924 		{ "scgi.debug",               NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },       /* 1 */
925 		{ NULL,                          NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
926 	};
927 
928 	p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *));
929 
930 	for (i = 0; i < srv->config_context->used; i++) {
931 		plugin_config *s;
932 		array *ca;
933 
934 		s = malloc(sizeof(plugin_config));
935 		s->exts          = scgi_extensions_init();
936 		s->debug         = 0;
937 
938 		cv[0].destination = s->exts;
939 		cv[1].destination = &(s->debug);
940 
941 		p->config_storage[i] = s;
942 		ca = ((data_config *)srv->config_context->data[i])->value;
943 
944 		if (0 != config_insert_values_global(srv, ca, cv)) {
945 			return HANDLER_ERROR;
946 		}
947 
948 		/*
949 		 * <key> = ( ... )
950 		 */
951 
952 		if (NULL != (du = array_get_element(ca, "scgi.server"))) {
953 			size_t j;
954 			data_array *da = (data_array *)du;
955 
956 			if (du->type != TYPE_ARRAY) {
957 				log_error_write(srv, __FILE__, __LINE__, "sss",
958 						"unexpected type for key: ", "scgi.server", "array of strings");
959 
960 				return HANDLER_ERROR;
961 			}
962 
963 
964 			/*
965 			 * scgi.server = ( "<ext>" => ( ... ),
966 			 *                    "<ext>" => ( ... ) )
967 			 */
968 
969 			for (j = 0; j < da->value->used; j++) {
970 				size_t n;
971 				data_array *da_ext = (data_array *)da->value->data[j];
972 
973 				if (da->value->data[j]->type != TYPE_ARRAY) {
974 					log_error_write(srv, __FILE__, __LINE__, "sssbs",
975 							"unexpected type for key: ", "scgi.server",
976 							"[", da->value->data[j]->key, "](string)");
977 
978 					return HANDLER_ERROR;
979 				}
980 
981 				/*
982 				 * da_ext->key == name of the extension
983 				 */
984 
985 				/*
986 				 * scgi.server = ( "<ext>" =>
987 				 *                     ( "<host>" => ( ... ),
988 				 *                       "<host>" => ( ... )
989 				 *                     ),
990 				 *                    "<ext>" => ... )
991 				 */
992 
993 				for (n = 0; n < da_ext->value->used; n++) {
994 					data_array *da_host = (data_array *)da_ext->value->data[n];
995 
996 					scgi_extension_host *df;
997 
998 					config_values_t fcv[] = {
999 						{ "host",              NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },       /* 0 */
1000 						{ "docroot",           NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },       /* 1 */
1001 						{ "socket",            NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },       /* 2 */
1002 						{ "bin-path",          NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION },       /* 3 */
1003 
1004 						{ "check-local",       NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION },      /* 4 */
1005 						{ "port",              NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },        /* 5 */
1006 						{ "min-procs-not-working",         NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },        /* 7 this is broken for now */
1007 						{ "max-procs",         NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },        /* 7 */
1008 						{ "max-load-per-proc", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },        /* 8 */
1009 						{ "idle-timeout",      NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },        /* 9 */
1010 						{ "disable-time",      NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION },        /* 10 */
1011 
1012 						{ "bin-environment",   NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION },        /* 11 */
1013 						{ "bin-copy-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION },     /* 12 */
1014 						{ "fix-root-scriptname",  NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION },   /* 13 */
1015 
1016 
1017 						{ NULL,                NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1018 					};
1019 
1020 					if (da_host->type != TYPE_ARRAY) {
1021 						log_error_write(srv, __FILE__, __LINE__, "ssSBS",
1022 								"unexpected type for key:",
1023 								"scgi.server",
1024 								"[", da_host->key, "](string)");
1025 
1026 						return HANDLER_ERROR;
1027 					}
1028 
1029 					df = scgi_host_init();
1030 
1031 					df->check_local  = 1;
1032 					df->min_procs    = 4;
1033 					df->max_procs    = 4;
1034 					df->max_load_per_proc = 1;
1035 					df->idle_timeout = 60;
1036 					df->disable_time = 60;
1037 					df->fix_root_path_name = 0;
1038 
1039 					fcv[0].destination = df->host;
1040 					fcv[1].destination = df->docroot;
1041 					fcv[2].destination = df->unixsocket;
1042 					fcv[3].destination = df->bin_path;
1043 
1044 					fcv[4].destination = &(df->check_local);
1045 					fcv[5].destination = &(df->port);
1046 					fcv[6].destination = &(df->min_procs);
1047 					fcv[7].destination = &(df->max_procs);
1048 					fcv[8].destination = &(df->max_load_per_proc);
1049 					fcv[9].destination = &(df->idle_timeout);
1050 					fcv[10].destination = &(df->disable_time);
1051 
1052 					fcv[11].destination = df->bin_env;
1053 					fcv[12].destination = df->bin_env_copy;
1054 					fcv[13].destination = &(df->fix_root_path_name);
1055 
1056 
1057 					if (0 != config_insert_values_internal(srv, da_host->value, fcv)) {
1058 						return HANDLER_ERROR;
1059 					}
1060 
1061 					if ((!buffer_is_empty(df->host) || df->port) &&
1062 					    !buffer_is_empty(df->unixsocket)) {
1063 						log_error_write(srv, __FILE__, __LINE__, "s",
1064 								"either host+port or socket");
1065 
1066 						return HANDLER_ERROR;
1067 					}
1068 
1069 					if (!buffer_is_empty(df->unixsocket)) {
1070 						/* unix domain socket */
1071 						struct sockaddr_un un;
1072 
1073 						if (df->unixsocket->used > sizeof(un.sun_path) - 2) {
1074 							log_error_write(srv, __FILE__, __LINE__, "s",
1075 									"path of the unixdomain socket is too large");
1076 							return HANDLER_ERROR;
1077 						}
1078 					} else {
1079 						/* tcp/ip */
1080 
1081 						if (buffer_is_empty(df->host) &&
1082 						    buffer_is_empty(df->bin_path)) {
1083 							log_error_write(srv, __FILE__, __LINE__, "sbbbs",
1084 									"missing key (string):",
1085 									da->key,
1086 									da_ext->key,
1087 									da_host->key,
1088 									"host");
1089 
1090 							return HANDLER_ERROR;
1091 						} else if (df->port == 0) {
1092 							log_error_write(srv, __FILE__, __LINE__, "sbbbs",
1093 									"missing key (short):",
1094 									da->key,
1095 									da_ext->key,
1096 									da_host->key,
1097 									"port");
1098 							return HANDLER_ERROR;
1099 						}
1100 					}
1101 
1102 					if (!buffer_is_empty(df->bin_path)) {
1103 						/* a local socket + self spawning */
1104 						size_t pno;
1105 
1106 						/* HACK:  just to make sure the adaptive spawing is disabled */
1107 						df->min_procs = df->max_procs;
1108 
1109 						if (df->min_procs > df->max_procs) df->max_procs = df->min_procs;
1110 						if (df->max_load_per_proc < 1) df->max_load_per_proc = 0;
1111 
1112 						if (s->debug) {
1113 							log_error_write(srv, __FILE__, __LINE__, "ssbsdsbsdsd",
1114 									"--- scgi spawning local",
1115 									"\n\tproc:", df->bin_path,
1116 									"\n\tport:", df->port,
1117 									"\n\tsocket", df->unixsocket,
1118 									"\n\tmin-procs:", df->min_procs,
1119 									"\n\tmax-procs:", df->max_procs);
1120 						}
1121 
1122 						for (pno = 0; pno < df->min_procs; pno++) {
1123 							scgi_proc *proc;
1124 
1125 							proc = scgi_process_init();
1126 							proc->id = df->num_procs++;
1127 							df->max_id++;
1128 
1129 							if (buffer_is_empty(df->unixsocket)) {
1130 								proc->port = df->port + pno;
1131 							} else {
1132 								buffer_copy_string_buffer(proc->socket, df->unixsocket);
1133 								buffer_append_string_len(proc->socket, CONST_STR_LEN("-"));
1134 								buffer_append_long(proc->socket, pno);
1135 							}
1136 
1137 							if (s->debug) {
1138 								log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
1139 										"--- scgi spawning",
1140 										"\n\tport:", df->port,
1141 										"\n\tsocket", df->unixsocket,
1142 										"\n\tcurrent:", pno, "/", df->min_procs);
1143 							}
1144 
1145 							if (scgi_spawn_connection(srv, p, df, proc)) {
1146 								log_error_write(srv, __FILE__, __LINE__, "s",
1147 										"[ERROR]: spawning fcgi failed.");
1148 								return HANDLER_ERROR;
1149 							}
1150 
1151 							proc->next = df->first;
1152 							if (df->first) 	df->first->prev = proc;
1153 
1154 							df->first = proc;
1155 						}
1156 					} else {
1157 						scgi_proc *fp;
1158 
1159 						fp = scgi_process_init();
1160 						fp->id = df->num_procs++;
1161 						df->max_id++;
1162 						df->active_procs++;
1163 						fp->state = PROC_STATE_RUNNING;
1164 
1165 						if (buffer_is_empty(df->unixsocket)) {
1166 							fp->port = df->port;
1167 						} else {
1168 							buffer_copy_string_buffer(fp->socket, df->unixsocket);
1169 						}
1170 
1171 						df->first = fp;
1172 
1173 						df->min_procs = 1;
1174 						df->max_procs = 1;
1175 					}
1176 
1177 					/* if extension already exists, take it */
1178 					scgi_extension_insert(s->exts, da_ext->key, df);
1179 				}
1180 			}
1181 		}
1182 	}
1183 
1184 	return HANDLER_GO_ON;
1185 }
1186 
scgi_set_state(server * srv,handler_ctx * hctx,scgi_connection_state_t state)1187 static int scgi_set_state(server *srv, handler_ctx *hctx, scgi_connection_state_t state) {
1188 	hctx->state = state;
1189 	hctx->state_timestamp = srv->cur_ts;
1190 
1191 	return 0;
1192 }
1193 
1194 
scgi_connection_cleanup(server * srv,handler_ctx * hctx)1195 static void scgi_connection_cleanup(server *srv, handler_ctx *hctx) {
1196 	plugin_data *p;
1197 	connection  *con;
1198 
1199 	if (NULL == hctx) return;
1200 
1201 	p    = hctx->plugin_data;
1202 	con  = hctx->remote_conn;
1203 
1204 	if (hctx->fd != -1) {
1205 		fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1206 		fdevent_unregister(srv->ev, hctx->fd);
1207 		close(hctx->fd);
1208 		srv->cur_fds--;
1209 	}
1210 
1211 	if (hctx->host && hctx->proc) {
1212 		hctx->host->load--;
1213 
1214 		if (hctx->got_proc) {
1215 			/* after the connect the process gets a load */
1216 			hctx->proc->load--;
1217 
1218 			if (p->conf.debug) {
1219 				log_error_write(srv, __FILE__, __LINE__, "sddb",
1220 						"release proc:",
1221 						hctx->fd,
1222 						hctx->proc->pid, hctx->proc->socket);
1223 			}
1224 		}
1225 
1226 		scgi_proclist_sort_down(srv, hctx->host, hctx->proc);
1227 	}
1228 
1229 
1230 	handler_ctx_free(hctx);
1231 	con->plugin_ctx[p->id] = NULL;
1232 }
1233 
scgi_reconnect(server * srv,handler_ctx * hctx)1234 static int scgi_reconnect(server *srv, handler_ctx *hctx) {
1235 	plugin_data *p    = hctx->plugin_data;
1236 
1237 	/* child died
1238 	 *
1239 	 * 1.
1240 	 *
1241 	 * connect was ok, connection was accepted
1242 	 * but the php accept loop checks after the accept if it should die or not.
1243 	 *
1244 	 * if yes we can only detect it at a write()
1245 	 *
1246 	 * next step is resetting this attemp and setup a connection again
1247 	 *
1248 	 * if we have more then 5 reconnects for the same request, die
1249 	 *
1250 	 * 2.
1251 	 *
1252 	 * we have a connection but the child died by some other reason
1253 	 *
1254 	 */
1255 
1256 	fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1257 	fdevent_unregister(srv->ev, hctx->fd);
1258 	close(hctx->fd);
1259 	srv->cur_fds--;
1260 
1261 	scgi_set_state(srv, hctx, FCGI_STATE_INIT);
1262 
1263 	hctx->request_id = 0;
1264 	hctx->reconnects++;
1265 
1266 	if (p->conf.debug) {
1267 		log_error_write(srv, __FILE__, __LINE__, "sddb",
1268 				"release proc:",
1269 				hctx->fd,
1270 				hctx->proc->pid, hctx->proc->socket);
1271 	}
1272 
1273 	hctx->proc->load--;
1274 	scgi_proclist_sort_down(srv, hctx->host, hctx->proc);
1275 
1276 	return 0;
1277 }
1278 
1279 
scgi_connection_reset(server * srv,connection * con,void * p_d)1280 static handler_t scgi_connection_reset(server *srv, connection *con, void *p_d) {
1281 	plugin_data *p = p_d;
1282 
1283 	scgi_connection_cleanup(srv, con->plugin_ctx[p->id]);
1284 
1285 	return HANDLER_GO_ON;
1286 }
1287 
1288 
scgi_env_add(buffer * env,const char * key,size_t key_len,const char * val,size_t val_len)1289 static int scgi_env_add(buffer *env, const char *key, size_t key_len, const char *val, size_t val_len) {
1290 	size_t len;
1291 
1292 	if (!key || !val) return -1;
1293 
1294 	len = key_len + val_len + 2;
1295 
1296 	buffer_prepare_append(env, len);
1297 
1298 	memcpy(env->ptr + env->used, key, key_len);
1299 	env->ptr[env->used + key_len] = '\0';
1300 	env->used += key_len + 1;
1301 	memcpy(env->ptr + env->used, val, val_len);
1302 	env->ptr[env->used + val_len] = '\0';
1303 	env->used += val_len + 1;
1304 
1305 	return 0;
1306 }
1307 
1308 
1309 /**
1310  *
1311  * returns
1312  *   -1 error
1313  *    0 connected
1314  *    1 not connected yet
1315  */
1316 
scgi_establish_connection(server * srv,handler_ctx * hctx)1317 static int scgi_establish_connection(server *srv, handler_ctx *hctx) {
1318 	struct sockaddr *scgi_addr;
1319 	struct sockaddr_in scgi_addr_in;
1320 #ifdef HAVE_SYS_UN_H
1321 	struct sockaddr_un scgi_addr_un;
1322 #endif
1323 	socklen_t servlen;
1324 
1325 	scgi_extension_host *host = hctx->host;
1326 	scgi_proc *proc   = hctx->proc;
1327 	int scgi_fd       = hctx->fd;
1328 
1329 	memset(&scgi_addr, 0, sizeof(scgi_addr));
1330 
1331 	if (!buffer_is_empty(proc->socket)) {
1332 #ifdef HAVE_SYS_UN_H
1333 		/* use the unix domain socket */
1334 		scgi_addr_un.sun_family = AF_UNIX;
1335 		strcpy(scgi_addr_un.sun_path, proc->socket->ptr);
1336 #ifdef SUN_LEN
1337 		servlen = SUN_LEN(&scgi_addr_un);
1338 #else
1339 		/* stevens says: */
1340 		servlen = proc->socket->used + sizeof(scgi_addr_un.sun_family);
1341 #endif
1342 		scgi_addr = (struct sockaddr *) &scgi_addr_un;
1343 #else
1344 		return -1;
1345 #endif
1346 	} else {
1347 		scgi_addr_in.sin_family = AF_INET;
1348 		if (0 == inet_aton(host->host->ptr, &(scgi_addr_in.sin_addr))) {
1349 			log_error_write(srv, __FILE__, __LINE__, "sbs",
1350 					"converting IP-adress failed for", host->host,
1351 					"\nBe sure to specify an IP address here");
1352 
1353 			return -1;
1354 		}
1355 		scgi_addr_in.sin_port = htons(proc->port);
1356 		servlen = sizeof(scgi_addr_in);
1357 
1358 		scgi_addr = (struct sockaddr *) &scgi_addr_in;
1359 	}
1360 
1361 	if (-1 == connect(scgi_fd, scgi_addr, servlen)) {
1362 		if (errno == EINPROGRESS ||
1363 		    errno == EALREADY ||
1364 		    errno == EINTR) {
1365 			if (hctx->conf.debug) {
1366 				log_error_write(srv, __FILE__, __LINE__, "sd",
1367 						"connect delayed, will continue later:", scgi_fd);
1368 			}
1369 
1370 			return 1;
1371 		} else {
1372 			log_error_write(srv, __FILE__, __LINE__, "sdsddb",
1373 					"connect failed:", scgi_fd,
1374 					strerror(errno), errno,
1375 					proc->port, proc->socket);
1376 
1377 			if (errno == EAGAIN) {
1378 				/* this is Linux only */
1379 
1380 				log_error_write(srv, __FILE__, __LINE__, "s",
1381 						"If this happend on Linux: You have been run out of local ports. "
1382 						"Check the manual, section Performance how to handle this.");
1383 			}
1384 
1385 			return -1;
1386 		}
1387 	}
1388 	if (hctx->conf.debug > 1) {
1389 		log_error_write(srv, __FILE__, __LINE__, "sd",
1390 				"connect succeeded: ", scgi_fd);
1391 	}
1392 
1393 
1394 
1395 	return 0;
1396 }
1397 
scgi_env_add_request_headers(server * srv,connection * con,plugin_data * p)1398 static int scgi_env_add_request_headers(server *srv, connection *con, plugin_data *p) {
1399 	size_t i;
1400 
1401 	for (i = 0; i < con->request.headers->used; i++) {
1402 		data_string *ds;
1403 
1404 		ds = (data_string *)con->request.headers->data[i];
1405 
1406 		if (ds->value->used && ds->key->used) {
1407 			size_t j;
1408 			buffer_reset(srv->tmp_buf);
1409 
1410 			if (0 != strcasecmp(ds->key->ptr, "CONTENT-TYPE")) {
1411 				buffer_copy_string_len(srv->tmp_buf, CONST_STR_LEN("HTTP_"));
1412 				srv->tmp_buf->used--;
1413 			}
1414 
1415 			buffer_prepare_append(srv->tmp_buf, ds->key->used + 2);
1416 			for (j = 0; j < ds->key->used - 1; j++) {
1417 				srv->tmp_buf->ptr[srv->tmp_buf->used++] =
1418 					light_isalpha(ds->key->ptr[j]) ?
1419 					ds->key->ptr[j] & ~32 : '_';
1420 			}
1421 			srv->tmp_buf->ptr[srv->tmp_buf->used++] = '\0';
1422 
1423 			scgi_env_add(p->scgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value));
1424 		}
1425 	}
1426 
1427 	for (i = 0; i < con->environment->used; i++) {
1428 		data_string *ds;
1429 
1430 		ds = (data_string *)con->environment->data[i];
1431 
1432 		if (ds->value->used && ds->key->used) {
1433 			size_t j;
1434 			buffer_reset(srv->tmp_buf);
1435 
1436 			buffer_prepare_append(srv->tmp_buf, ds->key->used + 2);
1437 			for (j = 0; j < ds->key->used - 1; j++) {
1438 				srv->tmp_buf->ptr[srv->tmp_buf->used++] =
1439 					light_isalnum((unsigned char)ds->key->ptr[j]) ?
1440 					toupper((unsigned char)ds->key->ptr[j]) : '_';
1441 			}
1442 			srv->tmp_buf->ptr[srv->tmp_buf->used++] = '\0';
1443 
1444 			scgi_env_add(p->scgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value));
1445 		}
1446 	}
1447 
1448 	return 0;
1449 }
1450 
1451 
scgi_create_env(server * srv,handler_ctx * hctx)1452 static int scgi_create_env(server *srv, handler_ctx *hctx) {
1453 	char buf[32];
1454 	const char *s;
1455 #ifdef HAVE_IPV6
1456 	char b2[INET6_ADDRSTRLEN + 1];
1457 #endif
1458 	buffer *b;
1459 
1460 	plugin_data *p    = hctx->plugin_data;
1461 	scgi_extension_host *host= hctx->host;
1462 
1463 	connection *con   = hctx->remote_conn;
1464 	server_socket *srv_sock = con->srv_socket;
1465 
1466 	sock_addr our_addr;
1467 	socklen_t our_addr_len;
1468 
1469 	buffer_prepare_copy(p->scgi_env, 1024);
1470 
1471 	/* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
1472 
1473 	/* request.content_length < SSIZE_MAX, see request.c */
1474 	LI_ltostr(buf, con->request.content_length);
1475 	scgi_env_add(p->scgi_env, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf));
1476 	scgi_env_add(p->scgi_env, CONST_STR_LEN("SCGI"), CONST_STR_LEN("1"));
1477 
1478 
1479 	if (buffer_is_empty(con->conf.server_tag)) {
1480 		scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_DESC));
1481 	} else {
1482 		scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con->conf.server_tag));
1483 	}
1484 
1485 	if (con->server_name->used) {
1486 		size_t len = con->server_name->used - 1;
1487 
1488 		if (con->server_name->ptr[0] == '[') {
1489 			const char *colon = strstr(con->server_name->ptr, "]:");
1490 			if (colon) len = (colon + 1) - con->server_name->ptr;
1491 		} else {
1492 			const char *colon = strchr(con->server_name->ptr, ':');
1493 			if (colon) len = colon - con->server_name->ptr;
1494 		}
1495 
1496 		scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_NAME"), con->server_name->ptr, len);
1497 	} else {
1498 #ifdef HAVE_IPV6
1499 		s = inet_ntop(srv_sock->addr.plain.sa_family,
1500 			      srv_sock->addr.plain.sa_family == AF_INET6 ?
1501 			      (const void *) &(srv_sock->addr.ipv6.sin6_addr) :
1502 			      (const void *) &(srv_sock->addr.ipv4.sin_addr),
1503 			      b2, sizeof(b2)-1);
1504 #else
1505 		s = inet_ntoa(srv_sock->addr.ipv4.sin_addr);
1506 #endif
1507 		scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_NAME"), s, strlen(s));
1508 	}
1509 
1510 	scgi_env_add(p->scgi_env, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1"));
1511 
1512 	LI_ltostr(buf,
1513 #ifdef HAVE_IPV6
1514 	       ntohs(srv_sock->addr.plain.sa_family ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port)
1515 #else
1516 	       ntohs(srv_sock->addr.ipv4.sin_port)
1517 #endif
1518 	       );
1519 
1520 	scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf));
1521 
1522 	/* get the server-side of the connection to the client */
1523 	our_addr_len = sizeof(our_addr);
1524 
1525 	if (-1 == getsockname(con->fd, &(our_addr.plain), &our_addr_len)) {
1526 		s = inet_ntop_cache_get_ip(srv, &(srv_sock->addr));
1527 	} else {
1528 		s = inet_ntop_cache_get_ip(srv, &(our_addr));
1529 	}
1530 	scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s));
1531 
1532 	LI_ltostr(buf,
1533 #ifdef HAVE_IPV6
1534 	       ntohs(con->dst_addr.plain.sa_family ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port)
1535 #else
1536 	       ntohs(con->dst_addr.ipv4.sin_port)
1537 #endif
1538 	       );
1539 
1540 	scgi_env_add(p->scgi_env, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf));
1541 
1542 	s = inet_ntop_cache_get_ip(srv, &(con->dst_addr));
1543 	scgi_env_add(p->scgi_env, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s));
1544 
1545 	if (!buffer_is_empty(con->authed_user)) {
1546 		scgi_env_add(p->scgi_env, CONST_STR_LEN("REMOTE_USER"),
1547 			     CONST_BUF_LEN(con->authed_user));
1548 	}
1549 
1550 
1551 	/*
1552 	 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1553 	 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1554 	 * (6.1.14, 6.1.6, 6.1.7)
1555 	 */
1556 
1557 	scgi_env_add(p->scgi_env, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path));
1558 
1559 	if (!buffer_is_empty(con->request.pathinfo)) {
1560 		scgi_env_add(p->scgi_env, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo));
1561 
1562 		/* PATH_TRANSLATED is only defined if PATH_INFO is set */
1563 
1564 		if (!buffer_is_empty(host->docroot)) {
1565 			buffer_copy_string_buffer(p->path, host->docroot);
1566 		} else {
1567 			buffer_copy_string_buffer(p->path, con->physical.basedir);
1568 		}
1569 		buffer_append_string_buffer(p->path, con->request.pathinfo);
1570 		scgi_env_add(p->scgi_env, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p->path));
1571 	} else {
1572 		scgi_env_add(p->scgi_env, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN(""));
1573 	}
1574 
1575 	/*
1576 	 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1577 	 * http://www.php.net/manual/en/reserved.variables.php
1578 	 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1579 	 * TODO: this code should be checked against cgi.fix_pathinfo php
1580 	 * parameter.
1581 	 */
1582 
1583 	if (!buffer_is_empty(host->docroot)) {
1584 		/*
1585 		 * rewrite SCRIPT_FILENAME
1586 		 *
1587 		 */
1588 
1589 		buffer_copy_string_buffer(p->path, host->docroot);
1590 		buffer_append_string_buffer(p->path, con->uri.path);
1591 
1592 		scgi_env_add(p->scgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path));
1593 		scgi_env_add(p->scgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host->docroot));
1594 	} else {
1595 		buffer_copy_string_buffer(p->path, con->physical.path);
1596 
1597 		scgi_env_add(p->scgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path));
1598 		scgi_env_add(p->scgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.basedir));
1599 	}
1600 	scgi_env_add(p->scgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri));
1601 	if (!buffer_is_equal(con->request.uri, con->request.orig_uri)) {
1602 		scgi_env_add(p->scgi_env, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con->request.uri));
1603 	}
1604 	if (!buffer_is_empty(con->uri.query)) {
1605 		scgi_env_add(p->scgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query));
1606 	} else {
1607 		scgi_env_add(p->scgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN(""));
1608 	}
1609 
1610 	s = get_http_method_name(con->request.http_method);
1611 	scgi_env_add(p->scgi_env, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s));
1612 	scgi_env_add(p->scgi_env, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")); /* if php is compiled with --force-redirect */
1613 	s = get_http_version_name(con->request.http_version);
1614 	scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));
1615 
1616 #ifdef USE_OPENSSL
1617 	if (srv_sock->is_ssl) {
1618 		scgi_env_add(p->scgi_env, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1619 	}
1620 #endif
1621 
1622 	scgi_env_add_request_headers(srv, con, p);
1623 
1624 	b = chunkqueue_get_append_buffer(hctx->wb);
1625 
1626 	buffer_append_long(b, p->scgi_env->used);
1627 	buffer_append_string_len(b, CONST_STR_LEN(":"));
1628 	buffer_append_string_len(b, (const char *)p->scgi_env->ptr, p->scgi_env->used);
1629 	buffer_append_string_len(b, CONST_STR_LEN(","));
1630 
1631 	hctx->wb->bytes_in += b->used - 1;
1632 
1633 	if (con->request.content_length) {
1634 		chunkqueue *req_cq = con->request_content_queue;
1635 		chunk *req_c;
1636 		off_t offset;
1637 
1638 		/* something to send ? */
1639 		for (offset = 0, req_c = req_cq->first; offset != req_cq->bytes_in; req_c = req_c->next) {
1640 			off_t weWant = req_cq->bytes_in - offset;
1641 			off_t weHave = 0;
1642 
1643 			/* we announce toWrite octects
1644 			 * now take all the request_content chunk that we need to fill this request
1645 			 * */
1646 
1647 			switch (req_c->type) {
1648 			case FILE_CHUNK:
1649 				weHave = req_c->file.length - req_c->offset;
1650 
1651 				if (weHave > weWant) weHave = weWant;
1652 
1653 				chunkqueue_append_file(hctx->wb, req_c->file.name, req_c->offset, weHave);
1654 
1655 				req_c->offset += weHave;
1656 				req_cq->bytes_out += weHave;
1657 
1658 				hctx->wb->bytes_in += weHave;
1659 
1660 				break;
1661 			case MEM_CHUNK:
1662 				/* append to the buffer */
1663 				weHave = req_c->mem->used - 1 - req_c->offset;
1664 
1665 				if (weHave > weWant) weHave = weWant;
1666 
1667 				b = chunkqueue_get_append_buffer(hctx->wb);
1668 				buffer_append_memory(b, req_c->mem->ptr + req_c->offset, weHave);
1669 				b->used++; /* add virtual \0 */
1670 
1671 				req_c->offset += weHave;
1672 				req_cq->bytes_out += weHave;
1673 
1674 				hctx->wb->bytes_in += weHave;
1675 
1676 				break;
1677 			default:
1678 				break;
1679 			}
1680 
1681 			offset += weHave;
1682 		}
1683 	}
1684 
1685 	return 0;
1686 }
1687 
scgi_response_parse(server * srv,connection * con,plugin_data * p,buffer * in,int eol)1688 static int scgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in, int eol) {
1689 	char *ns;
1690 	const char *s;
1691 	int line = 0;
1692 
1693 	UNUSED(srv);
1694 
1695 	buffer_copy_string_buffer(p->parse_response, in);
1696 
1697 	for (s = p->parse_response->ptr;
1698 	     NULL != (ns = (eol == EOL_RN ? strstr(s, "\r\n") : strchr(s, '\n')));
1699 	     s = ns + (eol == EOL_RN ? 2 : 1), line++) {
1700 		const char *key, *value;
1701 		int key_len;
1702 		data_string *ds;
1703 
1704 		ns[0] = '\0';
1705 
1706 		if (line == 0 &&
1707 		    0 == strncmp(s, "HTTP/1.", 7)) {
1708 			/* non-parsed header ... we parse them anyway */
1709 
1710 			if ((s[7] == '1' ||
1711 			     s[7] == '0') &&
1712 			    s[8] == ' ') {
1713 				int status;
1714 				/* after the space should be a status code for us */
1715 
1716 				status = strtol(s+9, NULL, 10);
1717 
1718 				if (status >= 100 && status < 1000) {
1719 					/* we expected 3 digits got them */
1720 					con->parsed_response |= HTTP_STATUS;
1721 					con->http_status = status;
1722 				}
1723 			}
1724 		} else {
1725 
1726 			key = s;
1727 			if (NULL == (value = strchr(s, ':'))) {
1728 				/* we expect: "<key>: <value>\r\n" */
1729 				continue;
1730 			}
1731 
1732 			key_len = value - key;
1733 			value += 1;
1734 
1735 			/* skip LWS */
1736 			while (*value == ' ' || *value == '\t') value++;
1737 
1738 			if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
1739 				ds = data_response_init();
1740 			}
1741 			buffer_copy_string_len(ds->key, key, key_len);
1742 			buffer_copy_string(ds->value, value);
1743 
1744 			array_insert_unique(con->response.headers, (data_unset *)ds);
1745 
1746 			switch(key_len) {
1747 			case 4:
1748 				if (0 == strncasecmp(key, "Date", key_len)) {
1749 					con->parsed_response |= HTTP_DATE;
1750 				}
1751 				break;
1752 			case 6:
1753 				if (0 == strncasecmp(key, "Status", key_len)) {
1754 					con->http_status = strtol(value, NULL, 10);
1755 					con->parsed_response |= HTTP_STATUS;
1756 				}
1757 				break;
1758 			case 8:
1759 				if (0 == strncasecmp(key, "Location", key_len)) {
1760 					con->parsed_response |= HTTP_LOCATION;
1761 				}
1762 				break;
1763 			case 10:
1764 				if (0 == strncasecmp(key, "Connection", key_len)) {
1765 					con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
1766 					con->parsed_response |= HTTP_CONNECTION;
1767 				}
1768 				break;
1769 			case 14:
1770 				if (0 == strncasecmp(key, "Content-Length", key_len)) {
1771 					con->response.content_length = strtol(value, NULL, 10);
1772 					con->parsed_response |= HTTP_CONTENT_LENGTH;
1773 				}
1774 				break;
1775 			default:
1776 				break;
1777 			}
1778 		}
1779 	}
1780 
1781 	/* CGI/1.1 rev 03 - 7.2.1.2 */
1782 	if ((con->parsed_response & HTTP_LOCATION) &&
1783 	    !(con->parsed_response & HTTP_STATUS)) {
1784 		con->http_status = 302;
1785 	}
1786 
1787 	return 0;
1788 }
1789 
1790 
scgi_demux_response(server * srv,handler_ctx * hctx)1791 static int scgi_demux_response(server *srv, handler_ctx *hctx) {
1792 	plugin_data *p    = hctx->plugin_data;
1793 	connection  *con  = hctx->remote_conn;
1794 
1795 	while(1) {
1796 		int n;
1797 
1798 		buffer_prepare_copy(hctx->response, 1024);
1799 		if (-1 == (n = read(hctx->fd, hctx->response->ptr, hctx->response->size - 1))) {
1800 			if (errno == EAGAIN || errno == EINTR) {
1801 				/* would block, wait for signal */
1802 				return 0;
1803 			}
1804 			/* error */
1805 			log_error_write(srv, __FILE__, __LINE__, "sdd", strerror(errno), con->fd, hctx->fd);
1806 			return -1;
1807 		}
1808 
1809 		if (n == 0) {
1810 			/* read finished */
1811 
1812 			con->file_finished = 1;
1813 
1814 			/* send final chunk */
1815 			http_chunk_append_mem(srv, con, NULL, 0);
1816 			joblist_append(srv, con);
1817 
1818 			return 1;
1819 		}
1820 
1821 		hctx->response->ptr[n] = '\0';
1822 		hctx->response->used = n+1;
1823 
1824 		/* split header from body */
1825 
1826 		if (con->file_started == 0) {
1827 			char *c;
1828 			int in_header = 0;
1829 			int header_end = 0;
1830 			int cp, eol = EOL_UNSET;
1831 			size_t used = 0;
1832 			size_t hlen = 0;
1833 
1834 			buffer_append_string_buffer(hctx->response_header, hctx->response);
1835 
1836 			/* nph (non-parsed headers) */
1837 			if (0 == strncmp(hctx->response_header->ptr, "HTTP/1.", 7)) in_header = 1;
1838 
1839 			/* search for the \r\n\r\n or \n\n in the string */
1840 			for (c = hctx->response_header->ptr, cp = 0, used = hctx->response_header->used - 1; used; c++, cp++, used--) {
1841 				if (*c == ':') in_header = 1;
1842 				else if (*c == '\n') {
1843 					if (in_header == 0) {
1844 						/* got a response without a response header */
1845 
1846 						c = NULL;
1847 						header_end = 1;
1848 						break;
1849 					}
1850 
1851 					if (eol == EOL_UNSET) eol = EOL_N;
1852 
1853 					if (*(c+1) == '\n') {
1854 						header_end = 1;
1855 						hlen = cp + 2;
1856 						break;
1857 					}
1858 
1859 				} else if (used > 1 && *c == '\r' && *(c+1) == '\n') {
1860 					if (in_header == 0) {
1861 						/* got a response without a response header */
1862 
1863 						c = NULL;
1864 						header_end = 1;
1865 						break;
1866 					}
1867 
1868 					if (eol == EOL_UNSET) eol = EOL_RN;
1869 
1870 					if (used > 3 &&
1871 					    *(c+2) == '\r' &&
1872 					    *(c+3) == '\n') {
1873 						header_end = 1;
1874 						hlen = cp + 4;
1875 						break;
1876 					}
1877 
1878 					/* skip the \n */
1879 					c++;
1880 					cp++;
1881 					used--;
1882 				}
1883 			}
1884 
1885 			if (header_end) {
1886 				if (c == NULL) {
1887 					/* no header, but a body */
1888 
1889 					if (con->request.http_version == HTTP_VERSION_1_1) {
1890 						con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
1891 					}
1892 
1893 					http_chunk_append_mem(srv, con, hctx->response_header->ptr, hctx->response_header->used);
1894 					joblist_append(srv, con);
1895 				} else {
1896 					size_t blen = hctx->response_header->used - hlen - 1;
1897 
1898 					/* a small hack: terminate after at the second \r */
1899 					hctx->response_header->used = hlen;
1900 					hctx->response_header->ptr[hlen - 1] = '\0';
1901 
1902 					/* parse the response header */
1903 					scgi_response_parse(srv, con, p, hctx->response_header, eol);
1904 
1905 					/* enable chunked-transfer-encoding */
1906 					if (con->request.http_version == HTTP_VERSION_1_1 &&
1907 					    !(con->parsed_response & HTTP_CONTENT_LENGTH)) {
1908 						con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
1909 					}
1910 
1911 					if ((hctx->response->used != hlen) && blen > 0) {
1912 						http_chunk_append_mem(srv, con, hctx->response_header->ptr + hlen, blen + 1);
1913 						joblist_append(srv, con);
1914 					}
1915 				}
1916 
1917 				con->file_started = 1;
1918 			}
1919 		} else {
1920 			http_chunk_append_mem(srv, con, hctx->response->ptr, hctx->response->used);
1921 			joblist_append(srv, con);
1922 		}
1923 
1924 #if 0
1925 		log_error_write(srv, __FILE__, __LINE__, "ddss", con->fd, hctx->fd, connection_get_state(con->state), b->ptr);
1926 #endif
1927 	}
1928 
1929 	return 0;
1930 }
1931 
1932 
scgi_proclist_sort_up(server * srv,scgi_extension_host * host,scgi_proc * proc)1933 static int scgi_proclist_sort_up(server *srv, scgi_extension_host *host, scgi_proc *proc) {
1934 	scgi_proc *p;
1935 
1936 	UNUSED(srv);
1937 
1938 	/* we have been the smallest of the current list
1939 	 * and we want to insert the node sorted as soon
1940 	 * possible
1941 	 *
1942 	 * 1 0 0 0 1 1 1
1943 	 * |      ^
1944 	 * |      |
1945 	 * +------+
1946 	 *
1947 	 */
1948 
1949 	/* nothing to sort, only one element */
1950 	if (host->first == proc && proc->next == NULL) return 0;
1951 
1952 	for (p = proc; p->next && p->next->load < proc->load; p = p->next);
1953 
1954 	/* no need to move something
1955 	 *
1956 	 * 1 2 2 2 3 3 3
1957 	 * ^
1958 	 * |
1959 	 * +
1960 	 *
1961 	 */
1962 	if (p == proc) return 0;
1963 
1964 	if (host->first == proc) {
1965 		/* we have been the first elememt */
1966 
1967 		host->first = proc->next;
1968 		host->first->prev = NULL;
1969 	}
1970 
1971 	/* disconnect proc */
1972 
1973 	if (proc->prev) proc->prev->next = proc->next;
1974 	if (proc->next) proc->next->prev = proc->prev;
1975 
1976 	/* proc should be right of p */
1977 
1978 	proc->next = p->next;
1979 	proc->prev = p;
1980 	if (p->next) p->next->prev = proc;
1981 	p->next = proc;
1982 #if 0
1983 	for(p = host->first; p; p = p->next) {
1984 		log_error_write(srv, __FILE__, __LINE__, "dd",
1985 				p->pid, p->load);
1986 	}
1987 #else
1988 	UNUSED(srv);
1989 #endif
1990 
1991 	return 0;
1992 }
1993 
scgi_proclist_sort_down(server * srv,scgi_extension_host * host,scgi_proc * proc)1994 int scgi_proclist_sort_down(server *srv, scgi_extension_host *host, scgi_proc *proc) {
1995 	scgi_proc *p;
1996 
1997 	UNUSED(srv);
1998 
1999 	/* we have been the smallest of the current list
2000 	 * and we want to insert the node sorted as soon
2001 	 * possible
2002 	 *
2003 	 *  0 0 0 0 1 0 1
2004 	 * ^          |
2005 	 * |          |
2006 	 * +----------+
2007 	 *
2008 	 *
2009 	 * the basic is idea is:
2010 	 * - the last active scgi process should be still
2011 	 *   in ram and is not swapped out yet
2012 	 * - processes that are not reused will be killed
2013 	 *   after some time by the trigger-handler
2014 	 * - remember it as:
2015 	 *   everything > 0 is hot
2016 	 *   all unused procs are colder the more right they are
2017 	 *   ice-cold processes are propably unused since more
2018 	 *   than 'unused-timeout', are swaped out and won't be
2019 	 *   reused in the next seconds anyway.
2020 	 *
2021 	 */
2022 
2023 	/* nothing to sort, only one element */
2024 	if (host->first == proc && proc->next == NULL) return 0;
2025 
2026 	for (p = host->first; p != proc && p->load < proc->load; p = p->next);
2027 
2028 
2029 	/* no need to move something
2030 	 *
2031 	 * 1 2 2 2 3 3 3
2032 	 * ^
2033 	 * |
2034 	 * +
2035 	 *
2036 	 */
2037 	if (p == proc) return 0;
2038 
2039 	/* we have to move left. If we are already the first element
2040 	 * we are done */
2041 	if (host->first == proc) return 0;
2042 
2043 	/* release proc */
2044 	if (proc->prev) proc->prev->next = proc->next;
2045 	if (proc->next) proc->next->prev = proc->prev;
2046 
2047 	/* proc should be left of p */
2048 	proc->next = p;
2049 	proc->prev = p->prev;
2050 	if (p->prev) p->prev->next = proc;
2051 	p->prev = proc;
2052 
2053 	if (proc->prev == NULL) host->first = proc;
2054 #if 0
2055 	for(p = host->first; p; p = p->next) {
2056 		log_error_write(srv, __FILE__, __LINE__, "dd",
2057 				p->pid, p->load);
2058 	}
2059 #else
2060 	UNUSED(srv);
2061 #endif
2062 
2063 	return 0;
2064 }
2065 
scgi_restart_dead_procs(server * srv,plugin_data * p,scgi_extension_host * host)2066 static int scgi_restart_dead_procs(server *srv, plugin_data *p, scgi_extension_host *host) {
2067 	scgi_proc *proc;
2068 
2069 	for (proc = host->first; proc; proc = proc->next) {
2070 		if (p->conf.debug) {
2071 			log_error_write(srv, __FILE__, __LINE__,  "sbdbdddd",
2072 					"proc:",
2073 					host->host, proc->port,
2074 					proc->socket,
2075 					proc->state,
2076 					proc->is_local,
2077 					proc->load,
2078 					proc->pid);
2079 		}
2080 
2081 		if (0 == proc->is_local) {
2082 			/*
2083 			 * external servers might get disabled
2084 			 *
2085 			 * enable the server again, perhaps it is back again
2086 			 */
2087 
2088 			if ((proc->state == PROC_STATE_DISABLED) &&
2089 			    (srv->cur_ts - proc->disable_ts > host->disable_time)) {
2090 				proc->state = PROC_STATE_RUNNING;
2091 				host->active_procs++;
2092 
2093 				log_error_write(srv, __FILE__, __LINE__,  "sbdb",
2094 						"fcgi-server re-enabled:",
2095 						host->host, host->port,
2096 						host->unixsocket);
2097 			}
2098 		} else {
2099 			/* the child should not terminate at all */
2100 			int status;
2101 
2102 			if (proc->state == PROC_STATE_DIED_WAIT_FOR_PID) {
2103 				switch(waitpid(proc->pid, &status, WNOHANG)) {
2104 				case 0:
2105 					/* child is still alive */
2106 					break;
2107 				case -1:
2108 					break;
2109 				default:
2110 					if (WIFEXITED(status)) {
2111 #if 0
2112 						log_error_write(srv, __FILE__, __LINE__, "sdsd",
2113 								"child exited, pid:", proc->pid,
2114 								"status:", WEXITSTATUS(status));
2115 #endif
2116 					} else if (WIFSIGNALED(status)) {
2117 						log_error_write(srv, __FILE__, __LINE__, "sd",
2118 								"child signaled:",
2119 								WTERMSIG(status));
2120 					} else {
2121 						log_error_write(srv, __FILE__, __LINE__, "sd",
2122 								"child died somehow:",
2123 								status);
2124 					}
2125 
2126 					proc->state = PROC_STATE_DIED;
2127 					break;
2128 				}
2129 			}
2130 
2131 			/*
2132 			 * local servers might died, but we restart them
2133 			 *
2134 			 */
2135 			if (proc->state == PROC_STATE_DIED &&
2136 			    proc->load == 0) {
2137 				/* restart the child */
2138 
2139 				if (p->conf.debug) {
2140 					log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
2141 							"--- scgi spawning",
2142 							"\n\tport:", host->port,
2143 							"\n\tsocket", host->unixsocket,
2144 							"\n\tcurrent:", 1, "/", host->min_procs);
2145 				}
2146 
2147 				if (scgi_spawn_connection(srv, p, host, proc)) {
2148 					log_error_write(srv, __FILE__, __LINE__, "s",
2149 							"ERROR: spawning fcgi failed.");
2150 					return HANDLER_ERROR;
2151 				}
2152 
2153 				scgi_proclist_sort_down(srv, host, proc);
2154 			}
2155 		}
2156 	}
2157 
2158 	return 0;
2159 }
2160 
2161 
scgi_write_request(server * srv,handler_ctx * hctx)2162 static handler_t scgi_write_request(server *srv, handler_ctx *hctx) {
2163 	plugin_data *p    = hctx->plugin_data;
2164 	scgi_extension_host *host= hctx->host;
2165 	connection *con   = hctx->remote_conn;
2166 
2167 	int ret;
2168 
2169 	/* sanity check */
2170 	if (!host) {
2171 		log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: host = NULL");
2172 		return HANDLER_ERROR;
2173 	}
2174 	if (((!host->host->used || !host->port) && !host->unixsocket->used)) {
2175 		log_error_write(srv, __FILE__, __LINE__, "sxddd",
2176 				"write-req: error",
2177 				host,
2178 				host->host->used,
2179 				host->port,
2180 				host->unixsocket->used);
2181 		return HANDLER_ERROR;
2182 	}
2183 
2184 
2185 	switch(hctx->state) {
2186 	case FCGI_STATE_INIT:
2187 		ret = host->unixsocket->used ? AF_UNIX : AF_INET;
2188 
2189 		if (-1 == (hctx->fd = socket(ret, SOCK_STREAM, 0))) {
2190 			if (errno == EMFILE ||
2191 			    errno == EINTR) {
2192 				log_error_write(srv, __FILE__, __LINE__, "sd",
2193 						"wait for fd at connection:", con->fd);
2194 
2195 				return HANDLER_WAIT_FOR_FD;
2196 			}
2197 
2198 			log_error_write(srv, __FILE__, __LINE__, "ssdd",
2199 					"socket failed:", strerror(errno), srv->cur_fds, srv->max_fds);
2200 			return HANDLER_ERROR;
2201 		}
2202 		hctx->fde_ndx = -1;
2203 
2204 		srv->cur_fds++;
2205 
2206 		fdevent_register(srv->ev, hctx->fd, scgi_handle_fdevent, hctx);
2207 
2208 		if (-1 == fdevent_fcntl_set(srv->ev, hctx->fd)) {
2209 			log_error_write(srv, __FILE__, __LINE__, "ss",
2210 					"fcntl failed: ", strerror(errno));
2211 
2212 			return HANDLER_ERROR;
2213 		}
2214 
2215 		/* fall through */
2216 	case FCGI_STATE_CONNECT:
2217 		if (hctx->state == FCGI_STATE_INIT) {
2218 			for (hctx->proc = hctx->host->first;
2219 			     hctx->proc && hctx->proc->state != PROC_STATE_RUNNING;
2220 			     hctx->proc = hctx->proc->next);
2221 
2222 			/* all childs are dead */
2223 			if (hctx->proc == NULL) {
2224 				hctx->fde_ndx = -1;
2225 
2226 				return HANDLER_ERROR;
2227 			}
2228 
2229 			if (hctx->proc->is_local) {
2230 				hctx->pid = hctx->proc->pid;
2231 			}
2232 
2233 			switch (scgi_establish_connection(srv, hctx)) {
2234 			case 1:
2235 				scgi_set_state(srv, hctx, FCGI_STATE_CONNECT);
2236 
2237 				/* connection is in progress, wait for an event and call getsockopt() below */
2238 
2239 				fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2240 
2241 				return HANDLER_WAIT_FOR_EVENT;
2242 			case -1:
2243 				/* if ECONNREFUSED choose another connection -> FIXME */
2244 				hctx->fde_ndx = -1;
2245 
2246 				return HANDLER_ERROR;
2247 			default:
2248 				/* everything is ok, go on */
2249 				break;
2250 			}
2251 
2252 
2253 		} else {
2254 			int socket_error;
2255 			socklen_t socket_error_len = sizeof(socket_error);
2256 
2257 			/* try to finish the connect() */
2258 			if (0 != getsockopt(hctx->fd, SOL_SOCKET, SO_ERROR, &socket_error, &socket_error_len)) {
2259 				log_error_write(srv, __FILE__, __LINE__, "ss",
2260 						"getsockopt failed:", strerror(errno));
2261 
2262 				return HANDLER_ERROR;
2263 			}
2264 			if (socket_error != 0) {
2265 				if (!hctx->proc->is_local || p->conf.debug) {
2266 					/* local procs get restarted */
2267 
2268 					log_error_write(srv, __FILE__, __LINE__, "ss",
2269 							"establishing connection failed:", strerror(socket_error),
2270 							"port:", hctx->proc->port);
2271 				}
2272 
2273 				return HANDLER_ERROR;
2274 			}
2275 		}
2276 
2277 		/* ok, we have the connection */
2278 
2279 		hctx->proc->load++;
2280 		hctx->proc->last_used = srv->cur_ts;
2281 		hctx->got_proc = 1;
2282 
2283 		if (p->conf.debug) {
2284 			log_error_write(srv, __FILE__, __LINE__, "sddbdd",
2285 					"got proc:",
2286 					hctx->fd,
2287 					hctx->proc->pid,
2288 					hctx->proc->socket,
2289 					hctx->proc->port,
2290 					hctx->proc->load);
2291 		}
2292 
2293 		/* move the proc-list entry down the list */
2294 		scgi_proclist_sort_up(srv, hctx->host, hctx->proc);
2295 
2296 		scgi_set_state(srv, hctx, FCGI_STATE_PREPARE_WRITE);
2297 		/* fall through */
2298 	case FCGI_STATE_PREPARE_WRITE:
2299 		scgi_create_env(srv, hctx);
2300 
2301 		scgi_set_state(srv, hctx, FCGI_STATE_WRITE);
2302 
2303 		/* fall through */
2304 	case FCGI_STATE_WRITE:
2305 		ret = srv->network_backend_write(srv, con, hctx->fd, hctx->wb, MAX_WRITE_LIMIT);
2306 
2307 		chunkqueue_remove_finished_chunks(hctx->wb);
2308 
2309 		if (ret < 0) {
2310 			if (errno == ENOTCONN || ret == -2) {
2311 				/* the connection got dropped after accept()
2312 				 *
2313 				 * this is most of the time a PHP which dies
2314 				 * after PHP_FCGI_MAX_REQUESTS
2315 				 *
2316 				 */
2317 				if (hctx->wb->bytes_out == 0 &&
2318 				    hctx->reconnects < 5) {
2319 					usleep(10000); /* take away the load of the webserver
2320 							* to let the php a chance to restart
2321 							*/
2322 
2323 					scgi_reconnect(srv, hctx);
2324 
2325 					return HANDLER_WAIT_FOR_FD;
2326 				}
2327 
2328 				/* not reconnected ... why
2329 				 *
2330 				 * far@#lighttpd report this for FreeBSD
2331 				 *
2332 				 */
2333 
2334 				log_error_write(srv, __FILE__, __LINE__, "ssosd",
2335 						"connection was dropped after accept(). reconnect() denied:",
2336 						"write-offset:", hctx->wb->bytes_out,
2337 						"reconnect attempts:", hctx->reconnects);
2338 
2339 				return HANDLER_ERROR;
2340 			} else {
2341 				/* -1 == ret => error on our side */
2342 				log_error_write(srv, __FILE__, __LINE__, "ssd",
2343 					"write failed:", strerror(errno), errno);
2344 
2345 				return HANDLER_ERROR;
2346 			}
2347 		}
2348 
2349 		if (hctx->wb->bytes_out == hctx->wb->bytes_in) {
2350 			/* we don't need the out event anymore */
2351 			fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
2352 			fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2353 			scgi_set_state(srv, hctx, FCGI_STATE_READ);
2354 		} else {
2355 			fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2356 
2357 			return HANDLER_WAIT_FOR_EVENT;
2358 		}
2359 
2360 		break;
2361 	case FCGI_STATE_READ:
2362 		/* waiting for a response */
2363 		break;
2364 	default:
2365 		log_error_write(srv, __FILE__, __LINE__, "s", "(debug) unknown state");
2366 		return HANDLER_ERROR;
2367 	}
2368 
2369 	return HANDLER_WAIT_FOR_EVENT;
2370 }
2371 
SUBREQUEST_FUNC(mod_scgi_handle_subrequest)2372 SUBREQUEST_FUNC(mod_scgi_handle_subrequest) {
2373 	plugin_data *p = p_d;
2374 
2375 	handler_ctx *hctx = con->plugin_ctx[p->id];
2376 	scgi_proc *proc;
2377 	scgi_extension_host *host;
2378 
2379 	if (NULL == hctx) return HANDLER_GO_ON;
2380 
2381 	/* not my job */
2382 	if (con->mode != p->id) return HANDLER_GO_ON;
2383 
2384 	/* ok, create the request */
2385 	switch(scgi_write_request(srv, hctx)) {
2386 	case HANDLER_ERROR:
2387 		proc = hctx->proc;
2388 		host = hctx->host;
2389 
2390 		if (proc &&
2391 		    0 == proc->is_local &&
2392 		    proc->state != PROC_STATE_DISABLED) {
2393 			/* only disable remote servers as we don't manage them*/
2394 
2395 			log_error_write(srv, __FILE__, __LINE__,  "sbdb", "fcgi-server disabled:",
2396 					host->host,
2397 					proc->port,
2398 					proc->socket);
2399 
2400 			/* disable this server */
2401 			proc->disable_ts = srv->cur_ts;
2402 			proc->state = PROC_STATE_DISABLED;
2403 			host->active_procs--;
2404 		}
2405 
2406 		if (hctx->state == FCGI_STATE_INIT ||
2407 		    hctx->state == FCGI_STATE_CONNECT) {
2408 			/* connect() or getsockopt() failed,
2409 			 * restart the request-handling
2410 			 */
2411 			if (proc && proc->is_local) {
2412 
2413 				if (p->conf.debug) {
2414 					log_error_write(srv, __FILE__, __LINE__,  "sbdb", "connect() to scgi failed, restarting the request-handling:",
2415 							host->host,
2416 							proc->port,
2417 							proc->socket);
2418 				}
2419 
2420 				/*
2421 				 * several hctx might reference the same proc
2422 				 *
2423 				 * Only one of them should mark the proc as dead all the other
2424 				 * ones should just take a new one.
2425 				 *
2426 				 * If a new proc was started with the old struct this might lead
2427 				 * the mark a perfect proc as dead otherwise
2428 				 *
2429 				 */
2430 				if (proc->state == PROC_STATE_RUNNING &&
2431 				    hctx->pid == proc->pid) {
2432 					proc->state = PROC_STATE_DIED_WAIT_FOR_PID;
2433 				}
2434 			}
2435 			scgi_restart_dead_procs(srv, p, host);
2436 
2437 			scgi_connection_cleanup(srv, hctx);
2438 
2439 			buffer_reset(con->physical.path);
2440 			con->mode = DIRECT;
2441 			joblist_append(srv, con);
2442 
2443 			/* mis-using HANDLER_WAIT_FOR_FD to break out of the loop
2444 			 * and hope that the childs will be restarted
2445 			 *
2446 			 */
2447 			return HANDLER_WAIT_FOR_FD;
2448 		} else {
2449 			scgi_connection_cleanup(srv, hctx);
2450 
2451 			buffer_reset(con->physical.path);
2452 			con->mode = DIRECT;
2453 			con->http_status = 503;
2454 
2455 			return HANDLER_FINISHED;
2456 		}
2457 	case HANDLER_WAIT_FOR_EVENT:
2458 		if (con->file_started == 1) {
2459 			return HANDLER_FINISHED;
2460 		} else {
2461 			return HANDLER_WAIT_FOR_EVENT;
2462 		}
2463 	case HANDLER_WAIT_FOR_FD:
2464 		return HANDLER_WAIT_FOR_FD;
2465 	default:
2466 		log_error_write(srv, __FILE__, __LINE__, "s", "subrequest write-req default");
2467 		return HANDLER_ERROR;
2468 	}
2469 }
2470 
scgi_connection_close(server * srv,handler_ctx * hctx)2471 static handler_t scgi_connection_close(server *srv, handler_ctx *hctx) {
2472 	connection  *con;
2473 
2474 	if (NULL == hctx) return HANDLER_GO_ON;
2475 
2476 	con  = hctx->remote_conn;
2477 
2478 	log_error_write(srv, __FILE__, __LINE__, "ssdsd",
2479 			"emergency exit: scgi:",
2480 			"connection-fd:", con->fd,
2481 			"fcgi-fd:", hctx->fd);
2482 
2483 	scgi_connection_cleanup(srv, hctx);
2484 
2485 	return HANDLER_FINISHED;
2486 }
2487 
2488 
scgi_handle_fdevent(server * srv,void * ctx,int revents)2489 static handler_t scgi_handle_fdevent(server *srv, void *ctx, int revents) {
2490 	handler_ctx *hctx = ctx;
2491 	connection  *con  = hctx->remote_conn;
2492 	plugin_data *p    = hctx->plugin_data;
2493 
2494 	scgi_proc *proc   = hctx->proc;
2495 	scgi_extension_host *host= hctx->host;
2496 
2497 	if ((revents & FDEVENT_IN) &&
2498 	    hctx->state == FCGI_STATE_READ) {
2499 		switch (scgi_demux_response(srv, hctx)) {
2500 		case 0:
2501 			break;
2502 		case 1:
2503 			/* we are done */
2504 			scgi_connection_cleanup(srv, hctx);
2505 
2506 			joblist_append(srv, con);
2507 			return HANDLER_FINISHED;
2508 		case -1:
2509 			if (proc->pid && proc->state != PROC_STATE_DIED) {
2510 				int status;
2511 
2512 				/* only fetch the zombie if it is not already done */
2513 
2514 				switch(waitpid(proc->pid, &status, WNOHANG)) {
2515 				case 0:
2516 					/* child is still alive */
2517 					break;
2518 				case -1:
2519 					break;
2520 				default:
2521 					/* the child should not terminate at all */
2522 					if (WIFEXITED(status)) {
2523 						log_error_write(srv, __FILE__, __LINE__, "sdsd",
2524 								"child exited, pid:", proc->pid,
2525 								"status:", WEXITSTATUS(status));
2526 					} else if (WIFSIGNALED(status)) {
2527 						log_error_write(srv, __FILE__, __LINE__, "sd",
2528 								"child signaled:",
2529 								WTERMSIG(status));
2530 					} else {
2531 						log_error_write(srv, __FILE__, __LINE__, "sd",
2532 								"child died somehow:",
2533 								status);
2534 					}
2535 
2536 					if (p->conf.debug) {
2537 						log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
2538 								"--- scgi spawning",
2539 								"\n\tport:", host->port,
2540 								"\n\tsocket", host->unixsocket,
2541 								"\n\tcurrent:", 1, "/", host->min_procs);
2542 					}
2543 
2544 					if (scgi_spawn_connection(srv, p, host, proc)) {
2545 						/* child died */
2546 						proc->state = PROC_STATE_DIED;
2547 					} else {
2548 						scgi_proclist_sort_down(srv, host, proc);
2549 					}
2550 
2551 					break;
2552 				}
2553 			}
2554 
2555 			if (con->file_started == 0) {
2556 				/* nothing has been send out yet, try to use another child */
2557 
2558 				if (hctx->wb->bytes_out == 0 &&
2559 				    hctx->reconnects < 5) {
2560 					scgi_reconnect(srv, hctx);
2561 
2562 					log_error_write(srv, __FILE__, __LINE__, "ssdsd",
2563 						"response not sent, request not sent, reconnection.",
2564 						"connection-fd:", con->fd,
2565 						"fcgi-fd:", hctx->fd);
2566 
2567 					return HANDLER_WAIT_FOR_FD;
2568 				}
2569 
2570 				log_error_write(srv, __FILE__, __LINE__, "sosdsd",
2571 						"response not sent, request sent:", hctx->wb->bytes_out,
2572 						"connection-fd:", con->fd,
2573 						"fcgi-fd:", hctx->fd);
2574 
2575 				scgi_connection_cleanup(srv, hctx);
2576 
2577 				connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
2578 				buffer_reset(con->physical.path);
2579 				con->http_status = 500;
2580 				con->mode = DIRECT;
2581 			} else {
2582 				/* response might have been already started, kill the connection */
2583 				log_error_write(srv, __FILE__, __LINE__, "ssdsd",
2584 						"response already sent out, termination connection",
2585 						"connection-fd:", con->fd,
2586 						"fcgi-fd:", hctx->fd);
2587 
2588 				scgi_connection_cleanup(srv, hctx);
2589 
2590 				connection_set_state(srv, con, CON_STATE_ERROR);
2591 			}
2592 
2593 			/* */
2594 
2595 
2596 			joblist_append(srv, con);
2597 			return HANDLER_FINISHED;
2598 		}
2599 	}
2600 
2601 	if (revents & FDEVENT_OUT) {
2602 		if (hctx->state == FCGI_STATE_CONNECT ||
2603 		    hctx->state == FCGI_STATE_WRITE) {
2604 			/* we are allowed to send something out
2605 			 *
2606 			 * 1. in a unfinished connect() call
2607 			 * 2. in a unfinished write() call (long POST request)
2608 			 */
2609 			return mod_scgi_handle_subrequest(srv, con, p);
2610 		} else {
2611 			log_error_write(srv, __FILE__, __LINE__, "sd",
2612 					"got a FDEVENT_OUT and didn't know why:",
2613 					hctx->state);
2614 		}
2615 	}
2616 
2617 	/* perhaps this issue is already handled */
2618 	if (revents & FDEVENT_HUP) {
2619 		if (hctx->state == FCGI_STATE_CONNECT) {
2620 			/* getoptsock will catch this one (right ?)
2621 			 *
2622 			 * if we are in connect we might get a EINPROGRESS
2623 			 * in the first call and a FDEVENT_HUP in the
2624 			 * second round
2625 			 *
2626 			 * FIXME: as it is a bit ugly.
2627 			 *
2628 			 */
2629 			return mod_scgi_handle_subrequest(srv, con, p);
2630 		} else if (hctx->state == FCGI_STATE_READ &&
2631 			   hctx->proc->port == 0) {
2632 			/* FIXME:
2633 			 *
2634 			 * ioctl says 8192 bytes to read from PHP and we receive directly a HUP for the socket
2635 			 * even if the FCGI_FIN packet is not received yet
2636 			 */
2637 		} else {
2638 			log_error_write(srv, __FILE__, __LINE__, "sbSBSDSd",
2639 					"error: unexpected close of scgi connection for",
2640 					con->uri.path,
2641 					"(no scgi process on host: ",
2642 					host->host,
2643 					", port: ",
2644 					host->port,
2645 					" ?)",
2646 					hctx->state);
2647 
2648 			connection_set_state(srv, con, CON_STATE_ERROR);
2649 			scgi_connection_close(srv, hctx);
2650 			joblist_append(srv, con);
2651 		}
2652 	} else if (revents & FDEVENT_ERR) {
2653 		log_error_write(srv, __FILE__, __LINE__, "s",
2654 				"fcgi: got a FDEVENT_ERR. Don't know why.");
2655 		/* kill all connections to the scgi process */
2656 
2657 
2658 		connection_set_state(srv, con, CON_STATE_ERROR);
2659 		scgi_connection_close(srv, hctx);
2660 		joblist_append(srv, con);
2661 	}
2662 
2663 	return HANDLER_FINISHED;
2664 }
2665 #define PATCH(x) \
2666 	p->conf.x = s->x;
scgi_patch_connection(server * srv,connection * con,plugin_data * p)2667 static int scgi_patch_connection(server *srv, connection *con, plugin_data *p) {
2668 	size_t i, j;
2669 	plugin_config *s = p->config_storage[0];
2670 
2671 	PATCH(exts);
2672 	PATCH(debug);
2673 
2674 	/* skip the first, the global context */
2675 	for (i = 1; i < srv->config_context->used; i++) {
2676 		data_config *dc = (data_config *)srv->config_context->data[i];
2677 		s = p->config_storage[i];
2678 
2679 		/* condition didn't match */
2680 		if (!config_check_cond(srv, con, dc)) continue;
2681 
2682 		/* merge config */
2683 		for (j = 0; j < dc->value->used; j++) {
2684 			data_unset *du = dc->value->data[j];
2685 
2686 			if (buffer_is_equal_string(du->key, CONST_STR_LEN("scgi.server"))) {
2687 				PATCH(exts);
2688 			} else if (buffer_is_equal_string(du->key, CONST_STR_LEN("scgi.debug"))) {
2689 				PATCH(debug);
2690 			}
2691 		}
2692 	}
2693 
2694 	return 0;
2695 }
2696 #undef PATCH
2697 
2698 
scgi_check_extension(server * srv,connection * con,void * p_d,int uri_path_handler)2699 static handler_t scgi_check_extension(server *srv, connection *con, void *p_d, int uri_path_handler) {
2700 	plugin_data *p = p_d;
2701 	size_t s_len;
2702 	int used = -1;
2703 	size_t k;
2704 	buffer *fn;
2705 	scgi_extension *extension = NULL;
2706 	scgi_extension_host *host = NULL;
2707 
2708 	if (con->mode != DIRECT) return HANDLER_GO_ON;
2709 
2710 	/* Possibly, we processed already this request */
2711 	if (con->file_started == 1) return HANDLER_GO_ON;
2712 
2713 	fn = uri_path_handler ? con->uri.path : con->physical.path;
2714 
2715 	if (buffer_is_empty(fn)) return HANDLER_GO_ON;
2716 
2717 	s_len = fn->used - 1;
2718 
2719 	scgi_patch_connection(srv, con, p);
2720 
2721 	/* check if extension matches */
2722 	for (k = 0; k < p->conf.exts->used; k++) {
2723 		size_t ct_len;
2724 		scgi_extension *ext = p->conf.exts->exts[k];
2725 
2726 		if (ext->key->used == 0) continue;
2727 
2728 		ct_len = ext->key->used - 1;
2729 
2730 		if (s_len < ct_len) continue;
2731 
2732 		/* check extension in the form "/scgi_pattern" */
2733 		if (*(ext->key->ptr) == '/') {
2734 			if (strncmp(fn->ptr, ext->key->ptr, ct_len) == 0) {
2735 				extension = ext;
2736 				break;
2737 			}
2738 		} else if (0 == strncmp(fn->ptr + s_len - ct_len, ext->key->ptr, ct_len)) {
2739 			/* check extension in the form ".fcg" */
2740 			extension = ext;
2741 			break;
2742 		}
2743 	}
2744 
2745 	/* extension doesn't match */
2746 	if (NULL == extension) {
2747 		return HANDLER_GO_ON;
2748 	}
2749 
2750 	/* get best server */
2751 	for (k = 0; k < extension->used; k++) {
2752 		scgi_extension_host *h = extension->hosts[k];
2753 
2754 		/* we should have at least one proc that can do something */
2755 		if (h->active_procs == 0) {
2756 			continue;
2757 		}
2758 
2759 		if (used == -1 || h->load < used) {
2760 			used = h->load;
2761 
2762 			host = h;
2763 		}
2764 	}
2765 
2766 	if (!host) {
2767 		/* sorry, we don't have a server alive for this ext */
2768 		buffer_reset(con->physical.path);
2769 		con->http_status = 500;
2770 
2771 		/* only send the 'no handler' once */
2772 		if (!extension->note_is_sent) {
2773 			extension->note_is_sent = 1;
2774 
2775 			log_error_write(srv, __FILE__, __LINE__, "sbsbs",
2776 					"all handlers for ", con->uri.path,
2777 					"on", extension->key,
2778 					"are down.");
2779 		}
2780 
2781 		return HANDLER_FINISHED;
2782 	}
2783 
2784 	/* a note about no handler is not sent yet */
2785 	extension->note_is_sent = 0;
2786 
2787 	/*
2788 	 * if check-local is disabled, use the uri.path handler
2789 	 *
2790 	 */
2791 
2792 	/* init handler-context */
2793 	if (uri_path_handler) {
2794 		if (host->check_local == 0) {
2795 			handler_ctx *hctx;
2796 			char *pathinfo;
2797 
2798 			hctx = handler_ctx_init();
2799 
2800 			hctx->remote_conn      = con;
2801 			hctx->plugin_data      = p;
2802 			hctx->host             = host;
2803 			hctx->proc	       = NULL;
2804 
2805 			hctx->conf.exts        = p->conf.exts;
2806 			hctx->conf.debug       = p->conf.debug;
2807 
2808 			con->plugin_ctx[p->id] = hctx;
2809 
2810 			host->load++;
2811 
2812 			con->mode = p->id;
2813 
2814 			if (con->conf.log_request_handling) {
2815 				log_error_write(srv, __FILE__, __LINE__, "s",
2816 				"handling it in mod_fastcgi");
2817 			}
2818 
2819 			/* the prefix is the SCRIPT_NAME,
2820 			 * everything from start to the next slash
2821 			 * this is important for check-local = "disable"
2822 			 *
2823 			 * if prefix = /admin.fcgi
2824 			 *
2825 			 * /admin.fcgi/foo/bar
2826 			 *
2827 			 * SCRIPT_NAME = /admin.fcgi
2828 			 * PATH_INFO   = /foo/bar
2829 			 *
2830 			 * if prefix = /fcgi-bin/
2831 			 *
2832 			 * /fcgi-bin/foo/bar
2833 			 *
2834 			 * SCRIPT_NAME = /fcgi-bin/foo
2835 			 * PATH_INFO   = /bar
2836 			 *
2837 			 */
2838 
2839 			/* the rewrite is only done for /prefix/? matches */
2840 			if (host->fix_root_path_name && extension->key->ptr[0] == '/' && extension->key->ptr[1] == '\0') {
2841 				buffer_copy_string(con->request.pathinfo, con->uri.path->ptr);
2842 				con->uri.path->used = 1;
2843 				con->uri.path->ptr[con->uri.path->used - 1] = '\0';
2844 			} else if (extension->key->ptr[0] == '/' &&
2845 			    con->uri.path->used > extension->key->used &&
2846 			    NULL != (pathinfo = strchr(con->uri.path->ptr + extension->key->used - 1, '/'))) {
2847 				/* rewrite uri.path and pathinfo */
2848 
2849 				buffer_copy_string(con->request.pathinfo, pathinfo);
2850 
2851 				con->uri.path->used -= con->request.pathinfo->used - 1;
2852 				con->uri.path->ptr[con->uri.path->used - 1] = '\0';
2853 			}
2854 		}
2855 	} else {
2856 		handler_ctx *hctx;
2857 		hctx = handler_ctx_init();
2858 
2859 		hctx->remote_conn      = con;
2860 		hctx->plugin_data      = p;
2861 		hctx->host             = host;
2862 		hctx->proc             = NULL;
2863 
2864 		hctx->conf.exts        = p->conf.exts;
2865 		hctx->conf.debug       = p->conf.debug;
2866 
2867 		con->plugin_ctx[p->id] = hctx;
2868 
2869 		host->load++;
2870 
2871 		con->mode = p->id;
2872 
2873 		if (con->conf.log_request_handling) {
2874 			log_error_write(srv, __FILE__, __LINE__, "s", "handling it in mod_fastcgi");
2875 		}
2876 	}
2877 
2878 	return HANDLER_GO_ON;
2879 }
2880 
2881 /* uri-path handler */
scgi_check_extension_1(server * srv,connection * con,void * p_d)2882 static handler_t scgi_check_extension_1(server *srv, connection *con, void *p_d) {
2883 	return scgi_check_extension(srv, con, p_d, 1);
2884 }
2885 
2886 /* start request handler */
scgi_check_extension_2(server * srv,connection * con,void * p_d)2887 static handler_t scgi_check_extension_2(server *srv, connection *con, void *p_d) {
2888 	return scgi_check_extension(srv, con, p_d, 0);
2889 }
2890 
JOBLIST_FUNC(mod_scgi_handle_joblist)2891 JOBLIST_FUNC(mod_scgi_handle_joblist) {
2892 	plugin_data *p = p_d;
2893 	handler_ctx *hctx = con->plugin_ctx[p->id];
2894 
2895 	if (hctx == NULL) return HANDLER_GO_ON;
2896 
2897 	if (hctx->fd != -1) {
2898 		switch (hctx->state) {
2899 		case FCGI_STATE_READ:
2900 			fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2901 
2902 			break;
2903 		case FCGI_STATE_CONNECT:
2904 		case FCGI_STATE_WRITE:
2905 			fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2906 
2907 			break;
2908 		case FCGI_STATE_INIT:
2909 			/* at reconnect */
2910 			break;
2911 		default:
2912 			log_error_write(srv, __FILE__, __LINE__, "sd", "unhandled fcgi.state", hctx->state);
2913 			break;
2914 		}
2915 	}
2916 
2917 	return HANDLER_GO_ON;
2918 }
2919 
2920 
scgi_connection_close_callback(server * srv,connection * con,void * p_d)2921 static handler_t scgi_connection_close_callback(server *srv, connection *con, void *p_d) {
2922 	plugin_data *p = p_d;
2923 
2924 	return scgi_connection_close(srv, con->plugin_ctx[p->id]);
2925 }
2926 
TRIGGER_FUNC(mod_scgi_handle_trigger)2927 TRIGGER_FUNC(mod_scgi_handle_trigger) {
2928 	plugin_data *p = p_d;
2929 	size_t i, j, n;
2930 
2931 
2932 	/* perhaps we should kill a connect attempt after 10-15 seconds
2933 	 *
2934 	 * currently we wait for the TCP timeout which is on Linux 180 seconds
2935 	 *
2936 	 *
2937 	 *
2938 	 */
2939 
2940 	/* check all childs if they are still up */
2941 
2942 	for (i = 0; i < srv->config_context->used; i++) {
2943 		plugin_config *conf;
2944 		scgi_exts *exts;
2945 
2946 		conf = p->config_storage[i];
2947 
2948 		exts = conf->exts;
2949 
2950 		for (j = 0; j < exts->used; j++) {
2951 			scgi_extension *ex;
2952 
2953 			ex = exts->exts[j];
2954 
2955 			for (n = 0; n < ex->used; n++) {
2956 
2957 				scgi_proc *proc;
2958 				unsigned long sum_load = 0;
2959 				scgi_extension_host *host;
2960 
2961 				host = ex->hosts[n];
2962 
2963 				scgi_restart_dead_procs(srv, p, host);
2964 
2965 				for (proc = host->first; proc; proc = proc->next) {
2966 					sum_load += proc->load;
2967 				}
2968 
2969 				if (host->num_procs &&
2970 				    host->num_procs < host->max_procs &&
2971 				    (sum_load / host->num_procs) > host->max_load_per_proc) {
2972 					/* overload, spawn new child */
2973 					scgi_proc *fp = NULL;
2974 
2975 					if (p->conf.debug) {
2976 						log_error_write(srv, __FILE__, __LINE__, "s",
2977 								"overload detected, spawning a new child");
2978 					}
2979 
2980 					for (fp = host->unused_procs; fp && fp->pid != 0; fp = fp->next);
2981 
2982 					if (fp) {
2983 						if (fp == host->unused_procs) host->unused_procs = fp->next;
2984 
2985 						if (fp->next) fp->next->prev = NULL;
2986 
2987 						host->max_id++;
2988 					} else {
2989 						fp = scgi_process_init();
2990 						fp->id = host->max_id++;
2991 					}
2992 
2993 					host->num_procs++;
2994 
2995 					if (buffer_is_empty(host->unixsocket)) {
2996 						fp->port = host->port + fp->id;
2997 					} else {
2998 						buffer_copy_string_buffer(fp->socket, host->unixsocket);
2999 						buffer_append_string_len(fp->socket, CONST_STR_LEN("-"));
3000 						buffer_append_long(fp->socket, fp->id);
3001 					}
3002 
3003 					if (scgi_spawn_connection(srv, p, host, fp)) {
3004 						log_error_write(srv, __FILE__, __LINE__, "s",
3005 								"ERROR: spawning fcgi failed.");
3006 						return HANDLER_ERROR;
3007 					}
3008 
3009 					fp->prev = NULL;
3010 					fp->next = host->first;
3011 					if (host->first) {
3012 						host->first->prev = fp;
3013 					}
3014 					host->first = fp;
3015 				}
3016 
3017 				for (proc = host->first; proc; proc = proc->next) {
3018 					if (proc->load != 0) break;
3019 					if (host->num_procs <= host->min_procs) break;
3020 					if (proc->pid == 0) continue;
3021 
3022 					if (srv->cur_ts - proc->last_used > host->idle_timeout) {
3023 						/* a proc is idling for a long time now,
3024 						 * terminated it */
3025 
3026 						if (p->conf.debug) {
3027 							log_error_write(srv, __FILE__, __LINE__, "ssbsd",
3028 									"idle-timeout reached, terminating child:",
3029 									"socket:", proc->socket,
3030 									"pid", proc->pid);
3031 						}
3032 
3033 
3034 						if (proc->next) proc->next->prev = proc->prev;
3035 						if (proc->prev) proc->prev->next = proc->next;
3036 
3037 						if (proc->prev == NULL) host->first = proc->next;
3038 
3039 						proc->prev = NULL;
3040 						proc->next = host->unused_procs;
3041 
3042 						if (host->unused_procs) host->unused_procs->prev = proc;
3043 						host->unused_procs = proc;
3044 
3045 						kill(proc->pid, SIGTERM);
3046 
3047 						proc->state = PROC_STATE_KILLED;
3048 
3049 						log_error_write(srv, __FILE__, __LINE__, "ssbsd",
3050 									"killed:",
3051 									"socket:", proc->socket,
3052 									"pid", proc->pid);
3053 
3054 						host->num_procs--;
3055 
3056 						/* proc is now in unused, let the next second handle the next process */
3057 						break;
3058 					}
3059 				}
3060 
3061 				for (proc = host->unused_procs; proc; proc = proc->next) {
3062 					int status;
3063 
3064 					if (proc->pid == 0) continue;
3065 
3066 					switch (waitpid(proc->pid, &status, WNOHANG)) {
3067 					case 0:
3068 						/* child still running after timeout, good */
3069 						break;
3070 					case -1:
3071 						if (errno != EINTR) {
3072 							/* no PID found ? should never happen */
3073 							log_error_write(srv, __FILE__, __LINE__, "sddss",
3074 									"pid ", proc->pid, proc->state,
3075 									"not found:", strerror(errno));
3076 
3077 #if 0
3078 							if (errno == ECHILD) {
3079 								/* someone else has cleaned up for us */
3080 								proc->pid = 0;
3081 								proc->state = PROC_STATE_UNSET;
3082 							}
3083 #endif
3084 						}
3085 						break;
3086 					default:
3087 						/* the child should not terminate at all */
3088 						if (WIFEXITED(status)) {
3089 							if (proc->state != PROC_STATE_KILLED) {
3090 								log_error_write(srv, __FILE__, __LINE__, "sdb",
3091 										"child exited:",
3092 										WEXITSTATUS(status), proc->socket);
3093 							}
3094 						} else if (WIFSIGNALED(status)) {
3095 							if (WTERMSIG(status) != SIGTERM) {
3096 								log_error_write(srv, __FILE__, __LINE__, "sd",
3097 										"child signaled:",
3098 										WTERMSIG(status));
3099 							}
3100 						} else {
3101 							log_error_write(srv, __FILE__, __LINE__, "sd",
3102 									"child died somehow:",
3103 									status);
3104 						}
3105 						proc->pid = 0;
3106 						proc->state = PROC_STATE_UNSET;
3107 						host->max_id--;
3108 					}
3109 				}
3110 			}
3111 		}
3112 	}
3113 
3114 	return HANDLER_GO_ON;
3115 }
3116 
3117 
3118 int mod_scgi_plugin_init(plugin *p);
mod_scgi_plugin_init(plugin * p)3119 int mod_scgi_plugin_init(plugin *p) {
3120 	p->version     = LIGHTTPD_VERSION_ID;
3121 	p->name         = buffer_init_string("scgi");
3122 
3123 	p->init         = mod_scgi_init;
3124 	p->cleanup      = mod_scgi_free;
3125 	p->set_defaults = mod_scgi_set_defaults;
3126 	p->connection_reset        = scgi_connection_reset;
3127 	p->handle_connection_close = scgi_connection_close_callback;
3128 	p->handle_uri_clean        = scgi_check_extension_1;
3129 	p->handle_subrequest_start = scgi_check_extension_2;
3130 	p->handle_subrequest       = mod_scgi_handle_subrequest;
3131 	p->handle_joblist          = mod_scgi_handle_joblist;
3132 	p->handle_trigger          = mod_scgi_handle_trigger;
3133 
3134 	p->data         = NULL;
3135 
3136 	return 0;
3137 }
3138