From df06e2dbf48a3b0d96f2c62071c1b5fc907a98d0 Mon Sep 17 00:00:00 2001 From: Michael Wallner Date: Thu, 21 Oct 2010 11:57:55 +0000 Subject: [PATCH] push a load of changes before holidays --- bench_select_vs_event.php | 94 ++ config9.m4 | 320 ++++-- php_http.c | 73 +- php_http.h | 17 +- php_http_cookie.c | 112 +- php_http_curl.c | 2050 ++++++++++++++++++++++++++++++++++ php_http_curl.h | 18 + php_http_encoding.c | 2 +- php_http_exception.c | 9 + php_http_exception.h | 2 + php_http_fluently_callable.c | 13 + php_http_fluently_callable.h | 9 + php_http_header_parser.c | 5 +- php_http_header_parser.h | 2 + php_http_message.c | 82 +- php_http_message_body.c | 458 ++++---- php_http_message_body.h | 2 + php_http_message_parser.c | 119 +- php_http_message_parser.h | 7 +- php_http_misc.h | 53 +- php_http_neon.c | 893 +++++++++++++++ php_http_neon.h | 9 + php_http_object.c | 55 +- php_http_request.c | 1795 ++++++----------------------- php_http_request.h | 211 ++-- php_http_request_datashare.c | 371 +++--- php_http_request_datashare.h | 70 +- php_http_request_factory.c | 344 ++++++ php_http_request_factory.h | 32 + php_http_request_info.c | 66 +- php_http_request_method.c | 2 +- php_http_request_pool.c | 719 +++--------- php_http_request_pool.h | 94 +- php_http_strlist.c | 9 +- reflection2php.php | 71 ++ 35 files changed, 5173 insertions(+), 3015 deletions(-) create mode 100644 bench_select_vs_event.php create mode 100644 php_http_curl.c create mode 100644 php_http_curl.h create mode 100644 php_http_fluently_callable.c create mode 100644 php_http_fluently_callable.h create mode 100644 php_http_neon.c create mode 100644 php_http_neon.h create mode 100644 php_http_request_factory.c create mode 100644 php_http_request_factory.h create mode 100755 reflection2php.php diff --git a/bench_select_vs_event.php b/bench_select_vs_event.php new file mode 100644 index 0000000..457f2d3 --- /dev/null +++ b/bench_select_vs_event.php @@ -0,0 +1,94 @@ + "pool", "requestClass" => "request")); + +class pool extends HttpRequestPool { + private $url; + private $cnt; + + private $factory; + + static function fetch($factory, $url, $n, $c, $e, $p) { + $pool = $factory->createPool(); + $pool->factory = $factory; + $pool->url = $url; + $pool->cnt = $n; + + $pool->enablePipelining($p); + $pool->enableEvents($e); + + for ($i = 0; $i < $c; ++$i) { + $pool->push(); + } + try { + $pool->send(); + } catch (Exception $ex) { + echo $ex, "\n"; + } + } + + function push() { + if ($this->cnt > 0) { + $this->factory->createRequest()->init($this, $this->url)->id = $this->cnt--; + } + } +} + +class request extends HttpRequest implements SplObserver { + static $counter = 0; + + public $id; + private $pool; + + function init(pool $pool, $url) { + $this->setUrl($url); + $this->pool = $pool; + $this->attach($this); + $pool->attach($this); + return $this; + } + + function update(SplSubject $r) { + if ($r->getProgress()->finished) { + ++self::$counter; + $this->pool->detach($this); + $this->detach($this); + $this->pool->push(); + } + } +} + +function usage($e = null) { + global $argv; + if ($e) { + fprintf(STDERR, "ERROR: %s\n\n", $e); + } + fprintf(STDERR, "Usage: %s -u -n -c [-p (enable pipelining)] [-e (use libevent)]\n", $argv[0]); + fprintf(STDERR, "\nDefaults: -u http://localhost/ -n 1000 -c 10\n\n"); + exit(-1); +} + +isset($argv) or $argv = $_SERVER['argv']; +defined('STDERR') or define('STDERR', fopen('php://stderr', 'w')); + +$opts = getopt("u:c:n:e"); +isset($opts["u"]) or $opts["u"] = "http://localhost/"; +isset($opts["c"]) or $opts["c"] = 10; +isset($opts["n"]) or $opts["n"] = 1000; + +try { + ($c=$factory->createRequest($opts["u"])->send()->getResponseCode()) == 200 or usage("Received response code $c"); +} catch (Exception $ex) { + usage($ex->getMessage()); +} + +$argc > 1 or usage(); + +$time = microtime(true); +pool::fetch($factory, $opts["u"], $opts["n"], $opts["c"], isset($opts["e"]), isset($opts["p"])); +printf("\n> %10.6fs (%3.2fM)\n", microtime(true)-$time, memory_get_peak_usage(true)/1024/1024); + +request::$counter == $opts["n"] or printf("\nOnly %d finished\n", request::$counter); diff --git a/config9.m4 b/config9.m4 index 50303a3..c59c53f 100644 --- a/config9.m4 +++ b/config9.m4 @@ -1,6 +1,6 @@ dnl config.m4 for pecl/http dnl $Id: config9.m4 242664 2007-09-18 19:13:37Z mike $ -dnl vim: noet ts=1 sw=4 +dnl vim: noet ts=4 sw=4 PHP_ARG_WITH([http], [whether to enable extended HTTP support], [ --with-http Enable extended HTTP support]) @@ -8,11 +8,17 @@ PHP_ARG_WITH([http-zlib-dir], [], [ --with-http-zlib-dir[=DIR] HTTP: where to find zlib], $PHP_HTTP, $PHP_HTTP) PHP_ARG_WITH([http-libcurl-dir], [], [ --with-http-libcurl-dir[=DIR] HTTP: where to find libcurl], $PHP_HTTP, $PHP_HTTP) +PHP_ARG_WITH([http-libneon-dir], [], +[ --with-http-libneon-dir[=DIR] HTTP: where to find libneon], $PHP_HTTP, $PHP_HTTP) +PHP_ARG_WITH([http-libserf-dir], [], +[ --with-http-libserf-dir[=DIR] HTTP: where to find libserf], $PHP_HTTP, $PHP_HTTP) PHP_ARG_WITH([http-libevent-dir], [], [ --with-http-libevent-dir[=DIR] HTTP: where to find libevent], $PHP_HTTP_LIBCURL_DIR, "") if test "$PHP_HTTP" != "no"; then + HTTP_HAVE_A_REQUEST_LIB=false + ifdef([AC_PROG_EGREP], [ AC_PROG_EGREP ], [ @@ -128,141 +134,218 @@ dnl ---- fi dnl ---- -dnl CURL +dnl NEON dnl ---- - AC_MSG_CHECKING([for curl/curl.h]) - CURL_DIR= - for i in "$PHP_HTTP_LIBCURL_DIR" /usr/local /usr /opt; do - if test -f "$i/include/curl/curl.h"; then - CURL_DIR=$i + + AC_MSG_CHECKING([for neon/ne_session.h]) + NEON_DIR= + for i in "$PHP_HTTP_LIBNEON_DIR" /usr/local /usr /opt; do + if test -f "$i/include/neon/ne_session.h"; then + NEON_DIR=$i break fi done - if test "x$CURL_DIR" = "x"; then + + if test "x$NEON_DIR" = "x"; then AC_MSG_RESULT([not found]) - AC_MSG_ERROR([could not find curl/curl.h]) else - AC_MSG_RESULT([found in $CURL_DIR]) + AC_MSG_RESULT([found in $NEON_DIR]) + + AC_MSG_CHECKING([for neon-config]) + NEON_CONFIG= + for i in "$NEON_DIR/bin/neon-config" "$NEON_DIR/neon-config" `which neon-config`; do + if test -x "$i"; then + NEON_CONFIG=$i + break + fi + done + if test "x$NEON_CONFIG" = "x"; then + AC_MSG_RESULT([not found]) + AC_MSG_ERROR([could not find neon-config]) + else + AC_MSG_RESULT([found: $NEON_CONFIG]) + fi + + AC_MSG_CHECKING([for libneon version]) + PHP_HTTP_NEON_VERSION=`$NEON_CONFIG --version | $SED -re 's/^neon ([[^ :]]+).*/\1/g'` + if test "x$PHP_HTTP_NEON_VERSION" = "x"; then + AC_MSG_RESULT([unknown]) + PHP_HTTP_NEON_VERSION="unknown" + else + AC_MSG_RESULT([$PHP_HTTP_NEON_VERSION]) + fi + AC_DEFINE_UNQUOTED([PHP_HTTP_NEON_VERSION], ["$PHP_HTTP_NEON_VERSION"], [neon-config --version]) + PHP_ADD_INCLUDE($NEON_DIR/include) + PHP_ADD_LIBRARY_WITH_PATH(neon, $NEON_DIR/$PHP_LIBDIR, HTTP_SHARED_LIBADD) + AC_DEFINE([PHP_HTTP_HAVE_NEON], [1], [Have libneon support]) + HTTP_HAVE_A_REQUEST_LIB=true fi - AC_MSG_CHECKING([for curl-config]) - CURL_CONFIG= - for i in "$CURL_DIR/bin/curl-config" "$CURL_DIR/curl-config" `which curl-config`; do - if test -x "$i"; then - CURL_CONFIG=$i +dnl ---- +dnl SERF +dnl ---- + + AC_MSG_CHECKING([for serf-?/serf.h]) + SERF_DIR= + for i in "$PHP_HTTP_LIBSERF_DIR" /usr/local /usr /opt; do + if test -f "$i/include/serf-0/serf.h"; then + SERF_DIR=$i + SERF_VER=0 break + elif test -f "$i/include/serf-1/serf.h"; then + SERF_DIR=$i + SERF_VER=1 fi done - if test "x$CURL_CONFIG" = "x"; then + + if test "x$SERF_DIR" = "x"; then AC_MSG_RESULT([not found]) - AC_MSG_ERROR([could not find curl-config]) else - AC_MSG_RESULT([found: $CURL_CONFIG]) - fi - - dnl Debian stable has currently 7.18.2 - AC_MSG_CHECKING([for curl version >= 7.18.2]) - CURL_VERSION=`$CURL_CONFIG --version | $SED -e 's/[[^0-9\.]]//g'` - AC_MSG_RESULT([$CURL_VERSION]) - if test `echo $CURL_VERSION | $SED -e 's/[[^0-9]]/ /g' | $AWK '{print $1*10000 + $2*100 + $3}'` -lt 71802; then - AC_MSG_ERROR([libcurl version greater or equal to 7.18.2 required]) + AC_MSG_RESULT([found in $SERF_DIR]) + + PHP_ADD_INCLUDE($SERF_DIR/include/serf-$SERV_VER) + PHP_ADD_LIBRARY_WITH_PATH(serf-$SERF_VER, $SERF_DIR/$PHP_LIBDIR, HTTP_SHARED_LIBADD) + AC_DEFINE([PHP_HTTP_HAVE_SERF], [1], [HAve libserf support]) + HTTP_HAVE_A_REQUEST_LIB=true fi - dnl - dnl compile tests - dnl - - save_INCLUDES="$INCLUDES" - INCLUDES= - save_LIBS="$LIBS" - LIBS= - save_CFLAGS="$CFLAGS" - CFLAGS=`$CURL_CONFIG --cflags` - save_LDFLAGS="$LDFLAGS" - LDFLAGS=`$CURL_CONFIG --libs` - LDFLAGS="$LDFLAGS $ld_runpath_switch$CURL_DIR/$PHP_LIBDIR" - - AC_MSG_CHECKING([for SSL support in libcurl]) - CURL_SSL=`$CURL_CONFIG --feature | $EGREP SSL` - if test "$CURL_SSL" = "SSL"; then - AC_MSG_RESULT([yes]) - AC_DEFINE([PHP_HTTP_HAVE_SSL], [1], [ ]) +dnl ---- +dnl CURL +dnl ---- + AC_MSG_CHECKING([for curl/curl.h]) + CURL_DIR= + for i in "$PHP_HTTP_LIBCURL_DIR" /usr/local /usr /opt; do + if test -f "$i/include/curl/curl.h"; then + CURL_DIR=$i + break + fi + done + if test "x$CURL_DIR" = "x"; then + AC_MSG_RESULT([not found]) + else + AC_MSG_RESULT([found in $CURL_DIR]) - AC_MSG_CHECKING([for openssl support in libcurl]) - AC_TRY_RUN([ - #include - int main(int argc, char *argv[]) { - curl_version_info_data *data = curl_version_info(CURLVERSION_NOW); - if (data && data->ssl_version && *data->ssl_version) { - const char *ptr = data->ssl_version; - while(*ptr == ' ') ++ptr; - return strncasecmp(ptr, "OpenSSL", sizeof("OpenSSL")-1); - } - return 1; - } - ], [ + AC_MSG_CHECKING([for curl-config]) + CURL_CONFIG= + for i in "$CURL_DIR/bin/curl-config" "$CURL_DIR/curl-config" `which curl-config`; do + if test -x "$i"; then + CURL_CONFIG=$i + break + fi + done + if test "x$CURL_CONFIG" = "x"; then + AC_MSG_RESULT([not found]) + AC_MSG_ERROR([could not find curl-config]) + else + AC_MSG_RESULT([found: $CURL_CONFIG]) + fi + + dnl Debian stable has currently 7.18.2 + AC_MSG_CHECKING([for curl version >= 7.18.2]) + CURL_VERSION=`$CURL_CONFIG --version | $SED -e 's/[[^0-9\.]]//g'` + AC_MSG_RESULT([$CURL_VERSION]) + if test `echo $CURL_VERSION | $SED -e 's/[[^0-9]]/ /g' | $AWK '{print $1*10000 + $2*100 + $3}'` -lt 71802; then + AC_MSG_ERROR([libcurl version greater or equal to 7.18.2 required]) + fi + + dnl + dnl compile tests + dnl + + save_INCLUDES="$INCLUDES" + INCLUDES= + save_LIBS="$LIBS" + LIBS= + save_CFLAGS="$CFLAGS" + CFLAGS=`$CURL_CONFIG --cflags` + save_LDFLAGS="$LDFLAGS" + LDFLAGS=`$CURL_CONFIG --libs` + LDFLAGS="$LDFLAGS $ld_runpath_switch$CURL_DIR/$PHP_LIBDIR" + + AC_MSG_CHECKING([for SSL support in libcurl]) + CURL_SSL=`$CURL_CONFIG --feature | $EGREP SSL` + if test "$CURL_SSL" = "SSL"; then AC_MSG_RESULT([yes]) - AC_CHECK_HEADER([openssl/crypto.h], [ - AC_DEFINE([PHP_HTTP_HAVE_OPENSSL], [1], [ ]) + AC_DEFINE([PHP_HTTP_HAVE_SSL], [1], [ ]) + + AC_MSG_CHECKING([for openssl support in libcurl]) + AC_TRY_RUN([ + #include + int main(int argc, char *argv[]) { + curl_version_info_data *data = curl_version_info(CURLVERSION_NOW); + if (data && data->ssl_version && *data->ssl_version) { + const char *ptr = data->ssl_version; + while(*ptr == ' ') ++ptr; + return strncasecmp(ptr, "OpenSSL", sizeof("OpenSSL")-1); + } + return 1; + } + ], [ + AC_MSG_RESULT([yes]) + AC_CHECK_HEADER([openssl/crypto.h], [ + AC_DEFINE([PHP_HTTP_HAVE_OPENSSL], [1], [ ]) + ]) + ], [ + AC_MSG_RESULT([no]) + ], [ + AC_MSG_RESULT([no]) ]) - ], [ - AC_MSG_RESULT([no]) - ], [ - AC_MSG_RESULT([no]) - ]) - - AC_MSG_CHECKING([for gnutls support in libcurl]) - AC_TRY_RUN([ - #include - int main(int argc, char *argv[]) { - curl_version_info_data *data = curl_version_info(CURLVERSION_NOW); - if (data && data->ssl_version && *data->ssl_version) { - const char *ptr = data->ssl_version; - while(*ptr == ' ') ++ptr; - return strncasecmp(ptr, "GnuTLS", sizeof("GnuTLS")-1); + + AC_MSG_CHECKING([for gnutls support in libcurl]) + AC_TRY_RUN([ + #include + int main(int argc, char *argv[]) { + curl_version_info_data *data = curl_version_info(CURLVERSION_NOW); + if (data && data->ssl_version && *data->ssl_version) { + const char *ptr = data->ssl_version; + while(*ptr == ' ') ++ptr; + return strncasecmp(ptr, "GnuTLS", sizeof("GnuTLS")-1); + } + return 1; } - return 1; - } - ], [ - AC_MSG_RESULT([yes]) - AC_CHECK_HEADER([gcrypt.h], [ - AC_DEFINE([PHP_HTTP_HAVE_GNUTLS], [1], [ ]) + ], [ + AC_MSG_RESULT([yes]) + AC_CHECK_HEADER([gcrypt.h], [ + AC_DEFINE([PHP_HTTP_HAVE_GNUTLS], [1], [ ]) + ]) + ], [ + AC_MSG_RESULT([no]) + ], [ + AC_MSG_RESULT([no]) ]) - ], [ - AC_MSG_RESULT([no]) - ], [ + else AC_MSG_RESULT([no]) - ]) - else - AC_MSG_RESULT([no]) - fi - - INCLUDES="$save_INCLUDES" - LIBS="$save_LIBS" - CFLAGS="$save_CFLAGS" - LDFLAGS="$save_LDFLAGS" - - dnl end compile tests - - AC_MSG_CHECKING([for bundled SSL CA info]) - CURL_CAINFO= - for i in `$CURL_CONFIG --ca` "/etc/ssl/certs/ca-certificates.crt"; do - if test -f "$i"; then - CURL_CAINFO="$i" - break fi - done - if test "x$CURL_CAINFO" = "x"; then - AC_MSG_RESULT([not found]) - else - AC_MSG_RESULT([$CURL_CAINFO]) - AC_DEFINE_UNQUOTED([PHP_HTTP_CURL_CAINFO], ["$CURL_CAINFO"], [path to bundled SSL CA info]) + + INCLUDES="$save_INCLUDES" + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" + LDFLAGS="$save_LDFLAGS" + + dnl end compile tests + + AC_MSG_CHECKING([for bundled SSL CA info]) + CURL_CAINFO= + for i in `$CURL_CONFIG --ca` "/etc/ssl/certs/ca-certificates.crt"; do + if test -f "$i"; then + CURL_CAINFO="$i" + break + fi + done + if test "x$CURL_CAINFO" = "x"; then + AC_MSG_RESULT([not found]) + else + AC_MSG_RESULT([$CURL_CAINFO]) + AC_DEFINE_UNQUOTED([PHP_HTTP_CURL_CAINFO], ["$CURL_CAINFO"], [path to bundled SSL CA info]) + fi + + PHP_ADD_INCLUDE($CURL_DIR/include) + PHP_ADD_LIBRARY_WITH_PATH(curl, $CURL_DIR/$PHP_LIBDIR, HTTP_SHARED_LIBADD) + PHP_EVAL_LIBLINE(`$CURL_CONFIG --libs`, HTTP_SHARED_LIBADD) + AC_DEFINE([PHP_HTTP_HAVE_CURL], [1], [Have libcurl support]) + HTTP_HAVE_A_REQUEST_LIB=true fi - - PHP_ADD_INCLUDE($CURL_DIR/include) - PHP_ADD_LIBRARY_WITH_PATH(curl, $CURL_DIR/$PHP_LIBDIR, HTTP_SHARED_LIBADD) - PHP_EVAL_LIBLINE(`$CURL_CONFIG --libs`, HTTP_SHARED_LIBADD) - + dnl ---- dnl EVENT dnl ---- @@ -350,6 +433,7 @@ dnl ---- php_http_etag.c \ php_http_exception.c \ php_http_filter.c \ + php_http_fluently_callable.c \ php_http_headers.c \ php_http_header_parser.c \ php_http_info.c \ @@ -364,10 +448,12 @@ dnl ---- php_http_property_proxy.c \ php_http_querystring.c \ php_http_request.c \ + php_http_request_factory.c \ + php_http_curl.c \ + php_http_neon.c \ + php_http_request_pool.c \ php_http_request_datashare.c \ - php_http_request_info.c \ php_http_request_method.c \ - php_http_request_pool.c \ php_http_strlist.c \ php_http_url.c \ php_http_version.c \ @@ -389,6 +475,7 @@ dnl ---- php_http_etag.h \ php_http_exception.h \ php_http_filter.h \ + php_http_fluently_callable.h \ php_http_headers.h \ php_http_header_parser.h \ php_http_info.h \ @@ -404,6 +491,9 @@ dnl ---- php_http_querystring.h \ php_http_request_datashare.h \ php_http_request.h \ + php_http_request_factory.h \ + php_http_curl.h \ + php_http_neon.h \ php_http_request_method.h \ php_http_request_pool.h \ php_http_strlist.h \ diff --git a/php_http.c b/php_http.c index 47fba64..5ce8aa4 100644 --- a/php_http.c +++ b/php_http.c @@ -15,9 +15,14 @@ #include "php_http.h" #include -#include -#ifdef PHP_HTTP_HAVE_EVENT -# include +#ifdef PHP_HTTP_HAVE_CURL +# include +# ifdef PHP_HTTP_HAVE_EVENT +# include +# endif +#endif +#ifdef PHP_HTTP_HAVE_NEON +# include "neon/ne_utils.h" #endif #include
@@ -71,6 +76,27 @@ zend_module_entry http_module_entry = { int http_module_number; +#if PHP_DEBUG +void _dpf(int type, const char *data, size_t length) +{ + static const char _sym[] = "><><><"; + if (type) { + int nwp = 0; + for (fprintf(stderr, "%c ", _sym[type-1]); length--; data++) { + int ip = PHP_HTTP_IS_CTYPE(print, *data); + if (!ip && *data != '\r' && *data != '\n') nwp = 1; + fprintf(stderr, ip?"%c":"\\x%02x", (int) (*data & 0xff)); + if (!nwp && *data == '\n' && length) { + fprintf(stderr, "\n%c ", _sym[type-1]); + } + } + fprintf(stderr, "\n"); + } else { + fprintf(stderr, "# %.*s\n", (long) length, data); + } +} +#endif + static void php_http_globals_init_once(zend_php_http_globals *G) { memset(G, 0, sizeof(*G)); @@ -116,17 +142,21 @@ PHP_MINIT_FUNCTION(http) REGISTER_INI_ENTRIES(); if (0 + || SUCCESS != PHP_MINIT_CALL(http_fluently_callable) || SUCCESS != PHP_MINIT_CALL(http_object) || SUCCESS != PHP_MINIT_CALL(http_exception) + || SUCCESS != PHP_MINIT_CALL(http_persistent_handle) || SUCCESS != PHP_MINIT_CALL(http_cookie) || SUCCESS != PHP_MINIT_CALL(http_encoding) || SUCCESS != PHP_MINIT_CALL(http_filter) || SUCCESS != PHP_MINIT_CALL(http_message) || SUCCESS != PHP_MINIT_CALL(http_message_body) - || SUCCESS != PHP_MINIT_CALL(http_persistent_handle) || SUCCESS != PHP_MINIT_CALL(http_property_proxy) || SUCCESS != PHP_MINIT_CALL(http_querystring) + || SUCCESS != PHP_MINIT_CALL(http_request_factory) || SUCCESS != PHP_MINIT_CALL(http_request) + || SUCCESS != PHP_MINIT_CALL(http_curl) + || SUCCESS != PHP_MINIT_CALL(http_neon) || SUCCESS != PHP_MINIT_CALL(http_request_datashare) || SUCCESS != PHP_MINIT_CALL(http_request_method) || SUCCESS != PHP_MINIT_CALL(http_request_pool) @@ -147,9 +177,11 @@ PHP_MSHUTDOWN_FUNCTION(http) if (0 || SUCCESS != PHP_MSHUTDOWN_CALL(http_message) - || SUCCESS != PHP_MSHUTDOWN_CALL(http_request) + || SUCCESS != PHP_MSHUTDOWN_CALL(http_curl) + || SUCCESS != PHP_MSHUTDOWN_CALL(http_neon) || SUCCESS != PHP_MSHUTDOWN_CALL(http_request_datashare) || SUCCESS != PHP_MSHUTDOWN_CALL(http_persistent_handle) + || SUCCESS != PHP_MSHUTDOWN_CALL(http_request_factory) ) { return FAILURE; } @@ -162,7 +194,7 @@ PHP_RINIT_FUNCTION(http) if (0 || SUCCESS != PHP_RINIT_CALL(http_env) || SUCCESS != PHP_RINIT_CALL(http_request_datashare) - || SUCCESS != PHP_RINIT_CALL(http_request_pool) + || SUCCESS != PHP_RINIT_CALL(http_curl) ) { return FAILURE; } @@ -185,25 +217,36 @@ PHP_RSHUTDOWN_FUNCTION(http) PHP_MINFO_FUNCTION(http) { php_info_print_table_start(); - { - php_info_print_table_header(2, "HTTP Support", "enabled"); - php_info_print_table_row(2, "Extension Version", PHP_HTTP_EXT_VERSION); - } + php_info_print_table_header(2, "HTTP Support", "enabled"); + php_info_print_table_row(2, "Extension Version", PHP_HTTP_EXT_VERSION); php_info_print_table_end(); php_info_print_table_start(); php_info_print_table_header(3, "Used Library", "Compiled", "Linked"); + php_info_print_table_row(3, "libz", ZLIB_VERSION, zlibVersion()); +#ifdef PHP_HTTP_HAVE_CURL { curl_version_info_data *cv = curl_version_info(CURLVERSION_NOW); - php_info_print_table_row(3, "libz", ZLIB_VERSION, zlibVersion()); php_info_print_table_row(3, "libcurl", LIBCURL_VERSION, cv->version); -#ifdef PHP_HTTP_HAVE_EVENT - php_info_print_table_row(3, "libevent", PHP_HTTP_EVENT_VERSION, event_get_version()); + } #else - php_info_print_table_row(3, "libevent", "disabled", "disabled"); + php_info_print_table_row(3, "libcurl", "disabled", "disabled"); #endif - php_info_print_table_row(3, "libz", "disabled", "disabled"); +#ifdef PHP_HTTP_HAVE_NEON + { + char ne_v[16] = {0}; + sscanf(ne_version_string(), "neon %15[^ :]", &ne_v[0]); + php_info_print_table_row(3, "libneon", PHP_HTTP_NEON_VERSION, ne_v); } +#else + php_info_print_table_row(3, "libneon", "disabled", "disabled"); +#endif + +#ifdef PHP_HTTP_HAVE_EVENT + php_info_print_table_row(3, "libevent", PHP_HTTP_EVENT_VERSION, event_get_version()); +#else + php_info_print_table_row(3, "libevent", "disabled", "disabled"); +#endif php_info_print_table_end(); php_info_print_table_start(); diff --git a/php_http.h b/php_http.h index 67e5262..d9906ef 100644 --- a/php_http.h +++ b/php_http.h @@ -64,8 +64,6 @@ typedef int STATUS; # endif #endif -#define PHP_HTTP_CURL_VERSION(x, y, z) (LIBCURL_VERSION_NUM >= (((x)<<16) + ((y)<<8) + (z))) - #include #define PHP_HTTP_IS_CTYPE(type, c) is##type((int) (unsigned char) (c)) #define PHP_HTTP_TO_CTYPE(type, c) to##type((int) (unsigned char) (c)) @@ -75,6 +73,15 @@ extern zend_module_entry http_module_entry; extern int http_module_number; +#if PHP_DEBUG +# define _DPF_STR 0 +# define _DPF_IN 1 +# define _DPF_OUT 2 +extern void _dpf(int type, const char *data, size_t length); +#else +# define _dpf(t,s,l); +#endif + #include "php_http_misc.h" #include "php_http_cookie.h" @@ -82,6 +89,7 @@ extern int http_module_number; #include "php_http_env.h" #include "php_http_etag.h" #include "php_http_exception.h" +#include "php_http_fluently_callable.h" #include "php_http_filter.h" #include "php_http_headers.h" #include "php_http_info.h" @@ -96,7 +104,10 @@ extern int http_module_number; #include "php_http_property_proxy.h" #include "php_http_querystring.h" #include "php_http_request_datashare.h" +#include "php_http_request_factory.h" #include "php_http_request.h" +#include "php_http_curl.h" +#include "php_http_neon.h" #include "php_http_request_method.h" #include "php_http_request_pool.h" #include "php_http_url.h" @@ -114,6 +125,8 @@ ZEND_EXTERN_MODULE_GLOBALS(php_http); #ifdef ZTS # include "TSRM/TSRM.h" # define PHP_HTTP_G ((zend_http_globals *) (*((void ***) tsrm_ls))[TSRM_UNSHUFFLE_RSRC_ID(php_http_globals_id)]) +# undef TSRMLS_FETCH_FROM_CTX +# define TSRMLS_FETCH_FROM_CTX(ctx) ((ctx)?(ctx):ts_resource_ex(0, NULL)) #else # define PHP_HTTP_G (&php_http_globals) #endif diff --git a/php_http_cookie.c b/php_http_cookie.c index 42f7d13..df7a76a 100644 --- a/php_http_cookie.c +++ b/php_http_cookie.c @@ -341,6 +341,7 @@ PHP_HTTP_API void php_http_cookie_list_to_string(php_http_cookie_list_t *list, c if (key.type == HASH_KEY_IS_STRING && key.len) { zval *tmp = php_http_zsep(IS_STRING, *val); append_encoded(&buf, key.str, key.len-1, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp)); + zval_ptr_dtor(&tmp); } } @@ -557,6 +558,9 @@ PHP_METHOD(HttpCookie, getCookies) if (SUCCESS == zend_parse_parameters_none()) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } array_init(return_value); array_copy(&obj->list->cookies, Z_ARRVAL_P(return_value)); return; @@ -571,13 +575,15 @@ PHP_METHOD(HttpCookie, setCookies) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|H", &cookies)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } zend_hash_clean(&obj->list->cookies); if (cookies) { array_copy(cookies, &obj->list->cookies); } - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, addCookies) @@ -587,10 +593,12 @@ PHP_METHOD(HttpCookie, addCookies) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &cookies)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } array_join(cookies, &obj->list->cookies, 1, ARRAY_JOIN_STRONLY); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } @@ -599,6 +607,9 @@ PHP_METHOD(HttpCookie, getExtras) if (SUCCESS == zend_parse_parameters_none()) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } array_init(return_value); array_copy(&obj->list->extras, Z_ARRVAL_P(return_value)); return; @@ -613,13 +624,15 @@ PHP_METHOD(HttpCookie, setExtras) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|H", &extras)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } zend_hash_clean(&obj->list->extras); if (extras) { array_copy(extras, &obj->list->extras); } - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, addExtras) @@ -629,10 +642,12 @@ PHP_METHOD(HttpCookie, addExtras) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "H", &extras)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } array_join(extras, &obj->list->extras, 1, ARRAY_JOIN_STRONLY); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, getCookie) @@ -644,6 +659,9 @@ PHP_METHOD(HttpCookie, getCookie) php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); zval **zvalue; + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } if (SUCCESS == zend_hash_find(&obj->list->cookies, name_str, name_len + 1, (void *) &zvalue)) { RETURN_ZVAL(*zvalue, 1, 0); } @@ -659,17 +677,20 @@ PHP_METHOD(HttpCookie, setCookie) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &name_str, &name_len, &value_str, &value_len)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } if (!value_str) { - RETURN_SUCCESS(zend_hash_del(&obj->list->cookies, name_str, name_len + 1)); + zend_hash_del(&obj->list->cookies, name_str, name_len + 1); } else { zval *zvalue; MAKE_STD_ZVAL(zvalue); ZVAL_STRINGL(zvalue, value_str, value_len, 1); - RETURN_SUCCESS(zend_hash_update(&obj->list->cookies, name_str, name_len + 1, &zvalue, sizeof(zval *), NULL)); + zend_hash_update(&obj->list->cookies, name_str, name_len + 1, &zvalue, sizeof(zval *), NULL); } } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, addCookie) @@ -681,11 +702,14 @@ PHP_METHOD(HttpCookie, addCookie) php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); zval *zvalue; + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } MAKE_STD_ZVAL(zvalue); ZVAL_STRINGL(zvalue, value_str, value_len, 1); - RETURN_SUCCESS(zend_hash_add(&obj->list->cookies, name_str, name_len + 1, &zvalue, sizeof(zval *), NULL)); + zend_hash_add(&obj->list->cookies, name_str, name_len + 1, &zvalue, sizeof(zval *), NULL); } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, getExtra) @@ -697,6 +721,9 @@ PHP_METHOD(HttpCookie, getExtra) php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); zval **zvalue; + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } if (SUCCESS == zend_hash_find(&obj->list->extras, name_str, name_len + 1, (void *) &zvalue)) { RETURN_ZVAL(*zvalue, 1, 0); } @@ -712,17 +739,20 @@ PHP_METHOD(HttpCookie, setExtra) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s!", &name_str, &name_len, &value_str, &value_len)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } if (!value_str) { - RETURN_SUCCESS(zend_hash_del(&obj->list->extras, name_str, name_len + 1)); + zend_hash_del(&obj->list->extras, name_str, name_len + 1); } else { zval *zvalue; MAKE_STD_ZVAL(zvalue); ZVAL_STRINGL(zvalue, value_str, value_len, 1); - RETURN_SUCCESS(zend_hash_update(&obj->list->extras, name_str, name_len + 1, &zvalue, sizeof(zval *), NULL)); + zend_hash_update(&obj->list->extras, name_str, name_len + 1, &zvalue, sizeof(zval *), NULL); } } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, addExtra) @@ -734,11 +764,14 @@ PHP_METHOD(HttpCookie, addExtra) php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); zval *zvalue; + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } MAKE_STD_ZVAL(zvalue); ZVAL_STRINGL(zvalue, value_str, value_len, 1); - RETURN_SUCCESS(zend_hash_add(&obj->list->extras, name_str, name_len + 1, &zvalue, sizeof(zval *), NULL)); + zend_hash_add(&obj->list->extras, name_str, name_len + 1, &zvalue, sizeof(zval *), NULL); } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, getDomain) @@ -746,6 +779,9 @@ PHP_METHOD(HttpCookie, getDomain) if (SUCCESS == zend_parse_parameters_none()) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } if (obj->list->domain) { RETURN_STRING(obj->list->domain, 1); } @@ -762,10 +798,12 @@ PHP_METHOD(HttpCookie, setDomain) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!", &domain_str, &domain_len)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } STR_SET(obj->list->domain, domain_str ? estrndup(domain_str, domain_len) : NULL); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, getPath) @@ -773,6 +811,9 @@ PHP_METHOD(HttpCookie, getPath) if (SUCCESS == zend_parse_parameters_none()) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } if (obj->list->path) { RETURN_STRING(obj->list->path, 1); } @@ -789,10 +830,12 @@ PHP_METHOD(HttpCookie, setPath) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!", &path_str, &path_len)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } STR_SET(obj->list->path, path_str ? estrndup(path_str, path_len) : NULL); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, getExpires) @@ -800,6 +843,9 @@ PHP_METHOD(HttpCookie, getExpires) if (SUCCESS == zend_parse_parameters_none()) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } RETURN_LONG(obj->list->expires); } RETURN_FALSE; @@ -812,10 +858,12 @@ PHP_METHOD(HttpCookie, setExpires) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &ts)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } obj->list->expires = ts; - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, getFlags) @@ -823,6 +871,9 @@ PHP_METHOD(HttpCookie, getFlags) if (SUCCESS == zend_parse_parameters_none()) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } RETURN_LONG(obj->list->flags); } RETURN_FALSE; @@ -835,10 +886,12 @@ PHP_METHOD(HttpCookie, setFlags) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &flags)) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } obj->list->flags = flags; - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpCookie, toString) @@ -848,6 +901,9 @@ PHP_METHOD(HttpCookie, toString) char *str; size_t len; + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } php_http_cookie_list_to_string(obj->list, &str, &len TSRMLS_CC); RETURN_STRINGL(str, len, 0); } @@ -859,6 +915,9 @@ PHP_METHOD(HttpCookie, toArray) if (SUCCESS == zend_parse_parameters_none()) { php_http_cookie_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + if (!obj->list) { + obj->list = php_http_cookie_list_init(NULL TSRMLS_CC); + } array_init(return_value); php_http_cookie_list_to_struct(obj->list, return_value TSRMLS_CC); } @@ -867,6 +926,7 @@ PHP_METHOD(HttpCookie, toArray) PHP_MINIT_FUNCTION(http_cookie) { PHP_HTTP_REGISTER_CLASS(http, Cookie, http_cookie, php_http_object_class_entry, 0); + zend_class_implements(php_http_cookie_class_entry TSRMLS_CC, 1, php_http_fluently_callable_class_entry); php_http_cookie_class_entry->create_object = php_http_cookie_object_new; memcpy(&php_http_cookie_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); php_http_cookie_object_handlers.clone_obj = php_http_cookie_object_clone; diff --git a/php_http_curl.c b/php_http_curl.c new file mode 100644 index 0000000..307d488 --- /dev/null +++ b/php_http_curl.c @@ -0,0 +1,2050 @@ + +#include "php_http.h" +#include "php_http_request.h" +#include "php_http_request_pool.h" + +#include +#define PHP_HTTP_CURL_VERSION(x, y, z) (LIBCURL_VERSION_NUM >= (((x)<<16) + ((y)<<8) + (z))) + +#ifdef PHP_HTTP_HAVE_EVENT +# include +#endif + +#include +#include + + +typedef struct php_http_curl_request { + CURL *handle; + + struct { + HashTable cache; + + struct curl_slist *headers; + php_http_buffer_t cookies; + + long redirects; + + struct { + uint count; + double delay; + } retry; + + } options; + + php_http_request_progress_t progress; + +} php_http_curl_request_t; + +typedef struct php_http_curl_request_storage { + char *url; + char *cookiestore; + char errorbuffer[0x100]; +} php_http_curl_request_storage_t; + +typedef struct php_http_curl_request_pool { + CURLM *handle; + + int unfinished; /* int because of curl_multi_perform() */ + +#ifdef PHP_HTTP_HAVE_EVENT + struct event *timeout; + unsigned useevents:1; + unsigned runsocket:1; +#endif +} php_http_curl_request_pool_t; + +#ifdef ZTS +typedef struct php_http_curl_request_datashare_lock { + CURL *ch; + MUTEX_T mx; +} php_http_curl_request_datashare_lock_t; +#endif + +typedef struct php_http_curl_request_datashare { + CURLSH *handle; + +#ifdef ZTS + php_http_curl_request_datashare_lock_t *locks; +#endif +} php_http_curl_request_datashare_t; + +#define PHP_HTTP_CURL_OPT_STRING(OPTION, ldiff, obdc) \ + { \ + char *K = #OPTION; \ + PHP_HTTP_CURL_OPT_STRING_EX(K+lenof("CURLOPT_KEY")+ldiff, OPTION, obdc); \ + } +#define PHP_HTTP_CURL_OPT_STRING_EX(keyname, optname, obdc) \ + if (!strcasecmp(key.str, keyname)) { \ + zval *copy = cache_option(&curl->options.cache, keyname, strlen(keyname)+1, 0, php_http_zsep(IS_STRING, *param)); \ + if (obdc) { \ + if (SUCCESS != php_check_open_basedir(Z_STRVAL_P(copy) TSRMLS_CC)) { \ + return FAILURE; \ + } \ + } \ + curl_easy_setopt(ch, optname, Z_STRVAL_P(copy)); \ + zval_ptr_dtor(©); \ + continue; \ + } +#define PHP_HTTP_CURL_OPT_LONG(OPTION, ldiff) \ + { \ + char *K = #OPTION; \ + PHP_HTTP_CURL_OPT_LONG_EX(K+lenof("CURLOPT_KEY")+ldiff, OPTION); \ + } +#define PHP_HTTP_CURL_OPT_LONG_EX(keyname, optname) \ + if (!strcasecmp(key.str, keyname)) { \ + zval *copy = php_http_zsep(IS_LONG, *param); \ + curl_easy_setopt(ch, optname, Z_LVAL_P(copy)); \ + zval_ptr_dtor(©); \ + continue; \ + } + +static inline php_http_curl_request_storage_t *get_storage(CURL *ch) { + php_http_curl_request_storage_t *st = NULL; + + curl_easy_getinfo(ch, CURLINFO_PRIVATE, &st); + + if (!st) { + st = pecalloc(1, sizeof(*st), 1); + curl_easy_setopt(ch, CURLOPT_PRIVATE, st); + curl_easy_setopt(ch, CURLOPT_ERRORBUFFER, st->errorbuffer); + } + + return st; +} + +static size_t php_http_curl_read_callback(void *data, size_t len, size_t n, void *ctx) +{ + php_http_message_body_t *body = ctx; + + if (body) { + TSRMLS_FETCH_FROM_CTX(body->ts); + return php_stream_read(php_http_message_body_stream(body), data, len * n); + } + return 0; +} + +static int php_http_curl_progress_callback(void *ctx, double dltotal, double dlnow, double ultotal, double ulnow) +{ + php_http_request_t *h = ctx; + php_http_curl_request_t *curl = h->ctx; + TSRMLS_FETCH_FROM_CTX(h->ts); + + curl->progress.state.dl.total = dltotal; + curl->progress.state.dl.now = dlnow; + curl->progress.state.ul.total = ultotal; + curl->progress.state.ul.now = ulnow; + + php_http_request_progress_notify(&curl->progress TSRMLS_CC); + + return 0; +} + +static curlioerr php_http_curl_ioctl_callback(CURL *ch, curliocmd cmd, void *ctx) +{ + php_http_message_body_t *body = ctx; + + if (cmd != CURLIOCMD_RESTARTREAD) { + return CURLIOE_UNKNOWNCMD; + } + + if (body) { + TSRMLS_FETCH_FROM_CTX(body->ts); + + if (SUCCESS == php_stream_rewind(php_http_message_body_stream(body))) { + return CURLIOE_OK; + } + } + + return CURLIOE_FAILRESTART; +} + +static int php_http_curl_raw_callback(CURL *ch, curl_infotype type, char *data, size_t length, void *ctx) +{ + php_http_request_t *h = ctx; + php_http_curl_request_t *curl = h->ctx; + unsigned flags = 0; + + /* process data */ + switch (type) { + case CURLINFO_HEADER_IN: + case CURLINFO_DATA_IN: + case CURLINFO_HEADER_OUT: + case CURLINFO_DATA_OUT: + php_http_buffer_append(h->buffer, data, length); + + if (curl->options.redirects) { + flags |= PHP_HTTP_MESSAGE_PARSER_EMPTY_REDIRECTS; + } + + if (PHP_HTTP_MESSAGE_PARSER_STATE_FAILURE == php_http_message_parser_parse(h->parser, h->buffer, flags, &h->message)) { + return -1; + } + break; + default: + break; + } + +#if 0 + /* debug */ + _dpf(type, data, length); +#endif + + return 0; +} + +static int php_http_curl_dummy_callback(char *data, size_t n, size_t l, void *s) +{ + return n*l; +} + +static STATUS php_http_curl_request_prepare(php_http_request_t *h, php_http_request_method_t meth, const char *url, php_http_message_body_t *body) +{ + php_http_curl_request_t *curl = h->ctx; + php_http_curl_request_storage_t *storage = get_storage(curl->handle); + TSRMLS_FETCH_FROM_CTX(h->ts); + + storage->errorbuffer[0] = '\0'; + if (storage->url) { + pefree(storage->url, 1); + } + storage->url = pestrdup(url, 1); + curl_easy_setopt(curl->handle, CURLOPT_URL, storage->url); + + /* request method */ + switch (meth) { + case PHP_HTTP_GET: + curl_easy_setopt(curl->handle, CURLOPT_HTTPGET, 1L); + break; + + case PHP_HTTP_HEAD: + curl_easy_setopt(curl->handle, CURLOPT_NOBODY, 1L); + break; + + case PHP_HTTP_POST: + curl_easy_setopt(curl->handle, CURLOPT_POST, 1L); + break; + + case PHP_HTTP_PUT: + curl_easy_setopt(curl->handle, CURLOPT_UPLOAD, 1L); + break; + + default: { + const char *name = php_http_request_method_name(meth); + + if (name) { + curl_easy_setopt(curl->handle, CURLOPT_CUSTOMREQUEST, name); + } else { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_METHOD, "Unsupported request method: %d (%s)", meth, url); + return FAILURE; + } + break; + } + } + + /* attach request body */ + if (body) { + /* RFC2616, section 4.3 (para. 4) states that »a message-body MUST NOT be included in a request if the + * specification of the request method (section 5.1.1) does not allow sending an entity-body in request.« + * Following the clause in section 5.1.1 (para. 2) that request methods »MUST be implemented with the + * same semantics as those specified in section 9« reveal that not any single defined HTTP/1.1 method + * does not allow a request body. + */ + switch (meth) { + default: { + size_t body_size = php_http_message_body_size(body); + + curl_easy_setopt(curl->handle, CURLOPT_IOCTLDATA, body); + curl_easy_setopt(curl->handle, CURLOPT_READDATA, body); + curl_easy_setopt(curl->handle, CURLOPT_INFILESIZE, body_size); + curl_easy_setopt(curl->handle, CURLOPT_POSTFIELDSIZE, body_size); + break; + } + } + } + + return SUCCESS; +} + +static void php_http_curl_request_pool_responsehandler(php_http_request_pool_t *pool) +{ + int remaining = 0; + zval **requests; + php_http_curl_request_pool_t *curl = pool->ctx; + TSRMLS_FETCH_FROM_CTX(pool->ts); + + do { + CURLMsg *msg = curl_multi_info_read(curl->handle, &remaining); + + if (msg && CURLMSG_DONE == msg->msg) { + zval **request; + + if (CURLE_OK != msg->data.result) { + php_http_curl_request_storage_t *st = get_storage(msg->easy_handle); + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "%s; %s (%s)", curl_easy_strerror(msg->data.result), STR_PTR(st->errorbuffer), STR_PTR(st->url)); + } + + php_http_request_pool_requests(pool, &requests, NULL); + for (request = requests; *request; ++request) { + php_http_request_object_t *obj = zend_object_store_get_object(*request TSRMLS_CC); + + if (msg->easy_handle == ((php_http_curl_request_t *) (obj->request->ctx))->handle) { + Z_ADDREF_PP(request); + zend_llist_add_element(&pool->requests.finished, request); + php_http_request_object_responsehandler(obj, *request TSRMLS_CC); + } + + zval_ptr_dtor(request); + } + efree(requests); + } + } while (remaining); +} + + +#ifdef PHP_HTTP_HAVE_EVENT + +typedef struct php_http_request_pool_event { + struct event evnt; + php_http_request_pool_t *pool; +} php_http_request_pool_event_t; + +static inline int etoca(short action) { + switch (action & (EV_READ|EV_WRITE)) { + case EV_READ: + return CURL_CSELECT_IN; + break; + case EV_WRITE: + return CURL_CSELECT_OUT; + break; + case EV_READ|EV_WRITE: + return CURL_CSELECT_IN|CURL_CSELECT_OUT; + break; + default: + return 0; + } +} + +static void php_http_curl_request_pool_timeout_callback(int socket, short action, void *event_data) +{ + php_http_request_pool_t *pool = event_data; + php_http_curl_request_pool_t *curl = pool->ctx; + +#if DBG_EVENTS + fprintf(stderr, "T"); +#endif + if (curl->useevents) { + CURLMcode rc; + TSRMLS_FETCH_FROM_CTX(pool->ts); + + while (CURLM_CALL_MULTI_PERFORM == (rc = curl_multi_socket_action(curl->handle, socket, etoca(action), &curl->unfinished))); + + if (CURLM_OK != rc) { + php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, "%s", curl_multi_strerror(rc)); + } + + php_http_curl_request_pool_responsehandler(pool); + } +} + +static void php_http_curl_request_pool_event_callback(int socket, short action, void *event_data) +{ + php_http_request_pool_t *pool = event_data; + php_http_curl_request_pool_t *curl = pool->ctx; + +#if DBG_EVENTS + fprintf(stderr, "E"); +#endif + if (curl->useevents) { + CURLMcode rc = CURLE_OK; + TSRMLS_FETCH_FROM_CTX(pool->ts); + + while (CURLM_CALL_MULTI_PERFORM == (rc = curl_multi_socket_action(curl->handle, socket, etoca(action), &curl->unfinished))); + + if (CURLM_OK != rc) { + php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, "%s", curl_multi_strerror(rc)); + } + + php_http_curl_request_pool_responsehandler(pool); + + /* remove timeout if there are no transfers left */ + if (!curl->unfinished && event_initialized(curl->timeout) && event_pending(curl->timeout, EV_TIMEOUT, NULL)) { + event_del(curl->timeout); + } + } +} + +static int php_http_curl_request_pool_socket_callback(CURL *easy, curl_socket_t sock, int action, void *socket_data, void *assign_data) +{ + php_http_request_pool_t *pool = socket_data; + php_http_curl_request_pool_t *curl = pool->ctx; + +#if DBG_EVENTS + fprintf(stderr, "S"); +#endif + if (curl->useevents) { + int events = EV_PERSIST; + php_http_request_pool_event_t *ev = assign_data; + TSRMLS_FETCH_FROM_CTX(pool->ts); + + if (!ev) { + ev = ecalloc(1, sizeof(php_http_request_pool_event_t)); + ev->pool = pool; + curl_multi_assign(curl->handle, sock, ev); + event_base_set(PHP_HTTP_G->request_pool.event_base, &ev->evnt); + } else { + event_del(&ev->evnt); + } + + switch (action) { + case CURL_POLL_IN: + events |= EV_READ; + break; + case CURL_POLL_OUT: + events |= EV_WRITE; + break; + case CURL_POLL_INOUT: + events |= EV_READ|EV_WRITE; + break; + + case CURL_POLL_REMOVE: + efree(ev); + case CURL_POLL_NONE: + return 0; + + default: + php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, "Unknown socket action %d", action); + return -1; + } + + event_set(&ev->evnt, sock, events, php_http_curl_request_pool_event_callback, pool); + event_add(&ev->evnt, NULL); + } + + return 0; +} + +static void php_http_curl_request_pool_timer_callback(CURLM *multi, long timeout_ms, void *timer_data) +{ + php_http_request_pool_t *pool = timer_data; + php_http_curl_request_pool_t *curl = pool->ctx; + +#if DBG_EVENTS + fprintf(stderr, "%ld", timeout_ms); +#endif + if (curl->useevents) { + + if (timeout_ms < 0) { + php_http_curl_request_pool_timeout_callback(CURL_SOCKET_TIMEOUT, CURL_CSELECT_IN|CURL_CSELECT_OUT, pool); + } else if (timeout_ms > 0 || !event_initialized(curl->timeout) || !event_pending(curl->timeout, EV_TIMEOUT, NULL)) { + struct timeval timeout; + TSRMLS_FETCH_FROM_CTX(pool->ts); + + if (!event_initialized(curl->timeout)) { + event_set(curl->timeout, -1, 0, php_http_curl_request_pool_timeout_callback, pool); + event_base_set(PHP_HTTP_G->request_pool.event_base, curl->timeout); + } else if (event_pending(curl->timeout, EV_TIMEOUT, NULL)) { + event_del(curl->timeout); + } + + timeout.tv_sec = timeout_ms / 1000; + timeout.tv_usec = (timeout_ms % 1000) * 1000; + + event_add(curl->timeout, &timeout); + } + } +} + +#endif /* HAVE_EVENT */ + + +static inline zval *cache_option(HashTable *cache, char *key, size_t keylen, ulong h, zval *opt) +{ + Z_ADDREF_P(opt); + + if (h) { + zend_hash_quick_update(cache, key, keylen, h, &opt, sizeof(zval *), NULL); + } else { + zend_hash_update(cache, key, keylen, &opt, sizeof(zval *), NULL); + } + + return opt; +} + +static inline zval *get_option(HashTable *cache, HashTable *options, char *key, size_t keylen, int type) +{ + if (options) { + zval **zoption; + ulong h = zend_hash_func(key, keylen); + + if (SUCCESS == zend_hash_quick_find(options, key, keylen, h, (void *) &zoption)) { + zval *option = php_http_zsep(type, *zoption); + + if (cache) { + zval *cached = cache_option(cache, key, keylen, h, option); + + zval_ptr_dtor(&option); + return cached; + } + return option; + } + } + + return NULL; +} + +static STATUS set_options(php_http_request_t *h, HashTable *options) +{ + zval *zoption; + int range_req = 0; + php_http_curl_request_t *curl = h->ctx; + CURL *ch = curl->handle; + + /* proxy */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("proxyhost"), IS_STRING))) { + curl_easy_setopt(ch, CURLOPT_PROXY, Z_STRVAL_P(zoption)); + /* type */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("proxytype"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_PROXYTYPE, Z_LVAL_P(zoption)); + } + /* port */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("proxyport"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_PROXYPORT, Z_LVAL_P(zoption)); + } + /* user:pass */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("proxyauth"), IS_STRING)) && Z_STRLEN_P(zoption)) { + curl_easy_setopt(ch, CURLOPT_PROXYUSERPWD, Z_STRVAL_P(zoption)); + } + /* auth method */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("proxyauthtype"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_PROXYAUTH, Z_LVAL_P(zoption)); + } + /* tunnel */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("proxytunnel"), IS_BOOL)) && Z_BVAL_P(zoption)) { + curl_easy_setopt(ch, CURLOPT_HTTPPROXYTUNNEL, 1L); + } + } +#if PHP_HTTP_CURL_VERSION(7,19,4) + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("noproxy"), IS_STRING))) { + curl_easy_setopt(ch, CURLOPT_NOPROXY, Z_STRVAL_P(zoption)); + } +#endif + + /* dns */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("dns_cache_timeout"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_DNS_CACHE_TIMEOUT, Z_LVAL_P(zoption)); + } + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("ipresolve"), IS_LONG)) && Z_LVAL_P(zoption)) { + curl_easy_setopt(ch, CURLOPT_IPRESOLVE, Z_LVAL_P(zoption)); + } + + /* limits */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("low_speed_limit"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_LOW_SPEED_LIMIT, Z_LVAL_P(zoption)); + } + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("low_speed_time"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_LOW_SPEED_TIME, Z_LVAL_P(zoption)); + } + /* LSF weirdance + if ((zoption = get_option(&curl->cache.options, options, ZEND_STRS("max_send_speed"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_MAX_SEND_SPEED_LARGE, (curl_off_t) Z_LVAL_P(zoption)); + } + if ((zoption = get_option(&curl->cache.options, options, ZEND_STRS("max_recv_speed"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t) Z_LVAL_P(zoption)); + } + */ + /* crashes + if ((zoption = get_option(&curl->cache.options, options, ZEND_STRS("maxconnects"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_MAXCONNECTS, Z_LVAL_P(zoption)); + } */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("fresh_connect"), IS_BOOL)) && Z_BVAL_P(zoption)) { + curl_easy_setopt(ch, CURLOPT_FRESH_CONNECT, 1L); + } + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("forbid_reuse"), IS_BOOL)) && Z_BVAL_P(zoption)) { + curl_easy_setopt(ch, CURLOPT_FORBID_REUSE, 1L); + } + + /* outgoing interface */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("interface"), IS_STRING))) { + curl_easy_setopt(ch, CURLOPT_INTERFACE, Z_STRVAL_P(zoption)); + + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("portrange"), IS_ARRAY))) { + zval **prs, **pre; + + zend_hash_internal_pointer_reset(Z_ARRVAL_P(zoption)); + if (SUCCESS == zend_hash_get_current_data(Z_ARRVAL_P(zoption), (void *) &prs)) { + zend_hash_move_forward(Z_ARRVAL_P(zoption)); + if (SUCCESS == zend_hash_get_current_data(Z_ARRVAL_P(zoption), (void *) &pre)) { + zval *prs_cpy = php_http_zsep(IS_LONG, *prs); + zval *pre_cpy = php_http_zsep(IS_LONG, *pre); + + if (Z_LVAL_P(prs_cpy) && Z_LVAL_P(pre_cpy)) { + curl_easy_setopt(ch, CURLOPT_LOCALPORT, MIN(Z_LVAL_P(prs_cpy), Z_LVAL_P(pre_cpy))); + curl_easy_setopt(ch, CURLOPT_LOCALPORTRANGE, labs(Z_LVAL_P(prs_cpy)-Z_LVAL_P(pre_cpy))+1L); + } + zval_ptr_dtor(&prs_cpy); + zval_ptr_dtor(&pre_cpy); + } + } + } + } + + /* another port */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("port"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_PORT, Z_LVAL_P(zoption)); + } + + /* RFC4007 zone_id */ +#if PHP_HTTP_CURL_VERSION(7,19,0) + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("address_scope"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_ADDRESS_SCOPE, Z_LVAL_P(zoption)); + } +#endif + + /* auth */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("httpauth"), IS_STRING)) && Z_STRLEN_P(zoption)) { + curl_easy_setopt(ch, CURLOPT_USERPWD, Z_STRVAL_P(zoption)); + } + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("httpauthtype"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_HTTPAUTH, Z_LVAL_P(zoption)); + } + + /* redirects, defaults to 0 */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("redirect"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_FOLLOWLOCATION, Z_LVAL_P(zoption) ? 1L : 0L); + curl_easy_setopt(ch, CURLOPT_MAXREDIRS, curl->options.redirects = Z_LVAL_P(zoption)); + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("unrestrictedauth"), IS_BOOL))) { + curl_easy_setopt(ch, CURLOPT_UNRESTRICTED_AUTH, Z_LVAL_P(zoption)); + } + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("postredir"), IS_BOOL))) { +#if PHP_HTTP_CURL_VERSION(7,19,1) + curl_easy_setopt(ch, CURLOPT_POSTREDIR, Z_BVAL_P(zoption) ? 1L : 0L); +#else + curl_easy_setopt(ch, CURLOPT_POST301, Z_BVAL_P(zoption) ? 1L : 0L); +#endif + } + } else { + curl->options.redirects = 0; + } + + /* retries, defaults to 0 */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("retrycount"), IS_LONG))) { + curl->options.retry.count = Z_LVAL_P(zoption); + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("retrydelay"), IS_DOUBLE))) { + curl->options.retry.delay = Z_DVAL_P(zoption); + } else { + curl->options.retry.delay = 0; + } + } else { + curl->options.retry.count = 0; + } + + /* referer */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("referer"), IS_STRING)) && Z_STRLEN_P(zoption)) { + curl_easy_setopt(ch, CURLOPT_REFERER, Z_STRVAL_P(zoption)); + } + + /* useragent, default "PECL::HTTP/version (PHP/version)" */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("useragent"), IS_STRING))) { + /* allow to send no user agent, not even default one */ + if (Z_STRLEN_P(zoption)) { + curl_easy_setopt(ch, CURLOPT_USERAGENT, Z_STRVAL_P(zoption)); + } else { + curl_easy_setopt(ch, CURLOPT_USERAGENT, NULL); + } + } + + /* resume */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("resume"), IS_LONG)) && (Z_LVAL_P(zoption) > 0)) { + range_req = 1; + curl_easy_setopt(ch, CURLOPT_RESUME_FROM, Z_LVAL_P(zoption)); + } + /* or range of kind array(array(0,499), array(100,1499)) */ + else if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("range"), IS_ARRAY)) && zend_hash_num_elements(Z_ARRVAL_P(zoption))) { + HashPosition pos1, pos2; + zval **rr, **rb, **re; + php_http_buffer_t rs; + + php_http_buffer_init(&rs); + FOREACH_VAL(pos1, zoption, rr) { + if (Z_TYPE_PP(rr) == IS_ARRAY) { + zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(rr), &pos2); + if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(rr), (void *) &rb, &pos2)) { + zend_hash_move_forward_ex(Z_ARRVAL_PP(rr), &pos2); + if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(rr), (void *) &re, &pos2)) { + if ( ((Z_TYPE_PP(rb) == IS_LONG) || ((Z_TYPE_PP(rb) == IS_STRING) && is_numeric_string(Z_STRVAL_PP(rb), Z_STRLEN_PP(rb), NULL, NULL, 1))) && + ((Z_TYPE_PP(re) == IS_LONG) || ((Z_TYPE_PP(re) == IS_STRING) && is_numeric_string(Z_STRVAL_PP(re), Z_STRLEN_PP(re), NULL, NULL, 1)))) { + zval *rbl = php_http_zsep(IS_LONG, *rb); + zval *rel = php_http_zsep(IS_LONG, *re); + + if ((Z_LVAL_P(rbl) >= 0) && (Z_LVAL_P(rel) >= 0)) { + php_http_buffer_appendf(&rs, "%ld-%ld,", Z_LVAL_P(rbl), Z_LVAL_P(rel)); + } + zval_ptr_dtor(&rbl); + zval_ptr_dtor(&rel); + } + } + } + } + } + + if (PHP_HTTP_BUFFER_LEN(&rs)) { + zval *cached_range; + + /* ditch last comma */ + PHP_HTTP_BUFFER_VAL(&rs)[PHP_HTTP_BUFFER_LEN(&rs)-- -1] = '\0'; + /* cache string */ + MAKE_STD_ZVAL(cached_range); + ZVAL_STRINGL(cached_range, PHP_HTTP_BUFFER_VAL(&rs), PHP_HTTP_BUFFER_LEN(&rs), 0); + curl_easy_setopt(ch, CURLOPT_RANGE, Z_STRVAL_P(cache_option(&curl->options.cache, ZEND_STRS("range"), 0, cached_range))); + zval_ptr_dtor(&cached_range); + } + } + + /* additional headers, array('name' => 'value') */ + if (curl->options.headers) { + curl_slist_free_all(curl->options.headers); + curl->options.headers = NULL; + } + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("headers"), IS_ARRAY))) { + php_http_array_hashkey_t header_key = php_http_array_hashkey_init(0); + zval **header_val; + HashPosition pos; + php_http_buffer_t header; + + php_http_buffer_init(&header); + FOREACH_KEYVAL(pos, zoption, header_key, header_val) { + if (header_key.type == HASH_KEY_IS_STRING) { + zval *header_cpy = php_http_zsep(IS_STRING, *header_val); + + if (!strcasecmp(header_key.str, "range")) { + range_req = 1; + } + + php_http_buffer_appendf(&header, "%s: %s", header_key.str, Z_STRVAL_P(header_cpy)); + php_http_buffer_fix(&header); + curl->options.headers = curl_slist_append(curl->options.headers, PHP_HTTP_BUFFER_VAL(&header)); + php_http_buffer_reset(&header); + + zval_ptr_dtor(&header_cpy); + } + } + php_http_buffer_dtor(&header); + } + /* etag */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("etag"), IS_STRING)) && Z_STRLEN_P(zoption)) { + zend_bool is_quoted = !((Z_STRVAL_P(zoption)[0] != '"') || (Z_STRVAL_P(zoption)[Z_STRLEN_P(zoption)-1] != '"')); + php_http_buffer_t header; + + php_http_buffer_init(&header); + php_http_buffer_appendf(&header, is_quoted?"%s: %s":"%s: \"%s\"", range_req?"If-Match":"If-None-Match", Z_STRVAL_P(zoption)); + php_http_buffer_fix(&header); + curl->options.headers = curl_slist_append(curl->options.headers, PHP_HTTP_BUFFER_VAL(&header)); + php_http_buffer_dtor(&header); + } + /* compression */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("compress"), IS_BOOL)) && Z_LVAL_P(zoption)) { + curl->options.headers = curl_slist_append(curl->options.headers, "Accept-Encoding: gzip;q=1.0,deflate;q=0.5"); + } + curl_easy_setopt(ch, CURLOPT_HTTPHEADER, curl->options.headers); + + /* lastmodified */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("lastmodified"), IS_LONG))) { + if (Z_LVAL_P(zoption)) { + if (Z_LVAL_P(zoption) > 0) { + curl_easy_setopt(ch, CURLOPT_TIMEVALUE, Z_LVAL_P(zoption)); + } else { + curl_easy_setopt(ch, CURLOPT_TIMEVALUE, (long) PHP_HTTP_G->env.request.time + Z_LVAL_P(zoption)); + } + curl_easy_setopt(ch, CURLOPT_TIMECONDITION, (long) (range_req ? CURL_TIMECOND_IFUNMODSINCE : CURL_TIMECOND_IFMODSINCE)); + } else { + curl_easy_setopt(ch, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE); + } + } + + /* cookies, array('name' => 'value') */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("cookies"), IS_ARRAY))) { + php_http_buffer_dtor(&curl->options.cookies); + if (zend_hash_num_elements(Z_ARRVAL_P(zoption))) { + zval *urlenc_cookies = NULL; + /* check whether cookies should not be urlencoded; default is to urlencode them */ + if ((!(urlenc_cookies = get_option(&curl->options.cache, options, ZEND_STRS("encodecookies"), IS_BOOL))) || Z_BVAL_P(urlenc_cookies)) { + if (SUCCESS == php_http_url_encode_hash_recursive(HASH_OF(zoption), &curl->options.cookies, "; ", lenof("; "), NULL, 0 TSRMLS_CC)) { + php_http_buffer_fix(&curl->options.cookies); + curl_easy_setopt(ch, CURLOPT_COOKIE, curl->options.cookies.data); + } + } else { + HashPosition pos; + php_http_array_hashkey_t cookie_key = php_http_array_hashkey_init(0); + zval **cookie_val; + + FOREACH_KEYVAL(pos, zoption, cookie_key, cookie_val) { + if (cookie_key.type == HASH_KEY_IS_STRING) { + zval *val = php_http_zsep(IS_STRING, *cookie_val); + php_http_buffer_appendf(&curl->options.cookies, "%s=%s; ", cookie_key.str, Z_STRVAL_P(val)); + zval_ptr_dtor(&val); + } + } + + php_http_buffer_fix(&curl->options.cookies); + if (PHP_HTTP_BUFFER_LEN(&curl->options.cookies)) { + curl_easy_setopt(ch, CURLOPT_COOKIE, PHP_HTTP_BUFFER_VAL(&curl->options.cookies)); + } + } + } + } + + /* don't load session cookies from cookiestore */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("cookiesession"), IS_BOOL)) && Z_BVAL_P(zoption)) { + curl_easy_setopt(ch, CURLOPT_COOKIESESSION, 1L); + } + + /* cookiestore, read initial cookies from that file and store cookies back into that file */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("cookiestore"), IS_STRING))) { + php_http_curl_request_storage_t *storage = get_storage(curl->handle); + + if (Z_STRLEN_P(zoption)) { + if (SUCCESS != php_check_open_basedir(Z_STRVAL_P(zoption) TSRMLS_CC)) { + return FAILURE; + } + } + if (storage->cookiestore) { + pefree(storage->cookiestore, 1); + } + storage->cookiestore = pestrndup(Z_STRVAL_P(zoption), Z_STRLEN_P(zoption), 1); + curl_easy_setopt(ch, CURLOPT_COOKIEFILE, storage->cookiestore); + curl_easy_setopt(ch, CURLOPT_COOKIEJAR, storage->cookiestore); + } + + /* maxfilesize */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("maxfilesize"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_MAXFILESIZE, Z_LVAL_P(zoption)); + } + + /* http protocol */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("protocol"), IS_LONG))) { + curl_easy_setopt(ch, CURLOPT_HTTP_VERSION, Z_LVAL_P(zoption)); + } + + /* timeout, defaults to 0 */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("timeout"), IS_DOUBLE))) { + curl_easy_setopt(ch, CURLOPT_TIMEOUT_MS, (long)(Z_DVAL_P(zoption)*1000)); + } + /* connecttimeout, defaults to 0 */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("connecttimeout"), IS_DOUBLE))) { + curl_easy_setopt(ch, CURLOPT_CONNECTTIMEOUT_MS, (long)(Z_DVAL_P(zoption)*1000)); + } + + /* ssl */ + if ((zoption = get_option(&curl->options.cache, options, ZEND_STRS("ssl"), IS_ARRAY))) { + php_http_array_hashkey_t key = php_http_array_hashkey_init(0); + zval **param; + HashPosition pos; + + FOREACH_KEYVAL(pos, zoption, key, param) { + if (key.type == HASH_KEY_IS_STRING) { + PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLCERT, 0, 1); + PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLCERTTYPE, 0, 0); + PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLCERTPASSWD, 0, 0); + + PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLKEY, 0, 0); + PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLKEYTYPE, 0, 0); + PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLKEYPASSWD, 0, 0); + + PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLENGINE, 0, 0); + PHP_HTTP_CURL_OPT_LONG(CURLOPT_SSLVERSION, 0); + + PHP_HTTP_CURL_OPT_LONG(CURLOPT_SSL_VERIFYPEER, 1); + PHP_HTTP_CURL_OPT_LONG(CURLOPT_SSL_VERIFYHOST, 1); + PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSL_CIPHER_LIST, 1, 0); + + PHP_HTTP_CURL_OPT_STRING(CURLOPT_CAINFO, -3, 1); + PHP_HTTP_CURL_OPT_STRING(CURLOPT_CAPATH, -3, 1); + PHP_HTTP_CURL_OPT_STRING(CURLOPT_RANDOM_FILE, -3, 1); + PHP_HTTP_CURL_OPT_STRING(CURLOPT_EGDSOCKET, -3, 1); +#if PHP_HTTP_CURL_VERSION(7,19,0) + PHP_HTTP_CURL_OPT_STRING(CURLOPT_ISSUERCERT, -3, 1); + #if defined(PHP_HTTP_HAVE_OPENSSL) + PHP_HTTP_CURL_OPT_STRING(CURLOPT_CRLFILE, -3, 1); + #endif +#endif +#if PHP_HTTP_CURL_VERSION(7,19,1) && defined(PHP_HTTP_HAVE_OPENSSL) + PHP_HTTP_CURL_OPT_LONG(CURLOPT_CERTINFO, -3); +#endif + } + } + } + return SUCCESS; +} + +static STATUS get_info(CURL *ch, HashTable *info) +{ + char *c; + long l; + double d; + struct curl_slist *s, *p; + zval *subarray, array; + INIT_PZVAL_ARRAY(&array, info); + + /* BEGIN::CURLINFO */ + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_EFFECTIVE_URL, &c)) { + add_assoc_string_ex(&array, "effective_url", sizeof("effective_url"), c ? c : "", 1); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_RESPONSE_CODE, &l)) { + add_assoc_long_ex(&array, "response_code", sizeof("response_code"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_TOTAL_TIME, &d)) { + add_assoc_double_ex(&array, "total_time", sizeof("total_time"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_NAMELOOKUP_TIME, &d)) { + add_assoc_double_ex(&array, "namelookup_time", sizeof("namelookup_time"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_CONNECT_TIME, &d)) { + add_assoc_double_ex(&array, "connect_time", sizeof("connect_time"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_PRETRANSFER_TIME, &d)) { + add_assoc_double_ex(&array, "pretransfer_time", sizeof("pretransfer_time"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_SIZE_UPLOAD, &d)) { + add_assoc_double_ex(&array, "size_upload", sizeof("size_upload"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_SIZE_DOWNLOAD, &d)) { + add_assoc_double_ex(&array, "size_download", sizeof("size_download"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_SPEED_DOWNLOAD, &d)) { + add_assoc_double_ex(&array, "speed_download", sizeof("speed_download"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_SPEED_UPLOAD, &d)) { + add_assoc_double_ex(&array, "speed_upload", sizeof("speed_upload"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_HEADER_SIZE, &l)) { + add_assoc_long_ex(&array, "header_size", sizeof("header_size"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_REQUEST_SIZE, &l)) { + add_assoc_long_ex(&array, "request_size", sizeof("request_size"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_SSL_VERIFYRESULT, &l)) { + add_assoc_long_ex(&array, "ssl_verifyresult", sizeof("ssl_verifyresult"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_FILETIME, &l)) { + add_assoc_long_ex(&array, "filetime", sizeof("filetime"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) { + add_assoc_double_ex(&array, "content_length_download", sizeof("content_length_download"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_CONTENT_LENGTH_UPLOAD, &d)) { + add_assoc_double_ex(&array, "content_length_upload", sizeof("content_length_upload"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_STARTTRANSFER_TIME, &d)) { + add_assoc_double_ex(&array, "starttransfer_time", sizeof("starttransfer_time"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_CONTENT_TYPE, &c)) { + add_assoc_string_ex(&array, "content_type", sizeof("content_type"), c ? c : "", 1); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_REDIRECT_TIME, &d)) { + add_assoc_double_ex(&array, "redirect_time", sizeof("redirect_time"), d); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_REDIRECT_COUNT, &l)) { + add_assoc_long_ex(&array, "redirect_count", sizeof("redirect_count"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_HTTP_CONNECTCODE, &l)) { + add_assoc_long_ex(&array, "connect_code", sizeof("connect_code"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_HTTPAUTH_AVAIL, &l)) { + add_assoc_long_ex(&array, "httpauth_avail", sizeof("httpauth_avail"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_PROXYAUTH_AVAIL, &l)) { + add_assoc_long_ex(&array, "proxyauth_avail", sizeof("proxyauth_avail"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_OS_ERRNO, &l)) { + add_assoc_long_ex(&array, "os_errno", sizeof("os_errno"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_NUM_CONNECTS, &l)) { + add_assoc_long_ex(&array, "num_connects", sizeof("num_connects"), l); + } + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_SSL_ENGINES, &s)) { + MAKE_STD_ZVAL(subarray); + array_init(subarray); + for (p = s; p; p = p->next) { + if (p->data) { + add_next_index_string(subarray, p->data, 1); + } + } + add_assoc_zval_ex(&array, "ssl_engines", sizeof("ssl_engines"), subarray); + curl_slist_free_all(s); + } +#if PHP_HTTP_CURL_VERSION(7,14,1) + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_COOKIELIST, &s)) { + MAKE_STD_ZVAL(subarray); + array_init(subarray); + for (p = s; p; p = p->next) { + if (p->data) { + add_next_index_string(subarray, p->data, 1); + } + } + add_assoc_zval_ex(&array, "cookies", sizeof("cookies"), subarray); + curl_slist_free_all(s); + } +#endif +#if PHP_HTTP_CURL_VERSION(7,18,2) + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_REDIRECT_URL, &c)) { + add_assoc_string_ex(&array, "redirect_url", sizeof("redirect_url"), c ? c : "", 1); + } +#endif +#if PHP_HTTP_CURL_VERSION(7,19,0) + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_PRIMARY_IP, &c)) { + add_assoc_string_ex(&array, "primary_ip", sizeof("primary_ip"), c ? c : "", 1); + } +#endif +#if PHP_HTTP_CURL_VERSION(7,19,0) + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_APPCONNECT_TIME, &d)) { + add_assoc_double_ex(&array, "appconnect_time", sizeof("appconnect_time"), d); + } +#endif +#if PHP_HTTP_CURL_VERSION(7,19,4) + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_CONDITION_UNMET, &l)) { + add_assoc_long_ex(&array, "condition_unmet", sizeof("condition_unmet"), l); + } +#endif + /* END::CURLINFO */ +#if PHP_HTTP_CURL_VERSION(7,19,1) && defined(PHP_HTTP_HAVE_OPENSSL) + { + int i; + zval *ci_array; + struct curl_certinfo *ci; + char *colon, *keyname; + + if (CURLE_OK == curl_easy_getinfo(ch, CURLINFO_CERTINFO, &ci)) { + MAKE_STD_ZVAL(ci_array); + array_init(ci_array); + + for (i = 0; i < ci->num_of_certs; ++i) { + s = ci->certinfo[i]; + + MAKE_STD_ZVAL(subarray); + array_init(subarray); + for (p = s; p; p = p->next) { + if (p->data) { + if ((colon = strchr(p->data, ':'))) { + keyname = estrndup(p->data, colon - p->data); + add_assoc_string_ex(subarray, keyname, colon - p->data + 1, colon + 1, 1); + efree(keyname); + } else { + add_next_index_string(subarray, p->data, 1); + } + } + } + add_next_index_zval(ci_array, subarray); + } + add_assoc_zval_ex(&array, "certinfo", sizeof("certinfo"), ci_array); + } + } +#endif + add_assoc_string_ex(&array, "error", sizeof("error"), get_storage(ch)->errorbuffer, 1); + + return SUCCESS; +} + + +#ifdef ZTS +static void *php_http_curl_request_datashare_locks_init(void) +{ + int i; + php_http_curl_request_datashare_lock_t *locks = pecalloc(CURL_LOCK_DATA_LAST, sizeof(*locks), 1); + + if (locks) { + for (i = 0; i < CURL_LOCK_DATA_LAST; ++i) { + locks[i].mx = tsrm_mutex_alloc(); + } + } + + return locks; +} + +static void php_http_curl_request_datashare_locks_dtor(void *l) +{ + int i; + php_http_curl_request_datashare_lock_t *locks = l; + + for (i = 0; i < CURL_LOCK_DATA_LAST; ++i) { + tsrm_mutex_free(locks[i].mx); + } + pefree(locks, 1); +} + +static void php_http_curl_request_datashare_lock_func(CURL *handle, curl_lock_data data, curl_lock_access locktype, void *userptr) +{ + php_http_curl_request_datashare_lock_t *locks = userptr; + + /* TSRM can't distinguish shared/exclusive locks */ + tsrm_mutex_lock(locks[data].mx); + locks[data].ch = handle; +} + +static void php_http_curl_request_datashare_unlock_func(CURL *handle, curl_lock_data data, void *userptr) +{ + php_http_curl_request_datashare_lock_t *locks = userptr; + + if (locks[data].ch == handle) { + tsrm_mutex_unlock(locks[data].mx); + } +} +#endif + + + +/* request datashare handler ops */ + +static php_http_request_datashare_t *php_http_curl_request_datashare_init(php_http_request_datashare_t *h, void *handle TSRMLS_DC) +{ + php_http_curl_request_datashare_t *curl; + + if (!handle && (SUCCESS != php_http_persistent_handle_acquire(ZEND_STRL("http_request_datashare.curl"), &handle TSRMLS_CC))) { + return NULL; + } + + curl = pecalloc(1, sizeof(*curl), h->persistent); + curl->handle = handle; +#ifdef ZTS + if (h->persistent) { + if (SUCCESS == php_http_persistent_handle_acquire(ZEND_STRL("http_request_datashare_lock.curl"), (void *) &curl->locks)) { + curl_share_setopt(share->ch, CURLSHOPT_LOCKFUNC, php_http_curl_request_datashare_lock_func); + curl_share_setopt(share->ch, CURLSHOPT_UNLOCKFUNC, php_http_curl_request_datashare_unlock_func); + curl_share_setopt(share->ch, CURLSHOPT_USERDATA, curl->locks); + } + } +#endif + h->ctx = curl; + + return h; +} + +static void php_http_curl_request_datashare_dtor(php_http_request_datashare_t *h) +{ + php_http_curl_request_datashare_t *curl = h->ctx; + TSRMLS_FETCH_FROM_CTX(h->ts); + + php_http_persistent_handle_release(ZEND_STRL("http_request_datashare.curl"), &curl->handle TSRMLS_CC); + +#ifdef ZTS + if (h->persistent) { + php_http_persistent_handle_release(ZEND_STRL("http_request_datashare_lock.curl"), (void *) &curl->locks TSRMLS_CC); + } +#endif + +} + +static STATUS php_http_curl_request_datashare_attach(php_http_request_datashare_t *h, php_http_request_t *r) +{ + CURLcode rc; + php_http_curl_request_datashare_t *curl = h->ctx; + php_http_curl_request_t *recurl = r->ctx; + TSRMLS_FETCH_FROM_CTX(h->ts); + + if (CURLE_OK != (rc = curl_easy_setopt(recurl->handle, CURLOPT_SHARE, curl->handle))) { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_DATASHARE, "Could not attach request to the datashare: %s", curl_easy_strerror(rc)); + return FAILURE; + } + return SUCCESS; +} + +static STATUS php_http_curl_request_datashare_detach(php_http_request_datashare_t *h, php_http_request_t *r) +{ + CURLcode rc; + php_http_curl_request_t *recurl = r->ctx; + TSRMLS_FETCH_FROM_CTX(h->ts); + + + if (CURLE_OK != (rc = curl_easy_setopt(recurl->handle, CURLOPT_SHARE, NULL))) { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_DATASHARE, "Could not detach request from the datashare: %s", curl_share_strerror(rc)); + return FAILURE; + } + return SUCCESS; +} + +static STATUS php_http_curl_request_datashare_setopt(php_http_request_datashare_t *h, php_http_request_datashare_setopt_opt_t opt, void *arg) +{ + CURLSHcode rc; + php_http_curl_request_datashare_t *curl = h->ctx; + + switch (opt) { + case PHP_HTTP_REQUEST_DATASHARE_OPT_COOKIES: + if (CURLSHE_OK != (rc = curl_share_setopt(curl->handle, *((zend_bool *) arg) ? CURLSHOPT_SHARE : CURLSHOPT_UNSHARE, CURL_LOCK_DATA_COOKIE))) { + TSRMLS_FETCH_FROM_CTX(h->ts); + + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_DATASHARE, "Could not %s sharing of cookie data: %s", *((zend_bool *) arg) ? "enable" : "disable", curl_share_strerror(rc)); + return FAILURE; + } + break; + + case PHP_HTTP_REQUEST_DATASHARE_OPT_RESOLVER: + if (CURLSHE_OK != (rc = curl_share_setopt(curl->handle, *((zend_bool *) arg) ? CURLSHOPT_SHARE : CURLSHOPT_UNSHARE, CURL_LOCK_DATA_COOKIE))) { + TSRMLS_FETCH_FROM_CTX(h->ts); + + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_DATASHARE, "Could not %s sharing of resolver data: %s", *((zend_bool *) arg) ? "enable" : "disable", curl_share_strerror(rc)); + return FAILURE; + } + break; + + default: + return FAILURE; + } + + return SUCCESS; +} + +static php_http_request_datashare_ops_t php_http_curl_request_datashare_ops = { + php_http_curl_request_datashare_init, + NULL /* copy */, + php_http_curl_request_datashare_dtor, + NULL /*reset */, + php_http_curl_request_datashare_attach, + php_http_curl_request_datashare_detach, + php_http_curl_request_datashare_setopt, +}; + +PHP_HTTP_API php_http_request_datashare_ops_t *php_http_curl_get_request_datashare_ops(void) +{ + return &php_http_curl_request_datashare_ops; +} + + +/* request pool handler ops */ + +static php_http_request_pool_t *php_http_curl_request_pool_init(php_http_request_pool_t *h, void *handle TSRMLS_DC) +{ + php_http_curl_request_pool_t *curl; + + if (!handle && (SUCCESS != php_http_persistent_handle_acquire(ZEND_STRL("http_request_pool.curl"), &handle TSRMLS_CC))) { + return NULL; + } + + curl = ecalloc(1, sizeof(*curl)); + curl->handle = handle; + curl->unfinished = 0; + h->ctx = curl; + + return h; +} + +static void php_http_curl_request_pool_dtor(php_http_request_pool_t *h) +{ + php_http_curl_request_pool_t *curl = h->ctx; + TSRMLS_FETCH_FROM_CTX(h->ts); + +#ifdef PHP_HTTP_HAVE_EVENT + if (curl->timeout) { + efree(curl->timeout); + curl->timeout = NULL; + } +#endif + curl->unfinished = 0; + php_http_request_pool_reset(h); + php_http_persistent_handle_release(ZEND_STRL("http_request_pool.curl"), &curl->handle TSRMLS_CC); + + efree(curl); + h->ctx = NULL; +} + +static STATUS php_http_curl_request_pool_attach(php_http_request_pool_t *h, php_http_request_t *r, php_http_request_method_t m, const char *url, php_http_message_body_t *body) +{ + php_http_curl_request_pool_t *curl = h->ctx; + php_http_curl_request_t *recurl = r->ctx; + CURLMcode rs; + + if (SUCCESS != php_http_curl_request_prepare(r, m, url, body)) { + return FAILURE; + } + + if (CURLM_OK == (rs = curl_multi_add_handle(curl->handle, recurl->handle))) { + ++curl->unfinished; + return SUCCESS; + } else { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_POOL, "Could not attach request to pool: %s", curl_multi_strerror(rs)); + return FAILURE; + } +} + +static STATUS php_http_curl_request_pool_detach(php_http_request_pool_t *h, php_http_request_t *r) +{ + php_http_curl_request_pool_t *curl = h->ctx; + php_http_curl_request_t *recurl = r->ctx; + CURLMcode rs = curl_multi_remove_handle(curl->handle, recurl->handle); + + if (CURLM_OK == rs) { + return SUCCESS; + } else { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_POOL, "Could not detach request from pool: %s", curl_multi_strerror(rs)); + return FAILURE; + } +} + +#ifdef PHP_WIN32 +# define SELECT_ERROR SOCKET_ERROR +#else +# define SELECT_ERROR -1 +#endif + +static STATUS php_http_curl_request_pool_wait(php_http_request_pool_t *h, struct timeval *custom_timeout) +{ + int MAX; + fd_set R, W, E; + struct timeval timeout; + php_http_curl_request_pool_t *curl = h->ctx; + +#ifdef PHP_HTTP_HAVE_EVENT + if (curl->useevents) { + TSRMLS_FETCH_FROM_CTX(pool->ts); + + php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "not implemented"); + return FAILURE; + } +#endif + + if (custom_timeout && timerisset(custom_timeout)) { + timeout = *custom_timeout; + } else { + long max_tout = 1000; + + if ((CURLM_OK == curl_multi_timeout(curl->handle, &max_tout)) && (max_tout > 0)) { + timeout.tv_sec = max_tout / 1000; + timeout.tv_usec = (max_tout % 1000) * 1000; + } else { + timeout.tv_sec = 0; + timeout.tv_usec = 1000; + } + } + + FD_ZERO(&R); + FD_ZERO(&W); + FD_ZERO(&E); + + if (CURLM_OK == curl_multi_fdset(curl->handle, &R, &W, &E, &MAX)) { + if (MAX == -1) { + php_http_sleep((double) timeout.tv_sec + (double) (timeout.tv_usec / PHP_HTTP_MCROSEC)); + return SUCCESS; + } else if (SELECT_ERROR != select(MAX + 1, &R, &W, &E, &timeout)) { + return SUCCESS; + } + } + return FAILURE; +} + +static int php_http_curl_request_pool_once(php_http_request_pool_t *h) +{ + php_http_curl_request_pool_t *curl = h->ctx; + TSRMLS_FETCH_FROM_CTX(h->ts); + +#ifdef PHP_HTTP_HAVE_EVENT + if (curl->useevents) { + php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "not implemented"); + return FAILURE; + } +#endif + + while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform(curl->handle, &curl->unfinished)); + + php_http_curl_request_pool_responsehandler(h); + + return curl->unfinished; + +} +static void dolog(int i, const char *m) { + fprintf(stderr, "%d: %s\n", i, m); +} +static STATUS php_http_curl_request_pool_exec(php_http_request_pool_t *h) +{ + php_http_curl_request_pool_t *curl = h->ctx; + +#ifdef PHP_HTTP_HAVE_EVENT + if (curl->useevents) { + event_set_log_callback(dolog); + do { +#if DBG_EVENTS + fprintf(stderr, "X"); +#endif + event_base_dispatch(PHP_HTTP_G->request_pool.event_base); + } while (curl->unfinished); + } else +#endif + { + while (php_http_curl_request_pool_once(h)) { + if (SUCCESS != php_http_curl_request_pool_wait(h, NULL)) { +#ifdef PHP_WIN32 + /* see http://msdn.microsoft.com/library/en-us/winsock/winsock/windows_sockets_error_codes_2.asp */ + php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, "WinSock error: %d", WSAGetLastError()); +#else + php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, strerror(errno)); +#endif + return FAILURE; + } + } + } + + return SUCCESS; +} + +static STATUS php_http_curl_request_pool_setopt(php_http_request_pool_t *h, php_http_request_pool_setopt_opt_t opt, void *arg) +{ + php_http_curl_request_pool_t *curl = h->ctx; + + switch (opt) { + case PHP_HTTP_REQUEST_POOL_OPT_ENABLE_PIPELINING: + if (CURLM_OK != curl_multi_setopt(curl->handle, CURLMOPT_PIPELINING, (long) *((zend_bool *) arg))) { + return FAILURE; + } + break; + + case PHP_HTTP_REQUEST_POOL_OPT_USE_EVENTS: +#if PHP_HTTP_HAVE_EVENT + if ((curl->useevents = *((zend_bool *) arg))) { + if (!curl->timeout) { + curl->timeout = ecalloc(1, sizeof(struct event)); + } + curl_multi_setopt(curl->handle, CURLMOPT_SOCKETDATA, h); + curl_multi_setopt(curl->handle, CURLMOPT_SOCKETFUNCTION, php_http_curl_request_pool_socket_callback); + curl_multi_setopt(curl->handle, CURLMOPT_TIMERDATA, h); + curl_multi_setopt(curl->handle, CURLMOPT_TIMERFUNCTION, php_http_curl_request_pool_timer_callback); + } else { + curl_multi_setopt(curl->handle, CURLMOPT_SOCKETDATA, NULL); + curl_multi_setopt(curl->handle, CURLMOPT_SOCKETFUNCTION, NULL); + curl_multi_setopt(curl->handle, CURLMOPT_TIMERDATA, NULL); + curl_multi_setopt(curl->handle, CURLMOPT_TIMERFUNCTION, NULL); + } + break; +#endif + + default: + return FAILURE; + } + return SUCCESS; +} + +static php_http_request_pool_ops_t php_http_curl_request_pool_ops = { + php_http_curl_request_pool_init, + NULL /* copy */, + php_http_curl_request_pool_dtor, + NULL /*reset */, + php_http_curl_request_pool_exec, + php_http_curl_request_pool_wait, + php_http_curl_request_pool_once, + php_http_curl_request_pool_attach, + php_http_curl_request_pool_detach, + php_http_curl_request_pool_setopt, +}; + +PHP_HTTP_API php_http_request_pool_ops_t *php_http_curl_get_request_pool_ops(void) +{ + return &php_http_curl_request_pool_ops; +} + +/* request handler ops */ + +static STATUS php_http_curl_request_reset(php_http_request_t *h); + +static php_http_request_t *php_http_curl_request_init(php_http_request_t *h, void *handle) +{ + php_http_curl_request_t *ctx; + TSRMLS_FETCH_FROM_CTX(h->ts); + + if (!handle && (SUCCESS != php_http_persistent_handle_acquire(ZEND_STRL("http_request.curl"), &handle TSRMLS_CC))) { + return NULL; + } + + ctx = ecalloc(1, sizeof(*ctx)); + ctx->handle = handle; + php_http_buffer_init(&ctx->options.cookies); + zend_hash_init(&ctx->options.cache, 0, NULL, ZVAL_PTR_DTOR, 0); + h->ctx = ctx; + +#if defined(ZTS) + curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1L); +#endif + curl_easy_setopt(handle, CURLOPT_HEADER, 0L); + curl_easy_setopt(handle, CURLOPT_FILETIME, 1L); + curl_easy_setopt(handle, CURLOPT_AUTOREFERER, 1L); + curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L); + curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(handle, CURLOPT_HEADERFUNCTION, NULL); + curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, php_http_curl_dummy_callback); + curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, php_http_curl_raw_callback); + curl_easy_setopt(handle, CURLOPT_READFUNCTION, php_http_curl_read_callback); + curl_easy_setopt(handle, CURLOPT_IOCTLFUNCTION, php_http_curl_ioctl_callback); + curl_easy_setopt(handle, CURLOPT_PROGRESSFUNCTION, php_http_curl_progress_callback); + curl_easy_setopt(handle, CURLOPT_DEBUGDATA, h); + curl_easy_setopt(handle, CURLOPT_PROGRESSDATA, h); + + php_http_curl_request_reset(h TSRMLS_CC); + + return h; +} + +static php_http_request_t *php_http_curl_request_copy(php_http_request_t *from, php_http_request_t *to) +{ + php_http_curl_request_t *ctx = from->ctx; + void *copy; + TSRMLS_FETCH_FROM_CTX(from->ts); + + if (SUCCESS != php_http_persistent_handle_accrete(ZEND_STRL("http_request.curl"), ctx->handle, © TSRMLS_CC)) { + return NULL; + } + + if (to) { + return php_http_curl_request_init(to, copy); + } else { + return php_http_request_init(NULL, from->ops, copy TSRMLS_CC); + } +} + +static void php_http_curl_request_dtor(php_http_request_t *h) +{ + php_http_curl_request_t *ctx = h->ctx; + + curl_easy_setopt(ctx->handle, CURLOPT_NOPROGRESS, 1L); + curl_easy_setopt(ctx->handle, CURLOPT_PROGRESSFUNCTION, NULL); + curl_easy_setopt(ctx->handle, CURLOPT_VERBOSE, 0L); + curl_easy_setopt(ctx->handle, CURLOPT_DEBUGFUNCTION, NULL); + + php_http_persistent_handle_release(ZEND_STRL("http_request.curl"), &ctx->handle TSRMLS_CC); + + php_http_buffer_dtor(&ctx->options.cookies); + zend_hash_destroy(&ctx->options.cache); + + if (ctx->options.headers) { + curl_slist_free_all(ctx->options.headers); + ctx->options.headers = NULL; + } + + if (ctx->progress.callback) { + zval_ptr_dtor(&ctx->progress.callback); + ctx->progress.callback = NULL; + } + + efree(ctx); + h->ctx = NULL; +} +static STATUS php_http_curl_request_reset(php_http_request_t *h) +{ + CURL *ch = ((php_http_curl_request_t *) h->ctx)->handle; + php_http_curl_request_storage_t *st; + + if ((st = get_storage(ch))) { + if (st->url) { + pefree(st->url, 1); + st->url = NULL; + } + if (st->cookiestore) { + pefree(st->cookiestore, 1); + st->cookiestore = NULL; + } + st->errorbuffer[0] = '\0'; + } + + curl_easy_setopt(ch, CURLOPT_URL, NULL); +#if PHP_HTTP_CURL_VERSION(7,19,4) + curl_easy_setopt(ch, CURLOPT_NOPROXY, NULL); +#endif + curl_easy_setopt(ch, CURLOPT_PROXY, NULL); + curl_easy_setopt(ch, CURLOPT_PROXYPORT, 0L); + curl_easy_setopt(ch, CURLOPT_PROXYTYPE, 0L); + /* libcurl < 7.19.6 does not clear auth info with USERPWD set to NULL */ +#if PHP_HTTP_CURL_VERSION(7,19,1) + curl_easy_setopt(ch, CURLOPT_PROXYUSERNAME, NULL); + curl_easy_setopt(ch, CURLOPT_PROXYPASSWORD, NULL); +#endif + curl_easy_setopt(ch, CURLOPT_PROXYAUTH, 0L); + curl_easy_setopt(ch, CURLOPT_HTTPPROXYTUNNEL, 0L); + curl_easy_setopt(ch, CURLOPT_DNS_CACHE_TIMEOUT, 60L); + curl_easy_setopt(ch, CURLOPT_IPRESOLVE, 0); + curl_easy_setopt(ch, CURLOPT_LOW_SPEED_LIMIT, 0L); + curl_easy_setopt(ch, CURLOPT_LOW_SPEED_TIME, 0L); + /* LFS weirdance + curl_easy_setopt(ch, CURLOPT_MAX_SEND_SPEED_LARGE, (curl_off_t) 0); + curl_easy_setopt(ch, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t) 0); + */ + /* crashes + curl_easy_setopt(ch, CURLOPT_MAXCONNECTS, 5L); */ + curl_easy_setopt(ch, CURLOPT_FRESH_CONNECT, 0L); + curl_easy_setopt(ch, CURLOPT_FORBID_REUSE, 0L); + curl_easy_setopt(ch, CURLOPT_INTERFACE, NULL); + curl_easy_setopt(ch, CURLOPT_PORT, 0L); +#if PHP_HTTP_CURL_VERSION(7,19,0) + curl_easy_setopt(ch, CURLOPT_ADDRESS_SCOPE, 0L); +#endif + curl_easy_setopt(ch, CURLOPT_LOCALPORT, 0L); + curl_easy_setopt(ch, CURLOPT_LOCALPORTRANGE, 0L); + /* libcurl < 7.19.6 does not clear auth info with USERPWD set to NULL */ +#if PHP_HTTP_CURL_VERSION(7,19,1) + curl_easy_setopt(ch, CURLOPT_USERNAME, NULL); + curl_easy_setopt(ch, CURLOPT_PASSWORD, NULL); +#endif + curl_easy_setopt(ch, CURLOPT_HTTPAUTH, 0L); + curl_easy_setopt(ch, CURLOPT_ENCODING, NULL); + /* we do this ourself anyway */ + curl_easy_setopt(ch, CURLOPT_HTTP_CONTENT_DECODING, 0L); + curl_easy_setopt(ch, CURLOPT_HTTP_TRANSFER_DECODING, 0L); + curl_easy_setopt(ch, CURLOPT_FOLLOWLOCATION, 0L); +#if PHP_HTTP_CURL_VERSION(7,19,1) + curl_easy_setopt(ch, CURLOPT_POSTREDIR, 0L); +#else + curl_easy_setopt(ch, CURLOPT_POST301, 0L); +#endif + curl_easy_setopt(ch, CURLOPT_UNRESTRICTED_AUTH, 0L); + curl_easy_setopt(ch, CURLOPT_REFERER, NULL); + curl_easy_setopt(ch, CURLOPT_USERAGENT, "PECL::HTTP/" PHP_HTTP_EXT_VERSION " (PHP/" PHP_VERSION ")"); + curl_easy_setopt(ch, CURLOPT_HTTPHEADER, NULL); + curl_easy_setopt(ch, CURLOPT_COOKIE, NULL); + curl_easy_setopt(ch, CURLOPT_COOKIESESSION, 0L); + /* these options would enable curl's cookie engine by default which we don't want + curl_easy_setopt(ch, CURLOPT_COOKIEFILE, NULL); + curl_easy_setopt(ch, CURLOPT_COOKIEJAR, NULL); */ + curl_easy_setopt(ch, CURLOPT_COOKIELIST, NULL); + curl_easy_setopt(ch, CURLOPT_RANGE, NULL); + curl_easy_setopt(ch, CURLOPT_RESUME_FROM, 0L); + curl_easy_setopt(ch, CURLOPT_MAXFILESIZE, 0L); + curl_easy_setopt(ch, CURLOPT_TIMECONDITION, 0L); + curl_easy_setopt(ch, CURLOPT_TIMEVALUE, 0L); + curl_easy_setopt(ch, CURLOPT_TIMEOUT, 0L); + curl_easy_setopt(ch, CURLOPT_CONNECTTIMEOUT, 3); + curl_easy_setopt(ch, CURLOPT_SSLCERT, NULL); + curl_easy_setopt(ch, CURLOPT_SSLCERTTYPE, NULL); + curl_easy_setopt(ch, CURLOPT_SSLCERTPASSWD, NULL); + curl_easy_setopt(ch, CURLOPT_SSLKEY, NULL); + curl_easy_setopt(ch, CURLOPT_SSLKEYTYPE, NULL); + curl_easy_setopt(ch, CURLOPT_SSLKEYPASSWD, NULL); + curl_easy_setopt(ch, CURLOPT_SSLENGINE, NULL); + curl_easy_setopt(ch, CURLOPT_SSLVERSION, 0L); + curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(ch, CURLOPT_SSL_VERIFYHOST, 0L); + curl_easy_setopt(ch, CURLOPT_SSL_CIPHER_LIST, NULL); +#if PHP_HTTP_CURL_VERSION(7,19,0) + curl_easy_setopt(ch, CURLOPT_ISSUERCERT, NULL); +#if defined(PHP_HTTP_HAVE_OPENSSL) + curl_easy_setopt(ch, CURLOPT_CRLFILE, NULL); +#endif +#endif +#if PHP_HTTP_CURL_VERSION(7,19,1) && defined(PHP_HTTP_HAVE_OPENSSL) + curl_easy_setopt(ch, CURLOPT_CERTINFO, NULL); +#endif +#ifdef PHP_HTTP_CURL_CAINFO + curl_easy_setopt(ch, CURLOPT_CAINFO, PHP_HTTP_CURL_CAINFO); +#else + curl_easy_setopt(ch, CURLOPT_CAINFO, NULL); +#endif + curl_easy_setopt(ch, CURLOPT_CAPATH, NULL); + curl_easy_setopt(ch, CURLOPT_RANDOM_FILE, NULL); + curl_easy_setopt(ch, CURLOPT_EGDSOCKET, NULL); + curl_easy_setopt(ch, CURLOPT_POSTFIELDS, NULL); + curl_easy_setopt(ch, CURLOPT_POSTFIELDSIZE, 0L); + curl_easy_setopt(ch, CURLOPT_HTTPPOST, NULL); + curl_easy_setopt(ch, CURLOPT_IOCTLDATA, NULL); + curl_easy_setopt(ch, CURLOPT_READDATA, NULL); + curl_easy_setopt(ch, CURLOPT_INFILESIZE, 0L); + curl_easy_setopt(ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE); + curl_easy_setopt(ch, CURLOPT_CUSTOMREQUEST, NULL); + curl_easy_setopt(ch, CURLOPT_NOBODY, 0L); + curl_easy_setopt(ch, CURLOPT_POST, 0L); + curl_easy_setopt(ch, CURLOPT_UPLOAD, 0L); + curl_easy_setopt(ch, CURLOPT_HTTPGET, 1L); + + return SUCCESS; +} + +static STATUS php_http_curl_request_exec(php_http_request_t *h, php_http_request_method_t meth, const char *url, php_http_message_body_t *body) +{ + uint tries = 0; + CURLcode result; + php_http_curl_request_t *curl = h->ctx; + php_http_curl_request_storage_t *storage = get_storage(curl->handle); + TSRMLS_FETCH_FROM_CTX(h->ts); + + if (SUCCESS != php_http_curl_request_prepare(h, meth, url, body)) { + return FAILURE; + } + +retry: + if (CURLE_OK != (result = curl_easy_perform(curl->handle))) { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "%s; %s (%s)", curl_easy_strerror(result), storage->errorbuffer, storage->url); + + if (EG(exception)) { + add_property_long(EG(exception), "curlCode", result); + } + + if (curl->options.retry.count > tries++) { + switch (result) { + case CURLE_COULDNT_RESOLVE_PROXY: + case CURLE_COULDNT_RESOLVE_HOST: + case CURLE_COULDNT_CONNECT: + case CURLE_WRITE_ERROR: + case CURLE_READ_ERROR: + case CURLE_OPERATION_TIMEDOUT: + case CURLE_SSL_CONNECT_ERROR: + case CURLE_GOT_NOTHING: + case CURLE_SSL_ENGINE_SETFAILED: + case CURLE_SEND_ERROR: + case CURLE_RECV_ERROR: + case CURLE_SSL_ENGINE_INITFAILED: + case CURLE_LOGIN_DENIED: + if (curl->options.retry.delay >= PHP_HTTP_DIFFSEC) { + php_http_sleep(curl->options.retry.delay); + } + goto retry; + default: + break; + } + } else { + return FAILURE; + } + } + + return SUCCESS; +} + +static STATUS php_http_curl_request_setopt(php_http_request_t *h, php_http_request_setopt_opt_t opt, void *arg) +{ + php_http_curl_request_t *curl = h->ctx; + + switch (opt) { + case PHP_HTTP_REQUEST_OPT_SETTINGS: + return set_options(h, arg); + break; + + case PHP_HTTP_REQUEST_OPT_PROGRESS_CALLBACK: + if (curl->progress.in_cb) { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "Cannot change progress callback while executing it"); + return FAILURE; + } + if (arg) { + Z_ADDREF_P(arg); + } + if (curl->progress.callback) { + zval_ptr_dtor(&curl->progress.callback); + } + curl->progress.callback = arg; + break; + + case PHP_HTTP_REQUEST_OPT_PROGRESS_CALLBACK_WANTS_STATE: + curl->progress.pass_state = *((int *)arg); + break; + + case PHP_HTTP_REQUEST_OPT_COOKIES_ENABLE: + /* are cookies already enabled anyway? */ + if (!get_storage(curl->handle)->cookiestore) { + if (CURLE_OK != curl_easy_setopt(curl->handle, CURLOPT_COOKIEFILE, "")) { + return FAILURE; + } + } + break; + + case PHP_HTTP_REQUEST_OPT_COOKIES_RESET: + if (CURLE_OK != curl_easy_setopt(curl->handle, CURLOPT_COOKIELIST, "ALL")) { + return FAILURE; + } + break; + + case PHP_HTTP_REQUEST_OPT_COOKIES_RESET_SESSION: + if (CURLE_OK != curl_easy_setopt(curl->handle, CURLOPT_COOKIELIST, "SESS")) { + return FAILURE; + } + break; + + case PHP_HTTP_REQUEST_OPT_COOKIES_FLUSH: + if (CURLE_OK != curl_easy_setopt(curl->handle, CURLOPT_COOKIELIST, "FLUSH")) { + return FAILURE; + } + break; + + default: + return FAILURE; + } + + return SUCCESS; +} + +static STATUS php_http_curl_request_getopt(php_http_request_t *h, php_http_request_getopt_opt_t opt, void *arg) +{ + php_http_curl_request_t *curl = h->ctx; + + switch (opt) { + case PHP_HTTP_REQUEST_OPT_PROGRESS_INFO: + *((php_http_request_progress_t **) arg) = &curl->progress; + break; + + case PHP_HTTP_REQUEST_OPT_TRANSFER_INFO: + get_info(curl->handle, arg); + break; + + default: + return FAILURE; + } + + return SUCCESS; +} + +static php_http_request_ops_t php_http_curl_request_ops = { + php_http_curl_request_init, + php_http_curl_request_copy, + php_http_curl_request_dtor, + php_http_curl_request_reset, + php_http_curl_request_exec, + php_http_curl_request_setopt, + php_http_curl_request_getopt +}; + +PHP_HTTP_API php_http_request_ops_t *php_http_curl_get_request_ops(void) +{ + return &php_http_curl_request_ops; +} + +/* safe curl wrappers */ +static void *safe_curl_init(void) +{ + void *ch; + + if ((ch = curl_easy_init())) { + get_storage(ch); + return ch; + } + return NULL; +} + +static void *safe_curl_copy(void *p) +{ + void *ch; + + if ((ch = curl_easy_duphandle(p))) { + get_storage(ch); + return ch; + } + return NULL; +} + +static void safe_curl_dtor(void *p) { + php_http_curl_request_storage_t *st = get_storage(p); + + curl_easy_cleanup(p); + + if (st) { + if (st->url) { + pefree(st->url, 1); + } + if (st->cookiestore) { + pefree(st->cookiestore, 1); + } + pefree(st, 1); + } +} + +#if defined(ZTS) && defined(PHP_HTTP_HAVE_SSL) +# ifdef PHP_WIN32 +# define PHP_HTTP_NEED_OPENSSL_TSL +# include +# else /* !PHP_WIN32 */ +# if defined(PHP_HTTP_HAVE_OPENSSL) +# define PHP_HTTP_NEED_OPENSSL_TSL +# include +# elif defined(PHP_HTTP_HAVE_GNUTLS) +# define PHP_HTTP_NEED_GNUTLS_TSL +# include +# else +# warning \ + "libcurl was compiled with SSL support, but configure could not determine which" \ + "library was used; thus no SSL crypto locking callbacks will be set, which may " \ + "cause random crashes on SSL requests" +# endif /* PHP_HTTP_HAVE_OPENSSL || PHP_HTTP_HAVE_GNUTLS */ +# endif /* PHP_WIN32 */ +#endif /* ZTS && PHP_HTTP_HAVE_SSL */ + + +#ifdef PHP_HTTP_NEED_OPENSSL_TSL +static MUTEX_T *php_http_openssl_tsl = NULL; + +static void php_http_openssl_thread_lock(int mode, int n, const char * file, int line) +{ + if (mode & CRYPTO_LOCK) { + tsrm_mutex_lock(php_http_openssl_tsl[n]); + } else { + tsrm_mutex_unlock(php_http_openssl_tsl[n]); + } +} + +static ulong php_http_openssl_thread_id(void) +{ + return (ulong) tsrm_thread_id(); +} +#endif +#ifdef PHP_HTTP_NEED_GNUTLS_TSL +static int php_http_gnutls_mutex_create(void **m) +{ + if (*((MUTEX_T *) m) = tsrm_mutex_alloc()) { + return SUCCESS; + } else { + return FAILURE; + } +} + +static int php_http_gnutls_mutex_destroy(void **m) +{ + tsrm_mutex_free(*((MUTEX_T *) m)); + return SUCCESS; +} + +static int php_http_gnutls_mutex_lock(void **m) +{ + return tsrm_mutex_lock(*((MUTEX_T *) m)); +} + +static int php_http_gnutls_mutex_unlock(void **m) +{ + return tsrm_mutex_unlock(*((MUTEX_T *) m)); +} + +static struct gcry_thread_cbs php_http_gnutls_tsl = { + GCRY_THREAD_OPTION_USER, + NULL, + php_http_gnutls_mutex_create, + php_http_gnutls_mutex_destroy, + php_http_gnutls_mutex_lock, + php_http_gnutls_mutex_unlock +}; +#endif + + + +PHP_MINIT_FUNCTION(http_curl) +{ + php_http_request_factory_driver_t driver = { + &php_http_curl_request_ops, + &php_http_curl_request_pool_ops, + &php_http_curl_request_datashare_ops + }; + +#ifdef PHP_HTTP_NEED_OPENSSL_TSL + /* mod_ssl, libpq or ext/curl might already have set thread lock callbacks */ + if (!CRYPTO_get_id_callback()) { + int i, c = CRYPTO_num_locks(); + + php_http_openssl_tsl = malloc(c * sizeof(MUTEX_T)); + + for (i = 0; i < c; ++i) { + php_http_openssl_tsl[i] = tsrm_mutex_alloc(); + } + + CRYPTO_set_id_callback(php_http_openssl_thread_id); + CRYPTO_set_locking_callback(php_http_openssl_thread_lock); + } +#endif +#ifdef PHP_HTTP_NEED_GNUTLS_TSL + gcry_control(GCRYCTL_SET_THREAD_CBS, &php_http_gnutls_tsl); +#endif + + if (CURLE_OK != curl_global_init(CURL_GLOBAL_ALL)) { + return FAILURE; + } + + if (SUCCESS != php_http_persistent_handle_provide(ZEND_STRL("http_request_datashare.curl"), curl_share_init, (php_http_persistent_handle_dtor_t) curl_share_cleanup, NULL TSRMLS_CC)) { + return FAILURE; + } + + if (SUCCESS != php_http_persistent_handle_provide(ZEND_STRL("http_request_pool.curl"), curl_multi_init, (php_http_persistent_handle_dtor_t) curl_multi_cleanup, NULL TSRMLS_CC)) { + return FAILURE; + } + + if (SUCCESS != php_http_persistent_handle_provide(ZEND_STRL("http_request.curl"), safe_curl_init, safe_curl_dtor, safe_curl_copy)) { + return FAILURE; + } + + if (SUCCESS != php_http_request_factory_add_driver(ZEND_STRL("curl"), &driver)) { + return FAILURE; + } + + /* + * HTTP Protocol Version Constants + */ + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("VERSION_1_0"), CURL_HTTP_VERSION_1_0 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("VERSION_1_1"), CURL_HTTP_VERSION_1_1 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("VERSION_NONE"), CURL_HTTP_VERSION_NONE TSRMLS_CC); /* to be removed */ + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("VERSION_ANY"), CURL_HTTP_VERSION_NONE TSRMLS_CC); + + /* + * SSL Version Constants + */ + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("SSL_VERSION_TLSv1"), CURL_SSLVERSION_TLSv1 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("SSL_VERSION_SSLv2"), CURL_SSLVERSION_SSLv2 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("SSL_VERSION_SSLv3"), CURL_SSLVERSION_SSLv3 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("SSL_VERSION_ANY"), CURL_SSLVERSION_DEFAULT TSRMLS_CC); + + /* + * DNS IPvX resolving + */ + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("IPRESOLVE_V4"), CURL_IPRESOLVE_V4 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("IPRESOLVE_V6"), CURL_IPRESOLVE_V6 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("IPRESOLVE_ANY"), CURL_IPRESOLVE_WHATEVER TSRMLS_CC); + + /* + * Auth Constants + */ + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_BASIC"), CURLAUTH_BASIC TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_DIGEST"), CURLAUTH_DIGEST TSRMLS_CC); +#if PHP_HTTP_CURL_VERSION(7,19,3) + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_DIGEST_IE"), CURLAUTH_DIGEST_IE TSRMLS_CC); +#endif + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_NTLM"), CURLAUTH_NTLM TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_GSSNEG"), CURLAUTH_GSSNEGOTIATE TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_ANY"), CURLAUTH_ANY TSRMLS_CC); + + /* + * Proxy Type Constants + */ + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS4"), CURLPROXY_SOCKS4 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS4A"), CURLPROXY_SOCKS5 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS5_HOSTNAME"), CURLPROXY_SOCKS5 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS5"), CURLPROXY_SOCKS5 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_HTTP"), CURLPROXY_HTTP TSRMLS_CC); +# if PHP_HTTP_CURL_VERSION(7,19,4) + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_HTTP_1_0"), CURLPROXY_HTTP_1_0 TSRMLS_CC); +# endif + + /* + * Post Redirection Constants + */ +#if PHP_HTTP_CURL_VERSION(7,19,1) + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("POSTREDIR_301"), CURL_REDIR_POST_301 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("POSTREDIR_302"), CURL_REDIR_POST_302 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("POSTREDIR_ALL"), CURL_REDIR_POST_ALL TSRMLS_CC); +#endif + + return SUCCESS; +} + +PHP_MSHUTDOWN_FUNCTION(http_curl) +{ + curl_global_cleanup(); +#ifdef PHP_HTTP_NEED_OPENSSL_TSL + if (php_http_openssl_tsl) { + int i, c = CRYPTO_num_locks(); + + CRYPTO_set_id_callback(NULL); + CRYPTO_set_locking_callback(NULL); + + for (i = 0; i < c; ++i) { + tsrm_mutex_free(php_http_openssl_tsl[i]); + } + + free(php_http_openssl_tsl); + php_http_openssl_tsl = NULL; + } +#endif + return SUCCESS; +} + +PHP_RINIT_FUNCTION(http_curl) +{ +#ifdef PHP_HTTP_HAVE_EVENT + if (!PHP_HTTP_G->request_pool.event_base && !(PHP_HTTP_G->request_pool.event_base = event_init())) { + return FAILURE; + } +#endif + + return SUCCESS; +} diff --git a/php_http_curl.h b/php_http_curl.h new file mode 100644 index 0000000..89f1948 --- /dev/null +++ b/php_http_curl.h @@ -0,0 +1,18 @@ +#ifndef PHP_HTTP_CURL_H +#define PHP_HTTP_CURL_H + +PHP_HTTP_API php_http_request_ops_t *php_http_curl_get_request_ops(void); +PHP_HTTP_API php_http_request_pool_ops_t *php_http_curl_get_request_pool_ops(void); +PHP_HTTP_API php_http_request_datashare_ops_t *php_http_curl_get_request_datashare_ops(void); + +extern PHP_MINIT_FUNCTION(http_curl); +extern PHP_MSHUTDOWN_FUNCTION(http_curl); +extern PHP_RINIT_FUNCTION(http_curl); + +#ifdef PHP_HTTP_HAVE_EVENT +struct php_http_request_pool_globals { + void *event_base; +}; +#endif + +#endif diff --git a/php_http_encoding.c b/php_http_encoding.c index 07a026d..93712c7 100644 --- a/php_http_encoding.c +++ b/php_http_encoding.c @@ -486,7 +486,7 @@ static STATUS inflate_update(php_http_encoding_stream_t *s, const char *data, si /* append input to buffer */ php_http_buffer_append(PHP_HTTP_BUFFER(ctx->opaque), data, data_len); - + retry_raw_inflate: ctx->next_in = (Bytef *) PHP_HTTP_BUFFER_VAL(ctx->opaque); ctx->avail_in = PHP_HTTP_BUFFER_LEN(ctx->opaque); diff --git a/php_http_exception.c b/php_http_exception.c index da657ac..e132df7 100644 --- a/php_http_exception.c +++ b/php_http_exception.c @@ -27,10 +27,13 @@ zend_class_entry *PHP_HTTP_EX_CE(malformed_headers); zend_class_entry *PHP_HTTP_EX_CE(request_method); zend_class_entry *PHP_HTTP_EX_CE(message); zend_class_entry *PHP_HTTP_EX_CE(message_type); +zend_class_entry *PHP_HTTP_EX_CE(message_body); zend_class_entry *PHP_HTTP_EX_CE(invalid_param); zend_class_entry *PHP_HTTP_EX_CE(encoding); zend_class_entry *PHP_HTTP_EX_CE(request); zend_class_entry *PHP_HTTP_EX_CE(request_pool); +zend_class_entry *PHP_HTTP_EX_CE(request_datashare); +zend_class_entry *PHP_HTTP_EX_CE(request_factory); zend_class_entry *PHP_HTTP_EX_CE(socket); zend_class_entry *PHP_HTTP_EX_CE(response); zend_class_entry *PHP_HTTP_EX_CE(url); @@ -64,12 +67,15 @@ PHP_MINIT_FUNCTION(http_exception) PHP_HTTP_REGISTER_EXCEPTION(RequestMethodException, PHP_HTTP_EX_CE(request_method), PHP_HTTP_EX_DEF_CE); PHP_HTTP_REGISTER_EXCEPTION(MessageException, PHP_HTTP_EX_CE(message), PHP_HTTP_EX_DEF_CE); PHP_HTTP_REGISTER_EXCEPTION(MessageTypeException, PHP_HTTP_EX_CE(message_type), PHP_HTTP_EX_DEF_CE); + PHP_HTTP_REGISTER_EXCEPTION(MessageBodyException, PHP_HTTP_EX_CE(message_body), PHP_HTTP_EX_DEF_CE); PHP_HTTP_REGISTER_EXCEPTION(EncodingException, PHP_HTTP_EX_CE(encoding), PHP_HTTP_EX_DEF_CE); PHP_HTTP_REGISTER_EXCEPTION(RequestException, PHP_HTTP_EX_CE(request), PHP_HTTP_EX_DEF_CE); zend_declare_property_long(PHP_HTTP_EX_CE(request), "curlCode", lenof("curlCode"), 0, ZEND_ACC_PUBLIC TSRMLS_CC); PHP_HTTP_REGISTER_EXCEPTION(RequestPoolException, PHP_HTTP_EX_CE(request_pool), PHP_HTTP_EX_DEF_CE); + PHP_HTTP_REGISTER_EXCEPTION(RequestDataShareException, PHP_HTTP_EX_CE(request_datashare), PHP_HTTP_EX_DEF_CE); + PHP_HTTP_REGISTER_EXCEPTION(RequestFactoryException, PHP_HTTP_EX_CE(request_factory), PHP_HTTP_EX_DEF_CE); PHP_HTTP_REGISTER_EXCEPTION(SocketException, PHP_HTTP_EX_CE(socket), PHP_HTTP_EX_DEF_CE); PHP_HTTP_REGISTER_EXCEPTION(ResponseException, PHP_HTTP_EX_CE(response), PHP_HTTP_EX_DEF_CE); PHP_HTTP_REGISTER_EXCEPTION(UrlException, PHP_HTTP_EX_CE(url), PHP_HTTP_EX_DEF_CE); @@ -100,9 +106,12 @@ zend_class_entry *php_http_exception_get_for_code(long code) case PHP_HTTP_E_REQUEST_METHOD: ex = PHP_HTTP_EX_CE(request_method); break; case PHP_HTTP_E_MESSAGE: ex = PHP_HTTP_EX_CE(message); break; case PHP_HTTP_E_MESSAGE_TYPE: ex = PHP_HTTP_EX_CE(message_type); break; + case PHP_HTTP_E_MESSAGE_BODY: ex = PHP_HTTP_EX_CE(message_body); break; case PHP_HTTP_E_ENCODING: ex = PHP_HTTP_EX_CE(encoding); break; case PHP_HTTP_E_REQUEST: ex = PHP_HTTP_EX_CE(request); break; case PHP_HTTP_E_REQUEST_POOL: ex = PHP_HTTP_EX_CE(request_pool); break; + case PHP_HTTP_E_REQUEST_DATASHARE: ex = PHP_HTTP_EX_CE(request_datashare); break; + case PHP_HTTP_E_REQUEST_FACTORY: ex = PHP_HTTP_EX_CE(request_factory); break; case PHP_HTTP_E_SOCKET: ex = PHP_HTTP_EX_CE(socket); break; case PHP_HTTP_E_RESPONSE: ex = PHP_HTTP_EX_CE(response); break; case PHP_HTTP_E_URL: ex = PHP_HTTP_EX_CE(url); break; diff --git a/php_http_exception.h b/php_http_exception.h index 1881190..73c7c6d 100644 --- a/php_http_exception.h +++ b/php_http_exception.h @@ -31,6 +31,8 @@ extern zend_class_entry *PHP_HTTP_EX_CE(invalid_param); extern zend_class_entry *PHP_HTTP_EX_CE(encoding); extern zend_class_entry *PHP_HTTP_EX_CE(request); extern zend_class_entry *PHP_HTTP_EX_CE(request_pool); +extern zend_class_entry *PHP_HTTP_EX_CE(request_datashare); +extern zend_class_entry *PHP_HTTP_EX_CE(request_factory); extern zend_class_entry *PHP_HTTP_EX_CE(socket); extern zend_class_entry *PHP_HTTP_EX_CE(response); extern zend_class_entry *PHP_HTTP_EX_CE(url); diff --git a/php_http_fluently_callable.c b/php_http_fluently_callable.c new file mode 100644 index 0000000..2f674b8 --- /dev/null +++ b/php_http_fluently_callable.c @@ -0,0 +1,13 @@ + +#include "php_http.h" + +zend_class_entry *php_http_fluently_callable_class_entry; +zend_function_entry php_http_fluently_callable_method_entry[] = { + EMPTY_FUNCTION_ENTRY +}; + +PHP_MINIT_FUNCTION(http_fluently_callable) +{ + PHP_HTTP_REGISTER_INTERFACE(http, FluentlyCallable, http_fluently_callable, 0); + return SUCCESS; +} diff --git a/php_http_fluently_callable.h b/php_http_fluently_callable.h new file mode 100644 index 0000000..9b4650f --- /dev/null +++ b/php_http_fluently_callable.h @@ -0,0 +1,9 @@ +#ifndef PHP_HTTP_FLUENTLY_CALLABLE_H +#define PHP_HTTP_FLUENTLY_CALLABLE_H + +extern zend_class_entry *php_http_fluently_callable_class_entry; +extern zend_function_entry php_http_fluently_callable_method_entry[]; + +extern PHP_MINIT_FUNCTION(http_fluently_callable); + +#endif /* PHP_HTTP_FLUENTLY_CALLABLE_H */ diff --git a/php_http_header_parser.c b/php_http_header_parser.c index 07bcab5..69a4191 100644 --- a/php_http_header_parser.c +++ b/php_http_header_parser.c @@ -89,9 +89,8 @@ PHP_HTTP_API STATUS php_http_header_parser_parse(php_http_header_parser_t *parse while (buffer->used || !php_http_header_parser_states[php_http_header_parser_state_is(parser)].need_data) { #if 0 const char *state[] = {"START", "KEY", "VALUE", "HEADER_DONE", "DONE"}; - fprintf(stderr, "#HP-%p: %s (%d) %.*s…\n", parser, - php_http_header_parser_state_is(parser)<0?"FAILURE":state[php_http_header_parser_state_is(parser)], - zend_hash_num_elements(headers), MIN(16,buffer->used), buffer->data); + fprintf(stderr, "#HP: %s (%d)\n", php_http_header_parser_state_is(parser) < 0 ? "FAILURE" : state[php_http_header_parser_state_is(parser)], zend_hash_num_elements(headers)); + _dpf(0, buffer->data, buffer->used); #endif switch (php_http_header_parser_state_pop(parser)) { case PHP_HTTP_HEADER_PARSER_STATE_FAILURE: diff --git a/php_http_header_parser.h b/php_http_header_parser.h index 9d6ebcc..0d52930 100644 --- a/php_http_header_parser.h +++ b/php_http_header_parser.h @@ -1,6 +1,8 @@ #ifndef PHP_HTTP_HEADER_PARSER_H #define PHP_HTTP_HEADER_PARSER_H +#include "php_http_info.h" + typedef enum php_http_header_parser_state { PHP_HTTP_HEADER_PARSER_STATE_FAILURE = FAILURE, PHP_HTTP_HEADER_PARSER_STATE_START = 0, diff --git a/php_http_message.c b/php_http_message.c index da0ac7d..76c79ff 100644 --- a/php_http_message.c +++ b/php_http_message.c @@ -225,7 +225,8 @@ static inline void message_headers(php_http_message_t *msg, php_http_buffer_t *s { php_http_array_hashkey_t key = php_http_array_hashkey_init(0); HashPosition pos1; - zval **header; + zval **header, *h; + size_t size; switch (msg->type) { case PHP_HTTP_REQUEST: @@ -240,6 +241,30 @@ static inline void message_headers(php_http_message_t *msg, php_http_buffer_t *s break; } + if ((size = php_http_message_body_size(&msg->body))) { + MAKE_STD_ZVAL(h); + ZVAL_LONG(h, size); + zend_hash_add(&msg->hdrs, "Content-Length", sizeof("Content-Length"), &h, sizeof(zval *), NULL); + + if (msg->body.boundary) { + char *str; + size_t len; + + if (!(h = php_http_message_header(msg, ZEND_STRL("Content-Type"), 1))) { + len = spprintf(&str, 0, "multipart/form-data; boundary=\"%s\"", msg->body.boundary); + MAKE_STD_ZVAL(h); + ZVAL_STRINGL(h, str, len, 0); + zend_hash_update(&msg->hdrs, "Content-Type", sizeof("Content-Type"), &h, sizeof(zval *), NULL); + } else if (!php_http_match(Z_STRVAL_P(h), "boundary=", PHP_HTTP_MATCH_WORD)) { + zval_dtor(h); + Z_STRLEN_P(h) = spprintf(&Z_STRVAL_P(h), 0, "%s; boundary=\"%s\"", Z_STRVAL_P(h), msg->body.boundary); + zend_hash_update(&msg->hdrs, "Content-Type", sizeof("Content-Type"), &h, sizeof(zval *), NULL); + } else { + zval_ptr_dtor(&h); + } + } + } + FOREACH_HASH_KEYVAL(pos1, &msg->hdrs, key, header) { if (key.type == HASH_KEY_IS_STRING) { HashPosition pos2; @@ -916,7 +941,7 @@ PHP_MINIT_FUNCTION(http_message) php_http_message_object_handlers.get_properties = php_http_message_object_get_props; php_http_message_object_handlers.get_property_ptr_ptr = php_http_message_object_get_prop_ptr; - zend_class_implements(php_http_message_class_entry TSRMLS_CC, 3, spl_ce_Countable, zend_ce_serializable, zend_ce_iterator); + zend_class_implements(php_http_message_class_entry TSRMLS_CC, 3, spl_ce_Countable, zend_ce_serializable, zend_ce_iterator, php_http_fluently_callable_class_entry); zend_hash_init(&php_http_message_object_prophandlers, 9, NULL, NULL, 1); zend_declare_property_long(php_http_message_class_entry, ZEND_STRL("type"), PHP_HTTP_NONE, ZEND_ACC_PROTECTED TSRMLS_CC); @@ -1111,7 +1136,8 @@ void php_http_message_object_free(void *object TSRMLS_DC) } -static zval **php_http_message_object_get_prop_ptr(zval *object, zval *member, const zend_literal *literal_key TSRMLS_DC) { +static zval **php_http_message_object_get_prop_ptr(zval *object, zval *member, const zend_literal *literal_key TSRMLS_DC) +{ php_http_message_object_prophandler_t *handler; zval *copy = php_http_zsep(IS_STRING, member); @@ -1308,12 +1334,11 @@ PHP_METHOD(HttpMessage, setBody) } php_http_message_body_dtor(&obj->message->body); - php_http_message_body_init(&obj->message->body, php_http_message_body_stream(body_obj->body)); + php_http_message_body_copy(body_obj->body, &obj->message->body, 0); Z_OBJ_ADDREF_P(zbody); obj->body = Z_OBJVAL_P(zbody); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, getHeader) @@ -1365,15 +1390,14 @@ PHP_METHOD(HttpMessage, setHeader) } if (!zvalue) { - RETVAL_SUCCESS(zend_hash_del(&obj->message->hdrs, name, name_len + 1)); + zend_hash_del(&obj->message->hdrs, name, name_len + 1); } else { Z_ADDREF_P(zvalue); - RETVAL_SUCCESS(zend_hash_update(&obj->message->hdrs, name, name_len + 1, &zvalue, sizeof(void *), NULL)); + zend_hash_update(&obj->message->hdrs, name, name_len + 1, &zvalue, sizeof(void *), NULL); } efree(name); - return; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, setHeaders) @@ -1391,9 +1415,8 @@ PHP_METHOD(HttpMessage, setHeaders) if (new_headers) { array_join(Z_ARRVAL_P(new_headers), &obj->message->hdrs, 0, ARRAY_JOIN_PRETTIFY|ARRAY_JOIN_STRONLY); } - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, addHeader) @@ -1414,14 +1437,13 @@ PHP_METHOD(HttpMessage, addHeader) Z_ADDREF_P(zvalue); if ((header = php_http_message_header(obj->message, name, name_len, 0))) { convert_to_array(header); - RETVAL_SUCCESS(zend_hash_next_index_insert(Z_ARRVAL_P(header), &zvalue, sizeof(void *), NULL)); + zend_hash_next_index_insert(Z_ARRVAL_P(header), &zvalue, sizeof(void *), NULL); } else { - RETVAL_SUCCESS(zend_hash_update(&obj->message->hdrs, name, name_len + 1, &zvalue, sizeof(void *), NULL)); + zend_hash_update(&obj->message->hdrs, name, name_len + 1, &zvalue, sizeof(void *), NULL); } efree(name); - return; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, addHeaders) @@ -1437,9 +1459,8 @@ PHP_METHOD(HttpMessage, addHeaders) } array_join(Z_ARRVAL_P(new_headers), &obj->message->hdrs, append, ARRAY_JOIN_STRONLY|ARRAY_JOIN_PRETTIFY); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, getType) @@ -1467,9 +1488,8 @@ PHP_METHOD(HttpMessage, setType) } php_http_message_set_type(obj->message, type); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, getInfo) @@ -1514,9 +1534,8 @@ PHP_METHOD(HttpMessage, setInfo) php_http_message_set_info(obj->message, &inf); php_http_info_dtor(&inf); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, getHttpVersion) @@ -1552,10 +1571,9 @@ PHP_METHOD(HttpMessage, setHttpVersion) if (php_http_version_parse(&version, v_str TSRMLS_CC)) { obj->message->http.version = version; - RETURN_TRUE; } } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, getResponseCode) @@ -1592,10 +1610,8 @@ PHP_METHOD(HttpMessage, setResponseCode) } obj->message->http.info.response.code = code; - RETURN_TRUE; } - - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, getResponseStatus) @@ -1632,10 +1648,8 @@ PHP_METHOD(HttpMessage, setResponseStatus) PHP_HTTP_MESSAGE_TYPE_CHECK(RESPONSE, obj->message, RETURN_FALSE); STR_SET(obj->message->http.info.response.status, estrndup(status, status_len)); - RETURN_TRUE; } - - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, getRequestMethod) @@ -1677,10 +1691,8 @@ PHP_METHOD(HttpMessage, setRequestMethod) } STR_SET(obj->message->http.info.request.method, estrndup(method, method_len)); - RETURN_TRUE; } - - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpMessage, getRequestUrl) @@ -1721,10 +1733,8 @@ PHP_METHOD(HttpMessage, setRequestUrl) RETURN_FALSE; } STR_SET(obj->message->http.info.request.url, estrndup(url_str, url_len)); - RETURN_TRUE; } - - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } diff --git a/php_http_message_body.c b/php_http_message_body.c index 969f860..783e76d 100644 --- a/php_http_message_body.c +++ b/php_http_message_body.c @@ -14,25 +14,39 @@ #include "php_http.h" -typedef struct curl_httppost *post_data[2]; - -static inline STATUS add_field(php_http_message_body_t *body, const char *name, const char *value_str, size_t value_len); -static inline STATUS add_file(php_http_message_body_t *body, const char *name, const char *path, const char *ctype); -static STATUS recursive_fields(post_data http_post_data, HashTable *fields, const char *prefix TSRMLS_DC); -static STATUS recursive_files(post_data http_post_data, HashTable *files, const char *prefix TSRMLS_DC); +#include +#include +#include + +#define BOUNDARY_OPEN(body) \ + do {\ + size_t size = php_http_message_body_size(body); \ + if (size) { \ + php_stream_truncate_set_size(php_http_message_body_stream(body), size - lenof("--" PHP_HTTP_CRLF)); \ + php_http_message_body_append(body, ZEND_STRL(PHP_HTTP_CRLF)); \ + } else { \ + php_http_message_body_appendf(body, "--%s" PHP_HTTP_CRLF, php_http_message_body_boundary(body)); \ + } \ + } while(0) +#define BOUNDARY_CLOSE(body) \ + php_http_message_body_appendf(body, PHP_HTTP_CRLF "--%s--" PHP_HTTP_CRLF, php_http_message_body_boundary(body)) + +static STATUS add_recursive_fields(php_http_message_body_t *body, const char *name, zval *value); +static STATUS add_recursive_files(php_http_message_body_t *body, const char *name, zval *value); PHP_HTTP_API php_http_message_body_t *php_http_message_body_init(php_http_message_body_t *body, php_stream *stream TSRMLS_DC) { if (!body) { body = emalloc(sizeof(php_http_message_body_t)); } + memset(body, 0, sizeof(*body)); if (stream) { php_stream_auto_cleanup(stream); body->stream_id = php_stream_get_resource_id(stream); zend_list_addref(body->stream_id); } else { - stream = php_stream_temp_new(); + stream = php_stream_temp_create(TEMP_STREAM_DEFAULT, 0xffff); php_stream_auto_cleanup(stream); body->stream_id = php_stream_get_resource_id(stream); } @@ -55,16 +69,19 @@ PHP_HTTP_API php_http_message_body_t *php_http_message_body_copy(php_http_messag to = php_http_message_body_init(to, php_http_message_body_stream(from) TSRMLS_CC); } + if (from->boundary) { + to->boundary = estrdup(from->boundary); + } + return to; } } PHP_HTTP_API void php_http_message_body_dtor(php_http_message_body_t *body) { - if (body) { - /* NO FIXME: shows leakinfo in DEBUG mode */ - zend_list_delete(body->stream_id); - } + /* NO FIXME: shows leakinfo in DEBUG mode */ + zend_list_delete(body->stream_id); + STR_FREE(body->boundary); } PHP_HTTP_API void php_http_message_body_free(php_http_message_body_t **body) @@ -83,6 +100,18 @@ PHP_HTTP_API php_stream_statbuf *php_http_message_body_stat(php_http_message_bod return &body->ssb; } +PHP_HTTP_API const char *php_http_message_body_boundary(php_http_message_body_t *body) +{ + if (!body->boundary) { + union { double dbl; int num[2]; } data; + TSRMLS_FETCH_FROM_CTX(body->ts); + + data.dbl = php_combined_lcg(TSRMLS_C); + spprintf(&body->boundary, 0, "%x.%x", data.num[0], data.num[1]); + } + return body->boundary; +} + PHP_HTTP_API char *php_http_message_body_etag(php_http_message_body_t *body) { TSRMLS_FETCH_FROM_CTX(body->ts); @@ -154,87 +183,114 @@ PHP_HTTP_API void php_http_message_body_to_callback(php_http_message_body_t *bod } } -PHP_HTTP_API STATUS php_http_message_body_to_callback_in_chunks(php_http_message_body_t *body, php_http_pass_callback_t cb, void *cb_arg, HashTable *chunks) +PHP_HTTP_API size_t php_http_message_body_append(php_http_message_body_t *body, const char *buf, size_t len) { + php_stream *s; TSRMLS_FETCH_FROM_CTX(body->ts); - php_stream *s = php_http_message_body_stream(body); - HashPosition pos; - zval **chunk; - - FOREACH_HASH_VAL(pos, chunks, chunk) { - zval **begin, **end; - - if (IS_ARRAY == Z_TYPE_PP(chunk) - && SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(chunk), 0, (void *) &begin) - && IS_LONG == Z_TYPE_PP(begin) - && SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(chunk), 1, (void *) &end) - && IS_LONG == Z_TYPE_PP(end) - ) { - if (SUCCESS != php_stream_seek(s, Z_LVAL_PP(begin), SEEK_SET)) { - return FAILURE; - } else { - long length = Z_LVAL_PP(end) - Z_LVAL_PP(begin) + 1; - - while (length > 0 && !php_stream_eof(s)) { - char buf[0x1000]; - size_t read = php_stream_read(s, buf, MIN(length, sizeof(buf))); - - if (read) { - cb(cb_arg, buf, read); - } - - if (read < MIN(length, sizeof(buf))) { - break; - } - - length -= read; - } - } - } - } - return SUCCESS; + s = php_http_message_body_stream(body); + php_stream_seek(s, 0, SEEK_END); + return php_stream_write(s, buf, len); } -PHP_HTTP_API size_t php_http_message_body_append(php_http_message_body_t *body, const char *buf, size_t len) +PHP_HTTP_API size_t php_http_message_body_appendf(php_http_message_body_t *body, const char *fmt, ...) { - TSRMLS_FETCH_FROM_CTX(body->ts); - php_stream *s = php_http_message_body_stream(body); + va_list argv; + char *print_str; + size_t print_len; - php_stream_seek(s, 0, SEEK_END); - return php_stream_write(s, buf, len); + va_start(argv, fmt); + print_len = vspprintf(&print_str, 0, fmt, argv); + va_end(argv); + + print_len = php_http_message_body_append(body, print_str, print_len); + efree(print_str); + + return print_len; } PHP_HTTP_API STATUS php_http_message_body_add(php_http_message_body_t *body, HashTable *fields, HashTable *files) { - post_data http_post_data = {NULL, NULL}; + zval tmp; TSRMLS_FETCH_FROM_CTX(body->ts); - if (fields && SUCCESS != recursive_fields(http_post_data, fields, NULL TSRMLS_CC)) { - return FAILURE; - } - if (files && (zend_hash_num_elements(files) > 0) && (SUCCESS != recursive_files(http_post_data, files, NULL TSRMLS_CC))) { - return FAILURE; + if (fields) { + INIT_PZVAL_ARRAY(&tmp, fields); + if (SUCCESS != add_recursive_fields(body, NULL, &tmp)) { + return FAILURE; + } } - if (CURLE_OK != curl_formget(http_post_data[0], body, (curl_formget_callback) php_http_message_body_append)) { - return FAILURE; + if (files) { + INIT_PZVAL_ARRAY(&tmp, files); + if (SUCCESS != add_recursive_files(body, NULL, &tmp)) { + return FAILURE; + } } + return SUCCESS; } + PHP_HTTP_API STATUS php_http_message_body_add_field(php_http_message_body_t *body, const char *name, const char *value_str, size_t value_len) { - return add_field(body, name, value_str, value_len); + char *safe_name = php_addslashes(estrdup(name), strlen(name), NULL, 1 TSRMLS_CC); + + BOUNDARY_OPEN(body); + php_http_message_body_appendf( + body, + "Content-Disposition: form-data; name=\"%s\"" PHP_HTTP_CRLF + "" PHP_HTTP_CRLF, + safe_name); + php_http_message_body_append(body, value_str, value_len); + BOUNDARY_CLOSE(body); + + efree(safe_name); + return SUCCESS; } PHP_HTTP_API STATUS php_http_message_body_add_file(php_http_message_body_t *body, const char *name, const char *path, const char *ctype) { - return add_file(body, name, path, ctype); + php_stream *in; + char *path_dup = estrdup(path); + TSRMLS_FETCH_FROM_CTX(body->ts); + + if ((in = php_stream_open_wrapper(path_dup, "r", REPORT_ERRORS|USE_PATH|STREAM_MUST_SEEK, NULL))) { + php_stream_statbuf ssb = {{0}}; + + if (SUCCESS == php_stream_stat(in, &ssb) && S_ISREG(ssb.sb.st_mode)) { + char *safe_name = php_addslashes(estrdup(name), strlen(name), NULL, 1 TSRMLS_CC); + + BOUNDARY_OPEN(body); + php_http_message_body_appendf( + body, + "Content-Disposition: attachment; name=\"%s\"; filename=\"%s\"" PHP_HTTP_CRLF + "Content-Type: %s" PHP_HTTP_CRLF + "Content-Length: %zu" PHP_HTTP_CRLF + "" PHP_HTTP_CRLF, + safe_name, basename(path_dup), ctype, ssb.sb.st_size); + php_stream_copy_to_stream_ex(in, php_http_message_body_stream(body), PHP_STREAM_COPY_ALL, NULL); + BOUNDARY_CLOSE(body); + + efree(safe_name); + efree(path_dup); + php_stream_close(in); + return SUCCESS; + } else { + efree(path_dup); + php_stream_close(in); + php_http_error(HE_WARNING, PHP_HTTP_E_MESSAGE_BODY, "Not a valid regular file: %s", path); + return FAILURE; + } + } else { + efree(path_dup); + return FAILURE; + } + } -static inline char *format_key(uint type, char *str, ulong num, const char *prefix, int numeric_key_for_empty_prefix) { +static inline char *format_key(uint type, char *str, ulong num, const char *prefix) { char *new_key = NULL; - + if (prefix && *prefix) { if (type == HASH_KEY_IS_STRING) { spprintf(&new_key, 0, "%s[%s]", prefix, str); @@ -243,223 +299,88 @@ static inline char *format_key(uint type, char *str, ulong num, const char *pref } } else if (type == HASH_KEY_IS_STRING) { new_key = estrdup(str); - } else if (numeric_key_for_empty_prefix) { + } else { spprintf(&new_key, 0, "%lu", num); } - + return new_key; } -static inline STATUS add_field(php_http_message_body_t *body, const char *name, const char *value_str, size_t value_len) +static STATUS add_recursive_fields(php_http_message_body_t *body, const char *name, zval *value) { - post_data http_post_data = {NULL, NULL}; - CURLcode err; - - err = curl_formadd(&http_post_data[0], &http_post_data[1], - CURLFORM_COPYNAME, name, - CURLFORM_COPYCONTENTS, value_str, - CURLFORM_CONTENTSLENGTH, (long) value_len, - CURLFORM_END - ); - - if (CURLE_OK != err) { - return FAILURE; - } - - err = curl_formget(http_post_data[0], body, (curl_formget_callback) php_http_message_body_append); - - if (CURLE_OK != err) { - curl_formfree(http_post_data[0]); - return FAILURE; + if (Z_TYPE_P(value) == IS_ARRAY || Z_TYPE_P(value) == IS_OBJECT) { + zval **val; + HashPosition pos; + php_http_array_hashkey_t key = php_http_array_hashkey_init(0); + + if (!HASH_OF(value)->nApplyCount) { + ++HASH_OF(value)->nApplyCount; + FOREACH_KEYVAL(pos, value, key, val) { + char *str = format_key(key.type, key.str, key.num, name); + if (SUCCESS != add_recursive_fields(body, str, *val)) { + efree(str); + HASH_OF(value)->nApplyCount--; + return FAILURE; + } + efree(str); + } + --HASH_OF(value)->nApplyCount; + } + } else { + zval *cpy = php_http_zsep(IS_STRING, value); + php_http_message_body_add_field(body, name, Z_STRVAL_P(cpy), Z_STRLEN_P(cpy)); + zval_ptr_dtor(&cpy); } - curl_formfree(http_post_data[0]); return SUCCESS; } -static inline STATUS add_file(php_http_message_body_t *body, const char *name, const char *path, const char *ctype) +static STATUS add_recursive_files(php_http_message_body_t *body, const char *name, zval *value) { - post_data http_post_data = {NULL, NULL}; - CURLcode err; - - err = curl_formadd(&http_post_data[0], &http_post_data[1], - CURLFORM_COPYNAME, name, - CURLFORM_FILE, path, - CURLFORM_CONTENTTYPE, ctype ? ctype : "application/octet-stream", - CURLFORM_END - ); - - if (CURLE_OK != err) { - return FAILURE; - } + if (Z_TYPE_P(value) == IS_ARRAY || Z_TYPE_P(value) == IS_OBJECT) { + zval **zfile, **zname, **ztype; - err = curl_formget(http_post_data[0], body, (curl_formget_callback) php_http_message_body_append); - - if (CURLE_OK != err) { - curl_formfree(http_post_data[0]); - return FAILURE; - } + if ((SUCCESS == zend_hash_find(HASH_OF(value), ZEND_STRS("name"), (void *) &zname)) + && (SUCCESS == zend_hash_find(HASH_OF(value), ZEND_STRS("file"), (void *) &zfile)) + && (SUCCESS == zend_hash_find(HASH_OF(value), ZEND_STRS("type"), (void *) &ztype)) + ) { + zval *zfc = php_http_zsep(IS_STRING, *zfile), *znc = php_http_zsep(IS_STRING, *zname), *ztc = php_http_zsep(IS_STRING, *ztype); + char *str = format_key(HASH_KEY_IS_STRING, Z_STRVAL_P(znc), 0, name); + STATUS ret = php_http_message_body_add_file(body, str, Z_STRVAL_P(zfc), Z_STRVAL_P(ztc)); - curl_formfree(http_post_data[0]); - return SUCCESS; -} + efree(str); + zval_ptr_dtor(&znc); + zval_ptr_dtor(&zfc); + zval_ptr_dtor(&ztc); -static STATUS recursive_fields(post_data http_post_data, HashTable *fields, const char *prefix TSRMLS_DC) { - php_http_array_hashkey_t key = php_http_array_hashkey_init(0); - zval **data_ptr; - HashPosition pos; - char *new_key = NULL; - CURLcode err = 0; - - if (fields && !fields->nApplyCount) { - FOREACH_HASH_KEYVAL(pos, fields, key, data_ptr) { - if (key.type != HASH_KEY_IS_STRING || *key.str) { - new_key = format_key(key.type, key.str, key.num, prefix, 1); - - switch (Z_TYPE_PP(data_ptr)) { - case IS_ARRAY: - case IS_OBJECT: { - STATUS status; - - ++fields->nApplyCount; - status = recursive_fields(http_post_data, HASH_OF(*data_ptr), new_key TSRMLS_CC); - --fields->nApplyCount; - - if (SUCCESS != status) { - goto error; - } - break; - } - - default: { - zval *data = php_http_zsep(IS_STRING, *data_ptr); - - err = curl_formadd(&http_post_data[0], &http_post_data[1], - CURLFORM_COPYNAME, new_key, - CURLFORM_COPYCONTENTS, Z_STRVAL_P(data), - CURLFORM_CONTENTSLENGTH, (long) Z_STRLEN_P(data), - CURLFORM_END - ); - - zval_ptr_dtor(&data); - - if (CURLE_OK != err) { - goto error; - } - break; + if (ret != SUCCESS) { + return ret; + } + } else { + zval **val; + HashPosition pos; + php_http_array_hashkey_t key = php_http_array_hashkey_init(0); + + if (!HASH_OF(value)->nApplyCount) { + ++HASH_OF(value)->nApplyCount; + FOREACH_KEYVAL(pos, value, key, val) { + char *str = format_key(key.type, key.str, key.num, name); + if (SUCCESS != add_recursive_files(body, str, *val)) { + efree(str); + --HASH_OF(value)->nApplyCount; + return FAILURE; } + efree(str); } - STR_FREE(new_key); + --HASH_OF(value)->nApplyCount; } } - } - - return SUCCESS; - -error: - if (new_key) { - efree(new_key); - } - if (http_post_data[0]) { - curl_formfree(http_post_data[0]); - } - if (err) { - php_http_error(HE_WARNING, PHP_HTTP_E_ENCODING, "Could not encode post fields: %s", curl_easy_strerror(err)); } else { - php_http_error(HE_WARNING, PHP_HTTP_E_ENCODING, "Could not encode post fields: unknown error"); + php_http_error(HE_WARNING, PHP_HTTP_E_MESSAGE_BODY, "Unrecognized array format for message body file to add"); + return FAILURE; } - return FAILURE; -} -static STATUS recursive_files(post_data http_post_data, HashTable *files, const char *prefix TSRMLS_DC) { - php_http_array_hashkey_t key = php_http_array_hashkey_init(0); - zval **data_ptr; - HashPosition pos; - char *new_key = NULL; - CURLcode err = 0; - - if (files && !files->nApplyCount) { - FOREACH_HASH_KEYVAL(pos, files, key, data_ptr) { - zval **file_ptr, **type_ptr, **name_ptr; - - if (key.type != HASH_KEY_IS_STRING || *key.str) { - new_key = format_key(key.type, key.str, key.num, prefix, 0); - - if (Z_TYPE_PP(data_ptr) != IS_ARRAY && Z_TYPE_PP(data_ptr) != IS_OBJECT) { - if (new_key || key.type == HASH_KEY_IS_STRING) { - php_http_error(HE_NOTICE, PHP_HTTP_E_INVALID_PARAM, "Unrecognized type of post file array entry '%s'", new_key ? new_key : key.str); - } else { - php_http_error(HE_NOTICE, PHP_HTTP_E_INVALID_PARAM, "Unrecognized type of post file array entry '%lu'", key.num); - } - } else if ( SUCCESS != zend_hash_find(HASH_OF(*data_ptr), "name", sizeof("name"), (void *) &name_ptr) || - SUCCESS != zend_hash_find(HASH_OF(*data_ptr), "type", sizeof("type"), (void *) &type_ptr) || - SUCCESS != zend_hash_find(HASH_OF(*data_ptr), "file", sizeof("file"), (void *) &file_ptr)) { - STATUS status; - - ++files->nApplyCount; - status = recursive_files(http_post_data, HASH_OF(*data_ptr), new_key TSRMLS_CC); - --files->nApplyCount; - - if (SUCCESS != status) { - goto error; - } - } else { - const char *path; - zval *file = php_http_zsep(IS_STRING, *file_ptr); - zval *type = php_http_zsep(IS_STRING, *type_ptr); - zval *name = php_http_zsep(IS_STRING, *name_ptr); - - if (SUCCESS != php_check_open_basedir(Z_STRVAL_P(file) TSRMLS_CC)) { - goto error; - } - - /* this is blatant but should be sufficient for most cases */ - if (strncasecmp(Z_STRVAL_P(file), "file://", lenof("file://"))) { - path = Z_STRVAL_P(file); - } else { - path = Z_STRVAL_P(file) + lenof("file://"); - } - - if (new_key) { - char *tmp_key = format_key(HASH_KEY_IS_STRING, Z_STRVAL_P(name), 0, new_key, 0); - STR_SET(new_key, tmp_key); - } - - err = curl_formadd(&http_post_data[0], &http_post_data[1], - CURLFORM_COPYNAME, new_key ? new_key : Z_STRVAL_P(name), - CURLFORM_FILE, path, - CURLFORM_CONTENTTYPE, Z_STRVAL_P(type), - CURLFORM_END - ); - - zval_ptr_dtor(&file); - zval_ptr_dtor(&type); - zval_ptr_dtor(&name); - - if (CURLE_OK != err) { - goto error; - } - } - STR_FREE(new_key); - } - } - } - return SUCCESS; - -error: - if (new_key) { - efree(new_key); - } - if (http_post_data[0]) { - curl_formfree(http_post_data[0]); - } - if (err) { - php_http_error(HE_WARNING, PHP_HTTP_E_ENCODING, "Could not encode post files: %s", curl_easy_strerror(err)); - } else { - php_http_error(HE_WARNING, PHP_HTTP_E_ENCODING, "Could not encode post files: unknown error"); - } - return FAILURE; } /* PHP */ @@ -568,18 +489,23 @@ void php_http_message_body_object_free(void *object TSRMLS_DC) PHP_METHOD(HttpMessageBody, __construct) { php_http_message_body_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - zval *zstream; + zval *zstream = NULL; php_stream *stream; with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { - if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstream)) { - php_stream_from_zval(stream, &zstream); + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|r!", &zstream)) { + if (zstream) { + php_stream_from_zval(stream, &zstream); - if (stream) { - if (obj->body) { - php_http_message_body_dtor(obj->body); + if (stream) { + if (obj->body) { + php_http_message_body_dtor(obj->body); + } + obj->body = php_http_message_body_init(obj->body, stream TSRMLS_CC); } - obj->body = php_http_message_body_init(obj->body, stream TSRMLS_CC); + } + if (!obj->body) { + obj->body = php_http_message_body_init(NULL, NULL TSRMLS_CC); } } } end_error_handling(); diff --git a/php_http_message_body.h b/php_http_message_body.h index d253ff6..b687207 100644 --- a/php_http_message_body.h +++ b/php_http_message_body.h @@ -18,6 +18,7 @@ typedef struct php_http_message_body { int stream_id; php_stream_statbuf ssb; + char *boundary; #ifdef ZTS void ***ts; #endif @@ -38,6 +39,7 @@ PHP_HTTP_API php_stream_statbuf *php_http_message_body_stat(php_http_message_bod #define php_http_message_body_size(b) (php_http_message_body_stat((b))->sb.st_size) #define php_http_message_body_mtime(b) (php_http_message_body_stat((b))->sb.st_mtime) PHP_HTTP_API char *php_http_message_body_etag(php_http_message_body_t *body); +PHP_HTTP_API const char *php_http_message_body_boundary(php_http_message_body_t *body); static inline php_stream *php_http_message_body_stream(php_http_message_body_t *body) { diff --git a/php_http_message_parser.c b/php_http_message_parser.c index 2095471..9accc35 100644 --- a/php_http_message_parser.c +++ b/php_http_message_parser.c @@ -101,8 +101,8 @@ PHP_HTTP_API php_http_message_parser_state_t php_http_message_parser_parse(php_h while (buffer->used || !php_http_message_parser_states[php_http_message_parser_state_is(parser)].need_data) { #if 0 const char *state[] = {"START", "HEADER", "HEADER_DONE", "BODY", "BODY_DUMB", "BODY_LENGTH", "BODY_CHUNK", "BODY_DONE", "DONE"}; - fprintf(stderr, "#MP: %s (%d) %.*s…\n", - state[php_http_message_parser_state_is(parser)], (*message)->type, MIN(32, buffer->used), buffer->data); + fprintf(stderr, "#MP: %s (%d)\n", php_http_message_parser_state_is(parser) < 0 ? "FAILURE" : state[php_http_message_parser_state_is(parser)], (*message)->type); + _dpf(0, buffer->data, buffer->used); #endif switch (php_http_message_parser_state_pop(parser)) @@ -163,20 +163,6 @@ PHP_HTTP_API php_http_message_parser_state_t php_http_message_parser_parse(php_h zend_hash_del(&(*message)->hdrs, "Content-Range", sizeof("Content-Range")); } - if ((h = php_http_message_header(*message, ZEND_STRL("Content-Encoding"), 1))) { - if (strstr(Z_STRVAL_P(h), "gzip") || strstr(Z_STRVAL_P(h), "x-gzip") || strstr(Z_STRVAL_P(h), "deflate")) { - if (parser->inflate) { - php_http_encoding_stream_reset(&parser->inflate); - } else { - parser->inflate = php_http_encoding_stream_init(NULL, php_http_encoding_stream_get_inflate_ops(), 0 TSRMLS_CC); - } - zend_hash_update(&(*message)->hdrs, "X-Original-Content-Encoding", sizeof("X-Original-Content-Encoding"), &h, sizeof(zval *), NULL); - zend_hash_del(&(*message)->hdrs, "Content-Encoding", sizeof("Content-Encoding")); - } else { - zval_ptr_dtor(&h); - } - } - /* default */ MAKE_STD_ZVAL(h); ZVAL_LONG(h, 0); @@ -205,58 +191,79 @@ PHP_HTTP_API php_http_message_parser_state_t php_http_message_parser_parse(php_h zval_ptr_dtor(&h_con); } - if (h_te) { - if (strstr(Z_STRVAL_PP(h_te), "chunked")) { - parser->dechunk = php_http_encoding_stream_init(parser->dechunk, php_http_encoding_stream_get_dechunk_ops(), 0 TSRMLS_CC); - php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_BODY_CHUNKED); - break; + if ((h = php_http_message_header(*message, ZEND_STRL("Content-Encoding"), 1))) { + if (php_http_match(Z_STRVAL_P(h), "gzip", PHP_HTTP_MATCH_WORD) + || php_http_match(Z_STRVAL_P(h), "x-gzip", PHP_HTTP_MATCH_WORD) + || php_http_match(Z_STRVAL_P(h), "deflate", PHP_HTTP_MATCH_WORD) + ) { + if (parser->inflate) { + php_http_encoding_stream_reset(&parser->inflate); + } else { + parser->inflate = php_http_encoding_stream_init(NULL, php_http_encoding_stream_get_inflate_ops(), 0 TSRMLS_CC); + } + zend_hash_update(&(*message)->hdrs, "X-Original-Content-Encoding", sizeof("X-Original-Content-Encoding"), &h, sizeof(zval *), NULL); + zend_hash_del(&(*message)->hdrs, "Content-Encoding", sizeof("Content-Encoding")); + } else { + zval_ptr_dtor(&h); } } - if (h_cl) { - char *stop; - - parser->body_length = strtoul(Z_STRVAL_PP(h_cl), &stop, 10); - - if (stop != Z_STRVAL_PP(h_cl)) { - php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_BODY_LENGTH); - break; + if ((flags & PHP_HTTP_MESSAGE_PARSER_DUMB_BODIES)) { + php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_BODY_DUMB); + } else { + if (h_te) { + if (strstr(Z_STRVAL_PP(h_te), "chunked")) { + parser->dechunk = php_http_encoding_stream_init(parser->dechunk, php_http_encoding_stream_get_dechunk_ops(), 0 TSRMLS_CC); + php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_BODY_CHUNKED); + break; + } } - } - if (h_cr) { - ulong total = 0, start = 0, end = 0; + if (h_cl) { + char *stop; - if (!strncasecmp(Z_STRVAL_PP(h_cr), "bytes", lenof("bytes")) - && ( Z_STRVAL_P(h)[lenof("bytes")] == ':' - || Z_STRVAL_P(h)[lenof("bytes")] == ' ' - || Z_STRVAL_P(h)[lenof("bytes")] == '=' - ) - ) { - char *total_at = NULL, *end_at = NULL; - char *start_at = Z_STRVAL_PP(h_cr) + sizeof("bytes"); - - start = strtoul(start_at, &end_at, 10); - if (end_at) { - end = strtoul(end_at + 1, &total_at, 10); - if (total_at && strncmp(total_at + 1, "*", 1)) { - total = strtoul(total_at + 1, NULL, 10); - } + parser->body_length = strtoul(Z_STRVAL_PP(h_cl), &stop, 10); - if (end >= start && (!total || end < total)) { - parser->body_length = end + 1 - start; - php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_BODY_LENGTH); - break; + if (stop != Z_STRVAL_PP(h_cl)) { + php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_BODY_LENGTH); + break; + } + } + + if (h_cr) { + ulong total = 0, start = 0, end = 0; + + if (!strncasecmp(Z_STRVAL_PP(h_cr), "bytes", lenof("bytes")) + && ( Z_STRVAL_P(h)[lenof("bytes")] == ':' + || Z_STRVAL_P(h)[lenof("bytes")] == ' ' + || Z_STRVAL_P(h)[lenof("bytes")] == '=' + ) + ) { + char *total_at = NULL, *end_at = NULL; + char *start_at = Z_STRVAL_PP(h_cr) + sizeof("bytes"); + + start = strtoul(start_at, &end_at, 10); + if (end_at) { + end = strtoul(end_at + 1, &total_at, 10); + if (total_at && strncmp(total_at + 1, "*", 1)) { + total = strtoul(total_at + 1, NULL, 10); + } + + if (end >= start && (!total || end < total)) { + parser->body_length = end + 1 - start; + php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_BODY_LENGTH); + break; + } } } } - } - if ((*message)->type == PHP_HTTP_REQUEST) { - php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_DONE); - } else { - php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_BODY_DUMB); + if ((*message)->type == PHP_HTTP_REQUEST) { + php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_DONE); + } else { + php_http_message_parser_state_push(parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_BODY_DUMB); + } } break; } diff --git a/php_http_message_parser.h b/php_http_message_parser.h index ee6d022..dcde640 100644 --- a/php_http_message_parser.h +++ b/php_http_message_parser.h @@ -2,6 +2,10 @@ #ifndef PHP_HTTP_MESSAGE_PARSER_H #define PHP_HTTP_MESSAGE_PARSER_H +#include "php_http_header_parser.h" +#include "php_http_encoding.h" +#include "php_http_message.h" + typedef enum php_http_message_parser_state { PHP_HTTP_MESSAGE_PARSER_STATE_FAILURE = FAILURE, PHP_HTTP_MESSAGE_PARSER_STATE_START = 0, @@ -16,7 +20,8 @@ typedef enum php_http_message_parser_state { } php_http_message_parser_state_t; #define PHP_HTTP_MESSAGE_PARSER_CLEANUP 0x1 -#define PHP_HTTP_MESSAGE_PARSER_EMPTY_REDIRECTS 0x2 +#define PHP_HTTP_MESSAGE_PARSER_DUMB_BODIES 0x2 +#define PHP_HTTP_MESSAGE_PARSER_EMPTY_REDIRECTS 0x4 typedef struct php_http_message_parser { php_http_header_parser_t header; diff --git a/php_http_misc.h b/php_http_misc.h index 1cac48b..7e59530 100644 --- a/php_http_misc.h +++ b/php_http_misc.h @@ -275,6 +275,15 @@ static inline zval *php_http_zsep(int type, zval *z) php_ ##name## _class_entry->ce_flags |= flags; \ } +#define PHP_HTTP_REGISTER_INTERFACE(ns, ifacename, name, flags) \ + { \ + zend_class_entry ce; \ + memset(&ce, 0, sizeof(zend_class_entry)); \ + INIT_NS_CLASS_ENTRY(ce, #ns, #ifacename, php_ ##name## _method_entry); \ + php_ ##name## _class_entry = zend_register_internal_interface(&ce TSRMLS_CC); \ + php_ ##name## _class_entry->ce_flags |= flags; \ + } + #define PHP_HTTP_REGISTER_EXCEPTION(classname, cename, parent) \ { \ zend_class_entry ce; \ @@ -343,19 +352,19 @@ typedef struct php_http_array_hashkey { } php_http_array_hashkey_t; #define php_http_array_hashkey_init(dup) {NULL, 0, 0, (dup), 0} -#define FOREACH_VAL(pos, array, val) FOREACH_HASH_VAL(pos, Z_ARRVAL_P(array), val) +#define FOREACH_VAL(pos, array, val) FOREACH_HASH_VAL(pos, HASH_OF(array), val) #define FOREACH_HASH_VAL(pos, hash, val) \ for ( zend_hash_internal_pointer_reset_ex(hash, &pos); \ zend_hash_get_current_data_ex(hash, (void *) &val, &pos) == SUCCESS; \ zend_hash_move_forward_ex(hash, &pos)) -#define FOREACH_KEY(pos, array, key) FOREACH_HASH_KEY(pos, Z_ARRVAL_P(array), key) +#define FOREACH_KEY(pos, array, key) FOREACH_HASH_KEY(pos, HASH_OF(array), key) #define FOREACH_HASH_KEY(pos, hash, _key) \ for ( zend_hash_internal_pointer_reset_ex(hash, &pos); \ ((_key).type = zend_hash_get_current_key_ex(hash, &(_key).str, &(_key).len, &(_key).num, (zend_bool) (_key).dup, &pos)) != HASH_KEY_NON_EXISTANT; \ zend_hash_move_forward_ex(hash, &pos)) \ -#define FOREACH_KEYVAL(pos, array, key, val) FOREACH_HASH_KEYVAL(pos, Z_ARRVAL_P(array), key, val) +#define FOREACH_KEYVAL(pos, array, key, val) FOREACH_HASH_KEYVAL(pos, HASH_OF(array), key, val) #define FOREACH_HASH_KEYVAL(pos, hash, _key, val) \ for ( zend_hash_internal_pointer_reset_ex(hash, &pos); \ ((_key).type = zend_hash_get_current_key_ex(hash, &(_key).str, &(_key).len, &(_key).num, (zend_bool) (_key).dup, &pos)) != HASH_KEY_NON_EXISTANT && \ @@ -411,9 +420,12 @@ typedef enum php_http_error { PHP_HTTP_E_REQUEST_METHOD, PHP_HTTP_E_MESSAGE, PHP_HTTP_E_MESSAGE_TYPE, + PHP_HTTP_E_MESSAGE_BODY, PHP_HTTP_E_ENCODING, PHP_HTTP_E_REQUEST, PHP_HTTP_E_REQUEST_POOL, + PHP_HTTP_E_REQUEST_DATASHARE, + PHP_HTTP_E_REQUEST_FACTORY, PHP_HTTP_E_SOCKET, PHP_HTTP_E_RESPONSE, PHP_HTTP_E_URL, @@ -421,42 +433,7 @@ typedef enum php_http_error { PHP_HTTP_E_COOKIE, } php_http_error_t; -/* CURL */ - -#define PHP_HTTP_CURL_OPT(OPTION, p) curl_easy_setopt((request->ch), OPTION, (p)) - -#define PHP_HTTP_CURL_OPT_STRING(OPTION, ldiff, obdc) \ - { \ - char *K = #OPTION; \ - PHP_HTTP_CURL_OPT_STRING_EX(K+lenof("CURLOPT_KEY")+ldiff, OPTION, obdc); \ - } -#define PHP_HTTP_CURL_OPT_STRING_EX(keyname, optname, obdc) \ - if (!strcasecmp(key.str, keyname)) { \ - zval *copy = php_http_request_option_cache(request, keyname, strlen(keyname)+1, 0, php_http_zsep(IS_STRING, *param)); \ - if (obdc) { \ - if (SUCCESS != php_check_open_basedir(Z_STRVAL_P(copy) TSRMLS_CC)) { \ - return FAILURE; \ - } \ - } \ - PHP_HTTP_CURL_OPT(optname, Z_STRVAL_P(copy)); \ - zval_ptr_dtor(©); \ - continue; \ - } -#define PHP_HTTP_CURL_OPT_LONG(OPTION, ldiff) \ - { \ - char *K = #OPTION; \ - PHP_HTTP_CURL_OPT_LONG_EX(K+lenof("CURLOPT_KEY")+ldiff, OPTION); \ - } -#define PHP_HTTP_CURL_OPT_LONG_EX(keyname, optname) \ - if (!strcasecmp(key.str, keyname)) { \ - zval *copy = php_http_zsep(IS_LONG, *param); \ - PHP_HTTP_CURL_OPT(optname, Z_LVAL_P(copy)); \ - zval_ptr_dtor(©); \ - continue; \ - } - #endif - /* * Local variables: * tab-width: 4 diff --git a/php_http_neon.c b/php_http_neon.c new file mode 100644 index 0000000..5b26dfc --- /dev/null +++ b/php_http_neon.c @@ -0,0 +1,893 @@ + +#include "php_http.h" +#include "php_http_request.h" + +#include + +#include +#include +#include +#include +#include + +typedef struct php_http_neon_auth { + long type; + char *user; + char *pass; +} php_http_neon_auth_t; + +typedef struct php_http_neon_request { + php_http_message_body_t *body; + + struct { + HashTable cache; + + php_http_buffer_t headers; + char *useragent; + char *referer; + char *url; + short port; + + struct { + int type; + short port; + char *host; + } proxy; + + struct { + php_http_neon_auth_t proxy; + php_http_neon_auth_t http; + } auth; + + struct { + unsigned noverify:1; + ne_ssl_client_cert *clicert; + ne_ssl_certificate *trucert; + } ssl; + + long redirects; + char *cookiestore; + ne_inet_addr *interface; + long maxfilesize; + + struct { + unsigned count; + double delay; + } retry; + + struct { + long connect; + long read; + } timeout; + } options; + + php_http_request_progress_t progress; + +} php_http_neon_request_t; + +/* callbacks */ + +static ssize_t php_http_neon_read_callback(void *ctx, char *buf, size_t len) +{ + php_http_request_t *h = ctx; + php_http_neon_request_t *neon = h->ctx; + php_http_message_body_t *body = neon->body; + + if (body) { + TSRMLS_FETCH_FROM_CTX(body->ts); + + if (buf) { + size_t read = php_stream_read(php_http_message_body_stream(body), buf, len); + + php_http_buffer_append(h->buffer, buf, read); + php_http_message_parser_parse(h->parser, h->buffer, 0, &h->message); + return read; + } else { + return php_stream_rewind(php_http_message_body_stream(body)); + } + } + return 0; +} + +static void php_http_neon_pre_send_callback(ne_request *req, void *ctx, ne_buffer *header) +{ + php_http_request_t *h = ctx; + php_http_neon_request_t *neon = h->ctx; + + ne_buffer_append(header, neon->options.headers.data, neon->options.headers.used); + + php_http_buffer_append(h->buffer, header->data, header->used - 1 /* ne_buffer counts \0 */); + php_http_buffer_appends(h->buffer, PHP_HTTP_CRLF); + php_http_message_parser_parse(h->parser, h->buffer, 0, &h->message); +} + +static void php_http_neon_post_headers_callback(ne_request *req, void *ctx, const ne_status *status) +{ + php_http_request_t *h = ctx; + HashTable *hdrs = &h->message->hdrs; + php_http_info_t i; + void *iter = NULL; + zval tmp; + const char *name, *value; + TSRMLS_FETCH_FROM_CTX(h->ts); + + php_http_info_init(&i TSRMLS_CC); + i.type = PHP_HTTP_RESPONSE; + php_http_version_init(&i.http.version, status->major_version, status->minor_version TSRMLS_CC); + i.http.info.response.code = status->code; + i.http.info.response.status = estrdup(status->reason_phrase); + php_http_message_info_callback(&h->message, &hdrs, &i TSRMLS_CC); + php_http_info_dtor(&i); + + INIT_PZVAL_ARRAY(&tmp, hdrs); + while ((iter = ne_response_header_iterate(req, iter, &name, &value))) { + char *key = php_http_pretty_key(estrdup(name), strlen(name), 1, 1); + add_assoc_string(&tmp, key, estrdup(value), 0); + efree(key); + } + php_http_message_parser_state_push(h->parser, 1, PHP_HTTP_MESSAGE_PARSER_STATE_HEADER_DONE); +} + +static int php_http_neon_ssl_verify_callback(void *ctx, int failures, const ne_ssl_certificate *cert) +{ + php_http_request_t *h = ctx; + php_http_neon_request_t *neon = h->ctx; + + if (neon->options.ssl.noverify) { + return 0; + } + return failures; +} + +static void php_http_neon_progress_callback(void *ctx, ne_session_status status, const ne_session_status_info *info) +{ + php_http_request_t *h = ctx; + php_http_neon_request_t *neon = h->ctx; + + switch (status) { + case ne_status_lookup: + break; + case ne_status_connecting: + break; + case ne_status_connected: + break; + case ne_status_sending: + neon->progress.state.ul.total = info->sr.total; + neon->progress.state.ul.now = info->sr.progress; + break; + case ne_status_recving: + neon->progress.state.dl.total = info->sr.total; + neon->progress.state.dl.now = info->sr.progress; + break; + case ne_status_disconnected: + break; + } + + if (neon->progress.callback) { + zval retval; + TSRMLS_FETCH_FROM_CTX(h->ts); + + INIT_PZVAL(&retval); + ZVAL_NULL(&retval); + + with_error_handling(EH_NORMAL, NULL) { + if (neon->progress.pass_state) { + zval *param; + + MAKE_STD_ZVAL(param); + array_init(param); + add_assoc_double(param, "dltotal", neon->progress.state.dl.total); + add_assoc_double(param, "dlnow", neon->progress.state.dl.now); + add_assoc_double(param, "ultotal", neon->progress.state.ul.total); + add_assoc_double(param, "ulnow", neon->progress.state.ul.now); + + neon->progress.in_cb = 1; + call_user_function(EG(function_table), NULL, neon->progress.callback, &retval, 1, ¶m TSRMLS_CC); + neon->progress.in_cb = 0; + + zval_ptr_dtor(¶m); + } else { + neon->progress.in_cb = 1; + call_user_function(EG(function_table), NULL, neon->progress.callback, &retval, 0, NULL TSRMLS_CC); + neon->progress.in_cb = 0; + } + } end_error_handling(); + + zval_dtor(&retval); + } +} + +/* helpers */ + +static inline zval *cache_option(HashTable *cache, char *key, size_t keylen, ulong h, zval *opt) +{ + Z_ADDREF_P(opt); + + if (h) { + zend_hash_quick_update(cache, key, keylen, h, &opt, sizeof(zval *), NULL); + } else { + zend_hash_update(cache, key, keylen, &opt, sizeof(zval *), NULL); + } + + return opt; +} + +static inline zval *get_option(HashTable *cache, HashTable *options, char *key, size_t keylen, int type) +{ + if (options) { + zval **zoption; + ulong h = zend_hash_func(key, keylen); + + if (SUCCESS == zend_hash_quick_find(options, key, keylen, h, (void *) &zoption)) { + zval *option = php_http_zsep(type, *zoption); + + if (cache) { + zval *cached = cache_option(cache, key, keylen, h, option); + + zval_ptr_dtor(&option); + return cached; + } + return option; + } + } + + return NULL; +} + +static STATUS set_options(php_http_request_t *h, HashTable *options) +{ + zval *zoption; + int range_req = 0; + php_http_neon_request_t *neon = h->ctx; + + /* proxy */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("proxyhost"), IS_STRING))) { + neon->options.proxy.host = Z_STRVAL_P(zoption); + + /* user:pass */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("proxyauth"), IS_STRING)) && Z_STRLEN_P(zoption)) { + char *colon = strchr(Z_STRVAL_P(zoption), ':'); + + if (colon) { + STR_SET(neon->options.auth.proxy.user, estrndup(Z_STRVAL_P(zoption), colon - Z_STRVAL_P(zoption))); + STR_SET(neon->options.auth.proxy.pass, estrdup(colon + 1)); + } else { + STR_SET(neon->options.auth.proxy.user, estrdup(Z_STRVAL_P(zoption))); + } + } + + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("proxyauthtype"), IS_LONG))) { + neon->options.auth.proxy.type = Z_LVAL_P(zoption); + } else { + neon->options.auth.proxy.type = NE_AUTH_ALL; + } + + + /* port */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("proxyport"), IS_LONG))) { + neon->options.proxy.port = Z_LVAL_P(zoption); + } else { + neon->options.proxy.port = 0; + } + + /* type */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("proxytype"), IS_LONG))) { + neon->options.proxy.type = Z_LVAL_P(zoption); + } else { + neon->options.proxy.type = -1; + } + } + + /* outgoing interface */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("interface"), IS_STRING))) { + if (!(neon->options.interface = ne_iaddr_parse(Z_STRVAL_P(zoption), ne_iaddr_ipv4))) { + neon->options.interface = ne_iaddr_parse(Z_STRVAL_P(zoption), ne_iaddr_ipv6); + } + } + + /* another port */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("port"), IS_LONG))) { + neon->options.port = Z_LVAL_P(zoption); + } + + /* auth */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("httpauth"), IS_STRING)) && Z_STRLEN_P(zoption)) { + char *colon = strchr(Z_STRVAL_P(zoption), ':'); + + if (colon) { + STR_SET(neon->options.auth.http.user, estrndup(Z_STRVAL_P(zoption), colon - Z_STRVAL_P(zoption))); + STR_SET(neon->options.auth.http.pass, estrdup(colon + 1)); + } else { + STR_SET(neon->options.auth.http.user, estrdup(Z_STRVAL_P(zoption))); + } + } + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("httpauthtype"), IS_LONG))) { + neon->options.auth.http.type = Z_LVAL_P(zoption); + } else { + neon->options.auth.http.type = NE_AUTH_ALL; + } + + /* redirects, defaults to 0 */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("redirect"), IS_LONG))) { + neon->options.redirects = Z_LVAL_P(zoption); + } else { + neon->options.redirects = 0; + } + + /* retries, defaults to 0 */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("retrycount"), IS_LONG))) { + neon->options.retry.count = Z_LVAL_P(zoption); + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("retrydelay"), IS_DOUBLE))) { + neon->options.retry.delay = Z_DVAL_P(zoption); + } else { + neon->options.retry.delay = 0; + } + } else { + neon->options.retry.count = 0; + } + + /* referer */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("referer"), IS_STRING)) && Z_STRLEN_P(zoption)) { + neon->options.referer = Z_STRVAL_P(zoption); + } + + /* useragent, default "PECL::HTTP/version (PHP/version)" */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("useragent"), IS_STRING))) { + /* allow to send no user agent, not even default one */ + if (Z_STRLEN_P(zoption)) { + neon->options.useragent = Z_STRVAL_P(zoption); + } else { + neon->options.useragent = NULL; + } + } + + /* resume */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("resume"), IS_LONG)) && (Z_LVAL_P(zoption) > 0)) { + php_http_buffer_appendf(&neon->options.headers, "Range: bytes=%ld-" PHP_HTTP_CRLF, Z_LVAL_P(zoption)); + range_req = 1; + } + /* or range of kind array(array(0,499), array(100,1499)) */ + else if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("range"), IS_ARRAY)) && zend_hash_num_elements(Z_ARRVAL_P(zoption))) { + HashPosition pos1, pos2; + zval **rr, **rb, **re; + php_http_buffer_t rs; + + php_http_buffer_init(&rs); + FOREACH_VAL(pos1, zoption, rr) { + if (Z_TYPE_PP(rr) == IS_ARRAY) { + zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(rr), &pos2); + if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(rr), (void *) &rb, &pos2)) { + zend_hash_move_forward_ex(Z_ARRVAL_PP(rr), &pos2); + if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(rr), (void *) &re, &pos2)) { + if ( ((Z_TYPE_PP(rb) == IS_LONG) || ((Z_TYPE_PP(rb) == IS_STRING) && is_numeric_string(Z_STRVAL_PP(rb), Z_STRLEN_PP(rb), NULL, NULL, 1))) && + ((Z_TYPE_PP(re) == IS_LONG) || ((Z_TYPE_PP(re) == IS_STRING) && is_numeric_string(Z_STRVAL_PP(re), Z_STRLEN_PP(re), NULL, NULL, 1)))) { + zval *rbl = php_http_zsep(IS_LONG, *rb); + zval *rel = php_http_zsep(IS_LONG, *re); + + if ((Z_LVAL_P(rbl) >= 0) && (Z_LVAL_P(rel) >= 0)) { + php_http_buffer_appendf(&rs, "%ld-%ld,", Z_LVAL_P(rbl), Z_LVAL_P(rel)); + } + zval_ptr_dtor(&rbl); + zval_ptr_dtor(&rel); + } + } + } + } + } + + if (PHP_HTTP_BUFFER_LEN(&rs)) { + /* ignore last comma */ + php_http_buffer_appendf(&neon->options.headers, "Range: bytes=%.*s" PHP_HTTP_CRLF, rs.used - 1, rs.data); + range_req = 1; + } + php_http_buffer_dtor(&rs); + } + + /* additional headers, array('name' => 'value') */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("headers"), IS_ARRAY))) { + php_http_array_hashkey_t header_key = php_http_array_hashkey_init(0); + zval **header_val; + HashPosition pos; + + FOREACH_KEYVAL(pos, zoption, header_key, header_val) { + if (header_key.type == HASH_KEY_IS_STRING) { + zval *header_cpy = php_http_zsep(IS_STRING, *header_val); + + if (!strcasecmp(header_key.str, "range")) { + range_req = 1; + } + php_http_buffer_appendf(&neon->options.headers, "%s: %s" PHP_HTTP_CRLF, header_key.str, Z_STRVAL_P(header_cpy)); + zval_ptr_dtor(&header_cpy); + } + } + } + /* etag */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("etag"), IS_STRING)) && Z_STRLEN_P(zoption)) { + php_http_buffer_appends(&neon->options.headers, "If-"); + if (range_req) { + php_http_buffer_appends(&neon->options.headers, "None-"); + } + php_http_buffer_appends(&neon->options.headers, "Match: "); + + if ((Z_STRVAL_P(zoption)[0] == '"') && (Z_STRVAL_P(zoption)[Z_STRLEN_P(zoption)-1] == '"')) { + php_http_buffer_appendl(&neon->options.headers, Z_STRVAL_P(zoption)); + } else { + php_http_buffer_appendf(&neon->options.headers, "\"%s\"" PHP_HTTP_CRLF, Z_STRVAL_P(zoption)); + } + } + /* compression */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("compress"), IS_BOOL)) && Z_LVAL_P(zoption)) { + php_http_buffer_appends(&neon->options.headers, "Accept-Encoding: gzip;q=1.0,deflate;q=0.5" PHP_HTTP_CRLF); + } + + /* lastmodified */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("lastmodified"), IS_LONG))) { + if (Z_LVAL_P(zoption)) { + time_t time = Z_LVAL_P(zoption) > 0 ? Z_LVAL_P(zoption) : PHP_HTTP_G->env.request.time + Z_LVAL_P(zoption); + char *date = php_format_date(ZEND_STRS(PHP_HTTP_DATE_FORMAT), time, 0 TSRMLS_CC); + + php_http_buffer_appends(&neon->options.headers, "If-"); + if (range_req) { + php_http_buffer_appends(&neon->options.headers, "Un"); + } + php_http_buffer_appendf(&neon->options.headers, "Modified-Since: %s" PHP_HTTP_CRLF, date); + efree(date); + } + } + + /* cookies, array('name' => 'value') */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("cookies"), IS_ARRAY))) { + php_http_buffer_t cookies; + + php_http_buffer_init(&cookies); + if (zend_hash_num_elements(Z_ARRVAL_P(zoption))) { + zval *urlenc_cookies = NULL; + + php_http_buffer_appends(&neon->options.headers, "Cookie: "); + + /* check whether cookies should not be urlencoded; default is to urlencode them */ + if ((!(urlenc_cookies = get_option(&neon->options.cache, options, ZEND_STRS("encodecookies"), IS_BOOL))) || Z_BVAL_P(urlenc_cookies)) { + php_http_url_encode_hash_recursive(HASH_OF(zoption), &neon->options.headers, "; ", lenof("; "), NULL, 0 TSRMLS_CC); + } else { + HashPosition pos; + php_http_array_hashkey_t cookie_key = php_http_array_hashkey_init(0); + zval **cookie_val; + + FOREACH_KEYVAL(pos, zoption, cookie_key, cookie_val) { + if (cookie_key.type == HASH_KEY_IS_STRING) { + zval *val = php_http_zsep(IS_STRING, *cookie_val); + php_http_buffer_appendf(&neon->options.headers, "%s=%s; ", cookie_key.str, Z_STRVAL_P(val)); + zval_ptr_dtor(&val); + } + } + } + } + neon->options.headers.used -= lenof("; "); + php_http_buffer_appends(&neon->options.headers, PHP_HTTP_CRLF); + } + /* cookiestore, read initial cookies from that file and store cookies back into that file */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("cookiestore"), IS_STRING))) { + neon->options.cookiestore = Z_STRVAL_P(zoption); + } + + /* maxfilesize */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("maxfilesize"), IS_LONG))) { + neon->options.maxfilesize = Z_LVAL_P(zoption); + } + + /* READ timeout */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("timeout"), IS_DOUBLE))) { + neon->options.timeout.read = Z_DVAL_P(zoption) > 0 && Z_DVAL_P(zoption) < 1 ? 1 : round(Z_DVAL_P(zoption)); + } + /* connecttimeout, defaults to 0 */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("connecttimeout"), IS_DOUBLE))) { + neon->options.timeout.connect = Z_DVAL_P(zoption) > 0 && Z_DVAL_P(zoption) < 1 ? 1 : round(Z_DVAL_P(zoption)); + } + + /* ssl */ + if ((zoption = get_option(&neon->options.cache, options, ZEND_STRS("ssl"), IS_ARRAY))) { + zval **zssl; + + if (SUCCESS == zend_hash_find(Z_ARRVAL_P(zoption), ZEND_STRS("verifypeer"), (void *) &zssl)) { + if (!i_zend_is_true(*zssl)) { + neon->options.ssl.noverify = 1; + } + } + if (SUCCESS == zend_hash_find(Z_ARRVAL_P(zoption), ZEND_STRS("key"), (void *) &zssl)) { + zval *cpy = php_http_zsep(IS_STRING, *zssl); + ne_ssl_client_cert *cc = ne_ssl_clicert_read(Z_STRVAL_P(cpy)); + + if (cc) { + if (ne_ssl_clicert_encrypted(cc)) { + if (SUCCESS == zend_hash_find(Z_ARRVAL_P(zoption), ZEND_STRS("keypasswd"), (void *) &zssl)) { + zval *cpy = php_http_zsep(IS_STRING, *zssl); + + if (NE_OK == ne_ssl_clicert_decrypt(cc, Z_STRVAL_P(cpy))) { + neon->options.ssl.clicert = cc; + } + zval_ptr_dtor(&cpy); + } + } + } + + if (cc && !neon->options.ssl.clicert) { + ne_ssl_clicert_free(cc); + } + + zval_ptr_dtor(&cpy); + } + if (SUCCESS == zend_hash_find(Z_ARRVAL_P(zoption), ZEND_STRS("cert"), (void *) &zssl)) { + zval *cpy = php_http_zsep(IS_STRING, *zssl); + ne_ssl_certificate *tc = ne_ssl_cert_read(Z_STRVAL_P(cpy)); + + if (tc) { + neon->options.ssl.trucert = tc; + } + zval_ptr_dtor(&cpy); + } + } + + return SUCCESS; +} + +/* request handler ops */ + +static STATUS php_http_neon_request_reset(php_http_request_t *h); + +static php_http_request_t *php_http_neon_request_init(php_http_request_t *h, void *dummy) +{ + php_http_neon_request_t *ctx; + + ctx = ecalloc(1, sizeof(*ctx)); + php_http_buffer_init(&ctx->options.headers); + zend_hash_init(&ctx->options.cache, 0, NULL, ZVAL_PTR_DTOR, 0); + h->ctx = ctx; + + return h; +} + +static php_http_request_t *php_http_neon_request_copy(php_http_request_t *from, php_http_request_t *to) +{ + TSRMLS_FETCH_FROM_CTX(from->ts); + + if (to) { + return php_http_neon_request_init(to, NULL); + } else { + return php_http_request_init(NULL, from->ops, NULL TSRMLS_CC); + } +} + +static void php_http_neon_request_dtor(php_http_request_t *h) +{ + php_http_neon_request_t *ctx = h->ctx; + + php_http_neon_request_reset(h); + php_http_buffer_dtor(&ctx->options.headers); + zend_hash_destroy(&ctx->options.cache); + + efree(ctx); + h->ctx = NULL; +} + +static STATUS php_http_neon_request_reset(php_http_request_t *h) +{ + php_http_neon_request_t *neon = h->ctx; + + php_http_buffer_reset(&neon->options.headers); + STR_SET(neon->options.useragent, NULL); + STR_SET(neon->options.url, NULL); + neon->options.port = 0; + neon->options.proxy.type = -1; + neon->options.proxy.port = 0; + STR_SET(neon->options.proxy.host, NULL); + neon->options.auth.proxy.type = 0; + STR_SET(neon->options.auth.proxy.user, NULL); + STR_SET(neon->options.auth.proxy.pass, NULL); + neon->options.auth.http.type = 0; + STR_SET(neon->options.auth.http.user, NULL); + STR_SET(neon->options.auth.http.pass, NULL); + neon->options.ssl.noverify = 0; + if (neon->options.ssl.clicert) { + ne_ssl_clicert_free(neon->options.ssl.clicert); + neon->options.ssl.clicert = NULL; + } + if (neon->options.ssl.trucert) { + ne_ssl_cert_free(neon->options.ssl.trucert); + neon->options.ssl.trucert = NULL; + } + neon->options.redirects = 0; + STR_SET(neon->options.cookiestore, NULL); + if (neon->options.interface) { + ne_iaddr_free(neon->options.interface); + neon->options.interface = NULL; + } + neon->options.maxfilesize = 0; + neon->options.retry.delay = 0; + neon->options.retry.count = 0; + neon->options.timeout.read = 0; + neon->options.timeout.connect = 0; + + if (neon->progress.callback) { + zval_ptr_dtor(&neon->progress.callback); + neon->progress.callback = NULL; + } + neon->progress.pass_state = 0; + neon->progress.state.dl.now = 0; + neon->progress.state.dl.total = 0; + neon->progress.state.ul.now = 0; + neon->progress.state.ul.total = 0; + + return SUCCESS; +} + +static STATUS php_http_neon_request_exec(php_http_request_t *h, php_http_request_method_t meth_id, const char *url, php_http_message_body_t *body) +{ + unsigned tries = 0; + STATUS retval = SUCCESS; + int result; + php_url *purl; + const char *meth; + ne_session *session; + ne_request *request; + php_http_neon_request_t *neon = h->ctx; + TSRMLS_FETCH_FROM_CTX(h->ts); + + if (!(meth = php_http_request_method_name(meth_id))) { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_METHOD, "Unsupported request method: %d (%s)", meth, url); + return FAILURE; + } + + if (!(purl = php_url_parse(url))) { + php_http_error(HE_WARNING, PHP_HTTP_E_URL, "Could not parse url %s", url); + return FAILURE; + } + + if (neon->options.port) { + purl->port = neon->options.port; + } else if (!purl->port) { +#ifdef HAVE_GETSERVBYNAME + struct servent *se; + + if ((se = getservbyname(purl->scheme, "tcp")) && se->s_port) { + purl->port = ntohs(se->s_port); + } else +#endif + if (!strcasecmp(purl->scheme, "https")) { + purl->port = 443; + } else { + purl->port = 80; + } + } + + session = ne_session_create(purl->scheme, purl->host, purl->port); + if (neon->options.proxy.host) { + switch (neon->options.proxy.type) { + case NE_SOCK_SOCKSV4: + case NE_SOCK_SOCKSV4A: + case NE_SOCK_SOCKSV5: + ne_session_socks_proxy(session, neon->options.proxy.type, neon->options.proxy.host, neon->options.proxy.port, neon->options.auth.proxy.user, neon->options.auth.proxy.pass); + break; + + default: + ne_session_proxy(session, neon->options.proxy.host, neon->options.proxy.port); + break; + } + } + if (neon->options.interface) { + ne_set_localaddr(session, neon->options.interface); + } + if (neon->options.useragent) { + ne_set_useragent(session, neon->options.useragent); + } + if (neon->options.timeout.read) { + ne_set_read_timeout(session, neon->options.timeout.read); + } + if (neon->options.timeout.read) { + ne_set_connect_timeout(session, neon->options.timeout.connect); + } + if (neon->options.redirects) { + ne_redirect_register(session); + } + ne_hook_pre_send(session, php_http_neon_pre_send_callback, h); + ne_hook_post_headers(session, php_http_neon_post_headers_callback, h); + ne_set_notifier(session, php_http_neon_progress_callback, h); + ne_ssl_set_verify(session, php_http_neon_ssl_verify_callback, h); + if (neon->options.ssl.clicert) { + ne_ssl_set_clicert(session, neon->options.ssl.clicert); + } + /* this crashes + ne_ssl_trust_default_ca(session); */ + if (neon->options.ssl.trucert) { + ne_ssl_trust_cert(session, neon->options.ssl.trucert); + } + + request = ne_request_create(session, meth, purl->path /* . purl->query */); + if (body) { + /* RFC2616, section 4.3 (para. 4) states that »a message-body MUST NOT be included in a request if the + * specification of the request method (section 5.1.1) does not allow sending an entity-body in request.« + * Following the clause in section 5.1.1 (para. 2) that request methods »MUST be implemented with the + * same semantics as those specified in section 9« reveal that not any single defined HTTP/1.1 method + * does not allow a request body. + */ + switch (meth_id) { + default: + neon->body = body; + ne_set_request_body_provider(request, php_http_message_body_size(body), php_http_neon_read_callback, h); + break; + } + } + +retry: + switch (result = ne_begin_request(request)) { + case NE_OK: { + ssize_t len; + char *buf = emalloc(0x1000); + + while (0 < (len = ne_read_response_block(request, buf, 0x1000))) { + php_http_buffer_append(h->buffer, buf, len); + php_http_message_parser_parse(h->parser, h->buffer, PHP_HTTP_MESSAGE_PARSER_DUMB_BODIES, &h->message); + // php_http_message_body_append(&h->message->body, buf, len); + } + + efree(buf); + break; + } + + case NE_REDIRECT: + if (neon->options.redirects-- > 0){ + const ne_uri *uri = ne_redirect_location(session); + + if (uri) { + char *url = ne_uri_unparse(uri); + + retval = php_http_neon_request_exec(h, meth_id, url, body); + free(url); + } + } + break; + + default: + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "%s; (%s)", ne_get_error(session), url); + if (EG(exception)) { + add_property_long(EG(exception), "neonCode", result); + } + retval = FAILURE; + break; + } + + switch (result = ne_end_request(request)) { + case NE_OK: + break; + + case NE_RETRY: + if (neon->options.retry.count > tries++) { + if (neon->options.retry.delay >= PHP_HTTP_DIFFSEC) { + php_http_sleep(neon->options.retry.delay); + } + goto retry; + break; + } + + default: + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "%s; (%s)", ne_get_error(session), url); + if (EG(exception)) { + add_property_long(EG(exception), "neonCode", result); + } + retval = FAILURE; + break; + } + + ne_session_destroy(session); + php_url_free(purl); + + return retval; +} + +static STATUS php_http_neon_request_setopt(php_http_request_t *h, php_http_request_setopt_opt_t opt, void *arg) +{ + php_http_neon_request_t *neon = h->ctx; + + switch (opt) { + case PHP_HTTP_REQUEST_OPT_SETTINGS: + return set_options(h, arg); + break; + + case PHP_HTTP_REQUEST_OPT_PROGRESS_CALLBACK: + if (neon->progress.callback) { + zval_ptr_dtor(&neon->progress.callback); + } + if ((neon->progress.callback = arg)) { + Z_ADDREF_P(neon->progress.callback); + } + break; + + case PHP_HTTP_REQUEST_OPT_PROGRESS_CALLBACK_WANTS_STATE: + neon->progress.pass_state = *((int *)arg); + break; + + case PHP_HTTP_REQUEST_OPT_COOKIES_ENABLE: + case PHP_HTTP_REQUEST_OPT_COOKIES_RESET: + case PHP_HTTP_REQUEST_OPT_COOKIES_RESET_SESSION: + case PHP_HTTP_REQUEST_OPT_COOKIES_FLUSH: + /* still NOOPs */ + break; + + default: + return FAILURE; + } + + return SUCCESS; +} + +static STATUS php_http_neon_request_getopt(php_http_request_t *h, php_http_request_getopt_opt_t opt, void *arg) +{ + php_http_neon_request_t *neon = h->ctx; + + switch (opt) { + case PHP_HTTP_REQUEST_OPT_PROGRESS_INFO: + memcpy(arg, &neon->progress, sizeof(neon->progress)); + break; + + case PHP_HTTP_REQUEST_OPT_TRANSFER_INFO: + break; + + default: + return FAILURE; + } + + return SUCCESS; +} + +static php_http_request_ops_t php_http_neon_request_ops = { + php_http_neon_request_init, + php_http_neon_request_copy, + php_http_neon_request_dtor, + php_http_neon_request_reset, + php_http_neon_request_exec, + php_http_neon_request_setopt, + php_http_neon_request_getopt +}; + +PHP_HTTP_API php_http_request_ops_t *php_http_neon_get_request_ops(void) +{ + return &php_http_neon_request_ops; +} + +PHP_MINIT_FUNCTION(http_neon) +{ + php_http_request_factory_driver_t driver = { + &php_http_neon_request_ops, + NULL + }; + if (SUCCESS != php_http_request_factory_add_driver(ZEND_STRL("neon"), &driver)) { + return FAILURE; + } + + /* + * Auth Constants + */ + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_BASIC"), NE_AUTH_BASIC TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_DIGEST"), NE_AUTH_DIGEST TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_NTLM"), NE_AUTH_NTLM TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_GSSNEG"), NE_AUTH_GSSAPI TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_ANY"), NE_AUTH_ALL TSRMLS_CC); + + /* + * Proxy Type Constants + */ + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS4"), NE_SOCK_SOCKSV4 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS4A"), NE_SOCK_SOCKSV4A TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS5"), NE_SOCK_SOCKSV5 TSRMLS_CC); + zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_HTTP"), -1 TSRMLS_CC); + + if (NE_OK != ne_sock_init()) { + return FAILURE; + } + return SUCCESS; +} + +PHP_MSHUTDOWN_FUNCTION(http_neon) +{ + ne_sock_exit(); + return SUCCESS; +} diff --git a/php_http_neon.h b/php_http_neon.h new file mode 100644 index 0000000..96b7d0d --- /dev/null +++ b/php_http_neon.h @@ -0,0 +1,9 @@ +#ifndef PHP_HTTP_NEON_H +#define PHP_HTTP_NEON_H + +php_http_request_ops_t *php_http_neon_get_request_ops(void); + +PHP_MINIT_FUNCTION(http_neon); +PHP_MSHUTDOWN_FUNCTION(http_neon); + +#endif /* PHP_HTTP_NEON_H */ diff --git a/php_http_object.c b/php_http_object.c index 5a1a279..9282e5d 100644 --- a/php_http_object.c +++ b/php_http_object.c @@ -144,24 +144,20 @@ PHP_METHOD(HttpObject, setErrorHandling) long eh; zval *old; - if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &eh)) { - RETURN_FALSE; + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &eh)) { + switch (eh) { + case EH_NORMAL: + case EH_SUPPRESS: + case EH_THROW: + zend_update_property_long(php_http_object_class_entry, getThis(), ZEND_STRL("errorHandling"), eh TSRMLS_CC); + break; + + default: + php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "unknown error handling code (%ld)", eh); + } } - switch (eh) { - case EH_NORMAL: - case EH_SUPPRESS: - case EH_THROW: - break; - default: - php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "unknown error handling code (%ld)", eh); - RETURN_FALSE; - } - - old = zend_read_property(php_http_object_class_entry, getThis(), ZEND_STRL("errorHandling"), 0 TSRMLS_CC); - Z_ADDREF_P(old); - zend_update_property_long(php_http_object_class_entry, getThis(), ZEND_STRL("errorHandling"), eh TSRMLS_CC); - RETURN_ZVAL(old, 0, 0); + RETURN_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpObject, getDefaultErrorHandling) @@ -174,25 +170,20 @@ PHP_METHOD(HttpObject, setDefaultErrorHandling) long eh; zval *old; - if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &eh)) { - RETURN_FALSE; - } + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &eh)) { + switch (eh) { + case EH_NORMAL: + case EH_SUPPRESS: + case EH_THROW: + zend_update_static_property_long(php_http_object_class_entry, ZEND_STRL("defaultErrorHandling"), eh TSRMLS_CC); + break; - switch (eh) { - case EH_NORMAL: - case EH_SUPPRESS: - case EH_THROW: - break; - default: - php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "unknown error handling code (%ld)", eh); - RETURN_FALSE; + default: + php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "unknown error handling code (%ld)", eh); + } } - - old = zend_read_static_property(php_http_object_class_entry, ZEND_STRL("defaultErrorHandling"), 0 TSRMLS_CC); - Z_ADDREF_P(old); - zend_update_static_property_long(php_http_object_class_entry, ZEND_STRL("defaultErrorHandling"), eh TSRMLS_CC); - RETURN_ZVAL(old, 0, 1); } + PHP_MINIT_FUNCTION(http_object) { PHP_HTTP_REGISTER_CLASS(http, Object, http_object, NULL, ZEND_ACC_ABSTRACT); diff --git a/php_http_request.c b/php_http_request.c index 90b0f31..63d68db 100644 --- a/php_http_request.c +++ b/php_http_request.c @@ -14,1108 +14,106 @@ #include "php_http.h" +#include +#include #include -#if defined(ZTS) && defined(PHP_HTTP_HAVE_SSL) -# ifdef PHP_WIN32 -# define PHP_HTTP_NEED_OPENSSL_TSL -# include -# else /* !PHP_WIN32 */ -# if defined(PHP_HTTP_HAVE_OPENSSL) -# define PHP_HTTP_NEED_OPENSSL_TSL -# include -# elif defined(PHP_HTTP_HAVE_GNUTLS) -# define PHP_HTTP_NEED_GNUTLS_TSL -# include -# else -# warning \ - "libcurl was compiled with SSL support, but configure could not determine which" \ - "library was used; thus no SSL crypto locking callbacks will be set, which may " \ - "cause random crashes on SSL requests" -# endif /* PHP_HTTP_HAVE_OPENSSL || PHP_HTTP_HAVE_GNUTLS */ -# endif /* PHP_WIN32 */ -#endif /* ZTS && PHP_HTTP_HAVE_SSL */ - - -#ifdef PHP_HTTP_NEED_OPENSSL_TSL -static MUTEX_T *php_http_openssl_tsl = NULL; - -static void php_http_openssl_thread_lock(int mode, int n, const char * file, int line) -{ - if (mode & CRYPTO_LOCK) { - tsrm_mutex_lock(php_http_openssl_tsl[n]); - } else { - tsrm_mutex_unlock(php_http_openssl_tsl[n]); - } -} -static ulong php_http_openssl_thread_id(void) -{ - return (ulong) tsrm_thread_id(); -} -#endif -#ifdef PHP_HTTP_NEED_GNUTLS_TSL -static int php_http_gnutls_mutex_create(void **m) +PHP_HTTP_API php_http_request_t *php_http_request_init(php_http_request_t *h, php_http_request_ops_t *ops, void *init_arg TSRMLS_DC) { - if (*((MUTEX_T *) m) = tsrm_mutex_alloc()) { - return SUCCESS; - } else { - return FAILURE; - } -} + php_http_request_t *free_h = NULL; -static int php_http_gnutls_mutex_destroy(void **m) -{ - tsrm_mutex_free(*((MUTEX_T *) m)); - return SUCCESS; -} - -static int php_http_gnutls_mutex_lock(void **m) -{ - return tsrm_mutex_lock(*((MUTEX_T *) m)); -} - -static int php_http_gnutls_mutex_unlock(void **m) -{ - return tsrm_mutex_unlock(*((MUTEX_T *) m)); -} - -static struct gcry_thread_cbs php_http_gnutls_tsl = { - GCRY_THREAD_OPTION_USER, - NULL, - php_http_gnutls_mutex_create, - php_http_gnutls_mutex_destroy, - php_http_gnutls_mutex_lock, - php_http_gnutls_mutex_unlock -}; -#endif - - -/* safe curl wrappers */ -#define init_curl_storage(ch) \ - {\ - php_http_request_storage_t *st = pecalloc(1, sizeof(php_http_request_storage_t), 1); \ - curl_easy_setopt(ch, CURLOPT_PRIVATE, st); \ - curl_easy_setopt(ch, CURLOPT_ERRORBUFFER, st->errorbuffer); \ + if (!h) { + free_h = h = emalloc(sizeof(*h)); } + memset(h, 0, sizeof(*h)); -static void *safe_curl_init(void) -{ - CURL *ch; - - if ((ch = curl_easy_init())) { - init_curl_storage(ch); - return ch; - } - return NULL; -} -static void *safe_curl_copy(void *p) -{ - CURL *ch; - - if ((ch = curl_easy_duphandle(p))) { - init_curl_storage(ch); - return ch; - } - return NULL; -} -static void safe_curl_dtor(void *p) { - php_http_request_storage_t *st = php_http_request_storage_get(p); - - curl_easy_cleanup(p); - - if (st) { - if (st->url) { - pefree(st->url, 1); - } - if (st->cookiestore) { - pefree(st->cookiestore, 1); - } - pefree(st, 1); - } -} - -static inline zval *php_http_request_option(php_http_request_t *request, HashTable *options, char *key, size_t keylen, int type); -static inline zval *php_http_request_option_cache(php_http_request_t *r, char *key, size_t keylen, ulong h, zval *opt); -static inline int php_http_request_cookies_enabled(php_http_request_t *r); - -static size_t php_http_curl_read_callback(void *, size_t, size_t, void *); -static int php_http_curl_progress_callback(void *, double, double, double, double); -static int php_http_curl_raw_callback(CURL *, curl_infotype, char *, size_t, void *); -static int php_http_curl_dummy_callback(char *data, size_t n, size_t l, void *s) { return n*l; } -static curlioerr php_http_curl_ioctl_callback(CURL *, curliocmd, void *); - -PHP_HTTP_API CURL * php_http_curl_init(CURL *ch, php_http_request_t *request TSRMLS_DC) -{ - if (ch || (SUCCESS == php_http_persistent_handle_acquire(ZEND_STRL("http_request"), &ch TSRMLS_CC))) { -#if defined(ZTS) - curl_easy_setopt(ch, CURLOPT_NOSIGNAL, 1L); -#endif - curl_easy_setopt(ch, CURLOPT_HEADER, 0L); - curl_easy_setopt(ch, CURLOPT_FILETIME, 1L); - curl_easy_setopt(ch, CURLOPT_AUTOREFERER, 1L); - curl_easy_setopt(ch, CURLOPT_VERBOSE, 1L); - curl_easy_setopt(ch, CURLOPT_HEADERFUNCTION, NULL); - curl_easy_setopt(ch, CURLOPT_DEBUGFUNCTION, php_http_curl_raw_callback); - curl_easy_setopt(ch, CURLOPT_READFUNCTION, php_http_curl_read_callback); - curl_easy_setopt(ch, CURLOPT_IOCTLFUNCTION, php_http_curl_ioctl_callback); - curl_easy_setopt(ch, CURLOPT_WRITEFUNCTION, php_http_curl_dummy_callback); - - /* set context */ - if (request) { - curl_easy_setopt(ch, CURLOPT_DEBUGDATA, request); - - /* attach curl handle */ - request->ch = ch; - /* set defaults (also in php_http_request_reset()) */ - php_http_request_defaults(request); - } - } - - return ch; -} -PHP_HTTP_API CURL *php_http_curl_copy(CURL *ch TSRMLS_DC) -{ - CURL *copy; - - if (SUCCESS == php_http_persistent_handle_accrete(ZEND_STRL("http_request"), ch, © TSRMLS_CC)) { - return copy; - } - return NULL; -} -PHP_HTTP_API void php_http_curl_free(CURL **ch TSRMLS_DC) -{ - if (*ch) { - curl_easy_setopt(*ch, CURLOPT_NOPROGRESS, 1L); - curl_easy_setopt(*ch, CURLOPT_PROGRESSFUNCTION, NULL); - curl_easy_setopt(*ch, CURLOPT_VERBOSE, 0L); - curl_easy_setopt(*ch, CURLOPT_DEBUGFUNCTION, NULL); - - php_http_persistent_handle_release(ZEND_STRL("http_request"), ch TSRMLS_CC); - } -} - -PHP_HTTP_API php_http_request_t *php_http_request_init(php_http_request_t *request, CURL *ch, php_http_request_method_t meth, const char *url TSRMLS_DC) -{ - php_http_request_t *r; - - if (request) { - r = request; - } else { - r = emalloc(sizeof(php_http_request_t)); - } - memset(r, 0, sizeof(php_http_request_t)); - - r->ch = ch; - r->url = (url) ? php_http_url_absolute(url, 0) : NULL; - r->meth = (meth > 0) ? meth : PHP_HTTP_GET; - - r->parser.ctx = php_http_message_parser_init(NULL TSRMLS_CC); - r->parser.msg = php_http_message_init(NULL, 0 TSRMLS_CC); - r->parser.buf = php_http_buffer_init(NULL); - - php_http_buffer_init(&r->_cache.cookies); - zend_hash_init(&r->_cache.options, 0, NULL, ZVAL_PTR_DTOR, 0); - - TSRMLS_SET_CTX(r->ts); - - return r; -} - -PHP_HTTP_API void php_http_request_dtor(php_http_request_t *request) -{ - TSRMLS_FETCH_FROM_CTX(request->ts); - - php_http_request_reset(request); - php_http_curl_free(&request->ch); - php_http_message_body_free(&request->body); - php_http_message_parser_free(&request->parser.ctx); - php_http_message_free(&request->parser.msg); - php_http_buffer_free(&request->parser.buf); - - php_http_buffer_dtor(&request->_cache.cookies); - zend_hash_destroy(&request->_cache.options); - if (request->_cache.headers) { - curl_slist_free_all(request->_cache.headers); - request->_cache.headers = NULL; - } - if (request->_progress.callback) { - zval_ptr_dtor(&request->_progress.callback); - request->_progress.callback = NULL; - } -} + h->ops = ops; + h->buffer = php_http_buffer_init(NULL TSRMLS_CC); + h->parser = php_http_message_parser_init(NULL TSRMLS_CC); + h->message = php_http_message_init(NULL, 0 TSRMLS_CC); -PHP_HTTP_API void php_http_request_free(php_http_request_t **request) -{ - if (*request) { - TSRMLS_FETCH_FROM_CTX((*request)->ts); - php_http_request_dtor(*request); - efree(*request); - *request = NULL; - } -} + TSRMLS_SET_CTX(h->ts); -PHP_HTTP_API void php_http_request_reset(php_http_request_t *request) -{ - TSRMLS_FETCH_FROM_CTX(request->ts); - STR_SET(request->url, NULL); - php_http_message_body_dtor(request->body); - php_http_request_defaults(request); - - if (request->ch) { - php_http_request_storage_t *st = php_http_request_storage_get(request->ch); - - if (st) { - if (st->url) { - pefree(st->url, 1); - st->url = NULL; - } - if (st->cookiestore) { - pefree(st->cookiestore, 1); - st->cookiestore = NULL; + if (h->ops->init) { + if (!(h = h->ops->init(h, init_arg))) { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "Could not initialize request"); + if (free_h) { + efree(free_h); } - st->errorbuffer[0] = '\0'; } } -} - -PHP_HTTP_API STATUS php_http_request_enable_cookies(php_http_request_t *request) -{ - int initialized = 1; - TSRMLS_FETCH_FROM_CTX(request->ts); - - PHP_HTTP_CHECK_CURL_INIT(request->ch, php_http_curl_init(request->ch, request TSRMLS_CC), initialized = 0); - if (initialized && (php_http_request_cookies_enabled(request) || (CURLE_OK == curl_easy_setopt(request->ch, CURLOPT_COOKIEFILE, "")))) { - return SUCCESS; - } - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "Could not enable cookies for this session"); - return FAILURE; -} -PHP_HTTP_API STATUS php_http_request_reset_cookies(php_http_request_t *request, int session_only) -{ - int initialized = 1; - TSRMLS_FETCH_FROM_CTX(request->ts); - - PHP_HTTP_CHECK_CURL_INIT(request->ch, php_http_curl_init(request->ch, request TSRMLS_CC), initialized = 0); - if (initialized) { - if (!php_http_request_cookies_enabled(request)) { - if (SUCCESS != php_http_request_enable_cookies(request)) { - return FAILURE; - } - } - if (session_only) { - if (CURLE_OK == curl_easy_setopt(request->ch, CURLOPT_COOKIELIST, "SESS")) { - return SUCCESS; - } - } else { - if (CURLE_OK == curl_easy_setopt(request->ch, CURLOPT_COOKIELIST, "ALL")) { - return SUCCESS; - } - } - } - return FAILURE; + return h; } -PHP_HTTP_API STATUS php_http_request_flush_cookies(php_http_request_t *request) +PHP_HTTP_API void php_http_request_dtor(php_http_request_t *h) { - int initialized = 1; - TSRMLS_FETCH_FROM_CTX(request->ts); - - PHP_HTTP_CHECK_CURL_INIT(request->ch, php_http_curl_init(request->ch, request TSRMLS_CC), initialized = 0); - if (initialized) { - if (!php_http_request_cookies_enabled(request)) { - return FAILURE; - } - if (CURLE_OK == curl_easy_setopt(request->ch, CURLOPT_COOKIELIST, "FLUSH")) { - return SUCCESS; - } + if (h->ops->dtor) { + h->ops->dtor(h); } - return FAILURE; -} -PHP_HTTP_API void php_http_request_defaults(php_http_request_t *request) -{ - if (request->ch) { - PHP_HTTP_CURL_OPT(CURLOPT_NOPROGRESS, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_PROGRESSDATA, request); - PHP_HTTP_CURL_OPT(CURLOPT_PROGRESSFUNCTION, php_http_curl_progress_callback); - PHP_HTTP_CURL_OPT(CURLOPT_URL, NULL); -#if PHP_HTTP_CURL_VERSION(7,19,4) - PHP_HTTP_CURL_OPT(CURLOPT_NOPROXY, NULL); -#endif - PHP_HTTP_CURL_OPT(CURLOPT_PROXY, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_PROXYPORT, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_PROXYTYPE, 0L); - /* libcurl < 7.19.6 does not clear auth info with USERPWD set to NULL */ -#if PHP_HTTP_CURL_VERSION(7,19,1) - PHP_HTTP_CURL_OPT(CURLOPT_PROXYUSERNAME, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_PROXYPASSWORD, NULL); -#endif - PHP_HTTP_CURL_OPT(CURLOPT_PROXYAUTH, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_HTTPPROXYTUNNEL, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_DNS_CACHE_TIMEOUT, 60L); - PHP_HTTP_CURL_OPT(CURLOPT_IPRESOLVE, 0); - PHP_HTTP_CURL_OPT(CURLOPT_LOW_SPEED_LIMIT, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_LOW_SPEED_TIME, 0L); - /* LFS weirdance - PHP_HTTP_CURL_OPT(CURLOPT_MAX_SEND_SPEED_LARGE, (curl_off_t) 0); - PHP_HTTP_CURL_OPT(CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t) 0); - */ - /* crashes - PHP_HTTP_CURL_OPT(CURLOPT_MAXCONNECTS, 5L); */ - PHP_HTTP_CURL_OPT(CURLOPT_FRESH_CONNECT, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_FORBID_REUSE, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_INTERFACE, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_PORT, 0L); -#if PHP_HTTP_CURL_VERSION(7,19,0) - PHP_HTTP_CURL_OPT(CURLOPT_ADDRESS_SCOPE, 0L); -#endif - PHP_HTTP_CURL_OPT(CURLOPT_LOCALPORT, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_LOCALPORTRANGE, 0L); - /* libcurl < 7.19.6 does not clear auth info with USERPWD set to NULL */ -#if PHP_HTTP_CURL_VERSION(7,19,1) - PHP_HTTP_CURL_OPT(CURLOPT_USERNAME, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_PASSWORD, NULL); -#endif - PHP_HTTP_CURL_OPT(CURLOPT_HTTPAUTH, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_ENCODING, NULL); - /* we do this ourself anyway */ - PHP_HTTP_CURL_OPT(CURLOPT_HTTP_CONTENT_DECODING, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_HTTP_TRANSFER_DECODING, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_FOLLOWLOCATION, 0L); -#if PHP_HTTP_CURL_VERSION(7,19,1) - PHP_HTTP_CURL_OPT(CURLOPT_POSTREDIR, 0L); -#else - PHP_HTTP_CURL_OPT(CURLOPT_POST301, 0L); -#endif - PHP_HTTP_CURL_OPT(CURLOPT_UNRESTRICTED_AUTH, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_REFERER, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_USERAGENT, "PECL::HTTP/" PHP_HTTP_EXT_VERSION " (PHP/" PHP_VERSION ")"); - PHP_HTTP_CURL_OPT(CURLOPT_HTTPHEADER, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_COOKIE, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_COOKIESESSION, 0L); - /* these options would enable curl's cookie engine by default which we don't want - PHP_HTTP_CURL_OPT(CURLOPT_COOKIEFILE, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_COOKIEJAR, NULL); */ - PHP_HTTP_CURL_OPT(CURLOPT_COOKIELIST, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_RANGE, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_RESUME_FROM, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_MAXFILESIZE, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_TIMECONDITION, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_TIMEVALUE, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_TIMEOUT, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_CONNECTTIMEOUT, 3); - PHP_HTTP_CURL_OPT(CURLOPT_SSLCERT, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_SSLCERTTYPE, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_SSLCERTPASSWD, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_SSLKEY, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_SSLKEYTYPE, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_SSLKEYPASSWD, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_SSLENGINE, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_SSLVERSION, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_SSL_VERIFYPEER, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_SSL_VERIFYHOST, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_SSL_CIPHER_LIST, NULL); -#if PHP_HTTP_CURL_VERSION(7,19,0) - PHP_HTTP_CURL_OPT(CURLOPT_ISSUERCERT, NULL); - #if defined(PHP_HTTP_HAVE_OPENSSL) - PHP_HTTP_CURL_OPT(CURLOPT_CRLFILE, NULL); - #endif -#endif -#if PHP_HTTP_CURL_VERSION(7,19,1) && defined(PHP_HTTP_HAVE_OPENSSL) - PHP_HTTP_CURL_OPT(CURLOPT_CERTINFO, NULL); -#endif -#ifdef PHP_HTTP_CURL_CAINFO - PHP_HTTP_CURL_OPT(CURLOPT_CAINFO, PHP_HTTP_CURL_CAINFO); -#else - PHP_HTTP_CURL_OPT(CURLOPT_CAINFO, NULL); -#endif - PHP_HTTP_CURL_OPT(CURLOPT_CAPATH, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_RANDOM_FILE, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_EGDSOCKET, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_POSTFIELDS, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_POSTFIELDSIZE, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_HTTPPOST, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_IOCTLDATA, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_READDATA, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_INFILESIZE, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE); - PHP_HTTP_CURL_OPT(CURLOPT_CUSTOMREQUEST, NULL); - PHP_HTTP_CURL_OPT(CURLOPT_NOBODY, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_POST, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_UPLOAD, 0L); - PHP_HTTP_CURL_OPT(CURLOPT_HTTPGET, 1L); - } + php_http_message_parser_free(&h->parser); + php_http_message_free(&h->message); + php_http_buffer_free(&h->buffer); } -PHP_HTTP_API void php_http_request_set_progress_callback(php_http_request_t *request, zval *cb) +PHP_HTTP_API void php_http_request_free(php_http_request_t **h) { - if (request->_progress.callback) { - zval_ptr_dtor(&request->_progress.callback); - } - if ((request->_progress.callback = cb)) { - Z_ADDREF_P(cb); + if (*h) { + php_http_request_dtor(*h); + efree(*h); + *h = NULL; } } -PHP_HTTP_API STATUS php_http_request_prepare(php_http_request_t *request, HashTable *options) +PHP_HTTP_API php_http_request_t *php_http_request_copy(php_http_request_t *from, php_http_request_t *to) { - zval *zoption; - zend_bool range_req = 0; - php_http_request_storage_t *storage; - - TSRMLS_FETCH_FROM_CTX(request->ts); - - PHP_HTTP_CHECK_CURL_INIT(request->ch, php_http_curl_init(NULL, request TSRMLS_CC), return FAILURE); - - if (!(storage = php_http_request_storage_get(request->ch))) { - return FAILURE; - } - storage->errorbuffer[0] = '\0'; - /* set options */ - if (storage->url) { - pefree(storage->url, 1); - } - storage->url = pestrdup(request->url, 1); - PHP_HTTP_CURL_OPT(CURLOPT_URL, storage->url); - - /* progress callback */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("onprogress"), -1))) { - php_http_request_set_progress_callback(request, zoption); - } - - /* proxy */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("proxyhost"), IS_STRING))) { - PHP_HTTP_CURL_OPT(CURLOPT_PROXY, Z_STRVAL_P(zoption)); - /* type */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("proxytype"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_PROXYTYPE, Z_LVAL_P(zoption)); - } - /* port */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("proxyport"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_PROXYPORT, Z_LVAL_P(zoption)); - } - /* user:pass */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("proxyauth"), IS_STRING)) && Z_STRLEN_P(zoption)) { - PHP_HTTP_CURL_OPT(CURLOPT_PROXYUSERPWD, Z_STRVAL_P(zoption)); - } - /* auth method */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("proxyauthtype"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_PROXYAUTH, Z_LVAL_P(zoption)); - } - /* tunnel */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("proxytunnel"), IS_BOOL)) && Z_BVAL_P(zoption)) { - PHP_HTTP_CURL_OPT(CURLOPT_HTTPPROXYTUNNEL, 1L); - } - } -#if PHP_HTTP_CURL_VERSION(7,19,4) - if ((zoption = php_http_request_option(request, options, ZEND_STRS("noproxy"), IS_STRING))) { - PHP_HTTP_CURL_OPT(CURLOPT_NOPROXY, Z_STRVAL_P(zoption)); - } -#endif - - /* dns */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("dns_cache_timeout"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_DNS_CACHE_TIMEOUT, Z_LVAL_P(zoption)); - } - if ((zoption = php_http_request_option(request, options, ZEND_STRS("ipresolve"), IS_LONG)) && Z_LVAL_P(zoption)) { - PHP_HTTP_CURL_OPT(CURLOPT_IPRESOLVE, Z_LVAL_P(zoption)); - } - - /* limits */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("low_speed_limit"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_LOW_SPEED_LIMIT, Z_LVAL_P(zoption)); - } - if ((zoption = php_http_request_option(request, options, ZEND_STRS("low_speed_time"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_LOW_SPEED_TIME, Z_LVAL_P(zoption)); - } - /* LSF weirdance - if ((zoption = php_http_request_option(request, options, ZEND_STRS("max_send_speed"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_MAX_SEND_SPEED_LARGE, (curl_off_t) Z_LVAL_P(zoption)); - } - if ((zoption = php_http_request_option(request, options, ZEND_STRS("max_recv_speed"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t) Z_LVAL_P(zoption)); - } - */ - /* crashes - if ((zoption = php_http_request_option(request, options, ZEND_STRS("maxconnects"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_MAXCONNECTS, Z_LVAL_P(zoption)); - } */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("fresh_connect"), IS_BOOL)) && Z_BVAL_P(zoption)) { - PHP_HTTP_CURL_OPT(CURLOPT_FRESH_CONNECT, 1L); - } - if ((zoption = php_http_request_option(request, options, ZEND_STRS("forbid_reuse"), IS_BOOL)) && Z_BVAL_P(zoption)) { - PHP_HTTP_CURL_OPT(CURLOPT_FORBID_REUSE, 1L); - } - - /* outgoing interface */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("interface"), IS_STRING))) { - PHP_HTTP_CURL_OPT(CURLOPT_INTERFACE, Z_STRVAL_P(zoption)); - - if ((zoption = php_http_request_option(request, options, ZEND_STRS("portrange"), IS_ARRAY))) { - zval **prs, **pre; - - zend_hash_internal_pointer_reset(Z_ARRVAL_P(zoption)); - if (SUCCESS == zend_hash_get_current_data(Z_ARRVAL_P(zoption), (void *) &prs)) { - zend_hash_move_forward(Z_ARRVAL_P(zoption)); - if (SUCCESS == zend_hash_get_current_data(Z_ARRVAL_P(zoption), (void *) &pre)) { - zval *prs_cpy = php_http_zsep(IS_LONG, *prs); - zval *pre_cpy = php_http_zsep(IS_LONG, *pre); - - if (Z_LVAL_P(prs_cpy) && Z_LVAL_P(pre_cpy)) { - PHP_HTTP_CURL_OPT(CURLOPT_LOCALPORT, MIN(Z_LVAL_P(prs_cpy), Z_LVAL_P(pre_cpy))); - PHP_HTTP_CURL_OPT(CURLOPT_LOCALPORTRANGE, labs(Z_LVAL_P(prs_cpy)-Z_LVAL_P(pre_cpy))+1L); - } - zval_ptr_dtor(&prs_cpy); - zval_ptr_dtor(&pre_cpy); - } - } - } - } - - /* another port */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("port"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_PORT, Z_LVAL_P(zoption)); - } - - /* RFC4007 zone_id */ -#if PHP_HTTP_CURL_VERSION(7,19,0) - if ((zoption = php_http_request_option(request, options, ZEND_STRS("address_scope"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_ADDRESS_SCOPE, Z_LVAL_P(zoption)); - } -#endif - - /* auth */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("httpauth"), IS_STRING)) && Z_STRLEN_P(zoption)) { - PHP_HTTP_CURL_OPT(CURLOPT_USERPWD, Z_STRVAL_P(zoption)); - } - if ((zoption = php_http_request_option(request, options, ZEND_STRS("httpauthtype"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_HTTPAUTH, Z_LVAL_P(zoption)); - } - - /* redirects, defaults to 0 */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("redirect"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_FOLLOWLOCATION, Z_LVAL_P(zoption) ? 1L : 0L); - PHP_HTTP_CURL_OPT(CURLOPT_MAXREDIRS, request->_cache.redirects = Z_LVAL_P(zoption)); - if ((zoption = php_http_request_option(request, options, ZEND_STRS("unrestrictedauth"), IS_BOOL))) { - PHP_HTTP_CURL_OPT(CURLOPT_UNRESTRICTED_AUTH, Z_LVAL_P(zoption)); - } - if ((zoption = php_http_request_option(request, options, ZEND_STRS("postredir"), IS_BOOL))) { -#if PHP_HTTP_CURL_VERSION(7,19,1) - PHP_HTTP_CURL_OPT(CURLOPT_POSTREDIR, Z_BVAL_P(zoption) ? 1L : 0L); -#else - PHP_HTTP_CURL_OPT(CURLOPT_POST301, Z_BVAL_P(zoption) ? 1L : 0L); -#endif - } - } else { - request->_cache.redirects = 0; - } - - /* retries, defaults to 0 */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("retrycount"), IS_LONG))) { - request->_retry.count = Z_LVAL_P(zoption); - if ((zoption = php_http_request_option(request, options, ZEND_STRS("retrydelay"), IS_DOUBLE))) { - request->_retry.delay = Z_DVAL_P(zoption); - } else { - request->_retry.delay = 0; - } - } else { - request->_retry.count = 0; - } - - /* referer */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("referer"), IS_STRING)) && Z_STRLEN_P(zoption)) { - PHP_HTTP_CURL_OPT(CURLOPT_REFERER, Z_STRVAL_P(zoption)); - } - - /* useragent, default "PECL::HTTP/version (PHP/version)" */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("useragent"), IS_STRING))) { - /* allow to send no user agent, not even default one */ - if (Z_STRLEN_P(zoption)) { - PHP_HTTP_CURL_OPT(CURLOPT_USERAGENT, Z_STRVAL_P(zoption)); - } else { - PHP_HTTP_CURL_OPT(CURLOPT_USERAGENT, NULL); - } - } - - /* resume */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("resume"), IS_LONG)) && (Z_LVAL_P(zoption) > 0)) { - range_req = 1; - PHP_HTTP_CURL_OPT(CURLOPT_RESUME_FROM, Z_LVAL_P(zoption)); - } - /* or range of kind array(array(0,499), array(100,1499)) */ - else if ((zoption = php_http_request_option(request, options, ZEND_STRS("range"), IS_ARRAY)) && zend_hash_num_elements(Z_ARRVAL_P(zoption))) { - HashPosition pos1, pos2; - zval **rr, **rb, **re; - php_http_buffer_t rs; - - php_http_buffer_init(&rs); - FOREACH_VAL(pos1, zoption, rr) { - if (Z_TYPE_PP(rr) == IS_ARRAY) { - zend_hash_internal_pointer_reset_ex(Z_ARRVAL_PP(rr), &pos2); - if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(rr), (void *) &rb, &pos2)) { - zend_hash_move_forward_ex(Z_ARRVAL_PP(rr), &pos2); - if (SUCCESS == zend_hash_get_current_data_ex(Z_ARRVAL_PP(rr), (void *) &re, &pos2)) { - if ( ((Z_TYPE_PP(rb) == IS_LONG) || ((Z_TYPE_PP(rb) == IS_STRING) && is_numeric_string(Z_STRVAL_PP(rb), Z_STRLEN_PP(rb), NULL, NULL, 1))) && - ((Z_TYPE_PP(re) == IS_LONG) || ((Z_TYPE_PP(re) == IS_STRING) && is_numeric_string(Z_STRVAL_PP(re), Z_STRLEN_PP(re), NULL, NULL, 1)))) { - zval *rbl = php_http_zsep(IS_LONG, *rb); - zval *rel = php_http_zsep(IS_LONG, *re); - - if ((Z_LVAL_P(rbl) >= 0) && (Z_LVAL_P(rel) >= 0)) { - php_http_buffer_appendf(&rs, "%ld-%ld,", Z_LVAL_P(rbl), Z_LVAL_P(rel)); - } - zval_ptr_dtor(&rbl); - zval_ptr_dtor(&rel); - } - } - } - } - } - - if (PHP_HTTP_BUFFER_LEN(&rs)) { - zval *cached_range; - - /* ditch last comma */ - PHP_HTTP_BUFFER_VAL(&rs)[PHP_HTTP_BUFFER_LEN(&rs)-- -1] = '\0'; - /* cache string */ - MAKE_STD_ZVAL(cached_range); - ZVAL_STRINGL(cached_range, PHP_HTTP_BUFFER_VAL(&rs), PHP_HTTP_BUFFER_LEN(&rs), 0); - PHP_HTTP_CURL_OPT(CURLOPT_RANGE, Z_STRVAL_P(php_http_request_option_cache(request, ZEND_STRS("range"), 0, cached_range))); - zval_ptr_dtor(&cached_range); - } - } - - /* additional headers, array('name' => 'value') */ - if (request->_cache.headers) { - curl_slist_free_all(request->_cache.headers); - request->_cache.headers = NULL; - } - if ((zoption = php_http_request_option(request, options, ZEND_STRS("headers"), IS_ARRAY))) { - php_http_array_hashkey_t header_key = php_http_array_hashkey_init(0); - zval **header_val; - HashPosition pos; - php_http_buffer_t header; - - php_http_buffer_init(&header); - FOREACH_KEYVAL(pos, zoption, header_key, header_val) { - if (header_key.type == HASH_KEY_IS_STRING) { - zval *header_cpy = php_http_zsep(IS_STRING, *header_val); - - if (!strcasecmp(header_key.str, "range")) { - range_req = 1; - } - - php_http_buffer_appendf(&header, "%s: %s", header_key.str, Z_STRVAL_P(header_cpy)); - php_http_buffer_fix(&header); - request->_cache.headers = curl_slist_append(request->_cache.headers, PHP_HTTP_BUFFER_VAL(&header)); - php_http_buffer_reset(&header); - - zval_ptr_dtor(&header_cpy); - } - } - php_http_buffer_dtor(&header); - } - /* etag */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("etag"), IS_STRING)) && Z_STRLEN_P(zoption)) { - zend_bool is_quoted = !((Z_STRVAL_P(zoption)[0] != '"') || (Z_STRVAL_P(zoption)[Z_STRLEN_P(zoption)-1] != '"')); - php_http_buffer_t header; - - php_http_buffer_init(&header); - php_http_buffer_appendf(&header, is_quoted?"%s: %s":"%s: \"%s\"", range_req?"If-Match":"If-None-Match", Z_STRVAL_P(zoption)); - php_http_buffer_fix(&header); - request->_cache.headers = curl_slist_append(request->_cache.headers, PHP_HTTP_BUFFER_VAL(&header)); - php_http_buffer_dtor(&header); - } - /* compression */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("compress"), IS_BOOL)) && Z_LVAL_P(zoption)) { - request->_cache.headers = curl_slist_append(request->_cache.headers, "Accept-Encoding: gzip;q=1.0,deflate;q=0.5"); - } - PHP_HTTP_CURL_OPT(CURLOPT_HTTPHEADER, request->_cache.headers); - - /* lastmodified */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("lastmodified"), IS_LONG))) { - if (Z_LVAL_P(zoption)) { - if (Z_LVAL_P(zoption) > 0) { - PHP_HTTP_CURL_OPT(CURLOPT_TIMEVALUE, Z_LVAL_P(zoption)); - } else { - PHP_HTTP_CURL_OPT(CURLOPT_TIMEVALUE, (long) PHP_HTTP_G->env.request.time + Z_LVAL_P(zoption)); - } - PHP_HTTP_CURL_OPT(CURLOPT_TIMECONDITION, (long) (range_req ? CURL_TIMECOND_IFUNMODSINCE : CURL_TIMECOND_IFMODSINCE)); - } else { - PHP_HTTP_CURL_OPT(CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE); - } - } - - /* cookies, array('name' => 'value') */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("cookies"), IS_ARRAY))) { - php_http_buffer_dtor(&request->_cache.cookies); - if (zend_hash_num_elements(Z_ARRVAL_P(zoption))) { - zval *urlenc_cookies = NULL; - /* check whether cookies should not be urlencoded; default is to urlencode them */ - if ((!(urlenc_cookies = php_http_request_option(request, options, ZEND_STRS("encodecookies"), IS_BOOL))) || Z_BVAL_P(urlenc_cookies)) { - if (SUCCESS == php_http_url_encode_hash_recursive(HASH_OF(zoption), &request->_cache.cookies, "; ", lenof("; "), NULL, 0 TSRMLS_CC)) { - php_http_buffer_fix(&request->_cache.cookies); - PHP_HTTP_CURL_OPT(CURLOPT_COOKIE, request->_cache.cookies.data); - } - } else { - HashPosition pos; - php_http_array_hashkey_t cookie_key = php_http_array_hashkey_init(0); - zval **cookie_val; - - FOREACH_KEYVAL(pos, zoption, cookie_key, cookie_val) { - if (cookie_key.type == HASH_KEY_IS_STRING) { - zval *val = php_http_zsep(IS_STRING, *cookie_val); - php_http_buffer_appendf(&request->_cache.cookies, "%s=%s; ", cookie_key.str, Z_STRVAL_P(val)); - zval_ptr_dtor(&val); - } - } - - php_http_buffer_fix(&request->_cache.cookies); - if (PHP_HTTP_BUFFER_LEN(&request->_cache.cookies)) { - PHP_HTTP_CURL_OPT(CURLOPT_COOKIE, PHP_HTTP_BUFFER_VAL(&request->_cache.cookies)); - } - } - } - } - - /* don't load session cookies from cookiestore */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("cookiesession"), IS_BOOL)) && Z_BVAL_P(zoption)) { - PHP_HTTP_CURL_OPT(CURLOPT_COOKIESESSION, 1L); - } - - /* cookiestore, read initial cookies from that file and store cookies back into that file */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("cookiestore"), IS_STRING))) { - if (Z_STRLEN_P(zoption)) { - if (SUCCESS != php_check_open_basedir(Z_STRVAL_P(zoption) TSRMLS_CC)) { - return FAILURE; - } - } - if (storage->cookiestore) { - pefree(storage->cookiestore, 1); - } - storage->cookiestore = pestrndup(Z_STRVAL_P(zoption), Z_STRLEN_P(zoption), 1); - PHP_HTTP_CURL_OPT(CURLOPT_COOKIEFILE, storage->cookiestore); - PHP_HTTP_CURL_OPT(CURLOPT_COOKIEJAR, storage->cookiestore); - } - - /* maxfilesize */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("maxfilesize"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_MAXFILESIZE, Z_LVAL_P(zoption)); - } - - /* http protocol */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("protocol"), IS_LONG))) { - PHP_HTTP_CURL_OPT(CURLOPT_HTTP_VERSION, Z_LVAL_P(zoption)); - } - - /* timeout, defaults to 0 */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("timeout"), IS_DOUBLE))) { - PHP_HTTP_CURL_OPT(CURLOPT_TIMEOUT_MS, (long)(Z_DVAL_P(zoption)*1000)); - } - /* connecttimeout, defaults to 0 */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("connecttimeout"), IS_DOUBLE))) { - PHP_HTTP_CURL_OPT(CURLOPT_CONNECTTIMEOUT_MS, (long)(Z_DVAL_P(zoption)*1000)); - } - - /* ssl */ - if ((zoption = php_http_request_option(request, options, ZEND_STRS("ssl"), IS_ARRAY))) { - php_http_array_hashkey_t key = php_http_array_hashkey_init(0); - zval **param; - HashPosition pos; - - FOREACH_KEYVAL(pos, zoption, key, param) { - if (key.type == HASH_KEY_IS_STRING) { - PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLCERT, 0, 1); - PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLCERTTYPE, 0, 0); - PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLCERTPASSWD, 0, 0); - - PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLKEY, 0, 0); - PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLKEYTYPE, 0, 0); - PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLKEYPASSWD, 0, 0); - - PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSLENGINE, 0, 0); - PHP_HTTP_CURL_OPT_LONG(CURLOPT_SSLVERSION, 0); - - PHP_HTTP_CURL_OPT_LONG(CURLOPT_SSL_VERIFYPEER, 1); - PHP_HTTP_CURL_OPT_LONG(CURLOPT_SSL_VERIFYHOST, 1); - PHP_HTTP_CURL_OPT_STRING(CURLOPT_SSL_CIPHER_LIST, 1, 0); - - PHP_HTTP_CURL_OPT_STRING(CURLOPT_CAINFO, -3, 1); - PHP_HTTP_CURL_OPT_STRING(CURLOPT_CAPATH, -3, 1); - PHP_HTTP_CURL_OPT_STRING(CURLOPT_RANDOM_FILE, -3, 1); - PHP_HTTP_CURL_OPT_STRING(CURLOPT_EGDSOCKET, -3, 1); -#if PHP_HTTP_CURL_VERSION(7,19,0) - PHP_HTTP_CURL_OPT_STRING(CURLOPT_ISSUERCERT, -3, 1); - #if defined(PHP_HTTP_HAVE_OPENSSL) - PHP_HTTP_CURL_OPT_STRING(CURLOPT_CRLFILE, -3, 1); - #endif -#endif -#if PHP_HTTP_CURL_VERSION(7,19,1) && defined(PHP_HTTP_HAVE_OPENSSL) - PHP_HTTP_CURL_OPT_LONG(CURLOPT_CERTINFO, -3); -#endif - } - } - } - - /* request method */ - switch (request->meth) { - case PHP_HTTP_GET: - PHP_HTTP_CURL_OPT(CURLOPT_HTTPGET, 1L); - break; - - case PHP_HTTP_HEAD: - PHP_HTTP_CURL_OPT(CURLOPT_NOBODY, 1L); - break; - - case PHP_HTTP_POST: - PHP_HTTP_CURL_OPT(CURLOPT_POST, 1L); - break; - - case PHP_HTTP_PUT: - PHP_HTTP_CURL_OPT(CURLOPT_UPLOAD, 1L); - break; - - default: { - const char *meth = php_http_request_method_name(request->meth); - - if (meth) { - PHP_HTTP_CURL_OPT(CURLOPT_CUSTOMREQUEST, meth); - } else { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_METHOD, "Unsupported request method: %d (%s)", request->meth, request->url); - return FAILURE; - } - break; - } - } - - /* attach request body */ - if (request->body && (request->meth != PHP_HTTP_GET) && (request->meth != PHP_HTTP_HEAD) && (request->meth != PHP_HTTP_OPTIONS)) { - if (1 || request->meth == PHP_HTTP_PUT) { - /* PUT/UPLOAD _needs_ READDATA */ - PHP_HTTP_CURL_OPT(CURLOPT_IOCTLDATA, request); - PHP_HTTP_CURL_OPT(CURLOPT_READDATA, request); - PHP_HTTP_CURL_OPT(CURLOPT_INFILESIZE, php_http_message_body_size(request->body)); - } else { - abort(); - //PHP_HTTP_CURL_OPT(CURLOPT_POSTFIELDS, request->body->real->data); - PHP_HTTP_CURL_OPT(CURLOPT_POSTFIELDSIZE, php_http_message_body_size(request->body)); - } - } - - return SUCCESS; -} - -PHP_HTTP_API void php_http_request_exec(php_http_request_t *request) -{ - uint tries = 0; - CURLcode result; - TSRMLS_FETCH_FROM_CTX(request->ts); - -retry: - if (CURLE_OK != (result = curl_easy_perform(request->ch))) { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "%s; %s (%s)", curl_easy_strerror(result), php_http_request_storage_get(request->ch)->errorbuffer, request->url); - if (EG(exception)) { - add_property_long(EG(exception), "curlCode", result); - } - - if (request->_retry.count > tries++) { - switch (result) { - case CURLE_COULDNT_RESOLVE_PROXY: - case CURLE_COULDNT_RESOLVE_HOST: - case CURLE_COULDNT_CONNECT: - case CURLE_WRITE_ERROR: - case CURLE_READ_ERROR: - case CURLE_OPERATION_TIMEDOUT: - case CURLE_SSL_CONNECT_ERROR: - case CURLE_GOT_NOTHING: - case CURLE_SSL_ENGINE_SETFAILED: - case CURLE_SEND_ERROR: - case CURLE_RECV_ERROR: - case CURLE_SSL_ENGINE_INITFAILED: - case CURLE_LOGIN_DENIED: - if (request->_retry.delay >= PHP_HTTP_DIFFSEC) { - php_http_sleep(request->_retry.delay); - } - goto retry; - default: - break; - } - } + if (from->ops->copy) { + return from->ops->copy(from, to); } + return NULL; } -static size_t php_http_curl_read_callback(void *data, size_t len, size_t n, void *ctx) +PHP_HTTP_API STATUS php_http_request_exec(php_http_request_t *h, php_http_request_method_t meth, const char *url, php_http_message_body_t *body) { - php_http_request_t *request = (php_http_request_t *) ctx; - TSRMLS_FETCH_FROM_CTX(request->ts); - - if (request->body) { - return php_stream_read(php_http_message_body_stream(request->body), data, len * n); + if (h->ops->exec) { + return h->ops->exec(h, meth, url, body); } - return 0; -} - -static int php_http_curl_progress_callback(void *ctx, double dltotal, double dlnow, double ultotal, double ulnow) -{ - php_http_request_t *request = (php_http_request_t *) ctx; - - request->_progress.state.dl.total = dltotal; - request->_progress.state.dl.now = dlnow; - request->_progress.state.ul.total = ultotal; - request->_progress.state.ul.now = ulnow; - - if (request->_progress.callback) { - zval *param, retval; - TSRMLS_FETCH_FROM_CTX(request->ts); - - INIT_PZVAL(&retval); - ZVAL_NULL(&retval); - - MAKE_STD_ZVAL(param); - array_init(param); - add_assoc_double(param, "dltotal", request->_progress.state.dl.total); - add_assoc_double(param, "dlnow", request->_progress.state.dl.now); - add_assoc_double(param, "ultotal", request->_progress.state.ul.total); - add_assoc_double(param, "ulnow", request->_progress.state.ul.now); - - with_error_handling(EH_NORMAL, NULL) { - request->_progress.in_cb = 1; - call_user_function(EG(function_table), NULL, request->_progress.callback, &retval, 1, ¶m TSRMLS_CC); - request->_progress.in_cb = 0; - } end_error_handling(); - - zval_ptr_dtor(¶m); - zval_dtor(&retval); - } - - return 0; + return FAILURE; } -static curlioerr php_http_curl_ioctl_callback(CURL *ch, curliocmd cmd, void *ctx) +PHP_HTTP_API STATUS php_http_request_reset(php_http_request_t *h) { - php_http_request_t *request = (php_http_request_t *) ctx; - TSRMLS_FETCH_FROM_CTX(request->ts); - - if (cmd != CURLIOCMD_RESTARTREAD) { - return CURLIOE_UNKNOWNCMD; - } - - if (request->body) { - if (SUCCESS == php_stream_rewind(php_http_message_body_stream(request->body))) { - return CURLIOE_OK; - } + if (h->ops->reset) { + return h->ops->reset(h); } - - return CURLIOE_FAILRESTART; + return FAILURE; } -static int php_http_curl_raw_callback(CURL *ch, curl_infotype type, char *data, size_t length, void *ctx) +PHP_HTTP_API STATUS php_http_request_setopt(php_http_request_t *h, php_http_request_setopt_opt_t opt, void *arg) { - php_http_request_t *request = (php_http_request_t *) ctx; - - /* process data */ - switch (type) { - case CURLINFO_HEADER_IN: - case CURLINFO_DATA_IN: - case CURLINFO_HEADER_OUT: - case CURLINFO_DATA_OUT: - php_http_buffer_append(request->parser.buf, data, length); - if (PHP_HTTP_MESSAGE_PARSER_STATE_FAILURE == php_http_message_parser_parse(request->parser.ctx, request->parser.buf, request->_cache.redirects?PHP_HTTP_MESSAGE_PARSER_EMPTY_REDIRECTS:0, &request->parser.msg)) { - return -1; - } - break; - default: - break; + if (h->ops->setopt) { + return h->ops->setopt(h, opt, arg); } - - /* debug */ -#if 0 - { - const char _sym[] = "><><><"; - if (type) { - for (fprintf(stderr, "%c ", _sym[type-1]); length--; data++) { - fprintf(stderr, PHP_HTTP_IS_CTYPE(print, *data)?"%c":"\\x%02X", (int) *data); - if (*data == '\n' && length) { - fprintf(stderr, "\n%c ", _sym[type-1]); - } - } - fprintf(stderr, "\n"); - } else { - fprintf(stderr, "# %s", data); - } - } -#endif - - return 0; -} - -static inline zval *php_http_request_option(php_http_request_t *r, HashTable *options, char *key, size_t keylen, int type) -{ - TSRMLS_FETCH_FROM_CTX(r->ts); - - if (options) { - zval **zoption; - ulong h = zend_hash_func(key, keylen); - - if (SUCCESS == zend_hash_quick_find(options, key, keylen, h, (void *) &zoption)) { - zval *option, *cached; - - option = php_http_zsep(type, *zoption); - cached = php_http_request_option_cache(r, key, keylen, h, option); - - zval_ptr_dtor(&option); - return cached; - } - } - - return NULL; + return FAILURE; } -static inline zval *php_http_request_option_cache(php_http_request_t *r, char *key, size_t keylen, ulong h, zval *opt) +PHP_HTTP_API STATUS php_http_request_getopt(php_http_request_t *h, php_http_request_getopt_opt_t opt, void *arg) { - TSRMLS_FETCH_FROM_CTX(r->ts); - Z_ADDREF_P(opt); - - if (h) { - zend_hash_quick_update(&r->_cache.options, key, keylen, h, &opt, sizeof(zval *), NULL); - } else { - zend_hash_update(&r->_cache.options, key, keylen, &opt, sizeof(zval *), NULL); - } - - return opt; -} - -static inline int php_http_request_cookies_enabled(php_http_request_t *request) { - php_http_request_storage_t *st; - - if (request->ch && (st = php_http_request_storage_get(request->ch)) && st->cookiestore) { - /* cookies are enabled */ - return 1; + if (h->ops->getopt) { + return h->ops->getopt(h, opt, arg); } - return 0; + return FAILURE; } -/* USERLAND */ - #define PHP_HTTP_BEGIN_ARGS(method, req_args) PHP_HTTP_BEGIN_ARGS_EX(HttpRequest, method, 0, req_args) #define PHP_HTTP_EMPTY_ARGS(method) PHP_HTTP_EMPTY_ARGS_EX(HttpRequest, method, 0) #define PHP_HTTP_REQUEST_ME(method, visibility) PHP_ME(HttpRequest, method, PHP_HTTP_ARGS(HttpRequest, method), visibility) #define PHP_HTTP_REQUEST_ALIAS(method, func) PHP_HTTP_STATIC_ME_ALIAS(method, func, PHP_HTTP_ARGS(HttpRequest, method)) #define PHP_HTTP_REQUEST_MALIAS(me, al, vis) ZEND_FENTRY(me, ZEND_MN(HttpRequest_##al), PHP_HTTP_ARGS(HttpRequest, al), vis) -PHP_HTTP_BEGIN_ARGS(__construct, 0) - PHP_HTTP_ARG_VAL(url, 0) - PHP_HTTP_ARG_VAL(method, 0) - PHP_HTTP_ARG_VAL(options, 0) -PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(factory, 0) - PHP_HTTP_ARG_VAL(url, 0) - PHP_HTTP_ARG_VAL(method, 0) - PHP_HTTP_ARG_VAL(options, 0) - PHP_HTTP_ARG_VAL(class_name, 0) -PHP_HTTP_END_ARGS; +PHP_HTTP_EMPTY_ARGS(__construct); PHP_HTTP_EMPTY_ARGS(getOptions); PHP_HTTP_BEGIN_ARGS(setOptions, 0) @@ -1197,10 +195,6 @@ PHP_HTTP_END_ARGS; PHP_HTTP_EMPTY_ARGS(getResponseBody); PHP_HTTP_EMPTY_ARGS(getResponseCode); PHP_HTTP_EMPTY_ARGS(getResponseStatus); -PHP_HTTP_BEGIN_ARGS(getResponseInfo, 0) - PHP_HTTP_ARG_VAL(name, 0) -PHP_HTTP_END_ARGS; - PHP_HTTP_BEGIN_ARGS(getResponseHeader, 0) PHP_HTTP_ARG_VAL(header_name, 0) PHP_HTTP_END_ARGS; @@ -1218,79 +212,30 @@ PHP_HTTP_EMPTY_ARGS(getHistory); PHP_HTTP_EMPTY_ARGS(clearHistory); PHP_HTTP_EMPTY_ARGS(send); -PHP_HTTP_BEGIN_ARGS(get, 1) - PHP_HTTP_ARG_VAL(url, 0) - PHP_HTTP_ARG_VAL(options, 0) - PHP_HTTP_ARG_VAL(info, 1) +PHP_HTTP_EMPTY_ARGS(getObservers); +PHP_HTTP_BEGIN_ARGS(attach, 1) + PHP_HTTP_ARG_OBJ(SplObserver, observer, 0) PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(head, 1) - PHP_HTTP_ARG_VAL(url, 0) - PHP_HTTP_ARG_VAL(options, 0) - PHP_HTTP_ARG_VAL(info, 1) -PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(postData, 2) - PHP_HTTP_ARG_VAL(url, 0) - PHP_HTTP_ARG_VAL(data, 0) - PHP_HTTP_ARG_VAL(options, 0) - PHP_HTTP_ARG_VAL(info, 1) -PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(postFields, 2) - PHP_HTTP_ARG_VAL(url, 0) - PHP_HTTP_ARG_VAL(data, 0) - PHP_HTTP_ARG_VAL(options, 0) - PHP_HTTP_ARG_VAL(info, 1) -PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(putData, 2) - PHP_HTTP_ARG_VAL(url, 0) - PHP_HTTP_ARG_VAL(data, 0) - PHP_HTTP_ARG_VAL(options, 0) - PHP_HTTP_ARG_VAL(info, 1) +PHP_HTTP_BEGIN_ARGS(detach, 1) + PHP_HTTP_ARG_OBJ(SplObserver, observer, 0) PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(putFile, 2) - PHP_HTTP_ARG_VAL(url, 0) - PHP_HTTP_ARG_VAL(file, 0) - PHP_HTTP_ARG_VAL(options, 0) - PHP_HTTP_ARG_VAL(info, 1) -PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(putStream, 2) - PHP_HTTP_ARG_VAL(url, 0) - PHP_HTTP_ARG_VAL(stream, 0) - PHP_HTTP_ARG_VAL(options, 0) - PHP_HTTP_ARG_VAL(info, 1) -PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(methodRegister, 1) - PHP_HTTP_ARG_VAL(method_name, 0) -PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(methodUnregister, 1) - PHP_HTTP_ARG_VAL(method, 0) -PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(methodName, 1) - PHP_HTTP_ARG_VAL(method_id, 0) -PHP_HTTP_END_ARGS; - -PHP_HTTP_BEGIN_ARGS(methodExists, 1) - PHP_HTTP_ARG_VAL(method, 0) +PHP_HTTP_EMPTY_ARGS(notify); +PHP_HTTP_EMPTY_ARGS(getProgress); +PHP_HTTP_BEGIN_ARGS(getTransferInfo, 0) + PHP_HTTP_ARG_VAL(name, 0) PHP_HTTP_END_ARGS; -#ifdef HAVE_CURL_FORMGET -PHP_HTTP_BEGIN_ARGS(encodeBody, 2) - PHP_HTTP_ARG_VAL(fields, 0) - PHP_HTTP_ARG_VAL(files, 0) -PHP_HTTP_END_ARGS; -#endif zend_class_entry *php_http_request_class_entry; zend_function_entry php_http_request_method_entry[] = { - PHP_HTTP_REQUEST_ME(__construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) + PHP_HTTP_REQUEST_ME(__construct, ZEND_ACC_PRIVATE|ZEND_ACC_CTOR) + + PHP_HTTP_REQUEST_ME(getObservers, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_ME(notify, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_ME(attach, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_ME(detach, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_ME(getProgress, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_ME(getTransferInfo, ZEND_ACC_PUBLIC) PHP_HTTP_REQUEST_ME(setOptions, ZEND_ACC_PUBLIC) PHP_HTTP_REQUEST_ME(getOptions, ZEND_ACC_PUBLIC) @@ -1334,7 +279,6 @@ zend_function_entry php_http_request_method_entry[] = { PHP_HTTP_REQUEST_ME(getResponseCode, ZEND_ACC_PUBLIC) PHP_HTTP_REQUEST_ME(getResponseStatus, ZEND_ACC_PUBLIC) PHP_HTTP_REQUEST_ME(getResponseBody, ZEND_ACC_PUBLIC) - PHP_HTTP_REQUEST_ME(getResponseInfo, ZEND_ACC_PUBLIC) PHP_HTTP_REQUEST_ME(getResponseMessage, ZEND_ACC_PUBLIC) PHP_HTTP_REQUEST_ME(getRequestMessage, ZEND_ACC_PUBLIC) PHP_HTTP_REQUEST_ME(getHistory, ZEND_ACC_PUBLIC) @@ -1349,10 +293,10 @@ static zend_object_handlers php_http_request_object_handlers; zend_object_value php_http_request_object_new(zend_class_entry *ce TSRMLS_DC) { - return php_http_request_object_new_ex(ce, NULL, NULL); + return php_http_request_object_new_ex(ce, NULL, NULL TSRMLS_CC); } -zend_object_value php_http_request_object_new_ex(zend_class_entry *ce, CURL *ch, php_http_request_object_t **ptr TSRMLS_DC) +zend_object_value php_http_request_object_new_ex(zend_class_entry *ce, php_http_request_t *r, php_http_request_object_t **ptr TSRMLS_DC) { zend_object_value ov; php_http_request_object_t *o; @@ -1361,7 +305,9 @@ zend_object_value php_http_request_object_new_ex(zend_class_entry *ce, CURL *ch, zend_object_std_init((zend_object *) o, ce TSRMLS_CC); object_properties_init((zend_object *) o, ce); - o->request = php_http_request_init(NULL, ch, 0, NULL TSRMLS_CC); + if (!(o->request = r)) { + o->request = php_http_request_init(NULL, NULL, NULL TSRMLS_CC); + } if (ptr) { *ptr = o; @@ -1378,13 +324,8 @@ zend_object_value php_http_request_object_clone(zval *this_ptr TSRMLS_DC) zend_object_value new_ov; php_http_request_object_t *new_obj, *old_obj = zend_object_store_get_object(this_ptr TSRMLS_CC); - new_ov = php_http_request_object_new_ex(old_obj->zo.ce, NULL, &new_obj TSRMLS_CC); - if (old_obj->request->ch) { - php_http_curl_init(php_http_curl_copy(old_obj->request->ch), new_obj->request TSRMLS_CC); - } - + new_ov = php_http_request_object_new_ex(old_obj->zo.ce, php_http_request_copy(old_obj->request, NULL), &new_obj TSRMLS_CC); zend_objects_clone_members(&new_obj->zo, new_ov, &old_obj->zo, Z_OBJ_HANDLE_P(this_ptr) TSRMLS_CC); - /* FIXME */ return new_ov; } @@ -1458,55 +399,63 @@ static inline zend_object_value php_http_request_object_message(zval *this_ptr, } } -STATUS php_http_request_object_requesthandler(php_http_request_object_t *obj, zval *this_ptr TSRMLS_DC) +STATUS php_http_request_object_requesthandler(php_http_request_object_t *obj, zval *this_ptr, php_http_request_method_t *meth, char **url, php_http_message_body_t **body TSRMLS_DC) { - STATUS status = SUCCESS; - zval *zurl, *zmeth, *zbody, *zqdata, *zoptions; - php_http_message_body_t *body = NULL; - php_url *tmp, qdu = {0}; + zval *zoptions; + php_http_request_progress_t *progress; + /* reset request handle */ php_http_request_reset(obj->request); - PHP_HTTP_CHECK_CURL_INIT(obj->request->ch, php_http_curl_init(NULL, obj->request TSRMLS_CC), return FAILURE); - php_http_request_object_check_request_content_type(getThis() TSRMLS_CC); + /* reset transfer info */ + zend_update_property_null(php_http_request_class_entry, getThis(), ZEND_STRL("info") TSRMLS_CC); + + if (meth) { + *meth = (php_http_request_method_t) Z_LVAL_P(zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("method"), 0 TSRMLS_CC)); + } - zmeth = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("method"), 0 TSRMLS_CC); - obj->request->meth = Z_LVAL_P(zmeth); + if (url) { + php_url *tmp, qdu = {0}; + zval *zurl = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("url"), 0 TSRMLS_CC); + zval *zqdata = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("queryData"), 0 TSRMLS_CC); - zurl = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("url"), 0 TSRMLS_CC); - zqdata = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("queryData"), 0 TSRMLS_CC); - if (Z_STRLEN_P(zqdata)) { - qdu.query = Z_STRVAL_P(zqdata); + if (Z_STRLEN_P(zqdata)) { + qdu.query = Z_STRVAL_P(zqdata); + } + php_http_url(0, tmp = php_url_parse(Z_STRVAL_P(zurl)), &qdu, NULL, url, NULL TSRMLS_CC); + php_url_free(tmp); } - php_http_url(0, tmp = php_url_parse(Z_STRVAL_P(zurl)), &qdu, NULL, &obj->request->url, NULL TSRMLS_CC); - php_url_free(tmp); - zbody = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("requestBody"), 0 TSRMLS_CC); - if (Z_TYPE_P(zbody) == IS_OBJECT) { - body = ((php_http_message_body_object_t *)zend_object_store_get_object(zbody TSRMLS_CC))->body; + if (body) { + zval *zbody = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("requestBody"), 0 TSRMLS_CC); + + if (Z_TYPE_P(zbody) == IS_OBJECT) { + *body = ((php_http_message_body_object_t *)zend_object_store_get_object(zbody TSRMLS_CC))->body; + } } - obj->request->body = body; + php_http_request_object_check_request_content_type(getThis() TSRMLS_CC); zoptions = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), 0 TSRMLS_CC); - php_http_request_prepare(obj->request, Z_ARRVAL_P(zoptions)); + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_SETTINGS, Z_ARRVAL_P(zoptions)); - /* check if there's a onProgress method and add it as progress callback if one isn't already set */ - if (zend_hash_exists(&Z_OBJCE_P(getThis())->function_table, ZEND_STRS("onprogress"))) { - zval **entry, *pcb; + if (SUCCESS == php_http_request_getopt(obj->request, PHP_HTTP_REQUEST_OPT_PROGRESS_INFO, &progress)) { + if (!progress->callback) { + zval *pcb; + int no = 0; - if ((Z_TYPE_P(zoptions) != IS_ARRAY) - || (SUCCESS != zend_hash_find(Z_ARRVAL_P(zoptions), ZEND_STRS("onprogress"), (void *) &entry) - || (!zend_is_callable(*entry, 0, NULL TSRMLS_CC)))) { MAKE_STD_ZVAL(pcb); array_init(pcb); Z_ADDREF_P(getThis()); add_next_index_zval(pcb, getThis()); - add_next_index_stringl(pcb, "onprogress", lenof("onprogress"), 1); - php_http_request_set_progress_callback(obj->request, pcb); + add_next_index_stringl(pcb, ZEND_STRL("notify"), 1); + + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_PROGRESS_CALLBACK, pcb); + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_PROGRESS_CALLBACK_WANTS_STATE, &no); zval_ptr_dtor(&pcb); } + php_http_request_progress_notify(progress TSRMLS_CC); + progress->state.started = 1; } - - return status; + return SUCCESS; } STATUS php_http_request_object_responsehandler(php_http_request_object_t *obj, zval *this_ptr TSRMLS_DC) @@ -1514,12 +463,13 @@ STATUS php_http_request_object_responsehandler(php_http_request_object_t *obj, z STATUS ret = SUCCESS; zval *info; php_http_message_t *msg; + php_http_request_progress_t *progress; /* always fetch info */ MAKE_STD_ZVAL(info); array_init(info); - php_http_request_info(obj->request, Z_ARRVAL_P(info)); - zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("responseInfo"), info TSRMLS_CC); + php_http_request_getopt(obj->request, PHP_HTTP_REQUEST_OPT_TRANSFER_INFO, Z_ARRVAL_P(info)); + zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("transferInfo"), info TSRMLS_CC); zval_ptr_dtor(&info); /* update history * / @@ -1547,7 +497,7 @@ STATUS php_http_request_object_responsehandler(php_http_request_object_t *obj, z // zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("requestMessage"), message TSRMLS_CC); // } // fprintf(stderr, "RESPONSE MESSAGE: %p\n", obj->request->parser.msg); - if ((msg = obj->request->parser.msg)) { + if ((msg = obj->request->message)) { /* update properties with response info */ zval *message; @@ -1558,7 +508,7 @@ STATUS php_http_request_object_responsehandler(php_http_request_object_t *obj, z ZVAL_OBJVAL(message, php_http_request_object_message(getThis(), msg TSRMLS_CC), 0); zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("responseMessage"), message TSRMLS_CC); zval_ptr_dtor(&message); - obj->request->parser.msg = php_http_message_init(NULL, 0 TSRMLS_CC); + obj->request->message = php_http_message_init(NULL, 0 TSRMLS_CC); } else { /* update properties with empty values */ zval *znull; @@ -1572,18 +522,11 @@ STATUS php_http_request_object_responsehandler(php_http_request_object_t *obj, z zend_update_property_string(php_http_request_class_entry, getThis(), ZEND_STRL("responseStatus"), "" TSRMLS_CC); } - php_http_request_set_progress_callback(obj->request, NULL); - - if (!EG(exception) && zend_hash_exists(&Z_OBJCE_P(getThis())->function_table, ZEND_STRS("onfinish"))) { - zval *param; - - MAKE_STD_ZVAL(param); - ZVAL_BOOL(param, ret == SUCCESS); - with_error_handling(EH_NORMAL, NULL) { - zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "onfinish", NULL, param); - } end_error_handling(); - zval_ptr_dtor(¶m); + if (SUCCESS == php_http_request_getopt(obj->request, PHP_HTTP_REQUEST_OPT_PROGRESS_INFO, &progress)) { + progress->state.finished = 1; + php_http_request_progress_notify(progress TSRMLS_CC); } + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_PROGRESS_CALLBACK, NULL); return ret; } @@ -1600,39 +543,37 @@ static inline void php_http_request_object_set_options_subr(INTERNAL_FUNCTION_PA { zval *old_opts, *new_opts, *opts = NULL, **entry = NULL; - if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a/!", &opts)) { - RETURN_FALSE; - } - - MAKE_STD_ZVAL(new_opts); - array_init(new_opts); - old_opts = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), 0 TSRMLS_CC); - if (Z_TYPE_P(old_opts) == IS_ARRAY) { - array_copy(Z_ARRVAL_P(old_opts), Z_ARRVAL_P(new_opts)); - } - - if (SUCCESS == zend_hash_find(Z_ARRVAL_P(new_opts), key, len, (void *) &entry)) { - if (overwrite) { - zend_hash_clean(Z_ARRVAL_PP(entry)); + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a/!", &opts)) { + MAKE_STD_ZVAL(new_opts); + array_init(new_opts); + old_opts = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), 0 TSRMLS_CC); + if (Z_TYPE_P(old_opts) == IS_ARRAY) { + array_copy(Z_ARRVAL_P(old_opts), Z_ARRVAL_P(new_opts)); } - if (opts && zend_hash_num_elements(Z_ARRVAL_P(opts))) { + + if (SUCCESS == zend_hash_find(Z_ARRVAL_P(new_opts), key, len, (void *) &entry)) { if (overwrite) { - array_copy(Z_ARRVAL_P(opts), Z_ARRVAL_PP(entry)); - } else { - array_join(Z_ARRVAL_P(opts), Z_ARRVAL_PP(entry), 0, prettify_keys ? ARRAY_JOIN_PRETTIFY : 0); + zend_hash_clean(Z_ARRVAL_PP(entry)); } + if (opts && zend_hash_num_elements(Z_ARRVAL_P(opts))) { + if (overwrite) { + array_copy(Z_ARRVAL_P(opts), Z_ARRVAL_PP(entry)); + } else { + array_join(Z_ARRVAL_P(opts), Z_ARRVAL_PP(entry), 0, prettify_keys ? ARRAY_JOIN_PRETTIFY : 0); + } + } + } else if (opts) { + if (prettify_keys) { + zend_hash_apply_with_arguments(Z_ARRVAL_P(opts) TSRMLS_CC, apply_pretty_key, 0, NULL); + } + Z_ADDREF_P(opts); + add_assoc_zval_ex(new_opts, key, len, opts); } - } else if (opts) { - if (prettify_keys) { - zend_hash_apply_with_arguments(Z_ARRVAL_P(opts) TSRMLS_CC, apply_pretty_key, 0, NULL); - } - Z_ADDREF_P(opts); - add_assoc_zval_ex(new_opts, key, len, opts); + zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), new_opts TSRMLS_CC); + zval_ptr_dtor(&new_opts); } - zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), new_opts TSRMLS_CC); - zval_ptr_dtor(&new_opts); - RETURN_TRUE; + RETVAL_ZVAL(getThis(), 1, 0); } static inline void php_http_request_object_get_options_subr(INTERNAL_FUNCTION_PARAMETERS, char *key, size_t len) @@ -1654,26 +595,130 @@ static inline void php_http_request_object_get_options_subr(INTERNAL_FUNCTION_PA PHP_METHOD(HttpRequest, __construct) { - char *url_str = NULL; - int url_len; - long meth = -1; - zval *options = NULL; + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { + zend_parse_parameters_none(); + } end_error_handling(); +} +PHP_METHOD(HttpRequest, getObservers) +{ with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { - if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sla!", &url_str, &url_len, &meth, &options)) { - if (url_str) { - zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("url"), url_str, url_len TSRMLS_CC); - } - if (meth > -1) { - zend_update_property_long(php_http_request_class_entry, getThis(), ZEND_STRL("method"), meth TSRMLS_CC); - } - if (options) { - zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "setoptions", NULL, options); - } + if (SUCCESS == zend_parse_parameters_none()) { + RETVAL_PROP(php_http_request_class_entry, "observers"); } } end_error_handling(); } +static int notify(zend_object_iterator *iter, void *puser TSRMLS_DC) +{ + zval **observer = NULL; + + iter->funcs->get_current_data(iter, &observer TSRMLS_CC); + if (observer) { + zval *retval; + + zend_call_method_with_1_params(observer, NULL, NULL, "update", &retval, puser); + zval_ptr_dtor(&retval); + return SUCCESS; + } + return FAILURE; +} + +PHP_METHOD(HttpRequest, notify) +{ + if (SUCCESS == zend_parse_parameters_none()) { + zval *observers = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("observers"), 0 TSRMLS_CC); + + if (Z_TYPE_P(observers) == IS_OBJECT) { + Z_ADDREF_P(getThis()); + spl_iterator_apply(observers, notify, getThis() TSRMLS_CC); + zval_ptr_dtor(&getThis()); + } + } + + RETVAL_ZVAL(getThis(), 1, 0); +} + +PHP_METHOD(HttpRequest, attach) +{ + zval *observer; + + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &observer, spl_ce_SplObserver)) { + zval *retval, *observers = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("observers"), 0 TSRMLS_CC); + zend_call_method_with_1_params(&observers, NULL, NULL, "attach", &retval, observer); + zval_ptr_dtor(&retval); + } + + RETVAL_ZVAL(getThis(), 1, 0); +} + +PHP_METHOD(HttpRequest, detach) +{ + zval *observer; + + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O", &observer, spl_ce_SplObserver)) { + zval *retval, *observers = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("observers"), 0 TSRMLS_CC); + zend_call_method_with_1_params(&observers, NULL, NULL, "detach", &retval, observer); + zval_ptr_dtor(&retval); + } + + RETVAL_ZVAL(getThis(), 1, 0); +} + +PHP_METHOD(HttpRequest, getProgress) +{ + if (SUCCESS == zend_parse_parameters_none()) { + php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + php_http_request_progress_t *progress; + + php_http_request_getopt(obj->request, PHP_HTTP_REQUEST_OPT_PROGRESS_INFO, &progress); + object_init(return_value); + add_property_bool(return_value, "started", progress->state.started); + add_property_bool(return_value, "finished", progress->state.finished); + add_property_double(return_value, "dltotal", progress->state.dl.total); + add_property_double(return_value, "dlnow", progress->state.dl.now); + add_property_double(return_value, "ultotal", progress->state.ul.total); + add_property_double(return_value, "ulnow", progress->state.ul.now); + } +} + +PHP_METHOD(HttpRequest, getTransferInfo) +{ + char *info_name = NULL; + int info_len = 0; + + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &info_name, &info_len)) { + zval **infop, *temp = NULL, *info = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("transferInfo"), 0 TSRMLS_CC); + + /* request completed? */ + if (Z_TYPE_P(info) != IS_ARRAY) { + php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + + MAKE_STD_ZVAL(temp); + array_init(temp); + php_http_request_getopt(obj->request, PHP_HTTP_REQUEST_OPT_TRANSFER_INFO, Z_ARRVAL_P(temp)); + info = temp; + } + + if (info_len && info_name) { + if (SUCCESS == zend_hash_find(Z_ARRVAL_P(info), php_http_pretty_key(info_name, info_len, 0, 0), info_len + 1, (void *) &infop)) { + RETVAL_ZVAL(*infop, 1, 0); + } else { + php_http_error(HE_NOTICE, PHP_HTTP_E_INVALID_PARAM, "Could not find transfer info named %s", info_name); + RETVAL_FALSE; + } + } else { + RETVAL_ZVAL(info, 1, 0); + } + + if (temp) { + zval_ptr_dtor(&temp); + } + return; + } + RETURN_FALSE; +} + PHP_METHOD(HttpRequest, setOptions) { php_http_array_hashkey_t key = php_http_array_hashkey_init(0); @@ -1690,65 +735,64 @@ PHP_METHOD(HttpRequest, setOptions) if (!opts || !zend_hash_num_elements(Z_ARRVAL_P(opts))) { zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), new_opts TSRMLS_CC); zval_ptr_dtor(&new_opts); - RETURN_TRUE; - } - - MAKE_STD_ZVAL(add_opts); - array_init(add_opts); - /* some options need extra attention -- thus cannot use array_merge() directly */ - FOREACH_KEYVAL(pos, opts, key, opt) { - if (key.type == HASH_KEY_IS_STRING) { + } else { + MAKE_STD_ZVAL(add_opts); + array_init(add_opts); + /* some options need extra attention -- thus cannot use array_merge() directly */ + FOREACH_KEYVAL(pos, opts, key, opt) { + if (key.type == HASH_KEY_IS_STRING) { #define KEYMATCH(k, s) ((sizeof(s)==k.len) && !strcasecmp(k.str, s)) - if (KEYMATCH(key, "headers")) { - zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "addheaders", NULL, *opt); - } else if (KEYMATCH(key, "cookies")) { - zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "addcookies", NULL, *opt); - } else if (KEYMATCH(key, "ssl")) { - zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "addssloptions", NULL, *opt); - } else if (KEYMATCH(key, "url") || KEYMATCH(key, "uri")) { - zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "seturl", NULL, *opt); - } else if (KEYMATCH(key, "method")) { - zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "setmethod", NULL, *opt); - } else if (KEYMATCH(key, "flushcookies")) { - if (i_zend_is_true(*opt)) { + if (KEYMATCH(key, "headers")) { + zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "addheaders", NULL, *opt); + } else if (KEYMATCH(key, "cookies")) { + zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "addcookies", NULL, *opt); + } else if (KEYMATCH(key, "ssl")) { + zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "addssloptions", NULL, *opt); + } else if (KEYMATCH(key, "url") || KEYMATCH(key, "uri")) { + zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "seturl", NULL, *opt); + } else if (KEYMATCH(key, "method")) { + zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "setmethod", NULL, *opt); + } else if (KEYMATCH(key, "flushcookies")) { + if (i_zend_is_true(*opt)) { + php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_COOKIES_FLUSH, NULL); + } + } else if (KEYMATCH(key, "resetcookies")) { php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - php_http_request_flush_cookies(obj->request); - } - } else if (KEYMATCH(key, "resetcookies")) { - php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - - php_http_request_reset_cookies(obj->request, (zend_bool) i_zend_is_true(*opt)); - } else if (KEYMATCH(key, "enablecookies")) { - php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - - php_http_request_enable_cookies(obj->request); - } else if (KEYMATCH(key, "recordHistory")) { - zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("recordHistory"), *opt TSRMLS_CC); - } else if (KEYMATCH(key, "messageClass")) { - zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "setmessageclass", NULL, *opt); - } else if (Z_TYPE_PP(opt) == IS_NULL) { - old_opts = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), 0 TSRMLS_CC); - if (Z_TYPE_P(old_opts) == IS_ARRAY) { - zend_hash_del(Z_ARRVAL_P(old_opts), key.str, key.len); + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_COOKIES_RESET, NULL); + } else if (KEYMATCH(key, "enablecookies")) { + php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_COOKIES_ENABLE, NULL); + } else if (KEYMATCH(key, "recordHistory")) { + zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("recordHistory"), *opt TSRMLS_CC); + } else if (KEYMATCH(key, "messageClass")) { + zend_call_method_with_1_params(&getThis(), Z_OBJCE_P(getThis()), NULL, "setmessageclass", NULL, *opt); + } else if (Z_TYPE_PP(opt) == IS_NULL) { + old_opts = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), 0 TSRMLS_CC); + if (Z_TYPE_P(old_opts) == IS_ARRAY) { + zend_hash_del(Z_ARRVAL_P(old_opts), key.str, key.len); + } + } else { + Z_ADDREF_P(*opt); + add_assoc_zval_ex(add_opts, key.str, key.len, *opt); } - } else { - Z_ADDREF_P(*opt); - add_assoc_zval_ex(add_opts, key.str, key.len, *opt); } } - } - old_opts = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), 0 TSRMLS_CC); - if (Z_TYPE_P(old_opts) == IS_ARRAY) { - array_copy(Z_ARRVAL_P(old_opts), Z_ARRVAL_P(new_opts)); + old_opts = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), 0 TSRMLS_CC); + if (Z_TYPE_P(old_opts) == IS_ARRAY) { + array_copy(Z_ARRVAL_P(old_opts), Z_ARRVAL_P(new_opts)); + } + array_join(Z_ARRVAL_P(add_opts), Z_ARRVAL_P(new_opts), 0, 0); + zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), new_opts TSRMLS_CC); + zval_ptr_dtor(&new_opts); + zval_ptr_dtor(&add_opts); } - array_join(Z_ARRVAL_P(add_opts), Z_ARRVAL_P(new_opts), 0, 0); - zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("options"), new_opts TSRMLS_CC); - zval_ptr_dtor(&new_opts); - zval_ptr_dtor(&add_opts); - RETURN_TRUE; + RETVAL_ZVAL(getThis(), 1, 0); } @@ -1811,9 +855,9 @@ PHP_METHOD(HttpRequest, enableCookies) if (SUCCESS == zend_parse_parameters_none()){ php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - RETURN_SUCCESS(php_http_request_enable_cookies(obj->request)); + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_COOKIES_ENABLE, NULL); } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, resetCookies) @@ -1822,9 +866,13 @@ PHP_METHOD(HttpRequest, resetCookies) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &session_only)) { php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - RETURN_SUCCESS(php_http_request_reset_cookies(obj->request, session_only)); + if (session_only) { + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_COOKIES_RESET_SESSION, NULL); + } else { + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_COOKIES_RESET, NULL); + } } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, flushCookies) @@ -1832,9 +880,9 @@ PHP_METHOD(HttpRequest, flushCookies) if (SUCCESS == zend_parse_parameters_none()) { php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - RETURN_SUCCESS(php_http_request_flush_cookies(obj->request)); + php_http_request_setopt(obj->request, PHP_HTTP_REQUEST_OPT_COOKIES_FLUSH, NULL); } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, setUrl) @@ -1842,11 +890,10 @@ PHP_METHOD(HttpRequest, setUrl) char *url_str = NULL; int url_len; - if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &url_len, &url_len)) { + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &url_str, &url_len)) { zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("url"), url_str, url_len TSRMLS_CC); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, getUrl) @@ -1863,9 +910,8 @@ PHP_METHOD(HttpRequest, setMethod) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &meth)) { zend_update_property_long(php_http_request_class_entry, getThis(), ZEND_STRL("method"), meth TSRMLS_CC); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, getMethod) @@ -1882,13 +928,17 @@ PHP_METHOD(HttpRequest, setContentType) int ct_len; if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &ctype, &ct_len)) { + int invalid = 0; + if (ct_len) { - PHP_HTTP_CHECK_CONTENT_TYPE(ctype, RETURN_FALSE); + PHP_HTTP_CHECK_CONTENT_TYPE(ctype, invalid = 1); + } + + if (!invalid) { + zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("contentType"), ctype, ct_len TSRMLS_CC); } - zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("contentType"), ctype, ct_len TSRMLS_CC); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, getContentType) @@ -1910,21 +960,18 @@ PHP_METHOD(HttpRequest, setQueryData) char *query_data_str = NULL; size_t query_data_len; - if (SUCCESS != php_http_url_encode_hash(HASH_OF(qdata), 0, NULL, 0, &query_data_str, &query_data_len TSRMLS_CC)) { - RETURN_FALSE; + if (SUCCESS == php_http_url_encode_hash(HASH_OF(qdata), 0, NULL, 0, &query_data_str, &query_data_len TSRMLS_CC)) { + zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("queryData"), query_data_str, query_data_len TSRMLS_CC); + efree(query_data_str); } - - zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("queryData"), query_data_str, query_data_len TSRMLS_CC); - efree(query_data_str); } else { zval *data = php_http_zsep(IS_STRING, qdata); zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("queryData"), Z_STRVAL_P(data), Z_STRLEN_P(data) TSRMLS_CC); zval_ptr_dtor(&data); } - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, getQueryData) @@ -1944,16 +991,12 @@ PHP_METHOD(HttpRequest, addQueryData) size_t query_data_len = 0; zval *old_qdata = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("queryData"), 0 TSRMLS_CC); - if (SUCCESS != php_http_url_encode_hash(HASH_OF(qdata), 1, Z_STRVAL_P(old_qdata), Z_STRLEN_P(old_qdata), &query_data_str, &query_data_len TSRMLS_CC)) { - RETURN_FALSE; + if (SUCCESS == php_http_url_encode_hash(HASH_OF(qdata), 1, Z_STRVAL_P(old_qdata), Z_STRLEN_P(old_qdata), &query_data_str, &query_data_len TSRMLS_CC)) { + zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("queryData"), query_data_str, query_data_len TSRMLS_CC); + efree(query_data_str); } - - zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("queryData"), query_data_str, query_data_len TSRMLS_CC); - efree(query_data_str); - - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } @@ -1967,9 +1010,8 @@ PHP_METHOD(HttpRequest, setBody) } else { zend_update_property_null(php_http_request_class_entry, getThis(), ZEND_STRL("requestBody") TSRMLS_CC); } - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, addBody) @@ -1987,9 +1029,8 @@ PHP_METHOD(HttpRequest, addBody) } else { zend_update_property(php_http_request_class_entry, getThis(), ZEND_STRL("requestBody"), new_body TSRMLS_CC); } - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, getBody) @@ -2124,32 +1165,6 @@ PHP_METHOD(HttpRequest, getResponseStatus) RETURN_FALSE; } -PHP_METHOD(HttpRequest, getResponseInfo) -{ - char *info_name = NULL; - int info_len = 0; - - if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &info_name, &info_len)) { - zval **infop, *info = zend_read_property(php_http_request_class_entry, getThis(), ZEND_STRL("responseInfo"), 0 TSRMLS_CC); - - if (Z_TYPE_P(info) != IS_ARRAY) { - RETURN_FALSE; - } - - if (info_len && info_name) { - if (SUCCESS == zend_hash_find(Z_ARRVAL_P(info), php_http_pretty_key(info_name, info_len, 0, 0), info_len + 1, (void *) &infop)) { - RETURN_ZVAL(*infop, 1, 0); - } else { - php_http_error(HE_NOTICE, PHP_HTTP_E_INVALID_PARAM, "Could not find response info named %s", info_name); - RETURN_FALSE; - } - } else { - RETURN_ZVAL(info, 1, 0); - } - } - RETURN_FALSE; -} - PHP_METHOD(HttpRequest, getResponseMessage) { with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { @@ -2199,9 +1214,8 @@ PHP_METHOD(HttpRequest, clearHistory) { if (SUCCESS == zend_parse_parameters_none()) { zend_update_property_null(php_http_request_class_entry, getThis(), ZEND_STRL("history") TSRMLS_CC); - RETURN_TRUE; } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, getMessageClass) @@ -2220,6 +1234,7 @@ PHP_METHOD(HttpRequest, setMessageClass) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &cn, &cl)) { zend_update_property_stringl(php_http_request_class_entry, getThis(), ZEND_STRL("messageClass"), cn, cl TSRMLS_CC); } + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequest, send) @@ -2229,11 +1244,12 @@ PHP_METHOD(HttpRequest, send) with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { if (SUCCESS == zend_parse_parameters_none()) { php_http_request_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); + php_http_request_method_t meth = PHP_HTTP_NO_REQUEST_METHOD; + php_http_message_body_t *body = NULL; + char *url = NULL; - if (obj->pool) { - php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "Cannot perform HttpRequest::send() while attached to an HttpRequestPool"); - } else if (SUCCESS == php_http_request_object_requesthandler(obj, getThis() TSRMLS_CC)) { - php_http_request_exec(obj->request); + if (SUCCESS == php_http_request_object_requesthandler(obj, getThis(), &meth, &url, &body TSRMLS_CC)) { + php_http_request_exec(obj->request, meth, url, body); if (SUCCESS == php_http_request_object_responsehandler(obj, getThis() TSRMLS_CC)) { RETVAL_PROP(php_http_request_class_entry, "responseMessage"); } else { @@ -2242,46 +1258,24 @@ PHP_METHOD(HttpRequest, send) } else { php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "Failed to handle request"); } + + STR_FREE(url); } } end_error_handling(); } PHP_MINIT_FUNCTION(http_request) { -#ifdef PHP_HTTP_NEED_OPENSSL_TSL - /* mod_ssl, libpq or ext/curl might already have set thread lock callbacks */ - if (!CRYPTO_get_id_callback()) { - int i, c = CRYPTO_num_locks(); - - php_http_openssl_tsl = malloc(c * sizeof(MUTEX_T)); - - for (i = 0; i < c; ++i) { - php_http_openssl_tsl[i] = tsrm_mutex_alloc(); - } - - CRYPTO_set_id_callback(php_http_openssl_thread_id); - CRYPTO_set_locking_callback(php_http_openssl_thread_lock); - } -#endif -#ifdef PHP_HTTP_NEED_GNUTLS_TSL - gcry_control(GCRYCTL_SET_THREAD_CBS, &php_http_gnutls_tsl); -#endif - - if (CURLE_OK != curl_global_init(CURL_GLOBAL_ALL)) { - return FAILURE; - } - - if (SUCCESS != php_http_persistent_handle_provide(ZEND_STRL("http_request"), safe_curl_init, safe_curl_dtor, safe_curl_copy)) { - return FAILURE; - } - PHP_HTTP_REGISTER_CLASS(http, Request, http_request, php_http_object_class_entry, 0); php_http_request_class_entry->create_object = php_http_request_object_new; memcpy(&php_http_request_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); php_http_request_object_handlers.clone_obj = php_http_request_object_clone; + zend_class_implements(php_http_request_class_entry TSRMLS_CC, 2, spl_ce_SplSubject, php_http_fluently_callable_class_entry); + + zend_declare_property_null(php_http_request_class_entry, ZEND_STRL("observers"), ZEND_ACC_PRIVATE TSRMLS_CC); zend_declare_property_null(php_http_request_class_entry, ZEND_STRL("options"), ZEND_ACC_PRIVATE TSRMLS_CC); - zend_declare_property_null(php_http_request_class_entry, ZEND_STRL("responseInfo"), ZEND_ACC_PRIVATE TSRMLS_CC); + zend_declare_property_null(php_http_request_class_entry, ZEND_STRL("transferInfo"), ZEND_ACC_PRIVATE TSRMLS_CC); zend_declare_property_null(php_http_request_class_entry, ZEND_STRL("responseMessage"), ZEND_ACC_PRIVATE TSRMLS_CC); zend_declare_property_long(php_http_request_class_entry, ZEND_STRL("responseCode"), 0, ZEND_ACC_PRIVATE TSRMLS_CC); zend_declare_property_string(php_http_request_class_entry, ZEND_STRL("responseStatus"), "", ZEND_ACC_PRIVATE TSRMLS_CC); @@ -2295,83 +1289,6 @@ PHP_MINIT_FUNCTION(http_request) zend_declare_property_bool(php_http_request_class_entry, ZEND_STRL("recordHistory"), 0, ZEND_ACC_PUBLIC TSRMLS_CC); zend_declare_property_string(php_http_request_class_entry, ZEND_STRL("messageClass"), "", ZEND_ACC_PRIVATE TSRMLS_CC); - /* - * HTTP Protocol Version Constants - */ - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("VERSION_1_0"), CURL_HTTP_VERSION_1_0 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("VERSION_1_1"), CURL_HTTP_VERSION_1_1 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("VERSION_NONE"), CURL_HTTP_VERSION_NONE TSRMLS_CC); /* to be removed */ - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("VERSION_ANY"), CURL_HTTP_VERSION_NONE TSRMLS_CC); - - /* - * SSL Version Constants - */ - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("SSL_VERSION_TLSv1"), CURL_SSLVERSION_TLSv1 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("SSL_VERSION_SSLv2"), CURL_SSLVERSION_SSLv2 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("SSL_VERSION_SSLv3"), CURL_SSLVERSION_SSLv3 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("SSL_VERSION_ANY"), CURL_SSLVERSION_DEFAULT TSRMLS_CC); - - /* - * DNS IPvX resolving - */ - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("IPRESOLVE_V4"), CURL_IPRESOLVE_V4 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("IPRESOLVE_V6"), CURL_IPRESOLVE_V6 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("IPRESOLVE_ANY"), CURL_IPRESOLVE_WHATEVER TSRMLS_CC); - - /* - * Auth Constants - */ - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_BASIC"), CURLAUTH_BASIC TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_DIGEST"), CURLAUTH_DIGEST TSRMLS_CC); -#if PHP_HTTP_CURL_VERSION(7,19,3) - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_DIGEST_IE"), CURLAUTH_DIGEST_IE TSRMLS_CC); -#endif - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_NTLM"), CURLAUTH_NTLM TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_GSSNEG"), CURLAUTH_GSSNEGOTIATE TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("AUTH_ANY"), CURLAUTH_ANY TSRMLS_CC); - - /* - * Proxy Type Constants - */ - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS4"), CURLPROXY_SOCKS4 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS4A"), CURLPROXY_SOCKS5 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS5_HOSTNAME"), CURLPROXY_SOCKS5 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_SOCKS5"), CURLPROXY_SOCKS5 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_HTTP"), CURLPROXY_HTTP TSRMLS_CC); -# if PHP_HTTP_CURL_VERSION(7,19,4) - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("PROXY_HTTP_1_0"), CURLPROXY_HTTP_1_0 TSRMLS_CC); -# endif - - /* - * Post Redirection Constants - */ -#if PHP_HTTP_CURL_VERSION(7,19,1) - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("POSTREDIR_301"), CURL_REDIR_POST_301 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("POSTREDIR_302"), CURL_REDIR_POST_302 TSRMLS_CC); - zend_declare_class_constant_long(php_http_request_class_entry, ZEND_STRL("POSTREDIR_ALL"), CURL_REDIR_POST_ALL TSRMLS_CC); -#endif - - return SUCCESS; -} - -PHP_MSHUTDOWN_FUNCTION(http_request) -{ - curl_global_cleanup(); -#ifdef PHP_HTTP_NEED_OPENSSL_TSL - if (php_http_openssl_tsl) { - int i, c = CRYPTO_num_locks(); - - CRYPTO_set_id_callback(NULL); - CRYPTO_set_locking_callback(NULL); - - for (i = 0; i < c; ++i) { - tsrm_mutex_free(php_http_openssl_tsl[i]); - } - - free(php_http_openssl_tsl); - php_http_openssl_tsl = NULL; - } -#endif return SUCCESS; } diff --git a/php_http_request.h b/php_http_request.h index a81199e..b848612 100644 --- a/php_http_request.h +++ b/php_http_request.h @@ -15,127 +15,147 @@ #ifndef PHP_HTTP_REQUEST_H #define PHP_HTTP_REQUEST_H -#include - +#include "php_http_message_body.h" +#include "php_http_message_parser.h" #include "php_http_request_method.h" -#include "php_http_request_pool.h" - -extern PHP_MINIT_FUNCTION(http_request); -extern PHP_MSHUTDOWN_FUNCTION(http_request); - -typedef struct php_http_request_progress_state_counter { - double now; - double total; -} php_http_request_progress_state_counter_t; typedef struct php_http_request_progress_state { - php_http_request_progress_state_counter_t ul; - php_http_request_progress_state_counter_t dl; -} php_http_request_progress_state_t; - -typedef struct php_http_request { - CURL *ch; - char *url; - php_http_request_method_t meth; - php_http_message_body_t *body; - struct { - php_http_message_parser_t *ctx; - php_http_message_t *msg; - php_http_buffer_t *buf; - } parser; - struct { - php_http_buffer_t cookies; - HashTable options; - struct curl_slist *headers; - long redirects; - } _cache; - + double now; + double total; + } ul; struct { - uint count; - double delay; - } _retry; - - struct { - struct { - struct { - double now; - double total; - } ul; - struct { - double now; - double total; - } dl; - } state; - zval *callback; - unsigned in_cb:1; - } _progress; - -#ifdef ZTS - void ***ts; -#endif - -} php_http_request_t; - -/* CURLOPT_PRIVATE storage living as long as a CURL handle */ -typedef struct php_http_request_storage { - char *url; - char *cookiestore; - char errorbuffer[CURL_ERROR_SIZE]; -} php_http_request_storage_t; + double now; + double total; + } dl; + unsigned started:1; + unsigned finished:1; +} php_http_request_progress_state_t; +typedef struct php_http_request_progress { + php_http_request_progress_state_t state; + zval *callback; + unsigned in_cb:1; + unsigned pass_state:1; +} php_http_request_progress_t; -static inline php_http_request_storage_t *php_http_request_storage_get(CURL *ch) +static inline void php_http_request_progress_notify(php_http_request_progress_t *progress TSRMLS_DC) { - php_http_request_storage_t *st = NULL; - curl_easy_getinfo(ch, CURLINFO_PRIVATE, &st); - return st; -} - -PHP_HTTP_API CURL *php_http_curl_init(CURL *ch, php_http_request_t *request TSRMLS_DC); -PHP_HTTP_API void php_http_curl_free(CURL **ch TSRMLS_DC); -PHP_HTTP_API CURL *php_http_curl_copy(CURL *ch TSRMLS_DC); - -#define PHP_HTTP_CHECK_CURL_INIT(ch, init, action) \ - if ((!(ch)) && (!((ch) = init))) { \ - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "Could not initialize curl"); \ - action; \ + if (progress->callback) { + zval retval; + + INIT_PZVAL(&retval); + ZVAL_NULL(&retval); + + with_error_handling(EH_NORMAL, NULL) { + if (progress->pass_state) { + zval *param; + + MAKE_STD_ZVAL(param); + array_init(param); + add_assoc_bool(param, "started", progress->state.started); + add_assoc_bool(param, "finished", progress->state.finished); + add_assoc_double(param, "dltotal", progress->state.dl.total); + add_assoc_double(param, "dlnow", progress->state.dl.now); + add_assoc_double(param, "ultotal", progress->state.ul.total); + add_assoc_double(param, "ulnow", progress->state.ul.now); + + progress->in_cb = 1; + call_user_function(EG(function_table), NULL, progress->callback, &retval, 1, ¶m TSRMLS_CC); + progress->in_cb = 0; + + zval_ptr_dtor(¶m); + } else { + progress->in_cb = 1; + call_user_function(EG(function_table), NULL, progress->callback, &retval, 0, NULL TSRMLS_CC); + progress->in_cb = 0; + } + } end_error_handling(); + + zval_dtor(&retval); } +} +typedef enum php_http_request_setopt_opt { + PHP_HTTP_REQUEST_OPT_SETTINGS, /* HashTable* */ + PHP_HTTP_REQUEST_OPT_PROGRESS_CALLBACK, /* zval* */ + PHP_HTTP_REQUEST_OPT_PROGRESS_CALLBACK_WANTS_STATE, /* int* */ + PHP_HTTP_REQUEST_OPT_COOKIES_ENABLE, /* - */ + PHP_HTTP_REQUEST_OPT_COOKIES_RESET, /* - */ + PHP_HTTP_REQUEST_OPT_COOKIES_RESET_SESSION, /* - */ + PHP_HTTP_REQUEST_OPT_COOKIES_FLUSH, /* - */ +} php_http_request_setopt_opt_t; + +typedef enum php_http_request_getopt_opt { + PHP_HTTP_REQUEST_OPT_PROGRESS_INFO, /* php_http_request_progress_t** */ + PHP_HTTP_REQUEST_OPT_TRANSFER_INFO, /* HashTable* */ +} php_http_request_getopt_opt_t; + +typedef struct php_http_request php_http_request_t; + +typedef php_http_request_t *(*php_http_request_init_func_t)(php_http_request_t *h, void *arg); +typedef php_http_request_t *(*php_http_request_copy_func_t)(php_http_request_t *from, php_http_request_t *to); +typedef void (*php_http_request_dtor_func_t)(php_http_request_t *h); +typedef STATUS (*php_http_request_exec_func_t)(php_http_request_t *h, php_http_request_method_t meth, const char *url, php_http_message_body_t *body); +typedef STATUS (*php_http_request_reset_func_t)(php_http_request_t *h); +typedef STATUS (*php_http_request_setopt_func_t)(php_http_request_t *h, php_http_request_setopt_opt_t opt, void *arg); +typedef STATUS (*php_http_request_getopt_func_t)(php_http_request_t *h, php_http_request_getopt_opt_t opt, void *arg); + +typedef struct php_http_request_ops { + php_http_request_init_func_t init; + php_http_request_copy_func_t copy; + php_http_request_dtor_func_t dtor; + php_http_request_reset_func_t reset; + php_http_request_exec_func_t exec; + php_http_request_setopt_func_t setopt; + php_http_request_getopt_func_t getopt; +} php_http_request_ops_t; + +PHP_HTTP_API php_http_request_ops_t *php_http_request_get_default_ops(TSRMLS_D); + +struct php_http_request { + void *ctx; + php_http_request_ops_t *ops; + php_http_message_parser_t *parser; + php_http_message_t *message; + php_http_buffer_t *buffer; +#ifdef ZTS + void ***ts; +#endif +}; -PHP_HTTP_API php_http_request_t *php_http_request_init(php_http_request_t *request, CURL *ch, php_http_request_method_t meth, const char *url TSRMLS_DC); -PHP_HTTP_API void php_http_request_dtor(php_http_request_t *request); -PHP_HTTP_API void php_http_request_free(php_http_request_t **request); -PHP_HTTP_API void php_http_request_reset(php_http_request_t *r); -PHP_HTTP_API STATUS php_http_request_enable_cookies(php_http_request_t *request); -PHP_HTTP_API STATUS php_http_request_reset_cookies(php_http_request_t *request, int session_only); -PHP_HTTP_API STATUS php_http_request_flush_cookies(php_http_request_t *request); -PHP_HTTP_API void php_http_request_defaults(php_http_request_t *request); -PHP_HTTP_API STATUS php_http_request_prepare(php_http_request_t *request, HashTable *options); -PHP_HTTP_API void php_http_request_exec(php_http_request_t *request); -PHP_HTTP_API void php_http_request_info(php_http_request_t *request, HashTable *info); -PHP_HTTP_API void php_http_request_set_progress_callback(php_http_request_t *request, zval *cb); - +PHP_HTTP_API php_http_request_t *php_http_request_init(php_http_request_t *h, php_http_request_ops_t *ops, void *init_arg TSRMLS_DC); +PHP_HTTP_API php_http_request_t *php_http_request_copy(php_http_request_t *from, php_http_request_t *to); +PHP_HTTP_API STATUS php_http_request_exec(php_http_request_t *h, php_http_request_method_t meth, const char *url, php_http_message_body_t *body); +PHP_HTTP_API STATUS php_http_request_reset(php_http_request_t *h); +PHP_HTTP_API STATUS php_http_request_setopt(php_http_request_t *h, php_http_request_setopt_opt_t opt, void *arg); +PHP_HTTP_API STATUS php_http_request_getopt(php_http_request_t *h, php_http_request_getopt_opt_t opt, void *arg); +PHP_HTTP_API void php_http_request_dtor(php_http_request_t *h); +PHP_HTTP_API void php_http_request_free(php_http_request_t **h); typedef struct php_http_request_object { zend_object zo; php_http_request_t *request; - php_http_request_pool_t *pool; - php_http_request_datashare_t *share; } php_http_request_object_t; extern zend_class_entry *php_http_request_class_entry; extern zend_function_entry php_http_request_method_entry[]; extern zend_object_value php_http_request_object_new(zend_class_entry *ce TSRMLS_DC); -extern zend_object_value php_http_request_object_new_ex(zend_class_entry *ce, CURL *ch, php_http_request_object_t **ptr TSRMLS_DC); +extern zend_object_value php_http_request_object_new_ex(zend_class_entry *ce, php_http_request_t *r, php_http_request_object_t **ptr TSRMLS_DC); extern zend_object_value php_http_request_object_clone(zval *zobject TSRMLS_DC); extern void php_http_request_object_free(void *object TSRMLS_DC); -extern STATUS php_http_request_object_requesthandler(php_http_request_object_t *obj, zval *this_ptr TSRMLS_DC); +extern STATUS php_http_request_object_requesthandler(php_http_request_object_t *obj, zval *this_ptr, php_http_request_method_t *meth, char **url, php_http_message_body_t **body TSRMLS_DC); extern STATUS php_http_request_object_responsehandler(php_http_request_object_t *obj, zval *this_ptr TSRMLS_DC); PHP_METHOD(HttpRequest, __construct); +PHP_METHOD(HttpRequest, getObservers); +PHP_METHOD(HttpRequest, notify); +PHP_METHOD(HttpRequest, attach); +PHP_METHOD(HttpRequest, detach); +PHP_METHOD(HttpRequest, getProgress); +PHP_METHOD(HttpRequest, getTransferInfo); PHP_METHOD(HttpRequest, setOptions); PHP_METHOD(HttpRequest, getOptions); PHP_METHOD(HttpRequest, addSslOptions); @@ -169,7 +189,6 @@ PHP_METHOD(HttpRequest, getResponseCookies); PHP_METHOD(HttpRequest, getResponseCode); PHP_METHOD(HttpRequest, getResponseStatus); PHP_METHOD(HttpRequest, getResponseBody); -PHP_METHOD(HttpRequest, getResponseInfo); PHP_METHOD(HttpRequest, getResponseMessage); PHP_METHOD(HttpRequest, getRawResponseMessage); PHP_METHOD(HttpRequest, getRequestMessage); @@ -179,6 +198,8 @@ PHP_METHOD(HttpRequest, clearHistory); PHP_METHOD(HttpRequest, getMessageClass); PHP_METHOD(HttpRequest, setMessageClass); +extern PHP_MINIT_FUNCTION(http_request); + #endif /* diff --git a/php_http_request_datashare.c b/php_http_request_datashare.c index f572d3f..68e4c07 100644 --- a/php_http_request_datashare.c +++ b/php_http_request_datashare.c @@ -1,150 +1,114 @@ #include "php_http.h" +#include #include -static HashTable php_http_request_datashare_options; -static php_http_request_datashare_t php_http_request_datashare_global; static int php_http_request_datashare_compare_handles(void *h1, void *h2); -static void php_http_request_datashare_destroy_handles(void *el); #ifdef ZTS static void *php_http_request_datashare_locks_init(void); static void php_http_request_datashare_locks_dtor(void *l); static void php_http_request_datashare_lock_func(CURL *handle, curl_lock_data data, curl_lock_access locktype, void *userptr); static void php_http_request_datashare_unlock_func(CURL *handle, curl_lock_data data, void *userptr); +static MUTEX_T php_http_request_datashare_global_shares_lock; #endif - -php_http_request_datashare_t *php_http_request_datashare_global_get(void) -{ - return &php_http_request_datashare_global; -} - -PHP_HTTP_API php_http_request_datashare_t *php_http_request_datashare_init(php_http_request_datashare_t *share, zend_bool persistent TSRMLS_DC) +static HashTable php_http_request_datashare_global_shares; +php_http_request_datashare_t *php_http_request_datashare_global_get(const char *driver_str, size_t driver_len TSRMLS_DC) { - zend_bool free_share; + php_http_request_datashare_t *s = NULL, **s_ptr; + char *lower_str = php_strtolower(estrndup(driver_str, driver_len), driver_len); - if ((free_share = !share)) { - share = pemalloc(sizeof(php_http_request_datashare_t), persistent); - } - memset(share, 0, sizeof(php_http_request_datashare_t)); +#ifdef ZTS + tsrm_mutex_lock(php_http_request_datashare_global_shares_lock); +#endif + if (zend_hash_find(&php_http_request_datashare_global_shares, lower_str, driver_len + 1, (void *) &s_ptr)) { + s = *s_ptr; + } else { + php_http_request_factory_driver_t driver; - if (SUCCESS != php_http_persistent_handle_acquire(ZEND_STRL("http_request_datashare"), &share->ch TSRMLS_CC)) { - if (free_share) { - pefree(share, persistent); + if ((SUCCESS == php_http_request_factory_get_driver(driver_str, driver_len, &driver)) && driver.request_datashare_ops) { + s = php_http_request_datashare_init(NULL, driver.request_datashare_ops, NULL, 1 TSRMLS_CC); + zend_hash_add(&php_http_request_datashare_global_shares, lower_str, driver_len + 1, &s, sizeof(php_http_request_datashare_t *), NULL); } - return NULL; } - - if (!(share->persistent = persistent)) { - share->handle.list = emalloc(sizeof(zend_llist)); - zend_llist_init(share->handle.list, sizeof(zval *), ZVAL_PTR_DTOR, 0); #ifdef ZTS - } else { - if (SUCCESS == php_http_persistent_handle_acquire(ZEND_STRL("http_request_datashare_lock"), (void *) &share->handle.locks)) { - curl_share_setopt(share->ch, CURLSHOPT_LOCKFUNC, php_http_request_datashare_lock_func); - curl_share_setopt(share->ch, CURLSHOPT_UNLOCKFUNC, php_http_request_datashare_unlock_func); - curl_share_setopt(share->ch, CURLSHOPT_USERDATA, share->handle.locks); - } + tsrm_mutex_unlock(php_http_request_datashare_global_shares_lock); #endif - } - TSRMLS_SET_CTX(share->ts); - - return share; + efree(lower_str); + return s; } -PHP_HTTP_API STATUS php_http_request_datashare_attach(php_http_request_datashare_t *share, zval *request) +PHP_HTTP_API php_http_request_datashare_t *php_http_request_datashare_init(php_http_request_datashare_t *h, php_http_request_datashare_ops_t *ops, void *init_arg, zend_bool persistent TSRMLS_DC) { - CURLcode rc; - TSRMLS_FETCH_FROM_CTX(share->ts); - php_http_request_object_t *obj = zend_object_store_get_object(request TSRMLS_CC); + php_http_request_datashare_t *free_h; - if (obj->share) { - if (obj->share == share) { - return SUCCESS; - } else if (SUCCESS != php_http_request_datashare_detach(obj->share, request)) { - return FAILURE; - } + if (!h) { + free_h = h = pemalloc(sizeof(*h), persistent); } + memset(h, sizeof(*h), 0); - PHP_HTTP_CHECK_CURL_INIT(obj->request->ch, php_http_curl_init(obj->request->ch, obj->request TSRMLS_CC), return FAILURE); - if (CURLE_OK != (rc = curl_easy_setopt(obj->request->ch, CURLOPT_SHARE, share->ch))) { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "Could not attach HttpRequest object(#%d) to the HttpRequestDataShare: %s", Z_OBJ_HANDLE_P(request), curl_easy_strerror(rc)); - return FAILURE; + if (!(h->persistent = persistent)) { + h->requests = emalloc(sizeof(*h->requests)); + zend_llist_init(h->requests, sizeof(zval *), ZVAL_PTR_DTOR, 0); + TSRMLS_SET_CTX(h->ts); } + h->ops = ops; - obj->share = share; - Z_ADDREF_P(request); - zend_llist_add_element(PHP_HTTP_RSHARE_HANDLES(share), (void *) &request); + if (h->ops->init) { + if (!(h = h->ops->init(h, init_arg))) { + if (free_h) { + pefree(free_h, persistent); + } + } + } - return SUCCESS; + return h; } -PHP_HTTP_API STATUS php_http_request_datashare_detach(php_http_request_datashare_t *share, zval *request) +PHP_HTTP_API php_http_request_datashare_t *php_http_request_datashare_copy(php_http_request_datashare_t *from, php_http_request_datashare_t *to) { - CURLcode rc; - TSRMLS_FETCH_FROM_CTX(share->ts); - php_http_request_object_t *obj = zend_object_store_get_object(request TSRMLS_CC); - - if (!obj->share) { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "HttpRequest object(#%d) is not attached to any HttpRequestDataShare", Z_OBJ_HANDLE_P(request)); - } else if (obj->share != share) { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "HttpRequest object(#%d) is not attached to this HttpRequestDataShare", Z_OBJ_HANDLE_P(request)); - } else if (CURLE_OK != (rc = curl_easy_setopt(obj->request->ch, CURLOPT_SHARE, NULL))) { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "Could not detach HttpRequest object(#%d) from the HttpRequestDataShare: %s", Z_OBJ_HANDLE_P(request), curl_share_strerror(rc)); - } else { - obj->share = NULL; - zend_llist_del_element(PHP_HTTP_RSHARE_HANDLES(share), request, php_http_request_datashare_compare_handles); - return SUCCESS; + if (from->ops->copy) { + return from->ops->copy(from, to); } - return FAILURE; -} - -PHP_HTTP_API void php_http_request_datashare_detach_all(php_http_request_datashare_t *share) -{ - zval **r; - while ((r = zend_llist_get_first(PHP_HTTP_RSHARE_HANDLES(share)))) { - php_http_request_datashare_detach(share, *r); - } + return NULL; } -PHP_HTTP_API void php_http_request_datashare_dtor(php_http_request_datashare_t *share) +PHP_HTTP_API void php_http_request_datashare_dtor(php_http_request_datashare_t *h) { - TSRMLS_FETCH_FROM_CTX(share->ts); - - if (!share->persistent) { - zend_llist_destroy(share->handle.list); - efree(share->handle.list); + if (h->ops->dtor) { + h->ops->dtor(h); } - php_http_persistent_handle_release(ZEND_STRL("http_request_datashare"), &share->ch TSRMLS_CC); -#ifdef ZTS - if (share->persistent) { - php_http_persistent_handle_release(ZEND_STRL("http_request_datashare_lock"), (void *) &share->handle.locks TSRMLS_CC); + if (h->requests) { + zend_llist_destroy(h->requests); + pefree(h->requests, h->persistent); + h->requests = NULL; } -#endif } -PHP_HTTP_API void php_http_request_datashare_free(php_http_request_datashare_t **share) +PHP_HTTP_API void php_http_request_datashare_free(php_http_request_datashare_t **h) { - php_http_request_datashare_dtor(*share); - pefree(*share, (*share)->persistent); - *share = NULL; + php_http_request_datashare_dtor(*h); + pefree(*h, (*h)->persistent); + *h = NULL; } -PHP_HTTP_API STATUS php_http_request_datashare_set(php_http_request_datashare_t *share, const char *option, size_t option_len, zend_bool enable) +PHP_HTTP_API STATUS php_http_request_datashare_attach(php_http_request_datashare_t *h, zval *request) { - curl_lock_data *opt; - CURLSHcode rc; - TSRMLS_FETCH_FROM_CTX(share->ts); + TSRMLS_FETCH_FROM_CTX(h->ts); + + if (h->ops->attach) { + php_http_request_object_t *obj = zend_object_store_get_object(request TSRMLS_CC); - if (SUCCESS == zend_hash_find(&php_http_request_datashare_options, (char *) option, option_len + 1, (void *) &opt)) { - if (CURLSHE_OK == (rc = curl_share_setopt(share->ch, enable ? CURLSHOPT_SHARE : CURLSHOPT_UNSHARE, *opt))) { + if (SUCCESS == h->ops->attach(h, obj->request)) { + Z_ADDREF_P(request); + zend_llist_add_element(PHP_HTTP_REQUEST_DATASHARE_REQUESTS(h), &request); return SUCCESS; } - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "Could not %s sharing of %s data: %s", enable ? "enable" : "disable", option, curl_share_strerror(rc)); } + return FAILURE; } @@ -153,70 +117,60 @@ static int php_http_request_datashare_compare_handles(void *h1, void *h2) return (Z_OBJ_HANDLE_PP((zval **) h1) == Z_OBJ_HANDLE_P((zval *) h2)); } -static void php_http_request_datashare_destroy_handles(void *el) +PHP_HTTP_API STATUS php_http_request_datashare_detach(php_http_request_datashare_t *h, zval *request) { - zval **r = (zval **) el; - TSRMLS_FETCH(); - - { /* gcc 2.95 needs these braces */ - php_http_request_object_t *obj = zend_object_store_get_object(*r TSRMLS_CC); + TSRMLS_FETCH_FROM_CTX(h->ts); - curl_easy_setopt(obj->request->ch, CURLOPT_SHARE, NULL); - zval_ptr_dtor(r); - } -} + if (h->ops->detach) { + php_http_request_object_t *obj = zend_object_store_get_object(request TSRMLS_CC); -#ifdef ZTS -static void *php_http_request_datashare_locks_init(void) -{ - int i; - php_http_request_datashare_lock_t *locks = pecalloc(CURL_LOCK_DATA_LAST, sizeof(php_http_request_datashare_lock_t), 1); - - if (locks) { - for (i = 0; i < CURL_LOCK_DATA_LAST; ++i) { - locks[i].mx = tsrm_mutex_alloc(); + if (SUCCESS == h->ops->detach(h, obj->request)) { + zend_llist_del_element(PHP_HTTP_REQUEST_DATASHARE_REQUESTS(h), request, php_http_request_datashare_compare_handles); + return SUCCESS; } } - - return locks; + return FAILURE; } -static void php_http_request_datashare_locks_dtor(void *l) +PHP_HTTP_API STATUS php_http_request_datashare_setopt(php_http_request_datashare_t *h, php_http_request_datashare_setopt_opt_t opt, void *arg) { - int i; - php_http_request_datashare_lock_t *locks = (php_http_request_datashare_lock_t *) l; - - for (i = 0; i < CURL_LOCK_DATA_LAST; ++i) { - tsrm_mutex_free(locks[i].mx); + if (h->ops->setopt) { + return h->ops->setopt(h, opt, arg); } - pefree(locks, 1); + return FAILURE; } -static void php_http_request_datashare_lock_func(CURL *handle, curl_lock_data data, curl_lock_access locktype, void *userptr) +static void detach(void *r, void *h TSRMLS_DC) { - php_http_request_datashare_lock_t *locks = (php_http_request_datashare_lock_t *) userptr; - - /* TSRM can't distinguish shared/exclusive locks */ - tsrm_mutex_lock(locks[data].mx); - locks[data].ch = handle; + ((php_http_request_datashare_t *) h)->ops->detach(h, ((php_http_request_object_t *) zend_object_store_get_object(*((zval **) r) TSRMLS_CC))->request); } -static void php_http_request_datashare_unlock_func(CURL *handle, curl_lock_data data, void *userptr) +PHP_HTTP_API void php_http_request_datashare_reset(php_http_request_datashare_t *h) { - php_http_request_datashare_lock_t *locks = (php_http_request_datashare_lock_t *) userptr; + if (h->ops->reset) { + h->ops->reset(h); + } else if (h->ops->detach) { + TSRMLS_FETCH_FROM_CTX(h->ts); - if (locks[data].ch == handle) { - tsrm_mutex_unlock(locks[data].mx); + zend_llist_apply_with_argument(PHP_HTTP_REQUEST_DATASHARE_REQUESTS(h), detach, h TSRMLS_CC); } + + zend_llist_clean(PHP_HTTP_REQUEST_DATASHARE_REQUESTS(h)); } -#endif +static void php_http_request_datashare_global_requests_dtor(void *el) +{ + //php_http_request_datashare_detach(php_http_request_datashare_global_get(), *((zval **) el)); + zval_ptr_dtor(el); +} #define PHP_HTTP_BEGIN_ARGS(method, req_args) PHP_HTTP_BEGIN_ARGS_EX(HttpRequestDataShare, method, 0, req_args) #define PHP_HTTP_EMPTY_ARGS(method) PHP_HTTP_EMPTY_ARGS_EX(HttpRequestDataShare, method, 0) #define PHP_HTTP_RSHARE_ME(method, visibility) PHP_ME(HttpRequestDataShare, method, PHP_HTTP_ARGS(HttpRequestDataShare, method), visibility) +PHP_HTTP_EMPTY_ARGS(__construct); PHP_HTTP_EMPTY_ARGS(__destruct); +PHP_HTTP_EMPTY_ARGS(reset); PHP_HTTP_EMPTY_ARGS(count); PHP_HTTP_BEGIN_ARGS(attach, 1) @@ -226,23 +180,17 @@ PHP_HTTP_BEGIN_ARGS(detach, 1) PHP_HTTP_ARG_OBJ(http\\Request, request, 0) PHP_HTTP_END_ARGS; -PHP_HTTP_EMPTY_ARGS(reset); - -PHP_HTTP_EMPTY_ARGS(getGlobalInstance); - - -static zval *php_http_request_datashare_object_read_prop(zval *object, zval *member, int type, const zend_literal *literal_key TSRMLS_DC); static void php_http_request_datashare_object_write_prop(zval *object, zval *member, zval *value, const zend_literal *literal_key TSRMLS_DC); -#define THIS_CE php_http_request_datashare_class_entry +#define php_http_request_datashare_class_entry php_http_request_datashare_class_entry zend_class_entry *php_http_request_datashare_class_entry; zend_function_entry php_http_request_datashare_method_entry[] = { + PHP_HTTP_RSHARE_ME(__construct, ZEND_ACC_PRIVATE|ZEND_ACC_CTOR) PHP_HTTP_RSHARE_ME(__destruct, ZEND_ACC_PUBLIC|ZEND_ACC_DTOR) PHP_HTTP_RSHARE_ME(count, ZEND_ACC_PUBLIC) PHP_HTTP_RSHARE_ME(attach, ZEND_ACC_PUBLIC) PHP_HTTP_RSHARE_ME(detach, ZEND_ACC_PUBLIC) PHP_HTTP_RSHARE_ME(reset, ZEND_ACC_PUBLIC) - PHP_HTTP_RSHARE_ME(getGlobalInstance, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) EMPTY_FUNCTION_ENTRY }; static zend_object_handlers php_http_request_datashare_object_handlers; @@ -264,7 +212,7 @@ zend_object_value php_http_request_datashare_object_new_ex(zend_class_entry *ce, if (share) { o->share = share; } else { - o->share = php_http_request_datashare_init(NULL, 0 TSRMLS_CC); + o->share = php_http_request_datashare_init(NULL, NULL, NULL, 0 TSRMLS_CC); } if (ptr) { @@ -288,24 +236,24 @@ void php_http_request_datashare_object_free(void *object TSRMLS_DC) efree(o); } -static zval *php_http_request_datashare_object_read_prop(zval *object, zval *member, int type, const zend_literal *literal_key TSRMLS_DC) -{ - if (type == BP_VAR_W && zend_get_property_info(THIS_CE, member, 1 TSRMLS_CC)) { - zend_error(E_ERROR, "Cannot access HttpRequestDataShare default properties by reference or array key/index"); - return NULL; - } - - return zend_get_std_object_handlers()->read_property(object, member, type, literal_key TSRMLS_CC); -} - static void php_http_request_datashare_object_write_prop(zval *object, zval *member, zval *value, const zend_literal *literal_key TSRMLS_DC) { - if (zend_get_property_info(THIS_CE, member, 1 TSRMLS_CC)) { - int status; + zend_property_info *pi; + + if ((pi = zend_get_property_info(php_http_request_datashare_class_entry, member, 1 TSRMLS_CC))) { + zend_bool enable = i_zend_is_true(value); + php_http_request_datashare_setopt_opt_t opt; php_http_request_datashare_object_t *obj = zend_object_store_get_object(object TSRMLS_CC); - status = php_http_request_datashare_set(obj->share, Z_STRVAL_P(member), Z_STRLEN_P(member), (zend_bool) i_zend_is_true(value)); - if (SUCCESS != status) { + if (!strcmp(pi->name, "cookie")) { + opt = PHP_HTTP_REQUEST_DATASHARE_OPT_COOKIES; + } else if (!strcmp(pi->name, "dns")) { + opt = PHP_HTTP_REQUEST_DATASHARE_OPT_RESOLVER; + } else { + return; + } + + if (SUCCESS != php_http_request_datashare_setopt(obj->share, opt, &enable)) { return; } } @@ -313,6 +261,25 @@ static void php_http_request_datashare_object_write_prop(zval *object, zval *mem zend_get_std_object_handlers()->write_property(object, member, value, literal_key TSRMLS_CC); } +static zval **php_http_request_datashare_object_get_prop_ptr(zval *object, zval *member, const zend_literal *literal_key TSRMLS_DC) +{ + zend_property_info *pi; + + if ((pi = zend_get_property_info(php_http_request_datashare_class_entry, member, 1 TSRMLS_CC))) { + return &php_http_property_proxy_init(NULL, object, member TSRMLS_CC)->myself; + } + + return zend_get_std_object_handlers()->get_property_ptr_ptr(object, member, literal_key TSRMLS_CC); +} + + +PHP_METHOD(HttpRequestDataShare, __construct) +{ + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { + zend_parse_parameters_none(); + } end_error_handling(); +} + PHP_METHOD(HttpRequestDataShare, __destruct) { php_http_request_datashare_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); @@ -321,7 +288,7 @@ PHP_METHOD(HttpRequestDataShare, __destruct) ; /* we always want to clean up */ } - php_http_request_datashare_detach_all(obj->share); + php_http_request_datashare_reset(obj->share); } PHP_METHOD(HttpRequestDataShare, count) @@ -329,7 +296,7 @@ PHP_METHOD(HttpRequestDataShare, count) if (SUCCESS == zend_parse_parameters_none()) { php_http_request_datashare_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - RETURN_LONG(zend_llist_count(PHP_HTTP_RSHARE_HANDLES(obj->share))); + RETURN_LONG(zend_llist_count(PHP_HTTP_REQUEST_DATASHARE_REQUESTS(obj->share))); } RETURN_FALSE; } @@ -365,105 +332,55 @@ PHP_METHOD(HttpRequestDataShare, reset) if (SUCCESS == zend_parse_parameters_none()) { php_http_request_datashare_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - php_http_request_datashare_detach_all(obj->share); + php_http_request_datashare_reset(obj->share); RETURN_TRUE; } RETURN_FALSE; } -PHP_METHOD(HttpRequestDataShare, getGlobalInstance) -{ - with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { - if (SUCCESS == zend_parse_parameters_none()) { - zval *instance = *zend_std_get_static_property(THIS_CE, ZEND_STRL("instance"), 0, NULL TSRMLS_CC); - - if (Z_TYPE_P(instance) != IS_OBJECT) { - MAKE_STD_ZVAL(instance); - ZVAL_OBJVAL(instance, php_http_request_datashare_object_new_ex(THIS_CE, php_http_request_datashare_global_get(), NULL TSRMLS_CC), 1); - zend_update_static_property(THIS_CE, ZEND_STRL("instance"), instance TSRMLS_CC); - - if (PHP_HTTP_G->request_datashare.cookie) { - zend_update_property_bool(THIS_CE, instance, ZEND_STRL("cookie"), PHP_HTTP_G->request_datashare.cookie TSRMLS_CC); - } - if (PHP_HTTP_G->request_datashare.dns) { - zend_update_property_bool(THIS_CE, instance, ZEND_STRL("dns"), PHP_HTTP_G->request_datashare.dns TSRMLS_CC); - } - if (PHP_HTTP_G->request_datashare.ssl) { - zend_update_property_bool(THIS_CE, instance, ZEND_STRL("ssl"), PHP_HTTP_G->request_datashare.ssl TSRMLS_CC); - } - if (PHP_HTTP_G->request_datashare.connect) { - zend_update_property_bool(THIS_CE, instance, ZEND_STRL("connect"), PHP_HTTP_G->request_datashare.connect TSRMLS_CC); - } - } - - RETVAL_ZVAL(instance, 0, 0); - } - }end_error_handling(); -} - PHP_MINIT_FUNCTION(http_request_datashare) { - curl_lock_data val; - - if (SUCCESS != php_http_persistent_handle_provide(ZEND_STRL("http_request_datashare"), curl_share_init, (php_http_persistent_handle_dtor_t) curl_share_cleanup, NULL)) { - return FAILURE; - } -#ifdef ZTS - if (SUCCESS != php_http_persistent_handle_provide(ZEND_STRL("http_request_datashare_lock"), php_http_request_datashare_locks_init, php_http_request_datashare_locks_dtor, NULL)) { - return FAILURE; - } -#endif - - if (!php_http_request_datashare_init(&php_http_request_datashare_global, 1 TSRMLS_CC)) { - return FAILURE; - } - - zend_hash_init(&php_http_request_datashare_options, 4, NULL, NULL, 1); -#define ADD_DATASHARE_OPT(name, opt) \ - val = opt; \ - zend_hash_add(&php_http_request_datashare_options, name, sizeof(name), &val, sizeof(curl_lock_data), NULL) - ADD_DATASHARE_OPT("cookie", CURL_LOCK_DATA_COOKIE); - ADD_DATASHARE_OPT("dns", CURL_LOCK_DATA_DNS); - ADD_DATASHARE_OPT("ssl", CURL_LOCK_DATA_SSL_SESSION); - ADD_DATASHARE_OPT("connect", CURL_LOCK_DATA_CONNECT); - PHP_HTTP_REGISTER_CLASS(http\\request, DataShare, http_request_datashare, php_http_object_class_entry, 0); php_http_request_datashare_class_entry->create_object = php_http_request_datashare_object_new; memcpy(&php_http_request_datashare_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); php_http_request_datashare_object_handlers.clone_obj = NULL; - php_http_request_datashare_object_handlers.read_property = php_http_request_datashare_object_read_prop; php_http_request_datashare_object_handlers.write_property = php_http_request_datashare_object_write_prop; - php_http_request_datashare_object_handlers.get_property_ptr_ptr = NULL; + php_http_request_datashare_object_handlers.get_property_ptr_ptr = php_http_request_datashare_object_get_prop_ptr; zend_class_implements(php_http_request_datashare_class_entry TSRMLS_CC, 1, spl_ce_Countable); - zend_declare_property_null(THIS_CE, ZEND_STRL("instance"), (ZEND_ACC_STATIC|ZEND_ACC_PRIVATE) TSRMLS_CC); - zend_declare_property_bool(THIS_CE, ZEND_STRL("cookie"), 0, ZEND_ACC_PUBLIC TSRMLS_CC); - zend_declare_property_bool(THIS_CE, ZEND_STRL("dns"), 0, ZEND_ACC_PUBLIC TSRMLS_CC); - zend_declare_property_bool(THIS_CE, ZEND_STRL("ssl"), 0, ZEND_ACC_PUBLIC TSRMLS_CC); - zend_declare_property_bool(THIS_CE, ZEND_STRL("connect"), 0, ZEND_ACC_PUBLIC TSRMLS_CC); + zend_declare_property_null(php_http_request_datashare_class_entry, ZEND_STRL("instance"), (ZEND_ACC_STATIC|ZEND_ACC_PRIVATE) TSRMLS_CC); + zend_declare_property_bool(php_http_request_datashare_class_entry, ZEND_STRL("cookie"), 0, ZEND_ACC_PUBLIC TSRMLS_CC); + zend_declare_property_bool(php_http_request_datashare_class_entry, ZEND_STRL("dns"), 0, ZEND_ACC_PUBLIC TSRMLS_CC); + +#ifdef ZTS + php_http_request_datashare_global_shares_lock = tsrm_mutex_alloc(); +#endif + zend_hash_init(&php_http_request_datashare_global_shares, 0, NULL, (dtor_func_t) php_http_request_datashare_free, 1); return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(http_request_datashare) { - php_http_request_datashare_dtor(&php_http_request_datashare_global); - zend_hash_destroy(&php_http_request_datashare_options); + zend_hash_destroy(&php_http_request_datashare_global_shares); +#ifdef ZTS + tsrm_mutex_free(php_http_request_datashare_global_shares_lock); +#endif return SUCCESS; } PHP_RINIT_FUNCTION(http_request_datashare) { - zend_llist_init(&PHP_HTTP_G->request_datashare.handles, sizeof(zval *), php_http_request_datashare_destroy_handles, 0); + zend_llist_init(&PHP_HTTP_G->request_datashare.requests, sizeof(zval *), php_http_request_datashare_global_requests_dtor, 0); return SUCCESS; } PHP_RSHUTDOWN_FUNCTION(http_request_datashare) { - zend_llist_destroy(&PHP_HTTP_G->request_datashare.handles); + zend_llist_destroy(&PHP_HTTP_G->request_datashare.requests); return SUCCESS; } diff --git a/php_http_request_datashare.h b/php_http_request_datashare.h index 31e2a43..cdc4142 100644 --- a/php_http_request_datashare.h +++ b/php_http_request_datashare.h @@ -1,55 +1,67 @@ #ifndef PHP_HTTP_REQUEST_DATASHARE_H #define PHP_HTTP_REQUEST_DATASHARE_H -#include +#include "php_http_request.h" -#ifdef ZTS -typedef struct php_http_request_datashare_lock { - CURL *ch; - MUTEX_T mx; -} php_http_request_datashare_lock_t; -#endif +typedef enum php_http_request_datashare_setopt_opt { + PHP_HTTP_REQUEST_DATASHARE_OPT_COOKIES, + PHP_HTTP_REQUEST_DATASHARE_OPT_RESOLVER, +} php_http_request_datashare_setopt_opt_t; -typedef union php_http_request_datashare_handle { - zend_llist *list; -#ifdef ZTS - php_http_request_datashare_lock_t *locks; -#endif -} php_http_request_datashare_handle_t; +typedef struct php_http_request_datashare php_http_request_datashare_t; -typedef struct php_http_request_datashare_t { - CURLSH *ch; - php_http_request_datashare_handle_t handle; +typedef php_http_request_datashare_t *(*php_http_request_datashare_init_func_t)(php_http_request_datashare_t *h, void *init_arg); +typedef php_http_request_datashare_t *(*php_http_request_datashare_copy_func_t)(php_http_request_datashare_t *from, php_http_request_datashare_t *to); +typedef void (*php_http_request_datashare_dtor_func_t)(php_http_request_datashare_t *h); +typedef void (*php_http_request_datashare_reset_func_t)(php_http_request_datashare_t *h); +typedef STATUS (*php_http_request_datashare_attach_func_t)(php_http_request_datashare_t *h, php_http_request_t *request); +typedef STATUS (*php_http_request_datashare_detach_func_t)(php_http_request_datashare_t *h, php_http_request_t *request); +typedef STATUS (*php_http_request_datashare_setopt_func_t)(php_http_request_datashare_t *h, php_http_request_datashare_setopt_opt_t opt, void *arg); + +typedef struct php_http_request_datashare_ops { + php_http_request_datashare_init_func_t init; + php_http_request_datashare_copy_func_t copy; + php_http_request_datashare_dtor_func_t dtor; + php_http_request_datashare_reset_func_t reset; + php_http_request_datashare_attach_func_t attach; + php_http_request_datashare_detach_func_t detach; + php_http_request_datashare_setopt_func_t setopt; +} php_http_request_datashare_ops_t; + +#define PHP_HTTP_REQUEST_DATASHARE_REQUESTS(s) ((s)->persistent ? &PHP_HTTP_G->request_datashare.requests : (s)->requests) +struct php_http_request_datashare { + void *ctx; + php_http_request_datashare_ops_t *ops; + zend_llist *requests; /* NULL if persistent, use PHP_HTTP_REQUEST_DATASHARE_REQUESTS */ unsigned persistent:1; #ifdef ZTS void ***ts; #endif -} php_http_request_datashare_t; +}; struct php_http_request_datashare_globals { - zend_llist handles; + zend_llist requests; zend_bool cookie; zend_bool dns; zend_bool ssl; zend_bool connect; }; -#define PHP_HTTP_RSHARE_HANDLES(s) ((s)->persistent ? &PHP_HTTP_G->request_datashare.handles : (s)->handle.list) - -extern php_http_request_datashare_t *php_http_request_datashare_global_get(void); +extern php_http_request_datashare_t *php_http_request_datashare_global_get(const char *driver_str, size_t driver_len TSRMLS_DC); extern PHP_MINIT_FUNCTION(http_request_datashare); extern PHP_MSHUTDOWN_FUNCTION(http_request_datashare); extern PHP_RINIT_FUNCTION(http_request_datashare); extern PHP_RSHUTDOWN_FUNCTION(http_request_datashare); -PHP_HTTP_API php_http_request_datashare_t *php_http_request_datashare_init(php_http_request_datashare_t *share, zend_bool persistent TSRMLS_DC); -PHP_HTTP_API STATUS php_http_request_datashare_attach(php_http_request_datashare_t *share, zval *request); -PHP_HTTP_API STATUS php_http_request_datashare_detach(php_http_request_datashare_t *share, zval *request); -PHP_HTTP_API void php_http_request_datashare_detach_all(php_http_request_datashare_t *share); -PHP_HTTP_API void php_http_request_datashare_dtor(php_http_request_datashare_t *share); -PHP_HTTP_API void php_http_request_datashare_free(php_http_request_datashare_t **share); -PHP_HTTP_API STATUS php_http_request_datashare_set(php_http_request_datashare_t *share, const char *option, size_t option_len, zend_bool enable); +PHP_HTTP_API php_http_request_datashare_t *php_http_request_datashare_init(php_http_request_datashare_t *h, php_http_request_datashare_ops_t *ops, void *init_arg, zend_bool persistent TSRMLS_DC); +PHP_HTTP_API php_http_request_datashare_t *php_http_request_datashare_copy(php_http_request_datashare_t *from, php_http_request_datashare_t *to); +PHP_HTTP_API void php_http_request_datashare_dtor(php_http_request_datashare_t *h); +PHP_HTTP_API void php_http_request_datashare_free(php_http_request_datashare_t **h); +PHP_HTTP_API STATUS php_http_request_datashare_attach(php_http_request_datashare_t *h, zval *request); +PHP_HTTP_API STATUS php_http_request_datashare_detach(php_http_request_datashare_t *h, zval *request); +PHP_HTTP_API STATUS php_http_request_datashare_setopt(php_http_request_datashare_t *h, php_http_request_datashare_setopt_opt_t opt, void *arg); +PHP_HTTP_API void php_http_request_datashare_reset(php_http_request_datashare_t *h); typedef struct php_http_request_datashare_object { zend_object zo; @@ -63,11 +75,11 @@ extern zend_object_value php_http_request_datashare_object_new(zend_class_entry extern zend_object_value php_http_request_datashare_object_new_ex(zend_class_entry *ce, php_http_request_datashare_t *share, php_http_request_datashare_object_t **ptr TSRMLS_DC); extern void php_http_request_datashare_object_free(void *object TSRMLS_DC); +PHP_METHOD(HttpRequestDataShare, __construct); PHP_METHOD(HttpRequestDataShare, __destruct); PHP_METHOD(HttpRequestDataShare, count); PHP_METHOD(HttpRequestDataShare, attach); PHP_METHOD(HttpRequestDataShare, detach); PHP_METHOD(HttpRequestDataShare, reset); -PHP_METHOD(HttpRequestDataShare, getGlobalInstance); #endif /* PHP_HTTP_REQUEST_DATASHARE_H */ diff --git a/php_http_request_factory.c b/php_http_request_factory.c new file mode 100644 index 0000000..16352ee --- /dev/null +++ b/php_http_request_factory.c @@ -0,0 +1,344 @@ + +#include "php_http.h" + +#include +#include +#include + +/* + * array of name => php_http_request_factory_driver_t* + */ +static HashTable php_http_request_factory_drivers; + +PHP_HTTP_API STATUS php_http_request_factory_add_driver(const char *name_str, size_t name_len, php_http_request_factory_driver_t *driver) +{ + return zend_hash_add(&php_http_request_factory_drivers, name_str, name_len + 1, (void *) driver, sizeof(php_http_request_factory_driver_t), NULL); +} + +PHP_HTTP_API STATUS php_http_request_factory_get_driver(const char *name_str, size_t name_len, php_http_request_factory_driver_t *driver) +{ + php_http_request_factory_driver_t *tmp; + + if (SUCCESS == zend_hash_find(&php_http_request_factory_drivers, name_str, name_len + 1, (void *) &tmp)) { + *driver = *tmp; + return SUCCESS; + } + return FAILURE; +} + +static zend_class_entry *php_http_request_factory_get_class_entry(zval *this_ptr, const char *for_str, size_t for_len TSRMLS_DC) +{ + /* stupid non-const api */ + char *sc = estrndup(for_str, for_len); + zval *cn = zend_read_property(Z_OBJCE_P(getThis()), getThis(), sc, for_len, 0 TSRMLS_CC); + + efree(sc); + if (Z_TYPE_P(cn) == IS_STRING && Z_STRLEN_P(cn)) { + return zend_fetch_class(Z_STRVAL_P(cn), Z_STRLEN_P(cn), 0 TSRMLS_CC); + } + + return NULL; +} + +#define PHP_HTTP_BEGIN_ARGS(method, req_args) PHP_HTTP_BEGIN_ARGS_EX(HttpRequestFactory, method, 0, req_args) +#define PHP_HTTP_EMPTY_ARGS(method) PHP_HTTP_EMPTY_ARGS_EX(HttpRequestFactory, method, 0) +#define PHP_HTTP_REQUEST_FACTORY_ME(method, visibility) PHP_ME(HttpRequestFactory, method, PHP_HTTP_ARGS(HttpRequestFactory, method), visibility) +#define PHP_HTTP_REQUEST_FACTORY_ALIAS(method, func) PHP_HTTP_STATIC_ME_ALIAS(method, func, PHP_HTTP_ARGS(HttpRequestFactory, method)) +#define PHP_HTTP_REQUEST_FACTORY_MALIAS(me, al, vis) ZEND_FENTRY(me, ZEND_MN(HttpRequestFactory_##al), PHP_HTTP_ARGS(HttpRequestFactory, al), vis) + +PHP_HTTP_BEGIN_ARGS(__construct, 1) + PHP_HTTP_ARG_VAL(driver, 0) + PHP_HTTP_ARG_VAL(options, 0) +PHP_HTTP_END_ARGS; +PHP_HTTP_BEGIN_ARGS(createRequest, 0) + PHP_HTTP_ARG_VAL(persistentHandle, 0) +PHP_HTTP_END_ARGS; +PHP_HTTP_BEGIN_ARGS(createPool, 0) + PHP_HTTP_ARG_VAL(persistentHandle, 0) +PHP_HTTP_END_ARGS; +PHP_HTTP_BEGIN_ARGS(createDataShare, 0) + PHP_HTTP_ARG_VAL(persistentHandle, 0) +PHP_HTTP_END_ARGS; +PHP_HTTP_EMPTY_ARGS(getGlobalDataShareInstance); +PHP_HTTP_EMPTY_ARGS(getDriver); +PHP_HTTP_EMPTY_ARGS(getAvailableDrivers); + +zend_class_entry *php_http_request_factory_class_entry; +zend_function_entry php_http_request_factory_method_entry[] = { + PHP_HTTP_REQUEST_FACTORY_ME(__construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) + PHP_HTTP_REQUEST_FACTORY_ME(createRequest, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_FACTORY_ME(createPool, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_FACTORY_ME(createDataShare, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_FACTORY_ME(getGlobalDataShareInstance, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_FACTORY_ME(getDriver, ZEND_ACC_PUBLIC) + PHP_HTTP_REQUEST_FACTORY_ME(getAvailableDrivers, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) + + EMPTY_FUNCTION_ENTRY +}; + +PHP_METHOD(HttpRequestFactory, __construct) +{ + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { + char *driver_str; + int driver_len; + HashTable *options = NULL; + + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|h", &driver_str, &driver_len, &options)) { + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(request_factory)) { + char *lower_str = php_strtolower(estrdup(driver_str), driver_len); + + if (zend_hash_exists(&php_http_request_factory_drivers, lower_str, driver_len + 1)) { + zend_update_property_stringl(php_http_request_factory_class_entry, getThis(), ZEND_STRL("driver"), lower_str, driver_len TSRMLS_CC); + + if (options) { + zval **val; + HashPosition pos; + php_http_array_hashkey_t key = php_http_array_hashkey_init(0); + + FOREACH_HASH_KEYVAL(pos, options, key, val) { + if (key.type == HASH_KEY_IS_STRING) { + zend_update_property(php_http_request_factory_class_entry, getThis(), key.str, key.len - 1, *val); + } + } + } + } else { + php_http_error(HE_THROW, PHP_HTTP_E_REQUEST_FACTORY, "unknown request driver: '%s'", driver_str); + } + efree(lower_str); + } end_error_handling(); + } + } end_error_handling(); +} + +PHP_METHOD(HttpRequestFactory, createRequest) +{ + char *url_str = NULL; + int url_len; + long meth = -1; + zval *options = NULL; + + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s!la!", &url_str, &url_len, &meth, &options)) { + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(request_factory)) { + zval *zdriver, *os; + zend_object_value ov; + zend_class_entry *class_entry = NULL; + php_http_request_t *req = NULL; + php_http_request_factory_driver_t driver; + + if (!(class_entry = php_http_request_factory_get_class_entry(getThis(), ZEND_STRL("requestClass") TSRMLS_CC))) { + class_entry = php_http_request_class_entry; + } + + if ((zdriver = zend_read_property(php_http_request_factory_class_entry, getThis(), ZEND_STRL("driver"), 0 TSRMLS_CC)) + && (IS_STRING == Z_TYPE_P(zdriver)) + && (SUCCESS == php_http_request_factory_get_driver(Z_STRVAL_P(zdriver), Z_STRLEN_P(zdriver), &driver)) + && (driver.request_ops) + && (req = php_http_request_init(NULL, driver.request_ops, NULL TSRMLS_CC)) + && (SUCCESS == php_http_new(&ov, class_entry, (php_http_new_t) php_http_request_object_new_ex, php_http_request_class_entry, req, NULL TSRMLS_CC)) + ) { + ZVAL_OBJVAL(return_value, ov, 0); + + MAKE_STD_ZVAL(os); + object_init_ex(os, spl_ce_SplObjectStorage); + zend_update_property(php_http_request_class_entry, return_value, ZEND_STRL("observers"), os TSRMLS_CC); + zval_ptr_dtor(&os); + + if (url_str) { + zend_update_property_stringl(php_http_request_class_entry, return_value, ZEND_STRL("url"), url_str, url_len TSRMLS_CC); + } + if (meth > 0) { + zend_update_property_long(php_http_request_class_entry, return_value, ZEND_STRL("method"), meth TSRMLS_CC); + } + if (options) { + zend_call_method_with_1_params(&return_value, Z_OBJCE_P(return_value), NULL, "setoptions", NULL, options); + } + } else { + if (req) { + php_http_request_free(&req); + } else { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_FACTORY, "requests are not supported by this driver"); + } + } + } end_error_handling(); + } + } end_error_handling(); +} + +PHP_METHOD(HttpRequestFactory, createPool) +{ + int argc = 0; + zval ***argv; + + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|*", &argv, &argc)) { + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(request_factory)) { + int i; + zval *zdriver; + zend_object_value ov; + zend_class_entry *class_entry = NULL; + php_http_request_pool_t *pool = NULL; + php_http_request_pool_object_t *obj; + php_http_request_factory_driver_t driver; + + if (!(class_entry = php_http_request_factory_get_class_entry(getThis(), ZEND_STRL("requestPoolClass") TSRMLS_CC))) { + class_entry = php_http_request_pool_class_entry; + } + + if ((zdriver = zend_read_property(php_http_request_factory_class_entry, getThis(), ZEND_STRL("driver"), 0 TSRMLS_CC)) + && (IS_STRING == Z_TYPE_P(zdriver)) + && (SUCCESS == php_http_request_factory_get_driver(Z_STRVAL_P(zdriver), Z_STRLEN_P(zdriver), &driver)) + && (driver.request_pool_ops) + && (pool = php_http_request_pool_init(NULL, driver.request_pool_ops, NULL TSRMLS_CC)) + && (SUCCESS == php_http_new(&ov, class_entry, (php_http_new_t) php_http_request_pool_object_new_ex, php_http_request_pool_class_entry, pool, (void *) &obj TSRMLS_CC)) + ) { + ZVAL_OBJVAL(return_value, ov, 0); + + for (i = 0; i < argc; ++i) { + if (Z_TYPE_PP(argv[i]) == IS_OBJECT && instanceof_function(Z_OBJCE_PP(argv[i]), php_http_request_class_entry TSRMLS_CC)) { + php_http_request_pool_attach(obj->pool, *(argv[i])); + } + } + } else { + if (pool) { + php_http_request_pool_free(&pool); + } else { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_FACTORY, "pools are not supported by this driver"); + } + } + } end_error_handling(); + } + } end_error_handling(); +} + +PHP_METHOD(HttpRequestFactory, createDataShare) +{ + int argc = 0; + zval ***argv; + + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { + if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|*", &argv, &argc)) { + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(request_factory)) { + int i; + zval *zdriver; + zend_object_value ov; + zend_class_entry *class_entry; + php_http_request_datashare_t *share = NULL; + php_http_request_datashare_object_t *obj; + php_http_request_factory_driver_t driver; + + if (!(class_entry = php_http_request_factory_get_class_entry(getThis(), ZEND_STRL("requestDataShareClass") TSRMLS_CC))) { + class_entry = php_http_request_datashare_class_entry; + } + + if ((zdriver = zend_read_property(php_http_request_factory_class_entry, getThis(), ZEND_STRL("driver"), 0 TSRMLS_CC)) + && (IS_STRING == Z_TYPE_P(zdriver)) + && (SUCCESS == php_http_request_factory_get_driver(Z_STRVAL_P(zdriver), Z_STRLEN_P(zdriver), &driver)) + && (driver.request_datashare_ops) + && (share = php_http_request_datashare_init(NULL, driver.request_datashare_ops, NULL, 0 TSRMLS_CC)) + && (SUCCESS == php_http_new(&ov, class_entry, (php_http_new_t) php_http_request_datashare_object_new_ex, php_http_request_datashare_class_entry, share, (void *) &obj TSRMLS_CC)) + ) { + ZVAL_OBJVAL(return_value, ov, 0); + + for (i = 0; i < argc; ++i) { + if (Z_TYPE_PP(argv[i]) == IS_OBJECT && instanceof_function(Z_OBJCE_PP(argv[i]), php_http_request_class_entry TSRMLS_CC)) { + php_http_request_datashare_attach(obj->share, *(argv[i])); + } + } + } else { + if (share) { + php_http_request_datashare_free(&share); + } else { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_FACTORY, "datashares are not supported by this driver"); + } + } + } end_error_handling(); + } + } end_error_handling(); +} + +PHP_METHOD(HttpRequestFactory, getGlobalDataShareInstance) +{ + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { + if (SUCCESS == zend_parse_parameters_none()) { + with_error_handling(EH_THROW, PHP_HTTP_EX_CE(request_datashare)) { + zval *instance = *zend_std_get_static_property(php_http_request_datashare_class_entry, ZEND_STRL("instance"), 0, NULL TSRMLS_CC); + + if (Z_TYPE_P(instance) != IS_OBJECT) { + zval *zdriver; + zend_object_value ov; + zend_class_entry *class_entry; + php_http_request_datashare_t *share; + + if (!(class_entry = php_http_request_factory_get_class_entry(getThis(), ZEND_STRL("requestDataShareClass") TSRMLS_CC))) { + class_entry = php_http_request_datashare_class_entry; + } + + if ((zdriver = zend_read_property(php_http_request_factory_class_entry, getThis(), ZEND_STRL("driver"), 0 TSRMLS_CC)) + && (IS_STRING == Z_TYPE_P(zdriver)) + && (share = php_http_request_datashare_global_get(Z_STRVAL_P(zdriver), Z_STRLEN_P(zdriver) TSRMLS_CC)) + && (SUCCESS == php_http_new(&ov, class_entry, (php_http_new_t) php_http_request_datashare_object_new_ex, php_http_request_datashare_class_entry, share, NULL TSRMLS_CC)) + ) { + MAKE_STD_ZVAL(instance); + ZVAL_OBJVAL(instance, ov, 0); + zend_update_static_property(php_http_request_datashare_class_entry, ZEND_STRL("instance"), instance TSRMLS_CC); + + if (PHP_HTTP_G->request_datashare.cookie) { + zend_update_property_bool(php_http_request_datashare_class_entry, instance, ZEND_STRL("cookie"), PHP_HTTP_G->request_datashare.cookie TSRMLS_CC); + } + if (PHP_HTTP_G->request_datashare.dns) { + zend_update_property_bool(php_http_request_datashare_class_entry, instance, ZEND_STRL("dns"), PHP_HTTP_G->request_datashare.dns TSRMLS_CC); + } + } + } + + RETVAL_ZVAL(instance, 1, 0); + } end_error_handling(); + } + } end_error_handling(); +} + + +PHP_METHOD(HttpRequestFactory, getDriver) +{ + if (SUCCESS == zend_parse_parameters_none()) { + RETURN_PROP(php_http_request_factory_class_entry, "driver"); + } + RETURN_FALSE; +} + +PHP_METHOD(HttpRequestFactory, getAvailableDrivers) +{ + if (SUCCESS == zend_parse_parameters_none()) { + HashPosition pos; + php_http_array_hashkey_t key = php_http_array_hashkey_init(0); + + array_init(return_value); + FOREACH_HASH_KEY(pos, &php_http_request_factory_drivers, key) { + add_next_index_stringl(return_value, key.str, key.len - 1, 1); + } + return; + } + RETURN_FALSE; +} + +PHP_MINIT_FUNCTION(http_request_factory) +{ + zend_hash_init(&php_http_request_factory_drivers, 0, NULL, NULL, 1); + + PHP_HTTP_REGISTER_CLASS(http\\request, Factory, http_request_factory, php_http_object_class_entry, 0); + zend_declare_property_null(php_http_request_factory_class_entry, ZEND_STRL("driver"), ZEND_ACC_PRIVATE TSRMLS_CC); + zend_declare_property_null(php_http_request_factory_class_entry, ZEND_STRL("requestClass"), ZEND_ACC_PUBLIC TSRMLS_CC); + zend_declare_property_null(php_http_request_factory_class_entry, ZEND_STRL("requestPoolClass"), ZEND_ACC_PUBLIC TSRMLS_CC); + zend_declare_property_null(php_http_request_factory_class_entry, ZEND_STRL("requestDataShareClass"), ZEND_ACC_PUBLIC TSRMLS_CC); + + return SUCCESS; +} + +PHP_MSHUTDOWN_FUNCTION(http_request_factory) +{ + zend_hash_destroy(&php_http_request_factory_drivers); + + return SUCCESS; +} + diff --git a/php_http_request_factory.h b/php_http_request_factory.h new file mode 100644 index 0000000..881025a --- /dev/null +++ b/php_http_request_factory.h @@ -0,0 +1,32 @@ +#ifndef PHP_HTTP_REQUEST_FACTORY_H +#define PHP_HTTP_REQUEST_FACTORY_H + +#include "php_http_request.h" +#include "php_http_request_pool.h" + +typedef struct php_http_request_factory_driver { + php_http_request_ops_t *request_ops; + php_http_request_pool_ops_t *request_pool_ops; + php_http_request_datashare_ops_t *request_datashare_ops; +} php_http_request_factory_driver_t; + +PHP_HTTP_API STATUS php_http_request_factory_add_driver(const char *name_str, size_t name_len, php_http_request_factory_driver_t *driver); +PHP_HTTP_API STATUS php_http_request_factory_get_driver(const char *name_str, size_t name_len, php_http_request_factory_driver_t *driver); + +extern zend_class_entry *php_http_request_factory_class_entry; +extern zend_function_entry php_http_request_factory_method_entry[]; + +#define php_http_request_factory_new php_http_object_new + +PHP_METHOD(HttpRequestFactory, __construct); +PHP_METHOD(HttpRequestFactory, createRequest); +PHP_METHOD(HttpRequestFactory, createPool); +PHP_METHOD(HttpRequestFactory, createDataShare); +PHP_METHOD(HttpRequestFactory, getGlobalDataShareInstance); +PHP_METHOD(HttpRequestFactory, getDriver); +PHP_METHOD(HttpRequestFactory, getAvailableDrivers); + +extern PHP_MINIT_FUNCTION(http_request_factory); +extern PHP_MSHUTDOWN_FUNCTION(http_request_factory); + +#endif /* PHP_HTTP_REQUEST_FACTORY_H */ diff --git a/php_http_request_info.c b/php_http_request_info.c index 494a5dc..10d9440 100644 --- a/php_http_request_info.c +++ b/php_http_request_info.c @@ -24,82 +24,82 @@ PHP_HTTP_API void php_http_request_info(php_http_request_t *request, HashTable * INIT_PZVAL_ARRAY(&array, info); /* BEGIN */ - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_EFFECTIVE_URL, &c)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_EFFECTIVE_URL, &c)) { add_assoc_string_ex(&array, "effective_url", sizeof("effective_url"), c ? c : "", 1); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_RESPONSE_CODE, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_RESPONSE_CODE, &l)) { add_assoc_long_ex(&array, "response_code", sizeof("response_code"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_TOTAL_TIME, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_TOTAL_TIME, &d)) { add_assoc_double_ex(&array, "total_time", sizeof("total_time"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_NAMELOOKUP_TIME, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_NAMELOOKUP_TIME, &d)) { add_assoc_double_ex(&array, "namelookup_time", sizeof("namelookup_time"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_CONNECT_TIME, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_CONNECT_TIME, &d)) { add_assoc_double_ex(&array, "connect_time", sizeof("connect_time"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_PRETRANSFER_TIME, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_PRETRANSFER_TIME, &d)) { add_assoc_double_ex(&array, "pretransfer_time", sizeof("pretransfer_time"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_SIZE_UPLOAD, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_SIZE_UPLOAD, &d)) { add_assoc_double_ex(&array, "size_upload", sizeof("size_upload"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_SIZE_DOWNLOAD, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_SIZE_DOWNLOAD, &d)) { add_assoc_double_ex(&array, "size_download", sizeof("size_download"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_SPEED_DOWNLOAD, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_SPEED_DOWNLOAD, &d)) { add_assoc_double_ex(&array, "speed_download", sizeof("speed_download"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_SPEED_UPLOAD, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_SPEED_UPLOAD, &d)) { add_assoc_double_ex(&array, "speed_upload", sizeof("speed_upload"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_HEADER_SIZE, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_HEADER_SIZE, &l)) { add_assoc_long_ex(&array, "header_size", sizeof("header_size"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_REQUEST_SIZE, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_REQUEST_SIZE, &l)) { add_assoc_long_ex(&array, "request_size", sizeof("request_size"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_SSL_VERIFYRESULT, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_SSL_VERIFYRESULT, &l)) { add_assoc_long_ex(&array, "ssl_verifyresult", sizeof("ssl_verifyresult"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_FILETIME, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_FILETIME, &l)) { add_assoc_long_ex(&array, "filetime", sizeof("filetime"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d)) { add_assoc_double_ex(&array, "content_length_download", sizeof("content_length_download"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_CONTENT_LENGTH_UPLOAD, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_CONTENT_LENGTH_UPLOAD, &d)) { add_assoc_double_ex(&array, "content_length_upload", sizeof("content_length_upload"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_STARTTRANSFER_TIME, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_STARTTRANSFER_TIME, &d)) { add_assoc_double_ex(&array, "starttransfer_time", sizeof("starttransfer_time"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_CONTENT_TYPE, &c)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_CONTENT_TYPE, &c)) { add_assoc_string_ex(&array, "content_type", sizeof("content_type"), c ? c : "", 1); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_REDIRECT_TIME, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_REDIRECT_TIME, &d)) { add_assoc_double_ex(&array, "redirect_time", sizeof("redirect_time"), d); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_REDIRECT_COUNT, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_REDIRECT_COUNT, &l)) { add_assoc_long_ex(&array, "redirect_count", sizeof("redirect_count"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_HTTP_CONNECTCODE, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_HTTP_CONNECTCODE, &l)) { add_assoc_long_ex(&array, "connect_code", sizeof("connect_code"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_HTTPAUTH_AVAIL, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_HTTPAUTH_AVAIL, &l)) { add_assoc_long_ex(&array, "httpauth_avail", sizeof("httpauth_avail"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_PROXYAUTH_AVAIL, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_PROXYAUTH_AVAIL, &l)) { add_assoc_long_ex(&array, "proxyauth_avail", sizeof("proxyauth_avail"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_OS_ERRNO, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_OS_ERRNO, &l)) { add_assoc_long_ex(&array, "os_errno", sizeof("os_errno"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_NUM_CONNECTS, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_NUM_CONNECTS, &l)) { add_assoc_long_ex(&array, "num_connects", sizeof("num_connects"), l); } - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_SSL_ENGINES, &s)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_SSL_ENGINES, &s)) { MAKE_STD_ZVAL(subarray); array_init(subarray); for (p = s; p; p = p->next) { @@ -111,7 +111,7 @@ PHP_HTTP_API void php_http_request_info(php_http_request_t *request, HashTable * curl_slist_free_all(s); } #if PHP_HTTP_CURL_VERSION(7,14,1) - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_COOKIELIST, &s)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_COOKIELIST, &s)) { MAKE_STD_ZVAL(subarray); array_init(subarray); for (p = s; p; p = p->next) { @@ -124,22 +124,22 @@ PHP_HTTP_API void php_http_request_info(php_http_request_t *request, HashTable * } #endif #if PHP_HTTP_CURL_VERSION(7,18,2) - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_REDIRECT_URL, &c)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_REDIRECT_URL, &c)) { add_assoc_string_ex(&array, "redirect_url", sizeof("redirect_url"), c ? c : "", 1); } #endif #if PHP_HTTP_CURL_VERSION(7,19,0) - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_PRIMARY_IP, &c)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_PRIMARY_IP, &c)) { add_assoc_string_ex(&array, "primary_ip", sizeof("primary_ip"), c ? c : "", 1); } #endif #if PHP_HTTP_CURL_VERSION(7,19,0) - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_APPCONNECT_TIME, &d)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_APPCONNECT_TIME, &d)) { add_assoc_double_ex(&array, "appconnect_time", sizeof("appconnect_time"), d); } #endif #if PHP_HTTP_CURL_VERSION(7,19,4) - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_CONDITION_UNMET, &l)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_CONDITION_UNMET, &l)) { add_assoc_long_ex(&array, "condition_unmet", sizeof("condition_unmet"), l); } #endif @@ -151,7 +151,7 @@ PHP_HTTP_API void php_http_request_info(php_http_request_t *request, HashTable * struct curl_certinfo *ci; char *colon, *keyname; - if (CURLE_OK == curl_easy_getinfo(request->ch, CURLINFO_CERTINFO, &ci)) { + if (CURLE_OK == curl_easy_getinfo(request->curl.handle, CURLINFO_CERTINFO, &ci)) { MAKE_STD_ZVAL(ci_array); array_init(ci_array); @@ -177,7 +177,7 @@ PHP_HTTP_API void php_http_request_info(php_http_request_t *request, HashTable * } } #endif - add_assoc_string_ex(&array, "error", sizeof("error"), php_http_request_storage_get(request->ch)->errorbuffer, 1); + add_assoc_string_ex(&array, "error", sizeof("error"), php_http_request_storage_get(request->curl.handle)->errorbuffer, 1); } diff --git a/php_http_request_method.c b/php_http_request_method.c index b482d03..83b6232 100644 --- a/php_http_request_method.c +++ b/php_http_request_method.c @@ -55,7 +55,7 @@ static PHP_HTTP_STRLIST(php_http_request_methods) = PHP_HTTP_API const char *php_http_request_method_name(php_http_request_method_t meth) { if (meth > PHP_HTTP_NO_REQUEST_METHOD && meth < PHP_HTTP_MAX_REQUEST_METHOD) { - return php_http_strlist_find(php_http_request_methods, 1, meth); + return php_http_strlist_find(php_http_request_methods, 0, meth); } else { zval **val, *cmp, res; HashPosition pos; diff --git a/php_http_request_pool.c b/php_http_request_pool.c index 4be1111..7f081b8 100644 --- a/php_http_request_pool.c +++ b/php_http_request_pool.c @@ -1,579 +1,200 @@ #include "php_http.h" -#ifdef PHP_HTTP_HAVE_EVENT -# include -#endif - -#include #include +#include -#ifndef PHP_HTTP_DEBUG_REQPOOLS -# define PHP_HTTP_DEBUG_REQPOOLS 0 -#endif - -#ifdef PHP_HTTP_HAVE_EVENT -typedef struct php_http_request_pool_event { - struct event evnt; - php_http_request_pool_t *pool; -} php_http_request_pool_event_t; - -static void php_http_request_pool_timeout_callback(int socket, short action, void *event_data); -static void php_http_request_pool_event_callback(int socket, short action, void *event_data); -static int php_http_request_pool_socket_callback(CURL *easy, curl_socket_t s, int action, void *, void *); -static void php_http_request_pool_timer_callback(CURLM *multi, long timeout_ms, void *timer_data); -#endif - -static int php_http_request_pool_compare_handles(void *h1, void *h2); - -PHP_HTTP_API php_http_request_pool_t *php_http_request_pool_init(php_http_request_pool_t *pool TSRMLS_DC) +PHP_HTTP_API php_http_request_pool_t *php_http_request_pool_init(php_http_request_pool_t *h, php_http_request_pool_ops_t *ops, void *init_arg TSRMLS_DC) { - zend_bool free_pool; - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Initializing request pool %p\n", pool); -#endif + php_http_request_pool_t *free_h = NULL; - if ((free_pool = (!pool))) { - pool = emalloc(sizeof(php_http_request_pool_t)); - pool->ch = NULL; + if (!h) { + free_h = h = emalloc(sizeof(*h)); } + memset(h, 0, sizeof(*h)); - if (SUCCESS != php_http_persistent_handle_acquire(ZEND_STRL("http_request_pool"), &pool->ch TSRMLS_CC)) { - if (free_pool) { - efree(pool); + h->ops = ops; + zend_llist_init(&h->requests.attached, sizeof(zval *), (llist_dtor_func_t) ZVAL_PTR_DTOR, 0); + zend_llist_init(&h->requests.finished, sizeof(zval *), (llist_dtor_func_t) ZVAL_PTR_DTOR, 0); + TSRMLS_SET_CTX(h->ts); + + if (h->ops->init) { + if (!(h = h->ops->init(h, init_arg))) { + php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_POOL, "Could not initialize request pool"); + if (free_h) { + efree(h); + } } - return NULL; } - TSRMLS_SET_CTX(pool->ts); - -#ifdef PHP_HTTP_HAVE_EVENT - pool->timeout = ecalloc(1, sizeof(struct event)); - curl_multi_setopt(pool->ch, CURLMOPT_SOCKETDATA, pool); - curl_multi_setopt(pool->ch, CURLMOPT_SOCKETFUNCTION, php_http_request_pool_socket_callback); - curl_multi_setopt(pool->ch, CURLMOPT_TIMERDATA, pool); - curl_multi_setopt(pool->ch, CURLMOPT_TIMERFUNCTION, php_http_request_pool_timer_callback); -#endif - - pool->unfinished = 0; - zend_llist_init(&pool->finished, sizeof(zval *), (llist_dtor_func_t) ZVAL_PTR_DTOR, 0); - zend_llist_init(&pool->handles, sizeof(zval *), (llist_dtor_func_t) ZVAL_PTR_DTOR, 0); - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Initialized request pool %p\n", pool); -#endif - - return pool; + return h; } -PHP_HTTP_API STATUS php_http_request_pool_attach(php_http_request_pool_t *pool, zval *request) +PHP_HTTP_API php_http_request_pool_t *php_http_request_pool_copy(php_http_request_pool_t *from, php_http_request_pool_t *to) { -#ifdef ZTS - TSRMLS_FETCH_FROM_CTX(pool->ts); -#endif - php_http_request_object_t *req = zend_object_store_get_object(request TSRMLS_CC); - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Attaching HttpRequest(#%d) %p to pool %p\n", Z_OBJ_HANDLE_P(request), req, pool); -#endif - - if (req->pool) { - php_http_error(HE_WARNING, PHP_HTTP_E_INVALID_PARAM, "HttpRequest object(#%d) is already member of %s HttpRequestPool", Z_OBJ_HANDLE_P(request), req->pool == pool ? "this" : "another"); - } else if (SUCCESS != php_http_request_object_requesthandler(req, request)) { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "Could not initialize HttpRequest object(#%d) for attaching to the HttpRequestPool", Z_OBJ_HANDLE_P(request)); - } else { - CURLMcode code = curl_multi_add_handle(pool->ch, req->request->ch); - - if (CURLM_OK != code) { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_POOL, "Could not attach HttpRequest object(#%d) to the HttpRequestPool: %s", Z_OBJ_HANDLE_P(request), curl_multi_strerror(code)); - } else { - req->pool = pool; - - Z_ADDREF_P(request); - zend_llist_add_element(&pool->handles, &request); - ++pool->unfinished; - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "> %d HttpRequests attached to pool %p\n", zend_llist_count(&pool->handles), pool); -#endif - return SUCCESS; - } + if (from->ops->copy) { + return from->ops->copy(from, to); } - return FAILURE; -} -PHP_HTTP_API STATUS php_http_request_pool_detach(php_http_request_pool_t *pool, zval *request) -{ - CURLMcode code; -#ifdef ZTS - TSRMLS_FETCH_FROM_CTX(pool->ts); -#endif - php_http_request_object_t *req = zend_object_store_get_object(request TSRMLS_CC); - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Detaching HttpRequest(#%d) %p from pool %p\n", Z_OBJ_HANDLE_P(request), req, pool); -#endif - - if (!req->pool) { - /* not attached to any pool */ -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "HttpRequest object(#%d) %p is not attached to any HttpRequestPool\n", Z_OBJ_HANDLE_P(request), req); -#endif - } else if (req->pool != pool) { - php_http_error(HE_WARNING, PHP_HTTP_E_INVALID_PARAM, "HttpRequest object(#%d) is not attached to this HttpRequestPool", Z_OBJ_HANDLE_P(request)); - } else if (req->request->_progress.in_cb) { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_POOL, "HttpRequest object(#%d) cannot be detached from the HttpRequestPool while executing the progress callback", Z_OBJ_HANDLE_P(request)); - } else if (CURLM_OK != (code = curl_multi_remove_handle(pool->ch, req->request->ch))) { - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST_POOL, "Could not detach HttpRequest object(#%d) from the HttpRequestPool: %s", Z_OBJ_HANDLE_P(request), curl_multi_strerror(code)); - } else { - req->pool = NULL; - zend_llist_del_element(&pool->finished, request, php_http_request_pool_compare_handles); - zend_llist_del_element(&pool->handles, request, php_http_request_pool_compare_handles); - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "> %d HttpRequests remaining in pool %p\n", zend_llist_count(&pool->handles), pool); -#endif - - return SUCCESS; - } - return FAILURE; + return NULL; } -PHP_HTTP_API void php_http_request_pool_apply(php_http_request_pool_t *pool, php_http_request_pool_apply_func_t cb) +PHP_HTTP_API void php_http_request_pool_dtor(php_http_request_pool_t *h) { - int count = zend_llist_count(&pool->handles); - - if (count) { - int i = 0; - zend_llist_position pos; - zval **handle, **handles = emalloc(count * sizeof(zval *)); - - for (handle = zend_llist_get_first_ex(&pool->handles, &pos); handle; handle = zend_llist_get_next_ex(&pool->handles, &pos)) { - handles[i++] = *handle; - } + if (h->ops->dtor) { + h->ops->dtor(h); + } - /* should never happen */ - if (i != count) { - zend_error(E_ERROR, "number of fetched request handles do not match overall count"); - count = i; - } + zend_llist_clean(&h->requests.finished); + zend_llist_clean(&h->requests.attached); +} - for (i = 0; i < count; ++i) { - if (cb(pool, handles[i])) { - break; - } - } - efree(handles); +PHP_HTTP_API void php_http_request_pool_free(php_http_request_pool_t **h) { + if (*h) { + php_http_request_pool_dtor(*h); + efree(*h); + *h = NULL; } } -PHP_HTTP_API void php_http_request_pool_apply_with_arg(php_http_request_pool_t *pool, php_http_request_pool_apply_with_arg_func_t cb, void *arg) +PHP_HTTP_API STATUS php_http_request_pool_attach(php_http_request_pool_t *h, zval *request) { - int count = zend_llist_count(&pool->handles); - - if (count) { - int i = 0; - zend_llist_position pos; - zval **handle, **handles = emalloc(count * sizeof(zval *)); - - for (handle = zend_llist_get_first_ex(&pool->handles, &pos); handle; handle = zend_llist_get_next_ex(&pool->handles, &pos)) { - handles[i++] = *handle; - } + TSRMLS_FETCH_FROM_CTX(h->ts); - /* should never happen */ - if (i != count) { - zend_error(E_ERROR, "number of fetched request handles do not match overall count"); - count = i; - } + if (h->ops->attach) { + char *url = NULL; + php_http_request_method_t m = PHP_HTTP_NO_REQUEST_METHOD; + php_http_message_body_t *body = NULL; + php_http_request_object_t *obj = zend_object_store_get_object(request TSRMLS_CC); - for (i = 0; i < count; ++i) { - if (cb(pool, handles[i], arg)) { - break; - } + if (SUCCESS != php_http_request_object_requesthandler(obj, request, &m, &url, &body)) { + return FAILURE; } - efree(handles); - } -} - -PHP_HTTP_API void php_http_request_pool_detach_all(php_http_request_pool_t *pool) -{ -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Detaching %d requests from pool %p\n", zend_llist_count(&pool->handles), pool); -#endif - php_http_request_pool_apply(pool, php_http_request_pool_detach); -} - -PHP_HTTP_API STATUS php_http_request_pool_send(php_http_request_pool_t *pool) -{ - TSRMLS_FETCH_FROM_CTX(pool->ts); - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Attempt to send %d requests of pool %p\n", zend_llist_count(&pool->handles), pool); -#endif - -#ifdef PHP_HTTP_HAVE_EVENT - if (pool->useevents) { - do { -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "& Starting event dispatcher of pool %p\n", pool); -#endif - event_base_dispatch(PHP_HTTP_G->request_pool.event_base); - } while (pool->unfinished); - } else -#endif - { - while (php_http_request_pool_perform(pool)) { - if (SUCCESS != php_http_request_pool_select(pool, NULL)) { -#ifdef PHP_WIN32 - /* see http://msdn.microsoft.com/library/en-us/winsock/winsock/windows_sockets_error_codes_2.asp */ - php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, "WinSock error: %d", WSAGetLastError()); -#else - php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, strerror(errno)); -#endif - return FAILURE; - } + if (SUCCESS == h->ops->attach(h, obj->request, m, url, body)) { + STR_FREE(url); + Z_ADDREF_P(request); + zend_llist_add_element(&h->requests.attached, &request); + return SUCCESS; } + STR_FREE(url); } -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Finished sending %d HttpRequests of pool %p (still unfinished: %d)\n", zend_llist_count(&pool->handles), pool, pool->unfinished); -#endif - - return SUCCESS; + return FAILURE; } -PHP_HTTP_API void php_http_request_pool_dtor(php_http_request_pool_t *pool) +static int php_http_request_pool_compare_handles(void *h1, void *h2) { - TSRMLS_FETCH_FROM_CTX(pool->ts); - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Destructing request pool %p\n", pool); -#endif - -#ifdef PHP_HTTP_HAVE_EVENT - efree(pool->timeout); -#endif - - php_http_request_pool_detach_all(pool); - - pool->unfinished = 0; - zend_llist_clean(&pool->finished); - zend_llist_clean(&pool->handles); - php_http_persistent_handle_release(ZEND_STRL("http_request_pool"), &pool->ch TSRMLS_CC); -} - -PHP_HTTP_API void php_http_request_pool_free(php_http_request_pool_t **pool) { - if (*pool) { - php_http_request_pool_dtor(*pool); - efree(*pool); - *pool = NULL; - } + return (Z_OBJ_HANDLE_PP((zval **) h1) == Z_OBJ_HANDLE_P((zval *) h2)); } -#ifdef PHP_WIN32 -# define SELECT_ERROR SOCKET_ERROR -#else -# define SELECT_ERROR -1 -#endif -PHP_HTTP_API STATUS php_http_request_pool_select(php_http_request_pool_t *pool, struct timeval *custom_timeout) +PHP_HTTP_API STATUS php_http_request_pool_detach(php_http_request_pool_t *h, zval *request) { - int MAX; - fd_set R, W, E; - struct timeval timeout; - -#ifdef PHP_HTTP_HAVE_EVENT - if (pool->useevents) { - TSRMLS_FETCH_FROM_CTX(pool->ts); - php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "not implemented; use HttpRequest callbacks"); - return FAILURE; - } -#endif - - if (custom_timeout && timerisset(custom_timeout)) { - timeout = *custom_timeout; - } else { - php_http_request_pool_timeout(pool, &timeout); - } + TSRMLS_FETCH_FROM_CTX(h->ts); - FD_ZERO(&R); - FD_ZERO(&W); - FD_ZERO(&E); + if (h->ops->detach) { + php_http_request_object_t *obj = zend_object_store_get_object(request TSRMLS_CC); - if (CURLM_OK == curl_multi_fdset(pool->ch, &R, &W, &E, &MAX)) { - if (MAX == -1) { - php_http_sleep((double) timeout.tv_sec + (double) (timeout.tv_usec / PHP_HTTP_MCROSEC)); - return SUCCESS; - } else if (SELECT_ERROR != select(MAX + 1, &R, &W, &E, &timeout)) { + if (SUCCESS == h->ops->detach(h, obj->request)) { + zend_llist_del_element(&h->requests.finished, request, php_http_request_pool_compare_handles); + zend_llist_del_element(&h->requests.attached, request, php_http_request_pool_compare_handles); return SUCCESS; } } + return FAILURE; } -PHP_HTTP_API int php_http_request_pool_perform(php_http_request_pool_t *pool) +PHP_HTTP_API STATUS php_http_request_pool_wait(php_http_request_pool_t *h, struct timeval *custom_timeout) { - TSRMLS_FETCH_FROM_CTX(pool->ts); - -#ifdef PHP_HTTP_HAVE_EVENT - if (pool->useevents) { - php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "not implemented; use HttpRequest callbacks"); - return FAILURE; + if (h->ops->wait) { + return h->ops->wait(h, custom_timeout); } -#endif - - while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform(pool->ch, &pool->unfinished)); - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "%u unfinished requests of pool %p remaining\n", pool->unfinished, pool); -#endif - php_http_request_pool_responsehandler(pool); - - return pool->unfinished; -} - -void php_http_request_pool_responsehandler(php_http_request_pool_t *pool) -{ - CURLMsg *msg; - int remaining = 0; - TSRMLS_FETCH_FROM_CTX(pool->ts); - - do { - msg = curl_multi_info_read(pool->ch, &remaining); - if (msg && CURLMSG_DONE == msg->msg) { - if (CURLE_OK != msg->data.result) { - php_http_request_storage_t *st = php_http_request_storage_get(msg->easy_handle); - php_http_error(HE_WARNING, PHP_HTTP_E_REQUEST, "%s; %s (%s)", curl_easy_strerror(msg->data.result), STR_PTR(st->errorbuffer), STR_PTR(st->url)); - } - php_http_request_pool_apply_with_arg(pool, php_http_request_pool_apply_responsehandler, msg->easy_handle); - } - } while (remaining); + return FAILURE; } -int php_http_request_pool_apply_responsehandler(php_http_request_pool_t *pool, zval *req, void *ch) +PHP_HTTP_API int php_http_request_pool_once(php_http_request_pool_t *h) { -#ifdef ZTS - TSRMLS_FETCH_FROM_CTX(pool->ts); -#endif - php_http_request_object_t *obj = zend_object_store_get_object(req TSRMLS_CC); - - if ((!ch) || obj->request->ch == (CURL *) ch) { - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Fetching data from HttpRequest(#%d) %p of pool %p\n", Z_OBJ_HANDLE_P(req), obj, obj->pool); -#endif - - Z_ADDREF_P(req); - zend_llist_add_element(&obj->pool->finished, &req); - php_http_request_object_responsehandler(obj, req); - return 1; + if (h->ops->once) { + return h->ops->once(h); } - return 0; + + return FAILURE; } -struct timeval *php_http_request_pool_timeout(php_http_request_pool_t *pool, struct timeval *timeout) +PHP_HTTP_API STATUS php_http_request_pool_exec(php_http_request_pool_t *h) { -#ifdef HAVE_CURL_MULTI_TIMEOUT - long max_tout = 1000; + TSRMLS_FETCH_FROM_CTX(h->ts); - if ((CURLM_OK == curl_multi_timeout(pool->ch, &max_tout)) && (max_tout > 0)) { - timeout->tv_sec = max_tout / 1000; - timeout->tv_usec = (max_tout % 1000) * 1000; - } else { -#endif - timeout->tv_sec = 0; - timeout->tv_usec = 1000; -#ifdef HAVE_CURL_MULTI_TIMEOUT + if (h->ops->exec) { + return h->ops->exec(h); } -#endif - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Calculating timeout (%lu, %lu) of pool %p\n", (ulong) timeout->tv_sec, (ulong) timeout->tv_usec, pool); -#endif - return timeout; + return FAILURE; } -/*#*/ - -static int php_http_request_pool_compare_handles(void *h1, void *h2) +static void detach(void *r, void *h TSRMLS_DC) { - return (Z_OBJ_HANDLE_PP((zval **) h1) == Z_OBJ_HANDLE_P((zval *) h2)); + ((php_http_request_pool_t *) h)->ops->detach(h, ((php_http_request_object_t *) zend_object_store_get_object(*((zval **) r) TSRMLS_CC))->request); } -#ifdef PHP_HTTP_HAVE_EVENT - -static void php_http_request_pool_timeout_callback(int socket, short action, void *event_data) +PHP_HTTP_API void php_http_request_pool_reset(php_http_request_pool_t *h) { - php_http_request_pool_t *pool = event_data; - - if (pool->useevents) { - CURLMcode rc; - TSRMLS_FETCH_FROM_CTX(pool->ts); - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Timeout occurred of pool %p\n", pool); -#endif + if (h->ops->reset) { + h->ops->reset(h); + } else if (h->ops->detach) { + TSRMLS_FETCH_FROM_CTX(h->ts); - while (CURLM_CALL_MULTI_PERFORM == (rc = curl_multi_socket(pool->ch, CURL_SOCKET_TIMEOUT, &pool->unfinished))); - - if (CURLM_OK != rc) { - php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, curl_multi_strerror(rc)); - } - - php_http_request_pool_responsehandler(pool); + zend_llist_apply_with_argument(&h->requests.attached, detach, h TSRMLS_CC); } + + zend_llist_clean(&h->requests.attached); + zend_llist_clean(&h->requests.finished); } -static void php_http_request_pool_event_callback(int socket, short action, void *event_data) +PHP_HTTP_API STATUS php_http_request_pool_setopt(php_http_request_pool_t *h, php_http_request_pool_setopt_opt_t opt, void *arg) { - php_http_request_pool_event_t *ev = event_data; - php_http_request_pool_t *pool = ev->pool; - - if (pool->useevents) { - CURLMcode rc = CURLE_OK; - TSRMLS_FETCH_FROM_CTX(ev->pool->ts); - -#if PHP_HTTP_DEBUG_REQPOOLS - { - static const char event_strings[][20] = {"NONE","TIMEOUT","READ","TIMEOUT|READ","WRITE","TIMEOUT|WRITE","READ|WRITE","TIMEOUT|READ|WRITE","SIGNAL"}; - fprintf(stderr, "Event on socket %d (%s) event %p of pool %p\n", socket, event_strings[action], ev, pool); - } -#endif - - /* don't use 'ev' below this loop as it might 've been freed in the socket callback */ - do { -#ifdef HAVE_CURL_MULTI_SOCKET_ACTION - switch (action & (EV_READ|EV_WRITE)) { - case EV_READ: - rc = curl_multi_socket_action(pool->ch, socket, CURL_CSELECT_IN, &pool->unfinished); - break; - case EV_WRITE: - rc = curl_multi_socket_action(pool->ch, socket, CURL_CSELECT_OUT, &pool->unfinished); - break; - case EV_READ|EV_WRITE: - rc = curl_multi_socket_action(pool->ch, socket, CURL_CSELECT_IN|CURL_CSELECT_OUT, &pool->unfinished); - break; - default: - php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, "Unknown event %d", (int) action); - return; - } -#else - rc = curl_multi_socket(pool->ch, socket, &pool->unfinished); -#endif - } while (CURLM_CALL_MULTI_PERFORM == rc); - - switch (rc) { - case CURLM_BAD_SOCKET: -#if 0 - fprintf(stderr, "!!! Bad socket: %d (%d)\n", socket, (int) action); -#endif - case CURLM_OK: - break; - default: - php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, curl_multi_strerror(rc)); - break; - } - - php_http_request_pool_responsehandler(pool); - - /* remove timeout if there are no transfers left */ - if (!pool->unfinished && event_initialized(pool->timeout) && event_pending(pool->timeout, EV_TIMEOUT, NULL)) { - event_del(pool->timeout); -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Removed timeout of pool %p\n", pool); -#endif - } + if (h->ops->setopt) { + return h->ops->setopt(h, opt, arg); } + + return FAILURE; } -static int php_http_request_pool_socket_callback(CURL *easy, curl_socket_t sock, int action, void *socket_data, void *assign_data) +PHP_HTTP_API void php_http_request_pool_requests(php_http_request_pool_t *h, zval ***attached, zval ***finished) { - php_http_request_pool_t *pool = socket_data; + zval **handle; + int i, count; - if (pool->useevents) { - int events = EV_PERSIST; - php_http_request_pool_event_t *ev = assign_data; - TSRMLS_FETCH_FROM_CTX(pool->ts); + if (attached) { + if ((count = zend_llist_count(&h->requests.attached))) { + *attached = ecalloc(count + 1 /* terminating NULL */, sizeof(zval *)); - if (!ev) { - ev = ecalloc(1, sizeof(php_http_request_pool_event_t)); - ev->pool = pool; - curl_multi_assign(pool->ch, sock, ev); - event_base_set(PHP_HTTP_G->request_pool.event_base, &ev->evnt); + for (i = 0, handle = zend_llist_get_first(&h->requests.attached); handle; handle = zend_llist_get_next(&h->requests.attached)) { + Z_ADDREF_PP(handle); + (*attached)[i++] = *handle; + } } else { - event_del(&ev->evnt); + *attached = NULL; } - -#if PHP_HTTP_DEBUG_REQPOOLS - { - static const char action_strings[][8] = {"NONE", "IN", "OUT", "INOUT", "REMOVE"}; - php_http_request_t *r; - curl_easy_getinfo(easy, CURLINFO_PRIVATE, &r); - fprintf(stderr, "Callback on socket %2d (%8s) event %p of pool %p (%d)\n", (int) sock, action_strings[action], ev, pool, pool->unfinished); - } -#endif - - switch (action) { - case CURL_POLL_IN: - events |= EV_READ; - break; - case CURL_POLL_OUT: - events |= EV_WRITE; - break; - case CURL_POLL_INOUT: - events |= EV_READ|EV_WRITE; - break; - - case CURL_POLL_REMOVE: - efree(ev); - case CURL_POLL_NONE: - return 0; - - default: - php_http_error(HE_WARNING, PHP_HTTP_E_SOCKET, "Unknown socket action %d", action); - return -1; - } - - event_set(&ev->evnt, sock, events, php_http_request_pool_event_callback, ev); - event_add(&ev->evnt, NULL); } - return 0; -} - -static void php_http_request_pool_timer_callback(CURLM *multi, long timeout_ms, void *timer_data) -{ - php_http_request_pool_t *pool = timer_data; - - if (pool->useevents) { - TSRMLS_FETCH_FROM_CTX(pool->ts); - struct timeval timeout; - - if (!event_initialized(pool->timeout)) { - event_set(pool->timeout, -1, 0, php_http_request_pool_timeout_callback, pool); - event_base_set(PHP_HTTP_G->request_pool.event_base, pool->timeout); - } else if (event_pending(pool->timeout, EV_TIMEOUT, NULL)) { - event_del(pool->timeout); - } + if (finished) { + if ((count = zend_llist_count(&h->requests.finished))) { + *finished = ecalloc(count + 1 /* terminating NULL */, sizeof(zval *)); - if (timeout_ms > 0) { - timeout.tv_sec = timeout_ms / 1000; - timeout.tv_usec = (timeout_ms % 1000) * 1000; + for (i = 0, handle = zend_llist_get_first(&h->requests.finished); handle; handle = zend_llist_get_next(&h->requests.finished)) { + Z_ADDREF_PP(handle); + (*finished)[i++] = *handle; + } } else { - php_http_request_pool_timeout(pool, &timeout); + *finished = NULL; } - - event_add(pool->timeout, &timeout); - -#if PHP_HTTP_DEBUG_REQPOOLS - fprintf(stderr, "Updating timeout %lu (%lu, %lu) of pool %p\n", (ulong) timeout_ms, (ulong) timeout.tv_sec, (ulong) timeout.tv_usec, pool); -#endif } } -#endif /* HAVE_EVENT */ + +/*#*/ #define PHP_HTTP_BEGIN_ARGS(method, req_args) PHP_HTTP_BEGIN_ARGS_EX(HttpRequestPool, method, 0, req_args) #define PHP_HTTP_EMPTY_ARGS(method) PHP_HTTP_EMPTY_ARGS_EX(HttpRequestPool, method, 0) @@ -593,8 +214,8 @@ PHP_HTTP_BEGIN_ARGS(detach, 1) PHP_HTTP_END_ARGS; PHP_HTTP_EMPTY_ARGS(send); -PHP_HTTP_EMPTY_ARGS(socketPerform); -PHP_HTTP_BEGIN_ARGS(socketSelect, 0) +PHP_HTTP_EMPTY_ARGS(once); +PHP_HTTP_BEGIN_ARGS(wait, 0) PHP_HTTP_ARG_VAL(timeout, 0) PHP_HTTP_END_ARGS; @@ -619,15 +240,15 @@ PHP_HTTP_END_ARGS; zend_class_entry *php_http_request_pool_class_entry; zend_function_entry php_http_request_pool_method_entry[] = { - PHP_HTTP_REQPOOL_ME(__construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) + PHP_HTTP_REQPOOL_ME(__construct, ZEND_ACC_PRIVATE|ZEND_ACC_CTOR) PHP_HTTP_REQPOOL_ME(__destruct, ZEND_ACC_PUBLIC|ZEND_ACC_DTOR) PHP_HTTP_REQPOOL_ME(attach, ZEND_ACC_PUBLIC) PHP_HTTP_REQPOOL_ME(detach, ZEND_ACC_PUBLIC) PHP_HTTP_REQPOOL_ME(send, ZEND_ACC_PUBLIC) PHP_HTTP_REQPOOL_ME(reset, ZEND_ACC_PUBLIC) - PHP_HTTP_REQPOOL_ME(socketPerform, ZEND_ACC_PROTECTED) - PHP_HTTP_REQPOOL_ME(socketSelect, ZEND_ACC_PROTECTED) + PHP_HTTP_REQPOOL_ME(once, ZEND_ACC_PROTECTED) + PHP_HTTP_REQPOOL_ME(wait, ZEND_ACC_PROTECTED) /* implements Iterator */ PHP_HTTP_REQPOOL_ME(valid, ZEND_ACC_PUBLIC) @@ -650,6 +271,11 @@ zend_function_entry php_http_request_pool_method_entry[] = { static zend_object_handlers php_http_request_pool_object_handlers; zend_object_value php_http_request_pool_object_new(zend_class_entry *ce TSRMLS_DC) +{ + return php_http_request_pool_object_new_ex(ce, NULL, NULL TSRMLS_CC); +} + +zend_object_value php_http_request_pool_object_new_ex(zend_class_entry *ce, php_http_request_pool_t *p, php_http_request_pool_object_t **ptr TSRMLS_DC) { zend_object_value ov; php_http_request_pool_object_t *o; @@ -658,7 +284,13 @@ zend_object_value php_http_request_pool_object_new(zend_class_entry *ce TSRMLS_D zend_object_std_init((zend_object *) o, ce TSRMLS_CC); object_properties_init((zend_object *) o, ce); - php_http_request_pool_init(&o->pool TSRMLS_CC); + if (!(o->pool = p)) { + o->pool = php_http_request_pool_init(NULL, NULL, NULL TSRMLS_CC); + } + + if (ptr) { + *ptr = o; + } ov.handle = zend_objects_store_put(o, NULL, php_http_request_pool_object_free, NULL TSRMLS_CC); ov.handlers = &php_http_request_pool_object_handlers; @@ -670,7 +302,7 @@ void php_http_request_pool_object_free(void *object TSRMLS_DC) { php_http_request_pool_object_t *o = (php_http_request_pool_object_t *) object; - php_http_request_pool_dtor(&o->pool); + php_http_request_pool_free(&o->pool); zend_object_std_dtor((zend_object *) o TSRMLS_CC); efree(o); } @@ -681,26 +313,11 @@ static void php_http_request_pool_object_llist2array(zval **req, zval *array TSR add_next_index_zval(array, *req); } -/* ### USERLAND ### */ PHP_METHOD(HttpRequestPool, __construct) { with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { - int argc; - zval ***argv; - - if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "*", &argv, &argc)) { - with_error_handling(EH_THROW, PHP_HTTP_EX_CE(request_pool)) { - int i; - php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - - for (i = 0; i < argc; ++i) { - if (Z_TYPE_PP(argv[i]) == IS_OBJECT && instanceof_function(Z_OBJCE_PP(argv[i]), php_http_request_class_entry TSRMLS_CC)) { - php_http_request_pool_attach(&obj->pool, *(argv[i])); - } - } - } end_error_handling(); - } + zend_parse_parameters_none(); } end_error_handling(); } @@ -712,7 +329,7 @@ PHP_METHOD(HttpRequestPool, __destruct) ; /* we always want to clean up */ } - php_http_request_pool_detach_all(&obj->pool); + php_http_request_pool_reset(obj->pool); } PHP_METHOD(HttpRequestPool, reset) @@ -721,16 +338,13 @@ PHP_METHOD(HttpRequestPool, reset) php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); obj->iterator.pos = 0; - php_http_request_pool_detach_all(&obj->pool); - RETURN_TRUE; + php_http_request_pool_reset(obj->pool); } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequestPool, attach) { - RETVAL_FALSE; - with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { zval *request; @@ -738,14 +352,16 @@ PHP_METHOD(HttpRequestPool, attach) with_error_handling(EH_THROW, PHP_HTTP_EX_CE(runtime)) { php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - if (obj->iterator.pos > 0 && obj->iterator.pos < zend_llist_count(&obj->pool.handles)) { + if (obj->iterator.pos > 0 && obj->iterator.pos < zend_llist_count(&obj->pool->requests.attached)) { php_http_error(HE_THROW, PHP_HTTP_E_REQUEST_POOL, "Cannot attach to the HttpRequestPool while the iterator is active"); } else { - RETVAL_SUCCESS(php_http_request_pool_attach(&obj->pool, request)); + php_http_request_pool_attach(obj->pool, request); } } end_error_handling(); } } end_error_handling(); + + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequestPool, detach) @@ -760,10 +376,12 @@ PHP_METHOD(HttpRequestPool, detach) php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); obj->iterator.pos = -1; - RETVAL_SUCCESS(php_http_request_pool_detach(&obj->pool, request)); + php_http_request_pool_detach(obj->pool, request); } end_error_handling(); } } end_error_handling(); + + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequestPool, send) @@ -775,25 +393,27 @@ PHP_METHOD(HttpRequestPool, send) with_error_handling(EH_THROW, PHP_HTTP_EX_CE(request_pool)) { php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - RETVAL_SUCCESS(php_http_request_pool_send(&obj->pool)); + php_http_request_pool_exec(obj->pool); } end_error_handling(); } } end_error_handling(); + + RETVAL_ZVAL(getThis(), 1, 0); } -PHP_METHOD(HttpRequestPool, socketPerform) +PHP_METHOD(HttpRequestPool, once) { if (SUCCESS == zend_parse_parameters_none()) { php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - if (0 < php_http_request_pool_perform(&obj->pool)) { + if (0 < php_http_request_pool_once(obj->pool)) { RETURN_TRUE; } } RETURN_FALSE; } -PHP_METHOD(HttpRequestPool, socketSelect) +PHP_METHOD(HttpRequestPool, wait) { double timeout = 0; @@ -804,7 +424,7 @@ PHP_METHOD(HttpRequestPool, socketSelect) timeout_val.tv_sec = (time_t) timeout; timeout_val.tv_usec = PHP_HTTP_USEC(timeout) % PHP_HTTP_MCROSEC; - RETURN_SUCCESS(php_http_request_pool_select(&obj->pool, timeout ? &timeout_val : NULL)); + RETURN_SUCCESS(php_http_request_pool_wait(obj->pool, timeout ? &timeout_val : NULL)); } RETURN_FALSE; } @@ -814,7 +434,7 @@ PHP_METHOD(HttpRequestPool, valid) if (SUCCESS == zend_parse_parameters_none()) { php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - RETURN_BOOL(obj->iterator.pos >= 0 && obj->iterator.pos < zend_llist_count(&obj->pool.handles)); + RETURN_BOOL(obj->iterator.pos >= 0 && obj->iterator.pos < zend_llist_count(&obj->pool->requests.attached)); } RETURN_FALSE; } @@ -824,14 +444,14 @@ PHP_METHOD(HttpRequestPool, current) if (SUCCESS == zend_parse_parameters_none()) { php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - if (obj->iterator.pos < zend_llist_count(&obj->pool.handles)) { + if (obj->iterator.pos < zend_llist_count(&obj->pool->requests.attached)) { long pos = 0; zval **current = NULL; zend_llist_position lpos; - for ( current = zend_llist_get_first_ex(&obj->pool.handles, &lpos); + for ( current = zend_llist_get_first_ex(&obj->pool->requests.attached, &lpos); current && obj->iterator.pos != pos++; - current = zend_llist_get_next_ex(&obj->pool.handles, &lpos)); + current = zend_llist_get_next_ex(&obj->pool->requests.attached, &lpos)); if (current) { RETURN_OBJECT(*current, 1); } @@ -873,7 +493,7 @@ PHP_METHOD(HttpRequestPool, count) if (SUCCESS == zend_parse_parameters_none()) { php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - RETURN_LONG((long) zend_llist_count(&obj->pool.handles)); + RETURN_LONG((long) zend_llist_count(&obj->pool->requests.attached)); } } @@ -883,7 +503,7 @@ PHP_METHOD(HttpRequestPool, getAttachedRequests) php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); array_init(return_value); - zend_llist_apply_with_argument(&obj->pool.handles, + zend_llist_apply_with_argument(&obj->pool->requests.attached, (llist_apply_with_arg_func_t) php_http_request_pool_object_llist2array, return_value TSRMLS_CC); return; @@ -897,7 +517,7 @@ PHP_METHOD(HttpRequestPool, getFinishedRequests) php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); array_init(return_value); - zend_llist_apply_with_argument(&obj->pool.finished, + zend_llist_apply_with_argument(&obj->pool->requests.finished, (llist_apply_with_arg_func_t) php_http_request_pool_object_llist2array, return_value TSRMLS_CC); return; @@ -912,11 +532,9 @@ PHP_METHOD(HttpRequestPool, enablePipelining) if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &enable)) { php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - if (CURLM_OK == curl_multi_setopt(obj->pool.ch, CURLMOPT_PIPELINING, (long) enable)) { - RETURN_TRUE; - } + php_http_request_pool_setopt(obj->pool, PHP_HTTP_REQUEST_POOL_OPT_ENABLE_PIPELINING, &enable); } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_METHOD(HttpRequestPool, enableEvents) @@ -924,41 +542,22 @@ PHP_METHOD(HttpRequestPool, enableEvents) zend_bool enable = 1; if (SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &enable)) { -#if PHP_HTTP_HAVE_EVENT php_http_request_pool_object_t *obj = zend_object_store_get_object(getThis() TSRMLS_CC); - obj->pool.useevents = enable; - RETURN_TRUE; -#endif + php_http_request_pool_setopt(obj->pool, PHP_HTTP_REQUEST_POOL_OPT_USE_EVENTS, &enable); } - RETURN_FALSE; + RETVAL_ZVAL(getThis(), 1, 0); } PHP_MINIT_FUNCTION(http_request_pool) { - if (SUCCESS != php_http_persistent_handle_provide(ZEND_STRL("http_request_pool"), curl_multi_init, (php_http_persistent_handle_dtor_t) curl_multi_cleanup, NULL TSRMLS_CC)) { - return FAILURE; - } - PHP_HTTP_REGISTER_CLASS(http\\request, Pool, http_request_pool, php_http_object_class_entry, 0); php_http_request_pool_class_entry->create_object = php_http_request_pool_object_new; memcpy(&php_http_request_pool_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); php_http_request_pool_object_handlers.clone_obj = NULL; - zend_class_implements(php_http_request_pool_class_entry TSRMLS_CC, 2, spl_ce_Countable, zend_ce_iterator); + zend_class_implements(php_http_request_pool_class_entry TSRMLS_CC, 3, spl_ce_Countable, zend_ce_iterator, php_http_fluently_callable_class_entry); return SUCCESS; } -PHP_RINIT_FUNCTION(http_request_pool) -{ -#ifdef PHP_HTTP_HAVE_EVENT - if (!PHP_HTTP_G->request_pool.event_base && !(PHP_HTTP_G->request_pool.event_base = event_init())) { - return FAILURE; - } -#endif - - return SUCCESS; -} - - diff --git a/php_http_request_pool.h b/php_http_request_pool.h index 18d7243..f75c01d 100644 --- a/php_http_request_pool.h +++ b/php_http_request_pool.h @@ -2,53 +2,69 @@ #ifndef PHP_HTTP_REQUESTPOOL_H #define PHP_HTTP_REQUESTPOOL_H -#include +#include "php_http_request.h" -struct php_http_request_pool_globals { - void *event_base; -}; +typedef enum php_http_request_pool_setopt_opt { + PHP_HTTP_REQUEST_POOL_OPT_ENABLE_PIPELINING, + PHP_HTTP_REQUEST_POOL_OPT_USE_EVENTS, +} php_http_request_pool_setopt_opt_t; -typedef struct php_http_request_pool { - CURLM *ch; - zend_llist finished; - zend_llist handles; - int unfinished; /* int because of curl_multi_perform() */ -#ifdef ZTS - void ***ts; -#endif -#ifdef PHP_HTTP_HAVE_EVENT - struct event *timeout; - unsigned useevents:1; - unsigned runsocket:1; -#endif -} php_http_request_pool_t; +typedef struct php_http_request_pool php_http_request_pool_t; -typedef int (*php_http_request_pool_apply_func_t)(php_http_request_pool_t *pool, zval *request); -typedef int (*php_http_request_pool_apply_with_arg_func_t)(php_http_request_pool_t *pool, zval *request, void *arg); +typedef php_http_request_pool_t *(*php_http_request_pool_init_func_t)(php_http_request_pool_t *p, void *arg); +typedef php_http_request_pool_t *(*php_http_request_pool_copy_func_t)(php_http_request_pool_t *from, php_http_request_pool_t *to); +typedef void (*php_http_request_pool_dtor_func_t)(php_http_request_pool_t *p); +typedef void (*php_http_request_pool_reset_func_t)(php_http_request_pool_t *p); +typedef STATUS (*php_http_request_pool_exec_func_t)(php_http_request_pool_t *p); +typedef STATUS (*php_http_request_pool_wait_func_t)(php_http_request_pool_t *p, struct timeval *custom_timeout); +typedef int (*php_http_request_pool_once_func_t)(php_http_request_pool_t *p); +typedef STATUS (*php_http_request_pool_attach_func_t)(php_http_request_pool_t *p, php_http_request_t *r, php_http_request_method_t m, const char *url, php_http_message_body_t *body); +typedef STATUS (*php_http_request_pool_detach_func_t)(php_http_request_pool_t *p, php_http_request_t *r); +typedef STATUS (*php_http_request_pool_setopt_func_t)(php_http_request_pool_t *p, php_http_request_pool_setopt_opt_t opt, void *arg); -#ifdef PHP_HTTP_HAVE_EVENT -PHP_RINIT_FUNCTION(php_http_request_pool); -#endif +typedef struct php_http_request_pool_ops { + php_http_request_pool_init_func_t init; + php_http_request_pool_copy_func_t copy; + php_http_request_pool_dtor_func_t dtor; + php_http_request_pool_reset_func_t reset; + php_http_request_pool_exec_func_t exec; + php_http_request_pool_wait_func_t wait; + php_http_request_pool_once_func_t once; + php_http_request_pool_attach_func_t attach; + php_http_request_pool_detach_func_t detach; + php_http_request_pool_setopt_func_t setopt; +} php_http_request_pool_ops_t; -extern struct timeval *php_http_request_pool_timeout(php_http_request_pool_t *pool, struct timeval *timeout); -extern void php_http_request_pool_responsehandler(php_http_request_pool_t *pool); -extern int php_http_request_pool_apply_responsehandler(php_http_request_pool_t *pool, zval *req, void *ch); +struct php_http_request_pool { + void *ctx; + php_http_request_pool_ops_t *ops; -PHP_HTTP_API php_http_request_pool_t *php_http_request_pool_init(php_http_request_pool_t *pool TSRMLS_DC); -PHP_HTTP_API STATUS php_http_request_pool_attach(php_http_request_pool_t *pool, zval *request); -PHP_HTTP_API STATUS php_http_request_pool_detach(php_http_request_pool_t *pool, zval *request); -PHP_HTTP_API void php_http_request_pool_apply(php_http_request_pool_t *pool, php_http_request_pool_apply_func_t cb); -PHP_HTTP_API void php_http_request_pool_apply_with_arg(php_http_request_pool_t *pool, php_http_request_pool_apply_with_arg_func_t cb, void *arg); -PHP_HTTP_API void php_http_request_pool_detach_all(php_http_request_pool_t *pool); -PHP_HTTP_API STATUS php_http_request_pool_send(php_http_request_pool_t *pool); -PHP_HTTP_API STATUS php_http_request_pool_select(php_http_request_pool_t *pool, struct timeval *custom_timeout); -PHP_HTTP_API int php_http_request_pool_perform(php_http_request_pool_t *pool); + struct { + zend_llist attached; + zend_llist finished; + } requests; + +#ifdef ZTS + void ***ts; +#endif +}; + +PHP_HTTP_API php_http_request_pool_t *php_http_request_pool_init(php_http_request_pool_t *pool, php_http_request_pool_ops_t *ops, void *init_arg TSRMLS_DC); +PHP_HTTP_API php_http_request_pool_t *php_http_request_pool_copy(php_http_request_pool_t *from, php_http_request_pool_t *to); PHP_HTTP_API void php_http_request_pool_dtor(php_http_request_pool_t *pool); PHP_HTTP_API void php_http_request_pool_free(php_http_request_pool_t **pool); +PHP_HTTP_API void php_http_request_pool_reset(php_http_request_pool_t *pool); +PHP_HTTP_API STATUS php_http_request_pool_exec(php_http_request_pool_t *pool); +PHP_HTTP_API STATUS php_http_request_pool_wait(php_http_request_pool_t *pool, struct timeval *custom_timeout); +PHP_HTTP_API STATUS php_http_request_pool_once(php_http_request_pool_t *pool); +PHP_HTTP_API STATUS php_http_request_pool_attach(php_http_request_pool_t *pool, zval *request); +PHP_HTTP_API STATUS php_http_request_pool_detach(php_http_request_pool_t *pool, zval *request); +PHP_HTTP_API STATUS php_http_request_pool_setopt(php_http_request_pool_t *pool, php_http_request_pool_setopt_opt_t opt, void *arg); +PHP_HTTP_API void php_http_request_pool_requests(php_http_request_pool_t *h, zval ***attached, zval ***finished); typedef struct php_http_request_pool_object { zend_object zo; - php_http_request_pool_t pool; + php_http_request_pool_t *pool; struct { long pos; } iterator; @@ -58,6 +74,7 @@ extern zend_class_entry *php_http_request_pool_class_entry; extern zend_function_entry php_http_request_pool_method_entry[]; extern zend_object_value php_http_request_pool_object_new(zend_class_entry *ce TSRMLS_DC); +extern zend_object_value php_http_request_pool_object_new_ex(zend_class_entry *ce, php_http_request_pool_t *p, php_http_request_pool_object_t **ptr TSRMLS_DC); extern void php_http_request_pool_object_free(void *object TSRMLS_DC); PHP_METHOD(HttpRequestPool, __construct); @@ -66,8 +83,8 @@ PHP_METHOD(HttpRequestPool, attach); PHP_METHOD(HttpRequestPool, detach); PHP_METHOD(HttpRequestPool, send); PHP_METHOD(HttpRequestPool, reset); -PHP_METHOD(HttpRequestPool, socketPerform); -PHP_METHOD(HttpRequestPool, socketSelect); +PHP_METHOD(HttpRequestPool, once); +PHP_METHOD(HttpRequestPool, wait); PHP_METHOD(HttpRequestPool, valid); PHP_METHOD(HttpRequestPool, current); PHP_METHOD(HttpRequestPool, key); @@ -80,6 +97,5 @@ PHP_METHOD(HttpRequestPool, enablePipelining); PHP_METHOD(HttpRequestPool, enableEvents); PHP_MINIT_FUNCTION(http_request_pool); -PHP_RINIT_FUNCTION(http_request_pool); #endif /* PHP_HTTP_REQUESTPOOL_H */ diff --git a/php_http_strlist.c b/php_http_strlist.c index a00f201..53ccac9 100644 --- a/php_http_strlist.c +++ b/php_http_strlist.c @@ -56,9 +56,16 @@ PHP_HTTP_API void php_http_strlist_iterator_free(php_http_strlist_iterator_t **i PHP_HTTP_API const char *php_http_strlist_find(const char list[], unsigned factor, unsigned item) { - unsigned M = 0, m = 0, major = (item / factor) - 1, minor = (item % factor); + unsigned M = 0, m = 0, major, minor; const char *p = &list[0]; + if (factor) { + major = (item / factor) - 1; + minor = item % factor; + } else { + major = 0; + minor = item; + } while (*p && major != M++) { while (*p) { while (*p) { diff --git a/reflection2php.php b/reflection2php.php new file mode 100755 index 0000000..6791aba --- /dev/null +++ b/reflection2php.php @@ -0,0 +1,71 @@ +#!/usr/bin/env php +getClass()) return $c->getName() . " "; + if ($p->isArray()) return "array "; +} + +if (!strlen($ext = $argv[1])) + die(sprintf("Usage: %s \n", $argv[0])); + +$ext = new ReflectionExtension($ext); +foreach ($ext->getClasses() as $class) { + + printf("%s%s %s ", m($class->getModifiers()), $class->isInterface() ? "interface":"class" ,$class->getName()); + if ($p = $class->getParentClass()) { + printf("extends %s ", $p->getName()); + } + if ($i = $class->getInterfaceNames()) { + printf("implements %s ", implode(", ", array_filter($i,function($v){return$v!="Traversable";}))); + } + printf("\n{\n"); + + $_=0; + foreach ($class->getConstants() as $n => $v) { + $_+=printf("\tconst %s = %s;\n", $n, var_export($v, true)); + } + $_ and printf("\n"); + $_=0; + foreach ($class->getProperties() as $p) { + if ($p->getDeclaringClass()->getName() == $class->getName()) { + $_+=printf("\t%s\$%s;\n", m($p->getModifiers()), $p->getName()); + } + } + $_ and printf("\n"); + + foreach ($class->getMethods() as $m) { + if ($m->getDeclaringClass()->getName() == $class->getName()) { + printf("\t%sfunction %s(", m($m->getModifiers()), $m->getName()); + $ps = array(); + foreach ($m->getParameters() as $p) { + $p1 = sprintf("%s%s", t($p), $p->isPassedByReference()?"&":""); + if ($p->isOptional()) { + $p1 .= sprintf("[\$%s", $p->getName()); + } else { + $p1 .= sprintf("\$%s", $p->getName()); + } + if ($p->isDefaultValueAvailable()) { + $p1 .= sprintf(" = %s", var_export($p->getDefaultValue(), true)); + } elseif ($p->allowsNull()) { + $p1 .= sprintf(" = NULL"); + } + if ($p->isOptional()) { + $p1 .= sprintf("]"); + } + $ps[] = $p1; + } + printf("%s) {\n\t}\n", implode(", ", $ps)); + } + } + + printf("}\n\n"); +} + -- 2.30.2