MediaWiki REL1_39
MultiHttpClient.php
Go to the documentation of this file.
1<?php
24use Psr\Log\LoggerAwareInterface;
25use Psr\Log\LoggerInterface;
26use Psr\Log\NullLogger;
27
55class MultiHttpClient implements LoggerAwareInterface {
57 private const SENSITIVE_HEADERS = '/(^|-|_)(authorization|auth|password|cookie)($|-|_)/';
62 protected $cmh = null;
64 protected $caBundlePath;
66 protected $connTimeout = 10;
68 protected $maxConnTimeout = INF;
70 protected $reqTimeout = 30;
72 protected $maxReqTimeout = INF;
74 protected $usePipelining = false;
76 protected $maxConnsPerHost = 50;
78 protected $proxy;
80 protected $localProxy = false;
82 protected $localVirtualHosts = [];
84 protected $userAgent = 'wikimedia/multi-http-client v1.0';
86 protected $logger;
87
88 // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
89 // timeouts are periodically polled instead of being accurately respected.
90 // The select timeout is set to the minimum timeout multiplied by this factor.
91 private const TIMEOUT_ACCURACY_FACTOR = 0.1;
92
113 public function __construct( array $options ) {
114 if ( isset( $options['caBundlePath'] ) ) {
115 $this->caBundlePath = $options['caBundlePath'];
116 if ( !file_exists( $this->caBundlePath ) ) {
117 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
118 }
119 }
120 static $opts = [
121 'connTimeout', 'maxConnTimeout', 'reqTimeout', 'maxReqTimeout',
122 'usePipelining', 'maxConnsPerHost', 'proxy', 'userAgent', 'logger',
123 'localProxy', 'localVirtualHosts',
124 ];
125 foreach ( $opts as $key ) {
126 if ( isset( $options[$key] ) ) {
127 $this->$key = $options[$key];
128 }
129 }
130 if ( $this->logger === null ) {
131 $this->logger = new NullLogger;
132 }
133 }
134
158 public function run( array $req, array $opts = [] ) {
159 return $this->runMulti( [ $req ], $opts )[0]['response'];
160 }
161
193 public function runMulti( array $reqs, array $opts = [] ) {
194 $this->normalizeRequests( $reqs );
195 $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
196
197 if ( $this->maxConnTimeout && $opts['connTimeout'] > $this->maxConnTimeout ) {
198 $opts['connTimeout'] = $this->maxConnTimeout;
199 }
200 if ( $this->maxReqTimeout && $opts['reqTimeout'] > $this->maxReqTimeout ) {
201 $opts['reqTimeout'] = $this->maxReqTimeout;
202 }
203
204 if ( $this->isCurlEnabled() ) {
205 switch ( $opts['httpVersion'] ?? null ) {
206 case 'v1.0':
207 $opts['httpVersion'] = CURL_HTTP_VERSION_1_0;
208 break;
209 case 'v1.1':
210 $opts['httpVersion'] = CURL_HTTP_VERSION_1_1;
211 break;
212 case 'v2':
213 case 'v2.0':
214 $opts['httpVersion'] = CURL_HTTP_VERSION_2_0;
215 break;
216 default:
217 $opts['httpVersion'] = CURL_HTTP_VERSION_NONE;
218 }
219 return $this->runMultiCurl( $reqs, $opts );
220 } else {
221 # TODO: Add handling for httpVersion option
222 return $this->runMultiHttp( $reqs, $opts );
223 }
224 }
225
231 protected function isCurlEnabled() {
232 // Explicitly test if curl_multi* is blocked, as some users' hosts provide
233 // them with a modified curl with the multi-threaded parts removed(!)
234 return extension_loaded( 'curl' ) && function_exists( 'curl_multi_init' );
235 }
236
254 private function runMultiCurl( array $reqs, array $opts ) {
255 $chm = $this->getCurlMulti( $opts );
256
257 $selectTimeout = $this->getSelectTimeout( $opts );
258
259 // Add all of the required cURL handles...
260 $handles = [];
261 foreach ( $reqs as $index => &$req ) {
262 $handles[$index] = $this->getCurlHandle( $req, $opts );
263 curl_multi_add_handle( $chm, $handles[$index] );
264 }
265 unset( $req ); // don't assign over this by accident
266
267 $infos = [];
268 // Execute the cURL handles concurrently...
269 $active = null; // handles still being processed
270 do {
271 // Do any available work...
272 do {
273 $mrc = curl_multi_exec( $chm, $active );
274 $info = curl_multi_info_read( $chm );
275 if ( $info !== false ) {
276 // Note: cast to integer even works on PHP 8.0+ despite the
277 // handle being an object not a resource, because CurlHandle
278 // has a backwards-compatible cast_object handler.
279 $infos[(int)$info['handle']] = $info;
280 }
281 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
282 // Wait (if possible) for available work...
283 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
284 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
285 usleep( 5000 ); // 5ms
286 }
287 } while ( $active > 0 && $mrc == CURLM_OK );
288
289 // Remove all of the added cURL handles and check for errors...
290 foreach ( $reqs as $index => &$req ) {
291 $ch = $handles[$index];
292 curl_multi_remove_handle( $chm, $ch );
293
294 if ( isset( $infos[(int)$ch] ) ) {
295 $info = $infos[(int)$ch];
296 $errno = $info['result'];
297 if ( $errno !== 0 ) {
298 $req['response']['error'] = "(curl error: $errno)";
299 if ( function_exists( 'curl_strerror' ) ) {
300 $req['response']['error'] .= " " . curl_strerror( $errno );
301 }
302 $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
303 $req['response']['error'] );
304 } else {
305 $this->logger->debug(
306 "HTTP complete: {method} {url} code={response_code} size={size} " .
307 "total={total_time} connect={connect_time}",
308 [
309 'method' => $req['method'],
310 'url' => $req['url'],
311 'response_code' => $req['response']['code'],
312 'size' => curl_getinfo( $ch, CURLINFO_SIZE_DOWNLOAD ),
313 'total_time' => $this->getCurlTime(
314 $ch, CURLINFO_TOTAL_TIME, 'CURLINFO_TOTAL_TIME_T'
315 ),
316 'connect_time' => $this->getCurlTime(
317 $ch, CURLINFO_CONNECT_TIME, 'CURLINFO_CONNECT_TIME_T'
318 ),
319 ]
320 );
321 }
322 } else {
323 $req['response']['error'] = "(curl error: no status set)";
324 }
325
326 // For convenience with the list() operator
327 $req['response'][0] = $req['response']['code'];
328 $req['response'][1] = $req['response']['reason'];
329 $req['response'][2] = $req['response']['headers'];
330 $req['response'][3] = $req['response']['body'];
331 $req['response'][4] = $req['response']['error'];
332 curl_close( $ch );
333 // Close any string wrapper file handles
334 if ( isset( $req['_closeHandle'] ) ) {
335 fclose( $req['_closeHandle'] );
336 unset( $req['_closeHandle'] );
337 }
338 }
339 unset( $req ); // don't assign over this by accident
340
341 return $reqs;
342 }
343
356 protected function getCurlHandle( array &$req, array $opts ) {
357 $ch = curl_init();
358
359 curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
360 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
361 curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
362 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
363 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
364 curl_setopt( $ch, CURLOPT_HEADER, 0 );
365 if ( $this->caBundlePath !== null ) {
366 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
367 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
368 }
369 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
370
371 $url = $req['url'];
372 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
373 if ( $query != '' ) {
374 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
375 }
376 curl_setopt( $ch, CURLOPT_URL, $url );
377 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
378 curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
379 curl_setopt( $ch, CURLOPT_HTTP_VERSION, $opts['httpVersion'] ?? CURL_HTTP_VERSION_NONE );
380
381 if ( $req['method'] === 'PUT' ) {
382 curl_setopt( $ch, CURLOPT_PUT, 1 );
383 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
384 if ( is_resource( $req['body'] ) ) {
385 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
386 if ( isset( $req['headers']['content-length'] ) ) {
387 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
388 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
389 $req['headers']['transfer-encoding'] === 'chunks'
390 ) {
391 curl_setopt( $ch, CURLOPT_UPLOAD, true );
392 } else {
393 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
394 }
395 } elseif ( $req['body'] !== '' ) {
396 $fp = fopen( "php://temp", "wb+" );
397 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
398 rewind( $fp );
399 curl_setopt( $ch, CURLOPT_INFILE, $fp );
400 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
401 $req['_closeHandle'] = $fp; // remember to close this later
402 } else {
403 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
404 }
405 curl_setopt( $ch, CURLOPT_READFUNCTION,
406 static function ( $ch, $fd, $length ) {
407 return (string)fread( $fd, $length );
408 }
409 );
410 } elseif ( $req['method'] === 'POST' ) {
411 curl_setopt( $ch, CURLOPT_POST, 1 );
412 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
413 } else {
414 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
415 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
416 throw new Exception( "HTTP body specified for a non PUT/POST request." );
417 }
418 $req['headers']['content-length'] = 0;
419 }
420
421 if ( !isset( $req['headers']['user-agent'] ) ) {
422 $req['headers']['user-agent'] = $this->userAgent;
423 }
424
425 $headers = [];
426 foreach ( $req['headers'] as $name => $value ) {
427 if ( strpos( $name, ': ' ) ) {
428 throw new Exception( "Headers cannot have ':' in the name." );
429 }
430 $headers[] = $name . ': ' . trim( $value );
431 }
432 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
433
434 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
435 static function ( $ch, $header ) use ( &$req ) {
436 if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
437 header( $header );
438 }
439 $length = strlen( $header );
440 $matches = [];
441 if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
442 $req['response']['code'] = (int)$matches[2];
443 $req['response']['reason'] = trim( $matches[3] );
444 // After a redirect we will receive this again, but we already stored headers
445 // that belonged to a redirect response. Start over.
446 $req['response']['headers'] = [];
447 return $length;
448 }
449 if ( strpos( $header, ":" ) === false ) {
450 return $length;
451 }
452 list( $name, $value ) = explode( ":", $header, 2 );
453 $name = strtolower( $name );
454 $value = trim( $value );
455 if ( isset( $req['response']['headers'][$name] ) ) {
456 $req['response']['headers'][$name] .= ', ' . $value;
457 } else {
458 $req['response']['headers'][$name] = $value;
459 }
460 return $length;
461 }
462 );
463
464 // This works with both file and php://temp handles (unlike CURLOPT_FILE)
465 $hasOutputStream = isset( $req['stream'] );
466 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
467 static function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
468 if ( $hasOutputStream ) {
469 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
470 return fwrite( $req['stream'], $data );
471 } else {
472 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
473 $req['response']['body'] .= $data;
474
475 return strlen( $data );
476 }
477 }
478 );
479
480 return $ch;
481 }
482
489 protected function getCurlMulti( array $opts ) {
490 if ( !$this->cmh ) {
491 $cmh = curl_multi_init();
492 // Limit the size of the idle connection cache such that consecutive parallel
493 // request batches to the same host can avoid having to keep making connections
494 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
495 $this->cmh = $cmh;
496 }
497
498 $curlVersion = curl_version()['version'];
499
500 // CURLMOPT_MAX_HOST_CONNECTIONS is available since PHP 7.0.7 and cURL 7.30.0
501 if ( version_compare( $curlVersion, '7.30.0', '>=' ) ) {
502 // Limit the number of in-flight requests for any given host
503 $maxHostConns = $opts['maxConnsPerHost'] ?? $this->maxConnsPerHost;
504 curl_multi_setopt( $this->cmh, CURLMOPT_MAX_HOST_CONNECTIONS, (int)$maxHostConns );
505 }
506
507 if ( $opts['usePipelining'] ?? $this->usePipelining ) {
508 if ( version_compare( $curlVersion, '7.43', '<' ) ) {
509 // The option is a boolean
510 $pipelining = 1;
511 } elseif ( version_compare( $curlVersion, '7.62', '<' ) ) {
512 // The option is a bitfield and HTTP/1.x pipelining is supported
513 $pipelining = CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX;
514 } else {
515 // The option is a bitfield but HTTP/1.x pipelining has been removed
516 $pipelining = CURLPIPE_MULTIPLEX;
517 }
518 // Suppress deprecation, we know already (T264735)
519 // phpcs:ignore Generic.PHP.NoSilencedErrors
520 @curl_multi_setopt( $this->cmh, CURLMOPT_PIPELINING, $pipelining );
521 }
522
523 return $this->cmh;
524 }
525
536 private function getCurlTime( $ch, $oldOption, $newConstName ): string {
537 if ( defined( $newConstName ) ) {
538 return sprintf( "%.6F", curl_getinfo( $ch, constant( $newConstName ) ) / 1e6 );
539 } else {
540 return (string)curl_getinfo( $ch, $oldOption );
541 }
542 }
543
559 private function runMultiHttp( array $reqs, array $opts = [] ) {
560 $httpOptions = [
561 'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
562 'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
563 'logger' => $this->logger,
564 'caInfo' => $this->caBundlePath,
565 ];
566 foreach ( $reqs as &$req ) {
567 $reqOptions = $httpOptions + [
568 'method' => $req['method'],
569 'proxy' => $req['proxy'] ?? $this->proxy,
570 'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
571 'postData' => $req['body'],
572 ];
573
574 $url = $req['url'];
575 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
576 if ( $query != '' ) {
577 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
578 }
579
580 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
581 $url, $reqOptions, __METHOD__ );
582 $httpRequest->setLogger( $this->logger );
583 $sv = $httpRequest->execute()->getStatusValue();
584
585 $respHeaders = array_map(
586 static function ( $v ) {
587 return implode( ', ', $v );
588 },
589 $httpRequest->getResponseHeaders() );
590
591 $req['response'] = [
592 'code' => $httpRequest->getStatus(),
593 'reason' => '',
594 'headers' => $respHeaders,
595 'body' => $httpRequest->getContent(),
596 'error' => '',
597 ];
598
599 if ( !$sv->isOK() ) {
600 $svErrors = $sv->getErrors();
601 if ( isset( $svErrors[0] ) ) {
602 $req['response']['error'] = $svErrors[0]['message'];
603
604 // param values vary per failure type (ex. unknown host vs unknown page)
605 if ( isset( $svErrors[0]['params'][0] ) ) {
606 if ( is_numeric( $svErrors[0]['params'][0] ) ) {
607 if ( isset( $svErrors[0]['params'][1] ) ) {
608 // @phan-suppress-next-line PhanTypeInvalidDimOffset
609 $req['response']['reason'] = $svErrors[0]['params'][1];
610 }
611 } else {
612 $req['response']['reason'] = $svErrors[0]['params'][0];
613 }
614 }
615 }
616 }
617
618 $req['response'][0] = $req['response']['code'];
619 $req['response'][1] = $req['response']['reason'];
620 $req['response'][2] = $req['response']['headers'];
621 $req['response'][3] = $req['response']['body'];
622 $req['response'][4] = $req['response']['error'];
623 }
624
625 return $reqs;
626 }
627
633 private function normalizeRequests( array &$reqs ) {
634 foreach ( $reqs as &$req ) {
635 $req['response'] = [
636 'code' => 0,
637 'reason' => '',
638 'headers' => [],
639 'body' => '',
640 'error' => ''
641 ];
642 if ( isset( $req[0] ) ) {
643 $req['method'] = $req[0]; // short-form
644 unset( $req[0] );
645 }
646 if ( isset( $req[1] ) ) {
647 $req['url'] = $req[1]; // short-form
648 unset( $req[1] );
649 }
650 if ( !isset( $req['method'] ) ) {
651 throw new Exception( "Request has no 'method' field set." );
652 } elseif ( !isset( $req['url'] ) ) {
653 throw new Exception( "Request has no 'url' field set." );
654 }
655 if ( $this->localProxy !== false && $this->isLocalURL( $req['url'] ) ) {
656 $this->useReverseProxy( $req, $this->localProxy );
657 }
658 $req['query'] = $req['query'] ?? [];
659 $headers = []; // normalized headers
660 if ( isset( $req['headers'] ) ) {
661 foreach ( $req['headers'] as $name => $value ) {
662 $headers[strtolower( $name )] = $value;
663 }
664 }
665 $req['headers'] = $headers;
666 if ( !isset( $req['body'] ) ) {
667 $req['body'] = '';
668 $req['headers']['content-length'] = 0;
669 }
670 // Redact some headers we know to have tokens before logging them
671 $logHeaders = $req['headers'];
672 foreach ( $logHeaders as $header => $value ) {
673 if ( preg_match( self::SENSITIVE_HEADERS, $header ) === 1 ) {
674 $logHeaders[$header] = '[redacted]';
675 }
676 }
677 $this->logger->debug( "HTTP start: {method} {url}",
678 [
679 'method' => $req['method'],
680 'url' => $req['url'],
681 'headers' => $logHeaders,
682 ]
683 );
684 $req['flags'] = $req['flags'] ?? [];
685 }
686 }
687
688 private function useReverseProxy( array &$req, $proxy ) {
689 $parsedProxy = wfParseUrl( $proxy );
690 if ( $parsedProxy === false ) {
691 throw new Exception( "Invalid reverseProxy configured: $proxy" );
692 }
693 $parsedUrl = wfParseUrl( $req['url'] );
694 if ( $parsedUrl === false ) {
695 throw new Exception( "Invalid url specified: {$req['url']}" );
696 }
697 // Set the current host in the Host header
698 $req['headers']['Host'] = $parsedUrl['host'];
699 // Replace scheme, host and port in the request
700 $parsedUrl['scheme'] = $parsedProxy['scheme'];
701 $parsedUrl['host'] = $parsedProxy['host'];
702 if ( isset( $parsedProxy['port'] ) ) {
703 $parsedUrl['port'] = $parsedProxy['port'];
704 } else {
705 unset( $parsedUrl['port'] );
706 }
707 $req['url'] = wfAssembleUrl( $parsedUrl );
708 // Explicitly disable use of another proxy by setting to false,
709 // since null will fallback to $this->proxy
710 $req['proxy'] = false;
711 }
712
720 private function isLocalURL( $url ) {
721 if ( !$this->localVirtualHosts ) {
722 // Shortcut
723 return false;
724 }
725
726 // Extract host part
727 $matches = [];
728 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
729 $host = $matches[1];
730 // Split up dotwise
731 $domainParts = explode( '.', $host );
732 // Check if this domain or any superdomain is listed as a local virtual host
733 $domainParts = array_reverse( $domainParts );
734
735 $domain = '';
736 $countParts = count( $domainParts );
737 for ( $i = 0; $i < $countParts; $i++ ) {
738 $domainPart = $domainParts[$i];
739 if ( $i == 0 ) {
740 $domain = $domainPart;
741 } else {
742 $domain = $domainPart . '.' . $domain;
743 }
744
745 if ( in_array( $domain, $this->localVirtualHosts ) ) {
746 return true;
747 }
748 }
749 }
750
751 return false;
752 }
753
760 private function getSelectTimeout( $opts ) {
761 $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
762 $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
763 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
764 if ( count( $timeouts ) === 0 ) {
765 return 1;
766 }
767
768 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
769 // Minimum 10us
770 if ( $selectTimeout < 10e-6 ) {
771 $selectTimeout = 10e-6;
772 }
773 return $selectTimeout;
774 }
775
781 public function setLogger( LoggerInterface $logger ) {
782 $this->logger = $logger;
783 }
784
785 public function __destruct() {
786 if ( $this->cmh ) {
787 curl_multi_close( $this->cmh );
788 $this->cmh = null;
789 }
790 }
791}
wfParseUrl( $url)
parse_url() work-alike, but non-broken.
wfAssembleUrl( $urlParts)
This function will reassemble a URL parsed with wfParseURL.
if(!defined('MW_SETUP_CALLBACK'))
The persistent session ID (if any) loaded at startup.
Definition WebStart.php:82
Service locator for MediaWiki core services.
Class to handle multiple HTTP requests.
string[] $localVirtualHosts
runMulti(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests.
string bool $localProxy
__construct(array $options)
Since 1.35, callers should use HttpRequestFactory::createMultiClient() to get a client object with ap...
string null $proxy
proxy
string null $caBundlePath
SSL certificates path.
LoggerInterface $logger
resource object null $cmh
@phpcs:ignore MediaWiki.Commenting.PropertyDocumentation.ObjectTypeHintVar curl_multi_init() handle,...
setLogger(LoggerInterface $logger)
Register a logger.
run(array $req, array $opts=[])
Execute an HTTP(S) request.
getCurlHandle(array &$req, array $opts)
isCurlEnabled()
Determines if the curl extension is available.
getCurlMulti(array $opts)
$header