8 #include "http_chunk.h"
10 #include "connections.h"
16 #include "inet_ntop_cache.h"
18 #include <sys/types.h>
30 #include "sys-socket.h"
36 #ifdef HAVE_SYS_WAIT_H
37 # include <sys/wait.h>
40 enum {EOL_UNSET
, EOL_N
, EOL_RN
};
46 * - add timeout for a connect to a non-scgi process
47 * (use state_timestamp + state)
51 typedef struct scgi_proc
{
52 size_t id
; /* id will be between 1 and max_procs */
53 buffer
*socket
; /* config.socket + "-" + id */
54 unsigned port
; /* config.port + pno */
56 pid_t pid
; /* PID of the spawned process (0 if not spawned locally) */
59 size_t load
; /* number of requests waiting on this process */
61 time_t last_used
; /* see idle_timeout */
62 size_t requests
; /* see max_requests */
63 struct scgi_proc
*prev
, *next
; /* see first */
65 time_t disable_ts
; /* replace by host->something */
69 enum { PROC_STATE_UNSET
, /* init-phase */
70 PROC_STATE_RUNNING
, /* alive */
71 PROC_STATE_DIED_WAIT_FOR_PID
,
72 PROC_STATE_KILLED
, /* was killed as we don't have the load anymore */
73 PROC_STATE_DIED
, /* marked as dead, should be restarted */
74 PROC_STATE_DISABLED
/* proc disabled as it resulted in an error */
79 /* list of processes handling this extension
80 * sorted by lowest load
82 * whenever a job is done move it up in the list
83 * until it is sorted, move it down as soon as the
87 scgi_proc
*unused_procs
;
90 * spawn at least min_procs, at max_procs.
92 * as soon as the load of the first entry
93 * is max_load_per_proc we spawn a new one
94 * and add it to the first entry and give it
99 unsigned short min_procs
;
100 unsigned short max_procs
;
101 size_t num_procs
; /* how many procs are started */
102 size_t active_procs
; /* how many of them are really running */
104 unsigned short max_load_per_proc
;
107 * kick the process from the list if it was not
108 * used for idle_timeout until min_procs is
109 * reached. this helps to get the processlist
110 * small again we had a small peak load.
114 unsigned short idle_timeout
;
117 * time after a disabled remote connection is tried to be re-enabled
122 unsigned short disable_time
;
125 * same scgi processes get a little bit larger
126 * than wanted. max_requests_per_proc kills a
127 * process after a number of handled requests.
130 size_t max_requests_per_proc
;
138 * if host is one of the local IP adresses the
139 * whole connection is local
141 * if tcp/ip should be used host AND port have
152 * instead of TCP/IP we can use Unix Domain Sockets
153 * - more secure (you have fileperms to play with)
154 * - more control (on locally)
155 * - more speed (no extra overhead)
159 /* if socket is local we can start the scgi
162 * bin-path is the path to the binary
164 * check min_procs and max_procs for the number
165 * of process to start-up
169 /* bin-path is set bin-environment is taken to
170 * create the environement before starting the
179 * docroot-translation between URL->phys and the
183 * - different dir-layout if remote
190 * check_local tell you if the phys file is stat()ed
191 * or not. FastCGI doesn't care if the service is
192 * remote. If the web-server side doesn't contain
193 * the scgi-files we should not stat() for them
194 * and say '404 not found'.
196 unsigned short check_local
;
199 * append PATH_INFO to SCRIPT_FILENAME
201 * php needs this if cgi.fix_pathinfo is provied
206 * workaround for program when prefix="/"
208 * rule to build PATH_INFO is hardcoded for when check_local is disabled
209 * enable this option to use the workaround
213 unsigned short fix_root_path_name
;
216 * If the backend includes X-Sendfile in the response
217 * we use the value as filename and ignore the content.
220 unsigned short xsendfile_allow
;
221 array
*xsendfile_docroot
;
223 ssize_t load
; /* replace by host->load */
225 size_t max_id
; /* corresponds most of the time to
228 only if a process is killed max_id waits for the process itself
229 to die and decrements its afterwards */
233 } scgi_extension_host
;
236 * one extension can have multiple hosts assigned
237 * one host can spawn additional processes on the same
238 * socket (if we control it)
240 * ext -> host -> procs
243 * if the scgi process is remote that whole goes down
246 * ext -> host -> procs
249 * in case of PHP and FCGI_CHILDREN we have again a procs
250 * but we don't control it directly.
255 buffer
*key
; /* like .php */
258 scgi_extension_host
**hosts
;
265 scgi_extension
**exts
;
285 /* generic plugin data, shared between all connections */
292 buffer
*parse_response
;
294 plugin_config
**config_storage
;
296 plugin_config conf
; /* this is only used as long as no handler_ctx is setup */
299 /* connection specific data */
300 typedef enum { FCGI_STATE_INIT
, FCGI_STATE_CONNECT
, FCGI_STATE_PREPARE_WRITE
,
301 FCGI_STATE_WRITE
, FCGI_STATE_READ
302 } scgi_connection_state_t
;
308 scgi_extension_host
*host
;
310 scgi_connection_state_t state
;
311 time_t state_timestamp
;
316 buffer
*response_header
;
318 int fd
; /* fd to the scgi process */
319 int fde_ndx
; /* index into the fd-event buffer */
323 int reconnects
; /* number of reconnect attempts */
327 connection
*remote_conn
; /* dumb pointer */
328 plugin_data
*plugin_data
; /* dumb pointer */
332 /* ok, we need a prototype */
333 static handler_t
scgi_handle_fdevent(server
*srv
, void *ctx
, int revents
);
335 int scgi_proclist_sort_down(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
);
337 static void reset_signals(void) {
339 signal(SIGTTOU
, SIG_DFL
);
342 signal(SIGTTIN
, SIG_DFL
);
345 signal(SIGTSTP
, SIG_DFL
);
347 signal(SIGHUP
, SIG_DFL
);
348 signal(SIGPIPE
, SIG_DFL
);
349 signal(SIGUSR1
, SIG_DFL
);
352 static handler_ctx
* handler_ctx_init(void) {
355 hctx
= calloc(1, sizeof(*hctx
));
360 hctx
->response
= buffer_init();
361 hctx
->response_header
= buffer_init();
363 hctx
->state
= FCGI_STATE_INIT
;
368 hctx
->reconnects
= 0;
370 hctx
->wb
= chunkqueue_init();
376 static void handler_ctx_free(handler_ctx
*hctx
) {
377 buffer_free(hctx
->response
);
378 buffer_free(hctx
->response_header
);
380 chunkqueue_free(hctx
->wb
);
385 static scgi_proc
*scgi_process_init(void) {
388 f
= calloc(1, sizeof(*f
));
390 f
->socket
= buffer_init();
398 static void scgi_process_free(scgi_proc
*f
) {
401 scgi_process_free(f
->next
);
403 buffer_free(f
->socket
);
408 static scgi_extension_host
*scgi_host_init(void) {
409 scgi_extension_host
*f
;
411 f
= calloc(1, sizeof(*f
));
413 f
->host
= buffer_init();
414 f
->unixsocket
= buffer_init();
415 f
->docroot
= buffer_init();
416 f
->bin_path
= buffer_init();
417 f
->bin_env
= array_init();
418 f
->bin_env_copy
= array_init();
419 f
->xsendfile_docroot
= array_init();
424 static void scgi_host_free(scgi_extension_host
*h
) {
431 buffer_free(h
->host
);
432 buffer_free(h
->unixsocket
);
433 buffer_free(h
->docroot
);
434 buffer_free(h
->bin_path
);
435 array_free(h
->bin_env
);
436 array_free(h
->bin_env_copy
);
437 array_free(h
->xsendfile_docroot
);
439 scgi_process_free(h
->first
);
440 scgi_process_free(h
->unused_procs
);
446 static scgi_exts
*scgi_extensions_init(void) {
449 f
= calloc(1, sizeof(*f
));
455 static void scgi_extensions_free(scgi_exts
*f
) {
460 for (i
= 0; i
< f
->used
; i
++) {
466 for (j
= 0; j
< fe
->used
; j
++) {
467 scgi_extension_host
*h
;
474 buffer_free(fe
->key
);
485 static int scgi_extension_insert(scgi_exts
*ext
, buffer
*key
, scgi_extension_host
*fh
) {
489 /* there is something */
491 for (i
= 0; i
< ext
->used
; i
++) {
492 if (buffer_is_equal(key
, ext
->exts
[i
]->key
)) {
497 if (i
== ext
->used
) {
498 /* filextension is new */
499 fe
= calloc(1, sizeof(*fe
));
501 fe
->key
= buffer_init();
502 buffer_copy_buffer(fe
->key
, key
);
506 if (ext
->size
== 0) {
508 ext
->exts
= malloc(ext
->size
* sizeof(*(ext
->exts
)));
509 force_assert(ext
->exts
);
510 } else if (ext
->used
== ext
->size
) {
512 ext
->exts
= realloc(ext
->exts
, ext
->size
* sizeof(*(ext
->exts
)));
513 force_assert(ext
->exts
);
515 ext
->exts
[ext
->used
++] = fe
;
522 fe
->hosts
= malloc(fe
->size
* sizeof(*(fe
->hosts
)));
523 force_assert(fe
->hosts
);
524 } else if (fe
->size
== fe
->used
) {
526 fe
->hosts
= realloc(fe
->hosts
, fe
->size
* sizeof(*(fe
->hosts
)));
527 force_assert(fe
->hosts
);
530 fe
->hosts
[fe
->used
++] = fh
;
536 INIT_FUNC(mod_scgi_init
) {
539 p
= calloc(1, sizeof(*p
));
542 p
->scgi_env
= buffer_init();
544 p
->path
= buffer_init();
545 p
->parse_response
= buffer_init();
551 FREE_FUNC(mod_scgi_free
) {
552 plugin_data
*p
= p_d
;
556 buffer_free(p
->scgi_env
);
557 buffer_free(p
->path
);
558 buffer_free(p
->parse_response
);
560 if (p
->config_storage
) {
562 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
563 plugin_config
*s
= p
->config_storage
[i
];
566 if (NULL
== s
) continue;
570 for (j
= 0; j
< exts
->used
; j
++) {
575 for (n
= 0; n
< ex
->used
; n
++) {
577 scgi_extension_host
*host
;
581 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
582 if (proc
->pid
!= 0) kill(proc
->pid
, SIGTERM
);
584 if (proc
->is_local
&&
585 !buffer_string_is_empty(proc
->socket
)) {
586 unlink(proc
->socket
->ptr
);
590 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
591 if (proc
->pid
!= 0) kill(proc
->pid
, SIGTERM
);
593 if (proc
->is_local
&&
594 !buffer_string_is_empty(proc
->socket
)) {
595 unlink(proc
->socket
->ptr
);
601 scgi_extensions_free(s
->exts
);
605 free(p
->config_storage
);
610 return HANDLER_GO_ON
;
613 static int env_add(char_array
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
617 if (!key
|| !val
) return -1;
619 dst
= malloc(key_len
+ val_len
+ 3);
621 memcpy(dst
, key
, key_len
);
623 /* add the \0 from the value */
624 memcpy(dst
+ key_len
+ 1, val
, val_len
+ 1);
626 for (i
= 0; i
< env
->used
; i
++) {
627 if (0 == strncmp(dst
, env
->ptr
[i
], key_len
+ 1)) {
628 /* don't care about free as we are in a forked child which is going to exec(...) */
629 /* free(env->ptr[i]); */
635 if (env
->size
== 0) {
637 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
638 force_assert(env
->ptr
);
639 } else if (env
->size
== env
->used
) {
641 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
642 force_assert(env
->ptr
);
645 env
->ptr
[env
->used
++] = dst
;
650 #if !defined(HAVE_FORK)
651 static int scgi_spawn_connection(server
*srv
,
653 scgi_extension_host
*host
,
662 #else /* -> defined(HAVE_FORK) */
664 static int scgi_spawn_connection(server
*srv
,
666 scgi_extension_host
*host
,
670 struct timeval tv
= { 0, 100 * 1000 };
672 struct sockaddr_un scgi_addr_un
;
674 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
675 struct sockaddr_in6 scgi_addr_in6
;
677 struct sockaddr_in scgi_addr_in
;
678 struct sockaddr
*scgi_addr
;
683 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
684 "new proc, socket:", proc
->port
, proc
->socket
);
688 if (!buffer_string_is_empty(proc
->socket
)) {
690 memset(&scgi_addr_un
, 0, sizeof(scgi_addr_un
));
691 scgi_addr_un
.sun_family
= AF_UNIX
;
692 if (buffer_string_length(proc
->socket
) + 1 > sizeof(scgi_addr_un
.sun_path
)) {
693 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
694 "ERROR: Unix Domain socket filename too long:",
698 memcpy(scgi_addr_un
.sun_path
, proc
->socket
->ptr
, buffer_string_length(proc
->socket
) + 1);
701 servlen
= SUN_LEN(&scgi_addr_un
);
704 servlen
= buffer_string_length(proc
->socket
) + 1 + sizeof(scgi_addr_un
.sun_family
);
706 scgi_addr
= (struct sockaddr
*) &scgi_addr_un
;
708 log_error_write(srv
, __FILE__
, __LINE__
, "s",
709 "ERROR: Unix Domain sockets are not supported.");
712 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
713 } else if (host
->family
== AF_INET6
&& !buffer_string_is_empty(host
->host
)) {
714 memset(&scgi_addr_in6
, 0, sizeof(scgi_addr_in6
));
715 scgi_addr_in6
.sin6_family
= AF_INET6
;
716 inet_pton(AF_INET6
, host
->host
->ptr
, (char *) &scgi_addr_in6
.sin6_addr
);
717 scgi_addr_in6
.sin6_port
= htons(proc
->port
);
718 servlen
= sizeof(scgi_addr_in6
);
719 scgi_addr
= (struct sockaddr
*) &scgi_addr_in6
;
722 memset(&scgi_addr_in
, 0, sizeof(scgi_addr_in
));
723 scgi_addr_in
.sin_family
= AF_INET
;
725 if (buffer_string_is_empty(host
->host
)) {
726 scgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
730 /* set a usefull default */
731 scgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
734 if (NULL
== (he
= gethostbyname(host
->host
->ptr
))) {
735 log_error_write(srv
, __FILE__
, __LINE__
,
736 "sdb", "gethostbyname failed: ",
737 h_errno
, host
->host
);
741 if (he
->h_addrtype
!= AF_INET
) {
742 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-type != AF_INET: ", he
->h_addrtype
);
746 if (he
->h_length
!= sizeof(struct in_addr
)) {
747 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-length != sizeof(in_addr): ", he
->h_length
);
751 memcpy(&(scgi_addr_in
.sin_addr
.s_addr
), he
->h_addr_list
[0], he
->h_length
);
754 scgi_addr_in
.sin_port
= htons(proc
->port
);
755 servlen
= sizeof(scgi_addr_in
);
757 scgi_addr
= (struct sockaddr
*) &scgi_addr_in
;
760 if (-1 == (scgi_fd
= socket(scgi_addr
->sa_family
, SOCK_STREAM
, 0))) {
761 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
762 "failed:", strerror(errno
));
766 if (-1 == connect(scgi_fd
, scgi_addr
, servlen
)) {
767 /* server is not up, spawn in */
771 if (!buffer_string_is_empty(proc
->socket
)) {
772 unlink(proc
->socket
->ptr
);
778 if (-1 == (scgi_fd
= socket(scgi_addr
->sa_family
, SOCK_STREAM
, 0))) {
779 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
780 "socket failed:", strerror(errno
));
785 if (setsockopt(scgi_fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
)) < 0) {
786 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
787 "socketsockopt failed:", strerror(errno
));
793 if (-1 == bind(scgi_fd
, scgi_addr
, servlen
)) {
794 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
803 if (-1 == listen(scgi_fd
, host
->listen_backlog
)) {
804 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
805 "listen failed:", strerror(errno
));
810 switch ((child
= fork())) {
818 /* create environment */
828 /* we don't need the client socket */
829 for (fd
= 3; fd
< 256; fd
++) {
833 /* build clean environment */
834 if (host
->bin_env_copy
->used
) {
835 for (i
= 0; i
< host
->bin_env_copy
->used
; i
++) {
836 data_string
*ds
= (data_string
*)host
->bin_env_copy
->data
[i
];
839 if (NULL
!= (ge
= getenv(ds
->value
->ptr
))) {
840 env_add(&env
, CONST_BUF_LEN(ds
->value
), ge
, strlen(ge
));
844 char ** const e
= environ
;
845 for (i
= 0; e
[i
]; ++i
) {
848 if (NULL
!= (eq
= strchr(e
[i
], '='))) {
849 env_add(&env
, e
[i
], eq
- e
[i
], eq
+1, strlen(eq
+1));
854 /* create environment */
855 for (i
= 0; i
< host
->bin_env
->used
; i
++) {
856 data_string
*ds
= (data_string
*)host
->bin_env
->data
[i
];
858 env_add(&env
, CONST_BUF_LEN(ds
->key
), CONST_BUF_LEN(ds
->value
));
861 for (i
= 0; i
< env
.used
; i
++) {
862 /* search for PHP_FCGI_CHILDREN */
863 if (0 == strncmp(env
.ptr
[i
], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
866 /* not found, add a default */
868 env_add(&env
, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
871 env
.ptr
[env
.used
] = NULL
;
874 buffer_copy_string_len(b
, CONST_STR_LEN("exec "));
875 buffer_append_string_buffer(b
, host
->bin_path
);
880 execle("/bin/sh", "sh", "-c", b
->ptr
, (char *)NULL
, env
.ptr
);
882 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
883 "execl failed for:", host
->bin_path
, strerror(errno
));
898 select(0, NULL
, NULL
, NULL
, &tv
);
900 switch (waitpid(child
, &status
, WNOHANG
)) {
902 /* child still running after timeout, good */
905 /* no PID found ? should never happen */
906 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
907 "pid not found:", strerror(errno
));
910 /* the child should not terminate at all */
911 if (WIFEXITED(status
)) {
912 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
913 "child exited (is this a SCGI binary ?):",
914 WEXITSTATUS(status
));
915 } else if (WIFSIGNALED(status
)) {
916 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
920 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
921 "child died somehow:",
927 /* register process */
929 proc
->last_used
= srv
->cur_ts
;
941 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
942 "(debug) socket is already used, won't spawn:",
947 proc
->state
= PROC_STATE_RUNNING
;
948 host
->active_procs
++;
953 #endif /* HAVE_FORK */
955 static scgi_extension_host
* unixsocket_is_dup(plugin_data
*p
, size_t used
, buffer
*unixsocket
) {
957 for (i
= 0; i
< used
; ++i
) {
958 scgi_exts
*exts
= p
->config_storage
[i
]->exts
;
959 for (j
= 0; j
< exts
->used
; ++j
) {
960 scgi_extension
*ex
= exts
->exts
[j
];
961 for (n
= 0; n
< ex
->used
; ++n
) {
962 scgi_extension_host
*host
= ex
->hosts
[n
];
963 if (!buffer_string_is_empty(host
->unixsocket
)
964 && buffer_is_equal(host
->unixsocket
, unixsocket
)
965 && !buffer_string_is_empty(host
->bin_path
))
974 SETDEFAULTS_FUNC(mod_scgi_set_defaults
) {
975 plugin_data
*p
= p_d
;
978 scgi_extension_host
*df
= NULL
;
980 config_values_t cv
[] = {
981 { "scgi.server", NULL
, T_CONFIG_LOCAL
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
982 { "scgi.debug", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
983 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
986 p
->config_storage
= calloc(1, srv
->config_context
->used
* sizeof(plugin_config
*));
987 force_assert(p
->config_storage
);
989 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
990 data_config
const* config
= (data_config
const*)srv
->config_context
->data
[i
];
993 s
= malloc(sizeof(plugin_config
));
995 s
->exts
= scgi_extensions_init();
998 cv
[0].destination
= s
->exts
;
999 cv
[1].destination
= &(s
->debug
);
1001 p
->config_storage
[i
] = s
;
1003 if (0 != config_insert_values_global(srv
, config
->value
, cv
, i
== 0 ? T_CONFIG_SCOPE_SERVER
: T_CONFIG_SCOPE_CONNECTION
)) {
1011 if (NULL
!= (du
= array_get_element(config
->value
, "scgi.server"))) {
1013 data_array
*da
= (data_array
*)du
;
1015 if (du
->type
!= TYPE_ARRAY
) {
1016 log_error_write(srv
, __FILE__
, __LINE__
, "sss",
1017 "unexpected type for key: ", "scgi.server", "expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1024 * scgi.server = ( "<ext>" => ( ... ),
1025 * "<ext>" => ( ... ) )
1028 for (j
= 0; j
< da
->value
->used
; j
++) {
1030 data_array
*da_ext
= (data_array
*)da
->value
->data
[j
];
1032 if (da
->value
->data
[j
]->type
!= TYPE_ARRAY
) {
1033 log_error_write(srv
, __FILE__
, __LINE__
, "sssbs",
1034 "unexpected type for key: ", "scgi.server",
1035 "[", da
->value
->data
[j
]->key
, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1041 * da_ext->key == name of the extension
1045 * scgi.server = ( "<ext>" =>
1046 * ( "<host>" => ( ... ),
1047 * "<host>" => ( ... )
1052 for (n
= 0; n
< da_ext
->value
->used
; n
++) {
1053 data_array
*da_host
= (data_array
*)da_ext
->value
->data
[n
];
1055 config_values_t fcv
[] = {
1056 { "host", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
1057 { "docroot", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
1058 { "socket", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
1059 { "bin-path", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 3 */
1061 { "check-local", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 4 */
1062 { "port", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 5 */
1063 { "min-procs-not-working", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 this is broken for now */
1064 { "max-procs", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 */
1065 { "max-load-per-proc", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 8 */
1066 { "idle-timeout", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 9 */
1067 { "disable-time", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 10 */
1069 { "bin-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 11 */
1070 { "bin-copy-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 12 */
1071 { "fix-root-scriptname", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 13 */
1072 { "listen-backlog", NULL
, T_CONFIG_INT
, T_CONFIG_SCOPE_CONNECTION
}, /* 14 */
1073 { "x-sendfile", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 15 */
1074 { "x-sendfile-docroot",NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 16 */
1077 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
1080 if (da_host
->type
!= TYPE_ARRAY
) {
1081 log_error_write(srv
, __FILE__
, __LINE__
, "ssSBS",
1082 "unexpected type for key:",
1084 "[", da_host
->key
, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1089 df
= scgi_host_init();
1091 df
->check_local
= 1;
1094 df
->max_load_per_proc
= 1;
1095 df
->idle_timeout
= 60;
1096 df
->disable_time
= 60;
1097 df
->fix_root_path_name
= 0;
1098 df
->listen_backlog
= 1024;
1099 df
->xsendfile_allow
= 0;
1102 fcv
[0].destination
= df
->host
;
1103 fcv
[1].destination
= df
->docroot
;
1104 fcv
[2].destination
= df
->unixsocket
;
1105 fcv
[3].destination
= df
->bin_path
;
1107 fcv
[4].destination
= &(df
->check_local
);
1108 fcv
[5].destination
= &(df
->port
);
1109 fcv
[6].destination
= &(df
->min_procs
);
1110 fcv
[7].destination
= &(df
->max_procs
);
1111 fcv
[8].destination
= &(df
->max_load_per_proc
);
1112 fcv
[9].destination
= &(df
->idle_timeout
);
1113 fcv
[10].destination
= &(df
->disable_time
);
1115 fcv
[11].destination
= df
->bin_env
;
1116 fcv
[12].destination
= df
->bin_env_copy
;
1117 fcv
[13].destination
= &(df
->fix_root_path_name
);
1118 fcv
[14].destination
= &(df
->listen_backlog
);
1119 fcv
[15].destination
= &(df
->xsendfile_allow
);
1120 fcv
[16].destination
= df
->xsendfile_docroot
;
1123 if (0 != config_insert_values_internal(srv
, da_host
->value
, fcv
, T_CONFIG_SCOPE_CONNECTION
)) {
1127 if ((!buffer_string_is_empty(df
->host
) || df
->port
) &&
1128 !buffer_string_is_empty(df
->unixsocket
)) {
1129 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1130 "either host+port or socket");
1135 if (!buffer_string_is_empty(df
->unixsocket
)) {
1136 /* unix domain socket */
1137 struct sockaddr_un un
;
1139 if (buffer_string_length(df
->unixsocket
) + 1 > sizeof(un
.sun_path
) - 2) {
1140 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1141 "path of the unixdomain socket is too large");
1145 if (!buffer_string_is_empty(df
->bin_path
)) {
1146 scgi_extension_host
*duplicate
= unixsocket_is_dup(p
, i
+1, df
->unixsocket
);
1147 if (NULL
!= duplicate
) {
1148 if (!buffer_is_equal(df
->bin_path
, duplicate
->bin_path
)) {
1149 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1150 "duplicate unixsocket path:",
1160 df
->family
= AF_UNIX
;
1164 if (buffer_string_is_empty(df
->host
) &&
1165 buffer_string_is_empty(df
->bin_path
)) {
1166 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbs",
1167 "missing key (string):",
1174 } else if (df
->port
== 0) {
1175 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbs",
1176 "missing key (short):",
1184 df
->family
= (!buffer_string_is_empty(df
->host
) && NULL
!= strchr(df
->host
->ptr
, ':')) ? AF_INET6
: AF_INET
;
1188 /* already init'd; skip spawning */
1189 } else if (!buffer_string_is_empty(df
->bin_path
)) {
1190 /* a local socket + self spawning */
1193 /* HACK: just to make sure the adaptive spawing is disabled */
1194 df
->min_procs
= df
->max_procs
;
1196 if (df
->min_procs
> df
->max_procs
) df
->max_procs
= df
->min_procs
;
1197 if (df
->max_load_per_proc
< 1) df
->max_load_per_proc
= 0;
1200 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsbsdsd",
1201 "--- scgi spawning local",
1202 "\n\tproc:", df
->bin_path
,
1203 "\n\tport:", df
->port
,
1204 "\n\tsocket", df
->unixsocket
,
1205 "\n\tmin-procs:", df
->min_procs
,
1206 "\n\tmax-procs:", df
->max_procs
);
1209 for (pno
= 0; pno
< df
->min_procs
; pno
++) {
1212 proc
= scgi_process_init();
1213 proc
->id
= df
->num_procs
++;
1216 if (buffer_string_is_empty(df
->unixsocket
)) {
1217 proc
->port
= df
->port
+ pno
;
1219 buffer_copy_buffer(proc
->socket
, df
->unixsocket
);
1220 buffer_append_string_len(proc
->socket
, CONST_STR_LEN("-"));
1221 buffer_append_int(proc
->socket
, pno
);
1225 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
1226 "--- scgi spawning",
1227 "\n\tport:", df
->port
,
1228 "\n\tsocket", df
->unixsocket
,
1229 "\n\tcurrent:", pno
, "/", df
->min_procs
);
1232 if (!srv
->srvconf
.preflight_check
1233 && scgi_spawn_connection(srv
, p
, df
, proc
)) {
1234 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1235 "[ERROR]: spawning fcgi failed.");
1236 scgi_process_free(proc
);
1240 proc
->next
= df
->first
;
1241 if (df
->first
) df
->first
->prev
= proc
;
1248 fp
= scgi_process_init();
1249 fp
->id
= df
->num_procs
++;
1252 fp
->state
= PROC_STATE_RUNNING
;
1254 if (buffer_string_is_empty(df
->unixsocket
)) {
1255 fp
->port
= df
->port
;
1257 buffer_copy_buffer(fp
->socket
, df
->unixsocket
);
1266 if (df
->xsendfile_docroot
->used
) {
1268 for (k
= 0; k
< df
->xsendfile_docroot
->used
; ++k
) {
1269 data_string
*ds
= (data_string
*)df
->xsendfile_docroot
->data
[k
];
1270 if (ds
->type
!= TYPE_STRING
) {
1271 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1272 "unexpected type for x-sendfile-docroot; expected: \"x-sendfile-docroot\" => ( \"/allowed/path\", ... )");
1275 if (ds
->value
->ptr
[0] != '/') {
1276 log_error_write(srv
, __FILE__
, __LINE__
, "SBs",
1277 "x-sendfile-docroot paths must begin with '/'; invalid: \"", ds
->value
, "\"");
1280 buffer_path_simplify(ds
->value
, ds
->value
);
1281 buffer_append_slash(ds
->value
);
1285 /* if extension already exists, take it */
1286 scgi_extension_insert(s
->exts
, da_ext
->key
, df
);
1293 return HANDLER_GO_ON
;
1296 if (NULL
!= df
) scgi_host_free(df
);
1297 return HANDLER_ERROR
;
1300 static int scgi_set_state(server
*srv
, handler_ctx
*hctx
, scgi_connection_state_t state
) {
1301 hctx
->state
= state
;
1302 hctx
->state_timestamp
= srv
->cur_ts
;
1308 static void scgi_connection_close(server
*srv
, handler_ctx
*hctx
) {
1312 p
= hctx
->plugin_data
;
1313 con
= hctx
->remote_conn
;
1315 if (hctx
->fd
!= -1) {
1316 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1317 fdevent_unregister(srv
->ev
, hctx
->fd
);
1322 if (hctx
->host
&& hctx
->proc
) {
1325 if (hctx
->got_proc
) {
1326 /* after the connect the process gets a load */
1329 if (p
->conf
.debug
) {
1330 log_error_write(srv
, __FILE__
, __LINE__
, "sddb",
1333 hctx
->proc
->pid
, hctx
->proc
->socket
);
1337 scgi_proclist_sort_down(srv
, hctx
->host
, hctx
->proc
);
1341 handler_ctx_free(hctx
);
1342 con
->plugin_ctx
[p
->id
] = NULL
;
1344 /* finish response (if not already con->file_started, con->file_finished) */
1345 if (con
->mode
== p
->id
) {
1346 http_response_backend_done(srv
, con
);
1350 static int scgi_reconnect(server
*srv
, handler_ctx
*hctx
) {
1351 plugin_data
*p
= hctx
->plugin_data
;
1357 * connect was ok, connection was accepted
1358 * but the php accept loop checks after the accept if it should die or not.
1360 * if yes we can only detect it at a write()
1362 * next step is resetting this attemp and setup a connection again
1364 * if we have more then 5 reconnects for the same request, die
1368 * we have a connection but the child died by some other reason
1372 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1373 fdevent_unregister(srv
->ev
, hctx
->fd
);
1377 scgi_set_state(srv
, hctx
, FCGI_STATE_INIT
);
1381 if (p
->conf
.debug
) {
1382 log_error_write(srv
, __FILE__
, __LINE__
, "sddb",
1385 hctx
->proc
->pid
, hctx
->proc
->socket
);
1389 scgi_proclist_sort_down(srv
, hctx
->host
, hctx
->proc
);
1395 static handler_t
scgi_connection_reset(server
*srv
, connection
*con
, void *p_d
) {
1396 plugin_data
*p
= p_d
;
1397 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
1398 if (hctx
) scgi_connection_close(srv
, hctx
);
1400 return HANDLER_GO_ON
;
1404 static int scgi_env_add(buffer
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
1407 if (!key
|| !val
) return -1;
1409 len
= key_len
+ val_len
+ 2;
1411 buffer_string_prepare_append(env
, len
);
1413 buffer_append_string_len(env
, key
, key_len
);
1414 buffer_append_string_len(env
, "", 1);
1415 buffer_append_string_len(env
, val
, val_len
);
1416 buffer_append_string_len(env
, "", 1);
1427 * 1 not connected yet
1430 static int scgi_establish_connection(server
*srv
, handler_ctx
*hctx
) {
1431 struct sockaddr
*scgi_addr
;
1432 struct sockaddr_in scgi_addr_in
;
1433 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1434 struct sockaddr_in6 scgi_addr_in6
;
1436 #ifdef HAVE_SYS_UN_H
1437 struct sockaddr_un scgi_addr_un
;
1441 scgi_extension_host
*host
= hctx
->host
;
1442 scgi_proc
*proc
= hctx
->proc
;
1443 int scgi_fd
= hctx
->fd
;
1445 if (!buffer_string_is_empty(proc
->socket
)) {
1446 #ifdef HAVE_SYS_UN_H
1447 /* use the unix domain socket */
1448 memset(&scgi_addr_un
, 0, sizeof(scgi_addr_un
));
1449 scgi_addr_un
.sun_family
= AF_UNIX
;
1450 if (buffer_string_length(proc
->socket
) + 1 > sizeof(scgi_addr_un
.sun_path
)) {
1451 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
1452 "ERROR: Unix Domain socket filename too long:",
1456 memcpy(scgi_addr_un
.sun_path
, proc
->socket
->ptr
, buffer_string_length(proc
->socket
) + 1);
1459 servlen
= SUN_LEN(&scgi_addr_un
);
1462 servlen
= buffer_string_length(proc
->socket
) + 1 + sizeof(scgi_addr_un
.sun_family
);
1464 scgi_addr
= (struct sockaddr
*) &scgi_addr_un
;
1468 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1469 } else if (host
->family
== AF_INET6
&& !buffer_string_is_empty(host
->host
)) {
1470 memset(&scgi_addr_in6
, 0, sizeof(scgi_addr_in6
));
1471 scgi_addr_in6
.sin6_family
= AF_INET6
;
1472 inet_pton(AF_INET6
, host
->host
->ptr
, (char *) &scgi_addr_in6
.sin6_addr
);
1473 scgi_addr_in6
.sin6_port
= htons(proc
->port
);
1474 servlen
= sizeof(scgi_addr_in6
);
1475 scgi_addr
= (struct sockaddr
*) &scgi_addr_in6
;
1478 memset(&scgi_addr_in
, 0, sizeof(scgi_addr_in
));
1479 scgi_addr_in
.sin_family
= AF_INET
;
1480 if (0 == inet_aton(host
->host
->ptr
, &(scgi_addr_in
.sin_addr
))) {
1481 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1482 "converting IP-adress failed for", host
->host
,
1483 "\nBe sure to specify an IP address here");
1487 scgi_addr_in
.sin_port
= htons(proc
->port
);
1488 servlen
= sizeof(scgi_addr_in
);
1490 scgi_addr
= (struct sockaddr
*) &scgi_addr_in
;
1493 if (-1 == connect(scgi_fd
, scgi_addr
, servlen
)) {
1494 if (errno
== EINPROGRESS
||
1495 errno
== EALREADY
||
1497 if (hctx
->conf
.debug
) {
1498 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1499 "connect delayed, will continue later:", scgi_fd
);
1504 log_error_write(srv
, __FILE__
, __LINE__
, "sdsddb",
1505 "connect failed:", scgi_fd
,
1506 strerror(errno
), errno
,
1507 proc
->port
, proc
->socket
);
1509 if (errno
== EAGAIN
) {
1510 /* this is Linux only */
1512 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1513 "If this happend on Linux: You have been run out of local ports. "
1514 "Check the manual, section Performance how to handle this.");
1520 if (hctx
->conf
.debug
> 1) {
1521 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1522 "connect succeeded: ", scgi_fd
);
1530 static int scgi_env_add_request_headers(server
*srv
, connection
*con
, plugin_data
*p
) {
1533 for (i
= 0; i
< con
->request
.headers
->used
; i
++) {
1536 ds
= (data_string
*)con
->request
.headers
->data
[i
];
1538 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
1539 /* Do not emit HTTP_PROXY in environment.
1540 * Some executables use HTTP_PROXY to configure
1541 * outgoing proxy. See also https://httpoxy.org/ */
1542 if (buffer_is_equal_caseless_string(ds
->key
, CONST_STR_LEN("Proxy"))) {
1546 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 1);
1548 scgi_env_add(p
->scgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
));
1552 for (i
= 0; i
< con
->environment
->used
; i
++) {
1555 ds
= (data_string
*)con
->environment
->data
[i
];
1557 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
1558 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 0);
1560 scgi_env_add(p
->scgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
));
1568 static int scgi_create_env(server
*srv
, handler_ctx
*hctx
) {
1569 char buf
[LI_ITOSTRING_LENGTH
];
1572 char b2
[INET6_ADDRSTRLEN
+ 1];
1576 plugin_data
*p
= hctx
->plugin_data
;
1577 scgi_extension_host
*host
= hctx
->host
;
1579 connection
*con
= hctx
->remote_conn
;
1580 server_socket
*srv_sock
= con
->srv_socket
;
1583 socklen_t our_addr_len
;
1585 buffer_string_prepare_copy(p
->scgi_env
, 1023);
1587 /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
1589 li_itostrn(buf
, sizeof(buf
), con
->request
.content_length
);
1590 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("CONTENT_LENGTH"), buf
, strlen(buf
));
1591 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCGI"), CONST_STR_LEN("1"));
1593 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con
->conf
.server_tag
));
1595 if (!buffer_is_empty(con
->server_name
)) {
1596 size_t len
= buffer_string_length(con
->server_name
);
1598 if (con
->server_name
->ptr
[0] == '[') {
1599 const char *colon
= strstr(con
->server_name
->ptr
, "]:");
1600 if (colon
) len
= (colon
+ 1) - con
->server_name
->ptr
;
1602 const char *colon
= strchr(con
->server_name
->ptr
, ':');
1603 if (colon
) len
= colon
- con
->server_name
->ptr
;
1606 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_NAME"), con
->server_name
->ptr
, len
);
1609 s
= inet_ntop(srv_sock
->addr
.plain
.sa_family
,
1610 srv_sock
->addr
.plain
.sa_family
== AF_INET6
?
1611 (const void *) &(srv_sock
->addr
.ipv6
.sin6_addr
) :
1612 (const void *) &(srv_sock
->addr
.ipv4
.sin_addr
),
1615 s
= inet_ntoa(srv_sock
->addr
.ipv4
.sin_addr
);
1618 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_NAME"), s
, strlen(s
));
1621 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1"));
1623 li_utostrn(buf
, sizeof(buf
),
1625 ntohs(srv_sock
->addr
.plain
.sa_family
? srv_sock
->addr
.ipv6
.sin6_port
: srv_sock
->addr
.ipv4
.sin_port
)
1627 ntohs(srv_sock
->addr
.ipv4
.sin_port
)
1631 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_PORT"), buf
, strlen(buf
));
1633 /* get the server-side of the connection to the client */
1634 our_addr_len
= sizeof(our_addr
);
1636 if (-1 == getsockname(con
->fd
, (struct sockaddr
*)&our_addr
, &our_addr_len
)
1637 || our_addr_len
> (socklen_t
)sizeof(our_addr
)) {
1638 s
= inet_ntop_cache_get_ip(srv
, &(srv_sock
->addr
));
1640 s
= inet_ntop_cache_get_ip(srv
, &(our_addr
));
1642 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_ADDR"), s
, strlen(s
));
1644 li_utostrn(buf
, sizeof(buf
),
1646 ntohs(con
->dst_addr
.plain
.sa_family
? con
->dst_addr
.ipv6
.sin6_port
: con
->dst_addr
.ipv4
.sin_port
)
1648 ntohs(con
->dst_addr
.ipv4
.sin_port
)
1652 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REMOTE_PORT"), buf
, strlen(buf
));
1654 s
= inet_ntop_cache_get_ip(srv
, &(con
->dst_addr
));
1656 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REMOTE_ADDR"), s
, strlen(s
));
1659 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1660 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1661 * (6.1.14, 6.1.6, 6.1.7)
1664 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con
->uri
.path
));
1666 if (!buffer_string_is_empty(con
->request
.pathinfo
)) {
1667 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con
->request
.pathinfo
));
1669 /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1671 if (!buffer_string_is_empty(host
->docroot
)) {
1672 buffer_copy_buffer(p
->path
, host
->docroot
);
1674 buffer_copy_buffer(p
->path
, con
->physical
.basedir
);
1676 buffer_append_string_buffer(p
->path
, con
->request
.pathinfo
);
1677 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p
->path
));
1679 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN(""));
1683 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1684 * http://www.php.net/manual/en/reserved.variables.php
1685 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1686 * TODO: this code should be checked against cgi.fix_pathinfo php
1690 if (!buffer_string_is_empty(host
->docroot
)) {
1692 * rewrite SCRIPT_FILENAME
1696 buffer_copy_buffer(p
->path
, host
->docroot
);
1697 buffer_append_string_buffer(p
->path
, con
->uri
.path
);
1699 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
));
1700 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host
->docroot
));
1702 buffer_copy_buffer(p
->path
, con
->physical
.path
);
1704 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
));
1705 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con
->physical
.basedir
));
1707 if (con
->error_handler_saved_status
>= 0) {
1708 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con
->request
.uri
));
1710 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con
->request
.orig_uri
));
1712 if (!buffer_string_is_empty(con
->uri
.query
)) {
1713 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con
->uri
.query
));
1715 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN(""));
1718 s
= get_http_method_name(con
->request
.http_method
);
1720 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_METHOD"), s
, strlen(s
));
1721 /* set REDIRECT_STATUS for php compiled with --force-redirect
1722 * (if REDIRECT_STATUS has not already been set by error handler) */
1723 if (0 == con
->error_handler_saved_status
) {
1724 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200"));
1726 s
= get_http_version_name(con
->request
.http_version
);
1728 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_PROTOCOL"), s
, strlen(s
));
1731 if (buffer_is_equal_caseless_string(con
->uri
.scheme
, CONST_STR_LEN("https"))) {
1732 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1736 scgi_env_add_request_headers(srv
, con
, p
);
1740 buffer_append_int(b
, buffer_string_length(p
->scgi_env
));
1741 buffer_append_string_len(b
, CONST_STR_LEN(":"));
1742 buffer_append_string_buffer(b
, p
->scgi_env
);
1743 buffer_append_string_len(b
, CONST_STR_LEN(","));
1745 hctx
->wb_reqlen
= buffer_string_length(b
);
1746 chunkqueue_append_buffer(hctx
->wb
, b
);
1749 if (con
->request
.content_length
) {
1750 chunkqueue_append_chunkqueue(hctx
->wb
, con
->request_content_queue
);
1751 hctx
->wb_reqlen
+= con
->request
.content_length
;/* (eventual) total request size */
1757 static int scgi_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
, int eol
) {
1764 buffer_copy_buffer(p
->parse_response
, in
);
1766 for (s
= p
->parse_response
->ptr
;
1767 NULL
!= (ns
= (eol
== EOL_RN
? strstr(s
, "\r\n") : strchr(s
, '\n')));
1768 s
= ns
+ (eol
== EOL_RN
? 2 : 1), line
++) {
1769 const char *key
, *value
;
1776 0 == strncmp(s
, "HTTP/1.", 7)) {
1777 /* non-parsed header ... we parse them anyway */
1783 /* after the space should be a status code for us */
1785 status
= strtol(s
+9, NULL
, 10);
1787 if (status
>= 100 && status
< 1000) {
1788 /* we expected 3 digits got them */
1789 con
->parsed_response
|= HTTP_STATUS
;
1790 con
->http_status
= status
;
1796 if (NULL
== (value
= strchr(s
, ':'))) {
1797 /* we expect: "<key>: <value>\r\n" */
1801 key_len
= value
- key
;
1805 while (*value
== ' ' || *value
== '\t') value
++;
1807 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
1808 ds
= data_response_init();
1810 buffer_copy_string_len(ds
->key
, key
, key_len
);
1811 buffer_copy_string(ds
->value
, value
);
1813 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
1817 if (0 == strncasecmp(key
, "Date", key_len
)) {
1818 con
->parsed_response
|= HTTP_DATE
;
1822 if (0 == strncasecmp(key
, "Status", key_len
)) {
1823 int status
= strtol(value
, NULL
, 10);
1824 if (status
>= 100 && status
< 1000) {
1825 con
->http_status
= status
;
1826 con
->parsed_response
|= HTTP_STATUS
;
1828 con
->http_status
= 502;
1833 if (0 == strncasecmp(key
, "Location", key_len
)) {
1834 con
->parsed_response
|= HTTP_LOCATION
;
1838 if (0 == strncasecmp(key
, "Connection", key_len
)) {
1839 con
->response
.keep_alive
= (0 == strcasecmp(value
, "Keep-Alive")) ? 1 : 0;
1840 con
->parsed_response
|= HTTP_CONNECTION
;
1844 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
1845 con
->response
.content_length
= strtoul(value
, NULL
, 10);
1846 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
1855 /* CGI/1.1 rev 03 - 7.2.1.2 */
1856 if ((con
->parsed_response
& HTTP_LOCATION
) &&
1857 !(con
->parsed_response
& HTTP_STATUS
)) {
1858 con
->http_status
= 302;
1865 static int scgi_demux_response(server
*srv
, handler_ctx
*hctx
) {
1866 plugin_data
*p
= hctx
->plugin_data
;
1867 connection
*con
= hctx
->remote_conn
;
1872 buffer_string_prepare_copy(hctx
->response
, 1023);
1873 if (-1 == (n
= read(hctx
->fd
, hctx
->response
->ptr
, hctx
->response
->size
- 1))) {
1874 if (errno
== EAGAIN
|| errno
== EINTR
) {
1875 /* would block, wait for signal */
1876 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
1880 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", strerror(errno
), con
->fd
, hctx
->fd
);
1889 buffer_commit(hctx
->response
, n
);
1891 /* split header from body */
1893 if (con
->file_started
== 0) {
1897 int cp
, eol
= EOL_UNSET
;
1901 buffer_append_string_buffer(hctx
->response_header
, hctx
->response
);
1903 /* nph (non-parsed headers) */
1904 if (0 == strncmp(hctx
->response_header
->ptr
, "HTTP/1.", 7)) in_header
= 1;
1906 /* search for the \r\n\r\n or \n\n in the string */
1907 for (c
= hctx
->response_header
->ptr
, cp
= 0, used
= buffer_string_length(hctx
->response_header
); used
; c
++, cp
++, used
--) {
1908 if (*c
== ':') in_header
= 1;
1909 else if (*c
== '\n') {
1910 if (in_header
== 0) {
1911 /* got a response without a response header */
1918 if (eol
== EOL_UNSET
) eol
= EOL_N
;
1920 if (*(c
+1) == '\n') {
1926 } else if (used
> 1 && *c
== '\r' && *(c
+1) == '\n') {
1927 if (in_header
== 0) {
1928 /* got a response without a response header */
1935 if (eol
== EOL_UNSET
) eol
= EOL_RN
;
1954 /* no header, but a body */
1955 if (0 != http_chunk_append_buffer(srv
, con
, hctx
->response_header
)) {
1956 /* error writing to tempfile;
1957 * truncate response or send 500 if nothing sent yet */
1961 size_t blen
= buffer_string_length(hctx
->response_header
) - hlen
;
1963 /* a small hack: terminate after at the second \r */
1964 buffer_string_set_length(hctx
->response_header
, hlen
- 1);
1966 /* parse the response header */
1967 scgi_response_parse(srv
, con
, p
, hctx
->response_header
, eol
);
1969 if (hctx
->host
->xsendfile_allow
) {
1971 if (NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "X-Sendfile"))) {
1972 http_response_xsendfile(srv
, con
, ds
->value
, hctx
->host
->xsendfile_docroot
);
1978 if (0 != http_chunk_append_mem(srv
, con
, hctx
->response_header
->ptr
+ hlen
, blen
)) {
1979 /* error writing to tempfile;
1980 * truncate response or send 500 if nothing sent yet */
1986 con
->file_started
= 1;
1988 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
1989 if (buffer_string_length(hctx
->response_header
) > MAX_HTTP_REQUEST_HEADER
) {
1990 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "response headers too large for", con
->uri
.path
);
1991 con
->http_status
= 502; /* Bad Gateway */
1997 if (0 != http_chunk_append_buffer(srv
, con
, hctx
->response
)) {
1998 /* error writing to tempfile;
1999 * truncate response or send 500 if nothing sent yet */
2002 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
2003 && chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
2004 if (!con
->is_writable
) {
2005 /*(defer removal of FDEVENT_IN interest since
2006 * connection_state_machine() might be able to send data
2007 * immediately, unless !con->is_writable, where
2008 * connection_state_machine() might not loop back to call
2009 * mod_scgi_handle_subrequest())*/
2010 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2017 log_error_write(srv
, __FILE__
, __LINE__
, "ddss", con
->fd
, hctx
->fd
, connection_get_state(con
->state
), b
->ptr
);
2025 static int scgi_proclist_sort_up(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
2030 /* we have been the smallest of the current list
2031 * and we want to insert the node sorted as soon
2041 /* nothing to sort, only one element */
2042 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
2044 for (p
= proc
; p
->next
&& p
->next
->load
< proc
->load
; p
= p
->next
);
2046 /* no need to move something
2054 if (p
== proc
) return 0;
2056 if (host
->first
== proc
) {
2057 /* we have been the first elememt */
2059 host
->first
= proc
->next
;
2060 host
->first
->prev
= NULL
;
2063 /* disconnect proc */
2065 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
2066 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
2068 /* proc should be right of p */
2070 proc
->next
= p
->next
;
2072 if (p
->next
) p
->next
->prev
= proc
;
2075 for(p
= host
->first
; p
; p
= p
->next
) {
2076 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
2086 int scgi_proclist_sort_down(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
2091 /* we have been the smallest of the current list
2092 * and we want to insert the node sorted as soon
2101 * the basic is idea is:
2102 * - the last active scgi process should be still
2103 * in ram and is not swapped out yet
2104 * - processes that are not reused will be killed
2105 * after some time by the trigger-handler
2107 * everything > 0 is hot
2108 * all unused procs are colder the more right they are
2109 * ice-cold processes are propably unused since more
2110 * than 'unused-timeout', are swaped out and won't be
2111 * reused in the next seconds anyway.
2115 /* nothing to sort, only one element */
2116 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
2118 for (p
= host
->first
; p
!= proc
&& p
->load
< proc
->load
; p
= p
->next
);
2121 /* no need to move something
2129 if (p
== proc
) return 0;
2131 /* we have to move left. If we are already the first element
2133 if (host
->first
== proc
) return 0;
2136 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
2137 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
2139 /* proc should be left of p */
2141 proc
->prev
= p
->prev
;
2142 if (p
->prev
) p
->prev
->next
= proc
;
2145 if (proc
->prev
== NULL
) host
->first
= proc
;
2147 for(p
= host
->first
; p
; p
= p
->next
) {
2148 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
2158 static int scgi_restart_dead_procs(server
*srv
, plugin_data
*p
, scgi_extension_host
*host
) {
2161 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2162 if (p
->conf
.debug
) {
2163 log_error_write(srv
, __FILE__
, __LINE__
, "sbdbdddd",
2165 host
->host
, proc
->port
,
2173 if (0 == proc
->is_local
) {
2175 * external servers might get disabled
2177 * enable the server again, perhaps it is back again
2180 if ((proc
->state
== PROC_STATE_DISABLED
) &&
2181 (srv
->cur_ts
- proc
->disable_ts
> host
->disable_time
)) {
2182 proc
->state
= PROC_STATE_RUNNING
;
2183 host
->active_procs
++;
2185 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2186 "fcgi-server re-enabled:",
2187 host
->host
, host
->port
,
2191 /* the child should not terminate at all */
2194 if (proc
->state
== PROC_STATE_DIED_WAIT_FOR_PID
) {
2195 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2197 /* child is still alive */
2202 if (WIFEXITED(status
)) {
2204 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2205 "child exited, pid:", proc
->pid
,
2206 "status:", WEXITSTATUS(status
));
2208 } else if (WIFSIGNALED(status
)) {
2209 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2213 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2214 "child died somehow:",
2218 proc
->state
= PROC_STATE_DIED
;
2224 * local servers might died, but we restart them
2227 if (proc
->state
== PROC_STATE_DIED
&&
2229 /* restart the child */
2231 if (p
->conf
.debug
) {
2232 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2233 "--- scgi spawning",
2234 "\n\tport:", host
->port
,
2235 "\n\tsocket", host
->unixsocket
,
2236 "\n\tcurrent:", 1, "/", host
->min_procs
);
2239 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2240 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2241 "ERROR: spawning fcgi failed.");
2242 return HANDLER_ERROR
;
2245 scgi_proclist_sort_down(srv
, host
, proc
);
2254 static handler_t
scgi_write_request(server
*srv
, handler_ctx
*hctx
) {
2255 plugin_data
*p
= hctx
->plugin_data
;
2256 scgi_extension_host
*host
= hctx
->host
;
2257 connection
*con
= hctx
->remote_conn
;
2263 log_error_write(srv
, __FILE__
, __LINE__
, "s", "fatal error: host = NULL");
2264 return HANDLER_ERROR
;
2266 if (((buffer_string_is_empty(host
->host
) || !host
->port
) && buffer_string_is_empty(host
->unixsocket
))) {
2267 log_error_write(srv
, __FILE__
, __LINE__
, "sxddd",
2270 buffer_string_length(host
->host
),
2272 buffer_string_length(host
->unixsocket
));
2273 return HANDLER_ERROR
;
2277 switch(hctx
->state
) {
2278 case FCGI_STATE_INIT
:
2279 if (-1 == (hctx
->fd
= socket(host
->family
, SOCK_STREAM
, 0))) {
2280 if (errno
== EMFILE
||
2282 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2283 "wait for fd at connection:", con
->fd
);
2285 return HANDLER_WAIT_FOR_FD
;
2288 log_error_write(srv
, __FILE__
, __LINE__
, "ssdd",
2289 "socket failed:", strerror(errno
), srv
->cur_fds
, srv
->max_fds
);
2290 return HANDLER_ERROR
;
2296 fdevent_register(srv
->ev
, hctx
->fd
, scgi_handle_fdevent
, hctx
);
2298 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
2299 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2300 "fcntl failed: ", strerror(errno
));
2302 return HANDLER_ERROR
;
2306 case FCGI_STATE_CONNECT
:
2307 if (hctx
->state
== FCGI_STATE_INIT
) {
2308 for (hctx
->proc
= hctx
->host
->first
;
2309 hctx
->proc
&& hctx
->proc
->state
!= PROC_STATE_RUNNING
;
2310 hctx
->proc
= hctx
->proc
->next
);
2312 /* all childs are dead */
2313 if (hctx
->proc
== NULL
) {
2316 return HANDLER_ERROR
;
2319 if (hctx
->proc
->is_local
) {
2320 hctx
->pid
= hctx
->proc
->pid
;
2323 switch (scgi_establish_connection(srv
, hctx
)) {
2325 scgi_set_state(srv
, hctx
, FCGI_STATE_CONNECT
);
2327 /* connection is in progress, wait for an event and call getsockopt() below */
2329 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2331 return HANDLER_WAIT_FOR_EVENT
;
2333 /* if ECONNREFUSED choose another connection -> FIXME */
2336 return HANDLER_ERROR
;
2338 /* everything is ok, go on */
2345 socklen_t socket_error_len
= sizeof(socket_error
);
2347 /* try to finish the connect() */
2348 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
2349 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2350 "getsockopt failed:", strerror(errno
));
2352 return HANDLER_ERROR
;
2354 if (socket_error
!= 0) {
2355 if (!hctx
->proc
->is_local
|| p
->conf
.debug
) {
2356 /* local procs get restarted */
2358 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2359 "establishing connection failed:", strerror(socket_error
),
2360 "port:", hctx
->proc
->port
);
2363 return HANDLER_ERROR
;
2367 /* ok, we have the connection */
2370 hctx
->proc
->last_used
= srv
->cur_ts
;
2373 if (p
->conf
.debug
) {
2374 log_error_write(srv
, __FILE__
, __LINE__
, "sddbdd",
2383 /* move the proc-list entry down the list */
2384 scgi_proclist_sort_up(srv
, hctx
->host
, hctx
->proc
);
2386 scgi_set_state(srv
, hctx
, FCGI_STATE_PREPARE_WRITE
);
2388 case FCGI_STATE_PREPARE_WRITE
:
2389 scgi_create_env(srv
, hctx
);
2391 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2392 scgi_set_state(srv
, hctx
, FCGI_STATE_WRITE
);
2395 case FCGI_STATE_WRITE
:
2396 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
2398 chunkqueue_remove_finished_chunks(hctx
->wb
);
2401 if (errno
== ENOTCONN
|| ret
== -2) {
2402 /* the connection got dropped after accept()
2404 * this is most of the time a PHP which dies
2405 * after PHP_FCGI_MAX_REQUESTS
2408 if (hctx
->wb
->bytes_out
== 0 &&
2409 hctx
->reconnects
< 5) {
2410 usleep(10000); /* take away the load of the webserver
2411 * to let the php a chance to restart
2414 scgi_reconnect(srv
, hctx
);
2416 return HANDLER_COMEBACK
;
2419 /* not reconnected ... why
2421 * far@#lighttpd report this for FreeBSD
2425 log_error_write(srv
, __FILE__
, __LINE__
, "ssosd",
2426 "connection was dropped after accept(). reconnect() denied:",
2427 "write-offset:", hctx
->wb
->bytes_out
,
2428 "reconnect attempts:", hctx
->reconnects
);
2430 return HANDLER_ERROR
;
2432 /* -1 == ret => error on our side */
2433 log_error_write(srv
, __FILE__
, __LINE__
, "ssd",
2434 "write failed:", strerror(errno
), errno
);
2436 return HANDLER_ERROR
;
2440 if (hctx
->wb
->bytes_out
== hctx
->wb_reqlen
) {
2441 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2442 shutdown(hctx
->fd
, SHUT_WR
);
2443 scgi_set_state(srv
, hctx
, FCGI_STATE_READ
);
2445 off_t wblen
= hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
;
2446 if (hctx
->wb
->bytes_in
< hctx
->wb_reqlen
&& wblen
< 65536 - 16384) {
2447 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
2448 if (!(con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_POLLIN
)) {
2449 con
->conf
.stream_request_body
|= FDEVENT_STREAM_REQUEST_POLLIN
;
2450 con
->is_readable
= 1; /* trigger optimistic read from client */
2454 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2456 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2460 return HANDLER_WAIT_FOR_EVENT
;
2461 case FCGI_STATE_READ
:
2462 /* waiting for a response */
2463 return HANDLER_WAIT_FOR_EVENT
;
2465 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
2466 return HANDLER_ERROR
;
2470 static handler_t
scgi_send_request(server
*srv
, handler_ctx
*hctx
) {
2471 /* ok, create the request */
2472 handler_t rc
= scgi_write_request(srv
, hctx
);
2473 if (HANDLER_ERROR
!= rc
) {
2476 scgi_proc
*proc
= hctx
->proc
;
2477 scgi_extension_host
*host
= hctx
->host
;
2478 plugin_data
*p
= hctx
->plugin_data
;
2479 connection
*con
= hctx
->remote_conn
;
2482 0 == proc
->is_local
&&
2483 proc
->state
!= PROC_STATE_DISABLED
) {
2484 /* only disable remote servers as we don't manage them*/
2486 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "fcgi-server disabled:",
2491 /* disable this server */
2492 proc
->disable_ts
= srv
->cur_ts
;
2493 proc
->state
= PROC_STATE_DISABLED
;
2494 host
->active_procs
--;
2497 if (hctx
->state
== FCGI_STATE_INIT
||
2498 hctx
->state
== FCGI_STATE_CONNECT
) {
2499 /* connect() or getsockopt() failed,
2500 * restart the request-handling
2502 if (proc
&& proc
->is_local
) {
2504 if (p
->conf
.debug
) {
2505 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "connect() to scgi failed, restarting the request-handling:",
2512 * several hctx might reference the same proc
2514 * Only one of them should mark the proc as dead all the other
2515 * ones should just take a new one.
2517 * If a new proc was started with the old struct this might lead
2518 * the mark a perfect proc as dead otherwise
2521 if (proc
->state
== PROC_STATE_RUNNING
&&
2522 hctx
->pid
== proc
->pid
) {
2523 proc
->state
= PROC_STATE_DIED_WAIT_FOR_PID
;
2526 scgi_restart_dead_procs(srv
, p
, host
);
2528 con
->mode
= DIRECT
;/*(avoid changing con->state, con->http_status)*/
2529 scgi_connection_close(srv
, hctx
);
2532 return HANDLER_COMEBACK
;
2534 scgi_connection_close(srv
, hctx
);
2535 con
->http_status
= 503;
2537 return HANDLER_FINISHED
;
2543 static handler_t
scgi_recv_response(server
*srv
, handler_ctx
*hctx
);
2546 SUBREQUEST_FUNC(mod_scgi_handle_subrequest
) {
2547 plugin_data
*p
= p_d
;
2549 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2551 if (NULL
== hctx
) return HANDLER_GO_ON
;
2554 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
2556 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
2557 && con
->file_started
) {
2558 if (chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
2559 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2560 } else if (!(fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_IN
)) {
2561 /* optimistic read from backend, which might re-enable FDEVENT_IN */
2562 handler_t rc
= scgi_recv_response(srv
, hctx
); /*(might invalidate hctx)*/
2563 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
2567 if (0 == hctx
->wb
->bytes_in
2568 ? con
->state
== CON_STATE_READ_POST
2569 : hctx
->wb
->bytes_in
< hctx
->wb_reqlen
) {
2570 /*(64k - 4k to attempt to avoid temporary files
2571 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
2572 if (hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
> 65536 - 4096
2573 && (con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_BUFMIN
)){
2574 con
->conf
.stream_request_body
&= ~FDEVENT_STREAM_REQUEST_POLLIN
;
2575 if (0 != hctx
->wb
->bytes_in
) return HANDLER_WAIT_FOR_EVENT
;
2577 handler_t r
= connection_handle_read_post_state(srv
, con
);
2578 chunkqueue
*req_cq
= con
->request_content_queue
;
2579 if (0 != hctx
->wb
->bytes_in
&& !chunkqueue_is_empty(req_cq
)) {
2580 chunkqueue_append_chunkqueue(hctx
->wb
, req_cq
);
2581 if (fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_OUT
) {
2582 return (r
== HANDLER_GO_ON
) ? HANDLER_WAIT_FOR_EVENT
: r
;
2585 if (r
!= HANDLER_GO_ON
) return r
;
2589 return (0 == hctx
->wb
->bytes_in
|| !chunkqueue_is_empty(hctx
->wb
))
2590 ? scgi_send_request(srv
, hctx
)
2591 : HANDLER_WAIT_FOR_EVENT
;
2595 static handler_t
scgi_recv_response(server
*srv
, handler_ctx
*hctx
) {
2597 switch (scgi_demux_response(srv
, hctx
)) {
2602 scgi_connection_close(srv
, hctx
);
2604 return HANDLER_FINISHED
;
2606 connection
*con
= hctx
->remote_conn
;
2607 plugin_data
*p
= hctx
->plugin_data
;
2609 scgi_proc
*proc
= hctx
->proc
;
2610 scgi_extension_host
*host
= hctx
->host
;
2612 if (proc
->pid
&& proc
->state
!= PROC_STATE_DIED
) {
2615 /* only fetch the zombie if it is not already done */
2617 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2619 /* child is still alive */
2624 /* the child should not terminate at all */
2625 if (WIFEXITED(status
)) {
2626 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2627 "child exited, pid:", proc
->pid
,
2628 "status:", WEXITSTATUS(status
));
2629 } else if (WIFSIGNALED(status
)) {
2630 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2634 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2635 "child died somehow:",
2639 if (p
->conf
.debug
) {
2640 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2641 "--- scgi spawning",
2642 "\n\tport:", host
->port
,
2643 "\n\tsocket", host
->unixsocket
,
2644 "\n\tcurrent:", 1, "/", host
->min_procs
);
2647 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2649 proc
->state
= PROC_STATE_DIED
;
2651 scgi_proclist_sort_down(srv
, host
, proc
);
2658 if (con
->file_started
== 0) {
2659 /* nothing has been send out yet, try to use another child */
2661 if (hctx
->wb
->bytes_out
== 0 &&
2662 hctx
->reconnects
< 5) {
2664 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2665 "response not sent, request not sent, reconnection.",
2666 "connection-fd:", con
->fd
,
2667 "fcgi-fd:", hctx
->fd
);
2669 scgi_reconnect(srv
, hctx
);
2671 return HANDLER_COMEBACK
;
2674 log_error_write(srv
, __FILE__
, __LINE__
, "sosdsd",
2675 "response not sent, request sent:", hctx
->wb
->bytes_out
,
2676 "connection-fd:", con
->fd
,
2677 "fcgi-fd:", hctx
->fd
);
2679 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2680 "response already sent out, termination connection",
2681 "connection-fd:", con
->fd
,
2682 "fcgi-fd:", hctx
->fd
);
2685 http_response_backend_error(srv
, con
);
2686 scgi_connection_close(srv
, hctx
);
2687 return HANDLER_FINISHED
;
2691 return HANDLER_GO_ON
;
2695 static handler_t
scgi_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
2696 handler_ctx
*hctx
= ctx
;
2697 connection
*con
= hctx
->remote_conn
;
2699 joblist_append(srv
, con
);
2701 if (revents
& FDEVENT_IN
) {
2702 handler_t rc
= scgi_recv_response(srv
, hctx
);/*(might invalidate hctx)*/
2703 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
2706 if (revents
& FDEVENT_OUT
) {
2707 return scgi_send_request(srv
, hctx
); /*(might invalidate hctx)*/
2710 /* perhaps this issue is already handled */
2711 if (revents
& FDEVENT_HUP
) {
2712 if (hctx
->state
== FCGI_STATE_CONNECT
) {
2713 /* getoptsock will catch this one (right ?)
2715 * if we are in connect we might get a EINPROGRESS
2716 * in the first call and a FDEVENT_HUP in the
2719 * FIXME: as it is a bit ugly.
2722 scgi_send_request(srv
, hctx
);
2723 } else if (con
->file_started
) {
2724 /* drain any remaining data from kernel pipe buffers
2725 * even if (con->conf.stream_response_body
2726 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
2727 * since event loop will spin on fd FDEVENT_HUP event
2728 * until unregistered. */
2731 rc
= scgi_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
2732 } while (rc
== HANDLER_GO_ON
); /*(unless HANDLER_GO_ON)*/
2733 return rc
; /* HANDLER_FINISHED or HANDLER_ERROR */
2735 scgi_extension_host
*host
= hctx
->host
;
2736 log_error_write(srv
, __FILE__
, __LINE__
, "sbSBSDSd",
2737 "error: unexpected close of scgi connection for",
2739 "(no scgi process on host: ",
2746 scgi_connection_close(srv
, hctx
);
2748 } else if (revents
& FDEVENT_ERR
) {
2749 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2750 "fcgi: got a FDEVENT_ERR. Don't know why.");
2752 http_response_backend_error(srv
, con
);
2753 scgi_connection_close(srv
, hctx
);
2756 return HANDLER_FINISHED
;
2760 static int scgi_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
2762 plugin_config
*s
= p
->config_storage
[0];
2767 /* skip the first, the global context */
2768 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
2769 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
2770 s
= p
->config_storage
[i
];
2772 /* condition didn't match */
2773 if (!config_check_cond(srv
, con
, dc
)) continue;
2776 for (j
= 0; j
< dc
->value
->used
; j
++) {
2777 data_unset
*du
= dc
->value
->data
[j
];
2779 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.server"))) {
2781 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.debug"))) {
2792 static handler_t
scgi_check_extension(server
*srv
, connection
*con
, void *p_d
, int uri_path_handler
) {
2793 plugin_data
*p
= p_d
;
2798 scgi_extension
*extension
= NULL
;
2799 scgi_extension_host
*host
= NULL
;
2801 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
2803 /* Possibly, we processed already this request */
2804 if (con
->file_started
== 1) return HANDLER_GO_ON
;
2806 fn
= uri_path_handler
? con
->uri
.path
: con
->physical
.path
;
2808 if (buffer_string_is_empty(fn
)) return HANDLER_GO_ON
;
2810 s_len
= buffer_string_length(fn
);
2812 scgi_patch_connection(srv
, con
, p
);
2814 /* check if extension matches */
2815 for (k
= 0; k
< p
->conf
.exts
->used
; k
++) {
2817 scgi_extension
*ext
= p
->conf
.exts
->exts
[k
];
2819 if (buffer_is_empty(ext
->key
)) continue;
2821 ct_len
= buffer_string_length(ext
->key
);
2823 if (s_len
< ct_len
) continue;
2825 /* check extension in the form "/scgi_pattern" */
2826 if (*(ext
->key
->ptr
) == '/') {
2827 if (strncmp(fn
->ptr
, ext
->key
->ptr
, ct_len
) == 0) {
2831 } else if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
)) {
2832 /* check extension in the form ".fcg" */
2838 /* extension doesn't match */
2839 if (NULL
== extension
) {
2840 return HANDLER_GO_ON
;
2843 /* get best server */
2844 for (k
= 0; k
< extension
->used
; k
++) {
2845 scgi_extension_host
*h
= extension
->hosts
[k
];
2847 /* we should have at least one proc that can do something */
2848 if (h
->active_procs
== 0) {
2852 if (used
== -1 || h
->load
< used
) {
2860 /* sorry, we don't have a server alive for this ext */
2861 con
->http_status
= 500;
2864 /* only send the 'no handler' once */
2865 if (!extension
->note_is_sent
) {
2866 extension
->note_is_sent
= 1;
2868 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbs",
2869 "all handlers for ", con
->uri
.path
,
2870 "on", extension
->key
,
2874 return HANDLER_FINISHED
;
2877 /* a note about no handler is not sent yet */
2878 extension
->note_is_sent
= 0;
2880 /* SCGI requires that Content-Length be set.
2881 * Send 411 Length Required if Content-Length missing.
2882 * (Alternatively, collect full request body before proceeding
2883 * in mod_scgi_handle_subrequest()) */
2884 if (0 == con
->request
.content_length
2885 && array_get_element(con
->request
.headers
, "Transfer-Encoding")) {
2886 con
->keep_alive
= 0;
2887 con
->http_status
= 411; /* Length Required */
2889 return HANDLER_FINISHED
;
2893 * if check-local is disabled, use the uri.path handler
2897 /* init handler-context */
2898 if (uri_path_handler
) {
2899 if (host
->check_local
== 0) {
2903 hctx
= handler_ctx_init();
2905 hctx
->remote_conn
= con
;
2906 hctx
->plugin_data
= p
;
2910 hctx
->conf
.exts
= p
->conf
.exts
;
2911 hctx
->conf
.debug
= p
->conf
.debug
;
2913 con
->plugin_ctx
[p
->id
] = hctx
;
2919 if (con
->conf
.log_request_handling
) {
2920 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2921 "handling it in mod_scgi");
2924 /* the prefix is the SCRIPT_NAME,
2925 * everything from start to the next slash
2926 * this is important for check-local = "disable"
2928 * if prefix = /admin.fcgi
2930 * /admin.fcgi/foo/bar
2932 * SCRIPT_NAME = /admin.fcgi
2933 * PATH_INFO = /foo/bar
2935 * if prefix = /fcgi-bin/
2939 * SCRIPT_NAME = /fcgi-bin/foo
2944 /* the rewrite is only done for /prefix/? matches */
2945 if (host
->fix_root_path_name
&& extension
->key
->ptr
[0] == '/' && extension
->key
->ptr
[1] == '\0') {
2946 buffer_copy_string(con
->request
.pathinfo
, con
->uri
.path
->ptr
);
2947 buffer_string_set_length(con
->uri
.path
, 0);
2948 } else if (extension
->key
->ptr
[0] == '/' &&
2949 buffer_string_length(con
->uri
.path
) > buffer_string_length(extension
->key
) &&
2950 NULL
!= (pathinfo
= strchr(con
->uri
.path
->ptr
+ buffer_string_length(extension
->key
), '/'))) {
2951 /* rewrite uri.path and pathinfo */
2953 buffer_copy_string(con
->request
.pathinfo
, pathinfo
);
2954 buffer_string_set_length(con
->uri
.path
, buffer_string_length(con
->uri
.path
) - buffer_string_length(con
->request
.pathinfo
));
2959 hctx
= handler_ctx_init();
2961 hctx
->remote_conn
= con
;
2962 hctx
->plugin_data
= p
;
2966 hctx
->conf
.exts
= p
->conf
.exts
;
2967 hctx
->conf
.debug
= p
->conf
.debug
;
2969 con
->plugin_ctx
[p
->id
] = hctx
;
2975 if (con
->conf
.log_request_handling
) {
2976 log_error_write(srv
, __FILE__
, __LINE__
, "s", "handling it in mod_scgi");
2980 return HANDLER_GO_ON
;
2983 /* uri-path handler */
2984 static handler_t
scgi_check_extension_1(server
*srv
, connection
*con
, void *p_d
) {
2985 return scgi_check_extension(srv
, con
, p_d
, 1);
2988 /* start request handler */
2989 static handler_t
scgi_check_extension_2(server
*srv
, connection
*con
, void *p_d
) {
2990 return scgi_check_extension(srv
, con
, p_d
, 0);
2994 TRIGGER_FUNC(mod_scgi_handle_trigger
) {
2995 plugin_data
*p
= p_d
;
2999 /* perhaps we should kill a connect attempt after 10-15 seconds
3001 * currently we wait for the TCP timeout which is on Linux 180 seconds
3007 /* check all childs if they are still up */
3009 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
3010 plugin_config
*conf
;
3013 conf
= p
->config_storage
[i
];
3017 for (j
= 0; j
< exts
->used
; j
++) {
3022 for (n
= 0; n
< ex
->used
; n
++) {
3025 unsigned long sum_load
= 0;
3026 scgi_extension_host
*host
;
3028 host
= ex
->hosts
[n
];
3030 scgi_restart_dead_procs(srv
, p
, host
);
3032 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
3033 sum_load
+= proc
->load
;
3036 if (host
->num_procs
&&
3037 host
->num_procs
< host
->max_procs
&&
3038 (sum_load
/ host
->num_procs
) > host
->max_load_per_proc
) {
3039 /* overload, spawn new child */
3040 scgi_proc
*fp
= NULL
;
3042 if (p
->conf
.debug
) {
3043 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3044 "overload detected, spawning a new child");
3047 for (fp
= host
->unused_procs
; fp
&& fp
->pid
!= 0; fp
= fp
->next
);
3050 if (fp
== host
->unused_procs
) host
->unused_procs
= fp
->next
;
3052 if (fp
->next
) fp
->next
->prev
= NULL
;
3056 fp
= scgi_process_init();
3057 fp
->id
= host
->max_id
++;
3062 if (buffer_string_is_empty(host
->unixsocket
)) {
3063 fp
->port
= host
->port
+ fp
->id
;
3065 buffer_copy_buffer(fp
->socket
, host
->unixsocket
);
3066 buffer_append_string_len(fp
->socket
, CONST_STR_LEN("-"));
3067 buffer_append_int(fp
->socket
, fp
->id
);
3070 if (scgi_spawn_connection(srv
, p
, host
, fp
)) {
3071 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3072 "ERROR: spawning fcgi failed.");
3073 scgi_process_free(fp
);
3074 return HANDLER_ERROR
;
3078 fp
->next
= host
->first
;
3080 host
->first
->prev
= fp
;
3085 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
3086 if (proc
->load
!= 0) break;
3087 if (host
->num_procs
<= host
->min_procs
) break;
3088 if (proc
->pid
== 0) continue;
3090 if (srv
->cur_ts
- proc
->last_used
> host
->idle_timeout
) {
3091 /* a proc is idling for a long time now,
3094 if (p
->conf
.debug
) {
3095 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
3096 "idle-timeout reached, terminating child:",
3097 "socket:", proc
->socket
,
3102 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
3103 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
3105 if (proc
->prev
== NULL
) host
->first
= proc
->next
;
3108 proc
->next
= host
->unused_procs
;
3110 if (host
->unused_procs
) host
->unused_procs
->prev
= proc
;
3111 host
->unused_procs
= proc
;
3113 kill(proc
->pid
, SIGTERM
);
3115 proc
->state
= PROC_STATE_KILLED
;
3117 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
3119 "socket:", proc
->socket
,
3124 /* proc is now in unused, let the next second handle the next process */
3129 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
3132 if (proc
->pid
== 0) continue;
3134 switch (waitpid(proc
->pid
, &status
, WNOHANG
)) {
3136 /* child still running after timeout, good */
3139 if (errno
!= EINTR
) {
3140 /* no PID found ? should never happen */
3141 log_error_write(srv
, __FILE__
, __LINE__
, "sddss",
3142 "pid ", proc
->pid
, proc
->state
,
3143 "not found:", strerror(errno
));
3146 if (errno
== ECHILD
) {
3147 /* someone else has cleaned up for us */
3149 proc
->state
= PROC_STATE_UNSET
;
3155 /* the child should not terminate at all */
3156 if (WIFEXITED(status
)) {
3157 if (proc
->state
!= PROC_STATE_KILLED
) {
3158 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
3160 WEXITSTATUS(status
), proc
->socket
);
3162 } else if (WIFSIGNALED(status
)) {
3163 if (WTERMSIG(status
) != SIGTERM
) {
3164 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3169 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3170 "child died somehow:",
3174 proc
->state
= PROC_STATE_UNSET
;
3182 return HANDLER_GO_ON
;
3186 int mod_scgi_plugin_init(plugin
*p
);
3187 int mod_scgi_plugin_init(plugin
*p
) {
3188 p
->version
= LIGHTTPD_VERSION_ID
;
3189 p
->name
= buffer_init_string("scgi");
3191 p
->init
= mod_scgi_init
;
3192 p
->cleanup
= mod_scgi_free
;
3193 p
->set_defaults
= mod_scgi_set_defaults
;
3194 p
->connection_reset
= scgi_connection_reset
;
3195 p
->handle_connection_close
= scgi_connection_reset
;
3196 p
->handle_uri_clean
= scgi_check_extension_1
;
3197 p
->handle_subrequest_start
= scgi_check_extension_2
;
3198 p
->handle_subrequest
= mod_scgi_handle_subrequest
;
3199 p
->handle_trigger
= mod_scgi_handle_trigger
;