File:  [ELWIX - Embedded LightWeight unIX -] / embedaddon / lighttpd / src / mod_scgi.c
Revision 1.1.1.2 (vendor branch): download - view: text, annotated - select for diffs - revision graph
Sun Jun 15 20:20:06 2014 UTC (10 years ago) by misho
Branches: lighttpd, MAIN
CVS tags: v1_4_35p0, v1_4_35, HEAD
lighttpd 1.4.35

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>