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
57 * - add timeout for a connect to a non-fastcgi process
58 * (use state_timestamp + state)
62 typedef struct fcgi_proc
{
63 size_t id
; /* id will be between 1 and max_procs */
64 buffer
*unixsocket
; /* config.socket + "-" + id */
65 unsigned port
; /* config.port + pno */
67 buffer
*connection_name
; /* either tcp:<host>:<port> or unix:<socket> for debugging purposes */
69 pid_t pid
; /* PID of the spawned process (0 if not spawned locally) */
72 size_t load
; /* number of requests waiting on this process */
74 size_t requests
; /* see max_requests */
75 struct fcgi_proc
*prev
, *next
; /* see first */
77 time_t disabled_until
; /* this proc is disabled until, use something else until then */
82 PROC_STATE_UNSET
, /* init-phase */
83 PROC_STATE_RUNNING
, /* alive */
84 PROC_STATE_OVERLOADED
, /* listen-queue is full,
85 don't send anything to this proc for the next 2 seconds */
86 PROC_STATE_DIED_WAIT_FOR_PID
, /* */
87 PROC_STATE_DIED
, /* marked as dead, should be restarted */
88 PROC_STATE_KILLED
/* was killed as we don't have the load anymore */
93 /* the key that is used to reference this value */
96 /* list of processes handling this extension
97 * sorted by lowest load
99 * whenever a job is done move it up in the list
100 * until it is sorted, move it down as soon as the
104 fcgi_proc
*unused_procs
;
107 * spawn at least min_procs, at max_procs.
109 * as soon as the load of the first entry
110 * is max_load_per_proc we spawn a new one
111 * and add it to the first entry and give it
116 unsigned short max_procs
;
117 size_t num_procs
; /* how many procs are started */
118 size_t active_procs
; /* how many of them are really running, i.e. state = PROC_STATE_RUNNING */
121 * time after a disabled remote connection is tried to be re-enabled
126 unsigned short disable_time
;
129 * some fastcgi processes get a little bit larger
130 * than wanted. max_requests_per_proc kills a
131 * process after a number of handled requests.
134 size_t max_requests_per_proc
;
142 * if host is one of the local IP adresses the
143 * whole connection is local
145 * if port is not 0, and host is not specified,
146 * "localhost" (INADDR_LOOPBACK) is assumed.
155 * instead of TCP/IP we can use Unix Domain Sockets
156 * - more secure (you have fileperms to play with)
157 * - more control (on locally)
158 * - more speed (no extra overhead)
162 /* if socket is local we can start the fastcgi
165 * bin-path is the path to the binary
167 * check min_procs and max_procs for the number
168 * of process to start up
172 /* bin-path is set bin-environment is taken to
173 * create the environement before starting the
182 * docroot-translation between URL->phys and the
186 * - different dir-layout if remote
201 * check_local tells you if the phys file is stat()ed
202 * or not. FastCGI doesn't care if the service is
203 * remote. If the web-server side doesn't contain
204 * the fastcgi-files we should not stat() for them
205 * and say '404 not found'.
207 unsigned short check_local
;
210 * append PATH_INFO to SCRIPT_FILENAME
212 * php needs this if cgi.fix_pathinfo is provided
216 unsigned short break_scriptfilename_for_php
;
219 * workaround for program when prefix="/"
221 * rule to build PATH_INFO is hardcoded for when check_local is disabled
222 * enable this option to use the workaround
226 unsigned short fix_root_path_name
;
229 * If the backend includes X-LIGHTTPD-send-file in the response
230 * we use the value as filename and ignore the content.
233 unsigned short allow_xsendfile
;
235 ssize_t load
; /* replace by host->load */
237 size_t max_id
; /* corresponds most of the time to
240 only if a process is killed max_id waits for the process itself
241 to die and decrements it afterwards */
243 buffer
*strip_request_uri
;
245 unsigned short kill_signal
; /* we need a setting for this as libfcgi
246 applications prefer SIGUSR1 while the
247 rest of the world would use SIGTERM
251 } fcgi_extension_host
;
254 * one extension can have multiple hosts assigned
255 * one host can spawn additional processes on the same
256 * socket (if we control it)
258 * ext -> host -> procs
261 * if the fastcgi process is remote that whole goes down
264 * ext -> host -> procs
267 * in case of PHP and FCGI_CHILDREN we have again a procs
268 * but we don't control it directly.
273 buffer
*key
; /* like .php */
278 fcgi_extension_host
**hosts
;
285 fcgi_extension
**exts
;
307 /* generic plugin data, shared between all connections */
317 plugin_config
**config_storage
;
319 plugin_config conf
; /* this is only used as long as no handler_ctx is setup */
322 /* connection specific data */
325 FCGI_STATE_CONNECT_DELAYED
,
326 FCGI_STATE_PREPARE_WRITE
,
329 } fcgi_connection_state_t
;
333 fcgi_extension_host
*host
;
336 fcgi_connection_state_t state
;
337 time_t state_timestamp
;
339 int reconnects
; /* number of reconnect attempts */
341 chunkqueue
*rb
; /* read queue */
342 chunkqueue
*wb
; /* write queue */
344 buffer
*response_header
;
347 int fd
; /* fd to the fastcgi process */
348 int fde_ndx
; /* index into the fd-event buffer */
353 int send_content_body
;
357 connection
*remote_conn
; /* dumb pointer */
358 plugin_data
*plugin_data
; /* dumb pointer */
362 /* ok, we need a prototype */
363 static handler_t
fcgi_handle_fdevent(server
*srv
, void *ctx
, int revents
);
365 static void reset_signals(void) {
367 signal(SIGTTOU
, SIG_DFL
);
370 signal(SIGTTIN
, SIG_DFL
);
373 signal(SIGTSTP
, SIG_DFL
);
375 signal(SIGHUP
, SIG_DFL
);
376 signal(SIGPIPE
, SIG_DFL
);
377 signal(SIGUSR1
, SIG_DFL
);
380 static void fastcgi_status_copy_procname(buffer
*b
, fcgi_extension_host
*host
, fcgi_proc
*proc
) {
381 buffer_copy_string_len(b
, CONST_STR_LEN("fastcgi.backend."));
382 buffer_append_string_buffer(b
, host
->id
);
384 buffer_append_string_len(b
, CONST_STR_LEN("."));
385 buffer_append_int(b
, proc
->id
);
389 static void fcgi_proc_load_inc(server
*srv
, handler_ctx
*hctx
) {
390 plugin_data
*p
= hctx
->plugin_data
;
393 status_counter_inc(srv
, CONST_STR_LEN("fastcgi.active-requests"));
395 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
396 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".load"));
398 status_counter_set(srv
, CONST_BUF_LEN(p
->statuskey
), hctx
->proc
->load
);
401 static void fcgi_proc_load_dec(server
*srv
, handler_ctx
*hctx
) {
402 plugin_data
*p
= hctx
->plugin_data
;
405 status_counter_dec(srv
, CONST_STR_LEN("fastcgi.active-requests"));
407 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
408 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".load"));
410 status_counter_set(srv
, CONST_BUF_LEN(p
->statuskey
), hctx
->proc
->load
);
413 static void fcgi_host_assign(server
*srv
, handler_ctx
*hctx
, fcgi_extension_host
*host
) {
414 plugin_data
*p
= hctx
->plugin_data
;
418 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, NULL
);
419 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".load"));
421 status_counter_set(srv
, CONST_BUF_LEN(p
->statuskey
), hctx
->host
->load
);
424 static void fcgi_host_reset(server
*srv
, handler_ctx
*hctx
) {
425 plugin_data
*p
= hctx
->plugin_data
;
428 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, NULL
);
429 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".load"));
431 status_counter_set(srv
, CONST_BUF_LEN(p
->statuskey
), hctx
->host
->load
);
436 static void fcgi_host_disable(server
*srv
, handler_ctx
*hctx
) {
437 plugin_data
*p
= hctx
->plugin_data
;
439 if (hctx
->host
->disable_time
|| hctx
->proc
->is_local
) {
440 if (hctx
->proc
->state
== PROC_STATE_RUNNING
) hctx
->host
->active_procs
--;
441 hctx
->proc
->disabled_until
= srv
->cur_ts
+ hctx
->host
->disable_time
;
442 hctx
->proc
->state
= hctx
->proc
->is_local
? PROC_STATE_DIED_WAIT_FOR_PID
: PROC_STATE_DIED
;
445 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
446 "backend disabled for", hctx
->host
->disable_time
, "seconds");
451 static int fastcgi_status_init(server
*srv
, buffer
*b
, fcgi_extension_host
*host
, fcgi_proc
*proc
) {
453 fastcgi_status_copy_procname(b, host, proc); \
454 buffer_append_string_len(b, CONST_STR_LEN(x)); \
455 status_counter_set(srv, CONST_BUF_LEN(b), 0);
459 CLEAN(".overloaded");
466 fastcgi_status_copy_procname(b, host, NULL); \
467 buffer_append_string_len(b, CONST_STR_LEN(x)); \
468 status_counter_set(srv, CONST_BUF_LEN(b), 0);
477 static handler_ctx
* handler_ctx_init(void) {
480 hctx
= calloc(1, sizeof(*hctx
));
485 hctx
->response_header
= buffer_init();
487 hctx
->request_id
= 0;
488 hctx
->state
= FCGI_STATE_INIT
;
493 hctx
->reconnects
= 0;
494 hctx
->send_content_body
= 1;
496 hctx
->rb
= chunkqueue_init();
497 hctx
->wb
= chunkqueue_init();
502 static void handler_ctx_free(server
*srv
, handler_ctx
*hctx
) {
504 fcgi_host_reset(srv
, hctx
);
507 buffer_free(hctx
->response_header
);
509 chunkqueue_free(hctx
->rb
);
510 chunkqueue_free(hctx
->wb
);
515 static fcgi_proc
*fastcgi_process_init(void) {
518 f
= calloc(1, sizeof(*f
));
519 f
->unixsocket
= buffer_init();
520 f
->connection_name
= buffer_init();
528 static void fastcgi_process_free(fcgi_proc
*f
) {
531 fastcgi_process_free(f
->next
);
533 buffer_free(f
->unixsocket
);
534 buffer_free(f
->connection_name
);
539 static fcgi_extension_host
*fastcgi_host_init(void) {
540 fcgi_extension_host
*f
;
542 f
= calloc(1, sizeof(*f
));
544 f
->id
= buffer_init();
545 f
->host
= buffer_init();
546 f
->unixsocket
= buffer_init();
547 f
->docroot
= buffer_init();
548 f
->bin_path
= buffer_init();
549 f
->bin_env
= array_init();
550 f
->bin_env_copy
= array_init();
551 f
->strip_request_uri
= buffer_init();
556 static void fastcgi_host_free(fcgi_extension_host
*h
) {
560 buffer_free(h
->host
);
561 buffer_free(h
->unixsocket
);
562 buffer_free(h
->docroot
);
563 buffer_free(h
->bin_path
);
564 buffer_free(h
->strip_request_uri
);
565 array_free(h
->bin_env
);
566 array_free(h
->bin_env_copy
);
568 fastcgi_process_free(h
->first
);
569 fastcgi_process_free(h
->unused_procs
);
575 static fcgi_exts
*fastcgi_extensions_init(void) {
578 f
= calloc(1, sizeof(*f
));
583 static void fastcgi_extensions_free(fcgi_exts
*f
) {
588 for (i
= 0; i
< f
->used
; i
++) {
594 for (j
= 0; j
< fe
->used
; j
++) {
595 fcgi_extension_host
*h
;
599 fastcgi_host_free(h
);
602 buffer_free(fe
->key
);
613 static int fastcgi_extension_insert(fcgi_exts
*ext
, buffer
*key
, fcgi_extension_host
*fh
) {
617 /* there is something */
619 for (i
= 0; i
< ext
->used
; i
++) {
620 if (buffer_is_equal(key
, ext
->exts
[i
]->key
)) {
625 if (i
== ext
->used
) {
626 /* filextension is new */
627 fe
= calloc(1, sizeof(*fe
));
629 fe
->key
= buffer_init();
630 fe
->last_used_ndx
= -1;
631 buffer_copy_buffer(fe
->key
, key
);
635 if (ext
->size
== 0) {
637 ext
->exts
= malloc(ext
->size
* sizeof(*(ext
->exts
)));
638 force_assert(ext
->exts
);
639 } else if (ext
->used
== ext
->size
) {
641 ext
->exts
= realloc(ext
->exts
, ext
->size
* sizeof(*(ext
->exts
)));
642 force_assert(ext
->exts
);
644 ext
->exts
[ext
->used
++] = fe
;
651 fe
->hosts
= malloc(fe
->size
* sizeof(*(fe
->hosts
)));
652 force_assert(fe
->hosts
);
653 } else if (fe
->size
== fe
->used
) {
655 fe
->hosts
= realloc(fe
->hosts
, fe
->size
* sizeof(*(fe
->hosts
)));
656 force_assert(fe
->hosts
);
659 fe
->hosts
[fe
->used
++] = fh
;
665 INIT_FUNC(mod_fastcgi_init
) {
668 p
= calloc(1, sizeof(*p
));
670 p
->fcgi_env
= buffer_init();
672 p
->path
= buffer_init();
674 p
->statuskey
= buffer_init();
680 FREE_FUNC(mod_fastcgi_free
) {
681 plugin_data
*p
= p_d
;
685 buffer_free(p
->fcgi_env
);
686 buffer_free(p
->path
);
687 buffer_free(p
->statuskey
);
689 if (p
->config_storage
) {
691 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
692 plugin_config
*s
= p
->config_storage
[i
];
695 if (NULL
== s
) continue;
699 for (j
= 0; j
< exts
->used
; j
++) {
704 for (n
= 0; n
< ex
->used
; n
++) {
706 fcgi_extension_host
*host
;
710 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
711 if (proc
->pid
!= 0) {
712 kill(proc
->pid
, host
->kill_signal
);
715 if (proc
->is_local
&&
716 !buffer_string_is_empty(proc
->unixsocket
)) {
717 unlink(proc
->unixsocket
->ptr
);
721 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
722 if (proc
->pid
!= 0) {
723 kill(proc
->pid
, host
->kill_signal
);
725 if (proc
->is_local
&&
726 !buffer_string_is_empty(proc
->unixsocket
)) {
727 unlink(proc
->unixsocket
->ptr
);
733 fastcgi_extensions_free(s
->exts
);
734 array_free(s
->ext_mapping
);
738 free(p
->config_storage
);
743 return HANDLER_GO_ON
;
746 static int env_add(char_array
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
750 if (!key
|| !val
) return -1;
752 dst
= malloc(key_len
+ val_len
+ 3);
753 memcpy(dst
, key
, key_len
);
755 memcpy(dst
+ key_len
+ 1, val
, val_len
);
756 dst
[key_len
+ 1 + val_len
] = '\0';
758 for (i
= 0; i
< env
->used
; i
++) {
759 if (0 == strncmp(dst
, env
->ptr
[i
], key_len
+ 1)) {
760 /* don't care about free as we are in a forked child which is going to exec(...) */
761 /* free(env->ptr[i]); */
767 if (env
->size
== 0) {
769 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
770 } else if (env
->size
== env
->used
+ 1) {
772 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
775 env
->ptr
[env
->used
++] = dst
;
780 static int parse_binpath(char_array
*env
, buffer
*b
) {
783 /* search for spaces */
786 for (i
= 0; i
< buffer_string_length(b
); i
++) {
790 /* a WS, stop here and copy the argument */
792 if (env
->size
== 0) {
794 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
795 } else if (env
->size
== env
->used
) {
797 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
802 env
->ptr
[env
->used
++] = start
;
804 start
= b
->ptr
+ i
+ 1;
811 if (env
->size
== 0) {
813 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
814 } else if (env
->size
== env
->used
) { /* we need one extra for the terminating NULL */
816 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
820 env
->ptr
[env
->used
++] = start
;
822 if (env
->size
== 0) {
824 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
825 } else if (env
->size
== env
->used
) { /* we need one extra for the terminating NULL */
827 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
831 env
->ptr
[env
->used
++] = NULL
;
836 #if !defined(HAVE_FORK)
837 static int fcgi_spawn_connection(server
*srv
,
839 fcgi_extension_host
*host
,
848 #else /* -> defined(HAVE_FORK) */
850 static int fcgi_spawn_connection(server
*srv
,
852 fcgi_extension_host
*host
,
855 int socket_type
, status
;
856 struct timeval tv
= { 0, 100 * 1000 };
858 struct sockaddr_un fcgi_addr_un
;
860 struct sockaddr_in fcgi_addr_in
;
861 struct sockaddr
*fcgi_addr
;
866 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
867 "new proc, socket:", proc
->port
, proc
->unixsocket
);
870 if (!buffer_string_is_empty(proc
->unixsocket
)) {
872 memset(&fcgi_addr_un
, 0, sizeof(fcgi_addr_un
));
873 fcgi_addr_un
.sun_family
= AF_UNIX
;
874 if (buffer_string_length(proc
->unixsocket
) + 1 > sizeof(fcgi_addr_un
.sun_path
)) {
875 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
876 "ERROR: Unix Domain socket filename too long:",
880 memcpy(fcgi_addr_un
.sun_path
, proc
->unixsocket
->ptr
, buffer_string_length(proc
->unixsocket
) + 1);
883 servlen
= SUN_LEN(&fcgi_addr_un
);
886 servlen
= buffer_string_length(proc
->unixsocket
) + 1 + sizeof(fcgi_addr_un
.sun_family
);
888 socket_type
= AF_UNIX
;
889 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_un
;
891 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("unix:"));
892 buffer_append_string_buffer(proc
->connection_name
, proc
->unixsocket
);
895 log_error_write(srv
, __FILE__
, __LINE__
, "s",
896 "ERROR: Unix Domain sockets are not supported.");
900 memset(&fcgi_addr_in
, 0, sizeof(fcgi_addr_in
));
901 fcgi_addr_in
.sin_family
= AF_INET
;
903 if (buffer_string_is_empty(host
->host
)) {
904 fcgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
908 /* set a useful default */
909 fcgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
912 if (NULL
== (he
= gethostbyname(host
->host
->ptr
))) {
913 log_error_write(srv
, __FILE__
, __LINE__
,
914 "sdb", "gethostbyname failed: ",
915 h_errno
, host
->host
);
919 if (he
->h_addrtype
!= AF_INET
) {
920 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-type != AF_INET: ", he
->h_addrtype
);
924 if (he
->h_length
!= sizeof(struct in_addr
)) {
925 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-length != sizeof(in_addr): ", he
->h_length
);
929 memcpy(&(fcgi_addr_in
.sin_addr
.s_addr
), he
->h_addr_list
[0], he
->h_length
);
932 fcgi_addr_in
.sin_port
= htons(proc
->port
);
933 servlen
= sizeof(fcgi_addr_in
);
935 socket_type
= AF_INET
;
936 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_in
;
938 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("tcp:"));
939 if (!buffer_string_is_empty(host
->host
)) {
940 buffer_append_string_buffer(proc
->connection_name
, host
->host
);
942 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN("localhost"));
944 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN(":"));
945 buffer_append_int(proc
->connection_name
, proc
->port
);
948 if (-1 == (fcgi_fd
= socket(socket_type
, SOCK_STREAM
, 0))) {
949 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
950 "failed:", strerror(errno
));
954 if (-1 == connect(fcgi_fd
, fcgi_addr
, servlen
)) {
955 /* server is not up, spawn it */
959 if (errno
!= ENOENT
&&
960 !buffer_string_is_empty(proc
->unixsocket
)) {
961 unlink(proc
->unixsocket
->ptr
);
967 if (-1 == (fcgi_fd
= socket(socket_type
, SOCK_STREAM
, 0))) {
968 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
969 "socket failed:", strerror(errno
));
974 if (setsockopt(fcgi_fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
)) < 0) {
975 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
976 "socketsockopt failed:", strerror(errno
));
982 if (-1 == bind(fcgi_fd
, fcgi_addr
, servlen
)) {
983 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
985 proc
->connection_name
,
991 if (-1 == listen(fcgi_fd
, host
->listen_backlog
)) {
992 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
993 "listen failed:", strerror(errno
));
998 switch ((child
= fork())) {
1005 /* create environment */
1014 if(fcgi_fd
!= FCGI_LISTENSOCK_FILENO
) {
1015 close(FCGI_LISTENSOCK_FILENO
);
1016 dup2(fcgi_fd
, FCGI_LISTENSOCK_FILENO
);
1020 /* we don't need the client socket */
1021 for (i
= 3; i
< 256; i
++) {
1025 /* build clean environment */
1026 if (host
->bin_env_copy
->used
) {
1027 for (i
= 0; i
< host
->bin_env_copy
->used
; i
++) {
1028 data_string
*ds
= (data_string
*)host
->bin_env_copy
->data
[i
];
1031 if (NULL
!= (ge
= getenv(ds
->value
->ptr
))) {
1032 env_add(&env
, CONST_BUF_LEN(ds
->value
), ge
, strlen(ge
));
1036 for (i
= 0; environ
[i
]; i
++) {
1039 if (NULL
!= (eq
= strchr(environ
[i
], '='))) {
1040 env_add(&env
, environ
[i
], eq
- environ
[i
], eq
+1, strlen(eq
+1));
1045 /* create environment */
1046 for (i
= 0; i
< host
->bin_env
->used
; i
++) {
1047 data_string
*ds
= (data_string
*)host
->bin_env
->data
[i
];
1049 env_add(&env
, CONST_BUF_LEN(ds
->key
), CONST_BUF_LEN(ds
->value
));
1052 for (i
= 0; i
< env
.used
; i
++) {
1053 /* search for PHP_FCGI_CHILDREN */
1054 if (0 == strncmp(env
.ptr
[i
], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
1057 /* not found, add a default */
1058 if (i
== env
.used
) {
1059 env_add(&env
, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
1062 env
.ptr
[env
.used
] = NULL
;
1064 parse_binpath(&arg
, host
->bin_path
);
1066 /* chdir into the base of the bin-path,
1067 * search for the last / */
1068 if (NULL
!= (c
= strrchr(arg
.ptr
[0], '/'))) {
1071 /* change to the physical directory */
1072 if (-1 == chdir(arg
.ptr
[0])) {
1074 log_error_write(srv
, __FILE__
, __LINE__
, "sss", "chdir failed:", strerror(errno
), arg
.ptr
[0]);
1082 execve(arg
.ptr
[0], arg
.ptr
, env
.ptr
);
1084 /* log_error_write(srv, __FILE__, __LINE__, "sbs",
1085 "execve failed for:", host->bin_path, strerror(errno)); */
1100 select(0, NULL
, NULL
, NULL
, &tv
);
1102 switch (waitpid(child
, &status
, WNOHANG
)) {
1104 /* child still running after timeout, good */
1107 /* no PID found ? should never happen */
1108 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
1109 "pid not found:", strerror(errno
));
1112 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1113 "the fastcgi-backend", host
->bin_path
, "failed to start:");
1114 /* the child should not terminate at all */
1115 if (WIFEXITED(status
)) {
1116 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
1117 "child exited with status",
1118 WEXITSTATUS(status
), host
->bin_path
);
1119 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1120 "If you're trying to run your app as a FastCGI backend, make sure you're using the FastCGI-enabled version.\n"
1121 "If this is PHP on Gentoo, add 'fastcgi' to the USE flags.");
1122 } else if (WIFSIGNALED(status
)) {
1123 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1124 "terminated by signal:",
1127 if (WTERMSIG(status
) == 11) {
1128 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1129 "to be exact: it segfaulted, crashed, died, ... you get the idea." );
1130 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1131 "If this is PHP, try removing the bytecode caches for now and try again.");
1134 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1135 "child died somehow:",
1141 /* register process */
1152 if (p
->conf
.debug
) {
1153 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1154 "(debug) socket is already used; won't spawn:",
1155 proc
->connection_name
);
1159 proc
->state
= PROC_STATE_RUNNING
;
1160 host
->active_procs
++;
1165 #endif /* HAVE_FORK */
1167 static int unixsocket_is_dup(plugin_data
*p
, size_t used
, buffer
*unixsocket
) {
1169 for (i
= 0; i
< used
; ++i
) {
1170 fcgi_exts
*exts
= p
->config_storage
[i
]->exts
;
1171 for (j
= 0; j
< exts
->used
; ++j
) {
1172 fcgi_extension
*ex
= exts
->exts
[j
];
1173 for (n
= 0; n
< ex
->used
; ++n
) {
1174 fcgi_extension_host
*host
= ex
->hosts
[n
];
1175 if (!buffer_string_is_empty(host
->unixsocket
)
1176 && buffer_is_equal(host
->unixsocket
, unixsocket
))
1185 SETDEFAULTS_FUNC(mod_fastcgi_set_defaults
) {
1186 plugin_data
*p
= p_d
;
1189 buffer
*fcgi_mode
= buffer_init();
1190 fcgi_extension_host
*host
= NULL
;
1192 config_values_t cv
[] = {
1193 { "fastcgi.server", NULL
, T_CONFIG_LOCAL
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
1194 { "fastcgi.debug", NULL
, T_CONFIG_INT
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
1195 { "fastcgi.map-extensions", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
1196 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
1199 p
->config_storage
= calloc(1, srv
->config_context
->used
* sizeof(plugin_config
*));
1201 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
1202 data_config
const* config
= (data_config
const*)srv
->config_context
->data
[i
];
1205 s
= malloc(sizeof(plugin_config
));
1206 s
->exts
= fastcgi_extensions_init();
1208 s
->ext_mapping
= array_init();
1210 cv
[0].destination
= s
->exts
;
1211 cv
[1].destination
= &(s
->debug
);
1212 cv
[2].destination
= s
->ext_mapping
;
1214 p
->config_storage
[i
] = s
;
1216 if (0 != config_insert_values_global(srv
, config
->value
, cv
, i
== 0 ? T_CONFIG_SCOPE_SERVER
: T_CONFIG_SCOPE_CONNECTION
)) {
1224 if (NULL
!= (du
= array_get_element(config
->value
, "fastcgi.server"))) {
1226 data_array
*da
= (data_array
*)du
;
1228 if (du
->type
!= TYPE_ARRAY
) {
1229 log_error_write(srv
, __FILE__
, __LINE__
, "sss",
1230 "unexpected type for key: ", "fastcgi.server", "array of strings");
1237 * fastcgi.server = ( "<ext>" => ( ... ),
1238 * "<ext>" => ( ... ) )
1241 for (j
= 0; j
< da
->value
->used
; j
++) {
1243 data_array
*da_ext
= (data_array
*)da
->value
->data
[j
];
1245 if (da
->value
->data
[j
]->type
!= TYPE_ARRAY
) {
1246 log_error_write(srv
, __FILE__
, __LINE__
, "sssbs",
1247 "unexpected type for key: ", "fastcgi.server",
1248 "[", da
->value
->data
[j
]->key
, "](string)");
1254 * da_ext->key == name of the extension
1258 * fastcgi.server = ( "<ext>" =>
1259 * ( "<host>" => ( ... ),
1260 * "<host>" => ( ... )
1265 for (n
= 0; n
< da_ext
->value
->used
; n
++) {
1266 data_array
*da_host
= (data_array
*)da_ext
->value
->data
[n
];
1268 config_values_t fcv
[] = {
1269 { "host", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
1270 { "docroot", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
1271 { "mode", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
1272 { "socket", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 3 */
1273 { "bin-path", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 4 */
1275 { "check-local", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 5 */
1276 { "port", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 6 */
1277 { "max-procs", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 */
1278 { "disable-time", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 8 */
1280 { "bin-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 9 */
1281 { "bin-copy-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 10 */
1283 { "broken-scriptfilename", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 11 */
1284 { "allow-x-send-file", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 12 */
1285 { "strip-request-uri", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 13 */
1286 { "kill-signal", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 14 */
1287 { "fix-root-scriptname", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 15 */
1288 { "listen-backlog", NULL
, T_CONFIG_INT
, T_CONFIG_SCOPE_CONNECTION
}, /* 16 */
1290 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
1293 if (da_host
->type
!= TYPE_ARRAY
) {
1294 log_error_write(srv
, __FILE__
, __LINE__
, "ssSBS",
1295 "unexpected type for key:",
1297 "[", da_host
->key
, "](string)");
1302 host
= fastcgi_host_init();
1303 buffer_reset(fcgi_mode
);
1305 buffer_copy_buffer(host
->id
, da_host
->key
);
1307 host
->check_local
= 1;
1308 host
->max_procs
= 4;
1309 host
->mode
= FCGI_RESPONDER
;
1310 host
->disable_time
= 1;
1311 host
->break_scriptfilename_for_php
= 0;
1312 host
->allow_xsendfile
= 0; /* handle X-LIGHTTPD-send-file */
1313 host
->kill_signal
= SIGTERM
;
1314 host
->fix_root_path_name
= 0;
1315 host
->listen_backlog
= 1024;
1317 fcv
[0].destination
= host
->host
;
1318 fcv
[1].destination
= host
->docroot
;
1319 fcv
[2].destination
= fcgi_mode
;
1320 fcv
[3].destination
= host
->unixsocket
;
1321 fcv
[4].destination
= host
->bin_path
;
1323 fcv
[5].destination
= &(host
->check_local
);
1324 fcv
[6].destination
= &(host
->port
);
1325 fcv
[7].destination
= &(host
->max_procs
);
1326 fcv
[8].destination
= &(host
->disable_time
);
1328 fcv
[9].destination
= host
->bin_env
;
1329 fcv
[10].destination
= host
->bin_env_copy
;
1330 fcv
[11].destination
= &(host
->break_scriptfilename_for_php
);
1331 fcv
[12].destination
= &(host
->allow_xsendfile
);
1332 fcv
[13].destination
= host
->strip_request_uri
;
1333 fcv
[14].destination
= &(host
->kill_signal
);
1334 fcv
[15].destination
= &(host
->fix_root_path_name
);
1335 fcv
[16].destination
= &(host
->listen_backlog
);
1337 if (0 != config_insert_values_internal(srv
, da_host
->value
, fcv
, T_CONFIG_SCOPE_CONNECTION
)) {
1341 if ((!buffer_string_is_empty(host
->host
) || host
->port
) &&
1342 !buffer_string_is_empty(host
->unixsocket
)) {
1343 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsbs",
1344 "either host/port or socket have to be set in:",
1346 da_ext
->key
, " => (",
1347 da_host
->key
, " ( ...");
1352 if (!buffer_string_is_empty(host
->unixsocket
)) {
1353 /* unix domain socket */
1354 struct sockaddr_un un
;
1356 if (buffer_string_length(host
->unixsocket
) + 1 > sizeof(un
.sun_path
) - 2) {
1357 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsbs",
1358 "unixsocket is too long in:",
1360 da_ext
->key
, " => (",
1361 da_host
->key
, " ( ...");
1366 if (!buffer_string_is_empty(host
->bin_path
)
1367 && unixsocket_is_dup(p
, i
+1, host
->unixsocket
)) {
1368 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1369 "duplicate unixsocket path:",
1376 if (buffer_string_is_empty(host
->host
) &&
1377 buffer_string_is_empty(host
->bin_path
)) {
1378 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsbs",
1379 "host or binpath have to be set in:",
1381 da_ext
->key
, " => (",
1382 da_host
->key
, " ( ...");
1385 } else if (host
->port
== 0) {
1386 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbsbs",
1387 "port has to be set in:",
1389 da_ext
->key
, " => (",
1390 da_host
->key
, " ( ...");
1396 if (!buffer_string_is_empty(host
->bin_path
)) {
1397 /* a local socket + self spawning */
1401 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsbsd",
1402 "--- fastcgi spawning local",
1403 "\n\tproc:", host
->bin_path
,
1404 "\n\tport:", host
->port
,
1405 "\n\tsocket", host
->unixsocket
,
1406 "\n\tmax-procs:", host
->max_procs
);
1409 for (pno
= 0; pno
< host
->max_procs
; pno
++) {
1412 proc
= fastcgi_process_init();
1413 proc
->id
= host
->num_procs
++;
1416 if (buffer_string_is_empty(host
->unixsocket
)) {
1417 proc
->port
= host
->port
+ pno
;
1419 buffer_copy_buffer(proc
->unixsocket
, host
->unixsocket
);
1420 buffer_append_string_len(proc
->unixsocket
, CONST_STR_LEN("-"));
1421 buffer_append_int(proc
->unixsocket
, pno
);
1425 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
1426 "--- fastcgi spawning",
1427 "\n\tport:", host
->port
,
1428 "\n\tsocket", host
->unixsocket
,
1429 "\n\tcurrent:", pno
, "/", host
->max_procs
);
1432 if (!srv
->srvconf
.preflight_check
1433 && fcgi_spawn_connection(srv
, p
, host
, proc
)) {
1434 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1435 "[ERROR]: spawning fcgi failed.");
1436 fastcgi_process_free(proc
);
1440 fastcgi_status_init(srv
, p
->statuskey
, host
, proc
);
1442 proc
->next
= host
->first
;
1443 if (host
->first
) host
->first
->prev
= proc
;
1450 proc
= fastcgi_process_init();
1451 proc
->id
= host
->num_procs
++;
1453 host
->active_procs
++;
1454 proc
->state
= PROC_STATE_RUNNING
;
1456 if (buffer_string_is_empty(host
->unixsocket
)) {
1457 proc
->port
= host
->port
;
1459 buffer_copy_buffer(proc
->unixsocket
, host
->unixsocket
);
1462 fastcgi_status_init(srv
, p
->statuskey
, host
, proc
);
1466 host
->max_procs
= 1;
1469 if (!buffer_string_is_empty(fcgi_mode
)) {
1470 if (strcmp(fcgi_mode
->ptr
, "responder") == 0) {
1471 host
->mode
= FCGI_RESPONDER
;
1472 } else if (strcmp(fcgi_mode
->ptr
, "authorizer") == 0) {
1473 host
->mode
= FCGI_AUTHORIZER
;
1474 if (buffer_string_is_empty(host
->docroot
)) {
1475 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1476 "ERROR: docroot is required for authorizer mode.");
1480 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1481 "WARNING: unknown fastcgi mode:",
1482 fcgi_mode
, "(ignored, mode set to responder)");
1486 /* if extension already exists, take it */
1487 fastcgi_extension_insert(s
->exts
, da_ext
->key
, host
);
1494 buffer_free(fcgi_mode
);
1495 return HANDLER_GO_ON
;
1498 if (NULL
!= host
) fastcgi_host_free(host
);
1499 buffer_free(fcgi_mode
);
1500 return HANDLER_ERROR
;
1503 static int fcgi_set_state(server
*srv
, handler_ctx
*hctx
, fcgi_connection_state_t state
) {
1504 hctx
->state
= state
;
1505 hctx
->state_timestamp
= srv
->cur_ts
;
1511 static void fcgi_connection_close(server
*srv
, handler_ctx
*hctx
) {
1515 p
= hctx
->plugin_data
;
1516 con
= hctx
->remote_conn
;
1518 if (hctx
->fd
!= -1) {
1519 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1520 fdevent_unregister(srv
->ev
, hctx
->fd
);
1525 if (hctx
->host
&& hctx
->proc
) {
1526 if (hctx
->got_proc
) {
1527 /* after the connect the process gets a load */
1528 fcgi_proc_load_dec(srv
, hctx
);
1530 if (p
->conf
.debug
) {
1531 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsd",
1533 "pid:", hctx
->proc
->pid
,
1534 "socket:", hctx
->proc
->connection_name
,
1535 "load:", hctx
->proc
->load
);
1541 handler_ctx_free(srv
, hctx
);
1542 con
->plugin_ctx
[p
->id
] = NULL
;
1544 /* finish response (if not already finished) */
1545 if (con
->mode
== p
->id
1546 && (con
->state
== CON_STATE_HANDLE_REQUEST
|| con
->state
== CON_STATE_READ_POST
)) {
1547 /* (not CON_STATE_ERROR and not CON_STATE_RESPONSE_END,
1548 * i.e. not called from fcgi_connection_reset()) */
1550 /* Send an error if we haven't sent any data yet */
1551 if (0 == con
->file_started
) {
1552 con
->http_status
= 500;
1555 else if (!con
->file_finished
) {
1556 http_chunk_close(srv
, con
);
1557 con
->file_finished
= 1;
1562 static int fcgi_reconnect(server
*srv
, handler_ctx
*hctx
) {
1563 plugin_data
*p
= hctx
->plugin_data
;
1569 * connect was ok, connection was accepted
1570 * but the php accept loop checks after the accept if it should die or not.
1572 * if yes we can only detect it at a write()
1574 * next step is resetting this attemp and setup a connection again
1576 * if we have more than 5 reconnects for the same request, die
1580 * we have a connection but the child died by some other reason
1584 if (hctx
->fd
!= -1) {
1585 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1586 fdevent_unregister(srv
->ev
, hctx
->fd
);
1592 fcgi_set_state(srv
, hctx
, FCGI_STATE_INIT
);
1594 hctx
->request_id
= 0;
1597 if (p
->conf
.debug
> 2) {
1599 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
1600 "release proc for reconnect:",
1601 hctx
->proc
->pid
, hctx
->proc
->connection_name
);
1603 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1604 "release proc for reconnect:",
1605 hctx
->host
->unixsocket
);
1609 if (hctx
->proc
&& hctx
->got_proc
) {
1610 fcgi_proc_load_dec(srv
, hctx
);
1613 /* perhaps another host gives us more luck */
1614 fcgi_host_reset(srv
, hctx
);
1620 static handler_t
fcgi_connection_reset(server
*srv
, connection
*con
, void *p_d
) {
1621 plugin_data
*p
= p_d
;
1622 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
1623 if (hctx
) fcgi_connection_close(srv
, hctx
);
1625 return HANDLER_GO_ON
;
1629 static int fcgi_env_add(buffer
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
1632 size_t len_enc_len
= 0;
1634 if (!key
|| !val
) return -1;
1636 len
= key_len
+ val_len
;
1638 len
+= key_len
> 127 ? 4 : 1;
1639 len
+= val_len
> 127 ? 4 : 1;
1641 if (buffer_string_length(env
) + len
>= FCGI_MAX_LENGTH
) {
1643 * we can't append more headers, ignore it
1649 * field length can be 31bit max
1651 * HINT: this can't happen as FCGI_MAX_LENGTH is only 16bit
1653 force_assert(key_len
< 0x7fffffffu
);
1654 force_assert(val_len
< 0x7fffffffu
);
1656 buffer_string_prepare_append(env
, len
);
1658 if (key_len
> 127) {
1659 len_enc
[len_enc_len
++] = ((key_len
>> 24) & 0xff) | 0x80;
1660 len_enc
[len_enc_len
++] = (key_len
>> 16) & 0xff;
1661 len_enc
[len_enc_len
++] = (key_len
>> 8) & 0xff;
1662 len_enc
[len_enc_len
++] = (key_len
>> 0) & 0xff;
1664 len_enc
[len_enc_len
++] = (key_len
>> 0) & 0xff;
1667 if (val_len
> 127) {
1668 len_enc
[len_enc_len
++] = ((val_len
>> 24) & 0xff) | 0x80;
1669 len_enc
[len_enc_len
++] = (val_len
>> 16) & 0xff;
1670 len_enc
[len_enc_len
++] = (val_len
>> 8) & 0xff;
1671 len_enc
[len_enc_len
++] = (val_len
>> 0) & 0xff;
1673 len_enc
[len_enc_len
++] = (val_len
>> 0) & 0xff;
1676 buffer_append_string_len(env
, len_enc
, len_enc_len
);
1677 buffer_append_string_len(env
, key
, key_len
);
1678 buffer_append_string_len(env
, val
, val_len
);
1683 static int fcgi_header(FCGI_Header
* header
, unsigned char type
, size_t request_id
, int contentLength
, unsigned char paddingLength
) {
1684 force_assert(contentLength
<= FCGI_MAX_LENGTH
);
1686 header
->version
= FCGI_VERSION_1
;
1687 header
->type
= type
;
1688 header
->requestIdB0
= request_id
& 0xff;
1689 header
->requestIdB1
= (request_id
>> 8) & 0xff;
1690 header
->contentLengthB0
= contentLength
& 0xff;
1691 header
->contentLengthB1
= (contentLength
>> 8) & 0xff;
1692 header
->paddingLength
= paddingLength
;
1693 header
->reserved
= 0;
1700 CONNECTION_DELAYED
, /* retry after event, take same host */
1701 CONNECTION_OVERLOADED
, /* disable for 1 second, take another backend */
1702 CONNECTION_DEAD
/* disable for 60 seconds, take another backend */
1703 } connection_result_t
;
1705 static connection_result_t
fcgi_establish_connection(server
*srv
, handler_ctx
*hctx
) {
1706 struct sockaddr
*fcgi_addr
;
1707 struct sockaddr_in fcgi_addr_in
;
1708 #ifdef HAVE_SYS_UN_H
1709 struct sockaddr_un fcgi_addr_un
;
1713 fcgi_extension_host
*host
= hctx
->host
;
1714 fcgi_proc
*proc
= hctx
->proc
;
1715 int fcgi_fd
= hctx
->fd
;
1717 if (!buffer_string_is_empty(proc
->unixsocket
)) {
1718 #ifdef HAVE_SYS_UN_H
1719 /* use the unix domain socket */
1720 memset(&fcgi_addr_un
, 0, sizeof(fcgi_addr_un
));
1721 fcgi_addr_un
.sun_family
= AF_UNIX
;
1722 if (buffer_string_length(proc
->unixsocket
) + 1 > sizeof(fcgi_addr_un
.sun_path
)) {
1723 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
1724 "ERROR: Unix Domain socket filename too long:",
1728 memcpy(fcgi_addr_un
.sun_path
, proc
->unixsocket
->ptr
, buffer_string_length(proc
->unixsocket
) + 1);
1731 servlen
= SUN_LEN(&fcgi_addr_un
);
1734 servlen
= buffer_string_length(proc
->unixsocket
) + 1 + sizeof(fcgi_addr_un
.sun_family
);
1736 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_un
;
1738 if (buffer_string_is_empty(proc
->connection_name
)) {
1739 /* on remote spawing we have to set the connection-name now */
1740 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("unix:"));
1741 buffer_append_string_buffer(proc
->connection_name
, proc
->unixsocket
);
1744 return CONNECTION_DEAD
;
1747 memset(&fcgi_addr_in
, 0, sizeof(fcgi_addr_in
));
1748 fcgi_addr_in
.sin_family
= AF_INET
;
1749 if (!buffer_string_is_empty(host
->host
)) {
1750 if (0 == inet_aton(host
->host
->ptr
, &(fcgi_addr_in
.sin_addr
))) {
1751 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1752 "converting IP address failed for", host
->host
,
1753 "\nBe sure to specify an IP address here");
1755 return CONNECTION_DEAD
;
1758 fcgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
1760 fcgi_addr_in
.sin_port
= htons(proc
->port
);
1761 servlen
= sizeof(fcgi_addr_in
);
1763 fcgi_addr
= (struct sockaddr
*) &fcgi_addr_in
;
1765 if (buffer_string_is_empty(proc
->connection_name
)) {
1766 /* on remote spawing we have to set the connection-name now */
1767 buffer_copy_string_len(proc
->connection_name
, CONST_STR_LEN("tcp:"));
1768 if (!buffer_string_is_empty(host
->host
)) {
1769 buffer_append_string_buffer(proc
->connection_name
, host
->host
);
1771 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN("localhost"));
1773 buffer_append_string_len(proc
->connection_name
, CONST_STR_LEN(":"));
1774 buffer_append_int(proc
->connection_name
, proc
->port
);
1778 if (-1 == connect(fcgi_fd
, fcgi_addr
, servlen
)) {
1779 if (errno
== EINPROGRESS
||
1780 errno
== EALREADY
||
1782 if (hctx
->conf
.debug
> 2) {
1783 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1784 "connect delayed; will continue later:", proc
->connection_name
);
1787 return CONNECTION_DELAYED
;
1788 } else if (errno
== EAGAIN
) {
1789 if (hctx
->conf
.debug
) {
1790 log_error_write(srv
, __FILE__
, __LINE__
, "sbsd",
1791 "This means that you have more incoming requests than your FastCGI backend can handle in parallel."
1792 "It might help to spawn more FastCGI backends or PHP children; if not, decrease server.max-connections."
1793 "The load for this FastCGI backend", proc
->connection_name
, "is", proc
->load
);
1796 return CONNECTION_OVERLOADED
;
1798 log_error_write(srv
, __FILE__
, __LINE__
, "sssb",
1800 strerror(errno
), "on",
1801 proc
->connection_name
);
1803 return CONNECTION_DEAD
;
1807 hctx
->reconnects
= 0;
1808 if (hctx
->conf
.debug
> 1) {
1809 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1810 "connect succeeded: ", fcgi_fd
);
1813 return CONNECTION_OK
;
1816 #define FCGI_ENV_ADD_CHECK(ret, con) \
1818 con->http_status = 400; \
1819 con->file_finished = 1; \
1822 static int fcgi_env_add_request_headers(server
*srv
, connection
*con
, plugin_data
*p
) {
1825 for (i
= 0; i
< con
->request
.headers
->used
; i
++) {
1828 ds
= (data_string
*)con
->request
.headers
->data
[i
];
1830 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
1831 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 1);
1833 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
)),con
);
1837 for (i
= 0; i
< con
->environment
->used
; i
++) {
1840 ds
= (data_string
*)con
->environment
->data
[i
];
1842 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
1843 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 0);
1845 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
)), con
);
1852 static int fcgi_create_env(server
*srv
, handler_ctx
*hctx
, size_t request_id
) {
1853 FCGI_BeginRequestRecord beginRecord
;
1856 char buf
[LI_ITOSTRING_LENGTH
];
1859 char b2
[INET6_ADDRSTRLEN
+ 1];
1862 plugin_data
*p
= hctx
->plugin_data
;
1863 fcgi_extension_host
*host
= hctx
->host
;
1865 connection
*con
= hctx
->remote_conn
;
1866 server_socket
*srv_sock
= con
->srv_socket
;
1869 socklen_t our_addr_len
;
1871 /* send FCGI_BEGIN_REQUEST */
1873 fcgi_header(&(beginRecord
.header
), FCGI_BEGIN_REQUEST
, request_id
, sizeof(beginRecord
.body
), 0);
1874 beginRecord
.body
.roleB0
= host
->mode
;
1875 beginRecord
.body
.roleB1
= 0;
1876 beginRecord
.body
.flags
= 0;
1877 memset(beginRecord
.body
.reserved
, 0, sizeof(beginRecord
.body
.reserved
));
1879 /* send FCGI_PARAMS */
1880 buffer_string_prepare_copy(p
->fcgi_env
, 1023);
1883 if (buffer_is_empty(con
->conf
.server_tag
)) {
1884 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_DESC
)),con
)
1886 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con
->conf
.server_tag
)),con
)
1889 if (!buffer_is_empty(con
->server_name
)) {
1890 size_t len
= buffer_string_length(con
->server_name
);
1892 if (con
->server_name
->ptr
[0] == '[') {
1893 const char *colon
= strstr(con
->server_name
->ptr
, "]:");
1894 if (colon
) len
= (colon
+ 1) - con
->server_name
->ptr
;
1896 const char *colon
= strchr(con
->server_name
->ptr
, ':');
1897 if (colon
) len
= colon
- con
->server_name
->ptr
;
1900 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SERVER_NAME"), con
->server_name
->ptr
, len
),con
)
1903 s
= inet_ntop(srv_sock
->addr
.plain
.sa_family
,
1904 srv_sock
->addr
.plain
.sa_family
== AF_INET6
?
1905 (const void *) &(srv_sock
->addr
.ipv6
.sin6_addr
) :
1906 (const void *) &(srv_sock
->addr
.ipv4
.sin_addr
),
1909 s
= inet_ntoa(srv_sock
->addr
.ipv4
.sin_addr
);
1911 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SERVER_NAME"), s
, strlen(s
)),con
)
1914 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1")),con
)
1916 li_utostrn(buf
, sizeof(buf
),
1918 ntohs(srv_sock
->addr
.plain
.sa_family
? srv_sock
->addr
.ipv6
.sin6_port
: srv_sock
->addr
.ipv4
.sin_port
)
1920 ntohs(srv_sock
->addr
.ipv4
.sin_port
)
1924 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SERVER_PORT"), buf
, strlen(buf
)),con
)
1926 /* get the server-side of the connection to the client */
1927 our_addr_len
= sizeof(our_addr
);
1929 if (-1 == getsockname(con
->fd
, &(our_addr
.plain
), &our_addr_len
)) {
1930 s
= inet_ntop_cache_get_ip(srv
, &(srv_sock
->addr
));
1932 s
= inet_ntop_cache_get_ip(srv
, &(our_addr
));
1934 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SERVER_ADDR"), s
, strlen(s
)),con
)
1936 li_utostrn(buf
, sizeof(buf
),
1938 ntohs(con
->dst_addr
.plain
.sa_family
? con
->dst_addr
.ipv6
.sin6_port
: con
->dst_addr
.ipv4
.sin_port
)
1940 ntohs(con
->dst_addr
.ipv4
.sin_port
)
1944 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("REMOTE_PORT"), buf
, strlen(buf
)),con
)
1946 s
= inet_ntop_cache_get_ip(srv
, &(con
->dst_addr
));
1947 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("REMOTE_ADDR"), s
, strlen(s
)),con
)
1949 if (con
->request
.content_length
> 0 && host
->mode
!= FCGI_AUTHORIZER
) {
1950 /* CGI-SPEC 6.1.2 and FastCGI spec 6.3 */
1952 li_itostrn(buf
, sizeof(buf
), con
->request
.content_length
);
1953 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("CONTENT_LENGTH"), buf
, strlen(buf
)),con
)
1956 if (host
->mode
!= FCGI_AUTHORIZER
) {
1958 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1959 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1960 * (6.1.14, 6.1.6, 6.1.7)
1961 * For AUTHORIZER mode these headers should be omitted.
1964 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con
->uri
.path
)),con
)
1966 if (!buffer_string_is_empty(con
->request
.pathinfo
)) {
1967 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con
->request
.pathinfo
)),con
)
1969 /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1971 if (!buffer_string_is_empty(host
->docroot
)) {
1972 buffer_copy_buffer(p
->path
, host
->docroot
);
1974 buffer_copy_buffer(p
->path
, con
->physical
.basedir
);
1976 buffer_append_string_buffer(p
->path
, con
->request
.pathinfo
);
1977 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p
->path
)),con
)
1979 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN("")),con
)
1984 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1985 * http://www.php.net/manual/en/reserved.variables.php
1986 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1987 * TODO: this code should be checked against cgi.fix_pathinfo php
1991 if (!buffer_string_is_empty(host
->docroot
)) {
1993 * rewrite SCRIPT_FILENAME
1997 buffer_copy_buffer(p
->path
, host
->docroot
);
1998 buffer_append_string_buffer(p
->path
, con
->uri
.path
);
2000 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
)),con
)
2001 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host
->docroot
)),con
)
2003 buffer_copy_buffer(p
->path
, con
->physical
.path
);
2005 /* cgi.fix_pathinfo need a broken SCRIPT_FILENAME to find out what PATH_INFO is itself
2007 * see src/sapi/cgi_main.c, init_request_info()
2009 if (host
->break_scriptfilename_for_php
) {
2010 buffer_append_string_buffer(p
->path
, con
->request
.pathinfo
);
2013 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
)),con
)
2014 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con
->physical
.basedir
)),con
)
2017 if (!buffer_string_is_empty(host
->strip_request_uri
)) {
2018 /* we need at least one char to strip off */
2022 * stripping /app1 or /app1/ should lead to
2027 if ('/' != host
->strip_request_uri
->ptr
[buffer_string_length(host
->strip_request_uri
) - 1]) {
2028 /* fix the user-input to have / as last char */
2029 buffer_append_string_len(host
->strip_request_uri
, CONST_STR_LEN("/"));
2032 if (buffer_string_length(con
->request
.orig_uri
) >= buffer_string_length(host
->strip_request_uri
) &&
2033 0 == strncmp(con
->request
.orig_uri
->ptr
, host
->strip_request_uri
->ptr
, buffer_string_length(host
->strip_request_uri
))) {
2034 /* the left is the same */
2036 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("REQUEST_URI"),
2037 con
->request
.orig_uri
->ptr
+ (buffer_string_length(host
->strip_request_uri
) - 1),
2038 buffer_string_length(con
->request
.orig_uri
) - (buffer_string_length(host
->strip_request_uri
) - 1)), con
);
2040 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con
->request
.orig_uri
)),con
)
2043 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con
->request
.orig_uri
)),con
)
2045 if (!buffer_is_equal(con
->request
.uri
, con
->request
.orig_uri
)) {
2046 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con
->request
.uri
)),con
)
2048 if (!buffer_string_is_empty(con
->uri
.query
)) {
2049 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con
->uri
.query
)),con
)
2051 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN("")),con
)
2054 s
= get_http_method_name(con
->request
.http_method
);
2056 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("REQUEST_METHOD"), s
, strlen(s
)),con
)
2057 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")),con
) /* if php is compiled with --force-redirect */
2058 s
= get_http_version_name(con
->request
.http_version
);
2060 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("SERVER_PROTOCOL"), s
, strlen(s
)),con
)
2062 if (buffer_is_equal_caseless_string(con
->uri
.scheme
, CONST_STR_LEN("https"))) {
2063 FCGI_ENV_ADD_CHECK(fcgi_env_add(p
->fcgi_env
, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on")),con
)
2066 FCGI_ENV_ADD_CHECK(fcgi_env_add_request_headers(srv
, con
, p
), con
);
2069 buffer
*b
= buffer_init();
2071 buffer_copy_string_len(b
, (const char *)&beginRecord
, sizeof(beginRecord
));
2073 fcgi_header(&(header
), FCGI_PARAMS
, request_id
, buffer_string_length(p
->fcgi_env
), 0);
2074 buffer_append_string_len(b
, (const char *)&header
, sizeof(header
));
2075 buffer_append_string_buffer(b
, p
->fcgi_env
);
2077 fcgi_header(&(header
), FCGI_PARAMS
, request_id
, 0, 0);
2078 buffer_append_string_len(b
, (const char *)&header
, sizeof(header
));
2080 chunkqueue_append_buffer(hctx
->wb
, b
);
2084 if (con
->request
.content_length
) {
2085 chunkqueue
*req_cq
= con
->request_content_queue
;
2088 /* something to send ? */
2089 for (offset
= 0; offset
!= req_cq
->bytes_in
; ) {
2090 off_t weWant
= req_cq
->bytes_in
- offset
> FCGI_MAX_LENGTH
? FCGI_MAX_LENGTH
: req_cq
->bytes_in
- offset
;
2092 /* we announce toWrite octets
2093 * now take all the request_content chunks that we need to fill this request
2096 fcgi_header(&(header
), FCGI_STDIN
, request_id
, weWant
, 0);
2097 chunkqueue_append_mem(hctx
->wb
, (const char *)&header
, sizeof(header
));
2099 if (p
->conf
.debug
> 10) {
2100 log_error_write(srv
, __FILE__
, __LINE__
, "soso", "tosend:", offset
, "/", req_cq
->bytes_in
);
2103 chunkqueue_steal(hctx
->wb
, req_cq
, weWant
);
2109 /* terminate STDIN */
2110 fcgi_header(&(header
), FCGI_STDIN
, request_id
, 0, 0);
2111 chunkqueue_append_mem(hctx
->wb
, (const char *)&header
, sizeof(header
));
2116 static int fcgi_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
) {
2119 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2120 fcgi_extension_host
*host
= hctx
->host
;
2121 int have_sendfile2
= 0;
2122 off_t sendfile2_content_length
= 0;
2127 for (s
= in
->ptr
; NULL
!= (ns
= strchr(s
, '\n')); s
= ns
+ 1) {
2130 data_string
*ds
= NULL
;
2132 /* a good day. Someone has read the specs and is sending a \r\n to us */
2142 if (NULL
== (value
= strchr(s
, ':'))) {
2143 /* we expect: "<key>: <value>\n" */
2147 key_len
= value
- key
;
2151 while (*value
== ' ' || *value
== '\t') value
++;
2153 if (host
->mode
!= FCGI_AUTHORIZER
||
2154 !(con
->http_status
== 0 ||
2155 con
->http_status
== 200)) {
2156 /* authorizers shouldn't affect the response headers sent back to the client */
2158 /* don't forward Status: */
2159 if (0 != strncasecmp(key
, "Status", key_len
)) {
2160 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
2161 ds
= data_response_init();
2163 buffer_copy_string_len(ds
->key
, key
, key_len
);
2164 buffer_copy_string(ds
->value
, value
);
2166 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
2172 if (0 == strncasecmp(key
, "Date", key_len
)) {
2173 con
->parsed_response
|= HTTP_DATE
;
2177 if (0 == strncasecmp(key
, "Status", key_len
)) {
2178 int status
= strtol(value
, NULL
, 10);
2179 if (status
>= 100 && status
< 1000) {
2180 con
->http_status
= status
;
2181 con
->parsed_response
|= HTTP_STATUS
;
2183 con
->http_status
= 502;
2188 if (0 == strncasecmp(key
, "Location", key_len
)) {
2189 con
->parsed_response
|= HTTP_LOCATION
;
2193 if (0 == strncasecmp(key
, "Connection", key_len
)) {
2194 con
->response
.keep_alive
= (0 == strcasecmp(value
, "Keep-Alive")) ? 1 : 0;
2195 con
->parsed_response
|= HTTP_CONNECTION
;
2199 if (host
->allow_xsendfile
&& 0 == strncasecmp(key
, "X-Sendfile2", key_len
)&& hctx
->send_content_body
) {
2204 char *filename
, *range
;
2205 stat_cache_entry
*sce
;
2206 off_t begin_range
, end_range
, range_len
;
2208 while (' ' == *pos
) pos
++;
2212 if (NULL
== (range
= strchr(pos
, ' '))) {
2214 if (p
->conf
.debug
) {
2215 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't find range after filename:", filename
);
2219 buffer_copy_string_len(srv
->tmp_buf
, filename
, range
- filename
);
2221 /* find end of range */
2222 for (pos
= ++range
; *pos
&& *pos
!= ' ' && *pos
!= ','; pos
++) ;
2224 buffer_urldecode_path(srv
->tmp_buf
);
2225 if (HANDLER_ERROR
== stat_cache_get_entry(srv
, con
, srv
->tmp_buf
, &sce
)) {
2226 if (p
->conf
.debug
) {
2227 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2228 "send-file error: couldn't get stat_cache entry for X-Sendfile2:",
2232 } else if (!S_ISREG(sce
->st
.st_mode
)) {
2233 if (p
->conf
.debug
) {
2234 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2235 "send-file error: wrong filetype for X-Sendfile2:",
2240 /* found the file */
2243 begin_range
= 0; end_range
= sce
->st
.st_size
- 1;
2247 begin_range
= strtoll(range
, &rpos
, 10);
2248 if (errno
!= 0 || begin_range
< 0 || rpos
== range
) goto range_failed
;
2249 if ('-' != *rpos
++) goto range_failed
;
2252 end_range
= strtoll(range
, &rpos
, 10);
2253 if (errno
!= 0 || end_range
< 0 || rpos
== range
) goto range_failed
;
2255 if (rpos
!= pos
) goto range_failed
;
2260 if (p
->conf
.debug
) {
2261 log_error_write(srv
, __FILE__
, __LINE__
, "ss", "Couldn't decode range after filename:", filename
);
2268 /* no parameters accepted */
2270 while (*pos
== ' ') pos
++;
2271 if (*pos
!= '\0' && *pos
!= ',') return 502;
2273 range_len
= end_range
- begin_range
+ 1;
2274 if (range_len
< 0) return 502;
2275 if (range_len
!= 0) {
2276 if (0 != http_chunk_append_file_range(srv
, con
, srv
->tmp_buf
, begin_range
, range_len
)) {
2280 sendfile2_content_length
+= range_len
;
2282 if (*pos
== ',') pos
++;
2287 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
2288 con
->response
.content_length
= strtoul(value
, NULL
, 10);
2289 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
2291 if (con
->response
.content_length
< 0) con
->response
.content_length
= 0;
2299 if (have_sendfile2
) {
2302 hctx
->send_content_body
= 0;
2303 joblist_append(srv
, con
);
2305 /* fix content-length */
2306 if (NULL
== (dcls
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
2307 dcls
= data_response_init();
2310 buffer_copy_string_len(dcls
->key
, "Content-Length", sizeof("Content-Length")-1);
2311 buffer_copy_int(dcls
->value
, sendfile2_content_length
);
2312 array_replace(con
->response
.headers
, (data_unset
*)dcls
);
2314 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
2315 con
->response
.content_length
= sendfile2_content_length
;
2318 /* CGI/1.1 rev 03 - 7.2.1.2 */
2319 if ((con
->parsed_response
& HTTP_LOCATION
) &&
2320 !(con
->parsed_response
& HTTP_STATUS
)) {
2321 con
->http_status
= 302;
2333 } fastcgi_response_packet
;
2335 static int fastcgi_get_packet(server
*srv
, handler_ctx
*hctx
, fastcgi_response_packet
*packet
) {
2339 FCGI_Header
*header
;
2341 if (!hctx
->rb
->first
) return -1;
2343 packet
->b
= buffer_init();
2346 packet
->padding
= 0;
2347 packet
->request_id
= 0;
2349 offset
= 0; toread
= 8;
2350 /* get at least the FastCGI header */
2351 for (c
= hctx
->rb
->first
; c
; c
= c
->next
) {
2352 size_t weHave
= buffer_string_length(c
->mem
) - c
->offset
;
2354 if (weHave
> toread
) weHave
= toread
;
2356 buffer_append_string_len(packet
->b
, c
->mem
->ptr
+ c
->offset
, weHave
);
2358 offset
= weHave
; /* skip offset bytes in chunk for "real" data */
2360 if (0 == toread
) break;
2363 if (buffer_string_length(packet
->b
) < sizeof(FCGI_Header
)) {
2365 if (hctx
->plugin_data
->conf
.debug
) {
2366 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");
2369 buffer_free(packet
->b
);
2374 /* we have at least a header, now check how much me have to fetch */
2375 header
= (FCGI_Header
*)(packet
->b
->ptr
);
2377 packet
->len
= (header
->contentLengthB0
| (header
->contentLengthB1
<< 8)) + header
->paddingLength
;
2378 packet
->request_id
= (header
->requestIdB0
| (header
->requestIdB1
<< 8));
2379 packet
->type
= header
->type
;
2380 packet
->padding
= header
->paddingLength
;
2382 /* ->b should only be the content */
2383 buffer_string_set_length(packet
->b
, 0);
2386 /* copy the content */
2387 for (; c
&& (buffer_string_length(packet
->b
) < packet
->len
); c
= c
->next
) {
2388 size_t weWant
= packet
->len
- buffer_string_length(packet
->b
);
2389 size_t weHave
= buffer_string_length(c
->mem
) - c
->offset
- offset
;
2391 if (weHave
> weWant
) weHave
= weWant
;
2393 buffer_append_string_len(packet
->b
, c
->mem
->ptr
+ c
->offset
+ offset
, weHave
);
2395 /* we only skipped the first bytes as they belonged to the fcgi header */
2399 if (buffer_string_length(packet
->b
) < packet
->len
) {
2400 /* we didn't get the full packet */
2402 buffer_free(packet
->b
);
2406 buffer_string_set_length(packet
->b
, buffer_string_length(packet
->b
) - packet
->padding
);
2409 chunkqueue_mark_written(hctx
->rb
, packet
->len
+ sizeof(FCGI_Header
));
2414 static int fcgi_demux_response(server
*srv
, handler_ctx
*hctx
) {
2419 plugin_data
*p
= hctx
->plugin_data
;
2420 connection
*con
= hctx
->remote_conn
;
2421 int fcgi_fd
= hctx
->fd
;
2422 fcgi_extension_host
*host
= hctx
->host
;
2423 fcgi_proc
*proc
= hctx
->proc
;
2426 * check how much we have to read
2428 if (ioctl(hctx
->fd
, FIONREAD
, &toread
)) {
2429 if (errno
== EAGAIN
) return 0;
2430 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2431 "unexpected end-of-file (perhaps the fastcgi process died):",
2440 chunkqueue_get_memory(hctx
->rb
, &mem
, &mem_len
, 0, toread
);
2441 r
= read(hctx
->fd
, mem
, mem_len
);
2442 chunkqueue_use_memory(hctx
->rb
, r
> 0 ? r
: 0);
2445 if (errno
== EAGAIN
) return 0;
2446 log_error_write(srv
, __FILE__
, __LINE__
, "sds",
2447 "unexpected end-of-file (perhaps the fastcgi process died):",
2448 fcgi_fd
, strerror(errno
));
2452 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsb",
2453 "unexpected end-of-file (perhaps the fastcgi process died):",
2455 "socket:", proc
->connection_name
);
2461 * parse the fastcgi packets and forward the content to the write-queue
2465 fastcgi_response_packet packet
;
2467 /* check if we have at least one packet */
2468 if (0 != fastcgi_get_packet(srv
, hctx
, &packet
)) {
2469 /* no full packet */
2473 switch(packet
.type
) {
2475 if (packet
.len
== 0) break;
2477 /* is the header already finished */
2478 if (0 == con
->file_started
) {
2482 /* search for header terminator
2484 * if we start with \r\n check if last packet terminated with \r\n
2485 * if we start with \n check if last packet terminated with \n
2486 * search for \r\n\r\n
2490 buffer_append_string_buffer(hctx
->response_header
, packet
.b
);
2492 if (NULL
!= (c
= buffer_search_string_len(hctx
->response_header
, CONST_STR_LEN("\r\n\r\n")))) {
2493 char *hend
= c
+ 4; /* header end == body start */
2494 size_t hlen
= hend
- hctx
->response_header
->ptr
;
2495 buffer_copy_string_len(packet
.b
, hend
, buffer_string_length(hctx
->response_header
) - hlen
);
2496 buffer_string_set_length(hctx
->response_header
, hlen
);
2497 } else if (NULL
!= (c
= buffer_search_string_len(hctx
->response_header
, CONST_STR_LEN("\n\n")))) {
2498 char *hend
= c
+ 2; /* header end == body start */
2499 size_t hlen
= hend
- hctx
->response_header
->ptr
;
2500 buffer_copy_string_len(packet
.b
, hend
, buffer_string_length(hctx
->response_header
) - hlen
);
2501 buffer_string_set_length(hctx
->response_header
, hlen
);
2503 /* no luck, no header found */
2507 /* parse the response header */
2508 if ((ret
= fcgi_response_parse(srv
, con
, p
, hctx
->response_header
))) {
2509 con
->http_status
= ret
;
2510 hctx
->send_content_body
= 0;
2511 con
->file_started
= 1;
2515 con
->file_started
= 1;
2517 if (host
->mode
== FCGI_AUTHORIZER
&&
2518 (con
->http_status
== 0 ||
2519 con
->http_status
== 200)) {
2520 /* a authorizer with approved the static request, ignore the content here */
2521 hctx
->send_content_body
= 0;
2524 if (host
->allow_xsendfile
&& hctx
->send_content_body
&&
2525 (NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "X-LIGHTTPD-send-file"))
2526 || NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "X-Sendfile")))) {
2527 if (0 == http_chunk_append_file(srv
, con
, ds
->value
)) {
2529 data_string
*dcls
= (data_string
*) array_get_element(con
->response
.headers
, "Content-Length");
2530 if (dcls
) buffer_reset(dcls
->value
);
2531 con
->parsed_response
&= ~HTTP_CONTENT_LENGTH
;
2532 con
->response
.content_length
= -1;
2533 hctx
->send_content_body
= 0; /* ignore the content */
2535 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2536 "send-file error: couldn't get stat_cache entry for:",
2538 con
->http_status
= 404;
2539 hctx
->send_content_body
= 0;
2540 con
->file_started
= 1;
2546 if (hctx
->send_content_body
&& buffer_string_length(packet
.b
) > 0) {
2547 /* enable chunked-transfer-encoding */
2548 if (con
->request
.http_version
== HTTP_VERSION_1_1
&&
2549 !(con
->parsed_response
& HTTP_CONTENT_LENGTH
)) {
2550 con
->response
.transfer_encoding
= HTTP_TRANSFER_ENCODING_CHUNKED
;
2553 http_chunk_append_buffer(srv
, con
, packet
.b
);
2555 } else if (hctx
->send_content_body
&& !buffer_string_is_empty(packet
.b
)) {
2556 if (con
->request
.http_version
== HTTP_VERSION_1_1
&&
2557 !(con
->parsed_response
& HTTP_CONTENT_LENGTH
)) {
2558 /* enable chunked-transfer-encoding */
2559 con
->response
.transfer_encoding
= HTTP_TRANSFER_ENCODING_CHUNKED
;
2562 http_chunk_append_buffer(srv
, con
, packet
.b
);
2566 if (packet
.len
== 0) break;
2568 log_error_write_multiline_buffer(srv
, __FILE__
, __LINE__
, packet
.b
, "s",
2572 case FCGI_END_REQUEST
:
2573 con
->file_finished
= 1;
2575 if (host
->mode
!= FCGI_AUTHORIZER
||
2576 !(con
->http_status
== 0 ||
2577 con
->http_status
== 200)) {
2578 /* send chunk-end if necessary */
2579 http_chunk_close(srv
, con
);
2585 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2586 "FastCGI: header.type not handled: ", packet
.type
);
2589 buffer_free(packet
.b
);
2595 static int fcgi_restart_dead_procs(server
*srv
, plugin_data
*p
, fcgi_extension_host
*host
) {
2598 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2601 if (p
->conf
.debug
> 2) {
2602 log_error_write(srv
, __FILE__
, __LINE__
, "sbdddd",
2604 proc
->connection_name
,
2612 * if the remote side is overloaded, we check back after <n> seconds
2615 switch (proc
->state
) {
2616 case PROC_STATE_KILLED
:
2617 case PROC_STATE_UNSET
:
2618 /* this should never happen as long as adaptive spawing is disabled */
2622 case PROC_STATE_RUNNING
:
2624 case PROC_STATE_OVERLOADED
:
2625 if (srv
->cur_ts
<= proc
->disabled_until
) break;
2627 proc
->state
= PROC_STATE_RUNNING
;
2628 host
->active_procs
++;
2630 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2631 "fcgi-server re-enabled:",
2632 host
->host
, host
->port
,
2635 case PROC_STATE_DIED_WAIT_FOR_PID
:
2636 /* non-local procs don't have PIDs to wait for */
2637 if (!proc
->is_local
) {
2638 proc
->state
= PROC_STATE_DIED
;
2640 /* the child should not terminate at all */
2643 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2645 /* child is still alive */
2646 if (srv
->cur_ts
<= proc
->disabled_until
) break;
2648 proc
->state
= PROC_STATE_RUNNING
;
2649 host
->active_procs
++;
2651 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2652 "fcgi-server re-enabled:",
2653 host
->host
, host
->port
,
2657 if (errno
== EINTR
) continue;
2659 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2660 "child died somehow, waitpid failed:",
2662 proc
->state
= PROC_STATE_DIED
;
2665 if (WIFEXITED(status
)) {
2667 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2668 "child exited, pid:", proc
->pid
,
2669 "status:", WEXITSTATUS(status
));
2671 } else if (WIFSIGNALED(status
)) {
2672 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2676 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2677 "child died somehow:",
2681 proc
->state
= PROC_STATE_DIED
;
2688 /* fall through if we have a dead proc now */
2689 if (proc
->state
!= PROC_STATE_DIED
) break;
2691 case PROC_STATE_DIED
:
2692 /* local procs get restarted by us,
2693 * remote ones hopefully by the admin */
2695 if (!buffer_string_is_empty(host
->bin_path
)) {
2696 /* we still have connections bound to this proc,
2697 * let them terminate first */
2698 if (proc
->load
!= 0) break;
2700 /* restart the child */
2702 if (p
->conf
.debug
) {
2703 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsd",
2704 "--- fastcgi spawning",
2705 "\n\tsocket", proc
->connection_name
,
2706 "\n\tcurrent:", 1, "/", host
->max_procs
);
2709 if (fcgi_spawn_connection(srv
, p
, host
, proc
)) {
2710 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2711 "ERROR: spawning fcgi failed.");
2712 return HANDLER_ERROR
;
2715 if (srv
->cur_ts
<= proc
->disabled_until
) break;
2717 proc
->state
= PROC_STATE_RUNNING
;
2718 host
->active_procs
++;
2720 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
2721 "fcgi-server re-enabled:",
2722 proc
->connection_name
);
2731 static handler_t
fcgi_write_request(server
*srv
, handler_ctx
*hctx
) {
2732 plugin_data
*p
= hctx
->plugin_data
;
2733 fcgi_extension_host
*host
= hctx
->host
;
2734 connection
*con
= hctx
->remote_conn
;
2742 * - tcp socket (do not check host->host->uses, as it may be not set which means INADDR_LOOPBACK)
2746 log_error_write(srv
, __FILE__
, __LINE__
, "s", "fatal error: host = NULL");
2747 return HANDLER_ERROR
;
2749 if ((!host
->port
&& buffer_string_is_empty(host
->unixsocket
))) {
2750 log_error_write(srv
, __FILE__
, __LINE__
, "s", "fatal error: neither host->port nor host->unixsocket is set");
2751 return HANDLER_ERROR
;
2754 /* we can't handle this in the switch as we have to fall through in it */
2755 if (hctx
->state
== FCGI_STATE_CONNECT_DELAYED
) {
2757 socklen_t socket_error_len
= sizeof(socket_error
);
2759 /* try to finish the connect() */
2760 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
2761 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2762 "getsockopt failed:", strerror(errno
));
2764 fcgi_host_disable(srv
, hctx
);
2766 return HANDLER_ERROR
;
2768 if (socket_error
!= 0) {
2769 if (!hctx
->proc
->is_local
|| p
->conf
.debug
) {
2770 /* local procs get restarted */
2772 log_error_write(srv
, __FILE__
, __LINE__
, "sssb",
2773 "establishing connection failed:", strerror(socket_error
),
2774 "socket:", hctx
->proc
->connection_name
);
2777 fcgi_host_disable(srv
, hctx
);
2778 log_error_write(srv
, __FILE__
, __LINE__
, "sdssdsd",
2779 "backend is overloaded; we'll disable it for", hctx
->host
->disable_time
, "seconds and send the request to another backend instead:",
2780 "reconnects:", hctx
->reconnects
,
2781 "load:", host
->load
);
2783 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2784 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".died"));
2786 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2788 return HANDLER_ERROR
;
2790 /* go on with preparing the request */
2791 hctx
->state
= FCGI_STATE_PREPARE_WRITE
;
2795 switch(hctx
->state
) {
2796 case FCGI_STATE_CONNECT_DELAYED
:
2797 /* should never happen */
2798 return HANDLER_WAIT_FOR_EVENT
;
2799 case FCGI_STATE_INIT
:
2800 /* do we have a running process for this host (max-procs) ? */
2803 for (proc
= hctx
->host
->first
;
2804 proc
&& proc
->state
!= PROC_STATE_RUNNING
;
2807 /* all children are dead */
2811 return HANDLER_ERROR
;
2816 /* check the other procs if they have a lower load */
2817 for (proc
= proc
->next
; proc
; proc
= proc
->next
) {
2818 if (proc
->state
!= PROC_STATE_RUNNING
) continue;
2819 if (proc
->load
< hctx
->proc
->load
) hctx
->proc
= proc
;
2822 ret
= buffer_string_is_empty(host
->unixsocket
) ? AF_INET
: AF_UNIX
;
2824 if (-1 == (hctx
->fd
= socket(ret
, SOCK_STREAM
, 0))) {
2825 if (errno
== EMFILE
||
2827 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2828 "wait for fd at connection:", con
->fd
);
2830 return HANDLER_WAIT_FOR_FD
;
2833 log_error_write(srv
, __FILE__
, __LINE__
, "ssdd",
2834 "socket failed:", strerror(errno
), srv
->cur_fds
, srv
->max_fds
);
2835 return HANDLER_ERROR
;
2841 fdevent_register(srv
->ev
, hctx
->fd
, fcgi_handle_fdevent
, hctx
);
2843 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
2844 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2845 "fcntl failed:", strerror(errno
));
2847 return HANDLER_ERROR
;
2850 if (hctx
->proc
->is_local
) {
2851 hctx
->pid
= hctx
->proc
->pid
;
2854 switch (fcgi_establish_connection(srv
, hctx
)) {
2855 case CONNECTION_DELAYED
:
2856 /* connection is in progress, wait for an event and call getsockopt() below */
2858 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2860 fcgi_set_state(srv
, hctx
, FCGI_STATE_CONNECT_DELAYED
);
2861 return HANDLER_WAIT_FOR_EVENT
;
2862 case CONNECTION_OVERLOADED
:
2863 /* cool down the backend, it is overloaded
2866 if (hctx
->host
->disable_time
) {
2867 log_error_write(srv
, __FILE__
, __LINE__
, "sdssdsd",
2868 "backend is overloaded; we'll disable it for", hctx
->host
->disable_time
, "seconds and send the request to another backend instead:",
2869 "reconnects:", hctx
->reconnects
,
2870 "load:", host
->load
);
2872 hctx
->proc
->disabled_until
= srv
->cur_ts
+ hctx
->host
->disable_time
;
2873 if (hctx
->proc
->state
== PROC_STATE_RUNNING
) hctx
->host
->active_procs
--;
2874 hctx
->proc
->state
= PROC_STATE_OVERLOADED
;
2877 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2878 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".overloaded"));
2880 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2882 return HANDLER_ERROR
;
2883 case CONNECTION_DEAD
:
2884 /* we got a hard error from the backend like
2885 * - ECONNREFUSED for tcp-ip sockets
2886 * - ENOENT for unix-domain-sockets
2888 * for check if the host is back in hctx->host->disable_time seconds
2891 fcgi_host_disable(srv
, hctx
);
2893 log_error_write(srv
, __FILE__
, __LINE__
, "sdssdsd",
2894 "backend died; we'll disable it for", hctx
->host
->disable_time
, "seconds and send the request to another backend instead:",
2895 "reconnects:", hctx
->reconnects
,
2896 "load:", host
->load
);
2898 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2899 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".died"));
2901 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2903 return HANDLER_ERROR
;
2905 /* everything is ok, go on */
2907 fcgi_set_state(srv
, hctx
, FCGI_STATE_PREPARE_WRITE
);
2912 case FCGI_STATE_PREPARE_WRITE
:
2913 /* ok, we have the connection */
2915 fcgi_proc_load_inc(srv
, hctx
);
2918 status_counter_inc(srv
, CONST_STR_LEN("fastcgi.requests"));
2920 fastcgi_status_copy_procname(p
->statuskey
, hctx
->host
, hctx
->proc
);
2921 buffer_append_string_len(p
->statuskey
, CONST_STR_LEN(".connected"));
2923 status_counter_inc(srv
, CONST_BUF_LEN(p
->statuskey
));
2925 if (p
->conf
.debug
) {
2926 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsd",
2928 "pid:", hctx
->proc
->pid
,
2929 "socket:", hctx
->proc
->connection_name
,
2930 "load:", hctx
->proc
->load
);
2933 /* move the proc-list entry down the list */
2934 if (hctx
->request_id
== 0) {
2935 hctx
->request_id
= 1; /* always use id 1 as we don't use multiplexing */
2937 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2938 "fcgi-request is already in use:", hctx
->request_id
);
2941 if (-1 == fcgi_create_env(srv
, hctx
, hctx
->request_id
)) return HANDLER_ERROR
;
2943 fcgi_set_state(srv
, hctx
, FCGI_STATE_WRITE
);
2945 case FCGI_STATE_WRITE
:
2946 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
2948 chunkqueue_remove_finished_chunks(hctx
->wb
);
2955 /* the connection got dropped after accept()
2956 * we don't care about that - if you accept() it, you have to handle it.
2959 log_error_write(srv
, __FILE__
, __LINE__
, "ssosb",
2960 "connection was dropped after accept() (perhaps the fastcgi process died),",
2961 "write-offset:", hctx
->wb
->bytes_out
,
2962 "socket:", hctx
->proc
->connection_name
);
2964 return HANDLER_ERROR
;
2966 log_error_write(srv
, __FILE__
, __LINE__
, "ssd",
2967 "write failed:", strerror(errno
), errno
);
2969 return HANDLER_ERROR
;
2973 if (hctx
->wb
->bytes_out
== hctx
->wb
->bytes_in
) {
2974 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2975 fcgi_set_state(srv
, hctx
, FCGI_STATE_READ
);
2977 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
|FDEVENT_OUT
);
2980 return HANDLER_WAIT_FOR_EVENT
;
2981 case FCGI_STATE_READ
:
2982 /* waiting for a response */
2983 return HANDLER_WAIT_FOR_EVENT
;
2985 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
2986 return HANDLER_ERROR
;
2991 /* might be called on fdevent after a connect() is delay too
2993 static handler_t
fcgi_send_request(server
*srv
, handler_ctx
*hctx
) {
2994 fcgi_extension_host
*host
;
2997 /* we don't have a host yet, choose one
2998 * -> this happens in the first round
2999 * and when the host died and we have to select a new one */
3000 if (hctx
->host
== NULL
) {
3004 /* check if the next server has no load. */
3005 ndx
= hctx
->ext
->last_used_ndx
+ 1;
3006 if(ndx
>= (int) hctx
->ext
->used
|| ndx
< 0) ndx
= 0;
3007 host
= hctx
->ext
->hosts
[ndx
];
3008 if (host
->load
> 0) {
3009 /* get backend with the least load. */
3010 for (k
= 0, ndx
= -1; k
< hctx
->ext
->used
; k
++) {
3011 host
= hctx
->ext
->hosts
[k
];
3013 /* we should have at least one proc that can do something */
3014 if (host
->active_procs
== 0) continue;
3016 if (used
== -1 || host
->load
< used
) {
3024 /* found a server */
3026 /* all hosts are down */
3028 fcgi_connection_close(srv
, hctx
);
3030 return HANDLER_FINISHED
;
3033 hctx
->ext
->last_used_ndx
= ndx
;
3034 host
= hctx
->ext
->hosts
[ndx
];
3037 * if check-local is disabled, use the uri.path handler
3041 /* init handler-context */
3043 /* we put a connection on this host, move the other new connections to other hosts
3045 * as soon as hctx->host is unassigned, decrease the load again */
3046 fcgi_host_assign(srv
, hctx
, host
);
3052 /* ok, create the request */
3053 rc
= fcgi_write_request(srv
, hctx
);
3054 if (HANDLER_ERROR
!= rc
) {
3057 plugin_data
*p
= hctx
->plugin_data
;
3058 connection
*con
= hctx
->remote_conn
;
3060 if (hctx
->state
== FCGI_STATE_INIT
||
3061 hctx
->state
== FCGI_STATE_CONNECT_DELAYED
) {
3062 fcgi_restart_dead_procs(srv
, p
, host
);
3064 /* cleanup this request and let the request handler start this request again */
3065 if (hctx
->reconnects
< 5) {
3066 fcgi_reconnect(srv
, hctx
);
3068 return HANDLER_COMEBACK
;
3070 fcgi_connection_close(srv
, hctx
);
3071 con
->http_status
= 503;
3073 return HANDLER_FINISHED
;
3076 int status
= con
->http_status
;
3077 fcgi_connection_close(srv
, hctx
);
3078 con
->http_status
= (status
== 400) ? 400 : 503; /* see FCGI_ENV_ADD_CHECK() for 400 error */
3080 return HANDLER_FINISHED
;
3086 SUBREQUEST_FUNC(mod_fastcgi_handle_subrequest
) {
3087 plugin_data
*p
= p_d
;
3089 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
3091 if (NULL
== hctx
) return HANDLER_GO_ON
;
3094 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
3096 if (con
->state
== CON_STATE_READ_POST
) {
3097 handler_t r
= connection_handle_read_post_state(srv
, con
);
3098 if (r
!= HANDLER_GO_ON
) return r
;
3101 return (hctx
->state
!= FCGI_STATE_READ
)
3102 ? fcgi_send_request(srv
, hctx
)
3103 : HANDLER_WAIT_FOR_EVENT
;
3106 static handler_t
fcgi_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
3107 handler_ctx
*hctx
= ctx
;
3108 connection
*con
= hctx
->remote_conn
;
3109 plugin_data
*p
= hctx
->plugin_data
;
3111 fcgi_proc
*proc
= hctx
->proc
;
3112 fcgi_extension_host
*host
= hctx
->host
;
3114 joblist_append(srv
, con
);
3116 if ((revents
& FDEVENT_IN
) &&
3117 hctx
->state
== FCGI_STATE_READ
) {
3118 switch (fcgi_demux_response(srv
, hctx
)) {
3123 if (host
->mode
== FCGI_AUTHORIZER
&&
3124 (con
->http_status
== 200 ||
3125 con
->http_status
== 0)) {
3127 * If we are here in AUTHORIZER mode then a request for authorizer
3128 * was processed already, and status 200 has been returned. We need
3129 * now to handle authorized request.
3132 buffer_copy_buffer(con
->physical
.doc_root
, host
->docroot
);
3133 buffer_copy_buffer(con
->physical
.basedir
, host
->docroot
);
3135 buffer_copy_buffer(con
->physical
.path
, host
->docroot
);
3136 buffer_append_string_buffer(con
->physical
.path
, con
->uri
.path
);
3138 con
->mode
= DIRECT
;/*(avoid changing con->state, con->http_status)*/
3139 fcgi_connection_close(srv
, hctx
);
3140 con
->http_status
= 0;
3141 con
->file_started
= 1; /* fcgi_extension won't touch the request afterwards */
3144 fcgi_connection_close(srv
, hctx
);
3147 return HANDLER_FINISHED
;
3149 if (proc
->pid
&& proc
->state
!= PROC_STATE_DIED
) {
3152 /* only fetch the zombie if it is not already done */
3154 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
3156 /* child is still alive */
3161 /* the child should not terminate at all */
3162 if (WIFEXITED(status
)) {
3163 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
3164 "child exited, pid:", proc
->pid
,
3165 "status:", WEXITSTATUS(status
));
3166 } else if (WIFSIGNALED(status
)) {
3167 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3171 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3172 "child died somehow:",
3176 if (p
->conf
.debug
) {
3177 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsd",
3178 "--- fastcgi spawning",
3179 "\n\tsocket", proc
->connection_name
,
3180 "\n\tcurrent:", 1, "/", host
->max_procs
);
3183 if (fcgi_spawn_connection(srv
, p
, host
, proc
)) {
3184 /* respawning failed, retry later */
3185 proc
->state
= PROC_STATE_DIED
;
3187 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3188 "respawning failed, will retry later");
3195 if (con
->file_started
== 0) {
3196 /* nothing has been sent out yet, try to use another child */
3198 if (hctx
->wb
->bytes_out
== 0 &&
3199 hctx
->reconnects
< 5) {
3201 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsBSBs",
3202 "response not received, request not sent",
3203 "on socket:", proc
->connection_name
,
3204 "for", con
->uri
.path
, "?", con
->uri
.query
, ", reconnecting");
3206 fcgi_reconnect(srv
, hctx
);
3208 return HANDLER_COMEBACK
;
3211 log_error_write(srv
, __FILE__
, __LINE__
, "sosbsBSBs",
3212 "response not received, request sent:", hctx
->wb
->bytes_out
,
3213 "on socket:", proc
->connection_name
,
3214 "for", con
->uri
.path
, "?", con
->uri
.query
, ", closing connection");
3216 fcgi_connection_close(srv
, hctx
);
3218 /* response might have been already started, kill the connection */
3219 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsBSBs",
3220 "response already sent out, but backend returned error",
3221 "on socket:", proc
->connection_name
,
3222 "for", con
->uri
.path
, "?", con
->uri
.query
, ", terminating connection");
3224 con
->keep_alive
= 0;
3225 con
->file_finished
= 1;
3226 con
->mode
= DIRECT
; /*(avoid sending final chunked block)*/
3227 fcgi_connection_close(srv
, hctx
);
3230 return HANDLER_FINISHED
;
3234 if (revents
& FDEVENT_OUT
) {
3235 if (hctx
->state
== FCGI_STATE_CONNECT_DELAYED
||
3236 hctx
->state
== FCGI_STATE_WRITE
) {
3237 /* we are allowed to send something out
3239 * 1. in an unfinished connect() call
3240 * 2. in an unfinished write() call (long POST request)
3242 return fcgi_send_request(srv
, hctx
); /*(might invalidate hctx)*/
3244 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3245 "got a FDEVENT_OUT and didn't know why:",
3250 /* perhaps this issue is already handled */
3251 if (revents
& FDEVENT_HUP
) {
3252 if (hctx
->state
== FCGI_STATE_CONNECT_DELAYED
) {
3253 /* getoptsock will catch this one (right ?)
3255 * if we are in connect we might get an EINPROGRESS
3256 * in the first call and an FDEVENT_HUP in the
3259 * FIXME: as it is a bit ugly.
3262 fcgi_send_request(srv
, hctx
);
3263 } else if (hctx
->state
== FCGI_STATE_READ
&&
3264 hctx
->proc
->port
== 0) {
3267 * ioctl says 8192 bytes to read from PHP and we receive directly a HUP for the socket
3268 * even if the FCGI_FIN packet is not received yet
3271 log_error_write(srv
, __FILE__
, __LINE__
, "sBSbsbsd",
3272 "error: unexpected close of fastcgi connection for",
3273 con
->uri
.path
, "?", con
->uri
.query
,
3274 "(no fastcgi process on socket:", proc
->connection_name
, "?)",
3277 fcgi_connection_close(srv
, hctx
);
3279 } else if (revents
& FDEVENT_ERR
) {
3280 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3281 "fcgi: got a FDEVENT_ERR. Don't know why.");
3283 if (con
->file_started
) {
3284 con
->keep_alive
= 0;
3285 con
->file_finished
= 1;
3286 con
->mode
= DIRECT
; /*(avoid sending final chunked block)*/
3288 fcgi_connection_close(srv
, hctx
);
3291 return HANDLER_FINISHED
;
3296 static int fcgi_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
3298 plugin_config
*s
= p
->config_storage
[0];
3304 /* skip the first, the global context */
3305 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
3306 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
3307 s
= p
->config_storage
[i
];
3309 /* condition didn't match */
3310 if (!config_check_cond(srv
, con
, dc
)) continue;
3313 for (j
= 0; j
< dc
->value
->used
; j
++) {
3314 data_unset
*du
= dc
->value
->data
[j
];
3316 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("fastcgi.server"))) {
3318 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("fastcgi.debug"))) {
3320 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("fastcgi.map-extensions"))) {
3331 static handler_t
fcgi_check_extension(server
*srv
, connection
*con
, void *p_d
, int uri_path_handler
) {
3332 plugin_data
*p
= p_d
;
3336 fcgi_extension
*extension
= NULL
;
3337 fcgi_extension_host
*host
= NULL
;
3339 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
3341 /* Possibly, we processed already this request */
3342 if (con
->file_started
== 1) return HANDLER_GO_ON
;
3344 fn
= uri_path_handler
? con
->uri
.path
: con
->physical
.path
;
3346 if (buffer_string_is_empty(fn
)) return HANDLER_GO_ON
;
3348 s_len
= buffer_string_length(fn
);
3350 fcgi_patch_connection(srv
, con
, p
);
3352 /* fastcgi.map-extensions maps extensions to existing fastcgi.server entries
3354 * fastcgi.map-extensions = ( ".php3" => ".php" )
3356 * fastcgi.server = ( ".php" => ... )
3360 /* check if extension-mapping matches */
3361 for (k
= 0; k
< p
->conf
.ext_mapping
->used
; k
++) {
3362 data_string
*ds
= (data_string
*)p
->conf
.ext_mapping
->data
[k
];
3363 size_t ct_len
; /* length of the config entry */
3365 if (buffer_is_empty(ds
->key
)) continue;
3367 ct_len
= buffer_string_length(ds
->key
);
3369 if (s_len
< ct_len
) continue;
3371 /* found a mapping */
3372 if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ds
->key
->ptr
, ct_len
)) {
3373 /* check if we know the extension */
3375 /* we can reuse k here */
3376 for (k
= 0; k
< p
->conf
.exts
->used
; k
++) {
3377 extension
= p
->conf
.exts
->exts
[k
];
3379 if (buffer_is_equal(ds
->value
, extension
->key
)) {
3384 if (k
== p
->conf
.exts
->used
) {
3392 if (extension
== NULL
) {
3393 size_t uri_path_len
= buffer_string_length(con
->uri
.path
);
3395 /* check if extension matches */
3396 for (k
= 0; k
< p
->conf
.exts
->used
; k
++) {
3397 size_t ct_len
; /* length of the config entry */
3398 fcgi_extension
*ext
= p
->conf
.exts
->exts
[k
];
3400 if (buffer_is_empty(ext
->key
)) continue;
3402 ct_len
= buffer_string_length(ext
->key
);
3404 /* check _url_ in the form "/fcgi_pattern" */
3405 if (ext
->key
->ptr
[0] == '/') {
3406 if ((ct_len
<= uri_path_len
) &&
3407 (strncmp(con
->uri
.path
->ptr
, ext
->key
->ptr
, ct_len
) == 0)) {
3411 } else if ((ct_len
<= s_len
) && (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
))) {
3412 /* check extension in the form ".fcg" */
3417 /* extension doesn't match */
3418 if (NULL
== extension
) {
3419 return HANDLER_GO_ON
;
3423 /* check if we have at least one server for this extension up and running */
3424 for (k
= 0; k
< extension
->used
; k
++) {
3425 fcgi_extension_host
*h
= extension
->hosts
[k
];
3427 /* we should have at least one proc that can do something */
3428 if (h
->active_procs
== 0) {
3432 /* we found one host that is alive */
3438 /* sorry, we don't have a server alive for this ext */
3439 con
->http_status
= 500;
3442 /* only send the 'no handler' once */
3443 if (!extension
->note_is_sent
) {
3444 extension
->note_is_sent
= 1;
3446 log_error_write(srv
, __FILE__
, __LINE__
, "sBSbsbs",
3447 "all handlers for", con
->uri
.path
, "?", con
->uri
.query
,
3448 "on", extension
->key
,
3452 return HANDLER_FINISHED
;
3455 /* a note about no handler is not sent yet */
3456 extension
->note_is_sent
= 0;
3459 * if check-local is disabled, use the uri.path handler
3463 /* init handler-context */
3464 if (uri_path_handler
) {
3465 if (host
->check_local
== 0) {
3469 hctx
= handler_ctx_init();
3471 hctx
->remote_conn
= con
;
3472 hctx
->plugin_data
= p
;
3474 hctx
->ext
= extension
;
3477 hctx
->conf
.exts
= p
->conf
.exts
;
3478 hctx
->conf
.debug
= p
->conf
.debug
;
3480 con
->plugin_ctx
[p
->id
] = hctx
;
3484 if (con
->conf
.log_request_handling
) {
3485 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3486 "handling it in mod_fastcgi");
3489 /* do not split path info for authorizer */
3490 if (host
->mode
!= FCGI_AUTHORIZER
) {
3491 /* the prefix is the SCRIPT_NAME,
3492 * everything from start to the next slash
3493 * this is important for check-local = "disable"
3495 * if prefix = /admin.fcgi
3497 * /admin.fcgi/foo/bar
3499 * SCRIPT_NAME = /admin.fcgi
3500 * PATH_INFO = /foo/bar
3502 * if prefix = /fcgi-bin/
3506 * SCRIPT_NAME = /fcgi-bin/foo
3509 * if prefix = /, and fix-root-path-name is enable
3513 * SCRIPT_NAME = /fcgi-bin/foo
3518 /* the rewrite is only done for /prefix/? matches */
3519 if (host
->fix_root_path_name
&& extension
->key
->ptr
[0] == '/' && extension
->key
->ptr
[1] == '\0') {
3520 buffer_copy_string(con
->request
.pathinfo
, con
->uri
.path
->ptr
);
3521 buffer_string_set_length(con
->uri
.path
, 0);
3522 } else if (extension
->key
->ptr
[0] == '/' &&
3523 buffer_string_length(con
->uri
.path
) > buffer_string_length(extension
->key
) &&
3524 NULL
!= (pathinfo
= strchr(con
->uri
.path
->ptr
+ buffer_string_length(extension
->key
), '/'))) {
3525 /* rewrite uri.path and pathinfo */
3527 buffer_copy_string(con
->request
.pathinfo
, pathinfo
);
3528 buffer_string_set_length(con
->uri
.path
, buffer_string_length(con
->uri
.path
) - buffer_string_length(con
->request
.pathinfo
));
3534 hctx
= handler_ctx_init();
3536 hctx
->remote_conn
= con
;
3537 hctx
->plugin_data
= p
;
3539 hctx
->ext
= extension
;
3541 hctx
->conf
.exts
= p
->conf
.exts
;
3542 hctx
->conf
.debug
= p
->conf
.debug
;
3544 con
->plugin_ctx
[p
->id
] = hctx
;
3548 if (con
->conf
.log_request_handling
) {
3549 log_error_write(srv
, __FILE__
, __LINE__
, "s", "handling it in mod_fastcgi");
3553 return HANDLER_GO_ON
;
3556 /* uri-path handler */
3557 static handler_t
fcgi_check_extension_1(server
*srv
, connection
*con
, void *p_d
) {
3558 return fcgi_check_extension(srv
, con
, p_d
, 1);
3561 /* start request handler */
3562 static handler_t
fcgi_check_extension_2(server
*srv
, connection
*con
, void *p_d
) {
3563 return fcgi_check_extension(srv
, con
, p_d
, 0);
3567 TRIGGER_FUNC(mod_fastcgi_handle_trigger
) {
3568 plugin_data
*p
= p_d
;
3572 /* perhaps we should kill a connect attempt after 10-15 seconds
3574 * currently we wait for the TCP timeout which is 180 seconds on Linux
3580 /* check all children if they are still up */
3582 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
3583 plugin_config
*conf
;
3586 conf
= p
->config_storage
[i
];
3590 for (j
= 0; j
< exts
->used
; j
++) {
3595 for (n
= 0; n
< ex
->used
; n
++) {
3598 fcgi_extension_host
*host
;
3600 host
= ex
->hosts
[n
];
3602 fcgi_restart_dead_procs(srv
, p
, host
);
3604 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
3607 if (proc
->pid
== 0) continue;
3609 switch (waitpid(proc
->pid
, &status
, WNOHANG
)) {
3611 /* child still running after timeout, good */
3614 if (errno
!= EINTR
) {
3615 /* no PID found ? should never happen */
3616 log_error_write(srv
, __FILE__
, __LINE__
, "sddss",
3617 "pid ", proc
->pid
, proc
->state
,
3618 "not found:", strerror(errno
));
3621 if (errno
== ECHILD
) {
3622 /* someone else has cleaned up for us */
3624 proc
->state
= PROC_STATE_UNSET
;
3630 /* the child should not terminate at all */
3631 if (WIFEXITED(status
)) {
3632 if (proc
->state
!= PROC_STATE_KILLED
) {
3633 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
3635 WEXITSTATUS(status
), proc
->connection_name
);
3637 } else if (WIFSIGNALED(status
)) {
3638 if (WTERMSIG(status
) != SIGTERM
) {
3639 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3644 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3645 "child died somehow:",
3649 if (proc
->state
== PROC_STATE_RUNNING
) host
->active_procs
--;
3650 proc
->state
= PROC_STATE_UNSET
;
3658 return HANDLER_GO_ON
;
3662 int mod_fastcgi_plugin_init(plugin
*p
);
3663 int mod_fastcgi_plugin_init(plugin
*p
) {
3664 p
->version
= LIGHTTPD_VERSION_ID
;
3665 p
->name
= buffer_init_string("fastcgi");
3667 p
->init
= mod_fastcgi_init
;
3668 p
->cleanup
= mod_fastcgi_free
;
3669 p
->set_defaults
= mod_fastcgi_set_defaults
;
3670 p
->connection_reset
= fcgi_connection_reset
;
3671 p
->handle_connection_close
= fcgi_connection_reset
;
3672 p
->handle_uri_clean
= fcgi_check_extension_1
;
3673 p
->handle_subrequest_start
= fcgi_check_extension_2
;
3674 p
->handle_subrequest
= mod_fastcgi_handle_subrequest
;
3675 p
->handle_trigger
= mod_fastcgi_handle_trigger
;