Merge "TOC: Add z-index: -1 to hidden checkbox"
[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 use MediaWiki\MediaWikiServices;
27
28 /**
29 * Class to handle multiple HTTP requests
30 *
31 * If curl is available, requests will be made concurrently.
32 * Otherwise, they will be made serially.
33 *
34 * HTTP request maps are arrays that use the following format:
35 * - method : GET/HEAD/PUT/POST/DELETE
36 * - url : HTTP/HTTPS URL
37 * - query : <query parameter field/value associative array> (uses RFC 3986)
38 * - headers : <header name/value associative array>
39 * - body : source to get the HTTP request body from;
40 * this can simply be a string (always), a resource for
41 * PUT requests, and a field/value array for POST request;
42 * array bodies are encoded as multipart/form-data and strings
43 * use application/x-www-form-urlencoded (headers sent automatically)
44 * - stream : resource to stream the HTTP response body to
45 * - proxy : HTTP proxy to use
46 * - flags : map of boolean flags which supports:
47 * - relayResponseHeaders : write out header via header()
48 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
49 *
50 * @since 1.23
51 */
52 class MultiHttpClient implements LoggerAwareInterface {
53 /** @var resource */
54 protected $multiHandle = null; // curl_multi handle
55 /** @var string|null SSL certificates path */
56 protected $caBundlePath;
57 /** @var float */
58 protected $connTimeout = 10;
59 /** @var float */
60 protected $reqTimeout = 300;
61 /** @var bool */
62 protected $usePipelining = false;
63 /** @var int */
64 protected $maxConnsPerHost = 50;
65 /** @var string|null proxy */
66 protected $proxy;
67 /** @var string */
68 protected $userAgent = 'wikimedia/multi-http-client v1.0';
69 /** @var LoggerInterface */
70 protected $logger;
71
72 // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
73 // timeouts are periodically polled instead of being accurately respected.
74 // The select timeout is set to the minimum timeout multiplied by this factor.
75 const TIMEOUT_ACCURACY_FACTOR = 0.1;
76
77 /**
78 * @param array $options
79 * - connTimeout : default connection timeout (seconds)
80 * - reqTimeout : default request timeout (seconds)
81 * - proxy : HTTP proxy to use
82 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
83 * - maxConnsPerHost : maximum number of concurrent connections (per host)
84 * - userAgent : The User-Agent header value to send
85 * - logger : a \Psr\Log\LoggerInterface instance for debug logging
86 * - caBundlePath : path to specific Certificate Authority bundle (if any)
87 * @throws Exception
88 */
89 public function __construct( array $options ) {
90 if ( isset( $options['caBundlePath'] ) ) {
91 $this->caBundlePath = $options['caBundlePath'];
92 if ( !file_exists( $this->caBundlePath ) ) {
93 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
94 }
95 }
96 static $opts = [
97 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost',
98 'proxy', 'userAgent', 'logger'
99 ];
100 foreach ( $opts as $key ) {
101 if ( isset( $options[$key] ) ) {
102 $this->$key = $options[$key];
103 }
104 }
105 if ( $this->logger === null ) {
106 $this->logger = new NullLogger;
107 }
108 }
109
110 /**
111 * Execute an HTTP(S) request
112 *
113 * This method returns a response map of:
114 * - code : HTTP response code or 0 if there was a serious error
115 * - reason : HTTP response reason (empty if there was a serious error)
116 * - headers : <header name/value associative array>
117 * - body : HTTP response body or resource (if "stream" was set)
118 * - error : Any error string
119 * The map also stores integer-indexed copies of these values. This lets callers do:
120 * @code
121 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
122 * @endcode
123 * @param array $req HTTP request array
124 * @param array $opts
125 * - connTimeout : connection timeout per request (seconds)
126 * - reqTimeout : post-connection timeout per request (seconds)
127 * @return array Response array for request
128 */
129 public function run( array $req, array $opts = [] ) {
130 return $this->runMulti( [ $req ], $opts )[0]['response'];
131 }
132
133 /**
134 * Execute a set of HTTP(S) requests.
135 *
136 * If curl is available, requests will be made concurrently.
137 * Otherwise, they will be made serially.
138 *
139 * The maps are returned by this method with the 'response' field set to a map of:
140 * - code : HTTP response code or 0 if there was a serious error
141 * - reason : HTTP response reason (empty if there was a serious error)
142 * - headers : <header name/value associative array>
143 * - body : HTTP response body or resource (if "stream" was set)
144 * - error : Any error string
145 * The map also stores integer-indexed copies of these values. This lets callers do:
146 * @code
147 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
148 * @endcode
149 * All headers in the 'headers' field are normalized to use lower case names.
150 * This is true for the request headers and the response headers. Integer-indexed
151 * method/URL entries will also be changed to use the corresponding string keys.
152 *
153 * @param array $reqs Map of HTTP request arrays
154 * @param array $opts
155 * - connTimeout : connection timeout per request (seconds)
156 * - reqTimeout : post-connection timeout per request (seconds)
157 * - usePipelining : whether to use HTTP pipelining if possible
158 * - maxConnsPerHost : maximum number of concurrent connections (per host)
159 * @return array $reqs With response array populated for each
160 * @throws Exception
161 */
162 public function runMulti( array $reqs, array $opts = [] ) {
163 $this->normalizeRequests( $reqs );
164 if ( $this->isCurlEnabled() ) {
165 return $this->runMultiCurl( $reqs, $opts );
166 } else {
167 return $this->runMultiHttp( $reqs, $opts );
168 }
169 }
170
171 /**
172 * Determines if the curl extension is available
173 *
174 * @return bool true if curl is available, false otherwise.
175 */
176 protected function isCurlEnabled() {
177 return extension_loaded( 'curl' );
178 }
179
180 /**
181 * Execute a set of HTTP(S) requests concurrently
182 *
183 * @see MultiHttpClient::runMulti()
184 *
185 * @param array $reqs Map of HTTP request arrays
186 * @param array $opts
187 * - connTimeout : connection timeout per request (seconds)
188 * - reqTimeout : post-connection timeout per request (seconds)
189 * - usePipelining : whether to use HTTP pipelining if possible
190 * - maxConnsPerHost : maximum number of concurrent connections (per host)
191 * @return array $reqs With response array populated for each
192 * @throws Exception
193 */
194 private function runMultiCurl( array $reqs, array $opts = [] ) {
195 $chm = $this->getCurlMulti();
196
197 $selectTimeout = $this->getSelectTimeout( $opts );
198
199 // Add all of the required cURL handles...
200 $handles = [];
201 foreach ( $reqs as $index => &$req ) {
202 $handles[$index] = $this->getCurlHandle( $req, $opts );
203 if ( count( $reqs ) > 1 ) {
204 // https://github.com/guzzle/guzzle/issues/349
205 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
206 }
207 }
208 unset( $req ); // don't assign over this by accident
209
210 $indexes = array_keys( $reqs );
211 if ( isset( $opts['usePipelining'] ) ) {
212 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
213 }
214 if ( isset( $opts['maxConnsPerHost'] ) ) {
215 // Keep these sockets around as they may be needed later in the request
216 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
217 }
218
219 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
220 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
221 $infos = [];
222
223 foreach ( $batches as $batch ) {
224 // Attach all cURL handles for this batch
225 foreach ( $batch as $index ) {
226 curl_multi_add_handle( $chm, $handles[$index] );
227 }
228 // Execute the cURL handles concurrently...
229 $active = null; // handles still being processed
230 do {
231 // Do any available work...
232 do {
233 $mrc = curl_multi_exec( $chm, $active );
234 $info = curl_multi_info_read( $chm );
235 if ( $info !== false ) {
236 $infos[(int)$info['handle']] = $info;
237 }
238 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
239 // Wait (if possible) for available work...
240 if ( $active > 0 && $mrc == CURLM_OK ) {
241 if ( curl_multi_select( $chm, $selectTimeout ) == -1 ) {
242 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
243 usleep( 5000 ); // 5ms
244 }
245 }
246 } while ( $active > 0 && $mrc == CURLM_OK );
247 }
248
249 // Remove all of the added cURL handles and check for errors...
250 foreach ( $reqs as $index => &$req ) {
251 $ch = $handles[$index];
252 curl_multi_remove_handle( $chm, $ch );
253
254 if ( isset( $infos[(int)$ch] ) ) {
255 $info = $infos[(int)$ch];
256 $errno = $info['result'];
257 if ( $errno !== 0 ) {
258 $req['response']['error'] = "(curl error: $errno)";
259 if ( function_exists( 'curl_strerror' ) ) {
260 $req['response']['error'] .= " " . curl_strerror( $errno );
261 }
262 $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
263 $req['response']['error'] );
264 }
265 } else {
266 $req['response']['error'] = "(curl error: no status set)";
267 }
268
269 // For convenience with the list() operator
270 $req['response'][0] = $req['response']['code'];
271 $req['response'][1] = $req['response']['reason'];
272 $req['response'][2] = $req['response']['headers'];
273 $req['response'][3] = $req['response']['body'];
274 $req['response'][4] = $req['response']['error'];
275 curl_close( $ch );
276 // Close any string wrapper file handles
277 if ( isset( $req['_closeHandle'] ) ) {
278 fclose( $req['_closeHandle'] );
279 unset( $req['_closeHandle'] );
280 }
281 }
282 unset( $req ); // don't assign over this by accident
283
284 // Restore the default settings
285 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
286 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
287
288 return $reqs;
289 }
290
291 /**
292 * @param array &$req HTTP request map
293 * @param array $opts
294 * - connTimeout : default connection timeout
295 * - reqTimeout : default request timeout
296 * @return resource
297 * @throws Exception
298 */
299 protected function getCurlHandle( array &$req, array $opts = [] ) {
300 $ch = curl_init();
301
302 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS,
303 ( $opts['connTimeout'] ?? $this->connTimeout ) * 1000 );
304 curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
305 curl_setopt( $ch, CURLOPT_TIMEOUT_MS,
306 ( $opts['reqTimeout'] ?? $this->reqTimeout ) * 1000 );
307 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
308 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
309 curl_setopt( $ch, CURLOPT_HEADER, 0 );
310 if ( !is_null( $this->caBundlePath ) ) {
311 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
312 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
313 }
314 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
315
316 $url = $req['url'];
317 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
318 if ( $query != '' ) {
319 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
320 }
321 curl_setopt( $ch, CURLOPT_URL, $url );
322
323 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
324 if ( $req['method'] === 'HEAD' ) {
325 curl_setopt( $ch, CURLOPT_NOBODY, 1 );
326 }
327
328 if ( $req['method'] === 'PUT' ) {
329 curl_setopt( $ch, CURLOPT_PUT, 1 );
330 if ( is_resource( $req['body'] ) ) {
331 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
332 if ( isset( $req['headers']['content-length'] ) ) {
333 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
334 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
335 $req['headers']['transfer-encoding'] === 'chunks'
336 ) {
337 curl_setopt( $ch, CURLOPT_UPLOAD, true );
338 } else {
339 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
340 }
341 } elseif ( $req['body'] !== '' ) {
342 $fp = fopen( "php://temp", "wb+" );
343 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
344 rewind( $fp );
345 curl_setopt( $ch, CURLOPT_INFILE, $fp );
346 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
347 $req['_closeHandle'] = $fp; // remember to close this later
348 } else {
349 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
350 }
351 curl_setopt( $ch, CURLOPT_READFUNCTION,
352 function ( $ch, $fd, $length ) {
353 $data = fread( $fd, $length );
354 $len = strlen( $data );
355 return $data;
356 }
357 );
358 } elseif ( $req['method'] === 'POST' ) {
359 curl_setopt( $ch, CURLOPT_POST, 1 );
360 // Don't interpret POST parameters starting with '@' as file uploads, because this
361 // makes it impossible to POST plain values starting with '@' (and causes security
362 // issues potentially exposing the contents of local files).
363 curl_setopt( $ch, CURLOPT_SAFE_UPLOAD, true );
364 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
365 } else {
366 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
367 throw new Exception( "HTTP body specified for a non PUT/POST request." );
368 }
369 $req['headers']['content-length'] = 0;
370 }
371
372 if ( !isset( $req['headers']['user-agent'] ) ) {
373 $req['headers']['user-agent'] = $this->userAgent;
374 }
375
376 $headers = [];
377 foreach ( $req['headers'] as $name => $value ) {
378 if ( strpos( $name, ': ' ) ) {
379 throw new Exception( "Headers cannot have ':' in the name." );
380 }
381 $headers[] = $name . ': ' . trim( $value );
382 }
383 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
384
385 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
386 function ( $ch, $header ) use ( &$req ) {
387 if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
388 header( $header );
389 }
390 $length = strlen( $header );
391 $matches = [];
392 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
393 $req['response']['code'] = (int)$matches[2];
394 $req['response']['reason'] = trim( $matches[3] );
395 return $length;
396 }
397 if ( strpos( $header, ":" ) === false ) {
398 return $length;
399 }
400 list( $name, $value ) = explode( ":", $header, 2 );
401 $name = strtolower( $name );
402 $value = trim( $value );
403 if ( isset( $req['response']['headers'][$name] ) ) {
404 $req['response']['headers'][$name] .= ', ' . $value;
405 } else {
406 $req['response']['headers'][$name] = $value;
407 }
408 return $length;
409 }
410 );
411
412 if ( isset( $req['stream'] ) ) {
413 // Don't just use CURLOPT_FILE as that might give:
414 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
415 // The callback here handles both normal files and php://temp handles.
416 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
417 function ( $ch, $data ) use ( &$req ) {
418 return fwrite( $req['stream'], $data );
419 }
420 );
421 } else {
422 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
423 function ( $ch, $data ) use ( &$req ) {
424 $req['response']['body'] .= $data;
425 return strlen( $data );
426 }
427 );
428 }
429
430 return $ch;
431 }
432
433 /**
434 * @return resource
435 * @throws Exception
436 */
437 protected function getCurlMulti() {
438 if ( !$this->multiHandle ) {
439 if ( !function_exists( 'curl_multi_init' ) ) {
440 throw new Exception( "PHP cURL function curl_multi_init missing. " .
441 "Check https://www.mediawiki.org/wiki/Manual:CURL" );
442 }
443 $cmh = curl_multi_init();
444 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
445 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
446 $this->multiHandle = $cmh;
447 }
448 return $this->multiHandle;
449 }
450
451 /**
452 * Execute a set of HTTP(S) requests sequentially.
453 *
454 * @see MultiHttpClient::runMulti()
455 * @todo Remove dependency on MediaWikiServices: use a separate HTTP client
456 * library or copy code from PhpHttpRequest
457 * @param array $reqs Map of HTTP request arrays
458 * @param array $opts
459 * - connTimeout : connection timeout per request (seconds)
460 * - reqTimeout : post-connection timeout per request (seconds)
461 * @return array $reqs With response array populated for each
462 * @throws Exception
463 */
464 private function runMultiHttp( array $reqs, array $opts = [] ) {
465 $httpOptions = [
466 'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
467 'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
468 'logger' => $this->logger,
469 'caInfo' => $this->caBundlePath,
470 ];
471 foreach ( $reqs as &$req ) {
472 $reqOptions = $httpOptions + [
473 'method' => $req['method'],
474 'proxy' => $req['proxy'] ?? $this->proxy,
475 'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
476 'postData' => $req['body'],
477 ];
478
479 $url = $req['url'];
480 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
481 if ( $query != '' ) {
482 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
483 }
484
485 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
486 $url, $reqOptions );
487 $sv = $httpRequest->execute()->getStatusValue();
488
489 $respHeaders = array_map(
490 function ( $v ) {
491 return implode( ', ', $v );
492 },
493 $httpRequest->getResponseHeaders() );
494
495 $req['response'] = [
496 'code' => $httpRequest->getStatus(),
497 'reason' => '',
498 'headers' => $respHeaders,
499 'body' => $httpRequest->getContent(),
500 'error' => '',
501 ];
502
503 if ( !$sv->isOk() ) {
504 $svErrors = $sv->getErrors();
505 if ( isset( $svErrors[0] ) ) {
506 $req['response']['error'] = $svErrors[0]['message'];
507
508 // param values vary per failure type (ex. unknown host vs unknown page)
509 if ( isset( $svErrors[0]['params'][0] ) ) {
510 if ( is_numeric( $svErrors[0]['params'][0] ) ) {
511 if ( isset( $svErrors[0]['params'][1] ) ) {
512 $req['response']['reason'] = $svErrors[0]['params'][1];
513 }
514 } else {
515 $req['response']['reason'] = $svErrors[0]['params'][0];
516 }
517 }
518 }
519 }
520
521 $req['response'][0] = $req['response']['code'];
522 $req['response'][1] = $req['response']['reason'];
523 $req['response'][2] = $req['response']['headers'];
524 $req['response'][3] = $req['response']['body'];
525 $req['response'][4] = $req['response']['error'];
526 }
527
528 return $reqs;
529 }
530
531 /**
532 * Normalize request information
533 *
534 * @param array $reqs the requests to normalize
535 */
536 private function normalizeRequests( array &$reqs ) {
537 foreach ( $reqs as &$req ) {
538 $req['response'] = [
539 'code' => 0,
540 'reason' => '',
541 'headers' => [],
542 'body' => '',
543 'error' => ''
544 ];
545 if ( isset( $req[0] ) ) {
546 $req['method'] = $req[0]; // short-form
547 unset( $req[0] );
548 }
549 if ( isset( $req[1] ) ) {
550 $req['url'] = $req[1]; // short-form
551 unset( $req[1] );
552 }
553 if ( !isset( $req['method'] ) ) {
554 throw new Exception( "Request has no 'method' field set." );
555 } elseif ( !isset( $req['url'] ) ) {
556 throw new Exception( "Request has no 'url' field set." );
557 }
558 $this->logger->debug( "{$req['method']}: {$req['url']}" );
559 $req['query'] = $req['query'] ?? [];
560 $headers = []; // normalized headers
561 if ( isset( $req['headers'] ) ) {
562 foreach ( $req['headers'] as $name => $value ) {
563 $headers[strtolower( $name )] = $value;
564 }
565 }
566 $req['headers'] = $headers;
567 if ( !isset( $req['body'] ) ) {
568 $req['body'] = '';
569 $req['headers']['content-length'] = 0;
570 }
571 $req['flags'] = $req['flags'] ?? [];
572 }
573 }
574
575 /**
576 * Get a suitable select timeout for the given options.
577 *
578 * @param array $opts
579 * @return float
580 */
581 private function getSelectTimeout( $opts ) {
582 $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
583 $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
584 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
585 if ( count( $timeouts ) === 0 ) {
586 return 1;
587 }
588
589 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
590 // Minimum 10us for sanity
591 if ( $selectTimeout < 10e-6 ) {
592 $selectTimeout = 10e-6;
593 }
594 return $selectTimeout;
595 }
596
597 /**
598 * Register a logger
599 *
600 * @param LoggerInterface $logger
601 */
602 public function setLogger( LoggerInterface $logger ) {
603 $this->logger = $logger;
604 }
605
606 function __destruct() {
607 if ( $this->multiHandle ) {
608 curl_multi_close( $this->multiHandle );
609 }
610 }
611 }