skip spawning backends for preflight tests (#2642)
[lighttpd.git] / src / mod_fastcgi.c
blob26f6838598492c03f045b82498d68947acb85054
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 #ifdef HAVE_SYS_FILIO_H
43 # include <sys/filio.h>
44 #endif
46 #include "sys-socket.h"
48 #ifdef HAVE_SYS_UIO_H
49 #include <sys/uio.h>
50 #endif
51 #ifdef HAVE_SYS_WAIT_H
52 #include <sys/wait.h>
53 #endif
55 #include "version.h"
59 * TODO:
61 * - add timeout for a connect to a non-fastcgi process
62 * (use state_timestamp + state)
66 typedef struct fcgi_proc {
67 size_t id; /* id will be between 1 and max_procs */
68 buffer *unixsocket; /* config.socket + "-" + id */
69 unsigned port; /* config.port + pno */
71 buffer *connection_name; /* either tcp:<host>:<port> or unix:<socket> for debugging purposes */
73 pid_t pid; /* PID of the spawned process (0 if not spawned locally) */
76 size_t load; /* number of requests waiting on this process */
78 size_t requests; /* see max_requests */
79 struct fcgi_proc *prev, *next; /* see first */
81 time_t disabled_until; /* this proc is disabled until, use something else until then */
83 int is_local;
85 enum {
86 PROC_STATE_UNSET, /* init-phase */
87 PROC_STATE_RUNNING, /* alive */
88 PROC_STATE_OVERLOADED, /* listen-queue is full,
89 don't send anything to this proc for the next 2 seconds */
90 PROC_STATE_DIED_WAIT_FOR_PID, /* */
91 PROC_STATE_DIED, /* marked as dead, should be restarted */
92 PROC_STATE_KILLED /* was killed as we don't have the load anymore */
93 } state;
94 } fcgi_proc;
96 typedef struct {
97 /* the key that is used to reference this value */
98 buffer *id;
100 /* list of processes handling this extension
101 * sorted by lowest load
103 * whenever a job is done move it up in the list
104 * until it is sorted, move it down as soon as the
105 * job is started
107 fcgi_proc *first;
108 fcgi_proc *unused_procs;
111 * spawn at least min_procs, at max_procs.
113 * as soon as the load of the first entry
114 * is max_load_per_proc we spawn a new one
115 * and add it to the first entry and give it
116 * the load
120 unsigned short max_procs;
121 size_t num_procs; /* how many procs are started */
122 size_t active_procs; /* how many of them are really running, i.e. state = PROC_STATE_RUNNING */
125 * time after a disabled remote connection is tried to be re-enabled
130 unsigned short disable_time;
133 * some fastcgi processes get a little bit larger
134 * than wanted. max_requests_per_proc kills a
135 * process after a number of handled requests.
138 size_t max_requests_per_proc;
141 /* config */
144 * host:port
146 * if host is one of the local IP adresses the
147 * whole connection is local
149 * if port is not 0, and host is not specified,
150 * "localhost" (INADDR_LOOPBACK) is assumed.
153 buffer *host;
154 unsigned short port;
157 * Unix Domain Socket
159 * instead of TCP/IP we can use Unix Domain Sockets
160 * - more secure (you have fileperms to play with)
161 * - more control (on locally)
162 * - more speed (no extra overhead)
164 buffer *unixsocket;
166 /* if socket is local we can start the fastcgi
167 * process ourself
169 * bin-path is the path to the binary
171 * check min_procs and max_procs for the number
172 * of process to start up
174 buffer *bin_path;
176 /* bin-path is set bin-environment is taken to
177 * create the environement before starting the
178 * FastCGI process
181 array *bin_env;
183 array *bin_env_copy;
186 * docroot-translation between URL->phys and the
187 * remote host
189 * reasons:
190 * - different dir-layout if remote
191 * - chroot if local
194 buffer *docroot;
197 * fastcgi-mode:
198 * - responser
199 * - authorizer
202 unsigned short mode;
205 * check_local tells you if the phys file is stat()ed
206 * or not. FastCGI doesn't care if the service is
207 * remote. If the web-server side doesn't contain
208 * the fastcgi-files we should not stat() for them
209 * and say '404 not found'.
211 unsigned short check_local;
214 * append PATH_INFO to SCRIPT_FILENAME
216 * php needs this if cgi.fix_pathinfo is provided
220 unsigned short break_scriptfilename_for_php;
223 * workaround for program when prefix="/"
225 * rule to build PATH_INFO is hardcoded for when check_local is disabled
226 * enable this option to use the workaround
230 unsigned short fix_root_path_name;
233 * If the backend includes X-LIGHTTPD-send-file in the response
234 * we use the value as filename and ignore the content.
237 unsigned short allow_xsendfile;
239 ssize_t load; /* replace by host->load */
241 size_t max_id; /* corresponds most of the time to
242 num_procs.
244 only if a process is killed max_id waits for the process itself
245 to die and decrements it afterwards */
247 buffer *strip_request_uri;
249 unsigned short kill_signal; /* we need a setting for this as libfcgi
250 applications prefer SIGUSR1 while the
251 rest of the world would use SIGTERM
252 *sigh* */
253 } fcgi_extension_host;
256 * one extension can have multiple hosts assigned
257 * one host can spawn additional processes on the same
258 * socket (if we control it)
260 * ext -> host -> procs
261 * 1:n 1:n
263 * if the fastcgi process is remote that whole goes down
264 * to
266 * ext -> host -> procs
267 * 1:n 1:1
269 * in case of PHP and FCGI_CHILDREN we have again a procs
270 * but we don't control it directly.
274 typedef struct {
275 buffer *key; /* like .php */
277 int note_is_sent;
278 int last_used_ndx;
280 fcgi_extension_host **hosts;
282 size_t used;
283 size_t size;
284 } fcgi_extension;
286 typedef struct {
287 fcgi_extension **exts;
289 size_t used;
290 size_t size;
291 } fcgi_exts;
294 typedef struct {
295 fcgi_exts *exts;
297 array *ext_mapping;
299 unsigned int debug;
300 } plugin_config;
302 typedef struct {
303 char **ptr;
305 size_t size;
306 size_t used;
307 } char_array;
309 /* generic plugin data, shared between all connections */
310 typedef struct {
311 PLUGIN_DATA;
313 buffer *fcgi_env;
315 buffer *path;
317 buffer *statuskey;
319 plugin_config **config_storage;
321 plugin_config conf; /* this is only used as long as no handler_ctx is setup */
322 } plugin_data;
324 /* connection specific data */
325 typedef enum {
326 FCGI_STATE_UNSET,
327 FCGI_STATE_INIT,
328 FCGI_STATE_CONNECT_DELAYED,
329 FCGI_STATE_PREPARE_WRITE,
330 FCGI_STATE_WRITE,
331 FCGI_STATE_READ
332 } fcgi_connection_state_t;
334 typedef struct {
335 fcgi_proc *proc;
336 fcgi_extension_host *host;
337 fcgi_extension *ext;
339 fcgi_connection_state_t state;
340 time_t state_timestamp;
342 int reconnects; /* number of reconnect attempts */
344 chunkqueue *rb; /* read queue */
345 chunkqueue *wb; /* write queue */
347 buffer *response_header;
349 size_t request_id;
350 int fd; /* fd to the fastcgi process */
351 int fde_ndx; /* index into the fd-event buffer */
353 pid_t pid;
354 int got_proc;
356 int send_content_body;
358 plugin_config conf;
360 connection *remote_conn; /* dumb pointer */
361 plugin_data *plugin_data; /* dumb pointer */
362 } handler_ctx;
365 /* ok, we need a prototype */
366 static handler_t fcgi_handle_fdevent(server *srv, void *ctx, int revents);
368 static void reset_signals(void) {
369 #ifdef SIGTTOU
370 signal(SIGTTOU, SIG_DFL);
371 #endif
372 #ifdef SIGTTIN
373 signal(SIGTTIN, SIG_DFL);
374 #endif
375 #ifdef SIGTSTP
376 signal(SIGTSTP, SIG_DFL);
377 #endif
378 signal(SIGHUP, SIG_DFL);
379 signal(SIGPIPE, SIG_DFL);
380 signal(SIGUSR1, SIG_DFL);
383 static void fastcgi_status_copy_procname(buffer *b, fcgi_extension_host *host, fcgi_proc *proc) {
384 buffer_copy_string_len(b, CONST_STR_LEN("fastcgi.backend."));
385 buffer_append_string_buffer(b, host->id);
386 if (proc) {
387 buffer_append_string_len(b, CONST_STR_LEN("."));
388 buffer_append_int(b, proc->id);
392 static void fcgi_proc_load_inc(server *srv, handler_ctx *hctx) {
393 plugin_data *p = hctx->plugin_data;
394 hctx->proc->load++;
396 status_counter_inc(srv, CONST_STR_LEN("fastcgi.active-requests"));
398 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
399 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
401 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->proc->load);
404 static void fcgi_proc_load_dec(server *srv, handler_ctx *hctx) {
405 plugin_data *p = hctx->plugin_data;
406 hctx->proc->load--;
408 status_counter_dec(srv, CONST_STR_LEN("fastcgi.active-requests"));
410 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
411 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
413 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->proc->load);
416 static void fcgi_host_assign(server *srv, handler_ctx *hctx, fcgi_extension_host *host) {
417 plugin_data *p = hctx->plugin_data;
418 hctx->host = host;
419 hctx->host->load++;
421 fastcgi_status_copy_procname(p->statuskey, hctx->host, NULL);
422 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
424 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->host->load);
427 static void fcgi_host_reset(server *srv, handler_ctx *hctx) {
428 plugin_data *p = hctx->plugin_data;
429 hctx->host->load--;
431 fastcgi_status_copy_procname(p->statuskey, hctx->host, NULL);
432 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".load"));
434 status_counter_set(srv, CONST_BUF_LEN(p->statuskey), hctx->host->load);
436 hctx->host = NULL;
439 static void fcgi_host_disable(server *srv, handler_ctx *hctx) {
440 plugin_data *p = hctx->plugin_data;
442 if (hctx->host->disable_time || hctx->proc->is_local) {
443 if (hctx->proc->state == PROC_STATE_RUNNING) hctx->host->active_procs--;
444 hctx->proc->disabled_until = srv->cur_ts + hctx->host->disable_time;
445 hctx->proc->state = hctx->proc->is_local ? PROC_STATE_DIED_WAIT_FOR_PID : PROC_STATE_DIED;
447 if (p->conf.debug) {
448 log_error_write(srv, __FILE__, __LINE__, "sds",
449 "backend disabled for", hctx->host->disable_time, "seconds");
454 static int fastcgi_status_init(server *srv, buffer *b, fcgi_extension_host *host, fcgi_proc *proc) {
455 #define CLEAN(x) \
456 fastcgi_status_copy_procname(b, host, proc); \
457 buffer_append_string_len(b, CONST_STR_LEN(x)); \
458 status_counter_set(srv, CONST_BUF_LEN(b), 0);
460 CLEAN(".disabled");
461 CLEAN(".died");
462 CLEAN(".overloaded");
463 CLEAN(".connected");
464 CLEAN(".load");
466 #undef CLEAN
468 #define CLEAN(x) \
469 fastcgi_status_copy_procname(b, host, NULL); \
470 buffer_append_string_len(b, CONST_STR_LEN(x)); \
471 status_counter_set(srv, CONST_BUF_LEN(b), 0);
473 CLEAN(".load");
475 #undef CLEAN
477 return 0;
480 static handler_ctx * handler_ctx_init(void) {
481 handler_ctx * hctx;
483 hctx = calloc(1, sizeof(*hctx));
484 force_assert(hctx);
486 hctx->fde_ndx = -1;
488 hctx->response_header = buffer_init();
490 hctx->request_id = 0;
491 hctx->state = FCGI_STATE_INIT;
492 hctx->proc = NULL;
494 hctx->fd = -1;
496 hctx->reconnects = 0;
497 hctx->send_content_body = 1;
499 hctx->rb = chunkqueue_init();
500 hctx->wb = chunkqueue_init();
502 return hctx;
505 static void handler_ctx_free(server *srv, handler_ctx *hctx) {
506 if (hctx->host) {
507 fcgi_host_reset(srv, hctx);
510 buffer_free(hctx->response_header);
512 chunkqueue_free(hctx->rb);
513 chunkqueue_free(hctx->wb);
515 free(hctx);
518 static fcgi_proc *fastcgi_process_init(void) {
519 fcgi_proc *f;
521 f = calloc(1, sizeof(*f));
522 f->unixsocket = buffer_init();
523 f->connection_name = buffer_init();
525 f->prev = NULL;
526 f->next = NULL;
528 return f;
531 static void fastcgi_process_free(fcgi_proc *f) {
532 if (!f) return;
534 fastcgi_process_free(f->next);
536 buffer_free(f->unixsocket);
537 buffer_free(f->connection_name);
539 free(f);
542 static fcgi_extension_host *fastcgi_host_init(void) {
543 fcgi_extension_host *f;
545 f = calloc(1, sizeof(*f));
547 f->id = buffer_init();
548 f->host = buffer_init();
549 f->unixsocket = buffer_init();
550 f->docroot = buffer_init();
551 f->bin_path = buffer_init();
552 f->bin_env = array_init();
553 f->bin_env_copy = array_init();
554 f->strip_request_uri = buffer_init();
556 return f;
559 static void fastcgi_host_free(fcgi_extension_host *h) {
560 if (!h) return;
562 buffer_free(h->id);
563 buffer_free(h->host);
564 buffer_free(h->unixsocket);
565 buffer_free(h->docroot);
566 buffer_free(h->bin_path);
567 buffer_free(h->strip_request_uri);
568 array_free(h->bin_env);
569 array_free(h->bin_env_copy);
571 fastcgi_process_free(h->first);
572 fastcgi_process_free(h->unused_procs);
574 free(h);
578 static fcgi_exts *fastcgi_extensions_init(void) {
579 fcgi_exts *f;
581 f = calloc(1, sizeof(*f));
583 return f;
586 static void fastcgi_extensions_free(fcgi_exts *f) {
587 size_t i;
589 if (!f) return;
591 for (i = 0; i < f->used; i++) {
592 fcgi_extension *fe;
593 size_t j;
595 fe = f->exts[i];
597 for (j = 0; j < fe->used; j++) {
598 fcgi_extension_host *h;
600 h = fe->hosts[j];
602 fastcgi_host_free(h);
605 buffer_free(fe->key);
606 free(fe->hosts);
608 free(fe);
611 free(f->exts);
613 free(f);
616 static int fastcgi_extension_insert(fcgi_exts *ext, buffer *key, fcgi_extension_host *fh) {
617 fcgi_extension *fe;
618 size_t i;
620 /* there is something */
622 for (i = 0; i < ext->used; i++) {
623 if (buffer_is_equal(key, ext->exts[i]->key)) {
624 break;
628 if (i == ext->used) {
629 /* filextension is new */
630 fe = calloc(1, sizeof(*fe));
631 force_assert(fe);
632 fe->key = buffer_init();
633 fe->last_used_ndx = -1;
634 buffer_copy_buffer(fe->key, key);
636 /* */
638 if (ext->size == 0) {
639 ext->size = 8;
640 ext->exts = malloc(ext->size * sizeof(*(ext->exts)));
641 force_assert(ext->exts);
642 } else if (ext->used == ext->size) {
643 ext->size += 8;
644 ext->exts = realloc(ext->exts, ext->size * sizeof(*(ext->exts)));
645 force_assert(ext->exts);
647 ext->exts[ext->used++] = fe;
648 } else {
649 fe = ext->exts[i];
652 if (fe->size == 0) {
653 fe->size = 4;
654 fe->hosts = malloc(fe->size * sizeof(*(fe->hosts)));
655 force_assert(fe->hosts);
656 } else if (fe->size == fe->used) {
657 fe->size += 4;
658 fe->hosts = realloc(fe->hosts, fe->size * sizeof(*(fe->hosts)));
659 force_assert(fe->hosts);
662 fe->hosts[fe->used++] = fh;
664 return 0;
668 INIT_FUNC(mod_fastcgi_init) {
669 plugin_data *p;
671 p = calloc(1, sizeof(*p));
673 p->fcgi_env = buffer_init();
675 p->path = buffer_init();
677 p->statuskey = buffer_init();
679 return p;
683 FREE_FUNC(mod_fastcgi_free) {
684 plugin_data *p = p_d;
686 UNUSED(srv);
688 buffer_free(p->fcgi_env);
689 buffer_free(p->path);
690 buffer_free(p->statuskey);
692 if (p->config_storage) {
693 size_t i, j, n;
694 for (i = 0; i < srv->config_context->used; i++) {
695 plugin_config *s = p->config_storage[i];
696 fcgi_exts *exts;
698 if (NULL == s) continue;
700 exts = s->exts;
702 for (j = 0; j < exts->used; j++) {
703 fcgi_extension *ex;
705 ex = exts->exts[j];
707 for (n = 0; n < ex->used; n++) {
708 fcgi_proc *proc;
709 fcgi_extension_host *host;
711 host = ex->hosts[n];
713 for (proc = host->first; proc; proc = proc->next) {
714 if (proc->pid != 0) {
715 kill(proc->pid, host->kill_signal);
718 if (proc->is_local &&
719 !buffer_string_is_empty(proc->unixsocket)) {
720 unlink(proc->unixsocket->ptr);
724 for (proc = host->unused_procs; proc; proc = proc->next) {
725 if (proc->pid != 0) {
726 kill(proc->pid, host->kill_signal);
728 if (proc->is_local &&
729 !buffer_string_is_empty(proc->unixsocket)) {
730 unlink(proc->unixsocket->ptr);
736 fastcgi_extensions_free(s->exts);
737 array_free(s->ext_mapping);
739 free(s);
741 free(p->config_storage);
744 free(p);
746 return HANDLER_GO_ON;
749 static int env_add(char_array *env, const char *key, size_t key_len, const char *val, size_t val_len) {
750 char *dst;
751 size_t i;
753 if (!key || !val) return -1;
755 dst = malloc(key_len + val_len + 3);
756 memcpy(dst, key, key_len);
757 dst[key_len] = '=';
758 memcpy(dst + key_len + 1, val, val_len);
759 dst[key_len + 1 + val_len] = '\0';
761 for (i = 0; i < env->used; i++) {
762 if (0 == strncmp(dst, env->ptr[i], key_len + 1)) {
763 /* don't care about free as we are in a forked child which is going to exec(...) */
764 /* free(env->ptr[i]); */
765 env->ptr[i] = dst;
766 return 0;
770 if (env->size == 0) {
771 env->size = 16;
772 env->ptr = malloc(env->size * sizeof(*env->ptr));
773 } else if (env->size == env->used + 1) {
774 env->size += 16;
775 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
778 env->ptr[env->used++] = dst;
780 return 0;
783 static int parse_binpath(char_array *env, buffer *b) {
784 char *start;
785 size_t i;
786 /* search for spaces */
788 start = b->ptr;
789 for (i = 0; i < buffer_string_length(b); i++) {
790 switch(b->ptr[i]) {
791 case ' ':
792 case '\t':
793 /* a WS, stop here and copy the argument */
795 if (env->size == 0) {
796 env->size = 16;
797 env->ptr = malloc(env->size * sizeof(*env->ptr));
798 } else if (env->size == env->used) {
799 env->size += 16;
800 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
803 b->ptr[i] = '\0';
805 env->ptr[env->used++] = start;
807 start = b->ptr + i + 1;
808 break;
809 default:
810 break;
814 if (env->size == 0) {
815 env->size = 16;
816 env->ptr = malloc(env->size * sizeof(*env->ptr));
817 } else if (env->size == env->used) { /* we need one extra for the terminating NULL */
818 env->size += 16;
819 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
822 /* the rest */
823 env->ptr[env->used++] = start;
825 if (env->size == 0) {
826 env->size = 16;
827 env->ptr = malloc(env->size * sizeof(*env->ptr));
828 } else if (env->size == env->used) { /* we need one extra for the terminating NULL */
829 env->size += 16;
830 env->ptr = realloc(env->ptr, env->size * sizeof(*env->ptr));
833 /* terminate */
834 env->ptr[env->used++] = NULL;
836 return 0;
839 #if !defined(HAVE_FORK)
840 static int fcgi_spawn_connection(server *srv,
841 plugin_data *p,
842 fcgi_extension_host *host,
843 fcgi_proc *proc) {
844 UNUSED(srv);
845 UNUSED(p);
846 UNUSED(host);
847 UNUSED(proc);
848 return -1;
851 #else /* -> defined(HAVE_FORK) */
853 static int fcgi_spawn_connection(server *srv,
854 plugin_data *p,
855 fcgi_extension_host *host,
856 fcgi_proc *proc) {
857 int fcgi_fd;
858 int socket_type, status;
859 struct timeval tv = { 0, 100 * 1000 };
860 #ifdef HAVE_SYS_UN_H
861 struct sockaddr_un fcgi_addr_un;
862 #endif
863 struct sockaddr_in fcgi_addr_in;
864 struct sockaddr *fcgi_addr;
866 socklen_t servlen;
868 if (p->conf.debug) {
869 log_error_write(srv, __FILE__, __LINE__, "sdb",
870 "new proc, socket:", proc->port, proc->unixsocket);
873 if (!buffer_string_is_empty(proc->unixsocket)) {
874 #ifdef HAVE_SYS_UN_H
875 memset(&fcgi_addr_un, 0, sizeof(fcgi_addr_un));
876 fcgi_addr_un.sun_family = AF_UNIX;
877 if (buffer_string_length(proc->unixsocket) + 1 > sizeof(fcgi_addr_un.sun_path)) {
878 log_error_write(srv, __FILE__, __LINE__, "sB",
879 "ERROR: Unix Domain socket filename too long:",
880 proc->unixsocket);
881 return -1;
883 memcpy(fcgi_addr_un.sun_path, proc->unixsocket->ptr, buffer_string_length(proc->unixsocket) + 1);
885 #ifdef SUN_LEN
886 servlen = SUN_LEN(&fcgi_addr_un);
887 #else
888 /* stevens says: */
889 servlen = buffer_string_length(proc->unixsocket) + 1 + sizeof(fcgi_addr_un.sun_family);
890 #endif
891 socket_type = AF_UNIX;
892 fcgi_addr = (struct sockaddr *) &fcgi_addr_un;
894 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("unix:"));
895 buffer_append_string_buffer(proc->connection_name, proc->unixsocket);
897 #else
898 log_error_write(srv, __FILE__, __LINE__, "s",
899 "ERROR: Unix Domain sockets are not supported.");
900 return -1;
901 #endif
902 } else {
903 memset(&fcgi_addr_in, 0, sizeof(fcgi_addr_in));
904 fcgi_addr_in.sin_family = AF_INET;
906 if (buffer_string_is_empty(host->host)) {
907 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
908 } else {
909 struct hostent *he;
911 /* set a useful default */
912 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
915 if (NULL == (he = gethostbyname(host->host->ptr))) {
916 log_error_write(srv, __FILE__, __LINE__,
917 "sdb", "gethostbyname failed: ",
918 h_errno, host->host);
919 return -1;
922 if (he->h_addrtype != AF_INET) {
923 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-type != AF_INET: ", he->h_addrtype);
924 return -1;
927 if (he->h_length != sizeof(struct in_addr)) {
928 log_error_write(srv, __FILE__, __LINE__, "sd", "addr-length != sizeof(in_addr): ", he->h_length);
929 return -1;
932 memcpy(&(fcgi_addr_in.sin_addr.s_addr), he->h_addr_list[0], he->h_length);
935 fcgi_addr_in.sin_port = htons(proc->port);
936 servlen = sizeof(fcgi_addr_in);
938 socket_type = AF_INET;
939 fcgi_addr = (struct sockaddr *) &fcgi_addr_in;
941 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("tcp:"));
942 if (!buffer_string_is_empty(host->host)) {
943 buffer_append_string_buffer(proc->connection_name, host->host);
944 } else {
945 buffer_append_string_len(proc->connection_name, CONST_STR_LEN("localhost"));
947 buffer_append_string_len(proc->connection_name, CONST_STR_LEN(":"));
948 buffer_append_int(proc->connection_name, proc->port);
951 if (-1 == (fcgi_fd = socket(socket_type, SOCK_STREAM, 0))) {
952 log_error_write(srv, __FILE__, __LINE__, "ss",
953 "failed:", strerror(errno));
954 return -1;
957 if (-1 == connect(fcgi_fd, fcgi_addr, servlen)) {
958 /* server is not up, spawn it */
959 pid_t child;
960 int val;
962 if (errno != ENOENT &&
963 !buffer_string_is_empty(proc->unixsocket)) {
964 unlink(proc->unixsocket->ptr);
967 close(fcgi_fd);
969 /* reopen socket */
970 if (-1 == (fcgi_fd = socket(socket_type, SOCK_STREAM, 0))) {
971 log_error_write(srv, __FILE__, __LINE__, "ss",
972 "socket failed:", strerror(errno));
973 return -1;
976 val = 1;
977 if (setsockopt(fcgi_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) {
978 log_error_write(srv, __FILE__, __LINE__, "ss",
979 "socketsockopt failed:", strerror(errno));
980 close(fcgi_fd);
981 return -1;
984 /* create socket */
985 if (-1 == bind(fcgi_fd, fcgi_addr, servlen)) {
986 log_error_write(srv, __FILE__, __LINE__, "sbs",
987 "bind failed for:",
988 proc->connection_name,
989 strerror(errno));
990 close(fcgi_fd);
991 return -1;
994 if (-1 == listen(fcgi_fd, 1024)) {
995 log_error_write(srv, __FILE__, __LINE__, "ss",
996 "listen failed:", strerror(errno));
997 close(fcgi_fd);
998 return -1;
1001 switch ((child = fork())) {
1002 case 0: {
1003 size_t i = 0;
1004 char *c;
1005 char_array env;
1006 char_array arg;
1008 /* create environment */
1009 env.ptr = NULL;
1010 env.size = 0;
1011 env.used = 0;
1013 arg.ptr = NULL;
1014 arg.size = 0;
1015 arg.used = 0;
1017 if(fcgi_fd != FCGI_LISTENSOCK_FILENO) {
1018 close(FCGI_LISTENSOCK_FILENO);
1019 dup2(fcgi_fd, FCGI_LISTENSOCK_FILENO);
1020 close(fcgi_fd);
1023 /* we don't need the client socket */
1024 for (i = 3; i < 256; i++) {
1025 close(i);
1028 /* build clean environment */
1029 if (host->bin_env_copy->used) {
1030 for (i = 0; i < host->bin_env_copy->used; i++) {
1031 data_string *ds = (data_string *)host->bin_env_copy->data[i];
1032 char *ge;
1034 if (NULL != (ge = getenv(ds->value->ptr))) {
1035 env_add(&env, CONST_BUF_LEN(ds->value), ge, strlen(ge));
1038 } else {
1039 for (i = 0; environ[i]; i++) {
1040 char *eq;
1042 if (NULL != (eq = strchr(environ[i], '='))) {
1043 env_add(&env, environ[i], eq - environ[i], eq+1, strlen(eq+1));
1048 /* create environment */
1049 for (i = 0; i < host->bin_env->used; i++) {
1050 data_string *ds = (data_string *)host->bin_env->data[i];
1052 env_add(&env, CONST_BUF_LEN(ds->key), CONST_BUF_LEN(ds->value));
1055 for (i = 0; i < env.used; i++) {
1056 /* search for PHP_FCGI_CHILDREN */
1057 if (0 == strncmp(env.ptr[i], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
1060 /* not found, add a default */
1061 if (i == env.used) {
1062 env_add(&env, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
1065 env.ptr[env.used] = NULL;
1067 parse_binpath(&arg, host->bin_path);
1069 /* chdir into the base of the bin-path,
1070 * search for the last / */
1071 if (NULL != (c = strrchr(arg.ptr[0], '/'))) {
1072 *c = '\0';
1074 /* change to the physical directory */
1075 if (-1 == chdir(arg.ptr[0])) {
1076 *c = '/';
1077 log_error_write(srv, __FILE__, __LINE__, "sss", "chdir failed:", strerror(errno), arg.ptr[0]);
1079 *c = '/';
1082 reset_signals();
1084 /* exec the cgi */
1085 execve(arg.ptr[0], arg.ptr, env.ptr);
1087 /* log_error_write(srv, __FILE__, __LINE__, "sbs",
1088 "execve failed for:", host->bin_path, strerror(errno)); */
1090 exit(errno);
1092 break;
1094 case -1:
1095 /* error */
1096 close(fcgi_fd);
1097 break;
1098 default:
1099 /* father */
1100 close(fcgi_fd);
1102 /* wait */
1103 select(0, NULL, NULL, NULL, &tv);
1105 switch (waitpid(child, &status, WNOHANG)) {
1106 case 0:
1107 /* child still running after timeout, good */
1108 break;
1109 case -1:
1110 /* no PID found ? should never happen */
1111 log_error_write(srv, __FILE__, __LINE__, "ss",
1112 "pid not found:", strerror(errno));
1113 return -1;
1114 default:
1115 log_error_write(srv, __FILE__, __LINE__, "sbs",
1116 "the fastcgi-backend", host->bin_path, "failed to start:");
1117 /* the child should not terminate at all */
1118 if (WIFEXITED(status)) {
1119 log_error_write(srv, __FILE__, __LINE__, "sdb",
1120 "child exited with status",
1121 WEXITSTATUS(status), host->bin_path);
1122 log_error_write(srv, __FILE__, __LINE__, "s",
1123 "If you're trying to run your app as a FastCGI backend, make sure you're using the FastCGI-enabled version.\n"
1124 "If this is PHP on Gentoo, add 'fastcgi' to the USE flags.");
1125 } else if (WIFSIGNALED(status)) {
1126 log_error_write(srv, __FILE__, __LINE__, "sd",
1127 "terminated by signal:",
1128 WTERMSIG(status));
1130 if (WTERMSIG(status) == 11) {
1131 log_error_write(srv, __FILE__, __LINE__, "s",
1132 "to be exact: it segfaulted, crashed, died, ... you get the idea." );
1133 log_error_write(srv, __FILE__, __LINE__, "s",
1134 "If this is PHP, try removing the bytecode caches for now and try again.");
1136 } else {
1137 log_error_write(srv, __FILE__, __LINE__, "sd",
1138 "child died somehow:",
1139 status);
1141 return -1;
1144 /* register process */
1145 proc->pid = child;
1146 proc->is_local = 1;
1148 break;
1150 } else {
1151 close(fcgi_fd);
1152 proc->is_local = 0;
1153 proc->pid = 0;
1155 if (p->conf.debug) {
1156 log_error_write(srv, __FILE__, __LINE__, "sb",
1157 "(debug) socket is already used; won't spawn:",
1158 proc->connection_name);
1162 proc->state = PROC_STATE_RUNNING;
1163 host->active_procs++;
1165 return 0;
1168 #endif /* HAVE_FORK */
1170 static int unixsocket_is_dup(plugin_data *p, size_t used, buffer *unixsocket) {
1171 size_t i, j, n;
1172 for (i = 0; i < used; ++i) {
1173 fcgi_exts *exts = p->config_storage[i]->exts;
1174 for (j = 0; j < exts->used; ++j) {
1175 fcgi_extension *ex = exts->exts[j];
1176 for (n = 0; n < ex->used; ++n) {
1177 fcgi_extension_host *host = ex->hosts[n];
1178 if (!buffer_string_is_empty(host->unixsocket)
1179 && buffer_is_equal(host->unixsocket, unixsocket))
1180 return 1;
1185 return 0;
1188 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults) {
1189 plugin_data *p = p_d;
1190 data_unset *du;
1191 size_t i = 0;
1192 buffer *fcgi_mode = buffer_init();
1193 fcgi_extension_host *host = NULL;
1195 config_values_t cv[] = {
1196 { "fastcgi.server", NULL, T_CONFIG_LOCAL, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1197 { "fastcgi.debug", NULL, T_CONFIG_INT , T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1198 { "fastcgi.map-extensions", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1199 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1202 p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *));
1204 for (i = 0; i < srv->config_context->used; i++) {
1205 data_config const* config = (data_config const*)srv->config_context->data[i];
1206 plugin_config *s;
1208 s = malloc(sizeof(plugin_config));
1209 s->exts = fastcgi_extensions_init();
1210 s->debug = 0;
1211 s->ext_mapping = array_init();
1213 cv[0].destination = s->exts;
1214 cv[1].destination = &(s->debug);
1215 cv[2].destination = s->ext_mapping;
1217 p->config_storage[i] = s;
1219 if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) {
1220 goto error;
1224 * <key> = ( ... )
1227 if (NULL != (du = array_get_element(config->value, "fastcgi.server"))) {
1228 size_t j;
1229 data_array *da = (data_array *)du;
1231 if (du->type != TYPE_ARRAY) {
1232 log_error_write(srv, __FILE__, __LINE__, "sss",
1233 "unexpected type for key: ", "fastcgi.server", "array of strings");
1235 goto error;
1240 * fastcgi.server = ( "<ext>" => ( ... ),
1241 * "<ext>" => ( ... ) )
1244 for (j = 0; j < da->value->used; j++) {
1245 size_t n;
1246 data_array *da_ext = (data_array *)da->value->data[j];
1248 if (da->value->data[j]->type != TYPE_ARRAY) {
1249 log_error_write(srv, __FILE__, __LINE__, "sssbs",
1250 "unexpected type for key: ", "fastcgi.server",
1251 "[", da->value->data[j]->key, "](string)");
1253 goto error;
1257 * da_ext->key == name of the extension
1261 * fastcgi.server = ( "<ext>" =>
1262 * ( "<host>" => ( ... ),
1263 * "<host>" => ( ... )
1264 * ),
1265 * "<ext>" => ... )
1268 for (n = 0; n < da_ext->value->used; n++) {
1269 data_array *da_host = (data_array *)da_ext->value->data[n];
1271 config_values_t fcv[] = {
1272 { "host", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 0 */
1273 { "docroot", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 1 */
1274 { "mode", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 2 */
1275 { "socket", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 3 */
1276 { "bin-path", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 4 */
1278 { "check-local", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 5 */
1279 { "port", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 6 */
1280 { "max-procs", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 7 */
1281 { "disable-time", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 8 */
1283 { "bin-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 9 */
1284 { "bin-copy-environment", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, /* 10 */
1286 { "broken-scriptfilename", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 11 */
1287 { "allow-x-send-file", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 12 */
1288 { "strip-request-uri", NULL, T_CONFIG_STRING, T_CONFIG_SCOPE_CONNECTION }, /* 13 */
1289 { "kill-signal", NULL, T_CONFIG_SHORT, T_CONFIG_SCOPE_CONNECTION }, /* 14 */
1290 { "fix-root-scriptname", NULL, T_CONFIG_BOOLEAN, T_CONFIG_SCOPE_CONNECTION }, /* 15 */
1292 { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET }
1295 if (da_host->type != TYPE_ARRAY) {
1296 log_error_write(srv, __FILE__, __LINE__, "ssSBS",
1297 "unexpected type for key:",
1298 "fastcgi.server",
1299 "[", da_host->key, "](string)");
1301 goto error;
1304 host = fastcgi_host_init();
1305 buffer_reset(fcgi_mode);
1307 buffer_copy_buffer(host->id, da_host->key);
1309 host->check_local = 1;
1310 host->max_procs = 4;
1311 host->mode = FCGI_RESPONDER;
1312 host->disable_time = 1;
1313 host->break_scriptfilename_for_php = 0;
1314 host->allow_xsendfile = 0; /* handle X-LIGHTTPD-send-file */
1315 host->kill_signal = SIGTERM;
1316 host->fix_root_path_name = 0;
1318 fcv[0].destination = host->host;
1319 fcv[1].destination = host->docroot;
1320 fcv[2].destination = fcgi_mode;
1321 fcv[3].destination = host->unixsocket;
1322 fcv[4].destination = host->bin_path;
1324 fcv[5].destination = &(host->check_local);
1325 fcv[6].destination = &(host->port);
1326 fcv[7].destination = &(host->max_procs);
1327 fcv[8].destination = &(host->disable_time);
1329 fcv[9].destination = host->bin_env;
1330 fcv[10].destination = host->bin_env_copy;
1331 fcv[11].destination = &(host->break_scriptfilename_for_php);
1332 fcv[12].destination = &(host->allow_xsendfile);
1333 fcv[13].destination = host->strip_request_uri;
1334 fcv[14].destination = &(host->kill_signal);
1335 fcv[15].destination = &(host->fix_root_path_name);
1337 if (0 != config_insert_values_internal(srv, da_host->value, fcv, T_CONFIG_SCOPE_CONNECTION)) {
1338 goto error;
1341 if ((!buffer_string_is_empty(host->host) || host->port) &&
1342 !buffer_string_is_empty(host->unixsocket)) {
1343 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1344 "either host/port or socket have to be set in:",
1345 da->key, "= (",
1346 da_ext->key, " => (",
1347 da_host->key, " ( ...");
1349 goto error;
1352 if (!buffer_string_is_empty(host->unixsocket)) {
1353 /* unix domain socket */
1354 struct sockaddr_un un;
1356 if (buffer_string_length(host->unixsocket) + 1 > sizeof(un.sun_path) - 2) {
1357 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1358 "unixsocket is too long in:",
1359 da->key, "= (",
1360 da_ext->key, " => (",
1361 da_host->key, " ( ...");
1363 goto error;
1366 if (!buffer_string_is_empty(host->bin_path)
1367 && unixsocket_is_dup(p, i+1, host->unixsocket)) {
1368 log_error_write(srv, __FILE__, __LINE__, "sb",
1369 "duplicate unixsocket path:",
1370 host->unixsocket);
1371 goto error;
1373 } else {
1374 /* tcp/ip */
1376 if (buffer_string_is_empty(host->host) &&
1377 buffer_string_is_empty(host->bin_path)) {
1378 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1379 "host or binpath have to be set in:",
1380 da->key, "= (",
1381 da_ext->key, " => (",
1382 da_host->key, " ( ...");
1384 goto error;
1385 } else if (host->port == 0) {
1386 log_error_write(srv, __FILE__, __LINE__, "sbsbsbs",
1387 "port has to be set in:",
1388 da->key, "= (",
1389 da_ext->key, " => (",
1390 da_host->key, " ( ...");
1392 goto error;
1396 if (!buffer_string_is_empty(host->bin_path)) {
1397 /* a local socket + self spawning */
1398 size_t pno;
1400 if (s->debug) {
1401 log_error_write(srv, __FILE__, __LINE__, "ssbsdsbsd",
1402 "--- fastcgi spawning local",
1403 "\n\tproc:", host->bin_path,
1404 "\n\tport:", host->port,
1405 "\n\tsocket", host->unixsocket,
1406 "\n\tmax-procs:", host->max_procs);
1409 for (pno = 0; pno < host->max_procs; pno++) {
1410 fcgi_proc *proc;
1412 proc = fastcgi_process_init();
1413 proc->id = host->num_procs++;
1414 host->max_id++;
1416 if (buffer_string_is_empty(host->unixsocket)) {
1417 proc->port = host->port + pno;
1418 } else {
1419 buffer_copy_buffer(proc->unixsocket, host->unixsocket);
1420 buffer_append_string_len(proc->unixsocket, CONST_STR_LEN("-"));
1421 buffer_append_int(proc->unixsocket, pno);
1424 if (s->debug) {
1425 log_error_write(srv, __FILE__, __LINE__, "ssdsbsdsd",
1426 "--- fastcgi spawning",
1427 "\n\tport:", host->port,
1428 "\n\tsocket", host->unixsocket,
1429 "\n\tcurrent:", pno, "/", host->max_procs);
1432 if (!srv->srvconf.preflight_check
1433 && fcgi_spawn_connection(srv, p, host, proc)) {
1434 log_error_write(srv, __FILE__, __LINE__, "s",
1435 "[ERROR]: spawning fcgi failed.");
1436 fastcgi_process_free(proc);
1437 goto error;
1440 fastcgi_status_init(srv, p->statuskey, host, proc);
1442 proc->next = host->first;
1443 if (host->first) host->first->prev = proc;
1445 host->first = proc;
1447 } else {
1448 fcgi_proc *proc;
1450 proc = fastcgi_process_init();
1451 proc->id = host->num_procs++;
1452 host->max_id++;
1453 host->active_procs++;
1454 proc->state = PROC_STATE_RUNNING;
1456 if (buffer_string_is_empty(host->unixsocket)) {
1457 proc->port = host->port;
1458 } else {
1459 buffer_copy_buffer(proc->unixsocket, host->unixsocket);
1462 fastcgi_status_init(srv, p->statuskey, host, proc);
1464 host->first = proc;
1466 host->max_procs = 1;
1469 if (!buffer_string_is_empty(fcgi_mode)) {
1470 if (strcmp(fcgi_mode->ptr, "responder") == 0) {
1471 host->mode = FCGI_RESPONDER;
1472 } else if (strcmp(fcgi_mode->ptr, "authorizer") == 0) {
1473 host->mode = FCGI_AUTHORIZER;
1474 if (buffer_string_is_empty(host->docroot)) {
1475 log_error_write(srv, __FILE__, __LINE__, "s",
1476 "ERROR: docroot is required for authorizer mode.");
1477 goto error;
1479 } else {
1480 log_error_write(srv, __FILE__, __LINE__, "sbs",
1481 "WARNING: unknown fastcgi mode:",
1482 fcgi_mode, "(ignored, mode set to responder)");
1486 /* if extension already exists, take it */
1487 fastcgi_extension_insert(s->exts, da_ext->key, host);
1488 host = NULL;
1494 buffer_free(fcgi_mode);
1495 return HANDLER_GO_ON;
1497 error:
1498 if (NULL != host) fastcgi_host_free(host);
1499 buffer_free(fcgi_mode);
1500 return HANDLER_ERROR;
1503 static int fcgi_set_state(server *srv, handler_ctx *hctx, fcgi_connection_state_t state) {
1504 hctx->state = state;
1505 hctx->state_timestamp = srv->cur_ts;
1507 return 0;
1511 static void fcgi_connection_close(server *srv, handler_ctx *hctx) {
1512 plugin_data *p;
1513 connection *con;
1515 if (NULL == hctx) return;
1517 p = hctx->plugin_data;
1518 con = hctx->remote_conn;
1520 if (hctx->fd != -1) {
1521 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1522 fdevent_unregister(srv->ev, hctx->fd);
1523 close(hctx->fd);
1524 srv->cur_fds--;
1527 if (hctx->host && hctx->proc) {
1528 if (hctx->got_proc) {
1529 /* after the connect the process gets a load */
1530 fcgi_proc_load_dec(srv, hctx);
1532 if (p->conf.debug) {
1533 log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
1534 "released proc:",
1535 "pid:", hctx->proc->pid,
1536 "socket:", hctx->proc->connection_name,
1537 "load:", hctx->proc->load);
1543 handler_ctx_free(srv, hctx);
1544 con->plugin_ctx[p->id] = NULL;
1547 static int fcgi_reconnect(server *srv, handler_ctx *hctx) {
1548 plugin_data *p = hctx->plugin_data;
1550 /* child died
1552 * 1.
1554 * connect was ok, connection was accepted
1555 * but the php accept loop checks after the accept if it should die or not.
1557 * if yes we can only detect it at a write()
1559 * next step is resetting this attemp and setup a connection again
1561 * if we have more than 5 reconnects for the same request, die
1563 * 2.
1565 * we have a connection but the child died by some other reason
1569 if (hctx->fd != -1) {
1570 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
1571 fdevent_unregister(srv->ev, hctx->fd);
1572 close(hctx->fd);
1573 srv->cur_fds--;
1574 hctx->fd = -1;
1577 fcgi_set_state(srv, hctx, FCGI_STATE_INIT);
1579 hctx->request_id = 0;
1580 hctx->reconnects++;
1582 if (p->conf.debug > 2) {
1583 if (hctx->proc) {
1584 log_error_write(srv, __FILE__, __LINE__, "sdb",
1585 "release proc for reconnect:",
1586 hctx->proc->pid, hctx->proc->connection_name);
1587 } else {
1588 log_error_write(srv, __FILE__, __LINE__, "sb",
1589 "release proc for reconnect:",
1590 hctx->host->unixsocket);
1594 if (hctx->proc && hctx->got_proc) {
1595 fcgi_proc_load_dec(srv, hctx);
1598 /* perhaps another host gives us more luck */
1599 fcgi_host_reset(srv, hctx);
1601 return 0;
1605 static handler_t fcgi_connection_reset(server *srv, connection *con, void *p_d) {
1606 plugin_data *p = p_d;
1608 fcgi_connection_close(srv, con->plugin_ctx[p->id]);
1610 return HANDLER_GO_ON;
1614 static int fcgi_env_add(buffer *env, const char *key, size_t key_len, const char *val, size_t val_len) {
1615 size_t len;
1616 char len_enc[8];
1617 size_t len_enc_len = 0;
1619 if (!key || !val) return -1;
1621 len = key_len + val_len;
1623 len += key_len > 127 ? 4 : 1;
1624 len += val_len > 127 ? 4 : 1;
1626 if (buffer_string_length(env) + len >= FCGI_MAX_LENGTH) {
1628 * we can't append more headers, ignore it
1630 return -1;
1634 * field length can be 31bit max
1636 * HINT: this can't happen as FCGI_MAX_LENGTH is only 16bit
1638 force_assert(key_len < 0x7fffffffu);
1639 force_assert(val_len < 0x7fffffffu);
1641 buffer_string_prepare_append(env, len);
1643 if (key_len > 127) {
1644 len_enc[len_enc_len++] = ((key_len >> 24) & 0xff) | 0x80;
1645 len_enc[len_enc_len++] = (key_len >> 16) & 0xff;
1646 len_enc[len_enc_len++] = (key_len >> 8) & 0xff;
1647 len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1648 } else {
1649 len_enc[len_enc_len++] = (key_len >> 0) & 0xff;
1652 if (val_len > 127) {
1653 len_enc[len_enc_len++] = ((val_len >> 24) & 0xff) | 0x80;
1654 len_enc[len_enc_len++] = (val_len >> 16) & 0xff;
1655 len_enc[len_enc_len++] = (val_len >> 8) & 0xff;
1656 len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1657 } else {
1658 len_enc[len_enc_len++] = (val_len >> 0) & 0xff;
1661 buffer_append_string_len(env, len_enc, len_enc_len);
1662 buffer_append_string_len(env, key, key_len);
1663 buffer_append_string_len(env, val, val_len);
1665 return 0;
1668 static int fcgi_header(FCGI_Header * header, unsigned char type, size_t request_id, int contentLength, unsigned char paddingLength) {
1669 force_assert(contentLength <= FCGI_MAX_LENGTH);
1671 header->version = FCGI_VERSION_1;
1672 header->type = type;
1673 header->requestIdB0 = request_id & 0xff;
1674 header->requestIdB1 = (request_id >> 8) & 0xff;
1675 header->contentLengthB0 = contentLength & 0xff;
1676 header->contentLengthB1 = (contentLength >> 8) & 0xff;
1677 header->paddingLength = paddingLength;
1678 header->reserved = 0;
1680 return 0;
1683 typedef enum {
1684 CONNECTION_OK,
1685 CONNECTION_DELAYED, /* retry after event, take same host */
1686 CONNECTION_OVERLOADED, /* disable for 1 second, take another backend */
1687 CONNECTION_DEAD /* disable for 60 seconds, take another backend */
1688 } connection_result_t;
1690 static connection_result_t fcgi_establish_connection(server *srv, handler_ctx *hctx) {
1691 struct sockaddr *fcgi_addr;
1692 struct sockaddr_in fcgi_addr_in;
1693 #ifdef HAVE_SYS_UN_H
1694 struct sockaddr_un fcgi_addr_un;
1695 #endif
1696 socklen_t servlen;
1698 fcgi_extension_host *host = hctx->host;
1699 fcgi_proc *proc = hctx->proc;
1700 int fcgi_fd = hctx->fd;
1702 if (!buffer_string_is_empty(proc->unixsocket)) {
1703 #ifdef HAVE_SYS_UN_H
1704 /* use the unix domain socket */
1705 memset(&fcgi_addr_un, 0, sizeof(fcgi_addr_un));
1706 fcgi_addr_un.sun_family = AF_UNIX;
1707 if (buffer_string_length(proc->unixsocket) + 1 > sizeof(fcgi_addr_un.sun_path)) {
1708 log_error_write(srv, __FILE__, __LINE__, "sB",
1709 "ERROR: Unix Domain socket filename too long:",
1710 proc->unixsocket);
1711 return -1;
1713 memcpy(fcgi_addr_un.sun_path, proc->unixsocket->ptr, buffer_string_length(proc->unixsocket) + 1);
1715 #ifdef SUN_LEN
1716 servlen = SUN_LEN(&fcgi_addr_un);
1717 #else
1718 /* stevens says: */
1719 servlen = buffer_string_length(proc->unixsocket) + 1 + sizeof(fcgi_addr_un.sun_family);
1720 #endif
1721 fcgi_addr = (struct sockaddr *) &fcgi_addr_un;
1723 if (buffer_string_is_empty(proc->connection_name)) {
1724 /* on remote spawing we have to set the connection-name now */
1725 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("unix:"));
1726 buffer_append_string_buffer(proc->connection_name, proc->unixsocket);
1728 #else
1729 return CONNECTION_DEAD;
1730 #endif
1731 } else {
1732 memset(&fcgi_addr_in, 0, sizeof(fcgi_addr_in));
1733 fcgi_addr_in.sin_family = AF_INET;
1734 if (!buffer_string_is_empty(host->host)) {
1735 if (0 == inet_aton(host->host->ptr, &(fcgi_addr_in.sin_addr))) {
1736 log_error_write(srv, __FILE__, __LINE__, "sbs",
1737 "converting IP address failed for", host->host,
1738 "\nBe sure to specify an IP address here");
1740 return CONNECTION_DEAD;
1742 } else {
1743 fcgi_addr_in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1745 fcgi_addr_in.sin_port = htons(proc->port);
1746 servlen = sizeof(fcgi_addr_in);
1748 fcgi_addr = (struct sockaddr *) &fcgi_addr_in;
1750 if (buffer_string_is_empty(proc->connection_name)) {
1751 /* on remote spawing we have to set the connection-name now */
1752 buffer_copy_string_len(proc->connection_name, CONST_STR_LEN("tcp:"));
1753 if (!buffer_string_is_empty(host->host)) {
1754 buffer_append_string_buffer(proc->connection_name, host->host);
1755 } else {
1756 buffer_append_string_len(proc->connection_name, CONST_STR_LEN("localhost"));
1758 buffer_append_string_len(proc->connection_name, CONST_STR_LEN(":"));
1759 buffer_append_int(proc->connection_name, proc->port);
1763 if (-1 == connect(fcgi_fd, fcgi_addr, servlen)) {
1764 if (errno == EINPROGRESS ||
1765 errno == EALREADY ||
1766 errno == EINTR) {
1767 if (hctx->conf.debug > 2) {
1768 log_error_write(srv, __FILE__, __LINE__, "sb",
1769 "connect delayed; will continue later:", proc->connection_name);
1772 return CONNECTION_DELAYED;
1773 } else if (errno == EAGAIN) {
1774 if (hctx->conf.debug) {
1775 log_error_write(srv, __FILE__, __LINE__, "sbsd",
1776 "This means that you have more incoming requests than your FastCGI backend can handle in parallel."
1777 "It might help to spawn more FastCGI backends or PHP children; if not, decrease server.max-connections."
1778 "The load for this FastCGI backend", proc->connection_name, "is", proc->load);
1781 return CONNECTION_OVERLOADED;
1782 } else {
1783 log_error_write(srv, __FILE__, __LINE__, "sssb",
1784 "connect failed:",
1785 strerror(errno), "on",
1786 proc->connection_name);
1788 return CONNECTION_DEAD;
1792 hctx->reconnects = 0;
1793 if (hctx->conf.debug > 1) {
1794 log_error_write(srv, __FILE__, __LINE__, "sd",
1795 "connect succeeded: ", fcgi_fd);
1798 return CONNECTION_OK;
1801 #define FCGI_ENV_ADD_CHECK(ret, con) \
1802 if (ret == -1) { \
1803 con->http_status = 400; \
1804 con->file_finished = 1; \
1805 return -1; \
1807 static int fcgi_env_add_request_headers(server *srv, connection *con, plugin_data *p) {
1808 size_t i;
1810 for (i = 0; i < con->request.headers->used; i++) {
1811 data_string *ds;
1813 ds = (data_string *)con->request.headers->data[i];
1815 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1816 buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 1);
1818 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value)),con);
1822 for (i = 0; i < con->environment->used; i++) {
1823 data_string *ds;
1825 ds = (data_string *)con->environment->data[i];
1827 if (!buffer_is_empty(ds->value) && !buffer_is_empty(ds->key)) {
1828 buffer_copy_string_encoded_cgi_varnames(srv->tmp_buf, CONST_BUF_LEN(ds->key), 0);
1830 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_BUF_LEN(srv->tmp_buf), CONST_BUF_LEN(ds->value)), con);
1834 return 0;
1837 static int fcgi_create_env(server *srv, handler_ctx *hctx, size_t request_id) {
1838 FCGI_BeginRequestRecord beginRecord;
1839 FCGI_Header header;
1841 char buf[LI_ITOSTRING_LENGTH];
1842 const char *s;
1843 #ifdef HAVE_IPV6
1844 char b2[INET6_ADDRSTRLEN + 1];
1845 #endif
1847 plugin_data *p = hctx->plugin_data;
1848 fcgi_extension_host *host= hctx->host;
1850 connection *con = hctx->remote_conn;
1851 server_socket *srv_sock = con->srv_socket;
1853 sock_addr our_addr;
1854 socklen_t our_addr_len;
1856 /* send FCGI_BEGIN_REQUEST */
1858 fcgi_header(&(beginRecord.header), FCGI_BEGIN_REQUEST, request_id, sizeof(beginRecord.body), 0);
1859 beginRecord.body.roleB0 = host->mode;
1860 beginRecord.body.roleB1 = 0;
1861 beginRecord.body.flags = 0;
1862 memset(beginRecord.body.reserved, 0, sizeof(beginRecord.body.reserved));
1864 /* send FCGI_PARAMS */
1865 buffer_string_prepare_copy(p->fcgi_env, 1023);
1868 if (buffer_is_empty(con->conf.server_tag)) {
1869 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_DESC)),con)
1870 } else {
1871 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con->conf.server_tag)),con)
1874 if (!buffer_is_empty(con->server_name)) {
1875 size_t len = buffer_string_length(con->server_name);
1877 if (con->server_name->ptr[0] == '[') {
1878 const char *colon = strstr(con->server_name->ptr, "]:");
1879 if (colon) len = (colon + 1) - con->server_name->ptr;
1880 } else {
1881 const char *colon = strchr(con->server_name->ptr, ':');
1882 if (colon) len = colon - con->server_name->ptr;
1885 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_NAME"), con->server_name->ptr, len),con)
1886 } else {
1887 #ifdef HAVE_IPV6
1888 s = inet_ntop(srv_sock->addr.plain.sa_family,
1889 srv_sock->addr.plain.sa_family == AF_INET6 ?
1890 (const void *) &(srv_sock->addr.ipv6.sin6_addr) :
1891 (const void *) &(srv_sock->addr.ipv4.sin_addr),
1892 b2, sizeof(b2)-1);
1893 #else
1894 s = inet_ntoa(srv_sock->addr.ipv4.sin_addr);
1895 #endif
1896 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_NAME"), s, strlen(s)),con)
1899 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1")),con)
1901 li_utostrn(buf, sizeof(buf),
1902 #ifdef HAVE_IPV6
1903 ntohs(srv_sock->addr.plain.sa_family ? srv_sock->addr.ipv6.sin6_port : srv_sock->addr.ipv4.sin_port)
1904 #else
1905 ntohs(srv_sock->addr.ipv4.sin_port)
1906 #endif
1909 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_PORT"), buf, strlen(buf)),con)
1911 /* get the server-side of the connection to the client */
1912 our_addr_len = sizeof(our_addr);
1914 if (-1 == getsockname(con->fd, &(our_addr.plain), &our_addr_len)) {
1915 s = inet_ntop_cache_get_ip(srv, &(srv_sock->addr));
1916 } else {
1917 s = inet_ntop_cache_get_ip(srv, &(our_addr));
1919 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s)),con)
1921 li_utostrn(buf, sizeof(buf),
1922 #ifdef HAVE_IPV6
1923 ntohs(con->dst_addr.plain.sa_family ? con->dst_addr.ipv6.sin6_port : con->dst_addr.ipv4.sin_port)
1924 #else
1925 ntohs(con->dst_addr.ipv4.sin_port)
1926 #endif
1929 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REMOTE_PORT"), buf, strlen(buf)),con)
1931 s = inet_ntop_cache_get_ip(srv, &(con->dst_addr));
1932 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REMOTE_ADDR"), s, strlen(s)),con)
1934 if (con->request.content_length > 0 && host->mode != FCGI_AUTHORIZER) {
1935 /* CGI-SPEC 6.1.2 and FastCGI spec 6.3 */
1937 li_itostrn(buf, sizeof(buf), con->request.content_length);
1938 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("CONTENT_LENGTH"), buf, strlen(buf)),con)
1941 if (host->mode != FCGI_AUTHORIZER) {
1943 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1944 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1945 * (6.1.14, 6.1.6, 6.1.7)
1946 * For AUTHORIZER mode these headers should be omitted.
1949 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con->uri.path)),con)
1951 if (!buffer_string_is_empty(con->request.pathinfo)) {
1952 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con->request.pathinfo)),con)
1954 /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1956 if (!buffer_string_is_empty(host->docroot)) {
1957 buffer_copy_buffer(p->path, host->docroot);
1958 } else {
1959 buffer_copy_buffer(p->path, con->physical.basedir);
1961 buffer_append_string_buffer(p->path, con->request.pathinfo);
1962 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p->path)),con)
1963 } else {
1964 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN("")),con)
1969 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1970 * http://www.php.net/manual/en/reserved.variables.php
1971 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1972 * TODO: this code should be checked against cgi.fix_pathinfo php
1973 * parameter.
1976 if (!buffer_string_is_empty(host->docroot)) {
1978 * rewrite SCRIPT_FILENAME
1982 buffer_copy_buffer(p->path, host->docroot);
1983 buffer_append_string_buffer(p->path, con->uri.path);
1985 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path)),con)
1986 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host->docroot)),con)
1987 } else {
1988 buffer_copy_buffer(p->path, con->physical.path);
1990 /* cgi.fix_pathinfo need a broken SCRIPT_FILENAME to find out what PATH_INFO is itself
1992 * see src/sapi/cgi_main.c, init_request_info()
1994 if (host->break_scriptfilename_for_php) {
1995 buffer_append_string_buffer(p->path, con->request.pathinfo);
1998 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p->path)),con)
1999 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con->physical.basedir)),con)
2002 if (!buffer_string_is_empty(host->strip_request_uri)) {
2003 /* we need at least one char to strip off */
2005 * /app1/index/list
2007 * stripping /app1 or /app1/ should lead to
2009 * /index/list
2012 if ('/' != host->strip_request_uri->ptr[buffer_string_length(host->strip_request_uri) - 1]) {
2013 /* fix the user-input to have / as last char */
2014 buffer_append_string_len(host->strip_request_uri, CONST_STR_LEN("/"));
2017 if (buffer_string_length(con->request.orig_uri) >= buffer_string_length(host->strip_request_uri) &&
2018 0 == strncmp(con->request.orig_uri->ptr, host->strip_request_uri->ptr, buffer_string_length(host->strip_request_uri))) {
2019 /* the left is the same */
2021 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_URI"),
2022 con->request.orig_uri->ptr + (buffer_string_length(host->strip_request_uri) - 1),
2023 buffer_string_length(con->request.orig_uri) - (buffer_string_length(host->strip_request_uri) - 1)), con);
2024 } else {
2025 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri)),con)
2027 } else {
2028 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con->request.orig_uri)),con)
2030 if (!buffer_is_equal(con->request.uri, con->request.orig_uri)) {
2031 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con->request.uri)),con)
2033 if (!buffer_string_is_empty(con->uri.query)) {
2034 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con->uri.query)),con)
2035 } else {
2036 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN("")),con)
2039 s = get_http_method_name(con->request.http_method);
2040 force_assert(s);
2041 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s)),con)
2042 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")),con) /* if php is compiled with --force-redirect */
2043 s = get_http_version_name(con->request.http_version);
2044 force_assert(s);
2045 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s)),con)
2047 if (buffer_is_equal_caseless_string(con->uri.scheme, CONST_STR_LEN("https"))) {
2048 FCGI_ENV_ADD_CHECK(fcgi_env_add(p->fcgi_env, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on")),con)
2051 FCGI_ENV_ADD_CHECK(fcgi_env_add_request_headers(srv, con, p), con);
2054 buffer *b = buffer_init();
2056 buffer_copy_string_len(b, (const char *)&beginRecord, sizeof(beginRecord));
2058 fcgi_header(&(header), FCGI_PARAMS, request_id, buffer_string_length(p->fcgi_env), 0);
2059 buffer_append_string_len(b, (const char *)&header, sizeof(header));
2060 buffer_append_string_buffer(b, p->fcgi_env);
2062 fcgi_header(&(header), FCGI_PARAMS, request_id, 0, 0);
2063 buffer_append_string_len(b, (const char *)&header, sizeof(header));
2065 chunkqueue_append_buffer(hctx->wb, b);
2066 buffer_free(b);
2069 if (con->request.content_length) {
2070 chunkqueue *req_cq = con->request_content_queue;
2071 off_t offset;
2073 /* something to send ? */
2074 for (offset = 0; offset != req_cq->bytes_in; ) {
2075 off_t weWant = req_cq->bytes_in - offset > FCGI_MAX_LENGTH ? FCGI_MAX_LENGTH : req_cq->bytes_in - offset;
2077 /* we announce toWrite octets
2078 * now take all the request_content chunks that we need to fill this request
2079 * */
2081 fcgi_header(&(header), FCGI_STDIN, request_id, weWant, 0);
2082 chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
2084 if (p->conf.debug > 10) {
2085 log_error_write(srv, __FILE__, __LINE__, "soso", "tosend:", offset, "/", req_cq->bytes_in);
2088 chunkqueue_steal(hctx->wb, req_cq, weWant);
2090 offset += weWant;
2094 /* terminate STDIN */
2095 fcgi_header(&(header), FCGI_STDIN, request_id, 0, 0);
2096 chunkqueue_append_mem(hctx->wb, (const char *)&header, sizeof(header));
2098 return 0;
2101 static int fcgi_response_parse(server *srv, connection *con, plugin_data *p, buffer *in) {
2102 char *s, *ns;
2104 handler_ctx *hctx = con->plugin_ctx[p->id];
2105 fcgi_extension_host *host= hctx->host;
2106 int have_sendfile2 = 0;
2107 off_t sendfile2_content_length = 0;
2109 UNUSED(srv);
2111 /* search for \n */
2112 for (s = in->ptr; NULL != (ns = strchr(s, '\n')); s = ns + 1) {
2113 char *key, *value;
2114 int key_len;
2115 data_string *ds = NULL;
2117 /* a good day. Someone has read the specs and is sending a \r\n to us */
2119 if (ns > in->ptr &&
2120 *(ns-1) == '\r') {
2121 *(ns-1) = '\0';
2124 ns[0] = '\0';
2126 key = s;
2127 if (NULL == (value = strchr(s, ':'))) {
2128 /* we expect: "<key>: <value>\n" */
2129 continue;
2132 key_len = value - key;
2134 value++;
2135 /* strip WS */
2136 while (*value == ' ' || *value == '\t') value++;
2138 if (host->mode != FCGI_AUTHORIZER ||
2139 !(con->http_status == 0 ||
2140 con->http_status == 200)) {
2141 /* authorizers shouldn't affect the response headers sent back to the client */
2143 /* don't forward Status: */
2144 if (0 != strncasecmp(key, "Status", key_len)) {
2145 if (NULL == (ds = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2146 ds = data_response_init();
2148 buffer_copy_string_len(ds->key, key, key_len);
2149 buffer_copy_string(ds->value, value);
2151 array_insert_unique(con->response.headers, (data_unset *)ds);
2155 switch(key_len) {
2156 case 4:
2157 if (0 == strncasecmp(key, "Date", key_len)) {
2158 con->parsed_response |= HTTP_DATE;
2160 break;
2161 case 6:
2162 if (0 == strncasecmp(key, "Status", key_len)) {
2163 int status = strtol(value, NULL, 10);
2164 if (status >= 100 && status < 1000) {
2165 con->http_status = status;
2166 con->parsed_response |= HTTP_STATUS;
2167 } else {
2168 con->http_status = 502;
2171 break;
2172 case 8:
2173 if (0 == strncasecmp(key, "Location", key_len)) {
2174 con->parsed_response |= HTTP_LOCATION;
2176 break;
2177 case 10:
2178 if (0 == strncasecmp(key, "Connection", key_len)) {
2179 con->response.keep_alive = (0 == strcasecmp(value, "Keep-Alive")) ? 1 : 0;
2180 con->parsed_response |= HTTP_CONNECTION;
2182 break;
2183 case 11:
2184 if (host->allow_xsendfile && 0 == strncasecmp(key, "X-Sendfile2", key_len)&& hctx->send_content_body) {
2185 char *pos = value;
2186 have_sendfile2 = 1;
2188 while (*pos) {
2189 char *filename, *range;
2190 stat_cache_entry *sce;
2191 off_t begin_range, end_range, range_len;
2193 while (' ' == *pos) pos++;
2194 if (!*pos) break;
2196 filename = pos;
2197 if (NULL == (range = strchr(pos, ' '))) {
2198 /* missing range */
2199 if (p->conf.debug) {
2200 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't find range after filename:", filename);
2202 return 502;
2204 buffer_copy_string_len(srv->tmp_buf, filename, range - filename);
2206 /* find end of range */
2207 for (pos = ++range; *pos && *pos != ' ' && *pos != ','; pos++) ;
2209 buffer_urldecode_path(srv->tmp_buf);
2210 if (HANDLER_ERROR == stat_cache_get_entry(srv, con, srv->tmp_buf, &sce)) {
2211 if (p->conf.debug) {
2212 log_error_write(srv, __FILE__, __LINE__, "sb",
2213 "send-file error: couldn't get stat_cache entry for X-Sendfile2:",
2214 srv->tmp_buf);
2216 return 404;
2217 } else if (!S_ISREG(sce->st.st_mode)) {
2218 if (p->conf.debug) {
2219 log_error_write(srv, __FILE__, __LINE__, "sb",
2220 "send-file error: wrong filetype for X-Sendfile2:",
2221 srv->tmp_buf);
2223 return 502;
2225 /* found the file */
2227 /* parse range */
2228 begin_range = 0; end_range = sce->st.st_size - 1;
2230 char *rpos = NULL;
2231 errno = 0;
2232 begin_range = strtoll(range, &rpos, 10);
2233 if (errno != 0 || begin_range < 0 || rpos == range) goto range_failed;
2234 if ('-' != *rpos++) goto range_failed;
2235 if (rpos != pos) {
2236 range = rpos;
2237 end_range = strtoll(range, &rpos, 10);
2238 if (errno != 0 || end_range < 0 || rpos == range) goto range_failed;
2240 if (rpos != pos) goto range_failed;
2242 goto range_success;
2244 range_failed:
2245 if (p->conf.debug) {
2246 log_error_write(srv, __FILE__, __LINE__, "ss", "Couldn't decode range after filename:", filename);
2248 return 502;
2250 range_success: ;
2253 /* no parameters accepted */
2255 while (*pos == ' ') pos++;
2256 if (*pos != '\0' && *pos != ',') return 502;
2258 range_len = end_range - begin_range + 1;
2259 if (range_len < 0) return 502;
2260 if (range_len != 0) {
2261 http_chunk_append_file(srv, con, srv->tmp_buf, begin_range, range_len);
2263 sendfile2_content_length += range_len;
2265 if (*pos == ',') pos++;
2268 break;
2269 case 14:
2270 if (0 == strncasecmp(key, "Content-Length", key_len)) {
2271 con->response.content_length = strtoul(value, NULL, 10);
2272 con->parsed_response |= HTTP_CONTENT_LENGTH;
2274 if (con->response.content_length < 0) con->response.content_length = 0;
2276 break;
2277 default:
2278 break;
2282 if (have_sendfile2) {
2283 data_string *dcls;
2285 hctx->send_content_body = 0;
2286 joblist_append(srv, con);
2288 /* fix content-length */
2289 if (NULL == (dcls = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2290 dcls = data_response_init();
2293 buffer_copy_string_len(dcls->key, "Content-Length", sizeof("Content-Length")-1);
2294 buffer_copy_int(dcls->value, sendfile2_content_length);
2295 array_replace(con->response.headers, (data_unset *)dcls);
2297 con->parsed_response |= HTTP_CONTENT_LENGTH;
2298 con->response.content_length = sendfile2_content_length;
2301 /* CGI/1.1 rev 03 - 7.2.1.2 */
2302 if ((con->parsed_response & HTTP_LOCATION) &&
2303 !(con->parsed_response & HTTP_STATUS)) {
2304 con->http_status = 302;
2307 return 0;
2310 typedef struct {
2311 buffer *b;
2312 size_t len;
2313 int type;
2314 int padding;
2315 size_t request_id;
2316 } fastcgi_response_packet;
2318 static int fastcgi_get_packet(server *srv, handler_ctx *hctx, fastcgi_response_packet *packet) {
2319 chunk *c;
2320 size_t offset;
2321 size_t toread;
2322 FCGI_Header *header;
2324 if (!hctx->rb->first) return -1;
2326 packet->b = buffer_init();
2327 packet->len = 0;
2328 packet->type = 0;
2329 packet->padding = 0;
2330 packet->request_id = 0;
2332 offset = 0; toread = 8;
2333 /* get at least the FastCGI header */
2334 for (c = hctx->rb->first; c; c = c->next) {
2335 size_t weHave = buffer_string_length(c->mem) - c->offset;
2337 if (weHave > toread) weHave = toread;
2339 buffer_append_string_len(packet->b, c->mem->ptr + c->offset, weHave);
2340 toread -= weHave;
2341 offset = weHave; /* skip offset bytes in chunk for "real" data */
2343 if (0 == toread) break;
2346 if (buffer_string_length(packet->b) < sizeof(FCGI_Header)) {
2347 /* no header */
2348 if (hctx->plugin_data->conf.debug) {
2349 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");
2352 buffer_free(packet->b);
2354 return -1;
2357 /* we have at least a header, now check how much me have to fetch */
2358 header = (FCGI_Header *)(packet->b->ptr);
2360 packet->len = (header->contentLengthB0 | (header->contentLengthB1 << 8)) + header->paddingLength;
2361 packet->request_id = (header->requestIdB0 | (header->requestIdB1 << 8));
2362 packet->type = header->type;
2363 packet->padding = header->paddingLength;
2365 /* ->b should only be the content */
2366 buffer_string_set_length(packet->b, 0);
2368 if (packet->len) {
2369 /* copy the content */
2370 for (; c && (buffer_string_length(packet->b) < packet->len); c = c->next) {
2371 size_t weWant = packet->len - buffer_string_length(packet->b);
2372 size_t weHave = buffer_string_length(c->mem) - c->offset - offset;
2374 if (weHave > weWant) weHave = weWant;
2376 buffer_append_string_len(packet->b, c->mem->ptr + c->offset + offset, weHave);
2378 /* we only skipped the first bytes as they belonged to the fcgi header */
2379 offset = 0;
2382 if (buffer_string_length(packet->b) < packet->len) {
2383 /* we didn't get the full packet */
2385 buffer_free(packet->b);
2386 return -1;
2389 buffer_string_set_length(packet->b, buffer_string_length(packet->b) - packet->padding);
2392 chunkqueue_mark_written(hctx->rb, packet->len + sizeof(FCGI_Header));
2394 return 0;
2397 static int fcgi_demux_response(server *srv, handler_ctx *hctx) {
2398 int fin = 0;
2399 int toread, ret;
2400 ssize_t r;
2402 plugin_data *p = hctx->plugin_data;
2403 connection *con = hctx->remote_conn;
2404 int fcgi_fd = hctx->fd;
2405 fcgi_extension_host *host= hctx->host;
2406 fcgi_proc *proc = hctx->proc;
2409 * check how much we have to read
2411 if (ioctl(hctx->fd, FIONREAD, &toread)) {
2412 if (errno == EAGAIN) return 0;
2413 log_error_write(srv, __FILE__, __LINE__, "sd",
2414 "unexpected end-of-file (perhaps the fastcgi process died):",
2415 fcgi_fd);
2416 return -1;
2419 if (toread > 0) {
2420 char *mem;
2421 size_t mem_len;
2423 chunkqueue_get_memory(hctx->rb, &mem, &mem_len, 0, toread);
2424 r = read(hctx->fd, mem, mem_len);
2425 chunkqueue_use_memory(hctx->rb, r > 0 ? r : 0);
2427 if (-1 == r) {
2428 if (errno == EAGAIN) return 0;
2429 log_error_write(srv, __FILE__, __LINE__, "sds",
2430 "unexpected end-of-file (perhaps the fastcgi process died):",
2431 fcgi_fd, strerror(errno));
2432 return -1;
2434 } else {
2435 log_error_write(srv, __FILE__, __LINE__, "ssdsb",
2436 "unexpected end-of-file (perhaps the fastcgi process died):",
2437 "pid:", proc->pid,
2438 "socket:", proc->connection_name);
2440 return -1;
2444 * parse the fastcgi packets and forward the content to the write-queue
2447 while (fin == 0) {
2448 fastcgi_response_packet packet;
2450 /* check if we have at least one packet */
2451 if (0 != fastcgi_get_packet(srv, hctx, &packet)) {
2452 /* no full packet */
2453 break;
2456 switch(packet.type) {
2457 case FCGI_STDOUT:
2458 if (packet.len == 0) break;
2460 /* is the header already finished */
2461 if (0 == con->file_started) {
2462 char *c;
2463 data_string *ds;
2465 /* search for header terminator
2467 * if we start with \r\n check if last packet terminated with \r\n
2468 * if we start with \n check if last packet terminated with \n
2469 * search for \r\n\r\n
2470 * search for \n\n
2473 buffer_append_string_buffer(hctx->response_header, packet.b);
2475 if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\r\n\r\n")))) {
2476 char *hend = c + 4; /* header end == body start */
2477 size_t hlen = hend - hctx->response_header->ptr;
2478 buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2479 buffer_string_set_length(hctx->response_header, hlen);
2480 } else if (NULL != (c = buffer_search_string_len(hctx->response_header, CONST_STR_LEN("\n\n")))) {
2481 char *hend = c + 2; /* header end == body start */
2482 size_t hlen = hend - hctx->response_header->ptr;
2483 buffer_copy_string_len(packet.b, hend, buffer_string_length(hctx->response_header) - hlen);
2484 buffer_string_set_length(hctx->response_header, hlen);
2485 } else {
2486 /* no luck, no header found */
2487 break;
2490 /* parse the response header */
2491 if ((ret = fcgi_response_parse(srv, con, p, hctx->response_header))) {
2492 con->http_status = ret;
2493 hctx->send_content_body = 0;
2494 con->file_started = 1;
2495 break;
2498 con->file_started = 1;
2500 if (host->mode == FCGI_AUTHORIZER &&
2501 (con->http_status == 0 ||
2502 con->http_status == 200)) {
2503 /* a authorizer with approved the static request, ignore the content here */
2504 hctx->send_content_body = 0;
2507 if (host->allow_xsendfile && hctx->send_content_body &&
2508 (NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-LIGHTTPD-send-file"))
2509 || NULL != (ds = (data_string *) array_get_element(con->response.headers, "X-Sendfile")))) {
2510 stat_cache_entry *sce;
2512 if (HANDLER_ERROR != stat_cache_get_entry(srv, con, ds->value, &sce)) {
2513 data_string *dcls;
2514 if (NULL == (dcls = (data_string *)array_get_unused_element(con->response.headers, TYPE_STRING))) {
2515 dcls = data_response_init();
2517 /* found */
2518 http_chunk_append_file(srv, con, ds->value, 0, sce->st.st_size);
2519 hctx->send_content_body = 0; /* ignore the content */
2520 joblist_append(srv, con);
2522 buffer_copy_string_len(dcls->key, "Content-Length", sizeof("Content-Length")-1);
2523 buffer_copy_int(dcls->value, sce->st.st_size);
2524 array_replace(con->response.headers, (data_unset *)dcls);
2526 con->parsed_response |= HTTP_CONTENT_LENGTH;
2527 con->response.content_length = sce->st.st_size;
2528 } else {
2529 log_error_write(srv, __FILE__, __LINE__, "sb",
2530 "send-file error: couldn't get stat_cache entry for:",
2531 ds->value);
2532 con->http_status = 404;
2533 hctx->send_content_body = 0;
2534 con->file_started = 1;
2535 break;
2540 if (hctx->send_content_body && buffer_string_length(packet.b) > 0) {
2541 /* enable chunked-transfer-encoding */
2542 if (con->request.http_version == HTTP_VERSION_1_1 &&
2543 !(con->parsed_response & HTTP_CONTENT_LENGTH)) {
2544 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
2547 http_chunk_append_buffer(srv, con, packet.b);
2548 joblist_append(srv, con);
2550 } else if (hctx->send_content_body && !buffer_string_is_empty(packet.b)) {
2551 if (con->request.http_version == HTTP_VERSION_1_1 &&
2552 !(con->parsed_response & HTTP_CONTENT_LENGTH)) {
2553 /* enable chunked-transfer-encoding */
2554 con->response.transfer_encoding = HTTP_TRANSFER_ENCODING_CHUNKED;
2557 http_chunk_append_buffer(srv, con, packet.b);
2558 joblist_append(srv, con);
2560 break;
2561 case FCGI_STDERR:
2562 if (packet.len == 0) break;
2564 log_error_write_multiline_buffer(srv, __FILE__, __LINE__, packet.b, "s",
2565 "FastCGI-stderr:");
2567 break;
2568 case FCGI_END_REQUEST:
2569 con->file_finished = 1;
2571 if (host->mode != FCGI_AUTHORIZER ||
2572 !(con->http_status == 0 ||
2573 con->http_status == 200)) {
2574 /* send chunk-end if necessary */
2575 http_chunk_close(srv, con);
2576 joblist_append(srv, con);
2579 fin = 1;
2580 break;
2581 default:
2582 log_error_write(srv, __FILE__, __LINE__, "sd",
2583 "FastCGI: header.type not handled: ", packet.type);
2584 break;
2586 buffer_free(packet.b);
2589 return fin;
2592 static int fcgi_restart_dead_procs(server *srv, plugin_data *p, fcgi_extension_host *host) {
2593 fcgi_proc *proc;
2595 for (proc = host->first; proc; proc = proc->next) {
2596 int status;
2598 if (p->conf.debug > 2) {
2599 log_error_write(srv, __FILE__, __LINE__, "sbdddd",
2600 "proc:",
2601 proc->connection_name,
2602 proc->state,
2603 proc->is_local,
2604 proc->load,
2605 proc->pid);
2609 * if the remote side is overloaded, we check back after <n> seconds
2612 switch (proc->state) {
2613 case PROC_STATE_KILLED:
2614 case PROC_STATE_UNSET:
2615 /* this should never happen as long as adaptive spawing is disabled */
2616 force_assert(0);
2618 break;
2619 case PROC_STATE_RUNNING:
2620 break;
2621 case PROC_STATE_OVERLOADED:
2622 if (srv->cur_ts <= proc->disabled_until) break;
2624 proc->state = PROC_STATE_RUNNING;
2625 host->active_procs++;
2627 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2628 "fcgi-server re-enabled:",
2629 host->host, host->port,
2630 host->unixsocket);
2631 break;
2632 case PROC_STATE_DIED_WAIT_FOR_PID:
2633 /* non-local procs don't have PIDs to wait for */
2634 if (!proc->is_local) {
2635 proc->state = PROC_STATE_DIED;
2636 } else {
2637 /* the child should not terminate at all */
2639 for ( ;; ) {
2640 switch(waitpid(proc->pid, &status, WNOHANG)) {
2641 case 0:
2642 /* child is still alive */
2643 if (srv->cur_ts <= proc->disabled_until) break;
2645 proc->state = PROC_STATE_RUNNING;
2646 host->active_procs++;
2648 log_error_write(srv, __FILE__, __LINE__, "sbdb",
2649 "fcgi-server re-enabled:",
2650 host->host, host->port,
2651 host->unixsocket);
2652 break;
2653 case -1:
2654 if (errno == EINTR) continue;
2656 log_error_write(srv, __FILE__, __LINE__, "sd",
2657 "child died somehow, waitpid failed:",
2658 errno);
2659 proc->state = PROC_STATE_DIED;
2660 break;
2661 default:
2662 if (WIFEXITED(status)) {
2663 #if 0
2664 log_error_write(srv, __FILE__, __LINE__, "sdsd",
2665 "child exited, pid:", proc->pid,
2666 "status:", WEXITSTATUS(status));
2667 #endif
2668 } else if (WIFSIGNALED(status)) {
2669 log_error_write(srv, __FILE__, __LINE__, "sd",
2670 "child signaled:",
2671 WTERMSIG(status));
2672 } else {
2673 log_error_write(srv, __FILE__, __LINE__, "sd",
2674 "child died somehow:",
2675 status);
2678 proc->state = PROC_STATE_DIED;
2679 break;
2681 break;
2685 /* fall through if we have a dead proc now */
2686 if (proc->state != PROC_STATE_DIED) break;
2688 case PROC_STATE_DIED:
2689 /* local procs get restarted by us,
2690 * remote ones hopefully by the admin */
2692 if (!buffer_string_is_empty(host->bin_path)) {
2693 /* we still have connections bound to this proc,
2694 * let them terminate first */
2695 if (proc->load != 0) break;
2697 /* restart the child */
2699 if (p->conf.debug) {
2700 log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
2701 "--- fastcgi spawning",
2702 "\n\tsocket", proc->connection_name,
2703 "\n\tcurrent:", 1, "/", host->max_procs);
2706 if (fcgi_spawn_connection(srv, p, host, proc)) {
2707 log_error_write(srv, __FILE__, __LINE__, "s",
2708 "ERROR: spawning fcgi failed.");
2709 return HANDLER_ERROR;
2711 } else {
2712 if (srv->cur_ts <= proc->disabled_until) break;
2714 proc->state = PROC_STATE_RUNNING;
2715 host->active_procs++;
2717 log_error_write(srv, __FILE__, __LINE__, "sb",
2718 "fcgi-server re-enabled:",
2719 proc->connection_name);
2721 break;
2725 return 0;
2728 static handler_t fcgi_write_request(server *srv, handler_ctx *hctx) {
2729 plugin_data *p = hctx->plugin_data;
2730 fcgi_extension_host *host= hctx->host;
2731 connection *con = hctx->remote_conn;
2732 fcgi_proc *proc;
2734 int ret;
2736 /* sanity check:
2737 * - host != NULL
2738 * - either:
2739 * - tcp socket (do not check host->host->uses, as it may be not set which means INADDR_LOOPBACK)
2740 * - unix socket
2742 if (!host) {
2743 log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: host = NULL");
2744 return HANDLER_ERROR;
2746 if ((!host->port && buffer_string_is_empty(host->unixsocket))) {
2747 log_error_write(srv, __FILE__, __LINE__, "s", "fatal error: neither host->port nor host->unixsocket is set");
2748 return HANDLER_ERROR;
2751 /* we can't handle this in the switch as we have to fall through in it */
2752 if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
2753 int socket_error;
2754 socklen_t socket_error_len = sizeof(socket_error);
2756 /* try to finish the connect() */
2757 if (0 != getsockopt(hctx->fd, SOL_SOCKET, SO_ERROR, &socket_error, &socket_error_len)) {
2758 log_error_write(srv, __FILE__, __LINE__, "ss",
2759 "getsockopt failed:", strerror(errno));
2761 fcgi_host_disable(srv, hctx);
2763 return HANDLER_ERROR;
2765 if (socket_error != 0) {
2766 if (!hctx->proc->is_local || p->conf.debug) {
2767 /* local procs get restarted */
2769 log_error_write(srv, __FILE__, __LINE__, "sssb",
2770 "establishing connection failed:", strerror(socket_error),
2771 "socket:", hctx->proc->connection_name);
2774 fcgi_host_disable(srv, hctx);
2775 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2776 "backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2777 "reconnects:", hctx->reconnects,
2778 "load:", host->load);
2780 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2781 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2783 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2785 return HANDLER_ERROR;
2787 /* go on with preparing the request */
2788 hctx->state = FCGI_STATE_PREPARE_WRITE;
2792 switch(hctx->state) {
2793 case FCGI_STATE_CONNECT_DELAYED:
2794 /* should never happen */
2795 break;
2796 case FCGI_STATE_INIT:
2797 /* do we have a running process for this host (max-procs) ? */
2798 hctx->proc = NULL;
2800 for (proc = hctx->host->first;
2801 proc && proc->state != PROC_STATE_RUNNING;
2802 proc = proc->next);
2804 /* all children are dead */
2805 if (proc == NULL) {
2806 hctx->fde_ndx = -1;
2808 return HANDLER_ERROR;
2811 hctx->proc = proc;
2813 /* check the other procs if they have a lower load */
2814 for (proc = proc->next; proc; proc = proc->next) {
2815 if (proc->state != PROC_STATE_RUNNING) continue;
2816 if (proc->load < hctx->proc->load) hctx->proc = proc;
2819 ret = buffer_string_is_empty(host->unixsocket) ? AF_INET : AF_UNIX;
2821 if (-1 == (hctx->fd = socket(ret, SOCK_STREAM, 0))) {
2822 if (errno == EMFILE ||
2823 errno == EINTR) {
2824 log_error_write(srv, __FILE__, __LINE__, "sd",
2825 "wait for fd at connection:", con->fd);
2827 return HANDLER_WAIT_FOR_FD;
2830 log_error_write(srv, __FILE__, __LINE__, "ssdd",
2831 "socket failed:", strerror(errno), srv->cur_fds, srv->max_fds);
2832 return HANDLER_ERROR;
2834 hctx->fde_ndx = -1;
2836 srv->cur_fds++;
2838 fdevent_register(srv->ev, hctx->fd, fcgi_handle_fdevent, hctx);
2840 if (-1 == fdevent_fcntl_set(srv->ev, hctx->fd)) {
2841 log_error_write(srv, __FILE__, __LINE__, "ss",
2842 "fcntl failed:", strerror(errno));
2844 return HANDLER_ERROR;
2847 if (hctx->proc->is_local) {
2848 hctx->pid = hctx->proc->pid;
2851 switch (fcgi_establish_connection(srv, hctx)) {
2852 case CONNECTION_DELAYED:
2853 /* connection is in progress, wait for an event and call getsockopt() below */
2855 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2857 fcgi_set_state(srv, hctx, FCGI_STATE_CONNECT_DELAYED);
2858 return HANDLER_WAIT_FOR_EVENT;
2859 case CONNECTION_OVERLOADED:
2860 /* cool down the backend, it is overloaded
2861 * -> EAGAIN */
2863 if (hctx->host->disable_time) {
2864 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2865 "backend is overloaded; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2866 "reconnects:", hctx->reconnects,
2867 "load:", host->load);
2869 hctx->proc->disabled_until = srv->cur_ts + hctx->host->disable_time;
2870 if (hctx->proc->state == PROC_STATE_RUNNING) hctx->host->active_procs--;
2871 hctx->proc->state = PROC_STATE_OVERLOADED;
2874 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2875 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".overloaded"));
2877 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2879 return HANDLER_ERROR;
2880 case CONNECTION_DEAD:
2881 /* we got a hard error from the backend like
2882 * - ECONNREFUSED for tcp-ip sockets
2883 * - ENOENT for unix-domain-sockets
2885 * for check if the host is back in hctx->host->disable_time seconds
2886 * */
2888 fcgi_host_disable(srv, hctx);
2890 log_error_write(srv, __FILE__, __LINE__, "sdssdsd",
2891 "backend died; we'll disable it for", hctx->host->disable_time, "seconds and send the request to another backend instead:",
2892 "reconnects:", hctx->reconnects,
2893 "load:", host->load);
2895 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2896 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".died"));
2898 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2900 return HANDLER_ERROR;
2901 case CONNECTION_OK:
2902 /* everything is ok, go on */
2904 fcgi_set_state(srv, hctx, FCGI_STATE_PREPARE_WRITE);
2906 break;
2908 /* fallthrough */
2909 case FCGI_STATE_PREPARE_WRITE:
2910 /* ok, we have the connection */
2912 fcgi_proc_load_inc(srv, hctx);
2913 hctx->got_proc = 1;
2915 status_counter_inc(srv, CONST_STR_LEN("fastcgi.requests"));
2917 fastcgi_status_copy_procname(p->statuskey, hctx->host, hctx->proc);
2918 buffer_append_string_len(p->statuskey, CONST_STR_LEN(".connected"));
2920 status_counter_inc(srv, CONST_BUF_LEN(p->statuskey));
2922 if (p->conf.debug) {
2923 log_error_write(srv, __FILE__, __LINE__, "ssdsbsd",
2924 "got proc:",
2925 "pid:", hctx->proc->pid,
2926 "socket:", hctx->proc->connection_name,
2927 "load:", hctx->proc->load);
2930 /* move the proc-list entry down the list */
2931 if (hctx->request_id == 0) {
2932 hctx->request_id = 1; /* always use id 1 as we don't use multiplexing */
2933 } else {
2934 log_error_write(srv, __FILE__, __LINE__, "sd",
2935 "fcgi-request is already in use:", hctx->request_id);
2938 if (-1 == fcgi_create_env(srv, hctx, hctx->request_id)) return HANDLER_ERROR;
2940 fcgi_set_state(srv, hctx, FCGI_STATE_WRITE);
2941 /* fall through */
2942 case FCGI_STATE_WRITE:
2943 ret = srv->network_backend_write(srv, con, hctx->fd, hctx->wb, MAX_WRITE_LIMIT);
2945 chunkqueue_remove_finished_chunks(hctx->wb);
2947 if (ret < 0) {
2948 switch(errno) {
2949 case EPIPE:
2950 case ENOTCONN:
2951 case ECONNRESET:
2952 /* the connection got dropped after accept()
2953 * we don't care about that - if you accept() it, you have to handle it.
2956 log_error_write(srv, __FILE__, __LINE__, "ssosb",
2957 "connection was dropped after accept() (perhaps the fastcgi process died),",
2958 "write-offset:", hctx->wb->bytes_out,
2959 "socket:", hctx->proc->connection_name);
2961 return HANDLER_ERROR;
2962 default:
2963 log_error_write(srv, __FILE__, __LINE__, "ssd",
2964 "write failed:", strerror(errno), errno);
2966 return HANDLER_ERROR;
2970 if (hctx->wb->bytes_out == hctx->wb->bytes_in) {
2971 /* we don't need the out event anymore */
2972 fdevent_event_del(srv->ev, &(hctx->fde_ndx), hctx->fd);
2973 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
2974 fcgi_set_state(srv, hctx, FCGI_STATE_READ);
2975 } else {
2976 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
2978 return HANDLER_WAIT_FOR_EVENT;
2981 break;
2982 case FCGI_STATE_READ:
2983 /* waiting for a response */
2984 break;
2985 default:
2986 log_error_write(srv, __FILE__, __LINE__, "s", "(debug) unknown state");
2987 return HANDLER_ERROR;
2990 return HANDLER_WAIT_FOR_EVENT;
2994 /* might be called on fdevent after a connect() is delay too
2995 * */
2996 SUBREQUEST_FUNC(mod_fastcgi_handle_subrequest) {
2997 plugin_data *p = p_d;
2999 handler_ctx *hctx = con->plugin_ctx[p->id];
3000 fcgi_extension_host *host;
3002 if (NULL == hctx) return HANDLER_GO_ON;
3004 /* not my job */
3005 if (con->mode != p->id) return HANDLER_GO_ON;
3007 /* we don't have a host yet, choose one
3008 * -> this happens in the first round
3009 * and when the host died and we have to select a new one */
3010 if (hctx->host == NULL) {
3011 size_t k;
3012 int ndx, used = -1;
3014 /* check if the next server has no load. */
3015 ndx = hctx->ext->last_used_ndx + 1;
3016 if(ndx >= (int) hctx->ext->used || ndx < 0) ndx = 0;
3017 host = hctx->ext->hosts[ndx];
3018 if (host->load > 0) {
3019 /* get backend with the least load. */
3020 for (k = 0, ndx = -1; k < hctx->ext->used; k++) {
3021 host = hctx->ext->hosts[k];
3023 /* we should have at least one proc that can do something */
3024 if (host->active_procs == 0) continue;
3026 if (used == -1 || host->load < used) {
3027 used = host->load;
3029 ndx = k;
3034 /* found a server */
3035 if (ndx == -1) {
3036 /* all hosts are down */
3038 fcgi_connection_close(srv, hctx);
3040 con->http_status = 500;
3041 con->mode = DIRECT;
3043 return HANDLER_FINISHED;
3046 hctx->ext->last_used_ndx = ndx;
3047 host = hctx->ext->hosts[ndx];
3050 * if check-local is disabled, use the uri.path handler
3054 /* init handler-context */
3056 /* we put a connection on this host, move the other new connections to other hosts
3058 * as soon as hctx->host is unassigned, decrease the load again */
3059 fcgi_host_assign(srv, hctx, host);
3060 hctx->proc = NULL;
3061 } else {
3062 host = hctx->host;
3065 /* ok, create the request */
3066 switch(fcgi_write_request(srv, hctx)) {
3067 case HANDLER_ERROR:
3068 if (hctx->state == FCGI_STATE_INIT ||
3069 hctx->state == FCGI_STATE_CONNECT_DELAYED) {
3070 fcgi_restart_dead_procs(srv, p, host);
3072 /* cleanup this request and let the request handler start this request again */
3073 if (hctx->reconnects < 5) {
3074 fcgi_reconnect(srv, hctx);
3075 joblist_append(srv, con); /* in case we come from the event-handler */
3077 return HANDLER_WAIT_FOR_FD;
3078 } else {
3079 fcgi_connection_close(srv, hctx);
3081 buffer_reset(con->physical.path);
3082 con->mode = DIRECT;
3083 con->http_status = 503;
3084 joblist_append(srv, con); /* in case we come from the event-handler */
3086 return HANDLER_FINISHED;
3088 } else {
3089 fcgi_connection_close(srv, hctx);
3091 buffer_reset(con->physical.path);
3092 con->mode = DIRECT;
3093 if (con->http_status != 400) con->http_status = 503;
3094 joblist_append(srv, con); /* really ? */
3096 return HANDLER_FINISHED;
3098 case HANDLER_WAIT_FOR_EVENT:
3099 if (con->file_started == 1) {
3100 return HANDLER_FINISHED;
3101 } else {
3102 return HANDLER_WAIT_FOR_EVENT;
3104 case HANDLER_WAIT_FOR_FD:
3105 return HANDLER_WAIT_FOR_FD;
3106 default:
3107 log_error_write(srv, __FILE__, __LINE__, "s", "subrequest write-req default");
3108 return HANDLER_ERROR;
3112 static handler_t fcgi_handle_fdevent(server *srv, void *ctx, int revents) {
3113 handler_ctx *hctx = ctx;
3114 connection *con = hctx->remote_conn;
3115 plugin_data *p = hctx->plugin_data;
3117 fcgi_proc *proc = hctx->proc;
3118 fcgi_extension_host *host= hctx->host;
3120 if ((revents & FDEVENT_IN) &&
3121 hctx->state == FCGI_STATE_READ) {
3122 switch (fcgi_demux_response(srv, hctx)) {
3123 case 0:
3124 break;
3125 case 1:
3127 if (host->mode == FCGI_AUTHORIZER &&
3128 (con->http_status == 200 ||
3129 con->http_status == 0)) {
3131 * If we are here in AUTHORIZER mode then a request for authorizer
3132 * was processed already, and status 200 has been returned. We need
3133 * now to handle authorized request.
3136 buffer_copy_buffer(con->physical.doc_root, host->docroot);
3137 buffer_copy_buffer(con->physical.basedir, host->docroot);
3139 buffer_copy_buffer(con->physical.path, host->docroot);
3140 buffer_append_string_buffer(con->physical.path, con->uri.path);
3141 fcgi_connection_close(srv, hctx);
3143 con->mode = DIRECT;
3144 con->http_status = 0;
3145 con->file_started = 1; /* fcgi_extension won't touch the request afterwards */
3146 } else {
3147 /* we are done */
3148 fcgi_connection_close(srv, hctx);
3151 joblist_append(srv, con);
3152 return HANDLER_FINISHED;
3153 case -1:
3154 if (proc->pid && proc->state != PROC_STATE_DIED) {
3155 int status;
3157 /* only fetch the zombie if it is not already done */
3159 switch(waitpid(proc->pid, &status, WNOHANG)) {
3160 case 0:
3161 /* child is still alive */
3162 break;
3163 case -1:
3164 break;
3165 default:
3166 /* the child should not terminate at all */
3167 if (WIFEXITED(status)) {
3168 log_error_write(srv, __FILE__, __LINE__, "sdsd",
3169 "child exited, pid:", proc->pid,
3170 "status:", WEXITSTATUS(status));
3171 } else if (WIFSIGNALED(status)) {
3172 log_error_write(srv, __FILE__, __LINE__, "sd",
3173 "child signaled:",
3174 WTERMSIG(status));
3175 } else {
3176 log_error_write(srv, __FILE__, __LINE__, "sd",
3177 "child died somehow:",
3178 status);
3181 if (p->conf.debug) {
3182 log_error_write(srv, __FILE__, __LINE__, "ssbsdsd",
3183 "--- fastcgi spawning",
3184 "\n\tsocket", proc->connection_name,
3185 "\n\tcurrent:", 1, "/", host->max_procs);
3188 if (fcgi_spawn_connection(srv, p, host, proc)) {
3189 /* respawning failed, retry later */
3190 proc->state = PROC_STATE_DIED;
3192 log_error_write(srv, __FILE__, __LINE__, "s",
3193 "respawning failed, will retry later");
3196 break;
3200 if (con->file_started == 0) {
3201 /* nothing has been sent out yet, try to use another child */
3203 if (hctx->wb->bytes_out == 0 &&
3204 hctx->reconnects < 5) {
3205 fcgi_reconnect(srv, hctx);
3207 log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3208 "response not received, request not sent",
3209 "on socket:", proc->connection_name,
3210 "for", con->uri.path, "?", con->uri.query, ", reconnecting");
3212 return HANDLER_WAIT_FOR_FD;
3215 log_error_write(srv, __FILE__, __LINE__, "sosbsBSBs",
3216 "response not received, request sent:", hctx->wb->bytes_out,
3217 "on socket:", proc->connection_name,
3218 "for", con->uri.path, "?", con->uri.query, ", closing connection");
3220 fcgi_connection_close(srv, hctx);
3222 connection_set_state(srv, con, CON_STATE_HANDLE_REQUEST);
3223 buffer_reset(con->physical.path);
3224 con->http_status = 500;
3225 con->mode = DIRECT;
3226 } else {
3227 /* response might have been already started, kill the connection */
3228 fcgi_connection_close(srv, hctx);
3230 log_error_write(srv, __FILE__, __LINE__, "ssbsBSBs",
3231 "response already sent out, but backend returned error",
3232 "on socket:", proc->connection_name,
3233 "for", con->uri.path, "?", con->uri.query, ", terminating connection");
3235 connection_set_state(srv, con, CON_STATE_ERROR);
3238 /* */
3241 joblist_append(srv, con);
3242 return HANDLER_FINISHED;
3246 if (revents & FDEVENT_OUT) {
3247 if (hctx->state == FCGI_STATE_CONNECT_DELAYED ||
3248 hctx->state == FCGI_STATE_WRITE) {
3249 /* we are allowed to send something out
3251 * 1. in an unfinished connect() call
3252 * 2. in an unfinished write() call (long POST request)
3254 return mod_fastcgi_handle_subrequest(srv, con, p);
3255 } else {
3256 log_error_write(srv, __FILE__, __LINE__, "sd",
3257 "got a FDEVENT_OUT and didn't know why:",
3258 hctx->state);
3262 /* perhaps this issue is already handled */
3263 if (revents & FDEVENT_HUP) {
3264 if (hctx->state == FCGI_STATE_CONNECT_DELAYED) {
3265 /* getoptsock will catch this one (right ?)
3267 * if we are in connect we might get an EINPROGRESS
3268 * in the first call and an FDEVENT_HUP in the
3269 * second round
3271 * FIXME: as it is a bit ugly.
3274 return mod_fastcgi_handle_subrequest(srv, con, p);
3275 } else if (hctx->state == FCGI_STATE_READ &&
3276 hctx->proc->port == 0) {
3277 /* FIXME:
3279 * ioctl says 8192 bytes to read from PHP and we receive directly a HUP for the socket
3280 * even if the FCGI_FIN packet is not received yet
3282 } else {
3283 log_error_write(srv, __FILE__, __LINE__, "sBSbsbsd",
3284 "error: unexpected close of fastcgi connection for",
3285 con->uri.path, "?", con->uri.query,
3286 "(no fastcgi process on socket:", proc->connection_name, "?)",
3287 hctx->state);
3289 connection_set_state(srv, con, CON_STATE_ERROR);
3290 fcgi_connection_close(srv, hctx);
3291 joblist_append(srv, con);
3293 } else if (revents & FDEVENT_ERR) {
3294 log_error_write(srv, __FILE__, __LINE__, "s",
3295 "fcgi: got a FDEVENT_ERR. Don't know why.");
3296 /* kill all connections to the fastcgi process */
3299 connection_set_state(srv, con, CON_STATE_ERROR);
3300 fcgi_connection_close(srv, hctx);
3301 joblist_append(srv, con);
3304 return HANDLER_FINISHED;
3306 #define PATCH(x) \
3307 p->conf.x = s->x;
3308 static int fcgi_patch_connection(server *srv, connection *con, plugin_data *p) {
3309 size_t i, j;
3310 plugin_config *s = p->config_storage[0];
3312 PATCH(exts);
3313 PATCH(debug);
3314 PATCH(ext_mapping);
3316 /* skip the first, the global context */
3317 for (i = 1; i < srv->config_context->used; i++) {
3318 data_config *dc = (data_config *)srv->config_context->data[i];
3319 s = p->config_storage[i];
3321 /* condition didn't match */
3322 if (!config_check_cond(srv, con, dc)) continue;
3324 /* merge config */
3325 for (j = 0; j < dc->value->used; j++) {
3326 data_unset *du = dc->value->data[j];
3328 if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.server"))) {
3329 PATCH(exts);
3330 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.debug"))) {
3331 PATCH(debug);
3332 } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("fastcgi.map-extensions"))) {
3333 PATCH(ext_mapping);
3338 return 0;
3340 #undef PATCH
3343 static handler_t fcgi_check_extension(server *srv, connection *con, void *p_d, int uri_path_handler) {
3344 plugin_data *p = p_d;
3345 size_t s_len;
3346 size_t k;
3347 buffer *fn;
3348 fcgi_extension *extension = NULL;
3349 fcgi_extension_host *host = NULL;
3351 if (con->mode != DIRECT) return HANDLER_GO_ON;
3353 /* Possibly, we processed already this request */
3354 if (con->file_started == 1) return HANDLER_GO_ON;
3356 fn = uri_path_handler ? con->uri.path : con->physical.path;
3358 if (buffer_string_is_empty(fn)) return HANDLER_GO_ON;
3360 s_len = buffer_string_length(fn);
3362 fcgi_patch_connection(srv, con, p);
3364 /* fastcgi.map-extensions maps extensions to existing fastcgi.server entries
3366 * fastcgi.map-extensions = ( ".php3" => ".php" )
3368 * fastcgi.server = ( ".php" => ... )
3370 * */
3372 /* check if extension-mapping matches */
3373 for (k = 0; k < p->conf.ext_mapping->used; k++) {
3374 data_string *ds = (data_string *)p->conf.ext_mapping->data[k];
3375 size_t ct_len; /* length of the config entry */
3377 if (buffer_is_empty(ds->key)) continue;
3379 ct_len = buffer_string_length(ds->key);
3381 if (s_len < ct_len) continue;
3383 /* found a mapping */
3384 if (0 == strncmp(fn->ptr + s_len - ct_len, ds->key->ptr, ct_len)) {
3385 /* check if we know the extension */
3387 /* we can reuse k here */
3388 for (k = 0; k < p->conf.exts->used; k++) {
3389 extension = p->conf.exts->exts[k];
3391 if (buffer_is_equal(ds->value, extension->key)) {
3392 break;
3396 if (k == p->conf.exts->used) {
3397 /* found nothign */
3398 extension = NULL;
3400 break;
3404 if (extension == NULL) {
3405 size_t uri_path_len = buffer_string_length(con->uri.path);
3407 /* check if extension matches */
3408 for (k = 0; k < p->conf.exts->used; k++) {
3409 size_t ct_len; /* length of the config entry */
3410 fcgi_extension *ext = p->conf.exts->exts[k];
3412 if (buffer_is_empty(ext->key)) continue;
3414 ct_len = buffer_string_length(ext->key);
3416 /* check _url_ in the form "/fcgi_pattern" */
3417 if (ext->key->ptr[0] == '/') {
3418 if ((ct_len <= uri_path_len) &&
3419 (strncmp(con->uri.path->ptr, ext->key->ptr, ct_len) == 0)) {
3420 extension = ext;
3421 break;
3423 } else if ((ct_len <= s_len) && (0 == strncmp(fn->ptr + s_len - ct_len, ext->key->ptr, ct_len))) {
3424 /* check extension in the form ".fcg" */
3425 extension = ext;
3426 break;
3429 /* extension doesn't match */
3430 if (NULL == extension) {
3431 return HANDLER_GO_ON;
3435 /* check if we have at least one server for this extension up and running */
3436 for (k = 0; k < extension->used; k++) {
3437 fcgi_extension_host *h = extension->hosts[k];
3439 /* we should have at least one proc that can do something */
3440 if (h->active_procs == 0) {
3441 continue;
3444 /* we found one host that is alive */
3445 host = h;
3446 break;
3449 if (!host) {
3450 /* sorry, we don't have a server alive for this ext */
3451 buffer_reset(con->physical.path);
3452 con->http_status = 500;
3454 /* only send the 'no handler' once */
3455 if (!extension->note_is_sent) {
3456 extension->note_is_sent = 1;
3458 log_error_write(srv, __FILE__, __LINE__, "sBSbsbs",
3459 "all handlers for", con->uri.path, "?", con->uri.query,
3460 "on", extension->key,
3461 "are down.");
3464 return HANDLER_FINISHED;
3467 /* a note about no handler is not sent yet */
3468 extension->note_is_sent = 0;
3471 * if check-local is disabled, use the uri.path handler
3475 /* init handler-context */
3476 if (uri_path_handler) {
3477 if (host->check_local == 0) {
3478 handler_ctx *hctx;
3479 char *pathinfo;
3481 hctx = handler_ctx_init();
3483 hctx->remote_conn = con;
3484 hctx->plugin_data = p;
3485 hctx->proc = NULL;
3486 hctx->ext = extension;
3489 hctx->conf.exts = p->conf.exts;
3490 hctx->conf.debug = p->conf.debug;
3492 con->plugin_ctx[p->id] = hctx;
3494 con->mode = p->id;
3496 if (con->conf.log_request_handling) {
3497 log_error_write(srv, __FILE__, __LINE__, "s",
3498 "handling it in mod_fastcgi");
3501 /* do not split path info for authorizer */
3502 if (host->mode != FCGI_AUTHORIZER) {
3503 /* the prefix is the SCRIPT_NAME,
3504 * everything from start to the next slash
3505 * this is important for check-local = "disable"
3507 * if prefix = /admin.fcgi
3509 * /admin.fcgi/foo/bar
3511 * SCRIPT_NAME = /admin.fcgi
3512 * PATH_INFO = /foo/bar
3514 * if prefix = /fcgi-bin/
3516 * /fcgi-bin/foo/bar
3518 * SCRIPT_NAME = /fcgi-bin/foo
3519 * PATH_INFO = /bar
3521 * if prefix = /, and fix-root-path-name is enable
3523 * /fcgi-bin/foo/bar
3525 * SCRIPT_NAME = /fcgi-bin/foo
3526 * PATH_INFO = /bar
3530 /* the rewrite is only done for /prefix/? matches */
3531 if (host->fix_root_path_name && extension->key->ptr[0] == '/' && extension->key->ptr[1] == '\0') {
3532 buffer_copy_string(con->request.pathinfo, con->uri.path->ptr);
3533 buffer_string_set_length(con->uri.path, 0);
3534 } else if (extension->key->ptr[0] == '/' &&
3535 buffer_string_length(con->uri.path) > buffer_string_length(extension->key) &&
3536 NULL != (pathinfo = strchr(con->uri.path->ptr + buffer_string_length(extension->key), '/'))) {
3537 /* rewrite uri.path and pathinfo */
3539 buffer_copy_string(con->request.pathinfo, pathinfo);
3540 buffer_string_set_length(con->uri.path, buffer_string_length(con->uri.path) - buffer_string_length(con->request.pathinfo));
3544 } else {
3545 handler_ctx *hctx;
3546 hctx = handler_ctx_init();
3548 hctx->remote_conn = con;
3549 hctx->plugin_data = p;
3550 hctx->proc = NULL;
3551 hctx->ext = extension;
3553 hctx->conf.exts = p->conf.exts;
3554 hctx->conf.debug = p->conf.debug;
3556 con->plugin_ctx[p->id] = hctx;
3558 con->mode = p->id;
3560 if (con->conf.log_request_handling) {
3561 log_error_write(srv, __FILE__, __LINE__, "s", "handling it in mod_fastcgi");
3565 return HANDLER_GO_ON;
3568 /* uri-path handler */
3569 static handler_t fcgi_check_extension_1(server *srv, connection *con, void *p_d) {
3570 return fcgi_check_extension(srv, con, p_d, 1);
3573 /* start request handler */
3574 static handler_t fcgi_check_extension_2(server *srv, connection *con, void *p_d) {
3575 return fcgi_check_extension(srv, con, p_d, 0);
3578 JOBLIST_FUNC(mod_fastcgi_handle_joblist) {
3579 plugin_data *p = p_d;
3580 handler_ctx *hctx = con->plugin_ctx[p->id];
3582 if (hctx == NULL) return HANDLER_GO_ON;
3584 if (hctx->fd != -1) {
3585 switch (hctx->state) {
3586 case FCGI_STATE_READ:
3587 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_IN);
3589 break;
3590 case FCGI_STATE_CONNECT_DELAYED:
3591 case FCGI_STATE_WRITE:
3592 fdevent_event_set(srv->ev, &(hctx->fde_ndx), hctx->fd, FDEVENT_OUT);
3594 break;
3595 case FCGI_STATE_INIT:
3596 /* at reconnect */
3597 break;
3598 default:
3599 log_error_write(srv, __FILE__, __LINE__, "sd", "unhandled fcgi.state", hctx->state);
3600 break;
3604 return HANDLER_GO_ON;
3608 static handler_t fcgi_connection_close_callback(server *srv, connection *con, void *p_d) {
3609 plugin_data *p = p_d;
3611 fcgi_connection_close(srv, con->plugin_ctx[p->id]);
3613 return HANDLER_GO_ON;
3616 TRIGGER_FUNC(mod_fastcgi_handle_trigger) {
3617 plugin_data *p = p_d;
3618 size_t i, j, n;
3621 /* perhaps we should kill a connect attempt after 10-15 seconds
3623 * currently we wait for the TCP timeout which is 180 seconds on Linux
3629 /* check all children if they are still up */
3631 for (i = 0; i < srv->config_context->used; i++) {
3632 plugin_config *conf;
3633 fcgi_exts *exts;
3635 conf = p->config_storage[i];
3637 exts = conf->exts;
3639 for (j = 0; j < exts->used; j++) {
3640 fcgi_extension *ex;
3642 ex = exts->exts[j];
3644 for (n = 0; n < ex->used; n++) {
3646 fcgi_proc *proc;
3647 fcgi_extension_host *host;
3649 host = ex->hosts[n];
3651 fcgi_restart_dead_procs(srv, p, host);
3653 for (proc = host->unused_procs; proc; proc = proc->next) {
3654 int status;
3656 if (proc->pid == 0) continue;
3658 switch (waitpid(proc->pid, &status, WNOHANG)) {
3659 case 0:
3660 /* child still running after timeout, good */
3661 break;
3662 case -1:
3663 if (errno != EINTR) {
3664 /* no PID found ? should never happen */
3665 log_error_write(srv, __FILE__, __LINE__, "sddss",
3666 "pid ", proc->pid, proc->state,
3667 "not found:", strerror(errno));
3669 #if 0
3670 if (errno == ECHILD) {
3671 /* someone else has cleaned up for us */
3672 proc->pid = 0;
3673 proc->state = PROC_STATE_UNSET;
3675 #endif
3677 break;
3678 default:
3679 /* the child should not terminate at all */
3680 if (WIFEXITED(status)) {
3681 if (proc->state != PROC_STATE_KILLED) {
3682 log_error_write(srv, __FILE__, __LINE__, "sdb",
3683 "child exited:",
3684 WEXITSTATUS(status), proc->connection_name);
3686 } else if (WIFSIGNALED(status)) {
3687 if (WTERMSIG(status) != SIGTERM) {
3688 log_error_write(srv, __FILE__, __LINE__, "sd",
3689 "child signaled:",
3690 WTERMSIG(status));
3692 } else {
3693 log_error_write(srv, __FILE__, __LINE__, "sd",
3694 "child died somehow:",
3695 status);
3697 proc->pid = 0;
3698 if (proc->state == PROC_STATE_RUNNING) host->active_procs--;
3699 proc->state = PROC_STATE_UNSET;
3700 host->max_id--;
3707 return HANDLER_GO_ON;
3711 int mod_fastcgi_plugin_init(plugin *p);
3712 int mod_fastcgi_plugin_init(plugin *p) {
3713 p->version = LIGHTTPD_VERSION_ID;
3714 p->name = buffer_init_string("fastcgi");
3716 p->init = mod_fastcgi_init;
3717 p->cleanup = mod_fastcgi_free;
3718 p->set_defaults = mod_fastcgi_set_defaults;
3719 p->connection_reset = fcgi_connection_reset;
3720 p->handle_connection_close = fcgi_connection_close_callback;
3721 p->handle_uri_clean = fcgi_check_extension_1;
3722 p->handle_subrequest_start = fcgi_check_extension_2;
3723 p->handle_subrequest = mod_fastcgi_handle_subrequest;
3724 p->handle_joblist = mod_fastcgi_handle_joblist;
3725 p->handle_trigger = mod_fastcgi_handle_trigger;
3727 p->data = NULL;
3729 return 0;