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 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
39 * @author Aaron Schulz
42 class MultiHttpClient
{
44 protected $multiHandle = null; // curl_multi handle
45 /** @var string|null SSL certificates path */
46 protected $caBundlePath;
48 protected $connTimeout = 10;
50 protected $reqTimeout = 300;
52 protected $usePipelining = false;
54 protected $maxConnsPerHost = 50;
57 * @param array $options
58 * - connTimeout : default connection timeout
59 * - reqTimeout : default request timeout
60 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
61 * - maxConnsPerHost : maximum number of concurrent connections (per host)
64 public function __construct( array $options ) {
65 if ( isset( $options['caBundlePath'] ) ) {
66 $this->caBundlePath
= $options['caBundlePath'];
67 if ( !file_exists( $this->caBundlePath
) ) {
68 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath
);
71 static $opts = array( 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost' );
72 foreach ( $opts as $key ) {
73 if ( isset( $options[$key] ) ) {
74 $this->$key = $options[$key];
80 * Execute an HTTP(S) request
82 * This method returns a response map of:
83 * - code : HTTP response code or 0 if there was a serious cURL error
84 * - reason : HTTP response reason (empty if there was a serious cURL error)
85 * - headers : <header name/value associative array>
86 * - body : HTTP response body or resource (if "stream" was set)
87 * - error : Any cURL error string
88 * The map also stores integer-indexed copies of these values. This lets callers do:
90 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
92 * @param array $req HTTP request array
94 * - connTimeout : connection timeout per request
95 * - reqTimeout : post-connection timeout per request
96 * @return array Response array for request
98 final public function run( array $req, array $opts = array() ) {
99 $req = $this->runMulti( array( $req ), $opts );
100 return $req[0]['response'];
104 * Execute a set of HTTP(S) requests concurrently
106 * The maps are returned by this method with the 'response' field set to a map of:
107 * - code : HTTP response code or 0 if there was a serious cURL error
108 * - reason : HTTP response reason (empty if there was a serious cURL error)
109 * - headers : <header name/value associative array>
110 * - body : HTTP response body or resource (if "stream" was set)
111 * - error : Any cURL error string
112 * The map also stores integer-indexed copies of these values. This lets callers do:
114 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
116 * All headers in the 'headers' field are normalized to use lower case names.
117 * This is true for the request headers and the response headers. Integer-indexed
118 * method/URL entries will also be changed to use the corresponding string keys.
120 * @param array $reqs Map of HTTP request arrays
122 * - connTimeout : connection timeout per request
123 * - reqTimeout : post-connection timeout per request
124 * - usePipelining : whether to use HTTP pipelining if possible
125 * - maxConnsPerHost : maximum number of concurrent connections (per host)
126 * @return array $reqs With response array populated for each
129 public function runMulti( array $reqs, array $opts = array() ) {
130 $chm = $this->getCurlMulti();
132 // Normalize $reqs and add all of the required cURL handles...
134 foreach ( $reqs as $index => &$req ) {
135 $req['response'] = array(
138 'headers' => array(),
142 if ( isset( $req[0] ) ) {
143 $req['method'] = $req[0]; // short-form
146 if ( isset( $req[1] ) ) {
147 $req['url'] = $req[1]; // short-form
150 if ( !isset( $req['method'] ) ) {
151 throw new Exception( "Request has no 'method' field set." );
152 } elseif ( !isset( $req['url'] ) ) {
153 throw new Exception( "Request has no 'url' field set." );
155 $req['query'] = isset( $req['query'] ) ?
$req['query'] : array();
156 $headers = array(); // normalized headers
157 if ( isset( $req['headers'] ) ) {
158 foreach ( $req['headers'] as $name => $value ) {
159 $headers[strtolower( $name )] = $value;
162 $req['headers'] = $headers;
163 if ( !isset( $req['body'] ) ) {
165 $req['headers']['content-length'] = 0;
167 $handles[$index] = $this->getCurlHandle( $req, $opts );
168 if ( count( $reqs ) > 1 ) {
169 // https://github.com/guzzle/guzzle/issues/349
170 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE
, true );
173 unset( $req ); // don't assign over this by accident
175 $indexes = array_keys( $reqs );
176 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
177 if ( isset( $opts['usePipelining'] ) ) {
178 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$opts['usePipelining'] );
180 if ( isset( $opts['maxConnsPerHost'] ) ) {
181 // Keep these sockets around as they may be needed later in the request
182 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$opts['maxConnsPerHost'] );
186 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
187 $batches = array_chunk( $indexes, $this->maxConnsPerHost
);
189 foreach ( $batches as $batch ) {
190 // Attach all cURL handles for this batch
191 foreach ( $batch as $index ) {
192 curl_multi_add_handle( $chm, $handles[$index] );
194 // Execute the cURL handles concurrently...
195 $active = null; // handles still being processed
197 // Do any available work...
199 $mrc = curl_multi_exec( $chm, $active );
200 } while ( $mrc == CURLM_CALL_MULTI_PERFORM
);
201 // Wait (if possible) for available work...
202 if ( $active > 0 && $mrc == CURLM_OK
) {
203 if ( curl_multi_select( $chm, 10 ) == -1 ) {
204 // PHP bug 63411; http://curl.haxx.se/libcurl/c/curl_multi_fdset.html
205 usleep( 5000 ); // 5ms
208 } while ( $active > 0 && $mrc == CURLM_OK
);
211 // Remove all of the added cURL handles and check for errors...
212 foreach ( $reqs as $index => &$req ) {
213 $ch = $handles[$index];
214 curl_multi_remove_handle( $chm, $ch );
215 if ( curl_errno( $ch ) !== 0 ) {
216 $req['response']['error'] = "(curl error: " .
217 curl_errno( $ch ) . ") " . curl_error( $ch );
219 // For convenience with the list() operator
220 $req['response'][0] = $req['response']['code'];
221 $req['response'][1] = $req['response']['reason'];
222 $req['response'][2] = $req['response']['headers'];
223 $req['response'][3] = $req['response']['body'];
224 $req['response'][4] = $req['response']['error'];
226 // Close any string wrapper file handles
227 if ( isset( $req['_closeHandle'] ) ) {
228 fclose( $req['_closeHandle'] );
229 unset( $req['_closeHandle'] );
232 unset( $req ); // don't assign over this by accident
234 // Restore the default settings
235 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
236 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
237 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
244 * @param array $req HTTP request map
246 * - connTimeout : default connection timeout
247 * - reqTimeout : default request timeout
251 protected function getCurlHandle( array &$req, array $opts = array() ) {
254 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT
,
255 isset( $opts['connTimeout'] ) ?
$opts['connTimeout'] : $this->connTimeout
);
256 curl_setopt( $ch, CURLOPT_TIMEOUT
,
257 isset( $opts['reqTimeout'] ) ?
$opts['reqTimeout'] : $this->reqTimeout
);
258 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION
, 1 );
259 curl_setopt( $ch, CURLOPT_MAXREDIRS
, 4 );
260 curl_setopt( $ch, CURLOPT_HEADER
, 0 );
261 if ( !is_null( $this->caBundlePath
) ) {
262 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER
, true );
263 curl_setopt( $ch, CURLOPT_CAINFO
, $this->caBundlePath
);
265 curl_setopt( $ch, CURLOPT_RETURNTRANSFER
, 1 );
268 // PHP_QUERY_RFC3986 is PHP 5.4+ only
269 $query = str_replace(
272 http_build_query( $req['query'], '', '&' )
274 if ( $query != '' ) {
275 $url .= strpos( $req['url'], '?' ) === false ?
"?$query" : "&$query";
277 curl_setopt( $ch, CURLOPT_URL
, $url );
279 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST
, $req['method'] );
280 if ( $req['method'] === 'HEAD' ) {
281 curl_setopt( $ch, CURLOPT_NOBODY
, 1 );
284 if ( $req['method'] === 'PUT' ) {
285 curl_setopt( $ch, CURLOPT_PUT
, 1 );
286 if ( is_resource( $req['body'] ) ) {
287 curl_setopt( $ch, CURLOPT_INFILE
, $req['body'] );
288 if ( isset( $req['headers']['content-length'] ) ) {
289 curl_setopt( $ch, CURLOPT_INFILESIZE
, $req['headers']['content-length'] );
290 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
291 $req['headers']['transfer-encoding'] === 'chunks'
293 curl_setopt( $ch, CURLOPT_UPLOAD
, true );
295 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
297 } elseif ( $req['body'] !== '' ) {
298 $fp = fopen( "php://temp", "wb+" );
299 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
301 curl_setopt( $ch, CURLOPT_INFILE
, $fp );
302 curl_setopt( $ch, CURLOPT_INFILESIZE
, strlen( $req['body'] ) );
303 $req['_closeHandle'] = $fp; // remember to close this later
305 curl_setopt( $ch, CURLOPT_INFILESIZE
, 0 );
307 curl_setopt( $ch, CURLOPT_READFUNCTION
,
308 function ( $ch, $fd, $length ) {
309 $data = fread( $fd, $length );
310 $len = strlen( $data );
314 } elseif ( $req['method'] === 'POST' ) {
315 curl_setopt( $ch, CURLOPT_POST
, 1 );
316 curl_setopt( $ch, CURLOPT_POSTFIELDS
, $req['body'] );
318 if ( is_resource( $req['body'] ) ||
$req['body'] !== '' ) {
319 throw new Exception( "HTTP body specified for a non PUT/POST request." );
321 $req['headers']['content-length'] = 0;
325 foreach ( $req['headers'] as $name => $value ) {
326 if ( strpos( $name, ': ' ) ) {
327 throw new Exception( "Headers cannot have ':' in the name." );
329 $headers[] = $name . ': ' . trim( $value );
331 curl_setopt( $ch, CURLOPT_HTTPHEADER
, $headers );
333 curl_setopt( $ch, CURLOPT_HEADERFUNCTION
,
334 function ( $ch, $header ) use ( &$req ) {
335 $length = strlen( $header );
337 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
338 $req['response']['code'] = (int)$matches[2];
339 $req['response']['reason'] = trim( $matches[3] );
342 if ( strpos( $header, ":" ) === false ) {
345 list( $name, $value ) = explode( ":", $header, 2 );
346 $req['response']['headers'][strtolower( $name )] = trim( $value );
351 if ( isset( $req['stream'] ) ) {
352 // Don't just use CURLOPT_FILE as that might give:
353 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
354 // The callback here handles both normal files and php://temp handles.
355 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
356 function ( $ch, $data ) use ( &$req ) {
357 return fwrite( $req['stream'], $data );
361 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
362 function ( $ch, $data ) use ( &$req ) {
363 $req['response']['body'] .= $data;
364 return strlen( $data );
375 protected function getCurlMulti() {
376 if ( !$this->multiHandle
) {
377 $cmh = curl_multi_init();
378 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
379 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
380 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
382 $this->multiHandle
= $cmh;
384 return $this->multiHandle
;
387 function __destruct() {
388 if ( $this->multiHandle
) {
389 curl_multi_close( $this->multiHandle
);