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
);
75 static $opts = array( 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost', 'proxy' );
76 foreach ( $opts as $key ) {
77 if ( isset( $options[$key] ) ) {
78 $this->$key = $options[$key];
84 * Execute an HTTP(S) request
86 * This method returns a response map of:
87 * - code : HTTP response code or 0 if there was a serious cURL error
88 * - reason : HTTP response reason (empty if there was a serious cURL error)
89 * - headers : <header name/value associative array>
90 * - body : HTTP response body or resource (if "stream" was set)
91 * - error : Any cURL error string
92 * The map also stores integer-indexed copies of these values. This lets callers do:
94 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
96 * @param array $req HTTP request array
98 * - connTimeout : connection timeout per request (seconds)
99 * - reqTimeout : post-connection timeout per request (seconds)
100 * @return array Response array for request
102 final public function run( array $req, array $opts = array() ) {
103 $req = $this->runMulti( array( $req ), $opts );
104 return $req[0]['response'];
108 * Execute a set of HTTP(S) requests concurrently
110 * The maps are returned by this method with the 'response' field set to a map of:
111 * - code : HTTP response code or 0 if there was a serious cURL error
112 * - reason : HTTP response reason (empty if there was a serious cURL error)
113 * - headers : <header name/value associative array>
114 * - body : HTTP response body or resource (if "stream" was set)
115 * - error : Any cURL error string
116 * The map also stores integer-indexed copies of these values. This lets callers do:
118 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
120 * All headers in the 'headers' field are normalized to use lower case names.
121 * This is true for the request headers and the response headers. Integer-indexed
122 * method/URL entries will also be changed to use the corresponding string keys.
124 * @param array $reqs Map of HTTP request arrays
126 * - connTimeout : connection timeout per request (seconds)
127 * - reqTimeout : post-connection timeout per request (seconds)
128 * - usePipelining : whether to use HTTP pipelining if possible
129 * - maxConnsPerHost : maximum number of concurrent connections (per host)
130 * @return array $reqs With response array populated for each
133 public function runMulti( array $reqs, array $opts = array() ) {
134 $chm = $this->getCurlMulti();
136 // Normalize $reqs and add all of the required cURL handles...
138 foreach ( $reqs as $index => &$req ) {
139 $req['response'] = array(
142 'headers' => array(),
146 if ( isset( $req[0] ) ) {
147 $req['method'] = $req[0]; // short-form
150 if ( isset( $req[1] ) ) {
151 $req['url'] = $req[1]; // short-form
154 if ( !isset( $req['method'] ) ) {
155 throw new Exception( "Request has no 'method' field set." );
156 } elseif ( !isset( $req['url'] ) ) {
157 throw new Exception( "Request has no 'url' field set." );
159 $req['query'] = isset( $req['query'] ) ?
$req['query'] : array();
160 $headers = array(); // normalized headers
161 if ( isset( $req['headers'] ) ) {
162 foreach ( $req['headers'] as $name => $value ) {
163 $headers[strtolower( $name )] = $value;
166 $req['headers'] = $headers;
167 if ( !isset( $req['body'] ) ) {
169 $req['headers']['content-length'] = 0;
171 $handles[$index] = $this->getCurlHandle( $req, $opts );
172 if ( count( $reqs ) > 1 ) {
173 // https://github.com/guzzle/guzzle/issues/349
174 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE
, true );
177 unset( $req ); // don't assign over this by accident
179 $indexes = array_keys( $reqs );
180 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
181 if ( isset( $opts['usePipelining'] ) ) {
182 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$opts['usePipelining'] );
184 if ( isset( $opts['maxConnsPerHost'] ) ) {
185 // Keep these sockets around as they may be needed later in the request
186 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$opts['maxConnsPerHost'] );
190 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
191 $batches = array_chunk( $indexes, $this->maxConnsPerHost
);
194 foreach ( $batches as $batch ) {
195 // Attach all cURL handles for this batch
196 foreach ( $batch as $index ) {
197 curl_multi_add_handle( $chm, $handles[$index] );
199 // Execute the cURL handles concurrently...
200 $active = null; // handles still being processed
202 // Do any available work...
204 $mrc = curl_multi_exec( $chm, $active );
205 $info = curl_multi_info_read( $chm );
206 if ( $info !== false ) {
207 $infos[(int)$info['handle']] = $info;
209 } while ( $mrc == CURLM_CALL_MULTI_PERFORM
);
210 // Wait (if possible) for available work...
211 if ( $active > 0 && $mrc == CURLM_OK
) {
212 if ( curl_multi_select( $chm, 10 ) == -1 ) {
213 // PHP bug 63411; http://curl.haxx.se/libcurl/c/curl_multi_fdset.html
214 usleep( 5000 ); // 5ms
217 } while ( $active > 0 && $mrc == CURLM_OK
);
220 // Remove all of the added cURL handles and check for errors...
221 foreach ( $reqs as $index => &$req ) {
222 $ch = $handles[$index];
223 curl_multi_remove_handle( $chm, $ch );
225 $info = $infos[(int)$ch];
227 $errno = $info['result'];
228 if ( $errno !== 0 ) {
229 $req['response']['error'] = "(curl error: $errno)";
231 if ( version_compare( PHP_VERSION
, '5.5.0' ) >= 0 ) {
232 $req['response']['error'] .= " " . curl_strerror( $errno );
236 // For convenience with the list() operator
237 $req['response'][0] = $req['response']['code'];
238 $req['response'][1] = $req['response']['reason'];
239 $req['response'][2] = $req['response']['headers'];
240 $req['response'][3] = $req['response']['body'];
241 $req['response'][4] = $req['response']['error'];
243 // Close any string wrapper file handles
244 if ( isset( $req['_closeHandle'] ) ) {
245 fclose( $req['_closeHandle'] );
246 unset( $req['_closeHandle'] );
249 unset( $req ); // don't assign over this by accident
251 // Restore the default settings
252 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
253 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
254 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
261 * @param array $req HTTP request map
263 * - connTimeout : default connection timeout
264 * - reqTimeout : default request timeout
268 protected function getCurlHandle( array &$req, array $opts = array() ) {
271 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT
,
272 isset( $opts['connTimeout'] ) ?
$opts['connTimeout'] : $this->connTimeout
);
273 curl_setopt( $ch, CURLOPT_PROXY
, isset( $req['proxy'] ) ?
$req['proxy'] : $this->proxy
);
274 curl_setopt( $ch, CURLOPT_TIMEOUT
,
275 isset( $opts['reqTimeout'] ) ?
$opts['reqTimeout'] : $this->reqTimeout
);
276 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION
, 1 );
277 curl_setopt( $ch, CURLOPT_MAXREDIRS
, 4 );
278 curl_setopt( $ch, CURLOPT_HEADER
, 0 );
279 if ( !is_null( $this->caBundlePath
) ) {
280 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER
, true );
281 curl_setopt( $ch, CURLOPT_CAINFO
, $this->caBundlePath
);
283 curl_setopt( $ch, CURLOPT_RETURNTRANSFER
, 1 );
286 // PHP_QUERY_RFC3986 is PHP 5.4+ only
287 $query = str_replace(
290 http_build_query( $req['query'], '', '&' )
292 if ( $query != '' ) {
293 $url .= strpos( $req['url'], '?' ) === false ?
"?$query" : "&$query";
295 curl_setopt( $ch, CURLOPT_URL
, $url );
297 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST
, $req['method'] );
298 if ( $req['method'] === 'HEAD' ) {
299 curl_setopt( $ch, CURLOPT_NOBODY
, 1 );
302 if ( $req['method'] === 'PUT' ) {
303 curl_setopt( $ch, CURLOPT_PUT
, 1 );
304 if ( is_resource( $req['body'] ) ) {
305 curl_setopt( $ch, CURLOPT_INFILE
, $req['body'] );
306 if ( isset( $req['headers']['content-length'] ) ) {
307 curl_setopt( $ch, CURLOPT_INFILESIZE
, $req['headers']['content-length'] );
308 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
309 $req['headers']['transfer-encoding'] === 'chunks'
311 curl_setopt( $ch, CURLOPT_UPLOAD
, true );
313 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
315 } elseif ( $req['body'] !== '' ) {
316 $fp = fopen( "php://temp", "wb+" );
317 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
319 curl_setopt( $ch, CURLOPT_INFILE
, $fp );
320 curl_setopt( $ch, CURLOPT_INFILESIZE
, strlen( $req['body'] ) );
321 $req['_closeHandle'] = $fp; // remember to close this later
323 curl_setopt( $ch, CURLOPT_INFILESIZE
, 0 );
325 curl_setopt( $ch, CURLOPT_READFUNCTION
,
326 function ( $ch, $fd, $length ) {
327 $data = fread( $fd, $length );
328 $len = strlen( $data );
332 } elseif ( $req['method'] === 'POST' ) {
333 curl_setopt( $ch, CURLOPT_POST
, 1 );
334 curl_setopt( $ch, CURLOPT_POSTFIELDS
, $req['body'] );
336 if ( is_resource( $req['body'] ) ||
$req['body'] !== '' ) {
337 throw new Exception( "HTTP body specified for a non PUT/POST request." );
339 $req['headers']['content-length'] = 0;
343 foreach ( $req['headers'] as $name => $value ) {
344 if ( strpos( $name, ': ' ) ) {
345 throw new Exception( "Headers cannot have ':' in the name." );
347 $headers[] = $name . ': ' . trim( $value );
349 curl_setopt( $ch, CURLOPT_HTTPHEADER
, $headers );
351 curl_setopt( $ch, CURLOPT_HEADERFUNCTION
,
352 function ( $ch, $header ) use ( &$req ) {
353 $length = strlen( $header );
355 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
356 $req['response']['code'] = (int)$matches[2];
357 $req['response']['reason'] = trim( $matches[3] );
360 if ( strpos( $header, ":" ) === false ) {
363 list( $name, $value ) = explode( ":", $header, 2 );
364 $req['response']['headers'][strtolower( $name )] = trim( $value );
369 if ( isset( $req['stream'] ) ) {
370 // Don't just use CURLOPT_FILE as that might give:
371 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
372 // The callback here handles both normal files and php://temp handles.
373 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
374 function ( $ch, $data ) use ( &$req ) {
375 return fwrite( $req['stream'], $data );
379 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
380 function ( $ch, $data ) use ( &$req ) {
381 $req['response']['body'] .= $data;
382 return strlen( $data );
393 protected function getCurlMulti() {
394 if ( !$this->multiHandle
) {
395 $cmh = curl_multi_init();
396 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
397 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
398 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
400 $this->multiHandle
= $cmh;
402 return $this->multiHandle
;
405 function __destruct() {
406 if ( $this->multiHandle
) {
407 curl_multi_close( $this->multiHandle
);