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"
31 #include "sys-endian.h"
37 #ifdef HAVE_SYS_WAIT_H
38 # include <sys/wait.h>
41 enum {EOL_UNSET
, EOL_N
, EOL_RN
};
47 * - add timeout for a connect to a non-scgi process
48 * (use state_timestamp + state)
52 typedef struct scgi_proc
{
53 size_t id
; /* id will be between 1 and max_procs */
54 buffer
*socket
; /* config.socket + "-" + id */
55 unsigned port
; /* config.port + pno */
57 pid_t pid
; /* PID of the spawned process (0 if not spawned locally) */
60 size_t load
; /* number of requests waiting on this process */
62 time_t last_used
; /* see idle_timeout */
63 size_t requests
; /* see max_requests */
64 struct scgi_proc
*prev
, *next
; /* see first */
66 time_t disable_ts
; /* replace by host->something */
70 enum { PROC_STATE_UNSET
, /* init-phase */
71 PROC_STATE_RUNNING
, /* alive */
72 PROC_STATE_DIED_WAIT_FOR_PID
,
73 PROC_STATE_KILLED
, /* was killed as we don't have the load anymore */
74 PROC_STATE_DIED
, /* marked as dead, should be restarted */
75 PROC_STATE_DISABLED
/* proc disabled as it resulted in an error */
80 /* list of processes handling this extension
81 * sorted by lowest load
83 * whenever a job is done move it up in the list
84 * until it is sorted, move it down as soon as the
88 scgi_proc
*unused_procs
;
91 * spawn at least min_procs, at max_procs.
93 * as soon as the load of the first entry
94 * is max_load_per_proc we spawn a new one
95 * and add it to the first entry and give it
100 unsigned short min_procs
;
101 unsigned short max_procs
;
102 size_t num_procs
; /* how many procs are started */
103 size_t active_procs
; /* how many of them are really running */
105 unsigned short max_load_per_proc
;
108 * kick the process from the list if it was not
109 * used for idle_timeout until min_procs is
110 * reached. this helps to get the processlist
111 * small again we had a small peak load.
115 unsigned short idle_timeout
;
118 * time after a disabled remote connection is tried to be re-enabled
123 unsigned short disable_time
;
126 * same scgi processes get a little bit larger
127 * than wanted. max_requests_per_proc kills a
128 * process after a number of handled requests.
131 size_t max_requests_per_proc
;
139 * if host is one of the local IP adresses the
140 * whole connection is local
142 * if tcp/ip should be used host AND port have
153 * instead of TCP/IP we can use Unix Domain Sockets
154 * - more secure (you have fileperms to play with)
155 * - more control (on locally)
156 * - more speed (no extra overhead)
160 /* if socket is local we can start the scgi
163 * bin-path is the path to the binary
165 * check min_procs and max_procs for the number
166 * of process to start-up
170 /* bin-path is set bin-environment is taken to
171 * create the environement before starting the
180 * docroot-translation between URL->phys and the
184 * - different dir-layout if remote
191 * check_local tell you if the phys file is stat()ed
192 * or not. FastCGI doesn't care if the service is
193 * remote. If the web-server side doesn't contain
194 * the scgi-files we should not stat() for them
195 * and say '404 not found'.
197 unsigned short check_local
;
200 * append PATH_INFO to SCRIPT_FILENAME
202 * php needs this if cgi.fix_pathinfo is provied
207 * workaround for program when prefix="/"
209 * rule to build PATH_INFO is hardcoded for when check_local is disabled
210 * enable this option to use the workaround
214 unsigned short fix_root_path_name
;
217 * If the backend includes X-Sendfile in the response
218 * we use the value as filename and ignore the content.
221 unsigned short xsendfile_allow
;
222 array
*xsendfile_docroot
;
224 ssize_t load
; /* replace by host->load */
226 size_t max_id
; /* corresponds most of the time to
229 only if a process is killed max_id waits for the process itself
230 to die and decrements its afterwards */
234 } scgi_extension_host
;
237 * one extension can have multiple hosts assigned
238 * one host can spawn additional processes on the same
239 * socket (if we control it)
241 * ext -> host -> procs
244 * if the scgi process is remote that whole goes down
247 * ext -> host -> procs
250 * in case of PHP and FCGI_CHILDREN we have again a procs
251 * but we don't control it directly.
256 buffer
*key
; /* like .php */
259 scgi_extension_host
**hosts
;
266 scgi_extension
**exts
;
272 enum { LI_PROTOCOL_SCGI
, LI_PROTOCOL_UWSGI
};
288 /* generic plugin data, shared between all connections */
295 buffer
*parse_response
;
297 plugin_config
**config_storage
;
299 plugin_config conf
; /* this is only used as long as no handler_ctx is setup */
302 /* connection specific data */
303 typedef enum { FCGI_STATE_INIT
, FCGI_STATE_CONNECT
, FCGI_STATE_PREPARE_WRITE
,
304 FCGI_STATE_WRITE
, FCGI_STATE_READ
305 } scgi_connection_state_t
;
311 scgi_extension_host
*host
;
313 scgi_connection_state_t state
;
314 time_t state_timestamp
;
319 buffer
*response_header
;
321 int fd
; /* fd to the scgi process */
322 int fde_ndx
; /* index into the fd-event buffer */
326 int reconnects
; /* number of reconnect attempts */
330 connection
*remote_conn
; /* dumb pointer */
331 plugin_data
*plugin_data
; /* dumb pointer */
336 /* ok, we need a prototype */
337 static handler_t
scgi_handle_fdevent(server
*srv
, void *ctx
, int revents
);
339 int scgi_proclist_sort_down(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
);
341 static void reset_signals(void) {
343 signal(SIGTTOU
, SIG_DFL
);
346 signal(SIGTTIN
, SIG_DFL
);
349 signal(SIGTSTP
, SIG_DFL
);
351 signal(SIGHUP
, SIG_DFL
);
352 signal(SIGPIPE
, SIG_DFL
);
353 signal(SIGUSR1
, SIG_DFL
);
356 static handler_ctx
* handler_ctx_init(void) {
359 hctx
= calloc(1, sizeof(*hctx
));
364 hctx
->response
= buffer_init();
365 hctx
->response_header
= buffer_init();
367 hctx
->state
= FCGI_STATE_INIT
;
372 hctx
->reconnects
= 0;
374 hctx
->wb
= chunkqueue_init();
380 static void handler_ctx_free(handler_ctx
*hctx
) {
381 buffer_free(hctx
->response
);
382 buffer_free(hctx
->response_header
);
384 chunkqueue_free(hctx
->wb
);
389 static scgi_proc
*scgi_process_init(void) {
392 f
= calloc(1, sizeof(*f
));
394 f
->socket
= buffer_init();
402 static void scgi_process_free(scgi_proc
*f
) {
405 scgi_process_free(f
->next
);
407 buffer_free(f
->socket
);
412 static scgi_extension_host
*scgi_host_init(void) {
413 scgi_extension_host
*f
;
415 f
= calloc(1, sizeof(*f
));
417 f
->host
= buffer_init();
418 f
->unixsocket
= buffer_init();
419 f
->docroot
= buffer_init();
420 f
->bin_path
= buffer_init();
421 f
->bin_env
= array_init();
422 f
->bin_env_copy
= array_init();
423 f
->xsendfile_docroot
= array_init();
428 static void scgi_host_free(scgi_extension_host
*h
) {
435 buffer_free(h
->host
);
436 buffer_free(h
->unixsocket
);
437 buffer_free(h
->docroot
);
438 buffer_free(h
->bin_path
);
439 array_free(h
->bin_env
);
440 array_free(h
->bin_env_copy
);
441 array_free(h
->xsendfile_docroot
);
443 scgi_process_free(h
->first
);
444 scgi_process_free(h
->unused_procs
);
450 static scgi_exts
*scgi_extensions_init(void) {
453 f
= calloc(1, sizeof(*f
));
459 static void scgi_extensions_free(scgi_exts
*f
) {
464 for (i
= 0; i
< f
->used
; i
++) {
470 for (j
= 0; j
< fe
->used
; j
++) {
471 scgi_extension_host
*h
;
478 buffer_free(fe
->key
);
489 static int scgi_extension_insert(scgi_exts
*ext
, buffer
*key
, scgi_extension_host
*fh
) {
493 /* there is something */
495 for (i
= 0; i
< ext
->used
; i
++) {
496 if (buffer_is_equal(key
, ext
->exts
[i
]->key
)) {
501 if (i
== ext
->used
) {
502 /* filextension is new */
503 fe
= calloc(1, sizeof(*fe
));
505 fe
->key
= buffer_init();
506 buffer_copy_buffer(fe
->key
, key
);
510 if (ext
->size
== 0) {
512 ext
->exts
= malloc(ext
->size
* sizeof(*(ext
->exts
)));
513 force_assert(ext
->exts
);
514 } else if (ext
->used
== ext
->size
) {
516 ext
->exts
= realloc(ext
->exts
, ext
->size
* sizeof(*(ext
->exts
)));
517 force_assert(ext
->exts
);
519 ext
->exts
[ext
->used
++] = fe
;
526 fe
->hosts
= malloc(fe
->size
* sizeof(*(fe
->hosts
)));
527 force_assert(fe
->hosts
);
528 } else if (fe
->size
== fe
->used
) {
530 fe
->hosts
= realloc(fe
->hosts
, fe
->size
* sizeof(*(fe
->hosts
)));
531 force_assert(fe
->hosts
);
534 fe
->hosts
[fe
->used
++] = fh
;
540 INIT_FUNC(mod_scgi_init
) {
543 p
= calloc(1, sizeof(*p
));
546 p
->scgi_env
= buffer_init();
548 p
->path
= buffer_init();
549 p
->parse_response
= buffer_init();
555 FREE_FUNC(mod_scgi_free
) {
556 plugin_data
*p
= p_d
;
560 buffer_free(p
->scgi_env
);
561 buffer_free(p
->path
);
562 buffer_free(p
->parse_response
);
564 if (p
->config_storage
) {
566 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
567 plugin_config
*s
= p
->config_storage
[i
];
570 if (NULL
== s
) continue;
574 for (j
= 0; j
< exts
->used
; j
++) {
579 for (n
= 0; n
< ex
->used
; n
++) {
581 scgi_extension_host
*host
;
585 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
586 if (proc
->pid
!= 0) kill(proc
->pid
, SIGTERM
);
588 if (proc
->is_local
&&
589 !buffer_string_is_empty(proc
->socket
)) {
590 unlink(proc
->socket
->ptr
);
594 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
595 if (proc
->pid
!= 0) kill(proc
->pid
, SIGTERM
);
597 if (proc
->is_local
&&
598 !buffer_string_is_empty(proc
->socket
)) {
599 unlink(proc
->socket
->ptr
);
605 scgi_extensions_free(s
->exts
);
609 free(p
->config_storage
);
614 return HANDLER_GO_ON
;
617 static int env_add(char_array
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
621 if (!key
|| !val
) return -1;
623 dst
= malloc(key_len
+ val_len
+ 3);
625 memcpy(dst
, key
, key_len
);
627 /* add the \0 from the value */
628 memcpy(dst
+ key_len
+ 1, val
, val_len
+ 1);
630 for (i
= 0; i
< env
->used
; i
++) {
631 if (0 == strncmp(dst
, env
->ptr
[i
], key_len
+ 1)) {
632 /* don't care about free as we are in a forked child which is going to exec(...) */
633 /* free(env->ptr[i]); */
639 if (env
->size
== 0) {
641 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
642 force_assert(env
->ptr
);
643 } else if (env
->size
== env
->used
) {
645 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
646 force_assert(env
->ptr
);
649 env
->ptr
[env
->used
++] = dst
;
654 #if !defined(HAVE_FORK)
655 static int scgi_spawn_connection(server
*srv
,
657 scgi_extension_host
*host
,
666 #else /* -> defined(HAVE_FORK) */
668 static int scgi_spawn_connection(server
*srv
,
670 scgi_extension_host
*host
,
674 struct timeval tv
= { 0, 100 * 1000 };
676 struct sockaddr_un scgi_addr_un
;
678 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
679 struct sockaddr_in6 scgi_addr_in6
;
681 struct sockaddr_in scgi_addr_in
;
682 struct sockaddr
*scgi_addr
;
687 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
688 "new proc, socket:", proc
->port
, proc
->socket
);
692 if (!buffer_string_is_empty(proc
->socket
)) {
694 memset(&scgi_addr_un
, 0, sizeof(scgi_addr_un
));
695 scgi_addr_un
.sun_family
= AF_UNIX
;
696 if (buffer_string_length(proc
->socket
) + 1 > sizeof(scgi_addr_un
.sun_path
)) {
697 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
698 "ERROR: Unix Domain socket filename too long:",
702 memcpy(scgi_addr_un
.sun_path
, proc
->socket
->ptr
, buffer_string_length(proc
->socket
) + 1);
705 servlen
= SUN_LEN(&scgi_addr_un
);
708 servlen
= buffer_string_length(proc
->socket
) + 1 + sizeof(scgi_addr_un
.sun_family
);
710 scgi_addr
= (struct sockaddr
*) &scgi_addr_un
;
712 log_error_write(srv
, __FILE__
, __LINE__
, "s",
713 "ERROR: Unix Domain sockets are not supported.");
716 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
717 } else if (host
->family
== AF_INET6
&& !buffer_string_is_empty(host
->host
)) {
718 memset(&scgi_addr_in6
, 0, sizeof(scgi_addr_in6
));
719 scgi_addr_in6
.sin6_family
= AF_INET6
;
720 inet_pton(AF_INET6
, host
->host
->ptr
, (char *) &scgi_addr_in6
.sin6_addr
);
721 scgi_addr_in6
.sin6_port
= htons(proc
->port
);
722 servlen
= sizeof(scgi_addr_in6
);
723 scgi_addr
= (struct sockaddr
*) &scgi_addr_in6
;
726 memset(&scgi_addr_in
, 0, sizeof(scgi_addr_in
));
727 scgi_addr_in
.sin_family
= AF_INET
;
729 if (buffer_string_is_empty(host
->host
)) {
730 scgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
734 /* set a usefull default */
735 scgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
738 if (NULL
== (he
= gethostbyname(host
->host
->ptr
))) {
739 log_error_write(srv
, __FILE__
, __LINE__
,
740 "sdb", "gethostbyname failed: ",
741 h_errno
, host
->host
);
745 if (he
->h_addrtype
!= AF_INET
) {
746 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-type != AF_INET: ", he
->h_addrtype
);
750 if (he
->h_length
!= sizeof(struct in_addr
)) {
751 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-length != sizeof(in_addr): ", he
->h_length
);
755 memcpy(&(scgi_addr_in
.sin_addr
.s_addr
), he
->h_addr_list
[0], he
->h_length
);
758 scgi_addr_in
.sin_port
= htons(proc
->port
);
759 servlen
= sizeof(scgi_addr_in
);
761 scgi_addr
= (struct sockaddr
*) &scgi_addr_in
;
764 if (-1 == (scgi_fd
= fdevent_socket_cloexec(scgi_addr
->sa_family
, SOCK_STREAM
, 0))) {
765 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
766 "failed:", strerror(errno
));
770 if (-1 == connect(scgi_fd
, scgi_addr
, servlen
)) {
771 /* server is not up, spawn in */
775 if (!buffer_string_is_empty(proc
->socket
)) {
776 unlink(proc
->socket
->ptr
);
782 if (-1 == (scgi_fd
= fdevent_socket_cloexec(scgi_addr
->sa_family
, SOCK_STREAM
, 0))) {
783 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
784 "socket failed:", strerror(errno
));
789 if (setsockopt(scgi_fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
)) < 0) {
790 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
791 "socketsockopt failed:", strerror(errno
));
797 if (-1 == bind(scgi_fd
, scgi_addr
, servlen
)) {
798 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
807 if (-1 == listen(scgi_fd
, host
->listen_backlog
)) {
808 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
809 "listen failed:", strerror(errno
));
814 switch ((child
= fork())) {
822 /* create environment */
833 (void)fcntl(scgi_fd
, F_SETFD
, 0); /* clear cloexec */
836 /* we don't need the client socket */
837 for (fd
= 3; fd
< 256; fd
++) {
841 /* build clean environment */
842 if (host
->bin_env_copy
->used
) {
843 for (i
= 0; i
< host
->bin_env_copy
->used
; i
++) {
844 data_string
*ds
= (data_string
*)host
->bin_env_copy
->data
[i
];
847 if (NULL
!= (ge
= getenv(ds
->value
->ptr
))) {
848 env_add(&env
, CONST_BUF_LEN(ds
->value
), ge
, strlen(ge
));
852 char ** const e
= environ
;
853 for (i
= 0; e
[i
]; ++i
) {
856 if (NULL
!= (eq
= strchr(e
[i
], '='))) {
857 env_add(&env
, e
[i
], eq
- e
[i
], eq
+1, strlen(eq
+1));
862 /* create environment */
863 for (i
= 0; i
< host
->bin_env
->used
; i
++) {
864 data_string
*ds
= (data_string
*)host
->bin_env
->data
[i
];
866 env_add(&env
, CONST_BUF_LEN(ds
->key
), CONST_BUF_LEN(ds
->value
));
869 for (i
= 0; i
< env
.used
; i
++) {
870 /* search for PHP_FCGI_CHILDREN */
871 if (0 == strncmp(env
.ptr
[i
], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
874 /* not found, add a default */
876 env_add(&env
, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
879 env
.ptr
[env
.used
] = NULL
;
882 buffer_copy_string_len(b
, CONST_STR_LEN("exec "));
883 buffer_append_string_buffer(b
, host
->bin_path
);
888 execle("/bin/sh", "sh", "-c", b
->ptr
, (char *)NULL
, env
.ptr
);
890 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
891 "execl failed for:", host
->bin_path
, strerror(errno
));
906 select(0, NULL
, NULL
, NULL
, &tv
);
908 switch (waitpid(child
, &status
, WNOHANG
)) {
910 /* child still running after timeout, good */
913 /* no PID found ? should never happen */
914 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
915 "pid not found:", strerror(errno
));
918 /* the child should not terminate at all */
919 if (WIFEXITED(status
)) {
920 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
921 "child exited (is this a SCGI binary ?):",
922 WEXITSTATUS(status
));
923 } else if (WIFSIGNALED(status
)) {
924 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
928 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
929 "child died somehow:",
935 /* register process */
937 proc
->last_used
= srv
->cur_ts
;
949 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
950 "(debug) socket is already used, won't spawn:",
955 proc
->state
= PROC_STATE_RUNNING
;
956 host
->active_procs
++;
961 #endif /* HAVE_FORK */
963 static scgi_extension_host
* unixsocket_is_dup(plugin_data
*p
, size_t used
, buffer
*unixsocket
) {
965 for (i
= 0; i
< used
; ++i
) {
966 scgi_exts
*exts
= p
->config_storage
[i
]->exts
;
967 for (j
= 0; j
< exts
->used
; ++j
) {
968 scgi_extension
*ex
= exts
->exts
[j
];
969 for (n
= 0; n
< ex
->used
; ++n
) {
970 scgi_extension_host
*host
= ex
->hosts
[n
];
971 if (!buffer_string_is_empty(host
->unixsocket
)
972 && buffer_is_equal(host
->unixsocket
, unixsocket
)
973 && !buffer_string_is_empty(host
->bin_path
))
982 SETDEFAULTS_FUNC(mod_scgi_set_defaults
) {
983 plugin_data
*p
= p_d
;
986 scgi_extension_host
*df
= NULL
;
988 config_values_t cv
[] = {
989 { "scgi.server", NULL
, T_CONFIG_LOCAL
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
990 { "scgi.debug", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
991 { "scgi.protocol", NULL
, T_CONFIG_LOCAL
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
992 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
995 p
->config_storage
= calloc(1, srv
->config_context
->used
* sizeof(plugin_config
*));
996 force_assert(p
->config_storage
);
998 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
999 data_config
const* config
= (data_config
const*)srv
->config_context
->data
[i
];
1002 s
= malloc(sizeof(plugin_config
));
1004 s
->exts
= scgi_extensions_init();
1006 s
->proto
= LI_PROTOCOL_SCGI
;
1008 cv
[0].destination
= s
->exts
;
1009 cv
[1].destination
= &(s
->debug
);
1010 cv
[2].destination
= NULL
; /* T_CONFIG_LOCAL */
1012 p
->config_storage
[i
] = s
;
1014 if (0 != config_insert_values_global(srv
, config
->value
, cv
, i
== 0 ? T_CONFIG_SCOPE_SERVER
: T_CONFIG_SCOPE_CONNECTION
)) {
1022 if (NULL
!= (du
= array_get_element(config
->value
, "scgi.protocol"))) {
1023 data_string
*ds
= (data_string
*)du
;
1024 if (du
->type
== TYPE_STRING
1025 && buffer_is_equal_string(ds
->value
, CONST_STR_LEN("scgi"))) {
1026 s
->proto
= LI_PROTOCOL_SCGI
;
1027 } else if (du
->type
== TYPE_STRING
1028 && buffer_is_equal_string(ds
->value
, CONST_STR_LEN("uwsgi"))) {
1029 s
->proto
= LI_PROTOCOL_UWSGI
;
1031 log_error_write(srv
, __FILE__
, __LINE__
, "sss",
1032 "unexpected type for key: ", "scgi.protocol", "expected \"scgi\" or \"uwsgi\"");
1038 if (NULL
!= (du
= array_get_element(config
->value
, "scgi.server"))) {
1040 data_array
*da
= (data_array
*)du
;
1042 if (du
->type
!= TYPE_ARRAY
) {
1043 log_error_write(srv
, __FILE__
, __LINE__
, "sss",
1044 "unexpected type for key: ", "scgi.server", "expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1051 * scgi.server = ( "<ext>" => ( ... ),
1052 * "<ext>" => ( ... ) )
1055 for (j
= 0; j
< da
->value
->used
; j
++) {
1057 data_array
*da_ext
= (data_array
*)da
->value
->data
[j
];
1059 if (da
->value
->data
[j
]->type
!= TYPE_ARRAY
) {
1060 log_error_write(srv
, __FILE__
, __LINE__
, "sssbs",
1061 "unexpected type for key: ", "scgi.server",
1062 "[", da
->value
->data
[j
]->key
, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1068 * da_ext->key == name of the extension
1072 * scgi.server = ( "<ext>" =>
1073 * ( "<host>" => ( ... ),
1074 * "<host>" => ( ... )
1079 for (n
= 0; n
< da_ext
->value
->used
; n
++) {
1080 data_array
*da_host
= (data_array
*)da_ext
->value
->data
[n
];
1082 config_values_t fcv
[] = {
1083 { "host", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
1084 { "docroot", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
1085 { "socket", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
1086 { "bin-path", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 3 */
1088 { "check-local", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 4 */
1089 { "port", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 5 */
1090 { "min-procs-not-working", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 this is broken for now */
1091 { "max-procs", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 */
1092 { "max-load-per-proc", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 8 */
1093 { "idle-timeout", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 9 */
1094 { "disable-time", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 10 */
1096 { "bin-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 11 */
1097 { "bin-copy-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 12 */
1098 { "fix-root-scriptname", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 13 */
1099 { "listen-backlog", NULL
, T_CONFIG_INT
, T_CONFIG_SCOPE_CONNECTION
}, /* 14 */
1100 { "x-sendfile", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 15 */
1101 { "x-sendfile-docroot",NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 16 */
1104 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
1107 if (da_host
->type
!= TYPE_ARRAY
) {
1108 log_error_write(srv
, __FILE__
, __LINE__
, "ssSBS",
1109 "unexpected type for key:",
1111 "[", da_host
->key
, "](string); expected ( \"ext\" => ( \"backend-label\" => ( \"key\" => \"value\" )))");
1116 df
= scgi_host_init();
1118 df
->check_local
= 1;
1121 df
->max_load_per_proc
= 1;
1122 df
->idle_timeout
= 60;
1123 df
->disable_time
= 60;
1124 df
->fix_root_path_name
= 0;
1125 df
->listen_backlog
= 1024;
1126 df
->xsendfile_allow
= 0;
1129 fcv
[0].destination
= df
->host
;
1130 fcv
[1].destination
= df
->docroot
;
1131 fcv
[2].destination
= df
->unixsocket
;
1132 fcv
[3].destination
= df
->bin_path
;
1134 fcv
[4].destination
= &(df
->check_local
);
1135 fcv
[5].destination
= &(df
->port
);
1136 fcv
[6].destination
= &(df
->min_procs
);
1137 fcv
[7].destination
= &(df
->max_procs
);
1138 fcv
[8].destination
= &(df
->max_load_per_proc
);
1139 fcv
[9].destination
= &(df
->idle_timeout
);
1140 fcv
[10].destination
= &(df
->disable_time
);
1142 fcv
[11].destination
= df
->bin_env
;
1143 fcv
[12].destination
= df
->bin_env_copy
;
1144 fcv
[13].destination
= &(df
->fix_root_path_name
);
1145 fcv
[14].destination
= &(df
->listen_backlog
);
1146 fcv
[15].destination
= &(df
->xsendfile_allow
);
1147 fcv
[16].destination
= df
->xsendfile_docroot
;
1150 if (0 != config_insert_values_internal(srv
, da_host
->value
, fcv
, T_CONFIG_SCOPE_CONNECTION
)) {
1154 if ((!buffer_string_is_empty(df
->host
) || df
->port
) &&
1155 !buffer_string_is_empty(df
->unixsocket
)) {
1156 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1157 "either host+port or socket");
1162 if (!buffer_string_is_empty(df
->unixsocket
)) {
1163 /* unix domain socket */
1164 struct sockaddr_un un
;
1166 if (buffer_string_length(df
->unixsocket
) + 1 > sizeof(un
.sun_path
) - 2) {
1167 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1168 "path of the unixdomain socket is too large");
1172 if (!buffer_string_is_empty(df
->bin_path
)) {
1173 scgi_extension_host
*duplicate
= unixsocket_is_dup(p
, i
+1, df
->unixsocket
);
1174 if (NULL
!= duplicate
) {
1175 if (!buffer_is_equal(df
->bin_path
, duplicate
->bin_path
)) {
1176 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1177 "duplicate unixsocket path:",
1187 df
->family
= AF_UNIX
;
1191 if (buffer_string_is_empty(df
->host
) &&
1192 buffer_string_is_empty(df
->bin_path
)) {
1193 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbs",
1194 "missing key (string):",
1201 } else if (df
->port
== 0) {
1202 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbs",
1203 "missing key (short):",
1211 df
->family
= (!buffer_string_is_empty(df
->host
) && NULL
!= strchr(df
->host
->ptr
, ':')) ? AF_INET6
: AF_INET
;
1215 /* already init'd; skip spawning */
1216 } else if (!buffer_string_is_empty(df
->bin_path
)) {
1217 /* a local socket + self spawning */
1220 /* HACK: just to make sure the adaptive spawing is disabled */
1221 df
->min_procs
= df
->max_procs
;
1223 if (df
->min_procs
> df
->max_procs
) df
->max_procs
= df
->min_procs
;
1224 if (df
->max_load_per_proc
< 1) df
->max_load_per_proc
= 0;
1227 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsbsdsd",
1228 "--- scgi spawning local",
1229 "\n\tproc:", df
->bin_path
,
1230 "\n\tport:", df
->port
,
1231 "\n\tsocket", df
->unixsocket
,
1232 "\n\tmin-procs:", df
->min_procs
,
1233 "\n\tmax-procs:", df
->max_procs
);
1236 for (pno
= 0; pno
< df
->min_procs
; pno
++) {
1239 proc
= scgi_process_init();
1240 proc
->id
= df
->num_procs
++;
1243 if (buffer_string_is_empty(df
->unixsocket
)) {
1244 proc
->port
= df
->port
+ pno
;
1246 buffer_copy_buffer(proc
->socket
, df
->unixsocket
);
1247 buffer_append_string_len(proc
->socket
, CONST_STR_LEN("-"));
1248 buffer_append_int(proc
->socket
, pno
);
1252 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
1253 "--- scgi spawning",
1254 "\n\tport:", df
->port
,
1255 "\n\tsocket", df
->unixsocket
,
1256 "\n\tcurrent:", pno
, "/", df
->min_procs
);
1259 if (!srv
->srvconf
.preflight_check
1260 && scgi_spawn_connection(srv
, p
, df
, proc
)) {
1261 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1262 "[ERROR]: spawning fcgi failed.");
1263 scgi_process_free(proc
);
1267 proc
->next
= df
->first
;
1268 if (df
->first
) df
->first
->prev
= proc
;
1275 fp
= scgi_process_init();
1276 fp
->id
= df
->num_procs
++;
1279 fp
->state
= PROC_STATE_RUNNING
;
1281 if (buffer_string_is_empty(df
->unixsocket
)) {
1282 fp
->port
= df
->port
;
1284 buffer_copy_buffer(fp
->socket
, df
->unixsocket
);
1293 if (df
->xsendfile_docroot
->used
) {
1295 for (k
= 0; k
< df
->xsendfile_docroot
->used
; ++k
) {
1296 data_string
*ds
= (data_string
*)df
->xsendfile_docroot
->data
[k
];
1297 if (ds
->type
!= TYPE_STRING
) {
1298 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1299 "unexpected type for x-sendfile-docroot; expected: \"x-sendfile-docroot\" => ( \"/allowed/path\", ... )");
1302 if (ds
->value
->ptr
[0] != '/') {
1303 log_error_write(srv
, __FILE__
, __LINE__
, "SBs",
1304 "x-sendfile-docroot paths must begin with '/'; invalid: \"", ds
->value
, "\"");
1307 buffer_path_simplify(ds
->value
, ds
->value
);
1308 buffer_append_slash(ds
->value
);
1312 /* if extension already exists, take it */
1313 scgi_extension_insert(s
->exts
, da_ext
->key
, df
);
1320 return HANDLER_GO_ON
;
1323 if (NULL
!= df
) scgi_host_free(df
);
1324 return HANDLER_ERROR
;
1327 static int scgi_set_state(server
*srv
, handler_ctx
*hctx
, scgi_connection_state_t state
) {
1328 hctx
->state
= state
;
1329 hctx
->state_timestamp
= srv
->cur_ts
;
1335 static void scgi_backend_close(server
*srv
, handler_ctx
*hctx
) {
1336 if (hctx
->fd
!= -1) {
1337 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1338 fdevent_unregister(srv
->ev
, hctx
->fd
);
1339 fdevent_sched_close(srv
->ev
, hctx
->fd
, 1);
1346 /* after the connect the process gets a load */
1347 if (hctx
->got_proc
) hctx
->proc
->load
--;
1348 scgi_proclist_sort_down(srv
, hctx
->host
, hctx
->proc
);
1350 if (hctx
->conf
.debug
) {
1351 log_error_write(srv
, __FILE__
, __LINE__
, "sddb",
1354 hctx
->proc
->pid
, hctx
->proc
->socket
);
1363 static scgi_extension_host
* scgi_extension_host_get(server
*srv
, connection
*con
, plugin_data
*p
, scgi_extension
*extension
) {
1365 scgi_extension_host
*host
= NULL
;
1368 /* get best server */
1369 for (size_t k
= 0; k
< extension
->used
; ++k
) {
1370 scgi_extension_host
*h
= extension
->hosts
[k
];
1372 /* we should have at least one proc that can do something */
1373 if (h
->active_procs
== 0) {
1377 if (used
== -1 || h
->load
< used
) {
1385 /* sorry, we don't have a server alive for this ext */
1386 con
->http_status
= 503; /* Service Unavailable */
1389 /* only send the 'no handler' once */
1390 if (!extension
->note_is_sent
) {
1391 extension
->note_is_sent
= 1;
1393 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbs",
1394 "all handlers for ", con
->uri
.path
,
1395 "on", extension
->key
,
1403 static void scgi_connection_close(server
*srv
, handler_ctx
*hctx
) {
1407 p
= hctx
->plugin_data
;
1408 con
= hctx
->remote_conn
;
1410 scgi_backend_close(srv
, hctx
);
1411 handler_ctx_free(hctx
);
1412 con
->plugin_ctx
[p
->id
] = NULL
;
1414 /* finish response (if not already con->file_started, con->file_finished) */
1415 if (con
->mode
== p
->id
) {
1416 http_response_backend_done(srv
, con
);
1420 static handler_t
scgi_reconnect(server
*srv
, handler_ctx
*hctx
) {
1421 scgi_backend_close(srv
, hctx
);
1423 hctx
->host
= scgi_extension_host_get(srv
, hctx
->remote_conn
, hctx
->plugin_data
, hctx
->ext
);
1424 if (NULL
== hctx
->host
) return HANDLER_FINISHED
;
1427 scgi_set_state(srv
, hctx
, FCGI_STATE_INIT
);
1428 return HANDLER_COMEBACK
;
1432 static handler_t
scgi_connection_reset(server
*srv
, connection
*con
, void *p_d
) {
1433 plugin_data
*p
= p_d
;
1434 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
1435 if (hctx
) scgi_connection_close(srv
, hctx
);
1437 return HANDLER_GO_ON
;
1441 static int scgi_env_add_scgi(void *venv
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
1445 if (!key
|| !val
) return -1;
1447 len
= key_len
+ val_len
+ 2;
1449 buffer_string_prepare_append(env
, len
);
1451 buffer_append_string_len(env
, key
, key_len
);
1452 buffer_append_string_len(env
, "", 1);
1453 buffer_append_string_len(env
, val
, val_len
);
1454 buffer_append_string_len(env
, "", 1);
1460 #ifdef __LITTLE_ENDIAN__
1461 #define uwsgi_htole16(x) (x)
1462 #else /* __BIG_ENDIAN__ */
1463 #define uwsgi_htole16(x) ((uint16_t) (((x) & 0xff) << 8 | ((x) & 0xff00) >> 8))
1467 static int scgi_env_add_uwsgi(void *venv
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
1472 if (!key
|| !val
) return -1;
1473 if (key_len
> USHRT_MAX
|| val_len
> USHRT_MAX
) return -1;
1475 len
= 2 + key_len
+ 2 + val_len
;
1477 buffer_string_prepare_append(env
, len
);
1479 uwlen
= uwsgi_htole16((uint16_t)key_len
);
1480 buffer_append_string_len(env
, (char *)&uwlen
, 2);
1481 buffer_append_string_len(env
, key
, key_len
);
1482 uwlen
= uwsgi_htole16((uint16_t)val_len
);
1483 buffer_append_string_len(env
, (char *)&uwlen
, 2);
1484 buffer_append_string_len(env
, val
, val_len
);
1495 * 1 not connected yet
1498 static int scgi_establish_connection(server
*srv
, handler_ctx
*hctx
) {
1499 struct sockaddr
*scgi_addr
;
1500 struct sockaddr_in scgi_addr_in
;
1501 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1502 struct sockaddr_in6 scgi_addr_in6
;
1504 #ifdef HAVE_SYS_UN_H
1505 struct sockaddr_un scgi_addr_un
;
1509 scgi_extension_host
*host
= hctx
->host
;
1510 scgi_proc
*proc
= hctx
->proc
;
1511 int scgi_fd
= hctx
->fd
;
1513 if (!buffer_string_is_empty(proc
->socket
)) {
1514 #ifdef HAVE_SYS_UN_H
1515 /* use the unix domain socket */
1516 memset(&scgi_addr_un
, 0, sizeof(scgi_addr_un
));
1517 scgi_addr_un
.sun_family
= AF_UNIX
;
1518 if (buffer_string_length(proc
->socket
) + 1 > sizeof(scgi_addr_un
.sun_path
)) {
1519 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
1520 "ERROR: Unix Domain socket filename too long:",
1524 memcpy(scgi_addr_un
.sun_path
, proc
->socket
->ptr
, buffer_string_length(proc
->socket
) + 1);
1527 servlen
= SUN_LEN(&scgi_addr_un
);
1530 servlen
= buffer_string_length(proc
->socket
) + 1 + sizeof(scgi_addr_un
.sun_family
);
1532 scgi_addr
= (struct sockaddr
*) &scgi_addr_un
;
1536 #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
1537 } else if (host
->family
== AF_INET6
&& !buffer_string_is_empty(host
->host
)) {
1538 memset(&scgi_addr_in6
, 0, sizeof(scgi_addr_in6
));
1539 scgi_addr_in6
.sin6_family
= AF_INET6
;
1540 inet_pton(AF_INET6
, host
->host
->ptr
, (char *) &scgi_addr_in6
.sin6_addr
);
1541 scgi_addr_in6
.sin6_port
= htons(proc
->port
);
1542 servlen
= sizeof(scgi_addr_in6
);
1543 scgi_addr
= (struct sockaddr
*) &scgi_addr_in6
;
1546 memset(&scgi_addr_in
, 0, sizeof(scgi_addr_in
));
1547 scgi_addr_in
.sin_family
= AF_INET
;
1548 if (0 == inet_aton(host
->host
->ptr
, &(scgi_addr_in
.sin_addr
))) {
1549 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1550 "converting IP-adress failed for", host
->host
,
1551 "\nBe sure to specify an IP address here");
1555 scgi_addr_in
.sin_port
= htons(proc
->port
);
1556 servlen
= sizeof(scgi_addr_in
);
1558 scgi_addr
= (struct sockaddr
*) &scgi_addr_in
;
1561 if (-1 == connect(scgi_fd
, scgi_addr
, servlen
)) {
1562 if (errno
== EINPROGRESS
||
1563 errno
== EALREADY
||
1565 if (hctx
->conf
.debug
) {
1566 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1567 "connect delayed, will continue later:", scgi_fd
);
1572 log_error_write(srv
, __FILE__
, __LINE__
, "sdsddb",
1573 "connect failed:", scgi_fd
,
1574 strerror(errno
), errno
,
1575 proc
->port
, proc
->socket
);
1577 if (errno
== EAGAIN
) {
1578 /* this is Linux only */
1580 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1581 "If this happend on Linux: You have been run out of local ports. "
1582 "Check the manual, section Performance how to handle this.");
1588 if (hctx
->conf
.debug
> 1) {
1589 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1590 "connect succeeded: ", scgi_fd
);
1599 static int scgi_create_env(server
*srv
, handler_ctx
*hctx
) {
1602 plugin_data
*p
= hctx
->plugin_data
;
1603 scgi_extension_host
*host
= hctx
->host
;
1605 connection
*con
= hctx
->remote_conn
;
1607 http_cgi_opts opts
= { 0, 0, host
->docroot
, NULL
};
1609 http_cgi_header_append_cb scgi_env_add
= p
->conf
.proto
== LI_PROTOCOL_SCGI
1611 : scgi_env_add_uwsgi
;
1613 buffer_string_prepare_copy(p
->scgi_env
, 1023);
1615 if (0 != http_cgi_headers(srv
, con
, &opts
, scgi_env_add
, p
->scgi_env
)) {
1616 con
->http_status
= 400;
1620 if (p
->conf
.proto
== LI_PROTOCOL_SCGI
) {
1621 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCGI"), CONST_STR_LEN("1"));
1623 buffer_append_int(b
, buffer_string_length(p
->scgi_env
));
1624 buffer_append_string_len(b
, CONST_STR_LEN(":"));
1625 buffer_append_string_buffer(b
, p
->scgi_env
);
1626 buffer_append_string_len(b
, CONST_STR_LEN(","));
1627 } else { /* LI_PROTOCOL_UWSGI */
1628 /* http://uwsgi-docs.readthedocs.io/en/latest/Protocol.html */
1629 size_t len
= buffer_string_length(p
->scgi_env
);
1630 uint32_t uwsgi_header
;
1631 if (len
> USHRT_MAX
) {
1632 con
->http_status
= 431; /* Request Header Fields Too Large */
1634 return -1; /* trigger return of HANDLER_FINISHED */
1637 buffer_string_prepare_copy(b
, 4 + len
);
1638 uwsgi_header
= ((uint32_t)uwsgi_htole16((uint16_t)len
)) << 8;
1639 memcpy(b
->ptr
, (char *)&uwsgi_header
, 4);
1640 buffer_commit(b
, 4);
1641 buffer_append_string_buffer(b
, p
->scgi_env
);
1644 hctx
->wb_reqlen
= buffer_string_length(b
);
1645 chunkqueue_append_buffer(hctx
->wb
, b
);
1648 if (con
->request
.content_length
) {
1649 chunkqueue_append_chunkqueue(hctx
->wb
, con
->request_content_queue
);
1650 hctx
->wb_reqlen
+= con
->request
.content_length
;/* (eventual) total request size */
1656 static int scgi_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
, int eol
) {
1663 buffer_copy_buffer(p
->parse_response
, in
);
1665 for (s
= p
->parse_response
->ptr
;
1666 NULL
!= (ns
= (eol
== EOL_RN
? strstr(s
, "\r\n") : strchr(s
, '\n')));
1667 s
= ns
+ (eol
== EOL_RN
? 2 : 1), line
++) {
1668 const char *key
, *value
;
1675 0 == strncmp(s
, "HTTP/1.", 7)) {
1676 /* non-parsed header ... we parse them anyway */
1682 /* after the space should be a status code for us */
1684 status
= strtol(s
+9, NULL
, 10);
1686 if (status
>= 100 && status
< 1000) {
1687 /* we expected 3 digits got them */
1688 con
->parsed_response
|= HTTP_STATUS
;
1689 con
->http_status
= status
;
1695 if (NULL
== (value
= strchr(s
, ':'))) {
1696 /* we expect: "<key>: <value>\r\n" */
1700 key_len
= value
- key
;
1704 while (*value
== ' ' || *value
== '\t') value
++;
1706 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
1707 ds
= data_response_init();
1709 buffer_copy_string_len(ds
->key
, key
, key_len
);
1710 buffer_copy_string(ds
->value
, value
);
1712 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
1716 if (0 == strncasecmp(key
, "Date", key_len
)) {
1717 con
->parsed_response
|= HTTP_DATE
;
1721 if (0 == strncasecmp(key
, "Status", key_len
)) {
1722 int status
= strtol(value
, NULL
, 10);
1723 if (status
>= 100 && status
< 1000) {
1724 con
->http_status
= status
;
1725 con
->parsed_response
|= HTTP_STATUS
;
1727 con
->http_status
= 502;
1732 if (0 == strncasecmp(key
, "Location", key_len
)) {
1733 con
->parsed_response
|= HTTP_LOCATION
;
1737 if (0 == strncasecmp(key
, "Connection", key_len
)) {
1738 con
->response
.keep_alive
= (0 == strcasecmp(value
, "Keep-Alive")) ? 1 : 0;
1739 con
->parsed_response
|= HTTP_CONNECTION
;
1743 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
1744 con
->response
.content_length
= strtoul(value
, NULL
, 10);
1745 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
1754 /* CGI/1.1 rev 03 - 7.2.1.2 */
1755 if ((con
->parsed_response
& HTTP_LOCATION
) &&
1756 !(con
->parsed_response
& HTTP_STATUS
)) {
1757 con
->http_status
= 302;
1764 static int scgi_demux_response(server
*srv
, handler_ctx
*hctx
) {
1765 plugin_data
*p
= hctx
->plugin_data
;
1766 connection
*con
= hctx
->remote_conn
;
1771 buffer_string_prepare_copy(hctx
->response
, 1023);
1772 if (-1 == (n
= read(hctx
->fd
, hctx
->response
->ptr
, hctx
->response
->size
- 1))) {
1773 if (errno
== EAGAIN
|| errno
== EINTR
) {
1774 /* would block, wait for signal */
1775 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
1779 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", strerror(errno
), con
->fd
, hctx
->fd
);
1788 buffer_commit(hctx
->response
, n
);
1790 /* split header from body */
1792 if (con
->file_started
== 0) {
1796 int cp
, eol
= EOL_UNSET
;
1800 buffer_append_string_buffer(hctx
->response_header
, hctx
->response
);
1802 /* nph (non-parsed headers) */
1803 if (0 == strncmp(hctx
->response_header
->ptr
, "HTTP/1.", 7)) in_header
= 1;
1805 /* search for the \r\n\r\n or \n\n in the string */
1806 for (c
= hctx
->response_header
->ptr
, cp
= 0, used
= buffer_string_length(hctx
->response_header
); used
; c
++, cp
++, used
--) {
1807 if (*c
== ':') in_header
= 1;
1808 else if (*c
== '\n') {
1809 if (in_header
== 0) {
1810 /* got a response without a response header */
1817 if (eol
== EOL_UNSET
) eol
= EOL_N
;
1819 if (*(c
+1) == '\n') {
1825 } else if (used
> 1 && *c
== '\r' && *(c
+1) == '\n') {
1826 if (in_header
== 0) {
1827 /* got a response without a response header */
1834 if (eol
== EOL_UNSET
) eol
= EOL_RN
;
1853 /* no header, but a body */
1854 if (0 != http_chunk_append_buffer(srv
, con
, hctx
->response_header
)) {
1855 /* error writing to tempfile;
1856 * truncate response or send 500 if nothing sent yet */
1860 size_t blen
= buffer_string_length(hctx
->response_header
) - hlen
;
1862 /* a small hack: terminate after at the second \r */
1863 buffer_string_set_length(hctx
->response_header
, hlen
- 1);
1865 /* parse the response header */
1866 scgi_response_parse(srv
, con
, p
, hctx
->response_header
, eol
);
1868 if (hctx
->host
->xsendfile_allow
) {
1870 if (NULL
!= (ds
= (data_string
*) array_get_element(con
->response
.headers
, "X-Sendfile"))) {
1871 http_response_xsendfile(srv
, con
, ds
->value
, hctx
->host
->xsendfile_docroot
);
1877 if (0 != http_chunk_append_mem(srv
, con
, hctx
->response_header
->ptr
+ hlen
, blen
)) {
1878 /* error writing to tempfile;
1879 * truncate response or send 500 if nothing sent yet */
1885 con
->file_started
= 1;
1887 /*(reuse MAX_HTTP_REQUEST_HEADER as max size for response headers from backends)*/
1888 if (buffer_string_length(hctx
->response_header
) > MAX_HTTP_REQUEST_HEADER
) {
1889 log_error_write(srv
, __FILE__
, __LINE__
, "sb", "response headers too large for", con
->uri
.path
);
1890 con
->http_status
= 502; /* Bad Gateway */
1896 if (0 != http_chunk_append_buffer(srv
, con
, hctx
->response
)) {
1897 /* error writing to tempfile;
1898 * truncate response or send 500 if nothing sent yet */
1901 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
1902 && chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
1903 if (!con
->is_writable
) {
1904 /*(defer removal of FDEVENT_IN interest since
1905 * connection_state_machine() might be able to send data
1906 * immediately, unless !con->is_writable, where
1907 * connection_state_machine() might not loop back to call
1908 * mod_scgi_handle_subrequest())*/
1909 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
1916 log_error_write(srv
, __FILE__
, __LINE__
, "ddss", con
->fd
, hctx
->fd
, connection_get_state(con
->state
), b
->ptr
);
1924 static int scgi_proclist_sort_up(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
1929 /* we have been the smallest of the current list
1930 * and we want to insert the node sorted as soon
1940 /* nothing to sort, only one element */
1941 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
1943 for (p
= proc
; p
->next
&& p
->next
->load
< proc
->load
; p
= p
->next
);
1945 /* no need to move something
1953 if (p
== proc
) return 0;
1955 if (host
->first
== proc
) {
1956 /* we have been the first elememt */
1958 host
->first
= proc
->next
;
1959 host
->first
->prev
= NULL
;
1962 /* disconnect proc */
1964 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
1965 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
1967 /* proc should be right of p */
1969 proc
->next
= p
->next
;
1971 if (p
->next
) p
->next
->prev
= proc
;
1974 for(p
= host
->first
; p
; p
= p
->next
) {
1975 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
1985 int scgi_proclist_sort_down(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
1990 /* we have been the smallest of the current list
1991 * and we want to insert the node sorted as soon
2000 * the basic is idea is:
2001 * - the last active scgi process should be still
2002 * in ram and is not swapped out yet
2003 * - processes that are not reused will be killed
2004 * after some time by the trigger-handler
2006 * everything > 0 is hot
2007 * all unused procs are colder the more right they are
2008 * ice-cold processes are propably unused since more
2009 * than 'unused-timeout', are swaped out and won't be
2010 * reused in the next seconds anyway.
2014 /* nothing to sort, only one element */
2015 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
2017 for (p
= host
->first
; p
!= proc
&& p
->load
< proc
->load
; p
= p
->next
);
2020 /* no need to move something
2028 if (p
== proc
) return 0;
2030 /* we have to move left. If we are already the first element
2032 if (host
->first
== proc
) return 0;
2035 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
2036 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
2038 /* proc should be left of p */
2040 proc
->prev
= p
->prev
;
2041 if (p
->prev
) p
->prev
->next
= proc
;
2044 if (proc
->prev
== NULL
) host
->first
= proc
;
2046 for(p
= host
->first
; p
; p
= p
->next
) {
2047 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
2057 static int scgi_restart_dead_procs(server
*srv
, plugin_data
*p
, scgi_extension_host
*host
) {
2060 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2061 if (p
->conf
.debug
) {
2062 log_error_write(srv
, __FILE__
, __LINE__
, "sbdbdddd",
2064 host
->host
, proc
->port
,
2072 if (0 == proc
->is_local
) {
2074 * external servers might get disabled
2076 * enable the server again, perhaps it is back again
2079 if ((proc
->state
== PROC_STATE_DISABLED
) &&
2080 (srv
->cur_ts
- proc
->disable_ts
> host
->disable_time
)) {
2081 proc
->state
= PROC_STATE_RUNNING
;
2082 host
->active_procs
++;
2084 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2085 "fcgi-server re-enabled:",
2086 host
->host
, host
->port
,
2090 /* the child should not terminate at all */
2093 if (proc
->state
== PROC_STATE_DIED_WAIT_FOR_PID
) {
2094 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2096 /* child is still alive */
2101 if (WIFEXITED(status
)) {
2103 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2104 "child exited, pid:", proc
->pid
,
2105 "status:", WEXITSTATUS(status
));
2107 } else if (WIFSIGNALED(status
)) {
2108 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2112 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2113 "child died somehow:",
2117 proc
->state
= PROC_STATE_DIED
;
2123 * local servers might died, but we restart them
2126 if (proc
->state
== PROC_STATE_DIED
&&
2128 /* restart the child */
2130 if (p
->conf
.debug
) {
2131 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2132 "--- scgi spawning",
2133 "\n\tport:", host
->port
,
2134 "\n\tsocket", host
->unixsocket
,
2135 "\n\tcurrent:", 1, "/", host
->min_procs
);
2138 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2139 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2140 "ERROR: spawning fcgi failed.");
2141 return HANDLER_ERROR
;
2144 scgi_proclist_sort_down(srv
, host
, proc
);
2153 static handler_t
scgi_write_request(server
*srv
, handler_ctx
*hctx
) {
2154 scgi_extension_host
*host
= hctx
->host
;
2155 connection
*con
= hctx
->remote_conn
;
2159 switch(hctx
->state
) {
2160 case FCGI_STATE_INIT
:
2161 if (-1 == (hctx
->fd
= fdevent_socket_nb_cloexec(host
->family
, SOCK_STREAM
, 0))) {
2162 if (errno
== EMFILE
||
2164 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2165 "wait for fd at connection:", con
->fd
);
2167 return HANDLER_WAIT_FOR_FD
;
2170 log_error_write(srv
, __FILE__
, __LINE__
, "ssdd",
2171 "socket failed:", strerror(errno
), srv
->cur_fds
, srv
->max_fds
);
2172 return HANDLER_ERROR
;
2178 fdevent_register(srv
->ev
, hctx
->fd
, scgi_handle_fdevent
, hctx
);
2180 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
2181 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2182 "fcntl failed: ", strerror(errno
));
2183 return HANDLER_ERROR
;
2187 case FCGI_STATE_CONNECT
:
2188 if (hctx
->state
== FCGI_STATE_INIT
) {
2189 for (hctx
->proc
= hctx
->host
->first
;
2190 hctx
->proc
&& hctx
->proc
->state
!= PROC_STATE_RUNNING
;
2191 hctx
->proc
= hctx
->proc
->next
);
2193 /* all childs are dead */
2194 if (hctx
->proc
== NULL
) {
2197 return HANDLER_ERROR
;
2200 if (hctx
->proc
->is_local
) {
2201 hctx
->pid
= hctx
->proc
->pid
;
2204 switch (scgi_establish_connection(srv
, hctx
)) {
2206 scgi_set_state(srv
, hctx
, FCGI_STATE_CONNECT
);
2208 /* connection is in progress, wait for an event and call getsockopt() below */
2210 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2212 return HANDLER_WAIT_FOR_EVENT
;
2214 /* if ECONNREFUSED; choose another connection */
2217 return HANDLER_ERROR
;
2219 /* everything is ok, go on */
2226 socklen_t socket_error_len
= sizeof(socket_error
);
2228 /* try to finish the connect() */
2229 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
2230 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2231 "getsockopt failed:", strerror(errno
));
2233 return HANDLER_ERROR
;
2235 if (socket_error
!= 0) {
2236 if (!hctx
->proc
->is_local
|| hctx
->conf
.debug
) {
2237 /* local procs get restarted */
2239 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2240 "establishing connection failed:", strerror(socket_error
),
2241 "port:", hctx
->proc
->port
);
2244 return HANDLER_ERROR
;
2248 /* ok, we have the connection */
2251 hctx
->proc
->last_used
= srv
->cur_ts
;
2254 if (hctx
->conf
.debug
) {
2255 log_error_write(srv
, __FILE__
, __LINE__
, "sddbdd",
2264 /* move the proc-list entry down the list */
2265 scgi_proclist_sort_up(srv
, hctx
->host
, hctx
->proc
);
2267 scgi_set_state(srv
, hctx
, FCGI_STATE_PREPARE_WRITE
);
2269 case FCGI_STATE_PREPARE_WRITE
:
2270 if (0 != scgi_create_env(srv
, hctx
)) {
2271 return HANDLER_FINISHED
;
2274 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2275 scgi_set_state(srv
, hctx
, FCGI_STATE_WRITE
);
2278 case FCGI_STATE_WRITE
:
2279 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
2281 chunkqueue_remove_finished_chunks(hctx
->wb
);
2284 if (errno
== ENOTCONN
|| ret
== -2) {
2285 /* the connection got dropped after accept()
2287 * this is most of the time a PHP which dies
2288 * after PHP_FCGI_MAX_REQUESTS
2291 if (hctx
->wb
->bytes_out
== 0 &&
2292 hctx
->reconnects
++ < 5) {
2293 usleep(10000); /* take away the load of the webserver
2294 * to let the php a chance to restart
2297 return scgi_reconnect(srv
, hctx
);
2300 /* not reconnected ... why
2302 * far@#lighttpd report this for FreeBSD
2306 log_error_write(srv
, __FILE__
, __LINE__
, "ssosd",
2307 "connection was dropped after accept(). reconnect() denied:",
2308 "write-offset:", hctx
->wb
->bytes_out
,
2309 "reconnect attempts:", hctx
->reconnects
);
2311 return HANDLER_ERROR
;
2313 /* -1 == ret => error on our side */
2314 log_error_write(srv
, __FILE__
, __LINE__
, "ssd",
2315 "write failed:", strerror(errno
), errno
);
2317 return HANDLER_ERROR
;
2321 if (hctx
->wb
->bytes_out
== hctx
->wb_reqlen
) {
2322 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2323 scgi_set_state(srv
, hctx
, FCGI_STATE_READ
);
2325 off_t wblen
= hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
;
2326 if (hctx
->wb
->bytes_in
< hctx
->wb_reqlen
&& wblen
< 65536 - 16384) {
2327 /*(con->conf.stream_request_body & FDEVENT_STREAM_REQUEST)*/
2328 if (!(con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_POLLIN
)) {
2329 con
->conf
.stream_request_body
|= FDEVENT_STREAM_REQUEST_POLLIN
;
2330 con
->is_readable
= 1; /* trigger optimistic read from client */
2334 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2336 fdevent_event_add(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2340 return HANDLER_WAIT_FOR_EVENT
;
2341 case FCGI_STATE_READ
:
2342 /* waiting for a response */
2343 return HANDLER_WAIT_FOR_EVENT
;
2345 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
2346 return HANDLER_ERROR
;
2350 static handler_t
scgi_send_request(server
*srv
, handler_ctx
*hctx
) {
2351 /* ok, create the request */
2352 handler_t rc
= scgi_write_request(srv
, hctx
);
2353 if (HANDLER_ERROR
!= rc
) {
2356 scgi_proc
*proc
= hctx
->proc
;
2357 scgi_extension_host
*host
= hctx
->host
;
2358 plugin_data
*p
= hctx
->plugin_data
;
2359 connection
*con
= hctx
->remote_conn
;
2362 0 == proc
->is_local
&&
2363 proc
->state
!= PROC_STATE_DISABLED
) {
2364 /* only disable remote servers as we don't manage them*/
2366 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "fcgi-server disabled:",
2371 /* disable this server */
2372 proc
->disable_ts
= srv
->cur_ts
;
2373 proc
->state
= PROC_STATE_DISABLED
;
2374 host
->active_procs
--;
2377 if (hctx
->state
== FCGI_STATE_INIT
||
2378 hctx
->state
== FCGI_STATE_CONNECT
) {
2379 /* connect() or getsockopt() failed,
2380 * restart the request-handling
2382 if (proc
&& proc
->is_local
) {
2384 if (hctx
->conf
.debug
) {
2385 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "connect() to scgi failed, restarting the request-handling:",
2392 * several hctx might reference the same proc
2394 * Only one of them should mark the proc as dead all the other
2395 * ones should just take a new one.
2397 * If a new proc was started with the old struct this might lead
2398 * the mark a perfect proc as dead otherwise
2401 if (proc
->state
== PROC_STATE_RUNNING
&&
2402 hctx
->pid
== proc
->pid
) {
2403 proc
->state
= PROC_STATE_DIED_WAIT_FOR_PID
;
2406 scgi_restart_dead_procs(srv
, p
, host
);
2408 return scgi_reconnect(srv
, hctx
);
2410 scgi_connection_close(srv
, hctx
);
2411 con
->http_status
= 503;
2413 return HANDLER_FINISHED
;
2419 static handler_t
scgi_recv_response(server
*srv
, handler_ctx
*hctx
);
2422 SUBREQUEST_FUNC(mod_scgi_handle_subrequest
) {
2423 plugin_data
*p
= p_d
;
2425 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2427 if (NULL
== hctx
) return HANDLER_GO_ON
;
2430 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
2432 if ((con
->conf
.stream_response_body
& FDEVENT_STREAM_RESPONSE_BUFMIN
)
2433 && con
->file_started
) {
2434 if (chunkqueue_length(con
->write_queue
) > 65536 - 4096) {
2435 fdevent_event_clr(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2436 } else if (!(fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_IN
)) {
2437 /* optimistic read from backend, which might re-enable FDEVENT_IN */
2438 handler_t rc
= scgi_recv_response(srv
, hctx
); /*(might invalidate hctx)*/
2439 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
2443 if (0 == hctx
->wb
->bytes_in
2444 ? con
->state
== CON_STATE_READ_POST
2445 : hctx
->wb
->bytes_in
< hctx
->wb_reqlen
) {
2446 /*(64k - 4k to attempt to avoid temporary files
2447 * in conjunction with FDEVENT_STREAM_REQUEST_BUFMIN)*/
2448 if (hctx
->wb
->bytes_in
- hctx
->wb
->bytes_out
> 65536 - 4096
2449 && (con
->conf
.stream_request_body
& FDEVENT_STREAM_REQUEST_BUFMIN
)){
2450 con
->conf
.stream_request_body
&= ~FDEVENT_STREAM_REQUEST_POLLIN
;
2451 if (0 != hctx
->wb
->bytes_in
) return HANDLER_WAIT_FOR_EVENT
;
2453 handler_t r
= connection_handle_read_post_state(srv
, con
);
2454 chunkqueue
*req_cq
= con
->request_content_queue
;
2455 if (0 != hctx
->wb
->bytes_in
&& !chunkqueue_is_empty(req_cq
)) {
2456 chunkqueue_append_chunkqueue(hctx
->wb
, req_cq
);
2457 if (fdevent_event_get_interest(srv
->ev
, hctx
->fd
) & FDEVENT_OUT
) {
2458 return (r
== HANDLER_GO_ON
) ? HANDLER_WAIT_FOR_EVENT
: r
;
2461 if (r
!= HANDLER_GO_ON
) return r
;
2465 return ((0 == hctx
->wb
->bytes_in
|| !chunkqueue_is_empty(hctx
->wb
))
2466 && hctx
->state
!= FCGI_STATE_CONNECT
)
2467 ? scgi_send_request(srv
, hctx
)
2468 : HANDLER_WAIT_FOR_EVENT
;
2472 static handler_t
scgi_recv_response(server
*srv
, handler_ctx
*hctx
) {
2474 switch (scgi_demux_response(srv
, hctx
)) {
2479 scgi_connection_close(srv
, hctx
);
2481 return HANDLER_FINISHED
;
2483 connection
*con
= hctx
->remote_conn
;
2484 plugin_data
*p
= hctx
->plugin_data
;
2486 scgi_proc
*proc
= hctx
->proc
;
2487 scgi_extension_host
*host
= hctx
->host
;
2489 if (proc
->pid
&& proc
->state
!= PROC_STATE_DIED
) {
2492 /* only fetch the zombie if it is not already done */
2494 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2496 /* child is still alive */
2501 /* the child should not terminate at all */
2502 if (WIFEXITED(status
)) {
2503 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2504 "child exited, pid:", proc
->pid
,
2505 "status:", WEXITSTATUS(status
));
2506 } else if (WIFSIGNALED(status
)) {
2507 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2511 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2512 "child died somehow:",
2516 if (hctx
->conf
.debug
) {
2517 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2518 "--- scgi spawning",
2519 "\n\tport:", host
->port
,
2520 "\n\tsocket", host
->unixsocket
,
2521 "\n\tcurrent:", 1, "/", host
->min_procs
);
2524 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2526 proc
->state
= PROC_STATE_DIED
;
2528 scgi_proclist_sort_down(srv
, host
, proc
);
2535 if (con
->file_started
== 0) {
2536 /* nothing has been send out yet, try to use another child */
2538 if (hctx
->wb
->bytes_out
== 0 &&
2539 hctx
->reconnects
++ < 5) {
2541 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2542 "response not sent, request not sent, reconnection.",
2543 "connection-fd:", con
->fd
,
2544 "fcgi-fd:", hctx
->fd
);
2546 return scgi_reconnect(srv
, hctx
);
2549 log_error_write(srv
, __FILE__
, __LINE__
, "sosdsd",
2550 "response not sent, request sent:", hctx
->wb
->bytes_out
,
2551 "connection-fd:", con
->fd
,
2552 "fcgi-fd:", hctx
->fd
);
2554 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2555 "response already sent out, termination connection",
2556 "connection-fd:", con
->fd
,
2557 "fcgi-fd:", hctx
->fd
);
2560 http_response_backend_error(srv
, con
);
2561 scgi_connection_close(srv
, hctx
);
2562 return HANDLER_FINISHED
;
2566 return HANDLER_GO_ON
;
2570 static handler_t
scgi_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
2571 handler_ctx
*hctx
= ctx
;
2572 connection
*con
= hctx
->remote_conn
;
2574 joblist_append(srv
, con
);
2576 if (revents
& FDEVENT_IN
) {
2577 handler_t rc
= scgi_recv_response(srv
, hctx
);/*(might invalidate hctx)*/
2578 if (rc
!= HANDLER_GO_ON
) return rc
; /*(unless HANDLER_GO_ON)*/
2581 if (revents
& FDEVENT_OUT
) {
2582 return scgi_send_request(srv
, hctx
); /*(might invalidate hctx)*/
2585 /* perhaps this issue is already handled */
2586 if (revents
& FDEVENT_HUP
) {
2587 if (hctx
->state
== FCGI_STATE_CONNECT
) {
2588 /* getoptsock will catch this one (right ?)
2590 * if we are in connect we might get a EINPROGRESS
2591 * in the first call and a FDEVENT_HUP in the
2594 * FIXME: as it is a bit ugly.
2597 scgi_send_request(srv
, hctx
);
2598 } else if (con
->file_started
) {
2599 /* drain any remaining data from kernel pipe buffers
2600 * even if (con->conf.stream_response_body
2601 * & FDEVENT_STREAM_RESPONSE_BUFMIN)
2602 * since event loop will spin on fd FDEVENT_HUP event
2603 * until unregistered. */
2606 rc
= scgi_recv_response(srv
,hctx
);/*(might invalidate hctx)*/
2607 } while (rc
== HANDLER_GO_ON
); /*(unless HANDLER_GO_ON)*/
2608 return rc
; /* HANDLER_FINISHED or HANDLER_ERROR */
2610 scgi_extension_host
*host
= hctx
->host
;
2611 log_error_write(srv
, __FILE__
, __LINE__
, "sbSBSDSd",
2612 "error: unexpected close of scgi connection for",
2614 "(no scgi process on host: ",
2621 scgi_connection_close(srv
, hctx
);
2623 } else if (revents
& FDEVENT_ERR
) {
2624 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2625 "fcgi: got a FDEVENT_ERR. Don't know why.");
2627 http_response_backend_error(srv
, con
);
2628 scgi_connection_close(srv
, hctx
);
2631 return HANDLER_FINISHED
;
2635 static int scgi_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
2637 plugin_config
*s
= p
->config_storage
[0];
2643 /* skip the first, the global context */
2644 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
2645 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
2646 s
= p
->config_storage
[i
];
2648 /* condition didn't match */
2649 if (!config_check_cond(srv
, con
, dc
)) continue;
2652 for (j
= 0; j
< dc
->value
->used
; j
++) {
2653 data_unset
*du
= dc
->value
->data
[j
];
2655 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.server"))) {
2657 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.protocol"))) {
2659 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.debug"))) {
2670 static handler_t
scgi_check_extension(server
*srv
, connection
*con
, void *p_d
, int uri_path_handler
) {
2671 plugin_data
*p
= p_d
;
2672 size_t s_len
, uri_path_len
;
2675 scgi_extension
*extension
= NULL
;
2676 scgi_extension_host
*host
= NULL
;
2678 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
2680 /* Possibly, we processed already this request */
2681 if (con
->file_started
== 1) return HANDLER_GO_ON
;
2683 fn
= uri_path_handler
? con
->uri
.path
: con
->physical
.path
;
2685 if (buffer_string_is_empty(fn
)) return HANDLER_GO_ON
;
2687 s_len
= buffer_string_length(fn
);
2688 uri_path_len
= buffer_string_length(con
->uri
.path
);
2690 scgi_patch_connection(srv
, con
, p
);
2692 /* check if extension matches */
2693 for (k
= 0; k
< p
->conf
.exts
->used
; k
++) {
2695 scgi_extension
*ext
= p
->conf
.exts
->exts
[k
];
2697 if (buffer_is_empty(ext
->key
)) continue;
2699 ct_len
= buffer_string_length(ext
->key
);
2701 /* check _url_ in the form "/scgi_pattern" */
2702 if (extension
->key
->ptr
[0] == '/') {
2703 if (ct_len
<= uri_path_len
2704 && 0 == strncmp(con
->uri
.path
->ptr
, ext
->key
->ptr
, ct_len
)) {
2708 } else if (ct_len
<= s_len
2709 && 0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
)) {
2710 /* check extension in the form ".fcg" */
2716 /* extension doesn't match */
2717 if (NULL
== extension
) {
2718 return HANDLER_GO_ON
;
2721 /* get best server */
2722 host
= scgi_extension_host_get(srv
, con
, p
, extension
);
2724 return HANDLER_FINISHED
;
2727 /* a note about no handler is not sent yet */
2728 extension
->note_is_sent
= 0;
2730 /* SCGI requires that Content-Length be set.
2731 * Send 411 Length Required if Content-Length missing.
2732 * (Alternatively, collect full request body before proceeding
2733 * in mod_scgi_handle_subrequest()) */
2734 if (0 == con
->request
.content_length
2735 && array_get_element(con
->request
.headers
, "Transfer-Encoding")) {
2736 con
->keep_alive
= 0;
2737 con
->http_status
= 411; /* Length Required */
2739 return HANDLER_FINISHED
;
2743 * if check-local is disabled, use the uri.path handler
2747 /* init handler-context */
2748 if (uri_path_handler
) {
2749 if (host
->check_local
== 0) {
2753 hctx
= handler_ctx_init();
2755 hctx
->remote_conn
= con
;
2756 hctx
->plugin_data
= p
;
2759 hctx
->ext
= extension
;
2761 /*hctx->conf.exts = p->conf.exts;*/
2762 hctx
->conf
.debug
= p
->conf
.debug
;
2764 con
->plugin_ctx
[p
->id
] = hctx
;
2770 if (con
->conf
.log_request_handling
) {
2771 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2772 "handling it in mod_scgi");
2775 /* the prefix is the SCRIPT_NAME,
2776 * everything from start to the next slash
2777 * this is important for check-local = "disable"
2779 * if prefix = /admin.fcgi
2781 * /admin.fcgi/foo/bar
2783 * SCRIPT_NAME = /admin.fcgi
2784 * PATH_INFO = /foo/bar
2786 * if prefix = /fcgi-bin/
2790 * SCRIPT_NAME = /fcgi-bin/foo
2795 /* the rewrite is only done for /prefix/? matches */
2796 if (host
->fix_root_path_name
&& extension
->key
->ptr
[0] == '/' && extension
->key
->ptr
[1] == '\0') {
2797 buffer_copy_string(con
->request
.pathinfo
, con
->uri
.path
->ptr
);
2798 buffer_string_set_length(con
->uri
.path
, 0);
2799 } else if (extension
->key
->ptr
[0] == '/' &&
2800 buffer_string_length(con
->uri
.path
) > buffer_string_length(extension
->key
) &&
2801 NULL
!= (pathinfo
= strchr(con
->uri
.path
->ptr
+ buffer_string_length(extension
->key
), '/'))) {
2802 /* rewrite uri.path and pathinfo */
2804 buffer_copy_string(con
->request
.pathinfo
, pathinfo
);
2805 buffer_string_set_length(con
->uri
.path
, buffer_string_length(con
->uri
.path
) - buffer_string_length(con
->request
.pathinfo
));
2810 hctx
= handler_ctx_init();
2812 hctx
->remote_conn
= con
;
2813 hctx
->plugin_data
= p
;
2816 hctx
->ext
= extension
;
2818 /*hctx->conf.exts = p->conf.exts;*/
2819 hctx
->conf
.debug
= p
->conf
.debug
;
2821 con
->plugin_ctx
[p
->id
] = hctx
;
2827 if (con
->conf
.log_request_handling
) {
2828 log_error_write(srv
, __FILE__
, __LINE__
, "s", "handling it in mod_scgi");
2832 return HANDLER_GO_ON
;
2835 /* uri-path handler */
2836 static handler_t
scgi_check_extension_1(server
*srv
, connection
*con
, void *p_d
) {
2837 return scgi_check_extension(srv
, con
, p_d
, 1);
2840 /* start request handler */
2841 static handler_t
scgi_check_extension_2(server
*srv
, connection
*con
, void *p_d
) {
2842 return scgi_check_extension(srv
, con
, p_d
, 0);
2846 TRIGGER_FUNC(mod_scgi_handle_trigger
) {
2847 plugin_data
*p
= p_d
;
2851 /* perhaps we should kill a connect attempt after 10-15 seconds
2853 * currently we wait for the TCP timeout which is on Linux 180 seconds
2859 /* check all childs if they are still up */
2861 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
2862 plugin_config
*conf
;
2865 conf
= p
->config_storage
[i
];
2869 for (j
= 0; j
< exts
->used
; j
++) {
2874 for (n
= 0; n
< ex
->used
; n
++) {
2877 unsigned long sum_load
= 0;
2878 scgi_extension_host
*host
;
2880 host
= ex
->hosts
[n
];
2882 scgi_restart_dead_procs(srv
, p
, host
);
2884 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2885 sum_load
+= proc
->load
;
2888 if (host
->num_procs
&&
2889 host
->num_procs
< host
->max_procs
&&
2890 (sum_load
/ host
->num_procs
) > host
->max_load_per_proc
) {
2891 /* overload, spawn new child */
2892 scgi_proc
*fp
= NULL
;
2894 if (p
->conf
.debug
) {
2895 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2896 "overload detected, spawning a new child");
2899 for (fp
= host
->unused_procs
; fp
&& fp
->pid
!= 0; fp
= fp
->next
);
2902 if (fp
== host
->unused_procs
) host
->unused_procs
= fp
->next
;
2904 if (fp
->next
) fp
->next
->prev
= NULL
;
2908 fp
= scgi_process_init();
2909 fp
->id
= host
->max_id
++;
2914 if (buffer_string_is_empty(host
->unixsocket
)) {
2915 fp
->port
= host
->port
+ fp
->id
;
2917 buffer_copy_buffer(fp
->socket
, host
->unixsocket
);
2918 buffer_append_string_len(fp
->socket
, CONST_STR_LEN("-"));
2919 buffer_append_int(fp
->socket
, fp
->id
);
2922 if (scgi_spawn_connection(srv
, p
, host
, fp
)) {
2923 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2924 "ERROR: spawning fcgi failed.");
2925 scgi_process_free(fp
);
2926 return HANDLER_ERROR
;
2930 fp
->next
= host
->first
;
2932 host
->first
->prev
= fp
;
2937 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2938 if (proc
->load
!= 0) break;
2939 if (host
->num_procs
<= host
->min_procs
) break;
2940 if (proc
->pid
== 0) continue;
2942 if (srv
->cur_ts
- proc
->last_used
> host
->idle_timeout
) {
2943 /* a proc is idling for a long time now,
2946 if (p
->conf
.debug
) {
2947 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
2948 "idle-timeout reached, terminating child:",
2949 "socket:", proc
->socket
,
2954 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
2955 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
2957 if (proc
->prev
== NULL
) host
->first
= proc
->next
;
2960 proc
->next
= host
->unused_procs
;
2962 if (host
->unused_procs
) host
->unused_procs
->prev
= proc
;
2963 host
->unused_procs
= proc
;
2965 kill(proc
->pid
, SIGTERM
);
2967 proc
->state
= PROC_STATE_KILLED
;
2969 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
2971 "socket:", proc
->socket
,
2976 /* proc is now in unused, let the next second handle the next process */
2981 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
2984 if (proc
->pid
== 0) continue;
2986 switch (waitpid(proc
->pid
, &status
, WNOHANG
)) {
2988 /* child still running after timeout, good */
2991 if (errno
!= EINTR
) {
2992 /* no PID found ? should never happen */
2993 log_error_write(srv
, __FILE__
, __LINE__
, "sddss",
2994 "pid ", proc
->pid
, proc
->state
,
2995 "not found:", strerror(errno
));
2998 if (errno
== ECHILD
) {
2999 /* someone else has cleaned up for us */
3001 proc
->state
= PROC_STATE_UNSET
;
3007 /* the child should not terminate at all */
3008 if (WIFEXITED(status
)) {
3009 if (proc
->state
!= PROC_STATE_KILLED
) {
3010 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
3012 WEXITSTATUS(status
), proc
->socket
);
3014 } else if (WIFSIGNALED(status
)) {
3015 if (WTERMSIG(status
) != SIGTERM
) {
3016 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3021 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3022 "child died somehow:",
3026 proc
->state
= PROC_STATE_UNSET
;
3034 return HANDLER_GO_ON
;
3038 int mod_scgi_plugin_init(plugin
*p
);
3039 int mod_scgi_plugin_init(plugin
*p
) {
3040 p
->version
= LIGHTTPD_VERSION_ID
;
3041 p
->name
= buffer_init_string("scgi");
3043 p
->init
= mod_scgi_init
;
3044 p
->cleanup
= mod_scgi_free
;
3045 p
->set_defaults
= mod_scgi_set_defaults
;
3046 p
->connection_reset
= scgi_connection_reset
;
3047 p
->handle_connection_close
= scgi_connection_reset
;
3048 p
->handle_uri_clean
= scgi_check_extension_1
;
3049 p
->handle_subrequest_start
= scgi_check_extension_2
;
3050 p
->handle_subrequest
= mod_scgi_handle_subrequest
;
3051 p
->handle_trigger
= mod_scgi_handle_trigger
;