Merge "Increase $wgSVGMaxSize to 5120 pixels wide (previously 2048)."
[lhc/web/wiklou.git] / includes / libs / MultiHttpClient.php
1 <?php
2 /**
3 * HTTP service client
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * Class to handle concurrent HTTP requests
25 *
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'.
39 *
40 * @author Aaron Schulz
41 * @since 1.23
42 */
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;
58
59 /**
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 * @throws Exception
67 */
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 );
73 }
74 }
75 static $opts = array( 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost', 'proxy' );
76 foreach ( $opts as $key ) {
77 if ( isset( $options[$key] ) ) {
78 $this->$key = $options[$key];
79 }
80 }
81 }
82
83 /**
84 * Execute an HTTP(S) request
85 *
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 * @endcode
96 * @param array $req HTTP request array
97 * @param array $opts
98 * - connTimeout : connection timeout per request (seconds)
99 * - reqTimeout : post-connection timeout per request (seconds)
100 * @return array Response array for request
101 */
102 final public function run( array $req, array $opts = array() ) {
103 $req = $this->runMulti( array( $req ), $opts );
104 return $req[0]['response'];
105 }
106
107 /**
108 * Execute a set of HTTP(S) requests concurrently
109 *
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 * @endcode
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.
123 *
124 * @param array $reqs Map of HTTP request arrays
125 * @param array $opts
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
131 * @throws Exception
132 */
133 public function runMulti( array $reqs, array $opts = array() ) {
134 $chm = $this->getCurlMulti();
135
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' => ''
145 );
146 if ( isset( $req[0] ) ) {
147 $req['method'] = $req[0]; // short-form
148 unset( $req[0] );
149 }
150 if ( isset( $req[1] ) ) {
151 $req['url'] = $req[1]; // short-form
152 unset( $req[1] );
153 }
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." );
158 }
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;
164 }
165 }
166 $req['headers'] = $headers;
167 if ( !isset( $req['body'] ) ) {
168 $req['body'] = '';
169 $req['headers']['content-length'] = 0;
170 }
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 );
175 }
176 }
177 unset( $req ); // don't assign over this by accident
178
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'] );
183 }
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'] );
187 }
188 }
189
190 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
191 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
192 $infos = array();
193
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] );
198 }
199 // Execute the cURL handles concurrently...
200 $active = null; // handles still being processed
201 do {
202 // Do any available work...
203 do {
204 $mrc = curl_multi_exec( $chm, $active );
205 $info = curl_multi_info_read( $chm );
206 if ( $info !== false ) {
207 $infos[(int)$info['handle']] = $info;
208 }
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
215 }
216 }
217 } while ( $active > 0 && $mrc == CURLM_OK );
218 }
219
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 );
224
225 $info = $infos[(int)$ch];
226
227 $errno = $info['result'];
228 if ( $errno !== 0 ) {
229 $req['response']['error'] = "(curl error: $errno)";
230
231 if ( function_exists( 'curl_strerror' ) ) {
232 $req['response']['error'] .= " " . curl_strerror( $errno );
233 }
234 }
235
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'];
242 curl_close( $ch );
243 // Close any string wrapper file handles
244 if ( isset( $req['_closeHandle'] ) ) {
245 fclose( $req['_closeHandle'] );
246 unset( $req['_closeHandle'] );
247 }
248 }
249 unset( $req ); // don't assign over this by accident
250
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 );
255 }
256
257 return $reqs;
258 }
259
260 /**
261 * @param array $req HTTP request map
262 * @param array $opts
263 * - connTimeout : default connection timeout
264 * - reqTimeout : default request timeout
265 * @return resource
266 * @throws Exception
267 */
268 protected function getCurlHandle( array &$req, array $opts = array() ) {
269 $ch = curl_init();
270
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 );
282 }
283 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
284
285 $url = $req['url'];
286 // PHP_QUERY_RFC3986 is PHP 5.4+ only
287 $query = str_replace(
288 array( '+', '%7E' ),
289 array( '%20', '~' ),
290 http_build_query( $req['query'], '', '&' )
291 );
292 if ( $query != '' ) {
293 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
294 }
295 curl_setopt( $ch, CURLOPT_URL, $url );
296
297 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
298 if ( $req['method'] === 'HEAD' ) {
299 curl_setopt( $ch, CURLOPT_NOBODY, 1 );
300 }
301
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'
310 ) {
311 curl_setopt( $ch, CURLOPT_UPLOAD, true );
312 } else {
313 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
314 }
315 } elseif ( $req['body'] !== '' ) {
316 $fp = fopen( "php://temp", "wb+" );
317 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
318 rewind( $fp );
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
322 } else {
323 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
324 }
325 curl_setopt( $ch, CURLOPT_READFUNCTION,
326 function ( $ch, $fd, $length ) {
327 $data = fread( $fd, $length );
328 $len = strlen( $data );
329 return $data;
330 }
331 );
332 } elseif ( $req['method'] === 'POST' ) {
333 curl_setopt( $ch, CURLOPT_POST, 1 );
334 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
335 } else {
336 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
337 throw new Exception( "HTTP body specified for a non PUT/POST request." );
338 }
339 $req['headers']['content-length'] = 0;
340 }
341
342 $headers = array();
343 foreach ( $req['headers'] as $name => $value ) {
344 if ( strpos( $name, ': ' ) ) {
345 throw new Exception( "Headers cannot have ':' in the name." );
346 }
347 $headers[] = $name . ': ' . trim( $value );
348 }
349 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
350
351 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
352 function ( $ch, $header ) use ( &$req ) {
353 $length = strlen( $header );
354 $matches = array();
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] );
358 return $length;
359 }
360 if ( strpos( $header, ":" ) === false ) {
361 return $length;
362 }
363 list( $name, $value ) = explode( ":", $header, 2 );
364 $req['response']['headers'][strtolower( $name )] = trim( $value );
365 return $length;
366 }
367 );
368
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 );
376 }
377 );
378 } else {
379 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
380 function ( $ch, $data ) use ( &$req ) {
381 $req['response']['body'] .= $data;
382 return strlen( $data );
383 }
384 );
385 }
386
387 return $ch;
388 }
389
390 /**
391 * @return resource
392 */
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 );
399 }
400 $this->multiHandle = $cmh;
401 }
402 return $this->multiHandle;
403 }
404
405 function __destruct() {
406 if ( $this->multiHandle ) {
407 curl_multi_close( $this->multiHandle );
408 }
409 }
410 }