[core] compile fix for Mac OS X 10.6 (old) (fixes #2773)
[lighttpd.git] / src / mod_fastcgi.c
blobdb74c5f88ff0e1f2f71f2125bd6710c779b32165
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
53 * TODO:
55 * - add timeout for a connect to a non-fastcgi process
56 * (use state_timestamp + state)
60 typedef struct fcgi_proc {
61 size_t id; /* id will be between 1 and max_procs */
62 buffer *unixsocket; /* config.socket + "-" + id */
63 unsigned port; /* config.port + pno */
65 buffer *connection_name; /* either tcp:<host>:<port> or unix:<socket> for debugging purposes */
67 pid_t pid; /* PID of the spawned process (0 if not spawned locally) */
70 size_t load; /* number of requests waiting on this process */
72 size_t requests; /* see max_requests */
73 struct fcgi_proc *prev, *next; /* see first */
75 time_t disabled_until; /* this proc is disabled until, use something else until then */
77 int is_local;
79 enum {
80 PROC_STATE_UNSET, /* init-phase */
81 PROC_STATE_RUNNING, /* alive */
82 PROC_STATE_OVERLOADED, /* listen-queue is full,
83 don't send anything to this proc for the next 2 seconds */
84 PROC_STATE_DIED_WAIT_FOR_PID, /* */
85 PROC_STATE_DIED, /* marked as dead, should be restarted */
86 PROC_STATE_KILLED /* was killed as we don't have the load anymore */
87 } state;
88 } fcgi_proc;
90 typedef struct {
91 /* the key that is used to reference this value */
92 buffer *id;
94 /* list of processes handling this extension
95 * sorted by lowest load
97 * whenever a job is done move it up in the list
98 * until it is sorted, move it down as soon as the
99 * job is started
101 fcgi_proc *first;
102 fcgi_proc *unused_procs;
105 * spawn at least min_procs, at max_procs.
107 * as soon as the load of the first entry
108 * is max_load_per_proc we spawn a new one
109 * and add it to the first entry and give it
110 * the load
114 unsigned short max_procs;
115 size_t num_procs; /* how many procs are started */
116 size_t active_procs; /* how many of them are really running, i.e. state = PROC_STATE_RUNNING */
119 * time after a disabled remote connection is tried to be re-enabled
124 unsigned short disable_time;
127 * some fastcgi processes get a little bit larger
128 * than wanted. max_requests_per_proc kills a
129 * process after a number of handled requests.
132 size_t max_requests_per_proc;
135 /* config */
138 * host:port
140 * if host is one of the local IP adresses the
141 * whole connection is local
143 * if port is not 0, and host is not specified,
144 * "localhost" (INADDR_LOOPBACK) is assumed.
147 buffer *host;
148 unsigned short port;
149 sa_family_t family;
152 * Unix Domain Socket
154 * instead of TCP/IP we can use Unix Domain Sockets
155 * - more secure (you have fileperms to play with)
156 * - more control (on locally)
157 * - more speed (no extra overhead)
159 buffer *unixsocket;
161 /* if socket is local we can start the fastcgi
162 * process ourself
164 * bin-path is the path to the binary
166 * check min_procs and max_procs for the number
167 * of process to start up
169 buffer *bin_path;
171 /* bin-path is set bin-environment is taken to
172 * create the environement before starting the
173 * FastCGI process
176 array *bin_env;
178 array *bin_env_copy;
181 * docroot-translation between URL->phys and the
182 * remote host
184 * reasons:
185 * - different dir-layout if remote
186 * - chroot if local
189 buffer *docroot;
192 * check_local tells you if the phys file is stat()ed
193 * or not. FastCGI doesn't care if the service is
194 * remote. If the web-server side doesn't contain
195 * the fastcgi-files we should not stat() for them
196 * and say '404 not found'.
198 unsigned short check_local;
201 * append PATH_INFO to SCRIPT_FILENAME
203 * php needs this if cgi.fix_pathinfo is provided
207 unsigned short break_scriptfilename_for_php;
210 * workaround for program when prefix="/"
212 * rule to build PATH_INFO is hardcoded for when check_local is disabled
213 * enable this option to use the workaround
217 unsigned short fix_root_path_name;
220 * If the backend includes X-Sendfile in the response
221 * we use the value as filename and ignore the content.
224 unsigned short xsendfile_allow;
225 array *xsendfile_docroot;
227 ssize_t load; /* replace by host->load */
229 size_t max_id; /* corresponds most of the time to
230 num_procs.
232 only if a process is killed max_id waits for the process itself
233 to die and decrements it afterwards */
235 buffer *strip_request_uri;
237 unsigned short kill_signal; /* we need a setting for this as libfcgi
238 applications prefer SIGUSR1 while the
239 rest of the world would use SIGTERM
240 *sigh* */
242 int listen_backlog;
243 int refcount;
244 } fcgi_extension_host;
247 * one extension can have multiple hosts assigned
248 * one host can spawn additional processes on the same
249 * socket (if we control it)
251 * ext -> host -> procs
252 * 1:n 1:n
254 * if the fastcgi process is remote that whole goes down
255 * to
257 * ext -> host -> procs
258 * 1:n 1:1
260 * in case of PHP and FCGI_CHILDREN we have again a procs
261 * but we don't control it directly.
265 typedef struct {
266 buffer *key; /* like .php */
268 int note_is_sent;
269 int last_used_ndx;
271 fcgi_extension_host **hosts;
273 size_t used;
274 size_t size;
275 } fcgi_extension;
277 typedef struct {
278 fcgi_extension **exts;
280 size_t used;
281 size_t size;
282 } fcgi_exts;
285 typedef struct {
286 fcgi_exts *exts;
287 fcgi_exts *exts_auth;
288 fcgi_exts *exts_resp;
290 array *ext_mapping;
292 unsigned int debug;
293 } plugin_config;
295 typedef struct {
296 char **ptr;
298 size_t size;
299 size_t used;
300 } char_array;
302 /* generic plugin data, shared between all connections */
303 typedef struct {
304 PLUGIN_DATA;
306 buffer *fcgi_env;
308 buffer *path;
310 buffer *statuskey;
312 plugin_config **config_storage;
314 plugin_config conf; /* this is only used as long as no handler_ctx is setup */
315 } plugin_data;
317 /* connection specific data */
318 typedef enum {
319 FCGI_STATE_INIT,
320 FCGI_STATE_CONNECT_DELAYED,
321 FCGI_STATE_PREPARE_WRITE,
322 FCGI_STATE_WRITE,
323 FCGI_STATE_READ
324 } fcgi_connection_state_t;
326 typedef struct {
327 fcgi_proc *proc;
328 fcgi_extension_host *host;
329 fcgi_extension *ext;
330 fcgi_extension *ext_auth; /* (might be used in future to allow multiple authorizers)*/
331 unsigned short fcgi_mode; /* FastCGI mode: FCGI_AUTHORIZER or FCGI_RESPONDER */
333 fcgi_connection_state_t state;
334 time_t state_timestamp;
336 chunkqueue *rb; /* read queue */
337 chunkqueue *wb; /* write queue */
338 off_t wb_reqlen;
340 buffer *response_header;
342 int fd; /* fd to the fastcgi process */
343 int fde_ndx; /* index into the fd-event buffer */
345 pid_t pid;
346 int got_proc;
347 int reconnects; /* number of reconnect attempts */
349 int request_id;
350 int send_content_body;
352 plugin_config conf;
354 connection *remote_conn; /* dumb pointer */
355 plugin_data *plugin_data; /* dumb pointer */
356 } handler_ctx;
359 /* ok, we need a prototype */
360 static handler_t fcgi_handle_fdevent(server *srv, void *ctx, int revents);
362 static void reset_signals(void) {
363 #ifdef SIGTTOU
364 signal(SIGTTOU, SIG_DFL);
365 #endif
366 #ifdef SIGTTIN
367 signal(SIGTTIN, SIG_DFL);
368 #endif
369 #ifdef SIGTSTP
370 signal(SIGTSTP, SIG_DFL);
371 #endif
372 signal(SIGHUP, SIG_DFL);
373 signal(SIGPIPE, SIG_DFL);
374 signal(SIGUSR1, SIG_DFL);
377 static void fastcgi_status_copy_procname(buffer *b, fcgi_extension_host *host, fcgi_proc *proc) {
378 buffer_copy_string_len(b, CONST_STR_LEN("fastcgi.backend."));
379 buffer_append_string_buffer(b, host->id);
380 if (proc) {
381 buffer_append_string_len(b, CONST_STR_LEN("."));
382 buffer_append_int(b, proc->id);
386 static void fcgi_proc_load_inc(server *srv, handler_ctx *hctx) {
387 plugin_data *p = hctx->plugin_data;
388 hctx->proc->load++;
390 status_counter_inc(srv, CONST_STR_LEN("fastcgi.active-requests"));
392 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
393 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
395 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->proc->load);
398 static void fcgi_proc_load_dec(server *srv, handler_ctx *hctx) {
399 plugin_data *p = hctx->plugin_data;
400 hctx->proc->load--;
402 status_counter_dec(srv, CONST_STR_LEN("fastcgi.active-requests"));
404 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
405 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
407 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->proc->load);
410 static void fcgi_host_assign(server *srv, handler_ctx *hctx, fcgi_extension_host *host) {
411 plugin_data *p = hctx->plugin_data;
412 hctx->host = host;
413 hctx->host->load++;
415 fastcgi_status_copy_procname(p->statuskey, hctx->host, NULL);
416 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
418 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->host->load);
421 static void fcgi_host_reset(server *srv, handler_ctx *hctx) {
422 plugin_data *p = hctx->plugin_data;
423 hctx->host->load--;
425 fastcgi_status_copy_procname(p->statuskey, hctx->host, NULL);
426 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
428 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->host->load);
430 hctx->host = NULL;
433 static void fcgi_host_disable(server *srv, handler_ctx *hctx) {
434 if (hctx->host->disable_time || hctx->proc->is_local) {
435 if (hctx->proc->state == PROC_STATE_RUNNING) hctx->host->active_procs--;
436 hctx->proc->disabled_until = srv->cur_ts + hctx->host->disable_time;
437 hctx->proc->state = hctx->proc->is_local ? PROC_STATE_DIED_WAIT_FOR_PID : PROC_STATE_DIED;
439 if (hctx->conf.debug) {
440 log_error_write(srv, __FILE__, __LINE__, "sds",
441 "backend disabled for", hctx->host->disable_time, "seconds");
446 static int fastcgi_status_init(server *srv, buffer *b, fcgi_extension_host *host, fcgi_proc *proc) {
447 #define CLEAN(x) \
448 fastcgi_status_copy_procname(b, host, proc); \
449 buffer_append_string_len(b, CONST_STR_LEN(x)); \
450 status_counter_set(srv, CONST_BUF_LEN(b), 0);
452 CLEAN(".disabled");
453 CLEAN(".died");
454 CLEAN(".overloaded");
455 CLEAN(".connected");
456 CLEAN(".load");
458 #undef CLEAN
460 #define CLEAN(x) \
461 fastcgi_status_copy_procname(b, host, NULL); \
462 buffer_append_string_len(b, CONST_STR_LEN(x)); \
463 status_counter_set(srv, CONST_BUF_LEN(b), 0);
465 CLEAN(".load");
467 #undef CLEAN
469 return 0;
472 static handler_ctx * handler_ctx_init(void) {
473 handler_ctx * hctx;
475 hctx = calloc(1, sizeof(*hctx));
476 force_assert(hctx);
478 hctx->fde_ndx = -1;
480 hctx->response_header = buffer_init();
482 hctx->request_id = 0;
483 hctx->fcgi_mode = FCGI_RESPONDER;
484 hctx->state = FCGI_STATE_INIT;
485 hctx->proc = NULL;
487 hctx->fd = -1;
489 hctx->reconnects = 0;
490 hctx->send_content_body = 1;
492 hctx->rb = chunkqueue_init();
493 hctx->wb = chunkqueue_init();
494 hctx->wb_reqlen = 0;
496 return hctx;
499 static void handler_ctx_free(handler_ctx *hctx) {
500 /* caller MUST have called fcgi_backend_close(srv, hctx) if necessary */
501 buffer_free(hctx->response_header);
503 chunkqueue_free(hctx->rb);
504 chunkqueue_free(hctx->wb);
506 free(hctx);
509 static void handler_ctx_clear(handler_ctx *hctx) {
510 /* caller MUST have called fcgi_backend_close(srv, hctx) if necessary */
512 hctx->proc = NULL;
513 hctx->host = NULL;
514 hctx->ext = NULL;
515 /*hctx->ext_auth is intentionally preserved to flag prior authorizer*/
517 hctx->fcgi_mode = FCGI_RESPONDER;
518 hctx->state = FCGI_STATE_INIT;
519 /*hctx->state_timestamp = 0;*//*(unused; left as-is)*/
521 chunkqueue_reset(hctx->rb);
522 chunkqueue_reset(hctx->wb);
523 hctx->wb_reqlen = 0;
525 buffer_reset(hctx->response_header);
527 hctx->fd = -1;
528 hctx->fde_ndx = -1;
529 /*hctx->pid = -1;*//*(unused; left as-is)*/
530 hctx->got_proc = 0;
531 hctx->reconnects = 0;
532 hctx->request_id = 0;
533 hctx->send_content_body = 1;
535 /*plugin_config conf;*//*(no need to reset for same request)*/
537 /*hctx->remote_conn = NULL;*//*(no need to reset for same request)*/
538 /*hctx->plugin_data = NULL;*//*(no need to reset for same request)*/
541 static fcgi_proc *fastcgi_process_init(void) {
542 fcgi_proc *f;
544 f = calloc(1, sizeof(*f));
545 f->unixsocket = buffer_init();
546 f->connection_name = buffer_init();
548 f->prev = NULL;
549 f->next = NULL;
551 return f;
554 static void fastcgi_process_free(fcgi_proc *f) {
555 if (!f) return;
557 fastcgi_process_free(f->next);
559 buffer_free(f->unixsocket);
560 buffer_free(f->connection_name);
562 free(f);
565 static fcgi_extension_host *fastcgi_host_init(void) {
566 fcgi_extension_host *f;
568 f = calloc(1, sizeof(*f));
570 f->id = buffer_init();
571 f->host = buffer_init();
572 f->unixsocket = buffer_init();
573 f->docroot = buffer_init();
574 f->bin_path = buffer_init();
575 f->bin_env = array_init();
576 f->bin_env_copy = array_init();
577 f->strip_request_uri = buffer_init();
578 f->xsendfile_docroot = array_init();
580 return f;
583 static void fastcgi_host_free(fcgi_extension_host *h) {
584 if (!h) return;
585 if (h->refcount) {
586 --h->refcount;
587 return;
590 buffer_free(h->id);
591 buffer_free(h->host);
592 buffer_free(h->unixsocket);
593 buffer_free(h->docroot);
594 buffer_free(h->bin_path);
595 buffer_free(h->strip_request_uri);
596 array_free(h->bin_env);
597 array_free(h->bin_env_copy);
598 array_free(h->xsendfile_docroot);
600 fastcgi_process_free(h->first);
601 fastcgi_process_free(h->unused_procs);
603 free(h);
607 static fcgi_exts *fastcgi_extensions_init(void) {
608 fcgi_exts *f;
610 f = calloc(1, sizeof(*f));
612 return f;
615 static void fastcgi_extensions_free(fcgi_exts *f) {
616 size_t i;
618 if (!f) return;
620 for (i = 0; i < f->used; i++) {
621 fcgi_extension *fe;
622 size_t j;
624 fe = f->exts[i];
626 for (j = 0; j < fe->used; j++) {
627 fcgi_extension_host *h;
629 h = fe->hosts[j];
631 fastcgi_host_free(h);
634 buffer_free(fe->key);
635 free(fe->hosts);
637 free(fe);
640 free(f->exts);
642 free(f);
645 static int fastcgi_extension_insert(fcgi_exts *ext, buffer *key, fcgi_extension_host *fh) {
646 fcgi_extension *fe;
647 size_t i;
649 /* there is something */
651 for (i = 0; i < ext->used; i++) {
652 if (buffer_is_equal(key, ext->exts[i]->key)) {
653 break;
657 if (i == ext->used) {
658 /* filextension is new */
659 fe = calloc(1, sizeof(*fe));
660 force_assert(fe);
661 fe->key = buffer_init();
662 fe->last_used_ndx = -1;
663 buffer_copy_buffer(fe->key, key);
665 /* */
667 if (ext->size == 0) {
668 ext->size = 8;
669 ext->exts = malloc(ext->size * sizeof(*(ext->exts)));
670 force_assert(ext->exts);
671 } else if (ext->used == ext->size) {
672 ext->size += 8;
673 ext->exts = realloc(ext->exts, ext->size * sizeof(*(ext->exts)));
674 force_assert(ext->exts);
676 ext->exts[ext->used++] = fe;
677 } else {
678 fe = ext->exts[i];
681 if (fe->size == 0) {
682 fe->size = 4;
683 fe->hosts = malloc(fe->size * sizeof(*(fe->hosts)));
684 force_assert(fe->hosts);
685 } else if (fe->size == fe->used) {
686 fe->size += 4;
687 fe->hosts = realloc(fe->hosts, fe->size * sizeof(*(fe->hosts)));
688 force_assert(fe->hosts);
691 fe->hosts[fe->used++] = fh;
693 return 0;
697 INIT_FUNC(mod_fastcgi_init) {
698 plugin_data *p;
700 p = calloc(1, sizeof(*p));
702 p->fcgi_env = buffer_init();
704 p->path = buffer_init();
706 p->statuskey = buffer_init();
708 return p;
712 FREE_FUNC(mod_fastcgi_free) {
713 plugin_data *p = p_d;
715 UNUSED(srv);
717 buffer_free(p->fcgi_env);
718 buffer_free(p->path);
719 buffer_free(p->statuskey);
721 if (p->config_storage) {
722 size_t i, j, n;
723 for (i = 0; i < srv->config_context->used; i++) {
724 plugin_config *s = p->config_storage[i];
725 fcgi_exts *exts;
727 if (NULL == s) continue;
729 exts = s->exts;
731 if (exts) {
732 for (j = 0; j < exts->used; j++) {
733 fcgi_extension *ex;
735 ex = exts->exts[j];
737 for (n = 0; n < ex->used; n++) {
738 fcgi_proc *proc;
739 fcgi_extension_host *host;
741 host = ex->hosts[n];
743 for (proc = host->first; proc; proc = proc->next) {
744 if (proc->pid != 0) {
745 kill(proc->pid, host->kill_signal);
748 if (proc->is_local &&
749 !buffer_string_is_empty(proc->unixsocket)) {
750 unlink(proc->unixsocket->ptr);
754 for (proc = host->unused_procs; proc; proc = proc->next) {
755 if (proc->pid != 0) {
756 kill(proc->pid, host->kill_signal);
758 if (proc->is_local &&
759 !buffer_string_is_empty(proc->unixsocket)) {
760 unlink(proc->unixsocket->ptr);
766 fastcgi_extensions_free(s->exts);
767 fastcgi_extensions_free(s->exts_auth);
768 fastcgi_extensions_free(s->exts_resp);
770 array_free(s->ext_mapping);
772 free(s);
774 free(p->config_storage);
777 free(p);
779 return HANDLER_GO_ON;
782 static int env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) {
783 char *dst;
784 size_t i;
786 if (!key || !val) return -1;
788 dst = malloc(key_len + val_len + 3);
789 memcpy(dst, key, key_len);
790 dst[key_len] = '=';
791 memcpy(dst + key_len + 1, val, val_len);
792 dst[key_len + 1 + val_len] = '\0';
794 for (i = 0; i < env->used; i++) {
795 if (0 == strncmp(dst, env->ptr[i], key_len + 1)) {
796 /* don't care about free as we are in a forked child which is going to exec(...) */
797 /* free(env->ptr[i]); */
798 env->ptr[i] = dst;
799 return 0;
803 if (env->size == 0) {
804 env->size = 16;
805 env->ptr = malloc(env->size * sizeof(*env->ptr));
806 } else if (env->size == env->used + 1) {
807 env->size += 16;
808 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
811 env->ptr[env->used++] = dst;
813 return 0;
816 static int parse_binpath(char_array *env, buffer *b) {
817 char *start;
818 size_t i;
819 /* search for spaces */
821 start = b->ptr;
822 for (i = 0; i < buffer_string_length(b); i++) {
823 switch(b->ptr[i]) {
824 case ' ':
825 case '\t':
826 /* a WS, stop here and copy the argument */
828 if (env->size == 0) {
829 env->size = 16;
830 env->ptr = malloc(env->size * sizeof(*env->ptr));
831 } else if (env->size == env->used) {
832 env->size += 16;
833 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
836 b->ptr[i] = '\0';
838 env->ptr[env->used++] = start;
840 start = b->ptr + i + 1;
841 break;
842 default:
843 break;
847 if (env->size == 0) {
848 env->size = 16;
849 env->ptr = malloc(env->size * sizeof(*env->ptr));
850 } else if (env->size == env->used) { /* we need one extra for the terminating NULL */
851 env->size += 16;
852 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
855 /* the rest */
856 env->ptr[env->used++] = start;
858 if (env->size == 0) {
859 env->size = 16;
860 env->ptr = malloc(env->size * sizeof(*env->ptr));
861 } else if (env->size == env->used) { /* we need one extra for the terminating NULL */
862 env->size += 16;
863 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
866 /* terminate */
867 env->ptr[env->used++] = NULL;
869 return 0;
872 #if !defined(HAVE_FORK)
873 static int fcgi_spawn_connection(server *srv,
874 plugin_data *p,
875 fcgi_extension_host *host,
876 fcgi_proc *proc) {
877 UNUSED(srv);
878 UNUSED(p);
879 UNUSED(host);
880 UNUSED(proc);
881 return -1;
884 #else /* -> defined(HAVE_FORK) */
886 static int fcgi_spawn_connection(server *srv,
887 plugin_data *p,
888 fcgi_extension_host *host,
889 fcgi_proc *proc) {
890 int fcgi_fd;
891 int status;
892 struct timeval tv = { 0, 100 * 1000 };
893 #ifdef HAVE_SYS_UN_H
894 struct sockaddr_un fcgi_addr_un;
895 #endif
896 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
897 struct sockaddr_in6 fcgi_addr_in6;
898 #endif
899 struct sockaddr_in fcgi_addr_in;
900 struct sockaddr *fcgi_addr;
902 socklen_t servlen;
904 if (p->conf.debug) {
905 log_error_write(srv, __FILE__, __LINE__, "sdb",
906 "new proc, socket:", proc->port, proc->unixsocket);
909 if (!buffer_string_is_empty(proc->unixsocket)) {
910 #ifdef HAVE_SYS_UN_H
911 memset(&fcgi_addr_un, 0, sizeof(fcgi_addr_un));
912 fcgi_addr_un.sun_family = AF_UNIX;
913 if (buffer_string_length(proc->unixsocket) + 1 > sizeof(fcgi_addr_un.sun_path)) {
914 log_error_write(srv, __FILE__, __LINE__, "sB",
915 "ERROR: Unix Domain socket filename too long:",
916 proc->unixsocket);
917 return -1;
919 memcpy(fcgi_addr_un.sun_path, proc->unixsocket->ptr, buffer_string_length(proc->unixsocket) + 1);
921 #ifdef SUN_LEN
922 servlen = SUN_LEN(&fcgi_addr_un);
923 #else
924 /* stevens says: */
925 servlen = buffer_string_length(proc->unixsocket) + 1 + sizeof(fcgi_addr_un.sun_family);
926 #endif
927 fcgi_addr = (struct sockaddr *) &fcgi_addr_un;
929 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("unix:"));
930 buffer_append_string_buffer(proc->connection_name, proc->unixsocket);
932 #else
933 log_error_write(srv, __FILE__, __LINE__, "s",
934 "ERROR: Unix Domain sockets are not supported.");
935 return -1;
936 #endif
937 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
938 } else if (host->family == AF_INET6 && !buffer_string_is_empty(host->host)) {
939 memset(&fcgi_addr_in6, 0, sizeof(fcgi_addr_in6));
940 fcgi_addr_in6.sin6_family = AF_INET6;
941 inet_pton(AF_INET6, host->host->ptr, (char *) &fcgi_addr_in6.sin6_addr);
942 fcgi_addr_in6.sin6_port = htons(proc->port);
943 servlen = sizeof(fcgi_addr_in6);
944 fcgi_addr = (struct sockaddr *) &fcgi_addr_in6;
945 #endif
946 } else {
947 memset(&fcgi_addr_in, 0, sizeof(fcgi_addr_in));
948 fcgi_addr_in.sin_family = AF_INET;
950 if (buffer_string_is_empty(host->host)) {
951 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
952 } else {
953 struct hostent *he;
955 /* set a useful default */
956 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
959 if (NULL == (he = gethostbyname(host->host->ptr))) {
960 log_error_write(srv, __FILE__, __LINE__,
961 "sdb", "gethostbyname failed: ",
962 h_errno, host->host);
963 return -1;
966 if (he->h_addrtype != AF_INET) {
967 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-type != AF_INET: ", he->h_addrtype);
968 return -1;
971 if (he->h_length != sizeof(struct in_addr)) {
972 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-length != sizeof(in_addr): ", he->h_length);
973 return -1;
976 memcpy(&(fcgi_addr_in.sin_addr.s_addr), he->h_addr_list[0], he->h_length);
979 fcgi_addr_in.sin_port = htons(proc->port);
980 servlen = sizeof(fcgi_addr_in);
982 fcgi_addr = (struct sockaddr *) &fcgi_addr_in;
985 if (buffer_string_is_empty(proc->unixsocket)) {
986 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("tcp:"));
987 if (!buffer_string_is_empty(host->host)) {
988 buffer_append_string_buffer(proc->connection_name, host->host);
989 } else {
990 buffer_append_string_len(proc->connection_name, CONST_STR_LEN("localhost"));
992 buffer_append_string_len(proc->connection_name, CONST_STR_LEN(":"));
993 buffer_append_int(proc->connection_name, proc->port);
996 if (-1 == (fcgi_fd = fdevent_socket_cloexec(fcgi_addr->sa_family, SOCK_STREAM, 0))) {
997 log_error_write(srv, __FILE__, __LINE__, "ss",
998 "failed:", strerror(errno));
999 return -1;
1002 if (-1 == connect(fcgi_fd, fcgi_addr, servlen)) {
1003 /* server is not up, spawn it */
1004 pid_t child;
1005 int val;
1007 if (errno != ENOENT &&
1008 !buffer_string_is_empty(proc->unixsocket)) {
1009 unlink(proc->unixsocket->ptr);
1012 close(fcgi_fd);
1014 /* reopen socket */
1015 if (-1 == (fcgi_fd = fdevent_socket_cloexec(fcgi_addr->sa_family, SOCK_STREAM, 0))) {
1016 log_error_write(srv, __FILE__, __LINE__, "ss",
1017 "socket failed:", strerror(errno));
1018 return -1;
1021 val = 1;
1022 if (setsockopt(fcgi_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) {
1023 log_error_write(srv, __FILE__, __LINE__, "ss",
1024 "socketsockopt failed:", strerror(errno));
1025 close(fcgi_fd);
1026 return -1;
1029 /* create socket */
1030 if (-1 == bind(fcgi_fd, fcgi_addr, servlen)) {
1031 log_error_write(srv, __FILE__, __LINE__, "sbs",
1032 "bind failed for:",
1033 proc->connection_name,
1034 strerror(errno));
1035 close(fcgi_fd);
1036 return -1;
1039 if (-1 == listen(fcgi_fd, host->listen_backlog)) {
1040 log_error_write(srv, __FILE__, __LINE__, "ss",
1041 "listen failed:", strerror(errno));
1042 close(fcgi_fd);
1043 return -1;
1046 switch ((child = fork())) {
1047 case 0: {
1048 size_t i = 0;
1049 char *c;
1050 char_array env;
1051 char_array arg;
1053 /* create environment */
1054 env.ptr = NULL;
1055 env.size = 0;
1056 env.used = 0;
1058 arg.ptr = NULL;
1059 arg.size = 0;
1060 arg.used = 0;
1062 if(fcgi_fd != FCGI_LISTENSOCK_FILENO) {
1063 dup2(fcgi_fd, FCGI_LISTENSOCK_FILENO);
1064 close(fcgi_fd);
1066 #ifdef SOCK_CLOEXEC
1067 else
1068 (void)fcntl(fcgi_fd, F_SETFD, 0); /* clear cloexec */
1069 #endif
1071 /* we don't need the client socket */
1072 for (i = 3; i < 256; i++) {
1073 close(i);
1076 /* build clean environment */
1077 if (host->bin_env_copy->used) {
1078 for (i = 0; i < host->bin_env_copy->used; i++) {
1079 data_string *ds = (data_string *)host->bin_env_copy->data[i];
1080 char *ge;
1082 if (NULL != (ge = getenv(ds->value->ptr))) {
1083 env_add(&env, CONST_BUF_LEN(ds->value), ge, strlen(ge));
1086 } else {
1087 char ** const e = environ;
1088 for (i = 0; e[i]; ++i) {
1089 char *eq;
1091 if (NULL != (eq = strchr(e[i], '='))) {
1092 env_add(&env, e[i], eq - e[i], eq+1, strlen(eq+1));
1097 /* create environment */
1098 for (i = 0; i < host->bin_env->used; i++) {
1099 data_string *ds = (data_string *)host->bin_env->data[i];
1101 env_add(&env, CONST_BUF_LEN(ds->key), CONST_BUF_LEN(ds->value));
1104 for (i = 0; i < env.used; i++) {
1105 /* search for PHP_FCGI_CHILDREN */
1106 if (0 == strncmp(env.ptr[i], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
1109 /* not found, add a default */
1110 if (i == env.used) {
1111 env_add(&env, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
1114 env.ptr[env.used] = NULL;
1116 parse_binpath(&arg, host->bin_path);
1118 /* chdir into the base of the bin-path,
1119 * search for the last / */
1120 if (NULL != (c = strrchr(arg.ptr[0], '/'))) {
1121 *c = '\0';
1123 /* change to the physical directory */
1124 if (-1 == chdir(arg.ptr[0])) {
1125 *c = '/';
1126 log_error_write(srv, __FILE__, __LINE__, "sss", "chdir failed:", strerror(errno), arg.ptr[0]);
1128 *c = '/';
1131 reset_signals();
1133 /* exec the cgi */
1134 execve(arg.ptr[0], arg.ptr, env.ptr);
1136 /* log_error_write(srv, __FILE__, __LINE__, "sbs",
1137 "execve failed for:", host->bin_path, strerror(errno)); */
1139 _exit(errno);
1141 break;
1143 case -1:
1144 /* error */
1145 close(fcgi_fd);
1146 break;
1147 default:
1148 /* father */
1149 close(fcgi_fd);
1151 /* wait */
1152 select(0, NULL, NULL, NULL, &tv);
1154 switch (waitpid(child, &status, WNOHANG)) {
1155 case 0:
1156 /* child still running after timeout, good */
1157 break;
1158 case -1:
1159 /* no PID found ? should never happen */
1160 log_error_write(srv, __FILE__, __LINE__, "ss",
1161 "pid not found:", strerror(errno));
1162 return -1;
1163 default:
1164 log_error_write(srv, __FILE__, __LINE__, "sbs",
1165 "the fastcgi-backend", host->bin_path, "failed to start:");
1166 /* the child should not terminate at all */
1167 if (WIFEXITED(status)) {
1168 log_error_write(srv, __FILE__, __LINE__, "sdb",
1169 "child exited with status",
1170 WEXITSTATUS(status), host->bin_path);
1171 log_error_write(srv, __FILE__, __LINE__, "s",
1172 "If you're trying to run your app as a FastCGI backend, make sure you're using the FastCGI-enabled version.\n"
1173 "If this is PHP on Gentoo, add 'fastcgi' to the USE flags.");
1174 } else if (WIFSIGNALED(status)) {
1175 log_error_write(srv, __FILE__, __LINE__, "sd",
1176 "terminated by signal:",
1177 WTERMSIG(status));
1179 if (WTERMSIG(status) == 11) {
1180 log_error_write(srv, __FILE__, __LINE__, "s",
1181 "to be exact: it segfaulted, crashed, died, ... you get the idea." );
1182 log_error_write(srv, __FILE__, __LINE__, "s",
1183 "If this is PHP, try removing the bytecode caches for now and try again.");
1185 } else {
1186 log_error_write(srv, __FILE__, __LINE__, "sd",
1187 "child died somehow:",
1188 status);
1190 return -1;
1193 /* register process */
1194 proc->pid = child;
1195 proc->is_local = 1;
1197 break;
1199 } else {
1200 close(fcgi_fd);
1201 proc->is_local = 0;
1202 proc->pid = 0;
1204 if (p->conf.debug) {
1205 log_error_write(srv, __FILE__, __LINE__, "sb",
1206 "(debug) socket is already used; won't spawn:",
1207 proc->connection_name);
1211 proc->state = PROC_STATE_RUNNING;
1212 host->active_procs++;
1214 return 0;
1217 #endif /* HAVE_FORK */
1219 static fcgi_extension_host * unixsocket_is_dup(plugin_data *p, size_t used, buffer *unixsocket) {
1220 size_t i, j, n;
1221 for (i = 0; i < used; ++i) {
1222 fcgi_exts *exts = p->config_storage[i]->exts;
1223 if (NULL == exts) continue;
1224 for (j = 0; j < exts->used; ++j) {
1225 fcgi_extension *ex = exts->exts[j];
1226 for (n = 0; n < ex->used; ++n) {
1227 fcgi_extension_host *host = ex->hosts[n];
1228 if (!buffer_string_is_empty(host->unixsocket)
1229 && buffer_is_equal(host->unixsocket, unixsocket)
1230 && !buffer_string_is_empty(host->bin_path))
1231 return host;
1236 return NULL;
1239 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults) {
1240 plugin_data *p = p_d;
1241 data_unset *du;
1242 size_t i = 0;
1243 buffer *fcgi_mode = buffer_init();
1244 fcgi_extension_host *host = NULL;
1246 config_values_t cv[] = {
1247 { "fastcgi.server", NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1248 { "fastcgi.debug", NULL, T_CONFIG_INT , T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1249 { "fastcgi.map-extensions", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1250 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1253 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
1255 for (i = 0; i < srv->config_context->used; i++) {
1256 data_config const* config = (data_config const*)srv->config_context->data[i];
1257 plugin_config *s;
1259 s = malloc(sizeof(plugin_config));
1260 s->exts = NULL;
1261 s->exts_auth = NULL;
1262 s->exts_resp = NULL;
1263 s->debug = 0;
1264 s->ext_mapping = array_init();
1266 cv[0].destination = s->exts; /* not used; T_CONFIG_LOCAL */
1267 cv[1].destination = &(s->debug);
1268 cv[2].destination = s->ext_mapping;
1270 p->config_storage[i] = s;
1272 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
1273 goto error;
1277 * <key> = ( ... )
1280 if (NULL != (du = array_get_element(config->value, "fastcgi.server"))) {
1281 size_t j;
1282 data_array *da = (data_array *)du;
1284 if (du->type != TYPE_ARRAY) {
1285 log_error_write(srv, __FILE__, __LINE__, "sss",
1286 "unexpected type for key: ", "fastcgi.server", "expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1288 goto error;
1291 s->exts = fastcgi_extensions_init();
1292 s->exts_auth = fastcgi_extensions_init();
1293 s->exts_resp = fastcgi_extensions_init();
1296 * fastcgi.server = ( "<ext>" => ( ... ),
1297 * "<ext>" => ( ... ) )
1300 for (j = 0; j < da->value->used; j++) {
1301 size_t n;
1302 data_array *da_ext = (data_array *)da->value->data[j];
1304 if (da->value->data[j]->type != TYPE_ARRAY) {
1305 log_error_write(srv, __FILE__, __LINE__, "sssbs",
1306 "unexpected type for key: ", "fastcgi.server",
1307 "[", da->value->data[j]->key, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1309 goto error;
1313 * da_ext->key == name of the extension
1317 * fastcgi.server = ( "<ext>" =>
1318 * ( "<host>" => ( ... ),
1319 * "<host>" => ( ... )
1320 * ),
1321 * "<ext>" => ... )
1324 for (n = 0; n < da_ext->value->used; n++) {
1325 data_array *da_host = (data_array *)da_ext->value->data[n];
1327 config_values_t fcv[] = {
1328 { "host", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1329 { "docroot", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1330 { "mode", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1331 { "socket", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
1332 { "bin-path", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
1334 { "check-local", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 5 */
1335 { "port", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 6 */
1336 { "max-procs", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
1337 { "disable-time", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
1339 { "bin-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 9 */
1340 { "bin-copy-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 10 */
1342 { "broken-scriptfilename", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 11 */
1343 { "allow-x-send-file", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
1344 { "strip-request-uri", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 13 */
1345 { "kill-signal", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 14 */
1346 { "fix-root-scriptname", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 15 */
1347 { "listen-backlog", NULL, T_CONFIG_INT, T_CONFIG_SCOPE_CONNECTION }, /* 16 */
1348 { "x-sendfile", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 17 */
1349 { "x-sendfile-docroot",NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 18 */
1351 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1353 unsigned short host_mode = FCGI_RESPONDER;
1355 if (da_host->type != TYPE_ARRAY) {
1356 log_error_write(srv, __FILE__, __LINE__, "ssSBS",
1357 "unexpected type for key:",
1358 "fastcgi.server",
1359 "[", da_host->key, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1361 goto error;
1364 host = fastcgi_host_init();
1365 buffer_reset(fcgi_mode);
1367 buffer_copy_buffer(host->id, da_host->key);
1369 host->check_local = 1;
1370 host->max_procs = 4;
1371 host->disable_time = 1;
1372 host->break_scriptfilename_for_php = 0;
1373 host->xsendfile_allow = 0;
1374 host->kill_signal = SIGTERM;
1375 host->fix_root_path_name = 0;
1376 host->listen_backlog = 1024;
1377 host->refcount = 0;
1379 fcv[0].destination = host->host;
1380 fcv[1].destination = host->docroot;
1381 fcv[2].destination = fcgi_mode;
1382 fcv[3].destination = host->unixsocket;
1383 fcv[4].destination = host->bin_path;
1385 fcv[5].destination = &(host->check_local);
1386 fcv[6].destination = &(host->port);
1387 fcv[7].destination = &(host->max_procs);
1388 fcv[8].destination = &(host->disable_time);
1390 fcv[9].destination = host->bin_env;
1391 fcv[10].destination = host->bin_env_copy;
1392 fcv[11].destination = &(host->break_scriptfilename_for_php);
1393 fcv[12].destination = &(host->xsendfile_allow);
1394 fcv[13].destination = host->strip_request_uri;
1395 fcv[14].destination = &(host->kill_signal);
1396 fcv[15].destination = &(host->fix_root_path_name);
1397 fcv[16].destination = &(host->listen_backlog);
1398 fcv[17].destination = &(host->xsendfile_allow);
1399 fcv[18].destination = host->xsendfile_docroot;
1401 if (0 != config_insert_values_internal(srv, da_host->value, fcv, T_CONFIG_SCOPE_CONNECTION)) {
1402 goto error;
1405 if ((!buffer_string_is_empty(host->host) || host->port) &&
1406 !buffer_string_is_empty(host->unixsocket)) {
1407 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1408 "either host/port or socket have to be set in:",
1409 da->key, "= (",
1410 da_ext->key, " => (",
1411 da_host->key, " ( ...");
1413 goto error;
1416 if (!buffer_string_is_empty(host->unixsocket)) {
1417 /* unix domain socket */
1418 struct sockaddr_un un;
1420 if (buffer_string_length(host->unixsocket) + 1 > sizeof(un.sun_path) - 2) {
1421 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1422 "unixsocket is too long in:",
1423 da->key, "= (",
1424 da_ext->key, " => (",
1425 da_host->key, " ( ...");
1427 goto error;
1430 if (!buffer_string_is_empty(host->bin_path)) {
1431 fcgi_extension_host *duplicate = unixsocket_is_dup(p, i+1, host->unixsocket);
1432 if (NULL != duplicate) {
1433 if (!buffer_is_equal(host->bin_path, duplicate->bin_path)) {
1434 log_error_write(srv, __FILE__, __LINE__, "sb",
1435 "duplicate unixsocket path:",
1436 host->unixsocket);
1437 goto error;
1439 fastcgi_host_free(host);
1440 host = duplicate;
1441 ++host->refcount;
1445 host->family = AF_UNIX;
1446 } else {
1447 /* tcp/ip */
1449 if (buffer_string_is_empty(host->host) &&
1450 buffer_string_is_empty(host->bin_path)) {
1451 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1452 "host or binpath have to be set in:",
1453 da->key, "= (",
1454 da_ext->key, " => (",
1455 da_host->key, " ( ...");
1457 goto error;
1458 } else if (host->port == 0) {
1459 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1460 "port has to be set in:",
1461 da->key, "= (",
1462 da_ext->key, " => (",
1463 da_host->key, " ( ...");
1465 goto error;
1468 host->family = (!buffer_string_is_empty(host->host) && NULL != strchr(host->host->ptr, ':')) ? AF_INET6 : AF_INET;
1471 if (host->refcount) {
1472 /* already init'd; skip spawning */
1473 } else if (!buffer_string_is_empty(host->bin_path)) {
1474 /* a local socket + self spawning */
1475 size_t pno;
1477 if (s->debug) {
1478 log_error_write(srv, __FILE__, __LINE__, "ssbsdsbsd",
1479 "--- fastcgi spawning local",
1480 "\n\tproc:", host->bin_path,
1481 "\n\tport:", host->port,
1482 "\n\tsocket", host->unixsocket,
1483 "\n\tmax-procs:", host->max_procs);
1486 for (pno = 0; pno < host->max_procs; pno++) {
1487 fcgi_proc *proc;
1489 proc = fastcgi_process_init();
1490 proc->id = host->num_procs++;
1491 host->max_id++;
1493 if (buffer_string_is_empty(host->unixsocket)) {
1494 proc->port = host->port + pno;
1495 } else {
1496 buffer_copy_buffer(proc->unixsocket, host->unixsocket);
1497 buffer_append_string_len(proc->unixsocket, CONST_STR_LEN("-"));
1498 buffer_append_int(proc->unixsocket, pno);
1501 if (s->debug) {
1502 log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
1503 "--- fastcgi spawning",
1504 "\n\tport:", host->port,
1505 "\n\tsocket", host->unixsocket,
1506 "\n\tcurrent:", pno, "/", host->max_procs);
1509 if (!srv->srvconf.preflight_check
1510 && fcgi_spawn_connection(srv, p, host, proc)) {
1511 log_error_write(srv, __FILE__, __LINE__, "s",
1512 "[ERROR]: spawning fcgi failed.");
1513 fastcgi_process_free(proc);
1514 goto error;
1517 fastcgi_status_init(srv, p->statuskey, host, proc);
1519 proc->next = host->first;
1520 if (host->first) host->first->prev = proc;
1522 host->first = proc;
1524 } else {
1525 fcgi_proc *proc;
1527 proc = fastcgi_process_init();
1528 proc->id = host->num_procs++;
1529 host->max_id++;
1530 host->active_procs++;
1531 proc->state = PROC_STATE_RUNNING;
1533 if (buffer_string_is_empty(host->unixsocket)) {
1534 proc->port = host->port;
1535 } else {
1536 buffer_copy_buffer(proc->unixsocket, host->unixsocket);
1539 fastcgi_status_init(srv, p->statuskey, host, proc);
1541 host->first = proc;
1543 host->max_procs = 1;
1546 if (!buffer_string_is_empty(fcgi_mode)) {
1547 if (strcmp(fcgi_mode->ptr, "responder") == 0) {
1548 host_mode = FCGI_RESPONDER;
1549 } else if (strcmp(fcgi_mode->ptr, "authorizer") == 0) {
1550 host_mode = FCGI_AUTHORIZER;
1551 } else {
1552 log_error_write(srv, __FILE__, __LINE__, "sbs",
1553 "WARNING: unknown fastcgi mode:",
1554 fcgi_mode, "(ignored, mode set to responder)");
1558 if (host->xsendfile_docroot->used) {
1559 size_t k;
1560 for (k = 0; k < host->xsendfile_docroot->used; ++k) {
1561 data_string *ds = (data_string *)host->xsendfile_docroot->data[k];
1562 if (ds->type != TYPE_STRING) {
1563 log_error_write(srv, __FILE__, __LINE__, "s",
1564 "unexpected type for x-sendfile-docroot; expected: \"x-sendfile-docroot\" => ( \"/allowed/path\", ... )");
1565 goto error;
1567 if (ds->value->ptr[0] != '/') {
1568 log_error_write(srv, __FILE__, __LINE__, "SBs",
1569 "x-sendfile-docroot paths must begin with '/'; invalid: \"", ds->value, "\"");
1570 goto error;
1572 buffer_path_simplify(ds->value, ds->value);
1573 buffer_append_slash(ds->value);
1577 /* s->exts is list of exts -> hosts
1578 * s->exts now used as combined list of authorizer and responder hosts (for backend maintenance)
1579 * s->exts_auth is list of exts -> authorizer hosts
1580 * s->exts_resp is list of exts -> responder hosts
1581 * For each path/extension, there may be an independent FCGI_AUTHORIZER and FCGI_RESPONDER
1582 * (The FCGI_AUTHORIZER and FCGI_RESPONDER could be handled by the same host,
1583 * and an admin might want to do that for large uploads, since FCGI_AUTHORIZER
1584 * runs prior to receiving (potentially large) request body from client and can
1585 * authorizer or deny request prior to receiving the full upload)
1587 fastcgi_extension_insert(s->exts, da_ext->key, host);
1589 if (host_mode == FCGI_AUTHORIZER) {
1590 ++host->refcount;
1591 fastcgi_extension_insert(s->exts_auth, da_ext->key, host);
1592 } else if (host_mode == FCGI_RESPONDER) {
1593 ++host->refcount;
1594 fastcgi_extension_insert(s->exts_resp, da_ext->key, host);
1595 } /*(else should have been rejected above)*/
1597 host = NULL;
1603 buffer_free(fcgi_mode);
1604 return HANDLER_GO_ON;
1606 error:
1607 if (NULL != host) fastcgi_host_free(host);
1608 buffer_free(fcgi_mode);
1609 return HANDLER_ERROR;
1612 static int fcgi_set_state(server *srv, handler_ctx *hctx, fcgi_connection_state_t state) {
1613 hctx->state = state;
1614 hctx->state_timestamp = srv->cur_ts;
1616 return 0;
1620 static void fcgi_backend_close(server *srv, handler_ctx *hctx) {
1621 if (hctx->fd != -1) {
1622 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1623 fdevent_unregister(srv->ev, hctx->fd);
1624 fdevent_sched_close(srv->ev, hctx->fd, 1);
1625 hctx->fd = -1;
1626 hctx->fde_ndx = -1;
1629 if (hctx->host) {
1630 if (hctx->proc && hctx->got_proc) {
1631 /* after the connect the process gets a load */
1632 fcgi_proc_load_dec(srv, hctx);
1634 if (hctx->conf.debug) {
1635 log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
1636 "released proc:",
1637 "pid:", hctx->proc->pid,
1638 "socket:", hctx->proc->connection_name,
1639 "load:", hctx->proc->load);
1643 fcgi_host_reset(srv, hctx);
1647 static fcgi_extension_host * fcgi_extension_host_get(server *srv, connection *con, plugin_data *p, fcgi_extension *extension) {
1648 fcgi_extension_host *host;
1649 int ndx = extension->last_used_ndx + 1;
1650 if (ndx >= (int) extension->used || ndx < 0) ndx = 0;
1651 UNUSED(p);
1653 /* check if the next server has no load */
1654 host = extension->hosts[ndx];
1655 if (host->load > 0 || host->active_procs == 0) {
1656 /* get backend with the least load */
1657 size_t k;
1658 int used = -1;
1659 for (k = 0, ndx = -1; k < extension->used; k++) {
1660 host = extension->hosts[k];
1662 /* we should have at least one proc that can do something */
1663 if (host->active_procs == 0) continue;
1665 if (used == -1 || host->load < used) {
1666 used = host->load;
1667 ndx = k;
1672 if (ndx == -1) {
1673 /* all hosts are down */
1674 /* sorry, we don't have a server alive for this ext */
1675 con->http_status = 503; /* Service Unavailable */
1676 con->mode = DIRECT;
1678 /* only send the 'no handler' once */
1679 if (!extension->note_is_sent) {
1680 extension->note_is_sent = 1;
1682 log_error_write(srv, __FILE__, __LINE__, "sBSbsbs",
1683 "all handlers for", con->uri.path, "?", con->uri.query,
1684 "on", extension->key,
1685 "are down.");
1688 return NULL;
1691 /* found a server */
1692 extension->last_used_ndx = ndx;
1693 return extension->hosts[ndx];
1696 static void fcgi_connection_close(server *srv, handler_ctx *hctx) {
1697 plugin_data *p;
1698 connection *con;
1700 p = hctx->plugin_data;
1701 con = hctx->remote_conn;
1703 fcgi_backend_close(srv, hctx);
1704 handler_ctx_free(hctx);
1705 con->plugin_ctx[p->id] = NULL;
1707 /* finish response (if not already con->file_started, con->file_finished) */
1708 if (con->mode == p->id) {
1709 http_response_backend_done(srv, con);
1713 static handler_t fcgi_reconnect(server *srv, handler_ctx *hctx) {
1714 fcgi_backend_close(srv, hctx);
1716 hctx->host = fcgi_extension_host_get(srv, hctx->remote_conn, hctx->plugin_data, hctx->ext);
1717 if (NULL == hctx->host) return HANDLER_FINISHED;
1719 fcgi_host_assign(srv, hctx, hctx->host);
1720 hctx->request_id = 0;
1721 fcgi_set_state(srv, hctx, FCGI_STATE_INIT);
1722 return HANDLER_COMEBACK;
1726 static handler_t fcgi_connection_reset(server *srv, connection *con, void *p_d) {
1727 plugin_data *p = p_d;
1728 handler_ctx *hctx = con->plugin_ctx[p->id];
1729 if (hctx) fcgi_connection_close(srv, hctx);
1731 return HANDLER_GO_ON;
1735 static int fcgi_env_add(void *venv, const char *key, size_t key_len, const char *val, size_t val_len) {
1736 buffer *env = venv;
1737 size_t len;
1738 char len_enc[8];
1739 size_t len_enc_len = 0;
1741 if (!key || !val) return -1;
1743 len = key_len + val_len;
1745 len += key_len > 127 ? 4 : 1;
1746 len += val_len > 127 ? 4 : 1;
1748 if (buffer_string_length(env) + len >= FCGI_MAX_LENGTH) {
1750 * we can't append more headers, ignore it
1752 return -1;
1756 * field length can be 31bit max
1758 * HINT: this can't happen as FCGI_MAX_LENGTH is only 16bit
1760 force_assert(key_len < 0x7fffffffu);
1761 force_assert(val_len < 0x7fffffffu);
1763 buffer_string_prepare_append(env, len);
1765 if (key_len > 127) {
1766 len_enc[len_enc_len++] = ((key_len >> 24) & 0xff) | 0x80;
1767 len_enc[len_enc_len++] = (key_len >> 16) & 0xff;
1768 len_enc[len_enc_len++] = (key_len >> 8) & 0xff;
1769 len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1770 } else {
1771 len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1774 if (val_len > 127) {
1775 len_enc[len_enc_len++] = ((val_len >> 24) & 0xff) | 0x80;
1776 len_enc[len_enc_len++] = (val_len >> 16) & 0xff;
1777 len_enc[len_enc_len++] = (val_len >> 8) & 0xff;
1778 len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1779 } else {
1780 len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1783 buffer_append_string_len(env, len_enc, len_enc_len);
1784 buffer_append_string_len(env, key, key_len);
1785 buffer_append_string_len(env, val, val_len);
1787 return 0;
1790 static int fcgi_header(FCGI_Header * header, unsigned char type, int request_id, int contentLength, unsigned char paddingLength) {
1791 force_assert(contentLength <= FCGI_MAX_LENGTH);
1793 header->version = FCGI_VERSION_1;
1794 header->type = type;
1795 header->requestIdB0 = request_id & 0xff;
1796 header->requestIdB1 = (request_id >> 8) & 0xff;
1797 header->contentLengthB0 = contentLength & 0xff;
1798 header->contentLengthB1 = (contentLength >> 8) & 0xff;
1799 header->paddingLength = paddingLength;
1800 header->reserved = 0;
1802 return 0;
1805 typedef enum {
1806 CONNECTION_OK,
1807 CONNECTION_DELAYED, /* retry after event, take same host */
1808 CONNECTION_OVERLOADED, /* disable for 1 second, take another backend */
1809 CONNECTION_DEAD /* disable for 60 seconds, take another backend */
1810 } connection_result_t;
1812 static connection_result_t fcgi_establish_connection(server *srv, handler_ctx *hctx) {
1813 struct sockaddr *fcgi_addr;
1814 struct sockaddr_in fcgi_addr_in;
1815 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1816 struct sockaddr_in6 fcgi_addr_in6;
1817 #endif
1818 #ifdef HAVE_SYS_UN_H
1819 struct sockaddr_un fcgi_addr_un;
1820 #endif
1821 socklen_t servlen;
1823 fcgi_extension_host *host = hctx->host;
1824 fcgi_proc *proc = hctx->proc;
1825 int fcgi_fd = hctx->fd;
1827 if (!buffer_string_is_empty(proc->unixsocket)) {
1828 #ifdef HAVE_SYS_UN_H
1829 /* use the unix domain socket */
1830 memset(&fcgi_addr_un, 0, sizeof(fcgi_addr_un));
1831 fcgi_addr_un.sun_family = AF_UNIX;
1832 if (buffer_string_length(proc->unixsocket) + 1 > sizeof(fcgi_addr_un.sun_path)) {
1833 log_error_write(srv, __FILE__, __LINE__, "sB",
1834 "ERROR: Unix Domain socket filename too long:",
1835 proc->unixsocket);
1836 return -1;
1838 memcpy(fcgi_addr_un.sun_path, proc->unixsocket->ptr, buffer_string_length(proc->unixsocket) + 1);
1840 #ifdef SUN_LEN
1841 servlen = SUN_LEN(&fcgi_addr_un);
1842 #else
1843 /* stevens says: */
1844 servlen = buffer_string_length(proc->unixsocket) + 1 + sizeof(fcgi_addr_un.sun_family);
1845 #endif
1846 fcgi_addr = (struct sockaddr *) &fcgi_addr_un;
1848 if (buffer_string_is_empty(proc->connection_name)) {
1849 /* on remote spawing we have to set the connection-name now */
1850 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("unix:"));
1851 buffer_append_string_buffer(proc->connection_name, proc->unixsocket);
1853 #else
1854 return CONNECTION_DEAD;
1855 #endif
1856 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1857 } else if (host->family == AF_INET6 && !buffer_string_is_empty(host->host)) {
1858 memset(&fcgi_addr_in6, 0, sizeof(fcgi_addr_in6));
1859 fcgi_addr_in6.sin6_family = AF_INET6;
1860 inet_pton(AF_INET6, host->host->ptr, (char *) &fcgi_addr_in6.sin6_addr);
1861 fcgi_addr_in6.sin6_port = htons(proc->port);
1862 servlen = sizeof(fcgi_addr_in6);
1863 fcgi_addr = (struct sockaddr *) &fcgi_addr_in6;
1864 #endif
1865 } else {
1866 memset(&fcgi_addr_in, 0, sizeof(fcgi_addr_in));
1867 fcgi_addr_in.sin_family = AF_INET;
1868 if (!buffer_string_is_empty(host->host)) {
1869 if (0 == inet_aton(host->host->ptr, &(fcgi_addr_in.sin_addr))) {
1870 log_error_write(srv, __FILE__, __LINE__, "sbs",
1871 "converting IP address failed for", host->host,
1872 "\nBe sure to specify an IP address here");
1874 return CONNECTION_DEAD;
1876 } else {
1877 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1879 fcgi_addr_in.sin_port = htons(proc->port);
1880 servlen = sizeof(fcgi_addr_in);
1882 fcgi_addr = (struct sockaddr *) &fcgi_addr_in;
1885 if (buffer_string_is_empty(proc->unixsocket)) {
1886 if (buffer_string_is_empty(proc->connection_name)) {
1887 /* on remote spawing we have to set the connection-name now */
1888 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("tcp:"));
1889 if (!buffer_string_is_empty(host->host)) {
1890 buffer_append_string_buffer(proc->connection_name, host->host);
1891 } else {
1892 buffer_append_string_len(proc->connection_name, CONST_STR_LEN("localhost"));
1894 buffer_append_string_len(proc->connection_name, CONST_STR_LEN(":"));
1895 buffer_append_int(proc->connection_name, proc->port);
1899 if (-1 == connect(fcgi_fd, fcgi_addr, servlen)) {
1900 if (errno == EINPROGRESS ||
1901 errno == EALREADY ||
1902 errno == EINTR) {
1903 if (hctx->conf.debug > 2) {
1904 log_error_write(srv, __FILE__, __LINE__, "sb",
1905 "connect delayed; will continue later:", proc->connection_name);
1908 return CONNECTION_DELAYED;
1909 } else if (errno == EAGAIN) {
1910 if (hctx->conf.debug) {
1911 log_error_write(srv, __FILE__, __LINE__, "sbsd",
1912 "This means that you have more incoming requests than your FastCGI backend can handle in parallel."
1913 "It might help to spawn more FastCGI backends or PHP children; if not, decrease server.max-connections."
1914 "The load for this FastCGI backend", proc->connection_name, "is", proc->load);
1917 return CONNECTION_OVERLOADED;
1918 } else {
1919 log_error_write(srv, __FILE__, __LINE__, "sssb",
1920 "connect failed:",
1921 strerror(errno), "on",
1922 proc->connection_name);
1924 return CONNECTION_DEAD;
1928 hctx->reconnects = 0;
1929 if (hctx->conf.debug > 1) {
1930 log_error_write(srv, __FILE__, __LINE__, "sd",
1931 "connect succeeded: ", fcgi_fd);
1934 return CONNECTION_OK;
1937 static void fcgi_stdin_append(server *srv, connection *con, handler_ctx *hctx, int request_id) {
1938 FCGI_Header header;
1939 chunkqueue *req_cq = con->request_content_queue;
1940 off_t offset, weWant;
1941 const off_t req_cqlen = req_cq->bytes_in - req_cq->bytes_out;
1943 /* something to send ? */
1944 for (offset = 0; offset != req_cqlen; offset += weWant) {
1945 weWant = req_cqlen - offset > FCGI_MAX_LENGTH ? FCGI_MAX_LENGTH : req_cqlen - offset;
1947 /* we announce toWrite octets
1948 * now take all request_content chunks available
1949 * */
1951 fcgi_header(&(header), FCGI_STDIN, request_id, weWant, 0);
1952 chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
1953 hctx->wb_reqlen += sizeof(header);
1955 if (hctx->conf.debug > 10) {
1956 log_error_write(srv, __FILE__, __LINE__, "soso", "tosend:", offset, "/", req_cqlen);
1959 chunkqueue_steal(hctx->wb, req_cq, weWant);
1960 /*(hctx->wb_reqlen already includes content_length)*/
1963 if (hctx->wb->bytes_in == hctx->wb_reqlen) {
1964 /* terminate STDIN */
1965 fcgi_header(&(header), FCGI_STDIN, request_id, 0, 0);
1966 chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
1967 hctx->wb_reqlen += (int)sizeof(header);
1971 static int fcgi_create_env(server *srv, handler_ctx *hctx, int request_id) {
1972 FCGI_BeginRequestRecord beginRecord;
1973 FCGI_Header header;
1975 plugin_data *p = hctx->plugin_data;
1976 fcgi_extension_host *host= hctx->host;
1978 connection *con = hctx->remote_conn;
1980 http_cgi_opts opts = {
1981 (hctx->fcgi_mode == FCGI_AUTHORIZER),
1982 host->break_scriptfilename_for_php,
1983 host->docroot,
1984 host->strip_request_uri
1987 /* send FCGI_BEGIN_REQUEST */
1989 fcgi_header(&(beginRecord.header), FCGI_BEGIN_REQUEST, request_id, sizeof(beginRecord.body), 0);
1990 beginRecord.body.roleB0 = hctx->fcgi_mode;
1991 beginRecord.body.roleB1 = 0;
1992 beginRecord.body.flags = 0;
1993 memset(beginRecord.body.reserved, 0, sizeof(beginRecord.body.reserved));
1995 /* send FCGI_PARAMS */
1996 buffer_string_prepare_copy(p->fcgi_env, 1023);
1998 if (0 != http_cgi_headers(srv, con, &opts, fcgi_env_add, p->fcgi_env)) {
1999 con->http_status = 400;
2000 return -1;
2001 } else {
2002 buffer *b = buffer_init();
2004 buffer_copy_string_len(b, (const char *)&beginRecord, sizeof(beginRecord));
2006 fcgi_header(&(header), FCGI_PARAMS, request_id, buffer_string_length(p->fcgi_env), 0);
2007 buffer_append_string_len(b, (const char *)&header, sizeof(header));
2008 buffer_append_string_buffer(b, p->fcgi_env);
2010 fcgi_header(&(header), FCGI_PARAMS, request_id, 0, 0);
2011 buffer_append_string_len(b, (const char *)&header, sizeof(header));
2013 hctx->wb_reqlen = buffer_string_length(b);
2014 chunkqueue_append_buffer(hctx->wb, b);
2015 buffer_free(b);
2018 hctx->wb_reqlen += con->request.content_length;/* (eventual) (minimal) total request size, not necessarily including all fcgi_headers around content length yet */
2019 fcgi_stdin_append(srv, con, hctx, request_id);
2021 return 0;
2024 static int fcgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in) {
2025 char *s, *ns;
2027 handler_ctx *hctx = con->plugin_ctx[p->id];
2028 fcgi_extension_host *host= hctx->host;
2029 int have_sendfile2 = 0;
2030 off_t sendfile2_content_length = 0;
2032 UNUSED(srv);
2034 /* search for \n */
2035 for (s = in->ptr; NULL != (ns = strchr(s, '\n')); s = ns + 1) {
2036 char *key, *value;
2037 int key_len;
2039 /* a good day. Someone has read the specs and is sending a \r\n to us */
2041 if (ns > in->ptr &&
2042 *(ns-1) == '\r') {
2043 *(ns-1) = '\0';
2046 ns[0] = '\0';
2048 key = s;
2049 if (NULL == (value = strchr(s, ':'))) {
2050 /* we expect: "<key>: <value>\n" */
2051 continue;
2054 key_len = value - key;
2056 value++;
2057 /* strip WS */
2058 while (*value == ' ' || *value == '\t') value++;
2060 if (hctx->fcgi_mode != FCGI_AUTHORIZER ||
2061 !(con->http_status == 0 ||
2062 con->http_status == 200)) {
2063 /* authorizers shouldn't affect the response headers sent back to the client */
2065 /* don't forward Status: */
2066 if (0 != strncasecmp(key, "Status", key_len)) {
2067 data_string *ds;
2068 if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2069 ds = data_response_init();
2071 buffer_copy_string_len(ds->key, key, key_len);
2072 buffer_copy_string(ds->value, value);
2074 array_insert_unique(con->response.headers, (data_unset *)ds);
2078 if (hctx->fcgi_mode == FCGI_AUTHORIZER &&
2079 key_len > 9 &&
2080 0 == strncasecmp(key, CONST_STR_LEN("Variable-"))) {
2081 data_string *ds;
2082 if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
2083 ds = data_response_init();
2085 buffer_copy_string_len(ds->key, key + 9, key_len - 9);
2086 buffer_copy_string(ds->value, value);
2088 array_insert_unique(con->environment, (data_unset *)ds);
2091 switch(key_len) {
2092 case 4:
2093 if (0 == strncasecmp(key, "Date", key_len)) {
2094 con->parsed_response |= HTTP_DATE;
2096 break;
2097 case 6:
2098 if (0 == strncasecmp(key, "Status", key_len)) {
2099 int status = strtol(value, NULL, 10);
2100 if (status >= 100 && status < 1000) {
2101 con->http_status = status;
2102 con->parsed_response |= HTTP_STATUS;
2103 } else {
2104 con->http_status = 502;
2107 break;
2108 case 8:
2109 if (0 == strncasecmp(key, "Location", key_len)) {
2110 con->parsed_response |= HTTP_LOCATION;
2112 break;
2113 case 10:
2114 if (0 == strncasecmp(key, "Connection", key_len)) {
2115 con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
2116 con->parsed_response |= HTTP_CONNECTION;
2118 break;
2119 case 11:
2120 if (host->xsendfile_allow && 0 == strncasecmp(key, "X-Sendfile2", key_len) && hctx->send_content_body) {
2121 char *pos = value;
2122 have_sendfile2 = 1;
2124 while (*pos) {
2125 char *filename, *range;
2126 stat_cache_entry *sce;
2127 off_t begin_range, end_range, range_len;
2129 while (' ' == *pos) pos++;
2130 if (!*pos) break;
2132 filename = pos;
2133 if (NULL == (range = strchr(pos, ' '))) {
2134 /* missing range */
2135 if (hctx->conf.debug) {
2136 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't find range after filename:", filename);
2138 return 502;
2140 buffer_copy_string_len(srv->tmp_buf, filename, range - filename);
2142 /* find end of range */
2143 for (pos = ++range; *pos && *pos != ' ' && *pos != ','; pos++) ;
2145 buffer_urldecode_path(srv->tmp_buf);
2146 buffer_path_simplify(srv->tmp_buf, srv->tmp_buf);
2147 if (con->conf.force_lowercase_filenames) {
2148 buffer_to_lower(srv->tmp_buf);
2150 if (host->xsendfile_docroot->used) {
2151 size_t i, xlen = buffer_string_length(srv->tmp_buf);
2152 for (i = 0; i < host->xsendfile_docroot->used; ++i) {
2153 data_string *ds = (data_string *)host->xsendfile_docroot->data[i];
2154 size_t dlen = buffer_string_length(ds->value);
2155 if (dlen <= xlen
2156 && (!con->conf.force_lowercase_filenames
2157 ? 0 == memcmp(srv->tmp_buf->ptr, ds->value->ptr, dlen)
2158 : 0 == strncasecmp(srv->tmp_buf->ptr, ds->value->ptr, dlen))) {
2159 break;
2162 if (i == host->xsendfile_docroot->used) {
2163 log_error_write(srv, __FILE__, __LINE__, "SBs",
2164 "X-Sendfile2 (", srv->tmp_buf,
2165 ") not under configured x-sendfile-docroot(s)");
2166 return 403;
2170 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, srv->tmp_buf, &sce)) {
2171 if (hctx->conf.debug) {
2172 log_error_write(srv, __FILE__, __LINE__, "sb",
2173 "send-file error: couldn't get stat_cache entry for X-Sendfile2:",
2174 srv->tmp_buf);
2176 return 404;
2177 } else if (!S_ISREG(sce->st.st_mode)) {
2178 if (hctx->conf.debug) {
2179 log_error_write(srv, __FILE__, __LINE__, "sb",
2180 "send-file error: wrong filetype for X-Sendfile2:",
2181 srv->tmp_buf);
2183 return 502;
2185 /* found the file */
2187 /* parse range */
2188 end_range = sce->st.st_size - 1;
2190 char *rpos = NULL;
2191 errno = 0;
2192 begin_range = strtoll(range, &rpos, 10);
2193 if (errno != 0 || begin_range < 0 || rpos == range) goto range_failed;
2194 if ('-' != *rpos++) goto range_failed;
2195 if (rpos != pos) {
2196 range = rpos;
2197 end_range = strtoll(range, &rpos, 10);
2198 if (errno != 0 || end_range < 0 || rpos == range) goto range_failed;
2200 if (rpos != pos) goto range_failed;
2202 goto range_success;
2204 range_failed:
2205 if (hctx->conf.debug) {
2206 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't decode range after filename:", filename);
2208 return 502;
2210 range_success: ;
2213 /* no parameters accepted */
2215 while (*pos == ' ') pos++;
2216 if (*pos != '\0' && *pos != ',') return 502;
2218 range_len = end_range - begin_range + 1;
2219 if (range_len < 0) return 502;
2220 if (range_len != 0) {
2221 if (0 != http_chunk_append_file_range(srv, con, srv->tmp_buf, begin_range, range_len)) {
2222 return 502;
2225 sendfile2_content_length += range_len;
2227 if (*pos == ',') pos++;
2230 break;
2231 case 14:
2232 if (0 == strncasecmp(key, "Content-Length", key_len)) {
2233 con->response.content_length = strtoul(value, NULL, 10);
2234 con->parsed_response |= HTTP_CONTENT_LENGTH;
2236 if (con->response.content_length < 0) con->response.content_length = 0;
2238 break;
2239 default:
2240 break;
2244 if (have_sendfile2) {
2245 data_string *dcls;
2247 /* fix content-length */
2248 if (NULL == (dcls = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2249 dcls = data_response_init();
2252 buffer_copy_string_len(dcls->key, "Content-Length", sizeof("Content-Length")-1);
2253 buffer_copy_int(dcls->value, sendfile2_content_length);
2254 array_replace(con->response.headers, (data_unset *)dcls);
2256 con->parsed_response |= HTTP_CONTENT_LENGTH;
2257 con->response.content_length = sendfile2_content_length;
2258 return 200;
2261 /* CGI/1.1 rev 03 - 7.2.1.2 */
2262 if ((con->parsed_response & HTTP_LOCATION) &&
2263 !(con->parsed_response & HTTP_STATUS)) {
2264 con->http_status = 302;
2267 return 0;
2270 typedef struct {
2271 buffer *b;
2272 unsigned int len;
2273 int type;
2274 int padding;
2275 int request_id;
2276 } fastcgi_response_packet;
2278 static int fastcgi_get_packet(server *srv, handler_ctx *hctx, fastcgi_response_packet *packet) {
2279 chunk *c;
2280 size_t offset;
2281 size_t toread;
2282 FCGI_Header *header;
2284 if (!hctx->rb->first) return -1;
2286 packet->b = buffer_init();
2287 packet->len = 0;
2288 packet->type = 0;
2289 packet->padding = 0;
2290 packet->request_id = 0;
2292 offset = 0; toread = 8;
2293 /* get at least the FastCGI header */
2294 for (c = hctx->rb->first; c; c = c->next) {
2295 size_t weHave = buffer_string_length(c->mem) - c->offset;
2297 if (weHave > toread) weHave = toread;
2299 buffer_append_string_len(packet->b, c->mem->ptr + c->offset, weHave);
2300 toread -= weHave;
2301 offset = weHave; /* skip offset bytes in chunk for "real" data */
2303 if (0 == toread) break;
2306 if (buffer_string_length(packet->b) < sizeof(FCGI_Header)) {
2307 /* no header */
2308 if (hctx->conf.debug) {
2309 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");
2312 buffer_free(packet->b);
2314 return -1;
2317 /* we have at least a header, now check how much me have to fetch */
2318 header = (FCGI_Header *)(packet->b->ptr);
2320 packet->len = (header->contentLengthB0 | (header->contentLengthB1 << 8)) + header->paddingLength;
2321 packet->request_id = (header->requestIdB0 | (header->requestIdB1 << 8));
2322 packet->type = header->type;
2323 packet->padding = header->paddingLength;
2325 /* ->b should only be the content */
2326 buffer_string_set_length(packet->b, 0);
2328 if (packet->len) {
2329 /* copy the content */
2330 for (; c && (buffer_string_length(packet->b) < packet->len); c = c->next) {
2331 size_t weWant = packet->len - buffer_string_length(packet->b);
2332 size_t weHave = buffer_string_length(c->mem) - c->offset - offset;
2334 if (weHave > weWant) weHave = weWant;
2336 buffer_append_string_len(packet->b, c->mem->ptr + c->offset + offset, weHave);
2338 /* we only skipped the first bytes as they belonged to the fcgi header */
2339 offset = 0;
2342 if (buffer_string_length(packet->b) < packet->len) {
2343 /* we didn't get the full packet */
2345 buffer_free(packet->b);
2346 return -1;
2349 buffer_string_set_length(packet->b, buffer_string_length(packet->b) - packet->padding);
2352 chunkqueue_mark_written(hctx->rb, packet->len + sizeof(FCGI_Header));
2354 return 0;
2357 static int fcgi_demux_response(server *srv, handler_ctx *hctx) {
2358 int fin = 0;
2359 int toread, ret;
2360 ssize_t r = 0;
2362 plugin_data *p = hctx->plugin_data;
2363 connection *con = hctx->remote_conn;
2364 int fcgi_fd = hctx->fd;
2365 fcgi_extension_host *host= hctx->host;
2366 fcgi_proc *proc = hctx->proc;
2369 * check how much we have to read
2371 #if !defined(_WIN32) && !defined(__CYGWIN__)
2372 if (ioctl(hctx->fd, FIONREAD, &toread)) {
2373 if (errno == EAGAIN) {
2374 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2375 return 0;
2377 log_error_write(srv, __FILE__, __LINE__, "sd",
2378 "unexpected end-of-file (perhaps the fastcgi process died):",
2379 fcgi_fd);
2380 return -1;
2382 #else
2383 toread = 4096;
2384 #endif
2386 if (toread > 0) {
2387 char *mem;
2388 size_t mem_len;
2390 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)) {
2391 off_t cqlen = chunkqueue_length(hctx->rb);
2392 if (cqlen + toread > 65536 + (int)sizeof(FCGI_Header)) { /*(max size of FastCGI packet + 1)*/
2393 if (cqlen < 65536 + (int)sizeof(FCGI_Header)) {
2394 toread = 65536 + (int)sizeof(FCGI_Header) - cqlen;
2395 } else { /* should not happen */
2396 toread = toread < 1024 ? toread : 1024;
2401 chunkqueue_get_memory(hctx->rb, &mem, &mem_len, 0, toread);
2402 r = read(hctx->fd, mem, mem_len);
2403 chunkqueue_use_memory(hctx->rb, r > 0 ? r : 0);
2405 if (-1 == r) {
2406 if (errno == EAGAIN) {
2407 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2408 return 0;
2410 log_error_write(srv, __FILE__, __LINE__, "sds",
2411 "unexpected end-of-file (perhaps the fastcgi process died):",
2412 fcgi_fd, strerror(errno));
2413 return -1;
2416 if (0 == r) {
2417 log_error_write(srv, __FILE__, __LINE__, "ssdsb",
2418 "unexpected end-of-file (perhaps the fastcgi process died):",
2419 "pid:", proc->pid,
2420 "socket:", proc->connection_name);
2422 return -1;
2426 * parse the fastcgi packets and forward the content to the write-queue
2429 while (fin == 0) {
2430 fastcgi_response_packet packet;
2432 /* check if we have at least one packet */
2433 if (0 != fastcgi_get_packet(srv, hctx, &packet)) {
2434 /* no full packet */
2435 break;
2438 switch(packet.type) {
2439 case FCGI_STDOUT:
2440 if (packet.len == 0) break;
2442 /* is the header already finished */
2443 if (0 == con->file_started) {
2444 char *c;
2445 data_string *ds;
2447 /* search for header terminator
2449 * if we start with \r\n check if last packet terminated with \r\n
2450 * if we start with \n check if last packet terminated with \n
2451 * search for \r\n\r\n
2452 * search for \n\n
2455 buffer_append_string_buffer(hctx->response_header, packet.b);
2457 if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\r\n\r\n")))) {
2458 char *hend = c + 4; /* header end == body start */
2459 size_t hlen = hend - hctx->response_header->ptr;
2460 buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2461 buffer_string_set_length(hctx->response_header, hlen);
2462 } else if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\n\n")))) {
2463 char *hend = c + 2; /* header end == body start */
2464 size_t hlen = hend - hctx->response_header->ptr;
2465 buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2466 buffer_string_set_length(hctx->response_header, hlen);
2467 } else {
2468 /* no luck, no header found */
2469 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
2470 if (buffer_string_length(hctx->response_header) > MAX_HTTP_REQUEST_HEADER) {
2471 log_error_write(srv, __FILE__, __LINE__, "sb", "response headers too large for", con->uri.path);
2472 con->http_status = 502; /* Bad Gateway */
2473 con->mode = DIRECT;
2474 fin = 1;
2476 break;
2479 /* parse the response header */
2480 if ((ret = fcgi_response_parse(srv, con, p, hctx->response_header))) {
2481 if (200 != ret) { /*(200 returned for X-Sendfile2 handled)*/
2482 con->http_status = ret;
2483 con->mode = DIRECT;
2485 con->file_started = 1;
2486 hctx->send_content_body = 0;
2487 fin = 1;
2488 break;
2491 con->file_started = 1;
2493 if (hctx->fcgi_mode == FCGI_AUTHORIZER &&
2494 (con->http_status == 0 ||
2495 con->http_status == 200)) {
2496 /* a authorizer with approved the static request, ignore the content here */
2497 hctx->send_content_body = 0;
2500 if (host->xsendfile_allow && hctx->send_content_body &&
2501 (NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-LIGHTTPD-send-file"))
2502 || NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-Sendfile")))) {
2503 http_response_xsendfile(srv, con, ds->value, host->xsendfile_docroot);
2504 if (con->mode == DIRECT) {
2505 fin = 1;
2508 hctx->send_content_body = 0; /* ignore the content */
2509 break;
2513 if (hctx->send_content_body && !buffer_string_is_empty(packet.b)) {
2514 if (0 != http_chunk_append_buffer(srv, con, packet.b)) {
2515 /* error writing to tempfile;
2516 * truncate response or send 500 if nothing sent yet */
2517 fin = 1;
2518 break;
2520 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
2521 && chunkqueue_length(con->write_queue) > 65536 - 4096) {
2522 if (!con->is_writable) {
2523 /*(defer removal of FDEVENT_IN interest since
2524 * connection_state_machine() might be able to send data
2525 * immediately, unless !con->is_writable, where
2526 * connection_state_machine() might not loop back to call
2527 * mod_fastcgi_handle_subrequest())*/
2528 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2532 break;
2533 case FCGI_STDERR:
2534 if (packet.len == 0) break;
2536 log_error_write_multiline_buffer(srv, __FILE__, __LINE__, packet.b, "s",
2537 "FastCGI-stderr:");
2539 break;
2540 case FCGI_END_REQUEST:
2541 fin = 1;
2542 break;
2543 default:
2544 log_error_write(srv, __FILE__, __LINE__, "sd",
2545 "FastCGI: header.type not handled: ", packet.type);
2546 break;
2548 buffer_free(packet.b);
2551 return fin;
2554 static int fcgi_restart_dead_procs(server *srv, plugin_data *p, fcgi_extension_host *host) {
2555 fcgi_proc *proc;
2557 for (proc = host->first; proc; proc = proc->next) {
2558 int status;
2560 if (p->conf.debug > 2) {
2561 log_error_write(srv, __FILE__, __LINE__, "sbdddd",
2562 "proc:",
2563 proc->connection_name,
2564 proc->state,
2565 proc->is_local,
2566 proc->load,
2567 proc->pid);
2571 * if the remote side is overloaded, we check back after <n> seconds
2574 switch (proc->state) {
2575 case PROC_STATE_KILLED:
2576 case PROC_STATE_UNSET:
2577 /* this should never happen as long as adaptive spawing is disabled */
2578 force_assert(0);
2580 break;
2581 case PROC_STATE_RUNNING:
2582 break;
2583 case PROC_STATE_OVERLOADED:
2584 if (srv->cur_ts <= proc->disabled_until) break;
2586 proc->state = PROC_STATE_RUNNING;
2587 host->active_procs++;
2589 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2590 "fcgi-server re-enabled:",
2591 host->host, host->port,
2592 host->unixsocket);
2593 break;
2594 case PROC_STATE_DIED_WAIT_FOR_PID:
2595 /* non-local procs don't have PIDs to wait for */
2596 if (!proc->is_local) {
2597 proc->state = PROC_STATE_DIED;
2598 } else {
2599 /* the child should not terminate at all */
2601 for ( ;; ) {
2602 switch(waitpid(proc->pid, &status, WNOHANG)) {
2603 case 0:
2604 /* child is still alive */
2605 if (srv->cur_ts <= proc->disabled_until) break;
2607 proc->state = PROC_STATE_RUNNING;
2608 host->active_procs++;
2610 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2611 "fcgi-server re-enabled:",
2612 host->host, host->port,
2613 host->unixsocket);
2614 break;
2615 case -1:
2616 if (errno == EINTR) continue;
2618 log_error_write(srv, __FILE__, __LINE__, "sd",
2619 "child died somehow, waitpid failed:",
2620 errno);
2621 proc->state = PROC_STATE_DIED;
2622 break;
2623 default:
2624 if (WIFEXITED(status)) {
2625 #if 0
2626 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2627 "child exited, pid:", proc->pid,
2628 "status:", WEXITSTATUS(status));
2629 #endif
2630 } else if (WIFSIGNALED(status)) {
2631 log_error_write(srv, __FILE__, __LINE__, "sd",
2632 "child signaled:",
2633 WTERMSIG(status));
2634 } else {
2635 log_error_write(srv, __FILE__, __LINE__, "sd",
2636 "child died somehow:",
2637 status);
2640 proc->state = PROC_STATE_DIED;
2641 break;
2643 break;
2647 /* fall through if we have a dead proc now */
2648 if (proc->state != PROC_STATE_DIED) break;
2650 case PROC_STATE_DIED:
2651 /* local procs get restarted by us,
2652 * remote ones hopefully by the admin */
2654 if (!buffer_string_is_empty(host->bin_path)) {
2655 /* we still have connections bound to this proc,
2656 * let them terminate first */
2657 if (proc->load != 0) break;
2659 /* restart the child */
2661 if (p->conf.debug) {
2662 log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
2663 "--- fastcgi spawning",
2664 "\n\tsocket", proc->connection_name,
2665 "\n\tcurrent:", 1, "/", host->max_procs);
2668 if (fcgi_spawn_connection(srv, p, host, proc)) {
2669 log_error_write(srv, __FILE__, __LINE__, "s",
2670 "ERROR: spawning fcgi failed.");
2671 return HANDLER_ERROR;
2673 } else {
2674 if (srv->cur_ts <= proc->disabled_until) break;
2676 proc->state = PROC_STATE_RUNNING;
2677 host->active_procs++;
2679 log_error_write(srv, __FILE__, __LINE__, "sb",
2680 "fcgi-server re-enabled:",
2681 proc->connection_name);
2683 break;
2687 return 0;
2690 static handler_t fcgi_write_request(server *srv, handler_ctx *hctx) {
2691 plugin_data *p = hctx->plugin_data;
2692 fcgi_extension_host *host= hctx->host;
2693 connection *con = hctx->remote_conn;
2694 fcgi_proc *proc;
2696 int ret;
2698 /* we can't handle this in the switch as we have to fall through in it */
2699 if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
2700 int socket_error;
2701 socklen_t socket_error_len = sizeof(socket_error);
2703 /* try to finish the connect() */
2704 if (0 != getsockopt(hctx->fd, SOL_SOCKET, SO_ERROR, &socket_error, &socket_error_len)) {
2705 log_error_write(srv, __FILE__, __LINE__, "ss",
2706 "getsockopt failed:", strerror(errno));
2708 fcgi_host_disable(srv, hctx);
2710 return HANDLER_ERROR;
2712 if (socket_error != 0) {
2713 if (!hctx->proc->is_local || hctx->conf.debug) {
2714 /* local procs get restarted */
2716 log_error_write(srv, __FILE__, __LINE__, "sssb",
2717 "establishing connection failed:", strerror(socket_error),
2718 "socket:", hctx->proc->connection_name);
2721 fcgi_host_disable(srv, hctx);
2722 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2723 "backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2724 "reconnects:", hctx->reconnects,
2725 "load:", host->load);
2727 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2728 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2730 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2732 return HANDLER_ERROR;
2734 /* go on with preparing the request */
2735 hctx->state = FCGI_STATE_PREPARE_WRITE;
2739 switch(hctx->state) {
2740 case FCGI_STATE_CONNECT_DELAYED:
2741 /* should never happen */
2742 return HANDLER_WAIT_FOR_EVENT;
2743 case FCGI_STATE_INIT:
2744 /* do we have a running process for this host (max-procs) ? */
2745 hctx->proc = NULL;
2747 for (proc = hctx->host->first;
2748 proc && proc->state != PROC_STATE_RUNNING;
2749 proc = proc->next);
2751 /* all children are dead */
2752 if (proc == NULL) {
2753 hctx->fde_ndx = -1;
2755 return HANDLER_ERROR;
2758 hctx->proc = proc;
2760 /* check the other procs if they have a lower load */
2761 for (proc = proc->next; proc; proc = proc->next) {
2762 if (proc->state != PROC_STATE_RUNNING) continue;
2763 if (proc->load < hctx->proc->load) hctx->proc = proc;
2766 if (-1 == (hctx->fd = fdevent_socket_nb_cloexec(host->family, SOCK_STREAM, 0))) {
2767 if (errno == EMFILE ||
2768 errno == EINTR) {
2769 log_error_write(srv, __FILE__, __LINE__, "sd",
2770 "wait for fd at connection:", con->fd);
2772 return HANDLER_WAIT_FOR_FD;
2775 log_error_write(srv, __FILE__, __LINE__, "ssdd",
2776 "socket failed:", strerror(errno), srv->cur_fds, srv->max_fds);
2777 return HANDLER_ERROR;
2779 hctx->fde_ndx = -1;
2781 srv->cur_fds++;
2783 fdevent_register(srv->ev, hctx->fd, fcgi_handle_fdevent, hctx);
2785 if (-1 == fdevent_fcntl_set(srv->ev, hctx->fd)) {
2786 log_error_write(srv, __FILE__, __LINE__, "ss",
2787 "fcntl failed:", strerror(errno));
2789 return HANDLER_ERROR;
2792 if (hctx->proc->is_local) {
2793 hctx->pid = hctx->proc->pid;
2796 switch (fcgi_establish_connection(srv, hctx)) {
2797 case CONNECTION_DELAYED:
2798 /* connection is in progress, wait for an event and call getsockopt() below */
2800 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2802 fcgi_set_state(srv, hctx, FCGI_STATE_CONNECT_DELAYED);
2803 return HANDLER_WAIT_FOR_EVENT;
2804 case CONNECTION_OVERLOADED:
2805 /* cool down the backend, it is overloaded
2806 * -> EAGAIN */
2808 if (hctx->host->disable_time) {
2809 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2810 "backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2811 "reconnects:", hctx->reconnects,
2812 "load:", host->load);
2814 hctx->proc->disabled_until = srv->cur_ts + hctx->host->disable_time;
2815 if (hctx->proc->state == PROC_STATE_RUNNING) hctx->host->active_procs--;
2816 hctx->proc->state = PROC_STATE_OVERLOADED;
2819 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2820 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".overloaded"));
2822 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2824 return HANDLER_ERROR;
2825 case CONNECTION_DEAD:
2826 /* we got a hard error from the backend like
2827 * - ECONNREFUSED for tcp-ip sockets
2828 * - ENOENT for unix-domain-sockets
2830 * for check if the host is back in hctx->host->disable_time seconds
2831 * */
2833 fcgi_host_disable(srv, hctx);
2835 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2836 "backend died; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2837 "reconnects:", hctx->reconnects,
2838 "load:", host->load);
2840 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2841 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2843 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2845 return HANDLER_ERROR;
2846 case CONNECTION_OK:
2847 /* everything is ok, go on */
2849 fcgi_set_state(srv, hctx, FCGI_STATE_PREPARE_WRITE);
2851 break;
2853 /* fallthrough */
2854 case FCGI_STATE_PREPARE_WRITE:
2855 /* ok, we have the connection */
2857 fcgi_proc_load_inc(srv, hctx);
2858 hctx->got_proc = 1;
2860 status_counter_inc(srv, CONST_STR_LEN("fastcgi.requests"));
2862 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2863 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".connected"));
2865 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2867 if (hctx->conf.debug) {
2868 log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
2869 "got proc:",
2870 "pid:", hctx->proc->pid,
2871 "socket:", hctx->proc->connection_name,
2872 "load:", hctx->proc->load);
2875 /* move the proc-list entry down the list */
2876 if (hctx->request_id == 0) {
2877 hctx->request_id = 1; /* always use id 1 as we don't use multiplexing */
2878 } else {
2879 log_error_write(srv, __FILE__, __LINE__, "sd",
2880 "fcgi-request is already in use:", hctx->request_id);
2883 if (-1 == fcgi_create_env(srv, hctx, hctx->request_id)) return HANDLER_ERROR;
2885 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2886 fcgi_set_state(srv, hctx, FCGI_STATE_WRITE);
2887 /* fall through */
2888 case FCGI_STATE_WRITE:
2889 ret = srv->network_backend_write(srv, con, hctx->fd, hctx->wb, MAX_WRITE_LIMIT);
2891 chunkqueue_remove_finished_chunks(hctx->wb);
2893 if (ret < 0) {
2894 switch(errno) {
2895 case EPIPE:
2896 case ENOTCONN:
2897 case ECONNRESET:
2898 /* the connection got dropped after accept()
2899 * we don't care about that - if you accept() it, you have to handle it.
2902 log_error_write(srv, __FILE__, __LINE__, "ssosb",
2903 "connection was dropped after accept() (perhaps the fastcgi process died),",
2904 "write-offset:", hctx->wb->bytes_out,
2905 "socket:", hctx->proc->connection_name);
2907 return HANDLER_ERROR;
2908 default:
2909 log_error_write(srv, __FILE__, __LINE__, "ssd",
2910 "write failed:", strerror(errno), errno);
2912 return HANDLER_ERROR;
2916 if (hctx->wb->bytes_out == hctx->wb_reqlen) {
2917 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2918 fcgi_set_state(srv, hctx, FCGI_STATE_READ);
2919 } else {
2920 off_t wblen = hctx->wb->bytes_in - hctx->wb->bytes_out;
2921 if (hctx->wb->bytes_in < hctx->wb_reqlen && wblen < 65536 - 16384) {
2922 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
2923 if (!(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_POLLIN)) {
2924 con->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLIN;
2925 con->is_readable = 1; /* trigger optimistic read from client */
2928 if (0 == wblen) {
2929 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2930 } else {
2931 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2935 return HANDLER_WAIT_FOR_EVENT;
2936 case FCGI_STATE_READ:
2937 /* waiting for a response */
2938 return HANDLER_WAIT_FOR_EVENT;
2939 default:
2940 log_error_write(srv, __FILE__, __LINE__, "s", "(debug) unknown state");
2941 return HANDLER_ERROR;
2946 /* might be called on fdevent after a connect() is delay too
2947 * */
2948 static handler_t fcgi_send_request(server *srv, handler_ctx *hctx) {
2949 /* ok, create the request */
2950 fcgi_extension_host *host = hctx->host;
2951 handler_t rc = fcgi_write_request(srv, hctx);
2952 if (HANDLER_ERROR != rc) {
2953 return rc;
2954 } else {
2955 plugin_data *p = hctx->plugin_data;
2956 connection *con = hctx->remote_conn;
2958 if (hctx->state == FCGI_STATE_INIT ||
2959 hctx->state == FCGI_STATE_CONNECT_DELAYED) {
2960 fcgi_restart_dead_procs(srv, p, host);
2962 /* cleanup this request and let the request handler start this request again */
2963 if (hctx->reconnects++ < 5) {
2964 return fcgi_reconnect(srv, hctx);
2965 } else {
2966 fcgi_connection_close(srv, hctx);
2967 con->http_status = 503;
2969 return HANDLER_FINISHED;
2971 } else {
2972 int status = con->http_status;
2973 fcgi_connection_close(srv, hctx);
2974 con->http_status = (status == 400) ? 400 : 503;
2976 return HANDLER_FINISHED;
2982 static handler_t fcgi_recv_response(server *srv, handler_ctx *hctx);
2985 SUBREQUEST_FUNC(mod_fastcgi_handle_subrequest) {
2986 plugin_data *p = p_d;
2988 handler_ctx *hctx = con->plugin_ctx[p->id];
2990 if (NULL == hctx) return HANDLER_GO_ON;
2992 /* not my job */
2993 if (con->mode != p->id) return HANDLER_GO_ON;
2995 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
2996 && con->file_started) {
2997 if (chunkqueue_length(con->write_queue) > 65536 - 4096) {
2998 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2999 } else if (!(fdevent_event_get_interest(srv->ev, hctx->fd) & FDEVENT_IN)) {
3000 /* optimistic read from backend, which might re-enable FDEVENT_IN */
3001 handler_t rc = fcgi_recv_response(srv, hctx); /*(might invalidate hctx)*/
3002 if (rc != HANDLER_GO_ON) return rc; /*(unless HANDLER_GO_ON)*/
3006 /* (do not receive request body before FCGI_AUTHORIZER has run or else
3007 * the request body is discarded with handler_ctx_clear() after running
3008 * the FastCGI Authorizer) */
3010 if (hctx->fcgi_mode != FCGI_AUTHORIZER
3011 && (0 == hctx->wb->bytes_in
3012 ? con->state == CON_STATE_READ_POST
3013 : hctx->wb->bytes_in < hctx->wb_reqlen)) {
3014 /*(64k - 4k to attempt to avoid temporary files
3015 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
3016 if (hctx->wb->bytes_in - hctx->wb->bytes_out > 65536 - 4096
3017 && (con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_BUFMIN)){
3018 con->conf.stream_request_body &= ~FDEVENT_STREAM_REQUEST_POLLIN;
3019 if (0 != hctx->wb->bytes_in) return HANDLER_WAIT_FOR_EVENT;
3020 } else {
3021 handler_t r = connection_handle_read_post_state(srv, con);
3022 chunkqueue *req_cq = con->request_content_queue;
3023 if (0 != hctx->wb->bytes_in && !chunkqueue_is_empty(req_cq)) {
3024 fcgi_stdin_append(srv, con, hctx, hctx->request_id);
3025 if (fdevent_event_get_interest(srv->ev, hctx->fd) & FDEVENT_OUT) {
3026 return (r == HANDLER_GO_ON) ? HANDLER_WAIT_FOR_EVENT : r;
3029 if (r != HANDLER_GO_ON) return r;
3033 return ((0 == hctx->wb->bytes_in || !chunkqueue_is_empty(hctx->wb))
3034 && hctx->state != FCGI_STATE_CONNECT_DELAYED)
3035 ? fcgi_send_request(srv, hctx)
3036 : HANDLER_WAIT_FOR_EVENT;
3040 static handler_t fcgi_recv_response(server *srv, handler_ctx *hctx) {
3041 connection *con = hctx->remote_conn;
3042 plugin_data *p = hctx->plugin_data;
3044 fcgi_proc *proc = hctx->proc;
3045 fcgi_extension_host *host= hctx->host;
3047 switch (fcgi_demux_response(srv, hctx)) {
3048 case 0:
3049 break;
3050 case 1:
3052 if (hctx->fcgi_mode == FCGI_AUTHORIZER &&
3053 (con->http_status == 200 ||
3054 con->http_status == 0)) {
3056 * If we are here in AUTHORIZER mode then a request for authorizer
3057 * was processed already, and status 200 has been returned. We need
3058 * now to handle authorized request.
3060 buffer *physpath = NULL;
3062 if (!buffer_string_is_empty(host->docroot)) {
3063 buffer_copy_buffer(con->physical.doc_root, host->docroot);
3064 buffer_copy_buffer(con->physical.basedir, host->docroot);
3066 buffer_copy_buffer(con->physical.path, host->docroot);
3067 buffer_append_string_buffer(con->physical.path, con->uri.path);
3068 physpath = con->physical.path;
3071 fcgi_backend_close(srv, hctx);
3072 handler_ctx_clear(hctx);
3074 /* don't do more than 6 loops here, that normally shouldn't happen */
3075 if (++con->loops_per_request > 5) {
3076 log_error_write(srv, __FILE__, __LINE__, "sb", "too many loops while processing request:", con->request.orig_uri);
3077 con->http_status = 500; /* Internal Server Error */
3078 con->mode = DIRECT;
3079 return HANDLER_FINISHED;
3082 /* restart the request so other handlers can process it */
3084 if (physpath) con->physical.path = NULL;
3085 connection_response_reset(srv, con); /*(includes con->http_status = 0)*/
3086 if (physpath) con->physical.path = physpath; /* preserve con->physical.path with modified docroot */
3088 /*(FYI: if multiple FastCGI authorizers were to be supported,
3089 * next one could be started here instead of restarting request)*/
3091 con->mode = DIRECT;
3092 return HANDLER_COMEBACK;
3093 } else {
3094 /* we are done */
3095 fcgi_connection_close(srv, hctx);
3098 return HANDLER_FINISHED;
3099 case -1:
3100 if (proc->pid && proc->state != PROC_STATE_DIED) {
3101 int status;
3103 /* only fetch the zombie if it is not already done */
3105 switch(waitpid(proc->pid, &status, WNOHANG)) {
3106 case 0:
3107 /* child is still alive */
3108 break;
3109 case -1:
3110 break;
3111 default:
3112 /* the child should not terminate at all */
3113 if (WIFEXITED(status)) {
3114 log_error_write(srv, __FILE__, __LINE__, "sdsd",
3115 "child exited, pid:", proc->pid,
3116 "status:", WEXITSTATUS(status));
3117 } else if (WIFSIGNALED(status)) {
3118 log_error_write(srv, __FILE__, __LINE__, "sd",
3119 "child signaled:",
3120 WTERMSIG(status));
3121 } else {
3122 log_error_write(srv, __FILE__, __LINE__, "sd",
3123 "child died somehow:",
3124 status);
3127 if (hctx->conf.debug) {
3128 log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
3129 "--- fastcgi spawning",
3130 "\n\tsocket", proc->connection_name,
3131 "\n\tcurrent:", 1, "/", host->max_procs);
3134 if (fcgi_spawn_connection(srv, p, host, proc)) {
3135 /* respawning failed, retry later */
3136 proc->state = PROC_STATE_DIED;
3138 log_error_write(srv, __FILE__, __LINE__, "s",
3139 "respawning failed, will retry later");
3142 break;
3146 if (con->file_started == 0) {
3147 /* nothing has been sent out yet, try to use another child */
3149 if (hctx->wb->bytes_out == 0 &&
3150 hctx->reconnects++ < 5) {
3152 log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3153 "response not received, request not sent",
3154 "on socket:", proc->connection_name,
3155 "for", con->uri.path, "?", con->uri.query, ", reconnecting");
3157 return fcgi_reconnect(srv, hctx);
3160 log_error_write(srv, __FILE__, __LINE__, "sosbsBSBs",
3161 "response not received, request sent:", hctx->wb->bytes_out,
3162 "on socket:", proc->connection_name,
3163 "for", con->uri.path, "?", con->uri.query, ", closing connection");
3164 } else {
3165 log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3166 "response already sent out, but backend returned error",
3167 "on socket:", proc->connection_name,
3168 "for", con->uri.path, "?", con->uri.query, ", terminating connection");
3171 http_response_backend_error(srv, con);
3172 fcgi_connection_close(srv, hctx);
3173 return HANDLER_FINISHED;
3176 return HANDLER_GO_ON;
3180 static handler_t fcgi_handle_fdevent(server *srv, void *ctx, int revents) {
3181 handler_ctx *hctx = ctx;
3182 connection *con = hctx->remote_conn;
3184 joblist_append(srv, con);
3186 if (revents & FDEVENT_IN) {
3187 handler_t rc = fcgi_recv_response(srv, hctx);/*(might invalidate hctx)*/
3188 if (rc != HANDLER_GO_ON) return rc; /*(unless HANDLER_GO_ON)*/
3191 if (revents & FDEVENT_OUT) {
3192 return fcgi_send_request(srv, hctx); /*(might invalidate hctx)*/
3195 /* perhaps this issue is already handled */
3196 if (revents & FDEVENT_HUP) {
3197 if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
3198 /* getoptsock will catch this one (right ?)
3200 * if we are in connect we might get an EINPROGRESS
3201 * in the first call and an FDEVENT_HUP in the
3202 * second round
3204 * FIXME: as it is a bit ugly.
3207 fcgi_send_request(srv, hctx);
3208 } else if (con->file_started) {
3209 /* drain any remaining data from kernel pipe buffers
3210 * even if (con->conf.stream_response_body
3211 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
3212 * since event loop will spin on fd FDEVENT_HUP event
3213 * until unregistered. */
3214 handler_t rc;
3215 do {
3216 rc = fcgi_recv_response(srv,hctx);/*(might invalidate hctx)*/
3217 } while (rc == HANDLER_GO_ON); /*(unless HANDLER_GO_ON)*/
3218 return rc; /* HANDLER_FINISHED or HANDLER_ERROR */
3219 } else {
3220 fcgi_proc *proc = hctx->proc;
3221 log_error_write(srv, __FILE__, __LINE__, "sBSbsbsd",
3222 "error: unexpected close of fastcgi connection for",
3223 con->uri.path, "?", con->uri.query,
3224 "(no fastcgi process on socket:", proc->connection_name, "?)",
3225 hctx->state);
3227 fcgi_connection_close(srv, hctx);
3229 } else if (revents & FDEVENT_ERR) {
3230 log_error_write(srv, __FILE__, __LINE__, "s",
3231 "fcgi: got a FDEVENT_ERR. Don't know why.");
3233 http_response_backend_error(srv, con);
3234 fcgi_connection_close(srv, hctx);
3237 return HANDLER_FINISHED;
3240 #define PATCH(x) \
3241 p->conf.x = s->x;
3242 static int fcgi_patch_connection(server *srv, connection *con, plugin_data *p) {
3243 size_t i, j;
3244 plugin_config *s = p->config_storage[0];
3246 PATCH(exts);
3247 PATCH(exts_auth);
3248 PATCH(exts_resp);
3249 PATCH(debug);
3250 PATCH(ext_mapping);
3252 /* skip the first, the global context */
3253 for (i = 1; i < srv->config_context->used; i++) {
3254 data_config *dc = (data_config *)srv->config_context->data[i];
3255 s = p->config_storage[i];
3257 /* condition didn't match */
3258 if (!config_check_cond(srv, con, dc)) continue;
3260 /* merge config */
3261 for (j = 0; j < dc->value->used; j++) {
3262 data_unset *du = dc->value->data[j];
3264 if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.server"))) {
3265 PATCH(exts);
3266 PATCH(exts_auth);
3267 PATCH(exts_resp);
3268 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.debug"))) {
3269 PATCH(debug);
3270 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.map-extensions"))) {
3271 PATCH(ext_mapping);
3276 return 0;
3278 #undef PATCH
3281 static handler_t fcgi_check_extension(server *srv, connection *con, void *p_d, int uri_path_handler) {
3282 plugin_data *p = p_d;
3283 size_t s_len;
3284 size_t k;
3285 buffer *fn;
3286 fcgi_extension *extension = NULL;
3287 fcgi_extension_host *host = NULL;
3288 handler_ctx *hctx;
3289 unsigned short fcgi_mode;
3291 if (con->mode != DIRECT) return HANDLER_GO_ON;
3293 fn = uri_path_handler ? con->uri.path : con->physical.path;
3295 if (buffer_string_is_empty(fn)) return HANDLER_GO_ON;
3297 s_len = buffer_string_length(fn);
3299 fcgi_patch_connection(srv, con, p);
3300 if (NULL == p->conf.exts) return HANDLER_GO_ON;
3302 /* check p->conf.exts_auth list and then p->conf.ext_resp list
3303 * (skip p->conf.exts_auth if array is empty or if FCGI_AUTHORIZER already ran in this request */
3304 hctx = con->plugin_ctx[p->id]; /*(not NULL if FCGI_AUTHORIZER ran; hctx->ext-auth check is redundant)*/
3305 fcgi_mode = (NULL == hctx || NULL == hctx->ext_auth)
3306 ? 0 /* FCGI_AUTHORIZER p->conf.exts_auth will be searched next */
3307 : FCGI_AUTHORIZER; /* FCGI_RESPONDER p->conf.exts_resp will be searched next */
3309 do {
3311 fcgi_exts *exts;
3312 if (0 == fcgi_mode) {
3313 fcgi_mode = FCGI_AUTHORIZER;
3314 exts = p->conf.exts_auth;
3315 } else {
3316 fcgi_mode = FCGI_RESPONDER;
3317 exts = p->conf.exts_resp;
3320 if (0 == exts->used) continue;
3322 /* fastcgi.map-extensions maps extensions to existing fastcgi.server entries
3324 * fastcgi.map-extensions = ( ".php3" => ".php" )
3326 * fastcgi.server = ( ".php" => ... )
3328 * */
3330 /* check if extension-mapping matches */
3331 for (k = 0; k < p->conf.ext_mapping->used; k++) {
3332 data_string *ds = (data_string *)p->conf.ext_mapping->data[k];
3333 size_t ct_len; /* length of the config entry */
3335 if (buffer_is_empty(ds->key)) continue;
3337 ct_len = buffer_string_length(ds->key);
3339 if (s_len < ct_len) continue;
3341 /* found a mapping */
3342 if (0 == strncmp(fn->ptr + s_len - ct_len, ds->key->ptr, ct_len)) {
3343 /* check if we know the extension */
3345 /* we can reuse k here */
3346 for (k = 0; k < exts->used; k++) {
3347 extension = exts->exts[k];
3349 if (buffer_is_equal(ds->value, extension->key)) {
3350 break;
3354 if (k == exts->used) {
3355 /* found nothing */
3356 extension = NULL;
3358 break;
3362 if (extension == NULL) {
3363 size_t uri_path_len = buffer_string_length(con->uri.path);
3365 /* check if extension matches */
3366 for (k = 0; k < exts->used; k++) {
3367 size_t ct_len; /* length of the config entry */
3368 fcgi_extension *ext = exts->exts[k];
3370 if (buffer_is_empty(ext->key)) continue;
3372 ct_len = buffer_string_length(ext->key);
3374 /* check _url_ in the form "/fcgi_pattern" */
3375 if (ext->key->ptr[0] == '/') {
3376 if ((ct_len <= uri_path_len) &&
3377 (strncmp(con->uri.path->ptr, ext->key->ptr, ct_len) == 0)) {
3378 extension = ext;
3379 break;
3381 } else if ((ct_len <= s_len) && (0 == strncmp(fn->ptr + s_len - ct_len, ext->key->ptr, ct_len))) {
3382 /* check extension in the form ".fcg" */
3383 extension = ext;
3384 break;
3389 } while (NULL == extension && fcgi_mode != FCGI_RESPONDER);
3391 /* extension doesn't match */
3392 if (NULL == extension) {
3393 return HANDLER_GO_ON;
3396 /* check if we have at least one server for this extension up and running */
3397 host = fcgi_extension_host_get(srv, con, p, extension);
3398 if (NULL == host) {
3399 return HANDLER_FINISHED;
3402 /* a note about no handler is not sent yet */
3403 extension->note_is_sent = 0;
3406 * if check-local is disabled, use the uri.path handler
3410 /* init handler-context */
3411 if (uri_path_handler) {
3412 if (host->check_local != 0) {
3413 return HANDLER_GO_ON;
3414 } else {
3415 /* do not split path info for authorizer */
3416 if (fcgi_mode != FCGI_AUTHORIZER) {
3417 /* the prefix is the SCRIPT_NAME,
3418 * everything from start to the next slash
3419 * this is important for check-local = "disable"
3421 * if prefix = /admin.fcgi
3423 * /admin.fcgi/foo/bar
3425 * SCRIPT_NAME = /admin.fcgi
3426 * PATH_INFO = /foo/bar
3428 * if prefix = /fcgi-bin/
3430 * /fcgi-bin/foo/bar
3432 * SCRIPT_NAME = /fcgi-bin/foo
3433 * PATH_INFO = /bar
3435 * if prefix = /, and fix-root-path-name is enable
3437 * /fcgi-bin/foo/bar
3439 * SCRIPT_NAME = /fcgi-bin/foo
3440 * PATH_INFO = /bar
3443 char *pathinfo;
3445 /* the rewrite is only done for /prefix/? matches */
3446 if (host->fix_root_path_name && extension->key->ptr[0] == '/' && extension->key->ptr[1] == '\0') {
3447 buffer_copy_string(con->request.pathinfo, con->uri.path->ptr);
3448 buffer_string_set_length(con->uri.path, 0);
3449 } else if (extension->key->ptr[0] == '/' &&
3450 buffer_string_length(con->uri.path) > buffer_string_length(extension->key) &&
3451 NULL != (pathinfo = strchr(con->uri.path->ptr + buffer_string_length(extension->key), '/'))) {
3452 /* rewrite uri.path and pathinfo */
3454 buffer_copy_string(con->request.pathinfo, pathinfo);
3455 buffer_string_set_length(con->uri.path, buffer_string_length(con->uri.path) - buffer_string_length(con->request.pathinfo));
3461 if (!hctx) hctx = handler_ctx_init();
3463 hctx->remote_conn = con;
3464 hctx->plugin_data = p;
3465 hctx->proc = NULL;
3466 hctx->ext = extension;
3467 fcgi_host_assign(srv, hctx, host);
3469 hctx->fcgi_mode = fcgi_mode;
3470 if (fcgi_mode == FCGI_AUTHORIZER) {
3471 hctx->ext_auth = hctx->ext;
3474 /*hctx->conf.exts = p->conf.exts;*/
3475 /*hctx->conf.exts_auth = p->conf.exts_auth;*/
3476 /*hctx->conf.exts_resp = p->conf.exts_resp;*/
3477 /*hctx->conf.ext_mapping = p->conf.ext_mapping;*/
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", "handling it in mod_fastcgi");
3488 return HANDLER_GO_ON;
3491 /* uri-path handler */
3492 static handler_t fcgi_check_extension_1(server *srv, connection *con, void *p_d) {
3493 return fcgi_check_extension(srv, con, p_d, 1);
3496 /* start request handler */
3497 static handler_t fcgi_check_extension_2(server *srv, connection *con, void *p_d) {
3498 return fcgi_check_extension(srv, con, p_d, 0);
3502 TRIGGER_FUNC(mod_fastcgi_handle_trigger) {
3503 plugin_data *p = p_d;
3504 size_t i, j, n;
3507 /* perhaps we should kill a connect attempt after 10-15 seconds
3509 * currently we wait for the TCP timeout which is 180 seconds on Linux
3515 /* check all children if they are still up */
3517 for (i = 0; i < srv->config_context->used; i++) {
3518 plugin_config *conf;
3519 fcgi_exts *exts;
3521 conf = p->config_storage[i];
3523 exts = conf->exts;
3524 if (NULL == exts) continue;
3526 for (j = 0; j < exts->used; j++) {
3527 fcgi_extension *ex;
3529 ex = exts->exts[j];
3531 for (n = 0; n < ex->used; n++) {
3533 fcgi_proc *proc;
3534 fcgi_extension_host *host;
3536 host = ex->hosts[n];
3538 fcgi_restart_dead_procs(srv, p, host);
3540 for (proc = host->unused_procs; proc; proc = proc->next) {
3541 int status;
3543 if (proc->pid == 0) continue;
3545 switch (waitpid(proc->pid, &status, WNOHANG)) {
3546 case 0:
3547 /* child still running after timeout, good */
3548 break;
3549 case -1:
3550 if (errno != EINTR) {
3551 /* no PID found ? should never happen */
3552 log_error_write(srv, __FILE__, __LINE__, "sddss",
3553 "pid ", proc->pid, proc->state,
3554 "not found:", strerror(errno));
3556 #if 0
3557 if (errno == ECHILD) {
3558 /* someone else has cleaned up for us */
3559 proc->pid = 0;
3560 proc->state = PROC_STATE_UNSET;
3562 #endif
3564 break;
3565 default:
3566 /* the child should not terminate at all */
3567 if (WIFEXITED(status)) {
3568 if (proc->state != PROC_STATE_KILLED) {
3569 log_error_write(srv, __FILE__, __LINE__, "sdb",
3570 "child exited:",
3571 WEXITSTATUS(status), proc->connection_name);
3573 } else if (WIFSIGNALED(status)) {
3574 if (WTERMSIG(status) != SIGTERM) {
3575 log_error_write(srv, __FILE__, __LINE__, "sd",
3576 "child signaled:",
3577 WTERMSIG(status));
3579 } else {
3580 log_error_write(srv, __FILE__, __LINE__, "sd",
3581 "child died somehow:",
3582 status);
3584 proc->pid = 0;
3585 if (proc->state == PROC_STATE_RUNNING) host->active_procs--;
3586 proc->state = PROC_STATE_UNSET;
3587 host->max_id--;
3594 return HANDLER_GO_ON;
3598 int mod_fastcgi_plugin_init(plugin *p);
3599 int mod_fastcgi_plugin_init(plugin *p) {
3600 p->version = LIGHTTPD_VERSION_ID;
3601 p->name = buffer_init_string("fastcgi");
3603 p->init = mod_fastcgi_init;
3604 p->cleanup = mod_fastcgi_free;
3605 p->set_defaults = mod_fastcgi_set_defaults;
3606 p->connection_reset = fcgi_connection_reset;
3607 p->handle_connection_close = fcgi_connection_reset;
3608 p->handle_uri_clean = fcgi_check_extension_1;
3609 p->handle_subrequest_start = fcgi_check_extension_2;
3610 p->handle_subrequest = mod_fastcgi_handle_subrequest;
3611 p->handle_trigger = mod_fastcgi_handle_trigger;
3613 p->data = NULL;
3615 return 0;