skip spawning backends for preflight tests (#2642)
[lighttpd.git] / src / mod_scgi.c
blob4e194fed842551887adfc7d93815067e8ed9eacc
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 #ifdef HAVE_SYS_FILIO_H
31 # include <sys/filio.h>
32 #endif
34 #include "sys-socket.h"
36 #ifdef HAVE_SYS_UIO_H
37 # include <sys/uio.h>
38 #endif
40 #ifdef HAVE_SYS_WAIT_H
41 # include <sys/wait.h>
42 #endif
44 #include "version.h"
46 enum {EOL_UNSET, EOL_N, EOL_RN};
50 * TODO:
52 * - add timeout for a connect to a non-scgi process
53 * (use state_timestamp + state)
57 typedef struct scgi_proc {
58 size_t id; /* id will be between 1 and max_procs */
59 buffer *socket; /* config.socket + "-" + id */
60 unsigned port; /* config.port + pno */
62 pid_t pid; /* PID of the spawned process (0 if not spawned locally) */
65 size_t load; /* number of requests waiting on this process */
67 time_t last_used; /* see idle_timeout */
68 size_t requests; /* see max_requests */
69 struct scgi_proc *prev, *next; /* see first */
71 time_t disable_ts; /* replace by host->something */
73 int is_local;
75 enum { PROC_STATE_UNSET, /* init-phase */
76 PROC_STATE_RUNNING, /* alive */
77 PROC_STATE_DIED_WAIT_FOR_PID,
78 PROC_STATE_KILLED, /* was killed as we don't have the load anymore */
79 PROC_STATE_DIED, /* marked as dead, should be restarted */
80 PROC_STATE_DISABLED /* proc disabled as it resulted in an error */
81 } state;
82 } scgi_proc;
84 typedef struct {
85 /* list of processes handling this extension
86 * sorted by lowest load
88 * whenever a job is done move it up in the list
89 * until it is sorted, move it down as soon as the
90 * job is started
92 scgi_proc *first;
93 scgi_proc *unused_procs;
96 * spawn at least min_procs, at max_procs.
98 * as soon as the load of the first entry
99 * is max_load_per_proc we spawn a new one
100 * and add it to the first entry and give it
101 * the load
105 unsigned short min_procs;
106 unsigned short max_procs;
107 size_t num_procs; /* how many procs are started */
108 size_t active_procs; /* how many of them are really running */
110 unsigned short max_load_per_proc;
113 * kick the process from the list if it was not
114 * used for idle_timeout until min_procs is
115 * reached. this helps to get the processlist
116 * small again we had a small peak load.
120 unsigned short idle_timeout;
123 * time after a disabled remote connection is tried to be re-enabled
128 unsigned short disable_time;
131 * same scgi processes get a little bit larger
132 * than wanted. max_requests_per_proc kills a
133 * process after a number of handled requests.
136 size_t max_requests_per_proc;
139 /* config */
142 * host:port
144 * if host is one of the local IP adresses the
145 * whole connection is local
147 * if tcp/ip should be used host AND port have
148 * to be specified
151 buffer *host;
152 unsigned short port;
155 * Unix Domain Socket
157 * instead of TCP/IP we can use Unix Domain Sockets
158 * - more secure (you have fileperms to play with)
159 * - more control (on locally)
160 * - more speed (no extra overhead)
162 buffer *unixsocket;
164 /* if socket is local we can start the scgi
165 * process ourself
167 * bin-path is the path to the binary
169 * check min_procs and max_procs for the number
170 * of process to start-up
172 buffer *bin_path;
174 /* bin-path is set bin-environment is taken to
175 * create the environement before starting the
176 * FastCGI process
179 array *bin_env;
181 array *bin_env_copy;
184 * docroot-translation between URL->phys and the
185 * remote host
187 * reasons:
188 * - different dir-layout if remote
189 * - chroot if local
192 buffer *docroot;
195 * check_local tell you if the phys file is stat()ed
196 * or not. FastCGI doesn't care if the service is
197 * remote. If the web-server side doesn't contain
198 * the scgi-files we should not stat() for them
199 * and say '404 not found'.
201 unsigned short check_local;
204 * append PATH_INFO to SCRIPT_FILENAME
206 * php needs this if cgi.fix_pathinfo is provied
211 * workaround for program when prefix="/"
213 * rule to build PATH_INFO is hardcoded for when check_local is disabled
214 * enable this option to use the workaround
218 unsigned short fix_root_path_name;
219 ssize_t load; /* replace by host->load */
221 size_t max_id; /* corresponds most of the time to
222 num_procs.
224 only if a process is killed max_id waits for the process itself
225 to die and decrements its afterwards */
226 } scgi_extension_host;
229 * one extension can have multiple hosts assigned
230 * one host can spawn additional processes on the same
231 * socket (if we control it)
233 * ext -> host -> procs
234 * 1:n 1:n
236 * if the scgi process is remote that whole goes down
237 * to
239 * ext -> host -> procs
240 * 1:n 1:1
242 * in case of PHP and FCGI_CHILDREN we have again a procs
243 * but we don't control it directly.
247 typedef struct {
248 buffer *key; /* like .php */
250 int note_is_sent;
251 scgi_extension_host **hosts;
253 size_t used;
254 size_t size;
255 } scgi_extension;
257 typedef struct {
258 scgi_extension **exts;
260 size_t used;
261 size_t size;
262 } scgi_exts;
265 typedef struct {
266 scgi_exts *exts;
268 int debug;
269 } plugin_config;
271 typedef struct {
272 char **ptr;
274 size_t size;
275 size_t used;
276 } char_array;
278 /* generic plugin data, shared between all connections */
279 typedef struct {
280 PLUGIN_DATA;
282 buffer *scgi_env;
284 buffer *path;
285 buffer *parse_response;
287 plugin_config **config_storage;
289 plugin_config conf; /* this is only used as long as no handler_ctx is setup */
290 } plugin_data;
292 /* connection specific data */
293 typedef enum { FCGI_STATE_INIT, FCGI_STATE_CONNECT, FCGI_STATE_PREPARE_WRITE,
294 FCGI_STATE_WRITE, FCGI_STATE_READ
295 } scgi_connection_state_t;
297 typedef struct {
298 buffer *response;
299 size_t response_len;
300 int response_type;
301 int response_padding;
303 scgi_proc *proc;
304 scgi_extension_host *host;
306 scgi_connection_state_t state;
307 time_t state_timestamp;
309 int reconnects; /* number of reconnect attempts */
311 chunkqueue *wb;
313 buffer *response_header;
315 int delayed; /* flag to mark that the connect() is delayed */
317 size_t request_id;
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;
324 plugin_config conf;
326 connection *remote_conn; /* dumb pointer */
327 plugin_data *plugin_data; /* dumb pointer */
328 } handler_ctx;
331 /* ok, we need a prototype */
332 static handler_t scgi_handle_fdevent(server *srv, void *ctx, int revents);
334 int scgi_proclist_sort_down(server *srv, scgi_extension_host *host, scgi_proc *proc);
336 static void reset_signals(void) {
337 #ifdef SIGTTOU
338 signal(SIGTTOU, SIG_DFL);
339 #endif
340 #ifdef SIGTTIN
341 signal(SIGTTIN, SIG_DFL);
342 #endif
343 #ifdef SIGTSTP
344 signal(SIGTSTP, SIG_DFL);
345 #endif
346 signal(SIGHUP, SIG_DFL);
347 signal(SIGPIPE, SIG_DFL);
348 signal(SIGUSR1, SIG_DFL);
351 static handler_ctx * handler_ctx_init(void) {
352 handler_ctx * hctx;
354 hctx = calloc(1, sizeof(*hctx));
355 force_assert(hctx);
357 hctx->fde_ndx = -1;
359 hctx->response = buffer_init();
360 hctx->response_header = buffer_init();
362 hctx->request_id = 0;
363 hctx->state = FCGI_STATE_INIT;
364 hctx->proc = NULL;
366 hctx->response_len = 0;
367 hctx->response_type = 0;
368 hctx->response_padding = 0;
369 hctx->fd = -1;
371 hctx->reconnects = 0;
373 hctx->wb = chunkqueue_init();
375 return hctx;
378 static void handler_ctx_free(handler_ctx *hctx) {
379 buffer_free(hctx->response);
380 buffer_free(hctx->response_header);
382 chunkqueue_free(hctx->wb);
384 free(hctx);
387 static scgi_proc *scgi_process_init(void) {
388 scgi_proc *f;
390 f = calloc(1, sizeof(*f));
391 force_assert(f);
392 f->socket = buffer_init();
394 f->prev = NULL;
395 f->next = NULL;
397 return f;
400 static void scgi_process_free(scgi_proc *f) {
401 if (!f) return;
403 scgi_process_free(f->next);
405 buffer_free(f->socket);
407 free(f);
410 static scgi_extension_host *scgi_host_init(void) {
411 scgi_extension_host *f;
413 f = calloc(1, sizeof(*f));
415 f->host = buffer_init();
416 f->unixsocket = buffer_init();
417 f->docroot = buffer_init();
418 f->bin_path = buffer_init();
419 f->bin_env = array_init();
420 f->bin_env_copy = array_init();
422 return f;
425 static void scgi_host_free(scgi_extension_host *h) {
426 if (!h) return;
428 buffer_free(h->host);
429 buffer_free(h->unixsocket);
430 buffer_free(h->docroot);
431 buffer_free(h->bin_path);
432 array_free(h->bin_env);
433 array_free(h->bin_env_copy);
435 scgi_process_free(h->first);
436 scgi_process_free(h->unused_procs);
438 free(h);
442 static scgi_exts *scgi_extensions_init(void) {
443 scgi_exts *f;
445 f = calloc(1, sizeof(*f));
446 force_assert(f);
448 return f;
451 static void scgi_extensions_free(scgi_exts *f) {
452 size_t i;
454 if (!f) return;
456 for (i = 0; i < f->used; i++) {
457 scgi_extension *fe;
458 size_t j;
460 fe = f->exts[i];
462 for (j = 0; j < fe->used; j++) {
463 scgi_extension_host *h;
465 h = fe->hosts[j];
467 scgi_host_free(h);
470 buffer_free(fe->key);
471 free(fe->hosts);
473 free(fe);
476 free(f->exts);
478 free(f);
481 static int scgi_extension_insert(scgi_exts *ext, buffer *key, scgi_extension_host *fh) {
482 scgi_extension *fe;
483 size_t i;
485 /* there is something */
487 for (i = 0; i < ext->used; i++) {
488 if (buffer_is_equal(key, ext->exts[i]->key)) {
489 break;
493 if (i == ext->used) {
494 /* filextension is new */
495 fe = calloc(1, sizeof(*fe));
496 force_assert(fe);
497 fe->key = buffer_init();
498 buffer_copy_buffer(fe->key, key);
500 /* */
502 if (ext->size == 0) {
503 ext->size = 8;
504 ext->exts = malloc(ext->size * sizeof(*(ext->exts)));
505 force_assert(ext->exts);
506 } else if (ext->used == ext->size) {
507 ext->size += 8;
508 ext->exts = realloc(ext->exts, ext->size * sizeof(*(ext->exts)));
509 force_assert(ext->exts);
511 ext->exts[ext->used++] = fe;
512 } else {
513 fe = ext->exts[i];
516 if (fe->size == 0) {
517 fe->size = 4;
518 fe->hosts = malloc(fe->size * sizeof(*(fe->hosts)));
519 force_assert(fe->hosts);
520 } else if (fe->size == fe->used) {
521 fe->size += 4;
522 fe->hosts = realloc(fe->hosts, fe->size * sizeof(*(fe->hosts)));
523 force_assert(fe->hosts);
526 fe->hosts[fe->used++] = fh;
528 return 0;
532 INIT_FUNC(mod_scgi_init) {
533 plugin_data *p;
535 p = calloc(1, sizeof(*p));
536 force_assert(p);
538 p->scgi_env = buffer_init();
540 p->path = buffer_init();
541 p->parse_response = buffer_init();
543 return p;
547 FREE_FUNC(mod_scgi_free) {
548 plugin_data *p = p_d;
550 UNUSED(srv);
552 buffer_free(p->scgi_env);
553 buffer_free(p->path);
554 buffer_free(p->parse_response);
556 if (p->config_storage) {
557 size_t i, j, n;
558 for (i = 0; i < srv->config_context->used; i++) {
559 plugin_config *s = p->config_storage[i];
560 scgi_exts *exts;
562 if (NULL == s) continue;
564 exts = s->exts;
566 for (j = 0; j < exts->used; j++) {
567 scgi_extension *ex;
569 ex = exts->exts[j];
571 for (n = 0; n < ex->used; n++) {
572 scgi_proc *proc;
573 scgi_extension_host *host;
575 host = ex->hosts[n];
577 for (proc = host->first; proc; proc = proc->next) {
578 if (proc->pid != 0) kill(proc->pid, SIGTERM);
580 if (proc->is_local &&
581 !buffer_string_is_empty(proc->socket)) {
582 unlink(proc->socket->ptr);
586 for (proc = host->unused_procs; proc; proc = proc->next) {
587 if (proc->pid != 0) kill(proc->pid, SIGTERM);
589 if (proc->is_local &&
590 !buffer_string_is_empty(proc->socket)) {
591 unlink(proc->socket->ptr);
597 scgi_extensions_free(s->exts);
599 free(s);
601 free(p->config_storage);
604 free(p);
606 return HANDLER_GO_ON;
609 static int env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) {
610 char *dst;
611 size_t i;
613 if (!key || !val) return -1;
615 dst = malloc(key_len + val_len + 3);
616 force_assert(dst);
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);
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;
631 if (env->size == 0) {
632 env->size = 16;
633 env->ptr = malloc(env->size * sizeof(*env->ptr));
634 force_assert(env->ptr);
635 } else if (env->size == env->used) {
636 env->size += 16;
637 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
638 force_assert(env->ptr);
641 env->ptr[env->used++] = dst;
643 return 0;
646 #if !defined(HAVE_FORK)
647 static int scgi_spawn_connection(server *srv,
648 plugin_data *p,
649 scgi_extension_host *host,
650 scgi_proc *proc) {
651 UNUSED(srv);
652 UNUSED(p);
653 UNUSED(host);
654 UNUSED(proc);
655 return -1;
658 #else /* -> defined(HAVE_FORK) */
660 static int scgi_spawn_connection(server *srv,
661 plugin_data *p,
662 scgi_extension_host *host,
663 scgi_proc *proc) {
664 int scgi_fd;
665 int socket_type, status;
666 struct timeval tv = { 0, 100 * 1000 };
667 #ifdef HAVE_SYS_UN_H
668 struct sockaddr_un scgi_addr_un;
669 #endif
670 struct sockaddr_in scgi_addr_in;
671 struct sockaddr *scgi_addr;
673 socklen_t servlen;
675 if (p->conf.debug) {
676 log_error_write(srv, __FILE__, __LINE__, "sdb",
677 "new proc, socket:", proc->port, proc->socket);
681 if (!buffer_string_is_empty(proc->socket)) {
682 #ifdef HAVE_SYS_UN_H
683 memset(&scgi_addr_un, 0, sizeof(scgi_addr_un));
684 scgi_addr_un.sun_family = AF_UNIX;
685 if (buffer_string_length(proc->socket) + 1 > sizeof(scgi_addr_un.sun_path)) {
686 log_error_write(srv, __FILE__, __LINE__, "sB",
687 "ERROR: Unix Domain socket filename too long:",
688 proc->socket);
689 return -1;
691 memcpy(scgi_addr_un.sun_path, proc->socket->ptr, buffer_string_length(proc->socket) + 1);
693 #ifdef SUN_LEN
694 servlen = SUN_LEN(&scgi_addr_un);
695 #else
696 /* stevens says: */
697 servlen = buffer_string_length(proc->socket) + 1 + sizeof(scgi_addr_un.sun_family);
698 #endif
699 socket_type = AF_UNIX;
700 scgi_addr = (struct sockaddr *) &scgi_addr_un;
701 #else
702 log_error_write(srv, __FILE__, __LINE__, "s",
703 "ERROR: Unix Domain sockets are not supported.");
704 return -1;
705 #endif
706 } else {
707 memset(&scgi_addr_in, 0, sizeof(scgi_addr_in));
708 scgi_addr_in.sin_family = AF_INET;
710 if (buffer_string_is_empty(host->host)) {
711 scgi_addr_in.sin_addr.s_addr = htonl(INADDR_ANY);
712 } else {
713 struct hostent *he;
715 /* set a usefull default */
716 scgi_addr_in.sin_addr.s_addr = htonl(INADDR_ANY);
719 if (NULL == (he = gethostbyname(host->host->ptr))) {
720 log_error_write(srv, __FILE__, __LINE__,
721 "sdb", "gethostbyname failed: ",
722 h_errno, host->host);
723 return -1;
726 if (he->h_addrtype != AF_INET) {
727 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-type != AF_INET: ", he->h_addrtype);
728 return -1;
731 if (he->h_length != sizeof(struct in_addr)) {
732 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-length != sizeof(in_addr): ", he->h_length);
733 return -1;
736 memcpy(&(scgi_addr_in.sin_addr.s_addr), he->h_addr_list[0], he->h_length);
739 scgi_addr_in.sin_port = htons(proc->port);
740 servlen = sizeof(scgi_addr_in);
742 socket_type = AF_INET;
743 scgi_addr = (struct sockaddr *) &scgi_addr_in;
746 if (-1 == (scgi_fd = socket(socket_type, SOCK_STREAM, 0))) {
747 log_error_write(srv, __FILE__, __LINE__, "ss",
748 "failed:", strerror(errno));
749 return -1;
752 if (-1 == connect(scgi_fd, scgi_addr, servlen)) {
753 /* server is not up, spawn in */
754 pid_t child;
755 int val;
757 if (!buffer_string_is_empty(proc->socket)) {
758 unlink(proc->socket->ptr);
761 close(scgi_fd);
763 /* reopen socket */
764 if (-1 == (scgi_fd = socket(socket_type, SOCK_STREAM, 0))) {
765 log_error_write(srv, __FILE__, __LINE__, "ss",
766 "socket failed:", strerror(errno));
767 return -1;
770 val = 1;
771 if (setsockopt(scgi_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) {
772 log_error_write(srv, __FILE__, __LINE__, "ss",
773 "socketsockopt failed:", strerror(errno));
774 close(scgi_fd);
775 return -1;
778 /* create socket */
779 if (-1 == bind(scgi_fd, scgi_addr, servlen)) {
780 log_error_write(srv, __FILE__, __LINE__, "sbds",
781 "bind failed for:",
782 proc->socket,
783 proc->port,
784 strerror(errno));
785 close(scgi_fd);
786 return -1;
789 if (-1 == listen(scgi_fd, 1024)) {
790 log_error_write(srv, __FILE__, __LINE__, "ss",
791 "listen failed:", strerror(errno));
792 close(scgi_fd);
793 return -1;
796 switch ((child = fork())) {
797 case 0: {
798 buffer *b;
799 size_t i = 0;
800 int fd = 0;
801 char_array env;
804 /* create environment */
805 env.ptr = NULL;
806 env.size = 0;
807 env.used = 0;
809 if (scgi_fd != 0) {
810 dup2(scgi_fd, 0);
811 close(scgi_fd);
814 /* we don't need the client socket */
815 for (fd = 3; fd < 256; fd++) {
816 close(fd);
819 /* build clean environment */
820 if (host->bin_env_copy->used) {
821 for (i = 0; i < host->bin_env_copy->used; i++) {
822 data_string *ds = (data_string *)host->bin_env_copy->data[i];
823 char *ge;
825 if (NULL != (ge = getenv(ds->value->ptr))) {
826 env_add(&env, CONST_BUF_LEN(ds->value), ge, strlen(ge));
829 } else {
830 for (i = 0; environ[i]; i++) {
831 char *eq;
833 if (NULL != (eq = strchr(environ[i], '='))) {
834 env_add(&env, environ[i], eq - environ[i], eq+1, strlen(eq+1));
839 /* create environment */
840 for (i = 0; i < host->bin_env->used; i++) {
841 data_string *ds = (data_string *)host->bin_env->data[i];
843 env_add(&env, CONST_BUF_LEN(ds->key), CONST_BUF_LEN(ds->value));
846 for (i = 0; i < env.used; i++) {
847 /* search for PHP_FCGI_CHILDREN */
848 if (0 == strncmp(env.ptr[i], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
851 /* not found, add a default */
852 if (i == env.used) {
853 env_add(&env, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
856 env.ptr[env.used] = NULL;
858 b = buffer_init();
859 buffer_copy_string_len(b, CONST_STR_LEN("exec "));
860 buffer_append_string_buffer(b, host->bin_path);
862 reset_signals();
864 /* exec the cgi */
865 execle("/bin/sh", "sh", "-c", b->ptr, (char *)NULL, env.ptr);
867 log_error_write(srv, __FILE__, __LINE__, "sbs",
868 "execl failed for:", host->bin_path, strerror(errno));
870 exit(errno);
872 break;
874 case -1:
875 /* error */
876 close(scgi_fd);
877 break;
878 default:
879 /* father */
880 close(scgi_fd);
882 /* wait */
883 select(0, NULL, NULL, NULL, &tv);
885 switch (waitpid(child, &status, WNOHANG)) {
886 case 0:
887 /* child still running after timeout, good */
888 break;
889 case -1:
890 /* no PID found ? should never happen */
891 log_error_write(srv, __FILE__, __LINE__, "ss",
892 "pid not found:", strerror(errno));
893 return -1;
894 default:
895 /* the child should not terminate at all */
896 if (WIFEXITED(status)) {
897 log_error_write(srv, __FILE__, __LINE__, "sd",
898 "child exited (is this a SCGI binary ?):",
899 WEXITSTATUS(status));
900 } else if (WIFSIGNALED(status)) {
901 log_error_write(srv, __FILE__, __LINE__, "sd",
902 "child signaled:",
903 WTERMSIG(status));
904 } else {
905 log_error_write(srv, __FILE__, __LINE__, "sd",
906 "child died somehow:",
907 status);
909 return -1;
912 /* register process */
913 proc->pid = child;
914 proc->last_used = srv->cur_ts;
915 proc->is_local = 1;
917 break;
919 } else {
920 close(scgi_fd);
922 proc->is_local = 0;
923 proc->pid = 0;
925 if (p->conf.debug) {
926 log_error_write(srv, __FILE__, __LINE__, "sb",
927 "(debug) socket is already used, won't spawn:",
928 proc->socket);
932 proc->state = PROC_STATE_RUNNING;
933 host->active_procs++;
935 return 0;
938 #endif /* HAVE_FORK */
940 static int unixsocket_is_dup(plugin_data *p, size_t used, buffer *unixsocket) {
941 size_t i, j, n;
942 for (i = 0; i < used; ++i) {
943 scgi_exts *exts = p->config_storage[i]->exts;
944 for (j = 0; j < exts->used; ++j) {
945 scgi_extension *ex = exts->exts[j];
946 for (n = 0; n < ex->used; ++n) {
947 scgi_extension_host *host = ex->hosts[n];
948 if (!buffer_string_is_empty(host->unixsocket)
949 && buffer_is_equal(host->unixsocket, unixsocket))
950 return 1;
955 return 0;
958 SETDEFAULTS_FUNC(mod_scgi_set_defaults) {
959 plugin_data *p = p_d;
960 data_unset *du;
961 size_t i = 0;
962 scgi_extension_host *df = NULL;
964 config_values_t cv[] = {
965 { "scgi.server", NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
966 { "scgi.debug", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
967 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
970 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
971 force_assert(p->config_storage);
973 for (i = 0; i < srv->config_context->used; i++) {
974 data_config const* config = (data_config const*)srv->config_context->data[i];
975 plugin_config *s;
977 s = malloc(sizeof(plugin_config));
978 force_assert(s);
979 s->exts = scgi_extensions_init();
980 s->debug = 0;
982 cv[0].destination = s->exts;
983 cv[1].destination = &(s->debug);
985 p->config_storage[i] = s;
987 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
988 goto error;
992 * <key> = ( ... )
995 if (NULL != (du = array_get_element(config->value, "scgi.server"))) {
996 size_t j;
997 data_array *da = (data_array *)du;
999 if (du->type != TYPE_ARRAY) {
1000 log_error_write(srv, __FILE__, __LINE__, "sss",
1001 "unexpected type for key: ", "scgi.server", "array of strings");
1003 goto error;
1008 * scgi.server = ( "<ext>" => ( ... ),
1009 * "<ext>" => ( ... ) )
1012 for (j = 0; j < da->value->used; j++) {
1013 size_t n;
1014 data_array *da_ext = (data_array *)da->value->data[j];
1016 if (da->value->data[j]->type != TYPE_ARRAY) {
1017 log_error_write(srv, __FILE__, __LINE__, "sssbs",
1018 "unexpected type for key: ", "scgi.server",
1019 "[", da->value->data[j]->key, "](string)");
1021 goto error;
1025 * da_ext->key == name of the extension
1029 * scgi.server = ( "<ext>" =>
1030 * ( "<host>" => ( ... ),
1031 * "<host>" => ( ... )
1032 * ),
1033 * "<ext>" => ... )
1036 for (n = 0; n < da_ext->value->used; n++) {
1037 data_array *da_host = (data_array *)da_ext->value->data[n];
1039 config_values_t fcv[] = {
1040 { "host", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1041 { "docroot", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1042 { "socket", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1043 { "bin-path", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
1045 { "check-local", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
1046 { "port", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 5 */
1047 { "min-procs-not-working", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 7 this is broken for now */
1048 { "max-procs", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
1049 { "max-load-per-proc", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
1050 { "idle-timeout", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 9 */
1051 { "disable-time", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 10 */
1053 { "bin-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 11 */
1054 { "bin-copy-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
1055 { "fix-root-scriptname", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 13 */
1058 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1061 if (da_host->type != TYPE_ARRAY) {
1062 log_error_write(srv, __FILE__, __LINE__, "ssSBS",
1063 "unexpected type for key:",
1064 "scgi.server",
1065 "[", da_host->key, "](string)");
1067 goto error;
1070 df = scgi_host_init();
1072 df->check_local = 1;
1073 df->min_procs = 4;
1074 df->max_procs = 4;
1075 df->max_load_per_proc = 1;
1076 df->idle_timeout = 60;
1077 df->disable_time = 60;
1078 df->fix_root_path_name = 0;
1080 fcv[0].destination = df->host;
1081 fcv[1].destination = df->docroot;
1082 fcv[2].destination = df->unixsocket;
1083 fcv[3].destination = df->bin_path;
1085 fcv[4].destination = &(df->check_local);
1086 fcv[5].destination = &(df->port);
1087 fcv[6].destination = &(df->min_procs);
1088 fcv[7].destination = &(df->max_procs);
1089 fcv[8].destination = &(df->max_load_per_proc);
1090 fcv[9].destination = &(df->idle_timeout);
1091 fcv[10].destination = &(df->disable_time);
1093 fcv[11].destination = df->bin_env;
1094 fcv[12].destination = df->bin_env_copy;
1095 fcv[13].destination = &(df->fix_root_path_name);
1098 if (0 != config_insert_values_internal(srv, da_host->value, fcv, T_CONFIG_SCOPE_CONNECTION)) {
1099 goto error;
1102 if ((!buffer_string_is_empty(df->host) || df->port) &&
1103 !buffer_string_is_empty(df->unixsocket)) {
1104 log_error_write(srv, __FILE__, __LINE__, "s",
1105 "either host+port or socket");
1107 goto error;
1110 if (!buffer_string_is_empty(df->unixsocket)) {
1111 /* unix domain socket */
1112 struct sockaddr_un un;
1114 if (buffer_string_length(df->unixsocket) + 1 > sizeof(un.sun_path) - 2) {
1115 log_error_write(srv, __FILE__, __LINE__, "s",
1116 "path of the unixdomain socket is too large");
1117 goto error;
1120 if (!buffer_string_is_empty(df->bin_path)
1121 && unixsocket_is_dup(p, i+1, df->unixsocket)) {
1122 log_error_write(srv, __FILE__, __LINE__, "sb",
1123 "duplicate unixsocket path:",
1124 df->unixsocket);
1125 goto error;
1127 } else {
1128 /* tcp/ip */
1130 if (buffer_string_is_empty(df->host) &&
1131 buffer_string_is_empty(df->bin_path)) {
1132 log_error_write(srv, __FILE__, __LINE__, "sbbbs",
1133 "missing key (string):",
1134 da->key,
1135 da_ext->key,
1136 da_host->key,
1137 "host");
1139 goto error;
1140 } else if (df->port == 0) {
1141 log_error_write(srv, __FILE__, __LINE__, "sbbbs",
1142 "missing key (short):",
1143 da->key,
1144 da_ext->key,
1145 da_host->key,
1146 "port");
1147 goto error;
1151 if (!buffer_string_is_empty(df->bin_path)) {
1152 /* a local socket + self spawning */
1153 size_t pno;
1155 /* HACK: just to make sure the adaptive spawing is disabled */
1156 df->min_procs = df->max_procs;
1158 if (df->min_procs > df->max_procs) df->max_procs = df->min_procs;
1159 if (df->max_load_per_proc < 1) df->max_load_per_proc = 0;
1161 if (s->debug) {
1162 log_error_write(srv, __FILE__, __LINE__, "ssbsdsbsdsd",
1163 "--- scgi spawning local",
1164 "\n\tproc:", df->bin_path,
1165 "\n\tport:", df->port,
1166 "\n\tsocket", df->unixsocket,
1167 "\n\tmin-procs:", df->min_procs,
1168 "\n\tmax-procs:", df->max_procs);
1171 for (pno = 0; pno < df->min_procs; pno++) {
1172 scgi_proc *proc;
1174 proc = scgi_process_init();
1175 proc->id = df->num_procs++;
1176 df->max_id++;
1178 if (buffer_string_is_empty(df->unixsocket)) {
1179 proc->port = df->port + pno;
1180 } else {
1181 buffer_copy_buffer(proc->socket, df->unixsocket);
1182 buffer_append_string_len(proc->socket, CONST_STR_LEN("-"));
1183 buffer_append_int(proc->socket, pno);
1186 if (s->debug) {
1187 log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
1188 "--- scgi spawning",
1189 "\n\tport:", df->port,
1190 "\n\tsocket", df->unixsocket,
1191 "\n\tcurrent:", pno, "/", df->min_procs);
1194 if (!srv->srvconf.preflight_check
1195 && scgi_spawn_connection(srv, p, df, proc)) {
1196 log_error_write(srv, __FILE__, __LINE__, "s",
1197 "[ERROR]: spawning fcgi failed.");
1198 scgi_process_free(proc);
1199 goto error;
1202 proc->next = df->first;
1203 if (df->first) df->first->prev = proc;
1205 df->first = proc;
1207 } else {
1208 scgi_proc *fp;
1210 fp = scgi_process_init();
1211 fp->id = df->num_procs++;
1212 df->max_id++;
1213 df->active_procs++;
1214 fp->state = PROC_STATE_RUNNING;
1216 if (buffer_string_is_empty(df->unixsocket)) {
1217 fp->port = df->port;
1218 } else {
1219 buffer_copy_buffer(fp->socket, df->unixsocket);
1222 df->first = fp;
1224 df->min_procs = 1;
1225 df->max_procs = 1;
1228 /* if extension already exists, take it */
1229 scgi_extension_insert(s->exts, da_ext->key, df);
1230 df = NULL;
1236 return HANDLER_GO_ON;
1238 error:
1239 if (NULL != df) scgi_host_free(df);
1240 return HANDLER_ERROR;
1243 static int scgi_set_state(server *srv, handler_ctx *hctx, scgi_connection_state_t state) {
1244 hctx->state = state;
1245 hctx->state_timestamp = srv->cur_ts;
1247 return 0;
1251 static void scgi_connection_cleanup(server *srv, handler_ctx *hctx) {
1252 plugin_data *p;
1253 connection *con;
1255 if (NULL == hctx) return;
1257 p = hctx->plugin_data;
1258 con = hctx->remote_conn;
1260 if (hctx->fd != -1) {
1261 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1262 fdevent_unregister(srv->ev, hctx->fd);
1263 close(hctx->fd);
1264 srv->cur_fds--;
1267 if (hctx->host && hctx->proc) {
1268 hctx->host->load--;
1270 if (hctx->got_proc) {
1271 /* after the connect the process gets a load */
1272 hctx->proc->load--;
1274 if (p->conf.debug) {
1275 log_error_write(srv, __FILE__, __LINE__, "sddb",
1276 "release proc:",
1277 hctx->fd,
1278 hctx->proc->pid, hctx->proc->socket);
1282 scgi_proclist_sort_down(srv, hctx->host, hctx->proc);
1286 handler_ctx_free(hctx);
1287 con->plugin_ctx[p->id] = NULL;
1290 static int scgi_reconnect(server *srv, handler_ctx *hctx) {
1291 plugin_data *p = hctx->plugin_data;
1293 /* child died
1295 * 1.
1297 * connect was ok, connection was accepted
1298 * but the php accept loop checks after the accept if it should die or not.
1300 * if yes we can only detect it at a write()
1302 * next step is resetting this attemp and setup a connection again
1304 * if we have more then 5 reconnects for the same request, die
1306 * 2.
1308 * we have a connection but the child died by some other reason
1312 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1313 fdevent_unregister(srv->ev, hctx->fd);
1314 close(hctx->fd);
1315 srv->cur_fds--;
1317 scgi_set_state(srv, hctx, FCGI_STATE_INIT);
1319 hctx->request_id = 0;
1320 hctx->reconnects++;
1322 if (p->conf.debug) {
1323 log_error_write(srv, __FILE__, __LINE__, "sddb",
1324 "release proc:",
1325 hctx->fd,
1326 hctx->proc->pid, hctx->proc->socket);
1329 hctx->proc->load--;
1330 scgi_proclist_sort_down(srv, hctx->host, hctx->proc);
1332 return 0;
1336 static handler_t scgi_connection_reset(server *srv, connection *con, void *p_d) {
1337 plugin_data *p = p_d;
1339 scgi_connection_cleanup(srv, con->plugin_ctx[p->id]);
1341 return HANDLER_GO_ON;
1345 static int scgi_env_add(buffer *env, const char *key, size_t key_len, const char *val, size_t val_len) {
1346 size_t len;
1348 if (!key || !val) return -1;
1350 len = key_len + val_len + 2;
1352 buffer_string_prepare_append(env, len);
1354 buffer_append_string_len(env, key, key_len);
1355 buffer_append_string_len(env, "", 1);
1356 buffer_append_string_len(env, val, val_len);
1357 buffer_append_string_len(env, "", 1);
1359 return 0;
1365 * returns
1366 * -1 error
1367 * 0 connected
1368 * 1 not connected yet
1371 static int scgi_establish_connection(server *srv, handler_ctx *hctx) {
1372 struct sockaddr *scgi_addr;
1373 struct sockaddr_in scgi_addr_in;
1374 #ifdef HAVE_SYS_UN_H
1375 struct sockaddr_un scgi_addr_un;
1376 #endif
1377 socklen_t servlen;
1379 scgi_extension_host *host = hctx->host;
1380 scgi_proc *proc = hctx->proc;
1381 int scgi_fd = hctx->fd;
1383 if (!buffer_string_is_empty(proc->socket)) {
1384 #ifdef HAVE_SYS_UN_H
1385 /* use the unix domain socket */
1386 memset(&scgi_addr_un, 0, sizeof(scgi_addr_un));
1387 scgi_addr_un.sun_family = AF_UNIX;
1388 if (buffer_string_length(proc->socket) + 1 > sizeof(scgi_addr_un.sun_path)) {
1389 log_error_write(srv, __FILE__, __LINE__, "sB",
1390 "ERROR: Unix Domain socket filename too long:",
1391 proc->socket);
1392 return -1;
1394 memcpy(scgi_addr_un.sun_path, proc->socket->ptr, buffer_string_length(proc->socket) + 1);
1396 #ifdef SUN_LEN
1397 servlen = SUN_LEN(&scgi_addr_un);
1398 #else
1399 /* stevens says: */
1400 servlen = buffer_string_length(proc->socket) + 1 + sizeof(scgi_addr_un.sun_family);
1401 #endif
1402 scgi_addr = (struct sockaddr *) &scgi_addr_un;
1403 #else
1404 return -1;
1405 #endif
1406 } else {
1407 memset(&scgi_addr_in, 0, sizeof(scgi_addr_in));
1408 scgi_addr_in.sin_family = AF_INET;
1409 if (0 == inet_aton(host->host->ptr, &(scgi_addr_in.sin_addr))) {
1410 log_error_write(srv, __FILE__, __LINE__, "sbs",
1411 "converting IP-adress failed for", host->host,
1412 "\nBe sure to specify an IP address here");
1414 return -1;
1416 scgi_addr_in.sin_port = htons(proc->port);
1417 servlen = sizeof(scgi_addr_in);
1419 scgi_addr = (struct sockaddr *) &scgi_addr_in;
1422 if (-1 == connect(scgi_fd, scgi_addr, servlen)) {
1423 if (errno == EINPROGRESS ||
1424 errno == EALREADY ||
1425 errno == EINTR) {
1426 if (hctx->conf.debug) {
1427 log_error_write(srv, __FILE__, __LINE__, "sd",
1428 "connect delayed, will continue later:", scgi_fd);
1431 return 1;
1432 } else {
1433 log_error_write(srv, __FILE__, __LINE__, "sdsddb",
1434 "connect failed:", scgi_fd,
1435 strerror(errno), errno,
1436 proc->port, proc->socket);
1438 if (errno == EAGAIN) {
1439 /* this is Linux only */
1441 log_error_write(srv, __FILE__, __LINE__, "s",
1442 "If this happend on Linux: You have been run out of local ports. "
1443 "Check the manual, section Performance how to handle this.");
1446 return -1;
1449 if (hctx->conf.debug > 1) {
1450 log_error_write(srv, __FILE__, __LINE__, "sd",
1451 "connect succeeded: ", scgi_fd);
1456 return 0;
1459 static int scgi_env_add_request_headers(server *srv, connection *con, plugin_data *p) {
1460 size_t i;
1462 for (i = 0; i < con->request.headers->used; i++) {
1463 data_string *ds;
1465 ds = (data_string *)con->request.headers->data[i];
1467 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1468 buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 1);
1470 scgi_env_add(p->scgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value));
1474 for (i = 0; i < con->environment->used; i++) {
1475 data_string *ds;
1477 ds = (data_string *)con->environment->data[i];
1479 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1480 buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 0);
1482 scgi_env_add(p->scgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value));
1486 return 0;
1490 static int scgi_create_env(server *srv, handler_ctx *hctx) {
1491 char buf[LI_ITOSTRING_LENGTH];
1492 const char *s;
1493 #ifdef HAVE_IPV6
1494 char b2[INET6_ADDRSTRLEN + 1];
1495 #endif
1496 buffer *b;
1498 plugin_data *p = hctx->plugin_data;
1499 scgi_extension_host *host= hctx->host;
1501 connection *con = hctx->remote_conn;
1502 server_socket *srv_sock = con->srv_socket;
1504 sock_addr our_addr;
1505 socklen_t our_addr_len;
1507 buffer_string_prepare_copy(p->scgi_env, 1023);
1509 /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
1511 li_itostrn(buf, sizeof(buf), con->request.content_length);
1512 scgi_env_add(p->scgi_env, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf));
1513 scgi_env_add(p->scgi_env, CONST_STR_LEN("SCGI"), CONST_STR_LEN("1"));
1516 if (buffer_is_empty(con->conf.server_tag)) {
1517 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_DESC));
1518 } else {
1519 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con->conf.server_tag));
1522 if (!buffer_is_empty(con->server_name)) {
1523 size_t len = buffer_string_length(con->server_name);
1525 if (con->server_name->ptr[0] == '[') {
1526 const char *colon = strstr(con->server_name->ptr, "]:");
1527 if (colon) len = (colon + 1) - con->server_name->ptr;
1528 } else {
1529 const char *colon = strchr(con->server_name->ptr, ':');
1530 if (colon) len = colon - con->server_name->ptr;
1533 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_NAME"), con->server_name->ptr, len);
1534 } else {
1535 #ifdef HAVE_IPV6
1536 s = inet_ntop(srv_sock->addr.plain.sa_family,
1537 srv_sock->addr.plain.sa_family == AF_INET6 ?
1538 (const void *) &(srv_sock->addr.ipv6.sin6_addr) :
1539 (const void *) &(srv_sock->addr.ipv4.sin_addr),
1540 b2, sizeof(b2)-1);
1541 #else
1542 s = inet_ntoa(srv_sock->addr.ipv4.sin_addr);
1543 #endif
1544 force_assert(s);
1545 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_NAME"), s, strlen(s));
1548 scgi_env_add(p->scgi_env, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1"));
1550 li_utostrn(buf, sizeof(buf),
1551 #ifdef HAVE_IPV6
1552 ntohs(srv_sock->addr.plain.sa_family ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port)
1553 #else
1554 ntohs(srv_sock->addr.ipv4.sin_port)
1555 #endif
1558 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf));
1560 /* get the server-side of the connection to the client */
1561 our_addr_len = sizeof(our_addr);
1563 if (-1 == getsockname(con->fd, &(our_addr.plain), &our_addr_len)) {
1564 s = inet_ntop_cache_get_ip(srv, &(srv_sock->addr));
1565 } else {
1566 s = inet_ntop_cache_get_ip(srv, &(our_addr));
1568 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s));
1570 li_utostrn(buf, sizeof(buf),
1571 #ifdef HAVE_IPV6
1572 ntohs(con->dst_addr.plain.sa_family ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port)
1573 #else
1574 ntohs(con->dst_addr.ipv4.sin_port)
1575 #endif
1578 scgi_env_add(p->scgi_env, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf));
1580 s = inet_ntop_cache_get_ip(srv, &(con->dst_addr));
1581 force_assert(s);
1582 scgi_env_add(p->scgi_env, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s));
1585 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1586 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1587 * (6.1.14, 6.1.6, 6.1.7)
1590 scgi_env_add(p->scgi_env, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path));
1592 if (!buffer_string_is_empty(con->request.pathinfo)) {
1593 scgi_env_add(p->scgi_env, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo));
1595 /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1597 if (!buffer_string_is_empty(host->docroot)) {
1598 buffer_copy_buffer(p->path, host->docroot);
1599 } else {
1600 buffer_copy_buffer(p->path, con->physical.basedir);
1602 buffer_append_string_buffer(p->path, con->request.pathinfo);
1603 scgi_env_add(p->scgi_env, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p->path));
1604 } else {
1605 scgi_env_add(p->scgi_env, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN(""));
1609 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1610 * http://www.php.net/manual/en/reserved.variables.php
1611 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1612 * TODO: this code should be checked against cgi.fix_pathinfo php
1613 * parameter.
1616 if (!buffer_string_is_empty(host->docroot)) {
1618 * rewrite SCRIPT_FILENAME
1622 buffer_copy_buffer(p->path, host->docroot);
1623 buffer_append_string_buffer(p->path, con->uri.path);
1625 scgi_env_add(p->scgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path));
1626 scgi_env_add(p->scgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host->docroot));
1627 } else {
1628 buffer_copy_buffer(p->path, con->physical.path);
1630 scgi_env_add(p->scgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path));
1631 scgi_env_add(p->scgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.basedir));
1633 scgi_env_add(p->scgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri));
1634 if (!buffer_is_equal(con->request.uri, con->request.orig_uri)) {
1635 scgi_env_add(p->scgi_env, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con->request.uri));
1637 if (!buffer_string_is_empty(con->uri.query)) {
1638 scgi_env_add(p->scgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query));
1639 } else {
1640 scgi_env_add(p->scgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN(""));
1643 s = get_http_method_name(con->request.http_method);
1644 force_assert(s);
1645 scgi_env_add(p->scgi_env, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s));
1646 scgi_env_add(p->scgi_env, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")); /* if php is compiled with --force-redirect */
1647 s = get_http_version_name(con->request.http_version);
1648 force_assert(s);
1649 scgi_env_add(p->scgi_env, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));
1651 #ifdef USE_OPENSSL
1652 if (buffer_is_equal_caseless_string(con->uri.scheme, CONST_STR_LEN("https"))) {
1653 scgi_env_add(p->scgi_env, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1655 #endif
1657 scgi_env_add_request_headers(srv, con, p);
1659 b = buffer_init();
1661 buffer_append_int(b, buffer_string_length(p->scgi_env));
1662 buffer_append_string_len(b, CONST_STR_LEN(":"));
1663 buffer_append_string_buffer(b, p->scgi_env);
1664 buffer_append_string_len(b, CONST_STR_LEN(","));
1666 chunkqueue_append_buffer(hctx->wb, b);
1667 buffer_free(b);
1669 if (con->request.content_length) {
1670 chunkqueue *req_cq = con->request_content_queue;
1672 chunkqueue_steal(hctx->wb, req_cq, req_cq->bytes_in);
1675 return 0;
1678 static int scgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in, int eol) {
1679 char *ns;
1680 const char *s;
1681 int line = 0;
1683 UNUSED(srv);
1685 buffer_copy_buffer(p->parse_response, in);
1687 for (s = p->parse_response->ptr;
1688 NULL != (ns = (eol == EOL_RN ? strstr(s, "\r\n") : strchr(s, '\n')));
1689 s = ns + (eol == EOL_RN ? 2 : 1), line++) {
1690 const char *key, *value;
1691 int key_len;
1692 data_string *ds;
1694 ns[0] = '\0';
1696 if (line == 0 &&
1697 0 == strncmp(s, "HTTP/1.", 7)) {
1698 /* non-parsed header ... we parse them anyway */
1700 if ((s[7] == '1' ||
1701 s[7] == '0') &&
1702 s[8] == ' ') {
1703 int status;
1704 /* after the space should be a status code for us */
1706 status = strtol(s+9, NULL, 10);
1708 if (status >= 100 && status < 1000) {
1709 /* we expected 3 digits got them */
1710 con->parsed_response |= HTTP_STATUS;
1711 con->http_status = status;
1714 } else {
1716 key = s;
1717 if (NULL == (value = strchr(s, ':'))) {
1718 /* we expect: "<key>: <value>\r\n" */
1719 continue;
1722 key_len = value - key;
1723 value += 1;
1725 /* skip LWS */
1726 while (*value == ' ' || *value == '\t') value++;
1728 if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
1729 ds = data_response_init();
1731 buffer_copy_string_len(ds->key, key, key_len);
1732 buffer_copy_string(ds->value, value);
1734 array_insert_unique(con->response.headers, (data_unset *)ds);
1736 switch(key_len) {
1737 case 4:
1738 if (0 == strncasecmp(key, "Date", key_len)) {
1739 con->parsed_response |= HTTP_DATE;
1741 break;
1742 case 6:
1743 if (0 == strncasecmp(key, "Status", key_len)) {
1744 int status = strtol(value, NULL, 10);
1745 if (status >= 100 && status < 1000) {
1746 con->http_status = status;
1747 con->parsed_response |= HTTP_STATUS;
1748 } else {
1749 con->http_status = 502;
1752 break;
1753 case 8:
1754 if (0 == strncasecmp(key, "Location", key_len)) {
1755 con->parsed_response |= HTTP_LOCATION;
1757 break;
1758 case 10:
1759 if (0 == strncasecmp(key, "Connection", key_len)) {
1760 con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
1761 con->parsed_response |= HTTP_CONNECTION;
1763 break;
1764 case 14:
1765 if (0 == strncasecmp(key, "Content-Length", key_len)) {
1766 con->response.content_length = strtoul(value, NULL, 10);
1767 con->parsed_response |= HTTP_CONTENT_LENGTH;
1769 break;
1770 default:
1771 break;
1776 /* CGI/1.1 rev 03 - 7.2.1.2 */
1777 if ((con->parsed_response & HTTP_LOCATION) &&
1778 !(con->parsed_response & HTTP_STATUS)) {
1779 con->http_status = 302;
1782 return 0;
1786 static int scgi_demux_response(server *srv, handler_ctx *hctx) {
1787 plugin_data *p = hctx->plugin_data;
1788 connection *con = hctx->remote_conn;
1790 while(1) {
1791 int n;
1793 buffer_string_prepare_copy(hctx->response, 1023);
1794 if (-1 == (n = read(hctx->fd, hctx->response->ptr, hctx->response->size - 1))) {
1795 if (errno == EAGAIN || errno == EINTR) {
1796 /* would block, wait for signal */
1797 return 0;
1799 /* error */
1800 log_error_write(srv, __FILE__, __LINE__, "sdd", strerror(errno), con->fd, hctx->fd);
1801 return -1;
1804 if (n == 0) {
1805 /* read finished */
1807 con->file_finished = 1;
1809 /* send final chunk */
1810 http_chunk_close(srv, con);
1811 joblist_append(srv, con);
1813 return 1;
1816 buffer_commit(hctx->response, n);
1818 /* split header from body */
1820 if (con->file_started == 0) {
1821 char *c;
1822 int in_header = 0;
1823 int header_end = 0;
1824 int cp, eol = EOL_UNSET;
1825 size_t used = 0;
1826 size_t hlen = 0;
1828 buffer_append_string_buffer(hctx->response_header, hctx->response);
1830 /* nph (non-parsed headers) */
1831 if (0 == strncmp(hctx->response_header->ptr, "HTTP/1.", 7)) in_header = 1;
1833 /* search for the \r\n\r\n or \n\n in the string */
1834 for (c = hctx->response_header->ptr, cp = 0, used = buffer_string_length(hctx->response_header); used; c++, cp++, used--) {
1835 if (*c == ':') in_header = 1;
1836 else if (*c == '\n') {
1837 if (in_header == 0) {
1838 /* got a response without a response header */
1840 c = NULL;
1841 header_end = 1;
1842 break;
1845 if (eol == EOL_UNSET) eol = EOL_N;
1847 if (*(c+1) == '\n') {
1848 header_end = 1;
1849 hlen = cp + 2;
1850 break;
1853 } else if (used > 1 && *c == '\r' && *(c+1) == '\n') {
1854 if (in_header == 0) {
1855 /* got a response without a response header */
1857 c = NULL;
1858 header_end = 1;
1859 break;
1862 if (eol == EOL_UNSET) eol = EOL_RN;
1864 if (used > 3 &&
1865 *(c+2) == '\r' &&
1866 *(c+3) == '\n') {
1867 header_end = 1;
1868 hlen = cp + 4;
1869 break;
1872 /* skip the \n */
1873 c++;
1874 cp++;
1875 used--;
1879 if (header_end) {
1880 if (c == NULL) {
1881 /* no header, but a body */
1883 if (con->request.http_version == HTTP_VERSION_1_1) {
1884 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
1887 http_chunk_append_buffer(srv, con, hctx->response_header);
1888 joblist_append(srv, con);
1889 } else {
1890 size_t blen = buffer_string_length(hctx->response_header) - hlen;
1892 /* a small hack: terminate after at the second \r */
1893 buffer_string_set_length(hctx->response_header, hlen - 1);
1895 /* parse the response header */
1896 scgi_response_parse(srv, con, p, hctx->response_header, eol);
1898 /* enable chunked-transfer-encoding */
1899 if (con->request.http_version == HTTP_VERSION_1_1 &&
1900 !(con->parsed_response & HTTP_CONTENT_LENGTH)) {
1901 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
1904 if (blen > 0) {
1905 http_chunk_append_mem(srv, con, hctx->response_header->ptr + hlen, blen);
1906 joblist_append(srv, con);
1910 con->file_started = 1;
1912 } else {
1913 http_chunk_append_buffer(srv, con, hctx->response);
1914 joblist_append(srv, con);
1917 #if 0
1918 log_error_write(srv, __FILE__, __LINE__, "ddss", con->fd, hctx->fd, connection_get_state(con->state), b->ptr);
1919 #endif
1922 return 0;
1926 static int scgi_proclist_sort_up(server *srv, scgi_extension_host *host, scgi_proc *proc) {
1927 scgi_proc *p;
1929 UNUSED(srv);
1931 /* we have been the smallest of the current list
1932 * and we want to insert the node sorted as soon
1933 * possible
1935 * 1 0 0 0 1 1 1
1936 * | ^
1937 * | |
1938 * +------+
1942 /* nothing to sort, only one element */
1943 if (host->first == proc && proc->next == NULL) return 0;
1945 for (p = proc; p->next && p->next->load < proc->load; p = p->next);
1947 /* no need to move something
1949 * 1 2 2 2 3 3 3
1955 if (p == proc) return 0;
1957 if (host->first == proc) {
1958 /* we have been the first elememt */
1960 host->first = proc->next;
1961 host->first->prev = NULL;
1964 /* disconnect proc */
1966 if (proc->prev) proc->prev->next = proc->next;
1967 if (proc->next) proc->next->prev = proc->prev;
1969 /* proc should be right of p */
1971 proc->next = p->next;
1972 proc->prev = p;
1973 if (p->next) p->next->prev = proc;
1974 p->next = proc;
1975 #if 0
1976 for(p = host->first; p; p = p->next) {
1977 log_error_write(srv, __FILE__, __LINE__, "dd",
1978 p->pid, p->load);
1980 #else
1981 UNUSED(srv);
1982 #endif
1984 return 0;
1987 int scgi_proclist_sort_down(server *srv, scgi_extension_host *host, scgi_proc *proc) {
1988 scgi_proc *p;
1990 UNUSED(srv);
1992 /* we have been the smallest of the current list
1993 * and we want to insert the node sorted as soon
1994 * possible
1996 * 0 0 0 0 1 0 1
1997 * ^ |
1998 * | |
1999 * +----------+
2002 * the basic is idea is:
2003 * - the last active scgi process should be still
2004 * in ram and is not swapped out yet
2005 * - processes that are not reused will be killed
2006 * after some time by the trigger-handler
2007 * - remember it as:
2008 * everything > 0 is hot
2009 * all unused procs are colder the more right they are
2010 * ice-cold processes are propably unused since more
2011 * than 'unused-timeout', are swaped out and won't be
2012 * reused in the next seconds anyway.
2016 /* nothing to sort, only one element */
2017 if (host->first == proc && proc->next == NULL) return 0;
2019 for (p = host->first; p != proc && p->load < proc->load; p = p->next);
2022 /* no need to move something
2024 * 1 2 2 2 3 3 3
2030 if (p == proc) return 0;
2032 /* we have to move left. If we are already the first element
2033 * we are done */
2034 if (host->first == proc) return 0;
2036 /* release proc */
2037 if (proc->prev) proc->prev->next = proc->next;
2038 if (proc->next) proc->next->prev = proc->prev;
2040 /* proc should be left of p */
2041 proc->next = p;
2042 proc->prev = p->prev;
2043 if (p->prev) p->prev->next = proc;
2044 p->prev = proc;
2046 if (proc->prev == NULL) host->first = proc;
2047 #if 0
2048 for(p = host->first; p; p = p->next) {
2049 log_error_write(srv, __FILE__, __LINE__, "dd",
2050 p->pid, p->load);
2052 #else
2053 UNUSED(srv);
2054 #endif
2056 return 0;
2059 static int scgi_restart_dead_procs(server *srv, plugin_data *p, scgi_extension_host *host) {
2060 scgi_proc *proc;
2062 for (proc = host->first; proc; proc = proc->next) {
2063 if (p->conf.debug) {
2064 log_error_write(srv, __FILE__, __LINE__, "sbdbdddd",
2065 "proc:",
2066 host->host, proc->port,
2067 proc->socket,
2068 proc->state,
2069 proc->is_local,
2070 proc->load,
2071 proc->pid);
2074 if (0 == proc->is_local) {
2076 * external servers might get disabled
2078 * enable the server again, perhaps it is back again
2081 if ((proc->state == PROC_STATE_DISABLED) &&
2082 (srv->cur_ts - proc->disable_ts > host->disable_time)) {
2083 proc->state = PROC_STATE_RUNNING;
2084 host->active_procs++;
2086 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2087 "fcgi-server re-enabled:",
2088 host->host, host->port,
2089 host->unixsocket);
2091 } else {
2092 /* the child should not terminate at all */
2093 int status;
2095 if (proc->state == PROC_STATE_DIED_WAIT_FOR_PID) {
2096 switch(waitpid(proc->pid, &status, WNOHANG)) {
2097 case 0:
2098 /* child is still alive */
2099 break;
2100 case -1:
2101 break;
2102 default:
2103 if (WIFEXITED(status)) {
2104 #if 0
2105 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2106 "child exited, pid:", proc->pid,
2107 "status:", WEXITSTATUS(status));
2108 #endif
2109 } else if (WIFSIGNALED(status)) {
2110 log_error_write(srv, __FILE__, __LINE__, "sd",
2111 "child signaled:",
2112 WTERMSIG(status));
2113 } else {
2114 log_error_write(srv, __FILE__, __LINE__, "sd",
2115 "child died somehow:",
2116 status);
2119 proc->state = PROC_STATE_DIED;
2120 break;
2125 * local servers might died, but we restart them
2128 if (proc->state == PROC_STATE_DIED &&
2129 proc->load == 0) {
2130 /* restart the child */
2132 if (p->conf.debug) {
2133 log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
2134 "--- scgi spawning",
2135 "\n\tport:", host->port,
2136 "\n\tsocket", host->unixsocket,
2137 "\n\tcurrent:", 1, "/", host->min_procs);
2140 if (scgi_spawn_connection(srv, p, host, proc)) {
2141 log_error_write(srv, __FILE__, __LINE__, "s",
2142 "ERROR: spawning fcgi failed.");
2143 return HANDLER_ERROR;
2146 scgi_proclist_sort_down(srv, host, proc);
2151 return 0;
2155 static handler_t scgi_write_request(server *srv, handler_ctx *hctx) {
2156 plugin_data *p = hctx->plugin_data;
2157 scgi_extension_host *host= hctx->host;
2158 connection *con = hctx->remote_conn;
2160 int ret;
2162 /* sanity check */
2163 if (!host) {
2164 log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: host = NULL");
2165 return HANDLER_ERROR;
2167 if (((buffer_string_is_empty(host->host) || !host->port) && buffer_string_is_empty(host->unixsocket))) {
2168 log_error_write(srv, __FILE__, __LINE__, "sxddd",
2169 "write-req: error",
2170 host,
2171 buffer_string_length(host->host),
2172 host->port,
2173 buffer_string_length(host->unixsocket));
2174 return HANDLER_ERROR;
2178 switch(hctx->state) {
2179 case FCGI_STATE_INIT:
2180 ret = buffer_string_is_empty(host->unixsocket) ? AF_INET : AF_UNIX;
2182 if (-1 == (hctx->fd = socket(ret, SOCK_STREAM, 0))) {
2183 if (errno == EMFILE ||
2184 errno == EINTR) {
2185 log_error_write(srv, __FILE__, __LINE__, "sd",
2186 "wait for fd at connection:", con->fd);
2188 return HANDLER_WAIT_FOR_FD;
2191 log_error_write(srv, __FILE__, __LINE__, "ssdd",
2192 "socket failed:", strerror(errno), srv->cur_fds, srv->max_fds);
2193 return HANDLER_ERROR;
2195 hctx->fde_ndx = -1;
2197 srv->cur_fds++;
2199 fdevent_register(srv->ev, hctx->fd, scgi_handle_fdevent, hctx);
2201 if (-1 == fdevent_fcntl_set(srv->ev, hctx->fd)) {
2202 log_error_write(srv, __FILE__, __LINE__, "ss",
2203 "fcntl failed: ", strerror(errno));
2205 return HANDLER_ERROR;
2208 /* fall through */
2209 case FCGI_STATE_CONNECT:
2210 if (hctx->state == FCGI_STATE_INIT) {
2211 for (hctx->proc = hctx->host->first;
2212 hctx->proc && hctx->proc->state != PROC_STATE_RUNNING;
2213 hctx->proc = hctx->proc->next);
2215 /* all childs are dead */
2216 if (hctx->proc == NULL) {
2217 hctx->fde_ndx = -1;
2219 return HANDLER_ERROR;
2222 if (hctx->proc->is_local) {
2223 hctx->pid = hctx->proc->pid;
2226 switch (scgi_establish_connection(srv, hctx)) {
2227 case 1:
2228 scgi_set_state(srv, hctx, FCGI_STATE_CONNECT);
2230 /* connection is in progress, wait for an event and call getsockopt() below */
2232 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2234 return HANDLER_WAIT_FOR_EVENT;
2235 case -1:
2236 /* if ECONNREFUSED choose another connection -> FIXME */
2237 hctx->fde_ndx = -1;
2239 return HANDLER_ERROR;
2240 default:
2241 /* everything is ok, go on */
2242 break;
2246 } else {
2247 int socket_error;
2248 socklen_t socket_error_len = sizeof(socket_error);
2250 /* try to finish the connect() */
2251 if (0 != getsockopt(hctx->fd, SOL_SOCKET, SO_ERROR, &socket_error, &socket_error_len)) {
2252 log_error_write(srv, __FILE__, __LINE__, "ss",
2253 "getsockopt failed:", strerror(errno));
2255 return HANDLER_ERROR;
2257 if (socket_error != 0) {
2258 if (!hctx->proc->is_local || p->conf.debug) {
2259 /* local procs get restarted */
2261 log_error_write(srv, __FILE__, __LINE__, "ss",
2262 "establishing connection failed:", strerror(socket_error),
2263 "port:", hctx->proc->port);
2266 return HANDLER_ERROR;
2270 /* ok, we have the connection */
2272 hctx->proc->load++;
2273 hctx->proc->last_used = srv->cur_ts;
2274 hctx->got_proc = 1;
2276 if (p->conf.debug) {
2277 log_error_write(srv, __FILE__, __LINE__, "sddbdd",
2278 "got proc:",
2279 hctx->fd,
2280 hctx->proc->pid,
2281 hctx->proc->socket,
2282 hctx->proc->port,
2283 hctx->proc->load);
2286 /* move the proc-list entry down the list */
2287 scgi_proclist_sort_up(srv, hctx->host, hctx->proc);
2289 scgi_set_state(srv, hctx, FCGI_STATE_PREPARE_WRITE);
2290 /* fall through */
2291 case FCGI_STATE_PREPARE_WRITE:
2292 scgi_create_env(srv, hctx);
2294 scgi_set_state(srv, hctx, FCGI_STATE_WRITE);
2296 /* fall through */
2297 case FCGI_STATE_WRITE:
2298 ret = srv->network_backend_write(srv, con, hctx->fd, hctx->wb, MAX_WRITE_LIMIT);
2300 chunkqueue_remove_finished_chunks(hctx->wb);
2302 if (ret < 0) {
2303 if (errno == ENOTCONN || ret == -2) {
2304 /* the connection got dropped after accept()
2306 * this is most of the time a PHP which dies
2307 * after PHP_FCGI_MAX_REQUESTS
2310 if (hctx->wb->bytes_out == 0 &&
2311 hctx->reconnects < 5) {
2312 usleep(10000); /* take away the load of the webserver
2313 * to let the php a chance to restart
2316 scgi_reconnect(srv, hctx);
2318 return HANDLER_WAIT_FOR_FD;
2321 /* not reconnected ... why
2323 * far@#lighttpd report this for FreeBSD
2327 log_error_write(srv, __FILE__, __LINE__, "ssosd",
2328 "connection was dropped after accept(). reconnect() denied:",
2329 "write-offset:", hctx->wb->bytes_out,
2330 "reconnect attempts:", hctx->reconnects);
2332 return HANDLER_ERROR;
2333 } else {
2334 /* -1 == ret => error on our side */
2335 log_error_write(srv, __FILE__, __LINE__, "ssd",
2336 "write failed:", strerror(errno), errno);
2338 return HANDLER_ERROR;
2342 if (hctx->wb->bytes_out == hctx->wb->bytes_in) {
2343 /* we don't need the out event anymore */
2344 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
2345 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2346 scgi_set_state(srv, hctx, FCGI_STATE_READ);
2347 } else {
2348 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2350 return HANDLER_WAIT_FOR_EVENT;
2353 break;
2354 case FCGI_STATE_READ:
2355 /* waiting for a response */
2356 break;
2357 default:
2358 log_error_write(srv, __FILE__, __LINE__, "s", "(debug) unknown state");
2359 return HANDLER_ERROR;
2362 return HANDLER_WAIT_FOR_EVENT;
2365 SUBREQUEST_FUNC(mod_scgi_handle_subrequest) {
2366 plugin_data *p = p_d;
2368 handler_ctx *hctx = con->plugin_ctx[p->id];
2369 scgi_proc *proc;
2370 scgi_extension_host *host;
2372 if (NULL == hctx) return HANDLER_GO_ON;
2374 /* not my job */
2375 if (con->mode != p->id) return HANDLER_GO_ON;
2377 /* ok, create the request */
2378 switch(scgi_write_request(srv, hctx)) {
2379 case HANDLER_ERROR:
2380 proc = hctx->proc;
2381 host = hctx->host;
2383 if (proc &&
2384 0 == proc->is_local &&
2385 proc->state != PROC_STATE_DISABLED) {
2386 /* only disable remote servers as we don't manage them*/
2388 log_error_write(srv, __FILE__, __LINE__, "sbdb", "fcgi-server disabled:",
2389 host->host,
2390 proc->port,
2391 proc->socket);
2393 /* disable this server */
2394 proc->disable_ts = srv->cur_ts;
2395 proc->state = PROC_STATE_DISABLED;
2396 host->active_procs--;
2399 if (hctx->state == FCGI_STATE_INIT ||
2400 hctx->state == FCGI_STATE_CONNECT) {
2401 /* connect() or getsockopt() failed,
2402 * restart the request-handling
2404 if (proc && proc->is_local) {
2406 if (p->conf.debug) {
2407 log_error_write(srv, __FILE__, __LINE__, "sbdb", "connect() to scgi failed, restarting the request-handling:",
2408 host->host,
2409 proc->port,
2410 proc->socket);
2414 * several hctx might reference the same proc
2416 * Only one of them should mark the proc as dead all the other
2417 * ones should just take a new one.
2419 * If a new proc was started with the old struct this might lead
2420 * the mark a perfect proc as dead otherwise
2423 if (proc->state == PROC_STATE_RUNNING &&
2424 hctx->pid == proc->pid) {
2425 proc->state = PROC_STATE_DIED_WAIT_FOR_PID;
2428 scgi_restart_dead_procs(srv, p, host);
2430 scgi_connection_cleanup(srv, hctx);
2432 buffer_reset(con->physical.path);
2433 con->mode = DIRECT;
2434 joblist_append(srv, con);
2436 /* mis-using HANDLER_WAIT_FOR_FD to break out of the loop
2437 * and hope that the childs will be restarted
2440 return HANDLER_WAIT_FOR_FD;
2441 } else {
2442 scgi_connection_cleanup(srv, hctx);
2444 buffer_reset(con->physical.path);
2445 con->mode = DIRECT;
2446 con->http_status = 503;
2448 return HANDLER_FINISHED;
2450 case HANDLER_WAIT_FOR_EVENT:
2451 if (con->file_started == 1) {
2452 return HANDLER_FINISHED;
2453 } else {
2454 return HANDLER_WAIT_FOR_EVENT;
2456 case HANDLER_WAIT_FOR_FD:
2457 return HANDLER_WAIT_FOR_FD;
2458 default:
2459 log_error_write(srv, __FILE__, __LINE__, "s", "subrequest write-req default");
2460 return HANDLER_ERROR;
2464 static handler_t scgi_connection_close(server *srv, handler_ctx *hctx) {
2465 connection *con;
2467 if (NULL == hctx) return HANDLER_GO_ON;
2469 con = hctx->remote_conn;
2471 log_error_write(srv, __FILE__, __LINE__, "ssdsd",
2472 "emergency exit: scgi:",
2473 "connection-fd:", con->fd,
2474 "fcgi-fd:", hctx->fd);
2476 scgi_connection_cleanup(srv, hctx);
2478 return HANDLER_FINISHED;
2482 static handler_t scgi_handle_fdevent(server *srv, void *ctx, int revents) {
2483 handler_ctx *hctx = ctx;
2484 connection *con = hctx->remote_conn;
2485 plugin_data *p = hctx->plugin_data;
2487 scgi_proc *proc = hctx->proc;
2488 scgi_extension_host *host= hctx->host;
2490 if ((revents & FDEVENT_IN) &&
2491 hctx->state == FCGI_STATE_READ) {
2492 switch (scgi_demux_response(srv, hctx)) {
2493 case 0:
2494 break;
2495 case 1:
2496 /* we are done */
2497 scgi_connection_cleanup(srv, hctx);
2499 joblist_append(srv, con);
2500 return HANDLER_FINISHED;
2501 case -1:
2502 if (proc->pid && proc->state != PROC_STATE_DIED) {
2503 int status;
2505 /* only fetch the zombie if it is not already done */
2507 switch(waitpid(proc->pid, &status, WNOHANG)) {
2508 case 0:
2509 /* child is still alive */
2510 break;
2511 case -1:
2512 break;
2513 default:
2514 /* the child should not terminate at all */
2515 if (WIFEXITED(status)) {
2516 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2517 "child exited, pid:", proc->pid,
2518 "status:", WEXITSTATUS(status));
2519 } else if (WIFSIGNALED(status)) {
2520 log_error_write(srv, __FILE__, __LINE__, "sd",
2521 "child signaled:",
2522 WTERMSIG(status));
2523 } else {
2524 log_error_write(srv, __FILE__, __LINE__, "sd",
2525 "child died somehow:",
2526 status);
2529 if (p->conf.debug) {
2530 log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
2531 "--- scgi spawning",
2532 "\n\tport:", host->port,
2533 "\n\tsocket", host->unixsocket,
2534 "\n\tcurrent:", 1, "/", host->min_procs);
2537 if (scgi_spawn_connection(srv, p, host, proc)) {
2538 /* child died */
2539 proc->state = PROC_STATE_DIED;
2540 } else {
2541 scgi_proclist_sort_down(srv, host, proc);
2544 break;
2548 if (con->file_started == 0) {
2549 /* nothing has been send out yet, try to use another child */
2551 if (hctx->wb->bytes_out == 0 &&
2552 hctx->reconnects < 5) {
2553 scgi_reconnect(srv, hctx);
2555 log_error_write(srv, __FILE__, __LINE__, "ssdsd",
2556 "response not sent, request not sent, reconnection.",
2557 "connection-fd:", con->fd,
2558 "fcgi-fd:", hctx->fd);
2560 return HANDLER_WAIT_FOR_FD;
2563 log_error_write(srv, __FILE__, __LINE__, "sosdsd",
2564 "response not sent, request sent:", hctx->wb->bytes_out,
2565 "connection-fd:", con->fd,
2566 "fcgi-fd:", hctx->fd);
2568 scgi_connection_cleanup(srv, hctx);
2570 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
2571 buffer_reset(con->physical.path);
2572 con->http_status = 500;
2573 con->mode = DIRECT;
2574 } else {
2575 /* response might have been already started, kill the connection */
2576 log_error_write(srv, __FILE__, __LINE__, "ssdsd",
2577 "response already sent out, termination connection",
2578 "connection-fd:", con->fd,
2579 "fcgi-fd:", hctx->fd);
2581 scgi_connection_cleanup(srv, hctx);
2583 connection_set_state(srv, con, CON_STATE_ERROR);
2586 /* */
2589 joblist_append(srv, con);
2590 return HANDLER_FINISHED;
2594 if (revents & FDEVENT_OUT) {
2595 if (hctx->state == FCGI_STATE_CONNECT ||
2596 hctx->state == FCGI_STATE_WRITE) {
2597 /* we are allowed to send something out
2599 * 1. in a unfinished connect() call
2600 * 2. in a unfinished write() call (long POST request)
2602 return mod_scgi_handle_subrequest(srv, con, p);
2603 } else {
2604 log_error_write(srv, __FILE__, __LINE__, "sd",
2605 "got a FDEVENT_OUT and didn't know why:",
2606 hctx->state);
2610 /* perhaps this issue is already handled */
2611 if (revents & FDEVENT_HUP) {
2612 if (hctx->state == FCGI_STATE_CONNECT) {
2613 /* getoptsock will catch this one (right ?)
2615 * if we are in connect we might get a EINPROGRESS
2616 * in the first call and a FDEVENT_HUP in the
2617 * second round
2619 * FIXME: as it is a bit ugly.
2622 return mod_scgi_handle_subrequest(srv, con, p);
2623 } else if (hctx->state == FCGI_STATE_READ &&
2624 hctx->proc->port == 0) {
2625 /* FIXME:
2627 * ioctl says 8192 bytes to read from PHP and we receive directly a HUP for the socket
2628 * even if the FCGI_FIN packet is not received yet
2630 } else {
2631 log_error_write(srv, __FILE__, __LINE__, "sbSBSDSd",
2632 "error: unexpected close of scgi connection for",
2633 con->uri.path,
2634 "(no scgi process on host: ",
2635 host->host,
2636 ", port: ",
2637 host->port,
2638 " ?)",
2639 hctx->state);
2641 connection_set_state(srv, con, CON_STATE_ERROR);
2642 scgi_connection_close(srv, hctx);
2643 joblist_append(srv, con);
2645 } else if (revents & FDEVENT_ERR) {
2646 log_error_write(srv, __FILE__, __LINE__, "s",
2647 "fcgi: got a FDEVENT_ERR. Don't know why.");
2648 /* kill all connections to the scgi process */
2651 connection_set_state(srv, con, CON_STATE_ERROR);
2652 scgi_connection_close(srv, hctx);
2653 joblist_append(srv, con);
2656 return HANDLER_FINISHED;
2658 #define PATCH(x) \
2659 p->conf.x = s->x;
2660 static int scgi_patch_connection(server *srv, connection *con, plugin_data *p) {
2661 size_t i, j;
2662 plugin_config *s = p->config_storage[0];
2664 PATCH(exts);
2665 PATCH(debug);
2667 /* skip the first, the global context */
2668 for (i = 1; i < srv->config_context->used; i++) {
2669 data_config *dc = (data_config *)srv->config_context->data[i];
2670 s = p->config_storage[i];
2672 /* condition didn't match */
2673 if (!config_check_cond(srv, con, dc)) continue;
2675 /* merge config */
2676 for (j = 0; j < dc->value->used; j++) {
2677 data_unset *du = dc->value->data[j];
2679 if (buffer_is_equal_string(du->key, CONST_STR_LEN("scgi.server"))) {
2680 PATCH(exts);
2681 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("scgi.debug"))) {
2682 PATCH(debug);
2687 return 0;
2689 #undef PATCH
2692 static handler_t scgi_check_extension(server *srv, connection *con, void *p_d, int uri_path_handler) {
2693 plugin_data *p = p_d;
2694 size_t s_len;
2695 int used = -1;
2696 size_t k;
2697 buffer *fn;
2698 scgi_extension *extension = NULL;
2699 scgi_extension_host *host = NULL;
2701 if (con->mode != DIRECT) return HANDLER_GO_ON;
2703 /* Possibly, we processed already this request */
2704 if (con->file_started == 1) return HANDLER_GO_ON;
2706 fn = uri_path_handler ? con->uri.path : con->physical.path;
2708 if (buffer_string_is_empty(fn)) return HANDLER_GO_ON;
2710 s_len = buffer_string_length(fn);
2712 scgi_patch_connection(srv, con, p);
2714 /* check if extension matches */
2715 for (k = 0; k < p->conf.exts->used; k++) {
2716 size_t ct_len;
2717 scgi_extension *ext = p->conf.exts->exts[k];
2719 if (buffer_is_empty(ext->key)) continue;
2721 ct_len = buffer_string_length(ext->key);
2723 if (s_len < ct_len) continue;
2725 /* check extension in the form "/scgi_pattern" */
2726 if (*(ext->key->ptr) == '/') {
2727 if (strncmp(fn->ptr, ext->key->ptr, ct_len) == 0) {
2728 extension = ext;
2729 break;
2731 } else if (0 == strncmp(fn->ptr + s_len - ct_len, ext->key->ptr, ct_len)) {
2732 /* check extension in the form ".fcg" */
2733 extension = ext;
2734 break;
2738 /* extension doesn't match */
2739 if (NULL == extension) {
2740 return HANDLER_GO_ON;
2743 /* get best server */
2744 for (k = 0; k < extension->used; k++) {
2745 scgi_extension_host *h = extension->hosts[k];
2747 /* we should have at least one proc that can do something */
2748 if (h->active_procs == 0) {
2749 continue;
2752 if (used == -1 || h->load < used) {
2753 used = h->load;
2755 host = h;
2759 if (!host) {
2760 /* sorry, we don't have a server alive for this ext */
2761 buffer_reset(con->physical.path);
2762 con->http_status = 500;
2764 /* only send the 'no handler' once */
2765 if (!extension->note_is_sent) {
2766 extension->note_is_sent = 1;
2768 log_error_write(srv, __FILE__, __LINE__, "sbsbs",
2769 "all handlers for ", con->uri.path,
2770 "on", extension->key,
2771 "are down.");
2774 return HANDLER_FINISHED;
2777 /* a note about no handler is not sent yet */
2778 extension->note_is_sent = 0;
2781 * if check-local is disabled, use the uri.path handler
2785 /* init handler-context */
2786 if (uri_path_handler) {
2787 if (host->check_local == 0) {
2788 handler_ctx *hctx;
2789 char *pathinfo;
2791 hctx = handler_ctx_init();
2793 hctx->remote_conn = con;
2794 hctx->plugin_data = p;
2795 hctx->host = host;
2796 hctx->proc = NULL;
2798 hctx->conf.exts = p->conf.exts;
2799 hctx->conf.debug = p->conf.debug;
2801 con->plugin_ctx[p->id] = hctx;
2803 host->load++;
2805 con->mode = p->id;
2807 if (con->conf.log_request_handling) {
2808 log_error_write(srv, __FILE__, __LINE__, "s",
2809 "handling it in mod_scgi");
2812 /* the prefix is the SCRIPT_NAME,
2813 * everything from start to the next slash
2814 * this is important for check-local = "disable"
2816 * if prefix = /admin.fcgi
2818 * /admin.fcgi/foo/bar
2820 * SCRIPT_NAME = /admin.fcgi
2821 * PATH_INFO = /foo/bar
2823 * if prefix = /fcgi-bin/
2825 * /fcgi-bin/foo/bar
2827 * SCRIPT_NAME = /fcgi-bin/foo
2828 * PATH_INFO = /bar
2832 /* the rewrite is only done for /prefix/? matches */
2833 if (host->fix_root_path_name && extension->key->ptr[0] == '/' && extension->key->ptr[1] == '\0') {
2834 buffer_copy_string(con->request.pathinfo, con->uri.path->ptr);
2835 buffer_string_set_length(con->uri.path, 0);
2836 } else if (extension->key->ptr[0] == '/' &&
2837 buffer_string_length(con->uri.path) > buffer_string_length(extension->key) &&
2838 NULL != (pathinfo = strchr(con->uri.path->ptr + buffer_string_length(extension->key), '/'))) {
2839 /* rewrite uri.path and pathinfo */
2841 buffer_copy_string(con->request.pathinfo, pathinfo);
2842 buffer_string_set_length(con->uri.path, buffer_string_length(con->uri.path) - buffer_string_length(con->request.pathinfo));
2845 } else {
2846 handler_ctx *hctx;
2847 hctx = handler_ctx_init();
2849 hctx->remote_conn = con;
2850 hctx->plugin_data = p;
2851 hctx->host = host;
2852 hctx->proc = NULL;
2854 hctx->conf.exts = p->conf.exts;
2855 hctx->conf.debug = p->conf.debug;
2857 con->plugin_ctx[p->id] = hctx;
2859 host->load++;
2861 con->mode = p->id;
2863 if (con->conf.log_request_handling) {
2864 log_error_write(srv, __FILE__, __LINE__, "s", "handling it in mod_scgi");
2868 return HANDLER_GO_ON;
2871 /* uri-path handler */
2872 static handler_t scgi_check_extension_1(server *srv, connection *con, void *p_d) {
2873 return scgi_check_extension(srv, con, p_d, 1);
2876 /* start request handler */
2877 static handler_t scgi_check_extension_2(server *srv, connection *con, void *p_d) {
2878 return scgi_check_extension(srv, con, p_d, 0);
2881 JOBLIST_FUNC(mod_scgi_handle_joblist) {
2882 plugin_data *p = p_d;
2883 handler_ctx *hctx = con->plugin_ctx[p->id];
2885 if (hctx == NULL) return HANDLER_GO_ON;
2887 if (hctx->fd != -1) {
2888 switch (hctx->state) {
2889 case FCGI_STATE_READ:
2890 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2892 break;
2893 case FCGI_STATE_CONNECT:
2894 case FCGI_STATE_WRITE:
2895 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2897 break;
2898 case FCGI_STATE_INIT:
2899 /* at reconnect */
2900 break;
2901 default:
2902 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandled fcgi.state", hctx->state);
2903 break;
2907 return HANDLER_GO_ON;
2911 static handler_t scgi_connection_close_callback(server *srv, connection *con, void *p_d) {
2912 plugin_data *p = p_d;
2914 return scgi_connection_close(srv, con->plugin_ctx[p->id]);
2917 TRIGGER_FUNC(mod_scgi_handle_trigger) {
2918 plugin_data *p = p_d;
2919 size_t i, j, n;
2922 /* perhaps we should kill a connect attempt after 10-15 seconds
2924 * currently we wait for the TCP timeout which is on Linux 180 seconds
2930 /* check all childs if they are still up */
2932 for (i = 0; i < srv->config_context->used; i++) {
2933 plugin_config *conf;
2934 scgi_exts *exts;
2936 conf = p->config_storage[i];
2938 exts = conf->exts;
2940 for (j = 0; j < exts->used; j++) {
2941 scgi_extension *ex;
2943 ex = exts->exts[j];
2945 for (n = 0; n < ex->used; n++) {
2947 scgi_proc *proc;
2948 unsigned long sum_load = 0;
2949 scgi_extension_host *host;
2951 host = ex->hosts[n];
2953 scgi_restart_dead_procs(srv, p, host);
2955 for (proc = host->first; proc; proc = proc->next) {
2956 sum_load += proc->load;
2959 if (host->num_procs &&
2960 host->num_procs < host->max_procs &&
2961 (sum_load / host->num_procs) > host->max_load_per_proc) {
2962 /* overload, spawn new child */
2963 scgi_proc *fp = NULL;
2965 if (p->conf.debug) {
2966 log_error_write(srv, __FILE__, __LINE__, "s",
2967 "overload detected, spawning a new child");
2970 for (fp = host->unused_procs; fp && fp->pid != 0; fp = fp->next);
2972 if (fp) {
2973 if (fp == host->unused_procs) host->unused_procs = fp->next;
2975 if (fp->next) fp->next->prev = NULL;
2977 host->max_id++;
2978 } else {
2979 fp = scgi_process_init();
2980 fp->id = host->max_id++;
2983 host->num_procs++;
2985 if (buffer_string_is_empty(host->unixsocket)) {
2986 fp->port = host->port + fp->id;
2987 } else {
2988 buffer_copy_buffer(fp->socket, host->unixsocket);
2989 buffer_append_string_len(fp->socket, CONST_STR_LEN("-"));
2990 buffer_append_int(fp->socket, fp->id);
2993 if (scgi_spawn_connection(srv, p, host, fp)) {
2994 log_error_write(srv, __FILE__, __LINE__, "s",
2995 "ERROR: spawning fcgi failed.");
2996 scgi_process_free(fp);
2997 return HANDLER_ERROR;
3000 fp->prev = NULL;
3001 fp->next = host->first;
3002 if (host->first) {
3003 host->first->prev = fp;
3005 host->first = fp;
3008 for (proc = host->first; proc; proc = proc->next) {
3009 if (proc->load != 0) break;
3010 if (host->num_procs <= host->min_procs) break;
3011 if (proc->pid == 0) continue;
3013 if (srv->cur_ts - proc->last_used > host->idle_timeout) {
3014 /* a proc is idling for a long time now,
3015 * terminated it */
3017 if (p->conf.debug) {
3018 log_error_write(srv, __FILE__, __LINE__, "ssbsd",
3019 "idle-timeout reached, terminating child:",
3020 "socket:", proc->socket,
3021 "pid", proc->pid);
3025 if (proc->next) proc->next->prev = proc->prev;
3026 if (proc->prev) proc->prev->next = proc->next;
3028 if (proc->prev == NULL) host->first = proc->next;
3030 proc->prev = NULL;
3031 proc->next = host->unused_procs;
3033 if (host->unused_procs) host->unused_procs->prev = proc;
3034 host->unused_procs = proc;
3036 kill(proc->pid, SIGTERM);
3038 proc->state = PROC_STATE_KILLED;
3040 log_error_write(srv, __FILE__, __LINE__, "ssbsd",
3041 "killed:",
3042 "socket:", proc->socket,
3043 "pid", proc->pid);
3045 host->num_procs--;
3047 /* proc is now in unused, let the next second handle the next process */
3048 break;
3052 for (proc = host->unused_procs; proc; proc = proc->next) {
3053 int status;
3055 if (proc->pid == 0) continue;
3057 switch (waitpid(proc->pid, &status, WNOHANG)) {
3058 case 0:
3059 /* child still running after timeout, good */
3060 break;
3061 case -1:
3062 if (errno != EINTR) {
3063 /* no PID found ? should never happen */
3064 log_error_write(srv, __FILE__, __LINE__, "sddss",
3065 "pid ", proc->pid, proc->state,
3066 "not found:", strerror(errno));
3068 #if 0
3069 if (errno == ECHILD) {
3070 /* someone else has cleaned up for us */
3071 proc->pid = 0;
3072 proc->state = PROC_STATE_UNSET;
3074 #endif
3076 break;
3077 default:
3078 /* the child should not terminate at all */
3079 if (WIFEXITED(status)) {
3080 if (proc->state != PROC_STATE_KILLED) {
3081 log_error_write(srv, __FILE__, __LINE__, "sdb",
3082 "child exited:",
3083 WEXITSTATUS(status), proc->socket);
3085 } else if (WIFSIGNALED(status)) {
3086 if (WTERMSIG(status) != SIGTERM) {
3087 log_error_write(srv, __FILE__, __LINE__, "sd",
3088 "child signaled:",
3089 WTERMSIG(status));
3091 } else {
3092 log_error_write(srv, __FILE__, __LINE__, "sd",
3093 "child died somehow:",
3094 status);
3096 proc->pid = 0;
3097 proc->state = PROC_STATE_UNSET;
3098 host->max_id--;
3105 return HANDLER_GO_ON;
3109 int mod_scgi_plugin_init(plugin *p);
3110 int mod_scgi_plugin_init(plugin *p) {
3111 p->version = LIGHTTPD_VERSION_ID;
3112 p->name = buffer_init_string("scgi");
3114 p->init = mod_scgi_init;
3115 p->cleanup = mod_scgi_free;
3116 p->set_defaults = mod_scgi_set_defaults;
3117 p->connection_reset = scgi_connection_reset;
3118 p->handle_connection_close = scgi_connection_close_callback;
3119 p->handle_uri_clean = scgi_check_extension_1;
3120 p->handle_subrequest_start = scgi_check_extension_2;
3121 p->handle_subrequest = mod_scgi_handle_subrequest;
3122 p->handle_joblist = mod_scgi_handle_joblist;
3123 p->handle_trigger = mod_scgi_handle_trigger;
3125 p->data = NULL;
3127 return 0;