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)
66 * - userAgent : The User-Agent header value to send
69 public function __construct( array $options ) {
70 if ( isset( $options['caBundlePath'] ) ) {
71 $this->caBundlePath
= $options['caBundlePath'];
72 if ( !file_exists( $this->caBundlePath
) ) {
73 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath
);
77 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost', 'proxy', 'userAgent'
79 foreach ( $opts as $key ) {
80 if ( isset( $options[$key] ) ) {
81 $this->$key = $options[$key];
87 * Execute an HTTP(S) request
89 * This method returns a response map of:
90 * - code : HTTP response code or 0 if there was a serious cURL error
91 * - reason : HTTP response reason (empty if there was a serious cURL error)
92 * - headers : <header name/value associative array>
93 * - body : HTTP response body or resource (if "stream" was set)
94 * - error : Any cURL error string
95 * The map also stores integer-indexed copies of these values. This lets callers do:
97 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
99 * @param array $req HTTP request array
101 * - connTimeout : connection timeout per request (seconds)
102 * - reqTimeout : post-connection timeout per request (seconds)
103 * @return array Response array for request
105 final public function run( array $req, array $opts = array() ) {
106 $req = $this->runMulti( array( $req ), $opts );
107 return $req[0]['response'];
111 * Execute a set of HTTP(S) requests concurrently
113 * The maps are returned by this method with the 'response' field set to a map of:
114 * - code : HTTP response code or 0 if there was a serious cURL error
115 * - reason : HTTP response reason (empty if there was a serious cURL error)
116 * - headers : <header name/value associative array>
117 * - body : HTTP response body or resource (if "stream" was set)
118 * - error : Any cURL error string
119 * The map also stores integer-indexed copies of these values. This lets callers do:
121 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
123 * All headers in the 'headers' field are normalized to use lower case names.
124 * This is true for the request headers and the response headers. Integer-indexed
125 * method/URL entries will also be changed to use the corresponding string keys.
127 * @param array $reqs Map of HTTP request arrays
129 * - connTimeout : connection timeout per request (seconds)
130 * - reqTimeout : post-connection timeout per request (seconds)
131 * - usePipelining : whether to use HTTP pipelining if possible
132 * - maxConnsPerHost : maximum number of concurrent connections (per host)
133 * @return array $reqs With response array populated for each
136 public function runMulti( array $reqs, array $opts = array() ) {
137 $chm = $this->getCurlMulti();
139 // Normalize $reqs and add all of the required cURL handles...
141 foreach ( $reqs as $index => &$req ) {
142 $req['response'] = array(
145 'headers' => array(),
149 if ( isset( $req[0] ) ) {
150 $req['method'] = $req[0]; // short-form
153 if ( isset( $req[1] ) ) {
154 $req['url'] = $req[1]; // short-form
157 if ( !isset( $req['method'] ) ) {
158 throw new Exception( "Request has no 'method' field set." );
159 } elseif ( !isset( $req['url'] ) ) {
160 throw new Exception( "Request has no 'url' field set." );
162 $req['query'] = isset( $req['query'] ) ?
$req['query'] : array();
163 $headers = array(); // normalized headers
164 if ( isset( $req['headers'] ) ) {
165 foreach ( $req['headers'] as $name => $value ) {
166 $headers[strtolower( $name )] = $value;
169 $req['headers'] = $headers;
170 if ( !isset( $req['body'] ) ) {
172 $req['headers']['content-length'] = 0;
174 $handles[$index] = $this->getCurlHandle( $req, $opts );
175 if ( count( $reqs ) > 1 ) {
176 // https://github.com/guzzle/guzzle/issues/349
177 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE
, true );
180 unset( $req ); // don't assign over this by accident
182 $indexes = array_keys( $reqs );
183 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
184 if ( isset( $opts['usePipelining'] ) ) {
185 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$opts['usePipelining'] );
187 if ( isset( $opts['maxConnsPerHost'] ) ) {
188 // Keep these sockets around as they may be needed later in the request
189 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$opts['maxConnsPerHost'] );
193 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
194 $batches = array_chunk( $indexes, $this->maxConnsPerHost
);
197 foreach ( $batches as $batch ) {
198 // Attach all cURL handles for this batch
199 foreach ( $batch as $index ) {
200 curl_multi_add_handle( $chm, $handles[$index] );
202 // Execute the cURL handles concurrently...
203 $active = null; // handles still being processed
205 // Do any available work...
207 $mrc = curl_multi_exec( $chm, $active );
208 $info = curl_multi_info_read( $chm );
209 if ( $info !== false ) {
210 $infos[(int)$info['handle']] = $info;
212 } while ( $mrc == CURLM_CALL_MULTI_PERFORM
);
213 // Wait (if possible) for available work...
214 if ( $active > 0 && $mrc == CURLM_OK
) {
215 if ( curl_multi_select( $chm, 10 ) == -1 ) {
216 // PHP bug 63411; http://curl.haxx.se/libcurl/c/curl_multi_fdset.html
217 usleep( 5000 ); // 5ms
220 } while ( $active > 0 && $mrc == CURLM_OK
);
223 // Remove all of the added cURL handles and check for errors...
224 foreach ( $reqs as $index => &$req ) {
225 $ch = $handles[$index];
226 curl_multi_remove_handle( $chm, $ch );
228 if ( isset( $infos[(int)$ch] ) ) {
229 $info = $infos[(int)$ch];
230 $errno = $info['result'];
231 if ( $errno !== 0 ) {
232 $req['response']['error'] = "(curl error: $errno)";
233 if ( function_exists( 'curl_strerror' ) ) {
234 $req['response']['error'] .= " " . curl_strerror( $errno );
238 $req['response']['error'] = "(curl error: no status set)";
241 // For convenience with the list() operator
242 $req['response'][0] = $req['response']['code'];
243 $req['response'][1] = $req['response']['reason'];
244 $req['response'][2] = $req['response']['headers'];
245 $req['response'][3] = $req['response']['body'];
246 $req['response'][4] = $req['response']['error'];
248 // Close any string wrapper file handles
249 if ( isset( $req['_closeHandle'] ) ) {
250 fclose( $req['_closeHandle'] );
251 unset( $req['_closeHandle'] );
254 unset( $req ); // don't assign over this by accident
256 // Restore the default settings
257 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
258 curl_multi_setopt( $chm, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
259 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
266 * @param array $req HTTP request map
268 * - connTimeout : default connection timeout
269 * - reqTimeout : default request timeout
273 protected function getCurlHandle( array &$req, array $opts = array() ) {
276 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT
,
277 isset( $opts['connTimeout'] ) ?
$opts['connTimeout'] : $this->connTimeout
);
278 curl_setopt( $ch, CURLOPT_PROXY
, isset( $req['proxy'] ) ?
$req['proxy'] : $this->proxy
);
279 curl_setopt( $ch, CURLOPT_TIMEOUT
,
280 isset( $opts['reqTimeout'] ) ?
$opts['reqTimeout'] : $this->reqTimeout
);
281 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION
, 1 );
282 curl_setopt( $ch, CURLOPT_MAXREDIRS
, 4 );
283 curl_setopt( $ch, CURLOPT_HEADER
, 0 );
284 if ( !is_null( $this->caBundlePath
) ) {
285 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER
, true );
286 curl_setopt( $ch, CURLOPT_CAINFO
, $this->caBundlePath
);
288 curl_setopt( $ch, CURLOPT_RETURNTRANSFER
, 1 );
291 // PHP_QUERY_RFC3986 is PHP 5.4+ only
292 $query = str_replace(
295 http_build_query( $req['query'], '', '&' )
297 if ( $query != '' ) {
298 $url .= strpos( $req['url'], '?' ) === false ?
"?$query" : "&$query";
300 curl_setopt( $ch, CURLOPT_URL
, $url );
302 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST
, $req['method'] );
303 if ( $req['method'] === 'HEAD' ) {
304 curl_setopt( $ch, CURLOPT_NOBODY
, 1 );
307 if ( $req['method'] === 'PUT' ) {
308 curl_setopt( $ch, CURLOPT_PUT
, 1 );
309 if ( is_resource( $req['body'] ) ) {
310 curl_setopt( $ch, CURLOPT_INFILE
, $req['body'] );
311 if ( isset( $req['headers']['content-length'] ) ) {
312 curl_setopt( $ch, CURLOPT_INFILESIZE
, $req['headers']['content-length'] );
313 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
314 $req['headers']['transfer-encoding'] === 'chunks'
316 curl_setopt( $ch, CURLOPT_UPLOAD
, true );
318 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
320 } elseif ( $req['body'] !== '' ) {
321 $fp = fopen( "php://temp", "wb+" );
322 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
324 curl_setopt( $ch, CURLOPT_INFILE
, $fp );
325 curl_setopt( $ch, CURLOPT_INFILESIZE
, strlen( $req['body'] ) );
326 $req['_closeHandle'] = $fp; // remember to close this later
328 curl_setopt( $ch, CURLOPT_INFILESIZE
, 0 );
330 curl_setopt( $ch, CURLOPT_READFUNCTION
,
331 function ( $ch, $fd, $length ) {
332 $data = fread( $fd, $length );
333 $len = strlen( $data );
337 } elseif ( $req['method'] === 'POST' ) {
338 curl_setopt( $ch, CURLOPT_POST
, 1 );
339 curl_setopt( $ch, CURLOPT_POSTFIELDS
, $req['body'] );
341 if ( is_resource( $req['body'] ) ||
$req['body'] !== '' ) {
342 throw new Exception( "HTTP body specified for a non PUT/POST request." );
344 $req['headers']['content-length'] = 0;
347 if ( !isset( $req['headers']['user-agent'] ) ) {
348 $req['headers']['user-agent'] = self
::userAgent();
352 foreach ( $req['headers'] as $name => $value ) {
353 if ( strpos( $name, ': ' ) ) {
354 throw new Exception( "Headers cannot have ':' in the name." );
356 $headers[] = $name . ': ' . trim( $value );
358 curl_setopt( $ch, CURLOPT_HTTPHEADER
, $headers );
360 curl_setopt( $ch, CURLOPT_HEADERFUNCTION
,
361 function ( $ch, $header ) use ( &$req ) {
362 $length = strlen( $header );
364 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
365 $req['response']['code'] = (int)$matches[2];
366 $req['response']['reason'] = trim( $matches[3] );
369 if ( strpos( $header, ":" ) === false ) {
372 list( $name, $value ) = explode( ":", $header, 2 );
373 $req['response']['headers'][strtolower( $name )] = trim( $value );
378 if ( isset( $req['stream'] ) ) {
379 // Don't just use CURLOPT_FILE as that might give:
380 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
381 // The callback here handles both normal files and php://temp handles.
382 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
383 function ( $ch, $data ) use ( &$req ) {
384 return fwrite( $req['stream'], $data );
388 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
,
389 function ( $ch, $data ) use ( &$req ) {
390 $req['response']['body'] .= $data;
391 return strlen( $data );
402 protected function getCurlMulti() {
403 if ( !$this->multiHandle
) {
404 $cmh = curl_multi_init();
405 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
406 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING
, (int)$this->usePipelining
);
407 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS
, (int)$this->maxConnsPerHost
);
409 $this->multiHandle
= $cmh;
411 return $this->multiHandle
;
414 function __destruct() {
415 if ( $this->multiHandle
) {
416 curl_multi_close( $this->multiHandle
);
421 * The default User-Agent for requests.
424 public static function userAgent() {
425 return 'wikimedia/multi-http-client v1.0';