Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / libs / MultiHttpClient.php
blobfb2daa691459e15f68961628dd76afc7f53ff44d
1 <?php
2 /**
3 * HTTP service client
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
20 * @file
23 /**
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
41 * @since 1.23
43 class MultiHttpClient {
44 /** @var resource */
45 protected $multiHandle = null; // curl_multi handle
46 /** @var string|null SSL certificates path */
47 protected $caBundlePath;
48 /** @var integer */
49 protected $connTimeout = 10;
50 /** @var integer */
51 protected $reqTimeout = 300;
52 /** @var bool */
53 protected $usePipelining = false;
54 /** @var integer */
55 protected $maxConnsPerHost = 50;
56 /** @var string|null proxy */
57 protected $proxy;
59 /**
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)
66 * @throws Exception
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];
83 /**
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:
93 * <code>
94 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
95 * </code>
96 * @param array $req HTTP request array
97 * @param array $opts
98 * - connTimeout : connection timeout per request
99 * - reqTimeout : post-connection timeout per request
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:
117 * <code>
118 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
119 * </code>
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
125 * @param array $opts
126 * - connTimeout : connection timeout per request
127 * - reqTimeout : post-connection timeout per request
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
131 * @throws Exception
133 public function runMulti( array $reqs, array $opts = array() ) {
134 $chm = $this->getCurlMulti();
136 // Normalize $reqs and add all of the required cURL handles...
137 $handles = array();
138 foreach ( $reqs as $index => &$req ) {
139 $req['response'] = array(
140 'code' => 0,
141 'reason' => '',
142 'headers' => array(),
143 'body' => '',
144 'error' => ''
146 if ( isset( $req[0] ) ) {
147 $req['method'] = $req[0]; // short-form
148 unset( $req[0] );
150 if ( isset( $req[1] ) ) {
151 $req['url'] = $req[1]; // short-form
152 unset( $req[1] );
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'] ) ) {
168 $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 );
193 foreach ( $batches as $batch ) {
194 // Attach all cURL handles for this batch
195 foreach ( $batch as $index ) {
196 curl_multi_add_handle( $chm, $handles[$index] );
198 // Execute the cURL handles concurrently...
199 $active = null; // handles still being processed
200 do {
201 // Do any available work...
202 do {
203 $mrc = curl_multi_exec( $chm, $active );
204 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
205 // Wait (if possible) for available work...
206 if ( $active > 0 && $mrc == CURLM_OK ) {
207 if ( curl_multi_select( $chm, 10 ) == -1 ) {
208 // PHP bug 63411; http://curl.haxx.se/libcurl/c/curl_multi_fdset.html
209 usleep( 5000 ); // 5ms
212 } while ( $active > 0 && $mrc == CURLM_OK );
215 // Remove all of the added cURL handles and check for errors...
216 foreach ( $reqs as $index => &$req ) {
217 $ch = $handles[$index];
218 curl_multi_remove_handle( $chm, $ch );
219 if ( curl_errno( $ch ) !== 0 ) {
220 $req['response']['error'] = "(curl error: " .
221 curl_errno( $ch ) . ") " . curl_error( $ch );
223 // For convenience with the list() operator
224 $req['response'][0] = $req['response']['code'];
225 $req['response'][1] = $req['response']['reason'];
226 $req['response'][2] = $req['response']['headers'];
227 $req['response'][3] = $req['response']['body'];
228 $req['response'][4] = $req['response']['error'];
229 curl_close( $ch );
230 // Close any string wrapper file handles
231 if ( isset( $req['_closeHandle'] ) ) {
232 fclose( $req['_closeHandle'] );
233 unset( $req['_closeHandle'] );
236 unset( $req ); // don't assign over this by accident
238 // Restore the default settings
239 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
240 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
241 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
244 return $reqs;
248 * @param array $req HTTP request map
249 * @param array $opts
250 * - connTimeout : default connection timeout
251 * - reqTimeout : default request timeout
252 * @return resource
253 * @throws Exception
255 protected function getCurlHandle( array &$req, array $opts = array() ) {
256 $ch = curl_init();
258 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT,
259 isset( $opts['connTimeout'] ) ? $opts['connTimeout'] : $this->connTimeout );
260 curl_setopt( $ch, CURLOPT_PROXY, isset( $req['proxy'] ) ? $req['proxy'] : $this->proxy );
261 curl_setopt( $ch, CURLOPT_TIMEOUT,
262 isset( $opts['reqTimeout'] ) ? $opts['reqTimeout'] : $this->reqTimeout );
263 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
264 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
265 curl_setopt( $ch, CURLOPT_HEADER, 0 );
266 if ( !is_null( $this->caBundlePath ) ) {
267 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
268 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
270 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
272 $url = $req['url'];
273 // PHP_QUERY_RFC3986 is PHP 5.4+ only
274 $query = str_replace(
275 array( '+', '%7E' ),
276 array( '%20', '~' ),
277 http_build_query( $req['query'], '', '&' )
279 if ( $query != '' ) {
280 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
282 curl_setopt( $ch, CURLOPT_URL, $url );
284 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
285 if ( $req['method'] === 'HEAD' ) {
286 curl_setopt( $ch, CURLOPT_NOBODY, 1 );
289 if ( $req['method'] === 'PUT' ) {
290 curl_setopt( $ch, CURLOPT_PUT, 1 );
291 if ( is_resource( $req['body'] ) ) {
292 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
293 if ( isset( $req['headers']['content-length'] ) ) {
294 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
295 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
296 $req['headers']['transfer-encoding'] === 'chunks'
298 curl_setopt( $ch, CURLOPT_UPLOAD, true );
299 } else {
300 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
302 } elseif ( $req['body'] !== '' ) {
303 $fp = fopen( "php://temp", "wb+" );
304 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
305 rewind( $fp );
306 curl_setopt( $ch, CURLOPT_INFILE, $fp );
307 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
308 $req['_closeHandle'] = $fp; // remember to close this later
309 } else {
310 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
312 curl_setopt( $ch, CURLOPT_READFUNCTION,
313 function ( $ch, $fd, $length ) {
314 $data = fread( $fd, $length );
315 $len = strlen( $data );
316 return $data;
319 } elseif ( $req['method'] === 'POST' ) {
320 curl_setopt( $ch, CURLOPT_POST, 1 );
321 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
322 } else {
323 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
324 throw new Exception( "HTTP body specified for a non PUT/POST request." );
326 $req['headers']['content-length'] = 0;
329 $headers = array();
330 foreach ( $req['headers'] as $name => $value ) {
331 if ( strpos( $name, ': ' ) ) {
332 throw new Exception( "Headers cannot have ':' in the name." );
334 $headers[] = $name . ': ' . trim( $value );
336 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
338 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
339 function ( $ch, $header ) use ( &$req ) {
340 $length = strlen( $header );
341 $matches = array();
342 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
343 $req['response']['code'] = (int)$matches[2];
344 $req['response']['reason'] = trim( $matches[3] );
345 return $length;
347 if ( strpos( $header, ":" ) === false ) {
348 return $length;
350 list( $name, $value ) = explode( ":", $header, 2 );
351 $req['response']['headers'][strtolower( $name )] = trim( $value );
352 return $length;
356 if ( isset( $req['stream'] ) ) {
357 // Don't just use CURLOPT_FILE as that might give:
358 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
359 // The callback here handles both normal files and php://temp handles.
360 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
361 function ( $ch, $data ) use ( &$req ) {
362 return fwrite( $req['stream'], $data );
365 } else {
366 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
367 function ( $ch, $data ) use ( &$req ) {
368 $req['response']['body'] .= $data;
369 return strlen( $data );
374 return $ch;
378 * @return resource
380 protected function getCurlMulti() {
381 if ( !$this->multiHandle ) {
382 $cmh = curl_multi_init();
383 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
384 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
385 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
387 $this->multiHandle = $cmh;
389 return $this->multiHandle;
392 function __destruct() {
393 if ( $this->multiHandle ) {
394 curl_multi_close( $this->multiHandle );