handlers can read response before sending req body (fixes #131, #2566)
[lighttpd.git] / src / mod_fastcgi.c
blobbdf0d0bd07d878463e940d5ec23be05f7094c8b7
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"
17 #include "stat_cache.h"
18 #include "status_counter.h"
20 #include <sys/types.h>
21 #include <unistd.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
27 #include <assert.h>
28 #include <signal.h>
30 #ifdef HAVE_FASTCGI_FASTCGI_H
31 # include <fastcgi/fastcgi.h>
32 #else
33 # ifdef HAVE_FASTCGI_H
34 # include <fastcgi.h>
35 # else
36 # include "fastcgi.h"
37 # endif
38 #endif /* HAVE_FASTCGI_FASTCGI_H */
40 #include <stdio.h>
42 #include "sys-socket.h"
44 #ifdef HAVE_SYS_UIO_H
45 #include <sys/uio.h>
46 #endif
47 #ifdef HAVE_SYS_WAIT_H
48 #include <sys/wait.h>
49 #endif
51 #include "version.h"
55 * TODO:
57 * - add timeout for a connect to a non-fastcgi process
58 * (use state_timestamp + state)
62 typedef struct fcgi_proc {
63 size_t id; /* id will be between 1 and max_procs */
64 buffer *unixsocket; /* config.socket + "-" + id */
65 unsigned port; /* config.port + pno */
67 buffer *connection_name; /* either tcp:<host>:<port> or unix:<socket> for debugging purposes */
69 pid_t pid; /* PID of the spawned process (0 if not spawned locally) */
72 size_t load; /* number of requests waiting on this process */
74 size_t requests; /* see max_requests */
75 struct fcgi_proc *prev, *next; /* see first */
77 time_t disabled_until; /* this proc is disabled until, use something else until then */
79 int is_local;
81 enum {
82 PROC_STATE_UNSET, /* init-phase */
83 PROC_STATE_RUNNING, /* alive */
84 PROC_STATE_OVERLOADED, /* listen-queue is full,
85 don't send anything to this proc for the next 2 seconds */
86 PROC_STATE_DIED_WAIT_FOR_PID, /* */
87 PROC_STATE_DIED, /* marked as dead, should be restarted */
88 PROC_STATE_KILLED /* was killed as we don't have the load anymore */
89 } state;
90 } fcgi_proc;
92 typedef struct {
93 /* the key that is used to reference this value */
94 buffer *id;
96 /* list of processes handling this extension
97 * sorted by lowest load
99 * whenever a job is done move it up in the list
100 * until it is sorted, move it down as soon as the
101 * job is started
103 fcgi_proc *first;
104 fcgi_proc *unused_procs;
107 * spawn at least min_procs, at max_procs.
109 * as soon as the load of the first entry
110 * is max_load_per_proc we spawn a new one
111 * and add it to the first entry and give it
112 * the load
116 unsigned short max_procs;
117 size_t num_procs; /* how many procs are started */
118 size_t active_procs; /* how many of them are really running, i.e. state = PROC_STATE_RUNNING */
121 * time after a disabled remote connection is tried to be re-enabled
126 unsigned short disable_time;
129 * some fastcgi processes get a little bit larger
130 * than wanted. max_requests_per_proc kills a
131 * process after a number of handled requests.
134 size_t max_requests_per_proc;
137 /* config */
140 * host:port
142 * if host is one of the local IP adresses the
143 * whole connection is local
145 * if port is not 0, and host is not specified,
146 * "localhost" (INADDR_LOOPBACK) is assumed.
149 buffer *host;
150 unsigned short port;
153 * Unix Domain Socket
155 * instead of TCP/IP we can use Unix Domain Sockets
156 * - more secure (you have fileperms to play with)
157 * - more control (on locally)
158 * - more speed (no extra overhead)
160 buffer *unixsocket;
162 /* if socket is local we can start the fastcgi
163 * process ourself
165 * bin-path is the path to the binary
167 * check min_procs and max_procs for the number
168 * of process to start up
170 buffer *bin_path;
172 /* bin-path is set bin-environment is taken to
173 * create the environement before starting the
174 * FastCGI process
177 array *bin_env;
179 array *bin_env_copy;
182 * docroot-translation between URL->phys and the
183 * remote host
185 * reasons:
186 * - different dir-layout if remote
187 * - chroot if local
190 buffer *docroot;
193 * fastcgi-mode:
194 * - responser
195 * - authorizer
198 unsigned short mode;
201 * check_local tells you if the phys file is stat()ed
202 * or not. FastCGI doesn't care if the service is
203 * remote. If the web-server side doesn't contain
204 * the fastcgi-files we should not stat() for them
205 * and say '404 not found'.
207 unsigned short check_local;
210 * append PATH_INFO to SCRIPT_FILENAME
212 * php needs this if cgi.fix_pathinfo is provided
216 unsigned short break_scriptfilename_for_php;
219 * workaround for program when prefix="/"
221 * rule to build PATH_INFO is hardcoded for when check_local is disabled
222 * enable this option to use the workaround
226 unsigned short fix_root_path_name;
229 * If the backend includes X-LIGHTTPD-send-file in the response
230 * we use the value as filename and ignore the content.
233 unsigned short allow_xsendfile;
235 ssize_t load; /* replace by host->load */
237 size_t max_id; /* corresponds most of the time to
238 num_procs.
240 only if a process is killed max_id waits for the process itself
241 to die and decrements it afterwards */
243 buffer *strip_request_uri;
245 unsigned short kill_signal; /* we need a setting for this as libfcgi
246 applications prefer SIGUSR1 while the
247 rest of the world would use SIGTERM
248 *sigh* */
250 int listen_backlog;
251 } fcgi_extension_host;
254 * one extension can have multiple hosts assigned
255 * one host can spawn additional processes on the same
256 * socket (if we control it)
258 * ext -> host -> procs
259 * 1:n 1:n
261 * if the fastcgi process is remote that whole goes down
262 * to
264 * ext -> host -> procs
265 * 1:n 1:1
267 * in case of PHP and FCGI_CHILDREN we have again a procs
268 * but we don't control it directly.
272 typedef struct {
273 buffer *key; /* like .php */
275 int note_is_sent;
276 int last_used_ndx;
278 fcgi_extension_host **hosts;
280 size_t used;
281 size_t size;
282 } fcgi_extension;
284 typedef struct {
285 fcgi_extension **exts;
287 size_t used;
288 size_t size;
289 } fcgi_exts;
292 typedef struct {
293 fcgi_exts *exts;
295 array *ext_mapping;
297 unsigned int debug;
298 } plugin_config;
300 typedef struct {
301 char **ptr;
303 size_t size;
304 size_t used;
305 } char_array;
307 /* generic plugin data, shared between all connections */
308 typedef struct {
309 PLUGIN_DATA;
311 buffer *fcgi_env;
313 buffer *path;
315 buffer *statuskey;
317 plugin_config **config_storage;
319 plugin_config conf; /* this is only used as long as no handler_ctx is setup */
320 } plugin_data;
322 /* connection specific data */
323 typedef enum {
324 FCGI_STATE_INIT,
325 FCGI_STATE_CONNECT_DELAYED,
326 FCGI_STATE_PREPARE_WRITE,
327 FCGI_STATE_WRITE,
328 FCGI_STATE_READ
329 } fcgi_connection_state_t;
331 typedef struct {
332 fcgi_proc *proc;
333 fcgi_extension_host *host;
334 fcgi_extension *ext;
336 fcgi_connection_state_t state;
337 time_t state_timestamp;
339 int reconnects; /* number of reconnect attempts */
341 chunkqueue *rb; /* read queue */
342 chunkqueue *wb; /* write queue */
344 buffer *response_header;
346 size_t request_id;
347 int fd; /* fd to the fastcgi process */
348 int fde_ndx; /* index into the fd-event buffer */
350 pid_t pid;
351 int got_proc;
353 int send_content_body;
355 plugin_config conf;
357 connection *remote_conn; /* dumb pointer */
358 plugin_data *plugin_data; /* dumb pointer */
359 } handler_ctx;
362 /* ok, we need a prototype */
363 static handler_t fcgi_handle_fdevent(server *srv, void *ctx, int revents);
365 static void reset_signals(void) {
366 #ifdef SIGTTOU
367 signal(SIGTTOU, SIG_DFL);
368 #endif
369 #ifdef SIGTTIN
370 signal(SIGTTIN, SIG_DFL);
371 #endif
372 #ifdef SIGTSTP
373 signal(SIGTSTP, SIG_DFL);
374 #endif
375 signal(SIGHUP, SIG_DFL);
376 signal(SIGPIPE, SIG_DFL);
377 signal(SIGUSR1, SIG_DFL);
380 static void fastcgi_status_copy_procname(buffer *b, fcgi_extension_host *host, fcgi_proc *proc) {
381 buffer_copy_string_len(b, CONST_STR_LEN("fastcgi.backend."));
382 buffer_append_string_buffer(b, host->id);
383 if (proc) {
384 buffer_append_string_len(b, CONST_STR_LEN("."));
385 buffer_append_int(b, proc->id);
389 static void fcgi_proc_load_inc(server *srv, handler_ctx *hctx) {
390 plugin_data *p = hctx->plugin_data;
391 hctx->proc->load++;
393 status_counter_inc(srv, CONST_STR_LEN("fastcgi.active-requests"));
395 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
396 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
398 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->proc->load);
401 static void fcgi_proc_load_dec(server *srv, handler_ctx *hctx) {
402 plugin_data *p = hctx->plugin_data;
403 hctx->proc->load--;
405 status_counter_dec(srv, CONST_STR_LEN("fastcgi.active-requests"));
407 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
408 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
410 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->proc->load);
413 static void fcgi_host_assign(server *srv, handler_ctx *hctx, fcgi_extension_host *host) {
414 plugin_data *p = hctx->plugin_data;
415 hctx->host = host;
416 hctx->host->load++;
418 fastcgi_status_copy_procname(p->statuskey, hctx->host, NULL);
419 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
421 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->host->load);
424 static void fcgi_host_reset(server *srv, handler_ctx *hctx) {
425 plugin_data *p = hctx->plugin_data;
426 hctx->host->load--;
428 fastcgi_status_copy_procname(p->statuskey, hctx->host, NULL);
429 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
431 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->host->load);
433 hctx->host = NULL;
436 static void fcgi_host_disable(server *srv, handler_ctx *hctx) {
437 plugin_data *p = hctx->plugin_data;
439 if (hctx->host->disable_time || hctx->proc->is_local) {
440 if (hctx->proc->state == PROC_STATE_RUNNING) hctx->host->active_procs--;
441 hctx->proc->disabled_until = srv->cur_ts + hctx->host->disable_time;
442 hctx->proc->state = hctx->proc->is_local ? PROC_STATE_DIED_WAIT_FOR_PID : PROC_STATE_DIED;
444 if (p->conf.debug) {
445 log_error_write(srv, __FILE__, __LINE__, "sds",
446 "backend disabled for", hctx->host->disable_time, "seconds");
451 static int fastcgi_status_init(server *srv, buffer *b, fcgi_extension_host *host, fcgi_proc *proc) {
452 #define CLEAN(x) \
453 fastcgi_status_copy_procname(b, host, proc); \
454 buffer_append_string_len(b, CONST_STR_LEN(x)); \
455 status_counter_set(srv, CONST_BUF_LEN(b), 0);
457 CLEAN(".disabled");
458 CLEAN(".died");
459 CLEAN(".overloaded");
460 CLEAN(".connected");
461 CLEAN(".load");
463 #undef CLEAN
465 #define CLEAN(x) \
466 fastcgi_status_copy_procname(b, host, NULL); \
467 buffer_append_string_len(b, CONST_STR_LEN(x)); \
468 status_counter_set(srv, CONST_BUF_LEN(b), 0);
470 CLEAN(".load");
472 #undef CLEAN
474 return 0;
477 static handler_ctx * handler_ctx_init(void) {
478 handler_ctx * hctx;
480 hctx = calloc(1, sizeof(*hctx));
481 force_assert(hctx);
483 hctx->fde_ndx = -1;
485 hctx->response_header = buffer_init();
487 hctx->request_id = 0;
488 hctx->state = FCGI_STATE_INIT;
489 hctx->proc = NULL;
491 hctx->fd = -1;
493 hctx->reconnects = 0;
494 hctx->send_content_body = 1;
496 hctx->rb = chunkqueue_init();
497 hctx->wb = chunkqueue_init();
499 return hctx;
502 static void handler_ctx_free(server *srv, handler_ctx *hctx) {
503 if (hctx->host) {
504 fcgi_host_reset(srv, hctx);
507 buffer_free(hctx->response_header);
509 chunkqueue_free(hctx->rb);
510 chunkqueue_free(hctx->wb);
512 free(hctx);
515 static fcgi_proc *fastcgi_process_init(void) {
516 fcgi_proc *f;
518 f = calloc(1, sizeof(*f));
519 f->unixsocket = buffer_init();
520 f->connection_name = buffer_init();
522 f->prev = NULL;
523 f->next = NULL;
525 return f;
528 static void fastcgi_process_free(fcgi_proc *f) {
529 if (!f) return;
531 fastcgi_process_free(f->next);
533 buffer_free(f->unixsocket);
534 buffer_free(f->connection_name);
536 free(f);
539 static fcgi_extension_host *fastcgi_host_init(void) {
540 fcgi_extension_host *f;
542 f = calloc(1, sizeof(*f));
544 f->id = buffer_init();
545 f->host = buffer_init();
546 f->unixsocket = buffer_init();
547 f->docroot = buffer_init();
548 f->bin_path = buffer_init();
549 f->bin_env = array_init();
550 f->bin_env_copy = array_init();
551 f->strip_request_uri = buffer_init();
553 return f;
556 static void fastcgi_host_free(fcgi_extension_host *h) {
557 if (!h) return;
559 buffer_free(h->id);
560 buffer_free(h->host);
561 buffer_free(h->unixsocket);
562 buffer_free(h->docroot);
563 buffer_free(h->bin_path);
564 buffer_free(h->strip_request_uri);
565 array_free(h->bin_env);
566 array_free(h->bin_env_copy);
568 fastcgi_process_free(h->first);
569 fastcgi_process_free(h->unused_procs);
571 free(h);
575 static fcgi_exts *fastcgi_extensions_init(void) {
576 fcgi_exts *f;
578 f = calloc(1, sizeof(*f));
580 return f;
583 static void fastcgi_extensions_free(fcgi_exts *f) {
584 size_t i;
586 if (!f) return;
588 for (i = 0; i < f->used; i++) {
589 fcgi_extension *fe;
590 size_t j;
592 fe = f->exts[i];
594 for (j = 0; j < fe->used; j++) {
595 fcgi_extension_host *h;
597 h = fe->hosts[j];
599 fastcgi_host_free(h);
602 buffer_free(fe->key);
603 free(fe->hosts);
605 free(fe);
608 free(f->exts);
610 free(f);
613 static int fastcgi_extension_insert(fcgi_exts *ext, buffer *key, fcgi_extension_host *fh) {
614 fcgi_extension *fe;
615 size_t i;
617 /* there is something */
619 for (i = 0; i < ext->used; i++) {
620 if (buffer_is_equal(key, ext->exts[i]->key)) {
621 break;
625 if (i == ext->used) {
626 /* filextension is new */
627 fe = calloc(1, sizeof(*fe));
628 force_assert(fe);
629 fe->key = buffer_init();
630 fe->last_used_ndx = -1;
631 buffer_copy_buffer(fe->key, key);
633 /* */
635 if (ext->size == 0) {
636 ext->size = 8;
637 ext->exts = malloc(ext->size * sizeof(*(ext->exts)));
638 force_assert(ext->exts);
639 } else if (ext->used == ext->size) {
640 ext->size += 8;
641 ext->exts = realloc(ext->exts, ext->size * sizeof(*(ext->exts)));
642 force_assert(ext->exts);
644 ext->exts[ext->used++] = fe;
645 } else {
646 fe = ext->exts[i];
649 if (fe->size == 0) {
650 fe->size = 4;
651 fe->hosts = malloc(fe->size * sizeof(*(fe->hosts)));
652 force_assert(fe->hosts);
653 } else if (fe->size == fe->used) {
654 fe->size += 4;
655 fe->hosts = realloc(fe->hosts, fe->size * sizeof(*(fe->hosts)));
656 force_assert(fe->hosts);
659 fe->hosts[fe->used++] = fh;
661 return 0;
665 INIT_FUNC(mod_fastcgi_init) {
666 plugin_data *p;
668 p = calloc(1, sizeof(*p));
670 p->fcgi_env = buffer_init();
672 p->path = buffer_init();
674 p->statuskey = buffer_init();
676 return p;
680 FREE_FUNC(mod_fastcgi_free) {
681 plugin_data *p = p_d;
683 UNUSED(srv);
685 buffer_free(p->fcgi_env);
686 buffer_free(p->path);
687 buffer_free(p->statuskey);
689 if (p->config_storage) {
690 size_t i, j, n;
691 for (i = 0; i < srv->config_context->used; i++) {
692 plugin_config *s = p->config_storage[i];
693 fcgi_exts *exts;
695 if (NULL == s) continue;
697 exts = s->exts;
699 for (j = 0; j < exts->used; j++) {
700 fcgi_extension *ex;
702 ex = exts->exts[j];
704 for (n = 0; n < ex->used; n++) {
705 fcgi_proc *proc;
706 fcgi_extension_host *host;
708 host = ex->hosts[n];
710 for (proc = host->first; proc; proc = proc->next) {
711 if (proc->pid != 0) {
712 kill(proc->pid, host->kill_signal);
715 if (proc->is_local &&
716 !buffer_string_is_empty(proc->unixsocket)) {
717 unlink(proc->unixsocket->ptr);
721 for (proc = host->unused_procs; proc; proc = proc->next) {
722 if (proc->pid != 0) {
723 kill(proc->pid, host->kill_signal);
725 if (proc->is_local &&
726 !buffer_string_is_empty(proc->unixsocket)) {
727 unlink(proc->unixsocket->ptr);
733 fastcgi_extensions_free(s->exts);
734 array_free(s->ext_mapping);
736 free(s);
738 free(p->config_storage);
741 free(p);
743 return HANDLER_GO_ON;
746 static int env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) {
747 char *dst;
748 size_t i;
750 if (!key || !val) return -1;
752 dst = malloc(key_len + val_len + 3);
753 memcpy(dst, key, key_len);
754 dst[key_len] = '=';
755 memcpy(dst + key_len + 1, val, val_len);
756 dst[key_len + 1 + val_len] = '\0';
758 for (i = 0; i < env->used; i++) {
759 if (0 == strncmp(dst, env->ptr[i], key_len + 1)) {
760 /* don't care about free as we are in a forked child which is going to exec(...) */
761 /* free(env->ptr[i]); */
762 env->ptr[i] = dst;
763 return 0;
767 if (env->size == 0) {
768 env->size = 16;
769 env->ptr = malloc(env->size * sizeof(*env->ptr));
770 } else if (env->size == env->used + 1) {
771 env->size += 16;
772 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
775 env->ptr[env->used++] = dst;
777 return 0;
780 static int parse_binpath(char_array *env, buffer *b) {
781 char *start;
782 size_t i;
783 /* search for spaces */
785 start = b->ptr;
786 for (i = 0; i < buffer_string_length(b); i++) {
787 switch(b->ptr[i]) {
788 case ' ':
789 case '\t':
790 /* a WS, stop here and copy the argument */
792 if (env->size == 0) {
793 env->size = 16;
794 env->ptr = malloc(env->size * sizeof(*env->ptr));
795 } else if (env->size == env->used) {
796 env->size += 16;
797 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
800 b->ptr[i] = '\0';
802 env->ptr[env->used++] = start;
804 start = b->ptr + i + 1;
805 break;
806 default:
807 break;
811 if (env->size == 0) {
812 env->size = 16;
813 env->ptr = malloc(env->size * sizeof(*env->ptr));
814 } else if (env->size == env->used) { /* we need one extra for the terminating NULL */
815 env->size += 16;
816 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
819 /* the rest */
820 env->ptr[env->used++] = start;
822 if (env->size == 0) {
823 env->size = 16;
824 env->ptr = malloc(env->size * sizeof(*env->ptr));
825 } else if (env->size == env->used) { /* we need one extra for the terminating NULL */
826 env->size += 16;
827 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
830 /* terminate */
831 env->ptr[env->used++] = NULL;
833 return 0;
836 #if !defined(HAVE_FORK)
837 static int fcgi_spawn_connection(server *srv,
838 plugin_data *p,
839 fcgi_extension_host *host,
840 fcgi_proc *proc) {
841 UNUSED(srv);
842 UNUSED(p);
843 UNUSED(host);
844 UNUSED(proc);
845 return -1;
848 #else /* -> defined(HAVE_FORK) */
850 static int fcgi_spawn_connection(server *srv,
851 plugin_data *p,
852 fcgi_extension_host *host,
853 fcgi_proc *proc) {
854 int fcgi_fd;
855 int socket_type, status;
856 struct timeval tv = { 0, 100 * 1000 };
857 #ifdef HAVE_SYS_UN_H
858 struct sockaddr_un fcgi_addr_un;
859 #endif
860 struct sockaddr_in fcgi_addr_in;
861 struct sockaddr *fcgi_addr;
863 socklen_t servlen;
865 if (p->conf.debug) {
866 log_error_write(srv, __FILE__, __LINE__, "sdb",
867 "new proc, socket:", proc->port, proc->unixsocket);
870 if (!buffer_string_is_empty(proc->unixsocket)) {
871 #ifdef HAVE_SYS_UN_H
872 memset(&fcgi_addr_un, 0, sizeof(fcgi_addr_un));
873 fcgi_addr_un.sun_family = AF_UNIX;
874 if (buffer_string_length(proc->unixsocket) + 1 > sizeof(fcgi_addr_un.sun_path)) {
875 log_error_write(srv, __FILE__, __LINE__, "sB",
876 "ERROR: Unix Domain socket filename too long:",
877 proc->unixsocket);
878 return -1;
880 memcpy(fcgi_addr_un.sun_path, proc->unixsocket->ptr, buffer_string_length(proc->unixsocket) + 1);
882 #ifdef SUN_LEN
883 servlen = SUN_LEN(&fcgi_addr_un);
884 #else
885 /* stevens says: */
886 servlen = buffer_string_length(proc->unixsocket) + 1 + sizeof(fcgi_addr_un.sun_family);
887 #endif
888 socket_type = AF_UNIX;
889 fcgi_addr = (struct sockaddr *) &fcgi_addr_un;
891 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("unix:"));
892 buffer_append_string_buffer(proc->connection_name, proc->unixsocket);
894 #else
895 log_error_write(srv, __FILE__, __LINE__, "s",
896 "ERROR: Unix Domain sockets are not supported.");
897 return -1;
898 #endif
899 } else {
900 memset(&fcgi_addr_in, 0, sizeof(fcgi_addr_in));
901 fcgi_addr_in.sin_family = AF_INET;
903 if (buffer_string_is_empty(host->host)) {
904 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
905 } else {
906 struct hostent *he;
908 /* set a useful default */
909 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
912 if (NULL == (he = gethostbyname(host->host->ptr))) {
913 log_error_write(srv, __FILE__, __LINE__,
914 "sdb", "gethostbyname failed: ",
915 h_errno, host->host);
916 return -1;
919 if (he->h_addrtype != AF_INET) {
920 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-type != AF_INET: ", he->h_addrtype);
921 return -1;
924 if (he->h_length != sizeof(struct in_addr)) {
925 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-length != sizeof(in_addr): ", he->h_length);
926 return -1;
929 memcpy(&(fcgi_addr_in.sin_addr.s_addr), he->h_addr_list[0], he->h_length);
932 fcgi_addr_in.sin_port = htons(proc->port);
933 servlen = sizeof(fcgi_addr_in);
935 socket_type = AF_INET;
936 fcgi_addr = (struct sockaddr *) &fcgi_addr_in;
938 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("tcp:"));
939 if (!buffer_string_is_empty(host->host)) {
940 buffer_append_string_buffer(proc->connection_name, host->host);
941 } else {
942 buffer_append_string_len(proc->connection_name, CONST_STR_LEN("localhost"));
944 buffer_append_string_len(proc->connection_name, CONST_STR_LEN(":"));
945 buffer_append_int(proc->connection_name, proc->port);
948 if (-1 == (fcgi_fd = socket(socket_type, SOCK_STREAM, 0))) {
949 log_error_write(srv, __FILE__, __LINE__, "ss",
950 "failed:", strerror(errno));
951 return -1;
954 if (-1 == connect(fcgi_fd, fcgi_addr, servlen)) {
955 /* server is not up, spawn it */
956 pid_t child;
957 int val;
959 if (errno != ENOENT &&
960 !buffer_string_is_empty(proc->unixsocket)) {
961 unlink(proc->unixsocket->ptr);
964 close(fcgi_fd);
966 /* reopen socket */
967 if (-1 == (fcgi_fd = socket(socket_type, SOCK_STREAM, 0))) {
968 log_error_write(srv, __FILE__, __LINE__, "ss",
969 "socket failed:", strerror(errno));
970 return -1;
973 val = 1;
974 if (setsockopt(fcgi_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) {
975 log_error_write(srv, __FILE__, __LINE__, "ss",
976 "socketsockopt failed:", strerror(errno));
977 close(fcgi_fd);
978 return -1;
981 /* create socket */
982 if (-1 == bind(fcgi_fd, fcgi_addr, servlen)) {
983 log_error_write(srv, __FILE__, __LINE__, "sbs",
984 "bind failed for:",
985 proc->connection_name,
986 strerror(errno));
987 close(fcgi_fd);
988 return -1;
991 if (-1 == listen(fcgi_fd, host->listen_backlog)) {
992 log_error_write(srv, __FILE__, __LINE__, "ss",
993 "listen failed:", strerror(errno));
994 close(fcgi_fd);
995 return -1;
998 switch ((child = fork())) {
999 case 0: {
1000 size_t i = 0;
1001 char *c;
1002 char_array env;
1003 char_array arg;
1005 /* create environment */
1006 env.ptr = NULL;
1007 env.size = 0;
1008 env.used = 0;
1010 arg.ptr = NULL;
1011 arg.size = 0;
1012 arg.used = 0;
1014 if(fcgi_fd != FCGI_LISTENSOCK_FILENO) {
1015 close(FCGI_LISTENSOCK_FILENO);
1016 dup2(fcgi_fd, FCGI_LISTENSOCK_FILENO);
1017 close(fcgi_fd);
1020 /* we don't need the client socket */
1021 for (i = 3; i < 256; i++) {
1022 close(i);
1025 /* build clean environment */
1026 if (host->bin_env_copy->used) {
1027 for (i = 0; i < host->bin_env_copy->used; i++) {
1028 data_string *ds = (data_string *)host->bin_env_copy->data[i];
1029 char *ge;
1031 if (NULL != (ge = getenv(ds->value->ptr))) {
1032 env_add(&env, CONST_BUF_LEN(ds->value), ge, strlen(ge));
1035 } else {
1036 for (i = 0; environ[i]; i++) {
1037 char *eq;
1039 if (NULL != (eq = strchr(environ[i], '='))) {
1040 env_add(&env, environ[i], eq - environ[i], eq+1, strlen(eq+1));
1045 /* create environment */
1046 for (i = 0; i < host->bin_env->used; i++) {
1047 data_string *ds = (data_string *)host->bin_env->data[i];
1049 env_add(&env, CONST_BUF_LEN(ds->key), CONST_BUF_LEN(ds->value));
1052 for (i = 0; i < env.used; i++) {
1053 /* search for PHP_FCGI_CHILDREN */
1054 if (0 == strncmp(env.ptr[i], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
1057 /* not found, add a default */
1058 if (i == env.used) {
1059 env_add(&env, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
1062 env.ptr[env.used] = NULL;
1064 parse_binpath(&arg, host->bin_path);
1066 /* chdir into the base of the bin-path,
1067 * search for the last / */
1068 if (NULL != (c = strrchr(arg.ptr[0], '/'))) {
1069 *c = '\0';
1071 /* change to the physical directory */
1072 if (-1 == chdir(arg.ptr[0])) {
1073 *c = '/';
1074 log_error_write(srv, __FILE__, __LINE__, "sss", "chdir failed:", strerror(errno), arg.ptr[0]);
1076 *c = '/';
1079 reset_signals();
1081 /* exec the cgi */
1082 execve(arg.ptr[0], arg.ptr, env.ptr);
1084 /* log_error_write(srv, __FILE__, __LINE__, "sbs",
1085 "execve failed for:", host->bin_path, strerror(errno)); */
1087 _exit(errno);
1089 break;
1091 case -1:
1092 /* error */
1093 close(fcgi_fd);
1094 break;
1095 default:
1096 /* father */
1097 close(fcgi_fd);
1099 /* wait */
1100 select(0, NULL, NULL, NULL, &tv);
1102 switch (waitpid(child, &status, WNOHANG)) {
1103 case 0:
1104 /* child still running after timeout, good */
1105 break;
1106 case -1:
1107 /* no PID found ? should never happen */
1108 log_error_write(srv, __FILE__, __LINE__, "ss",
1109 "pid not found:", strerror(errno));
1110 return -1;
1111 default:
1112 log_error_write(srv, __FILE__, __LINE__, "sbs",
1113 "the fastcgi-backend", host->bin_path, "failed to start:");
1114 /* the child should not terminate at all */
1115 if (WIFEXITED(status)) {
1116 log_error_write(srv, __FILE__, __LINE__, "sdb",
1117 "child exited with status",
1118 WEXITSTATUS(status), host->bin_path);
1119 log_error_write(srv, __FILE__, __LINE__, "s",
1120 "If you're trying to run your app as a FastCGI backend, make sure you're using the FastCGI-enabled version.\n"
1121 "If this is PHP on Gentoo, add 'fastcgi' to the USE flags.");
1122 } else if (WIFSIGNALED(status)) {
1123 log_error_write(srv, __FILE__, __LINE__, "sd",
1124 "terminated by signal:",
1125 WTERMSIG(status));
1127 if (WTERMSIG(status) == 11) {
1128 log_error_write(srv, __FILE__, __LINE__, "s",
1129 "to be exact: it segfaulted, crashed, died, ... you get the idea." );
1130 log_error_write(srv, __FILE__, __LINE__, "s",
1131 "If this is PHP, try removing the bytecode caches for now and try again.");
1133 } else {
1134 log_error_write(srv, __FILE__, __LINE__, "sd",
1135 "child died somehow:",
1136 status);
1138 return -1;
1141 /* register process */
1142 proc->pid = child;
1143 proc->is_local = 1;
1145 break;
1147 } else {
1148 close(fcgi_fd);
1149 proc->is_local = 0;
1150 proc->pid = 0;
1152 if (p->conf.debug) {
1153 log_error_write(srv, __FILE__, __LINE__, "sb",
1154 "(debug) socket is already used; won't spawn:",
1155 proc->connection_name);
1159 proc->state = PROC_STATE_RUNNING;
1160 host->active_procs++;
1162 return 0;
1165 #endif /* HAVE_FORK */
1167 static int unixsocket_is_dup(plugin_data *p, size_t used, buffer *unixsocket) {
1168 size_t i, j, n;
1169 for (i = 0; i < used; ++i) {
1170 fcgi_exts *exts = p->config_storage[i]->exts;
1171 for (j = 0; j < exts->used; ++j) {
1172 fcgi_extension *ex = exts->exts[j];
1173 for (n = 0; n < ex->used; ++n) {
1174 fcgi_extension_host *host = ex->hosts[n];
1175 if (!buffer_string_is_empty(host->unixsocket)
1176 && buffer_is_equal(host->unixsocket, unixsocket))
1177 return 1;
1182 return 0;
1185 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults) {
1186 plugin_data *p = p_d;
1187 data_unset *du;
1188 size_t i = 0;
1189 buffer *fcgi_mode = buffer_init();
1190 fcgi_extension_host *host = NULL;
1192 config_values_t cv[] = {
1193 { "fastcgi.server", NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1194 { "fastcgi.debug", NULL, T_CONFIG_INT , T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1195 { "fastcgi.map-extensions", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1196 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1199 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
1201 for (i = 0; i < srv->config_context->used; i++) {
1202 data_config const* config = (data_config const*)srv->config_context->data[i];
1203 plugin_config *s;
1205 s = malloc(sizeof(plugin_config));
1206 s->exts = fastcgi_extensions_init();
1207 s->debug = 0;
1208 s->ext_mapping = array_init();
1210 cv[0].destination = s->exts;
1211 cv[1].destination = &(s->debug);
1212 cv[2].destination = s->ext_mapping;
1214 p->config_storage[i] = s;
1216 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
1217 goto error;
1221 * <key> = ( ... )
1224 if (NULL != (du = array_get_element(config->value, "fastcgi.server"))) {
1225 size_t j;
1226 data_array *da = (data_array *)du;
1228 if (du->type != TYPE_ARRAY) {
1229 log_error_write(srv, __FILE__, __LINE__, "sss",
1230 "unexpected type for key: ", "fastcgi.server", "array of strings");
1232 goto error;
1237 * fastcgi.server = ( "<ext>" => ( ... ),
1238 * "<ext>" => ( ... ) )
1241 for (j = 0; j < da->value->used; j++) {
1242 size_t n;
1243 data_array *da_ext = (data_array *)da->value->data[j];
1245 if (da->value->data[j]->type != TYPE_ARRAY) {
1246 log_error_write(srv, __FILE__, __LINE__, "sssbs",
1247 "unexpected type for key: ", "fastcgi.server",
1248 "[", da->value->data[j]->key, "](string)");
1250 goto error;
1254 * da_ext->key == name of the extension
1258 * fastcgi.server = ( "<ext>" =>
1259 * ( "<host>" => ( ... ),
1260 * "<host>" => ( ... )
1261 * ),
1262 * "<ext>" => ... )
1265 for (n = 0; n < da_ext->value->used; n++) {
1266 data_array *da_host = (data_array *)da_ext->value->data[n];
1268 config_values_t fcv[] = {
1269 { "host", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1270 { "docroot", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1271 { "mode", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1272 { "socket", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
1273 { "bin-path", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
1275 { "check-local", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 5 */
1276 { "port", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 6 */
1277 { "max-procs", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
1278 { "disable-time", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
1280 { "bin-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 9 */
1281 { "bin-copy-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 10 */
1283 { "broken-scriptfilename", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 11 */
1284 { "allow-x-send-file", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
1285 { "strip-request-uri", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 13 */
1286 { "kill-signal", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 14 */
1287 { "fix-root-scriptname", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 15 */
1288 { "listen-backlog", NULL, T_CONFIG_INT, T_CONFIG_SCOPE_CONNECTION }, /* 16 */
1290 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1293 if (da_host->type != TYPE_ARRAY) {
1294 log_error_write(srv, __FILE__, __LINE__, "ssSBS",
1295 "unexpected type for key:",
1296 "fastcgi.server",
1297 "[", da_host->key, "](string)");
1299 goto error;
1302 host = fastcgi_host_init();
1303 buffer_reset(fcgi_mode);
1305 buffer_copy_buffer(host->id, da_host->key);
1307 host->check_local = 1;
1308 host->max_procs = 4;
1309 host->mode = FCGI_RESPONDER;
1310 host->disable_time = 1;
1311 host->break_scriptfilename_for_php = 0;
1312 host->allow_xsendfile = 0; /* handle X-LIGHTTPD-send-file */
1313 host->kill_signal = SIGTERM;
1314 host->fix_root_path_name = 0;
1315 host->listen_backlog = 1024;
1317 fcv[0].destination = host->host;
1318 fcv[1].destination = host->docroot;
1319 fcv[2].destination = fcgi_mode;
1320 fcv[3].destination = host->unixsocket;
1321 fcv[4].destination = host->bin_path;
1323 fcv[5].destination = &(host->check_local);
1324 fcv[6].destination = &(host->port);
1325 fcv[7].destination = &(host->max_procs);
1326 fcv[8].destination = &(host->disable_time);
1328 fcv[9].destination = host->bin_env;
1329 fcv[10].destination = host->bin_env_copy;
1330 fcv[11].destination = &(host->break_scriptfilename_for_php);
1331 fcv[12].destination = &(host->allow_xsendfile);
1332 fcv[13].destination = host->strip_request_uri;
1333 fcv[14].destination = &(host->kill_signal);
1334 fcv[15].destination = &(host->fix_root_path_name);
1335 fcv[16].destination = &(host->listen_backlog);
1337 if (0 != config_insert_values_internal(srv, da_host->value, fcv, T_CONFIG_SCOPE_CONNECTION)) {
1338 goto error;
1341 if ((!buffer_string_is_empty(host->host) || host->port) &&
1342 !buffer_string_is_empty(host->unixsocket)) {
1343 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1344 "either host/port or socket have to be set in:",
1345 da->key, "= (",
1346 da_ext->key, " => (",
1347 da_host->key, " ( ...");
1349 goto error;
1352 if (!buffer_string_is_empty(host->unixsocket)) {
1353 /* unix domain socket */
1354 struct sockaddr_un un;
1356 if (buffer_string_length(host->unixsocket) + 1 > sizeof(un.sun_path) - 2) {
1357 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1358 "unixsocket is too long in:",
1359 da->key, "= (",
1360 da_ext->key, " => (",
1361 da_host->key, " ( ...");
1363 goto error;
1366 if (!buffer_string_is_empty(host->bin_path)
1367 && unixsocket_is_dup(p, i+1, host->unixsocket)) {
1368 log_error_write(srv, __FILE__, __LINE__, "sb",
1369 "duplicate unixsocket path:",
1370 host->unixsocket);
1371 goto error;
1373 } else {
1374 /* tcp/ip */
1376 if (buffer_string_is_empty(host->host) &&
1377 buffer_string_is_empty(host->bin_path)) {
1378 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1379 "host or binpath have to be set in:",
1380 da->key, "= (",
1381 da_ext->key, " => (",
1382 da_host->key, " ( ...");
1384 goto error;
1385 } else if (host->port == 0) {
1386 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1387 "port has to be set in:",
1388 da->key, "= (",
1389 da_ext->key, " => (",
1390 da_host->key, " ( ...");
1392 goto error;
1396 if (!buffer_string_is_empty(host->bin_path)) {
1397 /* a local socket + self spawning */
1398 size_t pno;
1400 if (s->debug) {
1401 log_error_write(srv, __FILE__, __LINE__, "ssbsdsbsd",
1402 "--- fastcgi spawning local",
1403 "\n\tproc:", host->bin_path,
1404 "\n\tport:", host->port,
1405 "\n\tsocket", host->unixsocket,
1406 "\n\tmax-procs:", host->max_procs);
1409 for (pno = 0; pno < host->max_procs; pno++) {
1410 fcgi_proc *proc;
1412 proc = fastcgi_process_init();
1413 proc->id = host->num_procs++;
1414 host->max_id++;
1416 if (buffer_string_is_empty(host->unixsocket)) {
1417 proc->port = host->port + pno;
1418 } else {
1419 buffer_copy_buffer(proc->unixsocket, host->unixsocket);
1420 buffer_append_string_len(proc->unixsocket, CONST_STR_LEN("-"));
1421 buffer_append_int(proc->unixsocket, pno);
1424 if (s->debug) {
1425 log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
1426 "--- fastcgi spawning",
1427 "\n\tport:", host->port,
1428 "\n\tsocket", host->unixsocket,
1429 "\n\tcurrent:", pno, "/", host->max_procs);
1432 if (!srv->srvconf.preflight_check
1433 && fcgi_spawn_connection(srv, p, host, proc)) {
1434 log_error_write(srv, __FILE__, __LINE__, "s",
1435 "[ERROR]: spawning fcgi failed.");
1436 fastcgi_process_free(proc);
1437 goto error;
1440 fastcgi_status_init(srv, p->statuskey, host, proc);
1442 proc->next = host->first;
1443 if (host->first) host->first->prev = proc;
1445 host->first = proc;
1447 } else {
1448 fcgi_proc *proc;
1450 proc = fastcgi_process_init();
1451 proc->id = host->num_procs++;
1452 host->max_id++;
1453 host->active_procs++;
1454 proc->state = PROC_STATE_RUNNING;
1456 if (buffer_string_is_empty(host->unixsocket)) {
1457 proc->port = host->port;
1458 } else {
1459 buffer_copy_buffer(proc->unixsocket, host->unixsocket);
1462 fastcgi_status_init(srv, p->statuskey, host, proc);
1464 host->first = proc;
1466 host->max_procs = 1;
1469 if (!buffer_string_is_empty(fcgi_mode)) {
1470 if (strcmp(fcgi_mode->ptr, "responder") == 0) {
1471 host->mode = FCGI_RESPONDER;
1472 } else if (strcmp(fcgi_mode->ptr, "authorizer") == 0) {
1473 host->mode = FCGI_AUTHORIZER;
1474 if (buffer_string_is_empty(host->docroot)) {
1475 log_error_write(srv, __FILE__, __LINE__, "s",
1476 "ERROR: docroot is required for authorizer mode.");
1477 goto error;
1479 } else {
1480 log_error_write(srv, __FILE__, __LINE__, "sbs",
1481 "WARNING: unknown fastcgi mode:",
1482 fcgi_mode, "(ignored, mode set to responder)");
1486 /* if extension already exists, take it */
1487 fastcgi_extension_insert(s->exts, da_ext->key, host);
1488 host = NULL;
1494 buffer_free(fcgi_mode);
1495 return HANDLER_GO_ON;
1497 error:
1498 if (NULL != host) fastcgi_host_free(host);
1499 buffer_free(fcgi_mode);
1500 return HANDLER_ERROR;
1503 static int fcgi_set_state(server *srv, handler_ctx *hctx, fcgi_connection_state_t state) {
1504 hctx->state = state;
1505 hctx->state_timestamp = srv->cur_ts;
1507 return 0;
1511 static void fcgi_connection_close(server *srv, handler_ctx *hctx) {
1512 plugin_data *p;
1513 connection *con;
1515 p = hctx->plugin_data;
1516 con = hctx->remote_conn;
1518 if (hctx->fd != -1) {
1519 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1520 fdevent_unregister(srv->ev, hctx->fd);
1521 close(hctx->fd);
1522 srv->cur_fds--;
1525 if (hctx->host && hctx->proc) {
1526 if (hctx->got_proc) {
1527 /* after the connect the process gets a load */
1528 fcgi_proc_load_dec(srv, hctx);
1530 if (p->conf.debug) {
1531 log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
1532 "released proc:",
1533 "pid:", hctx->proc->pid,
1534 "socket:", hctx->proc->connection_name,
1535 "load:", hctx->proc->load);
1541 handler_ctx_free(srv, hctx);
1542 con->plugin_ctx[p->id] = NULL;
1544 /* finish response (if not already finished) */
1545 if (con->mode == p->id
1546 && (con->state == CON_STATE_HANDLE_REQUEST || con->state == CON_STATE_READ_POST)) {
1547 /* (not CON_STATE_ERROR and not CON_STATE_RESPONSE_END,
1548 * i.e. not called from fcgi_connection_reset()) */
1550 /* Send an error if we haven't sent any data yet */
1551 if (0 == con->file_started) {
1552 con->http_status = 500;
1553 con->mode = DIRECT;
1555 else if (!con->file_finished) {
1556 http_chunk_close(srv, con);
1557 con->file_finished = 1;
1562 static int fcgi_reconnect(server *srv, handler_ctx *hctx) {
1563 plugin_data *p = hctx->plugin_data;
1565 /* child died
1567 * 1.
1569 * connect was ok, connection was accepted
1570 * but the php accept loop checks after the accept if it should die or not.
1572 * if yes we can only detect it at a write()
1574 * next step is resetting this attemp and setup a connection again
1576 * if we have more than 5 reconnects for the same request, die
1578 * 2.
1580 * we have a connection but the child died by some other reason
1584 if (hctx->fd != -1) {
1585 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1586 fdevent_unregister(srv->ev, hctx->fd);
1587 close(hctx->fd);
1588 srv->cur_fds--;
1589 hctx->fd = -1;
1592 fcgi_set_state(srv, hctx, FCGI_STATE_INIT);
1594 hctx->request_id = 0;
1595 hctx->reconnects++;
1597 if (p->conf.debug > 2) {
1598 if (hctx->proc) {
1599 log_error_write(srv, __FILE__, __LINE__, "sdb",
1600 "release proc for reconnect:",
1601 hctx->proc->pid, hctx->proc->connection_name);
1602 } else {
1603 log_error_write(srv, __FILE__, __LINE__, "sb",
1604 "release proc for reconnect:",
1605 hctx->host->unixsocket);
1609 if (hctx->proc && hctx->got_proc) {
1610 fcgi_proc_load_dec(srv, hctx);
1613 /* perhaps another host gives us more luck */
1614 fcgi_host_reset(srv, hctx);
1616 return 0;
1620 static handler_t fcgi_connection_reset(server *srv, connection *con, void *p_d) {
1621 plugin_data *p = p_d;
1622 handler_ctx *hctx = con->plugin_ctx[p->id];
1623 if (hctx) fcgi_connection_close(srv, hctx);
1625 return HANDLER_GO_ON;
1629 static int fcgi_env_add(buffer *env, const char *key, size_t key_len, const char *val, size_t val_len) {
1630 size_t len;
1631 char len_enc[8];
1632 size_t len_enc_len = 0;
1634 if (!key || !val) return -1;
1636 len = key_len + val_len;
1638 len += key_len > 127 ? 4 : 1;
1639 len += val_len > 127 ? 4 : 1;
1641 if (buffer_string_length(env) + len >= FCGI_MAX_LENGTH) {
1643 * we can't append more headers, ignore it
1645 return -1;
1649 * field length can be 31bit max
1651 * HINT: this can't happen as FCGI_MAX_LENGTH is only 16bit
1653 force_assert(key_len < 0x7fffffffu);
1654 force_assert(val_len < 0x7fffffffu);
1656 buffer_string_prepare_append(env, len);
1658 if (key_len > 127) {
1659 len_enc[len_enc_len++] = ((key_len >> 24) & 0xff) | 0x80;
1660 len_enc[len_enc_len++] = (key_len >> 16) & 0xff;
1661 len_enc[len_enc_len++] = (key_len >> 8) & 0xff;
1662 len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1663 } else {
1664 len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1667 if (val_len > 127) {
1668 len_enc[len_enc_len++] = ((val_len >> 24) & 0xff) | 0x80;
1669 len_enc[len_enc_len++] = (val_len >> 16) & 0xff;
1670 len_enc[len_enc_len++] = (val_len >> 8) & 0xff;
1671 len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1672 } else {
1673 len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1676 buffer_append_string_len(env, len_enc, len_enc_len);
1677 buffer_append_string_len(env, key, key_len);
1678 buffer_append_string_len(env, val, val_len);
1680 return 0;
1683 static int fcgi_header(FCGI_Header * header, unsigned char type, size_t request_id, int contentLength, unsigned char paddingLength) {
1684 force_assert(contentLength <= FCGI_MAX_LENGTH);
1686 header->version = FCGI_VERSION_1;
1687 header->type = type;
1688 header->requestIdB0 = request_id & 0xff;
1689 header->requestIdB1 = (request_id >> 8) & 0xff;
1690 header->contentLengthB0 = contentLength & 0xff;
1691 header->contentLengthB1 = (contentLength >> 8) & 0xff;
1692 header->paddingLength = paddingLength;
1693 header->reserved = 0;
1695 return 0;
1698 typedef enum {
1699 CONNECTION_OK,
1700 CONNECTION_DELAYED, /* retry after event, take same host */
1701 CONNECTION_OVERLOADED, /* disable for 1 second, take another backend */
1702 CONNECTION_DEAD /* disable for 60 seconds, take another backend */
1703 } connection_result_t;
1705 static connection_result_t fcgi_establish_connection(server *srv, handler_ctx *hctx) {
1706 struct sockaddr *fcgi_addr;
1707 struct sockaddr_in fcgi_addr_in;
1708 #ifdef HAVE_SYS_UN_H
1709 struct sockaddr_un fcgi_addr_un;
1710 #endif
1711 socklen_t servlen;
1713 fcgi_extension_host *host = hctx->host;
1714 fcgi_proc *proc = hctx->proc;
1715 int fcgi_fd = hctx->fd;
1717 if (!buffer_string_is_empty(proc->unixsocket)) {
1718 #ifdef HAVE_SYS_UN_H
1719 /* use the unix domain socket */
1720 memset(&fcgi_addr_un, 0, sizeof(fcgi_addr_un));
1721 fcgi_addr_un.sun_family = AF_UNIX;
1722 if (buffer_string_length(proc->unixsocket) + 1 > sizeof(fcgi_addr_un.sun_path)) {
1723 log_error_write(srv, __FILE__, __LINE__, "sB",
1724 "ERROR: Unix Domain socket filename too long:",
1725 proc->unixsocket);
1726 return -1;
1728 memcpy(fcgi_addr_un.sun_path, proc->unixsocket->ptr, buffer_string_length(proc->unixsocket) + 1);
1730 #ifdef SUN_LEN
1731 servlen = SUN_LEN(&fcgi_addr_un);
1732 #else
1733 /* stevens says: */
1734 servlen = buffer_string_length(proc->unixsocket) + 1 + sizeof(fcgi_addr_un.sun_family);
1735 #endif
1736 fcgi_addr = (struct sockaddr *) &fcgi_addr_un;
1738 if (buffer_string_is_empty(proc->connection_name)) {
1739 /* on remote spawing we have to set the connection-name now */
1740 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("unix:"));
1741 buffer_append_string_buffer(proc->connection_name, proc->unixsocket);
1743 #else
1744 return CONNECTION_DEAD;
1745 #endif
1746 } else {
1747 memset(&fcgi_addr_in, 0, sizeof(fcgi_addr_in));
1748 fcgi_addr_in.sin_family = AF_INET;
1749 if (!buffer_string_is_empty(host->host)) {
1750 if (0 == inet_aton(host->host->ptr, &(fcgi_addr_in.sin_addr))) {
1751 log_error_write(srv, __FILE__, __LINE__, "sbs",
1752 "converting IP address failed for", host->host,
1753 "\nBe sure to specify an IP address here");
1755 return CONNECTION_DEAD;
1757 } else {
1758 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1760 fcgi_addr_in.sin_port = htons(proc->port);
1761 servlen = sizeof(fcgi_addr_in);
1763 fcgi_addr = (struct sockaddr *) &fcgi_addr_in;
1765 if (buffer_string_is_empty(proc->connection_name)) {
1766 /* on remote spawing we have to set the connection-name now */
1767 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("tcp:"));
1768 if (!buffer_string_is_empty(host->host)) {
1769 buffer_append_string_buffer(proc->connection_name, host->host);
1770 } else {
1771 buffer_append_string_len(proc->connection_name, CONST_STR_LEN("localhost"));
1773 buffer_append_string_len(proc->connection_name, CONST_STR_LEN(":"));
1774 buffer_append_int(proc->connection_name, proc->port);
1778 if (-1 == connect(fcgi_fd, fcgi_addr, servlen)) {
1779 if (errno == EINPROGRESS ||
1780 errno == EALREADY ||
1781 errno == EINTR) {
1782 if (hctx->conf.debug > 2) {
1783 log_error_write(srv, __FILE__, __LINE__, "sb",
1784 "connect delayed; will continue later:", proc->connection_name);
1787 return CONNECTION_DELAYED;
1788 } else if (errno == EAGAIN) {
1789 if (hctx->conf.debug) {
1790 log_error_write(srv, __FILE__, __LINE__, "sbsd",
1791 "This means that you have more incoming requests than your FastCGI backend can handle in parallel."
1792 "It might help to spawn more FastCGI backends or PHP children; if not, decrease server.max-connections."
1793 "The load for this FastCGI backend", proc->connection_name, "is", proc->load);
1796 return CONNECTION_OVERLOADED;
1797 } else {
1798 log_error_write(srv, __FILE__, __LINE__, "sssb",
1799 "connect failed:",
1800 strerror(errno), "on",
1801 proc->connection_name);
1803 return CONNECTION_DEAD;
1807 hctx->reconnects = 0;
1808 if (hctx->conf.debug > 1) {
1809 log_error_write(srv, __FILE__, __LINE__, "sd",
1810 "connect succeeded: ", fcgi_fd);
1813 return CONNECTION_OK;
1816 #define FCGI_ENV_ADD_CHECK(ret, con) \
1817 if (ret == -1) { \
1818 con->http_status = 400; \
1819 con->file_finished = 1; \
1820 return -1; \
1822 static int fcgi_env_add_request_headers(server *srv, connection *con, plugin_data *p) {
1823 size_t i;
1825 for (i = 0; i < con->request.headers->used; i++) {
1826 data_string *ds;
1828 ds = (data_string *)con->request.headers->data[i];
1830 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1831 buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 1);
1833 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value)),con);
1837 for (i = 0; i < con->environment->used; i++) {
1838 data_string *ds;
1840 ds = (data_string *)con->environment->data[i];
1842 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1843 buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 0);
1845 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value)), con);
1849 return 0;
1852 static int fcgi_create_env(server *srv, handler_ctx *hctx, size_t request_id) {
1853 FCGI_BeginRequestRecord beginRecord;
1854 FCGI_Header header;
1856 char buf[LI_ITOSTRING_LENGTH];
1857 const char *s;
1858 #ifdef HAVE_IPV6
1859 char b2[INET6_ADDRSTRLEN + 1];
1860 #endif
1862 plugin_data *p = hctx->plugin_data;
1863 fcgi_extension_host *host= hctx->host;
1865 connection *con = hctx->remote_conn;
1866 server_socket *srv_sock = con->srv_socket;
1868 sock_addr our_addr;
1869 socklen_t our_addr_len;
1871 /* send FCGI_BEGIN_REQUEST */
1873 fcgi_header(&(beginRecord.header), FCGI_BEGIN_REQUEST, request_id, sizeof(beginRecord.body), 0);
1874 beginRecord.body.roleB0 = host->mode;
1875 beginRecord.body.roleB1 = 0;
1876 beginRecord.body.flags = 0;
1877 memset(beginRecord.body.reserved, 0, sizeof(beginRecord.body.reserved));
1879 /* send FCGI_PARAMS */
1880 buffer_string_prepare_copy(p->fcgi_env, 1023);
1883 if (buffer_is_empty(con->conf.server_tag)) {
1884 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_DESC)),con)
1885 } else {
1886 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con->conf.server_tag)),con)
1889 if (!buffer_is_empty(con->server_name)) {
1890 size_t len = buffer_string_length(con->server_name);
1892 if (con->server_name->ptr[0] == '[') {
1893 const char *colon = strstr(con->server_name->ptr, "]:");
1894 if (colon) len = (colon + 1) - con->server_name->ptr;
1895 } else {
1896 const char *colon = strchr(con->server_name->ptr, ':');
1897 if (colon) len = colon - con->server_name->ptr;
1900 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_NAME"), con->server_name->ptr, len),con)
1901 } else {
1902 #ifdef HAVE_IPV6
1903 s = inet_ntop(srv_sock->addr.plain.sa_family,
1904 srv_sock->addr.plain.sa_family == AF_INET6 ?
1905 (const void *) &(srv_sock->addr.ipv6.sin6_addr) :
1906 (const void *) &(srv_sock->addr.ipv4.sin_addr),
1907 b2, sizeof(b2)-1);
1908 #else
1909 s = inet_ntoa(srv_sock->addr.ipv4.sin_addr);
1910 #endif
1911 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_NAME"), s, strlen(s)),con)
1914 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1")),con)
1916 li_utostrn(buf, sizeof(buf),
1917 #ifdef HAVE_IPV6
1918 ntohs(srv_sock->addr.plain.sa_family ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port)
1919 #else
1920 ntohs(srv_sock->addr.ipv4.sin_port)
1921 #endif
1924 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf)),con)
1926 /* get the server-side of the connection to the client */
1927 our_addr_len = sizeof(our_addr);
1929 if (-1 == getsockname(con->fd, &(our_addr.plain), &our_addr_len)) {
1930 s = inet_ntop_cache_get_ip(srv, &(srv_sock->addr));
1931 } else {
1932 s = inet_ntop_cache_get_ip(srv, &(our_addr));
1934 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s)),con)
1936 li_utostrn(buf, sizeof(buf),
1937 #ifdef HAVE_IPV6
1938 ntohs(con->dst_addr.plain.sa_family ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port)
1939 #else
1940 ntohs(con->dst_addr.ipv4.sin_port)
1941 #endif
1944 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf)),con)
1946 s = inet_ntop_cache_get_ip(srv, &(con->dst_addr));
1947 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s)),con)
1949 if (con->request.content_length > 0 && host->mode != FCGI_AUTHORIZER) {
1950 /* CGI-SPEC 6.1.2 and FastCGI spec 6.3 */
1952 li_itostrn(buf, sizeof(buf), con->request.content_length);
1953 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf)),con)
1956 if (host->mode != FCGI_AUTHORIZER) {
1958 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1959 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1960 * (6.1.14, 6.1.6, 6.1.7)
1961 * For AUTHORIZER mode these headers should be omitted.
1964 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path)),con)
1966 if (!buffer_string_is_empty(con->request.pathinfo)) {
1967 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo)),con)
1969 /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1971 if (!buffer_string_is_empty(host->docroot)) {
1972 buffer_copy_buffer(p->path, host->docroot);
1973 } else {
1974 buffer_copy_buffer(p->path, con->physical.basedir);
1976 buffer_append_string_buffer(p->path, con->request.pathinfo);
1977 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p->path)),con)
1978 } else {
1979 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN("")),con)
1984 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1985 * http://www.php.net/manual/en/reserved.variables.php
1986 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1987 * TODO: this code should be checked against cgi.fix_pathinfo php
1988 * parameter.
1991 if (!buffer_string_is_empty(host->docroot)) {
1993 * rewrite SCRIPT_FILENAME
1997 buffer_copy_buffer(p->path, host->docroot);
1998 buffer_append_string_buffer(p->path, con->uri.path);
2000 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path)),con)
2001 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host->docroot)),con)
2002 } else {
2003 buffer_copy_buffer(p->path, con->physical.path);
2005 /* cgi.fix_pathinfo need a broken SCRIPT_FILENAME to find out what PATH_INFO is itself
2007 * see src/sapi/cgi_main.c, init_request_info()
2009 if (host->break_scriptfilename_for_php) {
2010 buffer_append_string_buffer(p->path, con->request.pathinfo);
2013 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path)),con)
2014 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.basedir)),con)
2017 if (!buffer_string_is_empty(host->strip_request_uri)) {
2018 /* we need at least one char to strip off */
2020 * /app1/index/list
2022 * stripping /app1 or /app1/ should lead to
2024 * /index/list
2027 if ('/' != host->strip_request_uri->ptr[buffer_string_length(host->strip_request_uri) - 1]) {
2028 /* fix the user-input to have / as last char */
2029 buffer_append_string_len(host->strip_request_uri, CONST_STR_LEN("/"));
2032 if (buffer_string_length(con->request.orig_uri) >= buffer_string_length(host->strip_request_uri) &&
2033 0 == strncmp(con->request.orig_uri->ptr, host->strip_request_uri->ptr, buffer_string_length(host->strip_request_uri))) {
2034 /* the left is the same */
2036 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_URI"),
2037 con->request.orig_uri->ptr + (buffer_string_length(host->strip_request_uri) - 1),
2038 buffer_string_length(con->request.orig_uri) - (buffer_string_length(host->strip_request_uri) - 1)), con);
2039 } else {
2040 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri)),con)
2042 } else {
2043 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri)),con)
2045 if (!buffer_is_equal(con->request.uri, con->request.orig_uri)) {
2046 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con->request.uri)),con)
2048 if (!buffer_string_is_empty(con->uri.query)) {
2049 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query)),con)
2050 } else {
2051 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN("")),con)
2054 s = get_http_method_name(con->request.http_method);
2055 force_assert(s);
2056 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s)),con)
2057 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")),con) /* if php is compiled with --force-redirect */
2058 s = get_http_version_name(con->request.http_version);
2059 force_assert(s);
2060 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s)),con)
2062 if (buffer_is_equal_caseless_string(con->uri.scheme, CONST_STR_LEN("https"))) {
2063 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on")),con)
2066 FCGI_ENV_ADD_CHECK(fcgi_env_add_request_headers(srv, con, p), con);
2069 buffer *b = buffer_init();
2071 buffer_copy_string_len(b, (const char *)&beginRecord, sizeof(beginRecord));
2073 fcgi_header(&(header), FCGI_PARAMS, request_id, buffer_string_length(p->fcgi_env), 0);
2074 buffer_append_string_len(b, (const char *)&header, sizeof(header));
2075 buffer_append_string_buffer(b, p->fcgi_env);
2077 fcgi_header(&(header), FCGI_PARAMS, request_id, 0, 0);
2078 buffer_append_string_len(b, (const char *)&header, sizeof(header));
2080 chunkqueue_append_buffer(hctx->wb, b);
2081 buffer_free(b);
2084 if (con->request.content_length) {
2085 chunkqueue *req_cq = con->request_content_queue;
2086 off_t offset;
2088 /* something to send ? */
2089 for (offset = 0; offset != req_cq->bytes_in; ) {
2090 off_t weWant = req_cq->bytes_in - offset > FCGI_MAX_LENGTH ? FCGI_MAX_LENGTH : req_cq->bytes_in - offset;
2092 /* we announce toWrite octets
2093 * now take all the request_content chunks that we need to fill this request
2094 * */
2096 fcgi_header(&(header), FCGI_STDIN, request_id, weWant, 0);
2097 chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
2099 if (p->conf.debug > 10) {
2100 log_error_write(srv, __FILE__, __LINE__, "soso", "tosend:", offset, "/", req_cq->bytes_in);
2103 chunkqueue_steal(hctx->wb, req_cq, weWant);
2105 offset += weWant;
2109 /* terminate STDIN */
2110 fcgi_header(&(header), FCGI_STDIN, request_id, 0, 0);
2111 chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
2113 return 0;
2116 static int fcgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in) {
2117 char *s, *ns;
2119 handler_ctx *hctx = con->plugin_ctx[p->id];
2120 fcgi_extension_host *host= hctx->host;
2121 int have_sendfile2 = 0;
2122 off_t sendfile2_content_length = 0;
2124 UNUSED(srv);
2126 /* search for \n */
2127 for (s = in->ptr; NULL != (ns = strchr(s, '\n')); s = ns + 1) {
2128 char *key, *value;
2129 int key_len;
2130 data_string *ds = NULL;
2132 /* a good day. Someone has read the specs and is sending a \r\n to us */
2134 if (ns > in->ptr &&
2135 *(ns-1) == '\r') {
2136 *(ns-1) = '\0';
2139 ns[0] = '\0';
2141 key = s;
2142 if (NULL == (value = strchr(s, ':'))) {
2143 /* we expect: "<key>: <value>\n" */
2144 continue;
2147 key_len = value - key;
2149 value++;
2150 /* strip WS */
2151 while (*value == ' ' || *value == '\t') value++;
2153 if (host->mode != FCGI_AUTHORIZER ||
2154 !(con->http_status == 0 ||
2155 con->http_status == 200)) {
2156 /* authorizers shouldn't affect the response headers sent back to the client */
2158 /* don't forward Status: */
2159 if (0 != strncasecmp(key, "Status", key_len)) {
2160 if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2161 ds = data_response_init();
2163 buffer_copy_string_len(ds->key, key, key_len);
2164 buffer_copy_string(ds->value, value);
2166 array_insert_unique(con->response.headers, (data_unset *)ds);
2170 switch(key_len) {
2171 case 4:
2172 if (0 == strncasecmp(key, "Date", key_len)) {
2173 con->parsed_response |= HTTP_DATE;
2175 break;
2176 case 6:
2177 if (0 == strncasecmp(key, "Status", key_len)) {
2178 int status = strtol(value, NULL, 10);
2179 if (status >= 100 && status < 1000) {
2180 con->http_status = status;
2181 con->parsed_response |= HTTP_STATUS;
2182 } else {
2183 con->http_status = 502;
2186 break;
2187 case 8:
2188 if (0 == strncasecmp(key, "Location", key_len)) {
2189 con->parsed_response |= HTTP_LOCATION;
2191 break;
2192 case 10:
2193 if (0 == strncasecmp(key, "Connection", key_len)) {
2194 con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
2195 con->parsed_response |= HTTP_CONNECTION;
2197 break;
2198 case 11:
2199 if (host->allow_xsendfile && 0 == strncasecmp(key, "X-Sendfile2", key_len)&& hctx->send_content_body) {
2200 char *pos = value;
2201 have_sendfile2 = 1;
2203 while (*pos) {
2204 char *filename, *range;
2205 stat_cache_entry *sce;
2206 off_t begin_range, end_range, range_len;
2208 while (' ' == *pos) pos++;
2209 if (!*pos) break;
2211 filename = pos;
2212 if (NULL == (range = strchr(pos, ' '))) {
2213 /* missing range */
2214 if (p->conf.debug) {
2215 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't find range after filename:", filename);
2217 return 502;
2219 buffer_copy_string_len(srv->tmp_buf, filename, range - filename);
2221 /* find end of range */
2222 for (pos = ++range; *pos && *pos != ' ' && *pos != ','; pos++) ;
2224 buffer_urldecode_path(srv->tmp_buf);
2225 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, srv->tmp_buf, &sce)) {
2226 if (p->conf.debug) {
2227 log_error_write(srv, __FILE__, __LINE__, "sb",
2228 "send-file error: couldn't get stat_cache entry for X-Sendfile2:",
2229 srv->tmp_buf);
2231 return 404;
2232 } else if (!S_ISREG(sce->st.st_mode)) {
2233 if (p->conf.debug) {
2234 log_error_write(srv, __FILE__, __LINE__, "sb",
2235 "send-file error: wrong filetype for X-Sendfile2:",
2236 srv->tmp_buf);
2238 return 502;
2240 /* found the file */
2242 /* parse range */
2243 begin_range = 0; end_range = sce->st.st_size - 1;
2245 char *rpos = NULL;
2246 errno = 0;
2247 begin_range = strtoll(range, &rpos, 10);
2248 if (errno != 0 || begin_range < 0 || rpos == range) goto range_failed;
2249 if ('-' != *rpos++) goto range_failed;
2250 if (rpos != pos) {
2251 range = rpos;
2252 end_range = strtoll(range, &rpos, 10);
2253 if (errno != 0 || end_range < 0 || rpos == range) goto range_failed;
2255 if (rpos != pos) goto range_failed;
2257 goto range_success;
2259 range_failed:
2260 if (p->conf.debug) {
2261 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't decode range after filename:", filename);
2263 return 502;
2265 range_success: ;
2268 /* no parameters accepted */
2270 while (*pos == ' ') pos++;
2271 if (*pos != '\0' && *pos != ',') return 502;
2273 range_len = end_range - begin_range + 1;
2274 if (range_len < 0) return 502;
2275 if (range_len != 0) {
2276 if (0 != http_chunk_append_file_range(srv, con, srv->tmp_buf, begin_range, range_len)) {
2277 return 502;
2280 sendfile2_content_length += range_len;
2282 if (*pos == ',') pos++;
2285 break;
2286 case 14:
2287 if (0 == strncasecmp(key, "Content-Length", key_len)) {
2288 con->response.content_length = strtoul(value, NULL, 10);
2289 con->parsed_response |= HTTP_CONTENT_LENGTH;
2291 if (con->response.content_length < 0) con->response.content_length = 0;
2293 break;
2294 default:
2295 break;
2299 if (have_sendfile2) {
2300 data_string *dcls;
2302 hctx->send_content_body = 0;
2303 joblist_append(srv, con);
2305 /* fix content-length */
2306 if (NULL == (dcls = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2307 dcls = data_response_init();
2310 buffer_copy_string_len(dcls->key, "Content-Length", sizeof("Content-Length")-1);
2311 buffer_copy_int(dcls->value, sendfile2_content_length);
2312 array_replace(con->response.headers, (data_unset *)dcls);
2314 con->parsed_response |= HTTP_CONTENT_LENGTH;
2315 con->response.content_length = sendfile2_content_length;
2318 /* CGI/1.1 rev 03 - 7.2.1.2 */
2319 if ((con->parsed_response & HTTP_LOCATION) &&
2320 !(con->parsed_response & HTTP_STATUS)) {
2321 con->http_status = 302;
2324 return 0;
2327 typedef struct {
2328 buffer *b;
2329 size_t len;
2330 int type;
2331 int padding;
2332 size_t request_id;
2333 } fastcgi_response_packet;
2335 static int fastcgi_get_packet(server *srv, handler_ctx *hctx, fastcgi_response_packet *packet) {
2336 chunk *c;
2337 size_t offset;
2338 size_t toread;
2339 FCGI_Header *header;
2341 if (!hctx->rb->first) return -1;
2343 packet->b = buffer_init();
2344 packet->len = 0;
2345 packet->type = 0;
2346 packet->padding = 0;
2347 packet->request_id = 0;
2349 offset = 0; toread = 8;
2350 /* get at least the FastCGI header */
2351 for (c = hctx->rb->first; c; c = c->next) {
2352 size_t weHave = buffer_string_length(c->mem) - c->offset;
2354 if (weHave > toread) weHave = toread;
2356 buffer_append_string_len(packet->b, c->mem->ptr + c->offset, weHave);
2357 toread -= weHave;
2358 offset = weHave; /* skip offset bytes in chunk for "real" data */
2360 if (0 == toread) break;
2363 if (buffer_string_length(packet->b) < sizeof(FCGI_Header)) {
2364 /* no header */
2365 if (hctx->plugin_data->conf.debug) {
2366 log_error_write(srv, __FILE__, __LINE__, "sdsds", "FastCGI: header too small:", buffer_string_length(packet->b), "bytes <", sizeof(FCGI_Header), "bytes, waiting for more data");
2369 buffer_free(packet->b);
2371 return -1;
2374 /* we have at least a header, now check how much me have to fetch */
2375 header = (FCGI_Header *)(packet->b->ptr);
2377 packet->len = (header->contentLengthB0 | (header->contentLengthB1 << 8)) + header->paddingLength;
2378 packet->request_id = (header->requestIdB0 | (header->requestIdB1 << 8));
2379 packet->type = header->type;
2380 packet->padding = header->paddingLength;
2382 /* ->b should only be the content */
2383 buffer_string_set_length(packet->b, 0);
2385 if (packet->len) {
2386 /* copy the content */
2387 for (; c && (buffer_string_length(packet->b) < packet->len); c = c->next) {
2388 size_t weWant = packet->len - buffer_string_length(packet->b);
2389 size_t weHave = buffer_string_length(c->mem) - c->offset - offset;
2391 if (weHave > weWant) weHave = weWant;
2393 buffer_append_string_len(packet->b, c->mem->ptr + c->offset + offset, weHave);
2395 /* we only skipped the first bytes as they belonged to the fcgi header */
2396 offset = 0;
2399 if (buffer_string_length(packet->b) < packet->len) {
2400 /* we didn't get the full packet */
2402 buffer_free(packet->b);
2403 return -1;
2406 buffer_string_set_length(packet->b, buffer_string_length(packet->b) - packet->padding);
2409 chunkqueue_mark_written(hctx->rb, packet->len + sizeof(FCGI_Header));
2411 return 0;
2414 static int fcgi_demux_response(server *srv, handler_ctx *hctx) {
2415 int fin = 0;
2416 int toread, ret;
2417 ssize_t r;
2419 plugin_data *p = hctx->plugin_data;
2420 connection *con = hctx->remote_conn;
2421 int fcgi_fd = hctx->fd;
2422 fcgi_extension_host *host= hctx->host;
2423 fcgi_proc *proc = hctx->proc;
2426 * check how much we have to read
2428 if (ioctl(hctx->fd, FIONREAD, &toread)) {
2429 if (errno == EAGAIN) return 0;
2430 log_error_write(srv, __FILE__, __LINE__, "sd",
2431 "unexpected end-of-file (perhaps the fastcgi process died):",
2432 fcgi_fd);
2433 return -1;
2436 if (toread > 0) {
2437 char *mem;
2438 size_t mem_len;
2440 chunkqueue_get_memory(hctx->rb, &mem, &mem_len, 0, toread);
2441 r = read(hctx->fd, mem, mem_len);
2442 chunkqueue_use_memory(hctx->rb, r > 0 ? r : 0);
2444 if (-1 == r) {
2445 if (errno == EAGAIN) return 0;
2446 log_error_write(srv, __FILE__, __LINE__, "sds",
2447 "unexpected end-of-file (perhaps the fastcgi process died):",
2448 fcgi_fd, strerror(errno));
2449 return -1;
2451 } else {
2452 log_error_write(srv, __FILE__, __LINE__, "ssdsb",
2453 "unexpected end-of-file (perhaps the fastcgi process died):",
2454 "pid:", proc->pid,
2455 "socket:", proc->connection_name);
2457 return -1;
2461 * parse the fastcgi packets and forward the content to the write-queue
2464 while (fin == 0) {
2465 fastcgi_response_packet packet;
2467 /* check if we have at least one packet */
2468 if (0 != fastcgi_get_packet(srv, hctx, &packet)) {
2469 /* no full packet */
2470 break;
2473 switch(packet.type) {
2474 case FCGI_STDOUT:
2475 if (packet.len == 0) break;
2477 /* is the header already finished */
2478 if (0 == con->file_started) {
2479 char *c;
2480 data_string *ds;
2482 /* search for header terminator
2484 * if we start with \r\n check if last packet terminated with \r\n
2485 * if we start with \n check if last packet terminated with \n
2486 * search for \r\n\r\n
2487 * search for \n\n
2490 buffer_append_string_buffer(hctx->response_header, packet.b);
2492 if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\r\n\r\n")))) {
2493 char *hend = c + 4; /* header end == body start */
2494 size_t hlen = hend - hctx->response_header->ptr;
2495 buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2496 buffer_string_set_length(hctx->response_header, hlen);
2497 } else if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\n\n")))) {
2498 char *hend = c + 2; /* header end == body start */
2499 size_t hlen = hend - hctx->response_header->ptr;
2500 buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2501 buffer_string_set_length(hctx->response_header, hlen);
2502 } else {
2503 /* no luck, no header found */
2504 break;
2507 /* parse the response header */
2508 if ((ret = fcgi_response_parse(srv, con, p, hctx->response_header))) {
2509 con->http_status = ret;
2510 hctx->send_content_body = 0;
2511 con->file_started = 1;
2512 break;
2515 con->file_started = 1;
2517 if (host->mode == FCGI_AUTHORIZER &&
2518 (con->http_status == 0 ||
2519 con->http_status == 200)) {
2520 /* a authorizer with approved the static request, ignore the content here */
2521 hctx->send_content_body = 0;
2524 if (host->allow_xsendfile && hctx->send_content_body &&
2525 (NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-LIGHTTPD-send-file"))
2526 || NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-Sendfile")))) {
2527 if (0 == http_chunk_append_file(srv, con, ds->value)) {
2528 /* found */
2529 data_string *dcls = (data_string *) array_get_element(con->response.headers, "Content-Length");
2530 if (dcls) buffer_reset(dcls->value);
2531 con->parsed_response &= ~HTTP_CONTENT_LENGTH;
2532 con->response.content_length = -1;
2533 hctx->send_content_body = 0; /* ignore the content */
2534 } else {
2535 log_error_write(srv, __FILE__, __LINE__, "sb",
2536 "send-file error: couldn't get stat_cache entry for:",
2537 ds->value);
2538 con->http_status = 404;
2539 hctx->send_content_body = 0;
2540 con->file_started = 1;
2541 break;
2546 if (hctx->send_content_body && buffer_string_length(packet.b) > 0) {
2547 /* enable chunked-transfer-encoding */
2548 if (con->request.http_version == HTTP_VERSION_1_1 &&
2549 !(con->parsed_response & HTTP_CONTENT_LENGTH)) {
2550 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
2553 http_chunk_append_buffer(srv, con, packet.b);
2555 } else if (hctx->send_content_body && !buffer_string_is_empty(packet.b)) {
2556 if (con->request.http_version == HTTP_VERSION_1_1 &&
2557 !(con->parsed_response & HTTP_CONTENT_LENGTH)) {
2558 /* enable chunked-transfer-encoding */
2559 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
2562 http_chunk_append_buffer(srv, con, packet.b);
2564 break;
2565 case FCGI_STDERR:
2566 if (packet.len == 0) break;
2568 log_error_write_multiline_buffer(srv, __FILE__, __LINE__, packet.b, "s",
2569 "FastCGI-stderr:");
2571 break;
2572 case FCGI_END_REQUEST:
2573 con->file_finished = 1;
2575 if (host->mode != FCGI_AUTHORIZER ||
2576 !(con->http_status == 0 ||
2577 con->http_status == 200)) {
2578 /* send chunk-end if necessary */
2579 http_chunk_close(srv, con);
2582 fin = 1;
2583 break;
2584 default:
2585 log_error_write(srv, __FILE__, __LINE__, "sd",
2586 "FastCGI: header.type not handled: ", packet.type);
2587 break;
2589 buffer_free(packet.b);
2592 return fin;
2595 static int fcgi_restart_dead_procs(server *srv, plugin_data *p, fcgi_extension_host *host) {
2596 fcgi_proc *proc;
2598 for (proc = host->first; proc; proc = proc->next) {
2599 int status;
2601 if (p->conf.debug > 2) {
2602 log_error_write(srv, __FILE__, __LINE__, "sbdddd",
2603 "proc:",
2604 proc->connection_name,
2605 proc->state,
2606 proc->is_local,
2607 proc->load,
2608 proc->pid);
2612 * if the remote side is overloaded, we check back after <n> seconds
2615 switch (proc->state) {
2616 case PROC_STATE_KILLED:
2617 case PROC_STATE_UNSET:
2618 /* this should never happen as long as adaptive spawing is disabled */
2619 force_assert(0);
2621 break;
2622 case PROC_STATE_RUNNING:
2623 break;
2624 case PROC_STATE_OVERLOADED:
2625 if (srv->cur_ts <= proc->disabled_until) break;
2627 proc->state = PROC_STATE_RUNNING;
2628 host->active_procs++;
2630 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2631 "fcgi-server re-enabled:",
2632 host->host, host->port,
2633 host->unixsocket);
2634 break;
2635 case PROC_STATE_DIED_WAIT_FOR_PID:
2636 /* non-local procs don't have PIDs to wait for */
2637 if (!proc->is_local) {
2638 proc->state = PROC_STATE_DIED;
2639 } else {
2640 /* the child should not terminate at all */
2642 for ( ;; ) {
2643 switch(waitpid(proc->pid, &status, WNOHANG)) {
2644 case 0:
2645 /* child is still alive */
2646 if (srv->cur_ts <= proc->disabled_until) break;
2648 proc->state = PROC_STATE_RUNNING;
2649 host->active_procs++;
2651 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2652 "fcgi-server re-enabled:",
2653 host->host, host->port,
2654 host->unixsocket);
2655 break;
2656 case -1:
2657 if (errno == EINTR) continue;
2659 log_error_write(srv, __FILE__, __LINE__, "sd",
2660 "child died somehow, waitpid failed:",
2661 errno);
2662 proc->state = PROC_STATE_DIED;
2663 break;
2664 default:
2665 if (WIFEXITED(status)) {
2666 #if 0
2667 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2668 "child exited, pid:", proc->pid,
2669 "status:", WEXITSTATUS(status));
2670 #endif
2671 } else if (WIFSIGNALED(status)) {
2672 log_error_write(srv, __FILE__, __LINE__, "sd",
2673 "child signaled:",
2674 WTERMSIG(status));
2675 } else {
2676 log_error_write(srv, __FILE__, __LINE__, "sd",
2677 "child died somehow:",
2678 status);
2681 proc->state = PROC_STATE_DIED;
2682 break;
2684 break;
2688 /* fall through if we have a dead proc now */
2689 if (proc->state != PROC_STATE_DIED) break;
2691 case PROC_STATE_DIED:
2692 /* local procs get restarted by us,
2693 * remote ones hopefully by the admin */
2695 if (!buffer_string_is_empty(host->bin_path)) {
2696 /* we still have connections bound to this proc,
2697 * let them terminate first */
2698 if (proc->load != 0) break;
2700 /* restart the child */
2702 if (p->conf.debug) {
2703 log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
2704 "--- fastcgi spawning",
2705 "\n\tsocket", proc->connection_name,
2706 "\n\tcurrent:", 1, "/", host->max_procs);
2709 if (fcgi_spawn_connection(srv, p, host, proc)) {
2710 log_error_write(srv, __FILE__, __LINE__, "s",
2711 "ERROR: spawning fcgi failed.");
2712 return HANDLER_ERROR;
2714 } else {
2715 if (srv->cur_ts <= proc->disabled_until) break;
2717 proc->state = PROC_STATE_RUNNING;
2718 host->active_procs++;
2720 log_error_write(srv, __FILE__, __LINE__, "sb",
2721 "fcgi-server re-enabled:",
2722 proc->connection_name);
2724 break;
2728 return 0;
2731 static handler_t fcgi_write_request(server *srv, handler_ctx *hctx) {
2732 plugin_data *p = hctx->plugin_data;
2733 fcgi_extension_host *host= hctx->host;
2734 connection *con = hctx->remote_conn;
2735 fcgi_proc *proc;
2737 int ret;
2739 /* sanity check:
2740 * - host != NULL
2741 * - either:
2742 * - tcp socket (do not check host->host->uses, as it may be not set which means INADDR_LOOPBACK)
2743 * - unix socket
2745 if (!host) {
2746 log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: host = NULL");
2747 return HANDLER_ERROR;
2749 if ((!host->port && buffer_string_is_empty(host->unixsocket))) {
2750 log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: neither host->port nor host->unixsocket is set");
2751 return HANDLER_ERROR;
2754 /* we can't handle this in the switch as we have to fall through in it */
2755 if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
2756 int socket_error;
2757 socklen_t socket_error_len = sizeof(socket_error);
2759 /* try to finish the connect() */
2760 if (0 != getsockopt(hctx->fd, SOL_SOCKET, SO_ERROR, &socket_error, &socket_error_len)) {
2761 log_error_write(srv, __FILE__, __LINE__, "ss",
2762 "getsockopt failed:", strerror(errno));
2764 fcgi_host_disable(srv, hctx);
2766 return HANDLER_ERROR;
2768 if (socket_error != 0) {
2769 if (!hctx->proc->is_local || p->conf.debug) {
2770 /* local procs get restarted */
2772 log_error_write(srv, __FILE__, __LINE__, "sssb",
2773 "establishing connection failed:", strerror(socket_error),
2774 "socket:", hctx->proc->connection_name);
2777 fcgi_host_disable(srv, hctx);
2778 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2779 "backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2780 "reconnects:", hctx->reconnects,
2781 "load:", host->load);
2783 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2784 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2786 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2788 return HANDLER_ERROR;
2790 /* go on with preparing the request */
2791 hctx->state = FCGI_STATE_PREPARE_WRITE;
2795 switch(hctx->state) {
2796 case FCGI_STATE_CONNECT_DELAYED:
2797 /* should never happen */
2798 return HANDLER_WAIT_FOR_EVENT;
2799 case FCGI_STATE_INIT:
2800 /* do we have a running process for this host (max-procs) ? */
2801 hctx->proc = NULL;
2803 for (proc = hctx->host->first;
2804 proc && proc->state != PROC_STATE_RUNNING;
2805 proc = proc->next);
2807 /* all children are dead */
2808 if (proc == NULL) {
2809 hctx->fde_ndx = -1;
2811 return HANDLER_ERROR;
2814 hctx->proc = proc;
2816 /* check the other procs if they have a lower load */
2817 for (proc = proc->next; proc; proc = proc->next) {
2818 if (proc->state != PROC_STATE_RUNNING) continue;
2819 if (proc->load < hctx->proc->load) hctx->proc = proc;
2822 ret = buffer_string_is_empty(host->unixsocket) ? AF_INET : AF_UNIX;
2824 if (-1 == (hctx->fd = socket(ret, SOCK_STREAM, 0))) {
2825 if (errno == EMFILE ||
2826 errno == EINTR) {
2827 log_error_write(srv, __FILE__, __LINE__, "sd",
2828 "wait for fd at connection:", con->fd);
2830 return HANDLER_WAIT_FOR_FD;
2833 log_error_write(srv, __FILE__, __LINE__, "ssdd",
2834 "socket failed:", strerror(errno), srv->cur_fds, srv->max_fds);
2835 return HANDLER_ERROR;
2837 hctx->fde_ndx = -1;
2839 srv->cur_fds++;
2841 fdevent_register(srv->ev, hctx->fd, fcgi_handle_fdevent, hctx);
2843 if (-1 == fdevent_fcntl_set(srv->ev, hctx->fd)) {
2844 log_error_write(srv, __FILE__, __LINE__, "ss",
2845 "fcntl failed:", strerror(errno));
2847 return HANDLER_ERROR;
2850 if (hctx->proc->is_local) {
2851 hctx->pid = hctx->proc->pid;
2854 switch (fcgi_establish_connection(srv, hctx)) {
2855 case CONNECTION_DELAYED:
2856 /* connection is in progress, wait for an event and call getsockopt() below */
2858 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2860 fcgi_set_state(srv, hctx, FCGI_STATE_CONNECT_DELAYED);
2861 return HANDLER_WAIT_FOR_EVENT;
2862 case CONNECTION_OVERLOADED:
2863 /* cool down the backend, it is overloaded
2864 * -> EAGAIN */
2866 if (hctx->host->disable_time) {
2867 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2868 "backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2869 "reconnects:", hctx->reconnects,
2870 "load:", host->load);
2872 hctx->proc->disabled_until = srv->cur_ts + hctx->host->disable_time;
2873 if (hctx->proc->state == PROC_STATE_RUNNING) hctx->host->active_procs--;
2874 hctx->proc->state = PROC_STATE_OVERLOADED;
2877 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2878 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".overloaded"));
2880 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2882 return HANDLER_ERROR;
2883 case CONNECTION_DEAD:
2884 /* we got a hard error from the backend like
2885 * - ECONNREFUSED for tcp-ip sockets
2886 * - ENOENT for unix-domain-sockets
2888 * for check if the host is back in hctx->host->disable_time seconds
2889 * */
2891 fcgi_host_disable(srv, hctx);
2893 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2894 "backend died; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2895 "reconnects:", hctx->reconnects,
2896 "load:", host->load);
2898 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2899 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2901 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2903 return HANDLER_ERROR;
2904 case CONNECTION_OK:
2905 /* everything is ok, go on */
2907 fcgi_set_state(srv, hctx, FCGI_STATE_PREPARE_WRITE);
2909 break;
2911 /* fallthrough */
2912 case FCGI_STATE_PREPARE_WRITE:
2913 /* ok, we have the connection */
2915 fcgi_proc_load_inc(srv, hctx);
2916 hctx->got_proc = 1;
2918 status_counter_inc(srv, CONST_STR_LEN("fastcgi.requests"));
2920 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2921 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".connected"));
2923 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2925 if (p->conf.debug) {
2926 log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
2927 "got proc:",
2928 "pid:", hctx->proc->pid,
2929 "socket:", hctx->proc->connection_name,
2930 "load:", hctx->proc->load);
2933 /* move the proc-list entry down the list */
2934 if (hctx->request_id == 0) {
2935 hctx->request_id = 1; /* always use id 1 as we don't use multiplexing */
2936 } else {
2937 log_error_write(srv, __FILE__, __LINE__, "sd",
2938 "fcgi-request is already in use:", hctx->request_id);
2941 if (-1 == fcgi_create_env(srv, hctx, hctx->request_id)) return HANDLER_ERROR;
2943 fcgi_set_state(srv, hctx, FCGI_STATE_WRITE);
2944 /* fall through */
2945 case FCGI_STATE_WRITE:
2946 ret = srv->network_backend_write(srv, con, hctx->fd, hctx->wb, MAX_WRITE_LIMIT);
2948 chunkqueue_remove_finished_chunks(hctx->wb);
2950 if (ret < 0) {
2951 switch(errno) {
2952 case EPIPE:
2953 case ENOTCONN:
2954 case ECONNRESET:
2955 /* the connection got dropped after accept()
2956 * we don't care about that - if you accept() it, you have to handle it.
2959 log_error_write(srv, __FILE__, __LINE__, "ssosb",
2960 "connection was dropped after accept() (perhaps the fastcgi process died),",
2961 "write-offset:", hctx->wb->bytes_out,
2962 "socket:", hctx->proc->connection_name);
2964 return HANDLER_ERROR;
2965 default:
2966 log_error_write(srv, __FILE__, __LINE__, "ssd",
2967 "write failed:", strerror(errno), errno);
2969 return HANDLER_ERROR;
2973 if (hctx->wb->bytes_out == hctx->wb->bytes_in) {
2974 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2975 fcgi_set_state(srv, hctx, FCGI_STATE_READ);
2976 } else {
2977 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN|FDEVENT_OUT);
2980 return HANDLER_WAIT_FOR_EVENT;
2981 case FCGI_STATE_READ:
2982 /* waiting for a response */
2983 return HANDLER_WAIT_FOR_EVENT;
2984 default:
2985 log_error_write(srv, __FILE__, __LINE__, "s", "(debug) unknown state");
2986 return HANDLER_ERROR;
2991 /* might be called on fdevent after a connect() is delay too
2992 * */
2993 static handler_t fcgi_send_request(server *srv, handler_ctx *hctx) {
2994 fcgi_extension_host *host;
2995 handler_t rc;
2997 /* we don't have a host yet, choose one
2998 * -> this happens in the first round
2999 * and when the host died and we have to select a new one */
3000 if (hctx->host == NULL) {
3001 size_t k;
3002 int ndx, used = -1;
3004 /* check if the next server has no load. */
3005 ndx = hctx->ext->last_used_ndx + 1;
3006 if(ndx >= (int) hctx->ext->used || ndx < 0) ndx = 0;
3007 host = hctx->ext->hosts[ndx];
3008 if (host->load > 0) {
3009 /* get backend with the least load. */
3010 for (k = 0, ndx = -1; k < hctx->ext->used; k++) {
3011 host = hctx->ext->hosts[k];
3013 /* we should have at least one proc that can do something */
3014 if (host->active_procs == 0) continue;
3016 if (used == -1 || host->load < used) {
3017 used = host->load;
3019 ndx = k;
3024 /* found a server */
3025 if (ndx == -1) {
3026 /* all hosts are down */
3028 fcgi_connection_close(srv, hctx);
3030 return HANDLER_FINISHED;
3033 hctx->ext->last_used_ndx = ndx;
3034 host = hctx->ext->hosts[ndx];
3037 * if check-local is disabled, use the uri.path handler
3041 /* init handler-context */
3043 /* we put a connection on this host, move the other new connections to other hosts
3045 * as soon as hctx->host is unassigned, decrease the load again */
3046 fcgi_host_assign(srv, hctx, host);
3047 hctx->proc = NULL;
3048 } else {
3049 host = hctx->host;
3052 /* ok, create the request */
3053 rc = fcgi_write_request(srv, hctx);
3054 if (HANDLER_ERROR != rc) {
3055 return rc;
3056 } else {
3057 plugin_data *p = hctx->plugin_data;
3058 connection *con = hctx->remote_conn;
3060 if (hctx->state == FCGI_STATE_INIT ||
3061 hctx->state == FCGI_STATE_CONNECT_DELAYED) {
3062 fcgi_restart_dead_procs(srv, p, host);
3064 /* cleanup this request and let the request handler start this request again */
3065 if (hctx->reconnects < 5) {
3066 fcgi_reconnect(srv, hctx);
3068 return HANDLER_COMEBACK;
3069 } else {
3070 fcgi_connection_close(srv, hctx);
3071 con->http_status = 503;
3073 return HANDLER_FINISHED;
3075 } else {
3076 int status = con->http_status;
3077 fcgi_connection_close(srv, hctx);
3078 con->http_status = (status == 400) ? 400 : 503; /* see FCGI_ENV_ADD_CHECK() for 400 error */
3080 return HANDLER_FINISHED;
3086 SUBREQUEST_FUNC(mod_fastcgi_handle_subrequest) {
3087 plugin_data *p = p_d;
3089 handler_ctx *hctx = con->plugin_ctx[p->id];
3091 if (NULL == hctx) return HANDLER_GO_ON;
3093 /* not my job */
3094 if (con->mode != p->id) return HANDLER_GO_ON;
3096 if (con->state == CON_STATE_READ_POST) {
3097 handler_t r = connection_handle_read_post_state(srv, con);
3098 if (r != HANDLER_GO_ON) return r;
3101 return (hctx->state != FCGI_STATE_READ)
3102 ? fcgi_send_request(srv, hctx)
3103 : HANDLER_WAIT_FOR_EVENT;
3106 static handler_t fcgi_handle_fdevent(server *srv, void *ctx, int revents) {
3107 handler_ctx *hctx = ctx;
3108 connection *con = hctx->remote_conn;
3109 plugin_data *p = hctx->plugin_data;
3111 fcgi_proc *proc = hctx->proc;
3112 fcgi_extension_host *host= hctx->host;
3114 joblist_append(srv, con);
3116 if ((revents & FDEVENT_IN) &&
3117 hctx->state == FCGI_STATE_READ) {
3118 switch (fcgi_demux_response(srv, hctx)) {
3119 case 0:
3120 break;
3121 case 1:
3123 if (host->mode == FCGI_AUTHORIZER &&
3124 (con->http_status == 200 ||
3125 con->http_status == 0)) {
3127 * If we are here in AUTHORIZER mode then a request for authorizer
3128 * was processed already, and status 200 has been returned. We need
3129 * now to handle authorized request.
3132 buffer_copy_buffer(con->physical.doc_root, host->docroot);
3133 buffer_copy_buffer(con->physical.basedir, host->docroot);
3135 buffer_copy_buffer(con->physical.path, host->docroot);
3136 buffer_append_string_buffer(con->physical.path, con->uri.path);
3138 con->mode = DIRECT;/*(avoid changing con->state, con->http_status)*/
3139 fcgi_connection_close(srv, hctx);
3140 con->http_status = 0;
3141 con->file_started = 1; /* fcgi_extension won't touch the request afterwards */
3142 } else {
3143 /* we are done */
3144 fcgi_connection_close(srv, hctx);
3147 return HANDLER_FINISHED;
3148 case -1:
3149 if (proc->pid && proc->state != PROC_STATE_DIED) {
3150 int status;
3152 /* only fetch the zombie if it is not already done */
3154 switch(waitpid(proc->pid, &status, WNOHANG)) {
3155 case 0:
3156 /* child is still alive */
3157 break;
3158 case -1:
3159 break;
3160 default:
3161 /* the child should not terminate at all */
3162 if (WIFEXITED(status)) {
3163 log_error_write(srv, __FILE__, __LINE__, "sdsd",
3164 "child exited, pid:", proc->pid,
3165 "status:", WEXITSTATUS(status));
3166 } else if (WIFSIGNALED(status)) {
3167 log_error_write(srv, __FILE__, __LINE__, "sd",
3168 "child signaled:",
3169 WTERMSIG(status));
3170 } else {
3171 log_error_write(srv, __FILE__, __LINE__, "sd",
3172 "child died somehow:",
3173 status);
3176 if (p->conf.debug) {
3177 log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
3178 "--- fastcgi spawning",
3179 "\n\tsocket", proc->connection_name,
3180 "\n\tcurrent:", 1, "/", host->max_procs);
3183 if (fcgi_spawn_connection(srv, p, host, proc)) {
3184 /* respawning failed, retry later */
3185 proc->state = PROC_STATE_DIED;
3187 log_error_write(srv, __FILE__, __LINE__, "s",
3188 "respawning failed, will retry later");
3191 break;
3195 if (con->file_started == 0) {
3196 /* nothing has been sent out yet, try to use another child */
3198 if (hctx->wb->bytes_out == 0 &&
3199 hctx->reconnects < 5) {
3201 log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3202 "response not received, request not sent",
3203 "on socket:", proc->connection_name,
3204 "for", con->uri.path, "?", con->uri.query, ", reconnecting");
3206 fcgi_reconnect(srv, hctx);
3208 return HANDLER_COMEBACK;
3211 log_error_write(srv, __FILE__, __LINE__, "sosbsBSBs",
3212 "response not received, request sent:", hctx->wb->bytes_out,
3213 "on socket:", proc->connection_name,
3214 "for", con->uri.path, "?", con->uri.query, ", closing connection");
3216 fcgi_connection_close(srv, hctx);
3217 } else {
3218 /* response might have been already started, kill the connection */
3219 log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3220 "response already sent out, but backend returned error",
3221 "on socket:", proc->connection_name,
3222 "for", con->uri.path, "?", con->uri.query, ", terminating connection");
3224 con->keep_alive = 0;
3225 con->file_finished = 1;
3226 con->mode = DIRECT; /*(avoid sending final chunked block)*/
3227 fcgi_connection_close(srv, hctx);
3230 return HANDLER_FINISHED;
3234 if (revents & FDEVENT_OUT) {
3235 if (hctx->state == FCGI_STATE_CONNECT_DELAYED ||
3236 hctx->state == FCGI_STATE_WRITE) {
3237 /* we are allowed to send something out
3239 * 1. in an unfinished connect() call
3240 * 2. in an unfinished write() call (long POST request)
3242 return fcgi_send_request(srv, hctx); /*(might invalidate hctx)*/
3243 } else {
3244 log_error_write(srv, __FILE__, __LINE__, "sd",
3245 "got a FDEVENT_OUT and didn't know why:",
3246 hctx->state);
3250 /* perhaps this issue is already handled */
3251 if (revents & FDEVENT_HUP) {
3252 if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
3253 /* getoptsock will catch this one (right ?)
3255 * if we are in connect we might get an EINPROGRESS
3256 * in the first call and an FDEVENT_HUP in the
3257 * second round
3259 * FIXME: as it is a bit ugly.
3262 fcgi_send_request(srv, hctx);
3263 } else if (hctx->state == FCGI_STATE_READ &&
3264 hctx->proc->port == 0) {
3265 /* FIXME:
3267 * ioctl says 8192 bytes to read from PHP and we receive directly a HUP for the socket
3268 * even if the FCGI_FIN packet is not received yet
3270 } else {
3271 log_error_write(srv, __FILE__, __LINE__, "sBSbsbsd",
3272 "error: unexpected close of fastcgi connection for",
3273 con->uri.path, "?", con->uri.query,
3274 "(no fastcgi process on socket:", proc->connection_name, "?)",
3275 hctx->state);
3277 fcgi_connection_close(srv, hctx);
3279 } else if (revents & FDEVENT_ERR) {
3280 log_error_write(srv, __FILE__, __LINE__, "s",
3281 "fcgi: got a FDEVENT_ERR. Don't know why.");
3283 if (con->file_started) {
3284 con->keep_alive = 0;
3285 con->file_finished = 1;
3286 con->mode = DIRECT; /*(avoid sending final chunked block)*/
3288 fcgi_connection_close(srv, hctx);
3291 return HANDLER_FINISHED;
3294 #define PATCH(x) \
3295 p->conf.x = s->x;
3296 static int fcgi_patch_connection(server *srv, connection *con, plugin_data *p) {
3297 size_t i, j;
3298 plugin_config *s = p->config_storage[0];
3300 PATCH(exts);
3301 PATCH(debug);
3302 PATCH(ext_mapping);
3304 /* skip the first, the global context */
3305 for (i = 1; i < srv->config_context->used; i++) {
3306 data_config *dc = (data_config *)srv->config_context->data[i];
3307 s = p->config_storage[i];
3309 /* condition didn't match */
3310 if (!config_check_cond(srv, con, dc)) continue;
3312 /* merge config */
3313 for (j = 0; j < dc->value->used; j++) {
3314 data_unset *du = dc->value->data[j];
3316 if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.server"))) {
3317 PATCH(exts);
3318 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.debug"))) {
3319 PATCH(debug);
3320 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.map-extensions"))) {
3321 PATCH(ext_mapping);
3326 return 0;
3328 #undef PATCH
3331 static handler_t fcgi_check_extension(server *srv, connection *con, void *p_d, int uri_path_handler) {
3332 plugin_data *p = p_d;
3333 size_t s_len;
3334 size_t k;
3335 buffer *fn;
3336 fcgi_extension *extension = NULL;
3337 fcgi_extension_host *host = NULL;
3339 if (con->mode != DIRECT) return HANDLER_GO_ON;
3341 /* Possibly, we processed already this request */
3342 if (con->file_started == 1) return HANDLER_GO_ON;
3344 fn = uri_path_handler ? con->uri.path : con->physical.path;
3346 if (buffer_string_is_empty(fn)) return HANDLER_GO_ON;
3348 s_len = buffer_string_length(fn);
3350 fcgi_patch_connection(srv, con, p);
3352 /* fastcgi.map-extensions maps extensions to existing fastcgi.server entries
3354 * fastcgi.map-extensions = ( ".php3" => ".php" )
3356 * fastcgi.server = ( ".php" => ... )
3358 * */
3360 /* check if extension-mapping matches */
3361 for (k = 0; k < p->conf.ext_mapping->used; k++) {
3362 data_string *ds = (data_string *)p->conf.ext_mapping->data[k];
3363 size_t ct_len; /* length of the config entry */
3365 if (buffer_is_empty(ds->key)) continue;
3367 ct_len = buffer_string_length(ds->key);
3369 if (s_len < ct_len) continue;
3371 /* found a mapping */
3372 if (0 == strncmp(fn->ptr + s_len - ct_len, ds->key->ptr, ct_len)) {
3373 /* check if we know the extension */
3375 /* we can reuse k here */
3376 for (k = 0; k < p->conf.exts->used; k++) {
3377 extension = p->conf.exts->exts[k];
3379 if (buffer_is_equal(ds->value, extension->key)) {
3380 break;
3384 if (k == p->conf.exts->used) {
3385 /* found nothign */
3386 extension = NULL;
3388 break;
3392 if (extension == NULL) {
3393 size_t uri_path_len = buffer_string_length(con->uri.path);
3395 /* check if extension matches */
3396 for (k = 0; k < p->conf.exts->used; k++) {
3397 size_t ct_len; /* length of the config entry */
3398 fcgi_extension *ext = p->conf.exts->exts[k];
3400 if (buffer_is_empty(ext->key)) continue;
3402 ct_len = buffer_string_length(ext->key);
3404 /* check _url_ in the form "/fcgi_pattern" */
3405 if (ext->key->ptr[0] == '/') {
3406 if ((ct_len <= uri_path_len) &&
3407 (strncmp(con->uri.path->ptr, ext->key->ptr, ct_len) == 0)) {
3408 extension = ext;
3409 break;
3411 } else if ((ct_len <= s_len) && (0 == strncmp(fn->ptr + s_len - ct_len, ext->key->ptr, ct_len))) {
3412 /* check extension in the form ".fcg" */
3413 extension = ext;
3414 break;
3417 /* extension doesn't match */
3418 if (NULL == extension) {
3419 return HANDLER_GO_ON;
3423 /* check if we have at least one server for this extension up and running */
3424 for (k = 0; k < extension->used; k++) {
3425 fcgi_extension_host *h = extension->hosts[k];
3427 /* we should have at least one proc that can do something */
3428 if (h->active_procs == 0) {
3429 continue;
3432 /* we found one host that is alive */
3433 host = h;
3434 break;
3437 if (!host) {
3438 /* sorry, we don't have a server alive for this ext */
3439 con->http_status = 500;
3440 con->mode = DIRECT;
3442 /* only send the 'no handler' once */
3443 if (!extension->note_is_sent) {
3444 extension->note_is_sent = 1;
3446 log_error_write(srv, __FILE__, __LINE__, "sBSbsbs",
3447 "all handlers for", con->uri.path, "?", con->uri.query,
3448 "on", extension->key,
3449 "are down.");
3452 return HANDLER_FINISHED;
3455 /* a note about no handler is not sent yet */
3456 extension->note_is_sent = 0;
3459 * if check-local is disabled, use the uri.path handler
3463 /* init handler-context */
3464 if (uri_path_handler) {
3465 if (host->check_local == 0) {
3466 handler_ctx *hctx;
3467 char *pathinfo;
3469 hctx = handler_ctx_init();
3471 hctx->remote_conn = con;
3472 hctx->plugin_data = p;
3473 hctx->proc = NULL;
3474 hctx->ext = extension;
3477 hctx->conf.exts = p->conf.exts;
3478 hctx->conf.debug = p->conf.debug;
3480 con->plugin_ctx[p->id] = hctx;
3482 con->mode = p->id;
3484 if (con->conf.log_request_handling) {
3485 log_error_write(srv, __FILE__, __LINE__, "s",
3486 "handling it in mod_fastcgi");
3489 /* do not split path info for authorizer */
3490 if (host->mode != FCGI_AUTHORIZER) {
3491 /* the prefix is the SCRIPT_NAME,
3492 * everything from start to the next slash
3493 * this is important for check-local = "disable"
3495 * if prefix = /admin.fcgi
3497 * /admin.fcgi/foo/bar
3499 * SCRIPT_NAME = /admin.fcgi
3500 * PATH_INFO = /foo/bar
3502 * if prefix = /fcgi-bin/
3504 * /fcgi-bin/foo/bar
3506 * SCRIPT_NAME = /fcgi-bin/foo
3507 * PATH_INFO = /bar
3509 * if prefix = /, and fix-root-path-name is enable
3511 * /fcgi-bin/foo/bar
3513 * SCRIPT_NAME = /fcgi-bin/foo
3514 * PATH_INFO = /bar
3518 /* the rewrite is only done for /prefix/? matches */
3519 if (host->fix_root_path_name && extension->key->ptr[0] == '/' && extension->key->ptr[1] == '\0') {
3520 buffer_copy_string(con->request.pathinfo, con->uri.path->ptr);
3521 buffer_string_set_length(con->uri.path, 0);
3522 } else if (extension->key->ptr[0] == '/' &&
3523 buffer_string_length(con->uri.path) > buffer_string_length(extension->key) &&
3524 NULL != (pathinfo = strchr(con->uri.path->ptr + buffer_string_length(extension->key), '/'))) {
3525 /* rewrite uri.path and pathinfo */
3527 buffer_copy_string(con->request.pathinfo, pathinfo);
3528 buffer_string_set_length(con->uri.path, buffer_string_length(con->uri.path) - buffer_string_length(con->request.pathinfo));
3532 } else {
3533 handler_ctx *hctx;
3534 hctx = handler_ctx_init();
3536 hctx->remote_conn = con;
3537 hctx->plugin_data = p;
3538 hctx->proc = NULL;
3539 hctx->ext = extension;
3541 hctx->conf.exts = p->conf.exts;
3542 hctx->conf.debug = p->conf.debug;
3544 con->plugin_ctx[p->id] = hctx;
3546 con->mode = p->id;
3548 if (con->conf.log_request_handling) {
3549 log_error_write(srv, __FILE__, __LINE__, "s", "handling it in mod_fastcgi");
3553 return HANDLER_GO_ON;
3556 /* uri-path handler */
3557 static handler_t fcgi_check_extension_1(server *srv, connection *con, void *p_d) {
3558 return fcgi_check_extension(srv, con, p_d, 1);
3561 /* start request handler */
3562 static handler_t fcgi_check_extension_2(server *srv, connection *con, void *p_d) {
3563 return fcgi_check_extension(srv, con, p_d, 0);
3567 TRIGGER_FUNC(mod_fastcgi_handle_trigger) {
3568 plugin_data *p = p_d;
3569 size_t i, j, n;
3572 /* perhaps we should kill a connect attempt after 10-15 seconds
3574 * currently we wait for the TCP timeout which is 180 seconds on Linux
3580 /* check all children if they are still up */
3582 for (i = 0; i < srv->config_context->used; i++) {
3583 plugin_config *conf;
3584 fcgi_exts *exts;
3586 conf = p->config_storage[i];
3588 exts = conf->exts;
3590 for (j = 0; j < exts->used; j++) {
3591 fcgi_extension *ex;
3593 ex = exts->exts[j];
3595 for (n = 0; n < ex->used; n++) {
3597 fcgi_proc *proc;
3598 fcgi_extension_host *host;
3600 host = ex->hosts[n];
3602 fcgi_restart_dead_procs(srv, p, host);
3604 for (proc = host->unused_procs; proc; proc = proc->next) {
3605 int status;
3607 if (proc->pid == 0) continue;
3609 switch (waitpid(proc->pid, &status, WNOHANG)) {
3610 case 0:
3611 /* child still running after timeout, good */
3612 break;
3613 case -1:
3614 if (errno != EINTR) {
3615 /* no PID found ? should never happen */
3616 log_error_write(srv, __FILE__, __LINE__, "sddss",
3617 "pid ", proc->pid, proc->state,
3618 "not found:", strerror(errno));
3620 #if 0
3621 if (errno == ECHILD) {
3622 /* someone else has cleaned up for us */
3623 proc->pid = 0;
3624 proc->state = PROC_STATE_UNSET;
3626 #endif
3628 break;
3629 default:
3630 /* the child should not terminate at all */
3631 if (WIFEXITED(status)) {
3632 if (proc->state != PROC_STATE_KILLED) {
3633 log_error_write(srv, __FILE__, __LINE__, "sdb",
3634 "child exited:",
3635 WEXITSTATUS(status), proc->connection_name);
3637 } else if (WIFSIGNALED(status)) {
3638 if (WTERMSIG(status) != SIGTERM) {
3639 log_error_write(srv, __FILE__, __LINE__, "sd",
3640 "child signaled:",
3641 WTERMSIG(status));
3643 } else {
3644 log_error_write(srv, __FILE__, __LINE__, "sd",
3645 "child died somehow:",
3646 status);
3648 proc->pid = 0;
3649 if (proc->state == PROC_STATE_RUNNING) host->active_procs--;
3650 proc->state = PROC_STATE_UNSET;
3651 host->max_id--;
3658 return HANDLER_GO_ON;
3662 int mod_fastcgi_plugin_init(plugin *p);
3663 int mod_fastcgi_plugin_init(plugin *p) {
3664 p->version = LIGHTTPD_VERSION_ID;
3665 p->name = buffer_init_string("fastcgi");
3667 p->init = mod_fastcgi_init;
3668 p->cleanup = mod_fastcgi_free;
3669 p->set_defaults = mod_fastcgi_set_defaults;
3670 p->connection_reset = fcgi_connection_reset;
3671 p->handle_connection_close = fcgi_connection_reset;
3672 p->handle_uri_clean = fcgi_check_extension_1;
3673 p->handle_subrequest_start = fcgi_check_extension_2;
3674 p->handle_subrequest = mod_fastcgi_handle_subrequest;
3675 p->handle_trigger = mod_fastcgi_handle_trigger;
3677 p->data = NULL;
3679 return 0;