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 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 1);
1541 scgi_env_add(p
->scgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
));
1545 for (i
= 0; i
< con
->environment
->used
; i
++) {
1548 ds
= (data_string
*)con
->environment
->data
[i
];
1550 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
1551 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 0);
1553 scgi_env_add(p
->scgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
));
1561 static int scgi_create_env(server
*srv
, handler_ctx
*hctx
) {
1562 char buf
[LI_ITOSTRING_LENGTH
];
1565 char b2
[INET6_ADDRSTRLEN
+ 1];
1569 plugin_data
*p
= hctx
->plugin_data
;
1570 scgi_extension_host
*host
= hctx
->host
;
1572 connection
*con
= hctx
->remote_conn
;
1573 server_socket
*srv_sock
= con
->srv_socket
;
1576 socklen_t our_addr_len
;
1578 buffer_string_prepare_copy(p
->scgi_env
, 1023);
1580 /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
1582 li_itostrn(buf
, sizeof(buf
), con
->request
.content_length
);
1583 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("CONTENT_LENGTH"), buf
, strlen(buf
));
1584 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCGI"), CONST_STR_LEN("1"));
1586 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con
->conf
.server_tag
));
1588 if (!buffer_is_empty(con
->server_name
)) {
1589 size_t len
= buffer_string_length(con
->server_name
);
1591 if (con
->server_name
->ptr
[0] == '[') {
1592 const char *colon
= strstr(con
->server_name
->ptr
, "]:");
1593 if (colon
) len
= (colon
+ 1) - con
->server_name
->ptr
;
1595 const char *colon
= strchr(con
->server_name
->ptr
, ':');
1596 if (colon
) len
= colon
- con
->server_name
->ptr
;
1599 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_NAME"), con
->server_name
->ptr
, len
);
1602 s
= inet_ntop(srv_sock
->addr
.plain
.sa_family
,
1603 srv_sock
->addr
.plain
.sa_family
== AF_INET6
?
1604 (const void *) &(srv_sock
->addr
.ipv6
.sin6_addr
) :
1605 (const void *) &(srv_sock
->addr
.ipv4
.sin_addr
),
1608 s
= inet_ntoa(srv_sock
->addr
.ipv4
.sin_addr
);
1611 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_NAME"), s
, strlen(s
));
1614 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1"));
1616 li_utostrn(buf
, sizeof(buf
),
1618 ntohs(srv_sock
->addr
.plain
.sa_family
? srv_sock
->addr
.ipv6
.sin6_port
: srv_sock
->addr
.ipv4
.sin_port
)
1620 ntohs(srv_sock
->addr
.ipv4
.sin_port
)
1624 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_PORT"), buf
, strlen(buf
));
1626 /* get the server-side of the connection to the client */
1627 our_addr_len
= sizeof(our_addr
);
1629 if (-1 == getsockname(con
->fd
, (struct sockaddr
*)&our_addr
, &our_addr_len
)
1630 || our_addr_len
> (socklen_t
)sizeof(our_addr
)) {
1631 s
= inet_ntop_cache_get_ip(srv
, &(srv_sock
->addr
));
1633 s
= inet_ntop_cache_get_ip(srv
, &(our_addr
));
1635 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_ADDR"), s
, strlen(s
));
1637 li_utostrn(buf
, sizeof(buf
),
1639 ntohs(con
->dst_addr
.plain
.sa_family
? con
->dst_addr
.ipv6
.sin6_port
: con
->dst_addr
.ipv4
.sin_port
)
1641 ntohs(con
->dst_addr
.ipv4
.sin_port
)
1645 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REMOTE_PORT"), buf
, strlen(buf
));
1647 s
= inet_ntop_cache_get_ip(srv
, &(con
->dst_addr
));
1649 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REMOTE_ADDR"), s
, strlen(s
));
1652 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1653 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1654 * (6.1.14, 6.1.6, 6.1.7)
1657 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con
->uri
.path
));
1659 if (!buffer_string_is_empty(con
->request
.pathinfo
)) {
1660 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con
->request
.pathinfo
));
1662 /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1664 if (!buffer_string_is_empty(host
->docroot
)) {
1665 buffer_copy_buffer(p
->path
, host
->docroot
);
1667 buffer_copy_buffer(p
->path
, con
->physical
.basedir
);
1669 buffer_append_string_buffer(p
->path
, con
->request
.pathinfo
);
1670 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p
->path
));
1672 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN(""));
1676 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1677 * http://www.php.net/manual/en/reserved.variables.php
1678 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1679 * TODO: this code should be checked against cgi.fix_pathinfo php
1683 if (!buffer_string_is_empty(host
->docroot
)) {
1685 * rewrite SCRIPT_FILENAME
1689 buffer_copy_buffer(p
->path
, host
->docroot
);
1690 buffer_append_string_buffer(p
->path
, con
->uri
.path
);
1692 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
));
1693 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host
->docroot
));
1695 buffer_copy_buffer(p
->path
, con
->physical
.path
);
1697 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
));
1698 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con
->physical
.basedir
));
1700 if (con
->error_handler_saved_status
>= 0) {
1701 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con
->request
.uri
));
1703 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con
->request
.orig_uri
));
1705 if (!buffer_string_is_empty(con
->uri
.query
)) {
1706 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con
->uri
.query
));
1708 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN(""));
1711 s
= get_http_method_name(con
->request
.http_method
);
1713 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_METHOD"), s
, strlen(s
));
1714 /* set REDIRECT_STATUS for php compiled with --force-redirect
1715 * (if REDIRECT_STATUS has not already been set by error handler) */
1716 if (0 == con
->error_handler_saved_status
) {
1717 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200"));
1719 s
= get_http_version_name(con
->request
.http_version
);
1721 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_PROTOCOL"), s
, strlen(s
));
1724 if (buffer_is_equal_caseless_string(con
->uri
.scheme
, CONST_STR_LEN("https"))) {
1725 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1729 scgi_env_add_request_headers(srv
, con
, p
);
1733 buffer_append_int(b
, buffer_string_length(p
->scgi_env
));
1734 buffer_append_string_len(b
, CONST_STR_LEN(":"));
1735 buffer_append_string_buffer(b
, p
->scgi_env
);
1736 buffer_append_string_len(b
, CONST_STR_LEN(","));
1738 hctx
->wb_reqlen
= buffer_string_length(b
);
1739 chunkqueue_append_buffer(hctx
->wb
, b
);
1742 if (con
->request
.content_length
) {
1743 chunkqueue_append_chunkqueue(hctx
->wb
, con
->request_content_queue
);
1744 hctx
->wb_reqlen
+= con
->request
.content_length
;/* (eventual) total request size */
1750 static int scgi_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
, int eol
) {
1757 buffer_copy_buffer(p
->parse_response
, in
);
1759 for (s
= p
->parse_response
->ptr
;
1760 NULL
!= (ns
= (eol
== EOL_RN
? strstr(s
, "\r\n") : strchr(s
, '\n')));
1761 s
= ns
+ (eol
== EOL_RN
? 2 : 1), line
++) {
1762 const char *key
, *value
;
1769 0 == strncmp(s
, "HTTP/1.", 7)) {
1770 /* non-parsed header ... we parse them anyway */
1776 /* after the space should be a status code for us */
1778 status
= strtol(s
+9, NULL
, 10);
1780 if (status
>= 100 && status
< 1000) {
1781 /* we expected 3 digits got them */
1782 con
->parsed_response
|= HTTP_STATUS
;
1783 con
->http_status
= status
;
1789 if (NULL
== (value
= strchr(s
, ':'))) {
1790 /* we expect: "<key>: <value>\r\n" */
1794 key_len
= value
- key
;
1798 while (*value
== ' ' || *value
== '\t') value
++;
1800 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
1801 ds
= data_response_init();
1803 buffer_copy_string_len(ds
->key
, key
, key_len
);
1804 buffer_copy_string(ds
->value
, value
);
1806 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
1810 if (0 == strncasecmp(key
, "Date", key_len
)) {
1811 con
->parsed_response
|= HTTP_DATE
;
1815 if (0 == strncasecmp(key
, "Status", key_len
)) {
1816 int status
= strtol(value
, NULL
, 10);
1817 if (status
>= 100 && status
< 1000) {
1818 con
->http_status
= status
;
1819 con
->parsed_response
|= HTTP_STATUS
;
1821 con
->http_status
= 502;
1826 if (0 == strncasecmp(key
, "Location", key_len
)) {
1827 con
->parsed_response
|= HTTP_LOCATION
;
1831 if (0 == strncasecmp(key
, "Connection", key_len
)) {
1832 con
->response
.keep_alive
= (0 == strcasecmp(value
, "Keep-Alive")) ? 1 : 0;
1833 con
->parsed_response
|= HTTP_CONNECTION
;
1837 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
1838 con
->response
.content_length
= strtoul(value
, NULL
, 10);
1839 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
1848 /* CGI/1.1 rev 03 - 7.2.1.2 */
1849 if ((con
->parsed_response
& HTTP_LOCATION
) &&
1850 !(con
->parsed_response
& HTTP_STATUS
)) {
1851 con
->http_status
= 302;
1858 static int scgi_demux_response(server
*srv
, handler_ctx
*hctx
) {
1859 plugin_data
*p
= hctx
->plugin_data
;
1860 connection
*con
= hctx
->remote_conn
;
1865 buffer_string_prepare_copy(hctx
->response
, 1023);
1866 if (-1 == (n
= read(hctx
->fd
, hctx
->response
->ptr
, hctx
->response
->size
- 1))) {
1867 if (errno
== EAGAIN
|| errno
== EINTR
) {
1868 /* would block, wait for signal */
1869 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
1873 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", strerror(errno
), con
->fd
, hctx
->fd
);
1882 buffer_commit(hctx
->response
, n
);
1884 /* split header from body */
1886 if (con
->file_started
== 0) {
1890 int cp
, eol
= EOL_UNSET
;
1894 buffer_append_string_buffer(hctx
->response_header
, hctx
->response
);
1896 /* nph (non-parsed headers) */
1897 if (0 == strncmp(hctx
->response_header
->ptr
, "HTTP/1.", 7)) in_header
= 1;
1899 /* search for the \r\n\r\n or \n\n in the string */
1900 for (c
= hctx
->response_header
->ptr
, cp
= 0, used
= buffer_string_length(hctx
->response_header
); used
; c
++, cp
++, used
--) {
1901 if (*c
== ':') in_header
= 1;
1902 else if (*c
== '\n') {
1903 if (in_header
== 0) {
1904 /* got a response without a response header */
1911 if (eol
== EOL_UNSET
) eol
= EOL_N
;
1913 if (*(c
+1) == '\n') {
1919 } else if (used
> 1 && *c
== '\r' && *(c
+1) == '\n') {
1920 if (in_header
== 0) {
1921 /* got a response without a response header */
1928 if (eol
== EOL_UNSET
) eol
= EOL_RN
;
1947 /* no header, but a body */
1948 if (0 != http_chunk_append_buffer(srv
, con
, hctx
->response_header
)) {
1949 /* error writing to tempfile;
1950 * truncate response or send 500 if nothing sent yet */
1954 size_t blen
= buffer_string_length(hctx
->response_header
) - hlen
;
1956 /* a small hack: terminate after at the second \r */
1957 buffer_string_set_length(hctx
->response_header
, hlen
- 1);
1959 /* parse the response header */
1960 scgi_response_parse(srv
, con
, p
, hctx
->response_header
, eol
);
1962 if (hctx
->host
->xsendfile_allow
) {
1964 if (NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "X-Sendfile"))) {
1965 http_response_xsendfile(srv
, con
, ds
->value
, hctx
->host
->xsendfile_docroot
);
1971 if (0 != http_chunk_append_mem(srv
, con
, hctx
->response_header
->ptr
+ hlen
, blen
)) {
1972 /* error writing to tempfile;
1973 * truncate response or send 500 if nothing sent yet */
1979 con
->file_started
= 1;
1981 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
1982 if (buffer_string_length(hctx
->response_header
) > MAX_HTTP_REQUEST_HEADER
) {
1983 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "response headers too large for", con
->uri
.path
);
1984 con
->http_status
= 502; /* Bad Gateway */
1990 if (0 != http_chunk_append_buffer(srv
, con
, hctx
->response
)) {
1991 /* error writing to tempfile;
1992 * truncate response or send 500 if nothing sent yet */
1995 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
1996 && chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
1997 if (!con
->is_writable
) {
1998 /*(defer removal of FDEVENT_IN interest since
1999 * connection_state_machine() might be able to send data
2000 * immediately, unless !con->is_writable, where
2001 * connection_state_machine() might not loop back to call
2002 * mod_scgi_handle_subrequest())*/
2003 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2010 log_error_write(srv
, __FILE__
, __LINE__
, "ddss", con
->fd
, hctx
->fd
, connection_get_state(con
->state
), b
->ptr
);
2018 static int scgi_proclist_sort_up(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
2023 /* we have been the smallest of the current list
2024 * and we want to insert the node sorted as soon
2034 /* nothing to sort, only one element */
2035 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
2037 for (p
= proc
; p
->next
&& p
->next
->load
< proc
->load
; p
= p
->next
);
2039 /* no need to move something
2047 if (p
== proc
) return 0;
2049 if (host
->first
== proc
) {
2050 /* we have been the first elememt */
2052 host
->first
= proc
->next
;
2053 host
->first
->prev
= NULL
;
2056 /* disconnect proc */
2058 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
2059 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
2061 /* proc should be right of p */
2063 proc
->next
= p
->next
;
2065 if (p
->next
) p
->next
->prev
= proc
;
2068 for(p
= host
->first
; p
; p
= p
->next
) {
2069 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
2079 int scgi_proclist_sort_down(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
2084 /* we have been the smallest of the current list
2085 * and we want to insert the node sorted as soon
2094 * the basic is idea is:
2095 * - the last active scgi process should be still
2096 * in ram and is not swapped out yet
2097 * - processes that are not reused will be killed
2098 * after some time by the trigger-handler
2100 * everything > 0 is hot
2101 * all unused procs are colder the more right they are
2102 * ice-cold processes are propably unused since more
2103 * than 'unused-timeout', are swaped out and won't be
2104 * reused in the next seconds anyway.
2108 /* nothing to sort, only one element */
2109 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
2111 for (p
= host
->first
; p
!= proc
&& p
->load
< proc
->load
; p
= p
->next
);
2114 /* no need to move something
2122 if (p
== proc
) return 0;
2124 /* we have to move left. If we are already the first element
2126 if (host
->first
== proc
) return 0;
2129 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
2130 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
2132 /* proc should be left of p */
2134 proc
->prev
= p
->prev
;
2135 if (p
->prev
) p
->prev
->next
= proc
;
2138 if (proc
->prev
== NULL
) host
->first
= proc
;
2140 for(p
= host
->first
; p
; p
= p
->next
) {
2141 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
2151 static int scgi_restart_dead_procs(server
*srv
, plugin_data
*p
, scgi_extension_host
*host
) {
2154 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2155 if (p
->conf
.debug
) {
2156 log_error_write(srv
, __FILE__
, __LINE__
, "sbdbdddd",
2158 host
->host
, proc
->port
,
2166 if (0 == proc
->is_local
) {
2168 * external servers might get disabled
2170 * enable the server again, perhaps it is back again
2173 if ((proc
->state
== PROC_STATE_DISABLED
) &&
2174 (srv
->cur_ts
- proc
->disable_ts
> host
->disable_time
)) {
2175 proc
->state
= PROC_STATE_RUNNING
;
2176 host
->active_procs
++;
2178 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2179 "fcgi-server re-enabled:",
2180 host
->host
, host
->port
,
2184 /* the child should not terminate at all */
2187 if (proc
->state
== PROC_STATE_DIED_WAIT_FOR_PID
) {
2188 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2190 /* child is still alive */
2195 if (WIFEXITED(status
)) {
2197 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2198 "child exited, pid:", proc
->pid
,
2199 "status:", WEXITSTATUS(status
));
2201 } else if (WIFSIGNALED(status
)) {
2202 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2206 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2207 "child died somehow:",
2211 proc
->state
= PROC_STATE_DIED
;
2217 * local servers might died, but we restart them
2220 if (proc
->state
== PROC_STATE_DIED
&&
2222 /* restart the child */
2224 if (p
->conf
.debug
) {
2225 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2226 "--- scgi spawning",
2227 "\n\tport:", host
->port
,
2228 "\n\tsocket", host
->unixsocket
,
2229 "\n\tcurrent:", 1, "/", host
->min_procs
);
2232 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2233 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2234 "ERROR: spawning fcgi failed.");
2235 return HANDLER_ERROR
;
2238 scgi_proclist_sort_down(srv
, host
, proc
);
2247 static handler_t
scgi_write_request(server
*srv
, handler_ctx
*hctx
) {
2248 plugin_data
*p
= hctx
->plugin_data
;
2249 scgi_extension_host
*host
= hctx
->host
;
2250 connection
*con
= hctx
->remote_conn
;
2256 log_error_write(srv
, __FILE__
, __LINE__
, "s", "fatal error: host = NULL");
2257 return HANDLER_ERROR
;
2259 if (((buffer_string_is_empty(host
->host
) || !host
->port
) && buffer_string_is_empty(host
->unixsocket
))) {
2260 log_error_write(srv
, __FILE__
, __LINE__
, "sxddd",
2263 buffer_string_length(host
->host
),
2265 buffer_string_length(host
->unixsocket
));
2266 return HANDLER_ERROR
;
2270 switch(hctx
->state
) {
2271 case FCGI_STATE_INIT
:
2272 if (-1 == (hctx
->fd
= socket(host
->family
, SOCK_STREAM
, 0))) {
2273 if (errno
== EMFILE
||
2275 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2276 "wait for fd at connection:", con
->fd
);
2278 return HANDLER_WAIT_FOR_FD
;
2281 log_error_write(srv
, __FILE__
, __LINE__
, "ssdd",
2282 "socket failed:", strerror(errno
), srv
->cur_fds
, srv
->max_fds
);
2283 return HANDLER_ERROR
;
2289 fdevent_register(srv
->ev
, hctx
->fd
, scgi_handle_fdevent
, hctx
);
2291 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
2292 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2293 "fcntl failed: ", strerror(errno
));
2295 return HANDLER_ERROR
;
2299 case FCGI_STATE_CONNECT
:
2300 if (hctx
->state
== FCGI_STATE_INIT
) {
2301 for (hctx
->proc
= hctx
->host
->first
;
2302 hctx
->proc
&& hctx
->proc
->state
!= PROC_STATE_RUNNING
;
2303 hctx
->proc
= hctx
->proc
->next
);
2305 /* all childs are dead */
2306 if (hctx
->proc
== NULL
) {
2309 return HANDLER_ERROR
;
2312 if (hctx
->proc
->is_local
) {
2313 hctx
->pid
= hctx
->proc
->pid
;
2316 switch (scgi_establish_connection(srv
, hctx
)) {
2318 scgi_set_state(srv
, hctx
, FCGI_STATE_CONNECT
);
2320 /* connection is in progress, wait for an event and call getsockopt() below */
2322 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2324 return HANDLER_WAIT_FOR_EVENT
;
2326 /* if ECONNREFUSED choose another connection -> FIXME */
2329 return HANDLER_ERROR
;
2331 /* everything is ok, go on */
2338 socklen_t socket_error_len
= sizeof(socket_error
);
2340 /* try to finish the connect() */
2341 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
2342 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2343 "getsockopt failed:", strerror(errno
));
2345 return HANDLER_ERROR
;
2347 if (socket_error
!= 0) {
2348 if (!hctx
->proc
->is_local
|| p
->conf
.debug
) {
2349 /* local procs get restarted */
2351 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2352 "establishing connection failed:", strerror(socket_error
),
2353 "port:", hctx
->proc
->port
);
2356 return HANDLER_ERROR
;
2360 /* ok, we have the connection */
2363 hctx
->proc
->last_used
= srv
->cur_ts
;
2366 if (p
->conf
.debug
) {
2367 log_error_write(srv
, __FILE__
, __LINE__
, "sddbdd",
2376 /* move the proc-list entry down the list */
2377 scgi_proclist_sort_up(srv
, hctx
->host
, hctx
->proc
);
2379 scgi_set_state(srv
, hctx
, FCGI_STATE_PREPARE_WRITE
);
2381 case FCGI_STATE_PREPARE_WRITE
:
2382 scgi_create_env(srv
, hctx
);
2384 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2385 scgi_set_state(srv
, hctx
, FCGI_STATE_WRITE
);
2388 case FCGI_STATE_WRITE
:
2389 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
2391 chunkqueue_remove_finished_chunks(hctx
->wb
);
2394 if (errno
== ENOTCONN
|| ret
== -2) {
2395 /* the connection got dropped after accept()
2397 * this is most of the time a PHP which dies
2398 * after PHP_FCGI_MAX_REQUESTS
2401 if (hctx
->wb
->bytes_out
== 0 &&
2402 hctx
->reconnects
< 5) {
2403 usleep(10000); /* take away the load of the webserver
2404 * to let the php a chance to restart
2407 scgi_reconnect(srv
, hctx
);
2409 return HANDLER_COMEBACK
;
2412 /* not reconnected ... why
2414 * far@#lighttpd report this for FreeBSD
2418 log_error_write(srv
, __FILE__
, __LINE__
, "ssosd",
2419 "connection was dropped after accept(). reconnect() denied:",
2420 "write-offset:", hctx
->wb
->bytes_out
,
2421 "reconnect attempts:", hctx
->reconnects
);
2423 return HANDLER_ERROR
;
2425 /* -1 == ret => error on our side */
2426 log_error_write(srv
, __FILE__
, __LINE__
, "ssd",
2427 "write failed:", strerror(errno
), errno
);
2429 return HANDLER_ERROR
;
2433 if (hctx
->wb
->bytes_out
== hctx
->wb_reqlen
) {
2434 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2435 shutdown(hctx
->fd
, SHUT_WR
);
2436 scgi_set_state(srv
, hctx
, FCGI_STATE_READ
);
2438 off_t wblen
= hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
;
2439 if (hctx
->wb
->bytes_in
< hctx
->wb_reqlen
&& wblen
< 65536 - 16384) {
2440 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
2441 if (!(con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_POLLIN
)) {
2442 con
->conf
.stream_request_body
|= FDEVENT_STREAM_REQUEST_POLLIN
;
2443 con
->is_readable
= 1; /* trigger optimistic read from client */
2447 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2449 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2453 return HANDLER_WAIT_FOR_EVENT
;
2454 case FCGI_STATE_READ
:
2455 /* waiting for a response */
2456 return HANDLER_WAIT_FOR_EVENT
;
2458 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
2459 return HANDLER_ERROR
;
2463 static handler_t
scgi_send_request(server
*srv
, handler_ctx
*hctx
) {
2464 /* ok, create the request */
2465 handler_t rc
= scgi_write_request(srv
, hctx
);
2466 if (HANDLER_ERROR
!= rc
) {
2469 scgi_proc
*proc
= hctx
->proc
;
2470 scgi_extension_host
*host
= hctx
->host
;
2471 plugin_data
*p
= hctx
->plugin_data
;
2472 connection
*con
= hctx
->remote_conn
;
2475 0 == proc
->is_local
&&
2476 proc
->state
!= PROC_STATE_DISABLED
) {
2477 /* only disable remote servers as we don't manage them*/
2479 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "fcgi-server disabled:",
2484 /* disable this server */
2485 proc
->disable_ts
= srv
->cur_ts
;
2486 proc
->state
= PROC_STATE_DISABLED
;
2487 host
->active_procs
--;
2490 if (hctx
->state
== FCGI_STATE_INIT
||
2491 hctx
->state
== FCGI_STATE_CONNECT
) {
2492 /* connect() or getsockopt() failed,
2493 * restart the request-handling
2495 if (proc
&& proc
->is_local
) {
2497 if (p
->conf
.debug
) {
2498 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "connect() to scgi failed, restarting the request-handling:",
2505 * several hctx might reference the same proc
2507 * Only one of them should mark the proc as dead all the other
2508 * ones should just take a new one.
2510 * If a new proc was started with the old struct this might lead
2511 * the mark a perfect proc as dead otherwise
2514 if (proc
->state
== PROC_STATE_RUNNING
&&
2515 hctx
->pid
== proc
->pid
) {
2516 proc
->state
= PROC_STATE_DIED_WAIT_FOR_PID
;
2519 scgi_restart_dead_procs(srv
, p
, host
);
2521 con
->mode
= DIRECT
;/*(avoid changing con->state, con->http_status)*/
2522 scgi_connection_close(srv
, hctx
);
2525 return HANDLER_COMEBACK
;
2527 scgi_connection_close(srv
, hctx
);
2528 con
->http_status
= 503;
2530 return HANDLER_FINISHED
;
2536 static handler_t
scgi_recv_response(server
*srv
, handler_ctx
*hctx
);
2539 SUBREQUEST_FUNC(mod_scgi_handle_subrequest
) {
2540 plugin_data
*p
= p_d
;
2542 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2544 if (NULL
== hctx
) return HANDLER_GO_ON
;
2547 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
2549 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
2550 && con
->file_started
) {
2551 if (chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
2552 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2553 } else if (!(fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_IN
)) {
2554 /* optimistic read from backend, which might re-enable FDEVENT_IN */
2555 handler_t rc
= scgi_recv_response(srv
, hctx
); /*(might invalidate hctx)*/
2556 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
2560 if (0 == hctx
->wb
->bytes_in
2561 ? con
->state
== CON_STATE_READ_POST
2562 : hctx
->wb
->bytes_in
< hctx
->wb_reqlen
) {
2563 /*(64k - 4k to attempt to avoid temporary files
2564 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
2565 if (hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
> 65536 - 4096
2566 && (con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_BUFMIN
)){
2567 con
->conf
.stream_request_body
&= ~FDEVENT_STREAM_REQUEST_POLLIN
;
2568 if (0 != hctx
->wb
->bytes_in
) return HANDLER_WAIT_FOR_EVENT
;
2570 handler_t r
= connection_handle_read_post_state(srv
, con
);
2571 chunkqueue
*req_cq
= con
->request_content_queue
;
2572 if (0 != hctx
->wb
->bytes_in
&& !chunkqueue_is_empty(req_cq
)) {
2573 chunkqueue_append_chunkqueue(hctx
->wb
, req_cq
);
2574 if (fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_OUT
) {
2575 return (r
== HANDLER_GO_ON
) ? HANDLER_WAIT_FOR_EVENT
: r
;
2578 if (r
!= HANDLER_GO_ON
) return r
;
2582 return (0 == hctx
->wb
->bytes_in
|| !chunkqueue_is_empty(hctx
->wb
))
2583 ? scgi_send_request(srv
, hctx
)
2584 : HANDLER_WAIT_FOR_EVENT
;
2588 static handler_t
scgi_recv_response(server
*srv
, handler_ctx
*hctx
) {
2590 switch (scgi_demux_response(srv
, hctx
)) {
2595 scgi_connection_close(srv
, hctx
);
2597 return HANDLER_FINISHED
;
2599 connection
*con
= hctx
->remote_conn
;
2600 plugin_data
*p
= hctx
->plugin_data
;
2602 scgi_proc
*proc
= hctx
->proc
;
2603 scgi_extension_host
*host
= hctx
->host
;
2605 if (proc
->pid
&& proc
->state
!= PROC_STATE_DIED
) {
2608 /* only fetch the zombie if it is not already done */
2610 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2612 /* child is still alive */
2617 /* the child should not terminate at all */
2618 if (WIFEXITED(status
)) {
2619 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2620 "child exited, pid:", proc
->pid
,
2621 "status:", WEXITSTATUS(status
));
2622 } else if (WIFSIGNALED(status
)) {
2623 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2627 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2628 "child died somehow:",
2632 if (p
->conf
.debug
) {
2633 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2634 "--- scgi spawning",
2635 "\n\tport:", host
->port
,
2636 "\n\tsocket", host
->unixsocket
,
2637 "\n\tcurrent:", 1, "/", host
->min_procs
);
2640 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2642 proc
->state
= PROC_STATE_DIED
;
2644 scgi_proclist_sort_down(srv
, host
, proc
);
2651 if (con
->file_started
== 0) {
2652 /* nothing has been send out yet, try to use another child */
2654 if (hctx
->wb
->bytes_out
== 0 &&
2655 hctx
->reconnects
< 5) {
2657 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2658 "response not sent, request not sent, reconnection.",
2659 "connection-fd:", con
->fd
,
2660 "fcgi-fd:", hctx
->fd
);
2662 scgi_reconnect(srv
, hctx
);
2664 return HANDLER_COMEBACK
;
2667 log_error_write(srv
, __FILE__
, __LINE__
, "sosdsd",
2668 "response not sent, request sent:", hctx
->wb
->bytes_out
,
2669 "connection-fd:", con
->fd
,
2670 "fcgi-fd:", hctx
->fd
);
2672 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2673 "response already sent out, termination connection",
2674 "connection-fd:", con
->fd
,
2675 "fcgi-fd:", hctx
->fd
);
2678 http_response_backend_error(srv
, con
);
2679 scgi_connection_close(srv
, hctx
);
2680 return HANDLER_FINISHED
;
2684 return HANDLER_GO_ON
;
2688 static handler_t
scgi_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
2689 handler_ctx
*hctx
= ctx
;
2690 connection
*con
= hctx
->remote_conn
;
2692 joblist_append(srv
, con
);
2694 if (revents
& FDEVENT_IN
) {
2695 handler_t rc
= scgi_recv_response(srv
, hctx
);/*(might invalidate hctx)*/
2696 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
2699 if (revents
& FDEVENT_OUT
) {
2700 return scgi_send_request(srv
, hctx
); /*(might invalidate hctx)*/
2703 /* perhaps this issue is already handled */
2704 if (revents
& FDEVENT_HUP
) {
2705 if (hctx
->state
== FCGI_STATE_CONNECT
) {
2706 /* getoptsock will catch this one (right ?)
2708 * if we are in connect we might get a EINPROGRESS
2709 * in the first call and a FDEVENT_HUP in the
2712 * FIXME: as it is a bit ugly.
2715 scgi_send_request(srv
, hctx
);
2716 } else if (con
->file_started
) {
2717 /* drain any remaining data from kernel pipe buffers
2718 * even if (con->conf.stream_response_body
2719 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
2720 * since event loop will spin on fd FDEVENT_HUP event
2721 * until unregistered. */
2724 rc
= scgi_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
2725 } while (rc
== HANDLER_GO_ON
); /*(unless HANDLER_GO_ON)*/
2726 return rc
; /* HANDLER_FINISHED or HANDLER_ERROR */
2728 scgi_extension_host
*host
= hctx
->host
;
2729 log_error_write(srv
, __FILE__
, __LINE__
, "sbSBSDSd",
2730 "error: unexpected close of scgi connection for",
2732 "(no scgi process on host: ",
2739 scgi_connection_close(srv
, hctx
);
2741 } else if (revents
& FDEVENT_ERR
) {
2742 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2743 "fcgi: got a FDEVENT_ERR. Don't know why.");
2745 http_response_backend_error(srv
, con
);
2746 scgi_connection_close(srv
, hctx
);
2749 return HANDLER_FINISHED
;
2753 static int scgi_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
2755 plugin_config
*s
= p
->config_storage
[0];
2760 /* skip the first, the global context */
2761 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
2762 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
2763 s
= p
->config_storage
[i
];
2765 /* condition didn't match */
2766 if (!config_check_cond(srv
, con
, dc
)) continue;
2769 for (j
= 0; j
< dc
->value
->used
; j
++) {
2770 data_unset
*du
= dc
->value
->data
[j
];
2772 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.server"))) {
2774 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.debug"))) {
2785 static handler_t
scgi_check_extension(server
*srv
, connection
*con
, void *p_d
, int uri_path_handler
) {
2786 plugin_data
*p
= p_d
;
2791 scgi_extension
*extension
= NULL
;
2792 scgi_extension_host
*host
= NULL
;
2794 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
2796 /* Possibly, we processed already this request */
2797 if (con
->file_started
== 1) return HANDLER_GO_ON
;
2799 fn
= uri_path_handler
? con
->uri
.path
: con
->physical
.path
;
2801 if (buffer_string_is_empty(fn
)) return HANDLER_GO_ON
;
2803 s_len
= buffer_string_length(fn
);
2805 scgi_patch_connection(srv
, con
, p
);
2807 /* check if extension matches */
2808 for (k
= 0; k
< p
->conf
.exts
->used
; k
++) {
2810 scgi_extension
*ext
= p
->conf
.exts
->exts
[k
];
2812 if (buffer_is_empty(ext
->key
)) continue;
2814 ct_len
= buffer_string_length(ext
->key
);
2816 if (s_len
< ct_len
) continue;
2818 /* check extension in the form "/scgi_pattern" */
2819 if (*(ext
->key
->ptr
) == '/') {
2820 if (strncmp(fn
->ptr
, ext
->key
->ptr
, ct_len
) == 0) {
2824 } else if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
)) {
2825 /* check extension in the form ".fcg" */
2831 /* extension doesn't match */
2832 if (NULL
== extension
) {
2833 return HANDLER_GO_ON
;
2836 /* get best server */
2837 for (k
= 0; k
< extension
->used
; k
++) {
2838 scgi_extension_host
*h
= extension
->hosts
[k
];
2840 /* we should have at least one proc that can do something */
2841 if (h
->active_procs
== 0) {
2845 if (used
== -1 || h
->load
< used
) {
2853 /* sorry, we don't have a server alive for this ext */
2854 con
->http_status
= 500;
2857 /* only send the 'no handler' once */
2858 if (!extension
->note_is_sent
) {
2859 extension
->note_is_sent
= 1;
2861 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbs",
2862 "all handlers for ", con
->uri
.path
,
2863 "on", extension
->key
,
2867 return HANDLER_FINISHED
;
2870 /* a note about no handler is not sent yet */
2871 extension
->note_is_sent
= 0;
2873 /* SCGI requires that Content-Length be set.
2874 * Send 411 Length Required if Content-Length missing.
2875 * (Alternatively, collect full request body before proceeding
2876 * in mod_scgi_handle_subrequest()) */
2877 if (0 == con
->request
.content_length
2878 && array_get_element(con
->request
.headers
, "Transfer-Encoding")) {
2879 con
->keep_alive
= 0;
2880 con
->http_status
= 411; /* Length Required */
2882 return HANDLER_FINISHED
;
2886 * if check-local is disabled, use the uri.path handler
2890 /* init handler-context */
2891 if (uri_path_handler
) {
2892 if (host
->check_local
== 0) {
2896 hctx
= handler_ctx_init();
2898 hctx
->remote_conn
= con
;
2899 hctx
->plugin_data
= p
;
2903 hctx
->conf
.exts
= p
->conf
.exts
;
2904 hctx
->conf
.debug
= p
->conf
.debug
;
2906 con
->plugin_ctx
[p
->id
] = hctx
;
2912 if (con
->conf
.log_request_handling
) {
2913 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2914 "handling it in mod_scgi");
2917 /* the prefix is the SCRIPT_NAME,
2918 * everything from start to the next slash
2919 * this is important for check-local = "disable"
2921 * if prefix = /admin.fcgi
2923 * /admin.fcgi/foo/bar
2925 * SCRIPT_NAME = /admin.fcgi
2926 * PATH_INFO = /foo/bar
2928 * if prefix = /fcgi-bin/
2932 * SCRIPT_NAME = /fcgi-bin/foo
2937 /* the rewrite is only done for /prefix/? matches */
2938 if (host
->fix_root_path_name
&& extension
->key
->ptr
[0] == '/' && extension
->key
->ptr
[1] == '\0') {
2939 buffer_copy_string(con
->request
.pathinfo
, con
->uri
.path
->ptr
);
2940 buffer_string_set_length(con
->uri
.path
, 0);
2941 } else if (extension
->key
->ptr
[0] == '/' &&
2942 buffer_string_length(con
->uri
.path
) > buffer_string_length(extension
->key
) &&
2943 NULL
!= (pathinfo
= strchr(con
->uri
.path
->ptr
+ buffer_string_length(extension
->key
), '/'))) {
2944 /* rewrite uri.path and pathinfo */
2946 buffer_copy_string(con
->request
.pathinfo
, pathinfo
);
2947 buffer_string_set_length(con
->uri
.path
, buffer_string_length(con
->uri
.path
) - buffer_string_length(con
->request
.pathinfo
));
2952 hctx
= handler_ctx_init();
2954 hctx
->remote_conn
= con
;
2955 hctx
->plugin_data
= p
;
2959 hctx
->conf
.exts
= p
->conf
.exts
;
2960 hctx
->conf
.debug
= p
->conf
.debug
;
2962 con
->plugin_ctx
[p
->id
] = hctx
;
2968 if (con
->conf
.log_request_handling
) {
2969 log_error_write(srv
, __FILE__
, __LINE__
, "s", "handling it in mod_scgi");
2973 return HANDLER_GO_ON
;
2976 /* uri-path handler */
2977 static handler_t
scgi_check_extension_1(server
*srv
, connection
*con
, void *p_d
) {
2978 return scgi_check_extension(srv
, con
, p_d
, 1);
2981 /* start request handler */
2982 static handler_t
scgi_check_extension_2(server
*srv
, connection
*con
, void *p_d
) {
2983 return scgi_check_extension(srv
, con
, p_d
, 0);
2987 TRIGGER_FUNC(mod_scgi_handle_trigger
) {
2988 plugin_data
*p
= p_d
;
2992 /* perhaps we should kill a connect attempt after 10-15 seconds
2994 * currently we wait for the TCP timeout which is on Linux 180 seconds
3000 /* check all childs if they are still up */
3002 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
3003 plugin_config
*conf
;
3006 conf
= p
->config_storage
[i
];
3010 for (j
= 0; j
< exts
->used
; j
++) {
3015 for (n
= 0; n
< ex
->used
; n
++) {
3018 unsigned long sum_load
= 0;
3019 scgi_extension_host
*host
;
3021 host
= ex
->hosts
[n
];
3023 scgi_restart_dead_procs(srv
, p
, host
);
3025 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
3026 sum_load
+= proc
->load
;
3029 if (host
->num_procs
&&
3030 host
->num_procs
< host
->max_procs
&&
3031 (sum_load
/ host
->num_procs
) > host
->max_load_per_proc
) {
3032 /* overload, spawn new child */
3033 scgi_proc
*fp
= NULL
;
3035 if (p
->conf
.debug
) {
3036 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3037 "overload detected, spawning a new child");
3040 for (fp
= host
->unused_procs
; fp
&& fp
->pid
!= 0; fp
= fp
->next
);
3043 if (fp
== host
->unused_procs
) host
->unused_procs
= fp
->next
;
3045 if (fp
->next
) fp
->next
->prev
= NULL
;
3049 fp
= scgi_process_init();
3050 fp
->id
= host
->max_id
++;
3055 if (buffer_string_is_empty(host
->unixsocket
)) {
3056 fp
->port
= host
->port
+ fp
->id
;
3058 buffer_copy_buffer(fp
->socket
, host
->unixsocket
);
3059 buffer_append_string_len(fp
->socket
, CONST_STR_LEN("-"));
3060 buffer_append_int(fp
->socket
, fp
->id
);
3063 if (scgi_spawn_connection(srv
, p
, host
, fp
)) {
3064 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3065 "ERROR: spawning fcgi failed.");
3066 scgi_process_free(fp
);
3067 return HANDLER_ERROR
;
3071 fp
->next
= host
->first
;
3073 host
->first
->prev
= fp
;
3078 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
3079 if (proc
->load
!= 0) break;
3080 if (host
->num_procs
<= host
->min_procs
) break;
3081 if (proc
->pid
== 0) continue;
3083 if (srv
->cur_ts
- proc
->last_used
> host
->idle_timeout
) {
3084 /* a proc is idling for a long time now,
3087 if (p
->conf
.debug
) {
3088 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
3089 "idle-timeout reached, terminating child:",
3090 "socket:", proc
->socket
,
3095 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
3096 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
3098 if (proc
->prev
== NULL
) host
->first
= proc
->next
;
3101 proc
->next
= host
->unused_procs
;
3103 if (host
->unused_procs
) host
->unused_procs
->prev
= proc
;
3104 host
->unused_procs
= proc
;
3106 kill(proc
->pid
, SIGTERM
);
3108 proc
->state
= PROC_STATE_KILLED
;
3110 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
3112 "socket:", proc
->socket
,
3117 /* proc is now in unused, let the next second handle the next process */
3122 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
3125 if (proc
->pid
== 0) continue;
3127 switch (waitpid(proc
->pid
, &status
, WNOHANG
)) {
3129 /* child still running after timeout, good */
3132 if (errno
!= EINTR
) {
3133 /* no PID found ? should never happen */
3134 log_error_write(srv
, __FILE__
, __LINE__
, "sddss",
3135 "pid ", proc
->pid
, proc
->state
,
3136 "not found:", strerror(errno
));
3139 if (errno
== ECHILD
) {
3140 /* someone else has cleaned up for us */
3142 proc
->state
= PROC_STATE_UNSET
;
3148 /* the child should not terminate at all */
3149 if (WIFEXITED(status
)) {
3150 if (proc
->state
!= PROC_STATE_KILLED
) {
3151 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
3153 WEXITSTATUS(status
), proc
->socket
);
3155 } else if (WIFSIGNALED(status
)) {
3156 if (WTERMSIG(status
) != SIGTERM
) {
3157 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3162 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3163 "child died somehow:",
3167 proc
->state
= PROC_STATE_UNSET
;
3175 return HANDLER_GO_ON
;
3179 int mod_scgi_plugin_init(plugin
*p
);
3180 int mod_scgi_plugin_init(plugin
*p
) {
3181 p
->version
= LIGHTTPD_VERSION_ID
;
3182 p
->name
= buffer_init_string("scgi");
3184 p
->init
= mod_scgi_init
;
3185 p
->cleanup
= mod_scgi_free
;
3186 p
->set_defaults
= mod_scgi_set_defaults
;
3187 p
->connection_reset
= scgi_connection_reset
;
3188 p
->handle_connection_close
= scgi_connection_reset
;
3189 p
->handle_uri_clean
= scgi_check_extension_1
;
3190 p
->handle_subrequest_start
= scgi_check_extension_2
;
3191 p
->handle_subrequest
= mod_scgi_handle_subrequest
;
3192 p
->handle_trigger
= mod_scgi_handle_trigger
;