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
24 * Class to handle concurrent HTTP requests
26 * HTTP request maps are arrays that use the following format:
27 * - method : GET/HEAD/PUT/POST/DELETE
28 * - url : HTTP/HTTPS URL
29 * - query : <query parameter field/value associative array> (uses RFC 3986)
30 * - headers : <header name/value associative array>
31 * - body : source to get the HTTP request body from;
32 * this can simply be a string (always), a resource for
33 * PUT requests, and a field/value array for POST request;
34 * array bodies are encoded as multipart/form-data and strings
35 * use application/x-www-form-urlencoded (headers sent automatically)
36 * - stream : resource to stream the HTTP response body to
37 * - proxy : HTTP proxy to use
38 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
40 * @author Aaron Schulz
43 class MultiHttpClient
{
45 protected $multiHandle = null; // curl_multi handle
46 /** @var string|null SSL certificates path */
47 protected $caBundlePath;
49 protected $connTimeout = 10;
51 protected $reqTimeout = 300;
53 protected $usePipelining = false;
55 protected $maxConnsPerHost = 50;
56 /** @var string|null proxy */
59 protected $userAgent = 'wikimedia/multi-http-client v1.0';
62 * @param array $options
63 * - connTimeout : default connection timeout (seconds)
64 * - reqTimeout : default request timeout (seconds)
65 * - proxy : HTTP proxy to use
66 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
67 * - maxConnsPerHost : maximum number of concurrent connections (per host)
68 * - userAgent : The User-Agent header value to send
71 public function __construct( array $options ) {
72 if ( isset( $options['caBundlePath'] ) ) {
73 $this->caBundlePath
= $options['caBundlePath'];
74 if ( !file_exists( $this->caBundlePath
) ) {
75 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath
);
79 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost', 'proxy', 'userAgent'
81 foreach ( $opts as $key ) {
82 if ( isset( $options[$key] ) ) {
83 $this->$key = $options[$key];
89 * Execute an HTTP(S) request
91 * This method returns a response map of:
92 * - code : HTTP response code or 0 if there was a serious cURL error
93 * - reason : HTTP response reason (empty if there was a serious cURL error)
94 * - headers : <header name/value associative array>
95 * - body : HTTP response body or resource (if "stream" was set)
96 * - error : Any cURL error string
97 * The map also stores integer-indexed copies of these values. This lets callers do:
99 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
101 * @param array $req HTTP request array
103 * - connTimeout : connection timeout per request (seconds)
104 * - reqTimeout : post-connection timeout per request (seconds)
105 * @return array Response array for request
107 final public function run( array $req, array $opts = array() ) {
108 $req = $this->runMulti( array( $req ), $opts );
109 return $req[0]['response'];
113 * Execute a set of HTTP(S) requests concurrently
115 * The maps are returned by this method with the 'response' field set to a map of:
116 * - code : HTTP response code or 0 if there was a serious cURL error
117 * - reason : HTTP response reason (empty if there was a serious cURL error)
118 * - headers : <header name/value associative array>
119 * - body : HTTP response body or resource (if "stream" was set)
120 * - error : Any cURL error string
121 * The map also stores integer-indexed copies of these values. This lets callers do:
123 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
125 * All headers in the 'headers' field are normalized to use lower case names.
126 * This is true for the request headers and the response headers. Integer-indexed
127 * method/URL entries will also be changed to use the corresponding string keys.
129 * @param array $reqs Map of HTTP request arrays
131 * - connTimeout : connection timeout per request (seconds)
132 * - reqTimeout : post-connection timeout per request (seconds)
133 * - usePipelining : whether to use HTTP pipelining if possible
134 * - maxConnsPerHost : maximum number of concurrent connections (per host)
135 * @return array $reqs With response array populated for each
138 public function runMulti( array $reqs, array $opts = array() ) {
139 $chm = $this->getCurlMulti();
141 // Normalize $reqs and add all of the required cURL handles...
143 foreach ( $reqs as $index => &$req ) {
144 $req['response'] = array(
147 'headers' => array(),
151 if ( isset( $req[0] ) ) {
152 $req['method'] = $req[0]; // short-form
155 if ( isset( $req[1] ) ) {
156 $req['url'] = $req[1]; // short-form
159 if ( !isset( $req['method'] ) ) {
160 throw new Exception( "Request has no 'method' field set." );
161 } elseif ( !isset( $req['url'] ) ) {
162 throw new Exception( "Request has no 'url' field set." );
164 $req['query'] = isset( $req['query'] ) ?
$req['query'] : array();
165 $headers = array(); // normalized headers
166 if ( isset( $req['headers'] ) ) {
167 foreach ( $req['headers'] as $name => $value ) {
168 $headers[strtolower( $name )] = $value;
171 $req['headers'] = $headers;
172 if ( !isset( $req['body'] ) ) {
174 $req['headers']['content-length'] = 0;
176 $handles[$index] = $this->getCurlHandle( $req, $opts );
177 if ( count( $reqs ) > 1 ) {
178 // https://github.com/guzzle/guzzle/issues/349
179 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE
, true );
182 unset( $req ); // don't assign over this by accident
184 $indexes = array_keys( $reqs );
185 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
186 if ( isset( $opts['usePipelining'] ) ) {
187 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$opts['usePipelining'] );
189 if ( isset( $opts['maxConnsPerHost'] ) ) {
190 // Keep these sockets around as they may be needed later in the request
191 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$opts['maxConnsPerHost'] );
195 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
196 $batches = array_chunk( $indexes, $this->maxConnsPerHost
);
199 foreach ( $batches as $batch ) {
200 // Attach all cURL handles for this batch
201 foreach ( $batch as $index ) {
202 curl_multi_add_handle( $chm, $handles[$index] );
204 // Execute the cURL handles concurrently...
205 $active = null; // handles still being processed
207 // Do any available work...
209 $mrc = curl_multi_exec( $chm, $active );
210 $info = curl_multi_info_read( $chm );
211 if ( $info !== false ) {
212 $infos[(int)$info['handle']] = $info;
214 } while ( $mrc == CURLM_CALL_MULTI_PERFORM
);
215 // Wait (if possible) for available work...
216 if ( $active > 0 && $mrc == CURLM_OK
) {
217 if ( curl_multi_select( $chm, 10 ) == -1 ) {
218 // PHP bug 63411; http://curl.haxx.se/libcurl/c/curl_multi_fdset.html
219 usleep( 5000 ); // 5ms
222 } while ( $active > 0 && $mrc == CURLM_OK
);
225 // Remove all of the added cURL handles and check for errors...
226 foreach ( $reqs as $index => &$req ) {
227 $ch = $handles[$index];
228 curl_multi_remove_handle( $chm, $ch );
230 if ( isset( $infos[(int)$ch] ) ) {
231 $info = $infos[(int)$ch];
232 $errno = $info['result'];
233 if ( $errno !== 0 ) {
234 $req['response']['error'] = "(curl error: $errno)";
235 if ( function_exists( 'curl_strerror' ) ) {
236 $req['response']['error'] .= " " . curl_strerror( $errno );
240 $req['response']['error'] = "(curl error: no status set)";
243 // For convenience with the list() operator
244 $req['response'][0] = $req['response']['code'];
245 $req['response'][1] = $req['response']['reason'];
246 $req['response'][2] = $req['response']['headers'];
247 $req['response'][3] = $req['response']['body'];
248 $req['response'][4] = $req['response']['error'];
250 // Close any string wrapper file handles
251 if ( isset( $req['_closeHandle'] ) ) {
252 fclose( $req['_closeHandle'] );
253 unset( $req['_closeHandle'] );
256 unset( $req ); // don't assign over this by accident
258 // Restore the default settings
259 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
260 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
261 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
268 * @param array $req HTTP request map
270 * - connTimeout : default connection timeout
271 * - reqTimeout : default request timeout
275 protected function getCurlHandle( array &$req, array $opts = array() ) {
278 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT
,
279 isset( $opts['connTimeout'] ) ?
$opts['connTimeout'] : $this->connTimeout
);
280 curl_setopt( $ch, CURLOPT_PROXY
, isset( $req['proxy'] ) ?
$req['proxy'] : $this->proxy
);
281 curl_setopt( $ch, CURLOPT_TIMEOUT
,
282 isset( $opts['reqTimeout'] ) ?
$opts['reqTimeout'] : $this->reqTimeout
);
283 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION
, 1 );
284 curl_setopt( $ch, CURLOPT_MAXREDIRS
, 4 );
285 curl_setopt( $ch, CURLOPT_HEADER
, 0 );
286 if ( !is_null( $this->caBundlePath
) ) {
287 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER
, true );
288 curl_setopt( $ch, CURLOPT_CAINFO
, $this->caBundlePath
);
290 curl_setopt( $ch, CURLOPT_RETURNTRANSFER
, 1 );
293 // PHP_QUERY_RFC3986 is PHP 5.4+ only
294 $query = str_replace(
297 http_build_query( $req['query'], '', '&' )
299 if ( $query != '' ) {
300 $url .= strpos( $req['url'], '?' ) === false ?
"?$query" : "&$query";
302 curl_setopt( $ch, CURLOPT_URL
, $url );
304 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST
, $req['method'] );
305 if ( $req['method'] === 'HEAD' ) {
306 curl_setopt( $ch, CURLOPT_NOBODY
, 1 );
309 if ( $req['method'] === 'PUT' ) {
310 curl_setopt( $ch, CURLOPT_PUT
, 1 );
311 if ( is_resource( $req['body'] ) ) {
312 curl_setopt( $ch, CURLOPT_INFILE
, $req['body'] );
313 if ( isset( $req['headers']['content-length'] ) ) {
314 curl_setopt( $ch, CURLOPT_INFILESIZE
, $req['headers']['content-length'] );
315 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
316 $req['headers']['transfer-encoding'] === 'chunks'
318 curl_setopt( $ch, CURLOPT_UPLOAD
, true );
320 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
322 } elseif ( $req['body'] !== '' ) {
323 $fp = fopen( "php://temp", "wb+" );
324 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
326 curl_setopt( $ch, CURLOPT_INFILE
, $fp );
327 curl_setopt( $ch, CURLOPT_INFILESIZE
, strlen( $req['body'] ) );
328 $req['_closeHandle'] = $fp; // remember to close this later
330 curl_setopt( $ch, CURLOPT_INFILESIZE
, 0 );
332 curl_setopt( $ch, CURLOPT_READFUNCTION
,
333 function ( $ch, $fd, $length ) {
334 $data = fread( $fd, $length );
335 $len = strlen( $data );
339 } elseif ( $req['method'] === 'POST' ) {
340 curl_setopt( $ch, CURLOPT_POST
, 1 );
341 // Don't interpret POST parameters starting with '@' as file uploads, because this
342 // makes it impossible to POST plain values starting with '@' (and causes security
343 // issues potentially exposing the contents of local files).
344 // The PHP manual says this option was introduced in PHP 5.5 defaults to true in PHP 5.6,
345 // but we support lower versions, and the option doesn't exist in HHVM 5.6.99.
346 if ( defined( 'CURLOPT_SAFE_UPLOAD' ) ) {
347 curl_setopt( $ch, CURLOPT_SAFE_UPLOAD
, true );
348 } elseif ( is_array( $req['body'] ) ) {
349 // In PHP 5.2 and later, '@' is interpreted as a file upload if POSTFIELDS
350 // is an array, but not if it's a string. So convert $req['body'] to a string
352 $req['body'] = wfArrayToCgi( $req['body'] );
354 curl_setopt( $ch, CURLOPT_POSTFIELDS
, $req['body'] );
356 if ( is_resource( $req['body'] ) ||
$req['body'] !== '' ) {
357 throw new Exception( "HTTP body specified for a non PUT/POST request." );
359 $req['headers']['content-length'] = 0;
362 if ( !isset( $req['headers']['user-agent'] ) ) {
363 $req['headers']['user-agent'] = $this->userAgent
;
367 foreach ( $req['headers'] as $name => $value ) {
368 if ( strpos( $name, ': ' ) ) {
369 throw new Exception( "Headers cannot have ':' in the name." );
371 $headers[] = $name . ': ' . trim( $value );
373 curl_setopt( $ch, CURLOPT_HTTPHEADER
, $headers );
375 curl_setopt( $ch, CURLOPT_HEADERFUNCTION
,
376 function ( $ch, $header ) use ( &$req ) {
377 $length = strlen( $header );
379 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
380 $req['response']['code'] = (int)$matches[2];
381 $req['response']['reason'] = trim( $matches[3] );
384 if ( strpos( $header, ":" ) === false ) {
387 list( $name, $value ) = explode( ":", $header, 2 );
388 $req['response']['headers'][strtolower( $name )] = trim( $value );
393 if ( isset( $req['stream'] ) ) {
394 // Don't just use CURLOPT_FILE as that might give:
395 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
396 // The callback here handles both normal files and php://temp handles.
397 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
398 function ( $ch, $data ) use ( &$req ) {
399 return fwrite( $req['stream'], $data );
403 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
404 function ( $ch, $data ) use ( &$req ) {
405 $req['response']['body'] .= $data;
406 return strlen( $data );
417 protected function getCurlMulti() {
418 if ( !$this->multiHandle
) {
419 $cmh = curl_multi_init();
420 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
421 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
422 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
424 $this->multiHandle
= $cmh;
426 return $this->multiHandle
;
429 function __destruct() {
430 if ( $this->multiHandle
) {
431 curl_multi_close( $this->multiHandle
);