8 #include "http_chunk.h"
10 #include "connections.h"
16 #include "inet_ntop_cache.h"
18 #include <sys/types.h>
30 #ifdef HAVE_SYS_FILIO_H
31 # include <sys/filio.h>
34 #include "sys-socket.h"
40 #ifdef HAVE_SYS_WAIT_H
41 # include <sys/wait.h>
46 enum {EOL_UNSET
, EOL_N
, EOL_RN
};
52 * - add timeout for a connect to a non-scgi process
53 * (use state_timestamp + state)
57 typedef struct scgi_proc
{
58 size_t id
; /* id will be between 1 and max_procs */
59 buffer
*socket
; /* config.socket + "-" + id */
60 unsigned port
; /* config.port + pno */
62 pid_t pid
; /* PID of the spawned process (0 if not spawned locally) */
65 size_t load
; /* number of requests waiting on this process */
67 time_t last_used
; /* see idle_timeout */
68 size_t requests
; /* see max_requests */
69 struct scgi_proc
*prev
, *next
; /* see first */
71 time_t disable_ts
; /* replace by host->something */
75 enum { PROC_STATE_UNSET
, /* init-phase */
76 PROC_STATE_RUNNING
, /* alive */
77 PROC_STATE_DIED_WAIT_FOR_PID
,
78 PROC_STATE_KILLED
, /* was killed as we don't have the load anymore */
79 PROC_STATE_DIED
, /* marked as dead, should be restarted */
80 PROC_STATE_DISABLED
/* proc disabled as it resulted in an error */
85 /* list of processes handling this extension
86 * sorted by lowest load
88 * whenever a job is done move it up in the list
89 * until it is sorted, move it down as soon as the
93 scgi_proc
*unused_procs
;
96 * spawn at least min_procs, at max_procs.
98 * as soon as the load of the first entry
99 * is max_load_per_proc we spawn a new one
100 * and add it to the first entry and give it
105 unsigned short min_procs
;
106 unsigned short max_procs
;
107 size_t num_procs
; /* how many procs are started */
108 size_t active_procs
; /* how many of them are really running */
110 unsigned short max_load_per_proc
;
113 * kick the process from the list if it was not
114 * used for idle_timeout until min_procs is
115 * reached. this helps to get the processlist
116 * small again we had a small peak load.
120 unsigned short idle_timeout
;
123 * time after a disabled remote connection is tried to be re-enabled
128 unsigned short disable_time
;
131 * same scgi processes get a little bit larger
132 * than wanted. max_requests_per_proc kills a
133 * process after a number of handled requests.
136 size_t max_requests_per_proc
;
144 * if host is one of the local IP adresses the
145 * whole connection is local
147 * if tcp/ip should be used host AND port have
157 * instead of TCP/IP we can use Unix Domain Sockets
158 * - more secure (you have fileperms to play with)
159 * - more control (on locally)
160 * - more speed (no extra overhead)
164 /* if socket is local we can start the scgi
167 * bin-path is the path to the binary
169 * check min_procs and max_procs for the number
170 * of process to start-up
174 /* bin-path is set bin-environment is taken to
175 * create the environement before starting the
184 * docroot-translation between URL->phys and the
188 * - different dir-layout if remote
195 * check_local tell you if the phys file is stat()ed
196 * or not. FastCGI doesn't care if the service is
197 * remote. If the web-server side doesn't contain
198 * the scgi-files we should not stat() for them
199 * and say '404 not found'.
201 unsigned short check_local
;
204 * append PATH_INFO to SCRIPT_FILENAME
206 * php needs this if cgi.fix_pathinfo is provied
211 * workaround for program when prefix="/"
213 * rule to build PATH_INFO is hardcoded for when check_local is disabled
214 * enable this option to use the workaround
218 unsigned short fix_root_path_name
;
219 ssize_t load
; /* replace by host->load */
221 size_t max_id
; /* corresponds most of the time to
224 only if a process is killed max_id waits for the process itself
225 to die and decrements its afterwards */
226 } scgi_extension_host
;
229 * one extension can have multiple hosts assigned
230 * one host can spawn additional processes on the same
231 * socket (if we control it)
233 * ext -> host -> procs
236 * if the scgi process is remote that whole goes down
239 * ext -> host -> procs
242 * in case of PHP and FCGI_CHILDREN we have again a procs
243 * but we don't control it directly.
248 buffer
*key
; /* like .php */
251 scgi_extension_host
**hosts
;
258 scgi_extension
**exts
;
278 /* generic plugin data, shared between all connections */
285 buffer
*parse_response
;
287 plugin_config
**config_storage
;
289 plugin_config conf
; /* this is only used as long as no handler_ctx is setup */
292 /* connection specific data */
293 typedef enum { FCGI_STATE_INIT
, FCGI_STATE_CONNECT
, FCGI_STATE_PREPARE_WRITE
,
294 FCGI_STATE_WRITE
, FCGI_STATE_READ
295 } scgi_connection_state_t
;
301 int response_padding
;
304 scgi_extension_host
*host
;
306 scgi_connection_state_t state
;
307 time_t state_timestamp
;
309 int reconnects
; /* number of reconnect attempts */
313 buffer
*response_header
;
315 int delayed
; /* flag to mark that the connect() is delayed */
318 int fd
; /* fd to the scgi process */
319 int fde_ndx
; /* index into the fd-event buffer */
326 connection
*remote_conn
; /* dumb pointer */
327 plugin_data
*plugin_data
; /* dumb pointer */
331 /* ok, we need a prototype */
332 static handler_t
scgi_handle_fdevent(server
*srv
, void *ctx
, int revents
);
334 int scgi_proclist_sort_down(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
);
336 static void reset_signals(void) {
338 signal(SIGTTOU
, SIG_DFL
);
341 signal(SIGTTIN
, SIG_DFL
);
344 signal(SIGTSTP
, SIG_DFL
);
346 signal(SIGHUP
, SIG_DFL
);
347 signal(SIGPIPE
, SIG_DFL
);
348 signal(SIGUSR1
, SIG_DFL
);
351 static handler_ctx
* handler_ctx_init(void) {
354 hctx
= calloc(1, sizeof(*hctx
));
359 hctx
->response
= buffer_init();
360 hctx
->response_header
= buffer_init();
362 hctx
->request_id
= 0;
363 hctx
->state
= FCGI_STATE_INIT
;
366 hctx
->response_len
= 0;
367 hctx
->response_type
= 0;
368 hctx
->response_padding
= 0;
371 hctx
->reconnects
= 0;
373 hctx
->wb
= chunkqueue_init();
378 static void handler_ctx_free(handler_ctx
*hctx
) {
379 buffer_free(hctx
->response
);
380 buffer_free(hctx
->response_header
);
382 chunkqueue_free(hctx
->wb
);
387 static scgi_proc
*scgi_process_init(void) {
390 f
= calloc(1, sizeof(*f
));
392 f
->socket
= buffer_init();
400 static void scgi_process_free(scgi_proc
*f
) {
403 scgi_process_free(f
->next
);
405 buffer_free(f
->socket
);
410 static scgi_extension_host
*scgi_host_init(void) {
411 scgi_extension_host
*f
;
413 f
= calloc(1, sizeof(*f
));
415 f
->host
= buffer_init();
416 f
->unixsocket
= buffer_init();
417 f
->docroot
= buffer_init();
418 f
->bin_path
= buffer_init();
419 f
->bin_env
= array_init();
420 f
->bin_env_copy
= array_init();
425 static void scgi_host_free(scgi_extension_host
*h
) {
428 buffer_free(h
->host
);
429 buffer_free(h
->unixsocket
);
430 buffer_free(h
->docroot
);
431 buffer_free(h
->bin_path
);
432 array_free(h
->bin_env
);
433 array_free(h
->bin_env_copy
);
435 scgi_process_free(h
->first
);
436 scgi_process_free(h
->unused_procs
);
442 static scgi_exts
*scgi_extensions_init(void) {
445 f
= calloc(1, sizeof(*f
));
451 static void scgi_extensions_free(scgi_exts
*f
) {
456 for (i
= 0; i
< f
->used
; i
++) {
462 for (j
= 0; j
< fe
->used
; j
++) {
463 scgi_extension_host
*h
;
470 buffer_free(fe
->key
);
481 static int scgi_extension_insert(scgi_exts
*ext
, buffer
*key
, scgi_extension_host
*fh
) {
485 /* there is something */
487 for (i
= 0; i
< ext
->used
; i
++) {
488 if (buffer_is_equal(key
, ext
->exts
[i
]->key
)) {
493 if (i
== ext
->used
) {
494 /* filextension is new */
495 fe
= calloc(1, sizeof(*fe
));
497 fe
->key
= buffer_init();
498 buffer_copy_buffer(fe
->key
, key
);
502 if (ext
->size
== 0) {
504 ext
->exts
= malloc(ext
->size
* sizeof(*(ext
->exts
)));
505 force_assert(ext
->exts
);
506 } else if (ext
->used
== ext
->size
) {
508 ext
->exts
= realloc(ext
->exts
, ext
->size
* sizeof(*(ext
->exts
)));
509 force_assert(ext
->exts
);
511 ext
->exts
[ext
->used
++] = fe
;
518 fe
->hosts
= malloc(fe
->size
* sizeof(*(fe
->hosts
)));
519 force_assert(fe
->hosts
);
520 } else if (fe
->size
== fe
->used
) {
522 fe
->hosts
= realloc(fe
->hosts
, fe
->size
* sizeof(*(fe
->hosts
)));
523 force_assert(fe
->hosts
);
526 fe
->hosts
[fe
->used
++] = fh
;
532 INIT_FUNC(mod_scgi_init
) {
535 p
= calloc(1, sizeof(*p
));
538 p
->scgi_env
= buffer_init();
540 p
->path
= buffer_init();
541 p
->parse_response
= buffer_init();
547 FREE_FUNC(mod_scgi_free
) {
548 plugin_data
*p
= p_d
;
552 buffer_free(p
->scgi_env
);
553 buffer_free(p
->path
);
554 buffer_free(p
->parse_response
);
556 if (p
->config_storage
) {
558 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
559 plugin_config
*s
= p
->config_storage
[i
];
562 if (NULL
== s
) continue;
566 for (j
= 0; j
< exts
->used
; j
++) {
571 for (n
= 0; n
< ex
->used
; n
++) {
573 scgi_extension_host
*host
;
577 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
578 if (proc
->pid
!= 0) kill(proc
->pid
, SIGTERM
);
580 if (proc
->is_local
&&
581 !buffer_string_is_empty(proc
->socket
)) {
582 unlink(proc
->socket
->ptr
);
586 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
587 if (proc
->pid
!= 0) kill(proc
->pid
, SIGTERM
);
589 if (proc
->is_local
&&
590 !buffer_string_is_empty(proc
->socket
)) {
591 unlink(proc
->socket
->ptr
);
597 scgi_extensions_free(s
->exts
);
601 free(p
->config_storage
);
606 return HANDLER_GO_ON
;
609 static int env_add(char_array
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
613 if (!key
|| !val
) return -1;
615 dst
= malloc(key_len
+ val_len
+ 3);
617 memcpy(dst
, key
, key_len
);
619 /* add the \0 from the value */
620 memcpy(dst
+ key_len
+ 1, val
, val_len
+ 1);
622 for (i
= 0; i
< env
->used
; i
++) {
623 if (0 == strncmp(dst
, env
->ptr
[i
], key_len
+ 1)) {
624 /* don't care about free as we are in a forked child which is going to exec(...) */
625 /* free(env->ptr[i]); */
631 if (env
->size
== 0) {
633 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
634 force_assert(env
->ptr
);
635 } else if (env
->size
== env
->used
) {
637 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
638 force_assert(env
->ptr
);
641 env
->ptr
[env
->used
++] = dst
;
646 #if !defined(HAVE_FORK)
647 static int scgi_spawn_connection(server
*srv
,
649 scgi_extension_host
*host
,
658 #else /* -> defined(HAVE_FORK) */
660 static int scgi_spawn_connection(server
*srv
,
662 scgi_extension_host
*host
,
665 int socket_type
, status
;
666 struct timeval tv
= { 0, 100 * 1000 };
668 struct sockaddr_un scgi_addr_un
;
670 struct sockaddr_in scgi_addr_in
;
671 struct sockaddr
*scgi_addr
;
676 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
677 "new proc, socket:", proc
->port
, proc
->socket
);
681 if (!buffer_string_is_empty(proc
->socket
)) {
683 memset(&scgi_addr_un
, 0, sizeof(scgi_addr_un
));
684 scgi_addr_un
.sun_family
= AF_UNIX
;
685 if (buffer_string_length(proc
->socket
) + 1 > sizeof(scgi_addr_un
.sun_path
)) {
686 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
687 "ERROR: Unix Domain socket filename too long:",
691 memcpy(scgi_addr_un
.sun_path
, proc
->socket
->ptr
, buffer_string_length(proc
->socket
) + 1);
694 servlen
= SUN_LEN(&scgi_addr_un
);
697 servlen
= buffer_string_length(proc
->socket
) + 1 + sizeof(scgi_addr_un
.sun_family
);
699 socket_type
= AF_UNIX
;
700 scgi_addr
= (struct sockaddr
*) &scgi_addr_un
;
702 log_error_write(srv
, __FILE__
, __LINE__
, "s",
703 "ERROR: Unix Domain sockets are not supported.");
707 memset(&scgi_addr_in
, 0, sizeof(scgi_addr_in
));
708 scgi_addr_in
.sin_family
= AF_INET
;
710 if (buffer_string_is_empty(host
->host
)) {
711 scgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
715 /* set a usefull default */
716 scgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
719 if (NULL
== (he
= gethostbyname(host
->host
->ptr
))) {
720 log_error_write(srv
, __FILE__
, __LINE__
,
721 "sdb", "gethostbyname failed: ",
722 h_errno
, host
->host
);
726 if (he
->h_addrtype
!= AF_INET
) {
727 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-type != AF_INET: ", he
->h_addrtype
);
731 if (he
->h_length
!= sizeof(struct in_addr
)) {
732 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-length != sizeof(in_addr): ", he
->h_length
);
736 memcpy(&(scgi_addr_in
.sin_addr
.s_addr
), he
->h_addr_list
[0], he
->h_length
);
739 scgi_addr_in
.sin_port
= htons(proc
->port
);
740 servlen
= sizeof(scgi_addr_in
);
742 socket_type
= AF_INET
;
743 scgi_addr
= (struct sockaddr
*) &scgi_addr_in
;
746 if (-1 == (scgi_fd
= socket(socket_type
, SOCK_STREAM
, 0))) {
747 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
748 "failed:", strerror(errno
));
752 if (-1 == connect(scgi_fd
, scgi_addr
, servlen
)) {
753 /* server is not up, spawn in */
757 if (!buffer_string_is_empty(proc
->socket
)) {
758 unlink(proc
->socket
->ptr
);
764 if (-1 == (scgi_fd
= socket(socket_type
, SOCK_STREAM
, 0))) {
765 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
766 "socket failed:", strerror(errno
));
771 if (setsockopt(scgi_fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
)) < 0) {
772 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
773 "socketsockopt failed:", strerror(errno
));
779 if (-1 == bind(scgi_fd
, scgi_addr
, servlen
)) {
780 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
789 if (-1 == listen(scgi_fd
, 1024)) {
790 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
791 "listen failed:", strerror(errno
));
796 switch ((child
= fork())) {
804 /* create environment */
814 /* we don't need the client socket */
815 for (fd
= 3; fd
< 256; fd
++) {
819 /* build clean environment */
820 if (host
->bin_env_copy
->used
) {
821 for (i
= 0; i
< host
->bin_env_copy
->used
; i
++) {
822 data_string
*ds
= (data_string
*)host
->bin_env_copy
->data
[i
];
825 if (NULL
!= (ge
= getenv(ds
->value
->ptr
))) {
826 env_add(&env
, CONST_BUF_LEN(ds
->value
), ge
, strlen(ge
));
830 for (i
= 0; environ
[i
]; i
++) {
833 if (NULL
!= (eq
= strchr(environ
[i
], '='))) {
834 env_add(&env
, environ
[i
], eq
- environ
[i
], eq
+1, strlen(eq
+1));
839 /* create environment */
840 for (i
= 0; i
< host
->bin_env
->used
; i
++) {
841 data_string
*ds
= (data_string
*)host
->bin_env
->data
[i
];
843 env_add(&env
, CONST_BUF_LEN(ds
->key
), CONST_BUF_LEN(ds
->value
));
846 for (i
= 0; i
< env
.used
; i
++) {
847 /* search for PHP_FCGI_CHILDREN */
848 if (0 == strncmp(env
.ptr
[i
], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
851 /* not found, add a default */
853 env_add(&env
, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
856 env
.ptr
[env
.used
] = NULL
;
859 buffer_copy_string_len(b
, CONST_STR_LEN("exec "));
860 buffer_append_string_buffer(b
, host
->bin_path
);
865 execle("/bin/sh", "sh", "-c", b
->ptr
, (char *)NULL
, env
.ptr
);
867 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
868 "execl failed for:", host
->bin_path
, strerror(errno
));
883 select(0, NULL
, NULL
, NULL
, &tv
);
885 switch (waitpid(child
, &status
, WNOHANG
)) {
887 /* child still running after timeout, good */
890 /* no PID found ? should never happen */
891 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
892 "pid not found:", strerror(errno
));
895 /* the child should not terminate at all */
896 if (WIFEXITED(status
)) {
897 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
898 "child exited (is this a SCGI binary ?):",
899 WEXITSTATUS(status
));
900 } else if (WIFSIGNALED(status
)) {
901 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
905 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
906 "child died somehow:",
912 /* register process */
914 proc
->last_used
= srv
->cur_ts
;
926 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
927 "(debug) socket is already used, won't spawn:",
932 proc
->state
= PROC_STATE_RUNNING
;
933 host
->active_procs
++;
938 #endif /* HAVE_FORK */
940 static int unixsocket_is_dup(plugin_data
*p
, size_t used
, buffer
*unixsocket
) {
942 for (i
= 0; i
< used
; ++i
) {
943 scgi_exts
*exts
= p
->config_storage
[i
]->exts
;
944 for (j
= 0; j
< exts
->used
; ++j
) {
945 scgi_extension
*ex
= exts
->exts
[j
];
946 for (n
= 0; n
< ex
->used
; ++n
) {
947 scgi_extension_host
*host
= ex
->hosts
[n
];
948 if (!buffer_string_is_empty(host
->unixsocket
)
949 && buffer_is_equal(host
->unixsocket
, unixsocket
))
958 SETDEFAULTS_FUNC(mod_scgi_set_defaults
) {
959 plugin_data
*p
= p_d
;
962 scgi_extension_host
*df
= NULL
;
964 config_values_t cv
[] = {
965 { "scgi.server", NULL
, T_CONFIG_LOCAL
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
966 { "scgi.debug", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
967 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
970 p
->config_storage
= calloc(1, srv
->config_context
->used
* sizeof(plugin_config
*));
971 force_assert(p
->config_storage
);
973 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
974 data_config
const* config
= (data_config
const*)srv
->config_context
->data
[i
];
977 s
= malloc(sizeof(plugin_config
));
979 s
->exts
= scgi_extensions_init();
982 cv
[0].destination
= s
->exts
;
983 cv
[1].destination
= &(s
->debug
);
985 p
->config_storage
[i
] = s
;
987 if (0 != config_insert_values_global(srv
, config
->value
, cv
, i
== 0 ? T_CONFIG_SCOPE_SERVER
: T_CONFIG_SCOPE_CONNECTION
)) {
995 if (NULL
!= (du
= array_get_element(config
->value
, "scgi.server"))) {
997 data_array
*da
= (data_array
*)du
;
999 if (du
->type
!= TYPE_ARRAY
) {
1000 log_error_write(srv
, __FILE__
, __LINE__
, "sss",
1001 "unexpected type for key: ", "scgi.server", "array of strings");
1008 * scgi.server = ( "<ext>" => ( ... ),
1009 * "<ext>" => ( ... ) )
1012 for (j
= 0; j
< da
->value
->used
; j
++) {
1014 data_array
*da_ext
= (data_array
*)da
->value
->data
[j
];
1016 if (da
->value
->data
[j
]->type
!= TYPE_ARRAY
) {
1017 log_error_write(srv
, __FILE__
, __LINE__
, "sssbs",
1018 "unexpected type for key: ", "scgi.server",
1019 "[", da
->value
->data
[j
]->key
, "](string)");
1025 * da_ext->key == name of the extension
1029 * scgi.server = ( "<ext>" =>
1030 * ( "<host>" => ( ... ),
1031 * "<host>" => ( ... )
1036 for (n
= 0; n
< da_ext
->value
->used
; n
++) {
1037 data_array
*da_host
= (data_array
*)da_ext
->value
->data
[n
];
1039 config_values_t fcv
[] = {
1040 { "host", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
1041 { "docroot", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
1042 { "socket", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
1043 { "bin-path", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 3 */
1045 { "check-local", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 4 */
1046 { "port", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 5 */
1047 { "min-procs-not-working", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 this is broken for now */
1048 { "max-procs", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 */
1049 { "max-load-per-proc", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 8 */
1050 { "idle-timeout", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 9 */
1051 { "disable-time", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 10 */
1053 { "bin-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 11 */
1054 { "bin-copy-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 12 */
1055 { "fix-root-scriptname", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 13 */
1058 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
1061 if (da_host
->type
!= TYPE_ARRAY
) {
1062 log_error_write(srv
, __FILE__
, __LINE__
, "ssSBS",
1063 "unexpected type for key:",
1065 "[", da_host
->key
, "](string)");
1070 df
= scgi_host_init();
1072 df
->check_local
= 1;
1075 df
->max_load_per_proc
= 1;
1076 df
->idle_timeout
= 60;
1077 df
->disable_time
= 60;
1078 df
->fix_root_path_name
= 0;
1080 fcv
[0].destination
= df
->host
;
1081 fcv
[1].destination
= df
->docroot
;
1082 fcv
[2].destination
= df
->unixsocket
;
1083 fcv
[3].destination
= df
->bin_path
;
1085 fcv
[4].destination
= &(df
->check_local
);
1086 fcv
[5].destination
= &(df
->port
);
1087 fcv
[6].destination
= &(df
->min_procs
);
1088 fcv
[7].destination
= &(df
->max_procs
);
1089 fcv
[8].destination
= &(df
->max_load_per_proc
);
1090 fcv
[9].destination
= &(df
->idle_timeout
);
1091 fcv
[10].destination
= &(df
->disable_time
);
1093 fcv
[11].destination
= df
->bin_env
;
1094 fcv
[12].destination
= df
->bin_env_copy
;
1095 fcv
[13].destination
= &(df
->fix_root_path_name
);
1098 if (0 != config_insert_values_internal(srv
, da_host
->value
, fcv
, T_CONFIG_SCOPE_CONNECTION
)) {
1102 if ((!buffer_string_is_empty(df
->host
) || df
->port
) &&
1103 !buffer_string_is_empty(df
->unixsocket
)) {
1104 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1105 "either host+port or socket");
1110 if (!buffer_string_is_empty(df
->unixsocket
)) {
1111 /* unix domain socket */
1112 struct sockaddr_un un
;
1114 if (buffer_string_length(df
->unixsocket
) + 1 > sizeof(un
.sun_path
) - 2) {
1115 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1116 "path of the unixdomain socket is too large");
1120 if (!buffer_string_is_empty(df
->bin_path
)
1121 && unixsocket_is_dup(p
, i
+1, df
->unixsocket
)) {
1122 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1123 "duplicate unixsocket path:",
1130 if (buffer_string_is_empty(df
->host
) &&
1131 buffer_string_is_empty(df
->bin_path
)) {
1132 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbs",
1133 "missing key (string):",
1140 } else if (df
->port
== 0) {
1141 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbs",
1142 "missing key (short):",
1151 if (!buffer_string_is_empty(df
->bin_path
)) {
1152 /* a local socket + self spawning */
1155 /* HACK: just to make sure the adaptive spawing is disabled */
1156 df
->min_procs
= df
->max_procs
;
1158 if (df
->min_procs
> df
->max_procs
) df
->max_procs
= df
->min_procs
;
1159 if (df
->max_load_per_proc
< 1) df
->max_load_per_proc
= 0;
1162 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsbsdsd",
1163 "--- scgi spawning local",
1164 "\n\tproc:", df
->bin_path
,
1165 "\n\tport:", df
->port
,
1166 "\n\tsocket", df
->unixsocket
,
1167 "\n\tmin-procs:", df
->min_procs
,
1168 "\n\tmax-procs:", df
->max_procs
);
1171 for (pno
= 0; pno
< df
->min_procs
; pno
++) {
1174 proc
= scgi_process_init();
1175 proc
->id
= df
->num_procs
++;
1178 if (buffer_string_is_empty(df
->unixsocket
)) {
1179 proc
->port
= df
->port
+ pno
;
1181 buffer_copy_buffer(proc
->socket
, df
->unixsocket
);
1182 buffer_append_string_len(proc
->socket
, CONST_STR_LEN("-"));
1183 buffer_append_int(proc
->socket
, pno
);
1187 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
1188 "--- scgi spawning",
1189 "\n\tport:", df
->port
,
1190 "\n\tsocket", df
->unixsocket
,
1191 "\n\tcurrent:", pno
, "/", df
->min_procs
);
1194 if (scgi_spawn_connection(srv
, p
, df
, proc
)) {
1195 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1196 "[ERROR]: spawning fcgi failed.");
1197 scgi_process_free(proc
);
1201 proc
->next
= df
->first
;
1202 if (df
->first
) df
->first
->prev
= proc
;
1209 fp
= scgi_process_init();
1210 fp
->id
= df
->num_procs
++;
1213 fp
->state
= PROC_STATE_RUNNING
;
1215 if (buffer_string_is_empty(df
->unixsocket
)) {
1216 fp
->port
= df
->port
;
1218 buffer_copy_buffer(fp
->socket
, df
->unixsocket
);
1227 /* if extension already exists, take it */
1228 scgi_extension_insert(s
->exts
, da_ext
->key
, df
);
1235 return HANDLER_GO_ON
;
1238 if (NULL
!= df
) scgi_host_free(df
);
1239 return HANDLER_ERROR
;
1242 static int scgi_set_state(server
*srv
, handler_ctx
*hctx
, scgi_connection_state_t state
) {
1243 hctx
->state
= state
;
1244 hctx
->state_timestamp
= srv
->cur_ts
;
1250 static void scgi_connection_cleanup(server
*srv
, handler_ctx
*hctx
) {
1254 if (NULL
== hctx
) return;
1256 p
= hctx
->plugin_data
;
1257 con
= hctx
->remote_conn
;
1259 if (hctx
->fd
!= -1) {
1260 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1261 fdevent_unregister(srv
->ev
, hctx
->fd
);
1266 if (hctx
->host
&& hctx
->proc
) {
1269 if (hctx
->got_proc
) {
1270 /* after the connect the process gets a load */
1273 if (p
->conf
.debug
) {
1274 log_error_write(srv
, __FILE__
, __LINE__
, "sddb",
1277 hctx
->proc
->pid
, hctx
->proc
->socket
);
1281 scgi_proclist_sort_down(srv
, hctx
->host
, hctx
->proc
);
1285 handler_ctx_free(hctx
);
1286 con
->plugin_ctx
[p
->id
] = NULL
;
1289 static int scgi_reconnect(server
*srv
, handler_ctx
*hctx
) {
1290 plugin_data
*p
= hctx
->plugin_data
;
1296 * connect was ok, connection was accepted
1297 * but the php accept loop checks after the accept if it should die or not.
1299 * if yes we can only detect it at a write()
1301 * next step is resetting this attemp and setup a connection again
1303 * if we have more then 5 reconnects for the same request, die
1307 * we have a connection but the child died by some other reason
1311 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1312 fdevent_unregister(srv
->ev
, hctx
->fd
);
1316 scgi_set_state(srv
, hctx
, FCGI_STATE_INIT
);
1318 hctx
->request_id
= 0;
1321 if (p
->conf
.debug
) {
1322 log_error_write(srv
, __FILE__
, __LINE__
, "sddb",
1325 hctx
->proc
->pid
, hctx
->proc
->socket
);
1329 scgi_proclist_sort_down(srv
, hctx
->host
, hctx
->proc
);
1335 static handler_t
scgi_connection_reset(server
*srv
, connection
*con
, void *p_d
) {
1336 plugin_data
*p
= p_d
;
1338 scgi_connection_cleanup(srv
, con
->plugin_ctx
[p
->id
]);
1340 return HANDLER_GO_ON
;
1344 static int scgi_env_add(buffer
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
1347 if (!key
|| !val
) return -1;
1349 len
= key_len
+ val_len
+ 2;
1351 buffer_string_prepare_append(env
, len
);
1353 buffer_append_string_len(env
, key
, key_len
);
1354 buffer_append_string_len(env
, "", 1);
1355 buffer_append_string_len(env
, val
, val_len
);
1356 buffer_append_string_len(env
, "", 1);
1367 * 1 not connected yet
1370 static int scgi_establish_connection(server
*srv
, handler_ctx
*hctx
) {
1371 struct sockaddr
*scgi_addr
;
1372 struct sockaddr_in scgi_addr_in
;
1373 #ifdef HAVE_SYS_UN_H
1374 struct sockaddr_un scgi_addr_un
;
1378 scgi_extension_host
*host
= hctx
->host
;
1379 scgi_proc
*proc
= hctx
->proc
;
1380 int scgi_fd
= hctx
->fd
;
1382 if (!buffer_string_is_empty(proc
->socket
)) {
1383 #ifdef HAVE_SYS_UN_H
1384 /* use the unix domain socket */
1385 memset(&scgi_addr_un
, 0, sizeof(scgi_addr_un
));
1386 scgi_addr_un
.sun_family
= AF_UNIX
;
1387 if (buffer_string_length(proc
->socket
) + 1 > sizeof(scgi_addr_un
.sun_path
)) {
1388 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
1389 "ERROR: Unix Domain socket filename too long:",
1393 memcpy(scgi_addr_un
.sun_path
, proc
->socket
->ptr
, buffer_string_length(proc
->socket
) + 1);
1396 servlen
= SUN_LEN(&scgi_addr_un
);
1399 servlen
= buffer_string_length(proc
->socket
) + 1 + sizeof(scgi_addr_un
.sun_family
);
1401 scgi_addr
= (struct sockaddr
*) &scgi_addr_un
;
1406 memset(&scgi_addr_in
, 0, sizeof(scgi_addr_in
));
1407 scgi_addr_in
.sin_family
= AF_INET
;
1408 if (0 == inet_aton(host
->host
->ptr
, &(scgi_addr_in
.sin_addr
))) {
1409 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1410 "converting IP-adress failed for", host
->host
,
1411 "\nBe sure to specify an IP address here");
1415 scgi_addr_in
.sin_port
= htons(proc
->port
);
1416 servlen
= sizeof(scgi_addr_in
);
1418 scgi_addr
= (struct sockaddr
*) &scgi_addr_in
;
1421 if (-1 == connect(scgi_fd
, scgi_addr
, servlen
)) {
1422 if (errno
== EINPROGRESS
||
1423 errno
== EALREADY
||
1425 if (hctx
->conf
.debug
) {
1426 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1427 "connect delayed, will continue later:", scgi_fd
);
1432 log_error_write(srv
, __FILE__
, __LINE__
, "sdsddb",
1433 "connect failed:", scgi_fd
,
1434 strerror(errno
), errno
,
1435 proc
->port
, proc
->socket
);
1437 if (errno
== EAGAIN
) {
1438 /* this is Linux only */
1440 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1441 "If this happend on Linux: You have been run out of local ports. "
1442 "Check the manual, section Performance how to handle this.");
1448 if (hctx
->conf
.debug
> 1) {
1449 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1450 "connect succeeded: ", scgi_fd
);
1458 static int scgi_env_add_request_headers(server
*srv
, connection
*con
, plugin_data
*p
) {
1461 for (i
= 0; i
< con
->request
.headers
->used
; i
++) {
1464 ds
= (data_string
*)con
->request
.headers
->data
[i
];
1466 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
1467 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 1);
1469 scgi_env_add(p
->scgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
));
1473 for (i
= 0; i
< con
->environment
->used
; i
++) {
1476 ds
= (data_string
*)con
->environment
->data
[i
];
1478 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
1479 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 0);
1481 scgi_env_add(p
->scgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
));
1489 static int scgi_create_env(server
*srv
, handler_ctx
*hctx
) {
1490 char buf
[LI_ITOSTRING_LENGTH
];
1493 char b2
[INET6_ADDRSTRLEN
+ 1];
1497 plugin_data
*p
= hctx
->plugin_data
;
1498 scgi_extension_host
*host
= hctx
->host
;
1500 connection
*con
= hctx
->remote_conn
;
1501 server_socket
*srv_sock
= con
->srv_socket
;
1504 socklen_t our_addr_len
;
1506 buffer_string_prepare_copy(p
->scgi_env
, 1023);
1508 /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
1510 li_itostrn(buf
, sizeof(buf
), con
->request
.content_length
);
1511 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("CONTENT_LENGTH"), buf
, strlen(buf
));
1512 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCGI"), CONST_STR_LEN("1"));
1515 if (buffer_is_empty(con
->conf
.server_tag
)) {
1516 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_DESC
));
1518 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con
->conf
.server_tag
));
1521 if (!buffer_is_empty(con
->server_name
)) {
1522 size_t len
= buffer_string_length(con
->server_name
);
1524 if (con
->server_name
->ptr
[0] == '[') {
1525 const char *colon
= strstr(con
->server_name
->ptr
, "]:");
1526 if (colon
) len
= (colon
+ 1) - con
->server_name
->ptr
;
1528 const char *colon
= strchr(con
->server_name
->ptr
, ':');
1529 if (colon
) len
= colon
- con
->server_name
->ptr
;
1532 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_NAME"), con
->server_name
->ptr
, len
);
1535 s
= inet_ntop(srv_sock
->addr
.plain
.sa_family
,
1536 srv_sock
->addr
.plain
.sa_family
== AF_INET6
?
1537 (const void *) &(srv_sock
->addr
.ipv6
.sin6_addr
) :
1538 (const void *) &(srv_sock
->addr
.ipv4
.sin_addr
),
1541 s
= inet_ntoa(srv_sock
->addr
.ipv4
.sin_addr
);
1544 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_NAME"), s
, strlen(s
));
1547 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1"));
1549 li_utostrn(buf
, sizeof(buf
),
1551 ntohs(srv_sock
->addr
.plain
.sa_family
? srv_sock
->addr
.ipv6
.sin6_port
: srv_sock
->addr
.ipv4
.sin_port
)
1553 ntohs(srv_sock
->addr
.ipv4
.sin_port
)
1557 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_PORT"), buf
, strlen(buf
));
1559 /* get the server-side of the connection to the client */
1560 our_addr_len
= sizeof(our_addr
);
1562 if (-1 == getsockname(con
->fd
, &(our_addr
.plain
), &our_addr_len
)) {
1563 s
= inet_ntop_cache_get_ip(srv
, &(srv_sock
->addr
));
1565 s
= inet_ntop_cache_get_ip(srv
, &(our_addr
));
1567 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_ADDR"), s
, strlen(s
));
1569 li_utostrn(buf
, sizeof(buf
),
1571 ntohs(con
->dst_addr
.plain
.sa_family
? con
->dst_addr
.ipv6
.sin6_port
: con
->dst_addr
.ipv4
.sin_port
)
1573 ntohs(con
->dst_addr
.ipv4
.sin_port
)
1577 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REMOTE_PORT"), buf
, strlen(buf
));
1579 s
= inet_ntop_cache_get_ip(srv
, &(con
->dst_addr
));
1581 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REMOTE_ADDR"), s
, strlen(s
));
1584 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1585 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1586 * (6.1.14, 6.1.6, 6.1.7)
1589 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con
->uri
.path
));
1591 if (!buffer_string_is_empty(con
->request
.pathinfo
)) {
1592 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con
->request
.pathinfo
));
1594 /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1596 if (!buffer_string_is_empty(host
->docroot
)) {
1597 buffer_copy_buffer(p
->path
, host
->docroot
);
1599 buffer_copy_buffer(p
->path
, con
->physical
.basedir
);
1601 buffer_append_string_buffer(p
->path
, con
->request
.pathinfo
);
1602 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p
->path
));
1604 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN(""));
1608 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1609 * http://www.php.net/manual/en/reserved.variables.php
1610 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1611 * TODO: this code should be checked against cgi.fix_pathinfo php
1615 if (!buffer_string_is_empty(host
->docroot
)) {
1617 * rewrite SCRIPT_FILENAME
1621 buffer_copy_buffer(p
->path
, host
->docroot
);
1622 buffer_append_string_buffer(p
->path
, con
->uri
.path
);
1624 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
));
1625 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host
->docroot
));
1627 buffer_copy_buffer(p
->path
, con
->physical
.path
);
1629 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
));
1630 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con
->physical
.basedir
));
1632 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con
->request
.orig_uri
));
1633 if (!buffer_is_equal(con
->request
.uri
, con
->request
.orig_uri
)) {
1634 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con
->request
.uri
));
1636 if (!buffer_string_is_empty(con
->uri
.query
)) {
1637 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con
->uri
.query
));
1639 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN(""));
1642 s
= get_http_method_name(con
->request
.http_method
);
1644 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_METHOD"), s
, strlen(s
));
1645 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")); /* if php is compiled with --force-redirect */
1646 s
= get_http_version_name(con
->request
.http_version
);
1648 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_PROTOCOL"), s
, strlen(s
));
1651 if (buffer_is_equal_caseless_string(con
->uri
.scheme
, CONST_STR_LEN("https"))) {
1652 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1656 scgi_env_add_request_headers(srv
, con
, p
);
1660 buffer_append_int(b
, buffer_string_length(p
->scgi_env
));
1661 buffer_append_string_len(b
, CONST_STR_LEN(":"));
1662 buffer_append_string_buffer(b
, p
->scgi_env
);
1663 buffer_append_string_len(b
, CONST_STR_LEN(","));
1665 chunkqueue_append_buffer(hctx
->wb
, b
);
1668 if (con
->request
.content_length
) {
1669 chunkqueue
*req_cq
= con
->request_content_queue
;
1671 chunkqueue_steal(hctx
->wb
, req_cq
, req_cq
->bytes_in
);
1677 static int scgi_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
, int eol
) {
1684 buffer_copy_buffer(p
->parse_response
, in
);
1686 for (s
= p
->parse_response
->ptr
;
1687 NULL
!= (ns
= (eol
== EOL_RN
? strstr(s
, "\r\n") : strchr(s
, '\n')));
1688 s
= ns
+ (eol
== EOL_RN
? 2 : 1), line
++) {
1689 const char *key
, *value
;
1696 0 == strncmp(s
, "HTTP/1.", 7)) {
1697 /* non-parsed header ... we parse them anyway */
1703 /* after the space should be a status code for us */
1705 status
= strtol(s
+9, NULL
, 10);
1707 if (status
>= 100 && status
< 1000) {
1708 /* we expected 3 digits got them */
1709 con
->parsed_response
|= HTTP_STATUS
;
1710 con
->http_status
= status
;
1716 if (NULL
== (value
= strchr(s
, ':'))) {
1717 /* we expect: "<key>: <value>\r\n" */
1721 key_len
= value
- key
;
1725 while (*value
== ' ' || *value
== '\t') value
++;
1727 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
1728 ds
= data_response_init();
1730 buffer_copy_string_len(ds
->key
, key
, key_len
);
1731 buffer_copy_string(ds
->value
, value
);
1733 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
1737 if (0 == strncasecmp(key
, "Date", key_len
)) {
1738 con
->parsed_response
|= HTTP_DATE
;
1742 if (0 == strncasecmp(key
, "Status", key_len
)) {
1743 int status
= strtol(value
, NULL
, 10);
1744 if (status
>= 100 && status
< 1000) {
1745 con
->http_status
= status
;
1746 con
->parsed_response
|= HTTP_STATUS
;
1748 con
->http_status
= 502;
1753 if (0 == strncasecmp(key
, "Location", key_len
)) {
1754 con
->parsed_response
|= HTTP_LOCATION
;
1758 if (0 == strncasecmp(key
, "Connection", key_len
)) {
1759 con
->response
.keep_alive
= (0 == strcasecmp(value
, "Keep-Alive")) ? 1 : 0;
1760 con
->parsed_response
|= HTTP_CONNECTION
;
1764 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
1765 con
->response
.content_length
= strtoul(value
, NULL
, 10);
1766 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
1775 /* CGI/1.1 rev 03 - 7.2.1.2 */
1776 if ((con
->parsed_response
& HTTP_LOCATION
) &&
1777 !(con
->parsed_response
& HTTP_STATUS
)) {
1778 con
->http_status
= 302;
1785 static int scgi_demux_response(server
*srv
, handler_ctx
*hctx
) {
1786 plugin_data
*p
= hctx
->plugin_data
;
1787 connection
*con
= hctx
->remote_conn
;
1792 buffer_string_prepare_copy(hctx
->response
, 1023);
1793 if (-1 == (n
= read(hctx
->fd
, hctx
->response
->ptr
, hctx
->response
->size
- 1))) {
1794 if (errno
== EAGAIN
|| errno
== EINTR
) {
1795 /* would block, wait for signal */
1799 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", strerror(errno
), con
->fd
, hctx
->fd
);
1806 con
->file_finished
= 1;
1808 /* send final chunk */
1809 http_chunk_close(srv
, con
);
1810 joblist_append(srv
, con
);
1815 buffer_commit(hctx
->response
, n
);
1817 /* split header from body */
1819 if (con
->file_started
== 0) {
1823 int cp
, eol
= EOL_UNSET
;
1827 buffer_append_string_buffer(hctx
->response_header
, hctx
->response
);
1829 /* nph (non-parsed headers) */
1830 if (0 == strncmp(hctx
->response_header
->ptr
, "HTTP/1.", 7)) in_header
= 1;
1832 /* search for the \r\n\r\n or \n\n in the string */
1833 for (c
= hctx
->response_header
->ptr
, cp
= 0, used
= buffer_string_length(hctx
->response_header
); used
; c
++, cp
++, used
--) {
1834 if (*c
== ':') in_header
= 1;
1835 else if (*c
== '\n') {
1836 if (in_header
== 0) {
1837 /* got a response without a response header */
1844 if (eol
== EOL_UNSET
) eol
= EOL_N
;
1846 if (*(c
+1) == '\n') {
1852 } else if (used
> 1 && *c
== '\r' && *(c
+1) == '\n') {
1853 if (in_header
== 0) {
1854 /* got a response without a response header */
1861 if (eol
== EOL_UNSET
) eol
= EOL_RN
;
1880 /* no header, but a body */
1882 if (con
->request
.http_version
== HTTP_VERSION_1_1
) {
1883 con
->response
.transfer_encoding
= HTTP_TRANSFER_ENCODING_CHUNKED
;
1886 http_chunk_append_buffer(srv
, con
, hctx
->response_header
);
1887 joblist_append(srv
, con
);
1889 size_t blen
= buffer_string_length(hctx
->response_header
) - hlen
;
1891 /* a small hack: terminate after at the second \r */
1892 buffer_string_set_length(hctx
->response_header
, hlen
- 1);
1894 /* parse the response header */
1895 scgi_response_parse(srv
, con
, p
, hctx
->response_header
, eol
);
1897 /* enable chunked-transfer-encoding */
1898 if (con
->request
.http_version
== HTTP_VERSION_1_1
&&
1899 !(con
->parsed_response
& HTTP_CONTENT_LENGTH
)) {
1900 con
->response
.transfer_encoding
= HTTP_TRANSFER_ENCODING_CHUNKED
;
1904 http_chunk_append_mem(srv
, con
, hctx
->response_header
->ptr
+ hlen
, blen
);
1905 joblist_append(srv
, con
);
1909 con
->file_started
= 1;
1912 http_chunk_append_buffer(srv
, con
, hctx
->response
);
1913 joblist_append(srv
, con
);
1917 log_error_write(srv
, __FILE__
, __LINE__
, "ddss", con
->fd
, hctx
->fd
, connection_get_state(con
->state
), b
->ptr
);
1925 static int scgi_proclist_sort_up(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
1930 /* we have been the smallest of the current list
1931 * and we want to insert the node sorted as soon
1941 /* nothing to sort, only one element */
1942 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
1944 for (p
= proc
; p
->next
&& p
->next
->load
< proc
->load
; p
= p
->next
);
1946 /* no need to move something
1954 if (p
== proc
) return 0;
1956 if (host
->first
== proc
) {
1957 /* we have been the first elememt */
1959 host
->first
= proc
->next
;
1960 host
->first
->prev
= NULL
;
1963 /* disconnect proc */
1965 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
1966 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
1968 /* proc should be right of p */
1970 proc
->next
= p
->next
;
1972 if (p
->next
) p
->next
->prev
= proc
;
1975 for(p
= host
->first
; p
; p
= p
->next
) {
1976 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
1986 int scgi_proclist_sort_down(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
1991 /* we have been the smallest of the current list
1992 * and we want to insert the node sorted as soon
2001 * the basic is idea is:
2002 * - the last active scgi process should be still
2003 * in ram and is not swapped out yet
2004 * - processes that are not reused will be killed
2005 * after some time by the trigger-handler
2007 * everything > 0 is hot
2008 * all unused procs are colder the more right they are
2009 * ice-cold processes are propably unused since more
2010 * than 'unused-timeout', are swaped out and won't be
2011 * reused in the next seconds anyway.
2015 /* nothing to sort, only one element */
2016 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
2018 for (p
= host
->first
; p
!= proc
&& p
->load
< proc
->load
; p
= p
->next
);
2021 /* no need to move something
2029 if (p
== proc
) return 0;
2031 /* we have to move left. If we are already the first element
2033 if (host
->first
== proc
) return 0;
2036 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
2037 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
2039 /* proc should be left of p */
2041 proc
->prev
= p
->prev
;
2042 if (p
->prev
) p
->prev
->next
= proc
;
2045 if (proc
->prev
== NULL
) host
->first
= proc
;
2047 for(p
= host
->first
; p
; p
= p
->next
) {
2048 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
2058 static int scgi_restart_dead_procs(server
*srv
, plugin_data
*p
, scgi_extension_host
*host
) {
2061 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2062 if (p
->conf
.debug
) {
2063 log_error_write(srv
, __FILE__
, __LINE__
, "sbdbdddd",
2065 host
->host
, proc
->port
,
2073 if (0 == proc
->is_local
) {
2075 * external servers might get disabled
2077 * enable the server again, perhaps it is back again
2080 if ((proc
->state
== PROC_STATE_DISABLED
) &&
2081 (srv
->cur_ts
- proc
->disable_ts
> host
->disable_time
)) {
2082 proc
->state
= PROC_STATE_RUNNING
;
2083 host
->active_procs
++;
2085 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2086 "fcgi-server re-enabled:",
2087 host
->host
, host
->port
,
2091 /* the child should not terminate at all */
2094 if (proc
->state
== PROC_STATE_DIED_WAIT_FOR_PID
) {
2095 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2097 /* child is still alive */
2102 if (WIFEXITED(status
)) {
2104 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2105 "child exited, pid:", proc
->pid
,
2106 "status:", WEXITSTATUS(status
));
2108 } else if (WIFSIGNALED(status
)) {
2109 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2113 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2114 "child died somehow:",
2118 proc
->state
= PROC_STATE_DIED
;
2124 * local servers might died, but we restart them
2127 if (proc
->state
== PROC_STATE_DIED
&&
2129 /* restart the child */
2131 if (p
->conf
.debug
) {
2132 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2133 "--- scgi spawning",
2134 "\n\tport:", host
->port
,
2135 "\n\tsocket", host
->unixsocket
,
2136 "\n\tcurrent:", 1, "/", host
->min_procs
);
2139 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2140 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2141 "ERROR: spawning fcgi failed.");
2142 return HANDLER_ERROR
;
2145 scgi_proclist_sort_down(srv
, host
, proc
);
2154 static handler_t
scgi_write_request(server
*srv
, handler_ctx
*hctx
) {
2155 plugin_data
*p
= hctx
->plugin_data
;
2156 scgi_extension_host
*host
= hctx
->host
;
2157 connection
*con
= hctx
->remote_conn
;
2163 log_error_write(srv
, __FILE__
, __LINE__
, "s", "fatal error: host = NULL");
2164 return HANDLER_ERROR
;
2166 if (((buffer_string_is_empty(host
->host
) || !host
->port
) && buffer_string_is_empty(host
->unixsocket
))) {
2167 log_error_write(srv
, __FILE__
, __LINE__
, "sxddd",
2170 buffer_string_length(host
->host
),
2172 buffer_string_length(host
->unixsocket
));
2173 return HANDLER_ERROR
;
2177 switch(hctx
->state
) {
2178 case FCGI_STATE_INIT
:
2179 ret
= buffer_string_is_empty(host
->unixsocket
) ? AF_INET
: AF_UNIX
;
2181 if (-1 == (hctx
->fd
= socket(ret
, SOCK_STREAM
, 0))) {
2182 if (errno
== EMFILE
||
2184 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2185 "wait for fd at connection:", con
->fd
);
2187 return HANDLER_WAIT_FOR_FD
;
2190 log_error_write(srv
, __FILE__
, __LINE__
, "ssdd",
2191 "socket failed:", strerror(errno
), srv
->cur_fds
, srv
->max_fds
);
2192 return HANDLER_ERROR
;
2198 fdevent_register(srv
->ev
, hctx
->fd
, scgi_handle_fdevent
, hctx
);
2200 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
2201 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2202 "fcntl failed: ", strerror(errno
));
2204 return HANDLER_ERROR
;
2208 case FCGI_STATE_CONNECT
:
2209 if (hctx
->state
== FCGI_STATE_INIT
) {
2210 for (hctx
->proc
= hctx
->host
->first
;
2211 hctx
->proc
&& hctx
->proc
->state
!= PROC_STATE_RUNNING
;
2212 hctx
->proc
= hctx
->proc
->next
);
2214 /* all childs are dead */
2215 if (hctx
->proc
== NULL
) {
2218 return HANDLER_ERROR
;
2221 if (hctx
->proc
->is_local
) {
2222 hctx
->pid
= hctx
->proc
->pid
;
2225 switch (scgi_establish_connection(srv
, hctx
)) {
2227 scgi_set_state(srv
, hctx
, FCGI_STATE_CONNECT
);
2229 /* connection is in progress, wait for an event and call getsockopt() below */
2231 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2233 return HANDLER_WAIT_FOR_EVENT
;
2235 /* if ECONNREFUSED choose another connection -> FIXME */
2238 return HANDLER_ERROR
;
2240 /* everything is ok, go on */
2247 socklen_t socket_error_len
= sizeof(socket_error
);
2249 /* try to finish the connect() */
2250 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
2251 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2252 "getsockopt failed:", strerror(errno
));
2254 return HANDLER_ERROR
;
2256 if (socket_error
!= 0) {
2257 if (!hctx
->proc
->is_local
|| p
->conf
.debug
) {
2258 /* local procs get restarted */
2260 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2261 "establishing connection failed:", strerror(socket_error
),
2262 "port:", hctx
->proc
->port
);
2265 return HANDLER_ERROR
;
2269 /* ok, we have the connection */
2272 hctx
->proc
->last_used
= srv
->cur_ts
;
2275 if (p
->conf
.debug
) {
2276 log_error_write(srv
, __FILE__
, __LINE__
, "sddbdd",
2285 /* move the proc-list entry down the list */
2286 scgi_proclist_sort_up(srv
, hctx
->host
, hctx
->proc
);
2288 scgi_set_state(srv
, hctx
, FCGI_STATE_PREPARE_WRITE
);
2290 case FCGI_STATE_PREPARE_WRITE
:
2291 scgi_create_env(srv
, hctx
);
2293 scgi_set_state(srv
, hctx
, FCGI_STATE_WRITE
);
2296 case FCGI_STATE_WRITE
:
2297 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
2299 chunkqueue_remove_finished_chunks(hctx
->wb
);
2302 if (errno
== ENOTCONN
|| ret
== -2) {
2303 /* the connection got dropped after accept()
2305 * this is most of the time a PHP which dies
2306 * after PHP_FCGI_MAX_REQUESTS
2309 if (hctx
->wb
->bytes_out
== 0 &&
2310 hctx
->reconnects
< 5) {
2311 usleep(10000); /* take away the load of the webserver
2312 * to let the php a chance to restart
2315 scgi_reconnect(srv
, hctx
);
2317 return HANDLER_WAIT_FOR_FD
;
2320 /* not reconnected ... why
2322 * far@#lighttpd report this for FreeBSD
2326 log_error_write(srv
, __FILE__
, __LINE__
, "ssosd",
2327 "connection was dropped after accept(). reconnect() denied:",
2328 "write-offset:", hctx
->wb
->bytes_out
,
2329 "reconnect attempts:", hctx
->reconnects
);
2331 return HANDLER_ERROR
;
2333 /* -1 == ret => error on our side */
2334 log_error_write(srv
, __FILE__
, __LINE__
, "ssd",
2335 "write failed:", strerror(errno
), errno
);
2337 return HANDLER_ERROR
;
2341 if (hctx
->wb
->bytes_out
== hctx
->wb
->bytes_in
) {
2342 /* we don't need the out event anymore */
2343 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
2344 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2345 scgi_set_state(srv
, hctx
, FCGI_STATE_READ
);
2347 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2349 return HANDLER_WAIT_FOR_EVENT
;
2353 case FCGI_STATE_READ
:
2354 /* waiting for a response */
2357 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
2358 return HANDLER_ERROR
;
2361 return HANDLER_WAIT_FOR_EVENT
;
2364 SUBREQUEST_FUNC(mod_scgi_handle_subrequest
) {
2365 plugin_data
*p
= p_d
;
2367 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2369 scgi_extension_host
*host
;
2371 if (NULL
== hctx
) return HANDLER_GO_ON
;
2374 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
2376 /* ok, create the request */
2377 switch(scgi_write_request(srv
, hctx
)) {
2383 0 == proc
->is_local
&&
2384 proc
->state
!= PROC_STATE_DISABLED
) {
2385 /* only disable remote servers as we don't manage them*/
2387 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "fcgi-server disabled:",
2392 /* disable this server */
2393 proc
->disable_ts
= srv
->cur_ts
;
2394 proc
->state
= PROC_STATE_DISABLED
;
2395 host
->active_procs
--;
2398 if (hctx
->state
== FCGI_STATE_INIT
||
2399 hctx
->state
== FCGI_STATE_CONNECT
) {
2400 /* connect() or getsockopt() failed,
2401 * restart the request-handling
2403 if (proc
&& proc
->is_local
) {
2405 if (p
->conf
.debug
) {
2406 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "connect() to scgi failed, restarting the request-handling:",
2413 * several hctx might reference the same proc
2415 * Only one of them should mark the proc as dead all the other
2416 * ones should just take a new one.
2418 * If a new proc was started with the old struct this might lead
2419 * the mark a perfect proc as dead otherwise
2422 if (proc
->state
== PROC_STATE_RUNNING
&&
2423 hctx
->pid
== proc
->pid
) {
2424 proc
->state
= PROC_STATE_DIED_WAIT_FOR_PID
;
2427 scgi_restart_dead_procs(srv
, p
, host
);
2429 scgi_connection_cleanup(srv
, hctx
);
2431 buffer_reset(con
->physical
.path
);
2433 joblist_append(srv
, con
);
2435 /* mis-using HANDLER_WAIT_FOR_FD to break out of the loop
2436 * and hope that the childs will be restarted
2439 return HANDLER_WAIT_FOR_FD
;
2441 scgi_connection_cleanup(srv
, hctx
);
2443 buffer_reset(con
->physical
.path
);
2445 con
->http_status
= 503;
2447 return HANDLER_FINISHED
;
2449 case HANDLER_WAIT_FOR_EVENT
:
2450 if (con
->file_started
== 1) {
2451 return HANDLER_FINISHED
;
2453 return HANDLER_WAIT_FOR_EVENT
;
2455 case HANDLER_WAIT_FOR_FD
:
2456 return HANDLER_WAIT_FOR_FD
;
2458 log_error_write(srv
, __FILE__
, __LINE__
, "s", "subrequest write-req default");
2459 return HANDLER_ERROR
;
2463 static handler_t
scgi_connection_close(server
*srv
, handler_ctx
*hctx
) {
2466 if (NULL
== hctx
) return HANDLER_GO_ON
;
2468 con
= hctx
->remote_conn
;
2470 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2471 "emergency exit: scgi:",
2472 "connection-fd:", con
->fd
,
2473 "fcgi-fd:", hctx
->fd
);
2475 scgi_connection_cleanup(srv
, hctx
);
2477 return HANDLER_FINISHED
;
2481 static handler_t
scgi_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
2482 handler_ctx
*hctx
= ctx
;
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 ((revents
& FDEVENT_IN
) &&
2490 hctx
->state
== FCGI_STATE_READ
) {
2491 switch (scgi_demux_response(srv
, hctx
)) {
2496 scgi_connection_cleanup(srv
, hctx
);
2498 joblist_append(srv
, con
);
2499 return HANDLER_FINISHED
;
2501 if (proc
->pid
&& proc
->state
!= PROC_STATE_DIED
) {
2504 /* only fetch the zombie if it is not already done */
2506 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2508 /* child is still alive */
2513 /* the child should not terminate at all */
2514 if (WIFEXITED(status
)) {
2515 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2516 "child exited, pid:", proc
->pid
,
2517 "status:", WEXITSTATUS(status
));
2518 } else if (WIFSIGNALED(status
)) {
2519 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2523 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2524 "child died somehow:",
2528 if (p
->conf
.debug
) {
2529 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2530 "--- scgi spawning",
2531 "\n\tport:", host
->port
,
2532 "\n\tsocket", host
->unixsocket
,
2533 "\n\tcurrent:", 1, "/", host
->min_procs
);
2536 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2538 proc
->state
= PROC_STATE_DIED
;
2540 scgi_proclist_sort_down(srv
, host
, proc
);
2547 if (con
->file_started
== 0) {
2548 /* nothing has been send out yet, try to use another child */
2550 if (hctx
->wb
->bytes_out
== 0 &&
2551 hctx
->reconnects
< 5) {
2552 scgi_reconnect(srv
, hctx
);
2554 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2555 "response not sent, request not sent, reconnection.",
2556 "connection-fd:", con
->fd
,
2557 "fcgi-fd:", hctx
->fd
);
2559 return HANDLER_WAIT_FOR_FD
;
2562 log_error_write(srv
, __FILE__
, __LINE__
, "sosdsd",
2563 "response not sent, request sent:", hctx
->wb
->bytes_out
,
2564 "connection-fd:", con
->fd
,
2565 "fcgi-fd:", hctx
->fd
);
2567 scgi_connection_cleanup(srv
, hctx
);
2569 connection_set_state(srv
, con
, CON_STATE_HANDLE_REQUEST
);
2570 buffer_reset(con
->physical
.path
);
2571 con
->http_status
= 500;
2574 /* response might have been already started, kill the connection */
2575 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2576 "response already sent out, termination connection",
2577 "connection-fd:", con
->fd
,
2578 "fcgi-fd:", hctx
->fd
);
2580 scgi_connection_cleanup(srv
, hctx
);
2582 connection_set_state(srv
, con
, CON_STATE_ERROR
);
2588 joblist_append(srv
, con
);
2589 return HANDLER_FINISHED
;
2593 if (revents
& FDEVENT_OUT
) {
2594 if (hctx
->state
== FCGI_STATE_CONNECT
||
2595 hctx
->state
== FCGI_STATE_WRITE
) {
2596 /* we are allowed to send something out
2598 * 1. in a unfinished connect() call
2599 * 2. in a unfinished write() call (long POST request)
2601 return mod_scgi_handle_subrequest(srv
, con
, p
);
2603 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2604 "got a FDEVENT_OUT and didn't know why:",
2609 /* perhaps this issue is already handled */
2610 if (revents
& FDEVENT_HUP
) {
2611 if (hctx
->state
== FCGI_STATE_CONNECT
) {
2612 /* getoptsock will catch this one (right ?)
2614 * if we are in connect we might get a EINPROGRESS
2615 * in the first call and a FDEVENT_HUP in the
2618 * FIXME: as it is a bit ugly.
2621 return mod_scgi_handle_subrequest(srv
, con
, p
);
2622 } else if (hctx
->state
== FCGI_STATE_READ
&&
2623 hctx
->proc
->port
== 0) {
2626 * ioctl says 8192 bytes to read from PHP and we receive directly a HUP for the socket
2627 * even if the FCGI_FIN packet is not received yet
2630 log_error_write(srv
, __FILE__
, __LINE__
, "sbSBSDSd",
2631 "error: unexpected close of scgi connection for",
2633 "(no scgi process on host: ",
2640 connection_set_state(srv
, con
, CON_STATE_ERROR
);
2641 scgi_connection_close(srv
, hctx
);
2642 joblist_append(srv
, con
);
2644 } else if (revents
& FDEVENT_ERR
) {
2645 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2646 "fcgi: got a FDEVENT_ERR. Don't know why.");
2647 /* kill all connections to the scgi process */
2650 connection_set_state(srv
, con
, CON_STATE_ERROR
);
2651 scgi_connection_close(srv
, hctx
);
2652 joblist_append(srv
, con
);
2655 return HANDLER_FINISHED
;
2659 static int scgi_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
2661 plugin_config
*s
= p
->config_storage
[0];
2666 /* skip the first, the global context */
2667 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
2668 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
2669 s
= p
->config_storage
[i
];
2671 /* condition didn't match */
2672 if (!config_check_cond(srv
, con
, dc
)) continue;
2675 for (j
= 0; j
< dc
->value
->used
; j
++) {
2676 data_unset
*du
= dc
->value
->data
[j
];
2678 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.server"))) {
2680 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.debug"))) {
2691 static handler_t
scgi_check_extension(server
*srv
, connection
*con
, void *p_d
, int uri_path_handler
) {
2692 plugin_data
*p
= p_d
;
2697 scgi_extension
*extension
= NULL
;
2698 scgi_extension_host
*host
= NULL
;
2700 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
2702 /* Possibly, we processed already this request */
2703 if (con
->file_started
== 1) return HANDLER_GO_ON
;
2705 fn
= uri_path_handler
? con
->uri
.path
: con
->physical
.path
;
2707 if (buffer_string_is_empty(fn
)) return HANDLER_GO_ON
;
2709 s_len
= buffer_string_length(fn
);
2711 scgi_patch_connection(srv
, con
, p
);
2713 /* check if extension matches */
2714 for (k
= 0; k
< p
->conf
.exts
->used
; k
++) {
2716 scgi_extension
*ext
= p
->conf
.exts
->exts
[k
];
2718 if (buffer_is_empty(ext
->key
)) continue;
2720 ct_len
= buffer_string_length(ext
->key
);
2722 if (s_len
< ct_len
) continue;
2724 /* check extension in the form "/scgi_pattern" */
2725 if (*(ext
->key
->ptr
) == '/') {
2726 if (strncmp(fn
->ptr
, ext
->key
->ptr
, ct_len
) == 0) {
2730 } else if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
)) {
2731 /* check extension in the form ".fcg" */
2737 /* extension doesn't match */
2738 if (NULL
== extension
) {
2739 return HANDLER_GO_ON
;
2742 /* get best server */
2743 for (k
= 0; k
< extension
->used
; k
++) {
2744 scgi_extension_host
*h
= extension
->hosts
[k
];
2746 /* we should have at least one proc that can do something */
2747 if (h
->active_procs
== 0) {
2751 if (used
== -1 || h
->load
< used
) {
2759 /* sorry, we don't have a server alive for this ext */
2760 buffer_reset(con
->physical
.path
);
2761 con
->http_status
= 500;
2763 /* only send the 'no handler' once */
2764 if (!extension
->note_is_sent
) {
2765 extension
->note_is_sent
= 1;
2767 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbs",
2768 "all handlers for ", con
->uri
.path
,
2769 "on", extension
->key
,
2773 return HANDLER_FINISHED
;
2776 /* a note about no handler is not sent yet */
2777 extension
->note_is_sent
= 0;
2780 * if check-local is disabled, use the uri.path handler
2784 /* init handler-context */
2785 if (uri_path_handler
) {
2786 if (host
->check_local
== 0) {
2790 hctx
= handler_ctx_init();
2792 hctx
->remote_conn
= con
;
2793 hctx
->plugin_data
= p
;
2797 hctx
->conf
.exts
= p
->conf
.exts
;
2798 hctx
->conf
.debug
= p
->conf
.debug
;
2800 con
->plugin_ctx
[p
->id
] = hctx
;
2806 if (con
->conf
.log_request_handling
) {
2807 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2808 "handling it in mod_scgi");
2811 /* the prefix is the SCRIPT_NAME,
2812 * everything from start to the next slash
2813 * this is important for check-local = "disable"
2815 * if prefix = /admin.fcgi
2817 * /admin.fcgi/foo/bar
2819 * SCRIPT_NAME = /admin.fcgi
2820 * PATH_INFO = /foo/bar
2822 * if prefix = /fcgi-bin/
2826 * SCRIPT_NAME = /fcgi-bin/foo
2831 /* the rewrite is only done for /prefix/? matches */
2832 if (host
->fix_root_path_name
&& extension
->key
->ptr
[0] == '/' && extension
->key
->ptr
[1] == '\0') {
2833 buffer_copy_string(con
->request
.pathinfo
, con
->uri
.path
->ptr
);
2834 buffer_string_set_length(con
->uri
.path
, 0);
2835 } else if (extension
->key
->ptr
[0] == '/' &&
2836 buffer_string_length(con
->uri
.path
) > buffer_string_length(extension
->key
) &&
2837 NULL
!= (pathinfo
= strchr(con
->uri
.path
->ptr
+ buffer_string_length(extension
->key
), '/'))) {
2838 /* rewrite uri.path and pathinfo */
2840 buffer_copy_string(con
->request
.pathinfo
, pathinfo
);
2841 buffer_string_set_length(con
->uri
.path
, buffer_string_length(con
->uri
.path
) - buffer_string_length(con
->request
.pathinfo
));
2846 hctx
= handler_ctx_init();
2848 hctx
->remote_conn
= con
;
2849 hctx
->plugin_data
= p
;
2853 hctx
->conf
.exts
= p
->conf
.exts
;
2854 hctx
->conf
.debug
= p
->conf
.debug
;
2856 con
->plugin_ctx
[p
->id
] = hctx
;
2862 if (con
->conf
.log_request_handling
) {
2863 log_error_write(srv
, __FILE__
, __LINE__
, "s", "handling it in mod_scgi");
2867 return HANDLER_GO_ON
;
2870 /* uri-path handler */
2871 static handler_t
scgi_check_extension_1(server
*srv
, connection
*con
, void *p_d
) {
2872 return scgi_check_extension(srv
, con
, p_d
, 1);
2875 /* start request handler */
2876 static handler_t
scgi_check_extension_2(server
*srv
, connection
*con
, void *p_d
) {
2877 return scgi_check_extension(srv
, con
, p_d
, 0);
2880 JOBLIST_FUNC(mod_scgi_handle_joblist
) {
2881 plugin_data
*p
= p_d
;
2882 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2884 if (hctx
== NULL
) return HANDLER_GO_ON
;
2886 if (hctx
->fd
!= -1) {
2887 switch (hctx
->state
) {
2888 case FCGI_STATE_READ
:
2889 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2892 case FCGI_STATE_CONNECT
:
2893 case FCGI_STATE_WRITE
:
2894 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2897 case FCGI_STATE_INIT
:
2901 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "unhandled fcgi.state", hctx
->state
);
2906 return HANDLER_GO_ON
;
2910 static handler_t
scgi_connection_close_callback(server
*srv
, connection
*con
, void *p_d
) {
2911 plugin_data
*p
= p_d
;
2913 return scgi_connection_close(srv
, con
->plugin_ctx
[p
->id
]);
2916 TRIGGER_FUNC(mod_scgi_handle_trigger
) {
2917 plugin_data
*p
= p_d
;
2921 /* perhaps we should kill a connect attempt after 10-15 seconds
2923 * currently we wait for the TCP timeout which is on Linux 180 seconds
2929 /* check all childs if they are still up */
2931 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
2932 plugin_config
*conf
;
2935 conf
= p
->config_storage
[i
];
2939 for (j
= 0; j
< exts
->used
; j
++) {
2944 for (n
= 0; n
< ex
->used
; n
++) {
2947 unsigned long sum_load
= 0;
2948 scgi_extension_host
*host
;
2950 host
= ex
->hosts
[n
];
2952 scgi_restart_dead_procs(srv
, p
, host
);
2954 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2955 sum_load
+= proc
->load
;
2958 if (host
->num_procs
&&
2959 host
->num_procs
< host
->max_procs
&&
2960 (sum_load
/ host
->num_procs
) > host
->max_load_per_proc
) {
2961 /* overload, spawn new child */
2962 scgi_proc
*fp
= NULL
;
2964 if (p
->conf
.debug
) {
2965 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2966 "overload detected, spawning a new child");
2969 for (fp
= host
->unused_procs
; fp
&& fp
->pid
!= 0; fp
= fp
->next
);
2972 if (fp
== host
->unused_procs
) host
->unused_procs
= fp
->next
;
2974 if (fp
->next
) fp
->next
->prev
= NULL
;
2978 fp
= scgi_process_init();
2979 fp
->id
= host
->max_id
++;
2984 if (buffer_string_is_empty(host
->unixsocket
)) {
2985 fp
->port
= host
->port
+ fp
->id
;
2987 buffer_copy_buffer(fp
->socket
, host
->unixsocket
);
2988 buffer_append_string_len(fp
->socket
, CONST_STR_LEN("-"));
2989 buffer_append_int(fp
->socket
, fp
->id
);
2992 if (scgi_spawn_connection(srv
, p
, host
, fp
)) {
2993 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2994 "ERROR: spawning fcgi failed.");
2995 scgi_process_free(fp
);
2996 return HANDLER_ERROR
;
3000 fp
->next
= host
->first
;
3002 host
->first
->prev
= fp
;
3007 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
3008 if (proc
->load
!= 0) break;
3009 if (host
->num_procs
<= host
->min_procs
) break;
3010 if (proc
->pid
== 0) continue;
3012 if (srv
->cur_ts
- proc
->last_used
> host
->idle_timeout
) {
3013 /* a proc is idling for a long time now,
3016 if (p
->conf
.debug
) {
3017 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
3018 "idle-timeout reached, terminating child:",
3019 "socket:", proc
->socket
,
3024 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
3025 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
3027 if (proc
->prev
== NULL
) host
->first
= proc
->next
;
3030 proc
->next
= host
->unused_procs
;
3032 if (host
->unused_procs
) host
->unused_procs
->prev
= proc
;
3033 host
->unused_procs
= proc
;
3035 kill(proc
->pid
, SIGTERM
);
3037 proc
->state
= PROC_STATE_KILLED
;
3039 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
3041 "socket:", proc
->socket
,
3046 /* proc is now in unused, let the next second handle the next process */
3051 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
3054 if (proc
->pid
== 0) continue;
3056 switch (waitpid(proc
->pid
, &status
, WNOHANG
)) {
3058 /* child still running after timeout, good */
3061 if (errno
!= EINTR
) {
3062 /* no PID found ? should never happen */
3063 log_error_write(srv
, __FILE__
, __LINE__
, "sddss",
3064 "pid ", proc
->pid
, proc
->state
,
3065 "not found:", strerror(errno
));
3068 if (errno
== ECHILD
) {
3069 /* someone else has cleaned up for us */
3071 proc
->state
= PROC_STATE_UNSET
;
3077 /* the child should not terminate at all */
3078 if (WIFEXITED(status
)) {
3079 if (proc
->state
!= PROC_STATE_KILLED
) {
3080 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
3082 WEXITSTATUS(status
), proc
->socket
);
3084 } else if (WIFSIGNALED(status
)) {
3085 if (WTERMSIG(status
) != SIGTERM
) {
3086 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3091 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3092 "child died somehow:",
3096 proc
->state
= PROC_STATE_UNSET
;
3104 return HANDLER_GO_ON
;
3108 int mod_scgi_plugin_init(plugin
*p
);
3109 int mod_scgi_plugin_init(plugin
*p
) {
3110 p
->version
= LIGHTTPD_VERSION_ID
;
3111 p
->name
= buffer_init_string("scgi");
3113 p
->init
= mod_scgi_init
;
3114 p
->cleanup
= mod_scgi_free
;
3115 p
->set_defaults
= mod_scgi_set_defaults
;
3116 p
->connection_reset
= scgi_connection_reset
;
3117 p
->handle_connection_close
= scgi_connection_close_callback
;
3118 p
->handle_uri_clean
= scgi_check_extension_1
;
3119 p
->handle_subrequest_start
= scgi_check_extension_2
;
3120 p
->handle_subrequest
= mod_scgi_handle_subrequest
;
3121 p
->handle_joblist
= mod_scgi_handle_joblist
;
3122 p
->handle_trigger
= mod_scgi_handle_trigger
;