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 (void)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);
1630 if (hctx
->proc
&& hctx
->got_proc
) {
1631 /* after the connect the process gets a load */
1632 fcgi_proc_load_dec(srv
, hctx
);
1634 if (hctx
->conf
.debug
) {
1635 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsd",
1637 "pid:", hctx
->proc
->pid
,
1638 "socket:", hctx
->proc
->connection_name
,
1639 "load:", hctx
->proc
->load
);
1643 fcgi_host_reset(srv
, hctx
);
1647 static fcgi_extension_host
* fcgi_extension_host_get(server
*srv
, connection
*con
, plugin_data
*p
, fcgi_extension
*extension
) {
1648 fcgi_extension_host
*host
;
1649 int ndx
= extension
->last_used_ndx
+ 1;
1650 if (ndx
>= (int) extension
->used
|| ndx
< 0) ndx
= 0;
1653 /* check if the next server has no load */
1654 host
= extension
->hosts
[ndx
];
1655 if (host
->load
> 0 || host
->active_procs
== 0) {
1656 /* get backend with the least load */
1659 for (k
= 0, ndx
= -1; k
< extension
->used
; k
++) {
1660 host
= extension
->hosts
[k
];
1662 /* we should have at least one proc that can do something */
1663 if (host
->active_procs
== 0) continue;
1665 if (used
== -1 || host
->load
< used
) {
1673 /* all hosts are down */
1674 /* sorry, we don't have a server alive for this ext */
1675 con
->http_status
= 503; /* Service Unavailable */
1678 /* only send the 'no handler' once */
1679 if (!extension
->note_is_sent
) {
1680 extension
->note_is_sent
= 1;
1682 log_error_write(srv
, __FILE__
, __LINE__
, "sBSbsbs",
1683 "all handlers for", con
->uri
.path
, "?", con
->uri
.query
,
1684 "on", extension
->key
,
1689 /* found a server */
1690 extension
->last_used_ndx
= ndx
;
1691 return extension
->hosts
[ndx
];
1694 static void fcgi_connection_close(server
*srv
, handler_ctx
*hctx
) {
1698 p
= hctx
->plugin_data
;
1699 con
= hctx
->remote_conn
;
1701 fcgi_backend_close(srv
, hctx
);
1702 handler_ctx_free(hctx
);
1703 con
->plugin_ctx
[p
->id
] = NULL
;
1705 /* finish response (if not already con->file_started, con->file_finished) */
1706 if (con
->mode
== p
->id
) {
1707 http_response_backend_done(srv
, con
);
1711 static handler_t
fcgi_reconnect(server
*srv
, handler_ctx
*hctx
) {
1712 fcgi_backend_close(srv
, hctx
);
1714 hctx
->host
= fcgi_extension_host_get(srv
, hctx
->remote_conn
, hctx
->plugin_data
, hctx
->ext
);
1715 if (NULL
== hctx
->host
) return HANDLER_FINISHED
;
1717 fcgi_host_assign(srv
, hctx
, hctx
->host
);
1718 hctx
->request_id
= 0;
1719 fcgi_set_state(srv
, hctx
, FCGI_STATE_INIT
);
1720 return HANDLER_COMEBACK
;
1724 static handler_t
fcgi_connection_reset(server
*srv
, connection
*con
, void *p_d
) {
1725 plugin_data
*p
= p_d
;
1726 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
1727 if (hctx
) fcgi_connection_close(srv
, hctx
);
1729 return HANDLER_GO_ON
;
1733 static int fcgi_env_add(void *venv
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
1737 size_t len_enc_len
= 0;
1739 if (!key
|| !val
) return -1;
1741 len
= key_len
+ val_len
;
1743 len
+= key_len
> 127 ? 4 : 1;
1744 len
+= val_len
> 127 ? 4 : 1;
1746 if (buffer_string_length(env
) + len
>= FCGI_MAX_LENGTH
) {
1748 * we can't append more headers, ignore it
1754 * field length can be 31bit max
1756 * HINT: this can't happen as FCGI_MAX_LENGTH is only 16bit
1758 force_assert(key_len
< 0x7fffffffu
);
1759 force_assert(val_len
< 0x7fffffffu
);
1761 buffer_string_prepare_append(env
, len
);
1763 if (key_len
> 127) {
1764 len_enc
[len_enc_len
++] = ((key_len
>> 24) & 0xff) | 0x80;
1765 len_enc
[len_enc_len
++] = (key_len
>> 16) & 0xff;
1766 len_enc
[len_enc_len
++] = (key_len
>> 8) & 0xff;
1767 len_enc
[len_enc_len
++] = (key_len
>> 0) & 0xff;
1769 len_enc
[len_enc_len
++] = (key_len
>> 0) & 0xff;
1772 if (val_len
> 127) {
1773 len_enc
[len_enc_len
++] = ((val_len
>> 24) & 0xff) | 0x80;
1774 len_enc
[len_enc_len
++] = (val_len
>> 16) & 0xff;
1775 len_enc
[len_enc_len
++] = (val_len
>> 8) & 0xff;
1776 len_enc
[len_enc_len
++] = (val_len
>> 0) & 0xff;
1778 len_enc
[len_enc_len
++] = (val_len
>> 0) & 0xff;
1781 buffer_append_string_len(env
, len_enc
, len_enc_len
);
1782 buffer_append_string_len(env
, key
, key_len
);
1783 buffer_append_string_len(env
, val
, val_len
);
1788 static int fcgi_header(FCGI_Header
* header
, unsigned char type
, int request_id
, int contentLength
, unsigned char paddingLength
) {
1789 force_assert(contentLength
<= FCGI_MAX_LENGTH
);
1791 header
->version
= FCGI_VERSION_1
;
1792 header
->type
= type
;
1793 header
->requestIdB0
= request_id
& 0xff;
1794 header
->requestIdB1
= (request_id
>> 8) & 0xff;
1795 header
->contentLengthB0
= contentLength
& 0xff;
1796 header
->contentLengthB1
= (contentLength
>> 8) & 0xff;
1797 header
->paddingLength
= paddingLength
;
1798 header
->reserved
= 0;
1805 CONNECTION_DELAYED
, /* retry after event, take same host */
1806 CONNECTION_OVERLOADED
, /* disable for 1 second, take another backend */
1807 CONNECTION_DEAD
/* disable for 60 seconds, take another backend */
1808 } connection_result_t
;
1810 static connection_result_t
fcgi_establish_connection(server
*srv
, handler_ctx
*hctx
) {
1811 struct sockaddr
*fcgi_addr
;
1812 struct sockaddr_in fcgi_addr_in
;
1813 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1814 struct sockaddr_in6 fcgi_addr_in6
;
1816 #ifdef HAVE_SYS_UN_H
1817 struct sockaddr_un fcgi_addr_un
;
1821 fcgi_extension_host
*host
= hctx
->host
;
1822 fcgi_proc
*proc
= hctx
->proc
;
1823 int fcgi_fd
= hctx
->fd
;
1825 if (!buffer_string_is_empty(proc
->unixsocket
)) {
1826 #ifdef HAVE_SYS_UN_H
1827 /* use the unix domain socket */
1828 memset(&fcgi_addr_un
, 0, sizeof(fcgi_addr_un
));
1829 fcgi_addr_un
.sun_family
= AF_UNIX
;
1830 if (buffer_string_length(proc
->unixsocket
) + 1 > sizeof(fcgi_addr_un
.sun_path
)) {
1831 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
1832 "ERROR: Unix Domain socket filename too long:",
1836 memcpy(fcgi_addr_un
.sun_path
, proc
->unixsocket
->ptr
, buffer_string_length(proc
->unixsocket
) + 1);
1839 servlen
= SUN_LEN(&fcgi_addr_un
);
1842 servlen
= buffer_string_length(proc
->unixsocket
) + 1 + sizeof(fcgi_addr_un
.sun_family
);
1844 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_un
;
1846 if (buffer_string_is_empty(proc
->connection_name
)) {
1847 /* on remote spawing we have to set the connection-name now */
1848 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("unix:"));
1849 buffer_append_string_buffer(proc
->connection_name
, proc
->unixsocket
);
1852 return CONNECTION_DEAD
;
1854 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1855 } else if (host
->family
== AF_INET6
&& !buffer_string_is_empty(host
->host
)) {
1856 memset(&fcgi_addr_in6
, 0, sizeof(fcgi_addr_in6
));
1857 fcgi_addr_in6
.sin6_family
= AF_INET6
;
1858 inet_pton(AF_INET6
, host
->host
->ptr
, (char *) &fcgi_addr_in6
.sin6_addr
);
1859 fcgi_addr_in6
.sin6_port
= htons(proc
->port
);
1860 servlen
= sizeof(fcgi_addr_in6
);
1861 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_in6
;
1864 memset(&fcgi_addr_in
, 0, sizeof(fcgi_addr_in
));
1865 fcgi_addr_in
.sin_family
= AF_INET
;
1866 if (!buffer_string_is_empty(host
->host
)) {
1867 if (0 == inet_aton(host
->host
->ptr
, &(fcgi_addr_in
.sin_addr
))) {
1868 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1869 "converting IP address failed for", host
->host
,
1870 "\nBe sure to specify an IP address here");
1872 return CONNECTION_DEAD
;
1875 fcgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
1877 fcgi_addr_in
.sin_port
= htons(proc
->port
);
1878 servlen
= sizeof(fcgi_addr_in
);
1880 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_in
;
1883 if (buffer_string_is_empty(proc
->unixsocket
)) {
1884 if (buffer_string_is_empty(proc
->connection_name
)) {
1885 /* on remote spawing we have to set the connection-name now */
1886 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("tcp:"));
1887 if (!buffer_string_is_empty(host
->host
)) {
1888 buffer_append_string_buffer(proc
->connection_name
, host
->host
);
1890 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN("localhost"));
1892 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN(":"));
1893 buffer_append_int(proc
->connection_name
, proc
->port
);
1897 if (-1 == connect(fcgi_fd
, fcgi_addr
, servlen
)) {
1898 if (errno
== EINPROGRESS
||
1899 errno
== EALREADY
||
1901 if (hctx
->conf
.debug
> 2) {
1902 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1903 "connect delayed; will continue later:", proc
->connection_name
);
1906 return CONNECTION_DELAYED
;
1907 } else if (errno
== EAGAIN
) {
1908 if (hctx
->conf
.debug
) {
1909 log_error_write(srv
, __FILE__
, __LINE__
, "sbsd",
1910 "This means that you have more incoming requests than your FastCGI backend can handle in parallel."
1911 "It might help to spawn more FastCGI backends or PHP children; if not, decrease server.max-connections."
1912 "The load for this FastCGI backend", proc
->connection_name
, "is", proc
->load
);
1915 return CONNECTION_OVERLOADED
;
1917 log_error_write(srv
, __FILE__
, __LINE__
, "sssb",
1919 strerror(errno
), "on",
1920 proc
->connection_name
);
1922 return CONNECTION_DEAD
;
1926 hctx
->reconnects
= 0;
1927 if (hctx
->conf
.debug
> 1) {
1928 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1929 "connect succeeded: ", fcgi_fd
);
1932 return CONNECTION_OK
;
1935 static void fcgi_stdin_append(server
*srv
, connection
*con
, handler_ctx
*hctx
, int request_id
) {
1937 chunkqueue
*req_cq
= con
->request_content_queue
;
1938 off_t offset
, weWant
;
1939 const off_t req_cqlen
= req_cq
->bytes_in
- req_cq
->bytes_out
;
1941 /* something to send ? */
1942 for (offset
= 0; offset
!= req_cqlen
; offset
+= weWant
) {
1943 weWant
= req_cqlen
- offset
> FCGI_MAX_LENGTH
? FCGI_MAX_LENGTH
: req_cqlen
- offset
;
1945 /* we announce toWrite octets
1946 * now take all request_content chunks available
1949 fcgi_header(&(header
), FCGI_STDIN
, request_id
, weWant
, 0);
1950 chunkqueue_append_mem(hctx
->wb
, (const char *)&header
, sizeof(header
));
1951 hctx
->wb_reqlen
+= sizeof(header
);
1953 if (hctx
->conf
.debug
> 10) {
1954 log_error_write(srv
, __FILE__
, __LINE__
, "soso", "tosend:", offset
, "/", req_cqlen
);
1957 chunkqueue_steal(hctx
->wb
, req_cq
, weWant
);
1958 /*(hctx->wb_reqlen already includes content_length)*/
1961 if (hctx
->wb
->bytes_in
== hctx
->wb_reqlen
) {
1962 /* terminate STDIN */
1963 fcgi_header(&(header
), FCGI_STDIN
, request_id
, 0, 0);
1964 chunkqueue_append_mem(hctx
->wb
, (const char *)&header
, sizeof(header
));
1965 hctx
->wb_reqlen
+= (int)sizeof(header
);
1969 static int fcgi_create_env(server
*srv
, handler_ctx
*hctx
, int request_id
) {
1970 FCGI_BeginRequestRecord beginRecord
;
1973 plugin_data
*p
= hctx
->plugin_data
;
1974 fcgi_extension_host
*host
= hctx
->host
;
1976 connection
*con
= hctx
->remote_conn
;
1978 http_cgi_opts opts
= {
1979 (hctx
->fcgi_mode
== FCGI_AUTHORIZER
),
1980 host
->break_scriptfilename_for_php
,
1982 host
->strip_request_uri
1985 /* send FCGI_BEGIN_REQUEST */
1987 fcgi_header(&(beginRecord
.header
), FCGI_BEGIN_REQUEST
, request_id
, sizeof(beginRecord
.body
), 0);
1988 beginRecord
.body
.roleB0
= hctx
->fcgi_mode
;
1989 beginRecord
.body
.roleB1
= 0;
1990 beginRecord
.body
.flags
= 0;
1991 memset(beginRecord
.body
.reserved
, 0, sizeof(beginRecord
.body
.reserved
));
1993 /* send FCGI_PARAMS */
1994 buffer_string_prepare_copy(p
->fcgi_env
, 1023);
1996 if (0 != http_cgi_headers(srv
, con
, &opts
, fcgi_env_add
, p
->fcgi_env
)) {
1997 con
->http_status
= 400;
2000 buffer
*b
= buffer_init();
2002 buffer_copy_string_len(b
, (const char *)&beginRecord
, sizeof(beginRecord
));
2004 fcgi_header(&(header
), FCGI_PARAMS
, request_id
, buffer_string_length(p
->fcgi_env
), 0);
2005 buffer_append_string_len(b
, (const char *)&header
, sizeof(header
));
2006 buffer_append_string_buffer(b
, p
->fcgi_env
);
2008 fcgi_header(&(header
), FCGI_PARAMS
, request_id
, 0, 0);
2009 buffer_append_string_len(b
, (const char *)&header
, sizeof(header
));
2011 hctx
->wb_reqlen
= buffer_string_length(b
);
2012 chunkqueue_append_buffer(hctx
->wb
, b
);
2016 hctx
->wb_reqlen
+= con
->request
.content_length
;/* (eventual) (minimal) total request size, not necessarily including all fcgi_headers around content length yet */
2017 fcgi_stdin_append(srv
, con
, hctx
, request_id
);
2022 static int fcgi_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
) {
2025 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2026 fcgi_extension_host
*host
= hctx
->host
;
2027 int have_sendfile2
= 0;
2028 off_t sendfile2_content_length
= 0;
2033 for (s
= in
->ptr
; NULL
!= (ns
= strchr(s
, '\n')); s
= ns
+ 1) {
2037 /* a good day. Someone has read the specs and is sending a \r\n to us */
2047 if (NULL
== (value
= strchr(s
, ':'))) {
2048 /* we expect: "<key>: <value>\n" */
2052 key_len
= value
- key
;
2056 while (*value
== ' ' || *value
== '\t') value
++;
2058 if (hctx
->fcgi_mode
!= FCGI_AUTHORIZER
||
2059 !(con
->http_status
== 0 ||
2060 con
->http_status
== 200)) {
2061 /* authorizers shouldn't affect the response headers sent back to the client */
2063 /* don't forward Status: */
2064 if (0 != strncasecmp(key
, "Status", key_len
)) {
2066 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
2067 ds
= data_response_init();
2069 buffer_copy_string_len(ds
->key
, key
, key_len
);
2070 buffer_copy_string(ds
->value
, value
);
2072 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
2076 if (hctx
->fcgi_mode
== FCGI_AUTHORIZER
&&
2078 0 == strncasecmp(key
, CONST_STR_LEN("Variable-"))) {
2080 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->environment
, TYPE_STRING
))) {
2081 ds
= data_response_init();
2083 buffer_copy_string_len(ds
->key
, key
+ 9, key_len
- 9);
2084 buffer_copy_string(ds
->value
, value
);
2086 array_insert_unique(con
->environment
, (data_unset
*)ds
);
2091 if (0 == strncasecmp(key
, "Date", key_len
)) {
2092 con
->parsed_response
|= HTTP_DATE
;
2096 if (0 == strncasecmp(key
, "Status", key_len
)) {
2097 int status
= strtol(value
, NULL
, 10);
2098 if (status
>= 100 && status
< 1000) {
2099 con
->http_status
= status
;
2100 con
->parsed_response
|= HTTP_STATUS
;
2102 con
->http_status
= 502;
2107 if (0 == strncasecmp(key
, "Location", key_len
)) {
2108 con
->parsed_response
|= HTTP_LOCATION
;
2112 if (0 == strncasecmp(key
, "Connection", key_len
)) {
2113 con
->response
.keep_alive
= (0 == strcasecmp(value
, "Keep-Alive")) ? 1 : 0;
2114 con
->parsed_response
|= HTTP_CONNECTION
;
2118 if (host
->xsendfile_allow
&& 0 == strncasecmp(key
, "X-Sendfile2", key_len
) && hctx
->send_content_body
) {
2123 char *filename
, *range
;
2124 stat_cache_entry
*sce
;
2125 off_t begin_range
, end_range
, range_len
;
2127 while (' ' == *pos
) pos
++;
2131 if (NULL
== (range
= strchr(pos
, ' '))) {
2133 if (hctx
->conf
.debug
) {
2134 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't find range after filename:", filename
);
2138 buffer_copy_string_len(srv
->tmp_buf
, filename
, range
- filename
);
2140 /* find end of range */
2141 for (pos
= ++range
; *pos
&& *pos
!= ' ' && *pos
!= ','; pos
++) ;
2143 buffer_urldecode_path(srv
->tmp_buf
);
2144 buffer_path_simplify(srv
->tmp_buf
, srv
->tmp_buf
);
2145 if (con
->conf
.force_lowercase_filenames
) {
2146 buffer_to_lower(srv
->tmp_buf
);
2148 if (host
->xsendfile_docroot
->used
) {
2149 size_t i
, xlen
= buffer_string_length(srv
->tmp_buf
);
2150 for (i
= 0; i
< host
->xsendfile_docroot
->used
; ++i
) {
2151 data_string
*ds
= (data_string
*)host
->xsendfile_docroot
->data
[i
];
2152 size_t dlen
= buffer_string_length(ds
->value
);
2154 && (!con
->conf
.force_lowercase_filenames
2155 ? 0 == memcmp(srv
->tmp_buf
->ptr
, ds
->value
->ptr
, dlen
)
2156 : 0 == strncasecmp(srv
->tmp_buf
->ptr
, ds
->value
->ptr
, dlen
))) {
2160 if (i
== host
->xsendfile_docroot
->used
) {
2161 log_error_write(srv
, __FILE__
, __LINE__
, "SBs",
2162 "X-Sendfile2 (", srv
->tmp_buf
,
2163 ") not under configured x-sendfile-docroot(s)");
2168 if (HANDLER_ERROR
== stat_cache_get_entry(srv
, con
, srv
->tmp_buf
, &sce
)) {
2169 if (hctx
->conf
.debug
) {
2170 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2171 "send-file error: couldn't get stat_cache entry for X-Sendfile2:",
2175 } else if (!S_ISREG(sce
->st
.st_mode
)) {
2176 if (hctx
->conf
.debug
) {
2177 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2178 "send-file error: wrong filetype for X-Sendfile2:",
2183 /* found the file */
2186 end_range
= sce
->st
.st_size
- 1;
2190 begin_range
= strtoll(range
, &rpos
, 10);
2191 if (errno
!= 0 || begin_range
< 0 || rpos
== range
) goto range_failed
;
2192 if ('-' != *rpos
++) goto range_failed
;
2195 end_range
= strtoll(range
, &rpos
, 10);
2196 if (errno
!= 0 || end_range
< 0 || rpos
== range
) goto range_failed
;
2198 if (rpos
!= pos
) goto range_failed
;
2203 if (hctx
->conf
.debug
) {
2204 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't decode range after filename:", filename
);
2211 /* no parameters accepted */
2213 while (*pos
== ' ') pos
++;
2214 if (*pos
!= '\0' && *pos
!= ',') return 502;
2216 range_len
= end_range
- begin_range
+ 1;
2217 if (range_len
< 0) return 502;
2218 if (range_len
!= 0) {
2219 if (0 != http_chunk_append_file_range(srv
, con
, srv
->tmp_buf
, begin_range
, range_len
)) {
2223 sendfile2_content_length
+= range_len
;
2225 if (*pos
== ',') pos
++;
2230 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
2231 con
->response
.content_length
= strtoul(value
, NULL
, 10);
2232 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
2234 if (con
->response
.content_length
< 0) con
->response
.content_length
= 0;
2242 if (have_sendfile2
) {
2245 /* fix content-length */
2246 if (NULL
== (dcls
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
2247 dcls
= data_response_init();
2250 buffer_copy_string_len(dcls
->key
, "Content-Length", sizeof("Content-Length")-1);
2251 buffer_copy_int(dcls
->value
, sendfile2_content_length
);
2252 array_replace(con
->response
.headers
, (data_unset
*)dcls
);
2254 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
2255 con
->response
.content_length
= sendfile2_content_length
;
2259 /* CGI/1.1 rev 03 - 7.2.1.2 */
2260 if ((con
->parsed_response
& HTTP_LOCATION
) &&
2261 !(con
->parsed_response
& HTTP_STATUS
)) {
2262 con
->http_status
= 302;
2274 } fastcgi_response_packet
;
2276 static int fastcgi_get_packet(server
*srv
, handler_ctx
*hctx
, fastcgi_response_packet
*packet
) {
2280 FCGI_Header
*header
;
2282 if (!hctx
->rb
->first
) return -1;
2284 packet
->b
= buffer_init();
2287 packet
->padding
= 0;
2288 packet
->request_id
= 0;
2290 offset
= 0; toread
= 8;
2291 /* get at least the FastCGI header */
2292 for (c
= hctx
->rb
->first
; c
; c
= c
->next
) {
2293 size_t weHave
= buffer_string_length(c
->mem
) - c
->offset
;
2295 if (weHave
> toread
) weHave
= toread
;
2297 buffer_append_string_len(packet
->b
, c
->mem
->ptr
+ c
->offset
, weHave
);
2299 offset
= weHave
; /* skip offset bytes in chunk for "real" data */
2301 if (0 == toread
) break;
2304 if (buffer_string_length(packet
->b
) < sizeof(FCGI_Header
)) {
2306 if (hctx
->conf
.debug
) {
2307 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");
2310 buffer_free(packet
->b
);
2315 /* we have at least a header, now check how much me have to fetch */
2316 header
= (FCGI_Header
*)(packet
->b
->ptr
);
2318 packet
->len
= (header
->contentLengthB0
| (header
->contentLengthB1
<< 8)) + header
->paddingLength
;
2319 packet
->request_id
= (header
->requestIdB0
| (header
->requestIdB1
<< 8));
2320 packet
->type
= header
->type
;
2321 packet
->padding
= header
->paddingLength
;
2323 /* ->b should only be the content */
2324 buffer_string_set_length(packet
->b
, 0);
2327 /* copy the content */
2328 for (; c
&& (buffer_string_length(packet
->b
) < packet
->len
); c
= c
->next
) {
2329 size_t weWant
= packet
->len
- buffer_string_length(packet
->b
);
2330 size_t weHave
= buffer_string_length(c
->mem
) - c
->offset
- offset
;
2332 if (weHave
> weWant
) weHave
= weWant
;
2334 buffer_append_string_len(packet
->b
, c
->mem
->ptr
+ c
->offset
+ offset
, weHave
);
2336 /* we only skipped the first bytes as they belonged to the fcgi header */
2340 if (buffer_string_length(packet
->b
) < packet
->len
) {
2341 /* we didn't get the full packet */
2343 buffer_free(packet
->b
);
2347 buffer_string_set_length(packet
->b
, buffer_string_length(packet
->b
) - packet
->padding
);
2350 chunkqueue_mark_written(hctx
->rb
, packet
->len
+ sizeof(FCGI_Header
));
2355 static int fcgi_demux_response(server
*srv
, handler_ctx
*hctx
) {
2360 plugin_data
*p
= hctx
->plugin_data
;
2361 connection
*con
= hctx
->remote_conn
;
2362 int fcgi_fd
= hctx
->fd
;
2363 fcgi_extension_host
*host
= hctx
->host
;
2364 fcgi_proc
*proc
= hctx
->proc
;
2367 * check how much we have to read
2369 #if !defined(_WIN32) && !defined(__CYGWIN__)
2370 if (ioctl(hctx
->fd
, FIONREAD
, &toread
)) {
2371 if (errno
== EAGAIN
) {
2372 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2375 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2376 "unexpected end-of-file (perhaps the fastcgi process died):",
2388 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)) {
2389 off_t cqlen
= chunkqueue_length(hctx
->rb
);
2390 if (cqlen
+ toread
> 65536 + (int)sizeof(FCGI_Header
)) { /*(max size of FastCGI packet + 1)*/
2391 if (cqlen
< 65536 + (int)sizeof(FCGI_Header
)) {
2392 toread
= 65536 + (int)sizeof(FCGI_Header
) - cqlen
;
2393 } else { /* should not happen */
2394 toread
= toread
< 1024 ? toread
: 1024;
2399 chunkqueue_get_memory(hctx
->rb
, &mem
, &mem_len
, 0, toread
);
2400 r
= read(hctx
->fd
, mem
, mem_len
);
2401 chunkqueue_use_memory(hctx
->rb
, r
> 0 ? r
: 0);
2404 if (errno
== EAGAIN
) {
2405 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2408 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
2409 "unexpected end-of-file (perhaps the fastcgi process died):",
2410 fcgi_fd
, strerror(errno
));
2415 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsb",
2416 "unexpected end-of-file (perhaps the fastcgi process died):",
2418 "socket:", proc
->connection_name
);
2424 * parse the fastcgi packets and forward the content to the write-queue
2428 fastcgi_response_packet packet
;
2430 /* check if we have at least one packet */
2431 if (0 != fastcgi_get_packet(srv
, hctx
, &packet
)) {
2432 /* no full packet */
2436 switch(packet
.type
) {
2438 if (packet
.len
== 0) break;
2440 /* is the header already finished */
2441 if (0 == con
->file_started
) {
2445 /* search for header terminator
2447 * if we start with \r\n check if last packet terminated with \r\n
2448 * if we start with \n check if last packet terminated with \n
2449 * search for \r\n\r\n
2453 buffer_append_string_buffer(hctx
->response_header
, packet
.b
);
2455 if (NULL
!= (c
= buffer_search_string_len(hctx
->response_header
, CONST_STR_LEN("\r\n\r\n")))) {
2456 char *hend
= c
+ 4; /* header end == body start */
2457 size_t hlen
= hend
- hctx
->response_header
->ptr
;
2458 buffer_copy_string_len(packet
.b
, hend
, buffer_string_length(hctx
->response_header
) - hlen
);
2459 buffer_string_set_length(hctx
->response_header
, hlen
);
2460 } else if (NULL
!= (c
= buffer_search_string_len(hctx
->response_header
, CONST_STR_LEN("\n\n")))) {
2461 char *hend
= c
+ 2; /* header end == body start */
2462 size_t hlen
= hend
- hctx
->response_header
->ptr
;
2463 buffer_copy_string_len(packet
.b
, hend
, buffer_string_length(hctx
->response_header
) - hlen
);
2464 buffer_string_set_length(hctx
->response_header
, hlen
);
2466 /* no luck, no header found */
2467 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
2468 if (buffer_string_length(hctx
->response_header
) > MAX_HTTP_REQUEST_HEADER
) {
2469 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "response headers too large for", con
->uri
.path
);
2470 con
->http_status
= 502; /* Bad Gateway */
2477 /* parse the response header */
2478 if ((ret
= fcgi_response_parse(srv
, con
, p
, hctx
->response_header
))) {
2479 if (200 != ret
) { /*(200 returned for X-Sendfile2 handled)*/
2480 con
->http_status
= ret
;
2483 con
->file_started
= 1;
2484 hctx
->send_content_body
= 0;
2489 con
->file_started
= 1;
2491 if (hctx
->fcgi_mode
== FCGI_AUTHORIZER
&&
2492 (con
->http_status
== 0 ||
2493 con
->http_status
== 200)) {
2494 /* a authorizer with approved the static request, ignore the content here */
2495 hctx
->send_content_body
= 0;
2498 if (host
->xsendfile_allow
&& hctx
->send_content_body
&&
2499 (NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "X-LIGHTTPD-send-file"))
2500 || NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "X-Sendfile")))) {
2501 http_response_xsendfile(srv
, con
, ds
->value
, host
->xsendfile_docroot
);
2502 if (con
->mode
== DIRECT
) {
2506 hctx
->send_content_body
= 0; /* ignore the content */
2511 if (hctx
->send_content_body
&& !buffer_string_is_empty(packet
.b
)) {
2512 if (0 != http_chunk_append_buffer(srv
, con
, packet
.b
)) {
2513 /* error writing to tempfile;
2514 * truncate response or send 500 if nothing sent yet */
2518 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
2519 && chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
2520 if (!con
->is_writable
) {
2521 /*(defer removal of FDEVENT_IN interest since
2522 * connection_state_machine() might be able to send data
2523 * immediately, unless !con->is_writable, where
2524 * connection_state_machine() might not loop back to call
2525 * mod_fastcgi_handle_subrequest())*/
2526 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2532 if (packet
.len
== 0) break;
2534 log_error_write_multiline_buffer(srv
, __FILE__
, __LINE__
, packet
.b
, "s",
2538 case FCGI_END_REQUEST
:
2542 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2543 "FastCGI: header.type not handled: ", packet
.type
);
2546 buffer_free(packet
.b
);
2552 static int fcgi_restart_dead_procs(server
*srv
, plugin_data
*p
, fcgi_extension_host
*host
) {
2555 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2558 if (p
->conf
.debug
> 2) {
2559 log_error_write(srv
, __FILE__
, __LINE__
, "sbdddd",
2561 proc
->connection_name
,
2569 * if the remote side is overloaded, we check back after <n> seconds
2572 switch (proc
->state
) {
2573 case PROC_STATE_KILLED
:
2574 case PROC_STATE_UNSET
:
2575 /* this should never happen as long as adaptive spawing is disabled */
2579 case PROC_STATE_RUNNING
:
2581 case PROC_STATE_OVERLOADED
:
2582 if (srv
->cur_ts
<= proc
->disabled_until
) break;
2584 proc
->state
= PROC_STATE_RUNNING
;
2585 host
->active_procs
++;
2587 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2588 "fcgi-server re-enabled:",
2589 host
->host
, host
->port
,
2592 case PROC_STATE_DIED_WAIT_FOR_PID
:
2593 /* non-local procs don't have PIDs to wait for */
2594 if (!proc
->is_local
) {
2595 proc
->state
= PROC_STATE_DIED
;
2597 /* the child should not terminate at all */
2600 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2602 /* child is still alive */
2603 if (srv
->cur_ts
<= proc
->disabled_until
) break;
2605 proc
->state
= PROC_STATE_RUNNING
;
2606 host
->active_procs
++;
2608 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2609 "fcgi-server re-enabled:",
2610 host
->host
, host
->port
,
2614 if (errno
== EINTR
) continue;
2616 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2617 "child died somehow, waitpid failed:",
2619 proc
->state
= PROC_STATE_DIED
;
2622 if (WIFEXITED(status
)) {
2624 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2625 "child exited, pid:", proc
->pid
,
2626 "status:", WEXITSTATUS(status
));
2628 } else if (WIFSIGNALED(status
)) {
2629 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2633 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2634 "child died somehow:",
2638 proc
->state
= PROC_STATE_DIED
;
2645 /* fall through if we have a dead proc now */
2646 if (proc
->state
!= PROC_STATE_DIED
) break;
2648 case PROC_STATE_DIED
:
2649 /* local procs get restarted by us,
2650 * remote ones hopefully by the admin */
2652 if (!buffer_string_is_empty(host
->bin_path
)) {
2653 /* we still have connections bound to this proc,
2654 * let them terminate first */
2655 if (proc
->load
!= 0) break;
2657 /* restart the child */
2659 if (p
->conf
.debug
) {
2660 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsd",
2661 "--- fastcgi spawning",
2662 "\n\tsocket", proc
->connection_name
,
2663 "\n\tcurrent:", 1, "/", host
->max_procs
);
2666 if (fcgi_spawn_connection(srv
, p
, host
, proc
)) {
2667 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2668 "ERROR: spawning fcgi failed.");
2669 return HANDLER_ERROR
;
2672 if (srv
->cur_ts
<= proc
->disabled_until
) break;
2674 proc
->state
= PROC_STATE_RUNNING
;
2675 host
->active_procs
++;
2677 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2678 "fcgi-server re-enabled:",
2679 proc
->connection_name
);
2688 static handler_t
fcgi_write_request(server
*srv
, handler_ctx
*hctx
) {
2689 plugin_data
*p
= hctx
->plugin_data
;
2690 fcgi_extension_host
*host
= hctx
->host
;
2691 connection
*con
= hctx
->remote_conn
;
2696 /* we can't handle this in the switch as we have to fall through in it */
2697 if (hctx
->state
== FCGI_STATE_CONNECT_DELAYED
) {
2699 socklen_t socket_error_len
= sizeof(socket_error
);
2701 /* try to finish the connect() */
2702 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
2703 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2704 "getsockopt failed:", strerror(errno
));
2706 fcgi_host_disable(srv
, hctx
);
2708 return HANDLER_ERROR
;
2710 if (socket_error
!= 0) {
2711 if (!hctx
->proc
->is_local
|| hctx
->conf
.debug
) {
2712 /* local procs get restarted */
2714 log_error_write(srv
, __FILE__
, __LINE__
, "sssb",
2715 "establishing connection failed:", strerror(socket_error
),
2716 "socket:", hctx
->proc
->connection_name
);
2719 fcgi_host_disable(srv
, hctx
);
2720 log_error_write(srv
, __FILE__
, __LINE__
, "sdssdsd",
2721 "backend is overloaded; we'll disable it for", hctx
->host
->disable_time
, "seconds and send the request to another backend instead:",
2722 "reconnects:", hctx
->reconnects
,
2723 "load:", host
->load
);
2725 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2726 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".died"));
2728 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2730 return HANDLER_ERROR
;
2732 /* go on with preparing the request */
2733 hctx
->state
= FCGI_STATE_PREPARE_WRITE
;
2737 switch(hctx
->state
) {
2738 case FCGI_STATE_CONNECT_DELAYED
:
2739 /* should never happen */
2740 return HANDLER_WAIT_FOR_EVENT
;
2741 case FCGI_STATE_INIT
:
2742 /* do we have a running process for this host (max-procs) ? */
2745 for (proc
= hctx
->host
->first
;
2746 proc
&& proc
->state
!= PROC_STATE_RUNNING
;
2749 /* all children are dead */
2753 return HANDLER_ERROR
;
2758 /* check the other procs if they have a lower load */
2759 for (proc
= proc
->next
; proc
; proc
= proc
->next
) {
2760 if (proc
->state
!= PROC_STATE_RUNNING
) continue;
2761 if (proc
->load
< hctx
->proc
->load
) hctx
->proc
= proc
;
2764 if (-1 == (hctx
->fd
= fdevent_socket_nb_cloexec(host
->family
, SOCK_STREAM
, 0))) {
2765 if (errno
== EMFILE
||
2767 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2768 "wait for fd at connection:", con
->fd
);
2770 return HANDLER_WAIT_FOR_FD
;
2773 log_error_write(srv
, __FILE__
, __LINE__
, "ssdd",
2774 "socket failed:", strerror(errno
), srv
->cur_fds
, srv
->max_fds
);
2775 return HANDLER_ERROR
;
2781 fdevent_register(srv
->ev
, hctx
->fd
, fcgi_handle_fdevent
, hctx
);
2783 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
2784 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2785 "fcntl failed:", strerror(errno
));
2787 return HANDLER_ERROR
;
2790 if (hctx
->proc
->is_local
) {
2791 hctx
->pid
= hctx
->proc
->pid
;
2794 switch (fcgi_establish_connection(srv
, hctx
)) {
2795 case CONNECTION_DELAYED
:
2796 /* connection is in progress, wait for an event and call getsockopt() below */
2798 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2800 fcgi_set_state(srv
, hctx
, FCGI_STATE_CONNECT_DELAYED
);
2801 return HANDLER_WAIT_FOR_EVENT
;
2802 case CONNECTION_OVERLOADED
:
2803 /* cool down the backend, it is overloaded
2806 if (hctx
->host
->disable_time
) {
2807 log_error_write(srv
, __FILE__
, __LINE__
, "sdssdsd",
2808 "backend is overloaded; we'll disable it for", hctx
->host
->disable_time
, "seconds and send the request to another backend instead:",
2809 "reconnects:", hctx
->reconnects
,
2810 "load:", host
->load
);
2812 hctx
->proc
->disabled_until
= srv
->cur_ts
+ hctx
->host
->disable_time
;
2813 if (hctx
->proc
->state
== PROC_STATE_RUNNING
) hctx
->host
->active_procs
--;
2814 hctx
->proc
->state
= PROC_STATE_OVERLOADED
;
2817 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2818 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".overloaded"));
2820 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2822 return HANDLER_ERROR
;
2823 case CONNECTION_DEAD
:
2824 /* we got a hard error from the backend like
2825 * - ECONNREFUSED for tcp-ip sockets
2826 * - ENOENT for unix-domain-sockets
2828 * for check if the host is back in hctx->host->disable_time seconds
2831 fcgi_host_disable(srv
, hctx
);
2833 log_error_write(srv
, __FILE__
, __LINE__
, "sdssdsd",
2834 "backend died; we'll disable it for", hctx
->host
->disable_time
, "seconds and send the request to another backend instead:",
2835 "reconnects:", hctx
->reconnects
,
2836 "load:", host
->load
);
2838 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2839 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".died"));
2841 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2843 return HANDLER_ERROR
;
2845 /* everything is ok, go on */
2847 fcgi_set_state(srv
, hctx
, FCGI_STATE_PREPARE_WRITE
);
2852 case FCGI_STATE_PREPARE_WRITE
:
2853 /* ok, we have the connection */
2855 fcgi_proc_load_inc(srv
, hctx
);
2858 status_counter_inc(srv
, CONST_STR_LEN("fastcgi.requests"));
2860 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2861 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".connected"));
2863 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2865 if (hctx
->conf
.debug
) {
2866 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsd",
2868 "pid:", hctx
->proc
->pid
,
2869 "socket:", hctx
->proc
->connection_name
,
2870 "load:", hctx
->proc
->load
);
2873 /* move the proc-list entry down the list */
2874 if (hctx
->request_id
== 0) {
2875 hctx
->request_id
= 1; /* always use id 1 as we don't use multiplexing */
2877 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2878 "fcgi-request is already in use:", hctx
->request_id
);
2881 if (-1 == fcgi_create_env(srv
, hctx
, hctx
->request_id
)) return HANDLER_ERROR
;
2883 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2884 fcgi_set_state(srv
, hctx
, FCGI_STATE_WRITE
);
2886 case FCGI_STATE_WRITE
:
2887 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
2889 chunkqueue_remove_finished_chunks(hctx
->wb
);
2896 /* the connection got dropped after accept()
2897 * we don't care about that - if you accept() it, you have to handle it.
2900 log_error_write(srv
, __FILE__
, __LINE__
, "ssosb",
2901 "connection was dropped after accept() (perhaps the fastcgi process died),",
2902 "write-offset:", hctx
->wb
->bytes_out
,
2903 "socket:", hctx
->proc
->connection_name
);
2905 return HANDLER_ERROR
;
2907 log_error_write(srv
, __FILE__
, __LINE__
, "ssd",
2908 "write failed:", strerror(errno
), errno
);
2910 return HANDLER_ERROR
;
2914 if (hctx
->wb
->bytes_out
== hctx
->wb_reqlen
) {
2915 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2916 fcgi_set_state(srv
, hctx
, FCGI_STATE_READ
);
2918 off_t wblen
= hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
;
2919 if (hctx
->wb
->bytes_in
< hctx
->wb_reqlen
&& wblen
< 65536 - 16384) {
2920 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
2921 if (!(con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_POLLIN
)) {
2922 con
->conf
.stream_request_body
|= FDEVENT_STREAM_REQUEST_POLLIN
;
2923 con
->is_readable
= 1; /* trigger optimistic read from client */
2927 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2929 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2933 return HANDLER_WAIT_FOR_EVENT
;
2934 case FCGI_STATE_READ
:
2935 /* waiting for a response */
2936 return HANDLER_WAIT_FOR_EVENT
;
2938 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
2939 return HANDLER_ERROR
;
2944 /* might be called on fdevent after a connect() is delay too
2946 static handler_t
fcgi_send_request(server
*srv
, handler_ctx
*hctx
) {
2947 /* ok, create the request */
2948 fcgi_extension_host
*host
= hctx
->host
;
2949 handler_t rc
= fcgi_write_request(srv
, hctx
);
2950 if (HANDLER_ERROR
!= rc
) {
2953 plugin_data
*p
= hctx
->plugin_data
;
2954 connection
*con
= hctx
->remote_conn
;
2956 if (hctx
->state
== FCGI_STATE_INIT
||
2957 hctx
->state
== FCGI_STATE_CONNECT_DELAYED
) {
2958 fcgi_restart_dead_procs(srv
, p
, host
);
2960 /* cleanup this request and let the request handler start this request again */
2961 if (hctx
->reconnects
++ < 5) {
2962 return fcgi_reconnect(srv
, hctx
);
2964 fcgi_connection_close(srv
, hctx
);
2965 con
->http_status
= 503;
2967 return HANDLER_FINISHED
;
2970 int status
= con
->http_status
;
2971 fcgi_connection_close(srv
, hctx
);
2972 con
->http_status
= (status
== 400) ? 400 : 503;
2974 return HANDLER_FINISHED
;
2980 static handler_t
fcgi_recv_response(server
*srv
, handler_ctx
*hctx
);
2983 SUBREQUEST_FUNC(mod_fastcgi_handle_subrequest
) {
2984 plugin_data
*p
= p_d
;
2986 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2988 if (NULL
== hctx
) return HANDLER_GO_ON
;
2991 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
2993 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
2994 && con
->file_started
) {
2995 if (chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
2996 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2997 } else if (!(fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_IN
)) {
2998 /* optimistic read from backend, which might re-enable FDEVENT_IN */
2999 handler_t rc
= fcgi_recv_response(srv
, hctx
); /*(might invalidate hctx)*/
3000 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
3004 /* (do not receive request body before FCGI_AUTHORIZER has run or else
3005 * the request body is discarded with handler_ctx_clear() after running
3006 * the FastCGI Authorizer) */
3008 if (hctx
->fcgi_mode
!= FCGI_AUTHORIZER
3009 && (0 == hctx
->wb
->bytes_in
3010 ? con
->state
== CON_STATE_READ_POST
3011 : hctx
->wb
->bytes_in
< hctx
->wb_reqlen
)) {
3012 /*(64k - 4k to attempt to avoid temporary files
3013 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
3014 if (hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
> 65536 - 4096
3015 && (con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_BUFMIN
)){
3016 con
->conf
.stream_request_body
&= ~FDEVENT_STREAM_REQUEST_POLLIN
;
3017 if (0 != hctx
->wb
->bytes_in
) return HANDLER_WAIT_FOR_EVENT
;
3019 handler_t r
= connection_handle_read_post_state(srv
, con
);
3020 chunkqueue
*req_cq
= con
->request_content_queue
;
3021 if (0 != hctx
->wb
->bytes_in
&& !chunkqueue_is_empty(req_cq
)) {
3022 fcgi_stdin_append(srv
, con
, hctx
, hctx
->request_id
);
3023 if (fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_OUT
) {
3024 return (r
== HANDLER_GO_ON
) ? HANDLER_WAIT_FOR_EVENT
: r
;
3027 if (r
!= HANDLER_GO_ON
) return r
;
3031 return ((0 == hctx
->wb
->bytes_in
|| !chunkqueue_is_empty(hctx
->wb
))
3032 && hctx
->state
!= FCGI_STATE_CONNECT_DELAYED
)
3033 ? fcgi_send_request(srv
, hctx
)
3034 : HANDLER_WAIT_FOR_EVENT
;
3038 static handler_t
fcgi_recv_response(server
*srv
, handler_ctx
*hctx
) {
3039 connection
*con
= hctx
->remote_conn
;
3040 plugin_data
*p
= hctx
->plugin_data
;
3042 fcgi_proc
*proc
= hctx
->proc
;
3043 fcgi_extension_host
*host
= hctx
->host
;
3045 switch (fcgi_demux_response(srv
, hctx
)) {
3050 if (hctx
->fcgi_mode
== FCGI_AUTHORIZER
&&
3051 (con
->http_status
== 200 ||
3052 con
->http_status
== 0)) {
3054 * If we are here in AUTHORIZER mode then a request for authorizer
3055 * was processed already, and status 200 has been returned. We need
3056 * now to handle authorized request.
3058 buffer
*physpath
= NULL
;
3060 if (!buffer_string_is_empty(host
->docroot
)) {
3061 buffer_copy_buffer(con
->physical
.doc_root
, host
->docroot
);
3062 buffer_copy_buffer(con
->physical
.basedir
, host
->docroot
);
3064 buffer_copy_buffer(con
->physical
.path
, host
->docroot
);
3065 buffer_append_string_buffer(con
->physical
.path
, con
->uri
.path
);
3066 physpath
= con
->physical
.path
;
3069 fcgi_backend_close(srv
, hctx
);
3070 handler_ctx_clear(hctx
);
3072 /* don't do more than 6 loops here, that normally shouldn't happen */
3073 if (++con
->loops_per_request
> 5) {
3074 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "too many loops while processing request:", con
->request
.orig_uri
);
3075 con
->http_status
= 500; /* Internal Server Error */
3077 return HANDLER_FINISHED
;
3080 /* restart the request so other handlers can process it */
3082 if (physpath
) con
->physical
.path
= NULL
;
3083 connection_response_reset(srv
, con
); /*(includes con->http_status = 0)*/
3084 if (physpath
) con
->physical
.path
= physpath
; /* preserve con->physical.path with modified docroot */
3086 /*(FYI: if multiple FastCGI authorizers were to be supported,
3087 * next one could be started here instead of restarting request)*/
3090 return HANDLER_COMEBACK
;
3093 fcgi_connection_close(srv
, hctx
);
3096 return HANDLER_FINISHED
;
3098 if (proc
->pid
&& proc
->state
!= PROC_STATE_DIED
) {
3101 /* only fetch the zombie if it is not already done */
3103 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
3105 /* child is still alive */
3110 /* the child should not terminate at all */
3111 if (WIFEXITED(status
)) {
3112 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
3113 "child exited, pid:", proc
->pid
,
3114 "status:", WEXITSTATUS(status
));
3115 } else if (WIFSIGNALED(status
)) {
3116 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3120 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3121 "child died somehow:",
3125 if (hctx
->conf
.debug
) {
3126 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsd",
3127 "--- fastcgi spawning",
3128 "\n\tsocket", proc
->connection_name
,
3129 "\n\tcurrent:", 1, "/", host
->max_procs
);
3132 if (fcgi_spawn_connection(srv
, p
, host
, proc
)) {
3133 /* respawning failed, retry later */
3134 proc
->state
= PROC_STATE_DIED
;
3136 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3137 "respawning failed, will retry later");
3144 if (con
->file_started
== 0) {
3145 /* nothing has been sent out yet, try to use another child */
3147 if (hctx
->wb
->bytes_out
== 0 &&
3148 hctx
->reconnects
++ < 5) {
3150 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsBSBs",
3151 "response not received, request not sent",
3152 "on socket:", proc
->connection_name
,
3153 "for", con
->uri
.path
, "?", con
->uri
.query
, ", reconnecting");
3155 return fcgi_reconnect(srv
, hctx
);
3158 log_error_write(srv
, __FILE__
, __LINE__
, "sosbsBSBs",
3159 "response not received, request sent:", hctx
->wb
->bytes_out
,
3160 "on socket:", proc
->connection_name
,
3161 "for", con
->uri
.path
, "?", con
->uri
.query
, ", closing connection");
3163 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsBSBs",
3164 "response already sent out, but backend returned error",
3165 "on socket:", proc
->connection_name
,
3166 "for", con
->uri
.path
, "?", con
->uri
.query
, ", terminating connection");
3169 http_response_backend_error(srv
, con
);
3170 fcgi_connection_close(srv
, hctx
);
3171 return HANDLER_FINISHED
;
3174 return HANDLER_GO_ON
;
3178 static handler_t
fcgi_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
3179 handler_ctx
*hctx
= ctx
;
3180 connection
*con
= hctx
->remote_conn
;
3182 joblist_append(srv
, con
);
3184 if (revents
& FDEVENT_IN
) {
3185 handler_t rc
= fcgi_recv_response(srv
, hctx
);/*(might invalidate hctx)*/
3186 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
3189 if (revents
& FDEVENT_OUT
) {
3190 return fcgi_send_request(srv
, hctx
); /*(might invalidate hctx)*/
3193 /* perhaps this issue is already handled */
3194 if (revents
& FDEVENT_HUP
) {
3195 if (hctx
->state
== FCGI_STATE_CONNECT_DELAYED
) {
3196 /* getoptsock will catch this one (right ?)
3198 * if we are in connect we might get an EINPROGRESS
3199 * in the first call and an FDEVENT_HUP in the
3202 * FIXME: as it is a bit ugly.
3205 fcgi_send_request(srv
, hctx
);
3206 } else if (con
->file_started
) {
3207 /* drain any remaining data from kernel pipe buffers
3208 * even if (con->conf.stream_response_body
3209 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
3210 * since event loop will spin on fd FDEVENT_HUP event
3211 * until unregistered. */
3214 rc
= fcgi_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
3215 } while (rc
== HANDLER_GO_ON
); /*(unless HANDLER_GO_ON)*/
3216 return rc
; /* HANDLER_FINISHED or HANDLER_ERROR */
3218 fcgi_proc
*proc
= hctx
->proc
;
3219 log_error_write(srv
, __FILE__
, __LINE__
, "sBSbsbsd",
3220 "error: unexpected close of fastcgi connection for",
3221 con
->uri
.path
, "?", con
->uri
.query
,
3222 "(no fastcgi process on socket:", proc
->connection_name
, "?)",
3225 fcgi_connection_close(srv
, hctx
);
3227 } else if (revents
& FDEVENT_ERR
) {
3228 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3229 "fcgi: got a FDEVENT_ERR. Don't know why.");
3231 http_response_backend_error(srv
, con
);
3232 fcgi_connection_close(srv
, hctx
);
3235 return HANDLER_FINISHED
;
3240 static int fcgi_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
3242 plugin_config
*s
= p
->config_storage
[0];
3250 /* skip the first, the global context */
3251 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
3252 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
3253 s
= p
->config_storage
[i
];
3255 /* condition didn't match */
3256 if (!config_check_cond(srv
, con
, dc
)) continue;
3259 for (j
= 0; j
< dc
->value
->used
; j
++) {
3260 data_unset
*du
= dc
->value
->data
[j
];
3262 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("fastcgi.server"))) {
3266 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("fastcgi.debug"))) {
3268 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("fastcgi.map-extensions"))) {
3279 static handler_t
fcgi_check_extension(server
*srv
, connection
*con
, void *p_d
, int uri_path_handler
) {
3280 plugin_data
*p
= p_d
;
3284 fcgi_extension
*extension
= NULL
;
3285 fcgi_extension_host
*host
= NULL
;
3287 unsigned short fcgi_mode
;
3289 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
3291 fn
= uri_path_handler
? con
->uri
.path
: con
->physical
.path
;
3293 if (buffer_string_is_empty(fn
)) return HANDLER_GO_ON
;
3295 s_len
= buffer_string_length(fn
);
3297 fcgi_patch_connection(srv
, con
, p
);
3298 if (NULL
== p
->conf
.exts
) return HANDLER_GO_ON
;
3300 /* check p->conf.exts_auth list and then p->conf.ext_resp list
3301 * (skip p->conf.exts_auth if array is empty or if FCGI_AUTHORIZER already ran in this request */
3302 hctx
= con
->plugin_ctx
[p
->id
]; /*(not NULL if FCGI_AUTHORIZER ran; hctx->ext-auth check is redundant)*/
3303 fcgi_mode
= (NULL
== hctx
|| NULL
== hctx
->ext_auth
)
3304 ? 0 /* FCGI_AUTHORIZER p->conf.exts_auth will be searched next */
3305 : FCGI_AUTHORIZER
; /* FCGI_RESPONDER p->conf.exts_resp will be searched next */
3310 if (0 == fcgi_mode
) {
3311 fcgi_mode
= FCGI_AUTHORIZER
;
3312 exts
= p
->conf
.exts_auth
;
3314 fcgi_mode
= FCGI_RESPONDER
;
3315 exts
= p
->conf
.exts_resp
;
3318 if (0 == exts
->used
) continue;
3320 /* fastcgi.map-extensions maps extensions to existing fastcgi.server entries
3322 * fastcgi.map-extensions = ( ".php3" => ".php" )
3324 * fastcgi.server = ( ".php" => ... )
3328 /* check if extension-mapping matches */
3329 for (k
= 0; k
< p
->conf
.ext_mapping
->used
; k
++) {
3330 data_string
*ds
= (data_string
*)p
->conf
.ext_mapping
->data
[k
];
3331 size_t ct_len
; /* length of the config entry */
3333 if (buffer_is_empty(ds
->key
)) continue;
3335 ct_len
= buffer_string_length(ds
->key
);
3337 if (s_len
< ct_len
) continue;
3339 /* found a mapping */
3340 if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ds
->key
->ptr
, ct_len
)) {
3341 /* check if we know the extension */
3343 /* we can reuse k here */
3344 for (k
= 0; k
< exts
->used
; k
++) {
3345 extension
= exts
->exts
[k
];
3347 if (buffer_is_equal(ds
->value
, extension
->key
)) {
3352 if (k
== exts
->used
) {
3360 if (extension
== NULL
) {
3361 size_t uri_path_len
= buffer_string_length(con
->uri
.path
);
3363 /* check if extension matches */
3364 for (k
= 0; k
< exts
->used
; k
++) {
3365 size_t ct_len
; /* length of the config entry */
3366 fcgi_extension
*ext
= exts
->exts
[k
];
3368 if (buffer_is_empty(ext
->key
)) continue;
3370 ct_len
= buffer_string_length(ext
->key
);
3372 /* check _url_ in the form "/fcgi_pattern" */
3373 if (ext
->key
->ptr
[0] == '/') {
3374 if ((ct_len
<= uri_path_len
) &&
3375 (strncmp(con
->uri
.path
->ptr
, ext
->key
->ptr
, ct_len
) == 0)) {
3379 } else if ((ct_len
<= s_len
) && (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
))) {
3380 /* check extension in the form ".fcg" */
3387 } while (NULL
== extension
&& fcgi_mode
!= FCGI_RESPONDER
);
3389 /* extension doesn't match */
3390 if (NULL
== extension
) {
3391 return HANDLER_GO_ON
;
3394 /* check if we have at least one server for this extension up and running */
3395 host
= fcgi_extension_host_get(srv
, con
, p
, extension
);
3397 return HANDLER_FINISHED
;
3400 /* a note about no handler is not sent yet */
3401 extension
->note_is_sent
= 0;
3404 * if check-local is disabled, use the uri.path handler
3408 /* init handler-context */
3409 if (uri_path_handler
) {
3410 if (host
->check_local
!= 0) {
3411 return HANDLER_GO_ON
;
3413 /* do not split path info for authorizer */
3414 if (fcgi_mode
!= FCGI_AUTHORIZER
) {
3415 /* the prefix is the SCRIPT_NAME,
3416 * everything from start to the next slash
3417 * this is important for check-local = "disable"
3419 * if prefix = /admin.fcgi
3421 * /admin.fcgi/foo/bar
3423 * SCRIPT_NAME = /admin.fcgi
3424 * PATH_INFO = /foo/bar
3426 * if prefix = /fcgi-bin/
3430 * SCRIPT_NAME = /fcgi-bin/foo
3433 * if prefix = /, and fix-root-path-name is enable
3437 * SCRIPT_NAME = /fcgi-bin/foo
3443 /* the rewrite is only done for /prefix/? matches */
3444 if (host
->fix_root_path_name
&& extension
->key
->ptr
[0] == '/' && extension
->key
->ptr
[1] == '\0') {
3445 buffer_copy_string(con
->request
.pathinfo
, con
->uri
.path
->ptr
);
3446 buffer_string_set_length(con
->uri
.path
, 0);
3447 } else if (extension
->key
->ptr
[0] == '/' &&
3448 buffer_string_length(con
->uri
.path
) > buffer_string_length(extension
->key
) &&
3449 NULL
!= (pathinfo
= strchr(con
->uri
.path
->ptr
+ buffer_string_length(extension
->key
), '/'))) {
3450 /* rewrite uri.path and pathinfo */
3452 buffer_copy_string(con
->request
.pathinfo
, pathinfo
);
3453 buffer_string_set_length(con
->uri
.path
, buffer_string_length(con
->uri
.path
) - buffer_string_length(con
->request
.pathinfo
));
3459 if (!hctx
) hctx
= handler_ctx_init();
3461 hctx
->remote_conn
= con
;
3462 hctx
->plugin_data
= p
;
3464 hctx
->ext
= extension
;
3465 fcgi_host_assign(srv
, hctx
, host
);
3467 hctx
->fcgi_mode
= fcgi_mode
;
3468 if (fcgi_mode
== FCGI_AUTHORIZER
) {
3469 hctx
->ext_auth
= hctx
->ext
;
3472 /*hctx->conf.exts = p->conf.exts;*/
3473 /*hctx->conf.exts_auth = p->conf.exts_auth;*/
3474 /*hctx->conf.exts_resp = p->conf.exts_resp;*/
3475 /*hctx->conf.ext_mapping = p->conf.ext_mapping;*/
3476 hctx
->conf
.debug
= p
->conf
.debug
;
3478 con
->plugin_ctx
[p
->id
] = hctx
;
3482 if (con
->conf
.log_request_handling
) {
3483 log_error_write(srv
, __FILE__
, __LINE__
, "s", "handling it in mod_fastcgi");
3486 return HANDLER_GO_ON
;
3489 /* uri-path handler */
3490 static handler_t
fcgi_check_extension_1(server
*srv
, connection
*con
, void *p_d
) {
3491 return fcgi_check_extension(srv
, con
, p_d
, 1);
3494 /* start request handler */
3495 static handler_t
fcgi_check_extension_2(server
*srv
, connection
*con
, void *p_d
) {
3496 return fcgi_check_extension(srv
, con
, p_d
, 0);
3500 TRIGGER_FUNC(mod_fastcgi_handle_trigger
) {
3501 plugin_data
*p
= p_d
;
3505 /* perhaps we should kill a connect attempt after 10-15 seconds
3507 * currently we wait for the TCP timeout which is 180 seconds on Linux
3513 /* check all children if they are still up */
3515 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
3516 plugin_config
*conf
;
3519 conf
= p
->config_storage
[i
];
3522 if (NULL
== exts
) continue;
3524 for (j
= 0; j
< exts
->used
; j
++) {
3529 for (n
= 0; n
< ex
->used
; n
++) {
3532 fcgi_extension_host
*host
;
3534 host
= ex
->hosts
[n
];
3536 fcgi_restart_dead_procs(srv
, p
, host
);
3538 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
3541 if (proc
->pid
== 0) continue;
3543 switch (waitpid(proc
->pid
, &status
, WNOHANG
)) {
3545 /* child still running after timeout, good */
3548 if (errno
!= EINTR
) {
3549 /* no PID found ? should never happen */
3550 log_error_write(srv
, __FILE__
, __LINE__
, "sddss",
3551 "pid ", proc
->pid
, proc
->state
,
3552 "not found:", strerror(errno
));
3555 if (errno
== ECHILD
) {
3556 /* someone else has cleaned up for us */
3558 proc
->state
= PROC_STATE_UNSET
;
3564 /* the child should not terminate at all */
3565 if (WIFEXITED(status
)) {
3566 if (proc
->state
!= PROC_STATE_KILLED
) {
3567 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
3569 WEXITSTATUS(status
), proc
->connection_name
);
3571 } else if (WIFSIGNALED(status
)) {
3572 if (WTERMSIG(status
) != SIGTERM
) {
3573 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3578 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3579 "child died somehow:",
3583 if (proc
->state
== PROC_STATE_RUNNING
) host
->active_procs
--;
3584 proc
->state
= PROC_STATE_UNSET
;
3592 return HANDLER_GO_ON
;
3596 int mod_fastcgi_plugin_init(plugin
*p
);
3597 int mod_fastcgi_plugin_init(plugin
*p
) {
3598 p
->version
= LIGHTTPD_VERSION_ID
;
3599 p
->name
= buffer_init_string("fastcgi");
3601 p
->init
= mod_fastcgi_init
;
3602 p
->cleanup
= mod_fastcgi_free
;
3603 p
->set_defaults
= mod_fastcgi_set_defaults
;
3604 p
->connection_reset
= fcgi_connection_reset
;
3605 p
->handle_connection_close
= fcgi_connection_reset
;
3606 p
->handle_uri_clean
= fcgi_check_extension_1
;
3607 p
->handle_subrequest_start
= fcgi_check_extension_2
;
3608 p
->handle_subrequest
= mod_fastcgi_handle_subrequest
;
3609 p
->handle_trigger
= mod_fastcgi_handle_trigger
;