diff --git a/configure b/configure index 2d88ed7..c490abf 100755 diff --git a/configure.in b/configure.in index e181ac9..4424930 100644 --- a/configure.in +++ b/configure.in @@ -295,6 +295,12 @@ if test "$enable_maintainer_zts" = "yes"; then PTHREADS_FLAGS fi +if test "$PHP_FASTCGI" = "yes" -a "$PHP_FPM" = "yes"; then + PHP_CONFIGURE_PART(Running FastCGI Process Manager checks) + sinclude(sapi/cgi/fpm/acinclude.m4) + sinclude(sapi/cgi/fpm/config.m4) +fi + divert(3) dnl ## In diversion 3 we check for compile-time options to the PHP @@ -511,6 +517,7 @@ AC_CHECK_FUNCS( alphasort \ asctime_r \ chroot \ +clearenv \ ctime_r \ cuserid \ crypt \ @@ -1253,6 +1260,8 @@ PHP_SUBST_OLD(EXTENSION_DIR) PHP_SUBST_OLD(EXTRA_LDFLAGS) PHP_SUBST_OLD(EXTRA_LDFLAGS_PROGRAM) PHP_SUBST_OLD(EXTRA_LIBS) +PHP_SUBST_OLD(SAPI_EXTRA_LIBS) +PHP_SUBST_OLD(SAPI_EXTRA_DEPS) PHP_SUBST_OLD(ZEND_EXTRA_LIBS) PHP_SUBST_OLD(INCLUDES) PHP_SUBST_OLD(EXTRA_INCLUDES) @@ -1364,7 +1373,7 @@ case $PHP_SAPI in install_targets="$PHP_INSTALL_CLI_TARGET $install_targets" ;; *) - install_targets="install-sapi $PHP_INSTALL_CLI_TARGET $install_targets" + install_targets="install-sapi $install_fpm $PHP_INSTALL_CLI_TARGET $install_targets" ;; esac diff --git a/libevent/ChangeLog b/libevent/ChangeLog new file mode 100644 index 0000000..c592139 diff --git a/libevent/Makefile.am b/libevent/Makefile.am new file mode 100644 index 0000000..5ccfd2c diff --git a/libevent/Makefile.in b/libevent/Makefile.in new file mode 100644 index 0000000..0600dcc diff --git a/libevent/README b/libevent/README new file mode 100644 index 0000000..b065039 diff --git a/libevent/aclocal.m4 b/libevent/aclocal.m4 new file mode 100644 index 0000000..74de4a1 diff --git a/libevent/autogen.sh b/libevent/autogen.sh new file mode 100644 index 0000000..218dbf4 diff --git a/libevent/buffer.c b/libevent/buffer.c new file mode 100644 index 0000000..e66080f diff --git a/libevent/compat/sys/_time.h b/libevent/compat/sys/_time.h new file mode 100644 index 0000000..8cabb0d diff --git a/libevent/compat/sys/queue.h b/libevent/compat/sys/queue.h new file mode 100644 index 0000000..c0956dd diff --git a/libevent/config.h.in b/libevent/config.h.in new file mode 100644 index 0000000..d151f87 diff --git a/libevent/configure b/libevent/configure new file mode 100644 index 0000000..0a74aec diff --git a/libevent/configure.in b/libevent/configure.in new file mode 100644 index 0000000..852d3c5 diff --git a/libevent/depcomp b/libevent/depcomp new file mode 100644 index 0000000..ffcd540 diff --git a/libevent/devpoll.c b/libevent/devpoll.c new file mode 100644 index 0000000..cbd2730 diff --git a/libevent/epoll.c b/libevent/epoll.c new file mode 100644 index 0000000..cf3c859 diff --git a/libevent/epoll_sub.c b/libevent/epoll_sub.c new file mode 100644 index 0000000..431970c diff --git a/libevent/evbuffer.c b/libevent/evbuffer.c new file mode 100644 index 0000000..f2179a5 diff --git a/libevent/event-config.h b/libevent/event-config.h new file mode 100644 index 0000000..0a278b3 diff --git a/libevent/event-fpm.h b/libevent/event-fpm.h new file mode 100644 index 0000000..8625ca5 diff --git a/libevent/event-internal.h b/libevent/event-internal.h new file mode 100644 index 0000000..7485f21 diff --git a/libevent/event.3 b/libevent/event.3 new file mode 100644 index 0000000..5b33ec6 diff --git a/libevent/event.c b/libevent/event.c new file mode 100644 index 0000000..826b7db diff --git a/libevent/event.h b/libevent/event.h new file mode 100644 index 0000000..d67ecb5 diff --git a/libevent/evhttp.h b/libevent/evhttp.h new file mode 100644 index 0000000..0d35f9e diff --git a/libevent/evport.c b/libevent/evport.c new file mode 100644 index 0000000..31523b4 diff --git a/libevent/evsignal.h b/libevent/evsignal.h new file mode 100644 index 0000000..8be9cbd diff --git a/libevent/evutil.c b/libevent/evutil.c new file mode 100644 index 0000000..86205b2 diff --git a/libevent/evutil.h b/libevent/evutil.h new file mode 100644 index 0000000..0a018b8 diff --git a/libevent/http-internal.h b/libevent/http-internal.h new file mode 100644 index 0000000..bc9a1ed diff --git a/libevent/http.c b/libevent/http.c new file mode 100644 index 0000000..1d60fc5 diff --git a/libevent/install-sh b/libevent/install-sh new file mode 100644 index 0000000..1a83534 diff --git a/libevent/kqueue.c b/libevent/kqueue.c new file mode 100644 index 0000000..38a1819 diff --git a/libevent/log.c b/libevent/log.c new file mode 100644 index 0000000..b62a619 diff --git a/libevent/log.h b/libevent/log.h new file mode 100644 index 0000000..7bc6632 diff --git a/libevent/min_heap.h b/libevent/min_heap.h new file mode 100644 index 0000000..d47e563 diff --git a/libevent/missing b/libevent/missing new file mode 100644 index 0000000..09edd88 diff --git a/libevent/poll.c b/libevent/poll.c new file mode 100644 index 0000000..b67c6ff diff --git a/libevent/select.c b/libevent/select.c new file mode 100644 index 0000000..7faafe4 diff --git a/libevent/signal.c b/libevent/signal.c new file mode 100644 index 0000000..bcaa3f9 diff --git a/libevent/strlcpy-internal.h b/libevent/strlcpy-internal.h new file mode 100644 index 0000000..22b5f61 diff --git a/libevent/strlcpy.c b/libevent/strlcpy.c new file mode 100644 index 0000000..a1a413d diff --git a/main/php_config.h.in b/main/php_config.h.in --- a/main/php_config.h.in +++ b/main/php_config.h.in @@ -170,6 +170,9 @@ /* Define if you have the chroot function. */ #undef HAVE_CHROOT +/* Define if you have the clearenv function. */ +#undef HAVE_CLEARENV + /* Define if you have the crypt function. */ #undef HAVE_CRYPT @@ -935,6 +938,9 @@ /* */ #undef PHP_FASTCGI +/* Is experimental fastcgi process manager code activated */ +#undef PHP_FASTCGI_PM + /* */ #undef FORCE_CGI_REDIRECT @@ -944,6 +950,27 @@ /* */ #undef ENABLE_PATHINFO_CHECK +/* do we have libxml? */ +#undef HAVE_LIBXML + +/* do we have prctl? */ +#undef HAVE_PRCTL + +/* do we have clock_gettime? */ +#undef HAVE_CLOCK_GETTIME + +/* do we have clock_get_time? */ +#undef HAVE_CLOCK_GET_TIME + +/* do we have ptrace? */ +#undef HAVE_PTRACE + +/* do we have mach_vm_read? */ +#undef HAVE_MACH_VM_READ + +/* /proc/pid/mem interface */ +#undef PROC_MEM_FILE + /* Define if system uses EBCDIC */ #undef CHARSET_EBCDIC --- php-5.2.17/sapi/cgi/Makefile.frag~ 2012-02-27 14:44:23.000000000 +0200 +++ php-5.2.17/sapi/cgi/Makefile.frag 2012-02-27 14:46:13.037731342 +0200 @@ -1,2 +1,2 @@ -$(SAPI_CGI_PATH): libphp_common.la $(PHP_SAPI_OBJS) +$(SAPI_CGI_PATH): libphp_common.la $(PHP_SAPI_OBJS) $(SAPI_EXTRA_DEPS) $(BUILD_CGI) diff --git a/sapi/cgi/cgi_main.c b/sapi/cgi/cgi_main.c --- a/sapi/cgi/cgi_main.c +++ b/sapi/cgi/cgi_main.c @@ -55,6 +55,9 @@ #if HAVE_SYS_WAIT_H #include #endif +#if HAVE_FCNTL_H +#include +#endif #include "zend.h" #include "zend_extensions.h" #include "php_ini.h" @@ -83,6 +86,11 @@ int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS; #if PHP_FASTCGI #include "fastcgi.h" +#if PHP_FASTCGI_PM +#include "fpm/fpm.h" +#include "fpm/fpm_request.h" +#endif + #ifndef PHP_WIN32 /* XXX this will need to change later when threaded fastcgi is implemented. shane */ @@ -115,8 +123,12 @@ static int parent_waiting = 0; static pid_t pgroup; #endif +static int request_body_fd; + #endif +static char *sapi_cgibin_getenv(char *name, size_t name_len TSRMLS_DC); + #define PHP_MODE_STANDARD 1 #define PHP_MODE_HIGHLIGHT 2 #define PHP_MODE_INDENT 3 @@ -146,6 +158,10 @@ static const opt_struct OPTIONS[] = { {'w', 0, "strip"}, {'?', 0, "usage"},/* help alias (both '?' and 'usage') */ {'v', 0, "version"}, +#if PHP_FASTCGI_PM + {'x', 0, "fpm"}, + {'y', 1, "fpm-config"}, +#endif {'z', 1, "zend-extension"}, #if PHP_FASTCGI {'T', 1, "timing"}, @@ -170,6 +186,7 @@ typedef struct _php_cgi_globals_struct { zend_bool impersonate; # endif #endif + char *error_header; } php_cgi_globals_struct; #ifdef ZTS @@ -474,7 +491,28 @@ static int sapi_cgi_read_post(char *buffer, uint count_bytes TSRMLS_DC) #if PHP_FASTCGI if (fcgi_is_fastcgi()) { fcgi_request *request = (fcgi_request*) SG(server_context); - tmp_read_bytes = fcgi_read(request, buffer + read_bytes, count_bytes - read_bytes); + + if (request_body_fd == -1) { + char *request_body_filename = sapi_cgibin_getenv((char *) "REQUEST_BODY_FILE", + sizeof("REQUEST_BODY_FILE")-1 TSRMLS_CC); + + if (request_body_filename && *request_body_filename) { + request_body_fd = open(request_body_filename, O_RDONLY); + + if (0 > request_body_fd) { + php_error(E_WARNING, "REQUEST_BODY_FILE: open('%s') failed: %s (%d)", + request_body_filename, strerror(errno), errno); + return 0; + } + } + } + + /* If REQUEST_BODY_FILE variable not available - read post body from fastcgi stream */ + if (request_body_fd < 0) { + tmp_read_bytes = fcgi_read(request, buffer + read_bytes, count_bytes - read_bytes); + } else { + tmp_read_bytes = read(request_body_fd, buffer + read_bytes, count_bytes - read_bytes); + } } else { tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, count_bytes - read_bytes); } @@ -786,7 +824,12 @@ static void php_cgi_usage(char *argv0) " -s Display colour syntax highlighted source.\n" " -v Version number\n" " -w Display source with stripped comments and whitespace.\n" - " -z Load Zend extension .\n" +#if PHP_FASTCGI_PM + " -x, --fpm Run in FastCGI process manager mode.\n" + " -y, --fpm-config \n" + " Specify alternative path to FastCGI process manager config file.\n" +#endif + " -z Load Zend extension .\n" #if PHP_FASTCGI " -T Measure execution time of script repeated times.\n" #endif @@ -1236,6 +1279,7 @@ PHP_INI_BEGIN() # ifdef PHP_WIN32 STD_PHP_INI_ENTRY("fastcgi.impersonate", "0", PHP_INI_SYSTEM, OnUpdateBool, impersonate, php_cgi_globals_struct, php_cgi_globals) # endif + STD_PHP_INI_ENTRY("fastcgi.error_header", NULL, PHP_INI_SYSTEM, OnUpdateString, error_header, php_cgi_globals_struct, php_cgi_globals) #endif PHP_INI_END() @@ -1258,6 +1302,7 @@ static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals TSRMLS_ # ifdef PHP_WIN32 php_cgi_globals->impersonate = 0; # endif + php_cgi_globals->error_header = NULL; #endif } /* }}} */ @@ -1290,9 +1335,47 @@ static PHP_MSHUTDOWN_FUNCTION(cgi) static PHP_MINFO_FUNCTION(cgi) { DISPLAY_INI_ENTRIES(); + +#if PHP_FASTCGI_PM + +#include "fpm/fpm_autoconf.h" + + php_info_print_table_start(); + php_info_print_table_row(2, "php-fpm", fpm ? "active" : "inactive"); + php_info_print_table_row(2, "php-fpm version", PHP_FPM_VERSION); + php_info_print_table_end(); +#endif + } /* }}} */ +#if PHP_FASTCGI +PHP_FUNCTION(fastcgi_finish_request) +{ + fcgi_request *request = (fcgi_request*) SG(server_context); + + if (fcgi_is_fastcgi() && request->fd >= 0) { + + php_end_ob_buffers(1 TSRMLS_CC); + php_header(TSRMLS_C); + + fcgi_flush(request, 1); + fcgi_close(request, 0, 0); + RETURN_TRUE; + } + + RETURN_FALSE; + +} +#endif + +function_entry cgi_fcgi_sapi_functions[] = { +#if PHP_FASTCGI + PHP_FE(fastcgi_finish_request, NULL) +#endif + {NULL, NULL, NULL} +}; + static zend_module_entry cgi_module_entry = { STANDARD_MODULE_HEADER, #if PHP_FASTCGI @@ -1300,7 +1383,7 @@ static zend_module_entry cgi_module_entry = { #else "cgi", #endif - NULL, + cgi_fcgi_sapi_functions, PHP_MINIT(cgi), PHP_MSHUTDOWN(cgi), NULL, @@ -1340,6 +1423,7 @@ int main(int argc, char *argv[]) char *bindpath = NULL; int fcgi_fd = 0; fcgi_request request; + char *fpm_config = NULL; int repeats = 1; int benchmark = 0; #if HAVE_GETTIMEOFDAY @@ -1460,6 +1544,14 @@ int main(int argc, char *argv[]) case 's': /* generate highlighted HTML from source */ behavior = PHP_MODE_HIGHLIGHT; break; +#if PHP_FASTCGI_PM + case 'y': + fpm_config = php_optarg; + break; + case 'x': + fpm = 1; + break; +#endif } @@ -1524,6 +1616,19 @@ consult the installation file that came with this distribution, or visit \n\ #endif /* FORCE_CGI_REDIRECT */ #if PHP_FASTCGI +#if PHP_FASTCGI_PM + if (fpm) { + if (0 > fpm_init(argc, argv, fpm_config)) { + return FAILURE; + } + + fcgi_fd = fpm_run(&max_requests); + + fcgi_set_is_fastcgi(fastcgi = 1); + } + else +#endif + if (bindpath) { fcgi_fd = fcgi_listen(bindpath, 128); if (fcgi_fd < 0) { @@ -1538,6 +1643,9 @@ consult the installation file that came with this distribution, or visit \n\ if (fastcgi) { /* How many times to run PHP scripts before dying */ +#if PHP_FASTCGI_PM + if (!fpm) +#endif if (getenv("PHP_FCGI_MAX_REQUESTS")) { max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS")); if (max_requests < 0) { @@ -1555,6 +1663,9 @@ consult the installation file that came with this distribution, or visit \n\ #ifndef PHP_WIN32 /* Pre-fork, if required */ +#if PHP_FASTCGI_PM + if (!fpm) +#endif if (getenv("PHP_FCGI_CHILDREN")) { char * children_str = getenv("PHP_FCGI_CHILDREN"); children = atoi(children_str); @@ -1704,6 +1815,8 @@ consult the installation file that came with this distribution, or visit \n\ #endif #if PHP_FASTCGI + request_body_fd = -1; + SG(server_context) = (void *) &request; #else SG(server_context) = (void *) 1; /* avoid server_context==NULL checks */ @@ -1711,6 +1824,10 @@ consult the installation file that came with this distribution, or visit \n\ init_request_info(TSRMLS_C); CG(interactive) = 0; +#if PHP_FASTCGI_PM + if (fpm) fpm_request_info(); +#endif + if (!cgi #if PHP_FASTCGI && !fastcgi @@ -1994,6 +2111,10 @@ consult the installation file that came with this distribution, or visit \n\ } } +#if PHP_FASTCGI_PM + if (fpm) fpm_request_executing(); +#endif + switch (behavior) { case PHP_MODE_STANDARD: php_execute_script(&file_handle TSRMLS_CC); @@ -2046,6 +2167,10 @@ consult the installation file that came with this distribution, or visit \n\ #if PHP_FASTCGI fastcgi_request_done: + + if (request_body_fd != -1) close(request_body_fd); + + request_body_fd = -2; #endif { char *path_translated; @@ -2059,6 +2184,16 @@ fastcgi_request_done: SG(request_info).path_translated = path_translated; } + if (EG(exit_status) == 255) { + if (CGIG(error_header) && *CGIG(error_header)) { + sapi_header_line ctr = {0}; + + ctr.line = CGIG(error_header); + ctr.line_len = strlen(CGIG(error_header)); + sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); + } + } + php_request_shutdown((void *) 0); if (exit_status == 0) { exit_status = EG(exit_status); @@ -2096,15 +2231,20 @@ fastcgi_request_done: if (bindpath) { free(bindpath); } - if (max_requests != 1) { - /* no need to return exit_status of the last request */ - exit_status = 0; - } break; } /* end of fastcgi loop */ } fcgi_shutdown(); + + if (fcgi_in_shutdown() || /* graceful shutdown by a signal */ + (max_requests && (requests == max_requests)) /* we were told to process max_requests and we are done */ + ) { + exit_status = 0; + } + else { + exit_status = 255; + } #endif if (cgi_sapi_module.php_ini_path_override) { --- php-5.2.17/sapi/cgi/config9.m4~ 2012-02-27 14:44:23.000000000 +0200 +++ php-5.2.17/sapi/cgi/config9.m4 2012-02-27 14:48:07.279580606 +0200 @@ -22,6 +22,10 @@ PHP_ARG_ENABLE(path-info-check,, [ --disable-path-info-check CGI: If this is disabled, paths such as /info.php/test?a=b will fail to work], yes, no) +PHP_ARG_ENABLE(fpm,, +[ --enable-fpm FastCGI: If this is enabled, the fastcgi support + will include experimental process manager code], no, no) + dnl dnl CGI setup dnl @@ -54,6 +58,20 @@ if test "$PHP_SAPI" = "default"; then AC_DEFINE_UNQUOTED(PHP_FASTCGI, $PHP_ENABLE_FASTCGI, [ ]) AC_MSG_RESULT($PHP_FASTCGI) + dnl --enable-fpm + if test "$PHP_FASTCGI" = "yes"; then + AC_MSG_CHECKING(whether to enable FastCGI Process Manager) + if test "$PHP_FPM" = "yes"; then + PHP_FASTCGI_PM=1 + else + PHP_FASTCGI_PM=0 + fi + AC_MSG_RESULT($PHP_FPM) + else + PHP_FASTCGI_PM=0 + fi + AC_DEFINE_UNQUOTED(PHP_FASTCGI_PM, $PHP_FASTCGI_PM, [Is experimental fastcgi process manager code activated]) + dnl --enable-force-cgi-redirect AC_MSG_CHECKING(whether to force Apache CGI redirect) if test "$PHP_FORCE_CGI_REDIRECT" = "yes"; then @@ -111,10 +111,10 @@ BUILD_CGI="echo '\#! .' > php.sym && echo >>php.sym && nm -BCpg \`echo \$(PHP_GLOBAL_OBJS) \$(PHP_SAPI_OBJS) | sed 's/\([A-Za-z0-9_]*\)\.lo/\1.o/g'\` | \$(AWK) '{ if (((\$\$2 == \"T\") || (\$\$2 == \"D\") || (\$\$2 == \"B\")) && (substr(\$\$3,1,1) != \".\")) { print \$\$3 } }' | sort -u >> php.sym && \$(LIBTOOL) --mode=link \$(CC) -export-dynamic \$(CFLAGS_CLEAN) \$(EXTRA_CFLAGS) \$(EXTRA_LDFLAGS_PROGRAM) \$(LDFLAGS) -Wl,-brtl -Wl,-bE:php.sym \$(PHP_RPATHS) \$(PHP_GLOBAL_OBJS) \$(PHP_SAPI_OBJS) \$(EXTRA_LIBS) \$(ZEND_EXTRA_LIBS) -o \$(SAPI_CGI_PATH)" ;; *darwin*) - BUILD_CGI="\$(CC) \$(CFLAGS_CLEAN) \$(EXTRA_CFLAGS) \$(EXTRA_LDFLAGS_PROGRAM) \$(LDFLAGS) \$(NATIVE_RPATHS) \$(PHP_GLOBAL_OBJS:.lo=.o) \$(PHP_SAPI_OBJS:.lo=.o) \$(PHP_FRAMEWORKS) \$(EXTRA_LIBS) \$(ZEND_EXTRA_LIBS) -o \$(SAPI_CGI_PATH)" + BUILD_CGI="\$(CC) \$(CFLAGS_CLEAN) \$(EXTRA_CFLAGS) \$(EXTRA_LDFLAGS_PROGRAM) \$(LDFLAGS) \$(NATIVE_RPATHS) \$(PHP_GLOBAL_OBJS:.lo=.o) \$(PHP_SAPI_OBJS:.lo=.o) \$(PHP_FRAMEWORKS) \$(EXTRA_LIBS) \$(SAPI_EXTRA_LIBS) \$(ZEND_EXTRA_LIBS) -o \$(SAPI_CGI_PATH)" ;; *) - BUILD_CGI="\$(LIBTOOL) --mode=link \$(CC) -export-dynamic \$(CFLAGS_CLEAN) \$(EXTRA_CFLAGS) \$(EXTRA_LDFLAGS_PROGRAM) \$(LDFLAGS) \$(PHP_RPATHS) libphp_common.la \$(PHP_SAPI_OBJS) \$(EXTRA_LIBS) \$(ZEND_EXTRA_LIBS) -o \$(SAPI_CGI_PATH)" + BUILD_CGI="\$(LIBTOOL) --mode=link \$(CC) -export-dynamic \$(CFLAGS_CLEAN) \$(EXTRA_CFLAGS) \$(EXTRA_LDFLAGS_PROGRAM) \$(LDFLAGS) \$(PHP_RPATHS) libphp_common.la \$(PHP_SAPI_OBJS) \$(EXTRA_LIBS) \$(SAPI_EXTRA_LIBS) \$(ZEND_EXTRA_LIBS) -o \$(SAPI_CGI_PATH)" ;; esac diff --git a/sapi/cgi/fastcgi.c b/sapi/cgi/fastcgi.c --- a/sapi/cgi/fastcgi.c +++ b/sapi/cgi/fastcgi.c @@ -27,6 +27,11 @@ #include #include +#if PHP_FASTCGI_PM +#include "fpm/fpm.h" +#include "fpm/fpm_request.h" +#endif + #ifdef _WIN32 #include @@ -234,6 +239,8 @@ int fcgi_init(void) } else { return is_fastcgi = 0; } + + fcgi_set_allowed_clients(getenv("FCGI_WEB_SERVER_ADDRS")); #endif } return is_fastcgi; @@ -249,14 +256,26 @@ int fcgi_is_fastcgi(void) } } +void fcgi_set_is_fastcgi(int new_value) +{ + is_fastcgi = new_value; +} + +void fcgi_set_in_shutdown(int new_value) +{ + in_shutdown = new_value; +} + void fcgi_shutdown(void) { if (is_initialized) { zend_hash_destroy(&fcgi_mgmt_vars); } is_fastcgi = 0; + if (allowed_clients) { free(allowed_clients); + allowed_clients = 0; } } @@ -330,6 +349,41 @@ out_fail: } #endif +void fcgi_set_allowed_clients(char *ip) +{ + char *cur, *end; + int n; + + if (ip) { + ip = strdup(ip); + cur = ip; + n = 0; + while (*cur) { + if (*cur == ',') n++; + cur++; + } + if (allowed_clients) free(allowed_clients); + allowed_clients = malloc(sizeof(in_addr_t) * (n+2)); + n = 0; + cur = ip; + while (cur) { + end = strchr(cur, ','); + if (end) { + *end = 0; + end++; + } + allowed_clients[n] = inet_addr(cur); + if (allowed_clients[n] == INADDR_NONE) { + fprintf(stderr, "Wrong IP address '%s' in FCGI_WEB_SERVER_ADDRS\n", cur); + } + n++; + cur = end; + } + allowed_clients[n] = INADDR_NONE; + free(ip); + } +} + static int is_port_number(const char *bindpath) { while (*bindpath) { @@ -458,38 +512,6 @@ int fcgi_listen(const char *path, int backlog) if (!tcp) { chmod(path, 0777); - } else { - char *ip = getenv("FCGI_WEB_SERVER_ADDRS"); - char *cur, *end; - int n; - - if (ip) { - ip = strdup(ip); - cur = ip; - n = 0; - while (*cur) { - if (*cur == ',') n++; - cur++; - } - allowed_clients = malloc(sizeof(in_addr_t) * (n+2)); - n = 0; - cur = ip; - while (cur) { - end = strchr(cur, ','); - if (end) { - *end = 0; - end++; - } - allowed_clients[n] = inet_addr(cur); - if (allowed_clients[n] == INADDR_NONE) { - fprintf(stderr, "Wrong IP address '%s' in FCGI_WEB_SERVER_ADDRS\n", cur); - } - n++; - cur = end; - } - allowed_clients[n] = INADDR_NONE; - free(ip); - } } if (!is_initialized) { @@ -866,7 +888,7 @@ int fcgi_read(fcgi_request *req, char *str, int len) return n; } -static inline void fcgi_close(fcgi_request *req, int force, int destroy) +void fcgi_close(fcgi_request *req, int force, int destroy) { if (destroy) { zend_hash_destroy(&req->env); @@ -906,6 +928,10 @@ static inline void fcgi_close(fcgi_request *req, int force, int destroy) close(req->fd); #endif req->fd = -1; + +#if PHP_FASTCGI_PM + if (fpm) fpm_request_finished(); +#endif } } @@ -953,6 +979,10 @@ int fcgi_accept_request(fcgi_request *req) sa_t sa; socklen_t len = sizeof(sa); +#if PHP_FASTCGI_PM + if (fpm) fpm_request_accepting(); +#endif + FCGI_LOCK(req->listen_socket); req->fd = accept(listen_socket, (struct sockaddr *)&sa, &len); FCGI_UNLOCK(req->listen_socket); @@ -988,6 +1018,11 @@ int fcgi_accept_request(fcgi_request *req) break; #else if (req->fd >= 0) { + +#if PHP_FASTCGI_PM + if (fpm) fpm_request_reading_headers(); +#endif + #if defined(HAVE_SYS_POLL_H) && defined(HAVE_POLL) struct pollfd fds; int ret; diff --git a/sapi/cgi/fastcgi.h b/sapi/cgi/fastcgi.h --- a/sapi/cgi/fastcgi.h +++ b/sapi/cgi/fastcgi.h @@ -114,6 +114,9 @@ typedef struct _fcgi_request { int fcgi_init(void); void fcgi_shutdown(void); int fcgi_is_fastcgi(void); +void fcgi_set_is_fastcgi(int); +void fcgi_set_in_shutdown(int); +void fcgi_set_allowed_clients(char *); int fcgi_in_shutdown(void); int fcgi_listen(const char *path, int backlog); void fcgi_init_request(fcgi_request *req, int listen_socket); @@ -128,6 +131,8 @@ int fcgi_read(fcgi_request *req, char *str, int len); int fcgi_write(fcgi_request *req, fcgi_request_type type, const char *str, int len); int fcgi_flush(fcgi_request *req, int close); +void fcgi_close(fcgi_request *req, int force, int destroy); + #ifdef PHP_WIN32 void fcgi_impersonate(void); #endif diff --git a/sapi/cgi/fpm/Makefile.frag b/sapi/cgi/fpm/Makefile.frag new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/Makefile.frag @@ -0,0 +1,21 @@ + +install-fpm: sapi/cgi/fpm/php-fpm.conf sapi/cgi/fpm/php-fpm + @echo "Installing FPM config: $(INSTALL_ROOT)$(php_fpm_conf_path)" + -@$(mkinstalldirs) \ + $(INSTALL_ROOT)$(prefix)/sbin \ + `dirname "$(INSTALL_ROOT)$(php_fpm_conf_path)"` \ + `dirname "$(INSTALL_ROOT)$(php_fpm_log_path)"` \ + `dirname "$(INSTALL_ROOT)$(php_fpm_pid_path)"` + -@if test -r "$(INSTALL_ROOT)$(php_fpm_conf_path)" ; then \ + dest=`basename "$(php_fpm_conf_path)"`.default ; \ + echo " (installing as $$dest)" ; \ + else \ + dest=`basename "$(php_fpm_conf_path)"` ; \ + fi ; \ + $(INSTALL_DATA) $(top_builddir)/sapi/cgi/fpm/php-fpm.conf $(INSTALL_ROOT)`dirname "$(php_fpm_conf_path)"`/$$dest + @echo "Installing init.d script: $(INSTALL_ROOT)$(prefix)/sbin/php-fpm" + -@$(INSTALL) -m 0755 $(top_builddir)/sapi/cgi/fpm/php-fpm $(INSTALL_ROOT)$(prefix)/sbin/php-fpm + +$(top_builddir)/libevent/libevent.a: $(top_builddir)/libevent/Makefile + cd $(top_builddir)/libevent && $(MAKE) libevent.a + diff --git a/sapi/cgi/fpm/acinclude.m4 b/sapi/cgi/fpm/acinclude.m4 new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/acinclude.m4 @@ -0,0 +1,377 @@ + +AC_DEFUN([AC_FPM_CHECK_FUNC], +[ + SAVED_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $2" + SAVED_LIBS="$LIBS" + LIBS="$LIBS $3" + + AC_CHECK_FUNC([$1],[$4],[$5]) + + CFLAGS="$SAVED_CFLAGS" + LIBS="$SAVED_LIBS" +]) + +AC_DEFUN([AC_FPM_LIBEVENT], +[ + AC_ARG_WITH([libevent], + [ --with-libevent=DIR FPM: libevent install directory]) + + LIBEVENT_CFLAGS="" + LIBEVENT_LIBS="-levent" + LIBEVENT_INCLUDE_PATH="" + + if test "$with_libevent" != "no" -a -n "$with_libevent"; then + LIBEVENT_CFLAGS="-I$with_libevent/include" + LIBEVENT_LIBS="-L$with_libevent/lib $LIBEVENT_LIBS" + LIBEVENT_INCLUDE_PATH="$with_libevent/include" + fi + + AC_MSG_CHECKING([for event.h]) + + found=no + + for dir in "$LIBEVENT_INCLUDE_PATH" /usr/include ; do + if test -r "$dir/event.h" ; then + found=yes + break + fi + done + + AC_MSG_RESULT([$found]) + + AC_FPM_CHECK_FUNC([event_set], [$LIBEVENT_CFLAGS], [$LIBEVENT_LIBS], , + [AC_MSG_ERROR([Failed to link with libevent. Perhaps --with-libevent=DIR option could help.])]) + + AC_FPM_CHECK_FUNC([event_base_free], [$LIBEVENT_CFLAGS], [$LIBEVENT_LIBS], , + [AC_MSG_ERROR([You have too old version. libevent version >= 1.2 is required.])]) + +]) + +AC_DEFUN([AC_FPM_LIBXML], +[ + AC_MSG_RESULT([checking for XML configuration]) + + AC_ARG_WITH(xml-config, + [ --with-xml-config=PATH FPM: use xml-config in PATH to find libxml], + [XMLCONFIG="$withval"], + [AC_PATH_PROGS(XMLCONFIG, [xml2-config xml-config], "")] + ) + + if test "x$XMLCONFIG" = "x"; then + AC_MSG_ERROR([XML configuration could not be found]) + else + AC_MSG_CHECKING([for libxml library]) + + if test ! -x "$XMLCONFIG"; then + AC_MSG_ERROR([$XMLCONFIG cannot be executed]) + fi + + LIBXML_LIBS="`$XMLCONFIG --libs`" + LIBXML_CFLAGS="`$XMLCONFIG --cflags`" + LIBXML_VERSION="`$XMLCONFIG --version`" + + AC_MSG_RESULT([yes, $LIBXML_VERSION]) + + AC_FPM_CHECK_FUNC([xmlParseFile], [$LIBXML_CFLAGS], [$LIBXML_LIBS], , + [AC_MSG_ERROR([Failed to link with libxml])]) + + AC_DEFINE(HAVE_LIBXML, 1, [do we have libxml?]) + fi +]) + +AC_DEFUN([AC_FPM_JUDY], +[ + AC_ARG_WITH([Judy], + [ --with-Judy=DIR FPM: Judy install directory]) + + JUDY_CFLAGS="" + JUDY_LIBS="-lJudy" + JUDY_INCLUDE_PATH="" + + if test "$with_Judy" != "no" -a -n "$with_Judy"; then + JUDY_INCLUDE_PATH="$with_Judy/include" + JUDY_CFLAGS="-I$with_Judy/include $JUDY_CFLAGS" + JUDY_LIBS="-L$with_Judy/lib $JUDY_LIBS" + fi + + AC_MSG_CHECKING([for Judy.h]) + + found=no + + for dir in "$JUDY_INCLUDE_PATH" /usr/include ; do + if test -r "$dir/Judy.h" ; then + found=yes + break + fi + done + + AC_MSG_RESULT([$found]) + + AC_FPM_CHECK_FUNC([JudyLCount], [$JUDY_CFLAGS], [$JUDY_LIBS], , + [AC_MSG_ERROR([Failed to link with Judy])]) + +]) + +AC_DEFUN([AC_FPM_CLOCK], +[ + have_clock_gettime=no + + AC_MSG_CHECKING([for clock_gettime]) + + AC_TRY_LINK([ #include ], [struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);], [ + have_clock_gettime=yes + AC_MSG_RESULT([yes]) + ], [ + AC_MSG_RESULT([no]) + ]) + + if test "$have_clock_gettime" = "no"; then + AC_MSG_CHECKING([for clock_gettime in -lrt]) + + SAVED_LIBS="$LIBS" + LIBS="$LIBS -lrt" + + AC_TRY_LINK([ #include ], [struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);], [ + have_clock_gettime=yes + AC_MSG_RESULT([yes]) + ], [ + LIBS="$SAVED_LIBS" + AC_MSG_RESULT([no]) + ]) + fi + + if test "$have_clock_gettime" = "yes"; then + AC_DEFINE([HAVE_CLOCK_GETTIME], 1, [do we have clock_gettime?]) + fi + + have_clock_get_time=no + + if test "$have_clock_gettime" = "no"; then + AC_MSG_CHECKING([for clock_get_time]) + + AC_TRY_RUN([ #include + #include + #include + + int main() + { + kern_return_t ret; clock_serv_t aClock; mach_timespec_t aTime; + ret = host_get_clock_service(mach_host_self(), REALTIME_CLOCK, &aClock); + + if (ret != KERN_SUCCESS) { + return 1; + } + + ret = clock_get_time(aClock, &aTime); + if (ret != KERN_SUCCESS) { + return 2; + } + + return 0; + } + ], [ + have_clock_get_time=yes + AC_MSG_RESULT([yes]) + ], [ + AC_MSG_RESULT([no]) + ]) + fi + + if test "$have_clock_get_time" = "yes"; then + AC_DEFINE([HAVE_CLOCK_GET_TIME], 1, [do we have clock_get_time?]) + fi +]) + +AC_DEFUN([AC_FPM_TRACE], +[ + have_ptrace=no + have_broken_ptrace=no + + AC_MSG_CHECKING([for ptrace]) + + AC_TRY_COMPILE([ + #include + #include ], [ptrace(0, 0, (void *) 0, 0);], [ + have_ptrace=yes + AC_MSG_RESULT([yes]) + ], [ + AC_MSG_RESULT([no]) + ]) + + if test "$have_ptrace" = "yes"; then + AC_MSG_CHECKING([whether ptrace works]) + + AC_TRY_RUN([ + #include + #include + #include + #include + #include + #include + + #if !defined(PTRACE_ATTACH) && defined(PT_ATTACH) + #define PTRACE_ATTACH PT_ATTACH + #endif + + #if !defined(PTRACE_DETACH) && defined(PT_DETACH) + #define PTRACE_DETACH PT_DETACH + #endif + + #if !defined(PTRACE_PEEKDATA) && defined(PT_READ_D) + #define PTRACE_PEEKDATA PT_READ_D + #endif + + int main() + { + long v1 = (unsigned int) -1; /* copy will fail if sizeof(long) == 8 and we've got "int ptrace()" */ + long v2; + pid_t child; + int status; + + if ( (child = fork()) ) { /* parent */ + int ret = 0; + + if (0 > ptrace(PTRACE_ATTACH, child, 0, 0)) { + return 1; + } + + waitpid(child, &status, 0); + + #ifdef PT_IO + struct ptrace_io_desc ptio = { + .piod_op = PIOD_READ_D, + .piod_offs = &v1, + .piod_addr = &v2, + .piod_len = sizeof(v1) + }; + + if (0 > ptrace(PT_IO, child, (void *) &ptio, 0)) { + ret = 1; + } + #else + errno = 0; + + v2 = ptrace(PTRACE_PEEKDATA, child, (void *) &v1, 0); + + if (errno) { + ret = 1; + } + #endif + ptrace(PTRACE_DETACH, child, (void *) 1, 0); + + kill(child, SIGKILL); + + return ret ? ret : (v1 != v2); + } + else { /* child */ + sleep(10); + return 0; + } + } + ], [ + AC_MSG_RESULT([yes]) + ], [ + have_ptrace=no + have_broken_ptrace=yes + AC_MSG_RESULT([no]) + ]) + fi + + if test "$have_ptrace" = "yes"; then + AC_DEFINE([HAVE_PTRACE], 1, [do we have ptrace?]) + fi + + have_mach_vm_read=no + + if test "$have_broken_ptrace" = "yes"; then + AC_MSG_CHECKING([for mach_vm_read]) + + AC_TRY_COMPILE([ #include + #include + ], [ + mach_vm_read((vm_map_t)0, (mach_vm_address_t)0, (mach_vm_size_t)0, (vm_offset_t *)0, (mach_msg_type_number_t*)0); + ], [ + have_mach_vm_read=yes + AC_MSG_RESULT([yes]) + ], [ + AC_MSG_RESULT([no]) + ]) + fi + + if test "$have_mach_vm_read" = "yes"; then + AC_DEFINE([HAVE_MACH_VM_READ], 1, [do we have mach_vm_read?]) + fi + + proc_mem_file="" + + if test -r /proc/$$/mem ; then + proc_mem_file="mem" + else + if test -r /proc/$$/as ; then + proc_mem_file="as" + fi + fi + + if test -n "$proc_mem_file" ; then + AC_MSG_CHECKING([for proc mem file]) + + AC_TRY_RUN([ + #define _GNU_SOURCE + #define _FILE_OFFSET_BITS 64 + #include + #include + #include + #include + #include + #include + int main() + { + long v1 = (unsigned int) -1, v2 = 0; + char buf[128]; + int fd; + sprintf(buf, "/proc/%d/$proc_mem_file", getpid()); + fd = open(buf, O_RDONLY); + if (0 > fd) { + return 1; + } + if (sizeof(long) != pread(fd, &v2, sizeof(long), (uintptr_t) &v1)) { + close(fd); + return 1; + } + close(fd); + return v1 != v2; + } + ], [ + AC_MSG_RESULT([$proc_mem_file]) + ], [ + proc_mem_file="" + AC_MSG_RESULT([no]) + ]) + fi + + if test -n "$proc_mem_file"; then + AC_DEFINE_UNQUOTED([PROC_MEM_FILE], "$proc_mem_file", [/proc/pid/mem interface]) + fi + + if test "$have_ptrace" = "yes"; then + FPM_SOURCES="$FPM_SOURCES fpm_trace.c fpm_trace_ptrace.c" + elif test -n "$proc_mem_file"; then + FPM_SOURCES="$FPM_SOURCES fpm_trace.c fpm_trace_pread.c" + elif test "$have_mach_vm_read" = "yes" ; then + FPM_SOURCES="$FPM_SOURCES fpm_trace.c fpm_trace_mach.c" + fi + +]) + +AC_DEFUN([AC_FPM_PRCTL], +[ + AC_MSG_CHECKING([for prctl]) + + AC_TRY_COMPILE([ #include ], [prctl(0, 0, 0, 0, 0);], [ + AC_DEFINE([HAVE_PRCTL], 1, [do we have prctl?]) + AC_MSG_RESULT([yes]) + ], [ + AC_MSG_RESULT([no]) + ]) +]) diff --git a/sapi/cgi/fpm/conf/php-fpm.conf.in b/sapi/cgi/fpm/conf/php-fpm.conf.in new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/conf/php-fpm.conf.in @@ -0,0 +1,156 @@ + + + + All relative paths in this config are relative to php's install prefix + +
+ + Pid file + @php_fpm_pid_path@ + + Error log file + @php_fpm_log_path@ + + Log level + notice + + When this amount of php processes exited with SIGSEGV or SIGBUS ... + 10 + + ... in a less than this interval of time, a graceful restart will be initiated. + Useful to work around accidental curruptions in accelerator's shared memory. + 1m + + Time limit on waiting child's reaction on signals from master + 5s + + Set to 'no' to debug fpm + yes + +
+ + + +
+ + Name of pool. Used in logs and stats. + default + + Address to accept fastcgi requests on. + Valid syntax is 'ip.ad.re.ss:port' or just 'port' or '/path/to/unix/socket' + 127.0.0.1:9000 + + + + Set listen(2) backlog + -1 + + Set permissions for unix socket, if one used. + In Linux read/write permissions must be set in order to allow connections from web server. + Many BSD-derrived systems allow connections regardless of permissions. + + + 0666 + + + Additional php.ini defines, specific to this pool of workers. + + + + + + Unix user of processes + + + Unix group of processes + + + Process manager settings + + + Sets style of controling worker process count. + Valid values are 'static' and 'apache-like' + static + + Sets the limit on the number of simultaneous requests that will be served. + Equivalent to Apache MaxClients directive. + Equivalent to PHP_FCGI_CHILDREN environment in original php.fcgi + Used with any pm_style. + 5 + + Settings group for 'apache-like' pm style + + + Sets the number of server processes created on startup. + Used only when 'apache-like' pm_style is selected + 20 + + Sets the desired minimum number of idle server processes. + Used only when 'apache-like' pm_style is selected + 5 + + Sets the desired maximum number of idle server processes. + Used only when 'apache-like' pm_style is selected + 35 + + + + + + The timeout (in seconds) for serving a single request after which the worker process will be terminated + Should be used when 'max_execution_time' ini option does not stop script execution for some reason + '0s' means 'off' + 0s + + The timeout (in seconds) for serving of single request after which a php backtrace will be dumped to slow.log file + '0s' means 'off' + 0s + + The log file for slow requests + logs/slow.log + + Set open file desc rlimit + 1024 + + Set max core size rlimit + 0 + + Chroot to this directory at the start, absolute path + + + Chdir to this directory at the start, absolute path + + + Redirect workers' stdout and stderr into main error log. + If not set, they will be redirected to /dev/null, according to FastCGI specs + yes + + How much requests each process should execute before respawn. + Useful to work around memory leaks in 3rd party libraries. + For endless request processing please specify 0 + Equivalent to PHP_FCGI_MAX_REQUESTS + 500 + + Comma separated list of ipv4 addresses of FastCGI clients that allowed to connect. + Equivalent to FCGI_WEB_SERVER_ADDRS environment in original php.fcgi (5.2.2+) + Makes sense only with AF_INET listening socket. + 127.0.0.1 + + Pass environment variables like LD_LIBRARY_PATH + All $VARIABLEs are taken from current environment + + $HOSTNAME + /usr/local/bin:/usr/bin:/bin + /tmp + /tmp + /tmp + $OSTYPE + $MACHTYPE + 2 + + +
+ +
+ +
diff --git a/sapi/cgi/fpm/config.m4 b/sapi/cgi/fpm/config.m4 new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/config.m4 @@ -0,0 +1,117 @@ + +FPM_VERSION="0.5.14" + +PHP_ARG_WITH(fpm-conf, for php-fpm config file path, +[ --with-fpm-conf=PATH Set the path for php-fpm configuration file [PREFIX/etc/php-fpm.conf]], \$prefix/etc/php-fpm.conf, no) + +PHP_ARG_WITH(fpm-log, for php-fpm log file path, +[ --with-fpm-log=PATH Set the path for php-fpm log file [PREFIX/logs/php-fpm.log]], \$prefix/logs/php-fpm.log, no) + +PHP_ARG_WITH(fpm-pid, for php-fpm pid file path, +[ --with-fpm-pid=PATH Set the path for php-fpm pid file [PREFIX/logs/php-fpm.pid]], \$prefix/logs/php-fpm.pid, no) + +FPM_SOURCES="fpm.c \ + fpm_conf.c \ + fpm_signals.c \ + fpm_children.c \ + fpm_worker_pool.c \ + fpm_unix.c \ + fpm_cleanup.c \ + fpm_sockets.c \ + fpm_stdio.c \ + fpm_env.c \ + fpm_events.c \ + fpm_php.c \ + fpm_php_trace.c \ + fpm_process_ctl.c \ + fpm_request.c \ + fpm_clock.c \ + fpm_shm.c \ + fpm_shm_slots.c \ + xml_config.c \ + zlog.c" + +dnl AC_FPM_LIBEVENT +AC_FPM_LIBXML +AC_FPM_PRCTL +AC_FPM_CLOCK +AC_FPM_TRACE +dnl AC_FPM_JUDY + +LIBEVENT_CFLAGS="" +LIBEVENT_LIBS="-levent" + +SAPI_EXTRA_DEPS="$LIBEVENT_LIBS" + +FPM_CFLAGS="$LIBEVENT_CFLAGS $LIBXML_CFLAGS $JUDY_CFLAGS" + +dnl FPM_CFLAGS="$FPM_CFLAGS -DJUDYERROR_NOTEST" # for Judy +FPM_CFLAGS="$FPM_CFLAGS -I$abs_srcdir/sapi/cgi" # for fastcgi.h + +if test "$ICC" = "yes" ; then + FPM_ADD_CFLAGS="-Wall -wd279,310,869,810,981" +elif test "$GCC" = "yes" ; then + FPM_ADD_CFLAGS="-Wall -Wpointer-arith -Wno-unused-parameter -Wunused-variable -Wunused-value -fno-strict-aliasing" +fi + +if test -n "$FPM_WERROR" ; then + FPM_ADD_CFLAGS="$FPM_ADD_CFLAGS -Werror" +fi + +FPM_CFLAGS="$FPM_ADD_CFLAGS $FPM_CFLAGS" + +PHP_ADD_MAKEFILE_FRAGMENT($abs_srcdir/sapi/cgi/fpm/Makefile.frag) + +PHP_ADD_SOURCES(sapi/cgi/fpm, $FPM_SOURCES, $FPM_CFLAGS, sapi) + +PHP_ADD_BUILD_DIR(sapi/cgi/fpm) + +install_fpm="install-fpm" + +SAPI_EXTRA_LIBS="$LIBEVENT_LIBS $LIBXML_LIBS $JUDY_LIBS" + + +if test "$prefix" = "NONE" ; then + fpm_prefix=/usr/local +else + fpm_prefix="$prefix" +fi + +if test "$PHP_FPM_CONF" = "\$prefix/etc/php-fpm.conf" ; then + php_fpm_conf_path="$fpm_prefix/etc/php-fpm.conf" +else + php_fpm_conf_path="$PHP_FPM_CONF" +fi + +if test "$PHP_FPM_LOG" = "\$prefix/logs/php-fpm.log" ; then + php_fpm_log_path="$fpm_prefix/logs/php-fpm.log" +else + php_fpm_log_path="$PHP_FPM_LOG" +fi + +if test "$PHP_FPM_PID" = "\$prefix/logs/php-fpm.pid" ; then + php_fpm_pid_path="$fpm_prefix/logs/php-fpm.pid" +else + php_fpm_pid_path="$PHP_FPM_PID" +fi + + +if grep nobody /etc/group >/dev/null 2>&1; then + php_fpm_group=nobody +else + if grep nogroup /etc/group >/dev/null 2>&1; then + php_fpm_group=nogroup + else + php_fpm_group=nobody + fi +fi + +PHP_SUBST_OLD(php_fpm_conf_path) +PHP_SUBST_OLD(php_fpm_log_path) +PHP_SUBST_OLD(php_fpm_pid_path) +PHP_SUBST_OLD(php_fpm_group) +PHP_SUBST_OLD(FPM_VERSION) + +PHP_OUTPUT(sapi/cgi/fpm/fpm_autoconf.h) +PHP_OUTPUT(sapi/cgi/fpm/php-fpm.conf:sapi/cgi/fpm/conf/php-fpm.conf.in) +PHP_OUTPUT(sapi/cgi/fpm/php-fpm:sapi/cgi/fpm/init.d/php-fpm.in) diff --git a/sapi/cgi/fpm/fpm.c b/sapi/cgi/fpm/fpm.c new file mode 100644 index 0000000..9db2c9b --- /dev/null +++ b/sapi/cgi/fpm/fpm.c @@ -0,0 +1,84 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include /* for exit */ + +#include "fpm.h" +#include "fpm_children.h" +#include "fpm_signals.h" +#include "fpm_env.h" +#include "fpm_events.h" +#include "fpm_cleanup.h" +#include "fpm_php.h" +#include "fpm_sockets.h" +#include "fpm_unix.h" +#include "fpm_process_ctl.h" +#include "fpm_conf.h" +#include "fpm_worker_pool.h" +#include "fpm_stdio.h" +#include "zlog.h" + +int fpm; + +struct fpm_globals_s fpm_globals; + +int fpm_init(int argc, char **argv, char *config) +{ + fpm_globals.argc = argc; + fpm_globals.argv = argv; + fpm_globals.config = config; + + if (0 > fpm_php_init_main() || + 0 > fpm_stdio_init_main() || + 0 > fpm_conf_init_main() || + 0 > fpm_unix_init_main() || + 0 > fpm_env_init_main() || + 0 > fpm_signals_init_main() || + 0 > fpm_pctl_init_main() || + 0 > fpm_children_init_main() || + 0 > fpm_sockets_init_main() || + 0 > fpm_worker_pool_init_main() || + 0 > fpm_event_init_main()) { + return -1; + } + + if (0 > fpm_conf_write_pid()) { + return -1; + } + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "fpm is running, pid %d", (int) fpm_globals.parent_pid); + + return 0; +} + +/* children: return listening socket + parent: never return */ +int fpm_run(int *max_requests) +{ + struct fpm_worker_pool_s *wp; + + /* create initial children in all pools */ + for (wp = fpm_worker_all_pools; wp; wp = wp->next) { + int is_parent; + + is_parent = fpm_children_create_initial(wp); + + if (!is_parent) { + goto run_child; + } + } + + /* run event loop forever */ + fpm_event_loop(); + +run_child: /* only workers reach this point */ + + fpm_cleanups_run(FPM_CLEANUP_CHILD); + + *max_requests = fpm_globals.max_requests; + return fpm_globals.listening_socket; +} + diff --git a/sapi/cgi/fpm/fpm.h b/sapi/cgi/fpm/fpm.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm.h @@ -0,0 +1,30 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_H +#define FPM_H 1 + +#include + +int fpm_run(int *max_requests); +int fpm_init(int argc, char **argv, char *config); + +struct fpm_globals_s { + pid_t parent_pid; + int argc; + char **argv; + char *config; + int running_children; + int error_log_fd; + int log_level; + int listening_socket; /* for this child */ + int max_requests; /* for this child */ + int is_child; +}; + +extern struct fpm_globals_s fpm_globals; + +extern int fpm; + +#endif diff --git a/sapi/cgi/fpm/fpm_arrays.h b/sapi/cgi/fpm/fpm_arrays.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_arrays.h @@ -0,0 +1,110 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_ARRAYS_H +#define FPM_ARRAYS_H 1 + +#include +#include + +struct fpm_array_s { + void *data; + size_t sz; + size_t used; + size_t allocated; +}; + +static inline struct fpm_array_s *fpm_array_init(struct fpm_array_s *a, unsigned int sz, unsigned int initial_num) +{ + void *allocated = 0; + + if (!a) { + a = malloc(sizeof(struct fpm_array_s)); + + if (!a) { + return 0; + } + + allocated = a; + } + + a->sz = sz; + + a->data = calloc(sz, initial_num); + + if (!a->data) { + free(allocated); + return 0; + } + + a->allocated = initial_num; + a->used = 0; + + return a; +} + +static inline void *fpm_array_item(struct fpm_array_s *a, unsigned int n) +{ + char *ret; + + ret = (char *) a->data + a->sz * n; + + return ret; +} + +static inline void *fpm_array_item_last(struct fpm_array_s *a) +{ + return fpm_array_item(a, a->used - 1); +} + +static inline int fpm_array_item_remove(struct fpm_array_s *a, unsigned int n) +{ + int ret = -1; + + if (n < a->used - 1) { + void *last = fpm_array_item(a, a->used - 1); + void *to_remove = fpm_array_item(a, n); + + memcpy(to_remove, last, a->sz); + + ret = n; + } + + --a->used; + + return ret; +} + +static inline void *fpm_array_push(struct fpm_array_s *a) +{ + void *ret; + + if (a->used == a->allocated) { + size_t new_allocated = a->allocated ? a->allocated * 2 : 20; + void *new_ptr = realloc(a->data, a->sz * new_allocated); + + if (!new_ptr) { + return 0; + } + + a->data = new_ptr; + a->allocated = new_allocated; + } + + ret = fpm_array_item(a, a->used); + + ++a->used; + + return ret; +} + +static inline void fpm_array_free(struct fpm_array_s *a) +{ + free(a->data); + a->data = 0; + a->sz = 0; + a->used = a->allocated = 0; +} + +#endif diff --git a/sapi/cgi/fpm/fpm_atomic.h b/sapi/cgi/fpm/fpm_atomic.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_atomic.h @@ -0,0 +1,85 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_ATOMIC_H +#define FPM_ATOMIC_H 1 + +#include +#include + +#if ( __i386__ || __i386 ) + +typedef int32_t atomic_int_t; +typedef uint32_t atomic_uint_t; +typedef volatile atomic_uint_t atomic_t; + + +static inline atomic_int_t atomic_fetch_add(atomic_t *value, atomic_int_t add) +{ + __asm__ volatile ( "lock;" "xaddl %0, %1;" : + "+r" (add) : "m" (*value) : "memory"); + + return add; +} + +static inline atomic_uint_t atomic_cmp_set(atomic_t *lock, atomic_uint_t old, atomic_uint_t set) +{ + unsigned char res; + + __asm__ volatile ( "lock;" "cmpxchgl %3, %1;" "sete %0;" : + "=a" (res) : "m" (*lock), "a" (old), "r" (set) : "memory"); + + return res; +} + +#elif ( __amd64__ || __amd64 ) + +typedef int64_t atomic_int_t; +typedef uint64_t atomic_uint_t; +typedef volatile atomic_uint_t atomic_t; + +static inline atomic_int_t atomic_fetch_add(atomic_t *value, atomic_int_t add) +{ + __asm__ volatile ( "lock;" "xaddq %0, %1;" : + "+r" (add) : "m" (*value) : "memory"); + + return add; +} + +static inline atomic_uint_t atomic_cmp_set(atomic_t *lock, atomic_uint_t old, atomic_uint_t set) +{ + unsigned char res; + + __asm__ volatile ( "lock;" "cmpxchgq %3, %1;" "sete %0;" : + "=a" (res) : "m" (*lock), "a" (old), "r" (set) : "memory"); + + return res; +} + +#else + +#error unsupported processor. please write a patch and send it to me + +#endif + +static inline int fpm_spinlock(atomic_t *lock, int try_once) +{ + if (try_once) { + return atomic_cmp_set(lock, 0, 1) ? 0 : -1; + } + + for (;;) { + + if (atomic_cmp_set(lock, 0, 1)) { + break; + } + + sched_yield(); + } + + return 0; +} + +#endif + diff --git a/sapi/cgi/fpm/fpm_autoconf.h.in b/sapi/cgi/fpm/fpm_autoconf.h.in new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_autoconf.h.in @@ -0,0 +1,9 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#define PHP_FPM_VERSION "@FPM_VERSION@" +#define PHP_FPM_CONF_PATH "@php_fpm_conf_path@" +#define PHP_FPM_LOG_PATH "@php_fpm_log_path@" +#define PHP_FPM_PID_PATH "@php_fpm_pid_path@" + diff --git a/sapi/cgi/fpm/fpm_children.c b/sapi/cgi/fpm/fpm_children.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_children.c @@ -0,0 +1,385 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include +#include +#include +#include + +#include "fpm.h" +#include "fpm_children.h" +#include "fpm_signals.h" +#include "fpm_worker_pool.h" +#include "fpm_sockets.h" +#include "fpm_process_ctl.h" +#include "fpm_php.h" +#include "fpm_conf.h" +#include "fpm_cleanup.h" +#include "fpm_events.h" +#include "fpm_clock.h" +#include "fpm_stdio.h" +#include "fpm_unix.h" +#include "fpm_env.h" +#include "fpm_shm_slots.h" + +#include "zlog.h" + +static time_t *last_faults; +static int fault; + +static int fpm_children_make(struct fpm_worker_pool_s *wp, int in_event_loop); + +static void fpm_children_cleanup(int which, void *arg) +{ + free(last_faults); +} + +static struct fpm_child_s *fpm_child_alloc() +{ + struct fpm_child_s *ret; + + ret = malloc(sizeof(struct fpm_child_s)); + + if (!ret) return 0; + + memset(ret, 0, sizeof(*ret)); + + return ret; +} + +static void fpm_child_free(struct fpm_child_s *child) +{ + free(child); +} + +static void fpm_child_close(struct fpm_child_s *child, int in_event_loop) +{ + if (child->fd_stdout != -1) { + if (in_event_loop) { + fpm_event_fire(&child->ev_stdout); + } + if (child->fd_stdout != -1) { + close(child->fd_stdout); + } + } + + if (child->fd_stderr != -1) { + if (in_event_loop) { + fpm_event_fire(&child->ev_stderr); + } + if (child->fd_stderr != -1) { + close(child->fd_stderr); + } + } + + fpm_child_free(child); +} + +static void fpm_child_link(struct fpm_child_s *child) +{ + struct fpm_worker_pool_s *wp = child->wp; + + ++wp->running_children; + ++fpm_globals.running_children; + + child->next = wp->children; + if (child->next) child->next->prev = child; + child->prev = 0; + wp->children = child; +} + +static void fpm_child_unlink(struct fpm_child_s *child) +{ + --child->wp->running_children; + --fpm_globals.running_children; + + if (child->prev) child->prev->next = child->next; + else child->wp->children = child->next; + if (child->next) child->next->prev = child->prev; + +} + +static struct fpm_child_s *fpm_child_find(pid_t pid) +{ + struct fpm_worker_pool_s *wp; + struct fpm_child_s *child = 0; + + for (wp = fpm_worker_all_pools; wp; wp = wp->next) { + + for (child = wp->children; child; child = child->next) { + if (child->pid == pid) { + break; + } + } + + if (child) break; + } + + if (!child) { + return 0; + } + + return child; +} + +static void fpm_child_init(struct fpm_worker_pool_s *wp) +{ + fpm_globals.max_requests = wp->config->max_requests; + + if (0 > fpm_stdio_init_child(wp) || + 0 > fpm_unix_init_child(wp) || + 0 > fpm_signals_init_child() || + 0 > fpm_env_init_child(wp) || + 0 > fpm_php_init_child(wp)) { + + zlog(ZLOG_STUFF, ZLOG_ERROR, "child failed to initialize (pool %s)", wp->config->name); + exit(255); + } +} + +int fpm_children_free(struct fpm_child_s *child) +{ + struct fpm_child_s *next; + + for (; child; child = next) { + next = child->next; + fpm_child_close(child, 0 /* in_event_loop */); + } + + return 0; +} + +void fpm_children_bury() +{ + int status; + pid_t pid; + struct fpm_child_s *child; + + while ( (pid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) { + char buf[128]; + int severity = ZLOG_NOTICE; + + child = fpm_child_find(pid); + + if (WIFEXITED(status)) { + + snprintf(buf, sizeof(buf), "with code %d", WEXITSTATUS(status)); + + if (WEXITSTATUS(status) != 0) { + severity = ZLOG_WARNING; + } + + } + else if (WIFSIGNALED(status)) { + const char *signame = fpm_signal_names[WTERMSIG(status)]; + const char *have_core = WCOREDUMP(status) ? " (core dumped)" : ""; + + if (signame == NULL) { + signame = ""; + } + + snprintf(buf, sizeof(buf), "on signal %d %s%s", WTERMSIG(status), signame, have_core); + + if (WTERMSIG(status) != SIGQUIT) { /* possible request loss */ + severity = ZLOG_WARNING; + } + } + else if (WIFSTOPPED(status)) { + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "child %d stopped for tracing", (int) pid); + + if (child && child->tracer) { + child->tracer(child); + } + + continue; + } + + if (child) { + struct fpm_worker_pool_s *wp = child->wp; + struct timeval tv1, tv2; + + fpm_child_unlink(child); + + fpm_shm_slots_discard_slot(child); + + fpm_clock_get(&tv1); + + timersub(&tv1, &child->started, &tv2); + + zlog(ZLOG_STUFF, severity, "child %d (pool %s) exited %s after %ld.%06d seconds from start", (int) pid, + child->wp->config->name, buf, tv2.tv_sec, (int) tv2.tv_usec); + + fpm_child_close(child, 1 /* in event_loop */); + + fpm_pctl_child_exited(); + + if (last_faults && (WTERMSIG(status) == SIGSEGV || WTERMSIG(status) == SIGBUS)) { + time_t now = tv1.tv_sec; + int restart_condition = 1; + int i; + + last_faults[fault++] = now; + + if (fault == fpm_global_config.emergency_restart_threshold) { + fault = 0; + } + + for (i = 0; i < fpm_global_config.emergency_restart_threshold; i++) { + if (now - last_faults[i] > fpm_global_config.emergency_restart_interval) { + restart_condition = 0; + break; + } + } + + if (restart_condition) { + + zlog(ZLOG_STUFF, ZLOG_WARNING, "failed processes threshold (%d in %d sec) is reached, initiating reload", + fpm_global_config.emergency_restart_threshold, fpm_global_config.emergency_restart_interval); + + fpm_pctl(FPM_PCTL_STATE_RELOADING, FPM_PCTL_ACTION_SET); + } + } + + fpm_children_make(wp, 1 /* in event loop */); + + if (fpm_globals.is_child) { + break; + } + } + else { + zlog(ZLOG_STUFF, ZLOG_ALERT, "oops, unknown child exited %s", buf); + } + } + +} + +static struct fpm_child_s *fpm_resources_prepare(struct fpm_worker_pool_s *wp) +{ + struct fpm_child_s *c; + + c = fpm_child_alloc(); + + if (!c) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "malloc failed (pool %s)", wp->config->name); + return 0; + } + + c->wp = wp; + c->fd_stdout = -1; c->fd_stderr = -1; + + if (0 > fpm_stdio_prepare_pipes(c)) { + fpm_child_free(c); + return 0; + } + + if (0 > fpm_shm_slots_prepare_slot(c)) { + fpm_stdio_discard_pipes(c); + fpm_child_free(c); + return 0; + } + + return c; +} + +static void fpm_resources_discard(struct fpm_child_s *child) +{ + fpm_shm_slots_discard_slot(child); + fpm_stdio_discard_pipes(child); + fpm_child_free(child); +} + +static void fpm_child_resources_use(struct fpm_child_s *child) +{ + fpm_shm_slots_child_use_slot(child); + fpm_stdio_child_use_pipes(child); + fpm_child_free(child); +} + +static void fpm_parent_resources_use(struct fpm_child_s *child) +{ + fpm_shm_slots_parent_use_slot(child); + fpm_stdio_parent_use_pipes(child); + fpm_child_link(child); +} + +static int fpm_children_make(struct fpm_worker_pool_s *wp, int in_event_loop) +{ + int enough = 0; + pid_t pid; + struct fpm_child_s *child; + + while (!enough && fpm_pctl_can_spawn_children() && wp->running_children < wp->config->pm->max_children) { + + child = fpm_resources_prepare(wp); + + if (!child) { + enough = 1; + break; + } + + pid = fork(); + + switch (pid) { + + case 0 : + fpm_child_resources_use(child); + fpm_globals.is_child = 1; + if (in_event_loop) { + fpm_event_exit_loop(); + } + fpm_child_init(wp); + return 0; + + case -1 : + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "fork() failed"); + enough = 1; + + fpm_resources_discard(child); + + break; /* dont try any more on error */ + + default : + child->pid = pid; + fpm_clock_get(&child->started); + fpm_parent_resources_use(child); + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "child %d (pool %s) started", (int) pid, wp->config->name); + } + + } + + return 1; /* we are done */ +} + +int fpm_children_create_initial(struct fpm_worker_pool_s *wp) +{ + return fpm_children_make(wp, 0 /* not in event loop yet */); +} + +int fpm_children_init_main() +{ + if (fpm_global_config.emergency_restart_threshold && + fpm_global_config.emergency_restart_interval) { + + last_faults = malloc(sizeof(time_t) * fpm_global_config.emergency_restart_threshold); + + if (!last_faults) { + return -1; + } + + memset(last_faults, 0, sizeof(time_t) * fpm_global_config.emergency_restart_threshold); + } + + if (0 > fpm_cleanup_add(FPM_CLEANUP_ALL, fpm_children_cleanup, 0)) { + return -1; + } + + return 0; +} + diff --git a/sapi/cgi/fpm/fpm_children.h b/sapi/cgi/fpm/fpm_children.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_children.h @@ -0,0 +1,33 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_CHILDREN_H +#define FPM_CHILDREN_H 1 + +#include +#include +#include + +#include "fpm_worker_pool.h" + +int fpm_children_create_initial(struct fpm_worker_pool_s *wp); +int fpm_children_free(struct fpm_child_s *child); +void fpm_children_bury(); +int fpm_children_init_main(); + +struct fpm_child_s; + +struct fpm_child_s { + struct fpm_child_s *prev, *next; + struct timeval started; + struct fpm_worker_pool_s *wp; + struct event ev_stdout, ev_stderr; + int shm_slot_i; + int fd_stdout, fd_stderr; + void (*tracer)(struct fpm_child_s *); + struct timeval slow_logged; + pid_t pid; +}; + +#endif diff --git a/sapi/cgi/fpm/fpm_cleanup.c b/sapi/cgi/fpm/fpm_cleanup.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_cleanup.c @@ -0,0 +1,51 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include + +#include "fpm_arrays.h" +#include "fpm_cleanup.h" +#include "zlog.h" + +struct cleanup_s { + int type; + void (*cleanup)(int, void *); + void *arg; +}; + +static struct fpm_array_s cleanups = { .sz = sizeof(struct cleanup_s) }; + +int fpm_cleanup_add(int type, void (*cleanup)(int, void *), void *arg) +{ + struct cleanup_s *c; + + c = fpm_array_push(&cleanups); + + if (!c) { + return -1; + } + + c->type = type; + c->cleanup = cleanup; + c->arg = arg; + + return 0; +} + +void fpm_cleanups_run(int type) +{ + struct cleanup_s *c = fpm_array_item_last(&cleanups); + int cl = cleanups.used; + + for ( ; cl--; c--) { + if (c->type & type) { + c->cleanup(type, c->arg); + } + } + + fpm_array_free(&cleanups); +} + diff --git a/sapi/cgi/fpm/fpm_cleanup.h b/sapi/cgi/fpm/fpm_cleanup.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_cleanup.h @@ -0,0 +1,21 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_CLEANUP_H +#define FPM_CLEANUP_H 1 + +int fpm_cleanup_add(int type, void (*cleanup)(int, void *), void *); +void fpm_cleanups_run(int type); + +enum { + FPM_CLEANUP_CHILD = (1 << 0), + FPM_CLEANUP_PARENT_EXIT = (1 << 1), + FPM_CLEANUP_PARENT_EXIT_MAIN = (1 << 2), + FPM_CLEANUP_PARENT_EXEC = (1 << 3), + FPM_CLEANUP_PARENT = (1 << 1) | (1 << 2) | (1 << 3), + FPM_CLEANUP_ALL = ~0, +}; + +#endif + diff --git a/sapi/cgi/fpm/fpm_clock.c b/sapi/cgi/fpm/fpm_clock.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_clock.c @@ -0,0 +1,115 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#if defined(HAVE_CLOCK_GETTIME) +#include /* for CLOCK_MONOTONIC */ +#endif + +#include "fpm_clock.h" +#include "zlog.h" + + +/* posix monotonic clock - preferred source of time */ +#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) + +static int monotonic_works; + +int fpm_clock_init() +{ + struct timespec ts; + + monotonic_works = 0; + + if (0 == clock_gettime(CLOCK_MONOTONIC, &ts)) { + monotonic_works = 1; + } + + return 0; +} + +int fpm_clock_get(struct timeval *tv) +{ + if (monotonic_works) { + struct timespec ts; + + if (0 > clock_gettime(CLOCK_MONOTONIC, &ts)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "clock_gettime() failed"); + return -1; + } + + tv->tv_sec = ts.tv_sec; + tv->tv_usec = ts.tv_nsec / 1000; + return 0; + } + + return gettimeofday(tv, 0); +} + +/* macosx clock */ +#elif defined(HAVE_CLOCK_GET_TIME) + +#include +#include +#include + +static clock_serv_t mach_clock; + +/* this code borrowed from here: http://lists.apple.com/archives/Darwin-development/2002/Mar/msg00746.html */ +/* mach_clock also should be re-initialized in child process after fork */ +int fpm_clock_init() +{ + kern_return_t ret; + mach_timespec_t aTime; + + ret = host_get_clock_service(mach_host_self(), REALTIME_CLOCK, &mach_clock); + + if (ret != KERN_SUCCESS) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "host_get_clock_service() failed: %s", mach_error_string(ret)); + return -1; + } + + /* test if it works */ + ret = clock_get_time(mach_clock, &aTime); + + if (ret != KERN_SUCCESS) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "clock_get_time() failed: %s", mach_error_string(ret)); + return -1; + } + + return 0; +} + +int fpm_clock_get(struct timeval *tv) +{ + kern_return_t ret; + mach_timespec_t aTime; + + ret = clock_get_time(mach_clock, &aTime); + + if (ret != KERN_SUCCESS) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "clock_get_time() failed: %s", mach_error_string(ret)); + return -1; + } + + tv->tv_sec = aTime.tv_sec; + tv->tv_usec = aTime.tv_nsec / 1000; + + return 0; +} + +#else /* no clock */ + +int fpm_clock_init() +{ + return 0; +} + +int fpm_clock_get(struct timeval *tv) +{ + return gettimeofday(tv, 0); +} + +#endif diff --git a/sapi/cgi/fpm/fpm_clock.h b/sapi/cgi/fpm/fpm_clock.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_clock.h @@ -0,0 +1,13 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_CLOCK_H +#define FPM_CLOCK_H 1 + +#include + +int fpm_clock_init(); +int fpm_clock_get(struct timeval *tv); + +#endif diff --git a/sapi/cgi/fpm/fpm_conf.c b/sapi/cgi/fpm/fpm_conf.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_conf.c @@ -0,0 +1,532 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "fpm.h" +#include "fpm_conf.h" +#include "fpm_stdio.h" +#include "fpm_worker_pool.h" +#include "fpm_cleanup.h" +#include "fpm_php.h" +#include "fpm_sockets.h" +#include "xml_config.h" +#include "zlog.h" + + +struct fpm_global_config_s fpm_global_config; + +static void *fpm_global_config_ptr() +{ + return &fpm_global_config; +} + +static char *fpm_conf_set_log_level(void **conf, char *name, void *vv, intptr_t offset) +{ + char *value = vv; + + if (!strcmp(value, "debug")) { + fpm_globals.log_level = ZLOG_DEBUG; + } + else if (!strcmp(value, "notice")) { + fpm_globals.log_level = ZLOG_NOTICE; + } + else if (!strcmp(value, "warn")) { + fpm_globals.log_level = ZLOG_WARNING; + } + else if (!strcmp(value, "error")) { + fpm_globals.log_level = ZLOG_ERROR; + } + else if (!strcmp(value, "alert")) { + fpm_globals.log_level = ZLOG_ALERT; + } + else { + return "invalid value for 'log_level'"; + } + + return NULL; +} + +static struct xml_conf_section xml_section_fpm_global_options = { + .conf = &fpm_global_config_ptr, + .path = "/configuration/global_options", + .parsers = (struct xml_value_parser []) { + { XML_CONF_SCALAR, "emergency_restart_threshold", &xml_conf_set_slot_integer, offsetof(struct fpm_global_config_s, emergency_restart_threshold) }, + { XML_CONF_SCALAR, "emergency_restart_interval", &xml_conf_set_slot_time, offsetof(struct fpm_global_config_s, emergency_restart_interval) }, + { XML_CONF_SCALAR, "process_control_timeout", &xml_conf_set_slot_time, offsetof(struct fpm_global_config_s, process_control_timeout) }, + { XML_CONF_SCALAR, "daemonize", &xml_conf_set_slot_boolean, offsetof(struct fpm_global_config_s, daemonize) }, + { XML_CONF_SCALAR, "pid_file", &xml_conf_set_slot_string, offsetof(struct fpm_global_config_s, pid_file) }, + { XML_CONF_SCALAR, "error_log", &xml_conf_set_slot_string, offsetof(struct fpm_global_config_s, error_log) }, + { XML_CONF_SCALAR, "log_level", &fpm_conf_set_log_level, 0 }, + { 0, 0, 0, 0 } + } +}; + +static char *fpm_conf_set_pm_style(void **conf, char *name, void *vv, intptr_t offset) +{ + char *value = vv; + struct fpm_pm_s *c = *conf; + + if (!strcmp(value, "static")) { + c->style = PM_STYLE_STATIC; + } + else if (!strcmp(value, "apache-like")) { + c->style = PM_STYLE_APACHE_LIKE; + } + else { + return "invalid value for 'style'"; + } + + return NULL; +} + +static char *fpm_conf_set_rlimit_core(void **conf, char *name, void *vv, intptr_t offset) +{ + char *value = vv; + struct fpm_worker_pool_config_s *c = *conf; + + if (!strcmp(value, "unlimited")) { + c->rlimit_core = -1; + } + else { + int int_value; + void *subconf = &int_value; + char *error; + + error = xml_conf_set_slot_integer(&subconf, name, vv, 0); + + if (error) return error; + + if (int_value < 0) return "invalid value for 'rlimit_core'"; + + c->rlimit_core = int_value; + } + + return NULL; +} + +static char *fpm_conf_set_catch_workers_output(void **conf, char *name, void *vv, intptr_t offset) +{ + struct fpm_worker_pool_config_s *c = *conf; + int int_value; + void *subconf = &int_value; + char *error; + + error = xml_conf_set_slot_boolean(&subconf, name, vv, 0); + + if (error) return error; + + c->catch_workers_output = int_value; + + return NULL; +} + +static struct xml_conf_section fpm_conf_set_apache_like_subsection_conf = { + .path = "apache_like somewhere", /* fixme */ + .parsers = (struct xml_value_parser []) { + { XML_CONF_SCALAR, "StartServers", &xml_conf_set_slot_integer, offsetof(struct fpm_pm_s, options_apache_like.StartServers) }, + { XML_CONF_SCALAR, "MinSpareServers", &xml_conf_set_slot_integer, offsetof(struct fpm_pm_s, options_apache_like.MinSpareServers) }, + { XML_CONF_SCALAR, "MaxSpareServers", &xml_conf_set_slot_integer, offsetof(struct fpm_pm_s, options_apache_like.MaxSpareServers) }, + { 0, 0, 0, 0 } + } +}; + +static char *fpm_conf_set_apache_like_subsection(void **conf, char *name, void *xml_node, intptr_t offset) +{ + return xml_conf_parse_section(conf, &fpm_conf_set_apache_like_subsection_conf, xml_node); +} + +static struct xml_conf_section fpm_conf_set_listen_options_subsection_conf = { + .path = "listen options somewhere", /* fixme */ + .parsers = (struct xml_value_parser []) { + { XML_CONF_SCALAR, "backlog", &xml_conf_set_slot_integer, offsetof(struct fpm_listen_options_s, backlog) }, + { XML_CONF_SCALAR, "owner", &xml_conf_set_slot_string, offsetof(struct fpm_listen_options_s, owner) }, + { XML_CONF_SCALAR, "group", &xml_conf_set_slot_string, offsetof(struct fpm_listen_options_s, group) }, + { XML_CONF_SCALAR, "mode", &xml_conf_set_slot_string, offsetof(struct fpm_listen_options_s, mode) }, + { 0, 0, 0, 0 } + } +}; + +static char *fpm_conf_set_listen_options_subsection(void **conf, char *name, void *xml_node, intptr_t offset) +{ + void *subconf = (char *) *conf + offset; + struct fpm_listen_options_s *lo; + + lo = malloc(sizeof(*lo)); + + if (!lo) { + return "malloc() failed"; + } + + memset(lo, 0, sizeof(*lo)); + + lo->backlog = -1; + + * (struct fpm_listen_options_s **) subconf = lo; + + subconf = lo; + + return xml_conf_parse_section(&subconf, &fpm_conf_set_listen_options_subsection_conf, xml_node); +} + +static struct xml_conf_section fpm_conf_set_pm_subsection_conf = { + .path = "pm settings somewhere", /* fixme */ + .parsers = (struct xml_value_parser []) { + { XML_CONF_SCALAR, "style", &fpm_conf_set_pm_style, 0 }, + { XML_CONF_SCALAR, "max_children", &xml_conf_set_slot_integer, offsetof(struct fpm_pm_s, max_children) }, + { XML_CONF_SUBSECTION, "apache_like", &fpm_conf_set_apache_like_subsection, offsetof(struct fpm_pm_s, options_apache_like) }, + { 0, 0, 0, 0 } + } +}; + +static char *fpm_conf_set_pm_subsection(void **conf, char *name, void *xml_node, intptr_t offset) +{ + void *subconf = (char *) *conf + offset; + struct fpm_pm_s *pm; + + pm = malloc(sizeof(*pm)); + + if (!pm) { + return "fpm_conf_set_pm_subsection(): malloc failed"; + } + + memset(pm, 0, sizeof(*pm)); + + * (struct fpm_pm_s **) subconf = pm; + + subconf = pm; + + return xml_conf_parse_section(&subconf, &fpm_conf_set_pm_subsection_conf, xml_node); +} + +static char *xml_conf_set_slot_key_value_pair(void **conf, char *name, void *vv, intptr_t offset) +{ + char *value = vv; + struct key_value_s *kv; + struct key_value_s ***parent = (struct key_value_s ***) conf; + + kv = malloc(sizeof(*kv)); + + if (!kv) { + return "malloc() failed"; + } + + memset(kv, 0, sizeof(*kv)); + + kv->key = strdup(name); + kv->value = strdup(value); + + if (!kv->key || !kv->value) { + return "xml_conf_set_slot_key_value_pair(): strdup() failed"; + } + + **parent = kv; + + *parent = &kv->next; + + return NULL; +} + +static struct xml_conf_section fpm_conf_set_key_value_pairs_subsection_conf = { + .path = "key_value_pairs somewhere", /* fixme */ + .parsers = (struct xml_value_parser []) { + { XML_CONF_SCALAR, 0, &xml_conf_set_slot_key_value_pair, 0 }, + { 0, 0, 0, 0 } + } +}; + +static char *fpm_conf_set_key_value_pairs_subsection(void **conf, char *name, void *xml_node, intptr_t offset) +{ + void *next_kv = (char *) *conf + offset; + + return xml_conf_parse_section(&next_kv, &fpm_conf_set_key_value_pairs_subsection_conf, xml_node); +} + +static void *fpm_worker_pool_config_alloc() +{ + static struct fpm_worker_pool_s *current_wp = 0; + struct fpm_worker_pool_s *wp; + + wp = fpm_worker_pool_alloc(); + + if (!wp) return 0; + + wp->config = malloc(sizeof(struct fpm_worker_pool_config_s)); + + if (!wp->config) return 0; + + memset(wp->config, 0, sizeof(struct fpm_worker_pool_config_s)); + + if (current_wp) current_wp->next = wp; + + current_wp = wp; + + return wp->config; +} + +int fpm_worker_pool_config_free(struct fpm_worker_pool_config_s *wpc) +{ + struct key_value_s *kv, *kv_next; + + free(wpc->name); + free(wpc->listen_address); + if (wpc->listen_options) { + free(wpc->listen_options->owner); + free(wpc->listen_options->group); + free(wpc->listen_options->mode); + free(wpc->listen_options); + } + for (kv = wpc->php_defines; kv; kv = kv_next) { + kv_next = kv->next; + free(kv->key); + free(kv->value); + free(kv); + } + for (kv = wpc->environment; kv; kv = kv_next) { + kv_next = kv->next; + free(kv->key); + free(kv->value); + free(kv); + } + free(wpc->pm); + free(wpc->user); + free(wpc->group); + free(wpc->chroot); + free(wpc->chdir); + free(wpc->allowed_clients); + free(wpc->slowlog); + + return 0; +} + +static struct xml_conf_section xml_section_fpm_worker_pool_config = { + .conf = &fpm_worker_pool_config_alloc, + .path = "/configuration/workers/pool", + .parsers = (struct xml_value_parser []) { + { XML_CONF_SCALAR, "name", &xml_conf_set_slot_string, offsetof(struct fpm_worker_pool_config_s, name) }, + { XML_CONF_SCALAR, "listen_address", &xml_conf_set_slot_string, offsetof(struct fpm_worker_pool_config_s, listen_address) }, + { XML_CONF_SUBSECTION, "listen_options", &fpm_conf_set_listen_options_subsection, offsetof(struct fpm_worker_pool_config_s, listen_options) }, + { XML_CONF_SUBSECTION, "php_defines", &fpm_conf_set_key_value_pairs_subsection, offsetof(struct fpm_worker_pool_config_s, php_defines) }, + { XML_CONF_SCALAR, "user", &xml_conf_set_slot_string, offsetof(struct fpm_worker_pool_config_s, user) }, + { XML_CONF_SCALAR, "group", &xml_conf_set_slot_string, offsetof(struct fpm_worker_pool_config_s, group) }, + { XML_CONF_SCALAR, "chroot", &xml_conf_set_slot_string, offsetof(struct fpm_worker_pool_config_s, chroot) }, + { XML_CONF_SCALAR, "chdir", &xml_conf_set_slot_string, offsetof(struct fpm_worker_pool_config_s, chdir) }, + { XML_CONF_SCALAR, "allowed_clients", &xml_conf_set_slot_string, offsetof(struct fpm_worker_pool_config_s, allowed_clients) }, + { XML_CONF_SUBSECTION, "environment", &fpm_conf_set_key_value_pairs_subsection, offsetof(struct fpm_worker_pool_config_s, environment) }, + { XML_CONF_SCALAR, "request_terminate_timeout", &xml_conf_set_slot_time, offsetof(struct fpm_worker_pool_config_s, request_terminate_timeout) }, + { XML_CONF_SCALAR, "request_slowlog_timeout", &xml_conf_set_slot_time, offsetof(struct fpm_worker_pool_config_s, request_slowlog_timeout) }, + { XML_CONF_SCALAR, "slowlog", &xml_conf_set_slot_string, offsetof(struct fpm_worker_pool_config_s, slowlog) }, + { XML_CONF_SCALAR, "rlimit_files", &xml_conf_set_slot_integer, offsetof(struct fpm_worker_pool_config_s, rlimit_files) }, + { XML_CONF_SCALAR, "rlimit_core", &fpm_conf_set_rlimit_core, 0 }, + { XML_CONF_SCALAR, "max_requests", &xml_conf_set_slot_integer, offsetof(struct fpm_worker_pool_config_s, max_requests) }, + { XML_CONF_SCALAR, "catch_workers_output", &fpm_conf_set_catch_workers_output, 0 }, + { XML_CONF_SUBSECTION, "pm", &fpm_conf_set_pm_subsection, offsetof(struct fpm_worker_pool_config_s, pm) }, + { 0, 0, 0, 0 } + } +}; + +static struct xml_conf_section *fpm_conf_all_sections[] = { + &xml_section_fpm_global_options, + &xml_section_fpm_worker_pool_config, + 0 +}; + +static int fpm_evaluate_full_path(char **path) +{ + if (**path != '/') { + char *full_path; + + full_path = malloc(sizeof(PHP_PREFIX) + strlen(*path) + 1); + + if (!full_path) return -1; + + sprintf(full_path, "%s/%s", PHP_PREFIX, *path); + + free(*path); + + *path = full_path; + } + + return 0; +} + +static int fpm_conf_process_all_pools() +{ + struct fpm_worker_pool_s *wp; + + if (!fpm_worker_all_pools) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "at least one pool section must be specified in config file"); + return -1; + } + + for (wp = fpm_worker_all_pools; wp; wp = wp->next) { + + if (wp->config->listen_address && *wp->config->listen_address) { + + wp->listen_address_domain = fpm_sockets_domain_from_address(wp->config->listen_address); + + if (wp->listen_address_domain == FPM_AF_UNIX && *wp->config->listen_address != '/') { + fpm_evaluate_full_path(&wp->config->listen_address); + } + + } + else { + + wp->is_template = 1; + + } + + if (wp->config->request_slowlog_timeout) { +#if HAVE_FPM_TRACE + if (! (wp->config->slowlog && *wp->config->slowlog)) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "pool %s: 'slowlog' must be specified for use with 'request_slowlog_timeout'", + wp->config->name); + return -1; + } +#else + static int warned = 0; + + if (!warned) { + zlog(ZLOG_STUFF, ZLOG_WARNING, "pool %s: 'request_slowlog_timeout' is not supported on your system", + wp->config->name); + warned = 1; + } + + wp->config->request_slowlog_timeout = 0; +#endif + } + + if (wp->config->request_slowlog_timeout && wp->config->slowlog && *wp->config->slowlog) { + int fd; + + fpm_evaluate_full_path(&wp->config->slowlog); + + if (wp->config->request_slowlog_timeout) { + fd = open(wp->config->slowlog, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); + + if (0 > fd) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "open(%s) failed", wp->config->slowlog); + return -1; + } + close(fd); + } + } + } + + return 0; +} + +int fpm_conf_unlink_pid() +{ + if (fpm_global_config.pid_file) { + + if (0 > unlink(fpm_global_config.pid_file)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "unlink(\"%s\") failed", fpm_global_config.pid_file); + return -1; + } + + } + + return 0; +} + +int fpm_conf_write_pid() +{ + int fd; + + if (fpm_global_config.pid_file) { + char buf[64]; + int len; + + unlink(fpm_global_config.pid_file); + + fd = creat(fpm_global_config.pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); + + if (fd < 0) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "creat(\"%s\") failed", fpm_global_config.pid_file); + return -1; + } + + len = sprintf(buf, "%d", (int) fpm_globals.parent_pid); + + if (len != write(fd, buf, len)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "write() failed"); + return -1; + } + + close(fd); + } + + return 0; +} + +static int fpm_conf_post_process() +{ + if (fpm_global_config.pid_file) { + fpm_evaluate_full_path(&fpm_global_config.pid_file); + } + + if (!fpm_global_config.error_log) { + fpm_global_config.error_log = strdup(PHP_FPM_LOG_PATH); + } + + fpm_evaluate_full_path(&fpm_global_config.error_log); + + if (0 > fpm_stdio_open_error_log(0)) { + return -1; + } + + return fpm_conf_process_all_pools(); +} + +static void fpm_conf_cleanup(int which, void *arg) +{ + free(fpm_global_config.pid_file); + free(fpm_global_config.error_log); + fpm_global_config.pid_file = 0; + fpm_global_config.error_log = 0; +} + +int fpm_conf_init_main() +{ + char *filename = fpm_globals.config; + char *err; + + if (0 > xml_conf_sections_register(fpm_conf_all_sections)) { + return -1; + } + + if (filename == NULL) { + filename = PHP_FPM_CONF_PATH; + } + + err = xml_conf_load_file(filename); + + if (err) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "failed to load configuration file: %s", err); + return -1; + } + + if (0 > fpm_conf_post_process()) { + return -1; + } + + xml_conf_clean(); + + if (0 > fpm_cleanup_add(FPM_CLEANUP_ALL, fpm_conf_cleanup, 0)) { + return -1; + } + + return 0; +} diff --git a/sapi/cgi/fpm/fpm_conf.h b/sapi/cgi/fpm/fpm_conf.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_conf.h @@ -0,0 +1,73 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_CONF_H +#define FPM_CONF_H 1 + +struct key_value_s; + +struct key_value_s { + struct key_value_s *next; + char *key; + char *value; +}; + +struct fpm_global_config_s { + int emergency_restart_threshold; + int emergency_restart_interval; + int process_control_timeout; + int daemonize; + char *pid_file; + char *error_log; +}; + +extern struct fpm_global_config_s fpm_global_config; + +struct fpm_pm_s { + int style; + int max_children; + struct { + int StartServers; + int MinSpareServers; + int MaxSpareServers; + } options_apache_like; +}; + +struct fpm_listen_options_s { + int backlog; + char *owner; + char *group; + char *mode; +}; + +struct fpm_worker_pool_config_s { + char *name; + char *listen_address; + struct fpm_listen_options_s *listen_options; + struct key_value_s *php_defines; + char *user; + char *group; + char *chroot; + char *chdir; + char *allowed_clients; + struct key_value_s *environment; + struct fpm_pm_s *pm; + int request_terminate_timeout; + int request_slowlog_timeout; + char *slowlog; + int max_requests; + int rlimit_files; + int rlimit_core; + unsigned catch_workers_output:1; +}; + +enum { PM_STYLE_STATIC = 1, PM_STYLE_APACHE_LIKE = 2 }; + +int fpm_conf_init_main(); +int fpm_worker_pool_config_free(struct fpm_worker_pool_config_s *wpc); +int fpm_conf_write_pid(); +int fpm_conf_unlink_pid(); + +#endif + diff --git a/sapi/cgi/fpm/fpm_config.h b/sapi/cgi/fpm/fpm_config.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_config.h @@ -0,0 +1,39 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "php_config.h" +#include "fpm_autoconf.h" + + +/* Solaris does not have it */ +#ifndef INADDR_NONE +#define INADDR_NONE (-1) +#endif + + +/* If we're not using GNU C, elide __attribute__ */ +#ifndef __GNUC__ +# define __attribute__(x) /*NOTHING*/ +#endif + + +/* Solaris does not have it */ +#ifndef timersub +#define timersub(tvp, uvp, vvp) \ + do { \ + (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \ + (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \ + if ((vvp)->tv_usec < 0) { \ + (vvp)->tv_sec--; \ + (vvp)->tv_usec += 1000000; \ + } \ + } while (0) +#endif + +#if defined(HAVE_PTRACE) || defined(PROC_MEM_FILE) || defined(HAVE_MACH_VM_READ) +#define HAVE_FPM_TRACE 1 +#else +#define HAVE_FPM_TRACE 0 +#endif + diff --git a/sapi/cgi/fpm/fpm_env.c b/sapi/cgi/fpm/fpm_env.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_env.c @@ -0,0 +1,125 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#ifdef HAVE_ALLOCA_H +#include +#endif +#include +#include +#include + +#include "fpm_env.h" +#include "zlog.h" + +#ifndef HAVE_SETENV +int setenv(char *name, char *value, int overwrite) +{ + int name_len = strlen(name); + int value_len = strlen(value); + char *var = alloca(name_len + 1 + value_len + 1); + + memcpy(var, name, name_len); + + var[name_len] = '='; + + memcpy(var + name_len + 1, value, value_len); + + var[name_len + 1 + value_len] = '\0'; + + return putenv(var); +} +#endif + +#ifndef HAVE_CLEARENV +void clearenv() +{ + char **envp; + char *s; + + /* this algo is the only one known to me + that works well on all systems */ + while (*(envp = environ)) { + char *eq = strchr(*envp, '='); + + s = strdup(*envp); + + if (eq) s[eq - *envp] = '\0'; + + unsetenv(s); + free(s); + } + +} +#endif + + +int fpm_env_init_child(struct fpm_worker_pool_s *wp) +{ + struct key_value_s *kv; + + clearenv(); + + for (kv = wp->config->environment; kv; kv = kv->next) { + setenv(kv->key, kv->value, 1); + } + + if (wp->user) { + setenv("USER", wp->user, 1); + } + + if (wp->home) { + setenv("HOME", wp->home, 1); + } + + return 0; +} + +static int fpm_env_conf_wp(struct fpm_worker_pool_s *wp) +{ + struct key_value_s *kv; + + kv = wp->config->environment; + + for (kv = wp->config->environment; kv; kv = kv->next) { + if (*kv->value == '$') { + char *value = getenv(kv->value + 1); + + if (!value) value = ""; + + free(kv->value); + kv->value = strdup(value); + } + + /* autodetected values should be removed + if these vars specified in config */ + if (!strcmp(kv->key, "USER")) { + free(wp->user); + wp->user = 0; + } + + if (!strcmp(kv->key, "HOME")) { + free(wp->home); + wp->home = 0; + } + } + + return 0; +} + +int fpm_env_init_main() +{ + struct fpm_worker_pool_s *wp; + + for (wp = fpm_worker_all_pools; wp; wp = wp->next) { + + if (0 > fpm_env_conf_wp(wp)) { + return -1; + } + + } + + return 0; +} diff --git a/sapi/cgi/fpm/fpm_env.h b/sapi/cgi/fpm/fpm_env.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_env.h @@ -0,0 +1,24 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_ENV_H +#define FPM_ENV_H 1 + +#include "fpm_worker_pool.h" + +int fpm_env_init_child(struct fpm_worker_pool_s *wp); +int fpm_env_init_main(); + +extern char **environ; + +#ifndef HAVE_SETENV +int setenv(char *name, char *value, int overwrite); +#endif + +#ifndef HAVE_CLEARENV +void clearenv(); +#endif + +#endif + diff --git a/sapi/cgi/fpm/fpm_events.c b/sapi/cgi/fpm/fpm_events.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_events.c @@ -0,0 +1,135 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include /* for putenv */ +#include +#include /* for event.h below */ +#include + +#include "fpm.h" +#include "fpm_process_ctl.h" +#include "fpm_events.h" +#include "fpm_cleanup.h" +#include "fpm_stdio.h" +#include "fpm_signals.h" +#include "fpm_children.h" +#include "zlog.h" + +static void fpm_event_cleanup(int which, void *arg) +{ + event_base_free(0); +} + +static void fpm_got_signal(int fd, short ev, void *arg) +{ + char c; + int res; + + do { + + do { + res = read(fd, &c, 1); + } while (res == -1 && errno == EINTR); + + if (res <= 0) { + if (res < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "read() failed"); + } + return; + } + + switch (c) { + case 'C' : /* SIGCHLD */ + zlog(ZLOG_STUFF, ZLOG_NOTICE, "received SIGCHLD"); + fpm_children_bury(); + break; + case 'I' : /* SIGINT */ + zlog(ZLOG_STUFF, ZLOG_NOTICE, "received SIGINT"); + fpm_pctl(FPM_PCTL_STATE_TERMINATING, FPM_PCTL_ACTION_SET); + break; + case 'T' : /* SIGTERM */ + zlog(ZLOG_STUFF, ZLOG_NOTICE, "received SIGTERM"); + fpm_pctl(FPM_PCTL_STATE_TERMINATING, FPM_PCTL_ACTION_SET); + break; + case 'Q' : /* SIGQUIT */ + zlog(ZLOG_STUFF, ZLOG_NOTICE, "received SIGQUIT"); + fpm_pctl(FPM_PCTL_STATE_FINISHING, FPM_PCTL_ACTION_SET); + break; + case '1' : /* SIGUSR1 */ + zlog(ZLOG_STUFF, ZLOG_NOTICE, "received SIGUSR1"); + if (0 == fpm_stdio_open_error_log(1)) { + zlog(ZLOG_STUFF, ZLOG_NOTICE, "log file re-opened"); + } + break; + case '2' : /* SIGUSR2 */ + zlog(ZLOG_STUFF, ZLOG_NOTICE, "received SIGUSR2"); + fpm_pctl(FPM_PCTL_STATE_RELOADING, FPM_PCTL_ACTION_SET); + break; + } + + if (fpm_globals.is_child) { + break; + } + + } while (1); + + return; +} + +int fpm_event_init_main() +{ + event_init(); + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "libevent: using %s", event_get_method()); + + if (0 > fpm_cleanup_add(FPM_CLEANUP_ALL, fpm_event_cleanup, 0)) { + return -1; + } + + return 0; +} + +int fpm_event_loop() +{ + static struct event signal_fd_event; + + event_set(&signal_fd_event, fpm_signals_get_fd(), EV_PERSIST | EV_READ, &fpm_got_signal, 0); + + event_add(&signal_fd_event, 0); + + fpm_pctl_heartbeat(-1, 0, 0); + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "libevent: entering main loop"); + + event_loop(0); + + return 0; +} + +int fpm_event_add(int fd, struct event *ev, void (*callback)(int, short, void *), void *arg) +{ + event_set(ev, fd, EV_PERSIST | EV_READ, callback, arg); + + return event_add(ev, 0); +} + +int fpm_event_del(struct event *ev) +{ + return event_del(ev); +} + +void fpm_event_exit_loop() +{ + event_loopbreak(); +} + +void fpm_event_fire(struct event *ev) +{ + (*ev->ev_callback)( (int) ev->ev_fd, (short) ev->ev_res, ev->ev_arg); +} + diff --git a/sapi/cgi/fpm/fpm_events.h b/sapi/cgi/fpm/fpm_events.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_events.h @@ -0,0 +1,16 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_EVENTS_H +#define FPM_EVENTS_H 1 + +void fpm_event_exit_loop(); +int fpm_event_loop(); +int fpm_event_add(int fd, struct event *ev, void (*callback)(int, short, void *), void *arg); +int fpm_event_del(struct event *ev); +void fpm_event_fire(struct event *ev); +int fpm_event_init_main(); + + +#endif diff --git a/sapi/cgi/fpm/fpm_php.c b/sapi/cgi/fpm/fpm_php.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_php.c @@ -0,0 +1,190 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include + +#include "php.h" +#include "php_main.h" +#include "php_ini.h" +#include "ext/standard/dl.h" + +#include "fastcgi.h" + +#include "fpm.h" +#include "fpm_php.h" +#include "fpm_cleanup.h" +#include "fpm_worker_pool.h" + +static int zend_ini_alter_master(char *name, int name_length, char *new_value, int new_value_length, int stage TSRMLS_DC) +{ + zend_ini_entry *ini_entry; + char *duplicate; + + if (zend_hash_find(EG(ini_directives), name, name_length, (void **) &ini_entry) == FAILURE) { + return FAILURE; + } + + duplicate = strdup(new_value); + + if (!ini_entry->on_modify + || ini_entry->on_modify(ini_entry, duplicate, new_value_length, + ini_entry->mh_arg1, ini_entry->mh_arg2, ini_entry->mh_arg3, stage TSRMLS_CC) == SUCCESS) { + ini_entry->value = duplicate; + ini_entry->value_length = new_value_length; + } else { + free(duplicate); + } + + return SUCCESS; +} + +static void fpm_php_disable(char *value, int (*zend_disable)(char *, uint TSRMLS_DC) TSRMLS_DC) +{ + char *s = 0, *e = value; + + while (*e) { + switch (*e) { + case ' ': + case ',': + if (s) { + *e = '\0'; + zend_disable(s, e - s TSRMLS_CC); + s = 0; + } + break; + default: + if (!s) { + s = e; + } + break; + } + e++; + } + + if (s) { + zend_disable(s, e - s TSRMLS_CC); + } +} + +static int fpm_php_apply_defines(struct fpm_worker_pool_s *wp) +{ + TSRMLS_FETCH(); + struct key_value_s *kv; + + for (kv = wp->config->php_defines; kv; kv = kv->next) { + char *name = kv->key; + char *value = kv->value; + int name_len = strlen(name); + int value_len = strlen(value); + + if (!strcmp(name, "extension") && *value) { + zval zv; + +#if defined(PHP_VERSION_ID) && (PHP_VERSION_ID >= 50300) + php_dl(value, MODULE_PERSISTENT, &zv, 1 TSRMLS_CC); +#else + zval filename; + ZVAL_STRINGL(&filename, value, value_len, 0); +#if (PHP_MAJOR_VERSION >= 5) + php_dl(&filename, MODULE_PERSISTENT, &zv, 1 TSRMLS_CC); +#else + php_dl(&filename, MODULE_PERSISTENT, &zv TSRMLS_CC); +#endif +#endif + continue; + } + + zend_ini_alter_master(name, name_len + 1, value, value_len, PHP_INI_STAGE_ACTIVATE TSRMLS_CC); + + if (!strcmp(name, "disable_functions") && *value) { + char *v = strdup(value); +#if (PHP_MAJOR_VERSION >= 5) + PG(disable_functions) = v; +#endif + fpm_php_disable(v, zend_disable_function TSRMLS_CC); + } + else if (!strcmp(name, "disable_classes") && *value) { + char *v = strdup(value); +#if (PHP_MAJOR_VERSION >= 5) + PG(disable_classes) = v; +#endif + fpm_php_disable(v, zend_disable_class TSRMLS_CC); + } + } + + return 0; +} + +static int fpm_php_set_allowed_clients(struct fpm_worker_pool_s *wp) +{ + if (wp->listen_address_domain == FPM_AF_INET) { + fcgi_set_allowed_clients(wp->config->allowed_clients); + } + + return 0; +} + +static int fpm_php_set_fcgi_mgmt_vars(struct fpm_worker_pool_s *wp) +{ + char max_workers[10 + 1]; /* 4294967295 */ + int len; + + len = sprintf(max_workers, "%u", (unsigned int) wp->config->pm->max_children); + + fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, max_workers, len); + fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, max_workers, len); + + return 0; +} + +char *fpm_php_script_filename(TSRMLS_D) +{ + return SG(request_info).path_translated; +} + +char *fpm_php_request_method(TSRMLS_D) +{ + return (char *) SG(request_info).request_method; +} + +size_t fpm_php_content_length(TSRMLS_D) +{ + return SG(request_info).content_length; +} + +static void fpm_php_cleanup(int which, void *arg) +{ + TSRMLS_FETCH(); + php_module_shutdown(TSRMLS_C); + sapi_shutdown(); +} + +void fpm_php_soft_quit() +{ + fcgi_set_in_shutdown(1); +} + +int fpm_php_init_main() +{ + if (0 > fpm_cleanup_add(FPM_CLEANUP_PARENT, fpm_php_cleanup, 0)) { + return -1; + } + + return 0; +} + +int fpm_php_init_child(struct fpm_worker_pool_s *wp) +{ + if (0 > fpm_php_apply_defines(wp) || + 0 > fpm_php_set_allowed_clients(wp) || + 0 > fpm_php_set_fcgi_mgmt_vars(wp)) { + return -1; + } + + return 0; +} diff --git a/sapi/cgi/fpm/fpm_php.h b/sapi/cgi/fpm/fpm_php.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_php.h @@ -0,0 +1,22 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_PHP_H +#define FPM_PHP_H 1 + +#include + +#include "build-defs.h" /* for PHP_ defines */ + +struct fpm_worker_pool_s; + +int fpm_php_init_child(struct fpm_worker_pool_s *wp); +char *fpm_php_script_filename(TSRMLS_D); +char *fpm_php_request_method(TSRMLS_D); +size_t fpm_php_content_length(TSRMLS_D); +void fpm_php_soft_quit(); +int fpm_php_init_main(); + +#endif + diff --git a/sapi/cgi/fpm/fpm_php_trace.c b/sapi/cgi/fpm/fpm_php_trace.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_php_trace.c @@ -0,0 +1,171 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#if HAVE_FPM_TRACE + +#include "php.h" +#include "php_main.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "fpm_trace.h" +#include "fpm_php_trace.h" +#include "fpm_children.h" +#include "fpm_worker_pool.h" +#include "fpm_process_ctl.h" + +#include "zlog.h" + + +#define valid_ptr(p) ((p) && 0 == ((p) & (sizeof(long) - 1))) + +#if SIZEOF_LONG == 4 +#define PTR_FMT "08" +#elif SIZEOF_LONG == 8 +#define PTR_FMT "016" +#endif + + +static int fpm_php_trace_dump(struct fpm_child_s *child, FILE *slowlog TSRMLS_DC) +{ + int callers_limit = 20; + pid_t pid = child->pid; + struct timeval tv; + static const int buf_size = 1024; + char buf[buf_size]; + long execute_data; + long l; + + gettimeofday(&tv, 0); + + zlog_print_time(&tv, buf, buf_size); + + fprintf(slowlog, "\n%s pid %d (pool %s)\n", buf, (int) pid, child->wp->config->name); + + if (0 > fpm_trace_get_strz(buf, buf_size, (long) &SG(request_info).path_translated)) { + return -1; + } + + fprintf(slowlog, "script_filename = %s\n", buf); + + if (0 > fpm_trace_get_long((long) &EG(current_execute_data), &l)) { + return -1; + } + + execute_data = l; + + while (execute_data) { + long function; + uint lineno = 0; + + fprintf(slowlog, "[0x%" PTR_FMT "lx] ", execute_data); + + if (0 > fpm_trace_get_long(execute_data + offsetof(zend_execute_data, function_state.function), &l)) { + return -1; + } + + function = l; + + if (valid_ptr(function)) { + if (0 > fpm_trace_get_strz(buf, buf_size, function + offsetof(zend_function, common.function_name))) { + return -1; + } + + fprintf(slowlog, "%s()", buf); + } + else { + fprintf(slowlog, "???"); + } + + if (0 > fpm_trace_get_long(execute_data + offsetof(zend_execute_data, op_array), &l)) { + return -1; + } + + *buf = '\0'; + + if (valid_ptr(l)) { + long op_array = l; + + if (0 > fpm_trace_get_strz(buf, buf_size, op_array + offsetof(zend_op_array, filename))) { + return -1; + } + } + + if (0 > fpm_trace_get_long(execute_data + offsetof(zend_execute_data, opline), &l)) { + return -1; + } + + if (valid_ptr(l)) { + long opline = l; + uint *lu = (uint *) &l; + + if (0 > fpm_trace_get_long(opline + offsetof(struct _zend_op, lineno), &l)) { + return -1; + } + + lineno = *lu; + } + + fprintf(slowlog, " %s:%u\n", *buf ? buf : "unknown", lineno); + + if (0 > fpm_trace_get_long(execute_data + offsetof(zend_execute_data, prev_execute_data), &l)) { + return -1; + } + + execute_data = l; + + if (0 == --callers_limit) { + break; + } + } + + return 0; +} + +void fpm_php_trace(struct fpm_child_s *child) +{ + TSRMLS_FETCH(); + FILE *slowlog; + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "about to trace %d", (int) child->pid); + + slowlog = fopen(child->wp->config->slowlog, "a+"); + + if (!slowlog) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "fopen(%s) failed", child->wp->config->slowlog); + goto done0; + } + + if (0 > fpm_trace_ready(child->pid)) { + goto done1; + } + + if (0 > fpm_php_trace_dump(child, slowlog TSRMLS_CC)) { + fprintf(slowlog, "+++ dump failed\n"); + } + + if (0 > fpm_trace_close(child->pid)) { + goto done1; + } + +done1: + fclose(slowlog); + +done0: + fpm_pctl_kill(child->pid, FPM_PCTL_CONT); + child->tracer = 0; + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "finished trace of %d", (int) child->pid); +} + +#endif + diff --git a/sapi/cgi/fpm/fpm_php_trace.h b/sapi/cgi/fpm/fpm_php_trace.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_php_trace.h @@ -0,0 +1,13 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_PHP_TRACE_H +#define FPM_PHP_TRACE_H 1 + +struct fpm_child_s; + +void fpm_php_trace(struct fpm_child_s *); + +#endif + diff --git a/sapi/cgi/fpm/fpm_process_ctl.c b/sapi/cgi/fpm/fpm_process_ctl.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_process_ctl.c @@ -0,0 +1,354 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include +#include + +#include "fpm.h" +#include "fpm_clock.h" +#include "fpm_children.h" +#include "fpm_signals.h" +#include "fpm_events.h" +#include "fpm_process_ctl.h" +#include "fpm_cleanup.h" +#include "fpm_request.h" +#include "fpm_worker_pool.h" +#include "zlog.h" + + +static int fpm_state = FPM_PCTL_STATE_NORMAL; +static int fpm_signal_sent = 0; + + +static const char *fpm_state_names[] = { + [FPM_PCTL_STATE_NORMAL] = "normal", + [FPM_PCTL_STATE_RELOADING] = "reloading", + [FPM_PCTL_STATE_TERMINATING] = "terminating", + [FPM_PCTL_STATE_FINISHING] = "finishing" +}; + +static int saved_argc; +static char **saved_argv; + +static void fpm_pctl_cleanup(int which, void *arg) +{ + int i; + + if (which != FPM_CLEANUP_PARENT_EXEC) { + + for (i = 0; i < saved_argc; i++) { + free(saved_argv[i]); + } + + free(saved_argv); + + } +} + +static struct event pctl_event; + +static void fpm_pctl_action(int fd, short which, void *arg) +{ + evtimer_del(&pctl_event); + + memset(&pctl_event, 0, sizeof(pctl_event)); + + fpm_pctl(FPM_PCTL_STATE_UNSPECIFIED, FPM_PCTL_ACTION_TIMEOUT); +} + +static int fpm_pctl_timeout_set(int sec) +{ + struct timeval tv = { .tv_sec = sec, .tv_usec = 0 }; + + if (evtimer_initialized(&pctl_event)) { + evtimer_del(&pctl_event); + } + + evtimer_set(&pctl_event, &fpm_pctl_action, 0); + + evtimer_add(&pctl_event, &tv); + + return 0; +} + +static void fpm_pctl_exit() +{ + zlog(ZLOG_STUFF, ZLOG_NOTICE, "exiting, bye-bye!"); + + fpm_conf_unlink_pid(); + + fpm_cleanups_run(FPM_CLEANUP_PARENT_EXIT_MAIN); + + exit(0); +} + +#define optional_arg(c) (saved_argc > c ? ", \"" : ""), (saved_argc > c ? saved_argv[c] : ""), (saved_argc > c ? "\"" : "") + +static void fpm_pctl_exec() +{ + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "reloading: execvp(\"%s\", {\"%s\"" + "%s%s%s" "%s%s%s" "%s%s%s" "%s%s%s" "%s%s%s" + "%s%s%s" "%s%s%s" "%s%s%s" "%s%s%s" "%s%s%s" + "})", + saved_argv[0], saved_argv[0], + optional_arg(1), + optional_arg(2), + optional_arg(3), + optional_arg(4), + optional_arg(5), + optional_arg(6), + optional_arg(7), + optional_arg(8), + optional_arg(9), + optional_arg(10) + ); + + fpm_cleanups_run(FPM_CLEANUP_PARENT_EXEC); + + execvp(saved_argv[0], saved_argv); + + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "execvp() failed"); + + exit(1); +} + +static void fpm_pctl_action_last() +{ + switch (fpm_state) { + + case FPM_PCTL_STATE_RELOADING : + + fpm_pctl_exec(); + break; + + case FPM_PCTL_STATE_FINISHING : + + case FPM_PCTL_STATE_TERMINATING : + + fpm_pctl_exit(); + break; + } +} + +int fpm_pctl_kill(pid_t pid, int how) +{ + int s = 0; + + switch (how) { + case FPM_PCTL_TERM : + s = SIGTERM; + break; + case FPM_PCTL_STOP : + s = SIGSTOP; + break; + case FPM_PCTL_CONT : + s = SIGCONT; + break; + default : + break; + } + + return kill(pid, s); +} + +static void fpm_pctl_kill_all(int signo) +{ + struct fpm_worker_pool_s *wp; + int alive_children = 0; + + for (wp = fpm_worker_all_pools; wp; wp = wp->next) { + struct fpm_child_s *child; + + for (child = wp->children; child; child = child->next) { + + int res = kill(child->pid, signo); + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "sending signal %d %s to child %d (pool %s)", signo, + fpm_signal_names[signo] ? fpm_signal_names[signo] : "", + (int) child->pid, child->wp->config->name); + + if (res == 0) ++alive_children; + } + } + + if (alive_children) { + zlog(ZLOG_STUFF, ZLOG_NOTICE, "%d %s still alive", alive_children, alive_children == 1 ? "child is" : "children are"); + } +} + +static void fpm_pctl_action_next() +{ + int sig, timeout; + + if (!fpm_globals.running_children) fpm_pctl_action_last(); + + if (fpm_signal_sent == 0) { + if (fpm_state == FPM_PCTL_STATE_TERMINATING) { + sig = SIGTERM; + } + else { + sig = SIGQUIT; + } + timeout = fpm_global_config.process_control_timeout; + } + else { + if (fpm_signal_sent == SIGQUIT) { + sig = SIGTERM; + } + else { + sig = SIGKILL; + } + timeout = 1; + } + + fpm_pctl_kill_all(sig); + + fpm_signal_sent = sig; + + fpm_pctl_timeout_set(timeout); +} + +void fpm_pctl(int new_state, int action) +{ + switch (action) { + + case FPM_PCTL_ACTION_SET : + + if (fpm_state == new_state) { /* already in progress - just ignore duplicate signal */ + return; + } + + switch (fpm_state) { /* check which states can be overridden */ + + case FPM_PCTL_STATE_NORMAL : + + /* 'normal' can be overridden by any other state */ + break; + + case FPM_PCTL_STATE_RELOADING : + + /* 'reloading' can be overridden by 'finishing' */ + if (new_state == FPM_PCTL_STATE_FINISHING) break; + + case FPM_PCTL_STATE_FINISHING : + + /* 'reloading' and 'finishing' can be overridden by 'terminating' */ + if (new_state == FPM_PCTL_STATE_TERMINATING) break; + + case FPM_PCTL_STATE_TERMINATING : + + /* nothing can override 'terminating' state */ + zlog(ZLOG_STUFF, ZLOG_NOTICE, "not switching to '%s' state, because already in '%s' state", + fpm_state_names[new_state], fpm_state_names[fpm_state]); + + return; + } + + fpm_signal_sent = 0; + fpm_state = new_state; + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "switching to '%s' state", fpm_state_names[fpm_state]); + + /* fall down */ + + case FPM_PCTL_ACTION_TIMEOUT : + + fpm_pctl_action_next(); + + break; + + case FPM_PCTL_ACTION_LAST_CHILD_EXITED : + + fpm_pctl_action_last(); + + break; + + } +} + +int fpm_pctl_can_spawn_children() +{ + return fpm_state == FPM_PCTL_STATE_NORMAL; +} + +int fpm_pctl_child_exited() +{ + if (fpm_state == FPM_PCTL_STATE_NORMAL) return 0; + + if (!fpm_globals.running_children) { + fpm_pctl(FPM_PCTL_STATE_UNSPECIFIED, FPM_PCTL_ACTION_LAST_CHILD_EXITED); + } + + return 0; +} + +int fpm_pctl_init_main() +{ + int i; + + saved_argc = fpm_globals.argc; + + saved_argv = malloc(sizeof(char *) * (saved_argc + 1)); + + if (!saved_argv) { + return -1; + } + + for (i = 0; i < saved_argc; i++) { + saved_argv[i] = strdup(fpm_globals.argv[i]); + + if (!saved_argv[i]) { + return -1; + } + } + + saved_argv[i] = 0; + + if (0 > fpm_cleanup_add(FPM_CLEANUP_ALL, fpm_pctl_cleanup, 0)) { + return -1; + } + + return 0; +} + +static void fpm_pctl_check_request_timeout(struct timeval *now) +{ + struct fpm_worker_pool_s *wp; + + for (wp = fpm_worker_all_pools; wp; wp = wp->next) { + int terminate_timeout = wp->config->request_terminate_timeout; + int slowlog_timeout = wp->config->request_slowlog_timeout; + struct fpm_child_s *child; + + if (terminate_timeout || slowlog_timeout) { + for (child = wp->children; child; child = child->next) { + fpm_request_check_timed_out(child, now, terminate_timeout, slowlog_timeout); + } + } + } + +} + +void fpm_pctl_heartbeat(int fd, short which, void *arg) +{ + static struct event heartbeat; + struct timeval tv = { .tv_sec = 0, .tv_usec = 130000 }; + struct timeval now; + + if (which == EV_TIMEOUT) { + evtimer_del(&heartbeat); + fpm_clock_get(&now); + fpm_pctl_check_request_timeout(&now); + } + + evtimer_set(&heartbeat, &fpm_pctl_heartbeat, 0); + + evtimer_add(&heartbeat, &tv); +} + diff --git a/sapi/cgi/fpm/fpm_process_ctl.h b/sapi/cgi/fpm/fpm_process_ctl.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_process_ctl.h @@ -0,0 +1,39 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_PROCESS_CTL_H +#define FPM_PROCESS_CTL_H 1 + +struct fpm_child_s; + +void fpm_pctl(int new_state, int action); +int fpm_pctl_can_spawn_children(); +int fpm_pctl_kill(pid_t pid, int how); +void fpm_pctl_heartbeat(int fd, short which, void *arg); +int fpm_pctl_child_exited(); +int fpm_pctl_init_main(); + + +enum { + FPM_PCTL_STATE_UNSPECIFIED, + FPM_PCTL_STATE_NORMAL, + FPM_PCTL_STATE_RELOADING, + FPM_PCTL_STATE_TERMINATING, + FPM_PCTL_STATE_FINISHING +}; + +enum { + FPM_PCTL_ACTION_SET, + FPM_PCTL_ACTION_TIMEOUT, + FPM_PCTL_ACTION_LAST_CHILD_EXITED +}; + +enum { + FPM_PCTL_TERM, + FPM_PCTL_STOP, + FPM_PCTL_CONT +}; + +#endif + diff --git a/sapi/cgi/fpm/fpm_request.c b/sapi/cgi/fpm/fpm_request.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_request.c @@ -0,0 +1,164 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include "fpm_php.h" +#include "fpm_str.h" +#include "fpm_clock.h" +#include "fpm_conf.h" +#include "fpm_trace.h" +#include "fpm_php_trace.h" +#include "fpm_process_ctl.h" +#include "fpm_children.h" +#include "fpm_shm_slots.h" +#include "fpm_request.h" + +#include "zlog.h" + +void fpm_request_accepting() +{ + struct fpm_shm_slot_s *slot; + + slot = fpm_shm_slots_acquire(0, 0); + + slot->request_stage = FPM_REQUEST_ACCEPTING; + + fpm_clock_get(&slot->tv); + memset(slot->request_method, 0, sizeof(slot->request_method)); + slot->content_length = 0; + memset(slot->script_filename, 0, sizeof(slot->script_filename)); + + fpm_shm_slots_release(slot); +} + +void fpm_request_reading_headers() +{ + struct fpm_shm_slot_s *slot; + + slot = fpm_shm_slots_acquire(0, 0); + + slot->request_stage = FPM_REQUEST_READING_HEADERS; + + fpm_clock_get(&slot->tv); + slot->accepted = slot->tv; + + fpm_shm_slots_release(slot); +} + +void fpm_request_info() +{ + TSRMLS_FETCH(); + struct fpm_shm_slot_s *slot; + char *request_method = fpm_php_request_method(TSRMLS_C); + char *script_filename = fpm_php_script_filename(TSRMLS_C); + + slot = fpm_shm_slots_acquire(0, 0); + + slot->request_stage = FPM_REQUEST_INFO; + + fpm_clock_get(&slot->tv); + + if (request_method) { + cpystrn(slot->request_method, request_method, sizeof(slot->request_method)); + } + + slot->content_length = fpm_php_content_length(TSRMLS_C); + + /* if cgi.fix_pathinfo is set to "1" and script cannot be found (404) + the sapi_globals.request_info.path_translated is set to NULL */ + if (script_filename) { + cpystrn(slot->script_filename, script_filename, sizeof(slot->script_filename)); + } + + fpm_shm_slots_release(slot); +} + +void fpm_request_executing() +{ + struct fpm_shm_slot_s *slot; + + slot = fpm_shm_slots_acquire(0, 0); + + slot->request_stage = FPM_REQUEST_EXECUTING; + + fpm_clock_get(&slot->tv); + + fpm_shm_slots_release(slot); +} + +void fpm_request_finished() +{ + struct fpm_shm_slot_s *slot; + + slot = fpm_shm_slots_acquire(0, 0); + + slot->request_stage = FPM_REQUEST_FINISHED; + + fpm_clock_get(&slot->tv); + memset(&slot->accepted, 0, sizeof(slot->accepted)); + + fpm_shm_slots_release(slot); +} + +void fpm_request_check_timed_out(struct fpm_child_s *child, struct timeval *now, int terminate_timeout, int slowlog_timeout) +{ + struct fpm_shm_slot_s *slot; + struct fpm_shm_slot_s slot_c; + + slot = fpm_shm_slot(child); + + if (!fpm_shm_slots_acquire(slot, 1)) { + return; + } + + slot_c = *slot; + + fpm_shm_slots_release(slot); + +#if HAVE_FPM_TRACE + if (child->slow_logged.tv_sec) { + if (child->slow_logged.tv_sec != slot_c.accepted.tv_sec || child->slow_logged.tv_usec != slot_c.accepted.tv_usec) { + child->slow_logged.tv_sec = 0; + child->slow_logged.tv_usec = 0; + } + } +#endif + + if (slot_c.request_stage > FPM_REQUEST_ACCEPTING && slot_c.request_stage < FPM_REQUEST_FINISHED) { + char purified_script_filename[sizeof(slot_c.script_filename)]; + struct timeval tv; + + timersub(now, &slot_c.accepted, &tv); + +#if HAVE_FPM_TRACE + if (child->slow_logged.tv_sec == 0 && slowlog_timeout && + slot_c.request_stage == FPM_REQUEST_EXECUTING && tv.tv_sec >= slowlog_timeout) { + + str_purify_filename(purified_script_filename, slot_c.script_filename, sizeof(slot_c.script_filename)); + + child->slow_logged = slot_c.accepted; + child->tracer = fpm_php_trace; + + fpm_trace_signal(child->pid); + + zlog(ZLOG_STUFF, ZLOG_WARNING, "child %d, script '%s' (pool %s) executing too slow (%d.%06d sec), logging", + (int) child->pid, purified_script_filename, child->wp->config->name, (int) tv.tv_sec, (int) tv.tv_usec); + } + + else +#endif + if (terminate_timeout && tv.tv_sec >= terminate_timeout) { + + str_purify_filename(purified_script_filename, slot_c.script_filename, sizeof(slot_c.script_filename)); + + fpm_pctl_kill(child->pid, FPM_PCTL_TERM); + + zlog(ZLOG_STUFF, ZLOG_WARNING, "child %d, script '%s' (pool %s) execution timed out (%d.%06d sec), terminating", + (int) child->pid, purified_script_filename, child->wp->config->name, (int) tv.tv_sec, (int) tv.tv_usec); + } + } + +} + diff --git a/sapi/cgi/fpm/fpm_request.h b/sapi/cgi/fpm/fpm_request.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_request.h @@ -0,0 +1,27 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_REQUEST_H +#define FPM_REQUEST_H 1 + +void fpm_request_accepting(); /* hanging in accept() */ +void fpm_request_reading_headers(); /* start reading fastcgi request from very first byte */ +void fpm_request_info(); /* not a stage really but a point in the php code, where all request params have become known to sapi */ +void fpm_request_executing(); /* the script is executing */ +void fpm_request_finished(); /* request processed: script response have been sent to web server */ + +struct fpm_child_s; +struct timeval; + +void fpm_request_check_timed_out(struct fpm_child_s *child, struct timeval *tv, int terminate_timeout, int slowlog_timeout); + +enum fpm_request_stage_e { + FPM_REQUEST_ACCEPTING = 1, + FPM_REQUEST_READING_HEADERS, + FPM_REQUEST_INFO, + FPM_REQUEST_EXECUTING, + FPM_REQUEST_FINISHED +}; + +#endif diff --git a/sapi/cgi/fpm/fpm_shm.c b/sapi/cgi/fpm/fpm_shm.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_shm.c @@ -0,0 +1,100 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include + +#include "fpm_shm.h" +#include "zlog.h" + + +/* MAP_ANON is depricated, but not in macosx */ +#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS) +#define MAP_ANONYMOUS MAP_ANON +#endif + + +struct fpm_shm_s *fpm_shm_alloc(size_t sz) +{ + struct fpm_shm_s *shm; + + shm = malloc(sizeof(*shm)); + + if (!shm) { + return 0; + } + + shm->mem = mmap(0, sz, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0); + + if (!shm->mem) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "mmap(MAP_ANONYMOUS | MAP_SHARED) failed"); + free(shm); + return 0; + } + + shm->used = 0; + shm->sz = sz; + + return shm; +} + +static void fpm_shm_free(struct fpm_shm_s *shm, int do_unmap) +{ + if (do_unmap) { + munmap(shm->mem, shm->sz); + } + + free(shm); +} + +void fpm_shm_free_list(struct fpm_shm_s *shm, void *mem) +{ + struct fpm_shm_s *next; + + for (; shm; shm = next) { + next = shm->next; + + fpm_shm_free(shm, mem != shm->mem); + } +} + +void *fpm_shm_alloc_chunk(struct fpm_shm_s **head, size_t sz, void **mem) +{ + size_t pagesize = getpagesize(); + static const size_t cache_line_size = 16; + size_t aligned_sz; + struct fpm_shm_s *shm; + void *ret; + + sz = (sz + cache_line_size - 1) & -cache_line_size; + + shm = *head; + + if (0 == shm || shm->sz - shm->used < sz) { + /* allocate one more shm segment */ + + aligned_sz = (sz + pagesize - 1) & -pagesize; + + shm = fpm_shm_alloc(aligned_sz); + + if (!shm) { + return 0; + } + + shm->next = *head; + if (shm->next) shm->next->prev = shm; + shm->prev = 0; + *head = shm; + } + + *mem = shm->mem; + ret = (char *) shm->mem + shm->used; + shm->used += sz; + + return ret; +} + diff --git a/sapi/cgi/fpm/fpm_shm.h b/sapi/cgi/fpm/fpm_shm.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_shm.h @@ -0,0 +1,22 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_SHM_H +#define FPM_SHM_H 1 + +struct fpm_shm_s; + +struct fpm_shm_s { + struct fpm_shm_s *prev, *next; + void *mem; + size_t sz; + size_t used; +}; + +struct fpm_shm_s *fpm_shm_alloc(size_t sz); +void fpm_shm_free_list(struct fpm_shm_s *, void *); +void *fpm_shm_alloc_chunk(struct fpm_shm_s **head, size_t sz, void **mem); + +#endif + diff --git a/sapi/cgi/fpm/fpm_shm_slots.c b/sapi/cgi/fpm/fpm_shm_slots.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_shm_slots.c @@ -0,0 +1,127 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include "fpm_atomic.h" +#include "fpm_worker_pool.h" +#include "fpm_children.h" +#include "fpm_shm.h" +#include "fpm_shm_slots.h" +#include "zlog.h" + +static void *shm_mem; +static struct fpm_shm_slot_s *shm_slot; + +int fpm_shm_slots_prepare_slot(struct fpm_child_s *child) +{ + struct fpm_worker_pool_s *wp = child->wp; + struct fpm_shm_slot_ptr_s *shm_slot_ptr; + + child->shm_slot_i = wp->slots_used.used; + + shm_slot_ptr = fpm_array_push(&wp->slots_used); + + if (0 == shm_slot_ptr) { + return -1; + } + + if (0 == wp->slots_free.used) { + shm_slot_ptr->shm_slot = fpm_shm_alloc_chunk(&wp->shm_list, sizeof(struct fpm_shm_slot_s), &shm_slot_ptr->mem); + + if (!shm_slot_ptr->shm_slot) { + return -1; + } + } + else { + *shm_slot_ptr = *(struct fpm_shm_slot_ptr_s *) fpm_array_item_last(&wp->slots_free); + + --wp->slots_free.used; + } + + memset(shm_slot_ptr->shm_slot, 0, sizeof(struct fpm_shm_slot_s)); + + shm_slot_ptr->child = child; + + return 0; +} + +void fpm_shm_slots_discard_slot(struct fpm_child_s *child) +{ + struct fpm_shm_slot_ptr_s *shm_slot_ptr; + struct fpm_worker_pool_s *wp = child->wp; + int n; + + shm_slot_ptr = fpm_array_push(&wp->slots_free); + + if (shm_slot_ptr) { + + struct fpm_shm_slot_ptr_s *shm_slot_ptr_used; + + shm_slot_ptr_used = fpm_array_item(&wp->slots_used, child->shm_slot_i); + + *shm_slot_ptr = *shm_slot_ptr_used; + + shm_slot_ptr->child = 0; + + } + + n = fpm_array_item_remove(&wp->slots_used, child->shm_slot_i); + + if (n > -1) { + shm_slot_ptr = fpm_array_item(&wp->slots_used, n); + + shm_slot_ptr->child->shm_slot_i = n; + } +} + +void fpm_shm_slots_child_use_slot(struct fpm_child_s *child) +{ + struct fpm_shm_slot_ptr_s *shm_slot_ptr; + struct fpm_worker_pool_s *wp = child->wp; + + shm_slot_ptr = fpm_array_item(&wp->slots_used, child->shm_slot_i); + + shm_slot = shm_slot_ptr->shm_slot; + shm_mem = shm_slot_ptr->mem; +} + +void fpm_shm_slots_parent_use_slot(struct fpm_child_s *child) +{ + /* nothing to do */ +} + +void *fpm_shm_slots_mem() +{ + return shm_mem; +} + +struct fpm_shm_slot_s *fpm_shm_slot(struct fpm_child_s *child) +{ + struct fpm_shm_slot_ptr_s *shm_slot_ptr; + struct fpm_worker_pool_s *wp = child->wp; + + shm_slot_ptr = fpm_array_item(&wp->slots_used, child->shm_slot_i); + + return shm_slot_ptr->shm_slot; +} + +struct fpm_shm_slot_s *fpm_shm_slots_acquire(struct fpm_shm_slot_s *s, int nohang) +{ + if (s == 0) { + s = shm_slot; + } + + if (0 > fpm_spinlock(&s->lock, nohang)) { + return 0; + } + + return s; +} + +void fpm_shm_slots_release(struct fpm_shm_slot_s *s) +{ + s->lock = 0; +} + diff --git a/sapi/cgi/fpm/fpm_shm_slots.h b/sapi/cgi/fpm/fpm_shm_slots.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_shm_slots.h @@ -0,0 +1,43 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_SHM_SLOTS_H +#define FPM_SHM_SLOTS_H 1 + +#include "fpm_atomic.h" +#include "fpm_worker_pool.h" +#include "fpm_request.h" + +struct fpm_child_s; + +struct fpm_shm_slot_s { + union { + atomic_t lock; + char dummy[16]; + }; + enum fpm_request_stage_e request_stage; + struct timeval accepted; + struct timeval tv; + char request_method[16]; + size_t content_length; /* used with POST only */ + char script_filename[256]; +}; + +struct fpm_shm_slot_ptr_s { + void *mem; + struct fpm_shm_slot_s *shm_slot; + struct fpm_child_s *child; +}; + +int fpm_shm_slots_prepare_slot(struct fpm_child_s *child); +void fpm_shm_slots_discard_slot(struct fpm_child_s *child); +void fpm_shm_slots_child_use_slot(struct fpm_child_s *child); +void fpm_shm_slots_parent_use_slot(struct fpm_child_s *child); +void *fpm_shm_slots_mem(); +struct fpm_shm_slot_s *fpm_shm_slot(struct fpm_child_s *child); +struct fpm_shm_slot_s *fpm_shm_slots_acquire(struct fpm_shm_slot_s *, int nohang); +void fpm_shm_slots_release(struct fpm_shm_slot_s *); + +#endif + diff --git a/sapi/cgi/fpm/fpm_signals.c b/sapi/cgi/fpm/fpm_signals.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_signals.c @@ -0,0 +1,252 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "fpm.h" +#include "fpm_signals.h" +#include "fpm_sockets.h" +#include "fpm_php.h" +#include "zlog.h" + +static int sp[2]; + +const char *fpm_signal_names[NSIG + 1] = { +#ifdef SIGHUP + [SIGHUP] = "SIGHUP", +#endif +#ifdef SIGINT + [SIGINT] = "SIGINT", +#endif +#ifdef SIGQUIT + [SIGQUIT] = "SIGQUIT", +#endif +#ifdef SIGILL + [SIGILL] = "SIGILL", +#endif +#ifdef SIGTRAP + [SIGTRAP] = "SIGTRAP", +#endif +#ifdef SIGABRT + [SIGABRT] = "SIGABRT", +#endif +#ifdef SIGEMT + [SIGEMT] = "SIGEMT", +#endif +#ifdef SIGBUS + [SIGBUS] = "SIGBUS", +#endif +#ifdef SIGFPE + [SIGFPE] = "SIGFPE", +#endif +#ifdef SIGKILL + [SIGKILL] = "SIGKILL", +#endif +#ifdef SIGUSR1 + [SIGUSR1] = "SIGUSR1", +#endif +#ifdef SIGSEGV + [SIGSEGV] = "SIGSEGV", +#endif +#ifdef SIGUSR2 + [SIGUSR2] = "SIGUSR2", +#endif +#ifdef SIGPIPE + [SIGPIPE] = "SIGPIPE", +#endif +#ifdef SIGALRM + [SIGALRM] = "SIGALRM", +#endif +#ifdef SIGTERM + [SIGTERM] = "SIGTERM", +#endif +#ifdef SIGCHLD + [SIGCHLD] = "SIGCHLD", +#endif +#ifdef SIGCONT + [SIGCONT] = "SIGCONT", +#endif +#ifdef SIGSTOP + [SIGSTOP] = "SIGSTOP", +#endif +#ifdef SIGTSTP + [SIGTSTP] = "SIGTSTP", +#endif +#ifdef SIGTTIN + [SIGTTIN] = "SIGTTIN", +#endif +#ifdef SIGTTOU + [SIGTTOU] = "SIGTTOU", +#endif +#ifdef SIGURG + [SIGURG] = "SIGURG", +#endif +#ifdef SIGXCPU + [SIGXCPU] = "SIGXCPU", +#endif +#ifdef SIGXFSZ + [SIGXFSZ] = "SIGXFSZ", +#endif +#ifdef SIGVTALRM + [SIGVTALRM] = "SIGVTALRM", +#endif +#ifdef SIGPROF + [SIGPROF] = "SIGPROF", +#endif +#ifdef SIGWINCH + [SIGWINCH] = "SIGWINCH", +#endif +#ifdef SIGINFO + [SIGINFO] = "SIGINFO", +#endif +#ifdef SIGIO + [SIGIO] = "SIGIO", +#endif +#ifdef SIGPWR + [SIGPWR] = "SIGPWR", +#endif +#ifdef SIGSYS + [SIGSYS] = "SIGSYS", +#endif +#ifdef SIGWAITING + [SIGWAITING] = "SIGWAITING", +#endif +#ifdef SIGLWP + [SIGLWP] = "SIGLWP", +#endif +#ifdef SIGFREEZE + [SIGFREEZE] = "SIGFREEZE", +#endif +#ifdef SIGTHAW + [SIGTHAW] = "SIGTHAW", +#endif +#ifdef SIGCANCEL + [SIGCANCEL] = "SIGCANCEL", +#endif +#ifdef SIGLOST + [SIGLOST] = "SIGLOST", +#endif +}; + +static void sig_soft_quit(int signo) +{ + int saved_errno = errno; + + /* closing fastcgi listening socket will force fcgi_accept() exit immediately */ + close(0); + socket(AF_UNIX, SOCK_STREAM, 0); + + fpm_php_soft_quit(); + + errno = saved_errno; +} + +static void sig_handler(int signo) +{ + static const char sig_chars[NSIG + 1] = { + [SIGTERM] = 'T', + [SIGINT] = 'I', + [SIGUSR1] = '1', + [SIGUSR2] = '2', + [SIGQUIT] = 'Q', + [SIGCHLD] = 'C' + }; + char s; + int saved_errno; + + if (fpm_globals.parent_pid != getpid()) { + /* prevent a signal race condition when child process + have not set up it's own signal handler yet */ + return; + } + + saved_errno = errno; + + s = sig_chars[signo]; + + write(sp[1], &s, sizeof(s)); + + errno = saved_errno; +} + +int fpm_signals_init_main() +{ + struct sigaction act; + + if (0 > socketpair(AF_UNIX, SOCK_STREAM, 0, sp)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "socketpair() failed"); + return -1; + } + + if (0 > fd_set_blocked(sp[0], 0) || 0 > fd_set_blocked(sp[1], 0)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "fd_set_blocked() failed"); + return -1; + } + + if (0 > fcntl(sp[0], F_SETFD, FD_CLOEXEC) || 0 > fcntl(sp[1], F_SETFD, FD_CLOEXEC)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "fcntl(F_SETFD, FD_CLOEXEC) failed"); + return -1; + } + + memset(&act, 0, sizeof(act)); + act.sa_handler = sig_handler; + sigfillset(&act.sa_mask); + + if (0 > sigaction(SIGTERM, &act, 0) || + 0 > sigaction(SIGINT, &act, 0) || + 0 > sigaction(SIGUSR1, &act, 0) || + 0 > sigaction(SIGUSR2, &act, 0) || + 0 > sigaction(SIGCHLD, &act, 0) || + 0 > sigaction(SIGQUIT, &act, 0)) { + + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "sigaction() failed"); + return -1; + } + + return 0; +} + +int fpm_signals_init_child() +{ + struct sigaction act, act_dfl; + + memset(&act, 0, sizeof(act)); + memset(&act_dfl, 0, sizeof(act_dfl)); + + act.sa_handler = &sig_soft_quit; + act.sa_flags |= SA_RESTART; + + act_dfl.sa_handler = SIG_DFL; + + close(sp[0]); + close(sp[1]); + + if (0 > sigaction(SIGTERM, &act_dfl, 0) || + 0 > sigaction(SIGINT, &act_dfl, 0) || + 0 > sigaction(SIGUSR1, &act_dfl, 0) || + 0 > sigaction(SIGUSR2, &act_dfl, 0) || + 0 > sigaction(SIGCHLD, &act_dfl, 0) || + 0 > sigaction(SIGQUIT, &act, 0)) { + + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "sigaction() failed"); + return -1; + } + + return 0; +} + +int fpm_signals_get_fd() +{ + return sp[0]; +} diff --git a/sapi/cgi/fpm/fpm_signals.h b/sapi/cgi/fpm/fpm_signals.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_signals.h @@ -0,0 +1,16 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_SIGNALS_H +#define FPM_SIGNALS_H 1 + +#include + +int fpm_signals_init_main(); +int fpm_signals_init_child(); +int fpm_signals_get_fd(); + +extern const char *fpm_signal_names[NSIG + 1]; + +#endif diff --git a/sapi/cgi/fpm/fpm_sockets.c b/sapi/cgi/fpm/fpm_sockets.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_sockets.c @@ -0,0 +1,427 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#ifdef HAVE_ALLOCA_H +#include +#endif +#include +#include /* for chmod(2) */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "zlog.h" +#include "fpm_arrays.h" +#include "fpm_sockets.h" +#include "fpm_worker_pool.h" +#include "fpm_unix.h" +#include "fpm_str.h" +#include "fpm_env.h" +#include "fpm_cleanup.h" + +struct listening_socket_s { + int refcount; + int sock; + int type; + char *key; +}; + +static struct fpm_array_s sockets_list; + +static int fpm_sockets_resolve_af_inet(char *node, char *service, struct sockaddr_in *addr) +{ + struct addrinfo *res; + struct addrinfo hints; + int ret; + + memset(&hints, 0, sizeof(hints)); + + hints.ai_family = AF_INET; + + ret = getaddrinfo(node, service, &hints, &res); + + if (ret != 0) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "can't resolve hostname '%s%s%s': getaddrinfo said: %s%s%s\n", + node, service ? ":" : "", service ? service : "", + gai_strerror(ret), ret == EAI_SYSTEM ? ", system error: " : "", ret == EAI_SYSTEM ? strerror(errno) : ""); + return -1; + } + + *addr = *(struct sockaddr_in *) res->ai_addr; + + freeaddrinfo(res); + + return 0; +} + +enum { FPM_GET_USE_SOCKET = 1, FPM_STORE_SOCKET = 2, FPM_STORE_USE_SOCKET = 3 }; + +static void fpm_sockets_cleanup(int which, void *arg) +{ + int i; + char *env_value = 0; + int p = 0; + struct listening_socket_s *ls = sockets_list.data; + + for (i = 0; i < sockets_list.used; i++, ls++) { + + if (which != FPM_CLEANUP_PARENT_EXEC) { + + close(ls->sock); + + } + else { /* on PARENT EXEC we want socket fds to be inherited through environment variable */ + char fd[32]; + sprintf(fd, "%d", ls->sock); + env_value = realloc(env_value, p + (p ? 1 : 0) + strlen(ls->key) + 1 + strlen(fd) + 1); + p += sprintf(env_value + p, "%s%s=%s", p ? "," : "", ls->key, fd); + } + + if (which == FPM_CLEANUP_PARENT_EXIT_MAIN) { + + if (ls->type == FPM_AF_UNIX) { + unlink(ls->key); + } + + } + + free(ls->key); + } + + if (env_value) { + setenv("FPM_SOCKETS", env_value, 1); + free(env_value); + } + + fpm_array_free(&sockets_list); +} + +static int fpm_sockets_hash_op(int sock, struct sockaddr *sa, char *key, int type, int op) +{ + + if (key == NULL) { + + switch (type) { + + case FPM_AF_INET : { + struct sockaddr_in *sa_in = (struct sockaddr_in *) sa; + + key = alloca(sizeof("xxx.xxx.xxx.xxx:ppppp")); + + sprintf(key, "%u.%u.%u.%u:%u", IPQUAD(&sa_in->sin_addr), (unsigned int) ntohs(sa_in->sin_port)); + + break; + } + + case FPM_AF_UNIX : { + struct sockaddr_un *sa_un = (struct sockaddr_un *) sa; + + key = alloca(strlen(sa_un->sun_path) + 1); + + strcpy(key, sa_un->sun_path); + + break; + } + + default : + + return -1; + } + + } + + switch (op) { + + case FPM_GET_USE_SOCKET : + { + + int i; + struct listening_socket_s *ls = sockets_list.data; + + for (i = 0; i < sockets_list.used; i++, ls++) { + + if (!strcmp(ls->key, key)) { + ++ls->refcount; + return ls->sock; + } + } + + break; + } + + case FPM_STORE_SOCKET : /* inherited socket */ + case FPM_STORE_USE_SOCKET : /* just created */ + { + + struct listening_socket_s *ls; + + ls = fpm_array_push(&sockets_list); + + if (!ls) { + break; + } + + if (op == FPM_STORE_SOCKET) { + ls->refcount = 0; + } + else { + ls->refcount = 1; + } + ls->type = type; + ls->sock = sock; + ls->key = strdup(key); + + return 0; + + } + } + + return -1; + +} + +static int fpm_sockets_new_listening_socket(struct fpm_worker_pool_s *wp, struct sockaddr *sa, int socklen) +{ + int backlog = -1; + int flags = 1; + int sock; + mode_t saved_umask; + + /* we have custom backlog value */ + if (wp->config->listen_options) { + backlog = wp->config->listen_options->backlog; + } + + sock = socket(sa->sa_family, SOCK_STREAM, 0); + + if (0 > sock) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "socket() failed"); + return -1; + } + + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags)); + + if (wp->listen_address_domain == FPM_AF_UNIX) { + unlink( ((struct sockaddr_un *) sa)->sun_path); + } + + saved_umask = umask(0777 ^ wp->socket_mode); + + if (0 > bind(sock, sa, socklen)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "bind() for address '%s' failed", wp->config->listen_address); + return -1; + } + + if (wp->listen_address_domain == FPM_AF_UNIX) { + + char *path = ((struct sockaddr_un *) sa)->sun_path; + + if (wp->socket_uid != -1 || wp->socket_gid != -1) { + + if (0 > chown(path, wp->socket_uid, wp->socket_gid)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "chown() for address '%s' failed", wp->config->listen_address); + return -1; + } + + } + + } + + umask(saved_umask); + + if (0 > listen(sock, backlog)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "listen() for address '%s' failed", wp->config->listen_address); + return -1; + } + + return sock; +} + +static int fpm_sockets_get_listening_socket(struct fpm_worker_pool_s *wp, struct sockaddr *sa, int socklen) +{ + int sock; + + sock = fpm_sockets_hash_op(0, sa, 0, wp->listen_address_domain, FPM_GET_USE_SOCKET); + + if (sock >= 0) return sock; + + sock = fpm_sockets_new_listening_socket(wp, sa, socklen); + + fpm_sockets_hash_op(sock, sa, 0, wp->listen_address_domain, FPM_STORE_USE_SOCKET); + + return sock; +} + +enum fpm_address_domain fpm_sockets_domain_from_address(char *address) +{ + if (strchr(address, ':')) return FPM_AF_INET; + + if (strlen(address) == strspn(address, "0123456789")) return FPM_AF_INET; + + return FPM_AF_UNIX; +} + +static int fpm_socket_af_inet_listening_socket(struct fpm_worker_pool_s *wp) +{ + struct sockaddr_in sa_in; + char *dup_address = strdup(wp->config->listen_address); + char *port_str = strchr(dup_address, ':'); + char *addr = NULL; + int port = 0; + + if (port_str) { /* this is host:port pair */ + *port_str++ = '\0'; + port = atoi(port_str); + addr = dup_address; + } + else if (strlen(dup_address) == strspn(dup_address, "0123456789")) { /* this is port */ + port = atoi(dup_address); + port_str = dup_address; + } + + if (port == 0) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "invalid port value '%s'", port_str); + return -1; + } + + memset(&sa_in, 0, sizeof(sa_in)); + + if (addr) { + + sa_in.sin_addr.s_addr = inet_addr(addr); + + if (sa_in.sin_addr.s_addr == INADDR_NONE) { /* do resolve */ + if (0 > fpm_sockets_resolve_af_inet(addr, NULL, &sa_in)) { + return -1; + } + zlog(ZLOG_STUFF, ZLOG_NOTICE, "address '%s' resolved as %u.%u.%u.%u", addr, IPQUAD(&sa_in.sin_addr)); + } + } + else { + + sa_in.sin_addr.s_addr = htonl(INADDR_ANY); + + } + + sa_in.sin_family = AF_INET; + sa_in.sin_port = htons(port); + + free(dup_address); + + return fpm_sockets_get_listening_socket(wp, (struct sockaddr *) &sa_in, sizeof(struct sockaddr_in)); +} + +static int fpm_socket_af_unix_listening_socket(struct fpm_worker_pool_s *wp) +{ + struct sockaddr_un sa_un; + + memset(&sa_un, 0, sizeof(sa_un)); + + cpystrn(sa_un.sun_path, wp->config->listen_address, sizeof(sa_un.sun_path)); + sa_un.sun_family = AF_UNIX; + + return fpm_sockets_get_listening_socket(wp, (struct sockaddr *) &sa_un, sizeof(struct sockaddr_un)); +} + +int fpm_sockets_init_main() +{ + int i; + struct fpm_worker_pool_s *wp; + char *inherited = getenv("FPM_SOCKETS"); + struct listening_socket_s *ls; + + if (0 == fpm_array_init(&sockets_list, sizeof(struct listening_socket_s), 10)) { + return -1; + } + + /* import inherited sockets */ + while (inherited && *inherited) { + char *comma = strchr(inherited, ','); + int type, fd_no; + char *eq; + + if (comma) *comma = '\0'; + + eq = strchr(inherited, '='); + + if (eq) { + *eq = '\0'; + + fd_no = atoi(eq + 1); + + type = fpm_sockets_domain_from_address(inherited); + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "using inherited socket fd=%d, \"%s\"", fd_no, inherited); + + fpm_sockets_hash_op(fd_no, 0, inherited, type, FPM_STORE_SOCKET); + } + + if (comma) inherited = comma + 1; + else inherited = 0; + } + + /* create all required sockets */ + for (wp = fpm_worker_all_pools; wp; wp = wp->next) { + + if (!wp->is_template) { + + switch (wp->listen_address_domain) { + + case FPM_AF_INET : + + wp->listening_socket = fpm_socket_af_inet_listening_socket(wp); + break; + + case FPM_AF_UNIX : + + if (0 > fpm_unix_resolve_socket_premissions(wp)) { + return -1; + } + + wp->listening_socket = fpm_socket_af_unix_listening_socket(wp); + break; + + } + + if (wp->listening_socket == -1) { + return -1; + } + } + + } + + /* close unused sockets that was inherited */ + ls = sockets_list.data; + + for (i = 0; i < sockets_list.used; ) { + + if (ls->refcount == 0) { + close(ls->sock); + if (ls->type == FPM_AF_UNIX) { + unlink(ls->key); + } + free(ls->key); + fpm_array_item_remove(&sockets_list, i); + } + else { + ++i; + ++ls; + } + } + + if (0 > fpm_cleanup_add(FPM_CLEANUP_ALL, fpm_sockets_cleanup, 0)) { + return -1; + } + + return 0; +} diff --git a/sapi/cgi/fpm/fpm_sockets.h b/sapi/cgi/fpm/fpm_sockets.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_sockets.h @@ -0,0 +1,37 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_MISC_H +#define FPM_MISC_H 1 + +#include +#include + +#include "fpm_worker_pool.h" + +enum fpm_address_domain fpm_sockets_domain_from_address(char *addr); +int fpm_sockets_init_main(); + + +static inline int fd_set_blocked(int fd, int blocked) +{ + int flags = fcntl(fd, F_GETFL); + + if (flags < 0) return -1; + + if (blocked) + flags &= ~O_NONBLOCK; + else + flags |= O_NONBLOCK; + + return fcntl(fd, F_SETFL, flags); +} + +#define IPQUAD(sin_addr) \ + (unsigned int) ((unsigned char *) &(sin_addr)->s_addr)[0], \ + (unsigned int) ((unsigned char *) &(sin_addr)->s_addr)[1], \ + (unsigned int) ((unsigned char *) &(sin_addr)->s_addr)[2], \ + (unsigned int) ((unsigned char *) &(sin_addr)->s_addr)[3] + +#endif diff --git a/sapi/cgi/fpm/fpm_stdio.c b/sapi/cgi/fpm/fpm_stdio.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_stdio.c @@ -0,0 +1,286 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include +#include +#include +#include + +#include "fpm.h" +#include "fpm_children.h" +#include "fpm_events.h" +#include "fpm_sockets.h" +#include "fpm_stdio.h" +#include "zlog.h" + +static int fd_stdout[2]; +static int fd_stderr[2]; + +int fpm_stdio_init_main() +{ + int fd = open("/dev/null", O_RDWR); + + if (0 > fd) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "open(\"/dev/null\") failed"); + return -1; + } + + if (0 > dup2(fd, STDIN_FILENO) || 0 > dup2(fd, STDOUT_FILENO)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "dup2() failed"); + return -1; + } + + close(fd); + + return 0; +} + +int fpm_stdio_init_final() +{ + if (fpm_global_config.daemonize) { + + if (fpm_globals.error_log_fd != STDERR_FILENO) { + /* there might be messages to stderr from libevent, we need to log them all */ + if (0 > dup2(fpm_globals.error_log_fd, STDERR_FILENO)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "dup2() failed"); + return -1; + } + } + + zlog_set_level(fpm_globals.log_level); + + zlog_set_fd(fpm_globals.error_log_fd); + } + + return 0; +} + +int fpm_stdio_init_child(struct fpm_worker_pool_s *wp) +{ + close(fpm_globals.error_log_fd); + fpm_globals.error_log_fd = -1; + zlog_set_fd(-1); + + if (wp->listening_socket != STDIN_FILENO) { + if (0 > dup2(wp->listening_socket, STDIN_FILENO)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "dup2() failed"); + return -1; + } + } + + return 0; +} + +static void fpm_stdio_child_said(int fd, short which, void *arg) +{ + static const int max_buf_size = 1024; + char buf[max_buf_size]; + struct fpm_child_s *child = arg; + int is_stdout = fd == child->fd_stdout; + struct event *ev = is_stdout ? &child->ev_stdout : &child->ev_stderr; + int fifo_in = 1, fifo_out = 1; + int is_last_message = 0; + int in_buf = 0; + int res; + +#if 0 + zlog(ZLOG_STUFF, ZLOG_DEBUG, "child %d said %s", (int) child->pid, is_stdout ? "stdout" : "stderr"); +#endif + + while (fifo_in || fifo_out) { + + if (fifo_in) { + + res = read(fd, buf + in_buf, max_buf_size - 1 - in_buf); + + if (res <= 0) { /* no data */ + fifo_in = 0; + + if (res < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + /* just no more data ready */ + } + else { /* error or pipe is closed */ + + if (res < 0) { /* error */ + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "read() failed"); + } + + fpm_event_del(ev); + is_last_message = 1; + + if (is_stdout) { + close(child->fd_stdout); + child->fd_stdout = -1; + } + else { + close(child->fd_stderr); + child->fd_stderr = -1; + } + +#if 0 + if (in_buf == 0 && !fpm_globals.is_child) { + zlog(ZLOG_STUFF, ZLOG_DEBUG, "child %d (pool %s) %s pipe is closed", (int) child->pid, + child->wp->config->name, is_stdout ? "stdout" : "stderr"); + } +#endif + } + } + else { + in_buf += res; + } + } + + if (fifo_out) { + if (in_buf == 0) { + fifo_out = 0; + } + else { + char *nl; + int should_print = 0; + buf[in_buf] = '\0'; + + /* FIXME: there might be binary data */ + + /* we should print if no more space in the buffer */ + if (in_buf == max_buf_size - 1) { + should_print = 1; + } + + /* we should print if no more data to come */ + if (!fifo_in) { + should_print = 1; + } + + nl = strchr(buf, '\n'); + + if (nl || should_print) { + + if (nl) { + *nl = '\0'; + } + + zlog(ZLOG_STUFF, ZLOG_WARNING, "child %d (pool %s) said into %s: \"%s\"%s", (int) child->pid, + child->wp->config->name, is_stdout ? "stdout" : "stderr", buf, is_last_message ? ", pipe is closed" : ""); + + if (nl) { + int out_buf = 1 + nl - buf; + memmove(buf, buf + out_buf, in_buf - out_buf); + in_buf -= out_buf; + } + else { + in_buf = 0; + } + } + } + } + } + +} + +int fpm_stdio_prepare_pipes(struct fpm_child_s *child) +{ + if (0 == child->wp->config->catch_workers_output) { /* not required */ + return 0; + } + + if (0 > pipe(fd_stdout)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "pipe() failed"); + return -1; + } + + if (0 > pipe(fd_stderr)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "pipe() failed"); + close(fd_stdout[0]); close(fd_stdout[1]); + return -1; + } + + if (0 > fd_set_blocked(fd_stdout[0], 0) || 0 > fd_set_blocked(fd_stderr[0], 0)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "fd_set_blocked() failed"); + close(fd_stdout[0]); close(fd_stdout[1]); + close(fd_stderr[0]); close(fd_stderr[1]); + return -1; + } + + return 0; +} + +int fpm_stdio_parent_use_pipes(struct fpm_child_s *child) +{ + if (0 == child->wp->config->catch_workers_output) { /* not required */ + return 0; + } + + close(fd_stdout[1]); + close(fd_stderr[1]); + + child->fd_stdout = fd_stdout[0]; + child->fd_stderr = fd_stderr[0]; + + fpm_event_add(child->fd_stdout, &child->ev_stdout, fpm_stdio_child_said, child); + fpm_event_add(child->fd_stderr, &child->ev_stderr, fpm_stdio_child_said, child); + + return 0; +} + +int fpm_stdio_discard_pipes(struct fpm_child_s *child) +{ + if (0 == child->wp->config->catch_workers_output) { /* not required */ + return 0; + } + + close(fd_stdout[1]); + close(fd_stderr[1]); + + close(fd_stdout[0]); + close(fd_stderr[0]); + + return 0; +} + +void fpm_stdio_child_use_pipes(struct fpm_child_s *child) +{ + if (child->wp->config->catch_workers_output) { + dup2(fd_stdout[1], STDOUT_FILENO); + dup2(fd_stderr[1], STDERR_FILENO); + close(fd_stdout[0]); close(fd_stdout[1]); + close(fd_stderr[0]); close(fd_stderr[1]); + } + else { + /* stdout of parent is always /dev/null */ + dup2(STDOUT_FILENO, STDERR_FILENO); + } +} + +int fpm_stdio_open_error_log(int reopen) +{ + int fd; + + fd = open(fpm_global_config.error_log, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); + + if (0 > fd) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "open(\"%s\") failed", fpm_global_config.error_log); + return -1; + } + + if (reopen) { + if (fpm_global_config.daemonize) { + dup2(fd, STDERR_FILENO); + } + + dup2(fd, fpm_globals.error_log_fd); + close(fd); + fd = fpm_globals.error_log_fd; /* for FD_CLOSEXEC to work */ + } + else { + fpm_globals.error_log_fd = fd; + } + + fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); + + return 0; +} diff --git a/sapi/cgi/fpm/fpm_stdio.h b/sapi/cgi/fpm/fpm_stdio.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_stdio.h @@ -0,0 +1,20 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_STDIO_H +#define FPM_STDIO_H 1 + +#include "fpm_worker_pool.h" + +int fpm_stdio_init_main(); +int fpm_stdio_init_final(); +int fpm_stdio_init_child(struct fpm_worker_pool_s *wp); +int fpm_stdio_prepare_pipes(struct fpm_child_s *child); +void fpm_stdio_child_use_pipes(struct fpm_child_s *child); +int fpm_stdio_parent_use_pipes(struct fpm_child_s *child); +int fpm_stdio_discard_pipes(struct fpm_child_s *child); +int fpm_stdio_open_error_log(int reopen); + +#endif + diff --git a/sapi/cgi/fpm/fpm_str.h b/sapi/cgi/fpm/fpm_str.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_str.h @@ -0,0 +1,49 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_STR_H +#define FPM_STR_H 1 + +static inline char *cpystrn(char *dst, const char *src, size_t dst_size) +{ + char *d, *end; + + if (!dst_size) return dst; + + d = dst; + end = dst + dst_size - 1; + + for (; d < end; ++d, ++src) { + if (!(*d = *src)) { + return d; + } + } + + *d = '\0'; + + return d; +} + +static inline char *str_purify_filename(char *dst, char *src, size_t size) +{ + char *d, *end; + + d = dst; + end = dst + size - 1; + + for (; d < end && *src; ++d, ++src) { + if (* (unsigned char *) src < ' ' || * (unsigned char *) src > '\x7f') { + *d = '.'; + } + else { + *d = *src; + } + } + + *d = '\0'; + + return d; +} + +#endif diff --git a/sapi/cgi/fpm/fpm_trace.c b/sapi/cgi/fpm/fpm_trace.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_trace.c @@ -0,0 +1,46 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include + +#include "fpm_trace.h" + +int fpm_trace_get_strz(char *buf, size_t sz, long addr) +{ + int i; + long l; + char *lc = (char *) &l; + + if (0 > fpm_trace_get_long(addr, &l)) { + return -1; + } + + i = l % SIZEOF_LONG; + + l -= i; + + for (addr = l; ; addr += SIZEOF_LONG) { + + if (0 > fpm_trace_get_long(addr, &l)) { + return -1; + } + + for ( ; i < SIZEOF_LONG; i++) { + --sz; + + if (sz && lc[i]) { + *buf++ = lc[i]; + continue; + } + + *buf = '\0'; + return 0; + } + + i = 0; + } +} + diff --git a/sapi/cgi/fpm/fpm_trace.h b/sapi/cgi/fpm/fpm_trace.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_trace.h @@ -0,0 +1,17 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_TRACE_H +#define FPM_TRACE_H 1 + +#include + +int fpm_trace_signal(pid_t pid); +int fpm_trace_ready(pid_t pid); +int fpm_trace_close(pid_t pid); +int fpm_trace_get_long(long addr, long *data); +int fpm_trace_get_strz(char *buf, size_t sz, long addr); + +#endif + diff --git a/sapi/cgi/fpm/fpm_trace_mach.c b/sapi/cgi/fpm/fpm_trace_mach.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_trace_mach.c @@ -0,0 +1,102 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include + +#include + +#include "fpm_trace.h" +#include "fpm_process_ctl.h" +#include "fpm_unix.h" +#include "zlog.h" + + +static mach_port_name_t target; +static vm_offset_t target_page_base; +static vm_offset_t local_page; +static mach_msg_type_number_t local_size; + +static void fpm_mach_vm_deallocate() +{ + if (local_page) { + mach_vm_deallocate(mach_task_self(), local_page, local_size); + target_page_base = 0; + local_page = 0; + local_size = 0; + } +} + +static int fpm_mach_vm_read_page(vm_offset_t page) +{ + kern_return_t kr; + + kr = mach_vm_read(target, page, fpm_pagesize, &local_page, &local_size); + + if (kr != KERN_SUCCESS) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "mach_vm_read() failed: %s (%d)", mach_error_string(kr), kr); + return -1; + } + + return 0; +} + +int fpm_trace_signal(pid_t pid) +{ + if (0 > fpm_pctl_kill(pid, FPM_PCTL_STOP)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "kill(SIGSTOP) failed"); + return -1; + } + + return 0; +} + +int fpm_trace_ready(pid_t pid) +{ + kern_return_t kr; + + kr = task_for_pid(mach_task_self(), pid, &target); + + if (kr != KERN_SUCCESS) { + char *msg = ""; + + if (kr == KERN_FAILURE) { + msg = " It seems that master process does not have enough privileges to trace processes."; + } + + zlog(ZLOG_STUFF, ZLOG_ERROR, "task_for_pid() failed: %s (%d)%s", mach_error_string(kr), kr, msg); + return -1; + } + + return 0; +} + +int fpm_trace_close(pid_t pid) +{ + fpm_mach_vm_deallocate(); + + target = 0; + + return 0; +} + +int fpm_trace_get_long(long addr, long *data) +{ + size_t offset = ((uintptr_t) (addr) % fpm_pagesize); + vm_offset_t base = (uintptr_t) (addr) - offset; + + if (base != target_page_base) { + fpm_mach_vm_deallocate(); + if (0 > fpm_mach_vm_read_page(base)) { + return -1; + } + } + + *data = * (long *) (local_page + offset); + + return 0; +} + diff --git a/sapi/cgi/fpm/fpm_trace_pread.c b/sapi/cgi/fpm/fpm_trace_pread.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_trace_pread.c @@ -0,0 +1,67 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#define _GNU_SOURCE +#define _FILE_OFFSET_BITS 64 + +#include "fpm_config.h" + +#include + +#include +#include +#include + +#include "fpm_trace.h" +#include "fpm_process_ctl.h" +#include "zlog.h" + + +static int mem_file = -1; + +int fpm_trace_signal(pid_t pid) +{ + if (0 > fpm_pctl_kill(pid, FPM_PCTL_STOP)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "kill(SIGSTOP) failed"); + return -1; + } + + return 0; +} + +int fpm_trace_ready(pid_t pid) +{ + char buf[128]; + + sprintf(buf, "/proc/%d/" PROC_MEM_FILE, (int) pid); + + mem_file = open(buf, O_RDONLY); + + if (0 > mem_file) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "open(%s) failed", buf); + return -1; + } + + return 0; +} + +int fpm_trace_close(pid_t pid) +{ + close(mem_file); + + mem_file = -1; + + return 0; +} + +int fpm_trace_get_long(long addr, long *data) +{ + if (sizeof(*data) != pread(mem_file, (void *) data, sizeof(*data), (uintptr_t) addr)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "pread() failed"); + return -1; + } + + return 0; +} + diff --git a/sapi/cgi/fpm/fpm_trace_ptrace.c b/sapi/cgi/fpm/fpm_trace_ptrace.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_trace_ptrace.c @@ -0,0 +1,85 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include +#include + +#if defined(PT_ATTACH) && !defined(PTRACE_ATTACH) +#define PTRACE_ATTACH PT_ATTACH +#endif + +#if defined(PT_DETACH) && !defined(PTRACE_DETACH) +#define PTRACE_DETACH PT_DETACH +#endif + +#if defined(PT_READ_D) && !defined(PTRACE_PEEKDATA) +#define PTRACE_PEEKDATA PT_READ_D +#endif + +#include "fpm_trace.h" +#include "zlog.h" + +static pid_t traced_pid; + +int fpm_trace_signal(pid_t pid) +{ + if (0 > ptrace(PTRACE_ATTACH, pid, 0, 0)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "ptrace(ATTACH) failed"); + return -1; + } + + return 0; +} + +int fpm_trace_ready(pid_t pid) +{ + traced_pid = pid; + + return 0; +} + +int fpm_trace_close(pid_t pid) +{ + if (0 > ptrace(PTRACE_DETACH, pid, (void *) 1, 0)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "ptrace(DETACH) failed"); + return -1; + } + + traced_pid = 0; + + return 0; +} + +int fpm_trace_get_long(long addr, long *data) +{ +#ifdef PT_IO + struct ptrace_io_desc ptio = { + .piod_op = PIOD_READ_D, + .piod_offs = (void *) addr, + .piod_addr = (void *) data, + .piod_len = sizeof(long) + }; + + if (0 > ptrace(PT_IO, traced_pid, (void *) &ptio, 0)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "ptrace(PT_IO) failed"); + return -1; + } +#else + errno = 0; + + *data = ptrace(PTRACE_PEEKDATA, traced_pid, (void *) addr, 0); + + if (errno) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "ptrace(PEEKDATA) failed"); + return -1; + } +#endif + + return 0; +} + diff --git a/sapi/cgi/fpm/fpm_unix.c b/sapi/cgi/fpm/fpm_unix.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_unix.c @@ -0,0 +1,289 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_PRCTL +#include +#endif + +#include "fpm.h" +#include "fpm_conf.h" +#include "fpm_cleanup.h" +#include "fpm_clock.h" +#include "fpm_stdio.h" +#include "fpm_unix.h" +#include "zlog.h" + +size_t fpm_pagesize; + +int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp) +{ + struct fpm_listen_options_s *lo = wp->config->listen_options; + + /* uninitialized */ + wp->socket_uid = -1; + wp->socket_gid = -1; + wp->socket_mode = 0666; + + if (!lo) return 0; + + if (lo->owner && *lo->owner) { + struct passwd *pwd; + + pwd = getpwnam(lo->owner); + + if (!pwd) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "cannot get uid for user '%s', pool '%s'", lo->owner, wp->config->name); + return -1; + } + + wp->socket_uid = pwd->pw_uid; + wp->socket_gid = pwd->pw_gid; + } + + if (lo->group && *lo->group) { + struct group *grp; + + grp = getgrnam(lo->group); + + if (!grp) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "cannot get gid for group '%s', pool '%s'", lo->group, wp->config->name); + return -1; + } + + wp->socket_gid = grp->gr_gid; + } + + if (lo->mode && *lo->mode) { + wp->socket_mode = strtoul(lo->mode, 0, 8); + } + + return 0; +} + +static int fpm_unix_conf_wp(struct fpm_worker_pool_s *wp) +{ + int is_root = !geteuid(); + + if (is_root) { + if (wp->config->user && *wp->config->user) { + + if (strlen(wp->config->user) == strspn(wp->config->user, "0123456789")) { + wp->set_uid = strtoul(wp->config->user, 0, 10); + } + else { + struct passwd *pwd; + + pwd = getpwnam(wp->config->user); + + if (!pwd) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "cannot get uid for user '%s', pool '%s'", wp->config->user, wp->config->name); + return -1; + } + + wp->set_uid = pwd->pw_uid; + wp->set_gid = pwd->pw_gid; + + wp->user = strdup(pwd->pw_name); + wp->home = strdup(pwd->pw_dir); + } + } + + if (wp->config->group && *wp->config->group) { + + if (strlen(wp->config->group) == strspn(wp->config->group, "0123456789")) { + wp->set_gid = strtoul(wp->config->group, 0, 10); + } + else { + struct group *grp; + + grp = getgrnam(wp->config->group); + + if (!grp) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "cannot get gid for group '%s', pool '%s'", wp->config->group, wp->config->name); + return -1; + } + + wp->set_gid = grp->gr_gid; + } + } + +#ifndef I_REALLY_WANT_ROOT_PHP + if (wp->set_uid == 0 || wp->set_gid == 0) { + zlog(ZLOG_STUFF, ZLOG_ERROR, "please specify user and group other than root, pool '%s'", wp->config->name); + return -1; + } +#endif + } + else { /* not root */ + if (wp->config->user && *wp->config->user) { + zlog(ZLOG_STUFF, ZLOG_WARNING, "'user' directive is ignored, pool '%s'", wp->config->name); + } + if (wp->config->group && *wp->config->group) { + zlog(ZLOG_STUFF, ZLOG_WARNING, "'group' directive is ignored, pool '%s'", wp->config->name); + } + if (wp->config->chroot && *wp->config->chroot) { + zlog(ZLOG_STUFF, ZLOG_WARNING, "'chroot' directive is ignored, pool '%s'", wp->config->name); + } + + { /* set up HOME and USER anyway */ + struct passwd *pwd; + + pwd = getpwuid(getuid()); + + if (pwd) { + wp->user = strdup(pwd->pw_name); + wp->home = strdup(pwd->pw_dir); + } + } + } + + return 0; +} + +int fpm_unix_init_child(struct fpm_worker_pool_s *wp) +{ + int is_root = !geteuid(); + int made_chroot = 0; + + if (wp->config->rlimit_files) { + struct rlimit r; + + getrlimit(RLIMIT_NOFILE, &r); + + r.rlim_cur = (rlim_t) wp->config->rlimit_files; + r.rlim_max = r.rlim_cur; + if (0 > setrlimit(RLIMIT_NOFILE, &r)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "setrlimit(RLIMIT_NOFILE) failed"); + } + } + + if (wp->config->rlimit_core) { + struct rlimit r; + + getrlimit(RLIMIT_CORE, &r); + + r.rlim_cur = wp->config->rlimit_core == -1 ? (rlim_t) RLIM_INFINITY : (rlim_t) wp->config->rlimit_core; + r.rlim_max = r.rlim_cur; + if (0 > setrlimit(RLIMIT_CORE, &r)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "setrlimit(RLIMIT_CORE) failed"); + } + } + + if (is_root && wp->config->chroot && *wp->config->chroot) { + if (0 > chroot(wp->config->chroot)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "chroot(%s) failed", wp->config->chroot); + return -1; + } + made_chroot = 1; + } + + if (wp->config->chdir && *wp->config->chdir) { + if (0 > chdir(wp->config->chdir)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "chdir(%s) failed", wp->config->chdir); + return -1; + } + } + else if (made_chroot) { + chdir("/"); + } + + if (is_root) { + if (wp->set_gid) { + if (0 > setgid(wp->set_gid)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "setgid(%d) failed", wp->set_gid); + return -1; + } + } + if (wp->set_uid) { + if (0 > initgroups(wp->config->user, wp->set_gid)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "initgroups(%s, %d) failed", wp->config->user, wp->set_gid); + return -1; + } + if (0 > setuid(wp->set_uid)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "setuid(%d) failed", wp->set_uid); + return -1; + } + } + } + +#ifdef HAVE_PRCTL + if (0 > prctl(PR_SET_DUMPABLE, 1, 0, 0, 0)) { + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "prctl(PR_SET_DUMPABLE) failed"); + } +#endif + + if (0 > fpm_clock_init()) { + return -1; + } + + return 0; +} + +int fpm_unix_init_main() +{ + struct fpm_worker_pool_s *wp; + + fpm_pagesize = getpagesize(); + + if (fpm_global_config.daemonize) { + + switch (fork()) { + + case -1 : + + zlog(ZLOG_STUFF, ZLOG_SYSERROR, "fork() failed"); + return -1; + + case 0 : + + break; + + default : + + fpm_cleanups_run(FPM_CLEANUP_PARENT_EXIT); + exit(0); + + } + + } + + setsid(); + + if (0 > fpm_clock_init()) { + return -1; + } + + fpm_globals.parent_pid = getpid(); + + for (wp = fpm_worker_all_pools; wp; wp = wp->next) { + + if (0 > fpm_unix_conf_wp(wp)) { + return -1; + } + + } + + fpm_stdio_init_final(); + + { + struct rlimit r; + getrlimit(RLIMIT_NOFILE, &r); + + zlog(ZLOG_STUFF, ZLOG_NOTICE, "getrlimit(nofile): max:%lld, cur:%lld", + (long long) r.rlim_max, (long long) r.rlim_cur); + } + + return 0; +} diff --git a/sapi/cgi/fpm/fpm_unix.h b/sapi/cgi/fpm/fpm_unix.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_unix.h @@ -0,0 +1,17 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_UNIX_H +#define FPM_UNIX_H 1 + +#include "fpm_worker_pool.h" + +int fpm_unix_resolve_socket_premissions(struct fpm_worker_pool_s *wp); +int fpm_unix_init_child(struct fpm_worker_pool_s *wp); +int fpm_unix_init_main(); + +extern size_t fpm_pagesize; + +#endif + diff --git a/sapi/cgi/fpm/fpm_worker_pool.c b/sapi/cgi/fpm/fpm_worker_pool.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_worker_pool.c @@ -0,0 +1,69 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include + +#include "fpm_worker_pool.h" +#include "fpm_cleanup.h" +#include "fpm_children.h" +#include "fpm_shm.h" +#include "fpm_shm_slots.h" +#include "fpm_conf.h" + +struct fpm_worker_pool_s *fpm_worker_all_pools; + +static void fpm_worker_pool_cleanup(int which, void *arg) +{ + struct fpm_worker_pool_s *wp, *wp_next; + + for (wp = fpm_worker_all_pools; wp; wp = wp_next) { + wp_next = wp->next; + fpm_worker_pool_config_free(wp->config); + fpm_children_free(wp->children); + fpm_array_free(&wp->slots_used); + fpm_array_free(&wp->slots_free); + fpm_shm_free_list(wp->shm_list, which == FPM_CLEANUP_CHILD ? fpm_shm_slots_mem() : 0); + free(wp->config); + free(wp->user); + free(wp->home); + free(wp); + } + + fpm_worker_all_pools = 0; +} + +struct fpm_worker_pool_s *fpm_worker_pool_alloc() +{ + struct fpm_worker_pool_s *ret; + + ret = malloc(sizeof(struct fpm_worker_pool_s)); + + if (!ret) { + return 0; + } + + memset(ret, 0, sizeof(struct fpm_worker_pool_s)); + + if (!fpm_worker_all_pools) { + fpm_worker_all_pools = ret; + } + + fpm_array_init(&ret->slots_used, sizeof(struct fpm_shm_slot_ptr_s), 50); + fpm_array_init(&ret->slots_free, sizeof(struct fpm_shm_slot_ptr_s), 50); + + return ret; +} + +int fpm_worker_pool_init_main() +{ + if (0 > fpm_cleanup_add(FPM_CLEANUP_ALL, fpm_worker_pool_cleanup, 0)) { + return -1; + } + + return 0; +} diff --git a/sapi/cgi/fpm/fpm_worker_pool.h b/sapi/cgi/fpm/fpm_worker_pool.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/fpm_worker_pool.h @@ -0,0 +1,46 @@ + + /* $Id$ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#ifndef FPM_WORKER_POOL_H +#define FPM_WORKER_POOL_H 1 + +#include "fpm_conf.h" +#include "fpm_arrays.h" + +struct fpm_worker_pool_s; +struct fpm_child_s; +struct fpm_child_stat_s; +struct fpm_shm_s; + +enum fpm_address_domain { + FPM_AF_UNIX = 1, + FPM_AF_INET = 2 +}; + +struct fpm_worker_pool_s { + struct fpm_worker_pool_s *next; + struct fpm_worker_pool_config_s *config; + char *user, *home; /* for setting env USER and HOME */ + enum fpm_address_domain listen_address_domain; + int listening_socket; + int set_uid, set_gid; /* config uid and gid */ + unsigned is_template:1; /* just config template, no processes will be created */ + int socket_uid, socket_gid, socket_mode; + + struct fpm_shm_s *shm_list; + struct fpm_array_s slots_used; + struct fpm_array_s slots_free; + + /* runtime */ + struct fpm_child_s *children; + int running_children; +}; + +struct fpm_worker_pool_s *fpm_worker_pool_alloc(); +int fpm_worker_pool_init_main(); + +extern struct fpm_worker_pool_s *fpm_worker_all_pools; + +#endif + diff --git a/sapi/cgi/fpm/init.d/php-fpm.in b/sapi/cgi/fpm/init.d/php-fpm.in new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/init.d/php-fpm.in @@ -0,0 +1,139 @@ +#! /bin/sh + +php_fpm_BIN=@prefix@/bin/php-cgi +php_fpm_CONF=@php_fpm_conf_path@ +php_fpm_PID=@php_fpm_pid_path@ + + +php_opts="--fpm-config $php_fpm_CONF" + + +wait_for_pid () { + try=0 + + while test $try -lt 35 ; do + + case "$1" in + 'created') + if [ -f "$2" ] ; then + try='' + break + fi + ;; + + 'removed') + if [ ! -f "$2" ] ; then + try='' + break + fi + ;; + esac + + echo -n . + try=`expr $try + 1` + sleep 1 + + done + +} + +case "$1" in + start) + echo -n "Starting php_fpm " + + $php_fpm_BIN --fpm $php_opts + + if [ "$?" != 0 ] ; then + echo " failed" + exit 1 + fi + + wait_for_pid created $php_fpm_PID + + if [ -n "$try" ] ; then + echo " failed" + exit 1 + else + echo " done" + fi + ;; + + stop) + echo -n "Shutting down php_fpm " + + if [ ! -r $php_fpm_PID ] ; then + echo "warning, no pid file found - php-fpm is not running ?" + exit 1 + fi + + kill -TERM `cat $php_fpm_PID` + + wait_for_pid removed $php_fpm_PID + + if [ -n "$try" ] ; then + echo " failed" + exit 1 + else + echo " done" + fi + ;; + + quit) + echo -n "Gracefully shutting down php_fpm " + + if [ ! -r $php_fpm_PID ] ; then + echo "warning, no pid file found - php-fpm is not running ?" + exit 1 + fi + + kill -QUIT `cat $php_fpm_PID` + + wait_for_pid removed $php_fpm_PID + + if [ -n "$try" ] ; then + echo " failed" + exit 1 + else + echo " done" + fi + ;; + + restart) + $0 stop + $0 start + ;; + + reload) + + echo -n "Reload service php-fpm " + + if [ ! -r $php_fpm_PID ] ; then + echo "warning, no pid file found - php-fpm is not running ?" + exit 1 + fi + + kill -USR2 `cat $php_fpm_PID` + + echo " done" + ;; + + logrotate) + + echo -n "Re-opening php-fpm log file " + + if [ ! -r $php_fpm_PID ] ; then + echo "warning, no pid file found - php-fpm is not running ?" + exit 1 + fi + + kill -USR1 `cat $php_fpm_PID` + + echo " done" + ;; + + *) + echo "Usage: $0 {start|stop|quit|restart|reload|logrotate}" + exit 1 + ;; + +esac diff --git a/sapi/cgi/fpm/xml_config.c b/sapi/cgi/fpm/xml_config.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/xml_config.c @@ -0,0 +1,278 @@ + + /* $Id$ */ + /* (c) 2004-2007 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#ifdef HAVE_ALLOCA_H +#include +#endif +#include +#include +#include +#include + +#include +#include + +#include "xml_config.h" + +static struct xml_conf_section **xml_conf_sections = 0; +static int xml_conf_sections_allocated = 0; +static int xml_conf_sections_used = 0; + +char *xml_conf_set_slot_boolean(void **conf, char *name, void *vv, intptr_t offset) +{ + char *value = vv; + long value_y = !strcasecmp(value, "yes") || !strcmp(value, "1") || !strcasecmp(value, "on"); + long value_n = !strcasecmp(value, "no") || !strcmp(value, "0") || !strcasecmp(value, "off"); + + if (!value_y && !value_n) { + return "xml_conf_set_slot(): invalid boolean value"; + } + +#ifdef XML_CONF_DEBUG + fprintf(stderr, "setting boolean '%s' => %s\n", name, value_y ? "TRUE" : "FALSE"); +#endif + + * (int *) ((char *) *conf + offset) = value_y ? 1 : 0; + + return NULL; +} + +char *xml_conf_set_slot_string(void **conf, char *name, void *vv, intptr_t offset) +{ + char *value = vv; + char *v = strdup(value); + + if (!v) return "xml_conf_set_slot_string(): strdup() failed"; + +#ifdef XML_CONF_DEBUG + fprintf(stderr, "setting string '%s' => '%s'\n", name, v); +#endif + + * (char **) ((char *) *conf + offset) = v; + + return NULL; +} + +char *xml_conf_set_slot_integer(void **conf, char *name, void *vv, intptr_t offset) +{ + char *value = vv; + int v = atoi(value); + + * (int *) ((char *) *conf + offset) = v; + +#ifdef XML_CONF_DEBUG + fprintf(stderr, "setting integer '%s' => %d\n", name, v); +#endif + + return NULL; +} + +char *xml_conf_set_slot_time(void **conf, char *name, void *vv, intptr_t offset) +{ + char *value = vv; + int len = strlen(value); + char suffix; + int seconds; + + if (!len) return "xml_conf_set_slot_timeval(): invalid timeval value"; + + suffix = value[len-1]; + + value[len-1] = '\0'; + + switch (suffix) { + case 's' : + seconds = atoi(value); + break; + case 'm' : + seconds = 60 * atoi(value); + break; + case 'h' : + seconds = 60 * 60 * atoi(value); + break; + case 'd' : + seconds = 24 * 60 * 60 * atoi(value); + break; + default : + return "xml_conf_set_slot_timeval(): unknown suffix used in timeval value"; + } + + * (int *) ((char *) *conf + offset) = seconds; + +#ifdef XML_CONF_DEBUG + fprintf(stderr, "setting time '%s' => %d:%02d:%02d:%02d\n", name, expand_dhms(seconds)); +#endif + + return NULL; +} + +char *xml_conf_parse_section(void **conf, struct xml_conf_section *section, void *xml_node) +{ + xmlNode *element = xml_node; + char *ret = 0; + +#ifdef XML_CONF_DEBUG + fprintf(stderr, "processing a section %s\n", section->path); +#endif + + for ( ; element; element = element->next) { + if (element->type == XML_ELEMENT_NODE && !strcmp((const char *) element->name, "value") && element->children) { + xmlChar *name = xmlGetProp(element, (unsigned char *) "name"); + + if (name) { + int i; + +#ifdef XML_CONF_DEBUG + fprintf(stderr, "found a value: %s\n", name); +#endif + for (i = 0; section->parsers[i].parser; i++) { + if (!section->parsers[i].name || !strcmp(section->parsers[i].name, (char *) name)) { + break; + } + } + + if (section->parsers[i].parser) { + if (section->parsers[i].type == XML_CONF_SCALAR) { + if (element->children->type == XML_TEXT_NODE) { + ret = section->parsers[i].parser(conf, (char *) name, element->children->content, section->parsers[i].offset); + } + else { + ret = "XML_TEXT_NODE is expected, something different is given"; + } + } + else { + ret = section->parsers[i].parser(conf, (char *) name, element->children, section->parsers[i].offset); + } + + xmlFree(name); + if (ret) return ret; + else continue; + } + + fprintf(stderr, "Warning, unknown setting '%s' in section '%s'\n", (char *) name, section->path); + + xmlFree(name); + } + } + } + + return NULL; +} + +static char *xml_conf_parse_file(xmlNode *element) +{ + char *ret = 0; + + for ( ; element; element = element->next) { + + if (element->parent && element->type == XML_ELEMENT_NODE && !strcmp((const char *) element->name, "section")) { + xmlChar *name = xmlGetProp(element, (unsigned char *) "name"); + + if (name) { + char *parent_name = (char *) xmlGetNodePath(element->parent); + char *full_name; + int i; + struct xml_conf_section *section = NULL; + +#ifdef XML_CONF_DEBUG + fprintf(stderr, "got a section: %s/%s\n", parent_name, name); +#endif + full_name = alloca(strlen(parent_name) + strlen((char *) name) + 1 + 1); + + sprintf(full_name, "%s/%s", parent_name, (char *) name); + + xmlFree(parent_name); + xmlFree(name); + + for (i = 0; i < xml_conf_sections_used; i++) { + if (!strcmp(xml_conf_sections[i]->path, full_name)) { + section = xml_conf_sections[i]; + } + } + + if (section) { /* found a registered section */ + void *conf = section->conf(); + ret = xml_conf_parse_section(&conf, section, element->children); + if (ret) break; + } + + } + } + + if (element->children) { + ret = xml_conf_parse_file(element->children); + if (ret) break; + } + } + + return ret; +} + +char *xml_conf_load_file(char *file) +{ + char *ret = 0; + xmlDoc *doc; + + LIBXML_TEST_VERSION + + doc = xmlParseFile(file); + + if (doc) { + ret = xml_conf_parse_file(doc->children); + xmlFreeDoc(doc); + } + else { + ret = "failed to parse conf file"; + } + + xmlCleanupParser(); + return ret; +} + +int xml_conf_init() +{ + return 0; +} + +void xml_conf_clean() +{ + if (xml_conf_sections) { + free(xml_conf_sections); + } +} + +int xml_conf_section_register(struct xml_conf_section *section) +{ + if (xml_conf_sections_allocated == xml_conf_sections_used) { + int new_size = xml_conf_sections_used + 10; + void *new_ptr = realloc(xml_conf_sections, sizeof(struct xml_conf_section *) * new_size); + + if (new_ptr) { + xml_conf_sections = new_ptr; + xml_conf_sections_allocated = new_size; + } + else { + fprintf(stderr, "xml_conf_section_register(): out of memory\n"); + return -1; + } + } + + xml_conf_sections[xml_conf_sections_used++] = section; + + return 0; +} + +int xml_conf_sections_register(struct xml_conf_section *sections[]) +{ + for ( ; sections && *sections; sections++) { + if (0 > xml_conf_section_register(*sections)) { + return -1; + } + } + + return 0; +} + diff --git a/sapi/cgi/fpm/xml_config.h b/sapi/cgi/fpm/xml_config.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/xml_config.h @@ -0,0 +1,43 @@ + + /* $Id$ */ + /* (c) 2004-2007 Andrei Nigmatulin */ + +#ifndef XML_CONFIG_H +#define XML_CONFIG_H 1 + +#include + +struct xml_value_parser; + +struct xml_value_parser { + int type; + char *name; + char *(*parser)(void **, char *, void *, intptr_t offset); + intptr_t offset; +}; + +struct xml_conf_section { + void *(*conf)(); + char *path; + struct xml_value_parser *parsers; +}; + +char *xml_conf_set_slot_boolean(void **conf, char *name, void *value, intptr_t offset); +char *xml_conf_set_slot_string(void **conf, char *name, void *value, intptr_t offset); +char *xml_conf_set_slot_integer(void **conf, char *name, void *value, intptr_t offset); +char *xml_conf_set_slot_time(void **conf, char *name, void *value, intptr_t offset); + +int xml_conf_init(); +void xml_conf_clean(); +char *xml_conf_load_file(char *file); +char *xml_conf_parse_section(void **conf, struct xml_conf_section *section, void *ve); +int xml_conf_section_register(struct xml_conf_section *section); +int xml_conf_sections_register(struct xml_conf_section *sections[]); + +#define expand_hms(value) (value) / 3600, ((value) % 3600) / 60, (value) % 60 + +#define expand_dhms(value) (value) / 86400, ((value) % 86400) / 3600, ((value) % 3600) / 60, (value) % 60 + +enum { XML_CONF_SCALAR = 1, XML_CONF_SUBSECTION = 2 }; + +#endif diff --git a/sapi/cgi/fpm/zlog.c b/sapi/cgi/fpm/zlog.c new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/zlog.c @@ -0,0 +1,113 @@ + + /* $Id$ */ + /* (c) 2004-2007 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "zlog.h" + +#define MAX_LINE_LENGTH 1024 + +static int zlog_fd = -1; +static int zlog_level = ZLOG_NOTICE; + +static const char *level_names[] = { + [ZLOG_DEBUG] = "DEBUG", + [ZLOG_NOTICE] = "NOTICE", + [ZLOG_WARNING] = "WARNING", + [ZLOG_ERROR] = "ERROR", + [ZLOG_ALERT] = "ALERT", +}; + +size_t zlog_print_time(struct timeval *tv, char *timebuf, size_t timebuf_len) +{ + struct tm t; + size_t len; + + len = strftime(timebuf, timebuf_len, "%b %d %H:%M:%S", localtime_r((const time_t *) &tv->tv_sec, &t)); + len += snprintf(timebuf + len, timebuf_len - len, ".%06d", (int) tv->tv_usec); + + return len; +} + +int zlog_set_fd(int new_fd) +{ + int old_fd = zlog_fd; + zlog_fd = new_fd; + + return old_fd; +} + +int zlog_set_level(int new_value) +{ + int old_value = zlog_level; + + zlog_level = new_value; + + return old_value; +} + +void zlog(const char *function, int line, int flags, const char *fmt, ...) +{ + struct timeval tv; + char buf[MAX_LINE_LENGTH]; + const size_t buf_size = MAX_LINE_LENGTH; + va_list args; + size_t len; + int truncated = 0; + int saved_errno; + + if ((flags & ZLOG_LEVEL_MASK) < zlog_level) { + return; + } + + saved_errno = errno; + + gettimeofday(&tv, 0); + + len = zlog_print_time(&tv, buf, buf_size); + + len += snprintf(buf + len, buf_size - len, " [%s] %s(), line %d: ", level_names[flags & ZLOG_LEVEL_MASK], function, line); + + if (len > buf_size - 1) { + truncated = 1; + } + + if (!truncated) { + va_start(args, fmt); + + len += vsnprintf(buf + len, buf_size - len, fmt, args); + + va_end(args); + + if (len >= buf_size) { + truncated = 1; + } + } + + if (!truncated) { + if (flags & ZLOG_HAVE_ERRNO) { + len += snprintf(buf + len, buf_size - len, ": %s (%d)", strerror(saved_errno), saved_errno); + if (len >= buf_size) { + truncated = 1; + } + } + } + + if (truncated) { + memcpy(buf + buf_size - sizeof("..."), "...", sizeof("...") - 1); + len = buf_size - 1; + } + + buf[len++] = '\n'; + + write(zlog_fd > -1 ? zlog_fd : STDERR_FILENO, buf, len); +} diff --git a/sapi/cgi/fpm/zlog.h b/sapi/cgi/fpm/zlog.h new file mode 100644 --- /dev/null +++ b/sapi/cgi/fpm/zlog.h @@ -0,0 +1,34 @@ + + /* $Id$ */ + /* (c) 2004-2007 Andrei Nigmatulin */ + +#ifndef ZLOG_H +#define ZLOG_H 1 + +#define ZLOG_STUFF __func__, __LINE__ + +struct timeval; + +int zlog_set_fd(int new_fd); +int zlog_set_level(int new_value); + +size_t zlog_print_time(struct timeval *tv, char *timebuf, size_t timebuf_len); + +void zlog(const char *function, int line, int flags, const char *fmt, ...) + __attribute__ ((format(printf,4,5))); + +enum { + ZLOG_DEBUG = 1, + ZLOG_NOTICE = 2, + ZLOG_WARNING = 3, + ZLOG_ERROR = 4, + ZLOG_ALERT = 5, +}; + +#define ZLOG_LEVEL_MASK 7 + +#define ZLOG_HAVE_ERRNO 0x100 + +#define ZLOG_SYSERROR (ZLOG_ERROR | ZLOG_HAVE_ERRNO) + +#endif