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
;
28 * Class to handle concurrent HTTP requests
30 * HTTP request maps are arrays that use the following format:
31 * - method : GET/HEAD/PUT/POST/DELETE
32 * - url : HTTP/HTTPS URL
33 * - query : <query parameter field/value associative array> (uses RFC 3986)
34 * - headers : <header name/value associative array>
35 * - body : source to get the HTTP request body from;
36 * this can simply be a string (always), a resource for
37 * PUT requests, and a field/value array for POST request;
38 * array bodies are encoded as multipart/form-data and strings
39 * use application/x-www-form-urlencoded (headers sent automatically)
40 * - stream : resource to stream the HTTP response body to
41 * - proxy : HTTP proxy to use
42 * - flags : map of boolean flags which supports:
43 * - relayResponseHeaders : write out header via header()
44 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
48 class MultiHttpClient
implements LoggerAwareInterface
{
50 protected $multiHandle = null; // curl_multi handle
51 /** @var string|null SSL certificates path */
52 protected $caBundlePath;
54 protected $connTimeout = 10;
56 protected $reqTimeout = 300;
58 protected $usePipelining = false;
60 protected $maxConnsPerHost = 50;
61 /** @var string|null proxy */
64 protected $userAgent = 'wikimedia/multi-http-client v1.0';
65 /** @var LoggerInterface */
68 // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
69 // timeouts are periodically polled instead of being accurately respected.
70 // The select timeout is set to the minimum timeout multiplied by this factor.
71 const TIMEOUT_ACCURACY_FACTOR
= 0.1;
74 * @param array $options
75 * - connTimeout : default connection timeout (seconds)
76 * - reqTimeout : default request timeout (seconds)
77 * - proxy : HTTP proxy to use
78 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
79 * - maxConnsPerHost : maximum number of concurrent connections (per host)
80 * - userAgent : The User-Agent header value to send
83 public function __construct( array $options ) {
84 if ( isset( $options['caBundlePath'] ) ) {
85 $this->caBundlePath
= $options['caBundlePath'];
86 if ( !file_exists( $this->caBundlePath
) ) {
87 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath
);
91 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost',
92 'proxy', 'userAgent', 'logger'
94 foreach ( $opts as $key ) {
95 if ( isset( $options[$key] ) ) {
96 $this->$key = $options[$key];
99 if ( $this->logger
=== null ) {
100 $this->logger
= new NullLogger
;
105 * Execute an HTTP(S) request
107 * This method returns a response map of:
108 * - code : HTTP response code or 0 if there was a serious cURL error
109 * - reason : HTTP response reason (empty if there was a serious cURL error)
110 * - headers : <header name/value associative array>
111 * - body : HTTP response body or resource (if "stream" was set)
112 * - error : Any cURL error string
113 * The map also stores integer-indexed copies of these values. This lets callers do:
115 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
117 * @param array $req HTTP request array
119 * - connTimeout : connection timeout per request (seconds)
120 * - reqTimeout : post-connection timeout per request (seconds)
121 * @return array Response array for request
123 public function run( array $req, array $opts = [] ) {
124 return $this->runMulti( [ $req ], $opts )[0]['response'];
128 * Execute a set of HTTP(S) requests concurrently
130 * The maps are returned by this method with the 'response' field set to a map of:
131 * - code : HTTP response code or 0 if there was a serious cURL error
132 * - reason : HTTP response reason (empty if there was a serious cURL error)
133 * - headers : <header name/value associative array>
134 * - body : HTTP response body or resource (if "stream" was set)
135 * - error : Any cURL error string
136 * The map also stores integer-indexed copies of these values. This lets callers do:
138 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
140 * All headers in the 'headers' field are normalized to use lower case names.
141 * This is true for the request headers and the response headers. Integer-indexed
142 * method/URL entries will also be changed to use the corresponding string keys.
144 * @param array $reqs Map of HTTP request arrays
146 * - connTimeout : connection timeout per request (seconds)
147 * - reqTimeout : post-connection timeout per request (seconds)
148 * - usePipelining : whether to use HTTP pipelining if possible
149 * - maxConnsPerHost : maximum number of concurrent connections (per host)
150 * @return array $reqs With response array populated for each
153 public function runMulti( array $reqs, array $opts = [] ) {
154 $chm = $this->getCurlMulti();
156 $selectTimeout = $this->getSelectTimeout( $opts );
158 // Normalize $reqs and add all of the required cURL handles...
160 foreach ( $reqs as $index => &$req ) {
168 if ( isset( $req[0] ) ) {
169 $req['method'] = $req[0]; // short-form
172 if ( isset( $req[1] ) ) {
173 $req['url'] = $req[1]; // short-form
176 if ( !isset( $req['method'] ) ) {
177 throw new Exception( "Request has no 'method' field set." );
178 } elseif ( !isset( $req['url'] ) ) {
179 throw new Exception( "Request has no 'url' field set." );
181 $this->logger
->debug( "{$req['method']}: {$req['url']}" );
182 $req['query'] = $req['query'] ??
[];
183 $headers = []; // normalized headers
184 if ( isset( $req['headers'] ) ) {
185 foreach ( $req['headers'] as $name => $value ) {
186 $headers[strtolower( $name )] = $value;
189 $req['headers'] = $headers;
190 if ( !isset( $req['body'] ) ) {
192 $req['headers']['content-length'] = 0;
194 $req['flags'] = $req['flags'] ??
[];
195 $handles[$index] = $this->getCurlHandle( $req, $opts );
196 if ( count( $reqs ) > 1 ) {
197 // https://github.com/guzzle/guzzle/issues/349
198 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE
, true );
201 unset( $req ); // don't assign over this by accident
203 $indexes = array_keys( $reqs );
204 if ( isset( $opts['usePipelining'] ) ) {
205 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$opts['usePipelining'] );
207 if ( isset( $opts['maxConnsPerHost'] ) ) {
208 // Keep these sockets around as they may be needed later in the request
209 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$opts['maxConnsPerHost'] );
212 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
213 $batches = array_chunk( $indexes, $this->maxConnsPerHost
);
216 foreach ( $batches as $batch ) {
217 // Attach all cURL handles for this batch
218 foreach ( $batch as $index ) {
219 curl_multi_add_handle( $chm, $handles[$index] );
221 // Execute the cURL handles concurrently...
222 $active = null; // handles still being processed
224 // Do any available work...
226 $mrc = curl_multi_exec( $chm, $active );
227 $info = curl_multi_info_read( $chm );
228 if ( $info !== false ) {
229 $infos[(int)$info['handle']] = $info;
231 } while ( $mrc == CURLM_CALL_MULTI_PERFORM
);
232 // Wait (if possible) for available work...
233 if ( $active > 0 && $mrc == CURLM_OK
) {
234 if ( curl_multi_select( $chm, $selectTimeout ) == -1 ) {
235 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
236 usleep( 5000 ); // 5ms
239 } while ( $active > 0 && $mrc == CURLM_OK
);
242 // Remove all of the added cURL handles and check for errors...
243 foreach ( $reqs as $index => &$req ) {
244 $ch = $handles[$index];
245 curl_multi_remove_handle( $chm, $ch );
247 if ( isset( $infos[(int)$ch] ) ) {
248 $info = $infos[(int)$ch];
249 $errno = $info['result'];
250 if ( $errno !== 0 ) {
251 $req['response']['error'] = "(curl error: $errno)";
252 if ( function_exists( 'curl_strerror' ) ) {
253 $req['response']['error'] .= " " . curl_strerror( $errno );
255 $this->logger
->warning( "Error fetching URL \"{$req['url']}\": " .
256 $req['response']['error'] );
259 $req['response']['error'] = "(curl error: no status set)";
262 // For convenience with the list() operator
263 $req['response'][0] = $req['response']['code'];
264 $req['response'][1] = $req['response']['reason'];
265 $req['response'][2] = $req['response']['headers'];
266 $req['response'][3] = $req['response']['body'];
267 $req['response'][4] = $req['response']['error'];
269 // Close any string wrapper file handles
270 if ( isset( $req['_closeHandle'] ) ) {
271 fclose( $req['_closeHandle'] );
272 unset( $req['_closeHandle'] );
275 unset( $req ); // don't assign over this by accident
277 // Restore the default settings
278 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
279 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
285 * @param array &$req HTTP request map
287 * - connTimeout : default connection timeout
288 * - reqTimeout : default request timeout
292 protected function getCurlHandle( array &$req, array $opts = [] ) {
295 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS
,
296 ( $opts['connTimeout'] ??
$this->connTimeout
) * 1000 );
297 curl_setopt( $ch, CURLOPT_PROXY
, $req['proxy'] ??
$this->proxy
);
298 curl_setopt( $ch, CURLOPT_TIMEOUT_MS
,
299 ( $opts['reqTimeout'] ??
$this->reqTimeout
) * 1000 );
300 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION
, 1 );
301 curl_setopt( $ch, CURLOPT_MAXREDIRS
, 4 );
302 curl_setopt( $ch, CURLOPT_HEADER
, 0 );
303 if ( !is_null( $this->caBundlePath
) ) {
304 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER
, true );
305 curl_setopt( $ch, CURLOPT_CAINFO
, $this->caBundlePath
);
307 curl_setopt( $ch, CURLOPT_RETURNTRANSFER
, 1 );
310 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986
);
311 if ( $query != '' ) {
312 $url .= strpos( $req['url'], '?' ) === false ?
"?$query" : "&$query";
314 curl_setopt( $ch, CURLOPT_URL
, $url );
316 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST
, $req['method'] );
317 if ( $req['method'] === 'HEAD' ) {
318 curl_setopt( $ch, CURLOPT_NOBODY
, 1 );
321 if ( $req['method'] === 'PUT' ) {
322 curl_setopt( $ch, CURLOPT_PUT
, 1 );
323 if ( is_resource( $req['body'] ) ) {
324 curl_setopt( $ch, CURLOPT_INFILE
, $req['body'] );
325 if ( isset( $req['headers']['content-length'] ) ) {
326 curl_setopt( $ch, CURLOPT_INFILESIZE
, $req['headers']['content-length'] );
327 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
328 $req['headers']['transfer-encoding'] === 'chunks'
330 curl_setopt( $ch, CURLOPT_UPLOAD
, true );
332 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
334 } elseif ( $req['body'] !== '' ) {
335 $fp = fopen( "php://temp", "wb+" );
336 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
338 curl_setopt( $ch, CURLOPT_INFILE
, $fp );
339 curl_setopt( $ch, CURLOPT_INFILESIZE
, strlen( $req['body'] ) );
340 $req['_closeHandle'] = $fp; // remember to close this later
342 curl_setopt( $ch, CURLOPT_INFILESIZE
, 0 );
344 curl_setopt( $ch, CURLOPT_READFUNCTION
,
345 function ( $ch, $fd, $length ) {
346 $data = fread( $fd, $length );
347 $len = strlen( $data );
351 } elseif ( $req['method'] === 'POST' ) {
352 curl_setopt( $ch, CURLOPT_POST
, 1 );
353 // Don't interpret POST parameters starting with '@' as file uploads, because this
354 // makes it impossible to POST plain values starting with '@' (and causes security
355 // issues potentially exposing the contents of local files).
356 curl_setopt( $ch, CURLOPT_SAFE_UPLOAD
, true );
357 curl_setopt( $ch, CURLOPT_POSTFIELDS
, $req['body'] );
359 if ( is_resource( $req['body'] ) ||
$req['body'] !== '' ) {
360 throw new Exception( "HTTP body specified for a non PUT/POST request." );
362 $req['headers']['content-length'] = 0;
365 if ( !isset( $req['headers']['user-agent'] ) ) {
366 $req['headers']['user-agent'] = $this->userAgent
;
370 foreach ( $req['headers'] as $name => $value ) {
371 if ( strpos( $name, ': ' ) ) {
372 throw new Exception( "Headers cannot have ':' in the name." );
374 $headers[] = $name . ': ' . trim( $value );
376 curl_setopt( $ch, CURLOPT_HTTPHEADER
, $headers );
378 curl_setopt( $ch, CURLOPT_HEADERFUNCTION
,
379 function ( $ch, $header ) use ( &$req ) {
380 if ( !empty( $req['flags']['relayResponseHeaders'] ) ) {
383 $length = strlen( $header );
385 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
386 $req['response']['code'] = (int)$matches[2];
387 $req['response']['reason'] = trim( $matches[3] );
390 if ( strpos( $header, ":" ) === false ) {
393 list( $name, $value ) = explode( ":", $header, 2 );
394 $req['response']['headers'][strtolower( $name )] = trim( $value );
399 if ( isset( $req['stream'] ) ) {
400 // Don't just use CURLOPT_FILE as that might give:
401 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
402 // The callback here handles both normal files and php://temp handles.
403 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
404 function ( $ch, $data ) use ( &$req ) {
405 return fwrite( $req['stream'], $data );
409 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
410 function ( $ch, $data ) use ( &$req ) {
411 $req['response']['body'] .= $data;
412 return strlen( $data );
421 * Get a suitable select timeout for the given options.
426 private function getSelectTimeout( $opts ) {
427 $connTimeout = $opts['connTimeout'] ??
$this->connTimeout
;
428 $reqTimeout = $opts['reqTimeout'] ??
$this->reqTimeout
;
429 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
430 if ( count( $timeouts ) === 0 ) {
434 $selectTimeout = min( $timeouts ) * self
::TIMEOUT_ACCURACY_FACTOR
;
435 // Minimum 10us for sanity
436 if ( $selectTimeout < 10e-6 ) {
437 $selectTimeout = 10e-6;
439 return $selectTimeout;
446 protected function getCurlMulti() {
447 if ( !$this->multiHandle
) {
448 if ( !function_exists( 'curl_multi_init' ) ) {
449 throw new Exception( "PHP cURL extension missing. " .
450 "Check https://www.mediawiki.org/wiki/Manual:CURL" );
452 $cmh = curl_multi_init();
453 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
454 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
455 $this->multiHandle
= $cmh;
457 return $this->multiHandle
;
463 * @param LoggerInterface $logger
465 public function setLogger( LoggerInterface
$logger ) {
466 $this->logger
= $logger;
469 function __destruct() {
470 if ( $this->multiHandle
) {
471 curl_multi_close( $this->multiHandle
);