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 */
60 * @param array $options
61 * - connTimeout : default connection timeout (seconds)
62 * - reqTimeout : default request timeout (seconds)
63 * - proxy : HTTP proxy to use
64 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
65 * - maxConnsPerHost : maximum number of concurrent connections (per host)
68 public function __construct( array $options ) {
69 if ( isset( $options['caBundlePath'] ) ) {
70 $this->caBundlePath
= $options['caBundlePath'];
71 if ( !file_exists( $this->caBundlePath
) ) {
72 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath
);
76 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost', 'proxy'
78 foreach ( $opts as $key ) {
79 if ( isset( $options[$key] ) ) {
80 $this->$key = $options[$key];
86 * Execute an HTTP(S) request
88 * This method returns a response map of:
89 * - code : HTTP response code or 0 if there was a serious cURL error
90 * - reason : HTTP response reason (empty if there was a serious cURL error)
91 * - headers : <header name/value associative array>
92 * - body : HTTP response body or resource (if "stream" was set)
93 * - error : Any cURL error string
94 * The map also stores integer-indexed copies of these values. This lets callers do:
96 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
98 * @param array $req HTTP request array
100 * - connTimeout : connection timeout per request (seconds)
101 * - reqTimeout : post-connection timeout per request (seconds)
102 * @return array Response array for request
104 final public function run( array $req, array $opts = array() ) {
105 $req = $this->runMulti( array( $req ), $opts );
106 return $req[0]['response'];
110 * Execute a set of HTTP(S) requests concurrently
112 * The maps are returned by this method with the 'response' field set to a map of:
113 * - code : HTTP response code or 0 if there was a serious cURL error
114 * - reason : HTTP response reason (empty if there was a serious cURL error)
115 * - headers : <header name/value associative array>
116 * - body : HTTP response body or resource (if "stream" was set)
117 * - error : Any cURL error string
118 * The map also stores integer-indexed copies of these values. This lets callers do:
120 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
122 * All headers in the 'headers' field are normalized to use lower case names.
123 * This is true for the request headers and the response headers. Integer-indexed
124 * method/URL entries will also be changed to use the corresponding string keys.
126 * @param array $reqs Map of HTTP request arrays
128 * - connTimeout : connection timeout per request (seconds)
129 * - reqTimeout : post-connection timeout per request (seconds)
130 * - usePipelining : whether to use HTTP pipelining if possible
131 * - maxConnsPerHost : maximum number of concurrent connections (per host)
132 * @return array $reqs With response array populated for each
135 public function runMulti( array $reqs, array $opts = array() ) {
136 $chm = $this->getCurlMulti();
138 // Normalize $reqs and add all of the required cURL handles...
140 foreach ( $reqs as $index => &$req ) {
141 $req['response'] = array(
144 'headers' => array(),
148 if ( isset( $req[0] ) ) {
149 $req['method'] = $req[0]; // short-form
152 if ( isset( $req[1] ) ) {
153 $req['url'] = $req[1]; // short-form
156 if ( !isset( $req['method'] ) ) {
157 throw new Exception( "Request has no 'method' field set." );
158 } elseif ( !isset( $req['url'] ) ) {
159 throw new Exception( "Request has no 'url' field set." );
161 $req['query'] = isset( $req['query'] ) ?
$req['query'] : array();
162 $headers = array(); // normalized headers
163 if ( isset( $req['headers'] ) ) {
164 foreach ( $req['headers'] as $name => $value ) {
165 $headers[strtolower( $name )] = $value;
168 $req['headers'] = $headers;
169 if ( !isset( $req['body'] ) ) {
171 $req['headers']['content-length'] = 0;
173 $handles[$index] = $this->getCurlHandle( $req, $opts );
174 if ( count( $reqs ) > 1 ) {
175 // https://github.com/guzzle/guzzle/issues/349
176 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE
, true );
179 unset( $req ); // don't assign over this by accident
181 $indexes = array_keys( $reqs );
182 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
183 if ( isset( $opts['usePipelining'] ) ) {
184 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$opts['usePipelining'] );
186 if ( isset( $opts['maxConnsPerHost'] ) ) {
187 // Keep these sockets around as they may be needed later in the request
188 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$opts['maxConnsPerHost'] );
192 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
193 $batches = array_chunk( $indexes, $this->maxConnsPerHost
);
196 foreach ( $batches as $batch ) {
197 // Attach all cURL handles for this batch
198 foreach ( $batch as $index ) {
199 curl_multi_add_handle( $chm, $handles[$index] );
201 // Execute the cURL handles concurrently...
202 $active = null; // handles still being processed
204 // Do any available work...
206 $mrc = curl_multi_exec( $chm, $active );
207 $info = curl_multi_info_read( $chm );
208 if ( $info !== false ) {
209 $infos[(int)$info['handle']] = $info;
211 } while ( $mrc == CURLM_CALL_MULTI_PERFORM
);
212 // Wait (if possible) for available work...
213 if ( $active > 0 && $mrc == CURLM_OK
) {
214 if ( curl_multi_select( $chm, 10 ) == -1 ) {
215 // PHP bug 63411; http://curl.haxx.se/libcurl/c/curl_multi_fdset.html
216 usleep( 5000 ); // 5ms
219 } while ( $active > 0 && $mrc == CURLM_OK
);
222 // Remove all of the added cURL handles and check for errors...
223 foreach ( $reqs as $index => &$req ) {
224 $ch = $handles[$index];
225 curl_multi_remove_handle( $chm, $ch );
227 if ( isset( $infos[(int)$ch] ) ) {
228 $info = $infos[(int)$ch];
229 $errno = $info['result'];
230 if ( $errno !== 0 ) {
231 $req['response']['error'] = "(curl error: $errno)";
232 if ( function_exists( 'curl_strerror' ) ) {
233 $req['response']['error'] .= " " . curl_strerror( $errno );
237 $req['response']['error'] = "(curl error: no status set)";
240 // For convenience with the list() operator
241 $req['response'][0] = $req['response']['code'];
242 $req['response'][1] = $req['response']['reason'];
243 $req['response'][2] = $req['response']['headers'];
244 $req['response'][3] = $req['response']['body'];
245 $req['response'][4] = $req['response']['error'];
247 // Close any string wrapper file handles
248 if ( isset( $req['_closeHandle'] ) ) {
249 fclose( $req['_closeHandle'] );
250 unset( $req['_closeHandle'] );
253 unset( $req ); // don't assign over this by accident
255 // Restore the default settings
256 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
257 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
258 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
265 * @param array $req HTTP request map
267 * - connTimeout : default connection timeout
268 * - reqTimeout : default request timeout
272 protected function getCurlHandle( array &$req, array $opts = array() ) {
275 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT
,
276 isset( $opts['connTimeout'] ) ?
$opts['connTimeout'] : $this->connTimeout
);
277 curl_setopt( $ch, CURLOPT_PROXY
, isset( $req['proxy'] ) ?
$req['proxy'] : $this->proxy
);
278 curl_setopt( $ch, CURLOPT_TIMEOUT
,
279 isset( $opts['reqTimeout'] ) ?
$opts['reqTimeout'] : $this->reqTimeout
);
280 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION
, 1 );
281 curl_setopt( $ch, CURLOPT_MAXREDIRS
, 4 );
282 curl_setopt( $ch, CURLOPT_HEADER
, 0 );
283 if ( !is_null( $this->caBundlePath
) ) {
284 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER
, true );
285 curl_setopt( $ch, CURLOPT_CAINFO
, $this->caBundlePath
);
287 curl_setopt( $ch, CURLOPT_RETURNTRANSFER
, 1 );
290 // PHP_QUERY_RFC3986 is PHP 5.4+ only
291 $query = str_replace(
294 http_build_query( $req['query'], '', '&' )
296 if ( $query != '' ) {
297 $url .= strpos( $req['url'], '?' ) === false ?
"?$query" : "&$query";
299 curl_setopt( $ch, CURLOPT_URL
, $url );
301 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST
, $req['method'] );
302 if ( $req['method'] === 'HEAD' ) {
303 curl_setopt( $ch, CURLOPT_NOBODY
, 1 );
306 if ( $req['method'] === 'PUT' ) {
307 curl_setopt( $ch, CURLOPT_PUT
, 1 );
308 if ( is_resource( $req['body'] ) ) {
309 curl_setopt( $ch, CURLOPT_INFILE
, $req['body'] );
310 if ( isset( $req['headers']['content-length'] ) ) {
311 curl_setopt( $ch, CURLOPT_INFILESIZE
, $req['headers']['content-length'] );
312 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
313 $req['headers']['transfer-encoding'] === 'chunks'
315 curl_setopt( $ch, CURLOPT_UPLOAD
, true );
317 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
319 } elseif ( $req['body'] !== '' ) {
320 $fp = fopen( "php://temp", "wb+" );
321 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
323 curl_setopt( $ch, CURLOPT_INFILE
, $fp );
324 curl_setopt( $ch, CURLOPT_INFILESIZE
, strlen( $req['body'] ) );
325 $req['_closeHandle'] = $fp; // remember to close this later
327 curl_setopt( $ch, CURLOPT_INFILESIZE
, 0 );
329 curl_setopt( $ch, CURLOPT_READFUNCTION
,
330 function ( $ch, $fd, $length ) {
331 $data = fread( $fd, $length );
332 $len = strlen( $data );
336 } elseif ( $req['method'] === 'POST' ) {
337 curl_setopt( $ch, CURLOPT_POST
, 1 );
338 curl_setopt( $ch, CURLOPT_POSTFIELDS
, $req['body'] );
340 if ( is_resource( $req['body'] ) ||
$req['body'] !== '' ) {
341 throw new Exception( "HTTP body specified for a non PUT/POST request." );
343 $req['headers']['content-length'] = 0;
347 foreach ( $req['headers'] as $name => $value ) {
348 if ( strpos( $name, ': ' ) ) {
349 throw new Exception( "Headers cannot have ':' in the name." );
351 $headers[] = $name . ': ' . trim( $value );
353 curl_setopt( $ch, CURLOPT_HTTPHEADER
, $headers );
355 curl_setopt( $ch, CURLOPT_HEADERFUNCTION
,
356 function ( $ch, $header ) use ( &$req ) {
357 $length = strlen( $header );
359 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
360 $req['response']['code'] = (int)$matches[2];
361 $req['response']['reason'] = trim( $matches[3] );
364 if ( strpos( $header, ":" ) === false ) {
367 list( $name, $value ) = explode( ":", $header, 2 );
368 $req['response']['headers'][strtolower( $name )] = trim( $value );
373 if ( isset( $req['stream'] ) ) {
374 // Don't just use CURLOPT_FILE as that might give:
375 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
376 // The callback here handles both normal files and php://temp handles.
377 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
378 function ( $ch, $data ) use ( &$req ) {
379 return fwrite( $req['stream'], $data );
383 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
384 function ( $ch, $data ) use ( &$req ) {
385 $req['response']['body'] .= $data;
386 return strlen( $data );
397 protected function getCurlMulti() {
398 if ( !$this->multiHandle
) {
399 $cmh = curl_multi_init();
400 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
401 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
402 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
404 $this->multiHandle
= $cmh;
406 return $this->multiHandle
;
409 function __destruct() {
410 if ( $this->multiHandle
) {
411 curl_multi_close( $this->multiHandle
);