[mod_fastcgi,mod_scgi] check for spawning on same unix socket (#319)
[lighttpd.git] / src / mod_scgi.c
blob584c20a1afe78fadf3b68009d572ca4ace724d5f
1 #include "first.h"
3 #include "buffer.h"
4 #include "server.h"
5 #include "keyvalue.h"
6 #include "log.h"
8 #include "http_chunk.h"
9 #include "fdevent.h"
10 #include "connections.h"
11 #include "response.h"
12 #include "joblist.h"
14 #include "plugin.h"
16 #include "inet_ntop_cache.h"
18 #include <sys/types.h>
19 #include <unistd.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <ctype.h>
25 #include <assert.h>
26 #include <signal.h>
28 #include <stdio.h>
30 #include "sys-socket.h"
32 #ifdef HAVE_SYS_UIO_H
33 # include <sys/uio.h>
34 #endif
36 #ifdef HAVE_SYS_WAIT_H
37 # include <sys/wait.h>
38 #endif
40 enum {EOL_UNSET, EOL_N, EOL_RN};
44 * TODO:
46 * - add timeout for a connect to a non-scgi process
47 * (use state_timestamp + state)
51 typedef struct scgi_proc {
52 size_t id; /* id will be between 1 and max_procs */
53 buffer *socket; /* config.socket + "-" + id */
54 unsigned port; /* config.port + pno */
56 pid_t pid; /* PID of the spawned process (0 if not spawned locally) */
59 size_t load; /* number of requests waiting on this process */
61 time_t last_used; /* see idle_timeout */
62 size_t requests; /* see max_requests */
63 struct scgi_proc *prev, *next; /* see first */
65 time_t disable_ts; /* replace by host->something */
67 int is_local;
69 enum { PROC_STATE_UNSET, /* init-phase */
70 PROC_STATE_RUNNING, /* alive */
71 PROC_STATE_DIED_WAIT_FOR_PID,
72 PROC_STATE_KILLED, /* was killed as we don't have the load anymore */
73 PROC_STATE_DIED, /* marked as dead, should be restarted */
74 PROC_STATE_DISABLED /* proc disabled as it resulted in an error */
75 } state;
76 } scgi_proc;
78 typedef struct {
79 /* list of processes handling this extension
80 * sorted by lowest load
82 * whenever a job is done move it up in the list
83 * until it is sorted, move it down as soon as the
84 * job is started
86 scgi_proc *first;
87 scgi_proc *unused_procs;
90 * spawn at least min_procs, at max_procs.
92 * as soon as the load of the first entry
93 * is max_load_per_proc we spawn a new one
94 * and add it to the first entry and give it
95 * the load
99 unsigned short min_procs;
100 unsigned short max_procs;
101 size_t num_procs; /* how many procs are started */
102 size_t active_procs; /* how many of them are really running */
104 unsigned short max_load_per_proc;
107 * kick the process from the list if it was not
108 * used for idle_timeout until min_procs is
109 * reached. this helps to get the processlist
110 * small again we had a small peak load.
114 unsigned short idle_timeout;
117 * time after a disabled remote connection is tried to be re-enabled
122 unsigned short disable_time;
125 * same scgi processes get a little bit larger
126 * than wanted. max_requests_per_proc kills a
127 * process after a number of handled requests.
130 size_t max_requests_per_proc;
133 /* config */
136 * host:port
138 * if host is one of the local IP adresses the
139 * whole connection is local
141 * if tcp/ip should be used host AND port have
142 * to be specified
145 buffer *host;
146 unsigned short port;
147 sa_family_t family;
150 * Unix Domain Socket
152 * instead of TCP/IP we can use Unix Domain Sockets
153 * - more secure (you have fileperms to play with)
154 * - more control (on locally)
155 * - more speed (no extra overhead)
157 buffer *unixsocket;
159 /* if socket is local we can start the scgi
160 * process ourself
162 * bin-path is the path to the binary
164 * check min_procs and max_procs for the number
165 * of process to start-up
167 buffer *bin_path;
169 /* bin-path is set bin-environment is taken to
170 * create the environement before starting the
171 * FastCGI process
174 array *bin_env;
176 array *bin_env_copy;
179 * docroot-translation between URL->phys and the
180 * remote host
182 * reasons:
183 * - different dir-layout if remote
184 * - chroot if local
187 buffer *docroot;
190 * check_local tell you if the phys file is stat()ed
191 * or not. FastCGI doesn't care if the service is
192 * remote. If the web-server side doesn't contain
193 * the scgi-files we should not stat() for them
194 * and say '404 not found'.
196 unsigned short check_local;
199 * append PATH_INFO to SCRIPT_FILENAME
201 * php needs this if cgi.fix_pathinfo is provied
206 * workaround for program when prefix="/"
208 * rule to build PATH_INFO is hardcoded for when check_local is disabled
209 * enable this option to use the workaround
213 unsigned short fix_root_path_name;
216 * If the backend includes X-Sendfile in the response
217 * we use the value as filename and ignore the content.
220 unsigned short xsendfile_allow;
221 array *xsendfile_docroot;
223 ssize_t load; /* replace by host->load */
225 size_t max_id; /* corresponds most of the time to
226 num_procs.
228 only if a process is killed max_id waits for the process itself
229 to die and decrements its afterwards */
231 int listen_backlog;
232 int refcount;
233 } scgi_extension_host;
236 * one extension can have multiple hosts assigned
237 * one host can spawn additional processes on the same
238 * socket (if we control it)
240 * ext -> host -> procs
241 * 1:n 1:n
243 * if the scgi process is remote that whole goes down
244 * to
246 * ext -> host -> procs
247 * 1:n 1:1
249 * in case of PHP and FCGI_CHILDREN we have again a procs
250 * but we don't control it directly.
254 typedef struct {
255 buffer *key; /* like .php */
257 int note_is_sent;
258 scgi_extension_host **hosts;
260 size_t used;
261 size_t size;
262 } scgi_extension;
264 typedef struct {
265 scgi_extension **exts;
267 size_t used;
268 size_t size;
269 } scgi_exts;
272 typedef struct {
273 scgi_exts *exts;
275 int debug;
276 } plugin_config;
278 typedef struct {
279 char **ptr;
281 size_t size;
282 size_t used;
283 } char_array;
285 /* generic plugin data, shared between all connections */
286 typedef struct {
287 PLUGIN_DATA;
289 buffer *scgi_env;
291 buffer *path;
292 buffer *parse_response;
294 plugin_config **config_storage;
296 plugin_config conf; /* this is only used as long as no handler_ctx is setup */
297 } plugin_data;
299 /* connection specific data */
300 typedef enum { FCGI_STATE_INIT, FCGI_STATE_CONNECT, FCGI_STATE_PREPARE_WRITE,
301 FCGI_STATE_WRITE, FCGI_STATE_READ
302 } scgi_connection_state_t;
304 typedef struct {
305 buffer *response;
307 scgi_proc *proc;
308 scgi_extension_host *host;
310 scgi_connection_state_t state;
311 time_t state_timestamp;
313 chunkqueue *wb;
314 off_t wb_reqlen;
316 buffer *response_header;
318 int fd; /* fd to the scgi process */
319 int fde_ndx; /* index into the fd-event buffer */
321 pid_t pid;
322 int got_proc;
323 int reconnects; /* number of reconnect attempts */
325 plugin_config conf;
327 connection *remote_conn; /* dumb pointer */
328 plugin_data *plugin_data; /* dumb pointer */
329 } handler_ctx;
332 /* ok, we need a prototype */
333 static handler_t scgi_handle_fdevent(server *srv, void *ctx, int revents);
335 int scgi_proclist_sort_down(server *srv, scgi_extension_host *host, scgi_proc *proc);
337 static void reset_signals(void) {
338 #ifdef SIGTTOU
339 signal(SIGTTOU, SIG_DFL);
340 #endif
341 #ifdef SIGTTIN
342 signal(SIGTTIN, SIG_DFL);
343 #endif
344 #ifdef SIGTSTP
345 signal(SIGTSTP, SIG_DFL);
346 #endif
347 signal(SIGHUP, SIG_DFL);
348 signal(SIGPIPE, SIG_DFL);
349 signal(SIGUSR1, SIG_DFL);
352 static handler_ctx * handler_ctx_init(void) {
353 handler_ctx * hctx;
355 hctx = calloc(1, sizeof(*hctx));
356 force_assert(hctx);
358 hctx->fde_ndx = -1;
360 hctx->response = buffer_init();
361 hctx->response_header = buffer_init();
363 hctx->state = FCGI_STATE_INIT;
364 hctx->proc = NULL;
366 hctx->fd = -1;
368 hctx->reconnects = 0;
370 hctx->wb = chunkqueue_init();
371 hctx->wb_reqlen = 0;
373 return hctx;
376 static void handler_ctx_free(handler_ctx *hctx) {
377 buffer_free(hctx->response);
378 buffer_free(hctx->response_header);
380 chunkqueue_free(hctx->wb);
382 free(hctx);
385 static scgi_proc *scgi_process_init(void) {
386 scgi_proc *f;
388 f = calloc(1, sizeof(*f));
389 force_assert(f);
390 f->socket = buffer_init();
392 f->prev = NULL;
393 f->next = NULL;
395 return f;
398 static void scgi_process_free(scgi_proc *f) {
399 if (!f) return;
401 scgi_process_free(f->next);
403 buffer_free(f->socket);
405 free(f);
408 static scgi_extension_host *scgi_host_init(void) {
409 scgi_extension_host *f;
411 f = calloc(1, sizeof(*f));
413 f->host = buffer_init();
414 f->unixsocket = buffer_init();
415 f->docroot = buffer_init();
416 f->bin_path = buffer_init();
417 f->bin_env = array_init();
418 f->bin_env_copy = array_init();
419 f->xsendfile_docroot = array_init();
421 return f;
424 static void scgi_host_free(scgi_extension_host *h) {
425 if (!h) return;
426 if (h->refcount) {
427 --h->refcount;
428 return;
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 array_free(h->xsendfile_docroot);
439 scgi_process_free(h->first);
440 scgi_process_free(h->unused_procs);
442 free(h);
446 static scgi_exts *scgi_extensions_init(void) {
447 scgi_exts *f;
449 f = calloc(1, sizeof(*f));
450 force_assert(f);
452 return f;
455 static void scgi_extensions_free(scgi_exts *f) {
456 size_t i;
458 if (!f) return;
460 for (i = 0; i < f->used; i++) {
461 scgi_extension *fe;
462 size_t j;
464 fe = f->exts[i];
466 for (j = 0; j < fe->used; j++) {
467 scgi_extension_host *h;
469 h = fe->hosts[j];
471 scgi_host_free(h);
474 buffer_free(fe->key);
475 free(fe->hosts);
477 free(fe);
480 free(f->exts);
482 free(f);
485 static int scgi_extension_insert(scgi_exts *ext, buffer *key, scgi_extension_host *fh) {
486 scgi_extension *fe;
487 size_t i;
489 /* there is something */
491 for (i = 0; i < ext->used; i++) {
492 if (buffer_is_equal(key, ext->exts[i]->key)) {
493 break;
497 if (i == ext->used) {
498 /* filextension is new */
499 fe = calloc(1, sizeof(*fe));
500 force_assert(fe);
501 fe->key = buffer_init();
502 buffer_copy_buffer(fe->key, key);
504 /* */
506 if (ext->size == 0) {
507 ext->size = 8;
508 ext->exts = malloc(ext->size * sizeof(*(ext->exts)));
509 force_assert(ext->exts);
510 } else if (ext->used == ext->size) {
511 ext->size += 8;
512 ext->exts = realloc(ext->exts, ext->size * sizeof(*(ext->exts)));
513 force_assert(ext->exts);
515 ext->exts[ext->used++] = fe;
516 } else {
517 fe = ext->exts[i];
520 if (fe->size == 0) {
521 fe->size = 4;
522 fe->hosts = malloc(fe->size * sizeof(*(fe->hosts)));
523 force_assert(fe->hosts);
524 } else if (fe->size == fe->used) {
525 fe->size += 4;
526 fe->hosts = realloc(fe->hosts, fe->size * sizeof(*(fe->hosts)));
527 force_assert(fe->hosts);
530 fe->hosts[fe->used++] = fh;
532 return 0;
536 INIT_FUNC(mod_scgi_init) {
537 plugin_data *p;
539 p = calloc(1, sizeof(*p));
540 force_assert(p);
542 p->scgi_env = buffer_init();
544 p->path = buffer_init();
545 p->parse_response = buffer_init();
547 return p;
551 FREE_FUNC(mod_scgi_free) {
552 plugin_data *p = p_d;
554 UNUSED(srv);
556 buffer_free(p->scgi_env);
557 buffer_free(p->path);
558 buffer_free(p->parse_response);
560 if (p->config_storage) {
561 size_t i, j, n;
562 for (i = 0; i < srv->config_context->used; i++) {
563 plugin_config *s = p->config_storage[i];
564 scgi_exts *exts;
566 if (NULL == s) continue;
568 exts = s->exts;
570 for (j = 0; j < exts->used; j++) {
571 scgi_extension *ex;
573 ex = exts->exts[j];
575 for (n = 0; n < ex->used; n++) {
576 scgi_proc *proc;
577 scgi_extension_host *host;
579 host = ex->hosts[n];
581 for (proc = host->first; proc; proc = proc->next) {
582 if (proc->pid != 0) kill(proc->pid, SIGTERM);
584 if (proc->is_local &&
585 !buffer_string_is_empty(proc->socket)) {
586 unlink(proc->socket->ptr);
590 for (proc = host->unused_procs; proc; proc = proc->next) {
591 if (proc->pid != 0) kill(proc->pid, SIGTERM);
593 if (proc->is_local &&
594 !buffer_string_is_empty(proc->socket)) {
595 unlink(proc->socket->ptr);
601 scgi_extensions_free(s->exts);
603 free(s);
605 free(p->config_storage);
608 free(p);
610 return HANDLER_GO_ON;
613 static int env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) {
614 char *dst;
615 size_t i;
617 if (!key || !val) return -1;
619 dst = malloc(key_len + val_len + 3);
620 force_assert(dst);
621 memcpy(dst, key, key_len);
622 dst[key_len] = '=';
623 /* add the \0 from the value */
624 memcpy(dst + key_len + 1, val, val_len + 1);
626 for (i = 0; i < env->used; i++) {
627 if (0 == strncmp(dst, env->ptr[i], key_len + 1)) {
628 /* don't care about free as we are in a forked child which is going to exec(...) */
629 /* free(env->ptr[i]); */
630 env->ptr[i] = dst;
631 return 0;
635 if (env->size == 0) {
636 env->size = 16;
637 env->ptr = malloc(env->size * sizeof(*env->ptr));
638 force_assert(env->ptr);
639 } else if (env->size == env->used) {
640 env->size += 16;
641 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
642 force_assert(env->ptr);
645 env->ptr[env->used++] = dst;
647 return 0;
650 #if !defined(HAVE_FORK)
651 static int scgi_spawn_connection(server *srv,
652 plugin_data *p,
653 scgi_extension_host *host,
654 scgi_proc *proc) {
655 UNUSED(srv);
656 UNUSED(p);
657 UNUSED(host);
658 UNUSED(proc);
659 return -1;
662 #else /* -> defined(HAVE_FORK) */
664 static int scgi_spawn_connection(server *srv,
665 plugin_data *p,
666 scgi_extension_host *host,
667 scgi_proc *proc) {
668 int scgi_fd;
669 int status;
670 struct timeval tv = { 0, 100 * 1000 };
671 #ifdef HAVE_SYS_UN_H
672 struct sockaddr_un scgi_addr_un;
673 #endif
674 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
675 struct sockaddr_in6 scgi_addr_in6;
676 #endif
677 struct sockaddr_in scgi_addr_in;
678 struct sockaddr *scgi_addr;
680 socklen_t servlen;
682 if (p->conf.debug) {
683 log_error_write(srv, __FILE__, __LINE__, "sdb",
684 "new proc, socket:", proc->port, proc->socket);
688 if (!buffer_string_is_empty(proc->socket)) {
689 #ifdef HAVE_SYS_UN_H
690 memset(&scgi_addr_un, 0, sizeof(scgi_addr_un));
691 scgi_addr_un.sun_family = AF_UNIX;
692 if (buffer_string_length(proc->socket) + 1 > sizeof(scgi_addr_un.sun_path)) {
693 log_error_write(srv, __FILE__, __LINE__, "sB",
694 "ERROR: Unix Domain socket filename too long:",
695 proc->socket);
696 return -1;
698 memcpy(scgi_addr_un.sun_path, proc->socket->ptr, buffer_string_length(proc->socket) + 1);
700 #ifdef SUN_LEN
701 servlen = SUN_LEN(&scgi_addr_un);
702 #else
703 /* stevens says: */
704 servlen = buffer_string_length(proc->socket) + 1 + sizeof(scgi_addr_un.sun_family);
705 #endif
706 scgi_addr = (struct sockaddr *) &scgi_addr_un;
707 #else
708 log_error_write(srv, __FILE__, __LINE__, "s",
709 "ERROR: Unix Domain sockets are not supported.");
710 return -1;
711 #endif
712 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
713 } else if (host->family == AF_INET6 && !buffer_string_is_empty(host->host)) {
714 memset(&scgi_addr_in6, 0, sizeof(scgi_addr_in6));
715 scgi_addr_in6.sin6_family = AF_INET6;
716 inet_pton(AF_INET6, host->host->ptr, (char *) &scgi_addr_in6.sin6_addr);
717 scgi_addr_in6.sin6_port = htons(proc->port);
718 servlen = sizeof(scgi_addr_in6);
719 scgi_addr = (struct sockaddr *) &scgi_addr_in6;
720 #endif
721 } else {
722 memset(&scgi_addr_in, 0, sizeof(scgi_addr_in));
723 scgi_addr_in.sin_family = AF_INET;
725 if (buffer_string_is_empty(host->host)) {
726 scgi_addr_in.sin_addr.s_addr = htonl(INADDR_ANY);
727 } else {
728 struct hostent *he;
730 /* set a usefull default */
731 scgi_addr_in.sin_addr.s_addr = htonl(INADDR_ANY);
734 if (NULL == (he = gethostbyname(host->host->ptr))) {
735 log_error_write(srv, __FILE__, __LINE__,
736 "sdb", "gethostbyname failed: ",
737 h_errno, host->host);
738 return -1;
741 if (he->h_addrtype != AF_INET) {
742 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-type != AF_INET: ", he->h_addrtype);
743 return -1;
746 if (he->h_length != sizeof(struct in_addr)) {
747 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-length != sizeof(in_addr): ", he->h_length);
748 return -1;
751 memcpy(&(scgi_addr_in.sin_addr.s_addr), he->h_addr_list[0], he->h_length);
754 scgi_addr_in.sin_port = htons(proc->port);
755 servlen = sizeof(scgi_addr_in);
757 scgi_addr = (struct sockaddr *) &scgi_addr_in;
760 if (-1 == (scgi_fd = socket(scgi_addr->sa_family, SOCK_STREAM, 0))) {
761 log_error_write(srv, __FILE__, __LINE__, "ss",
762 "failed:", strerror(errno));
763 return -1;
766 if (-1 == connect(scgi_fd, scgi_addr, servlen)) {
767 /* server is not up, spawn in */
768 pid_t child;
769 int val;
771 if (!buffer_string_is_empty(proc->socket)) {
772 unlink(proc->socket->ptr);
775 close(scgi_fd);
777 /* reopen socket */
778 if (-1 == (scgi_fd = socket(scgi_addr->sa_family, SOCK_STREAM, 0))) {
779 log_error_write(srv, __FILE__, __LINE__, "ss",
780 "socket failed:", strerror(errno));
781 return -1;
784 val = 1;
785 if (setsockopt(scgi_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) {
786 log_error_write(srv, __FILE__, __LINE__, "ss",
787 "socketsockopt failed:", strerror(errno));
788 close(scgi_fd);
789 return -1;
792 /* create socket */
793 if (-1 == bind(scgi_fd, scgi_addr, servlen)) {
794 log_error_write(srv, __FILE__, __LINE__, "sbds",
795 "bind failed for:",
796 proc->socket,
797 proc->port,
798 strerror(errno));
799 close(scgi_fd);
800 return -1;
803 if (-1 == listen(scgi_fd, host->listen_backlog)) {
804 log_error_write(srv, __FILE__, __LINE__, "ss",
805 "listen failed:", strerror(errno));
806 close(scgi_fd);
807 return -1;
810 switch ((child = fork())) {
811 case 0: {
812 buffer *b;
813 size_t i = 0;
814 int fd = 0;
815 char_array env;
818 /* create environment */
819 env.ptr = NULL;
820 env.size = 0;
821 env.used = 0;
823 if (scgi_fd != 0) {
824 dup2(scgi_fd, 0);
825 close(scgi_fd);
828 /* we don't need the client socket */
829 for (fd = 3; fd < 256; fd++) {
830 close(fd);
833 /* build clean environment */
834 if (host->bin_env_copy->used) {
835 for (i = 0; i < host->bin_env_copy->used; i++) {
836 data_string *ds = (data_string *)host->bin_env_copy->data[i];
837 char *ge;
839 if (NULL != (ge = getenv(ds->value->ptr))) {
840 env_add(&env, CONST_BUF_LEN(ds->value), ge, strlen(ge));
843 } else {
844 char ** const e = environ;
845 for (i = 0; e[i]; ++i) {
846 char *eq;
848 if (NULL != (eq = strchr(e[i], '='))) {
849 env_add(&env, e[i], eq - e[i], eq+1, strlen(eq+1));
854 /* create environment */
855 for (i = 0; i < host->bin_env->used; i++) {
856 data_string *ds = (data_string *)host->bin_env->data[i];
858 env_add(&env, CONST_BUF_LEN(ds->key), CONST_BUF_LEN(ds->value));
861 for (i = 0; i < env.used; i++) {
862 /* search for PHP_FCGI_CHILDREN */
863 if (0 == strncmp(env.ptr[i], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
866 /* not found, add a default */
867 if (i == env.used) {
868 env_add(&env, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
871 env.ptr[env.used] = NULL;
873 b = buffer_init();
874 buffer_copy_string_len(b, CONST_STR_LEN("exec "));
875 buffer_append_string_buffer(b, host->bin_path);
877 reset_signals();
879 /* exec the cgi */
880 execle("/bin/sh", "sh", "-c", b->ptr, (char *)NULL, env.ptr);
882 log_error_write(srv, __FILE__, __LINE__, "sbs",
883 "execl failed for:", host->bin_path, strerror(errno));
885 _exit(errno);
887 break;
889 case -1:
890 /* error */
891 close(scgi_fd);
892 break;
893 default:
894 /* father */
895 close(scgi_fd);
897 /* wait */
898 select(0, NULL, NULL, NULL, &tv);
900 switch (waitpid(child, &status, WNOHANG)) {
901 case 0:
902 /* child still running after timeout, good */
903 break;
904 case -1:
905 /* no PID found ? should never happen */
906 log_error_write(srv, __FILE__, __LINE__, "ss",
907 "pid not found:", strerror(errno));
908 return -1;
909 default:
910 /* the child should not terminate at all */
911 if (WIFEXITED(status)) {
912 log_error_write(srv, __FILE__, __LINE__, "sd",
913 "child exited (is this a SCGI binary ?):",
914 WEXITSTATUS(status));
915 } else if (WIFSIGNALED(status)) {
916 log_error_write(srv, __FILE__, __LINE__, "sd",
917 "child signaled:",
918 WTERMSIG(status));
919 } else {
920 log_error_write(srv, __FILE__, __LINE__, "sd",
921 "child died somehow:",
922 status);
924 return -1;
927 /* register process */
928 proc->pid = child;
929 proc->last_used = srv->cur_ts;
930 proc->is_local = 1;
932 break;
934 } else {
935 close(scgi_fd);
937 proc->is_local = 0;
938 proc->pid = 0;
940 if (p->conf.debug) {
941 log_error_write(srv, __FILE__, __LINE__, "sb",
942 "(debug) socket is already used, won't spawn:",
943 proc->socket);
947 proc->state = PROC_STATE_RUNNING;
948 host->active_procs++;
950 return 0;
953 #endif /* HAVE_FORK */
955 static scgi_extension_host * unixsocket_is_dup(plugin_data *p, size_t used, buffer *unixsocket) {
956 size_t i, j, n;
957 for (i = 0; i < used; ++i) {
958 scgi_exts *exts = p->config_storage[i]->exts;
959 for (j = 0; j < exts->used; ++j) {
960 scgi_extension *ex = exts->exts[j];
961 for (n = 0; n < ex->used; ++n) {
962 scgi_extension_host *host = ex->hosts[n];
963 if (!buffer_string_is_empty(host->unixsocket)
964 && buffer_is_equal(host->unixsocket, unixsocket)
965 && !buffer_string_is_empty(host->bin_path))
966 return host;
971 return NULL;
974 SETDEFAULTS_FUNC(mod_scgi_set_defaults) {
975 plugin_data *p = p_d;
976 data_unset *du;
977 size_t i = 0;
978 scgi_extension_host *df = NULL;
980 config_values_t cv[] = {
981 { "scgi.server", NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
982 { "scgi.debug", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
983 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
986 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
987 force_assert(p->config_storage);
989 for (i = 0; i < srv->config_context->used; i++) {
990 data_config const* config = (data_config const*)srv->config_context->data[i];
991 plugin_config *s;
993 s = malloc(sizeof(plugin_config));
994 force_assert(s);
995 s->exts = scgi_extensions_init();
996 s->debug = 0;
998 cv[0].destination = s->exts;
999 cv[1].destination = &(s->debug);
1001 p->config_storage[i] = s;
1003 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
1004 goto error;
1008 * <key> = ( ... )
1011 if (NULL != (du = array_get_element(config->value, "scgi.server"))) {
1012 size_t j;
1013 data_array *da = (data_array *)du;
1015 if (du->type != TYPE_ARRAY) {
1016 log_error_write(srv, __FILE__, __LINE__, "sss",
1017 "unexpected type for key: ", "scgi.server", "expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1019 goto error;
1024 * scgi.server = ( "<ext>" => ( ... ),
1025 * "<ext>" => ( ... ) )
1028 for (j = 0; j < da->value->used; j++) {
1029 size_t n;
1030 data_array *da_ext = (data_array *)da->value->data[j];
1032 if (da->value->data[j]->type != TYPE_ARRAY) {
1033 log_error_write(srv, __FILE__, __LINE__, "sssbs",
1034 "unexpected type for key: ", "scgi.server",
1035 "[", da->value->data[j]->key, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1037 goto error;
1041 * da_ext->key == name of the extension
1045 * scgi.server = ( "<ext>" =>
1046 * ( "<host>" => ( ... ),
1047 * "<host>" => ( ... )
1048 * ),
1049 * "<ext>" => ... )
1052 for (n = 0; n < da_ext->value->used; n++) {
1053 data_array *da_host = (data_array *)da_ext->value->data[n];
1055 config_values_t fcv[] = {
1056 { "host", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1057 { "docroot", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1058 { "socket", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1059 { "bin-path", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
1061 { "check-local", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
1062 { "port", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 5 */
1063 { "min-procs-not-working", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 7 this is broken for now */
1064 { "max-procs", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
1065 { "max-load-per-proc", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
1066 { "idle-timeout", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 9 */
1067 { "disable-time", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 10 */
1069 { "bin-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 11 */
1070 { "bin-copy-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
1071 { "fix-root-scriptname", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 13 */
1072 { "listen-backlog", NULL, T_CONFIG_INT, T_CONFIG_SCOPE_CONNECTION }, /* 14 */
1073 { "x-sendfile", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 15 */
1074 { "x-sendfile-docroot",NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 16 */
1077 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1080 if (da_host->type != TYPE_ARRAY) {
1081 log_error_write(srv, __FILE__, __LINE__, "ssSBS",
1082 "unexpected type for key:",
1083 "scgi.server",
1084 "[", da_host->key, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1086 goto error;
1089 df = scgi_host_init();
1091 df->check_local = 1;
1092 df->min_procs = 4;
1093 df->max_procs = 4;
1094 df->max_load_per_proc = 1;
1095 df->idle_timeout = 60;
1096 df->disable_time = 60;
1097 df->fix_root_path_name = 0;
1098 df->listen_backlog = 1024;
1099 df->xsendfile_allow = 0;
1100 df->refcount = 0;
1102 fcv[0].destination = df->host;
1103 fcv[1].destination = df->docroot;
1104 fcv[2].destination = df->unixsocket;
1105 fcv[3].destination = df->bin_path;
1107 fcv[4].destination = &(df->check_local);
1108 fcv[5].destination = &(df->port);
1109 fcv[6].destination = &(df->min_procs);
1110 fcv[7].destination = &(df->max_procs);
1111 fcv[8].destination = &(df->max_load_per_proc);
1112 fcv[9].destination = &(df->idle_timeout);
1113 fcv[10].destination = &(df->disable_time);
1115 fcv[11].destination = df->bin_env;
1116 fcv[12].destination = df->bin_env_copy;
1117 fcv[13].destination = &(df->fix_root_path_name);
1118 fcv[14].destination = &(df->listen_backlog);
1119 fcv[15].destination = &(df->xsendfile_allow);
1120 fcv[16].destination = df->xsendfile_docroot;
1123 if (0 != config_insert_values_internal(srv, da_host->value, fcv, T_CONFIG_SCOPE_CONNECTION)) {
1124 goto error;
1127 if ((!buffer_string_is_empty(df->host) || df->port) &&
1128 !buffer_string_is_empty(df->unixsocket)) {
1129 log_error_write(srv, __FILE__, __LINE__, "s",
1130 "either host+port or socket");
1132 goto error;
1135 if (!buffer_string_is_empty(df->unixsocket)) {
1136 /* unix domain socket */
1137 struct sockaddr_un un;
1139 if (buffer_string_length(df->unixsocket) + 1 > sizeof(un.sun_path) - 2) {
1140 log_error_write(srv, __FILE__, __LINE__, "s",
1141 "path of the unixdomain socket is too large");
1142 goto error;
1145 if (!buffer_string_is_empty(df->bin_path)) {
1146 scgi_extension_host *duplicate = unixsocket_is_dup(p, i+1, df->unixsocket);
1147 if (NULL != duplicate) {
1148 if (!buffer_is_equal(df->bin_path, duplicate->bin_path)) {
1149 log_error_write(srv, __FILE__, __LINE__, "sb",
1150 "duplicate unixsocket path:",
1151 df->unixsocket);
1152 goto error;
1154 scgi_host_free(df);
1155 df = duplicate;
1156 ++df->refcount;
1160 df->family = AF_UNIX;
1161 } else {
1162 /* tcp/ip */
1164 if (buffer_string_is_empty(df->host) &&
1165 buffer_string_is_empty(df->bin_path)) {
1166 log_error_write(srv, __FILE__, __LINE__, "sbbbs",
1167 "missing key (string):",
1168 da->key,
1169 da_ext->key,
1170 da_host->key,
1171 "host");
1173 goto error;
1174 } else if (df->port == 0) {
1175 log_error_write(srv, __FILE__, __LINE__, "sbbbs",
1176 "missing key (short):",
1177 da->key,
1178 da_ext->key,
1179 da_host->key,
1180 "port");
1181 goto error;
1184 df->family = (!buffer_string_is_empty(df->host) && NULL != strchr(df->host->ptr, ':')) ? AF_INET6 : AF_INET;
1187 if (df->refcount) {
1188 /* already init'd; skip spawning */
1189 } else if (!buffer_string_is_empty(df->bin_path)) {
1190 /* a local socket + self spawning */
1191 size_t pno;
1193 /* HACK: just to make sure the adaptive spawing is disabled */
1194 df->min_procs = df->max_procs;
1196 if (df->min_procs > df->max_procs) df->max_procs = df->min_procs;
1197 if (df->max_load_per_proc < 1) df->max_load_per_proc = 0;
1199 if (s->debug) {
1200 log_error_write(srv, __FILE__, __LINE__, "ssbsdsbsdsd",
1201 "--- scgi spawning local",
1202 "\n\tproc:", df->bin_path,
1203 "\n\tport:", df->port,
1204 "\n\tsocket", df->unixsocket,
1205 "\n\tmin-procs:", df->min_procs,
1206 "\n\tmax-procs:", df->max_procs);
1209 for (pno = 0; pno < df->min_procs; pno++) {
1210 scgi_proc *proc;
1212 proc = scgi_process_init();
1213 proc->id = df->num_procs++;
1214 df->max_id++;
1216 if (buffer_string_is_empty(df->unixsocket)) {
1217 proc->port = df->port + pno;
1218 } else {
1219 buffer_copy_buffer(proc->socket, df->unixsocket);
1220 buffer_append_string_len(proc->socket, CONST_STR_LEN("-"));
1221 buffer_append_int(proc->socket, pno);
1224 if (s->debug) {
1225 log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
1226 "--- scgi spawning",
1227 "\n\tport:", df->port,
1228 "\n\tsocket", df->unixsocket,
1229 "\n\tcurrent:", pno, "/", df->min_procs);
1232 if (!srv->srvconf.preflight_check
1233 && scgi_spawn_connection(srv, p, df, proc)) {
1234 log_error_write(srv, __FILE__, __LINE__, "s",
1235 "[ERROR]: spawning fcgi failed.");
1236 scgi_process_free(proc);
1237 goto error;
1240 proc->next = df->first;
1241 if (df->first) df->first->prev = proc;
1243 df->first = proc;
1245 } else {
1246 scgi_proc *fp;
1248 fp = scgi_process_init();
1249 fp->id = df->num_procs++;
1250 df->max_id++;
1251 df->active_procs++;
1252 fp->state = PROC_STATE_RUNNING;
1254 if (buffer_string_is_empty(df->unixsocket)) {
1255 fp->port = df->port;
1256 } else {
1257 buffer_copy_buffer(fp->socket, df->unixsocket);
1260 df->first = fp;
1262 df->min_procs = 1;
1263 df->max_procs = 1;
1266 if (df->xsendfile_docroot->used) {
1267 size_t k;
1268 for (k = 0; k < df->xsendfile_docroot->used; ++k) {
1269 data_string *ds = (data_string *)df->xsendfile_docroot->data[k];
1270 if (ds->type != TYPE_STRING) {
1271 log_error_write(srv, __FILE__, __LINE__, "s",
1272 "unexpected type for x-sendfile-docroot; expected: \"x-sendfile-docroot\" => ( \"/allowed/path\", ... )");
1273 goto error;
1275 if (ds->value->ptr[0] != '/') {
1276 log_error_write(srv, __FILE__, __LINE__, "SBs",
1277 "x-sendfile-docroot paths must begin with '/'; invalid: \"", ds->value, "\"");
1278 goto error;
1280 buffer_path_simplify(ds->value, ds->value);
1281 buffer_append_slash(ds->value);
1285 /* if extension already exists, take it */
1286 scgi_extension_insert(s->exts, da_ext->key, df);
1287 df = NULL;
1293 return HANDLER_GO_ON;
1295 error:
1296 if (NULL != df) scgi_host_free(df);
1297 return HANDLER_ERROR;
1300 static int scgi_set_state(server *srv, handler_ctx *hctx, scgi_connection_state_t state) {
1301 hctx->state = state;
1302 hctx->state_timestamp = srv->cur_ts;
1304 return 0;
1308 static void scgi_connection_close(server *srv, handler_ctx *hctx) {
1309 plugin_data *p;
1310 connection *con;
1312 p = hctx->plugin_data;
1313 con = hctx->remote_conn;
1315 if (hctx->fd != -1) {
1316 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1317 fdevent_unregister(srv->ev, hctx->fd);
1318 close(hctx->fd);
1319 srv->cur_fds--;
1322 if (hctx->host && hctx->proc) {
1323 hctx->host->load--;
1325 if (hctx->got_proc) {
1326 /* after the connect the process gets a load */
1327 hctx->proc->load--;
1329 if (p->conf.debug) {
1330 log_error_write(srv, __FILE__, __LINE__, "sddb",
1331 "release proc:",
1332 hctx->fd,
1333 hctx->proc->pid, hctx->proc->socket);
1337 scgi_proclist_sort_down(srv, hctx->host, hctx->proc);
1341 handler_ctx_free(hctx);
1342 con->plugin_ctx[p->id] = NULL;
1344 /* finish response (if not already con->file_started, con->file_finished) */
1345 if (con->mode == p->id) {
1346 http_response_backend_done(srv, con);
1350 static int scgi_reconnect(server *srv, handler_ctx *hctx) {
1351 plugin_data *p = hctx->plugin_data;
1353 /* child died
1355 * 1.
1357 * connect was ok, connection was accepted
1358 * but the php accept loop checks after the accept if it should die or not.
1360 * if yes we can only detect it at a write()
1362 * next step is resetting this attemp and setup a connection again
1364 * if we have more then 5 reconnects for the same request, die
1366 * 2.
1368 * we have a connection but the child died by some other reason
1372 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1373 fdevent_unregister(srv->ev, hctx->fd);
1374 close(hctx->fd);
1375 srv->cur_fds--;
1377 scgi_set_state(srv, hctx, FCGI_STATE_INIT);
1379 hctx->reconnects++;
1381 if (p->conf.debug) {
1382 log_error_write(srv, __FILE__, __LINE__, "sddb",
1383 "release proc:",
1384 hctx->fd,
1385 hctx->proc->pid, hctx->proc->socket);
1388 hctx->proc->load--;
1389 scgi_proclist_sort_down(srv, hctx->host, hctx->proc);
1391 return 0;
1395 static handler_t scgi_connection_reset(server *srv, connection *con, void *p_d) {
1396 plugin_data *p = p_d;
1397 handler_ctx *hctx = con->plugin_ctx[p->id];
1398 if (hctx) scgi_connection_close(srv, hctx);
1400 return HANDLER_GO_ON;
1404 static int scgi_env_add(buffer *env, const char *key, size_t key_len, const char *val, size_t val_len) {
1405 size_t len;
1407 if (!key || !val) return -1;
1409 len = key_len + val_len + 2;
1411 buffer_string_prepare_append(env, len);
1413 buffer_append_string_len(env, key, key_len);
1414 buffer_append_string_len(env, "", 1);
1415 buffer_append_string_len(env, val, val_len);
1416 buffer_append_string_len(env, "", 1);
1418 return 0;
1424 * returns
1425 * -1 error
1426 * 0 connected
1427 * 1 not connected yet
1430 static int scgi_establish_connection(server *srv, handler_ctx *hctx) {
1431 struct sockaddr *scgi_addr;
1432 struct sockaddr_in scgi_addr_in;
1433 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1434 struct sockaddr_in6 scgi_addr_in6;
1435 #endif
1436 #ifdef HAVE_SYS_UN_H
1437 struct sockaddr_un scgi_addr_un;
1438 #endif
1439 socklen_t servlen;
1441 scgi_extension_host *host = hctx->host;
1442 scgi_proc *proc = hctx->proc;
1443 int scgi_fd = hctx->fd;
1445 if (!buffer_string_is_empty(proc->socket)) {
1446 #ifdef HAVE_SYS_UN_H
1447 /* use the unix domain socket */
1448 memset(&scgi_addr_un, 0, sizeof(scgi_addr_un));
1449 scgi_addr_un.sun_family = AF_UNIX;
1450 if (buffer_string_length(proc->socket) + 1 > sizeof(scgi_addr_un.sun_path)) {
1451 log_error_write(srv, __FILE__, __LINE__, "sB",
1452 "ERROR: Unix Domain socket filename too long:",
1453 proc->socket);
1454 return -1;
1456 memcpy(scgi_addr_un.sun_path, proc->socket->ptr, buffer_string_length(proc->socket) + 1);
1458 #ifdef SUN_LEN
1459 servlen = SUN_LEN(&scgi_addr_un);
1460 #else
1461 /* stevens says: */
1462 servlen = buffer_string_length(proc->socket) + 1 + sizeof(scgi_addr_un.sun_family);
1463 #endif
1464 scgi_addr = (struct sockaddr *) &scgi_addr_un;
1465 #else
1466 return -1;
1467 #endif
1468 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1469 } else if (host->family == AF_INET6 && !buffer_string_is_empty(host->host)) {
1470 memset(&scgi_addr_in6, 0, sizeof(scgi_addr_in6));
1471 scgi_addr_in6.sin6_family = AF_INET6;
1472 inet_pton(AF_INET6, host->host->ptr, (char *) &scgi_addr_in6.sin6_addr);
1473 scgi_addr_in6.sin6_port = htons(proc->port);
1474 servlen = sizeof(scgi_addr_in6);
1475 scgi_addr = (struct sockaddr *) &scgi_addr_in6;
1476 #endif
1477 } else {
1478 memset(&scgi_addr_in, 0, sizeof(scgi_addr_in));
1479 scgi_addr_in.sin_family = AF_INET;
1480 if (0 == inet_aton(host->host->ptr, &(scgi_addr_in.sin_addr))) {
1481 log_error_write(srv, __FILE__, __LINE__, "sbs",
1482 "converting IP-adress failed for", host->host,
1483 "\nBe sure to specify an IP address here");
1485 return -1;
1487 scgi_addr_in.sin_port = htons(proc->port);
1488 servlen = sizeof(scgi_addr_in);
1490 scgi_addr = (struct sockaddr *) &scgi_addr_in;
1493 if (-1 == connect(scgi_fd, scgi_addr, servlen)) {
1494 if (errno == EINPROGRESS ||
1495 errno == EALREADY ||
1496 errno == EINTR) {
1497 if (hctx->conf.debug) {
1498 log_error_write(srv, __FILE__, __LINE__, "sd",
1499 "connect delayed, will continue later:", scgi_fd);
1502 return 1;
1503 } else {
1504 log_error_write(srv, __FILE__, __LINE__, "sdsddb",
1505 "connect failed:", scgi_fd,
1506 strerror(errno), errno,
1507 proc->port, proc->socket);
1509 if (errno == EAGAIN) {
1510 /* this is Linux only */
1512 log_error_write(srv, __FILE__, __LINE__, "s",
1513 "If this happend on Linux: You have been run out of local ports. "
1514 "Check the manual, section Performance how to handle this.");
1517 return -1;
1520 if (hctx->conf.debug > 1) {
1521 log_error_write(srv, __FILE__, __LINE__, "sd",
1522 "connect succeeded: ", scgi_fd);
1527 return 0;
1530 static int scgi_env_add_request_headers(server *srv, connection *con, plugin_data *p) {
1531 size_t i;
1533 for (i = 0; i < con->request.headers->used; i++) {
1534 data_string *ds;
1536 ds = (data_string *)con->request.headers->data[i];
1538 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1539 buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 1);
1541 scgi_env_add(p->scgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value));
1545 for (i = 0; i < con->environment->used; i++) {
1546 data_string *ds;
1548 ds = (data_string *)con->environment->data[i];
1550 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1551 buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 0);
1553 scgi_env_add(p->scgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value));
1557 return 0;
1561 static int scgi_create_env(server *srv, handler_ctx *hctx) {
1562 char buf[LI_ITOSTRING_LENGTH];
1563 const char *s;
1564 #ifdef HAVE_IPV6
1565 char b2[INET6_ADDRSTRLEN + 1];
1566 #endif
1567 buffer *b;
1569 plugin_data *p = hctx->plugin_data;
1570 scgi_extension_host *host= hctx->host;
1572 connection *con = hctx->remote_conn;
1573 server_socket *srv_sock = con->srv_socket;
1575 sock_addr our_addr;
1576 socklen_t our_addr_len;
1578 buffer_string_prepare_copy(p->scgi_env, 1023);
1580 /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
1582 li_itostrn(buf, sizeof(buf), con->request.content_length);
1583 scgi_env_add(p->scgi_env, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf));
1584 scgi_env_add(p->scgi_env, CONST_STR_LEN("SCGI"), CONST_STR_LEN("1"));
1586 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con->conf.server_tag));
1588 if (!buffer_is_empty(con->server_name)) {
1589 size_t len = buffer_string_length(con->server_name);
1591 if (con->server_name->ptr[0] == '[') {
1592 const char *colon = strstr(con->server_name->ptr, "]:");
1593 if (colon) len = (colon + 1) - con->server_name->ptr;
1594 } else {
1595 const char *colon = strchr(con->server_name->ptr, ':');
1596 if (colon) len = colon - con->server_name->ptr;
1599 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_NAME"), con->server_name->ptr, len);
1600 } else {
1601 #ifdef HAVE_IPV6
1602 s = inet_ntop(srv_sock->addr.plain.sa_family,
1603 srv_sock->addr.plain.sa_family == AF_INET6 ?
1604 (const void *) &(srv_sock->addr.ipv6.sin6_addr) :
1605 (const void *) &(srv_sock->addr.ipv4.sin_addr),
1606 b2, sizeof(b2)-1);
1607 #else
1608 s = inet_ntoa(srv_sock->addr.ipv4.sin_addr);
1609 #endif
1610 force_assert(s);
1611 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_NAME"), s, strlen(s));
1614 scgi_env_add(p->scgi_env, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1"));
1616 li_utostrn(buf, sizeof(buf),
1617 #ifdef HAVE_IPV6
1618 ntohs(srv_sock->addr.plain.sa_family ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port)
1619 #else
1620 ntohs(srv_sock->addr.ipv4.sin_port)
1621 #endif
1624 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf));
1626 /* get the server-side of the connection to the client */
1627 our_addr_len = sizeof(our_addr);
1629 if (-1 == getsockname(con->fd, (struct sockaddr *)&our_addr, &our_addr_len)
1630 || our_addr_len > (socklen_t)sizeof(our_addr)) {
1631 s = inet_ntop_cache_get_ip(srv, &(srv_sock->addr));
1632 } else {
1633 s = inet_ntop_cache_get_ip(srv, &(our_addr));
1635 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s));
1637 li_utostrn(buf, sizeof(buf),
1638 #ifdef HAVE_IPV6
1639 ntohs(con->dst_addr.plain.sa_family ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port)
1640 #else
1641 ntohs(con->dst_addr.ipv4.sin_port)
1642 #endif
1645 scgi_env_add(p->scgi_env, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf));
1647 s = inet_ntop_cache_get_ip(srv, &(con->dst_addr));
1648 force_assert(s);
1649 scgi_env_add(p->scgi_env, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s));
1652 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1653 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1654 * (6.1.14, 6.1.6, 6.1.7)
1657 scgi_env_add(p->scgi_env, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path));
1659 if (!buffer_string_is_empty(con->request.pathinfo)) {
1660 scgi_env_add(p->scgi_env, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo));
1662 /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1664 if (!buffer_string_is_empty(host->docroot)) {
1665 buffer_copy_buffer(p->path, host->docroot);
1666 } else {
1667 buffer_copy_buffer(p->path, con->physical.basedir);
1669 buffer_append_string_buffer(p->path, con->request.pathinfo);
1670 scgi_env_add(p->scgi_env, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p->path));
1671 } else {
1672 scgi_env_add(p->scgi_env, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN(""));
1676 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1677 * http://www.php.net/manual/en/reserved.variables.php
1678 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1679 * TODO: this code should be checked against cgi.fix_pathinfo php
1680 * parameter.
1683 if (!buffer_string_is_empty(host->docroot)) {
1685 * rewrite SCRIPT_FILENAME
1689 buffer_copy_buffer(p->path, host->docroot);
1690 buffer_append_string_buffer(p->path, con->uri.path);
1692 scgi_env_add(p->scgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path));
1693 scgi_env_add(p->scgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host->docroot));
1694 } else {
1695 buffer_copy_buffer(p->path, con->physical.path);
1697 scgi_env_add(p->scgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path));
1698 scgi_env_add(p->scgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.basedir));
1700 if (con->error_handler_saved_status >= 0) {
1701 scgi_env_add(p->scgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.uri));
1702 } else {
1703 scgi_env_add(p->scgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri));
1705 if (!buffer_string_is_empty(con->uri.query)) {
1706 scgi_env_add(p->scgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query));
1707 } else {
1708 scgi_env_add(p->scgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN(""));
1711 s = get_http_method_name(con->request.http_method);
1712 force_assert(s);
1713 scgi_env_add(p->scgi_env, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s));
1714 /* set REDIRECT_STATUS for php compiled with --force-redirect
1715 * (if REDIRECT_STATUS has not already been set by error handler) */
1716 if (0 == con->error_handler_saved_status) {
1717 scgi_env_add(p->scgi_env, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200"));
1719 s = get_http_version_name(con->request.http_version);
1720 force_assert(s);
1721 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));
1723 #ifdef USE_OPENSSL
1724 if (buffer_is_equal_caseless_string(con->uri.scheme, CONST_STR_LEN("https"))) {
1725 scgi_env_add(p->scgi_env, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1727 #endif
1729 scgi_env_add_request_headers(srv, con, p);
1731 b = buffer_init();
1733 buffer_append_int(b, buffer_string_length(p->scgi_env));
1734 buffer_append_string_len(b, CONST_STR_LEN(":"));
1735 buffer_append_string_buffer(b, p->scgi_env);
1736 buffer_append_string_len(b, CONST_STR_LEN(","));
1738 hctx->wb_reqlen = buffer_string_length(b);
1739 chunkqueue_append_buffer(hctx->wb, b);
1740 buffer_free(b);
1742 if (con->request.content_length) {
1743 chunkqueue_append_chunkqueue(hctx->wb, con->request_content_queue);
1744 hctx->wb_reqlen += con->request.content_length;/* (eventual) total request size */
1747 return 0;
1750 static int scgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in, int eol) {
1751 char *ns;
1752 const char *s;
1753 int line = 0;
1755 UNUSED(srv);
1757 buffer_copy_buffer(p->parse_response, in);
1759 for (s = p->parse_response->ptr;
1760 NULL != (ns = (eol == EOL_RN ? strstr(s, "\r\n") : strchr(s, '\n')));
1761 s = ns + (eol == EOL_RN ? 2 : 1), line++) {
1762 const char *key, *value;
1763 int key_len;
1764 data_string *ds;
1766 ns[0] = '\0';
1768 if (line == 0 &&
1769 0 == strncmp(s, "HTTP/1.", 7)) {
1770 /* non-parsed header ... we parse them anyway */
1772 if ((s[7] == '1' ||
1773 s[7] == '0') &&
1774 s[8] == ' ') {
1775 int status;
1776 /* after the space should be a status code for us */
1778 status = strtol(s+9, NULL, 10);
1780 if (status >= 100 && status < 1000) {
1781 /* we expected 3 digits got them */
1782 con->parsed_response |= HTTP_STATUS;
1783 con->http_status = status;
1786 } else {
1788 key = s;
1789 if (NULL == (value = strchr(s, ':'))) {
1790 /* we expect: "<key>: <value>\r\n" */
1791 continue;
1794 key_len = value - key;
1795 value += 1;
1797 /* skip LWS */
1798 while (*value == ' ' || *value == '\t') value++;
1800 if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
1801 ds = data_response_init();
1803 buffer_copy_string_len(ds->key, key, key_len);
1804 buffer_copy_string(ds->value, value);
1806 array_insert_unique(con->response.headers, (data_unset *)ds);
1808 switch(key_len) {
1809 case 4:
1810 if (0 == strncasecmp(key, "Date", key_len)) {
1811 con->parsed_response |= HTTP_DATE;
1813 break;
1814 case 6:
1815 if (0 == strncasecmp(key, "Status", key_len)) {
1816 int status = strtol(value, NULL, 10);
1817 if (status >= 100 && status < 1000) {
1818 con->http_status = status;
1819 con->parsed_response |= HTTP_STATUS;
1820 } else {
1821 con->http_status = 502;
1824 break;
1825 case 8:
1826 if (0 == strncasecmp(key, "Location", key_len)) {
1827 con->parsed_response |= HTTP_LOCATION;
1829 break;
1830 case 10:
1831 if (0 == strncasecmp(key, "Connection", key_len)) {
1832 con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
1833 con->parsed_response |= HTTP_CONNECTION;
1835 break;
1836 case 14:
1837 if (0 == strncasecmp(key, "Content-Length", key_len)) {
1838 con->response.content_length = strtoul(value, NULL, 10);
1839 con->parsed_response |= HTTP_CONTENT_LENGTH;
1841 break;
1842 default:
1843 break;
1848 /* CGI/1.1 rev 03 - 7.2.1.2 */
1849 if ((con->parsed_response & HTTP_LOCATION) &&
1850 !(con->parsed_response & HTTP_STATUS)) {
1851 con->http_status = 302;
1854 return 0;
1858 static int scgi_demux_response(server *srv, handler_ctx *hctx) {
1859 plugin_data *p = hctx->plugin_data;
1860 connection *con = hctx->remote_conn;
1862 while(1) {
1863 int n;
1865 buffer_string_prepare_copy(hctx->response, 1023);
1866 if (-1 == (n = read(hctx->fd, hctx->response->ptr, hctx->response->size - 1))) {
1867 if (errno == EAGAIN || errno == EINTR) {
1868 /* would block, wait for signal */
1869 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
1870 return 0;
1872 /* error */
1873 log_error_write(srv, __FILE__, __LINE__, "sdd", strerror(errno), con->fd, hctx->fd);
1874 return -1;
1877 if (n == 0) {
1878 /* read finished */
1879 return 1;
1882 buffer_commit(hctx->response, n);
1884 /* split header from body */
1886 if (con->file_started == 0) {
1887 char *c;
1888 int in_header = 0;
1889 int header_end = 0;
1890 int cp, eol = EOL_UNSET;
1891 size_t used = 0;
1892 size_t hlen = 0;
1894 buffer_append_string_buffer(hctx->response_header, hctx->response);
1896 /* nph (non-parsed headers) */
1897 if (0 == strncmp(hctx->response_header->ptr, "HTTP/1.", 7)) in_header = 1;
1899 /* search for the \r\n\r\n or \n\n in the string */
1900 for (c = hctx->response_header->ptr, cp = 0, used = buffer_string_length(hctx->response_header); used; c++, cp++, used--) {
1901 if (*c == ':') in_header = 1;
1902 else if (*c == '\n') {
1903 if (in_header == 0) {
1904 /* got a response without a response header */
1906 c = NULL;
1907 header_end = 1;
1908 break;
1911 if (eol == EOL_UNSET) eol = EOL_N;
1913 if (*(c+1) == '\n') {
1914 header_end = 1;
1915 hlen = cp + 2;
1916 break;
1919 } else if (used > 1 && *c == '\r' && *(c+1) == '\n') {
1920 if (in_header == 0) {
1921 /* got a response without a response header */
1923 c = NULL;
1924 header_end = 1;
1925 break;
1928 if (eol == EOL_UNSET) eol = EOL_RN;
1930 if (used > 3 &&
1931 *(c+2) == '\r' &&
1932 *(c+3) == '\n') {
1933 header_end = 1;
1934 hlen = cp + 4;
1935 break;
1938 /* skip the \n */
1939 c++;
1940 cp++;
1941 used--;
1945 if (header_end) {
1946 if (c == NULL) {
1947 /* no header, but a body */
1948 if (0 != http_chunk_append_buffer(srv, con, hctx->response_header)) {
1949 /* error writing to tempfile;
1950 * truncate response or send 500 if nothing sent yet */
1951 return 1;
1953 } else {
1954 size_t blen = buffer_string_length(hctx->response_header) - hlen;
1956 /* a small hack: terminate after at the second \r */
1957 buffer_string_set_length(hctx->response_header, hlen - 1);
1959 /* parse the response header */
1960 scgi_response_parse(srv, con, p, hctx->response_header, eol);
1962 if (hctx->host->xsendfile_allow) {
1963 data_string *ds;
1964 if (NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-Sendfile"))) {
1965 http_response_xsendfile(srv, con, ds->value, hctx->host->xsendfile_docroot);
1966 return 1;
1970 if (blen > 0) {
1971 if (0 != http_chunk_append_mem(srv, con, hctx->response_header->ptr + hlen, blen)) {
1972 /* error writing to tempfile;
1973 * truncate response or send 500 if nothing sent yet */
1974 return 1;
1979 con->file_started = 1;
1980 } else {
1981 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
1982 if (buffer_string_length(hctx->response_header) > MAX_HTTP_REQUEST_HEADER) {
1983 log_error_write(srv, __FILE__, __LINE__, "sb", "response headers too large for", con->uri.path);
1984 con->http_status = 502; /* Bad Gateway */
1985 con->mode = DIRECT;
1986 return 1;
1989 } else {
1990 if (0 != http_chunk_append_buffer(srv, con, hctx->response)) {
1991 /* error writing to tempfile;
1992 * truncate response or send 500 if nothing sent yet */
1993 return 1;
1995 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
1996 && chunkqueue_length(con->write_queue) > 65536 - 4096) {
1997 if (!con->is_writable) {
1998 /*(defer removal of FDEVENT_IN interest since
1999 * connection_state_machine() might be able to send data
2000 * immediately, unless !con->is_writable, where
2001 * connection_state_machine() might not loop back to call
2002 * mod_scgi_handle_subrequest())*/
2003 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2005 break;
2009 #if 0
2010 log_error_write(srv, __FILE__, __LINE__, "ddss", con->fd, hctx->fd, connection_get_state(con->state), b->ptr);
2011 #endif
2014 return 0;
2018 static int scgi_proclist_sort_up(server *srv, scgi_extension_host *host, scgi_proc *proc) {
2019 scgi_proc *p;
2021 UNUSED(srv);
2023 /* we have been the smallest of the current list
2024 * and we want to insert the node sorted as soon
2025 * possible
2027 * 1 0 0 0 1 1 1
2028 * | ^
2029 * | |
2030 * +------+
2034 /* nothing to sort, only one element */
2035 if (host->first == proc && proc->next == NULL) return 0;
2037 for (p = proc; p->next && p->next->load < proc->load; p = p->next);
2039 /* no need to move something
2041 * 1 2 2 2 3 3 3
2047 if (p == proc) return 0;
2049 if (host->first == proc) {
2050 /* we have been the first elememt */
2052 host->first = proc->next;
2053 host->first->prev = NULL;
2056 /* disconnect proc */
2058 if (proc->prev) proc->prev->next = proc->next;
2059 if (proc->next) proc->next->prev = proc->prev;
2061 /* proc should be right of p */
2063 proc->next = p->next;
2064 proc->prev = p;
2065 if (p->next) p->next->prev = proc;
2066 p->next = proc;
2067 #if 0
2068 for(p = host->first; p; p = p->next) {
2069 log_error_write(srv, __FILE__, __LINE__, "dd",
2070 p->pid, p->load);
2072 #else
2073 UNUSED(srv);
2074 #endif
2076 return 0;
2079 int scgi_proclist_sort_down(server *srv, scgi_extension_host *host, scgi_proc *proc) {
2080 scgi_proc *p;
2082 UNUSED(srv);
2084 /* we have been the smallest of the current list
2085 * and we want to insert the node sorted as soon
2086 * possible
2088 * 0 0 0 0 1 0 1
2089 * ^ |
2090 * | |
2091 * +----------+
2094 * the basic is idea is:
2095 * - the last active scgi process should be still
2096 * in ram and is not swapped out yet
2097 * - processes that are not reused will be killed
2098 * after some time by the trigger-handler
2099 * - remember it as:
2100 * everything > 0 is hot
2101 * all unused procs are colder the more right they are
2102 * ice-cold processes are propably unused since more
2103 * than 'unused-timeout', are swaped out and won't be
2104 * reused in the next seconds anyway.
2108 /* nothing to sort, only one element */
2109 if (host->first == proc && proc->next == NULL) return 0;
2111 for (p = host->first; p != proc && p->load < proc->load; p = p->next);
2114 /* no need to move something
2116 * 1 2 2 2 3 3 3
2122 if (p == proc) return 0;
2124 /* we have to move left. If we are already the first element
2125 * we are done */
2126 if (host->first == proc) return 0;
2128 /* release proc */
2129 if (proc->prev) proc->prev->next = proc->next;
2130 if (proc->next) proc->next->prev = proc->prev;
2132 /* proc should be left of p */
2133 proc->next = p;
2134 proc->prev = p->prev;
2135 if (p->prev) p->prev->next = proc;
2136 p->prev = proc;
2138 if (proc->prev == NULL) host->first = proc;
2139 #if 0
2140 for(p = host->first; p; p = p->next) {
2141 log_error_write(srv, __FILE__, __LINE__, "dd",
2142 p->pid, p->load);
2144 #else
2145 UNUSED(srv);
2146 #endif
2148 return 0;
2151 static int scgi_restart_dead_procs(server *srv, plugin_data *p, scgi_extension_host *host) {
2152 scgi_proc *proc;
2154 for (proc = host->first; proc; proc = proc->next) {
2155 if (p->conf.debug) {
2156 log_error_write(srv, __FILE__, __LINE__, "sbdbdddd",
2157 "proc:",
2158 host->host, proc->port,
2159 proc->socket,
2160 proc->state,
2161 proc->is_local,
2162 proc->load,
2163 proc->pid);
2166 if (0 == proc->is_local) {
2168 * external servers might get disabled
2170 * enable the server again, perhaps it is back again
2173 if ((proc->state == PROC_STATE_DISABLED) &&
2174 (srv->cur_ts - proc->disable_ts > host->disable_time)) {
2175 proc->state = PROC_STATE_RUNNING;
2176 host->active_procs++;
2178 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2179 "fcgi-server re-enabled:",
2180 host->host, host->port,
2181 host->unixsocket);
2183 } else {
2184 /* the child should not terminate at all */
2185 int status;
2187 if (proc->state == PROC_STATE_DIED_WAIT_FOR_PID) {
2188 switch(waitpid(proc->pid, &status, WNOHANG)) {
2189 case 0:
2190 /* child is still alive */
2191 break;
2192 case -1:
2193 break;
2194 default:
2195 if (WIFEXITED(status)) {
2196 #if 0
2197 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2198 "child exited, pid:", proc->pid,
2199 "status:", WEXITSTATUS(status));
2200 #endif
2201 } else if (WIFSIGNALED(status)) {
2202 log_error_write(srv, __FILE__, __LINE__, "sd",
2203 "child signaled:",
2204 WTERMSIG(status));
2205 } else {
2206 log_error_write(srv, __FILE__, __LINE__, "sd",
2207 "child died somehow:",
2208 status);
2211 proc->state = PROC_STATE_DIED;
2212 break;
2217 * local servers might died, but we restart them
2220 if (proc->state == PROC_STATE_DIED &&
2221 proc->load == 0) {
2222 /* restart the child */
2224 if (p->conf.debug) {
2225 log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
2226 "--- scgi spawning",
2227 "\n\tport:", host->port,
2228 "\n\tsocket", host->unixsocket,
2229 "\n\tcurrent:", 1, "/", host->min_procs);
2232 if (scgi_spawn_connection(srv, p, host, proc)) {
2233 log_error_write(srv, __FILE__, __LINE__, "s",
2234 "ERROR: spawning fcgi failed.");
2235 return HANDLER_ERROR;
2238 scgi_proclist_sort_down(srv, host, proc);
2243 return 0;
2247 static handler_t scgi_write_request(server *srv, handler_ctx *hctx) {
2248 plugin_data *p = hctx->plugin_data;
2249 scgi_extension_host *host= hctx->host;
2250 connection *con = hctx->remote_conn;
2252 int ret;
2254 /* sanity check */
2255 if (!host) {
2256 log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: host = NULL");
2257 return HANDLER_ERROR;
2259 if (((buffer_string_is_empty(host->host) || !host->port) && buffer_string_is_empty(host->unixsocket))) {
2260 log_error_write(srv, __FILE__, __LINE__, "sxddd",
2261 "write-req: error",
2262 host,
2263 buffer_string_length(host->host),
2264 host->port,
2265 buffer_string_length(host->unixsocket));
2266 return HANDLER_ERROR;
2270 switch(hctx->state) {
2271 case FCGI_STATE_INIT:
2272 if (-1 == (hctx->fd = socket(host->family, SOCK_STREAM, 0))) {
2273 if (errno == EMFILE ||
2274 errno == EINTR) {
2275 log_error_write(srv, __FILE__, __LINE__, "sd",
2276 "wait for fd at connection:", con->fd);
2278 return HANDLER_WAIT_FOR_FD;
2281 log_error_write(srv, __FILE__, __LINE__, "ssdd",
2282 "socket failed:", strerror(errno), srv->cur_fds, srv->max_fds);
2283 return HANDLER_ERROR;
2285 hctx->fde_ndx = -1;
2287 srv->cur_fds++;
2289 fdevent_register(srv->ev, hctx->fd, scgi_handle_fdevent, hctx);
2291 if (-1 == fdevent_fcntl_set(srv->ev, hctx->fd)) {
2292 log_error_write(srv, __FILE__, __LINE__, "ss",
2293 "fcntl failed: ", strerror(errno));
2295 return HANDLER_ERROR;
2298 /* fall through */
2299 case FCGI_STATE_CONNECT:
2300 if (hctx->state == FCGI_STATE_INIT) {
2301 for (hctx->proc = hctx->host->first;
2302 hctx->proc && hctx->proc->state != PROC_STATE_RUNNING;
2303 hctx->proc = hctx->proc->next);
2305 /* all childs are dead */
2306 if (hctx->proc == NULL) {
2307 hctx->fde_ndx = -1;
2309 return HANDLER_ERROR;
2312 if (hctx->proc->is_local) {
2313 hctx->pid = hctx->proc->pid;
2316 switch (scgi_establish_connection(srv, hctx)) {
2317 case 1:
2318 scgi_set_state(srv, hctx, FCGI_STATE_CONNECT);
2320 /* connection is in progress, wait for an event and call getsockopt() below */
2322 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2324 return HANDLER_WAIT_FOR_EVENT;
2325 case -1:
2326 /* if ECONNREFUSED choose another connection -> FIXME */
2327 hctx->fde_ndx = -1;
2329 return HANDLER_ERROR;
2330 default:
2331 /* everything is ok, go on */
2332 break;
2336 } else {
2337 int socket_error;
2338 socklen_t socket_error_len = sizeof(socket_error);
2340 /* try to finish the connect() */
2341 if (0 != getsockopt(hctx->fd, SOL_SOCKET, SO_ERROR, &socket_error, &socket_error_len)) {
2342 log_error_write(srv, __FILE__, __LINE__, "ss",
2343 "getsockopt failed:", strerror(errno));
2345 return HANDLER_ERROR;
2347 if (socket_error != 0) {
2348 if (!hctx->proc->is_local || p->conf.debug) {
2349 /* local procs get restarted */
2351 log_error_write(srv, __FILE__, __LINE__, "ss",
2352 "establishing connection failed:", strerror(socket_error),
2353 "port:", hctx->proc->port);
2356 return HANDLER_ERROR;
2360 /* ok, we have the connection */
2362 hctx->proc->load++;
2363 hctx->proc->last_used = srv->cur_ts;
2364 hctx->got_proc = 1;
2366 if (p->conf.debug) {
2367 log_error_write(srv, __FILE__, __LINE__, "sddbdd",
2368 "got proc:",
2369 hctx->fd,
2370 hctx->proc->pid,
2371 hctx->proc->socket,
2372 hctx->proc->port,
2373 hctx->proc->load);
2376 /* move the proc-list entry down the list */
2377 scgi_proclist_sort_up(srv, hctx->host, hctx->proc);
2379 scgi_set_state(srv, hctx, FCGI_STATE_PREPARE_WRITE);
2380 /* fall through */
2381 case FCGI_STATE_PREPARE_WRITE:
2382 scgi_create_env(srv, hctx);
2384 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2385 scgi_set_state(srv, hctx, FCGI_STATE_WRITE);
2387 /* fall through */
2388 case FCGI_STATE_WRITE:
2389 ret = srv->network_backend_write(srv, con, hctx->fd, hctx->wb, MAX_WRITE_LIMIT);
2391 chunkqueue_remove_finished_chunks(hctx->wb);
2393 if (ret < 0) {
2394 if (errno == ENOTCONN || ret == -2) {
2395 /* the connection got dropped after accept()
2397 * this is most of the time a PHP which dies
2398 * after PHP_FCGI_MAX_REQUESTS
2401 if (hctx->wb->bytes_out == 0 &&
2402 hctx->reconnects < 5) {
2403 usleep(10000); /* take away the load of the webserver
2404 * to let the php a chance to restart
2407 scgi_reconnect(srv, hctx);
2409 return HANDLER_COMEBACK;
2412 /* not reconnected ... why
2414 * far@#lighttpd report this for FreeBSD
2418 log_error_write(srv, __FILE__, __LINE__, "ssosd",
2419 "connection was dropped after accept(). reconnect() denied:",
2420 "write-offset:", hctx->wb->bytes_out,
2421 "reconnect attempts:", hctx->reconnects);
2423 return HANDLER_ERROR;
2424 } else {
2425 /* -1 == ret => error on our side */
2426 log_error_write(srv, __FILE__, __LINE__, "ssd",
2427 "write failed:", strerror(errno), errno);
2429 return HANDLER_ERROR;
2433 if (hctx->wb->bytes_out == hctx->wb_reqlen) {
2434 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2435 shutdown(hctx->fd, SHUT_WR);
2436 scgi_set_state(srv, hctx, FCGI_STATE_READ);
2437 } else {
2438 off_t wblen = hctx->wb->bytes_in - hctx->wb->bytes_out;
2439 if (hctx->wb->bytes_in < hctx->wb_reqlen && wblen < 65536 - 16384) {
2440 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
2441 if (!(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_POLLIN)) {
2442 con->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLIN;
2443 con->is_readable = 1; /* trigger optimistic read from client */
2446 if (0 == wblen) {
2447 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2448 } else {
2449 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2453 return HANDLER_WAIT_FOR_EVENT;
2454 case FCGI_STATE_READ:
2455 /* waiting for a response */
2456 return HANDLER_WAIT_FOR_EVENT;
2457 default:
2458 log_error_write(srv, __FILE__, __LINE__, "s", "(debug) unknown state");
2459 return HANDLER_ERROR;
2463 static handler_t scgi_send_request(server *srv, handler_ctx *hctx) {
2464 /* ok, create the request */
2465 handler_t rc = scgi_write_request(srv, hctx);
2466 if (HANDLER_ERROR != rc) {
2467 return rc;
2468 } else {
2469 scgi_proc *proc = hctx->proc;
2470 scgi_extension_host *host = hctx->host;
2471 plugin_data *p = hctx->plugin_data;
2472 connection *con = hctx->remote_conn;
2474 if (proc &&
2475 0 == proc->is_local &&
2476 proc->state != PROC_STATE_DISABLED) {
2477 /* only disable remote servers as we don't manage them*/
2479 log_error_write(srv, __FILE__, __LINE__, "sbdb", "fcgi-server disabled:",
2480 host->host,
2481 proc->port,
2482 proc->socket);
2484 /* disable this server */
2485 proc->disable_ts = srv->cur_ts;
2486 proc->state = PROC_STATE_DISABLED;
2487 host->active_procs--;
2490 if (hctx->state == FCGI_STATE_INIT ||
2491 hctx->state == FCGI_STATE_CONNECT) {
2492 /* connect() or getsockopt() failed,
2493 * restart the request-handling
2495 if (proc && proc->is_local) {
2497 if (p->conf.debug) {
2498 log_error_write(srv, __FILE__, __LINE__, "sbdb", "connect() to scgi failed, restarting the request-handling:",
2499 host->host,
2500 proc->port,
2501 proc->socket);
2505 * several hctx might reference the same proc
2507 * Only one of them should mark the proc as dead all the other
2508 * ones should just take a new one.
2510 * If a new proc was started with the old struct this might lead
2511 * the mark a perfect proc as dead otherwise
2514 if (proc->state == PROC_STATE_RUNNING &&
2515 hctx->pid == proc->pid) {
2516 proc->state = PROC_STATE_DIED_WAIT_FOR_PID;
2519 scgi_restart_dead_procs(srv, p, host);
2521 con->mode = DIRECT;/*(avoid changing con->state, con->http_status)*/
2522 scgi_connection_close(srv, hctx);
2523 con->mode = p->id;
2525 return HANDLER_COMEBACK;
2526 } else {
2527 scgi_connection_close(srv, hctx);
2528 con->http_status = 503;
2530 return HANDLER_FINISHED;
2536 static handler_t scgi_recv_response(server *srv, handler_ctx *hctx);
2539 SUBREQUEST_FUNC(mod_scgi_handle_subrequest) {
2540 plugin_data *p = p_d;
2542 handler_ctx *hctx = con->plugin_ctx[p->id];
2544 if (NULL == hctx) return HANDLER_GO_ON;
2546 /* not my job */
2547 if (con->mode != p->id) return HANDLER_GO_ON;
2549 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
2550 && con->file_started) {
2551 if (chunkqueue_length(con->write_queue) > 65536 - 4096) {
2552 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2553 } else if (!(fdevent_event_get_interest(srv->ev, hctx->fd) & FDEVENT_IN)) {
2554 /* optimistic read from backend, which might re-enable FDEVENT_IN */
2555 handler_t rc = scgi_recv_response(srv, hctx); /*(might invalidate hctx)*/
2556 if (rc != HANDLER_GO_ON) return rc; /*(unless HANDLER_GO_ON)*/
2560 if (0 == hctx->wb->bytes_in
2561 ? con->state == CON_STATE_READ_POST
2562 : hctx->wb->bytes_in < hctx->wb_reqlen) {
2563 /*(64k - 4k to attempt to avoid temporary files
2564 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
2565 if (hctx->wb->bytes_in - hctx->wb->bytes_out > 65536 - 4096
2566 && (con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_BUFMIN)){
2567 con->conf.stream_request_body &= ~FDEVENT_STREAM_REQUEST_POLLIN;
2568 if (0 != hctx->wb->bytes_in) return HANDLER_WAIT_FOR_EVENT;
2569 } else {
2570 handler_t r = connection_handle_read_post_state(srv, con);
2571 chunkqueue *req_cq = con->request_content_queue;
2572 if (0 != hctx->wb->bytes_in && !chunkqueue_is_empty(req_cq)) {
2573 chunkqueue_append_chunkqueue(hctx->wb, req_cq);
2574 if (fdevent_event_get_interest(srv->ev, hctx->fd) & FDEVENT_OUT) {
2575 return (r == HANDLER_GO_ON) ? HANDLER_WAIT_FOR_EVENT : r;
2578 if (r != HANDLER_GO_ON) return r;
2582 return (0 == hctx->wb->bytes_in || !chunkqueue_is_empty(hctx->wb))
2583 ? scgi_send_request(srv, hctx)
2584 : HANDLER_WAIT_FOR_EVENT;
2588 static handler_t scgi_recv_response(server *srv, handler_ctx *hctx) {
2590 switch (scgi_demux_response(srv, hctx)) {
2591 case 0:
2592 break;
2593 case 1:
2594 /* we are done */
2595 scgi_connection_close(srv, hctx);
2597 return HANDLER_FINISHED;
2598 case -1: {
2599 connection *con = hctx->remote_conn;
2600 plugin_data *p = hctx->plugin_data;
2602 scgi_proc *proc = hctx->proc;
2603 scgi_extension_host *host= hctx->host;
2605 if (proc->pid && proc->state != PROC_STATE_DIED) {
2606 int status;
2608 /* only fetch the zombie if it is not already done */
2610 switch(waitpid(proc->pid, &status, WNOHANG)) {
2611 case 0:
2612 /* child is still alive */
2613 break;
2614 case -1:
2615 break;
2616 default:
2617 /* the child should not terminate at all */
2618 if (WIFEXITED(status)) {
2619 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2620 "child exited, pid:", proc->pid,
2621 "status:", WEXITSTATUS(status));
2622 } else if (WIFSIGNALED(status)) {
2623 log_error_write(srv, __FILE__, __LINE__, "sd",
2624 "child signaled:",
2625 WTERMSIG(status));
2626 } else {
2627 log_error_write(srv, __FILE__, __LINE__, "sd",
2628 "child died somehow:",
2629 status);
2632 if (p->conf.debug) {
2633 log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
2634 "--- scgi spawning",
2635 "\n\tport:", host->port,
2636 "\n\tsocket", host->unixsocket,
2637 "\n\tcurrent:", 1, "/", host->min_procs);
2640 if (scgi_spawn_connection(srv, p, host, proc)) {
2641 /* child died */
2642 proc->state = PROC_STATE_DIED;
2643 } else {
2644 scgi_proclist_sort_down(srv, host, proc);
2647 break;
2651 if (con->file_started == 0) {
2652 /* nothing has been send out yet, try to use another child */
2654 if (hctx->wb->bytes_out == 0 &&
2655 hctx->reconnects < 5) {
2657 log_error_write(srv, __FILE__, __LINE__, "ssdsd",
2658 "response not sent, request not sent, reconnection.",
2659 "connection-fd:", con->fd,
2660 "fcgi-fd:", hctx->fd);
2662 scgi_reconnect(srv, hctx);
2664 return HANDLER_COMEBACK;
2667 log_error_write(srv, __FILE__, __LINE__, "sosdsd",
2668 "response not sent, request sent:", hctx->wb->bytes_out,
2669 "connection-fd:", con->fd,
2670 "fcgi-fd:", hctx->fd);
2671 } else {
2672 log_error_write(srv, __FILE__, __LINE__, "ssdsd",
2673 "response already sent out, termination connection",
2674 "connection-fd:", con->fd,
2675 "fcgi-fd:", hctx->fd);
2678 http_response_backend_error(srv, con);
2679 scgi_connection_close(srv, hctx);
2680 return HANDLER_FINISHED;
2684 return HANDLER_GO_ON;
2688 static handler_t scgi_handle_fdevent(server *srv, void *ctx, int revents) {
2689 handler_ctx *hctx = ctx;
2690 connection *con = hctx->remote_conn;
2692 joblist_append(srv, con);
2694 if (revents & FDEVENT_IN) {
2695 handler_t rc = scgi_recv_response(srv, hctx);/*(might invalidate hctx)*/
2696 if (rc != HANDLER_GO_ON) return rc; /*(unless HANDLER_GO_ON)*/
2699 if (revents & FDEVENT_OUT) {
2700 return scgi_send_request(srv, hctx); /*(might invalidate hctx)*/
2703 /* perhaps this issue is already handled */
2704 if (revents & FDEVENT_HUP) {
2705 if (hctx->state == FCGI_STATE_CONNECT) {
2706 /* getoptsock will catch this one (right ?)
2708 * if we are in connect we might get a EINPROGRESS
2709 * in the first call and a FDEVENT_HUP in the
2710 * second round
2712 * FIXME: as it is a bit ugly.
2715 scgi_send_request(srv, hctx);
2716 } else if (con->file_started) {
2717 /* drain any remaining data from kernel pipe buffers
2718 * even if (con->conf.stream_response_body
2719 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
2720 * since event loop will spin on fd FDEVENT_HUP event
2721 * until unregistered. */
2722 handler_t rc;
2723 do {
2724 rc = scgi_recv_response(srv,hctx);/*(might invalidate hctx)*/
2725 } while (rc == HANDLER_GO_ON); /*(unless HANDLER_GO_ON)*/
2726 return rc; /* HANDLER_FINISHED or HANDLER_ERROR */
2727 } else {
2728 scgi_extension_host *host= hctx->host;
2729 log_error_write(srv, __FILE__, __LINE__, "sbSBSDSd",
2730 "error: unexpected close of scgi connection for",
2731 con->uri.path,
2732 "(no scgi process on host: ",
2733 host->host,
2734 ", port: ",
2735 host->port,
2736 " ?)",
2737 hctx->state);
2739 scgi_connection_close(srv, hctx);
2741 } else if (revents & FDEVENT_ERR) {
2742 log_error_write(srv, __FILE__, __LINE__, "s",
2743 "fcgi: got a FDEVENT_ERR. Don't know why.");
2745 http_response_backend_error(srv, con);
2746 scgi_connection_close(srv, hctx);
2749 return HANDLER_FINISHED;
2751 #define PATCH(x) \
2752 p->conf.x = s->x;
2753 static int scgi_patch_connection(server *srv, connection *con, plugin_data *p) {
2754 size_t i, j;
2755 plugin_config *s = p->config_storage[0];
2757 PATCH(exts);
2758 PATCH(debug);
2760 /* skip the first, the global context */
2761 for (i = 1; i < srv->config_context->used; i++) {
2762 data_config *dc = (data_config *)srv->config_context->data[i];
2763 s = p->config_storage[i];
2765 /* condition didn't match */
2766 if (!config_check_cond(srv, con, dc)) continue;
2768 /* merge config */
2769 for (j = 0; j < dc->value->used; j++) {
2770 data_unset *du = dc->value->data[j];
2772 if (buffer_is_equal_string(du->key, CONST_STR_LEN("scgi.server"))) {
2773 PATCH(exts);
2774 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("scgi.debug"))) {
2775 PATCH(debug);
2780 return 0;
2782 #undef PATCH
2785 static handler_t scgi_check_extension(server *srv, connection *con, void *p_d, int uri_path_handler) {
2786 plugin_data *p = p_d;
2787 size_t s_len;
2788 int used = -1;
2789 size_t k;
2790 buffer *fn;
2791 scgi_extension *extension = NULL;
2792 scgi_extension_host *host = NULL;
2794 if (con->mode != DIRECT) return HANDLER_GO_ON;
2796 /* Possibly, we processed already this request */
2797 if (con->file_started == 1) return HANDLER_GO_ON;
2799 fn = uri_path_handler ? con->uri.path : con->physical.path;
2801 if (buffer_string_is_empty(fn)) return HANDLER_GO_ON;
2803 s_len = buffer_string_length(fn);
2805 scgi_patch_connection(srv, con, p);
2807 /* check if extension matches */
2808 for (k = 0; k < p->conf.exts->used; k++) {
2809 size_t ct_len;
2810 scgi_extension *ext = p->conf.exts->exts[k];
2812 if (buffer_is_empty(ext->key)) continue;
2814 ct_len = buffer_string_length(ext->key);
2816 if (s_len < ct_len) continue;
2818 /* check extension in the form "/scgi_pattern" */
2819 if (*(ext->key->ptr) == '/') {
2820 if (strncmp(fn->ptr, ext->key->ptr, ct_len) == 0) {
2821 extension = ext;
2822 break;
2824 } else if (0 == strncmp(fn->ptr + s_len - ct_len, ext->key->ptr, ct_len)) {
2825 /* check extension in the form ".fcg" */
2826 extension = ext;
2827 break;
2831 /* extension doesn't match */
2832 if (NULL == extension) {
2833 return HANDLER_GO_ON;
2836 /* get best server */
2837 for (k = 0; k < extension->used; k++) {
2838 scgi_extension_host *h = extension->hosts[k];
2840 /* we should have at least one proc that can do something */
2841 if (h->active_procs == 0) {
2842 continue;
2845 if (used == -1 || h->load < used) {
2846 used = h->load;
2848 host = h;
2852 if (!host) {
2853 /* sorry, we don't have a server alive for this ext */
2854 con->http_status = 500;
2855 con->mode = DIRECT;
2857 /* only send the 'no handler' once */
2858 if (!extension->note_is_sent) {
2859 extension->note_is_sent = 1;
2861 log_error_write(srv, __FILE__, __LINE__, "sbsbs",
2862 "all handlers for ", con->uri.path,
2863 "on", extension->key,
2864 "are down.");
2867 return HANDLER_FINISHED;
2870 /* a note about no handler is not sent yet */
2871 extension->note_is_sent = 0;
2873 /* SCGI requires that Content-Length be set.
2874 * Send 411 Length Required if Content-Length missing.
2875 * (Alternatively, collect full request body before proceeding
2876 * in mod_scgi_handle_subrequest()) */
2877 if (0 == con->request.content_length
2878 && array_get_element(con->request.headers, "Transfer-Encoding")) {
2879 con->keep_alive = 0;
2880 con->http_status = 411; /* Length Required */
2881 con->mode = DIRECT;
2882 return HANDLER_FINISHED;
2886 * if check-local is disabled, use the uri.path handler
2890 /* init handler-context */
2891 if (uri_path_handler) {
2892 if (host->check_local == 0) {
2893 handler_ctx *hctx;
2894 char *pathinfo;
2896 hctx = handler_ctx_init();
2898 hctx->remote_conn = con;
2899 hctx->plugin_data = p;
2900 hctx->host = host;
2901 hctx->proc = NULL;
2903 hctx->conf.exts = p->conf.exts;
2904 hctx->conf.debug = p->conf.debug;
2906 con->plugin_ctx[p->id] = hctx;
2908 host->load++;
2910 con->mode = p->id;
2912 if (con->conf.log_request_handling) {
2913 log_error_write(srv, __FILE__, __LINE__, "s",
2914 "handling it in mod_scgi");
2917 /* the prefix is the SCRIPT_NAME,
2918 * everything from start to the next slash
2919 * this is important for check-local = "disable"
2921 * if prefix = /admin.fcgi
2923 * /admin.fcgi/foo/bar
2925 * SCRIPT_NAME = /admin.fcgi
2926 * PATH_INFO = /foo/bar
2928 * if prefix = /fcgi-bin/
2930 * /fcgi-bin/foo/bar
2932 * SCRIPT_NAME = /fcgi-bin/foo
2933 * PATH_INFO = /bar
2937 /* the rewrite is only done for /prefix/? matches */
2938 if (host->fix_root_path_name && extension->key->ptr[0] == '/' && extension->key->ptr[1] == '\0') {
2939 buffer_copy_string(con->request.pathinfo, con->uri.path->ptr);
2940 buffer_string_set_length(con->uri.path, 0);
2941 } else if (extension->key->ptr[0] == '/' &&
2942 buffer_string_length(con->uri.path) > buffer_string_length(extension->key) &&
2943 NULL != (pathinfo = strchr(con->uri.path->ptr + buffer_string_length(extension->key), '/'))) {
2944 /* rewrite uri.path and pathinfo */
2946 buffer_copy_string(con->request.pathinfo, pathinfo);
2947 buffer_string_set_length(con->uri.path, buffer_string_length(con->uri.path) - buffer_string_length(con->request.pathinfo));
2950 } else {
2951 handler_ctx *hctx;
2952 hctx = handler_ctx_init();
2954 hctx->remote_conn = con;
2955 hctx->plugin_data = p;
2956 hctx->host = host;
2957 hctx->proc = NULL;
2959 hctx->conf.exts = p->conf.exts;
2960 hctx->conf.debug = p->conf.debug;
2962 con->plugin_ctx[p->id] = hctx;
2964 host->load++;
2966 con->mode = p->id;
2968 if (con->conf.log_request_handling) {
2969 log_error_write(srv, __FILE__, __LINE__, "s", "handling it in mod_scgi");
2973 return HANDLER_GO_ON;
2976 /* uri-path handler */
2977 static handler_t scgi_check_extension_1(server *srv, connection *con, void *p_d) {
2978 return scgi_check_extension(srv, con, p_d, 1);
2981 /* start request handler */
2982 static handler_t scgi_check_extension_2(server *srv, connection *con, void *p_d) {
2983 return scgi_check_extension(srv, con, p_d, 0);
2987 TRIGGER_FUNC(mod_scgi_handle_trigger) {
2988 plugin_data *p = p_d;
2989 size_t i, j, n;
2992 /* perhaps we should kill a connect attempt after 10-15 seconds
2994 * currently we wait for the TCP timeout which is on Linux 180 seconds
3000 /* check all childs if they are still up */
3002 for (i = 0; i < srv->config_context->used; i++) {
3003 plugin_config *conf;
3004 scgi_exts *exts;
3006 conf = p->config_storage[i];
3008 exts = conf->exts;
3010 for (j = 0; j < exts->used; j++) {
3011 scgi_extension *ex;
3013 ex = exts->exts[j];
3015 for (n = 0; n < ex->used; n++) {
3017 scgi_proc *proc;
3018 unsigned long sum_load = 0;
3019 scgi_extension_host *host;
3021 host = ex->hosts[n];
3023 scgi_restart_dead_procs(srv, p, host);
3025 for (proc = host->first; proc; proc = proc->next) {
3026 sum_load += proc->load;
3029 if (host->num_procs &&
3030 host->num_procs < host->max_procs &&
3031 (sum_load / host->num_procs) > host->max_load_per_proc) {
3032 /* overload, spawn new child */
3033 scgi_proc *fp = NULL;
3035 if (p->conf.debug) {
3036 log_error_write(srv, __FILE__, __LINE__, "s",
3037 "overload detected, spawning a new child");
3040 for (fp = host->unused_procs; fp && fp->pid != 0; fp = fp->next);
3042 if (fp) {
3043 if (fp == host->unused_procs) host->unused_procs = fp->next;
3045 if (fp->next) fp->next->prev = NULL;
3047 host->max_id++;
3048 } else {
3049 fp = scgi_process_init();
3050 fp->id = host->max_id++;
3053 host->num_procs++;
3055 if (buffer_string_is_empty(host->unixsocket)) {
3056 fp->port = host->port + fp->id;
3057 } else {
3058 buffer_copy_buffer(fp->socket, host->unixsocket);
3059 buffer_append_string_len(fp->socket, CONST_STR_LEN("-"));
3060 buffer_append_int(fp->socket, fp->id);
3063 if (scgi_spawn_connection(srv, p, host, fp)) {
3064 log_error_write(srv, __FILE__, __LINE__, "s",
3065 "ERROR: spawning fcgi failed.");
3066 scgi_process_free(fp);
3067 return HANDLER_ERROR;
3070 fp->prev = NULL;
3071 fp->next = host->first;
3072 if (host->first) {
3073 host->first->prev = fp;
3075 host->first = fp;
3078 for (proc = host->first; proc; proc = proc->next) {
3079 if (proc->load != 0) break;
3080 if (host->num_procs <= host->min_procs) break;
3081 if (proc->pid == 0) continue;
3083 if (srv->cur_ts - proc->last_used > host->idle_timeout) {
3084 /* a proc is idling for a long time now,
3085 * terminated it */
3087 if (p->conf.debug) {
3088 log_error_write(srv, __FILE__, __LINE__, "ssbsd",
3089 "idle-timeout reached, terminating child:",
3090 "socket:", proc->socket,
3091 "pid", proc->pid);
3095 if (proc->next) proc->next->prev = proc->prev;
3096 if (proc->prev) proc->prev->next = proc->next;
3098 if (proc->prev == NULL) host->first = proc->next;
3100 proc->prev = NULL;
3101 proc->next = host->unused_procs;
3103 if (host->unused_procs) host->unused_procs->prev = proc;
3104 host->unused_procs = proc;
3106 kill(proc->pid, SIGTERM);
3108 proc->state = PROC_STATE_KILLED;
3110 log_error_write(srv, __FILE__, __LINE__, "ssbsd",
3111 "killed:",
3112 "socket:", proc->socket,
3113 "pid", proc->pid);
3115 host->num_procs--;
3117 /* proc is now in unused, let the next second handle the next process */
3118 break;
3122 for (proc = host->unused_procs; proc; proc = proc->next) {
3123 int status;
3125 if (proc->pid == 0) continue;
3127 switch (waitpid(proc->pid, &status, WNOHANG)) {
3128 case 0:
3129 /* child still running after timeout, good */
3130 break;
3131 case -1:
3132 if (errno != EINTR) {
3133 /* no PID found ? should never happen */
3134 log_error_write(srv, __FILE__, __LINE__, "sddss",
3135 "pid ", proc->pid, proc->state,
3136 "not found:", strerror(errno));
3138 #if 0
3139 if (errno == ECHILD) {
3140 /* someone else has cleaned up for us */
3141 proc->pid = 0;
3142 proc->state = PROC_STATE_UNSET;
3144 #endif
3146 break;
3147 default:
3148 /* the child should not terminate at all */
3149 if (WIFEXITED(status)) {
3150 if (proc->state != PROC_STATE_KILLED) {
3151 log_error_write(srv, __FILE__, __LINE__, "sdb",
3152 "child exited:",
3153 WEXITSTATUS(status), proc->socket);
3155 } else if (WIFSIGNALED(status)) {
3156 if (WTERMSIG(status) != SIGTERM) {
3157 log_error_write(srv, __FILE__, __LINE__, "sd",
3158 "child signaled:",
3159 WTERMSIG(status));
3161 } else {
3162 log_error_write(srv, __FILE__, __LINE__, "sd",
3163 "child died somehow:",
3164 status);
3166 proc->pid = 0;
3167 proc->state = PROC_STATE_UNSET;
3168 host->max_id--;
3175 return HANDLER_GO_ON;
3179 int mod_scgi_plugin_init(plugin *p);
3180 int mod_scgi_plugin_init(plugin *p) {
3181 p->version = LIGHTTPD_VERSION_ID;
3182 p->name = buffer_init_string("scgi");
3184 p->init = mod_scgi_init;
3185 p->cleanup = mod_scgi_free;
3186 p->set_defaults = mod_scgi_set_defaults;
3187 p->connection_reset = scgi_connection_reset;
3188 p->handle_connection_close = scgi_connection_reset;
3189 p->handle_uri_clean = scgi_check_extension_1;
3190 p->handle_subrequest_start = scgi_check_extension_2;
3191 p->handle_subrequest = mod_scgi_handle_subrequest;
3192 p->handle_trigger = mod_scgi_handle_trigger;
3194 p->data = NULL;
3196 return 0;