[mod_cgi] fix pipe_cloexec() when no O_CLOEXEC
[lighttpd.git] / src / mod_fastcgi.c
blob1873af07bb3c163331576088c86a6dc714610269
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 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;
1628 if (hctx->host) {
1629 if (hctx->proc && hctx->got_proc) {
1630 /* after the connect the process gets a load */
1631 fcgi_proc_load_dec(srv, hctx);
1633 if (hctx->conf.debug) {
1634 log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
1635 "released proc:",
1636 "pid:", hctx->proc->pid,
1637 "socket:", hctx->proc->connection_name,
1638 "load:", hctx->proc->load);
1642 fcgi_host_reset(srv, hctx);
1646 static void fcgi_connection_close(server *srv, handler_ctx *hctx) {
1647 plugin_data *p;
1648 connection *con;
1650 p = hctx->plugin_data;
1651 con = hctx->remote_conn;
1653 fcgi_backend_close(srv, hctx);
1654 handler_ctx_free(hctx);
1655 con->plugin_ctx[p->id] = NULL;
1657 /* finish response (if not already con->file_started, con->file_finished) */
1658 if (con->mode == p->id) {
1659 http_response_backend_done(srv, con);
1663 static int fcgi_reconnect(server *srv, handler_ctx *hctx) {
1664 /* child died
1666 * 1.
1668 * connect was ok, connection was accepted
1669 * but the php accept loop checks after the accept if it should die or not.
1671 * if yes we can only detect it at a write()
1673 * next step is resetting this attemp and setup a connection again
1675 * if we have more than 5 reconnects for the same request, die
1677 * 2.
1679 * we have a connection but the child died by some other reason
1683 if (hctx->fd != -1) {
1684 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1685 fdevent_unregister(srv->ev, hctx->fd);
1686 fdevent_sched_close(srv->ev, hctx->fd, 1);
1687 hctx->fd = -1;
1690 fcgi_set_state(srv, hctx, FCGI_STATE_INIT);
1692 hctx->request_id = 0;
1693 hctx->reconnects++;
1695 if (hctx->conf.debug > 2) {
1696 if (hctx->proc) {
1697 log_error_write(srv, __FILE__, __LINE__, "sdb",
1698 "release proc for reconnect:",
1699 hctx->proc->pid, hctx->proc->connection_name);
1700 } else {
1701 log_error_write(srv, __FILE__, __LINE__, "sb",
1702 "release proc for reconnect:",
1703 hctx->host->unixsocket);
1707 if (hctx->proc && hctx->got_proc) {
1708 fcgi_proc_load_dec(srv, hctx);
1711 /* perhaps another host gives us more luck */
1712 fcgi_host_reset(srv, hctx);
1714 return 0;
1718 static handler_t fcgi_connection_reset(server *srv, connection *con, void *p_d) {
1719 plugin_data *p = p_d;
1720 handler_ctx *hctx = con->plugin_ctx[p->id];
1721 if (hctx) fcgi_connection_close(srv, hctx);
1723 return HANDLER_GO_ON;
1727 static int fcgi_env_add(void *venv, const char *key, size_t key_len, const char *val, size_t val_len) {
1728 buffer *env = venv;
1729 size_t len;
1730 char len_enc[8];
1731 size_t len_enc_len = 0;
1733 if (!key || !val) return -1;
1735 len = key_len + val_len;
1737 len += key_len > 127 ? 4 : 1;
1738 len += val_len > 127 ? 4 : 1;
1740 if (buffer_string_length(env) + len >= FCGI_MAX_LENGTH) {
1742 * we can't append more headers, ignore it
1744 return -1;
1748 * field length can be 31bit max
1750 * HINT: this can't happen as FCGI_MAX_LENGTH is only 16bit
1752 force_assert(key_len < 0x7fffffffu);
1753 force_assert(val_len < 0x7fffffffu);
1755 buffer_string_prepare_append(env, len);
1757 if (key_len > 127) {
1758 len_enc[len_enc_len++] = ((key_len >> 24) & 0xff) | 0x80;
1759 len_enc[len_enc_len++] = (key_len >> 16) & 0xff;
1760 len_enc[len_enc_len++] = (key_len >> 8) & 0xff;
1761 len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1762 } else {
1763 len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1766 if (val_len > 127) {
1767 len_enc[len_enc_len++] = ((val_len >> 24) & 0xff) | 0x80;
1768 len_enc[len_enc_len++] = (val_len >> 16) & 0xff;
1769 len_enc[len_enc_len++] = (val_len >> 8) & 0xff;
1770 len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1771 } else {
1772 len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1775 buffer_append_string_len(env, len_enc, len_enc_len);
1776 buffer_append_string_len(env, key, key_len);
1777 buffer_append_string_len(env, val, val_len);
1779 return 0;
1782 static int fcgi_header(FCGI_Header * header, unsigned char type, int request_id, int contentLength, unsigned char paddingLength) {
1783 force_assert(contentLength <= FCGI_MAX_LENGTH);
1785 header->version = FCGI_VERSION_1;
1786 header->type = type;
1787 header->requestIdB0 = request_id & 0xff;
1788 header->requestIdB1 = (request_id >> 8) & 0xff;
1789 header->contentLengthB0 = contentLength & 0xff;
1790 header->contentLengthB1 = (contentLength >> 8) & 0xff;
1791 header->paddingLength = paddingLength;
1792 header->reserved = 0;
1794 return 0;
1797 typedef enum {
1798 CONNECTION_OK,
1799 CONNECTION_DELAYED, /* retry after event, take same host */
1800 CONNECTION_OVERLOADED, /* disable for 1 second, take another backend */
1801 CONNECTION_DEAD /* disable for 60 seconds, take another backend */
1802 } connection_result_t;
1804 static connection_result_t fcgi_establish_connection(server *srv, handler_ctx *hctx) {
1805 struct sockaddr *fcgi_addr;
1806 struct sockaddr_in fcgi_addr_in;
1807 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1808 struct sockaddr_in6 fcgi_addr_in6;
1809 #endif
1810 #ifdef HAVE_SYS_UN_H
1811 struct sockaddr_un fcgi_addr_un;
1812 #endif
1813 socklen_t servlen;
1815 fcgi_extension_host *host = hctx->host;
1816 fcgi_proc *proc = hctx->proc;
1817 int fcgi_fd = hctx->fd;
1819 if (!buffer_string_is_empty(proc->unixsocket)) {
1820 #ifdef HAVE_SYS_UN_H
1821 /* use the unix domain socket */
1822 memset(&fcgi_addr_un, 0, sizeof(fcgi_addr_un));
1823 fcgi_addr_un.sun_family = AF_UNIX;
1824 if (buffer_string_length(proc->unixsocket) + 1 > sizeof(fcgi_addr_un.sun_path)) {
1825 log_error_write(srv, __FILE__, __LINE__, "sB",
1826 "ERROR: Unix Domain socket filename too long:",
1827 proc->unixsocket);
1828 return -1;
1830 memcpy(fcgi_addr_un.sun_path, proc->unixsocket->ptr, buffer_string_length(proc->unixsocket) + 1);
1832 #ifdef SUN_LEN
1833 servlen = SUN_LEN(&fcgi_addr_un);
1834 #else
1835 /* stevens says: */
1836 servlen = buffer_string_length(proc->unixsocket) + 1 + sizeof(fcgi_addr_un.sun_family);
1837 #endif
1838 fcgi_addr = (struct sockaddr *) &fcgi_addr_un;
1840 if (buffer_string_is_empty(proc->connection_name)) {
1841 /* on remote spawing we have to set the connection-name now */
1842 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("unix:"));
1843 buffer_append_string_buffer(proc->connection_name, proc->unixsocket);
1845 #else
1846 return CONNECTION_DEAD;
1847 #endif
1848 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1849 } else if (host->family == AF_INET6 && !buffer_string_is_empty(host->host)) {
1850 memset(&fcgi_addr_in6, 0, sizeof(fcgi_addr_in6));
1851 fcgi_addr_in6.sin6_family = AF_INET6;
1852 inet_pton(AF_INET6, host->host->ptr, (char *) &fcgi_addr_in6.sin6_addr);
1853 fcgi_addr_in6.sin6_port = htons(proc->port);
1854 servlen = sizeof(fcgi_addr_in6);
1855 fcgi_addr = (struct sockaddr *) &fcgi_addr_in6;
1856 #endif
1857 } else {
1858 memset(&fcgi_addr_in, 0, sizeof(fcgi_addr_in));
1859 fcgi_addr_in.sin_family = AF_INET;
1860 if (!buffer_string_is_empty(host->host)) {
1861 if (0 == inet_aton(host->host->ptr, &(fcgi_addr_in.sin_addr))) {
1862 log_error_write(srv, __FILE__, __LINE__, "sbs",
1863 "converting IP address failed for", host->host,
1864 "\nBe sure to specify an IP address here");
1866 return CONNECTION_DEAD;
1868 } else {
1869 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1871 fcgi_addr_in.sin_port = htons(proc->port);
1872 servlen = sizeof(fcgi_addr_in);
1874 fcgi_addr = (struct sockaddr *) &fcgi_addr_in;
1877 if (buffer_string_is_empty(proc->unixsocket)) {
1878 if (buffer_string_is_empty(proc->connection_name)) {
1879 /* on remote spawing we have to set the connection-name now */
1880 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("tcp:"));
1881 if (!buffer_string_is_empty(host->host)) {
1882 buffer_append_string_buffer(proc->connection_name, host->host);
1883 } else {
1884 buffer_append_string_len(proc->connection_name, CONST_STR_LEN("localhost"));
1886 buffer_append_string_len(proc->connection_name, CONST_STR_LEN(":"));
1887 buffer_append_int(proc->connection_name, proc->port);
1891 if (-1 == connect(fcgi_fd, fcgi_addr, servlen)) {
1892 if (errno == EINPROGRESS ||
1893 errno == EALREADY ||
1894 errno == EINTR) {
1895 if (hctx->conf.debug > 2) {
1896 log_error_write(srv, __FILE__, __LINE__, "sb",
1897 "connect delayed; will continue later:", proc->connection_name);
1900 return CONNECTION_DELAYED;
1901 } else if (errno == EAGAIN) {
1902 if (hctx->conf.debug) {
1903 log_error_write(srv, __FILE__, __LINE__, "sbsd",
1904 "This means that you have more incoming requests than your FastCGI backend can handle in parallel."
1905 "It might help to spawn more FastCGI backends or PHP children; if not, decrease server.max-connections."
1906 "The load for this FastCGI backend", proc->connection_name, "is", proc->load);
1909 return CONNECTION_OVERLOADED;
1910 } else {
1911 log_error_write(srv, __FILE__, __LINE__, "sssb",
1912 "connect failed:",
1913 strerror(errno), "on",
1914 proc->connection_name);
1916 return CONNECTION_DEAD;
1920 hctx->reconnects = 0;
1921 if (hctx->conf.debug > 1) {
1922 log_error_write(srv, __FILE__, __LINE__, "sd",
1923 "connect succeeded: ", fcgi_fd);
1926 return CONNECTION_OK;
1929 static void fcgi_stdin_append(server *srv, connection *con, handler_ctx *hctx, int request_id) {
1930 FCGI_Header header;
1931 chunkqueue *req_cq = con->request_content_queue;
1932 off_t offset, weWant;
1933 const off_t req_cqlen = req_cq->bytes_in - req_cq->bytes_out;
1935 /* something to send ? */
1936 for (offset = 0; offset != req_cqlen; offset += weWant) {
1937 weWant = req_cqlen - offset > FCGI_MAX_LENGTH ? FCGI_MAX_LENGTH : req_cqlen - offset;
1939 /* we announce toWrite octets
1940 * now take all request_content chunks available
1941 * */
1943 fcgi_header(&(header), FCGI_STDIN, request_id, weWant, 0);
1944 chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
1945 hctx->wb_reqlen += sizeof(header);
1947 if (hctx->conf.debug > 10) {
1948 log_error_write(srv, __FILE__, __LINE__, "soso", "tosend:", offset, "/", req_cqlen);
1951 chunkqueue_steal(hctx->wb, req_cq, weWant);
1952 /*(hctx->wb_reqlen already includes content_length)*/
1955 if (hctx->wb->bytes_in == hctx->wb_reqlen) {
1956 /* terminate STDIN */
1957 fcgi_header(&(header), FCGI_STDIN, request_id, 0, 0);
1958 chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
1959 hctx->wb_reqlen += (int)sizeof(header);
1963 static int fcgi_create_env(server *srv, handler_ctx *hctx, int request_id) {
1964 FCGI_BeginRequestRecord beginRecord;
1965 FCGI_Header header;
1967 plugin_data *p = hctx->plugin_data;
1968 fcgi_extension_host *host= hctx->host;
1970 connection *con = hctx->remote_conn;
1972 http_cgi_opts opts = {
1973 (hctx->fcgi_mode == FCGI_AUTHORIZER),
1974 host->break_scriptfilename_for_php,
1975 host->docroot,
1976 host->strip_request_uri
1979 /* send FCGI_BEGIN_REQUEST */
1981 fcgi_header(&(beginRecord.header), FCGI_BEGIN_REQUEST, request_id, sizeof(beginRecord.body), 0);
1982 beginRecord.body.roleB0 = hctx->fcgi_mode;
1983 beginRecord.body.roleB1 = 0;
1984 beginRecord.body.flags = 0;
1985 memset(beginRecord.body.reserved, 0, sizeof(beginRecord.body.reserved));
1987 /* send FCGI_PARAMS */
1988 buffer_string_prepare_copy(p->fcgi_env, 1023);
1990 if (0 != http_cgi_headers(srv, con, &opts, fcgi_env_add, p->fcgi_env)) {
1991 con->http_status = 400;
1992 return -1;
1993 } else {
1994 buffer *b = buffer_init();
1996 buffer_copy_string_len(b, (const char *)&beginRecord, sizeof(beginRecord));
1998 fcgi_header(&(header), FCGI_PARAMS, request_id, buffer_string_length(p->fcgi_env), 0);
1999 buffer_append_string_len(b, (const char *)&header, sizeof(header));
2000 buffer_append_string_buffer(b, p->fcgi_env);
2002 fcgi_header(&(header), FCGI_PARAMS, request_id, 0, 0);
2003 buffer_append_string_len(b, (const char *)&header, sizeof(header));
2005 hctx->wb_reqlen = buffer_string_length(b);
2006 chunkqueue_append_buffer(hctx->wb, b);
2007 buffer_free(b);
2010 hctx->wb_reqlen += con->request.content_length;/* (eventual) (minimal) total request size, not necessarily including all fcgi_headers around content length yet */
2011 fcgi_stdin_append(srv, con, hctx, request_id);
2013 return 0;
2016 static int fcgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in) {
2017 char *s, *ns;
2019 handler_ctx *hctx = con->plugin_ctx[p->id];
2020 fcgi_extension_host *host= hctx->host;
2021 int have_sendfile2 = 0;
2022 off_t sendfile2_content_length = 0;
2024 UNUSED(srv);
2026 /* search for \n */
2027 for (s = in->ptr; NULL != (ns = strchr(s, '\n')); s = ns + 1) {
2028 char *key, *value;
2029 int key_len;
2031 /* a good day. Someone has read the specs and is sending a \r\n to us */
2033 if (ns > in->ptr &&
2034 *(ns-1) == '\r') {
2035 *(ns-1) = '\0';
2038 ns[0] = '\0';
2040 key = s;
2041 if (NULL == (value = strchr(s, ':'))) {
2042 /* we expect: "<key>: <value>\n" */
2043 continue;
2046 key_len = value - key;
2048 value++;
2049 /* strip WS */
2050 while (*value == ' ' || *value == '\t') value++;
2052 if (hctx->fcgi_mode != FCGI_AUTHORIZER ||
2053 !(con->http_status == 0 ||
2054 con->http_status == 200)) {
2055 /* authorizers shouldn't affect the response headers sent back to the client */
2057 /* don't forward Status: */
2058 if (0 != strncasecmp(key, "Status", key_len)) {
2059 data_string *ds;
2060 if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2061 ds = data_response_init();
2063 buffer_copy_string_len(ds->key, key, key_len);
2064 buffer_copy_string(ds->value, value);
2066 array_insert_unique(con->response.headers, (data_unset *)ds);
2070 if (hctx->fcgi_mode == FCGI_AUTHORIZER &&
2071 key_len > 9 &&
2072 0 == strncasecmp(key, CONST_STR_LEN("Variable-"))) {
2073 data_string *ds;
2074 if (NULL == (ds = (data_string *)array_get_unused_element(con->environment, TYPE_STRING))) {
2075 ds = data_response_init();
2077 buffer_copy_string_len(ds->key, key + 9, key_len - 9);
2078 buffer_copy_string(ds->value, value);
2080 array_insert_unique(con->environment, (data_unset *)ds);
2083 switch(key_len) {
2084 case 4:
2085 if (0 == strncasecmp(key, "Date", key_len)) {
2086 con->parsed_response |= HTTP_DATE;
2088 break;
2089 case 6:
2090 if (0 == strncasecmp(key, "Status", key_len)) {
2091 int status = strtol(value, NULL, 10);
2092 if (status >= 100 && status < 1000) {
2093 con->http_status = status;
2094 con->parsed_response |= HTTP_STATUS;
2095 } else {
2096 con->http_status = 502;
2099 break;
2100 case 8:
2101 if (0 == strncasecmp(key, "Location", key_len)) {
2102 con->parsed_response |= HTTP_LOCATION;
2104 break;
2105 case 10:
2106 if (0 == strncasecmp(key, "Connection", key_len)) {
2107 con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
2108 con->parsed_response |= HTTP_CONNECTION;
2110 break;
2111 case 11:
2112 if (host->xsendfile_allow && 0 == strncasecmp(key, "X-Sendfile2", key_len) && hctx->send_content_body) {
2113 char *pos = value;
2114 have_sendfile2 = 1;
2116 while (*pos) {
2117 char *filename, *range;
2118 stat_cache_entry *sce;
2119 off_t begin_range, end_range, range_len;
2121 while (' ' == *pos) pos++;
2122 if (!*pos) break;
2124 filename = pos;
2125 if (NULL == (range = strchr(pos, ' '))) {
2126 /* missing range */
2127 if (hctx->conf.debug) {
2128 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't find range after filename:", filename);
2130 return 502;
2132 buffer_copy_string_len(srv->tmp_buf, filename, range - filename);
2134 /* find end of range */
2135 for (pos = ++range; *pos && *pos != ' ' && *pos != ','; pos++) ;
2137 buffer_urldecode_path(srv->tmp_buf);
2138 buffer_path_simplify(srv->tmp_buf, srv->tmp_buf);
2139 if (con->conf.force_lowercase_filenames) {
2140 buffer_to_lower(srv->tmp_buf);
2142 if (host->xsendfile_docroot->used) {
2143 size_t i, xlen = buffer_string_length(srv->tmp_buf);
2144 for (i = 0; i < host->xsendfile_docroot->used; ++i) {
2145 data_string *ds = (data_string *)host->xsendfile_docroot->data[i];
2146 size_t dlen = buffer_string_length(ds->value);
2147 if (dlen <= xlen
2148 && (!con->conf.force_lowercase_filenames
2149 ? 0 == memcmp(srv->tmp_buf->ptr, ds->value->ptr, dlen)
2150 : 0 == strncasecmp(srv->tmp_buf->ptr, ds->value->ptr, dlen))) {
2151 break;
2154 if (i == host->xsendfile_docroot->used) {
2155 log_error_write(srv, __FILE__, __LINE__, "SBs",
2156 "X-Sendfile2 (", srv->tmp_buf,
2157 ") not under configured x-sendfile-docroot(s)");
2158 return 403;
2162 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, srv->tmp_buf, &sce)) {
2163 if (hctx->conf.debug) {
2164 log_error_write(srv, __FILE__, __LINE__, "sb",
2165 "send-file error: couldn't get stat_cache entry for X-Sendfile2:",
2166 srv->tmp_buf);
2168 return 404;
2169 } else if (!S_ISREG(sce->st.st_mode)) {
2170 if (hctx->conf.debug) {
2171 log_error_write(srv, __FILE__, __LINE__, "sb",
2172 "send-file error: wrong filetype for X-Sendfile2:",
2173 srv->tmp_buf);
2175 return 502;
2177 /* found the file */
2179 /* parse range */
2180 end_range = sce->st.st_size - 1;
2182 char *rpos = NULL;
2183 errno = 0;
2184 begin_range = strtoll(range, &rpos, 10);
2185 if (errno != 0 || begin_range < 0 || rpos == range) goto range_failed;
2186 if ('-' != *rpos++) goto range_failed;
2187 if (rpos != pos) {
2188 range = rpos;
2189 end_range = strtoll(range, &rpos, 10);
2190 if (errno != 0 || end_range < 0 || rpos == range) goto range_failed;
2192 if (rpos != pos) goto range_failed;
2194 goto range_success;
2196 range_failed:
2197 if (hctx->conf.debug) {
2198 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't decode range after filename:", filename);
2200 return 502;
2202 range_success: ;
2205 /* no parameters accepted */
2207 while (*pos == ' ') pos++;
2208 if (*pos != '\0' && *pos != ',') return 502;
2210 range_len = end_range - begin_range + 1;
2211 if (range_len < 0) return 502;
2212 if (range_len != 0) {
2213 if (0 != http_chunk_append_file_range(srv, con, srv->tmp_buf, begin_range, range_len)) {
2214 return 502;
2217 sendfile2_content_length += range_len;
2219 if (*pos == ',') pos++;
2222 break;
2223 case 14:
2224 if (0 == strncasecmp(key, "Content-Length", key_len)) {
2225 con->response.content_length = strtoul(value, NULL, 10);
2226 con->parsed_response |= HTTP_CONTENT_LENGTH;
2228 if (con->response.content_length < 0) con->response.content_length = 0;
2230 break;
2231 default:
2232 break;
2236 if (have_sendfile2) {
2237 data_string *dcls;
2239 /* fix content-length */
2240 if (NULL == (dcls = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2241 dcls = data_response_init();
2244 buffer_copy_string_len(dcls->key, "Content-Length", sizeof("Content-Length")-1);
2245 buffer_copy_int(dcls->value, sendfile2_content_length);
2246 array_replace(con->response.headers, (data_unset *)dcls);
2248 con->parsed_response |= HTTP_CONTENT_LENGTH;
2249 con->response.content_length = sendfile2_content_length;
2250 return 200;
2253 /* CGI/1.1 rev 03 - 7.2.1.2 */
2254 if ((con->parsed_response & HTTP_LOCATION) &&
2255 !(con->parsed_response & HTTP_STATUS)) {
2256 con->http_status = 302;
2259 return 0;
2262 typedef struct {
2263 buffer *b;
2264 unsigned int len;
2265 int type;
2266 int padding;
2267 int request_id;
2268 } fastcgi_response_packet;
2270 static int fastcgi_get_packet(server *srv, handler_ctx *hctx, fastcgi_response_packet *packet) {
2271 chunk *c;
2272 size_t offset;
2273 size_t toread;
2274 FCGI_Header *header;
2276 if (!hctx->rb->first) return -1;
2278 packet->b = buffer_init();
2279 packet->len = 0;
2280 packet->type = 0;
2281 packet->padding = 0;
2282 packet->request_id = 0;
2284 offset = 0; toread = 8;
2285 /* get at least the FastCGI header */
2286 for (c = hctx->rb->first; c; c = c->next) {
2287 size_t weHave = buffer_string_length(c->mem) - c->offset;
2289 if (weHave > toread) weHave = toread;
2291 buffer_append_string_len(packet->b, c->mem->ptr + c->offset, weHave);
2292 toread -= weHave;
2293 offset = weHave; /* skip offset bytes in chunk for "real" data */
2295 if (0 == toread) break;
2298 if (buffer_string_length(packet->b) < sizeof(FCGI_Header)) {
2299 /* no header */
2300 if (hctx->conf.debug) {
2301 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");
2304 buffer_free(packet->b);
2306 return -1;
2309 /* we have at least a header, now check how much me have to fetch */
2310 header = (FCGI_Header *)(packet->b->ptr);
2312 packet->len = (header->contentLengthB0 | (header->contentLengthB1 << 8)) + header->paddingLength;
2313 packet->request_id = (header->requestIdB0 | (header->requestIdB1 << 8));
2314 packet->type = header->type;
2315 packet->padding = header->paddingLength;
2317 /* ->b should only be the content */
2318 buffer_string_set_length(packet->b, 0);
2320 if (packet->len) {
2321 /* copy the content */
2322 for (; c && (buffer_string_length(packet->b) < packet->len); c = c->next) {
2323 size_t weWant = packet->len - buffer_string_length(packet->b);
2324 size_t weHave = buffer_string_length(c->mem) - c->offset - offset;
2326 if (weHave > weWant) weHave = weWant;
2328 buffer_append_string_len(packet->b, c->mem->ptr + c->offset + offset, weHave);
2330 /* we only skipped the first bytes as they belonged to the fcgi header */
2331 offset = 0;
2334 if (buffer_string_length(packet->b) < packet->len) {
2335 /* we didn't get the full packet */
2337 buffer_free(packet->b);
2338 return -1;
2341 buffer_string_set_length(packet->b, buffer_string_length(packet->b) - packet->padding);
2344 chunkqueue_mark_written(hctx->rb, packet->len + sizeof(FCGI_Header));
2346 return 0;
2349 static int fcgi_demux_response(server *srv, handler_ctx *hctx) {
2350 int fin = 0;
2351 int toread, ret;
2352 ssize_t r = 0;
2354 plugin_data *p = hctx->plugin_data;
2355 connection *con = hctx->remote_conn;
2356 int fcgi_fd = hctx->fd;
2357 fcgi_extension_host *host= hctx->host;
2358 fcgi_proc *proc = hctx->proc;
2361 * check how much we have to read
2363 #if !defined(_WIN32) && !defined(__CYGWIN__)
2364 if (ioctl(hctx->fd, FIONREAD, &toread)) {
2365 if (errno == EAGAIN) {
2366 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2367 return 0;
2369 log_error_write(srv, __FILE__, __LINE__, "sd",
2370 "unexpected end-of-file (perhaps the fastcgi process died):",
2371 fcgi_fd);
2372 return -1;
2374 #else
2375 toread = 4096;
2376 #endif
2378 if (toread > 0) {
2379 char *mem;
2380 size_t mem_len;
2382 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)) {
2383 off_t cqlen = chunkqueue_length(hctx->rb);
2384 if (cqlen + toread > 65536 + (int)sizeof(FCGI_Header)) { /*(max size of FastCGI packet + 1)*/
2385 if (cqlen < 65536 + (int)sizeof(FCGI_Header)) {
2386 toread = 65536 + (int)sizeof(FCGI_Header) - cqlen;
2387 } else { /* should not happen */
2388 toread = toread < 1024 ? toread : 1024;
2393 chunkqueue_get_memory(hctx->rb, &mem, &mem_len, 0, toread);
2394 r = read(hctx->fd, mem, mem_len);
2395 chunkqueue_use_memory(hctx->rb, r > 0 ? r : 0);
2397 if (-1 == r) {
2398 if (errno == EAGAIN) {
2399 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2400 return 0;
2402 log_error_write(srv, __FILE__, __LINE__, "sds",
2403 "unexpected end-of-file (perhaps the fastcgi process died):",
2404 fcgi_fd, strerror(errno));
2405 return -1;
2408 if (0 == r) {
2409 log_error_write(srv, __FILE__, __LINE__, "ssdsb",
2410 "unexpected end-of-file (perhaps the fastcgi process died):",
2411 "pid:", proc->pid,
2412 "socket:", proc->connection_name);
2414 return -1;
2418 * parse the fastcgi packets and forward the content to the write-queue
2421 while (fin == 0) {
2422 fastcgi_response_packet packet;
2424 /* check if we have at least one packet */
2425 if (0 != fastcgi_get_packet(srv, hctx, &packet)) {
2426 /* no full packet */
2427 break;
2430 switch(packet.type) {
2431 case FCGI_STDOUT:
2432 if (packet.len == 0) break;
2434 /* is the header already finished */
2435 if (0 == con->file_started) {
2436 char *c;
2437 data_string *ds;
2439 /* search for header terminator
2441 * if we start with \r\n check if last packet terminated with \r\n
2442 * if we start with \n check if last packet terminated with \n
2443 * search for \r\n\r\n
2444 * search for \n\n
2447 buffer_append_string_buffer(hctx->response_header, packet.b);
2449 if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\r\n\r\n")))) {
2450 char *hend = c + 4; /* header end == body start */
2451 size_t hlen = hend - hctx->response_header->ptr;
2452 buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2453 buffer_string_set_length(hctx->response_header, hlen);
2454 } else if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\n\n")))) {
2455 char *hend = c + 2; /* header end == body start */
2456 size_t hlen = hend - hctx->response_header->ptr;
2457 buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2458 buffer_string_set_length(hctx->response_header, hlen);
2459 } else {
2460 /* no luck, no header found */
2461 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
2462 if (buffer_string_length(hctx->response_header) > MAX_HTTP_REQUEST_HEADER) {
2463 log_error_write(srv, __FILE__, __LINE__, "sb", "response headers too large for", con->uri.path);
2464 con->http_status = 502; /* Bad Gateway */
2465 con->mode = DIRECT;
2466 fin = 1;
2468 break;
2471 /* parse the response header */
2472 if ((ret = fcgi_response_parse(srv, con, p, hctx->response_header))) {
2473 if (200 != ret) { /*(200 returned for X-Sendfile2 handled)*/
2474 con->http_status = ret;
2475 con->mode = DIRECT;
2477 con->file_started = 1;
2478 hctx->send_content_body = 0;
2479 fin = 1;
2480 break;
2483 con->file_started = 1;
2485 if (hctx->fcgi_mode == FCGI_AUTHORIZER &&
2486 (con->http_status == 0 ||
2487 con->http_status == 200)) {
2488 /* a authorizer with approved the static request, ignore the content here */
2489 hctx->send_content_body = 0;
2492 if (host->xsendfile_allow && hctx->send_content_body &&
2493 (NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-LIGHTTPD-send-file"))
2494 || NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-Sendfile")))) {
2495 http_response_xsendfile(srv, con, ds->value, host->xsendfile_docroot);
2496 if (con->mode == DIRECT) {
2497 fin = 1;
2500 hctx->send_content_body = 0; /* ignore the content */
2501 break;
2505 if (hctx->send_content_body && !buffer_string_is_empty(packet.b)) {
2506 if (0 != http_chunk_append_buffer(srv, con, packet.b)) {
2507 /* error writing to tempfile;
2508 * truncate response or send 500 if nothing sent yet */
2509 fin = 1;
2510 break;
2512 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
2513 && chunkqueue_length(con->write_queue) > 65536 - 4096) {
2514 if (!con->is_writable) {
2515 /*(defer removal of FDEVENT_IN interest since
2516 * connection_state_machine() might be able to send data
2517 * immediately, unless !con->is_writable, where
2518 * connection_state_machine() might not loop back to call
2519 * mod_fastcgi_handle_subrequest())*/
2520 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2524 break;
2525 case FCGI_STDERR:
2526 if (packet.len == 0) break;
2528 log_error_write_multiline_buffer(srv, __FILE__, __LINE__, packet.b, "s",
2529 "FastCGI-stderr:");
2531 break;
2532 case FCGI_END_REQUEST:
2533 fin = 1;
2534 break;
2535 default:
2536 log_error_write(srv, __FILE__, __LINE__, "sd",
2537 "FastCGI: header.type not handled: ", packet.type);
2538 break;
2540 buffer_free(packet.b);
2543 return fin;
2546 static int fcgi_restart_dead_procs(server *srv, plugin_data *p, fcgi_extension_host *host) {
2547 fcgi_proc *proc;
2549 for (proc = host->first; proc; proc = proc->next) {
2550 int status;
2552 if (p->conf.debug > 2) {
2553 log_error_write(srv, __FILE__, __LINE__, "sbdddd",
2554 "proc:",
2555 proc->connection_name,
2556 proc->state,
2557 proc->is_local,
2558 proc->load,
2559 proc->pid);
2563 * if the remote side is overloaded, we check back after <n> seconds
2566 switch (proc->state) {
2567 case PROC_STATE_KILLED:
2568 case PROC_STATE_UNSET:
2569 /* this should never happen as long as adaptive spawing is disabled */
2570 force_assert(0);
2572 break;
2573 case PROC_STATE_RUNNING:
2574 break;
2575 case PROC_STATE_OVERLOADED:
2576 if (srv->cur_ts <= proc->disabled_until) break;
2578 proc->state = PROC_STATE_RUNNING;
2579 host->active_procs++;
2581 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2582 "fcgi-server re-enabled:",
2583 host->host, host->port,
2584 host->unixsocket);
2585 break;
2586 case PROC_STATE_DIED_WAIT_FOR_PID:
2587 /* non-local procs don't have PIDs to wait for */
2588 if (!proc->is_local) {
2589 proc->state = PROC_STATE_DIED;
2590 } else {
2591 /* the child should not terminate at all */
2593 for ( ;; ) {
2594 switch(waitpid(proc->pid, &status, WNOHANG)) {
2595 case 0:
2596 /* child is still alive */
2597 if (srv->cur_ts <= proc->disabled_until) break;
2599 proc->state = PROC_STATE_RUNNING;
2600 host->active_procs++;
2602 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2603 "fcgi-server re-enabled:",
2604 host->host, host->port,
2605 host->unixsocket);
2606 break;
2607 case -1:
2608 if (errno == EINTR) continue;
2610 log_error_write(srv, __FILE__, __LINE__, "sd",
2611 "child died somehow, waitpid failed:",
2612 errno);
2613 proc->state = PROC_STATE_DIED;
2614 break;
2615 default:
2616 if (WIFEXITED(status)) {
2617 #if 0
2618 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2619 "child exited, pid:", proc->pid,
2620 "status:", WEXITSTATUS(status));
2621 #endif
2622 } else if (WIFSIGNALED(status)) {
2623 log_error_write(srv, __FILE__, __LINE__, "sd",
2624 "child signaled:",
2625 WTERMSIG(status));
2626 } else {
2627 log_error_write(srv, __FILE__, __LINE__, "sd",
2628 "child died somehow:",
2629 status);
2632 proc->state = PROC_STATE_DIED;
2633 break;
2635 break;
2639 /* fall through if we have a dead proc now */
2640 if (proc->state != PROC_STATE_DIED) break;
2642 case PROC_STATE_DIED:
2643 /* local procs get restarted by us,
2644 * remote ones hopefully by the admin */
2646 if (!buffer_string_is_empty(host->bin_path)) {
2647 /* we still have connections bound to this proc,
2648 * let them terminate first */
2649 if (proc->load != 0) break;
2651 /* restart the child */
2653 if (p->conf.debug) {
2654 log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
2655 "--- fastcgi spawning",
2656 "\n\tsocket", proc->connection_name,
2657 "\n\tcurrent:", 1, "/", host->max_procs);
2660 if (fcgi_spawn_connection(srv, p, host, proc)) {
2661 log_error_write(srv, __FILE__, __LINE__, "s",
2662 "ERROR: spawning fcgi failed.");
2663 return HANDLER_ERROR;
2665 } else {
2666 if (srv->cur_ts <= proc->disabled_until) break;
2668 proc->state = PROC_STATE_RUNNING;
2669 host->active_procs++;
2671 log_error_write(srv, __FILE__, __LINE__, "sb",
2672 "fcgi-server re-enabled:",
2673 proc->connection_name);
2675 break;
2679 return 0;
2682 static handler_t fcgi_write_request(server *srv, handler_ctx *hctx) {
2683 plugin_data *p = hctx->plugin_data;
2684 fcgi_extension_host *host= hctx->host;
2685 connection *con = hctx->remote_conn;
2686 fcgi_proc *proc;
2688 int ret;
2690 /* sanity check:
2691 * - host != NULL
2692 * - either:
2693 * - tcp socket (do not check host->host->uses, as it may be not set which means INADDR_LOOPBACK)
2694 * - unix socket
2696 if (!host) {
2697 log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: host = NULL");
2698 return HANDLER_ERROR;
2700 if ((!host->port && buffer_string_is_empty(host->unixsocket))) {
2701 log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: neither host->port nor host->unixsocket is set");
2702 return HANDLER_ERROR;
2705 /* we can't handle this in the switch as we have to fall through in it */
2706 if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
2707 int socket_error;
2708 socklen_t socket_error_len = sizeof(socket_error);
2710 /* try to finish the connect() */
2711 if (0 != getsockopt(hctx->fd, SOL_SOCKET, SO_ERROR, &socket_error, &socket_error_len)) {
2712 log_error_write(srv, __FILE__, __LINE__, "ss",
2713 "getsockopt failed:", strerror(errno));
2715 fcgi_host_disable(srv, hctx);
2717 return HANDLER_ERROR;
2719 if (socket_error != 0) {
2720 if (!hctx->proc->is_local || hctx->conf.debug) {
2721 /* local procs get restarted */
2723 log_error_write(srv, __FILE__, __LINE__, "sssb",
2724 "establishing connection failed:", strerror(socket_error),
2725 "socket:", hctx->proc->connection_name);
2728 fcgi_host_disable(srv, hctx);
2729 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2730 "backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2731 "reconnects:", hctx->reconnects,
2732 "load:", host->load);
2734 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2735 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2737 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2739 return HANDLER_ERROR;
2741 /* go on with preparing the request */
2742 hctx->state = FCGI_STATE_PREPARE_WRITE;
2746 switch(hctx->state) {
2747 case FCGI_STATE_CONNECT_DELAYED:
2748 /* should never happen */
2749 return HANDLER_WAIT_FOR_EVENT;
2750 case FCGI_STATE_INIT:
2751 /* do we have a running process for this host (max-procs) ? */
2752 hctx->proc = NULL;
2754 for (proc = hctx->host->first;
2755 proc && proc->state != PROC_STATE_RUNNING;
2756 proc = proc->next);
2758 /* all children are dead */
2759 if (proc == NULL) {
2760 hctx->fde_ndx = -1;
2762 return HANDLER_ERROR;
2765 hctx->proc = proc;
2767 /* check the other procs if they have a lower load */
2768 for (proc = proc->next; proc; proc = proc->next) {
2769 if (proc->state != PROC_STATE_RUNNING) continue;
2770 if (proc->load < hctx->proc->load) hctx->proc = proc;
2773 if (-1 == (hctx->fd = fdevent_socket_nb_cloexec(host->family, SOCK_STREAM, 0))) {
2774 if (errno == EMFILE ||
2775 errno == EINTR) {
2776 log_error_write(srv, __FILE__, __LINE__, "sd",
2777 "wait for fd at connection:", con->fd);
2779 return HANDLER_WAIT_FOR_FD;
2782 log_error_write(srv, __FILE__, __LINE__, "ssdd",
2783 "socket failed:", strerror(errno), srv->cur_fds, srv->max_fds);
2784 return HANDLER_ERROR;
2786 hctx->fde_ndx = -1;
2788 srv->cur_fds++;
2790 fdevent_register(srv->ev, hctx->fd, fcgi_handle_fdevent, hctx);
2792 if (-1 == fdevent_fcntl_set(srv->ev, hctx->fd)) {
2793 log_error_write(srv, __FILE__, __LINE__, "ss",
2794 "fcntl failed:", strerror(errno));
2796 return HANDLER_ERROR;
2799 if (hctx->proc->is_local) {
2800 hctx->pid = hctx->proc->pid;
2803 switch (fcgi_establish_connection(srv, hctx)) {
2804 case CONNECTION_DELAYED:
2805 /* connection is in progress, wait for an event and call getsockopt() below */
2807 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2809 fcgi_set_state(srv, hctx, FCGI_STATE_CONNECT_DELAYED);
2810 return HANDLER_WAIT_FOR_EVENT;
2811 case CONNECTION_OVERLOADED:
2812 /* cool down the backend, it is overloaded
2813 * -> EAGAIN */
2815 if (hctx->host->disable_time) {
2816 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2817 "backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2818 "reconnects:", hctx->reconnects,
2819 "load:", host->load);
2821 hctx->proc->disabled_until = srv->cur_ts + hctx->host->disable_time;
2822 if (hctx->proc->state == PROC_STATE_RUNNING) hctx->host->active_procs--;
2823 hctx->proc->state = PROC_STATE_OVERLOADED;
2826 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2827 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".overloaded"));
2829 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2831 return HANDLER_ERROR;
2832 case CONNECTION_DEAD:
2833 /* we got a hard error from the backend like
2834 * - ECONNREFUSED for tcp-ip sockets
2835 * - ENOENT for unix-domain-sockets
2837 * for check if the host is back in hctx->host->disable_time seconds
2838 * */
2840 fcgi_host_disable(srv, hctx);
2842 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2843 "backend died; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2844 "reconnects:", hctx->reconnects,
2845 "load:", host->load);
2847 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2848 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2850 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2852 return HANDLER_ERROR;
2853 case CONNECTION_OK:
2854 /* everything is ok, go on */
2856 fcgi_set_state(srv, hctx, FCGI_STATE_PREPARE_WRITE);
2858 break;
2860 /* fallthrough */
2861 case FCGI_STATE_PREPARE_WRITE:
2862 /* ok, we have the connection */
2864 fcgi_proc_load_inc(srv, hctx);
2865 hctx->got_proc = 1;
2867 status_counter_inc(srv, CONST_STR_LEN("fastcgi.requests"));
2869 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2870 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".connected"));
2872 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2874 if (hctx->conf.debug) {
2875 log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
2876 "got proc:",
2877 "pid:", hctx->proc->pid,
2878 "socket:", hctx->proc->connection_name,
2879 "load:", hctx->proc->load);
2882 /* move the proc-list entry down the list */
2883 if (hctx->request_id == 0) {
2884 hctx->request_id = 1; /* always use id 1 as we don't use multiplexing */
2885 } else {
2886 log_error_write(srv, __FILE__, __LINE__, "sd",
2887 "fcgi-request is already in use:", hctx->request_id);
2890 if (-1 == fcgi_create_env(srv, hctx, hctx->request_id)) return HANDLER_ERROR;
2892 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2893 fcgi_set_state(srv, hctx, FCGI_STATE_WRITE);
2894 /* fall through */
2895 case FCGI_STATE_WRITE:
2896 ret = srv->network_backend_write(srv, con, hctx->fd, hctx->wb, MAX_WRITE_LIMIT);
2898 chunkqueue_remove_finished_chunks(hctx->wb);
2900 if (ret < 0) {
2901 switch(errno) {
2902 case EPIPE:
2903 case ENOTCONN:
2904 case ECONNRESET:
2905 /* the connection got dropped after accept()
2906 * we don't care about that - if you accept() it, you have to handle it.
2909 log_error_write(srv, __FILE__, __LINE__, "ssosb",
2910 "connection was dropped after accept() (perhaps the fastcgi process died),",
2911 "write-offset:", hctx->wb->bytes_out,
2912 "socket:", hctx->proc->connection_name);
2914 return HANDLER_ERROR;
2915 default:
2916 log_error_write(srv, __FILE__, __LINE__, "ssd",
2917 "write failed:", strerror(errno), errno);
2919 return HANDLER_ERROR;
2923 if (hctx->wb->bytes_out == hctx->wb_reqlen) {
2924 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2925 fcgi_set_state(srv, hctx, FCGI_STATE_READ);
2926 } else {
2927 off_t wblen = hctx->wb->bytes_in - hctx->wb->bytes_out;
2928 if (hctx->wb->bytes_in < hctx->wb_reqlen && wblen < 65536 - 16384) {
2929 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
2930 if (!(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_POLLIN)) {
2931 con->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLIN;
2932 con->is_readable = 1; /* trigger optimistic read from client */
2935 if (0 == wblen) {
2936 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2937 } else {
2938 fdevent_event_add(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2942 return HANDLER_WAIT_FOR_EVENT;
2943 case FCGI_STATE_READ:
2944 /* waiting for a response */
2945 return HANDLER_WAIT_FOR_EVENT;
2946 default:
2947 log_error_write(srv, __FILE__, __LINE__, "s", "(debug) unknown state");
2948 return HANDLER_ERROR;
2953 /* might be called on fdevent after a connect() is delay too
2954 * */
2955 static handler_t fcgi_send_request(server *srv, handler_ctx *hctx) {
2956 fcgi_extension_host *host;
2957 handler_t rc;
2959 /* we don't have a host yet, choose one
2960 * -> this happens in the first round
2961 * and when the host died and we have to select a new one */
2962 if (hctx->host == NULL) {
2963 size_t k;
2964 int ndx, used = -1;
2966 /* check if the next server has no load. */
2967 ndx = hctx->ext->last_used_ndx + 1;
2968 if(ndx >= (int) hctx->ext->used || ndx < 0) ndx = 0;
2969 host = hctx->ext->hosts[ndx];
2970 if (host->load > 0) {
2971 /* get backend with the least load. */
2972 for (k = 0, ndx = -1; k < hctx->ext->used; k++) {
2973 host = hctx->ext->hosts[k];
2975 /* we should have at least one proc that can do something */
2976 if (host->active_procs == 0) continue;
2978 if (used == -1 || host->load < used) {
2979 used = host->load;
2981 ndx = k;
2986 /* found a server */
2987 if (ndx == -1) {
2988 /* all hosts are down */
2990 fcgi_connection_close(srv, hctx);
2992 return HANDLER_FINISHED;
2995 hctx->ext->last_used_ndx = ndx;
2996 host = hctx->ext->hosts[ndx];
2999 * if check-local is disabled, use the uri.path handler
3003 /* init handler-context */
3005 /* we put a connection on this host, move the other new connections to other hosts
3007 * as soon as hctx->host is unassigned, decrease the load again */
3008 fcgi_host_assign(srv, hctx, host);
3009 hctx->proc = NULL;
3010 } else {
3011 host = hctx->host;
3014 /* ok, create the request */
3015 rc = fcgi_write_request(srv, hctx);
3016 if (HANDLER_ERROR != rc) {
3017 return rc;
3018 } else {
3019 plugin_data *p = hctx->plugin_data;
3020 connection *con = hctx->remote_conn;
3022 if (hctx->state == FCGI_STATE_INIT ||
3023 hctx->state == FCGI_STATE_CONNECT_DELAYED) {
3024 fcgi_restart_dead_procs(srv, p, host);
3026 /* cleanup this request and let the request handler start this request again */
3027 if (hctx->reconnects < 5) {
3028 fcgi_reconnect(srv, hctx);
3030 return HANDLER_COMEBACK;
3031 } else {
3032 fcgi_connection_close(srv, hctx);
3033 con->http_status = 503;
3035 return HANDLER_FINISHED;
3037 } else {
3038 int status = con->http_status;
3039 fcgi_connection_close(srv, hctx);
3040 con->http_status = (status == 400) ? 400 : 503;
3042 return HANDLER_FINISHED;
3048 static handler_t fcgi_recv_response(server *srv, handler_ctx *hctx);
3051 SUBREQUEST_FUNC(mod_fastcgi_handle_subrequest) {
3052 plugin_data *p = p_d;
3054 handler_ctx *hctx = con->plugin_ctx[p->id];
3056 if (NULL == hctx) return HANDLER_GO_ON;
3058 /* not my job */
3059 if (con->mode != p->id) return HANDLER_GO_ON;
3061 if ((con->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN)
3062 && con->file_started) {
3063 if (chunkqueue_length(con->write_queue) > 65536 - 4096) {
3064 fdevent_event_clr(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
3065 } else if (!(fdevent_event_get_interest(srv->ev, hctx->fd) & FDEVENT_IN)) {
3066 /* optimistic read from backend, which might re-enable FDEVENT_IN */
3067 handler_t rc = fcgi_recv_response(srv, hctx); /*(might invalidate hctx)*/
3068 if (rc != HANDLER_GO_ON) return rc; /*(unless HANDLER_GO_ON)*/
3072 /* (do not receive request body before FCGI_AUTHORIZER has run or else
3073 * the request body is discarded with handler_ctx_clear() after running
3074 * the FastCGI Authorizer) */
3076 if (hctx->fcgi_mode != FCGI_AUTHORIZER
3077 && (0 == hctx->wb->bytes_in
3078 ? con->state == CON_STATE_READ_POST
3079 : hctx->wb->bytes_in < hctx->wb_reqlen)) {
3080 /*(64k - 4k to attempt to avoid temporary files
3081 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
3082 if (hctx->wb->bytes_in - hctx->wb->bytes_out > 65536 - 4096
3083 && (con->conf.stream_request_body & FDEVENT_STREAM_REQUEST_BUFMIN)){
3084 con->conf.stream_request_body &= ~FDEVENT_STREAM_REQUEST_POLLIN;
3085 if (0 != hctx->wb->bytes_in) return HANDLER_WAIT_FOR_EVENT;
3086 } else {
3087 handler_t r = connection_handle_read_post_state(srv, con);
3088 chunkqueue *req_cq = con->request_content_queue;
3089 if (0 != hctx->wb->bytes_in && !chunkqueue_is_empty(req_cq)) {
3090 fcgi_stdin_append(srv, con, hctx, hctx->request_id);
3091 if (fdevent_event_get_interest(srv->ev, hctx->fd) & FDEVENT_OUT) {
3092 return (r == HANDLER_GO_ON) ? HANDLER_WAIT_FOR_EVENT : r;
3095 if (r != HANDLER_GO_ON) return r;
3099 return ((0 == hctx->wb->bytes_in || !chunkqueue_is_empty(hctx->wb))
3100 && hctx->state != FCGI_STATE_CONNECT_DELAYED)
3101 ? fcgi_send_request(srv, hctx)
3102 : HANDLER_WAIT_FOR_EVENT;
3106 static handler_t fcgi_recv_response(server *srv, handler_ctx *hctx) {
3107 connection *con = hctx->remote_conn;
3108 plugin_data *p = hctx->plugin_data;
3110 fcgi_proc *proc = hctx->proc;
3111 fcgi_extension_host *host= hctx->host;
3113 switch (fcgi_demux_response(srv, hctx)) {
3114 case 0:
3115 break;
3116 case 1:
3118 if (hctx->fcgi_mode == FCGI_AUTHORIZER &&
3119 (con->http_status == 200 ||
3120 con->http_status == 0)) {
3122 * If we are here in AUTHORIZER mode then a request for authorizer
3123 * was processed already, and status 200 has been returned. We need
3124 * now to handle authorized request.
3126 buffer *physpath = NULL;
3128 if (!buffer_string_is_empty(host->docroot)) {
3129 buffer_copy_buffer(con->physical.doc_root, host->docroot);
3130 buffer_copy_buffer(con->physical.basedir, host->docroot);
3132 buffer_copy_buffer(con->physical.path, host->docroot);
3133 buffer_append_string_buffer(con->physical.path, con->uri.path);
3134 physpath = con->physical.path;
3137 fcgi_backend_close(srv, hctx);
3138 handler_ctx_clear(hctx);
3140 /* don't do more than 6 loops here, that normally shouldn't happen */
3141 if (++con->loops_per_request > 5) {
3142 log_error_write(srv, __FILE__, __LINE__, "sb", "too many loops while processing request:", con->request.orig_uri);
3143 con->http_status = 500; /* Internal Server Error */
3144 con->mode = DIRECT;
3145 return HANDLER_FINISHED;
3148 /* restart the request so other handlers can process it */
3150 if (physpath) con->physical.path = NULL;
3151 connection_response_reset(srv, con); /*(includes con->http_status = 0)*/
3152 if (physpath) con->physical.path = physpath; /* preserve con->physical.path with modified docroot */
3154 /*(FYI: if multiple FastCGI authorizers were to be supported,
3155 * next one could be started here instead of restarting request)*/
3157 con->mode = DIRECT;
3158 return HANDLER_COMEBACK;
3159 } else {
3160 /* we are done */
3161 fcgi_connection_close(srv, hctx);
3164 return HANDLER_FINISHED;
3165 case -1:
3166 if (proc->pid && proc->state != PROC_STATE_DIED) {
3167 int status;
3169 /* only fetch the zombie if it is not already done */
3171 switch(waitpid(proc->pid, &status, WNOHANG)) {
3172 case 0:
3173 /* child is still alive */
3174 break;
3175 case -1:
3176 break;
3177 default:
3178 /* the child should not terminate at all */
3179 if (WIFEXITED(status)) {
3180 log_error_write(srv, __FILE__, __LINE__, "sdsd",
3181 "child exited, pid:", proc->pid,
3182 "status:", WEXITSTATUS(status));
3183 } else if (WIFSIGNALED(status)) {
3184 log_error_write(srv, __FILE__, __LINE__, "sd",
3185 "child signaled:",
3186 WTERMSIG(status));
3187 } else {
3188 log_error_write(srv, __FILE__, __LINE__, "sd",
3189 "child died somehow:",
3190 status);
3193 if (hctx->conf.debug) {
3194 log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
3195 "--- fastcgi spawning",
3196 "\n\tsocket", proc->connection_name,
3197 "\n\tcurrent:", 1, "/", host->max_procs);
3200 if (fcgi_spawn_connection(srv, p, host, proc)) {
3201 /* respawning failed, retry later */
3202 proc->state = PROC_STATE_DIED;
3204 log_error_write(srv, __FILE__, __LINE__, "s",
3205 "respawning failed, will retry later");
3208 break;
3212 if (con->file_started == 0) {
3213 /* nothing has been sent out yet, try to use another child */
3215 if (hctx->wb->bytes_out == 0 &&
3216 hctx->reconnects < 5) {
3218 log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3219 "response not received, request not sent",
3220 "on socket:", proc->connection_name,
3221 "for", con->uri.path, "?", con->uri.query, ", reconnecting");
3223 fcgi_reconnect(srv, hctx);
3225 return HANDLER_COMEBACK;
3228 log_error_write(srv, __FILE__, __LINE__, "sosbsBSBs",
3229 "response not received, request sent:", hctx->wb->bytes_out,
3230 "on socket:", proc->connection_name,
3231 "for", con->uri.path, "?", con->uri.query, ", closing connection");
3232 } else {
3233 log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3234 "response already sent out, but backend returned error",
3235 "on socket:", proc->connection_name,
3236 "for", con->uri.path, "?", con->uri.query, ", terminating connection");
3239 http_response_backend_error(srv, con);
3240 fcgi_connection_close(srv, hctx);
3241 return HANDLER_FINISHED;
3244 return HANDLER_GO_ON;
3248 static handler_t fcgi_handle_fdevent(server *srv, void *ctx, int revents) {
3249 handler_ctx *hctx = ctx;
3250 connection *con = hctx->remote_conn;
3252 joblist_append(srv, con);
3254 if (revents & FDEVENT_IN) {
3255 handler_t rc = fcgi_recv_response(srv, hctx);/*(might invalidate hctx)*/
3256 if (rc != HANDLER_GO_ON) return rc; /*(unless HANDLER_GO_ON)*/
3259 if (revents & FDEVENT_OUT) {
3260 return fcgi_send_request(srv, hctx); /*(might invalidate hctx)*/
3263 /* perhaps this issue is already handled */
3264 if (revents & FDEVENT_HUP) {
3265 if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
3266 /* getoptsock will catch this one (right ?)
3268 * if we are in connect we might get an EINPROGRESS
3269 * in the first call and an FDEVENT_HUP in the
3270 * second round
3272 * FIXME: as it is a bit ugly.
3275 fcgi_send_request(srv, hctx);
3276 } else if (con->file_started) {
3277 /* drain any remaining data from kernel pipe buffers
3278 * even if (con->conf.stream_response_body
3279 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
3280 * since event loop will spin on fd FDEVENT_HUP event
3281 * until unregistered. */
3282 handler_t rc;
3283 do {
3284 rc = fcgi_recv_response(srv,hctx);/*(might invalidate hctx)*/
3285 } while (rc == HANDLER_GO_ON); /*(unless HANDLER_GO_ON)*/
3286 return rc; /* HANDLER_FINISHED or HANDLER_ERROR */
3287 } else {
3288 fcgi_proc *proc = hctx->proc;
3289 log_error_write(srv, __FILE__, __LINE__, "sBSbsbsd",
3290 "error: unexpected close of fastcgi connection for",
3291 con->uri.path, "?", con->uri.query,
3292 "(no fastcgi process on socket:", proc->connection_name, "?)",
3293 hctx->state);
3295 fcgi_connection_close(srv, hctx);
3297 } else if (revents & FDEVENT_ERR) {
3298 log_error_write(srv, __FILE__, __LINE__, "s",
3299 "fcgi: got a FDEVENT_ERR. Don't know why.");
3301 http_response_backend_error(srv, con);
3302 fcgi_connection_close(srv, hctx);
3305 return HANDLER_FINISHED;
3308 #define PATCH(x) \
3309 p->conf.x = s->x;
3310 static int fcgi_patch_connection(server *srv, connection *con, plugin_data *p) {
3311 size_t i, j;
3312 plugin_config *s = p->config_storage[0];
3314 PATCH(exts);
3315 PATCH(exts_auth);
3316 PATCH(exts_resp);
3317 PATCH(debug);
3318 PATCH(ext_mapping);
3320 /* skip the first, the global context */
3321 for (i = 1; i < srv->config_context->used; i++) {
3322 data_config *dc = (data_config *)srv->config_context->data[i];
3323 s = p->config_storage[i];
3325 /* condition didn't match */
3326 if (!config_check_cond(srv, con, dc)) continue;
3328 /* merge config */
3329 for (j = 0; j < dc->value->used; j++) {
3330 data_unset *du = dc->value->data[j];
3332 if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.server"))) {
3333 PATCH(exts);
3334 PATCH(exts_auth);
3335 PATCH(exts_resp);
3336 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.debug"))) {
3337 PATCH(debug);
3338 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.map-extensions"))) {
3339 PATCH(ext_mapping);
3344 return 0;
3346 #undef PATCH
3349 static handler_t fcgi_check_extension(server *srv, connection *con, void *p_d, int uri_path_handler) {
3350 plugin_data *p = p_d;
3351 size_t s_len;
3352 size_t k;
3353 buffer *fn;
3354 fcgi_extension *extension = NULL;
3355 fcgi_extension_host *host = NULL;
3356 handler_ctx *hctx;
3357 unsigned short fcgi_mode;
3359 if (con->mode != DIRECT) return HANDLER_GO_ON;
3361 fn = uri_path_handler ? con->uri.path : con->physical.path;
3363 if (buffer_string_is_empty(fn)) return HANDLER_GO_ON;
3365 s_len = buffer_string_length(fn);
3367 fcgi_patch_connection(srv, con, p);
3368 if (NULL == p->conf.exts) return HANDLER_GO_ON;
3370 /* check p->conf.exts_auth list and then p->conf.ext_resp list
3371 * (skip p->conf.exts_auth if array is empty or if FCGI_AUTHORIZER already ran in this request */
3372 hctx = con->plugin_ctx[p->id]; /*(not NULL if FCGI_AUTHORIZER ran; hctx->ext-auth check is redundant)*/
3373 fcgi_mode = (NULL == hctx || NULL == hctx->ext_auth)
3374 ? 0 /* FCGI_AUTHORIZER p->conf.exts_auth will be searched next */
3375 : FCGI_AUTHORIZER; /* FCGI_RESPONDER p->conf.exts_resp will be searched next */
3377 do {
3379 fcgi_exts *exts;
3380 if (0 == fcgi_mode) {
3381 fcgi_mode = FCGI_AUTHORIZER;
3382 exts = p->conf.exts_auth;
3383 } else {
3384 fcgi_mode = FCGI_RESPONDER;
3385 exts = p->conf.exts_resp;
3388 if (0 == exts->used) continue;
3390 /* fastcgi.map-extensions maps extensions to existing fastcgi.server entries
3392 * fastcgi.map-extensions = ( ".php3" => ".php" )
3394 * fastcgi.server = ( ".php" => ... )
3396 * */
3398 /* check if extension-mapping matches */
3399 for (k = 0; k < p->conf.ext_mapping->used; k++) {
3400 data_string *ds = (data_string *)p->conf.ext_mapping->data[k];
3401 size_t ct_len; /* length of the config entry */
3403 if (buffer_is_empty(ds->key)) continue;
3405 ct_len = buffer_string_length(ds->key);
3407 if (s_len < ct_len) continue;
3409 /* found a mapping */
3410 if (0 == strncmp(fn->ptr + s_len - ct_len, ds->key->ptr, ct_len)) {
3411 /* check if we know the extension */
3413 /* we can reuse k here */
3414 for (k = 0; k < exts->used; k++) {
3415 extension = exts->exts[k];
3417 if (buffer_is_equal(ds->value, extension->key)) {
3418 break;
3422 if (k == exts->used) {
3423 /* found nothing */
3424 extension = NULL;
3426 break;
3430 if (extension == NULL) {
3431 size_t uri_path_len = buffer_string_length(con->uri.path);
3433 /* check if extension matches */
3434 for (k = 0; k < exts->used; k++) {
3435 size_t ct_len; /* length of the config entry */
3436 fcgi_extension *ext = exts->exts[k];
3438 if (buffer_is_empty(ext->key)) continue;
3440 ct_len = buffer_string_length(ext->key);
3442 /* check _url_ in the form "/fcgi_pattern" */
3443 if (ext->key->ptr[0] == '/') {
3444 if ((ct_len <= uri_path_len) &&
3445 (strncmp(con->uri.path->ptr, ext->key->ptr, ct_len) == 0)) {
3446 extension = ext;
3447 break;
3449 } else if ((ct_len <= s_len) && (0 == strncmp(fn->ptr + s_len - ct_len, ext->key->ptr, ct_len))) {
3450 /* check extension in the form ".fcg" */
3451 extension = ext;
3452 break;
3457 } while (NULL == extension && fcgi_mode != FCGI_RESPONDER);
3459 /* extension doesn't match */
3460 if (NULL == extension) {
3461 return HANDLER_GO_ON;
3464 /* check if we have at least one server for this extension up and running */
3465 for (k = 0; k < extension->used; k++) {
3466 fcgi_extension_host *h = extension->hosts[k];
3468 /* we should have at least one proc that can do something */
3469 if (h->active_procs == 0) {
3470 continue;
3473 /* we found one host that is alive */
3474 host = h;
3475 break;
3478 if (!host) {
3479 /* sorry, we don't have a server alive for this ext */
3480 con->http_status = 500;
3481 con->mode = DIRECT;
3483 /* only send the 'no handler' once */
3484 if (!extension->note_is_sent) {
3485 extension->note_is_sent = 1;
3487 log_error_write(srv, __FILE__, __LINE__, "sBSbsbs",
3488 "all handlers for", con->uri.path, "?", con->uri.query,
3489 "on", extension->key,
3490 "are down.");
3493 return HANDLER_FINISHED;
3496 /* a note about no handler is not sent yet */
3497 extension->note_is_sent = 0;
3500 * if check-local is disabled, use the uri.path handler
3504 /* init handler-context */
3505 if (uri_path_handler) {
3506 if (host->check_local != 0) {
3507 return HANDLER_GO_ON;
3508 } else {
3509 /* do not split path info for authorizer */
3510 if (fcgi_mode != FCGI_AUTHORIZER) {
3511 /* the prefix is the SCRIPT_NAME,
3512 * everything from start to the next slash
3513 * this is important for check-local = "disable"
3515 * if prefix = /admin.fcgi
3517 * /admin.fcgi/foo/bar
3519 * SCRIPT_NAME = /admin.fcgi
3520 * PATH_INFO = /foo/bar
3522 * if prefix = /fcgi-bin/
3524 * /fcgi-bin/foo/bar
3526 * SCRIPT_NAME = /fcgi-bin/foo
3527 * PATH_INFO = /bar
3529 * if prefix = /, and fix-root-path-name is enable
3531 * /fcgi-bin/foo/bar
3533 * SCRIPT_NAME = /fcgi-bin/foo
3534 * PATH_INFO = /bar
3537 char *pathinfo;
3539 /* the rewrite is only done for /prefix/? matches */
3540 if (host->fix_root_path_name && extension->key->ptr[0] == '/' && extension->key->ptr[1] == '\0') {
3541 buffer_copy_string(con->request.pathinfo, con->uri.path->ptr);
3542 buffer_string_set_length(con->uri.path, 0);
3543 } else if (extension->key->ptr[0] == '/' &&
3544 buffer_string_length(con->uri.path) > buffer_string_length(extension->key) &&
3545 NULL != (pathinfo = strchr(con->uri.path->ptr + buffer_string_length(extension->key), '/'))) {
3546 /* rewrite uri.path and pathinfo */
3548 buffer_copy_string(con->request.pathinfo, pathinfo);
3549 buffer_string_set_length(con->uri.path, buffer_string_length(con->uri.path) - buffer_string_length(con->request.pathinfo));
3555 if (!hctx) hctx = handler_ctx_init();
3557 hctx->remote_conn = con;
3558 hctx->plugin_data = p;
3559 hctx->proc = NULL;
3560 hctx->ext = extension;
3562 hctx->fcgi_mode = fcgi_mode;
3563 if (fcgi_mode == FCGI_AUTHORIZER) {
3564 hctx->ext_auth = hctx->ext;
3567 /*hctx->conf.exts = p->conf.exts;*/
3568 /*hctx->conf.exts_auth = p->conf.exts_auth;*/
3569 /*hctx->conf.exts_resp = p->conf.exts_resp;*/
3570 /*hctx->conf.ext_mapping = p->conf.ext_mapping;*/
3571 hctx->conf.debug = p->conf.debug;
3573 con->plugin_ctx[p->id] = hctx;
3575 con->mode = p->id;
3577 if (con->conf.log_request_handling) {
3578 log_error_write(srv, __FILE__, __LINE__, "s", "handling it in mod_fastcgi");
3581 return HANDLER_GO_ON;
3584 /* uri-path handler */
3585 static handler_t fcgi_check_extension_1(server *srv, connection *con, void *p_d) {
3586 return fcgi_check_extension(srv, con, p_d, 1);
3589 /* start request handler */
3590 static handler_t fcgi_check_extension_2(server *srv, connection *con, void *p_d) {
3591 return fcgi_check_extension(srv, con, p_d, 0);
3595 TRIGGER_FUNC(mod_fastcgi_handle_trigger) {
3596 plugin_data *p = p_d;
3597 size_t i, j, n;
3600 /* perhaps we should kill a connect attempt after 10-15 seconds
3602 * currently we wait for the TCP timeout which is 180 seconds on Linux
3608 /* check all children if they are still up */
3610 for (i = 0; i < srv->config_context->used; i++) {
3611 plugin_config *conf;
3612 fcgi_exts *exts;
3614 conf = p->config_storage[i];
3616 exts = conf->exts;
3617 if (NULL == exts) continue;
3619 for (j = 0; j < exts->used; j++) {
3620 fcgi_extension *ex;
3622 ex = exts->exts[j];
3624 for (n = 0; n < ex->used; n++) {
3626 fcgi_proc *proc;
3627 fcgi_extension_host *host;
3629 host = ex->hosts[n];
3631 fcgi_restart_dead_procs(srv, p, host);
3633 for (proc = host->unused_procs; proc; proc = proc->next) {
3634 int status;
3636 if (proc->pid == 0) continue;
3638 switch (waitpid(proc->pid, &status, WNOHANG)) {
3639 case 0:
3640 /* child still running after timeout, good */
3641 break;
3642 case -1:
3643 if (errno != EINTR) {
3644 /* no PID found ? should never happen */
3645 log_error_write(srv, __FILE__, __LINE__, "sddss",
3646 "pid ", proc->pid, proc->state,
3647 "not found:", strerror(errno));
3649 #if 0
3650 if (errno == ECHILD) {
3651 /* someone else has cleaned up for us */
3652 proc->pid = 0;
3653 proc->state = PROC_STATE_UNSET;
3655 #endif
3657 break;
3658 default:
3659 /* the child should not terminate at all */
3660 if (WIFEXITED(status)) {
3661 if (proc->state != PROC_STATE_KILLED) {
3662 log_error_write(srv, __FILE__, __LINE__, "sdb",
3663 "child exited:",
3664 WEXITSTATUS(status), proc->connection_name);
3666 } else if (WIFSIGNALED(status)) {
3667 if (WTERMSIG(status) != SIGTERM) {
3668 log_error_write(srv, __FILE__, __LINE__, "sd",
3669 "child signaled:",
3670 WTERMSIG(status));
3672 } else {
3673 log_error_write(srv, __FILE__, __LINE__, "sd",
3674 "child died somehow:",
3675 status);
3677 proc->pid = 0;
3678 if (proc->state == PROC_STATE_RUNNING) host->active_procs--;
3679 proc->state = PROC_STATE_UNSET;
3680 host->max_id--;
3687 return HANDLER_GO_ON;
3691 int mod_fastcgi_plugin_init(plugin *p);
3692 int mod_fastcgi_plugin_init(plugin *p) {
3693 p->version = LIGHTTPD_VERSION_ID;
3694 p->name = buffer_init_string("fastcgi");
3696 p->init = mod_fastcgi_init;
3697 p->cleanup = mod_fastcgi_free;
3698 p->set_defaults = mod_fastcgi_set_defaults;
3699 p->connection_reset = fcgi_connection_reset;
3700 p->handle_connection_close = fcgi_connection_reset;
3701 p->handle_uri_clean = fcgi_check_extension_1;
3702 p->handle_subrequest_start = fcgi_check_extension_2;
3703 p->handle_subrequest = mod_fastcgi_handle_subrequest;
3704 p->handle_trigger = mod_fastcgi_handle_trigger;
3706 p->data = NULL;
3708 return 0;