8 #include "http_chunk.h"
10 #include "connections.h"
16 #include "inet_ntop_cache.h"
17 #include "stat_cache.h"
18 #include "status_counter.h"
20 #include <sys/types.h>
30 #ifdef HAVE_FASTCGI_FASTCGI_H
31 # include <fastcgi/fastcgi.h>
33 # ifdef HAVE_FASTCGI_H
38 #endif /* HAVE_FASTCGI_FASTCGI_H */
42 #include "sys-socket.h"
47 #ifdef HAVE_SYS_WAIT_H
55 * - add timeout for a connect to a non-fastcgi process
56 * (use state_timestamp + state)
60 typedef struct fcgi_proc
{
61 size_t id
; /* id will be between 1 and max_procs */
62 buffer
*unixsocket
; /* config.socket + "-" + id */
63 unsigned port
; /* config.port + pno */
65 buffer
*connection_name
; /* either tcp:<host>:<port> or unix:<socket> for debugging purposes */
67 pid_t pid
; /* PID of the spawned process (0 if not spawned locally) */
70 size_t load
; /* number of requests waiting on this process */
72 size_t requests
; /* see max_requests */
73 struct fcgi_proc
*prev
, *next
; /* see first */
75 time_t disabled_until
; /* this proc is disabled until, use something else until then */
80 PROC_STATE_UNSET
, /* init-phase */
81 PROC_STATE_RUNNING
, /* alive */
82 PROC_STATE_OVERLOADED
, /* listen-queue is full,
83 don't send anything to this proc for the next 2 seconds */
84 PROC_STATE_DIED_WAIT_FOR_PID
, /* */
85 PROC_STATE_DIED
, /* marked as dead, should be restarted */
86 PROC_STATE_KILLED
/* was killed as we don't have the load anymore */
91 /* the key that is used to reference this value */
94 /* list of processes handling this extension
95 * sorted by lowest load
97 * whenever a job is done move it up in the list
98 * until it is sorted, move it down as soon as the
102 fcgi_proc
*unused_procs
;
105 * spawn at least min_procs, at max_procs.
107 * as soon as the load of the first entry
108 * is max_load_per_proc we spawn a new one
109 * and add it to the first entry and give it
114 unsigned short max_procs
;
115 size_t num_procs
; /* how many procs are started */
116 size_t active_procs
; /* how many of them are really running, i.e. state = PROC_STATE_RUNNING */
119 * time after a disabled remote connection is tried to be re-enabled
124 unsigned short disable_time
;
127 * some fastcgi processes get a little bit larger
128 * than wanted. max_requests_per_proc kills a
129 * process after a number of handled requests.
132 size_t max_requests_per_proc
;
140 * if host is one of the local IP adresses the
141 * whole connection is local
143 * if port is not 0, and host is not specified,
144 * "localhost" (INADDR_LOOPBACK) is assumed.
154 * instead of TCP/IP we can use Unix Domain Sockets
155 * - more secure (you have fileperms to play with)
156 * - more control (on locally)
157 * - more speed (no extra overhead)
161 /* if socket is local we can start the fastcgi
164 * bin-path is the path to the binary
166 * check min_procs and max_procs for the number
167 * of process to start up
171 /* bin-path is set bin-environment is taken to
172 * create the environement before starting the
181 * docroot-translation between URL->phys and the
185 * - different dir-layout if remote
192 * check_local tells you if the phys file is stat()ed
193 * or not. FastCGI doesn't care if the service is
194 * remote. If the web-server side doesn't contain
195 * the fastcgi-files we should not stat() for them
196 * and say '404 not found'.
198 unsigned short check_local
;
201 * append PATH_INFO to SCRIPT_FILENAME
203 * php needs this if cgi.fix_pathinfo is provided
207 unsigned short break_scriptfilename_for_php
;
210 * workaround for program when prefix="/"
212 * rule to build PATH_INFO is hardcoded for when check_local is disabled
213 * enable this option to use the workaround
217 unsigned short fix_root_path_name
;
220 * If the backend includes X-Sendfile in the response
221 * we use the value as filename and ignore the content.
224 unsigned short xsendfile_allow
;
225 array
*xsendfile_docroot
;
227 ssize_t load
; /* replace by host->load */
229 size_t max_id
; /* corresponds most of the time to
232 only if a process is killed max_id waits for the process itself
233 to die and decrements it afterwards */
235 buffer
*strip_request_uri
;
237 unsigned short kill_signal
; /* we need a setting for this as libfcgi
238 applications prefer SIGUSR1 while the
239 rest of the world would use SIGTERM
244 } fcgi_extension_host
;
247 * one extension can have multiple hosts assigned
248 * one host can spawn additional processes on the same
249 * socket (if we control it)
251 * ext -> host -> procs
254 * if the fastcgi process is remote that whole goes down
257 * ext -> host -> procs
260 * in case of PHP and FCGI_CHILDREN we have again a procs
261 * but we don't control it directly.
266 buffer
*key
; /* like .php */
271 fcgi_extension_host
**hosts
;
278 fcgi_extension
**exts
;
287 fcgi_exts
*exts_auth
;
288 fcgi_exts
*exts_resp
;
302 /* generic plugin data, shared between all connections */
312 plugin_config
**config_storage
;
314 plugin_config conf
; /* this is only used as long as no handler_ctx is setup */
317 /* connection specific data */
320 FCGI_STATE_CONNECT_DELAYED
,
321 FCGI_STATE_PREPARE_WRITE
,
324 } fcgi_connection_state_t
;
328 fcgi_extension_host
*host
;
330 fcgi_extension
*ext_auth
; /* (might be used in future to allow multiple authorizers)*/
331 unsigned short fcgi_mode
; /* FastCGI mode: FCGI_AUTHORIZER or FCGI_RESPONDER */
333 fcgi_connection_state_t state
;
334 time_t state_timestamp
;
336 chunkqueue
*rb
; /* read queue */
337 chunkqueue
*wb
; /* write queue */
340 buffer
*response_header
;
342 int fd
; /* fd to the fastcgi process */
343 int fde_ndx
; /* index into the fd-event buffer */
347 int reconnects
; /* number of reconnect attempts */
350 int send_content_body
;
354 connection
*remote_conn
; /* dumb pointer */
355 plugin_data
*plugin_data
; /* dumb pointer */
359 /* ok, we need a prototype */
360 static handler_t
fcgi_handle_fdevent(server
*srv
, void *ctx
, int revents
);
362 static void reset_signals(void) {
364 signal(SIGTTOU
, SIG_DFL
);
367 signal(SIGTTIN
, SIG_DFL
);
370 signal(SIGTSTP
, SIG_DFL
);
372 signal(SIGHUP
, SIG_DFL
);
373 signal(SIGPIPE
, SIG_DFL
);
374 signal(SIGUSR1
, SIG_DFL
);
377 static void fastcgi_status_copy_procname(buffer
*b
, fcgi_extension_host
*host
, fcgi_proc
*proc
) {
378 buffer_copy_string_len(b
, CONST_STR_LEN("fastcgi.backend."));
379 buffer_append_string_buffer(b
, host
->id
);
381 buffer_append_string_len(b
, CONST_STR_LEN("."));
382 buffer_append_int(b
, proc
->id
);
386 static void fcgi_proc_load_inc(server
*srv
, handler_ctx
*hctx
) {
387 plugin_data
*p
= hctx
->plugin_data
;
390 status_counter_inc(srv
, CONST_STR_LEN("fastcgi.active-requests"));
392 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
393 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".load"));
395 status_counter_set(srv
, CONST_BUF_LEN(p
->statuskey
), hctx
->proc
->load
);
398 static void fcgi_proc_load_dec(server
*srv
, handler_ctx
*hctx
) {
399 plugin_data
*p
= hctx
->plugin_data
;
402 status_counter_dec(srv
, CONST_STR_LEN("fastcgi.active-requests"));
404 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
405 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".load"));
407 status_counter_set(srv
, CONST_BUF_LEN(p
->statuskey
), hctx
->proc
->load
);
410 static void fcgi_host_assign(server
*srv
, handler_ctx
*hctx
, fcgi_extension_host
*host
) {
411 plugin_data
*p
= hctx
->plugin_data
;
415 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, NULL
);
416 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".load"));
418 status_counter_set(srv
, CONST_BUF_LEN(p
->statuskey
), hctx
->host
->load
);
421 static void fcgi_host_reset(server
*srv
, handler_ctx
*hctx
) {
422 plugin_data
*p
= hctx
->plugin_data
;
425 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, NULL
);
426 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".load"));
428 status_counter_set(srv
, CONST_BUF_LEN(p
->statuskey
), hctx
->host
->load
);
433 static void fcgi_host_disable(server
*srv
, handler_ctx
*hctx
) {
434 if (hctx
->host
->disable_time
|| hctx
->proc
->is_local
) {
435 if (hctx
->proc
->state
== PROC_STATE_RUNNING
) hctx
->host
->active_procs
--;
436 hctx
->proc
->disabled_until
= srv
->cur_ts
+ hctx
->host
->disable_time
;
437 hctx
->proc
->state
= hctx
->proc
->is_local
? PROC_STATE_DIED_WAIT_FOR_PID
: PROC_STATE_DIED
;
439 if (hctx
->conf
.debug
) {
440 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
441 "backend disabled for", hctx
->host
->disable_time
, "seconds");
446 static int fastcgi_status_init(server
*srv
, buffer
*b
, fcgi_extension_host
*host
, fcgi_proc
*proc
) {
448 fastcgi_status_copy_procname(b, host, proc); \
449 buffer_append_string_len(b, CONST_STR_LEN(x)); \
450 status_counter_set(srv, CONST_BUF_LEN(b), 0);
454 CLEAN(".overloaded");
461 fastcgi_status_copy_procname(b, host, NULL); \
462 buffer_append_string_len(b, CONST_STR_LEN(x)); \
463 status_counter_set(srv, CONST_BUF_LEN(b), 0);
472 static handler_ctx
* handler_ctx_init(void) {
475 hctx
= calloc(1, sizeof(*hctx
));
480 hctx
->response_header
= buffer_init();
482 hctx
->request_id
= 0;
483 hctx
->fcgi_mode
= FCGI_RESPONDER
;
484 hctx
->state
= FCGI_STATE_INIT
;
489 hctx
->reconnects
= 0;
490 hctx
->send_content_body
= 1;
492 hctx
->rb
= chunkqueue_init();
493 hctx
->wb
= chunkqueue_init();
499 static void handler_ctx_free(handler_ctx
*hctx
) {
500 /* caller MUST have called fcgi_backend_close(srv, hctx) if necessary */
501 buffer_free(hctx
->response_header
);
503 chunkqueue_free(hctx
->rb
);
504 chunkqueue_free(hctx
->wb
);
509 static void handler_ctx_clear(handler_ctx
*hctx
) {
510 /* caller MUST have called fcgi_backend_close(srv, hctx) if necessary */
515 /*hctx->ext_auth is intentionally preserved to flag prior authorizer*/
517 hctx
->fcgi_mode
= FCGI_RESPONDER
;
518 hctx
->state
= FCGI_STATE_INIT
;
519 /*hctx->state_timestamp = 0;*//*(unused; left as-is)*/
521 chunkqueue_reset(hctx
->rb
);
522 chunkqueue_reset(hctx
->wb
);
525 buffer_reset(hctx
->response_header
);
529 /*hctx->pid = -1;*//*(unused; left as-is)*/
531 hctx
->reconnects
= 0;
532 hctx
->request_id
= 0;
533 hctx
->send_content_body
= 1;
535 /*plugin_config conf;*//*(no need to reset for same request)*/
537 /*hctx->remote_conn = NULL;*//*(no need to reset for same request)*/
538 /*hctx->plugin_data = NULL;*//*(no need to reset for same request)*/
541 static fcgi_proc
*fastcgi_process_init(void) {
544 f
= calloc(1, sizeof(*f
));
545 f
->unixsocket
= buffer_init();
546 f
->connection_name
= buffer_init();
554 static void fastcgi_process_free(fcgi_proc
*f
) {
557 fastcgi_process_free(f
->next
);
559 buffer_free(f
->unixsocket
);
560 buffer_free(f
->connection_name
);
565 static fcgi_extension_host
*fastcgi_host_init(void) {
566 fcgi_extension_host
*f
;
568 f
= calloc(1, sizeof(*f
));
570 f
->id
= buffer_init();
571 f
->host
= buffer_init();
572 f
->unixsocket
= buffer_init();
573 f
->docroot
= buffer_init();
574 f
->bin_path
= buffer_init();
575 f
->bin_env
= array_init();
576 f
->bin_env_copy
= array_init();
577 f
->strip_request_uri
= buffer_init();
578 f
->xsendfile_docroot
= array_init();
583 static void fastcgi_host_free(fcgi_extension_host
*h
) {
591 buffer_free(h
->host
);
592 buffer_free(h
->unixsocket
);
593 buffer_free(h
->docroot
);
594 buffer_free(h
->bin_path
);
595 buffer_free(h
->strip_request_uri
);
596 array_free(h
->bin_env
);
597 array_free(h
->bin_env_copy
);
598 array_free(h
->xsendfile_docroot
);
600 fastcgi_process_free(h
->first
);
601 fastcgi_process_free(h
->unused_procs
);
607 static fcgi_exts
*fastcgi_extensions_init(void) {
610 f
= calloc(1, sizeof(*f
));
615 static void fastcgi_extensions_free(fcgi_exts
*f
) {
620 for (i
= 0; i
< f
->used
; i
++) {
626 for (j
= 0; j
< fe
->used
; j
++) {
627 fcgi_extension_host
*h
;
631 fastcgi_host_free(h
);
634 buffer_free(fe
->key
);
645 static int fastcgi_extension_insert(fcgi_exts
*ext
, buffer
*key
, fcgi_extension_host
*fh
) {
649 /* there is something */
651 for (i
= 0; i
< ext
->used
; i
++) {
652 if (buffer_is_equal(key
, ext
->exts
[i
]->key
)) {
657 if (i
== ext
->used
) {
658 /* filextension is new */
659 fe
= calloc(1, sizeof(*fe
));
661 fe
->key
= buffer_init();
662 fe
->last_used_ndx
= -1;
663 buffer_copy_buffer(fe
->key
, key
);
667 if (ext
->size
== 0) {
669 ext
->exts
= malloc(ext
->size
* sizeof(*(ext
->exts
)));
670 force_assert(ext
->exts
);
671 } else if (ext
->used
== ext
->size
) {
673 ext
->exts
= realloc(ext
->exts
, ext
->size
* sizeof(*(ext
->exts
)));
674 force_assert(ext
->exts
);
676 ext
->exts
[ext
->used
++] = fe
;
683 fe
->hosts
= malloc(fe
->size
* sizeof(*(fe
->hosts
)));
684 force_assert(fe
->hosts
);
685 } else if (fe
->size
== fe
->used
) {
687 fe
->hosts
= realloc(fe
->hosts
, fe
->size
* sizeof(*(fe
->hosts
)));
688 force_assert(fe
->hosts
);
691 fe
->hosts
[fe
->used
++] = fh
;
697 INIT_FUNC(mod_fastcgi_init
) {
700 p
= calloc(1, sizeof(*p
));
702 p
->fcgi_env
= buffer_init();
704 p
->path
= buffer_init();
706 p
->statuskey
= buffer_init();
712 FREE_FUNC(mod_fastcgi_free
) {
713 plugin_data
*p
= p_d
;
717 buffer_free(p
->fcgi_env
);
718 buffer_free(p
->path
);
719 buffer_free(p
->statuskey
);
721 if (p
->config_storage
) {
723 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
724 plugin_config
*s
= p
->config_storage
[i
];
727 if (NULL
== s
) continue;
732 for (j
= 0; j
< exts
->used
; j
++) {
737 for (n
= 0; n
< ex
->used
; n
++) {
739 fcgi_extension_host
*host
;
743 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
744 if (proc
->pid
!= 0) {
745 kill(proc
->pid
, host
->kill_signal
);
748 if (proc
->is_local
&&
749 !buffer_string_is_empty(proc
->unixsocket
)) {
750 unlink(proc
->unixsocket
->ptr
);
754 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
755 if (proc
->pid
!= 0) {
756 kill(proc
->pid
, host
->kill_signal
);
758 if (proc
->is_local
&&
759 !buffer_string_is_empty(proc
->unixsocket
)) {
760 unlink(proc
->unixsocket
->ptr
);
766 fastcgi_extensions_free(s
->exts
);
767 fastcgi_extensions_free(s
->exts_auth
);
768 fastcgi_extensions_free(s
->exts_resp
);
770 array_free(s
->ext_mapping
);
774 free(p
->config_storage
);
779 return HANDLER_GO_ON
;
782 static int env_add(char_array
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
786 if (!key
|| !val
) return -1;
788 dst
= malloc(key_len
+ val_len
+ 3);
789 memcpy(dst
, key
, key_len
);
791 memcpy(dst
+ key_len
+ 1, val
, val_len
);
792 dst
[key_len
+ 1 + val_len
] = '\0';
794 for (i
= 0; i
< env
->used
; i
++) {
795 if (0 == strncmp(dst
, env
->ptr
[i
], key_len
+ 1)) {
796 /* don't care about free as we are in a forked child which is going to exec(...) */
797 /* free(env->ptr[i]); */
803 if (env
->size
== 0) {
805 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
806 } else if (env
->size
== env
->used
+ 1) {
808 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
811 env
->ptr
[env
->used
++] = dst
;
816 static int parse_binpath(char_array
*env
, buffer
*b
) {
819 /* search for spaces */
822 for (i
= 0; i
< buffer_string_length(b
); i
++) {
826 /* a WS, stop here and copy the argument */
828 if (env
->size
== 0) {
830 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
831 } else if (env
->size
== env
->used
) {
833 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
838 env
->ptr
[env
->used
++] = start
;
840 start
= b
->ptr
+ i
+ 1;
847 if (env
->size
== 0) {
849 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
850 } else if (env
->size
== env
->used
) { /* we need one extra for the terminating NULL */
852 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
856 env
->ptr
[env
->used
++] = start
;
858 if (env
->size
== 0) {
860 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
861 } else if (env
->size
== env
->used
) { /* we need one extra for the terminating NULL */
863 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
867 env
->ptr
[env
->used
++] = NULL
;
872 #if !defined(HAVE_FORK)
873 static int fcgi_spawn_connection(server
*srv
,
875 fcgi_extension_host
*host
,
884 #else /* -> defined(HAVE_FORK) */
886 static int fcgi_spawn_connection(server
*srv
,
888 fcgi_extension_host
*host
,
892 struct timeval tv
= { 0, 100 * 1000 };
894 struct sockaddr_un fcgi_addr_un
;
896 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
897 struct sockaddr_in6 fcgi_addr_in6
;
899 struct sockaddr_in fcgi_addr_in
;
900 struct sockaddr
*fcgi_addr
;
905 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
906 "new proc, socket:", proc
->port
, proc
->unixsocket
);
909 if (!buffer_string_is_empty(proc
->unixsocket
)) {
911 memset(&fcgi_addr_un
, 0, sizeof(fcgi_addr_un
));
912 fcgi_addr_un
.sun_family
= AF_UNIX
;
913 if (buffer_string_length(proc
->unixsocket
) + 1 > sizeof(fcgi_addr_un
.sun_path
)) {
914 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
915 "ERROR: Unix Domain socket filename too long:",
919 memcpy(fcgi_addr_un
.sun_path
, proc
->unixsocket
->ptr
, buffer_string_length(proc
->unixsocket
) + 1);
922 servlen
= SUN_LEN(&fcgi_addr_un
);
925 servlen
= buffer_string_length(proc
->unixsocket
) + 1 + sizeof(fcgi_addr_un
.sun_family
);
927 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_un
;
929 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("unix:"));
930 buffer_append_string_buffer(proc
->connection_name
, proc
->unixsocket
);
933 log_error_write(srv
, __FILE__
, __LINE__
, "s",
934 "ERROR: Unix Domain sockets are not supported.");
937 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
938 } else if (host
->family
== AF_INET6
&& !buffer_string_is_empty(host
->host
)) {
939 memset(&fcgi_addr_in6
, 0, sizeof(fcgi_addr_in6
));
940 fcgi_addr_in6
.sin6_family
= AF_INET6
;
941 inet_pton(AF_INET6
, host
->host
->ptr
, (char *) &fcgi_addr_in6
.sin6_addr
);
942 fcgi_addr_in6
.sin6_port
= htons(proc
->port
);
943 servlen
= sizeof(fcgi_addr_in6
);
944 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_in6
;
947 memset(&fcgi_addr_in
, 0, sizeof(fcgi_addr_in
));
948 fcgi_addr_in
.sin_family
= AF_INET
;
950 if (buffer_string_is_empty(host
->host
)) {
951 fcgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
955 /* set a useful default */
956 fcgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
959 if (NULL
== (he
= gethostbyname(host
->host
->ptr
))) {
960 log_error_write(srv
, __FILE__
, __LINE__
,
961 "sdb", "gethostbyname failed: ",
962 h_errno
, host
->host
);
966 if (he
->h_addrtype
!= AF_INET
) {
967 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-type != AF_INET: ", he
->h_addrtype
);
971 if (he
->h_length
!= sizeof(struct in_addr
)) {
972 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-length != sizeof(in_addr): ", he
->h_length
);
976 memcpy(&(fcgi_addr_in
.sin_addr
.s_addr
), he
->h_addr_list
[0], he
->h_length
);
979 fcgi_addr_in
.sin_port
= htons(proc
->port
);
980 servlen
= sizeof(fcgi_addr_in
);
982 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_in
;
985 if (buffer_string_is_empty(proc
->unixsocket
)) {
986 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("tcp:"));
987 if (!buffer_string_is_empty(host
->host
)) {
988 buffer_append_string_buffer(proc
->connection_name
, host
->host
);
990 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN("localhost"));
992 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN(":"));
993 buffer_append_int(proc
->connection_name
, proc
->port
);
996 if (-1 == (fcgi_fd
= fdevent_socket_cloexec(fcgi_addr
->sa_family
, SOCK_STREAM
, 0))) {
997 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
998 "failed:", strerror(errno
));
1002 if (-1 == connect(fcgi_fd
, fcgi_addr
, servlen
)) {
1003 /* server is not up, spawn it */
1007 if (errno
!= ENOENT
&&
1008 !buffer_string_is_empty(proc
->unixsocket
)) {
1009 unlink(proc
->unixsocket
->ptr
);
1015 if (-1 == (fcgi_fd
= fdevent_socket_cloexec(fcgi_addr
->sa_family
, SOCK_STREAM
, 0))) {
1016 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1017 "socket failed:", strerror(errno
));
1022 if (setsockopt(fcgi_fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
)) < 0) {
1023 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1024 "socketsockopt failed:", strerror(errno
));
1030 if (-1 == bind(fcgi_fd
, fcgi_addr
, servlen
)) {
1031 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1033 proc
->connection_name
,
1039 if (-1 == listen(fcgi_fd
, host
->listen_backlog
)) {
1040 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1041 "listen failed:", strerror(errno
));
1046 switch ((child
= fork())) {
1053 /* create environment */
1062 if(fcgi_fd
!= FCGI_LISTENSOCK_FILENO
) {
1063 dup2(fcgi_fd
, FCGI_LISTENSOCK_FILENO
);
1068 fcntl(fcgi_fd
, F_SETFD
, 0); /* clear cloexec */
1071 /* we don't need the client socket */
1072 for (i
= 3; i
< 256; i
++) {
1076 /* build clean environment */
1077 if (host
->bin_env_copy
->used
) {
1078 for (i
= 0; i
< host
->bin_env_copy
->used
; i
++) {
1079 data_string
*ds
= (data_string
*)host
->bin_env_copy
->data
[i
];
1082 if (NULL
!= (ge
= getenv(ds
->value
->ptr
))) {
1083 env_add(&env
, CONST_BUF_LEN(ds
->value
), ge
, strlen(ge
));
1087 char ** const e
= environ
;
1088 for (i
= 0; e
[i
]; ++i
) {
1091 if (NULL
!= (eq
= strchr(e
[i
], '='))) {
1092 env_add(&env
, e
[i
], eq
- e
[i
], eq
+1, strlen(eq
+1));
1097 /* create environment */
1098 for (i
= 0; i
< host
->bin_env
->used
; i
++) {
1099 data_string
*ds
= (data_string
*)host
->bin_env
->data
[i
];
1101 env_add(&env
, CONST_BUF_LEN(ds
->key
), CONST_BUF_LEN(ds
->value
));
1104 for (i
= 0; i
< env
.used
; i
++) {
1105 /* search for PHP_FCGI_CHILDREN */
1106 if (0 == strncmp(env
.ptr
[i
], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
1109 /* not found, add a default */
1110 if (i
== env
.used
) {
1111 env_add(&env
, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
1114 env
.ptr
[env
.used
] = NULL
;
1116 parse_binpath(&arg
, host
->bin_path
);
1118 /* chdir into the base of the bin-path,
1119 * search for the last / */
1120 if (NULL
!= (c
= strrchr(arg
.ptr
[0], '/'))) {
1123 /* change to the physical directory */
1124 if (-1 == chdir(arg
.ptr
[0])) {
1126 log_error_write(srv
, __FILE__
, __LINE__
, "sss", "chdir failed:", strerror(errno
), arg
.ptr
[0]);
1134 execve(arg
.ptr
[0], arg
.ptr
, env
.ptr
);
1136 /* log_error_write(srv, __FILE__, __LINE__, "sbs",
1137 "execve failed for:", host->bin_path, strerror(errno)); */
1152 select(0, NULL
, NULL
, NULL
, &tv
);
1154 switch (waitpid(child
, &status
, WNOHANG
)) {
1156 /* child still running after timeout, good */
1159 /* no PID found ? should never happen */
1160 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1161 "pid not found:", strerror(errno
));
1164 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1165 "the fastcgi-backend", host
->bin_path
, "failed to start:");
1166 /* the child should not terminate at all */
1167 if (WIFEXITED(status
)) {
1168 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
1169 "child exited with status",
1170 WEXITSTATUS(status
), host
->bin_path
);
1171 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1172 "If you're trying to run your app as a FastCGI backend, make sure you're using the FastCGI-enabled version.\n"
1173 "If this is PHP on Gentoo, add 'fastcgi' to the USE flags.");
1174 } else if (WIFSIGNALED(status
)) {
1175 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1176 "terminated by signal:",
1179 if (WTERMSIG(status
) == 11) {
1180 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1181 "to be exact: it segfaulted, crashed, died, ... you get the idea." );
1182 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1183 "If this is PHP, try removing the bytecode caches for now and try again.");
1186 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1187 "child died somehow:",
1193 /* register process */
1204 if (p
->conf
.debug
) {
1205 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1206 "(debug) socket is already used; won't spawn:",
1207 proc
->connection_name
);
1211 proc
->state
= PROC_STATE_RUNNING
;
1212 host
->active_procs
++;
1217 #endif /* HAVE_FORK */
1219 static fcgi_extension_host
* unixsocket_is_dup(plugin_data
*p
, size_t used
, buffer
*unixsocket
) {
1221 for (i
= 0; i
< used
; ++i
) {
1222 fcgi_exts
*exts
= p
->config_storage
[i
]->exts
;
1223 if (NULL
== exts
) continue;
1224 for (j
= 0; j
< exts
->used
; ++j
) {
1225 fcgi_extension
*ex
= exts
->exts
[j
];
1226 for (n
= 0; n
< ex
->used
; ++n
) {
1227 fcgi_extension_host
*host
= ex
->hosts
[n
];
1228 if (!buffer_string_is_empty(host
->unixsocket
)
1229 && buffer_is_equal(host
->unixsocket
, unixsocket
)
1230 && !buffer_string_is_empty(host
->bin_path
))
1239 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults
) {
1240 plugin_data
*p
= p_d
;
1243 buffer
*fcgi_mode
= buffer_init();
1244 fcgi_extension_host
*host
= NULL
;
1246 config_values_t cv
[] = {
1247 { "fastcgi.server", NULL
, T_CONFIG_LOCAL
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
1248 { "fastcgi.debug", NULL
, T_CONFIG_INT
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
1249 { "fastcgi.map-extensions", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
1250 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
1253 p
->config_storage
= calloc(1, srv
->config_context
->used
* sizeof(plugin_config
*));
1255 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1256 data_config
const* config
= (data_config
const*)srv
->config_context
->data
[i
];
1259 s
= malloc(sizeof(plugin_config
));
1261 s
->exts_auth
= NULL
;
1262 s
->exts_resp
= NULL
;
1264 s
->ext_mapping
= array_init();
1266 cv
[0].destination
= s
->exts
; /* not used; T_CONFIG_LOCAL */
1267 cv
[1].destination
= &(s
->debug
);
1268 cv
[2].destination
= s
->ext_mapping
;
1270 p
->config_storage
[i
] = s
;
1272 if (0 != config_insert_values_global(srv
, config
->value
, cv
, i
== 0 ? T_CONFIG_SCOPE_SERVER
: T_CONFIG_SCOPE_CONNECTION
)) {
1280 if (NULL
!= (du
= array_get_element(config
->value
, "fastcgi.server"))) {
1282 data_array
*da
= (data_array
*)du
;
1284 if (du
->type
!= TYPE_ARRAY
) {
1285 log_error_write(srv
, __FILE__
, __LINE__
, "sss",
1286 "unexpected type for key: ", "fastcgi.server", "expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1291 s
->exts
= fastcgi_extensions_init();
1292 s
->exts_auth
= fastcgi_extensions_init();
1293 s
->exts_resp
= fastcgi_extensions_init();
1296 * fastcgi.server = ( "<ext>" => ( ... ),
1297 * "<ext>" => ( ... ) )
1300 for (j
= 0; j
< da
->value
->used
; j
++) {
1302 data_array
*da_ext
= (data_array
*)da
->value
->data
[j
];
1304 if (da
->value
->data
[j
]->type
!= TYPE_ARRAY
) {
1305 log_error_write(srv
, __FILE__
, __LINE__
, "sssbs",
1306 "unexpected type for key: ", "fastcgi.server",
1307 "[", da
->value
->data
[j
]->key
, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1313 * da_ext->key == name of the extension
1317 * fastcgi.server = ( "<ext>" =>
1318 * ( "<host>" => ( ... ),
1319 * "<host>" => ( ... )
1324 for (n
= 0; n
< da_ext
->value
->used
; n
++) {
1325 data_array
*da_host
= (data_array
*)da_ext
->value
->data
[n
];
1327 config_values_t fcv
[] = {
1328 { "host", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
1329 { "docroot", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
1330 { "mode", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
1331 { "socket", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 3 */
1332 { "bin-path", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 4 */
1334 { "check-local", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 5 */
1335 { "port", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 6 */
1336 { "max-procs", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 */
1337 { "disable-time", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 8 */
1339 { "bin-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 9 */
1340 { "bin-copy-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 10 */
1342 { "broken-scriptfilename", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 11 */
1343 { "allow-x-send-file", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 12 */
1344 { "strip-request-uri", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 13 */
1345 { "kill-signal", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 14 */
1346 { "fix-root-scriptname", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 15 */
1347 { "listen-backlog", NULL
, T_CONFIG_INT
, T_CONFIG_SCOPE_CONNECTION
}, /* 16 */
1348 { "x-sendfile", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 17 */
1349 { "x-sendfile-docroot",NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 18 */
1351 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
1353 unsigned short host_mode
= FCGI_RESPONDER
;
1355 if (da_host
->type
!= TYPE_ARRAY
) {
1356 log_error_write(srv
, __FILE__
, __LINE__
, "ssSBS",
1357 "unexpected type for key:",
1359 "[", da_host
->key
, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1364 host
= fastcgi_host_init();
1365 buffer_reset(fcgi_mode
);
1367 buffer_copy_buffer(host
->id
, da_host
->key
);
1369 host
->check_local
= 1;
1370 host
->max_procs
= 4;
1371 host
->disable_time
= 1;
1372 host
->break_scriptfilename_for_php
= 0;
1373 host
->xsendfile_allow
= 0;
1374 host
->kill_signal
= SIGTERM
;
1375 host
->fix_root_path_name
= 0;
1376 host
->listen_backlog
= 1024;
1379 fcv
[0].destination
= host
->host
;
1380 fcv
[1].destination
= host
->docroot
;
1381 fcv
[2].destination
= fcgi_mode
;
1382 fcv
[3].destination
= host
->unixsocket
;
1383 fcv
[4].destination
= host
->bin_path
;
1385 fcv
[5].destination
= &(host
->check_local
);
1386 fcv
[6].destination
= &(host
->port
);
1387 fcv
[7].destination
= &(host
->max_procs
);
1388 fcv
[8].destination
= &(host
->disable_time
);
1390 fcv
[9].destination
= host
->bin_env
;
1391 fcv
[10].destination
= host
->bin_env_copy
;
1392 fcv
[11].destination
= &(host
->break_scriptfilename_for_php
);
1393 fcv
[12].destination
= &(host
->xsendfile_allow
);
1394 fcv
[13].destination
= host
->strip_request_uri
;
1395 fcv
[14].destination
= &(host
->kill_signal
);
1396 fcv
[15].destination
= &(host
->fix_root_path_name
);
1397 fcv
[16].destination
= &(host
->listen_backlog
);
1398 fcv
[17].destination
= &(host
->xsendfile_allow
);
1399 fcv
[18].destination
= host
->xsendfile_docroot
;
1401 if (0 != config_insert_values_internal(srv
, da_host
->value
, fcv
, T_CONFIG_SCOPE_CONNECTION
)) {
1405 if ((!buffer_string_is_empty(host
->host
) || host
->port
) &&
1406 !buffer_string_is_empty(host
->unixsocket
)) {
1407 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsbs",
1408 "either host/port or socket have to be set in:",
1410 da_ext
->key
, " => (",
1411 da_host
->key
, " ( ...");
1416 if (!buffer_string_is_empty(host
->unixsocket
)) {
1417 /* unix domain socket */
1418 struct sockaddr_un un
;
1420 if (buffer_string_length(host
->unixsocket
) + 1 > sizeof(un
.sun_path
) - 2) {
1421 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsbs",
1422 "unixsocket is too long in:",
1424 da_ext
->key
, " => (",
1425 da_host
->key
, " ( ...");
1430 if (!buffer_string_is_empty(host
->bin_path
)) {
1431 fcgi_extension_host
*duplicate
= unixsocket_is_dup(p
, i
+1, host
->unixsocket
);
1432 if (NULL
!= duplicate
) {
1433 if (!buffer_is_equal(host
->bin_path
, duplicate
->bin_path
)) {
1434 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1435 "duplicate unixsocket path:",
1439 fastcgi_host_free(host
);
1445 host
->family
= AF_UNIX
;
1449 if (buffer_string_is_empty(host
->host
) &&
1450 buffer_string_is_empty(host
->bin_path
)) {
1451 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsbs",
1452 "host or binpath have to be set in:",
1454 da_ext
->key
, " => (",
1455 da_host
->key
, " ( ...");
1458 } else if (host
->port
== 0) {
1459 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsbs",
1460 "port has to be set in:",
1462 da_ext
->key
, " => (",
1463 da_host
->key
, " ( ...");
1468 host
->family
= (!buffer_string_is_empty(host
->host
) && NULL
!= strchr(host
->host
->ptr
, ':')) ? AF_INET6
: AF_INET
;
1471 if (host
->refcount
) {
1472 /* already init'd; skip spawning */
1473 } else if (!buffer_string_is_empty(host
->bin_path
)) {
1474 /* a local socket + self spawning */
1478 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsbsd",
1479 "--- fastcgi spawning local",
1480 "\n\tproc:", host
->bin_path
,
1481 "\n\tport:", host
->port
,
1482 "\n\tsocket", host
->unixsocket
,
1483 "\n\tmax-procs:", host
->max_procs
);
1486 for (pno
= 0; pno
< host
->max_procs
; pno
++) {
1489 proc
= fastcgi_process_init();
1490 proc
->id
= host
->num_procs
++;
1493 if (buffer_string_is_empty(host
->unixsocket
)) {
1494 proc
->port
= host
->port
+ pno
;
1496 buffer_copy_buffer(proc
->unixsocket
, host
->unixsocket
);
1497 buffer_append_string_len(proc
->unixsocket
, CONST_STR_LEN("-"));
1498 buffer_append_int(proc
->unixsocket
, pno
);
1502 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
1503 "--- fastcgi spawning",
1504 "\n\tport:", host
->port
,
1505 "\n\tsocket", host
->unixsocket
,
1506 "\n\tcurrent:", pno
, "/", host
->max_procs
);
1509 if (!srv
->srvconf
.preflight_check
1510 && fcgi_spawn_connection(srv
, p
, host
, proc
)) {
1511 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1512 "[ERROR]: spawning fcgi failed.");
1513 fastcgi_process_free(proc
);
1517 fastcgi_status_init(srv
, p
->statuskey
, host
, proc
);
1519 proc
->next
= host
->first
;
1520 if (host
->first
) host
->first
->prev
= proc
;
1527 proc
= fastcgi_process_init();
1528 proc
->id
= host
->num_procs
++;
1530 host
->active_procs
++;
1531 proc
->state
= PROC_STATE_RUNNING
;
1533 if (buffer_string_is_empty(host
->unixsocket
)) {
1534 proc
->port
= host
->port
;
1536 buffer_copy_buffer(proc
->unixsocket
, host
->unixsocket
);
1539 fastcgi_status_init(srv
, p
->statuskey
, host
, proc
);
1543 host
->max_procs
= 1;
1546 if (!buffer_string_is_empty(fcgi_mode
)) {
1547 if (strcmp(fcgi_mode
->ptr
, "responder") == 0) {
1548 host_mode
= FCGI_RESPONDER
;
1549 } else if (strcmp(fcgi_mode
->ptr
, "authorizer") == 0) {
1550 host_mode
= FCGI_AUTHORIZER
;
1552 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1553 "WARNING: unknown fastcgi mode:",
1554 fcgi_mode
, "(ignored, mode set to responder)");
1558 if (host
->xsendfile_docroot
->used
) {
1560 for (k
= 0; k
< host
->xsendfile_docroot
->used
; ++k
) {
1561 data_string
*ds
= (data_string
*)host
->xsendfile_docroot
->data
[k
];
1562 if (ds
->type
!= TYPE_STRING
) {
1563 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1564 "unexpected type for x-sendfile-docroot; expected: \"x-sendfile-docroot\" => ( \"/allowed/path\", ... )");
1567 if (ds
->value
->ptr
[0] != '/') {
1568 log_error_write(srv
, __FILE__
, __LINE__
, "SBs",
1569 "x-sendfile-docroot paths must begin with '/'; invalid: \"", ds
->value
, "\"");
1572 buffer_path_simplify(ds
->value
, ds
->value
);
1573 buffer_append_slash(ds
->value
);
1577 /* s->exts is list of exts -> hosts
1578 * s->exts now used as combined list of authorizer and responder hosts (for backend maintenance)
1579 * s->exts_auth is list of exts -> authorizer hosts
1580 * s->exts_resp is list of exts -> responder hosts
1581 * For each path/extension, there may be an independent FCGI_AUTHORIZER and FCGI_RESPONDER
1582 * (The FCGI_AUTHORIZER and FCGI_RESPONDER could be handled by the same host,
1583 * and an admin might want to do that for large uploads, since FCGI_AUTHORIZER
1584 * runs prior to receiving (potentially large) request body from client and can
1585 * authorizer or deny request prior to receiving the full upload)
1587 fastcgi_extension_insert(s
->exts
, da_ext
->key
, host
);
1589 if (host_mode
== FCGI_AUTHORIZER
) {
1591 fastcgi_extension_insert(s
->exts_auth
, da_ext
->key
, host
);
1592 } else if (host_mode
== FCGI_RESPONDER
) {
1594 fastcgi_extension_insert(s
->exts_resp
, da_ext
->key
, host
);
1595 } /*(else should have been rejected above)*/
1603 buffer_free(fcgi_mode
);
1604 return HANDLER_GO_ON
;
1607 if (NULL
!= host
) fastcgi_host_free(host
);
1608 buffer_free(fcgi_mode
);
1609 return HANDLER_ERROR
;
1612 static int fcgi_set_state(server
*srv
, handler_ctx
*hctx
, fcgi_connection_state_t state
) {
1613 hctx
->state
= state
;
1614 hctx
->state_timestamp
= srv
->cur_ts
;
1620 static void fcgi_backend_close(server
*srv
, handler_ctx
*hctx
) {
1621 if (hctx
->fd
!= -1) {
1622 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1623 fdevent_unregister(srv
->ev
, hctx
->fd
);
1624 fdevent_sched_close(srv
->ev
, hctx
->fd
, 1);
1629 if (hctx
->proc
&& hctx
->got_proc
) {
1630 /* after the connect the process gets a load */
1631 fcgi_proc_load_dec(srv
, hctx
);
1633 if (hctx
->conf
.debug
) {
1634 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsd",
1636 "pid:", hctx
->proc
->pid
,
1637 "socket:", hctx
->proc
->connection_name
,
1638 "load:", hctx
->proc
->load
);
1642 fcgi_host_reset(srv
, hctx
);
1646 static void fcgi_connection_close(server
*srv
, handler_ctx
*hctx
) {
1650 p
= hctx
->plugin_data
;
1651 con
= hctx
->remote_conn
;
1653 fcgi_backend_close(srv
, hctx
);
1654 handler_ctx_free(hctx
);
1655 con
->plugin_ctx
[p
->id
] = NULL
;
1657 /* finish response (if not already con->file_started, con->file_finished) */
1658 if (con
->mode
== p
->id
) {
1659 http_response_backend_done(srv
, con
);
1663 static int fcgi_reconnect(server
*srv
, handler_ctx
*hctx
) {
1668 * connect was ok, connection was accepted
1669 * but the php accept loop checks after the accept if it should die or not.
1671 * if yes we can only detect it at a write()
1673 * next step is resetting this attemp and setup a connection again
1675 * if we have more than 5 reconnects for the same request, die
1679 * we have a connection but the child died by some other reason
1683 if (hctx
->fd
!= -1) {
1684 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1685 fdevent_unregister(srv
->ev
, hctx
->fd
);
1686 fdevent_sched_close(srv
->ev
, hctx
->fd
, 1);
1690 fcgi_set_state(srv
, hctx
, FCGI_STATE_INIT
);
1692 hctx
->request_id
= 0;
1695 if (hctx
->conf
.debug
> 2) {
1697 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
1698 "release proc for reconnect:",
1699 hctx
->proc
->pid
, hctx
->proc
->connection_name
);
1701 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1702 "release proc for reconnect:",
1703 hctx
->host
->unixsocket
);
1707 if (hctx
->proc
&& hctx
->got_proc
) {
1708 fcgi_proc_load_dec(srv
, hctx
);
1711 /* perhaps another host gives us more luck */
1712 fcgi_host_reset(srv
, hctx
);
1718 static handler_t
fcgi_connection_reset(server
*srv
, connection
*con
, void *p_d
) {
1719 plugin_data
*p
= p_d
;
1720 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
1721 if (hctx
) fcgi_connection_close(srv
, hctx
);
1723 return HANDLER_GO_ON
;
1727 static int fcgi_env_add(void *venv
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
1731 size_t len_enc_len
= 0;
1733 if (!key
|| !val
) return -1;
1735 len
= key_len
+ val_len
;
1737 len
+= key_len
> 127 ? 4 : 1;
1738 len
+= val_len
> 127 ? 4 : 1;
1740 if (buffer_string_length(env
) + len
>= FCGI_MAX_LENGTH
) {
1742 * we can't append more headers, ignore it
1748 * field length can be 31bit max
1750 * HINT: this can't happen as FCGI_MAX_LENGTH is only 16bit
1752 force_assert(key_len
< 0x7fffffffu
);
1753 force_assert(val_len
< 0x7fffffffu
);
1755 buffer_string_prepare_append(env
, len
);
1757 if (key_len
> 127) {
1758 len_enc
[len_enc_len
++] = ((key_len
>> 24) & 0xff) | 0x80;
1759 len_enc
[len_enc_len
++] = (key_len
>> 16) & 0xff;
1760 len_enc
[len_enc_len
++] = (key_len
>> 8) & 0xff;
1761 len_enc
[len_enc_len
++] = (key_len
>> 0) & 0xff;
1763 len_enc
[len_enc_len
++] = (key_len
>> 0) & 0xff;
1766 if (val_len
> 127) {
1767 len_enc
[len_enc_len
++] = ((val_len
>> 24) & 0xff) | 0x80;
1768 len_enc
[len_enc_len
++] = (val_len
>> 16) & 0xff;
1769 len_enc
[len_enc_len
++] = (val_len
>> 8) & 0xff;
1770 len_enc
[len_enc_len
++] = (val_len
>> 0) & 0xff;
1772 len_enc
[len_enc_len
++] = (val_len
>> 0) & 0xff;
1775 buffer_append_string_len(env
, len_enc
, len_enc_len
);
1776 buffer_append_string_len(env
, key
, key_len
);
1777 buffer_append_string_len(env
, val
, val_len
);
1782 static int fcgi_header(FCGI_Header
* header
, unsigned char type
, int request_id
, int contentLength
, unsigned char paddingLength
) {
1783 force_assert(contentLength
<= FCGI_MAX_LENGTH
);
1785 header
->version
= FCGI_VERSION_1
;
1786 header
->type
= type
;
1787 header
->requestIdB0
= request_id
& 0xff;
1788 header
->requestIdB1
= (request_id
>> 8) & 0xff;
1789 header
->contentLengthB0
= contentLength
& 0xff;
1790 header
->contentLengthB1
= (contentLength
>> 8) & 0xff;
1791 header
->paddingLength
= paddingLength
;
1792 header
->reserved
= 0;
1799 CONNECTION_DELAYED
, /* retry after event, take same host */
1800 CONNECTION_OVERLOADED
, /* disable for 1 second, take another backend */
1801 CONNECTION_DEAD
/* disable for 60 seconds, take another backend */
1802 } connection_result_t
;
1804 static connection_result_t
fcgi_establish_connection(server
*srv
, handler_ctx
*hctx
) {
1805 struct sockaddr
*fcgi_addr
;
1806 struct sockaddr_in fcgi_addr_in
;
1807 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1808 struct sockaddr_in6 fcgi_addr_in6
;
1810 #ifdef HAVE_SYS_UN_H
1811 struct sockaddr_un fcgi_addr_un
;
1815 fcgi_extension_host
*host
= hctx
->host
;
1816 fcgi_proc
*proc
= hctx
->proc
;
1817 int fcgi_fd
= hctx
->fd
;
1819 if (!buffer_string_is_empty(proc
->unixsocket
)) {
1820 #ifdef HAVE_SYS_UN_H
1821 /* use the unix domain socket */
1822 memset(&fcgi_addr_un
, 0, sizeof(fcgi_addr_un
));
1823 fcgi_addr_un
.sun_family
= AF_UNIX
;
1824 if (buffer_string_length(proc
->unixsocket
) + 1 > sizeof(fcgi_addr_un
.sun_path
)) {
1825 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
1826 "ERROR: Unix Domain socket filename too long:",
1830 memcpy(fcgi_addr_un
.sun_path
, proc
->unixsocket
->ptr
, buffer_string_length(proc
->unixsocket
) + 1);
1833 servlen
= SUN_LEN(&fcgi_addr_un
);
1836 servlen
= buffer_string_length(proc
->unixsocket
) + 1 + sizeof(fcgi_addr_un
.sun_family
);
1838 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_un
;
1840 if (buffer_string_is_empty(proc
->connection_name
)) {
1841 /* on remote spawing we have to set the connection-name now */
1842 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("unix:"));
1843 buffer_append_string_buffer(proc
->connection_name
, proc
->unixsocket
);
1846 return CONNECTION_DEAD
;
1848 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1849 } else if (host
->family
== AF_INET6
&& !buffer_string_is_empty(host
->host
)) {
1850 memset(&fcgi_addr_in6
, 0, sizeof(fcgi_addr_in6
));
1851 fcgi_addr_in6
.sin6_family
= AF_INET6
;
1852 inet_pton(AF_INET6
, host
->host
->ptr
, (char *) &fcgi_addr_in6
.sin6_addr
);
1853 fcgi_addr_in6
.sin6_port
= htons(proc
->port
);
1854 servlen
= sizeof(fcgi_addr_in6
);
1855 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_in6
;
1858 memset(&fcgi_addr_in
, 0, sizeof(fcgi_addr_in
));
1859 fcgi_addr_in
.sin_family
= AF_INET
;
1860 if (!buffer_string_is_empty(host
->host
)) {
1861 if (0 == inet_aton(host
->host
->ptr
, &(fcgi_addr_in
.sin_addr
))) {
1862 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1863 "converting IP address failed for", host
->host
,
1864 "\nBe sure to specify an IP address here");
1866 return CONNECTION_DEAD
;
1869 fcgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
1871 fcgi_addr_in
.sin_port
= htons(proc
->port
);
1872 servlen
= sizeof(fcgi_addr_in
);
1874 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_in
;
1877 if (buffer_string_is_empty(proc
->unixsocket
)) {
1878 if (buffer_string_is_empty(proc
->connection_name
)) {
1879 /* on remote spawing we have to set the connection-name now */
1880 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("tcp:"));
1881 if (!buffer_string_is_empty(host
->host
)) {
1882 buffer_append_string_buffer(proc
->connection_name
, host
->host
);
1884 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN("localhost"));
1886 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN(":"));
1887 buffer_append_int(proc
->connection_name
, proc
->port
);
1891 if (-1 == connect(fcgi_fd
, fcgi_addr
, servlen
)) {
1892 if (errno
== EINPROGRESS
||
1893 errno
== EALREADY
||
1895 if (hctx
->conf
.debug
> 2) {
1896 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1897 "connect delayed; will continue later:", proc
->connection_name
);
1900 return CONNECTION_DELAYED
;
1901 } else if (errno
== EAGAIN
) {
1902 if (hctx
->conf
.debug
) {
1903 log_error_write(srv
, __FILE__
, __LINE__
, "sbsd",
1904 "This means that you have more incoming requests than your FastCGI backend can handle in parallel."
1905 "It might help to spawn more FastCGI backends or PHP children; if not, decrease server.max-connections."
1906 "The load for this FastCGI backend", proc
->connection_name
, "is", proc
->load
);
1909 return CONNECTION_OVERLOADED
;
1911 log_error_write(srv
, __FILE__
, __LINE__
, "sssb",
1913 strerror(errno
), "on",
1914 proc
->connection_name
);
1916 return CONNECTION_DEAD
;
1920 hctx
->reconnects
= 0;
1921 if (hctx
->conf
.debug
> 1) {
1922 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1923 "connect succeeded: ", fcgi_fd
);
1926 return CONNECTION_OK
;
1929 static void fcgi_stdin_append(server
*srv
, connection
*con
, handler_ctx
*hctx
, int request_id
) {
1931 chunkqueue
*req_cq
= con
->request_content_queue
;
1932 off_t offset
, weWant
;
1933 const off_t req_cqlen
= req_cq
->bytes_in
- req_cq
->bytes_out
;
1935 /* something to send ? */
1936 for (offset
= 0; offset
!= req_cqlen
; offset
+= weWant
) {
1937 weWant
= req_cqlen
- offset
> FCGI_MAX_LENGTH
? FCGI_MAX_LENGTH
: req_cqlen
- offset
;
1939 /* we announce toWrite octets
1940 * now take all request_content chunks available
1943 fcgi_header(&(header
), FCGI_STDIN
, request_id
, weWant
, 0);
1944 chunkqueue_append_mem(hctx
->wb
, (const char *)&header
, sizeof(header
));
1945 hctx
->wb_reqlen
+= sizeof(header
);
1947 if (hctx
->conf
.debug
> 10) {
1948 log_error_write(srv
, __FILE__
, __LINE__
, "soso", "tosend:", offset
, "/", req_cqlen
);
1951 chunkqueue_steal(hctx
->wb
, req_cq
, weWant
);
1952 /*(hctx->wb_reqlen already includes content_length)*/
1955 if (hctx
->wb
->bytes_in
== hctx
->wb_reqlen
) {
1956 /* terminate STDIN */
1957 fcgi_header(&(header
), FCGI_STDIN
, request_id
, 0, 0);
1958 chunkqueue_append_mem(hctx
->wb
, (const char *)&header
, sizeof(header
));
1959 hctx
->wb_reqlen
+= (int)sizeof(header
);
1963 static int fcgi_create_env(server
*srv
, handler_ctx
*hctx
, int request_id
) {
1964 FCGI_BeginRequestRecord beginRecord
;
1967 plugin_data
*p
= hctx
->plugin_data
;
1968 fcgi_extension_host
*host
= hctx
->host
;
1970 connection
*con
= hctx
->remote_conn
;
1972 http_cgi_opts opts
= {
1973 (hctx
->fcgi_mode
== FCGI_AUTHORIZER
),
1974 host
->break_scriptfilename_for_php
,
1976 host
->strip_request_uri
1979 /* send FCGI_BEGIN_REQUEST */
1981 fcgi_header(&(beginRecord
.header
), FCGI_BEGIN_REQUEST
, request_id
, sizeof(beginRecord
.body
), 0);
1982 beginRecord
.body
.roleB0
= hctx
->fcgi_mode
;
1983 beginRecord
.body
.roleB1
= 0;
1984 beginRecord
.body
.flags
= 0;
1985 memset(beginRecord
.body
.reserved
, 0, sizeof(beginRecord
.body
.reserved
));
1987 /* send FCGI_PARAMS */
1988 buffer_string_prepare_copy(p
->fcgi_env
, 1023);
1990 if (0 != http_cgi_headers(srv
, con
, &opts
, fcgi_env_add
, p
->fcgi_env
)) {
1991 con
->http_status
= 400;
1994 buffer
*b
= buffer_init();
1996 buffer_copy_string_len(b
, (const char *)&beginRecord
, sizeof(beginRecord
));
1998 fcgi_header(&(header
), FCGI_PARAMS
, request_id
, buffer_string_length(p
->fcgi_env
), 0);
1999 buffer_append_string_len(b
, (const char *)&header
, sizeof(header
));
2000 buffer_append_string_buffer(b
, p
->fcgi_env
);
2002 fcgi_header(&(header
), FCGI_PARAMS
, request_id
, 0, 0);
2003 buffer_append_string_len(b
, (const char *)&header
, sizeof(header
));
2005 hctx
->wb_reqlen
= buffer_string_length(b
);
2006 chunkqueue_append_buffer(hctx
->wb
, b
);
2010 hctx
->wb_reqlen
+= con
->request
.content_length
;/* (eventual) (minimal) total request size, not necessarily including all fcgi_headers around content length yet */
2011 fcgi_stdin_append(srv
, con
, hctx
, request_id
);
2016 static int fcgi_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
) {
2019 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2020 fcgi_extension_host
*host
= hctx
->host
;
2021 int have_sendfile2
= 0;
2022 off_t sendfile2_content_length
= 0;
2027 for (s
= in
->ptr
; NULL
!= (ns
= strchr(s
, '\n')); s
= ns
+ 1) {
2031 /* a good day. Someone has read the specs and is sending a \r\n to us */
2041 if (NULL
== (value
= strchr(s
, ':'))) {
2042 /* we expect: "<key>: <value>\n" */
2046 key_len
= value
- key
;
2050 while (*value
== ' ' || *value
== '\t') value
++;
2052 if (hctx
->fcgi_mode
!= FCGI_AUTHORIZER
||
2053 !(con
->http_status
== 0 ||
2054 con
->http_status
== 200)) {
2055 /* authorizers shouldn't affect the response headers sent back to the client */
2057 /* don't forward Status: */
2058 if (0 != strncasecmp(key
, "Status", key_len
)) {
2060 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
2061 ds
= data_response_init();
2063 buffer_copy_string_len(ds
->key
, key
, key_len
);
2064 buffer_copy_string(ds
->value
, value
);
2066 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
2070 if (hctx
->fcgi_mode
== FCGI_AUTHORIZER
&&
2072 0 == strncasecmp(key
, CONST_STR_LEN("Variable-"))) {
2074 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->environment
, TYPE_STRING
))) {
2075 ds
= data_response_init();
2077 buffer_copy_string_len(ds
->key
, key
+ 9, key_len
- 9);
2078 buffer_copy_string(ds
->value
, value
);
2080 array_insert_unique(con
->environment
, (data_unset
*)ds
);
2085 if (0 == strncasecmp(key
, "Date", key_len
)) {
2086 con
->parsed_response
|= HTTP_DATE
;
2090 if (0 == strncasecmp(key
, "Status", key_len
)) {
2091 int status
= strtol(value
, NULL
, 10);
2092 if (status
>= 100 && status
< 1000) {
2093 con
->http_status
= status
;
2094 con
->parsed_response
|= HTTP_STATUS
;
2096 con
->http_status
= 502;
2101 if (0 == strncasecmp(key
, "Location", key_len
)) {
2102 con
->parsed_response
|= HTTP_LOCATION
;
2106 if (0 == strncasecmp(key
, "Connection", key_len
)) {
2107 con
->response
.keep_alive
= (0 == strcasecmp(value
, "Keep-Alive")) ? 1 : 0;
2108 con
->parsed_response
|= HTTP_CONNECTION
;
2112 if (host
->xsendfile_allow
&& 0 == strncasecmp(key
, "X-Sendfile2", key_len
) && hctx
->send_content_body
) {
2117 char *filename
, *range
;
2118 stat_cache_entry
*sce
;
2119 off_t begin_range
, end_range
, range_len
;
2121 while (' ' == *pos
) pos
++;
2125 if (NULL
== (range
= strchr(pos
, ' '))) {
2127 if (hctx
->conf
.debug
) {
2128 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't find range after filename:", filename
);
2132 buffer_copy_string_len(srv
->tmp_buf
, filename
, range
- filename
);
2134 /* find end of range */
2135 for (pos
= ++range
; *pos
&& *pos
!= ' ' && *pos
!= ','; pos
++) ;
2137 buffer_urldecode_path(srv
->tmp_buf
);
2138 buffer_path_simplify(srv
->tmp_buf
, srv
->tmp_buf
);
2139 if (con
->conf
.force_lowercase_filenames
) {
2140 buffer_to_lower(srv
->tmp_buf
);
2142 if (host
->xsendfile_docroot
->used
) {
2143 size_t i
, xlen
= buffer_string_length(srv
->tmp_buf
);
2144 for (i
= 0; i
< host
->xsendfile_docroot
->used
; ++i
) {
2145 data_string
*ds
= (data_string
*)host
->xsendfile_docroot
->data
[i
];
2146 size_t dlen
= buffer_string_length(ds
->value
);
2148 && (!con
->conf
.force_lowercase_filenames
2149 ? 0 == memcmp(srv
->tmp_buf
->ptr
, ds
->value
->ptr
, dlen
)
2150 : 0 == strncasecmp(srv
->tmp_buf
->ptr
, ds
->value
->ptr
, dlen
))) {
2154 if (i
== host
->xsendfile_docroot
->used
) {
2155 log_error_write(srv
, __FILE__
, __LINE__
, "SBs",
2156 "X-Sendfile2 (", srv
->tmp_buf
,
2157 ") not under configured x-sendfile-docroot(s)");
2162 if (HANDLER_ERROR
== stat_cache_get_entry(srv
, con
, srv
->tmp_buf
, &sce
)) {
2163 if (hctx
->conf
.debug
) {
2164 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2165 "send-file error: couldn't get stat_cache entry for X-Sendfile2:",
2169 } else if (!S_ISREG(sce
->st
.st_mode
)) {
2170 if (hctx
->conf
.debug
) {
2171 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2172 "send-file error: wrong filetype for X-Sendfile2:",
2177 /* found the file */
2180 end_range
= sce
->st
.st_size
- 1;
2184 begin_range
= strtoll(range
, &rpos
, 10);
2185 if (errno
!= 0 || begin_range
< 0 || rpos
== range
) goto range_failed
;
2186 if ('-' != *rpos
++) goto range_failed
;
2189 end_range
= strtoll(range
, &rpos
, 10);
2190 if (errno
!= 0 || end_range
< 0 || rpos
== range
) goto range_failed
;
2192 if (rpos
!= pos
) goto range_failed
;
2197 if (hctx
->conf
.debug
) {
2198 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't decode range after filename:", filename
);
2205 /* no parameters accepted */
2207 while (*pos
== ' ') pos
++;
2208 if (*pos
!= '\0' && *pos
!= ',') return 502;
2210 range_len
= end_range
- begin_range
+ 1;
2211 if (range_len
< 0) return 502;
2212 if (range_len
!= 0) {
2213 if (0 != http_chunk_append_file_range(srv
, con
, srv
->tmp_buf
, begin_range
, range_len
)) {
2217 sendfile2_content_length
+= range_len
;
2219 if (*pos
== ',') pos
++;
2224 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
2225 con
->response
.content_length
= strtoul(value
, NULL
, 10);
2226 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
2228 if (con
->response
.content_length
< 0) con
->response
.content_length
= 0;
2236 if (have_sendfile2
) {
2239 /* fix content-length */
2240 if (NULL
== (dcls
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
2241 dcls
= data_response_init();
2244 buffer_copy_string_len(dcls
->key
, "Content-Length", sizeof("Content-Length")-1);
2245 buffer_copy_int(dcls
->value
, sendfile2_content_length
);
2246 array_replace(con
->response
.headers
, (data_unset
*)dcls
);
2248 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
2249 con
->response
.content_length
= sendfile2_content_length
;
2253 /* CGI/1.1 rev 03 - 7.2.1.2 */
2254 if ((con
->parsed_response
& HTTP_LOCATION
) &&
2255 !(con
->parsed_response
& HTTP_STATUS
)) {
2256 con
->http_status
= 302;
2268 } fastcgi_response_packet
;
2270 static int fastcgi_get_packet(server
*srv
, handler_ctx
*hctx
, fastcgi_response_packet
*packet
) {
2274 FCGI_Header
*header
;
2276 if (!hctx
->rb
->first
) return -1;
2278 packet
->b
= buffer_init();
2281 packet
->padding
= 0;
2282 packet
->request_id
= 0;
2284 offset
= 0; toread
= 8;
2285 /* get at least the FastCGI header */
2286 for (c
= hctx
->rb
->first
; c
; c
= c
->next
) {
2287 size_t weHave
= buffer_string_length(c
->mem
) - c
->offset
;
2289 if (weHave
> toread
) weHave
= toread
;
2291 buffer_append_string_len(packet
->b
, c
->mem
->ptr
+ c
->offset
, weHave
);
2293 offset
= weHave
; /* skip offset bytes in chunk for "real" data */
2295 if (0 == toread
) break;
2298 if (buffer_string_length(packet
->b
) < sizeof(FCGI_Header
)) {
2300 if (hctx
->conf
.debug
) {
2301 log_error_write(srv
, __FILE__
, __LINE__
, "sdsds", "FastCGI: header too small:", buffer_string_length(packet
->b
), "bytes <", sizeof(FCGI_Header
), "bytes, waiting for more data");
2304 buffer_free(packet
->b
);
2309 /* we have at least a header, now check how much me have to fetch */
2310 header
= (FCGI_Header
*)(packet
->b
->ptr
);
2312 packet
->len
= (header
->contentLengthB0
| (header
->contentLengthB1
<< 8)) + header
->paddingLength
;
2313 packet
->request_id
= (header
->requestIdB0
| (header
->requestIdB1
<< 8));
2314 packet
->type
= header
->type
;
2315 packet
->padding
= header
->paddingLength
;
2317 /* ->b should only be the content */
2318 buffer_string_set_length(packet
->b
, 0);
2321 /* copy the content */
2322 for (; c
&& (buffer_string_length(packet
->b
) < packet
->len
); c
= c
->next
) {
2323 size_t weWant
= packet
->len
- buffer_string_length(packet
->b
);
2324 size_t weHave
= buffer_string_length(c
->mem
) - c
->offset
- offset
;
2326 if (weHave
> weWant
) weHave
= weWant
;
2328 buffer_append_string_len(packet
->b
, c
->mem
->ptr
+ c
->offset
+ offset
, weHave
);
2330 /* we only skipped the first bytes as they belonged to the fcgi header */
2334 if (buffer_string_length(packet
->b
) < packet
->len
) {
2335 /* we didn't get the full packet */
2337 buffer_free(packet
->b
);
2341 buffer_string_set_length(packet
->b
, buffer_string_length(packet
->b
) - packet
->padding
);
2344 chunkqueue_mark_written(hctx
->rb
, packet
->len
+ sizeof(FCGI_Header
));
2349 static int fcgi_demux_response(server
*srv
, handler_ctx
*hctx
) {
2354 plugin_data
*p
= hctx
->plugin_data
;
2355 connection
*con
= hctx
->remote_conn
;
2356 int fcgi_fd
= hctx
->fd
;
2357 fcgi_extension_host
*host
= hctx
->host
;
2358 fcgi_proc
*proc
= hctx
->proc
;
2361 * check how much we have to read
2363 #if !defined(_WIN32) && !defined(__CYGWIN__)
2364 if (ioctl(hctx
->fd
, FIONREAD
, &toread
)) {
2365 if (errno
== EAGAIN
) {
2366 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2369 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2370 "unexpected end-of-file (perhaps the fastcgi process died):",
2382 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)) {
2383 off_t cqlen
= chunkqueue_length(hctx
->rb
);
2384 if (cqlen
+ toread
> 65536 + (int)sizeof(FCGI_Header
)) { /*(max size of FastCGI packet + 1)*/
2385 if (cqlen
< 65536 + (int)sizeof(FCGI_Header
)) {
2386 toread
= 65536 + (int)sizeof(FCGI_Header
) - cqlen
;
2387 } else { /* should not happen */
2388 toread
= toread
< 1024 ? toread
: 1024;
2393 chunkqueue_get_memory(hctx
->rb
, &mem
, &mem_len
, 0, toread
);
2394 r
= read(hctx
->fd
, mem
, mem_len
);
2395 chunkqueue_use_memory(hctx
->rb
, r
> 0 ? r
: 0);
2398 if (errno
== EAGAIN
) {
2399 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2402 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
2403 "unexpected end-of-file (perhaps the fastcgi process died):",
2404 fcgi_fd
, strerror(errno
));
2409 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsb",
2410 "unexpected end-of-file (perhaps the fastcgi process died):",
2412 "socket:", proc
->connection_name
);
2418 * parse the fastcgi packets and forward the content to the write-queue
2422 fastcgi_response_packet packet
;
2424 /* check if we have at least one packet */
2425 if (0 != fastcgi_get_packet(srv
, hctx
, &packet
)) {
2426 /* no full packet */
2430 switch(packet
.type
) {
2432 if (packet
.len
== 0) break;
2434 /* is the header already finished */
2435 if (0 == con
->file_started
) {
2439 /* search for header terminator
2441 * if we start with \r\n check if last packet terminated with \r\n
2442 * if we start with \n check if last packet terminated with \n
2443 * search for \r\n\r\n
2447 buffer_append_string_buffer(hctx
->response_header
, packet
.b
);
2449 if (NULL
!= (c
= buffer_search_string_len(hctx
->response_header
, CONST_STR_LEN("\r\n\r\n")))) {
2450 char *hend
= c
+ 4; /* header end == body start */
2451 size_t hlen
= hend
- hctx
->response_header
->ptr
;
2452 buffer_copy_string_len(packet
.b
, hend
, buffer_string_length(hctx
->response_header
) - hlen
);
2453 buffer_string_set_length(hctx
->response_header
, hlen
);
2454 } else if (NULL
!= (c
= buffer_search_string_len(hctx
->response_header
, CONST_STR_LEN("\n\n")))) {
2455 char *hend
= c
+ 2; /* header end == body start */
2456 size_t hlen
= hend
- hctx
->response_header
->ptr
;
2457 buffer_copy_string_len(packet
.b
, hend
, buffer_string_length(hctx
->response_header
) - hlen
);
2458 buffer_string_set_length(hctx
->response_header
, hlen
);
2460 /* no luck, no header found */
2461 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
2462 if (buffer_string_length(hctx
->response_header
) > MAX_HTTP_REQUEST_HEADER
) {
2463 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "response headers too large for", con
->uri
.path
);
2464 con
->http_status
= 502; /* Bad Gateway */
2471 /* parse the response header */
2472 if ((ret
= fcgi_response_parse(srv
, con
, p
, hctx
->response_header
))) {
2473 if (200 != ret
) { /*(200 returned for X-Sendfile2 handled)*/
2474 con
->http_status
= ret
;
2477 con
->file_started
= 1;
2478 hctx
->send_content_body
= 0;
2483 con
->file_started
= 1;
2485 if (hctx
->fcgi_mode
== FCGI_AUTHORIZER
&&
2486 (con
->http_status
== 0 ||
2487 con
->http_status
== 200)) {
2488 /* a authorizer with approved the static request, ignore the content here */
2489 hctx
->send_content_body
= 0;
2492 if (host
->xsendfile_allow
&& hctx
->send_content_body
&&
2493 (NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "X-LIGHTTPD-send-file"))
2494 || NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "X-Sendfile")))) {
2495 http_response_xsendfile(srv
, con
, ds
->value
, host
->xsendfile_docroot
);
2496 if (con
->mode
== DIRECT
) {
2500 hctx
->send_content_body
= 0; /* ignore the content */
2505 if (hctx
->send_content_body
&& !buffer_string_is_empty(packet
.b
)) {
2506 if (0 != http_chunk_append_buffer(srv
, con
, packet
.b
)) {
2507 /* error writing to tempfile;
2508 * truncate response or send 500 if nothing sent yet */
2512 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
2513 && chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
2514 if (!con
->is_writable
) {
2515 /*(defer removal of FDEVENT_IN interest since
2516 * connection_state_machine() might be able to send data
2517 * immediately, unless !con->is_writable, where
2518 * connection_state_machine() might not loop back to call
2519 * mod_fastcgi_handle_subrequest())*/
2520 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2526 if (packet
.len
== 0) break;
2528 log_error_write_multiline_buffer(srv
, __FILE__
, __LINE__
, packet
.b
, "s",
2532 case FCGI_END_REQUEST
:
2536 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2537 "FastCGI: header.type not handled: ", packet
.type
);
2540 buffer_free(packet
.b
);
2546 static int fcgi_restart_dead_procs(server
*srv
, plugin_data
*p
, fcgi_extension_host
*host
) {
2549 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2552 if (p
->conf
.debug
> 2) {
2553 log_error_write(srv
, __FILE__
, __LINE__
, "sbdddd",
2555 proc
->connection_name
,
2563 * if the remote side is overloaded, we check back after <n> seconds
2566 switch (proc
->state
) {
2567 case PROC_STATE_KILLED
:
2568 case PROC_STATE_UNSET
:
2569 /* this should never happen as long as adaptive spawing is disabled */
2573 case PROC_STATE_RUNNING
:
2575 case PROC_STATE_OVERLOADED
:
2576 if (srv
->cur_ts
<= proc
->disabled_until
) break;
2578 proc
->state
= PROC_STATE_RUNNING
;
2579 host
->active_procs
++;
2581 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2582 "fcgi-server re-enabled:",
2583 host
->host
, host
->port
,
2586 case PROC_STATE_DIED_WAIT_FOR_PID
:
2587 /* non-local procs don't have PIDs to wait for */
2588 if (!proc
->is_local
) {
2589 proc
->state
= PROC_STATE_DIED
;
2591 /* the child should not terminate at all */
2594 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2596 /* child is still alive */
2597 if (srv
->cur_ts
<= proc
->disabled_until
) break;
2599 proc
->state
= PROC_STATE_RUNNING
;
2600 host
->active_procs
++;
2602 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2603 "fcgi-server re-enabled:",
2604 host
->host
, host
->port
,
2608 if (errno
== EINTR
) continue;
2610 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2611 "child died somehow, waitpid failed:",
2613 proc
->state
= PROC_STATE_DIED
;
2616 if (WIFEXITED(status
)) {
2618 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2619 "child exited, pid:", proc
->pid
,
2620 "status:", WEXITSTATUS(status
));
2622 } else if (WIFSIGNALED(status
)) {
2623 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2627 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2628 "child died somehow:",
2632 proc
->state
= PROC_STATE_DIED
;
2639 /* fall through if we have a dead proc now */
2640 if (proc
->state
!= PROC_STATE_DIED
) break;
2642 case PROC_STATE_DIED
:
2643 /* local procs get restarted by us,
2644 * remote ones hopefully by the admin */
2646 if (!buffer_string_is_empty(host
->bin_path
)) {
2647 /* we still have connections bound to this proc,
2648 * let them terminate first */
2649 if (proc
->load
!= 0) break;
2651 /* restart the child */
2653 if (p
->conf
.debug
) {
2654 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsd",
2655 "--- fastcgi spawning",
2656 "\n\tsocket", proc
->connection_name
,
2657 "\n\tcurrent:", 1, "/", host
->max_procs
);
2660 if (fcgi_spawn_connection(srv
, p
, host
, proc
)) {
2661 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2662 "ERROR: spawning fcgi failed.");
2663 return HANDLER_ERROR
;
2666 if (srv
->cur_ts
<= proc
->disabled_until
) break;
2668 proc
->state
= PROC_STATE_RUNNING
;
2669 host
->active_procs
++;
2671 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2672 "fcgi-server re-enabled:",
2673 proc
->connection_name
);
2682 static handler_t
fcgi_write_request(server
*srv
, handler_ctx
*hctx
) {
2683 plugin_data
*p
= hctx
->plugin_data
;
2684 fcgi_extension_host
*host
= hctx
->host
;
2685 connection
*con
= hctx
->remote_conn
;
2693 * - tcp socket (do not check host->host->uses, as it may be not set which means INADDR_LOOPBACK)
2697 log_error_write(srv
, __FILE__
, __LINE__
, "s", "fatal error: host = NULL");
2698 return HANDLER_ERROR
;
2700 if ((!host
->port
&& buffer_string_is_empty(host
->unixsocket
))) {
2701 log_error_write(srv
, __FILE__
, __LINE__
, "s", "fatal error: neither host->port nor host->unixsocket is set");
2702 return HANDLER_ERROR
;
2705 /* we can't handle this in the switch as we have to fall through in it */
2706 if (hctx
->state
== FCGI_STATE_CONNECT_DELAYED
) {
2708 socklen_t socket_error_len
= sizeof(socket_error
);
2710 /* try to finish the connect() */
2711 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
2712 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2713 "getsockopt failed:", strerror(errno
));
2715 fcgi_host_disable(srv
, hctx
);
2717 return HANDLER_ERROR
;
2719 if (socket_error
!= 0) {
2720 if (!hctx
->proc
->is_local
|| hctx
->conf
.debug
) {
2721 /* local procs get restarted */
2723 log_error_write(srv
, __FILE__
, __LINE__
, "sssb",
2724 "establishing connection failed:", strerror(socket_error
),
2725 "socket:", hctx
->proc
->connection_name
);
2728 fcgi_host_disable(srv
, hctx
);
2729 log_error_write(srv
, __FILE__
, __LINE__
, "sdssdsd",
2730 "backend is overloaded; we'll disable it for", hctx
->host
->disable_time
, "seconds and send the request to another backend instead:",
2731 "reconnects:", hctx
->reconnects
,
2732 "load:", host
->load
);
2734 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2735 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".died"));
2737 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2739 return HANDLER_ERROR
;
2741 /* go on with preparing the request */
2742 hctx
->state
= FCGI_STATE_PREPARE_WRITE
;
2746 switch(hctx
->state
) {
2747 case FCGI_STATE_CONNECT_DELAYED
:
2748 /* should never happen */
2749 return HANDLER_WAIT_FOR_EVENT
;
2750 case FCGI_STATE_INIT
:
2751 /* do we have a running process for this host (max-procs) ? */
2754 for (proc
= hctx
->host
->first
;
2755 proc
&& proc
->state
!= PROC_STATE_RUNNING
;
2758 /* all children are dead */
2762 return HANDLER_ERROR
;
2767 /* check the other procs if they have a lower load */
2768 for (proc
= proc
->next
; proc
; proc
= proc
->next
) {
2769 if (proc
->state
!= PROC_STATE_RUNNING
) continue;
2770 if (proc
->load
< hctx
->proc
->load
) hctx
->proc
= proc
;
2773 if (-1 == (hctx
->fd
= fdevent_socket_nb_cloexec(host
->family
, SOCK_STREAM
, 0))) {
2774 if (errno
== EMFILE
||
2776 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2777 "wait for fd at connection:", con
->fd
);
2779 return HANDLER_WAIT_FOR_FD
;
2782 log_error_write(srv
, __FILE__
, __LINE__
, "ssdd",
2783 "socket failed:", strerror(errno
), srv
->cur_fds
, srv
->max_fds
);
2784 return HANDLER_ERROR
;
2790 fdevent_register(srv
->ev
, hctx
->fd
, fcgi_handle_fdevent
, hctx
);
2792 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
2793 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2794 "fcntl failed:", strerror(errno
));
2796 return HANDLER_ERROR
;
2799 if (hctx
->proc
->is_local
) {
2800 hctx
->pid
= hctx
->proc
->pid
;
2803 switch (fcgi_establish_connection(srv
, hctx
)) {
2804 case CONNECTION_DELAYED
:
2805 /* connection is in progress, wait for an event and call getsockopt() below */
2807 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2809 fcgi_set_state(srv
, hctx
, FCGI_STATE_CONNECT_DELAYED
);
2810 return HANDLER_WAIT_FOR_EVENT
;
2811 case CONNECTION_OVERLOADED
:
2812 /* cool down the backend, it is overloaded
2815 if (hctx
->host
->disable_time
) {
2816 log_error_write(srv
, __FILE__
, __LINE__
, "sdssdsd",
2817 "backend is overloaded; we'll disable it for", hctx
->host
->disable_time
, "seconds and send the request to another backend instead:",
2818 "reconnects:", hctx
->reconnects
,
2819 "load:", host
->load
);
2821 hctx
->proc
->disabled_until
= srv
->cur_ts
+ hctx
->host
->disable_time
;
2822 if (hctx
->proc
->state
== PROC_STATE_RUNNING
) hctx
->host
->active_procs
--;
2823 hctx
->proc
->state
= PROC_STATE_OVERLOADED
;
2826 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2827 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".overloaded"));
2829 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2831 return HANDLER_ERROR
;
2832 case CONNECTION_DEAD
:
2833 /* we got a hard error from the backend like
2834 * - ECONNREFUSED for tcp-ip sockets
2835 * - ENOENT for unix-domain-sockets
2837 * for check if the host is back in hctx->host->disable_time seconds
2840 fcgi_host_disable(srv
, hctx
);
2842 log_error_write(srv
, __FILE__
, __LINE__
, "sdssdsd",
2843 "backend died; we'll disable it for", hctx
->host
->disable_time
, "seconds and send the request to another backend instead:",
2844 "reconnects:", hctx
->reconnects
,
2845 "load:", host
->load
);
2847 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2848 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".died"));
2850 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2852 return HANDLER_ERROR
;
2854 /* everything is ok, go on */
2856 fcgi_set_state(srv
, hctx
, FCGI_STATE_PREPARE_WRITE
);
2861 case FCGI_STATE_PREPARE_WRITE
:
2862 /* ok, we have the connection */
2864 fcgi_proc_load_inc(srv
, hctx
);
2867 status_counter_inc(srv
, CONST_STR_LEN("fastcgi.requests"));
2869 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2870 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".connected"));
2872 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2874 if (hctx
->conf
.debug
) {
2875 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsd",
2877 "pid:", hctx
->proc
->pid
,
2878 "socket:", hctx
->proc
->connection_name
,
2879 "load:", hctx
->proc
->load
);
2882 /* move the proc-list entry down the list */
2883 if (hctx
->request_id
== 0) {
2884 hctx
->request_id
= 1; /* always use id 1 as we don't use multiplexing */
2886 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2887 "fcgi-request is already in use:", hctx
->request_id
);
2890 if (-1 == fcgi_create_env(srv
, hctx
, hctx
->request_id
)) return HANDLER_ERROR
;
2892 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2893 fcgi_set_state(srv
, hctx
, FCGI_STATE_WRITE
);
2895 case FCGI_STATE_WRITE
:
2896 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
2898 chunkqueue_remove_finished_chunks(hctx
->wb
);
2905 /* the connection got dropped after accept()
2906 * we don't care about that - if you accept() it, you have to handle it.
2909 log_error_write(srv
, __FILE__
, __LINE__
, "ssosb",
2910 "connection was dropped after accept() (perhaps the fastcgi process died),",
2911 "write-offset:", hctx
->wb
->bytes_out
,
2912 "socket:", hctx
->proc
->connection_name
);
2914 return HANDLER_ERROR
;
2916 log_error_write(srv
, __FILE__
, __LINE__
, "ssd",
2917 "write failed:", strerror(errno
), errno
);
2919 return HANDLER_ERROR
;
2923 if (hctx
->wb
->bytes_out
== hctx
->wb_reqlen
) {
2924 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2925 fcgi_set_state(srv
, hctx
, FCGI_STATE_READ
);
2927 off_t wblen
= hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
;
2928 if (hctx
->wb
->bytes_in
< hctx
->wb_reqlen
&& wblen
< 65536 - 16384) {
2929 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
2930 if (!(con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_POLLIN
)) {
2931 con
->conf
.stream_request_body
|= FDEVENT_STREAM_REQUEST_POLLIN
;
2932 con
->is_readable
= 1; /* trigger optimistic read from client */
2936 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2938 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2942 return HANDLER_WAIT_FOR_EVENT
;
2943 case FCGI_STATE_READ
:
2944 /* waiting for a response */
2945 return HANDLER_WAIT_FOR_EVENT
;
2947 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
2948 return HANDLER_ERROR
;
2953 /* might be called on fdevent after a connect() is delay too
2955 static handler_t
fcgi_send_request(server
*srv
, handler_ctx
*hctx
) {
2956 fcgi_extension_host
*host
;
2959 /* we don't have a host yet, choose one
2960 * -> this happens in the first round
2961 * and when the host died and we have to select a new one */
2962 if (hctx
->host
== NULL
) {
2966 /* check if the next server has no load. */
2967 ndx
= hctx
->ext
->last_used_ndx
+ 1;
2968 if(ndx
>= (int) hctx
->ext
->used
|| ndx
< 0) ndx
= 0;
2969 host
= hctx
->ext
->hosts
[ndx
];
2970 if (host
->load
> 0) {
2971 /* get backend with the least load. */
2972 for (k
= 0, ndx
= -1; k
< hctx
->ext
->used
; k
++) {
2973 host
= hctx
->ext
->hosts
[k
];
2975 /* we should have at least one proc that can do something */
2976 if (host
->active_procs
== 0) continue;
2978 if (used
== -1 || host
->load
< used
) {
2986 /* found a server */
2988 /* all hosts are down */
2990 fcgi_connection_close(srv
, hctx
);
2992 return HANDLER_FINISHED
;
2995 hctx
->ext
->last_used_ndx
= ndx
;
2996 host
= hctx
->ext
->hosts
[ndx
];
2999 * if check-local is disabled, use the uri.path handler
3003 /* init handler-context */
3005 /* we put a connection on this host, move the other new connections to other hosts
3007 * as soon as hctx->host is unassigned, decrease the load again */
3008 fcgi_host_assign(srv
, hctx
, host
);
3014 /* ok, create the request */
3015 rc
= fcgi_write_request(srv
, hctx
);
3016 if (HANDLER_ERROR
!= rc
) {
3019 plugin_data
*p
= hctx
->plugin_data
;
3020 connection
*con
= hctx
->remote_conn
;
3022 if (hctx
->state
== FCGI_STATE_INIT
||
3023 hctx
->state
== FCGI_STATE_CONNECT_DELAYED
) {
3024 fcgi_restart_dead_procs(srv
, p
, host
);
3026 /* cleanup this request and let the request handler start this request again */
3027 if (hctx
->reconnects
< 5) {
3028 fcgi_reconnect(srv
, hctx
);
3030 return HANDLER_COMEBACK
;
3032 fcgi_connection_close(srv
, hctx
);
3033 con
->http_status
= 503;
3035 return HANDLER_FINISHED
;
3038 int status
= con
->http_status
;
3039 fcgi_connection_close(srv
, hctx
);
3040 con
->http_status
= (status
== 400) ? 400 : 503;
3042 return HANDLER_FINISHED
;
3048 static handler_t
fcgi_recv_response(server
*srv
, handler_ctx
*hctx
);
3051 SUBREQUEST_FUNC(mod_fastcgi_handle_subrequest
) {
3052 plugin_data
*p
= p_d
;
3054 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
3056 if (NULL
== hctx
) return HANDLER_GO_ON
;
3059 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
3061 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
3062 && con
->file_started
) {
3063 if (chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
3064 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
3065 } else if (!(fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_IN
)) {
3066 /* optimistic read from backend, which might re-enable FDEVENT_IN */
3067 handler_t rc
= fcgi_recv_response(srv
, hctx
); /*(might invalidate hctx)*/
3068 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
3072 /* (do not receive request body before FCGI_AUTHORIZER has run or else
3073 * the request body is discarded with handler_ctx_clear() after running
3074 * the FastCGI Authorizer) */
3076 if (hctx
->fcgi_mode
!= FCGI_AUTHORIZER
3077 && (0 == hctx
->wb
->bytes_in
3078 ? con
->state
== CON_STATE_READ_POST
3079 : hctx
->wb
->bytes_in
< hctx
->wb_reqlen
)) {
3080 /*(64k - 4k to attempt to avoid temporary files
3081 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
3082 if (hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
> 65536 - 4096
3083 && (con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_BUFMIN
)){
3084 con
->conf
.stream_request_body
&= ~FDEVENT_STREAM_REQUEST_POLLIN
;
3085 if (0 != hctx
->wb
->bytes_in
) return HANDLER_WAIT_FOR_EVENT
;
3087 handler_t r
= connection_handle_read_post_state(srv
, con
);
3088 chunkqueue
*req_cq
= con
->request_content_queue
;
3089 if (0 != hctx
->wb
->bytes_in
&& !chunkqueue_is_empty(req_cq
)) {
3090 fcgi_stdin_append(srv
, con
, hctx
, hctx
->request_id
);
3091 if (fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_OUT
) {
3092 return (r
== HANDLER_GO_ON
) ? HANDLER_WAIT_FOR_EVENT
: r
;
3095 if (r
!= HANDLER_GO_ON
) return r
;
3099 return ((0 == hctx
->wb
->bytes_in
|| !chunkqueue_is_empty(hctx
->wb
))
3100 && hctx
->state
!= FCGI_STATE_CONNECT_DELAYED
)
3101 ? fcgi_send_request(srv
, hctx
)
3102 : HANDLER_WAIT_FOR_EVENT
;
3106 static handler_t
fcgi_recv_response(server
*srv
, handler_ctx
*hctx
) {
3107 connection
*con
= hctx
->remote_conn
;
3108 plugin_data
*p
= hctx
->plugin_data
;
3110 fcgi_proc
*proc
= hctx
->proc
;
3111 fcgi_extension_host
*host
= hctx
->host
;
3113 switch (fcgi_demux_response(srv
, hctx
)) {
3118 if (hctx
->fcgi_mode
== FCGI_AUTHORIZER
&&
3119 (con
->http_status
== 200 ||
3120 con
->http_status
== 0)) {
3122 * If we are here in AUTHORIZER mode then a request for authorizer
3123 * was processed already, and status 200 has been returned. We need
3124 * now to handle authorized request.
3126 buffer
*physpath
= NULL
;
3128 if (!buffer_string_is_empty(host
->docroot
)) {
3129 buffer_copy_buffer(con
->physical
.doc_root
, host
->docroot
);
3130 buffer_copy_buffer(con
->physical
.basedir
, host
->docroot
);
3132 buffer_copy_buffer(con
->physical
.path
, host
->docroot
);
3133 buffer_append_string_buffer(con
->physical
.path
, con
->uri
.path
);
3134 physpath
= con
->physical
.path
;
3137 fcgi_backend_close(srv
, hctx
);
3138 handler_ctx_clear(hctx
);
3140 /* don't do more than 6 loops here, that normally shouldn't happen */
3141 if (++con
->loops_per_request
> 5) {
3142 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "too many loops while processing request:", con
->request
.orig_uri
);
3143 con
->http_status
= 500; /* Internal Server Error */
3145 return HANDLER_FINISHED
;
3148 /* restart the request so other handlers can process it */
3150 if (physpath
) con
->physical
.path
= NULL
;
3151 connection_response_reset(srv
, con
); /*(includes con->http_status = 0)*/
3152 if (physpath
) con
->physical
.path
= physpath
; /* preserve con->physical.path with modified docroot */
3154 /*(FYI: if multiple FastCGI authorizers were to be supported,
3155 * next one could be started here instead of restarting request)*/
3158 return HANDLER_COMEBACK
;
3161 fcgi_connection_close(srv
, hctx
);
3164 return HANDLER_FINISHED
;
3166 if (proc
->pid
&& proc
->state
!= PROC_STATE_DIED
) {
3169 /* only fetch the zombie if it is not already done */
3171 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
3173 /* child is still alive */
3178 /* the child should not terminate at all */
3179 if (WIFEXITED(status
)) {
3180 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
3181 "child exited, pid:", proc
->pid
,
3182 "status:", WEXITSTATUS(status
));
3183 } else if (WIFSIGNALED(status
)) {
3184 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3188 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3189 "child died somehow:",
3193 if (hctx
->conf
.debug
) {
3194 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsd",
3195 "--- fastcgi spawning",
3196 "\n\tsocket", proc
->connection_name
,
3197 "\n\tcurrent:", 1, "/", host
->max_procs
);
3200 if (fcgi_spawn_connection(srv
, p
, host
, proc
)) {
3201 /* respawning failed, retry later */
3202 proc
->state
= PROC_STATE_DIED
;
3204 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3205 "respawning failed, will retry later");
3212 if (con
->file_started
== 0) {
3213 /* nothing has been sent out yet, try to use another child */
3215 if (hctx
->wb
->bytes_out
== 0 &&
3216 hctx
->reconnects
< 5) {
3218 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsBSBs",
3219 "response not received, request not sent",
3220 "on socket:", proc
->connection_name
,
3221 "for", con
->uri
.path
, "?", con
->uri
.query
, ", reconnecting");
3223 fcgi_reconnect(srv
, hctx
);
3225 return HANDLER_COMEBACK
;
3228 log_error_write(srv
, __FILE__
, __LINE__
, "sosbsBSBs",
3229 "response not received, request sent:", hctx
->wb
->bytes_out
,
3230 "on socket:", proc
->connection_name
,
3231 "for", con
->uri
.path
, "?", con
->uri
.query
, ", closing connection");
3233 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsBSBs",
3234 "response already sent out, but backend returned error",
3235 "on socket:", proc
->connection_name
,
3236 "for", con
->uri
.path
, "?", con
->uri
.query
, ", terminating connection");
3239 http_response_backend_error(srv
, con
);
3240 fcgi_connection_close(srv
, hctx
);
3241 return HANDLER_FINISHED
;
3244 return HANDLER_GO_ON
;
3248 static handler_t
fcgi_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
3249 handler_ctx
*hctx
= ctx
;
3250 connection
*con
= hctx
->remote_conn
;
3252 joblist_append(srv
, con
);
3254 if (revents
& FDEVENT_IN
) {
3255 handler_t rc
= fcgi_recv_response(srv
, hctx
);/*(might invalidate hctx)*/
3256 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
3259 if (revents
& FDEVENT_OUT
) {
3260 return fcgi_send_request(srv
, hctx
); /*(might invalidate hctx)*/
3263 /* perhaps this issue is already handled */
3264 if (revents
& FDEVENT_HUP
) {
3265 if (hctx
->state
== FCGI_STATE_CONNECT_DELAYED
) {
3266 /* getoptsock will catch this one (right ?)
3268 * if we are in connect we might get an EINPROGRESS
3269 * in the first call and an FDEVENT_HUP in the
3272 * FIXME: as it is a bit ugly.
3275 fcgi_send_request(srv
, hctx
);
3276 } else if (con
->file_started
) {
3277 /* drain any remaining data from kernel pipe buffers
3278 * even if (con->conf.stream_response_body
3279 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
3280 * since event loop will spin on fd FDEVENT_HUP event
3281 * until unregistered. */
3284 rc
= fcgi_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
3285 } while (rc
== HANDLER_GO_ON
); /*(unless HANDLER_GO_ON)*/
3286 return rc
; /* HANDLER_FINISHED or HANDLER_ERROR */
3288 fcgi_proc
*proc
= hctx
->proc
;
3289 log_error_write(srv
, __FILE__
, __LINE__
, "sBSbsbsd",
3290 "error: unexpected close of fastcgi connection for",
3291 con
->uri
.path
, "?", con
->uri
.query
,
3292 "(no fastcgi process on socket:", proc
->connection_name
, "?)",
3295 fcgi_connection_close(srv
, hctx
);
3297 } else if (revents
& FDEVENT_ERR
) {
3298 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3299 "fcgi: got a FDEVENT_ERR. Don't know why.");
3301 http_response_backend_error(srv
, con
);
3302 fcgi_connection_close(srv
, hctx
);
3305 return HANDLER_FINISHED
;
3310 static int fcgi_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
3312 plugin_config
*s
= p
->config_storage
[0];
3320 /* skip the first, the global context */
3321 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
3322 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
3323 s
= p
->config_storage
[i
];
3325 /* condition didn't match */
3326 if (!config_check_cond(srv
, con
, dc
)) continue;
3329 for (j
= 0; j
< dc
->value
->used
; j
++) {
3330 data_unset
*du
= dc
->value
->data
[j
];
3332 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("fastcgi.server"))) {
3336 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("fastcgi.debug"))) {
3338 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("fastcgi.map-extensions"))) {
3349 static handler_t
fcgi_check_extension(server
*srv
, connection
*con
, void *p_d
, int uri_path_handler
) {
3350 plugin_data
*p
= p_d
;
3354 fcgi_extension
*extension
= NULL
;
3355 fcgi_extension_host
*host
= NULL
;
3357 unsigned short fcgi_mode
;
3359 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
3361 fn
= uri_path_handler
? con
->uri
.path
: con
->physical
.path
;
3363 if (buffer_string_is_empty(fn
)) return HANDLER_GO_ON
;
3365 s_len
= buffer_string_length(fn
);
3367 fcgi_patch_connection(srv
, con
, p
);
3368 if (NULL
== p
->conf
.exts
) return HANDLER_GO_ON
;
3370 /* check p->conf.exts_auth list and then p->conf.ext_resp list
3371 * (skip p->conf.exts_auth if array is empty or if FCGI_AUTHORIZER already ran in this request */
3372 hctx
= con
->plugin_ctx
[p
->id
]; /*(not NULL if FCGI_AUTHORIZER ran; hctx->ext-auth check is redundant)*/
3373 fcgi_mode
= (NULL
== hctx
|| NULL
== hctx
->ext_auth
)
3374 ? 0 /* FCGI_AUTHORIZER p->conf.exts_auth will be searched next */
3375 : FCGI_AUTHORIZER
; /* FCGI_RESPONDER p->conf.exts_resp will be searched next */
3380 if (0 == fcgi_mode
) {
3381 fcgi_mode
= FCGI_AUTHORIZER
;
3382 exts
= p
->conf
.exts_auth
;
3384 fcgi_mode
= FCGI_RESPONDER
;
3385 exts
= p
->conf
.exts_resp
;
3388 if (0 == exts
->used
) continue;
3390 /* fastcgi.map-extensions maps extensions to existing fastcgi.server entries
3392 * fastcgi.map-extensions = ( ".php3" => ".php" )
3394 * fastcgi.server = ( ".php" => ... )
3398 /* check if extension-mapping matches */
3399 for (k
= 0; k
< p
->conf
.ext_mapping
->used
; k
++) {
3400 data_string
*ds
= (data_string
*)p
->conf
.ext_mapping
->data
[k
];
3401 size_t ct_len
; /* length of the config entry */
3403 if (buffer_is_empty(ds
->key
)) continue;
3405 ct_len
= buffer_string_length(ds
->key
);
3407 if (s_len
< ct_len
) continue;
3409 /* found a mapping */
3410 if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ds
->key
->ptr
, ct_len
)) {
3411 /* check if we know the extension */
3413 /* we can reuse k here */
3414 for (k
= 0; k
< exts
->used
; k
++) {
3415 extension
= exts
->exts
[k
];
3417 if (buffer_is_equal(ds
->value
, extension
->key
)) {
3422 if (k
== exts
->used
) {
3430 if (extension
== NULL
) {
3431 size_t uri_path_len
= buffer_string_length(con
->uri
.path
);
3433 /* check if extension matches */
3434 for (k
= 0; k
< exts
->used
; k
++) {
3435 size_t ct_len
; /* length of the config entry */
3436 fcgi_extension
*ext
= exts
->exts
[k
];
3438 if (buffer_is_empty(ext
->key
)) continue;
3440 ct_len
= buffer_string_length(ext
->key
);
3442 /* check _url_ in the form "/fcgi_pattern" */
3443 if (ext
->key
->ptr
[0] == '/') {
3444 if ((ct_len
<= uri_path_len
) &&
3445 (strncmp(con
->uri
.path
->ptr
, ext
->key
->ptr
, ct_len
) == 0)) {
3449 } else if ((ct_len
<= s_len
) && (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
))) {
3450 /* check extension in the form ".fcg" */
3457 } while (NULL
== extension
&& fcgi_mode
!= FCGI_RESPONDER
);
3459 /* extension doesn't match */
3460 if (NULL
== extension
) {
3461 return HANDLER_GO_ON
;
3464 /* check if we have at least one server for this extension up and running */
3465 for (k
= 0; k
< extension
->used
; k
++) {
3466 fcgi_extension_host
*h
= extension
->hosts
[k
];
3468 /* we should have at least one proc that can do something */
3469 if (h
->active_procs
== 0) {
3473 /* we found one host that is alive */
3479 /* sorry, we don't have a server alive for this ext */
3480 con
->http_status
= 500;
3483 /* only send the 'no handler' once */
3484 if (!extension
->note_is_sent
) {
3485 extension
->note_is_sent
= 1;
3487 log_error_write(srv
, __FILE__
, __LINE__
, "sBSbsbs",
3488 "all handlers for", con
->uri
.path
, "?", con
->uri
.query
,
3489 "on", extension
->key
,
3493 return HANDLER_FINISHED
;
3496 /* a note about no handler is not sent yet */
3497 extension
->note_is_sent
= 0;
3500 * if check-local is disabled, use the uri.path handler
3504 /* init handler-context */
3505 if (uri_path_handler
) {
3506 if (host
->check_local
!= 0) {
3507 return HANDLER_GO_ON
;
3509 /* do not split path info for authorizer */
3510 if (fcgi_mode
!= FCGI_AUTHORIZER
) {
3511 /* the prefix is the SCRIPT_NAME,
3512 * everything from start to the next slash
3513 * this is important for check-local = "disable"
3515 * if prefix = /admin.fcgi
3517 * /admin.fcgi/foo/bar
3519 * SCRIPT_NAME = /admin.fcgi
3520 * PATH_INFO = /foo/bar
3522 * if prefix = /fcgi-bin/
3526 * SCRIPT_NAME = /fcgi-bin/foo
3529 * if prefix = /, and fix-root-path-name is enable
3533 * SCRIPT_NAME = /fcgi-bin/foo
3539 /* the rewrite is only done for /prefix/? matches */
3540 if (host
->fix_root_path_name
&& extension
->key
->ptr
[0] == '/' && extension
->key
->ptr
[1] == '\0') {
3541 buffer_copy_string(con
->request
.pathinfo
, con
->uri
.path
->ptr
);
3542 buffer_string_set_length(con
->uri
.path
, 0);
3543 } else if (extension
->key
->ptr
[0] == '/' &&
3544 buffer_string_length(con
->uri
.path
) > buffer_string_length(extension
->key
) &&
3545 NULL
!= (pathinfo
= strchr(con
->uri
.path
->ptr
+ buffer_string_length(extension
->key
), '/'))) {
3546 /* rewrite uri.path and pathinfo */
3548 buffer_copy_string(con
->request
.pathinfo
, pathinfo
);
3549 buffer_string_set_length(con
->uri
.path
, buffer_string_length(con
->uri
.path
) - buffer_string_length(con
->request
.pathinfo
));
3555 if (!hctx
) hctx
= handler_ctx_init();
3557 hctx
->remote_conn
= con
;
3558 hctx
->plugin_data
= p
;
3560 hctx
->ext
= extension
;
3562 hctx
->fcgi_mode
= fcgi_mode
;
3563 if (fcgi_mode
== FCGI_AUTHORIZER
) {
3564 hctx
->ext_auth
= hctx
->ext
;
3567 /*hctx->conf.exts = p->conf.exts;*/
3568 /*hctx->conf.exts_auth = p->conf.exts_auth;*/
3569 /*hctx->conf.exts_resp = p->conf.exts_resp;*/
3570 /*hctx->conf.ext_mapping = p->conf.ext_mapping;*/
3571 hctx
->conf
.debug
= p
->conf
.debug
;
3573 con
->plugin_ctx
[p
->id
] = hctx
;
3577 if (con
->conf
.log_request_handling
) {
3578 log_error_write(srv
, __FILE__
, __LINE__
, "s", "handling it in mod_fastcgi");
3581 return HANDLER_GO_ON
;
3584 /* uri-path handler */
3585 static handler_t
fcgi_check_extension_1(server
*srv
, connection
*con
, void *p_d
) {
3586 return fcgi_check_extension(srv
, con
, p_d
, 1);
3589 /* start request handler */
3590 static handler_t
fcgi_check_extension_2(server
*srv
, connection
*con
, void *p_d
) {
3591 return fcgi_check_extension(srv
, con
, p_d
, 0);
3595 TRIGGER_FUNC(mod_fastcgi_handle_trigger
) {
3596 plugin_data
*p
= p_d
;
3600 /* perhaps we should kill a connect attempt after 10-15 seconds
3602 * currently we wait for the TCP timeout which is 180 seconds on Linux
3608 /* check all children if they are still up */
3610 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
3611 plugin_config
*conf
;
3614 conf
= p
->config_storage
[i
];
3617 if (NULL
== exts
) continue;
3619 for (j
= 0; j
< exts
->used
; j
++) {
3624 for (n
= 0; n
< ex
->used
; n
++) {
3627 fcgi_extension_host
*host
;
3629 host
= ex
->hosts
[n
];
3631 fcgi_restart_dead_procs(srv
, p
, host
);
3633 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
3636 if (proc
->pid
== 0) continue;
3638 switch (waitpid(proc
->pid
, &status
, WNOHANG
)) {
3640 /* child still running after timeout, good */
3643 if (errno
!= EINTR
) {
3644 /* no PID found ? should never happen */
3645 log_error_write(srv
, __FILE__
, __LINE__
, "sddss",
3646 "pid ", proc
->pid
, proc
->state
,
3647 "not found:", strerror(errno
));
3650 if (errno
== ECHILD
) {
3651 /* someone else has cleaned up for us */
3653 proc
->state
= PROC_STATE_UNSET
;
3659 /* the child should not terminate at all */
3660 if (WIFEXITED(status
)) {
3661 if (proc
->state
!= PROC_STATE_KILLED
) {
3662 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
3664 WEXITSTATUS(status
), proc
->connection_name
);
3666 } else if (WIFSIGNALED(status
)) {
3667 if (WTERMSIG(status
) != SIGTERM
) {
3668 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3673 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3674 "child died somehow:",
3678 if (proc
->state
== PROC_STATE_RUNNING
) host
->active_procs
--;
3679 proc
->state
= PROC_STATE_UNSET
;
3687 return HANDLER_GO_ON
;
3691 int mod_fastcgi_plugin_init(plugin
*p
);
3692 int mod_fastcgi_plugin_init(plugin
*p
) {
3693 p
->version
= LIGHTTPD_VERSION_ID
;
3694 p
->name
= buffer_init_string("fastcgi");
3696 p
->init
= mod_fastcgi_init
;
3697 p
->cleanup
= mod_fastcgi_free
;
3698 p
->set_defaults
= mod_fastcgi_set_defaults
;
3699 p
->connection_reset
= fcgi_connection_reset
;
3700 p
->handle_connection_close
= fcgi_connection_reset
;
3701 p
->handle_uri_clean
= fcgi_check_extension_1
;
3702 p
->handle_subrequest_start
= fcgi_check_extension_2
;
3703 p
->handle_subrequest
= mod_fastcgi_handle_subrequest
;
3704 p
->handle_trigger
= mod_fastcgi_handle_trigger
;