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 */
228 } scgi_extension_host
;
231 * one extension can have multiple hosts assigned
232 * one host can spawn additional processes on the same
233 * socket (if we control it)
235 * ext -> host -> procs
238 * if the scgi process is remote that whole goes down
241 * ext -> host -> procs
244 * in case of PHP and FCGI_CHILDREN we have again a procs
245 * but we don't control it directly.
250 buffer
*key
; /* like .php */
253 scgi_extension_host
**hosts
;
260 scgi_extension
**exts
;
280 /* generic plugin data, shared between all connections */
287 buffer
*parse_response
;
289 plugin_config
**config_storage
;
291 plugin_config conf
; /* this is only used as long as no handler_ctx is setup */
294 /* connection specific data */
295 typedef enum { FCGI_STATE_INIT
, FCGI_STATE_CONNECT
, FCGI_STATE_PREPARE_WRITE
,
296 FCGI_STATE_WRITE
, FCGI_STATE_READ
297 } scgi_connection_state_t
;
303 int response_padding
;
306 scgi_extension_host
*host
;
308 scgi_connection_state_t state
;
309 time_t state_timestamp
;
311 int reconnects
; /* number of reconnect attempts */
315 buffer
*response_header
;
317 int delayed
; /* flag to mark that the connect() is delayed */
320 int fd
; /* fd to the scgi process */
321 int fde_ndx
; /* index into the fd-event buffer */
328 connection
*remote_conn
; /* dumb pointer */
329 plugin_data
*plugin_data
; /* dumb pointer */
333 /* ok, we need a prototype */
334 static handler_t
scgi_handle_fdevent(server
*srv
, void *ctx
, int revents
);
336 int scgi_proclist_sort_down(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
);
338 static void reset_signals(void) {
340 signal(SIGTTOU
, SIG_DFL
);
343 signal(SIGTTIN
, SIG_DFL
);
346 signal(SIGTSTP
, SIG_DFL
);
348 signal(SIGHUP
, SIG_DFL
);
349 signal(SIGPIPE
, SIG_DFL
);
350 signal(SIGUSR1
, SIG_DFL
);
353 static handler_ctx
* handler_ctx_init(void) {
356 hctx
= calloc(1, sizeof(*hctx
));
361 hctx
->response
= buffer_init();
362 hctx
->response_header
= buffer_init();
364 hctx
->request_id
= 0;
365 hctx
->state
= FCGI_STATE_INIT
;
368 hctx
->response_len
= 0;
369 hctx
->response_type
= 0;
370 hctx
->response_padding
= 0;
373 hctx
->reconnects
= 0;
375 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();
427 static void scgi_host_free(scgi_extension_host
*h
) {
430 buffer_free(h
->host
);
431 buffer_free(h
->unixsocket
);
432 buffer_free(h
->docroot
);
433 buffer_free(h
->bin_path
);
434 array_free(h
->bin_env
);
435 array_free(h
->bin_env_copy
);
437 scgi_process_free(h
->first
);
438 scgi_process_free(h
->unused_procs
);
444 static scgi_exts
*scgi_extensions_init(void) {
447 f
= calloc(1, sizeof(*f
));
453 static void scgi_extensions_free(scgi_exts
*f
) {
458 for (i
= 0; i
< f
->used
; i
++) {
464 for (j
= 0; j
< fe
->used
; j
++) {
465 scgi_extension_host
*h
;
472 buffer_free(fe
->key
);
483 static int scgi_extension_insert(scgi_exts
*ext
, buffer
*key
, scgi_extension_host
*fh
) {
487 /* there is something */
489 for (i
= 0; i
< ext
->used
; i
++) {
490 if (buffer_is_equal(key
, ext
->exts
[i
]->key
)) {
495 if (i
== ext
->used
) {
496 /* filextension is new */
497 fe
= calloc(1, sizeof(*fe
));
499 fe
->key
= buffer_init();
500 buffer_copy_buffer(fe
->key
, key
);
504 if (ext
->size
== 0) {
506 ext
->exts
= malloc(ext
->size
* sizeof(*(ext
->exts
)));
507 force_assert(ext
->exts
);
508 } else if (ext
->used
== ext
->size
) {
510 ext
->exts
= realloc(ext
->exts
, ext
->size
* sizeof(*(ext
->exts
)));
511 force_assert(ext
->exts
);
513 ext
->exts
[ext
->used
++] = fe
;
520 fe
->hosts
= malloc(fe
->size
* sizeof(*(fe
->hosts
)));
521 force_assert(fe
->hosts
);
522 } else if (fe
->size
== fe
->used
) {
524 fe
->hosts
= realloc(fe
->hosts
, fe
->size
* sizeof(*(fe
->hosts
)));
525 force_assert(fe
->hosts
);
528 fe
->hosts
[fe
->used
++] = fh
;
534 INIT_FUNC(mod_scgi_init
) {
537 p
= calloc(1, sizeof(*p
));
540 p
->scgi_env
= buffer_init();
542 p
->path
= buffer_init();
543 p
->parse_response
= buffer_init();
549 FREE_FUNC(mod_scgi_free
) {
550 plugin_data
*p
= p_d
;
554 buffer_free(p
->scgi_env
);
555 buffer_free(p
->path
);
556 buffer_free(p
->parse_response
);
558 if (p
->config_storage
) {
560 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
561 plugin_config
*s
= p
->config_storage
[i
];
564 if (NULL
== s
) continue;
568 for (j
= 0; j
< exts
->used
; j
++) {
573 for (n
= 0; n
< ex
->used
; n
++) {
575 scgi_extension_host
*host
;
579 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
580 if (proc
->pid
!= 0) kill(proc
->pid
, SIGTERM
);
582 if (proc
->is_local
&&
583 !buffer_string_is_empty(proc
->socket
)) {
584 unlink(proc
->socket
->ptr
);
588 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
589 if (proc
->pid
!= 0) kill(proc
->pid
, SIGTERM
);
591 if (proc
->is_local
&&
592 !buffer_string_is_empty(proc
->socket
)) {
593 unlink(proc
->socket
->ptr
);
599 scgi_extensions_free(s
->exts
);
603 free(p
->config_storage
);
608 return HANDLER_GO_ON
;
611 static int env_add(char_array
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
615 if (!key
|| !val
) return -1;
617 dst
= malloc(key_len
+ val_len
+ 3);
619 memcpy(dst
, key
, key_len
);
621 /* add the \0 from the value */
622 memcpy(dst
+ key_len
+ 1, val
, val_len
+ 1);
624 for (i
= 0; i
< env
->used
; i
++) {
625 if (0 == strncmp(dst
, env
->ptr
[i
], key_len
+ 1)) {
626 /* don't care about free as we are in a forked child which is going to exec(...) */
627 /* free(env->ptr[i]); */
633 if (env
->size
== 0) {
635 env
->ptr
= malloc(env
->size
* sizeof(*env
->ptr
));
636 force_assert(env
->ptr
);
637 } else if (env
->size
== env
->used
) {
639 env
->ptr
= realloc(env
->ptr
, env
->size
* sizeof(*env
->ptr
));
640 force_assert(env
->ptr
);
643 env
->ptr
[env
->used
++] = dst
;
648 #if !defined(HAVE_FORK)
649 static int scgi_spawn_connection(server
*srv
,
651 scgi_extension_host
*host
,
660 #else /* -> defined(HAVE_FORK) */
662 static int scgi_spawn_connection(server
*srv
,
664 scgi_extension_host
*host
,
667 int socket_type
, status
;
668 struct timeval tv
= { 0, 100 * 1000 };
670 struct sockaddr_un scgi_addr_un
;
672 struct sockaddr_in scgi_addr_in
;
673 struct sockaddr
*scgi_addr
;
678 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
679 "new proc, socket:", proc
->port
, proc
->socket
);
683 if (!buffer_string_is_empty(proc
->socket
)) {
685 memset(&scgi_addr_un
, 0, sizeof(scgi_addr_un
));
686 scgi_addr_un
.sun_family
= AF_UNIX
;
687 if (buffer_string_length(proc
->socket
) + 1 > sizeof(scgi_addr_un
.sun_path
)) {
688 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
689 "ERROR: Unix Domain socket filename too long:",
693 memcpy(scgi_addr_un
.sun_path
, proc
->socket
->ptr
, buffer_string_length(proc
->socket
) + 1);
696 servlen
= SUN_LEN(&scgi_addr_un
);
699 servlen
= buffer_string_length(proc
->socket
) + 1 + sizeof(scgi_addr_un
.sun_family
);
701 socket_type
= AF_UNIX
;
702 scgi_addr
= (struct sockaddr
*) &scgi_addr_un
;
704 log_error_write(srv
, __FILE__
, __LINE__
, "s",
705 "ERROR: Unix Domain sockets are not supported.");
709 memset(&scgi_addr_in
, 0, sizeof(scgi_addr_in
));
710 scgi_addr_in
.sin_family
= AF_INET
;
712 if (buffer_string_is_empty(host
->host
)) {
713 scgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
717 /* set a usefull default */
718 scgi_addr_in
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
721 if (NULL
== (he
= gethostbyname(host
->host
->ptr
))) {
722 log_error_write(srv
, __FILE__
, __LINE__
,
723 "sdb", "gethostbyname failed: ",
724 h_errno
, host
->host
);
728 if (he
->h_addrtype
!= AF_INET
) {
729 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-type != AF_INET: ", he
->h_addrtype
);
733 if (he
->h_length
!= sizeof(struct in_addr
)) {
734 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "addr-length != sizeof(in_addr): ", he
->h_length
);
738 memcpy(&(scgi_addr_in
.sin_addr
.s_addr
), he
->h_addr_list
[0], he
->h_length
);
741 scgi_addr_in
.sin_port
= htons(proc
->port
);
742 servlen
= sizeof(scgi_addr_in
);
744 socket_type
= AF_INET
;
745 scgi_addr
= (struct sockaddr
*) &scgi_addr_in
;
748 if (-1 == (scgi_fd
= socket(socket_type
, SOCK_STREAM
, 0))) {
749 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
750 "failed:", strerror(errno
));
754 if (-1 == connect(scgi_fd
, scgi_addr
, servlen
)) {
755 /* server is not up, spawn in */
759 if (!buffer_string_is_empty(proc
->socket
)) {
760 unlink(proc
->socket
->ptr
);
766 if (-1 == (scgi_fd
= socket(socket_type
, SOCK_STREAM
, 0))) {
767 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
768 "socket failed:", strerror(errno
));
773 if (setsockopt(scgi_fd
, SOL_SOCKET
, SO_REUSEADDR
, &val
, sizeof(val
)) < 0) {
774 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
775 "socketsockopt failed:", strerror(errno
));
781 if (-1 == bind(scgi_fd
, scgi_addr
, servlen
)) {
782 log_error_write(srv
, __FILE__
, __LINE__
, "sbds",
791 if (-1 == listen(scgi_fd
, host
->listen_backlog
)) {
792 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
793 "listen failed:", strerror(errno
));
798 switch ((child
= fork())) {
806 /* create environment */
816 /* we don't need the client socket */
817 for (fd
= 3; fd
< 256; fd
++) {
821 /* build clean environment */
822 if (host
->bin_env_copy
->used
) {
823 for (i
= 0; i
< host
->bin_env_copy
->used
; i
++) {
824 data_string
*ds
= (data_string
*)host
->bin_env_copy
->data
[i
];
827 if (NULL
!= (ge
= getenv(ds
->value
->ptr
))) {
828 env_add(&env
, CONST_BUF_LEN(ds
->value
), ge
, strlen(ge
));
832 for (i
= 0; environ
[i
]; i
++) {
835 if (NULL
!= (eq
= strchr(environ
[i
], '='))) {
836 env_add(&env
, environ
[i
], eq
- environ
[i
], eq
+1, strlen(eq
+1));
841 /* create environment */
842 for (i
= 0; i
< host
->bin_env
->used
; i
++) {
843 data_string
*ds
= (data_string
*)host
->bin_env
->data
[i
];
845 env_add(&env
, CONST_BUF_LEN(ds
->key
), CONST_BUF_LEN(ds
->value
));
848 for (i
= 0; i
< env
.used
; i
++) {
849 /* search for PHP_FCGI_CHILDREN */
850 if (0 == strncmp(env
.ptr
[i
], "PHP_FCGI_CHILDREN=", sizeof("PHP_FCGI_CHILDREN=") - 1)) break;
853 /* not found, add a default */
855 env_add(&env
, CONST_STR_LEN("PHP_FCGI_CHILDREN"), CONST_STR_LEN("1"));
858 env
.ptr
[env
.used
] = NULL
;
861 buffer_copy_string_len(b
, CONST_STR_LEN("exec "));
862 buffer_append_string_buffer(b
, host
->bin_path
);
867 execle("/bin/sh", "sh", "-c", b
->ptr
, (char *)NULL
, env
.ptr
);
869 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
870 "execl failed for:", host
->bin_path
, strerror(errno
));
885 select(0, NULL
, NULL
, NULL
, &tv
);
887 switch (waitpid(child
, &status
, WNOHANG
)) {
889 /* child still running after timeout, good */
892 /* no PID found ? should never happen */
893 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
894 "pid not found:", strerror(errno
));
897 /* the child should not terminate at all */
898 if (WIFEXITED(status
)) {
899 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
900 "child exited (is this a SCGI binary ?):",
901 WEXITSTATUS(status
));
902 } else if (WIFSIGNALED(status
)) {
903 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
907 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
908 "child died somehow:",
914 /* register process */
916 proc
->last_used
= srv
->cur_ts
;
928 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
929 "(debug) socket is already used, won't spawn:",
934 proc
->state
= PROC_STATE_RUNNING
;
935 host
->active_procs
++;
940 #endif /* HAVE_FORK */
942 static int unixsocket_is_dup(plugin_data
*p
, size_t used
, buffer
*unixsocket
) {
944 for (i
= 0; i
< used
; ++i
) {
945 scgi_exts
*exts
= p
->config_storage
[i
]->exts
;
946 for (j
= 0; j
< exts
->used
; ++j
) {
947 scgi_extension
*ex
= exts
->exts
[j
];
948 for (n
= 0; n
< ex
->used
; ++n
) {
949 scgi_extension_host
*host
= ex
->hosts
[n
];
950 if (!buffer_string_is_empty(host
->unixsocket
)
951 && buffer_is_equal(host
->unixsocket
, unixsocket
))
960 SETDEFAULTS_FUNC(mod_scgi_set_defaults
) {
961 plugin_data
*p
= p_d
;
964 scgi_extension_host
*df
= NULL
;
966 config_values_t cv
[] = {
967 { "scgi.server", NULL
, T_CONFIG_LOCAL
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
968 { "scgi.debug", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
969 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
972 p
->config_storage
= calloc(1, srv
->config_context
->used
* sizeof(plugin_config
*));
973 force_assert(p
->config_storage
);
975 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
976 data_config
const* config
= (data_config
const*)srv
->config_context
->data
[i
];
979 s
= malloc(sizeof(plugin_config
));
981 s
->exts
= scgi_extensions_init();
984 cv
[0].destination
= s
->exts
;
985 cv
[1].destination
= &(s
->debug
);
987 p
->config_storage
[i
] = s
;
989 if (0 != config_insert_values_global(srv
, config
->value
, cv
, i
== 0 ? T_CONFIG_SCOPE_SERVER
: T_CONFIG_SCOPE_CONNECTION
)) {
997 if (NULL
!= (du
= array_get_element(config
->value
, "scgi.server"))) {
999 data_array
*da
= (data_array
*)du
;
1001 if (du
->type
!= TYPE_ARRAY
) {
1002 log_error_write(srv
, __FILE__
, __LINE__
, "sss",
1003 "unexpected type for key: ", "scgi.server", "array of strings");
1010 * scgi.server = ( "<ext>" => ( ... ),
1011 * "<ext>" => ( ... ) )
1014 for (j
= 0; j
< da
->value
->used
; j
++) {
1016 data_array
*da_ext
= (data_array
*)da
->value
->data
[j
];
1018 if (da
->value
->data
[j
]->type
!= TYPE_ARRAY
) {
1019 log_error_write(srv
, __FILE__
, __LINE__
, "sssbs",
1020 "unexpected type for key: ", "scgi.server",
1021 "[", da
->value
->data
[j
]->key
, "](string)");
1027 * da_ext->key == name of the extension
1031 * scgi.server = ( "<ext>" =>
1032 * ( "<host>" => ( ... ),
1033 * "<host>" => ( ... )
1038 for (n
= 0; n
< da_ext
->value
->used
; n
++) {
1039 data_array
*da_host
= (data_array
*)da_ext
->value
->data
[n
];
1041 config_values_t fcv
[] = {
1042 { "host", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 0 */
1043 { "docroot", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 1 */
1044 { "socket", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 2 */
1045 { "bin-path", NULL
, T_CONFIG_STRING
, T_CONFIG_SCOPE_CONNECTION
}, /* 3 */
1047 { "check-local", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 4 */
1048 { "port", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 5 */
1049 { "min-procs-not-working", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 this is broken for now */
1050 { "max-procs", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 7 */
1051 { "max-load-per-proc", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 8 */
1052 { "idle-timeout", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 9 */
1053 { "disable-time", NULL
, T_CONFIG_SHORT
, T_CONFIG_SCOPE_CONNECTION
}, /* 10 */
1055 { "bin-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 11 */
1056 { "bin-copy-environment", NULL
, T_CONFIG_ARRAY
, T_CONFIG_SCOPE_CONNECTION
}, /* 12 */
1057 { "fix-root-scriptname", NULL
, T_CONFIG_BOOLEAN
, T_CONFIG_SCOPE_CONNECTION
}, /* 13 */
1058 { "listen-backlog", NULL
, T_CONFIG_INT
, T_CONFIG_SCOPE_CONNECTION
}, /* 14 */
1061 { NULL
, NULL
, T_CONFIG_UNSET
, T_CONFIG_SCOPE_UNSET
}
1064 if (da_host
->type
!= TYPE_ARRAY
) {
1065 log_error_write(srv
, __FILE__
, __LINE__
, "ssSBS",
1066 "unexpected type for key:",
1068 "[", da_host
->key
, "](string)");
1073 df
= scgi_host_init();
1075 df
->check_local
= 1;
1078 df
->max_load_per_proc
= 1;
1079 df
->idle_timeout
= 60;
1080 df
->disable_time
= 60;
1081 df
->fix_root_path_name
= 0;
1082 df
->listen_backlog
= 1024;
1084 fcv
[0].destination
= df
->host
;
1085 fcv
[1].destination
= df
->docroot
;
1086 fcv
[2].destination
= df
->unixsocket
;
1087 fcv
[3].destination
= df
->bin_path
;
1089 fcv
[4].destination
= &(df
->check_local
);
1090 fcv
[5].destination
= &(df
->port
);
1091 fcv
[6].destination
= &(df
->min_procs
);
1092 fcv
[7].destination
= &(df
->max_procs
);
1093 fcv
[8].destination
= &(df
->max_load_per_proc
);
1094 fcv
[9].destination
= &(df
->idle_timeout
);
1095 fcv
[10].destination
= &(df
->disable_time
);
1097 fcv
[11].destination
= df
->bin_env
;
1098 fcv
[12].destination
= df
->bin_env_copy
;
1099 fcv
[13].destination
= &(df
->fix_root_path_name
);
1100 fcv
[14].destination
= &(df
->listen_backlog
);
1103 if (0 != config_insert_values_internal(srv
, da_host
->value
, fcv
, T_CONFIG_SCOPE_CONNECTION
)) {
1107 if ((!buffer_string_is_empty(df
->host
) || df
->port
) &&
1108 !buffer_string_is_empty(df
->unixsocket
)) {
1109 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1110 "either host+port or socket");
1115 if (!buffer_string_is_empty(df
->unixsocket
)) {
1116 /* unix domain socket */
1117 struct sockaddr_un un
;
1119 if (buffer_string_length(df
->unixsocket
) + 1 > sizeof(un
.sun_path
) - 2) {
1120 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1121 "path of the unixdomain socket is too large");
1125 if (!buffer_string_is_empty(df
->bin_path
)
1126 && unixsocket_is_dup(p
, i
+1, df
->unixsocket
)) {
1127 log_error_write(srv
, __FILE__
, __LINE__
, "sb",
1128 "duplicate unixsocket path:",
1135 if (buffer_string_is_empty(df
->host
) &&
1136 buffer_string_is_empty(df
->bin_path
)) {
1137 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbs",
1138 "missing key (string):",
1145 } else if (df
->port
== 0) {
1146 log_error_write(srv
, __FILE__
, __LINE__
, "sbbbs",
1147 "missing key (short):",
1156 if (!buffer_string_is_empty(df
->bin_path
)) {
1157 /* a local socket + self spawning */
1160 /* HACK: just to make sure the adaptive spawing is disabled */
1161 df
->min_procs
= df
->max_procs
;
1163 if (df
->min_procs
> df
->max_procs
) df
->max_procs
= df
->min_procs
;
1164 if (df
->max_load_per_proc
< 1) df
->max_load_per_proc
= 0;
1167 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsdsbsdsd",
1168 "--- scgi spawning local",
1169 "\n\tproc:", df
->bin_path
,
1170 "\n\tport:", df
->port
,
1171 "\n\tsocket", df
->unixsocket
,
1172 "\n\tmin-procs:", df
->min_procs
,
1173 "\n\tmax-procs:", df
->max_procs
);
1176 for (pno
= 0; pno
< df
->min_procs
; pno
++) {
1179 proc
= scgi_process_init();
1180 proc
->id
= df
->num_procs
++;
1183 if (buffer_string_is_empty(df
->unixsocket
)) {
1184 proc
->port
= df
->port
+ pno
;
1186 buffer_copy_buffer(proc
->socket
, df
->unixsocket
);
1187 buffer_append_string_len(proc
->socket
, CONST_STR_LEN("-"));
1188 buffer_append_int(proc
->socket
, pno
);
1192 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
1193 "--- scgi spawning",
1194 "\n\tport:", df
->port
,
1195 "\n\tsocket", df
->unixsocket
,
1196 "\n\tcurrent:", pno
, "/", df
->min_procs
);
1199 if (!srv
->srvconf
.preflight_check
1200 && scgi_spawn_connection(srv
, p
, df
, proc
)) {
1201 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1202 "[ERROR]: spawning fcgi failed.");
1203 scgi_process_free(proc
);
1207 proc
->next
= df
->first
;
1208 if (df
->first
) df
->first
->prev
= proc
;
1215 fp
= scgi_process_init();
1216 fp
->id
= df
->num_procs
++;
1219 fp
->state
= PROC_STATE_RUNNING
;
1221 if (buffer_string_is_empty(df
->unixsocket
)) {
1222 fp
->port
= df
->port
;
1224 buffer_copy_buffer(fp
->socket
, df
->unixsocket
);
1233 /* if extension already exists, take it */
1234 scgi_extension_insert(s
->exts
, da_ext
->key
, df
);
1241 return HANDLER_GO_ON
;
1244 if (NULL
!= df
) scgi_host_free(df
);
1245 return HANDLER_ERROR
;
1248 static int scgi_set_state(server
*srv
, handler_ctx
*hctx
, scgi_connection_state_t state
) {
1249 hctx
->state
= state
;
1250 hctx
->state_timestamp
= srv
->cur_ts
;
1256 static void scgi_connection_cleanup(server
*srv
, handler_ctx
*hctx
) {
1260 if (NULL
== hctx
) return;
1262 p
= hctx
->plugin_data
;
1263 con
= hctx
->remote_conn
;
1265 if (hctx
->fd
!= -1) {
1266 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1267 fdevent_unregister(srv
->ev
, hctx
->fd
);
1272 if (hctx
->host
&& hctx
->proc
) {
1275 if (hctx
->got_proc
) {
1276 /* after the connect the process gets a load */
1279 if (p
->conf
.debug
) {
1280 log_error_write(srv
, __FILE__
, __LINE__
, "sddb",
1283 hctx
->proc
->pid
, hctx
->proc
->socket
);
1287 scgi_proclist_sort_down(srv
, hctx
->host
, hctx
->proc
);
1291 handler_ctx_free(hctx
);
1292 con
->plugin_ctx
[p
->id
] = NULL
;
1295 static int scgi_reconnect(server
*srv
, handler_ctx
*hctx
) {
1296 plugin_data
*p
= hctx
->plugin_data
;
1302 * connect was ok, connection was accepted
1303 * but the php accept loop checks after the accept if it should die or not.
1305 * if yes we can only detect it at a write()
1307 * next step is resetting this attemp and setup a connection again
1309 * if we have more then 5 reconnects for the same request, die
1313 * we have a connection but the child died by some other reason
1317 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
1318 fdevent_unregister(srv
->ev
, hctx
->fd
);
1322 scgi_set_state(srv
, hctx
, FCGI_STATE_INIT
);
1324 hctx
->request_id
= 0;
1327 if (p
->conf
.debug
) {
1328 log_error_write(srv
, __FILE__
, __LINE__
, "sddb",
1331 hctx
->proc
->pid
, hctx
->proc
->socket
);
1335 scgi_proclist_sort_down(srv
, hctx
->host
, hctx
->proc
);
1341 static handler_t
scgi_connection_reset(server
*srv
, connection
*con
, void *p_d
) {
1342 plugin_data
*p
= p_d
;
1344 scgi_connection_cleanup(srv
, con
->plugin_ctx
[p
->id
]);
1346 return HANDLER_GO_ON
;
1350 static int scgi_env_add(buffer
*env
, const char *key
, size_t key_len
, const char *val
, size_t val_len
) {
1353 if (!key
|| !val
) return -1;
1355 len
= key_len
+ val_len
+ 2;
1357 buffer_string_prepare_append(env
, len
);
1359 buffer_append_string_len(env
, key
, key_len
);
1360 buffer_append_string_len(env
, "", 1);
1361 buffer_append_string_len(env
, val
, val_len
);
1362 buffer_append_string_len(env
, "", 1);
1373 * 1 not connected yet
1376 static int scgi_establish_connection(server
*srv
, handler_ctx
*hctx
) {
1377 struct sockaddr
*scgi_addr
;
1378 struct sockaddr_in scgi_addr_in
;
1379 #ifdef HAVE_SYS_UN_H
1380 struct sockaddr_un scgi_addr_un
;
1384 scgi_extension_host
*host
= hctx
->host
;
1385 scgi_proc
*proc
= hctx
->proc
;
1386 int scgi_fd
= hctx
->fd
;
1388 if (!buffer_string_is_empty(proc
->socket
)) {
1389 #ifdef HAVE_SYS_UN_H
1390 /* use the unix domain socket */
1391 memset(&scgi_addr_un
, 0, sizeof(scgi_addr_un
));
1392 scgi_addr_un
.sun_family
= AF_UNIX
;
1393 if (buffer_string_length(proc
->socket
) + 1 > sizeof(scgi_addr_un
.sun_path
)) {
1394 log_error_write(srv
, __FILE__
, __LINE__
, "sB",
1395 "ERROR: Unix Domain socket filename too long:",
1399 memcpy(scgi_addr_un
.sun_path
, proc
->socket
->ptr
, buffer_string_length(proc
->socket
) + 1);
1402 servlen
= SUN_LEN(&scgi_addr_un
);
1405 servlen
= buffer_string_length(proc
->socket
) + 1 + sizeof(scgi_addr_un
.sun_family
);
1407 scgi_addr
= (struct sockaddr
*) &scgi_addr_un
;
1412 memset(&scgi_addr_in
, 0, sizeof(scgi_addr_in
));
1413 scgi_addr_in
.sin_family
= AF_INET
;
1414 if (0 == inet_aton(host
->host
->ptr
, &(scgi_addr_in
.sin_addr
))) {
1415 log_error_write(srv
, __FILE__
, __LINE__
, "sbs",
1416 "converting IP-adress failed for", host
->host
,
1417 "\nBe sure to specify an IP address here");
1421 scgi_addr_in
.sin_port
= htons(proc
->port
);
1422 servlen
= sizeof(scgi_addr_in
);
1424 scgi_addr
= (struct sockaddr
*) &scgi_addr_in
;
1427 if (-1 == connect(scgi_fd
, scgi_addr
, servlen
)) {
1428 if (errno
== EINPROGRESS
||
1429 errno
== EALREADY
||
1431 if (hctx
->conf
.debug
) {
1432 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1433 "connect delayed, will continue later:", scgi_fd
);
1438 log_error_write(srv
, __FILE__
, __LINE__
, "sdsddb",
1439 "connect failed:", scgi_fd
,
1440 strerror(errno
), errno
,
1441 proc
->port
, proc
->socket
);
1443 if (errno
== EAGAIN
) {
1444 /* this is Linux only */
1446 log_error_write(srv
, __FILE__
, __LINE__
, "s",
1447 "If this happend on Linux: You have been run out of local ports. "
1448 "Check the manual, section Performance how to handle this.");
1454 if (hctx
->conf
.debug
> 1) {
1455 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
1456 "connect succeeded: ", scgi_fd
);
1464 static int scgi_env_add_request_headers(server
*srv
, connection
*con
, plugin_data
*p
) {
1467 for (i
= 0; i
< con
->request
.headers
->used
; i
++) {
1470 ds
= (data_string
*)con
->request
.headers
->data
[i
];
1472 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
1473 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 1);
1475 scgi_env_add(p
->scgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
));
1479 for (i
= 0; i
< con
->environment
->used
; i
++) {
1482 ds
= (data_string
*)con
->environment
->data
[i
];
1484 if (!buffer_is_empty(ds
->value
) && !buffer_is_empty(ds
->key
)) {
1485 buffer_copy_string_encoded_cgi_varnames(srv
->tmp_buf
, CONST_BUF_LEN(ds
->key
), 0);
1487 scgi_env_add(p
->scgi_env
, CONST_BUF_LEN(srv
->tmp_buf
), CONST_BUF_LEN(ds
->value
));
1495 static int scgi_create_env(server
*srv
, handler_ctx
*hctx
) {
1496 char buf
[LI_ITOSTRING_LENGTH
];
1499 char b2
[INET6_ADDRSTRLEN
+ 1];
1503 plugin_data
*p
= hctx
->plugin_data
;
1504 scgi_extension_host
*host
= hctx
->host
;
1506 connection
*con
= hctx
->remote_conn
;
1507 server_socket
*srv_sock
= con
->srv_socket
;
1510 socklen_t our_addr_len
;
1512 buffer_string_prepare_copy(p
->scgi_env
, 1023);
1514 /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
1516 li_itostrn(buf
, sizeof(buf
), con
->request
.content_length
);
1517 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("CONTENT_LENGTH"), buf
, strlen(buf
));
1518 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCGI"), CONST_STR_LEN("1"));
1521 if (buffer_is_empty(con
->conf
.server_tag
)) {
1522 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_STR_LEN(PACKAGE_DESC
));
1524 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_SOFTWARE"), CONST_BUF_LEN(con
->conf
.server_tag
));
1527 if (!buffer_is_empty(con
->server_name
)) {
1528 size_t len
= buffer_string_length(con
->server_name
);
1530 if (con
->server_name
->ptr
[0] == '[') {
1531 const char *colon
= strstr(con
->server_name
->ptr
, "]:");
1532 if (colon
) len
= (colon
+ 1) - con
->server_name
->ptr
;
1534 const char *colon
= strchr(con
->server_name
->ptr
, ':');
1535 if (colon
) len
= colon
- con
->server_name
->ptr
;
1538 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_NAME"), con
->server_name
->ptr
, len
);
1541 s
= inet_ntop(srv_sock
->addr
.plain
.sa_family
,
1542 srv_sock
->addr
.plain
.sa_family
== AF_INET6
?
1543 (const void *) &(srv_sock
->addr
.ipv6
.sin6_addr
) :
1544 (const void *) &(srv_sock
->addr
.ipv4
.sin_addr
),
1547 s
= inet_ntoa(srv_sock
->addr
.ipv4
.sin_addr
);
1550 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_NAME"), s
, strlen(s
));
1553 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("GATEWAY_INTERFACE"), CONST_STR_LEN("CGI/1.1"));
1555 li_utostrn(buf
, sizeof(buf
),
1557 ntohs(srv_sock
->addr
.plain
.sa_family
? srv_sock
->addr
.ipv6
.sin6_port
: srv_sock
->addr
.ipv4
.sin_port
)
1559 ntohs(srv_sock
->addr
.ipv4
.sin_port
)
1563 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_PORT"), buf
, strlen(buf
));
1565 /* get the server-side of the connection to the client */
1566 our_addr_len
= sizeof(our_addr
);
1568 if (-1 == getsockname(con
->fd
, &(our_addr
.plain
), &our_addr_len
)) {
1569 s
= inet_ntop_cache_get_ip(srv
, &(srv_sock
->addr
));
1571 s
= inet_ntop_cache_get_ip(srv
, &(our_addr
));
1573 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_ADDR"), s
, strlen(s
));
1575 li_utostrn(buf
, sizeof(buf
),
1577 ntohs(con
->dst_addr
.plain
.sa_family
? con
->dst_addr
.ipv6
.sin6_port
: con
->dst_addr
.ipv4
.sin_port
)
1579 ntohs(con
->dst_addr
.ipv4
.sin_port
)
1583 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REMOTE_PORT"), buf
, strlen(buf
));
1585 s
= inet_ntop_cache_get_ip(srv
, &(con
->dst_addr
));
1587 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REMOTE_ADDR"), s
, strlen(s
));
1590 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1591 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1592 * (6.1.14, 6.1.6, 6.1.7)
1595 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_NAME"), CONST_BUF_LEN(con
->uri
.path
));
1597 if (!buffer_string_is_empty(con
->request
.pathinfo
)) {
1598 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_BUF_LEN(con
->request
.pathinfo
));
1600 /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1602 if (!buffer_string_is_empty(host
->docroot
)) {
1603 buffer_copy_buffer(p
->path
, host
->docroot
);
1605 buffer_copy_buffer(p
->path
, con
->physical
.basedir
);
1607 buffer_append_string_buffer(p
->path
, con
->request
.pathinfo
);
1608 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_TRANSLATED"), CONST_BUF_LEN(p
->path
));
1610 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("PATH_INFO"), CONST_STR_LEN(""));
1614 * SCRIPT_FILENAME and DOCUMENT_ROOT for php. The PHP manual
1615 * http://www.php.net/manual/en/reserved.variables.php
1616 * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1617 * TODO: this code should be checked against cgi.fix_pathinfo php
1621 if (!buffer_string_is_empty(host
->docroot
)) {
1623 * rewrite SCRIPT_FILENAME
1627 buffer_copy_buffer(p
->path
, host
->docroot
);
1628 buffer_append_string_buffer(p
->path
, con
->uri
.path
);
1630 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
));
1631 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(host
->docroot
));
1633 buffer_copy_buffer(p
->path
, con
->physical
.path
);
1635 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SCRIPT_FILENAME"), CONST_BUF_LEN(p
->path
));
1636 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("DOCUMENT_ROOT"), CONST_BUF_LEN(con
->physical
.basedir
));
1638 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_URI"), CONST_BUF_LEN(con
->request
.orig_uri
));
1639 if (!buffer_is_equal(con
->request
.uri
, con
->request
.orig_uri
)) {
1640 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REDIRECT_URI"), CONST_BUF_LEN(con
->request
.uri
));
1642 if (!buffer_string_is_empty(con
->uri
.query
)) {
1643 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_BUF_LEN(con
->uri
.query
));
1645 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("QUERY_STRING"), CONST_STR_LEN(""));
1648 s
= get_http_method_name(con
->request
.http_method
);
1650 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REQUEST_METHOD"), s
, strlen(s
));
1651 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("REDIRECT_STATUS"), CONST_STR_LEN("200")); /* if php is compiled with --force-redirect */
1652 s
= get_http_version_name(con
->request
.http_version
);
1654 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("SERVER_PROTOCOL"), s
, strlen(s
));
1657 if (buffer_is_equal_caseless_string(con
->uri
.scheme
, CONST_STR_LEN("https"))) {
1658 scgi_env_add(p
->scgi_env
, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1662 scgi_env_add_request_headers(srv
, con
, p
);
1666 buffer_append_int(b
, buffer_string_length(p
->scgi_env
));
1667 buffer_append_string_len(b
, CONST_STR_LEN(":"));
1668 buffer_append_string_buffer(b
, p
->scgi_env
);
1669 buffer_append_string_len(b
, CONST_STR_LEN(","));
1671 chunkqueue_append_buffer(hctx
->wb
, b
);
1674 if (con
->request
.content_length
) {
1675 chunkqueue
*req_cq
= con
->request_content_queue
;
1677 chunkqueue_steal(hctx
->wb
, req_cq
, req_cq
->bytes_in
);
1683 static int scgi_response_parse(server
*srv
, connection
*con
, plugin_data
*p
, buffer
*in
, int eol
) {
1690 buffer_copy_buffer(p
->parse_response
, in
);
1692 for (s
= p
->parse_response
->ptr
;
1693 NULL
!= (ns
= (eol
== EOL_RN
? strstr(s
, "\r\n") : strchr(s
, '\n')));
1694 s
= ns
+ (eol
== EOL_RN
? 2 : 1), line
++) {
1695 const char *key
, *value
;
1702 0 == strncmp(s
, "HTTP/1.", 7)) {
1703 /* non-parsed header ... we parse them anyway */
1709 /* after the space should be a status code for us */
1711 status
= strtol(s
+9, NULL
, 10);
1713 if (status
>= 100 && status
< 1000) {
1714 /* we expected 3 digits got them */
1715 con
->parsed_response
|= HTTP_STATUS
;
1716 con
->http_status
= status
;
1722 if (NULL
== (value
= strchr(s
, ':'))) {
1723 /* we expect: "<key>: <value>\r\n" */
1727 key_len
= value
- key
;
1731 while (*value
== ' ' || *value
== '\t') value
++;
1733 if (NULL
== (ds
= (data_string
*)array_get_unused_element(con
->response
.headers
, TYPE_STRING
))) {
1734 ds
= data_response_init();
1736 buffer_copy_string_len(ds
->key
, key
, key_len
);
1737 buffer_copy_string(ds
->value
, value
);
1739 array_insert_unique(con
->response
.headers
, (data_unset
*)ds
);
1743 if (0 == strncasecmp(key
, "Date", key_len
)) {
1744 con
->parsed_response
|= HTTP_DATE
;
1748 if (0 == strncasecmp(key
, "Status", key_len
)) {
1749 int status
= strtol(value
, NULL
, 10);
1750 if (status
>= 100 && status
< 1000) {
1751 con
->http_status
= status
;
1752 con
->parsed_response
|= HTTP_STATUS
;
1754 con
->http_status
= 502;
1759 if (0 == strncasecmp(key
, "Location", key_len
)) {
1760 con
->parsed_response
|= HTTP_LOCATION
;
1764 if (0 == strncasecmp(key
, "Connection", key_len
)) {
1765 con
->response
.keep_alive
= (0 == strcasecmp(value
, "Keep-Alive")) ? 1 : 0;
1766 con
->parsed_response
|= HTTP_CONNECTION
;
1770 if (0 == strncasecmp(key
, "Content-Length", key_len
)) {
1771 con
->response
.content_length
= strtoul(value
, NULL
, 10);
1772 con
->parsed_response
|= HTTP_CONTENT_LENGTH
;
1781 /* CGI/1.1 rev 03 - 7.2.1.2 */
1782 if ((con
->parsed_response
& HTTP_LOCATION
) &&
1783 !(con
->parsed_response
& HTTP_STATUS
)) {
1784 con
->http_status
= 302;
1791 static int scgi_demux_response(server
*srv
, handler_ctx
*hctx
) {
1792 plugin_data
*p
= hctx
->plugin_data
;
1793 connection
*con
= hctx
->remote_conn
;
1798 buffer_string_prepare_copy(hctx
->response
, 1023);
1799 if (-1 == (n
= read(hctx
->fd
, hctx
->response
->ptr
, hctx
->response
->size
- 1))) {
1800 if (errno
== EAGAIN
|| errno
== EINTR
) {
1801 /* would block, wait for signal */
1805 log_error_write(srv
, __FILE__
, __LINE__
, "sdd", strerror(errno
), con
->fd
, hctx
->fd
);
1812 con
->file_finished
= 1;
1814 /* send final chunk */
1815 http_chunk_close(srv
, con
);
1816 joblist_append(srv
, con
);
1821 buffer_commit(hctx
->response
, n
);
1823 /* split header from body */
1825 if (con
->file_started
== 0) {
1829 int cp
, eol
= EOL_UNSET
;
1833 buffer_append_string_buffer(hctx
->response_header
, hctx
->response
);
1835 /* nph (non-parsed headers) */
1836 if (0 == strncmp(hctx
->response_header
->ptr
, "HTTP/1.", 7)) in_header
= 1;
1838 /* search for the \r\n\r\n or \n\n in the string */
1839 for (c
= hctx
->response_header
->ptr
, cp
= 0, used
= buffer_string_length(hctx
->response_header
); used
; c
++, cp
++, used
--) {
1840 if (*c
== ':') in_header
= 1;
1841 else if (*c
== '\n') {
1842 if (in_header
== 0) {
1843 /* got a response without a response header */
1850 if (eol
== EOL_UNSET
) eol
= EOL_N
;
1852 if (*(c
+1) == '\n') {
1858 } else if (used
> 1 && *c
== '\r' && *(c
+1) == '\n') {
1859 if (in_header
== 0) {
1860 /* got a response without a response header */
1867 if (eol
== EOL_UNSET
) eol
= EOL_RN
;
1886 /* no header, but a body */
1888 if (con
->request
.http_version
== HTTP_VERSION_1_1
) {
1889 con
->response
.transfer_encoding
= HTTP_TRANSFER_ENCODING_CHUNKED
;
1892 http_chunk_append_buffer(srv
, con
, hctx
->response_header
);
1893 joblist_append(srv
, con
);
1895 size_t blen
= buffer_string_length(hctx
->response_header
) - hlen
;
1897 /* a small hack: terminate after at the second \r */
1898 buffer_string_set_length(hctx
->response_header
, hlen
- 1);
1900 /* parse the response header */
1901 scgi_response_parse(srv
, con
, p
, hctx
->response_header
, eol
);
1903 /* enable chunked-transfer-encoding */
1904 if (con
->request
.http_version
== HTTP_VERSION_1_1
&&
1905 !(con
->parsed_response
& HTTP_CONTENT_LENGTH
)) {
1906 con
->response
.transfer_encoding
= HTTP_TRANSFER_ENCODING_CHUNKED
;
1910 http_chunk_append_mem(srv
, con
, hctx
->response_header
->ptr
+ hlen
, blen
);
1911 joblist_append(srv
, con
);
1915 con
->file_started
= 1;
1918 http_chunk_append_buffer(srv
, con
, hctx
->response
);
1919 joblist_append(srv
, con
);
1923 log_error_write(srv
, __FILE__
, __LINE__
, "ddss", con
->fd
, hctx
->fd
, connection_get_state(con
->state
), b
->ptr
);
1931 static int scgi_proclist_sort_up(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
1936 /* we have been the smallest of the current list
1937 * and we want to insert the node sorted as soon
1947 /* nothing to sort, only one element */
1948 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
1950 for (p
= proc
; p
->next
&& p
->next
->load
< proc
->load
; p
= p
->next
);
1952 /* no need to move something
1960 if (p
== proc
) return 0;
1962 if (host
->first
== proc
) {
1963 /* we have been the first elememt */
1965 host
->first
= proc
->next
;
1966 host
->first
->prev
= NULL
;
1969 /* disconnect proc */
1971 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
1972 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
1974 /* proc should be right of p */
1976 proc
->next
= p
->next
;
1978 if (p
->next
) p
->next
->prev
= proc
;
1981 for(p
= host
->first
; p
; p
= p
->next
) {
1982 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
1992 int scgi_proclist_sort_down(server
*srv
, scgi_extension_host
*host
, scgi_proc
*proc
) {
1997 /* we have been the smallest of the current list
1998 * and we want to insert the node sorted as soon
2007 * the basic is idea is:
2008 * - the last active scgi process should be still
2009 * in ram and is not swapped out yet
2010 * - processes that are not reused will be killed
2011 * after some time by the trigger-handler
2013 * everything > 0 is hot
2014 * all unused procs are colder the more right they are
2015 * ice-cold processes are propably unused since more
2016 * than 'unused-timeout', are swaped out and won't be
2017 * reused in the next seconds anyway.
2021 /* nothing to sort, only one element */
2022 if (host
->first
== proc
&& proc
->next
== NULL
) return 0;
2024 for (p
= host
->first
; p
!= proc
&& p
->load
< proc
->load
; p
= p
->next
);
2027 /* no need to move something
2035 if (p
== proc
) return 0;
2037 /* we have to move left. If we are already the first element
2039 if (host
->first
== proc
) return 0;
2042 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
2043 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
2045 /* proc should be left of p */
2047 proc
->prev
= p
->prev
;
2048 if (p
->prev
) p
->prev
->next
= proc
;
2051 if (proc
->prev
== NULL
) host
->first
= proc
;
2053 for(p
= host
->first
; p
; p
= p
->next
) {
2054 log_error_write(srv
, __FILE__
, __LINE__
, "dd",
2064 static int scgi_restart_dead_procs(server
*srv
, plugin_data
*p
, scgi_extension_host
*host
) {
2067 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2068 if (p
->conf
.debug
) {
2069 log_error_write(srv
, __FILE__
, __LINE__
, "sbdbdddd",
2071 host
->host
, proc
->port
,
2079 if (0 == proc
->is_local
) {
2081 * external servers might get disabled
2083 * enable the server again, perhaps it is back again
2086 if ((proc
->state
== PROC_STATE_DISABLED
) &&
2087 (srv
->cur_ts
- proc
->disable_ts
> host
->disable_time
)) {
2088 proc
->state
= PROC_STATE_RUNNING
;
2089 host
->active_procs
++;
2091 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb",
2092 "fcgi-server re-enabled:",
2093 host
->host
, host
->port
,
2097 /* the child should not terminate at all */
2100 if (proc
->state
== PROC_STATE_DIED_WAIT_FOR_PID
) {
2101 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2103 /* child is still alive */
2108 if (WIFEXITED(status
)) {
2110 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2111 "child exited, pid:", proc
->pid
,
2112 "status:", WEXITSTATUS(status
));
2114 } else if (WIFSIGNALED(status
)) {
2115 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2119 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2120 "child died somehow:",
2124 proc
->state
= PROC_STATE_DIED
;
2130 * local servers might died, but we restart them
2133 if (proc
->state
== PROC_STATE_DIED
&&
2135 /* restart the child */
2137 if (p
->conf
.debug
) {
2138 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2139 "--- scgi spawning",
2140 "\n\tport:", host
->port
,
2141 "\n\tsocket", host
->unixsocket
,
2142 "\n\tcurrent:", 1, "/", host
->min_procs
);
2145 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2146 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2147 "ERROR: spawning fcgi failed.");
2148 return HANDLER_ERROR
;
2151 scgi_proclist_sort_down(srv
, host
, proc
);
2160 static handler_t
scgi_write_request(server
*srv
, handler_ctx
*hctx
) {
2161 plugin_data
*p
= hctx
->plugin_data
;
2162 scgi_extension_host
*host
= hctx
->host
;
2163 connection
*con
= hctx
->remote_conn
;
2169 log_error_write(srv
, __FILE__
, __LINE__
, "s", "fatal error: host = NULL");
2170 return HANDLER_ERROR
;
2172 if (((buffer_string_is_empty(host
->host
) || !host
->port
) && buffer_string_is_empty(host
->unixsocket
))) {
2173 log_error_write(srv
, __FILE__
, __LINE__
, "sxddd",
2176 buffer_string_length(host
->host
),
2178 buffer_string_length(host
->unixsocket
));
2179 return HANDLER_ERROR
;
2183 switch(hctx
->state
) {
2184 case FCGI_STATE_INIT
:
2185 ret
= buffer_string_is_empty(host
->unixsocket
) ? AF_INET
: AF_UNIX
;
2187 if (-1 == (hctx
->fd
= socket(ret
, SOCK_STREAM
, 0))) {
2188 if (errno
== EMFILE
||
2190 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2191 "wait for fd at connection:", con
->fd
);
2193 return HANDLER_WAIT_FOR_FD
;
2196 log_error_write(srv
, __FILE__
, __LINE__
, "ssdd",
2197 "socket failed:", strerror(errno
), srv
->cur_fds
, srv
->max_fds
);
2198 return HANDLER_ERROR
;
2204 fdevent_register(srv
->ev
, hctx
->fd
, scgi_handle_fdevent
, hctx
);
2206 if (-1 == fdevent_fcntl_set(srv
->ev
, hctx
->fd
)) {
2207 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2208 "fcntl failed: ", strerror(errno
));
2210 return HANDLER_ERROR
;
2214 case FCGI_STATE_CONNECT
:
2215 if (hctx
->state
== FCGI_STATE_INIT
) {
2216 for (hctx
->proc
= hctx
->host
->first
;
2217 hctx
->proc
&& hctx
->proc
->state
!= PROC_STATE_RUNNING
;
2218 hctx
->proc
= hctx
->proc
->next
);
2220 /* all childs are dead */
2221 if (hctx
->proc
== NULL
) {
2224 return HANDLER_ERROR
;
2227 if (hctx
->proc
->is_local
) {
2228 hctx
->pid
= hctx
->proc
->pid
;
2231 switch (scgi_establish_connection(srv
, hctx
)) {
2233 scgi_set_state(srv
, hctx
, FCGI_STATE_CONNECT
);
2235 /* connection is in progress, wait for an event and call getsockopt() below */
2237 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2239 return HANDLER_WAIT_FOR_EVENT
;
2241 /* if ECONNREFUSED choose another connection -> FIXME */
2244 return HANDLER_ERROR
;
2246 /* everything is ok, go on */
2253 socklen_t socket_error_len
= sizeof(socket_error
);
2255 /* try to finish the connect() */
2256 if (0 != getsockopt(hctx
->fd
, SOL_SOCKET
, SO_ERROR
, &socket_error
, &socket_error_len
)) {
2257 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2258 "getsockopt failed:", strerror(errno
));
2260 return HANDLER_ERROR
;
2262 if (socket_error
!= 0) {
2263 if (!hctx
->proc
->is_local
|| p
->conf
.debug
) {
2264 /* local procs get restarted */
2266 log_error_write(srv
, __FILE__
, __LINE__
, "ss",
2267 "establishing connection failed:", strerror(socket_error
),
2268 "port:", hctx
->proc
->port
);
2271 return HANDLER_ERROR
;
2275 /* ok, we have the connection */
2278 hctx
->proc
->last_used
= srv
->cur_ts
;
2281 if (p
->conf
.debug
) {
2282 log_error_write(srv
, __FILE__
, __LINE__
, "sddbdd",
2291 /* move the proc-list entry down the list */
2292 scgi_proclist_sort_up(srv
, hctx
->host
, hctx
->proc
);
2294 scgi_set_state(srv
, hctx
, FCGI_STATE_PREPARE_WRITE
);
2296 case FCGI_STATE_PREPARE_WRITE
:
2297 scgi_create_env(srv
, hctx
);
2299 scgi_set_state(srv
, hctx
, FCGI_STATE_WRITE
);
2302 case FCGI_STATE_WRITE
:
2303 ret
= srv
->network_backend_write(srv
, con
, hctx
->fd
, hctx
->wb
, MAX_WRITE_LIMIT
);
2305 chunkqueue_remove_finished_chunks(hctx
->wb
);
2308 if (errno
== ENOTCONN
|| ret
== -2) {
2309 /* the connection got dropped after accept()
2311 * this is most of the time a PHP which dies
2312 * after PHP_FCGI_MAX_REQUESTS
2315 if (hctx
->wb
->bytes_out
== 0 &&
2316 hctx
->reconnects
< 5) {
2317 usleep(10000); /* take away the load of the webserver
2318 * to let the php a chance to restart
2321 scgi_reconnect(srv
, hctx
);
2323 return HANDLER_WAIT_FOR_FD
;
2326 /* not reconnected ... why
2328 * far@#lighttpd report this for FreeBSD
2332 log_error_write(srv
, __FILE__
, __LINE__
, "ssosd",
2333 "connection was dropped after accept(). reconnect() denied:",
2334 "write-offset:", hctx
->wb
->bytes_out
,
2335 "reconnect attempts:", hctx
->reconnects
);
2337 return HANDLER_ERROR
;
2339 /* -1 == ret => error on our side */
2340 log_error_write(srv
, __FILE__
, __LINE__
, "ssd",
2341 "write failed:", strerror(errno
), errno
);
2343 return HANDLER_ERROR
;
2347 if (hctx
->wb
->bytes_out
== hctx
->wb
->bytes_in
) {
2348 /* we don't need the out event anymore */
2349 fdevent_event_del(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
);
2350 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2351 scgi_set_state(srv
, hctx
, FCGI_STATE_READ
);
2353 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2355 return HANDLER_WAIT_FOR_EVENT
;
2359 case FCGI_STATE_READ
:
2360 /* waiting for a response */
2363 log_error_write(srv
, __FILE__
, __LINE__
, "s", "(debug) unknown state");
2364 return HANDLER_ERROR
;
2367 return HANDLER_WAIT_FOR_EVENT
;
2370 SUBREQUEST_FUNC(mod_scgi_handle_subrequest
) {
2371 plugin_data
*p
= p_d
;
2373 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2375 scgi_extension_host
*host
;
2377 if (NULL
== hctx
) return HANDLER_GO_ON
;
2380 if (con
->mode
!= p
->id
) return HANDLER_GO_ON
;
2382 /* ok, create the request */
2383 switch(scgi_write_request(srv
, hctx
)) {
2389 0 == proc
->is_local
&&
2390 proc
->state
!= PROC_STATE_DISABLED
) {
2391 /* only disable remote servers as we don't manage them*/
2393 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "fcgi-server disabled:",
2398 /* disable this server */
2399 proc
->disable_ts
= srv
->cur_ts
;
2400 proc
->state
= PROC_STATE_DISABLED
;
2401 host
->active_procs
--;
2404 if (hctx
->state
== FCGI_STATE_INIT
||
2405 hctx
->state
== FCGI_STATE_CONNECT
) {
2406 /* connect() or getsockopt() failed,
2407 * restart the request-handling
2409 if (proc
&& proc
->is_local
) {
2411 if (p
->conf
.debug
) {
2412 log_error_write(srv
, __FILE__
, __LINE__
, "sbdb", "connect() to scgi failed, restarting the request-handling:",
2419 * several hctx might reference the same proc
2421 * Only one of them should mark the proc as dead all the other
2422 * ones should just take a new one.
2424 * If a new proc was started with the old struct this might lead
2425 * the mark a perfect proc as dead otherwise
2428 if (proc
->state
== PROC_STATE_RUNNING
&&
2429 hctx
->pid
== proc
->pid
) {
2430 proc
->state
= PROC_STATE_DIED_WAIT_FOR_PID
;
2433 scgi_restart_dead_procs(srv
, p
, host
);
2435 scgi_connection_cleanup(srv
, hctx
);
2437 buffer_reset(con
->physical
.path
);
2439 joblist_append(srv
, con
);
2441 /* mis-using HANDLER_WAIT_FOR_FD to break out of the loop
2442 * and hope that the childs will be restarted
2445 return HANDLER_WAIT_FOR_FD
;
2447 scgi_connection_cleanup(srv
, hctx
);
2449 buffer_reset(con
->physical
.path
);
2451 con
->http_status
= 503;
2453 return HANDLER_FINISHED
;
2455 case HANDLER_WAIT_FOR_EVENT
:
2456 if (con
->file_started
== 1) {
2457 return HANDLER_FINISHED
;
2459 return HANDLER_WAIT_FOR_EVENT
;
2461 case HANDLER_WAIT_FOR_FD
:
2462 return HANDLER_WAIT_FOR_FD
;
2464 log_error_write(srv
, __FILE__
, __LINE__
, "s", "subrequest write-req default");
2465 return HANDLER_ERROR
;
2469 static handler_t
scgi_connection_close(server
*srv
, handler_ctx
*hctx
) {
2472 if (NULL
== hctx
) return HANDLER_GO_ON
;
2474 con
= hctx
->remote_conn
;
2476 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2477 "emergency exit: scgi:",
2478 "connection-fd:", con
->fd
,
2479 "fcgi-fd:", hctx
->fd
);
2481 scgi_connection_cleanup(srv
, hctx
);
2483 return HANDLER_FINISHED
;
2487 static handler_t
scgi_handle_fdevent(server
*srv
, void *ctx
, int revents
) {
2488 handler_ctx
*hctx
= ctx
;
2489 connection
*con
= hctx
->remote_conn
;
2490 plugin_data
*p
= hctx
->plugin_data
;
2492 scgi_proc
*proc
= hctx
->proc
;
2493 scgi_extension_host
*host
= hctx
->host
;
2495 if ((revents
& FDEVENT_IN
) &&
2496 hctx
->state
== FCGI_STATE_READ
) {
2497 switch (scgi_demux_response(srv
, hctx
)) {
2502 scgi_connection_cleanup(srv
, hctx
);
2504 joblist_append(srv
, con
);
2505 return HANDLER_FINISHED
;
2507 if (proc
->pid
&& proc
->state
!= PROC_STATE_DIED
) {
2510 /* only fetch the zombie if it is not already done */
2512 switch(waitpid(proc
->pid
, &status
, WNOHANG
)) {
2514 /* child is still alive */
2519 /* the child should not terminate at all */
2520 if (WIFEXITED(status
)) {
2521 log_error_write(srv
, __FILE__
, __LINE__
, "sdsd",
2522 "child exited, pid:", proc
->pid
,
2523 "status:", WEXITSTATUS(status
));
2524 } else if (WIFSIGNALED(status
)) {
2525 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2529 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2530 "child died somehow:",
2534 if (p
->conf
.debug
) {
2535 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsbsdsd",
2536 "--- scgi spawning",
2537 "\n\tport:", host
->port
,
2538 "\n\tsocket", host
->unixsocket
,
2539 "\n\tcurrent:", 1, "/", host
->min_procs
);
2542 if (scgi_spawn_connection(srv
, p
, host
, proc
)) {
2544 proc
->state
= PROC_STATE_DIED
;
2546 scgi_proclist_sort_down(srv
, host
, proc
);
2553 if (con
->file_started
== 0) {
2554 /* nothing has been send out yet, try to use another child */
2556 if (hctx
->wb
->bytes_out
== 0 &&
2557 hctx
->reconnects
< 5) {
2558 scgi_reconnect(srv
, hctx
);
2560 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2561 "response not sent, request not sent, reconnection.",
2562 "connection-fd:", con
->fd
,
2563 "fcgi-fd:", hctx
->fd
);
2565 return HANDLER_WAIT_FOR_FD
;
2568 log_error_write(srv
, __FILE__
, __LINE__
, "sosdsd",
2569 "response not sent, request sent:", hctx
->wb
->bytes_out
,
2570 "connection-fd:", con
->fd
,
2571 "fcgi-fd:", hctx
->fd
);
2573 scgi_connection_cleanup(srv
, hctx
);
2575 connection_set_state(srv
, con
, CON_STATE_HANDLE_REQUEST
);
2576 buffer_reset(con
->physical
.path
);
2577 con
->http_status
= 500;
2580 /* response might have been already started, kill the connection */
2581 log_error_write(srv
, __FILE__
, __LINE__
, "ssdsd",
2582 "response already sent out, termination connection",
2583 "connection-fd:", con
->fd
,
2584 "fcgi-fd:", hctx
->fd
);
2586 scgi_connection_cleanup(srv
, hctx
);
2588 connection_set_state(srv
, con
, CON_STATE_ERROR
);
2594 joblist_append(srv
, con
);
2595 return HANDLER_FINISHED
;
2599 if (revents
& FDEVENT_OUT
) {
2600 if (hctx
->state
== FCGI_STATE_CONNECT
||
2601 hctx
->state
== FCGI_STATE_WRITE
) {
2602 /* we are allowed to send something out
2604 * 1. in a unfinished connect() call
2605 * 2. in a unfinished write() call (long POST request)
2607 return mod_scgi_handle_subrequest(srv
, con
, p
);
2609 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
2610 "got a FDEVENT_OUT and didn't know why:",
2615 /* perhaps this issue is already handled */
2616 if (revents
& FDEVENT_HUP
) {
2617 if (hctx
->state
== FCGI_STATE_CONNECT
) {
2618 /* getoptsock will catch this one (right ?)
2620 * if we are in connect we might get a EINPROGRESS
2621 * in the first call and a FDEVENT_HUP in the
2624 * FIXME: as it is a bit ugly.
2627 return mod_scgi_handle_subrequest(srv
, con
, p
);
2628 } else if (hctx
->state
== FCGI_STATE_READ
&&
2629 hctx
->proc
->port
== 0) {
2632 * ioctl says 8192 bytes to read from PHP and we receive directly a HUP for the socket
2633 * even if the FCGI_FIN packet is not received yet
2636 log_error_write(srv
, __FILE__
, __LINE__
, "sbSBSDSd",
2637 "error: unexpected close of scgi connection for",
2639 "(no scgi process on host: ",
2646 connection_set_state(srv
, con
, CON_STATE_ERROR
);
2647 scgi_connection_close(srv
, hctx
);
2648 joblist_append(srv
, con
);
2650 } else if (revents
& FDEVENT_ERR
) {
2651 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2652 "fcgi: got a FDEVENT_ERR. Don't know why.");
2653 /* kill all connections to the scgi process */
2656 connection_set_state(srv
, con
, CON_STATE_ERROR
);
2657 scgi_connection_close(srv
, hctx
);
2658 joblist_append(srv
, con
);
2661 return HANDLER_FINISHED
;
2665 static int scgi_patch_connection(server
*srv
, connection
*con
, plugin_data
*p
) {
2667 plugin_config
*s
= p
->config_storage
[0];
2672 /* skip the first, the global context */
2673 for (i
= 1; i
< srv
->config_context
->used
; i
++) {
2674 data_config
*dc
= (data_config
*)srv
->config_context
->data
[i
];
2675 s
= p
->config_storage
[i
];
2677 /* condition didn't match */
2678 if (!config_check_cond(srv
, con
, dc
)) continue;
2681 for (j
= 0; j
< dc
->value
->used
; j
++) {
2682 data_unset
*du
= dc
->value
->data
[j
];
2684 if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.server"))) {
2686 } else if (buffer_is_equal_string(du
->key
, CONST_STR_LEN("scgi.debug"))) {
2697 static handler_t
scgi_check_extension(server
*srv
, connection
*con
, void *p_d
, int uri_path_handler
) {
2698 plugin_data
*p
= p_d
;
2703 scgi_extension
*extension
= NULL
;
2704 scgi_extension_host
*host
= NULL
;
2706 if (con
->mode
!= DIRECT
) return HANDLER_GO_ON
;
2708 /* Possibly, we processed already this request */
2709 if (con
->file_started
== 1) return HANDLER_GO_ON
;
2711 fn
= uri_path_handler
? con
->uri
.path
: con
->physical
.path
;
2713 if (buffer_string_is_empty(fn
)) return HANDLER_GO_ON
;
2715 s_len
= buffer_string_length(fn
);
2717 scgi_patch_connection(srv
, con
, p
);
2719 /* check if extension matches */
2720 for (k
= 0; k
< p
->conf
.exts
->used
; k
++) {
2722 scgi_extension
*ext
= p
->conf
.exts
->exts
[k
];
2724 if (buffer_is_empty(ext
->key
)) continue;
2726 ct_len
= buffer_string_length(ext
->key
);
2728 if (s_len
< ct_len
) continue;
2730 /* check extension in the form "/scgi_pattern" */
2731 if (*(ext
->key
->ptr
) == '/') {
2732 if (strncmp(fn
->ptr
, ext
->key
->ptr
, ct_len
) == 0) {
2736 } else if (0 == strncmp(fn
->ptr
+ s_len
- ct_len
, ext
->key
->ptr
, ct_len
)) {
2737 /* check extension in the form ".fcg" */
2743 /* extension doesn't match */
2744 if (NULL
== extension
) {
2745 return HANDLER_GO_ON
;
2748 /* get best server */
2749 for (k
= 0; k
< extension
->used
; k
++) {
2750 scgi_extension_host
*h
= extension
->hosts
[k
];
2752 /* we should have at least one proc that can do something */
2753 if (h
->active_procs
== 0) {
2757 if (used
== -1 || h
->load
< used
) {
2765 /* sorry, we don't have a server alive for this ext */
2766 buffer_reset(con
->physical
.path
);
2767 con
->http_status
= 500;
2769 /* only send the 'no handler' once */
2770 if (!extension
->note_is_sent
) {
2771 extension
->note_is_sent
= 1;
2773 log_error_write(srv
, __FILE__
, __LINE__
, "sbsbs",
2774 "all handlers for ", con
->uri
.path
,
2775 "on", extension
->key
,
2779 return HANDLER_FINISHED
;
2782 /* a note about no handler is not sent yet */
2783 extension
->note_is_sent
= 0;
2786 * if check-local is disabled, use the uri.path handler
2790 /* init handler-context */
2791 if (uri_path_handler
) {
2792 if (host
->check_local
== 0) {
2796 hctx
= handler_ctx_init();
2798 hctx
->remote_conn
= con
;
2799 hctx
->plugin_data
= p
;
2803 hctx
->conf
.exts
= p
->conf
.exts
;
2804 hctx
->conf
.debug
= p
->conf
.debug
;
2806 con
->plugin_ctx
[p
->id
] = hctx
;
2812 if (con
->conf
.log_request_handling
) {
2813 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2814 "handling it in mod_scgi");
2817 /* the prefix is the SCRIPT_NAME,
2818 * everything from start to the next slash
2819 * this is important for check-local = "disable"
2821 * if prefix = /admin.fcgi
2823 * /admin.fcgi/foo/bar
2825 * SCRIPT_NAME = /admin.fcgi
2826 * PATH_INFO = /foo/bar
2828 * if prefix = /fcgi-bin/
2832 * SCRIPT_NAME = /fcgi-bin/foo
2837 /* the rewrite is only done for /prefix/? matches */
2838 if (host
->fix_root_path_name
&& extension
->key
->ptr
[0] == '/' && extension
->key
->ptr
[1] == '\0') {
2839 buffer_copy_string(con
->request
.pathinfo
, con
->uri
.path
->ptr
);
2840 buffer_string_set_length(con
->uri
.path
, 0);
2841 } else if (extension
->key
->ptr
[0] == '/' &&
2842 buffer_string_length(con
->uri
.path
) > buffer_string_length(extension
->key
) &&
2843 NULL
!= (pathinfo
= strchr(con
->uri
.path
->ptr
+ buffer_string_length(extension
->key
), '/'))) {
2844 /* rewrite uri.path and pathinfo */
2846 buffer_copy_string(con
->request
.pathinfo
, pathinfo
);
2847 buffer_string_set_length(con
->uri
.path
, buffer_string_length(con
->uri
.path
) - buffer_string_length(con
->request
.pathinfo
));
2852 hctx
= handler_ctx_init();
2854 hctx
->remote_conn
= con
;
2855 hctx
->plugin_data
= p
;
2859 hctx
->conf
.exts
= p
->conf
.exts
;
2860 hctx
->conf
.debug
= p
->conf
.debug
;
2862 con
->plugin_ctx
[p
->id
] = hctx
;
2868 if (con
->conf
.log_request_handling
) {
2869 log_error_write(srv
, __FILE__
, __LINE__
, "s", "handling it in mod_scgi");
2873 return HANDLER_GO_ON
;
2876 /* uri-path handler */
2877 static handler_t
scgi_check_extension_1(server
*srv
, connection
*con
, void *p_d
) {
2878 return scgi_check_extension(srv
, con
, p_d
, 1);
2881 /* start request handler */
2882 static handler_t
scgi_check_extension_2(server
*srv
, connection
*con
, void *p_d
) {
2883 return scgi_check_extension(srv
, con
, p_d
, 0);
2886 JOBLIST_FUNC(mod_scgi_handle_joblist
) {
2887 plugin_data
*p
= p_d
;
2888 handler_ctx
*hctx
= con
->plugin_ctx
[p
->id
];
2890 if (hctx
== NULL
) return HANDLER_GO_ON
;
2892 if (hctx
->fd
!= -1) {
2893 switch (hctx
->state
) {
2894 case FCGI_STATE_READ
:
2895 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_IN
);
2898 case FCGI_STATE_CONNECT
:
2899 case FCGI_STATE_WRITE
:
2900 fdevent_event_set(srv
->ev
, &(hctx
->fde_ndx
), hctx
->fd
, FDEVENT_OUT
);
2903 case FCGI_STATE_INIT
:
2907 log_error_write(srv
, __FILE__
, __LINE__
, "sd", "unhandled fcgi.state", hctx
->state
);
2912 return HANDLER_GO_ON
;
2916 static handler_t
scgi_connection_close_callback(server
*srv
, connection
*con
, void *p_d
) {
2917 plugin_data
*p
= p_d
;
2919 return scgi_connection_close(srv
, con
->plugin_ctx
[p
->id
]);
2922 TRIGGER_FUNC(mod_scgi_handle_trigger
) {
2923 plugin_data
*p
= p_d
;
2927 /* perhaps we should kill a connect attempt after 10-15 seconds
2929 * currently we wait for the TCP timeout which is on Linux 180 seconds
2935 /* check all childs if they are still up */
2937 for (i
= 0; i
< srv
->config_context
->used
; i
++) {
2938 plugin_config
*conf
;
2941 conf
= p
->config_storage
[i
];
2945 for (j
= 0; j
< exts
->used
; j
++) {
2950 for (n
= 0; n
< ex
->used
; n
++) {
2953 unsigned long sum_load
= 0;
2954 scgi_extension_host
*host
;
2956 host
= ex
->hosts
[n
];
2958 scgi_restart_dead_procs(srv
, p
, host
);
2960 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
2961 sum_load
+= proc
->load
;
2964 if (host
->num_procs
&&
2965 host
->num_procs
< host
->max_procs
&&
2966 (sum_load
/ host
->num_procs
) > host
->max_load_per_proc
) {
2967 /* overload, spawn new child */
2968 scgi_proc
*fp
= NULL
;
2970 if (p
->conf
.debug
) {
2971 log_error_write(srv
, __FILE__
, __LINE__
, "s",
2972 "overload detected, spawning a new child");
2975 for (fp
= host
->unused_procs
; fp
&& fp
->pid
!= 0; fp
= fp
->next
);
2978 if (fp
== host
->unused_procs
) host
->unused_procs
= fp
->next
;
2980 if (fp
->next
) fp
->next
->prev
= NULL
;
2984 fp
= scgi_process_init();
2985 fp
->id
= host
->max_id
++;
2990 if (buffer_string_is_empty(host
->unixsocket
)) {
2991 fp
->port
= host
->port
+ fp
->id
;
2993 buffer_copy_buffer(fp
->socket
, host
->unixsocket
);
2994 buffer_append_string_len(fp
->socket
, CONST_STR_LEN("-"));
2995 buffer_append_int(fp
->socket
, fp
->id
);
2998 if (scgi_spawn_connection(srv
, p
, host
, fp
)) {
2999 log_error_write(srv
, __FILE__
, __LINE__
, "s",
3000 "ERROR: spawning fcgi failed.");
3001 scgi_process_free(fp
);
3002 return HANDLER_ERROR
;
3006 fp
->next
= host
->first
;
3008 host
->first
->prev
= fp
;
3013 for (proc
= host
->first
; proc
; proc
= proc
->next
) {
3014 if (proc
->load
!= 0) break;
3015 if (host
->num_procs
<= host
->min_procs
) break;
3016 if (proc
->pid
== 0) continue;
3018 if (srv
->cur_ts
- proc
->last_used
> host
->idle_timeout
) {
3019 /* a proc is idling for a long time now,
3022 if (p
->conf
.debug
) {
3023 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
3024 "idle-timeout reached, terminating child:",
3025 "socket:", proc
->socket
,
3030 if (proc
->next
) proc
->next
->prev
= proc
->prev
;
3031 if (proc
->prev
) proc
->prev
->next
= proc
->next
;
3033 if (proc
->prev
== NULL
) host
->first
= proc
->next
;
3036 proc
->next
= host
->unused_procs
;
3038 if (host
->unused_procs
) host
->unused_procs
->prev
= proc
;
3039 host
->unused_procs
= proc
;
3041 kill(proc
->pid
, SIGTERM
);
3043 proc
->state
= PROC_STATE_KILLED
;
3045 log_error_write(srv
, __FILE__
, __LINE__
, "ssbsd",
3047 "socket:", proc
->socket
,
3052 /* proc is now in unused, let the next second handle the next process */
3057 for (proc
= host
->unused_procs
; proc
; proc
= proc
->next
) {
3060 if (proc
->pid
== 0) continue;
3062 switch (waitpid(proc
->pid
, &status
, WNOHANG
)) {
3064 /* child still running after timeout, good */
3067 if (errno
!= EINTR
) {
3068 /* no PID found ? should never happen */
3069 log_error_write(srv
, __FILE__
, __LINE__
, "sddss",
3070 "pid ", proc
->pid
, proc
->state
,
3071 "not found:", strerror(errno
));
3074 if (errno
== ECHILD
) {
3075 /* someone else has cleaned up for us */
3077 proc
->state
= PROC_STATE_UNSET
;
3083 /* the child should not terminate at all */
3084 if (WIFEXITED(status
)) {
3085 if (proc
->state
!= PROC_STATE_KILLED
) {
3086 log_error_write(srv
, __FILE__
, __LINE__
, "sdb",
3088 WEXITSTATUS(status
), proc
->socket
);
3090 } else if (WIFSIGNALED(status
)) {
3091 if (WTERMSIG(status
) != SIGTERM
) {
3092 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3097 log_error_write(srv
, __FILE__
, __LINE__
, "sd",
3098 "child died somehow:",
3102 proc
->state
= PROC_STATE_UNSET
;
3110 return HANDLER_GO_ON
;
3114 int mod_scgi_plugin_init(plugin
*p
);
3115 int mod_scgi_plugin_init(plugin
*p
) {
3116 p
->version
= LIGHTTPD_VERSION_ID
;
3117 p
->name
= buffer_init_string("scgi");
3119 p
->init
= mod_scgi_init
;
3120 p
->cleanup
= mod_scgi_free
;
3121 p
->set_defaults
= mod_scgi_set_defaults
;
3122 p
->connection_reset
= scgi_connection_reset
;
3123 p
->handle_connection_close
= scgi_connection_close_callback
;
3124 p
->handle_uri_clean
= scgi_check_extension_1
;
3125 p
->handle_subrequest_start
= scgi_check_extension_2
;
3126 p
->handle_subrequest
= mod_scgi_handle_subrequest
;
3127 p
->handle_joblist
= mod_scgi_handle_joblist
;
3128 p
->handle_trigger
= mod_scgi_handle_trigger
;