5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Psr\Log\LoggerAwareInterface
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
26 use MediaWiki\MediaWikiServices
;
29 * Class to handle multiple HTTP requests
31 * If curl is available, requests will be made concurrently.
32 * Otherwise, they will be made serially.
34 * HTTP request maps are arrays that use the following format:
35 * - method : GET/HEAD/PUT/POST/DELETE
36 * - url : HTTP/HTTPS URL
37 * - query : <query parameter field/value associative array> (uses RFC 3986)
38 * - headers : <header name/value associative array>
39 * - body : source to get the HTTP request body from;
40 * this can simply be a string (always), a resource for
41 * PUT requests, and a field/value array for POST request;
42 * array bodies are encoded as multipart/form-data and strings
43 * use application/x-www-form-urlencoded (headers sent automatically)
44 * - stream : resource to stream the HTTP response body to
45 * - proxy : HTTP proxy to use
46 * - flags : map of boolean flags which supports:
47 * - relayResponseHeaders : write out header via header()
48 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
52 class MultiHttpClient
implements LoggerAwareInterface
{
54 protected $multiHandle = null; // curl_multi handle
55 /** @var string|null SSL certificates path */
56 protected $caBundlePath;
58 protected $connTimeout = 10;
60 protected $reqTimeout = 900;
62 protected $usePipelining = false;
64 protected $maxConnsPerHost = 50;
65 /** @var string|null proxy */
68 protected $userAgent = 'wikimedia/multi-http-client v1.0';
69 /** @var LoggerInterface */
72 // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
73 // timeouts are periodically polled instead of being accurately respected.
74 // The select timeout is set to the minimum timeout multiplied by this factor.
75 const TIMEOUT_ACCURACY_FACTOR
= 0.1;
78 * @param array $options
79 * - connTimeout : default connection timeout (seconds)
80 * - reqTimeout : default request timeout (seconds)
81 * - proxy : HTTP proxy to use
82 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
83 * - maxConnsPerHost : maximum number of concurrent connections (per host)
84 * - userAgent : The User-Agent header value to send
85 * - logger : a \Psr\Log\LoggerInterface instance for debug logging
86 * - caBundlePath : path to specific Certificate Authority bundle (if any)
89 public function __construct( array $options ) {
90 if ( isset( $options['caBundlePath'] ) ) {
91 $this->caBundlePath
= $options['caBundlePath'];
92 if ( !file_exists( $this->caBundlePath
) ) {
93 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath
);
97 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost',
98 'proxy', 'userAgent', 'logger'
100 foreach ( $opts as $key ) {
101 if ( isset( $options[$key] ) ) {
102 $this->$key = $options[$key];
105 if ( $this->logger
=== null ) {
106 $this->logger
= new NullLogger
;
111 * Execute an HTTP(S) request
113 * This method returns a response map of:
114 * - code : HTTP response code or 0 if there was a serious error
115 * - reason : HTTP response reason (empty if there was a serious error)
116 * - headers : <header name/value associative array>
117 * - body : HTTP response body or resource (if "stream" was set)
118 * - error : Any error string
119 * The map also stores integer-indexed copies of these values. This lets callers do:
121 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
123 * @param array $req HTTP request array
125 * - connTimeout : connection timeout per request (seconds)
126 * - reqTimeout : post-connection timeout per request (seconds)
127 * @return array Response array for request
129 public function run( array $req, array $opts = [] ) {
130 return $this->runMulti( [ $req ], $opts )[0]['response'];
134 * Execute a set of HTTP(S) requests.
136 * If curl is available, requests will be made concurrently.
137 * Otherwise, they will be made serially.
139 * The maps are returned by this method with the 'response' field set to a map of:
140 * - code : HTTP response code or 0 if there was a serious error
141 * - reason : HTTP response reason (empty if there was a serious error)
142 * - headers : <header name/value associative array>
143 * - body : HTTP response body or resource (if "stream" was set)
144 * - error : Any error string
145 * The map also stores integer-indexed copies of these values. This lets callers do:
147 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
149 * All headers in the 'headers' field are normalized to use lower case names.
150 * This is true for the request headers and the response headers. Integer-indexed
151 * method/URL entries will also be changed to use the corresponding string keys.
153 * @param array[] $reqs Map of HTTP request arrays
155 * - connTimeout : connection timeout per request (seconds)
156 * - reqTimeout : post-connection timeout per request (seconds)
157 * - usePipelining : whether to use HTTP pipelining if possible
158 * - maxConnsPerHost : maximum number of concurrent connections (per host)
159 * @return array $reqs With response array populated for each
162 public function runMulti( array $reqs, array $opts = [] ) {
163 $this->normalizeRequests( $reqs );
164 if ( $this->isCurlEnabled() ) {
165 return $this->runMultiCurl( $reqs, $opts );
167 return $this->runMultiHttp( $reqs, $opts );
172 * Determines if the curl extension is available
174 * @return bool true if curl is available, false otherwise.
176 protected function isCurlEnabled() {
177 return extension_loaded( 'curl' );
181 * Execute a set of HTTP(S) requests concurrently
183 * @see MultiHttpClient::runMulti()
185 * @param array[] $reqs Map of HTTP request arrays
187 * - connTimeout : connection timeout per request (seconds)
188 * - reqTimeout : post-connection timeout per request (seconds)
189 * - usePipelining : whether to use HTTP pipelining if possible
190 * - maxConnsPerHost : maximum number of concurrent connections (per host)
191 * @return array $reqs With response array populated for each
194 private function runMultiCurl( array $reqs, array $opts = [] ) {
195 $chm = $this->getCurlMulti();
197 $selectTimeout = $this->getSelectTimeout( $opts );
199 // Add all of the required cURL handles...
201 foreach ( $reqs as $index => &$req ) {
202 $handles[$index] = $this->getCurlHandle( $req, $opts );
203 if ( count( $reqs ) > 1 ) {
204 // https://github.com/guzzle/guzzle/issues/349
205 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE
, true );
208 unset( $req ); // don't assign over this by accident
210 $indexes = array_keys( $reqs );
211 if ( isset( $opts['usePipelining'] ) ) {
212 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$opts['usePipelining'] );
214 if ( isset( $opts['maxConnsPerHost'] ) ) {
215 // Keep these sockets around as they may be needed later in the request
216 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$opts['maxConnsPerHost'] );
219 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
220 $batches = array_chunk( $indexes, $this->maxConnsPerHost
);
223 foreach ( $batches as $batch ) {
224 // Attach all cURL handles for this batch
225 foreach ( $batch as $index ) {
226 curl_multi_add_handle( $chm, $handles[$index] );
228 // Execute the cURL handles concurrently...
229 $active = null; // handles still being processed
231 // Do any available work...
233 $mrc = curl_multi_exec( $chm, $active );
234 $info = curl_multi_info_read( $chm );
235 if ( $info !== false ) {
236 $infos[(int)$info['handle']] = $info;
238 } while ( $mrc == CURLM_CALL_MULTI_PERFORM
);
239 // Wait (if possible) for available work...
240 if ( $active > 0 && $mrc == CURLM_OK
&& curl_multi_select( $chm, $selectTimeout ) == -1 ) {
241 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
242 usleep( 5000 ); // 5ms
244 } while ( $active > 0 && $mrc == CURLM_OK
);
247 // Remove all of the added cURL handles and check for errors...
248 foreach ( $reqs as $index => &$req ) {
249 $ch = $handles[$index];
250 curl_multi_remove_handle( $chm, $ch );
252 if ( isset( $infos[(int)$ch] ) ) {
253 $info = $infos[(int)$ch];
254 $errno = $info['result'];
255 if ( $errno !== 0 ) {
256 $req['response']['error'] = "(curl error: $errno)";
257 if ( function_exists( 'curl_strerror' ) ) {
258 $req['response']['error'] .= " " . curl_strerror( $errno );
260 $this->logger
->warning( "Error fetching URL \"{$req['url']}\": " .
261 $req['response']['error'] );
264 $req['response']['error'] = "(curl error: no status set)";
267 // For convenience with the list() operator
268 $req['response'][0] = $req['response']['code'];
269 $req['response'][1] = $req['response']['reason'];
270 $req['response'][2] = $req['response']['headers'];
271 $req['response'][3] = $req['response']['body'];
272 $req['response'][4] = $req['response']['error'];
274 // Close any string wrapper file handles
275 if ( isset( $req['_closeHandle'] ) ) {
276 fclose( $req['_closeHandle'] );
277 unset( $req['_closeHandle'] );
280 unset( $req ); // don't assign over this by accident
282 // Restore the default settings
283 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
284 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
290 * @param array &$req HTTP request map
292 * - connTimeout : default connection timeout
293 * - reqTimeout : default request timeout
296 * @suppress PhanTypeMismatchArgumentInternal
298 protected function getCurlHandle( array &$req, array $opts = [] ) {
301 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS
,
302 ( $opts['connTimeout'] ??
$this->connTimeout
) * 1000 );
303 curl_setopt( $ch, CURLOPT_PROXY
, $req['proxy'] ??
$this->proxy
);
304 curl_setopt( $ch, CURLOPT_TIMEOUT_MS
,
305 ( $opts['reqTimeout'] ??
$this->reqTimeout
) * 1000 );
306 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION
, 1 );
307 curl_setopt( $ch, CURLOPT_MAXREDIRS
, 4 );
308 curl_setopt( $ch, CURLOPT_HEADER
, 0 );
309 if ( !is_null( $this->caBundlePath
) ) {
310 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER
, true );
311 curl_setopt( $ch, CURLOPT_CAINFO
, $this->caBundlePath
);
313 curl_setopt( $ch, CURLOPT_RETURNTRANSFER
, 1 );
316 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986
);
317 if ( $query != '' ) {
318 $url .= strpos( $req['url'], '?' ) === false ?
"?$query" : "&$query";
320 curl_setopt( $ch, CURLOPT_URL
, $url );
322 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST
, $req['method'] );
323 if ( $req['method'] === 'HEAD' ) {
324 curl_setopt( $ch, CURLOPT_NOBODY
, 1 );
327 if ( $req['method'] === 'PUT' ) {
328 curl_setopt( $ch, CURLOPT_PUT
, 1 );
329 if ( is_resource( $req['body'] ) ) {
330 curl_setopt( $ch, CURLOPT_INFILE
, $req['body'] );
331 if ( isset( $req['headers']['content-length'] ) ) {
332 curl_setopt( $ch, CURLOPT_INFILESIZE
, $req['headers']['content-length'] );
333 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
334 $req['headers']['transfer-encoding'] === 'chunks'
336 curl_setopt( $ch, CURLOPT_UPLOAD
, true );
338 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
340 } elseif ( $req['body'] !== '' ) {
341 $fp = fopen( "php://temp", "wb+" );
342 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
344 curl_setopt( $ch, CURLOPT_INFILE
, $fp );
345 curl_setopt( $ch, CURLOPT_INFILESIZE
, strlen( $req['body'] ) );
346 $req['_closeHandle'] = $fp; // remember to close this later
348 curl_setopt( $ch, CURLOPT_INFILESIZE
, 0 );
350 curl_setopt( $ch, CURLOPT_READFUNCTION
,
351 function ( $ch, $fd, $length ) {
352 $data = fread( $fd, $length );
353 $len = strlen( $data );
357 } elseif ( $req['method'] === 'POST' ) {
358 curl_setopt( $ch, CURLOPT_POST
, 1 );
359 // Don't interpret POST parameters starting with '@' as file uploads, because this
360 // makes it impossible to POST plain values starting with '@' (and causes security
361 // issues potentially exposing the contents of local files).
362 curl_setopt( $ch, CURLOPT_SAFE_UPLOAD
, true );
363 curl_setopt( $ch, CURLOPT_POSTFIELDS
, $req['body'] );
365 if ( is_resource( $req['body'] ) ||
$req['body'] !== '' ) {
366 throw new Exception( "HTTP body specified for a non PUT/POST request." );
368 $req['headers']['content-length'] = 0;
371 if ( !isset( $req['headers']['user-agent'] ) ) {
372 $req['headers']['user-agent'] = $this->userAgent
;
376 foreach ( $req['headers'] as $name => $value ) {
377 if ( strpos( $name, ': ' ) ) {
378 throw new Exception( "Headers cannot have ':' in the name." );
380 $headers[] = $name . ': ' . trim( $value );
382 curl_setopt( $ch, CURLOPT_HTTPHEADER
, $headers );
384 curl_setopt( $ch, CURLOPT_HEADERFUNCTION
,
385 function ( $ch, $header ) use ( &$req ) {
386 if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
389 $length = strlen( $header );
391 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
392 $req['response']['code'] = (int)$matches[2];
393 $req['response']['reason'] = trim( $matches[3] );
396 if ( strpos( $header, ":" ) === false ) {
399 list( $name, $value ) = explode( ":", $header, 2 );
400 $name = strtolower( $name );
401 $value = trim( $value );
402 if ( isset( $req['response']['headers'][$name] ) ) {
403 $req['response']['headers'][$name] .= ', ' . $value;
405 $req['response']['headers'][$name] = $value;
411 if ( isset( $req['stream'] ) ) {
412 // Don't just use CURLOPT_FILE as that might give:
413 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
414 // The callback here handles both normal files and php://temp handles.
415 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
416 function ( $ch, $data ) use ( &$req ) {
417 return fwrite( $req['stream'], $data );
421 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
422 function ( $ch, $data ) use ( &$req ) {
423 $req['response']['body'] .= $data;
424 return strlen( $data );
436 protected function getCurlMulti() {
437 if ( !$this->multiHandle
) {
438 if ( !function_exists( 'curl_multi_init' ) ) {
439 throw new Exception( "PHP cURL function curl_multi_init missing. " .
440 "Check https://www.mediawiki.org/wiki/Manual:CURL" );
442 $cmh = curl_multi_init();
443 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
444 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
445 $this->multiHandle
= $cmh;
447 return $this->multiHandle
;
451 * Execute a set of HTTP(S) requests sequentially.
453 * @see MultiHttpClient::runMulti()
454 * @todo Remove dependency on MediaWikiServices: use a separate HTTP client
455 * library or copy code from PhpHttpRequest
456 * @param array $reqs Map of HTTP request arrays
458 * - connTimeout : connection timeout per request (seconds)
459 * - reqTimeout : post-connection timeout per request (seconds)
460 * @return array $reqs With response array populated for each
463 private function runMultiHttp( array $reqs, array $opts = [] ) {
465 'timeout' => $opts['reqTimeout'] ??
$this->reqTimeout
,
466 'connectTimeout' => $opts['connTimeout'] ??
$this->connTimeout
,
467 'logger' => $this->logger
,
468 'caInfo' => $this->caBundlePath
,
470 foreach ( $reqs as &$req ) {
471 $reqOptions = $httpOptions +
[
472 'method' => $req['method'],
473 'proxy' => $req['proxy'] ??
$this->proxy
,
474 'userAgent' => $req['headers']['user-agent'] ??
$this->userAgent
,
475 'postData' => $req['body'],
479 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986
);
480 if ( $query != '' ) {
481 $url .= strpos( $req['url'], '?' ) === false ?
"?$query" : "&$query";
484 $httpRequest = MediaWikiServices
::getInstance()->getHttpRequestFactory()->create(
486 $sv = $httpRequest->execute()->getStatusValue();
488 $respHeaders = array_map(
490 return implode( ', ', $v );
492 $httpRequest->getResponseHeaders() );
495 'code' => $httpRequest->getStatus(),
497 'headers' => $respHeaders,
498 'body' => $httpRequest->getContent(),
502 if ( !$sv->isOk() ) {
503 $svErrors = $sv->getErrors();
504 if ( isset( $svErrors[0] ) ) {
505 $req['response']['error'] = $svErrors[0]['message'];
507 // param values vary per failure type (ex. unknown host vs unknown page)
508 if ( isset( $svErrors[0]['params'][0] ) ) {
509 if ( is_numeric( $svErrors[0]['params'][0] ) ) {
510 if ( isset( $svErrors[0]['params'][1] ) ) {
511 $req['response']['reason'] = $svErrors[0]['params'][1];
514 $req['response']['reason'] = $svErrors[0]['params'][0];
520 $req['response'][0] = $req['response']['code'];
521 $req['response'][1] = $req['response']['reason'];
522 $req['response'][2] = $req['response']['headers'];
523 $req['response'][3] = $req['response']['body'];
524 $req['response'][4] = $req['response']['error'];
531 * Normalize request information
533 * @param array[] $reqs the requests to normalize
535 private function normalizeRequests( array &$reqs ) {
536 foreach ( $reqs as &$req ) {
544 if ( isset( $req[0] ) ) {
545 $req['method'] = $req[0]; // short-form
548 if ( isset( $req[1] ) ) {
549 $req['url'] = $req[1]; // short-form
552 if ( !isset( $req['method'] ) ) {
553 throw new Exception( "Request has no 'method' field set." );
554 } elseif ( !isset( $req['url'] ) ) {
555 throw new Exception( "Request has no 'url' field set." );
557 $this->logger
->debug( "{$req['method']}: {$req['url']}" );
558 $req['query'] = $req['query'] ??
[];
559 $headers = []; // normalized headers
560 if ( isset( $req['headers'] ) ) {
561 foreach ( $req['headers'] as $name => $value ) {
562 $headers[strtolower( $name )] = $value;
565 $req['headers'] = $headers;
566 if ( !isset( $req['body'] ) ) {
568 $req['headers']['content-length'] = 0;
570 $req['flags'] = $req['flags'] ??
[];
575 * Get a suitable select timeout for the given options.
580 private function getSelectTimeout( $opts ) {
581 $connTimeout = $opts['connTimeout'] ??
$this->connTimeout
;
582 $reqTimeout = $opts['reqTimeout'] ??
$this->reqTimeout
;
583 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
584 if ( count( $timeouts ) === 0 ) {
588 $selectTimeout = min( $timeouts ) * self
::TIMEOUT_ACCURACY_FACTOR
;
589 // Minimum 10us for sanity
590 if ( $selectTimeout < 10e-6 ) {
591 $selectTimeout = 10e-6;
593 return $selectTimeout;
599 * @param LoggerInterface $logger
601 public function setLogger( LoggerInterface
$logger ) {
602 $this->logger
= $logger;
605 function __destruct() {
606 if ( $this->multiHandle
) {
607 curl_multi_close( $this->multiHandle
);