Merge "Add comment to ChangesList::showCharacterDifference"
[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 * - flags : map of boolean flags which supports:
39 * - relayResponseHeaders : write out header via header()
40 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
41 *
42 * @author Aaron Schulz
43 * @since 1.23
44 */
45 class MultiHttpClient {
46 /** @var resource */
47 protected $multiHandle = null; // curl_multi handle
48 /** @var string|null SSL certificates path */
49 protected $caBundlePath;
50 /** @var integer */
51 protected $connTimeout = 10;
52 /** @var integer */
53 protected $reqTimeout = 300;
54 /** @var bool */
55 protected $usePipelining = false;
56 /** @var integer */
57 protected $maxConnsPerHost = 50;
58 /** @var string|null proxy */
59 protected $proxy;
60 /** @var string */
61 protected $userAgent = 'wikimedia/multi-http-client v1.0';
62
63 /**
64 * @param array $options
65 * - connTimeout : default connection timeout (seconds)
66 * - reqTimeout : default request timeout (seconds)
67 * - proxy : HTTP proxy to use
68 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
69 * - maxConnsPerHost : maximum number of concurrent connections (per host)
70 * - userAgent : The User-Agent header value to send
71 * @throws Exception
72 */
73 public function __construct( array $options ) {
74 if ( isset( $options['caBundlePath'] ) ) {
75 $this->caBundlePath = $options['caBundlePath'];
76 if ( !file_exists( $this->caBundlePath ) ) {
77 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
78 }
79 }
80 static $opts = [
81 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost', 'proxy', 'userAgent'
82 ];
83 foreach ( $opts as $key ) {
84 if ( isset( $options[$key] ) ) {
85 $this->$key = $options[$key];
86 }
87 }
88 }
89
90 /**
91 * Execute an HTTP(S) request
92 *
93 * This method returns a response map of:
94 * - code : HTTP response code or 0 if there was a serious cURL error
95 * - reason : HTTP response reason (empty if there was a serious cURL error)
96 * - headers : <header name/value associative array>
97 * - body : HTTP response body or resource (if "stream" was set)
98 * - error : Any cURL error string
99 * The map also stores integer-indexed copies of these values. This lets callers do:
100 * @code
101 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
102 * @endcode
103 * @param array $req HTTP request array
104 * @param array $opts
105 * - connTimeout : connection timeout per request (seconds)
106 * - reqTimeout : post-connection timeout per request (seconds)
107 * @return array Response array for request
108 */
109 public function run( array $req, array $opts = [] ) {
110 return $this->runMulti( [ $req ], $opts )[0]['response'];
111 }
112
113 /**
114 * Execute a set of HTTP(S) requests concurrently
115 *
116 * The maps are returned by this method with the 'response' field set to a map of:
117 * - code : HTTP response code or 0 if there was a serious cURL error
118 * - reason : HTTP response reason (empty if there was a serious cURL error)
119 * - headers : <header name/value associative array>
120 * - body : HTTP response body or resource (if "stream" was set)
121 * - error : Any cURL error string
122 * The map also stores integer-indexed copies of these values. This lets callers do:
123 * @code
124 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
125 * @endcode
126 * All headers in the 'headers' field are normalized to use lower case names.
127 * This is true for the request headers and the response headers. Integer-indexed
128 * method/URL entries will also be changed to use the corresponding string keys.
129 *
130 * @param array $reqs Map of HTTP request arrays
131 * @param array $opts
132 * - connTimeout : connection timeout per request (seconds)
133 * - reqTimeout : post-connection timeout per request (seconds)
134 * - usePipelining : whether to use HTTP pipelining if possible
135 * - maxConnsPerHost : maximum number of concurrent connections (per host)
136 * @return array $reqs With response array populated for each
137 * @throws Exception
138 */
139 public function runMulti( array $reqs, array $opts = [] ) {
140 $chm = $this->getCurlMulti();
141
142 // Normalize $reqs and add all of the required cURL handles...
143 $handles = [];
144 foreach ( $reqs as $index => &$req ) {
145 $req['response'] = [
146 'code' => 0,
147 'reason' => '',
148 'headers' => [],
149 'body' => '',
150 'error' => ''
151 ];
152 if ( isset( $req[0] ) ) {
153 $req['method'] = $req[0]; // short-form
154 unset( $req[0] );
155 }
156 if ( isset( $req[1] ) ) {
157 $req['url'] = $req[1]; // short-form
158 unset( $req[1] );
159 }
160 if ( !isset( $req['method'] ) ) {
161 throw new Exception( "Request has no 'method' field set." );
162 } elseif ( !isset( $req['url'] ) ) {
163 throw new Exception( "Request has no 'url' field set." );
164 }
165 $req['query'] = isset( $req['query'] ) ? $req['query'] : [];
166 $headers = []; // normalized headers
167 if ( isset( $req['headers'] ) ) {
168 foreach ( $req['headers'] as $name => $value ) {
169 $headers[strtolower( $name )] = $value;
170 }
171 }
172 $req['headers'] = $headers;
173 if ( !isset( $req['body'] ) ) {
174 $req['body'] = '';
175 $req['headers']['content-length'] = 0;
176 }
177 $req['flags'] = isset( $req['flags'] ) ? $req['flags'] : [];
178 $handles[$index] = $this->getCurlHandle( $req, $opts );
179 if ( count( $reqs ) > 1 ) {
180 // https://github.com/guzzle/guzzle/issues/349
181 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
182 }
183 }
184 unset( $req ); // don't assign over this by accident
185
186 $indexes = array_keys( $reqs );
187 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
188 if ( isset( $opts['usePipelining'] ) ) {
189 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
190 }
191 if ( isset( $opts['maxConnsPerHost'] ) ) {
192 // Keep these sockets around as they may be needed later in the request
193 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
194 }
195 }
196
197 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
198 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
199 $infos = [];
200
201 foreach ( $batches as $batch ) {
202 // Attach all cURL handles for this batch
203 foreach ( $batch as $index ) {
204 curl_multi_add_handle( $chm, $handles[$index] );
205 }
206 // Execute the cURL handles concurrently...
207 $active = null; // handles still being processed
208 do {
209 // Do any available work...
210 do {
211 $mrc = curl_multi_exec( $chm, $active );
212 $info = curl_multi_info_read( $chm );
213 if ( $info !== false ) {
214 $infos[(int)$info['handle']] = $info;
215 }
216 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
217 // Wait (if possible) for available work...
218 if ( $active > 0 && $mrc == CURLM_OK ) {
219 if ( curl_multi_select( $chm, 10 ) == -1 ) {
220 // PHP bug 63411; http://curl.haxx.se/libcurl/c/curl_multi_fdset.html
221 usleep( 5000 ); // 5ms
222 }
223 }
224 } while ( $active > 0 && $mrc == CURLM_OK );
225 }
226
227 // Remove all of the added cURL handles and check for errors...
228 foreach ( $reqs as $index => &$req ) {
229 $ch = $handles[$index];
230 curl_multi_remove_handle( $chm, $ch );
231
232 if ( isset( $infos[(int)$ch] ) ) {
233 $info = $infos[(int)$ch];
234 $errno = $info['result'];
235 if ( $errno !== 0 ) {
236 $req['response']['error'] = "(curl error: $errno)";
237 if ( function_exists( 'curl_strerror' ) ) {
238 $req['response']['error'] .= " " . curl_strerror( $errno );
239 }
240 }
241 } else {
242 $req['response']['error'] = "(curl error: no status set)";
243 }
244
245 // For convenience with the list() operator
246 $req['response'][0] = $req['response']['code'];
247 $req['response'][1] = $req['response']['reason'];
248 $req['response'][2] = $req['response']['headers'];
249 $req['response'][3] = $req['response']['body'];
250 $req['response'][4] = $req['response']['error'];
251 curl_close( $ch );
252 // Close any string wrapper file handles
253 if ( isset( $req['_closeHandle'] ) ) {
254 fclose( $req['_closeHandle'] );
255 unset( $req['_closeHandle'] );
256 }
257 }
258 unset( $req ); // don't assign over this by accident
259
260 // Restore the default settings
261 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
262 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
263 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
264 }
265
266 return $reqs;
267 }
268
269 /**
270 * @param array $req HTTP request map
271 * @param array $opts
272 * - connTimeout : default connection timeout
273 * - reqTimeout : default request timeout
274 * @return resource
275 * @throws Exception
276 */
277 protected function getCurlHandle( array &$req, array $opts = [] ) {
278 $ch = curl_init();
279
280 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT,
281 isset( $opts['connTimeout'] ) ? $opts['connTimeout'] : $this->connTimeout );
282 curl_setopt( $ch, CURLOPT_PROXY, isset( $req['proxy'] ) ? $req['proxy'] : $this->proxy );
283 curl_setopt( $ch, CURLOPT_TIMEOUT,
284 isset( $opts['reqTimeout'] ) ? $opts['reqTimeout'] : $this->reqTimeout );
285 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
286 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
287 curl_setopt( $ch, CURLOPT_HEADER, 0 );
288 if ( !is_null( $this->caBundlePath ) ) {
289 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
290 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
291 }
292 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
293
294 $url = $req['url'];
295 // PHP_QUERY_RFC3986 is PHP 5.4+ only
296 $query = str_replace(
297 [ '+', '%7E' ],
298 [ '%20', '~' ],
299 http_build_query( $req['query'], '', '&' )
300 );
301 if ( $query != '' ) {
302 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
303 }
304 curl_setopt( $ch, CURLOPT_URL, $url );
305
306 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
307 if ( $req['method'] === 'HEAD' ) {
308 curl_setopt( $ch, CURLOPT_NOBODY, 1 );
309 }
310
311 if ( $req['method'] === 'PUT' ) {
312 curl_setopt( $ch, CURLOPT_PUT, 1 );
313 if ( is_resource( $req['body'] ) ) {
314 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
315 if ( isset( $req['headers']['content-length'] ) ) {
316 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
317 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
318 $req['headers']['transfer-encoding'] === 'chunks'
319 ) {
320 curl_setopt( $ch, CURLOPT_UPLOAD, true );
321 } else {
322 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
323 }
324 } elseif ( $req['body'] !== '' ) {
325 $fp = fopen( "php://temp", "wb+" );
326 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
327 rewind( $fp );
328 curl_setopt( $ch, CURLOPT_INFILE, $fp );
329 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
330 $req['_closeHandle'] = $fp; // remember to close this later
331 } else {
332 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
333 }
334 curl_setopt( $ch, CURLOPT_READFUNCTION,
335 function ( $ch, $fd, $length ) {
336 $data = fread( $fd, $length );
337 $len = strlen( $data );
338 return $data;
339 }
340 );
341 } elseif ( $req['method'] === 'POST' ) {
342 curl_setopt( $ch, CURLOPT_POST, 1 );
343 // Don't interpret POST parameters starting with '@' as file uploads, because this
344 // makes it impossible to POST plain values starting with '@' (and causes security
345 // issues potentially exposing the contents of local files).
346 // The PHP manual says this option was introduced in PHP 5.5 defaults to true in PHP 5.6,
347 // but we support lower versions, and the option doesn't exist in HHVM 5.6.99.
348 if ( defined( 'CURLOPT_SAFE_UPLOAD' ) ) {
349 curl_setopt( $ch, CURLOPT_SAFE_UPLOAD, true );
350 } elseif ( is_array( $req['body'] ) ) {
351 // In PHP 5.2 and later, '@' is interpreted as a file upload if POSTFIELDS
352 // is an array, but not if it's a string. So convert $req['body'] to a string
353 // for safety.
354 $req['body'] = wfArrayToCgi( $req['body'] );
355 }
356 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
357 } else {
358 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
359 throw new Exception( "HTTP body specified for a non PUT/POST request." );
360 }
361 $req['headers']['content-length'] = 0;
362 }
363
364 if ( !isset( $req['headers']['user-agent'] ) ) {
365 $req['headers']['user-agent'] = $this->userAgent;
366 }
367
368 $headers = [];
369 foreach ( $req['headers'] as $name => $value ) {
370 if ( strpos( $name, ': ' ) ) {
371 throw new Exception( "Headers cannot have ':' in the name." );
372 }
373 $headers[] = $name . ': ' . trim( $value );
374 }
375 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
376
377 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
378 function ( $ch, $header ) use ( &$req ) {
379 if ( !empty( $req['flags']['relayResponseHeaders'] ) ) {
380 header( $header );
381 }
382 $length = strlen( $header );
383 $matches = [];
384 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
385 $req['response']['code'] = (int)$matches[2];
386 $req['response']['reason'] = trim( $matches[3] );
387 return $length;
388 }
389 if ( strpos( $header, ":" ) === false ) {
390 return $length;
391 }
392 list( $name, $value ) = explode( ":", $header, 2 );
393 $req['response']['headers'][strtolower( $name )] = trim( $value );
394 return $length;
395 }
396 );
397
398 if ( isset( $req['stream'] ) ) {
399 // Don't just use CURLOPT_FILE as that might give:
400 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
401 // The callback here handles both normal files and php://temp handles.
402 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
403 function ( $ch, $data ) use ( &$req ) {
404 return fwrite( $req['stream'], $data );
405 }
406 );
407 } else {
408 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
409 function ( $ch, $data ) use ( &$req ) {
410 $req['response']['body'] .= $data;
411 return strlen( $data );
412 }
413 );
414 }
415
416 return $ch;
417 }
418
419 /**
420 * @return resource
421 */
422 protected function getCurlMulti() {
423 if ( !$this->multiHandle ) {
424 $cmh = curl_multi_init();
425 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
426 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
427 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
428 }
429 $this->multiHandle = $cmh;
430 }
431 return $this->multiHandle;
432 }
433
434 function __destruct() {
435 if ( $this->multiHandle ) {
436 curl_multi_close( $this->multiHandle );
437 }
438 }
439 }