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