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
62 * - reqTimeout : default request timeout
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)
67 public function __construct( array $options ) {
68 if ( isset( $options['caBundlePath'] ) ) {
69 $this->caBundlePath
= $options['caBundlePath'];
70 if ( !file_exists( $this->caBundlePath
) ) {
71 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath
);
74 static $opts = array( 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost', 'proxy' );
75 foreach ( $opts as $key ) {
76 if ( isset( $options[$key] ) ) {
77 $this->$key = $options[$key];
83 * Execute an HTTP(S) request
85 * This method returns a response map of:
86 * - code : HTTP response code or 0 if there was a serious cURL error
87 * - reason : HTTP response reason (empty if there was a serious cURL error)
88 * - headers : <header name/value associative array>
89 * - body : HTTP response body or resource (if "stream" was set)
90 * - error : Any cURL error string
91 * The map also stores integer-indexed copies of these values. This lets callers do:
93 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
95 * @param array $req HTTP request array
97 * - connTimeout : connection timeout per request
98 * - reqTimeout : post-connection timeout per request
99 * @return array Response array for request
101 final public function run( array $req, array $opts = array() ) {
102 $req = $this->runMulti( array( $req ), $opts );
103 return $req[0]['response'];
107 * Execute a set of HTTP(S) requests concurrently
109 * The maps are returned by this method with the 'response' field set to a map of:
110 * - code : HTTP response code or 0 if there was a serious cURL error
111 * - reason : HTTP response reason (empty if there was a serious cURL error)
112 * - headers : <header name/value associative array>
113 * - body : HTTP response body or resource (if "stream" was set)
114 * - error : Any cURL error string
115 * The map also stores integer-indexed copies of these values. This lets callers do:
117 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
119 * All headers in the 'headers' field are normalized to use lower case names.
120 * This is true for the request headers and the response headers. Integer-indexed
121 * method/URL entries will also be changed to use the corresponding string keys.
123 * @param array $reqs Map of HTTP request arrays
125 * - connTimeout : connection timeout per request
126 * - reqTimeout : post-connection timeout per request
127 * - usePipelining : whether to use HTTP pipelining if possible
128 * - maxConnsPerHost : maximum number of concurrent connections (per host)
129 * @return array $reqs With response array populated for each
131 public function runMulti( array $reqs, array $opts = array() ) {
132 $chm = $this->getCurlMulti();
134 // Normalize $reqs and add all of the required cURL handles...
136 foreach ( $reqs as $index => &$req ) {
137 $req['response'] = array(
140 'headers' => array(),
144 if ( isset( $req[0] ) ) {
145 $req['method'] = $req[0]; // short-form
148 if ( isset( $req[1] ) ) {
149 $req['url'] = $req[1]; // short-form
152 if ( !isset( $req['method'] ) ) {
153 throw new Exception( "Request has no 'method' field set." );
154 } elseif ( !isset( $req['url'] ) ) {
155 throw new Exception( "Request has no 'url' field set." );
157 $req['query'] = isset( $req['query'] ) ?
$req['query'] : array();
158 $headers = array(); // normalized headers
159 if ( isset( $req['headers'] ) ) {
160 foreach ( $req['headers'] as $name => $value ) {
161 $headers[strtolower( $name )] = $value;
164 $req['headers'] = $headers;
165 if ( !isset( $req['body'] ) ) {
167 $req['headers']['content-length'] = 0;
169 $handles[$index] = $this->getCurlHandle( $req, $opts );
170 if ( count( $reqs ) > 1 ) {
171 // https://github.com/guzzle/guzzle/issues/349
172 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE
, true );
175 unset( $req ); // don't assign over this by accident
177 $indexes = array_keys( $reqs );
178 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
179 if ( isset( $opts['usePipelining'] ) ) {
180 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$opts['usePipelining'] );
182 if ( isset( $opts['maxConnsPerHost'] ) ) {
183 // Keep these sockets around as they may be needed later in the request
184 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$opts['maxConnsPerHost'] );
188 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
189 $batches = array_chunk( $indexes, $this->maxConnsPerHost
);
191 foreach ( $batches as $batch ) {
192 // Attach all cURL handles for this batch
193 foreach ( $batch as $index ) {
194 curl_multi_add_handle( $chm, $handles[$index] );
196 // Execute the cURL handles concurrently...
197 $active = null; // handles still being processed
199 // Do any available work...
201 $mrc = curl_multi_exec( $chm, $active );
202 } while ( $mrc == CURLM_CALL_MULTI_PERFORM
);
203 // Wait (if possible) for available work...
204 if ( $active > 0 && $mrc == CURLM_OK
) {
205 if ( curl_multi_select( $chm, 10 ) == -1 ) {
206 // PHP bug 63411; http://curl.haxx.se/libcurl/c/curl_multi_fdset.html
207 usleep( 5000 ); // 5ms
210 } while ( $active > 0 && $mrc == CURLM_OK
);
213 // Remove all of the added cURL handles and check for errors...
214 foreach ( $reqs as $index => &$req ) {
215 $ch = $handles[$index];
216 curl_multi_remove_handle( $chm, $ch );
217 if ( curl_errno( $ch ) !== 0 ) {
218 $req['response']['error'] = "(curl error: " .
219 curl_errno( $ch ) . ") " . curl_error( $ch );
221 // For convenience with the list() operator
222 $req['response'][0] = $req['response']['code'];
223 $req['response'][1] = $req['response']['reason'];
224 $req['response'][2] = $req['response']['headers'];
225 $req['response'][3] = $req['response']['body'];
226 $req['response'][4] = $req['response']['error'];
228 // Close any string wrapper file handles
229 if ( isset( $req['_closeHandle'] ) ) {
230 fclose( $req['_closeHandle'] );
231 unset( $req['_closeHandle'] );
234 unset( $req ); // don't assign over this by accident
236 // Restore the default settings
237 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
238 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
239 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
246 * @param array $req HTTP request map
248 * - connTimeout : default connection timeout
249 * - reqTimeout : default request timeout
252 protected function getCurlHandle( array &$req, array $opts = array() ) {
255 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT
,
256 isset( $opts['connTimeout'] ) ?
$opts['connTimeout'] : $this->connTimeout
);
257 curl_setopt( $ch, CURLOPT_PROXY
, isset( $req['proxy'] ) ?
$req['proxy'] : $this->proxy
);
258 curl_setopt( $ch, CURLOPT_TIMEOUT
,
259 isset( $opts['reqTimeout'] ) ?
$opts['reqTimeout'] : $this->reqTimeout
);
260 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION
, 1 );
261 curl_setopt( $ch, CURLOPT_MAXREDIRS
, 4 );
262 curl_setopt( $ch, CURLOPT_HEADER
, 0 );
263 if ( !is_null( $this->caBundlePath
) ) {
264 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER
, true );
265 curl_setopt( $ch, CURLOPT_CAINFO
, $this->caBundlePath
);
267 curl_setopt( $ch, CURLOPT_RETURNTRANSFER
, 1 );
270 // PHP_QUERY_RFC3986 is PHP 5.4+ only
271 $query = str_replace(
274 http_build_query( $req['query'], '', '&' )
276 if ( $query != '' ) {
277 $url .= strpos( $req['url'], '?' ) === false ?
"?$query" : "&$query";
279 curl_setopt( $ch, CURLOPT_URL
, $url );
281 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST
, $req['method'] );
282 if ( $req['method'] === 'HEAD' ) {
283 curl_setopt( $ch, CURLOPT_NOBODY
, 1 );
286 if ( $req['method'] === 'PUT' ) {
287 curl_setopt( $ch, CURLOPT_PUT
, 1 );
288 if ( is_resource( $req['body'] ) ) {
289 curl_setopt( $ch, CURLOPT_INFILE
, $req['body'] );
290 if ( isset( $req['headers']['content-length'] ) ) {
291 curl_setopt( $ch, CURLOPT_INFILESIZE
, $req['headers']['content-length'] );
292 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
293 $req['headers']['transfer-encoding'] === 'chunks'
295 curl_setopt( $ch, CURLOPT_UPLOAD
, true );
297 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
299 } elseif ( $req['body'] !== '' ) {
300 $fp = fopen( "php://temp", "wb+" );
301 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
303 curl_setopt( $ch, CURLOPT_INFILE
, $fp );
304 curl_setopt( $ch, CURLOPT_INFILESIZE
, strlen( $req['body'] ) );
305 $req['_closeHandle'] = $fp; // remember to close this later
307 curl_setopt( $ch, CURLOPT_INFILESIZE
, 0 );
309 curl_setopt( $ch, CURLOPT_READFUNCTION
,
310 function ( $ch, $fd, $length ) {
311 $data = fread( $fd, $length );
312 $len = strlen( $data );
316 } elseif ( $req['method'] === 'POST' ) {
317 curl_setopt( $ch, CURLOPT_POST
, 1 );
318 curl_setopt( $ch, CURLOPT_POSTFIELDS
, $req['body'] );
320 if ( is_resource( $req['body'] ) ||
$req['body'] !== '' ) {
321 throw new Exception( "HTTP body specified for a non PUT/POST request." );
323 $req['headers']['content-length'] = 0;
327 foreach ( $req['headers'] as $name => $value ) {
328 if ( strpos( $name, ': ' ) ) {
329 throw new Exception( "Headers cannot have ':' in the name." );
331 $headers[] = $name . ': ' . trim( $value );
333 curl_setopt( $ch, CURLOPT_HTTPHEADER
, $headers );
335 curl_setopt( $ch, CURLOPT_HEADERFUNCTION
,
336 function ( $ch, $header ) use ( &$req ) {
337 $length = strlen( $header );
339 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
340 $req['response']['code'] = (int)$matches[2];
341 $req['response']['reason'] = trim( $matches[3] );
344 if ( strpos( $header, ":" ) === false ) {
347 list( $name, $value ) = explode( ":", $header, 2 );
348 $req['response']['headers'][strtolower( $name )] = trim( $value );
353 if ( isset( $req['stream'] ) ) {
354 // Don't just use CURLOPT_FILE as that might give:
355 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
356 // The callback here handles both normal files and php://temp handles.
357 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
358 function ( $ch, $data ) use ( &$req ) {
359 return fwrite( $req['stream'], $data );
363 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
364 function ( $ch, $data ) use ( &$req ) {
365 $req['response']['body'] .= $data;
366 return strlen( $data );
377 protected function getCurlMulti() {
378 if ( !$this->multiHandle
) {
379 $cmh = curl_multi_init();
380 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
381 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
382 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
384 $this->multiHandle
= $cmh;
386 return $this->multiHandle
;
389 function __destruct() {
390 if ( $this->multiHandle
) {
391 curl_multi_close( $this->multiHandle
);