2013-12-08 23:19:00 +00:00
|
|
|
<?php
|
2014-01-29 22:44:54 +00:00
|
|
|
/**
|
|
|
|
|
* HTTP service client
|
|
|
|
|
*
|
|
|
|
|
* This program is free software; you can redistribute it and/or modify
|
|
|
|
|
* it under the terms of the GNU General Public License as published by
|
|
|
|
|
* the Free Software Foundation; either version 2 of the License, or
|
|
|
|
|
* (at your option) any later version.
|
|
|
|
|
*
|
|
|
|
|
* This program is distributed in the hope that it will be useful,
|
|
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
|
* GNU General Public License for more details.
|
|
|
|
|
*
|
|
|
|
|
* You should have received a copy of the GNU General Public License along
|
|
|
|
|
* with this program; if not, write to the Free Software Foundation, Inc.,
|
|
|
|
|
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
|
|
|
|
* http://www.gnu.org/copyleft/gpl.html
|
|
|
|
|
*
|
|
|
|
|
* @file
|
|
|
|
|
*/
|
2013-12-08 23:19:00 +00:00
|
|
|
|
2017-04-28 01:32:44 +00:00
|
|
|
use Psr\Log\LoggerAwareInterface;
|
|
|
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
|
use Psr\Log\NullLogger;
|
2018-07-12 22:07:54 +00:00
|
|
|
use MediaWiki\MediaWikiServices;
|
2017-04-28 01:32:44 +00:00
|
|
|
|
2013-12-08 23:19:00 +00:00
|
|
|
/**
|
2018-07-12 22:07:54 +00:00
|
|
|
* Class to handle multiple HTTP requests
|
|
|
|
|
*
|
|
|
|
|
* If curl is available, requests will be made concurrently.
|
|
|
|
|
* Otherwise, they will be made serially.
|
2013-12-08 23:19:00 +00:00
|
|
|
*
|
2014-01-29 22:44:54 +00:00
|
|
|
* HTTP request maps are arrays that use the following format:
|
2013-12-08 23:19:00 +00:00
|
|
|
* - method : GET/HEAD/PUT/POST/DELETE
|
|
|
|
|
* - url : HTTP/HTTPS URL
|
2014-01-09 21:38:55 +00:00
|
|
|
* - query : <query parameter field/value associative array> (uses RFC 3986)
|
2013-12-08 23:19:00 +00:00
|
|
|
* - headers : <header name/value associative array>
|
|
|
|
|
* - body : source to get the HTTP request body from;
|
|
|
|
|
* this can simply be a string (always), a resource for
|
2014-01-09 21:38:55 +00:00
|
|
|
* PUT requests, and a field/value array for POST request;
|
|
|
|
|
* array bodies are encoded as multipart/form-data and strings
|
|
|
|
|
* use application/x-www-form-urlencoded (headers sent automatically)
|
2013-12-08 23:19:00 +00:00
|
|
|
* - stream : resource to stream the HTTP response body to
|
2014-12-24 00:18:40 +00:00
|
|
|
* - proxy : HTTP proxy to use
|
2014-04-20 08:40:06 +00:00
|
|
|
* - flags : map of boolean flags which supports:
|
|
|
|
|
* - relayResponseHeaders : write out header via header()
|
2014-01-29 22:44:54 +00:00
|
|
|
* Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
|
2013-12-08 23:19:00 +00:00
|
|
|
*
|
|
|
|
|
* @since 1.23
|
|
|
|
|
*/
|
2017-04-28 01:32:44 +00:00
|
|
|
class MultiHttpClient implements LoggerAwareInterface {
|
2013-12-08 23:19:00 +00:00
|
|
|
/** @var resource */
|
|
|
|
|
protected $multiHandle = null; // curl_multi handle
|
2018-02-05 18:21:09 +00:00
|
|
|
/** @var string|null SSL certificates path */
|
2013-12-08 23:19:00 +00:00
|
|
|
protected $caBundlePath;
|
2018-06-15 10:31:02 +00:00
|
|
|
/** @var float */
|
2014-01-17 21:32:46 +00:00
|
|
|
protected $connTimeout = 10;
|
2018-06-15 10:31:02 +00:00
|
|
|
/** @var float */
|
2014-01-17 21:32:46 +00:00
|
|
|
protected $reqTimeout = 300;
|
|
|
|
|
/** @var bool */
|
|
|
|
|
protected $usePipelining = false;
|
2017-08-20 11:20:59 +00:00
|
|
|
/** @var int */
|
2014-01-17 21:32:46 +00:00
|
|
|
protected $maxConnsPerHost = 50;
|
2014-12-24 00:18:40 +00:00
|
|
|
/** @var string|null proxy */
|
|
|
|
|
protected $proxy;
|
2015-10-06 22:26:59 +00:00
|
|
|
/** @var string */
|
|
|
|
|
protected $userAgent = 'wikimedia/multi-http-client v1.0';
|
2017-04-28 01:32:44 +00:00
|
|
|
/** @var LoggerInterface */
|
|
|
|
|
protected $logger;
|
2013-12-08 23:19:00 +00:00
|
|
|
|
2018-06-15 10:31:02 +00:00
|
|
|
// In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
|
|
|
|
|
// timeouts are periodically polled instead of being accurately respected.
|
|
|
|
|
// The select timeout is set to the minimum timeout multiplied by this factor.
|
|
|
|
|
const TIMEOUT_ACCURACY_FACTOR = 0.1;
|
|
|
|
|
|
2013-12-08 23:19:00 +00:00
|
|
|
/**
|
|
|
|
|
* @param array $options
|
2015-04-21 04:22:55 +00:00
|
|
|
* - connTimeout : default connection timeout (seconds)
|
|
|
|
|
* - reqTimeout : default request timeout (seconds)
|
2014-12-24 00:18:40 +00:00
|
|
|
* - proxy : HTTP proxy to use
|
2014-01-17 21:32:46 +00:00
|
|
|
* - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
|
|
|
|
|
* - maxConnsPerHost : maximum number of concurrent connections (per host)
|
2015-10-06 01:07:29 +00:00
|
|
|
* - userAgent : The User-Agent header value to send
|
2018-07-12 22:07:54 +00:00
|
|
|
* - logger : a \Psr\Log\LoggerInterface instance for debug logging
|
|
|
|
|
* - caBundlePath : path to specific Certificate Authority bundle (if any)
|
2014-12-24 13:49:20 +00:00
|
|
|
* @throws Exception
|
2013-12-08 23:19:00 +00:00
|
|
|
*/
|
|
|
|
|
public function __construct( array $options ) {
|
|
|
|
|
if ( isset( $options['caBundlePath'] ) ) {
|
|
|
|
|
$this->caBundlePath = $options['caBundlePath'];
|
|
|
|
|
if ( !file_exists( $this->caBundlePath ) ) {
|
|
|
|
|
throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-02-17 09:09:32 +00:00
|
|
|
static $opts = [
|
2017-04-28 01:32:44 +00:00
|
|
|
'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost',
|
|
|
|
|
'proxy', 'userAgent', 'logger'
|
2016-02-17 09:09:32 +00:00
|
|
|
];
|
2014-01-17 21:32:46 +00:00
|
|
|
foreach ( $opts as $key ) {
|
|
|
|
|
if ( isset( $options[$key] ) ) {
|
|
|
|
|
$this->$key = $options[$key];
|
|
|
|
|
}
|
2013-12-08 23:19:00 +00:00
|
|
|
}
|
2017-04-28 01:32:44 +00:00
|
|
|
if ( $this->logger === null ) {
|
|
|
|
|
$this->logger = new NullLogger;
|
|
|
|
|
}
|
2013-12-08 23:19:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Execute an HTTP(S) request
|
|
|
|
|
*
|
|
|
|
|
* This method returns a response map of:
|
2018-07-12 22:07:54 +00:00
|
|
|
* - code : HTTP response code or 0 if there was a serious error
|
|
|
|
|
* - reason : HTTP response reason (empty if there was a serious error)
|
2015-06-20 20:42:40 +00:00
|
|
|
* - headers : <header name/value associative array>
|
|
|
|
|
* - body : HTTP response body or resource (if "stream" was set)
|
2018-07-12 22:07:54 +00:00
|
|
|
* - error : Any error string
|
2015-06-20 20:42:40 +00:00
|
|
|
* The map also stores integer-indexed copies of these values. This lets callers do:
|
2015-04-29 04:49:40 +00:00
|
|
|
* @code
|
2018-05-19 20:46:54 +00:00
|
|
|
* list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
|
2015-04-29 04:49:40 +00:00
|
|
|
* @endcode
|
2013-12-08 23:19:00 +00:00
|
|
|
* @param array $req HTTP request array
|
2014-01-17 21:32:46 +00:00
|
|
|
* @param array $opts
|
2015-04-21 04:22:55 +00:00
|
|
|
* - connTimeout : connection timeout per request (seconds)
|
|
|
|
|
* - reqTimeout : post-connection timeout per request (seconds)
|
2013-12-08 23:19:00 +00:00
|
|
|
* @return array Response array for request
|
|
|
|
|
*/
|
2016-06-09 19:38:05 +00:00
|
|
|
public function run( array $req, array $opts = [] ) {
|
2016-02-17 19:54:59 +00:00
|
|
|
return $this->runMulti( [ $req ], $opts )[0]['response'];
|
2013-12-08 23:19:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2018-07-12 22:07:54 +00:00
|
|
|
* Execute a set of HTTP(S) requests.
|
|
|
|
|
*
|
|
|
|
|
* If curl is available, requests will be made concurrently.
|
|
|
|
|
* Otherwise, they will be made serially.
|
2013-12-08 23:19:00 +00:00
|
|
|
*
|
|
|
|
|
* The maps are returned by this method with the 'response' field set to a map of:
|
2018-07-12 22:07:54 +00:00
|
|
|
* - code : HTTP response code or 0 if there was a serious error
|
|
|
|
|
* - reason : HTTP response reason (empty if there was a serious error)
|
2014-12-24 13:49:20 +00:00
|
|
|
* - headers : <header name/value associative array>
|
|
|
|
|
* - body : HTTP response body or resource (if "stream" was set)
|
2018-07-12 22:07:54 +00:00
|
|
|
* - error : Any error string
|
2014-12-24 13:49:20 +00:00
|
|
|
* The map also stores integer-indexed copies of these values. This lets callers do:
|
2015-04-29 04:49:40 +00:00
|
|
|
* @code
|
2014-12-24 13:49:20 +00:00
|
|
|
* list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
|
2015-04-29 04:49:40 +00:00
|
|
|
* @endcode
|
2013-12-08 23:19:00 +00:00
|
|
|
* All headers in the 'headers' field are normalized to use lower case names.
|
2014-01-29 22:44:54 +00:00
|
|
|
* This is true for the request headers and the response headers. Integer-indexed
|
|
|
|
|
* method/URL entries will also be changed to use the corresponding string keys.
|
2013-12-08 23:19:00 +00:00
|
|
|
*
|
2014-08-14 22:35:30 +00:00
|
|
|
* @param array $reqs Map of HTTP request arrays
|
2014-01-17 21:32:46 +00:00
|
|
|
* @param array $opts
|
2015-04-21 04:22:55 +00:00
|
|
|
* - connTimeout : connection timeout per request (seconds)
|
|
|
|
|
* - reqTimeout : post-connection timeout per request (seconds)
|
2014-01-17 21:32:46 +00:00
|
|
|
* - usePipelining : whether to use HTTP pipelining if possible
|
|
|
|
|
* - maxConnsPerHost : maximum number of concurrent connections (per host)
|
2013-12-08 23:19:00 +00:00
|
|
|
* @return array $reqs With response array populated for each
|
2014-12-24 13:49:20 +00:00
|
|
|
* @throws Exception
|
2013-12-08 23:19:00 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
public function runMulti( array $reqs, array $opts = [] ) {
|
2018-07-12 22:07:54 +00:00
|
|
|
$this->normalizeRequests( $reqs );
|
|
|
|
|
if ( $this->isCurlEnabled() ) {
|
|
|
|
|
return $this->runMultiCurl( $reqs, $opts );
|
|
|
|
|
} else {
|
|
|
|
|
return $this->runMultiHttp( $reqs, $opts );
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Determines if the curl extension is available
|
|
|
|
|
*
|
|
|
|
|
* @return bool true if curl is available, false otherwise.
|
|
|
|
|
*/
|
|
|
|
|
protected function isCurlEnabled() {
|
|
|
|
|
return extension_loaded( 'curl' );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Execute a set of HTTP(S) requests concurrently
|
|
|
|
|
*
|
|
|
|
|
* @see MultiHttpClient::runMulti()
|
|
|
|
|
*
|
|
|
|
|
* @param array $reqs Map of HTTP request arrays
|
|
|
|
|
* @param array $opts
|
|
|
|
|
* - connTimeout : connection timeout per request (seconds)
|
|
|
|
|
* - reqTimeout : post-connection timeout per request (seconds)
|
|
|
|
|
* - usePipelining : whether to use HTTP pipelining if possible
|
|
|
|
|
* - maxConnsPerHost : maximum number of concurrent connections (per host)
|
|
|
|
|
* @return array $reqs With response array populated for each
|
|
|
|
|
* @throws Exception
|
|
|
|
|
*/
|
|
|
|
|
private function runMultiCurl( array $reqs, array $opts = [] ) {
|
2014-01-17 21:32:46 +00:00
|
|
|
$chm = $this->getCurlMulti();
|
2013-12-08 23:19:00 +00:00
|
|
|
|
2018-06-15 10:31:02 +00:00
|
|
|
$selectTimeout = $this->getSelectTimeout( $opts );
|
|
|
|
|
|
2018-07-12 22:07:54 +00:00
|
|
|
// Add all of the required cURL handles...
|
2016-02-17 09:09:32 +00:00
|
|
|
$handles = [];
|
2013-12-08 23:19:00 +00:00
|
|
|
foreach ( $reqs as $index => &$req ) {
|
2014-01-17 21:32:46 +00:00
|
|
|
$handles[$index] = $this->getCurlHandle( $req, $opts );
|
2013-12-08 23:19:00 +00:00
|
|
|
if ( count( $reqs ) > 1 ) {
|
|
|
|
|
// https://github.com/guzzle/guzzle/issues/349
|
|
|
|
|
curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
|
|
|
|
|
}
|
|
|
|
|
}
|
2014-01-29 22:44:54 +00:00
|
|
|
unset( $req ); // don't assign over this by accident
|
2013-12-08 23:19:00 +00:00
|
|
|
|
2014-01-17 21:32:46 +00:00
|
|
|
$indexes = array_keys( $reqs );
|
2016-10-02 05:25:06 +00:00
|
|
|
if ( isset( $opts['usePipelining'] ) ) {
|
|
|
|
|
curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
|
|
|
|
|
}
|
|
|
|
|
if ( isset( $opts['maxConnsPerHost'] ) ) {
|
|
|
|
|
// Keep these sockets around as they may be needed later in the request
|
|
|
|
|
curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
|
2014-01-17 21:32:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
|
|
|
|
|
$batches = array_chunk( $indexes, $this->maxConnsPerHost );
|
2016-02-17 09:09:32 +00:00
|
|
|
$infos = [];
|
2014-01-17 21:32:46 +00:00
|
|
|
|
|
|
|
|
foreach ( $batches as $batch ) {
|
|
|
|
|
// Attach all cURL handles for this batch
|
|
|
|
|
foreach ( $batch as $index ) {
|
|
|
|
|
curl_multi_add_handle( $chm, $handles[$index] );
|
|
|
|
|
}
|
|
|
|
|
// Execute the cURL handles concurrently...
|
|
|
|
|
$active = null; // handles still being processed
|
2013-12-08 23:19:00 +00:00
|
|
|
do {
|
2014-01-17 21:32:46 +00:00
|
|
|
// Do any available work...
|
|
|
|
|
do {
|
|
|
|
|
$mrc = curl_multi_exec( $chm, $active );
|
2015-05-13 09:38:21 +00:00
|
|
|
$info = curl_multi_info_read( $chm );
|
|
|
|
|
if ( $info !== false ) {
|
|
|
|
|
$infos[(int)$info['handle']] = $info;
|
|
|
|
|
}
|
2014-01-17 21:32:46 +00:00
|
|
|
} while ( $mrc == CURLM_CALL_MULTI_PERFORM );
|
|
|
|
|
// Wait (if possible) for available work...
|
|
|
|
|
if ( $active > 0 && $mrc == CURLM_OK ) {
|
2018-06-15 10:31:02 +00:00
|
|
|
if ( curl_multi_select( $chm, $selectTimeout ) == -1 ) {
|
2016-10-13 05:34:26 +00:00
|
|
|
// PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
|
2014-01-17 21:32:46 +00:00
|
|
|
usleep( 5000 ); // 5ms
|
|
|
|
|
}
|
2013-12-08 23:19:00 +00:00
|
|
|
}
|
2014-01-17 21:32:46 +00:00
|
|
|
} while ( $active > 0 && $mrc == CURLM_OK );
|
|
|
|
|
}
|
2013-12-08 23:19:00 +00:00
|
|
|
|
|
|
|
|
// Remove all of the added cURL handles and check for errors...
|
|
|
|
|
foreach ( $reqs as $index => &$req ) {
|
|
|
|
|
$ch = $handles[$index];
|
2014-01-17 21:32:46 +00:00
|
|
|
curl_multi_remove_handle( $chm, $ch );
|
2015-05-13 09:38:21 +00:00
|
|
|
|
2015-08-05 23:49:12 +00:00
|
|
|
if ( isset( $infos[(int)$ch] ) ) {
|
|
|
|
|
$info = $infos[(int)$ch];
|
|
|
|
|
$errno = $info['result'];
|
|
|
|
|
if ( $errno !== 0 ) {
|
|
|
|
|
$req['response']['error'] = "(curl error: $errno)";
|
|
|
|
|
if ( function_exists( 'curl_strerror' ) ) {
|
|
|
|
|
$req['response']['error'] .= " " . curl_strerror( $errno );
|
|
|
|
|
}
|
2017-04-28 01:32:44 +00:00
|
|
|
$this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
|
|
|
|
|
$req['response']['error'] );
|
2015-05-13 09:38:21 +00:00
|
|
|
}
|
2015-08-05 23:49:12 +00:00
|
|
|
} else {
|
|
|
|
|
$req['response']['error'] = "(curl error: no status set)";
|
2013-12-08 23:19:00 +00:00
|
|
|
}
|
2015-05-13 09:38:21 +00:00
|
|
|
|
2013-12-08 23:19:00 +00:00
|
|
|
// For convenience with the list() operator
|
|
|
|
|
$req['response'][0] = $req['response']['code'];
|
|
|
|
|
$req['response'][1] = $req['response']['reason'];
|
|
|
|
|
$req['response'][2] = $req['response']['headers'];
|
|
|
|
|
$req['response'][3] = $req['response']['body'];
|
|
|
|
|
$req['response'][4] = $req['response']['error'];
|
|
|
|
|
curl_close( $ch );
|
|
|
|
|
// Close any string wrapper file handles
|
|
|
|
|
if ( isset( $req['_closeHandle'] ) ) {
|
|
|
|
|
fclose( $req['_closeHandle'] );
|
|
|
|
|
unset( $req['_closeHandle'] );
|
|
|
|
|
}
|
|
|
|
|
}
|
2014-01-29 22:44:54 +00:00
|
|
|
unset( $req ); // don't assign over this by accident
|
2013-12-08 23:19:00 +00:00
|
|
|
|
2014-01-17 21:32:46 +00:00
|
|
|
// Restore the default settings
|
2016-10-02 05:25:06 +00:00
|
|
|
curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
|
|
|
|
|
curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
|
2014-01-17 21:32:46 +00:00
|
|
|
|
2013-12-08 23:19:00 +00:00
|
|
|
return $reqs;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2017-08-11 00:23:16 +00:00
|
|
|
* @param array &$req HTTP request map
|
2014-01-17 21:32:46 +00:00
|
|
|
* @param array $opts
|
|
|
|
|
* - connTimeout : default connection timeout
|
|
|
|
|
* - reqTimeout : default request timeout
|
2013-12-08 23:19:00 +00:00
|
|
|
* @return resource
|
2014-12-24 13:49:20 +00:00
|
|
|
* @throws Exception
|
2013-12-08 23:19:00 +00:00
|
|
|
*/
|
2016-02-17 09:09:32 +00:00
|
|
|
protected function getCurlHandle( array &$req, array $opts = [] ) {
|
2013-12-08 23:19:00 +00:00
|
|
|
$ch = curl_init();
|
|
|
|
|
|
2018-06-15 10:31:02 +00:00
|
|
|
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS,
|
|
|
|
|
( $opts['connTimeout'] ?? $this->connTimeout ) * 1000 );
|
2017-10-06 22:17:58 +00:00
|
|
|
curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
|
2018-06-15 10:31:02 +00:00
|
|
|
curl_setopt( $ch, CURLOPT_TIMEOUT_MS,
|
|
|
|
|
( $opts['reqTimeout'] ?? $this->reqTimeout ) * 1000 );
|
2013-12-08 23:19:00 +00:00
|
|
|
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
|
|
|
|
|
curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
|
|
|
|
|
curl_setopt( $ch, CURLOPT_HEADER, 0 );
|
|
|
|
|
if ( !is_null( $this->caBundlePath ) ) {
|
|
|
|
|
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
|
|
|
|
|
curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
|
|
|
|
|
}
|
|
|
|
|
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
|
|
|
|
|
|
|
|
|
|
$url = $req['url'];
|
2016-10-02 05:25:06 +00:00
|
|
|
$query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
|
2013-12-08 23:19:00 +00:00
|
|
|
if ( $query != '' ) {
|
|
|
|
|
$url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
|
|
|
|
|
}
|
|
|
|
|
curl_setopt( $ch, CURLOPT_URL, $url );
|
|
|
|
|
|
|
|
|
|
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
|
|
|
|
|
if ( $req['method'] === 'HEAD' ) {
|
|
|
|
|
curl_setopt( $ch, CURLOPT_NOBODY, 1 );
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ( $req['method'] === 'PUT' ) {
|
|
|
|
|
curl_setopt( $ch, CURLOPT_PUT, 1 );
|
|
|
|
|
if ( is_resource( $req['body'] ) ) {
|
|
|
|
|
curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
|
|
|
|
|
if ( isset( $req['headers']['content-length'] ) ) {
|
|
|
|
|
curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
|
|
|
|
|
} elseif ( isset( $req['headers']['transfer-encoding'] ) &&
|
|
|
|
|
$req['headers']['transfer-encoding'] === 'chunks'
|
|
|
|
|
) {
|
|
|
|
|
curl_setopt( $ch, CURLOPT_UPLOAD, true );
|
|
|
|
|
} else {
|
|
|
|
|
throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
|
|
|
|
|
}
|
|
|
|
|
} elseif ( $req['body'] !== '' ) {
|
|
|
|
|
$fp = fopen( "php://temp", "wb+" );
|
|
|
|
|
fwrite( $fp, $req['body'], strlen( $req['body'] ) );
|
|
|
|
|
rewind( $fp );
|
|
|
|
|
curl_setopt( $ch, CURLOPT_INFILE, $fp );
|
|
|
|
|
curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
|
|
|
|
|
$req['_closeHandle'] = $fp; // remember to close this later
|
|
|
|
|
} else {
|
|
|
|
|
curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
|
|
|
|
|
}
|
|
|
|
|
curl_setopt( $ch, CURLOPT_READFUNCTION,
|
|
|
|
|
function ( $ch, $fd, $length ) {
|
|
|
|
|
$data = fread( $fd, $length );
|
|
|
|
|
$len = strlen( $data );
|
|
|
|
|
return $data;
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
} elseif ( $req['method'] === 'POST' ) {
|
|
|
|
|
curl_setopt( $ch, CURLOPT_POST, 1 );
|
SECURITY: Work around CURL insanity breaking POST parameters that start with '@'
CURL has a "feature" where passing array( 'foo' => '@bar' )
in CURLOPT_POSTFIELDS results in the contents of the file named "bar"
being POSTed. This makes it impossible to POST the literal string "@bar",
because array( 'foo' => '%40bar' ) gets double-encoded to foo=%2540bar.
Disable this "feature" by setting CURLOPT_SAFE_UPLOAD to true,
if available. According to the PHP manual, this option became
available in 5.5 and started defaulting to true in 5.6.
However, we support versions as low as 5.3, and this option
doesn't exist at all in 5.6.99-hhvm, which we run in production.
For versions where this option is not available (pre-5.5 versions
and HHVM), serialize POSTFIELDS arrays to strings. This works
around the issue because the '@' "feature" only works
for arrays, not strings, as of PHP 5.2. (We don't support pre-5.2
versions, and I've verified 5.6.99-hhvm behaves this way as well.)
Bug: T118032
Signed-off-by: Chad Horohoe <chadh@wikimedia.org>
Change-Id: I3f996e2eb87c7bd3b94ca9d3cc14a3e12f34f241
2015-11-06 20:55:16 +00:00
|
|
|
// Don't interpret POST parameters starting with '@' as file uploads, because this
|
|
|
|
|
// makes it impossible to POST plain values starting with '@' (and causes security
|
|
|
|
|
// issues potentially exposing the contents of local files).
|
2018-01-18 23:34:32 +00:00
|
|
|
curl_setopt( $ch, CURLOPT_SAFE_UPLOAD, true );
|
2013-12-08 23:19:00 +00:00
|
|
|
curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
|
|
|
|
|
} else {
|
|
|
|
|
if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
|
|
|
|
|
throw new Exception( "HTTP body specified for a non PUT/POST request." );
|
|
|
|
|
}
|
|
|
|
|
$req['headers']['content-length'] = 0;
|
|
|
|
|
}
|
|
|
|
|
|
2015-10-06 01:07:29 +00:00
|
|
|
if ( !isset( $req['headers']['user-agent'] ) ) {
|
2015-10-06 22:26:59 +00:00
|
|
|
$req['headers']['user-agent'] = $this->userAgent;
|
2015-10-06 01:07:29 +00:00
|
|
|
}
|
|
|
|
|
|
2016-02-17 09:09:32 +00:00
|
|
|
$headers = [];
|
2013-12-08 23:19:00 +00:00
|
|
|
foreach ( $req['headers'] as $name => $value ) {
|
|
|
|
|
if ( strpos( $name, ': ' ) ) {
|
|
|
|
|
throw new Exception( "Headers cannot have ':' in the name." );
|
|
|
|
|
}
|
|
|
|
|
$headers[] = $name . ': ' . trim( $value );
|
|
|
|
|
}
|
|
|
|
|
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
|
|
|
|
|
|
|
|
|
|
curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
|
|
|
|
|
function ( $ch, $header ) use ( &$req ) {
|
2014-04-20 08:40:06 +00:00
|
|
|
if ( !empty( $req['flags']['relayResponseHeaders'] ) ) {
|
|
|
|
|
header( $header );
|
|
|
|
|
}
|
2013-12-08 23:19:00 +00:00
|
|
|
$length = strlen( $header );
|
2016-02-17 09:09:32 +00:00
|
|
|
$matches = [];
|
2013-12-08 23:19:00 +00:00
|
|
|
if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
|
|
|
|
|
$req['response']['code'] = (int)$matches[2];
|
|
|
|
|
$req['response']['reason'] = trim( $matches[3] );
|
|
|
|
|
return $length;
|
|
|
|
|
}
|
|
|
|
|
if ( strpos( $header, ":" ) === false ) {
|
|
|
|
|
return $length;
|
|
|
|
|
}
|
|
|
|
|
list( $name, $value ) = explode( ":", $header, 2 );
|
2018-07-12 22:07:54 +00:00
|
|
|
$name = strtolower( $name );
|
|
|
|
|
$value = trim( $value );
|
|
|
|
|
if ( isset( $req['response']['headers'][$name] ) ) {
|
|
|
|
|
$req['response']['headers'][$name] .= ', ' . $value;
|
|
|
|
|
} else {
|
|
|
|
|
$req['response']['headers'][$name] = $value;
|
|
|
|
|
}
|
2013-12-08 23:19:00 +00:00
|
|
|
return $length;
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if ( isset( $req['stream'] ) ) {
|
|
|
|
|
// Don't just use CURLOPT_FILE as that might give:
|
|
|
|
|
// curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
|
|
|
|
|
// The callback here handles both normal files and php://temp handles.
|
|
|
|
|
curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
|
|
|
|
|
function ( $ch, $data ) use ( &$req ) {
|
|
|
|
|
return fwrite( $req['stream'], $data );
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
} else {
|
|
|
|
|
curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
|
|
|
|
|
function ( $ch, $data ) use ( &$req ) {
|
|
|
|
|
$req['response']['body'] .= $data;
|
|
|
|
|
return strlen( $data );
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $ch;
|
|
|
|
|
}
|
|
|
|
|
|
2018-07-12 22:07:54 +00:00
|
|
|
/**
|
|
|
|
|
* @return resource
|
|
|
|
|
* @throws Exception
|
|
|
|
|
*/
|
|
|
|
|
protected function getCurlMulti() {
|
|
|
|
|
if ( !$this->multiHandle ) {
|
|
|
|
|
if ( !function_exists( 'curl_multi_init' ) ) {
|
|
|
|
|
throw new Exception( "PHP cURL function curl_multi_init missing. " .
|
2017-05-01 16:35:36 +00:00
|
|
|
"Check https://www.mediawiki.org/wiki/Manual:CURL" );
|
2018-07-12 22:07:54 +00:00
|
|
|
}
|
|
|
|
|
$cmh = curl_multi_init();
|
|
|
|
|
curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
|
|
|
|
|
curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
|
|
|
|
|
$this->multiHandle = $cmh;
|
|
|
|
|
}
|
|
|
|
|
return $this->multiHandle;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Execute a set of HTTP(S) requests sequentially.
|
|
|
|
|
*
|
|
|
|
|
* @see MultiHttpClient::runMulti()
|
|
|
|
|
* @todo Remove dependency on MediaWikiServices: use a separate HTTP client
|
|
|
|
|
* library or copy code from PhpHttpRequest
|
|
|
|
|
* @param array $reqs Map of HTTP request arrays
|
|
|
|
|
* @param array $opts
|
|
|
|
|
* - connTimeout : connection timeout per request (seconds)
|
|
|
|
|
* - reqTimeout : post-connection timeout per request (seconds)
|
|
|
|
|
* @return array $reqs With response array populated for each
|
|
|
|
|
* @throws Exception
|
|
|
|
|
*/
|
|
|
|
|
private function runMultiHttp( array $reqs, array $opts = [] ) {
|
|
|
|
|
$httpOptions = [
|
|
|
|
|
'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
|
|
|
|
|
'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
|
|
|
|
|
'logger' => $this->logger,
|
|
|
|
|
'caInfo' => $this->caBundlePath,
|
|
|
|
|
];
|
|
|
|
|
foreach ( $reqs as &$req ) {
|
|
|
|
|
$reqOptions = $httpOptions + [
|
|
|
|
|
'method' => $req['method'],
|
|
|
|
|
'proxy' => $req['proxy'] ?? $this->proxy,
|
|
|
|
|
'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
|
|
|
|
|
'postData' => $req['body'],
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
$url = $req['url'];
|
|
|
|
|
$query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
|
|
|
|
|
if ( $query != '' ) {
|
|
|
|
|
$url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
|
|
|
|
|
$url, $reqOptions );
|
|
|
|
|
$sv = $httpRequest->execute()->getStatusValue();
|
|
|
|
|
|
|
|
|
|
$respHeaders = array_map(
|
|
|
|
|
function ( $v ) {
|
|
|
|
|
return implode( ', ', $v );
|
|
|
|
|
},
|
|
|
|
|
$httpRequest->getResponseHeaders() );
|
|
|
|
|
|
|
|
|
|
$req['response'] = [
|
|
|
|
|
'code' => $httpRequest->getStatus(),
|
|
|
|
|
'reason' => '',
|
|
|
|
|
'headers' => $respHeaders,
|
|
|
|
|
'body' => $httpRequest->getContent(),
|
|
|
|
|
'error' => '',
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
if ( !$sv->isOk() ) {
|
|
|
|
|
$svErrors = $sv->getErrors();
|
|
|
|
|
if ( isset( $svErrors[0] ) ) {
|
|
|
|
|
$req['response']['error'] = $svErrors[0]['message'];
|
|
|
|
|
|
|
|
|
|
// param values vary per failure type (ex. unknown host vs unknown page)
|
|
|
|
|
if ( isset( $svErrors[0]['params'][0] ) ) {
|
|
|
|
|
if ( is_numeric( $svErrors[0]['params'][0] ) ) {
|
|
|
|
|
if ( isset( $svErrors[0]['params'][1] ) ) {
|
|
|
|
|
$req['response']['reason'] = $svErrors[0]['params'][1];
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
$req['response']['reason'] = $svErrors[0]['params'][0];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$req['response'][0] = $req['response']['code'];
|
|
|
|
|
$req['response'][1] = $req['response']['reason'];
|
|
|
|
|
$req['response'][2] = $req['response']['headers'];
|
|
|
|
|
$req['response'][3] = $req['response']['body'];
|
|
|
|
|
$req['response'][4] = $req['response']['error'];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $reqs;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Normalize request information
|
|
|
|
|
*
|
|
|
|
|
* @param array $reqs the requests to normalize
|
|
|
|
|
*/
|
|
|
|
|
private function normalizeRequests( array &$reqs ) {
|
|
|
|
|
foreach ( $reqs as &$req ) {
|
|
|
|
|
$req['response'] = [
|
|
|
|
|
'code' => 0,
|
|
|
|
|
'reason' => '',
|
|
|
|
|
'headers' => [],
|
|
|
|
|
'body' => '',
|
|
|
|
|
'error' => ''
|
|
|
|
|
];
|
|
|
|
|
if ( isset( $req[0] ) ) {
|
|
|
|
|
$req['method'] = $req[0]; // short-form
|
|
|
|
|
unset( $req[0] );
|
|
|
|
|
}
|
|
|
|
|
if ( isset( $req[1] ) ) {
|
|
|
|
|
$req['url'] = $req[1]; // short-form
|
|
|
|
|
unset( $req[1] );
|
|
|
|
|
}
|
|
|
|
|
if ( !isset( $req['method'] ) ) {
|
|
|
|
|
throw new Exception( "Request has no 'method' field set." );
|
|
|
|
|
} elseif ( !isset( $req['url'] ) ) {
|
|
|
|
|
throw new Exception( "Request has no 'url' field set." );
|
|
|
|
|
}
|
|
|
|
|
$this->logger->debug( "{$req['method']}: {$req['url']}" );
|
|
|
|
|
$req['query'] = $req['query'] ?? [];
|
|
|
|
|
$headers = []; // normalized headers
|
|
|
|
|
if ( isset( $req['headers'] ) ) {
|
|
|
|
|
foreach ( $req['headers'] as $name => $value ) {
|
|
|
|
|
$headers[strtolower( $name )] = $value;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
$req['headers'] = $headers;
|
|
|
|
|
if ( !isset( $req['body'] ) ) {
|
|
|
|
|
$req['body'] = '';
|
|
|
|
|
$req['headers']['content-length'] = 0;
|
|
|
|
|
}
|
|
|
|
|
$req['flags'] = $req['flags'] ?? [];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-06-15 10:31:02 +00:00
|
|
|
/**
|
|
|
|
|
* Get a suitable select timeout for the given options.
|
|
|
|
|
*
|
|
|
|
|
* @param array $opts
|
|
|
|
|
* @return float
|
|
|
|
|
*/
|
|
|
|
|
private function getSelectTimeout( $opts ) {
|
|
|
|
|
$connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
|
|
|
|
|
$reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
|
|
|
|
|
$timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
|
|
|
|
|
if ( count( $timeouts ) === 0 ) {
|
|
|
|
|
return 1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
|
|
|
|
|
// Minimum 10us for sanity
|
|
|
|
|
if ( $selectTimeout < 10e-6 ) {
|
|
|
|
|
$selectTimeout = 10e-6;
|
|
|
|
|
}
|
|
|
|
|
return $selectTimeout;
|
|
|
|
|
}
|
|
|
|
|
|
2017-04-28 01:32:44 +00:00
|
|
|
/**
|
|
|
|
|
* Register a logger
|
|
|
|
|
*
|
2017-08-11 16:09:41 +00:00
|
|
|
* @param LoggerInterface $logger
|
2017-04-28 01:32:44 +00:00
|
|
|
*/
|
|
|
|
|
public function setLogger( LoggerInterface $logger ) {
|
|
|
|
|
$this->logger = $logger;
|
|
|
|
|
}
|
|
|
|
|
|
2013-12-08 23:19:00 +00:00
|
|
|
function __destruct() {
|
|
|
|
|
if ( $this->multiHandle ) {
|
|
|
|
|
curl_multi_close( $this->multiHandle );
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|