MediaWiki master
MultiHttpClient.php
Go to the documentation of this file.
1<?php
9namespace Wikimedia\Http;
10
11use InvalidArgumentException;
13use Psr\Log\LoggerAwareInterface;
14use Psr\Log\LoggerInterface;
15use Psr\Log\NullLogger;
16use RuntimeException;
17
45class MultiHttpClient implements LoggerAwareInterface {
47 private const SENSITIVE_HEADERS = '/(^|-|_)(authorization|auth|password|cookie)($|-|_)/';
52 protected $cmh = null;
54 protected $caBundlePath;
56 protected $connTimeout = 10;
58 protected $maxConnTimeout = INF;
60 protected $reqTimeout = 30;
62 protected $maxReqTimeout = INF;
64 protected $usePipelining = false;
66 protected $maxConnsPerHost = 50;
68 protected $proxy;
70 protected $localProxy = false;
72 protected $localVirtualHosts = [];
74 protected $userAgent = 'wikimedia/multi-http-client v1.1';
76 protected $logger;
77 protected array $headers = [];
78
79 // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
80 // timeouts are periodically polled instead of being accurately respected.
81 // The select timeout is set to the minimum timeout multiplied by this factor.
82 private const TIMEOUT_ACCURACY_FACTOR = 0.1;
83
84 private ?TelemetryHeadersInterface $telemetry = null;
85
108 public function __construct( array $options ) {
109 if ( isset( $options['caBundlePath'] ) ) {
110 $this->caBundlePath = $options['caBundlePath'];
111 if ( !file_exists( $this->caBundlePath ) ) {
112 throw new InvalidArgumentException( "Cannot find CA bundle: " . $this->caBundlePath );
113 }
114 }
115 static $opts = [
116 'connTimeout', 'maxConnTimeout', 'reqTimeout', 'maxReqTimeout',
117 'usePipelining', 'maxConnsPerHost', 'proxy', 'userAgent', 'logger',
118 'localProxy', 'localVirtualHosts', 'headers', 'telemetry'
119 ];
120 foreach ( $opts as $key ) {
121 if ( isset( $options[$key] ) ) {
122 $this->$key = $options[$key];
123 }
124 }
125 $this->logger ??= new NullLogger;
126 }
127
152 public function run( array $req, array $opts = [], string $caller = __METHOD__ ) {
153 return $this->runMulti( [ $req ], $opts, $caller )[0]['response'];
154 }
155
188 public function runMulti( array $reqs, array $opts = [], string $caller = __METHOD__ ) {
189 $this->normalizeRequests( $reqs );
190 $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
191
192 if ( $this->maxConnTimeout && $opts['connTimeout'] > $this->maxConnTimeout ) {
193 $opts['connTimeout'] = $this->maxConnTimeout;
194 }
195 if ( $this->maxReqTimeout && $opts['reqTimeout'] > $this->maxReqTimeout ) {
196 $opts['reqTimeout'] = $this->maxReqTimeout;
197 }
198
199 if ( $this->isCurlEnabled() ) {
200 switch ( $opts['httpVersion'] ?? null ) {
201 case 'v1.0':
202 $opts['httpVersion'] = CURL_HTTP_VERSION_1_0;
203 break;
204 case 'v1.1':
205 $opts['httpVersion'] = CURL_HTTP_VERSION_1_1;
206 break;
207 case 'v2':
208 case 'v2.0':
209 $opts['httpVersion'] = CURL_HTTP_VERSION_2_0;
210 break;
211 default:
212 $opts['httpVersion'] = CURL_HTTP_VERSION_NONE;
213 }
214 return $this->runMultiCurl( $reqs, $opts, $caller );
215 } else {
216 # TODO: Add handling for httpVersion option
217 return $this->runMultiHttp( $reqs, $opts );
218 }
219 }
220
226 protected function isCurlEnabled() {
227 // Explicitly test if curl_multi* is blocked, as some users' hosts provide
228 // them with a modified curl with the multi-threaded parts removed(!)
229 return extension_loaded( 'curl' ) && function_exists( 'curl_multi_init' );
230 }
231
250 private function runMultiCurl( array $reqs, array $opts, string $caller = __METHOD__ ) {
251 $chm = $this->getCurlMulti( $opts );
252
253 $selectTimeout = $this->getSelectTimeout( $opts );
254
255 // Add all of the required cURL handles...
256 $handles = [];
257 foreach ( $reqs as $index => &$req ) {
258 $handles[$index] = $this->getCurlHandle( $req, $opts );
259 curl_multi_add_handle( $chm, $handles[$index] );
260 }
261 unset( $req ); // don't assign over this by accident
262
263 $infos = [];
264 // Execute the cURL handles concurrently...
265 $active = null; // handles still being processed
266 do {
267 // Do any available work...
268 $mrc = curl_multi_exec( $chm, $active );
269
270 if ( $mrc !== CURLM_OK ) {
271 $error = curl_multi_strerror( $mrc );
272 $this->logger->error( 'curl_multi_exec() failed: {error}', [
273 'error' => $error,
274 'exception' => new RuntimeException(),
275 'method' => $caller,
276 ] );
277 break;
278 }
279
280 // Wait (if possible) for available work...
281 if ( $active > 0 && curl_multi_select( $chm, $selectTimeout ) === -1 ) {
282 $errno = curl_multi_errno( $chm );
283 $error = curl_multi_strerror( $errno );
284 $this->logger->error( 'curl_multi_select() failed: {error}', [
285 'error' => $error,
286 'exception' => new RuntimeException(),
287 'method' => $caller,
288 ] );
289 }
290 } while ( $active > 0 );
291
292 $queuedMessages = null;
293 do {
294 $info = curl_multi_info_read( $chm, $queuedMessages );
295 if ( $info !== false && $info['msg'] === CURLMSG_DONE ) {
296 // Note: cast to integer even works on PHP 8.0+ despite the
297 // handle being an object not a resource, because CurlHandle
298 // has a backwards-compatible cast_object handler.
299 $infos[(int)$info['handle']] = $info;
300 }
301 } while ( $queuedMessages > 0 );
302
303 // Remove all of the added cURL handles and check for errors...
304 foreach ( $reqs as $index => &$req ) {
305 $ch = $handles[$index];
306 curl_multi_remove_handle( $chm, $ch );
307
308 if ( isset( $infos[(int)$ch] ) ) {
309 $info = $infos[(int)$ch];
310 $errno = $info['result'];
311 if ( $errno !== 0 ) {
312 $req['response']['error'] = "(curl error: $errno)";
313 if ( function_exists( 'curl_strerror' ) ) {
314 $req['response']['error'] .= " " . curl_strerror( $errno );
315 }
316 $this->logger->error( 'Error fetching URL "{url}": {error}', [
317 'url' => $req['url'],
318 'error' => $req['response']['error'],
319 'exception' => new RuntimeException(),
320 'method' => $caller,
321 ] );
322 } else {
323 $this->logger->debug(
324 "HTTP complete: {method} {url} code={response_code} size={size} " .
325 "total={total_time} connect={connect_time}",
326 [
327 'method' => $req['method'],
328 'url' => $req['url'],
329 'response_code' => $req['response']['code'],
330 'size' => curl_getinfo( $ch, CURLINFO_SIZE_DOWNLOAD ),
331 'total_time' => $this->getCurlTime(
332 $ch, CURLINFO_TOTAL_TIME, 'CURLINFO_TOTAL_TIME_T'
333 ),
334 'connect_time' => $this->getCurlTime(
335 $ch, CURLINFO_CONNECT_TIME, 'CURLINFO_CONNECT_TIME_T'
336 ),
337 ]
338 );
339 }
340 } else {
341 $req['response']['error'] = "(curl error: no status set)";
342 }
343
344 // For convenience with array destructuring
345 $req['response'][0] = $req['response']['code'];
346 $req['response'][1] = $req['response']['reason'];
347 $req['response'][2] = $req['response']['headers'];
348 $req['response'][3] = $req['response']['body'];
349 $req['response'][4] = $req['response']['error'];
350 curl_close( $ch );
351 // Close any string wrapper file handles
352 if ( isset( $req['_closeHandle'] ) ) {
353 fclose( $req['_closeHandle'] );
354 unset( $req['_closeHandle'] );
355 }
356 }
357 unset( $req ); // don't assign over this by accident
358
359 return $reqs;
360 }
361
374 protected function getCurlHandle( array &$req, array $opts ) {
375 $ch = curl_init();
376
377 curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
378 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
379 curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
380 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
381 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
382 curl_setopt( $ch, CURLOPT_HEADER, 0 );
383 if ( $this->caBundlePath !== null ) {
384 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
385 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
386 }
387 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
388
389 $url = $req['url'];
390 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
391 if ( $query != '' ) {
392 $url .= !str_contains( $req['url'], '?' ) ? "?$query" : "&$query";
393 }
394 curl_setopt( $ch, CURLOPT_URL, $url );
395 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
396 curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
397 curl_setopt( $ch, CURLOPT_HTTP_VERSION, $opts['httpVersion'] ?? CURL_HTTP_VERSION_NONE );
398
399 if ( $req['method'] === 'PUT' ) {
400 curl_setopt( $ch, CURLOPT_PUT, 1 );
401 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
402 if ( is_resource( $req['body'] ) ) {
403 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
404 if ( isset( $req['headers']['content-length'] ) ) {
405 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
406 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
407 $req['headers']['transfer-encoding'] === 'chunks'
408 ) {
409 curl_setopt( $ch, CURLOPT_UPLOAD, true );
410 } else {
411 throw new InvalidArgumentException( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
412 }
413 } elseif ( $req['body'] !== '' ) {
414 $fp = fopen( "php://temp", "wb+" );
415 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
416 rewind( $fp );
417 curl_setopt( $ch, CURLOPT_INFILE, $fp );
418 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
419 $req['_closeHandle'] = $fp; // remember to close this later
420 } else {
421 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
422 }
423 curl_setopt( $ch, CURLOPT_READFUNCTION,
424 static function ( $ch, $fd, $length ) {
425 return (string)fread( $fd, $length );
426 }
427 );
428 } elseif ( $req['method'] === 'POST' ) {
429 curl_setopt( $ch, CURLOPT_POST, 1 );
430 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
431 } else {
432 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
433 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
434 throw new InvalidArgumentException( "HTTP body specified for a non PUT/POST request." );
435 }
436 $req['headers']['content-length'] = 0;
437 }
438
439 if ( !isset( $req['headers']['user-agent'] ) ) {
440 $req['headers']['user-agent'] = $this->userAgent;
441 }
442
443 $headers = [];
444 foreach ( $req['headers'] as $name => $value ) {
445 if ( str_contains( $name, ':' ) ) {
446 throw new InvalidArgumentException( "Header name must not contain colon-space." );
447 }
448 $headers[] = $name . ': ' . trim( $value );
449 }
450 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
451
452 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
453 static function ( $ch, $header ) use ( &$req ) {
454 if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
455 header( $header );
456 }
457 $length = strlen( $header );
458 $matches = [];
459 if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
460 $req['response']['code'] = (int)$matches[2];
461 $req['response']['reason'] = trim( $matches[3] );
462 // After a redirect we will receive this again, but we already stored headers
463 // that belonged to a redirect response. Start over.
464 $req['response']['headers'] = [];
465 return $length;
466 }
467 if ( !str_contains( $header, ":" ) ) {
468 return $length;
469 }
470 [ $name, $value ] = explode( ":", $header, 2 );
471 $name = strtolower( $name );
472 $value = trim( $value );
473 if ( isset( $req['response']['headers'][$name] ) ) {
474 $req['response']['headers'][$name] .= ', ' . $value;
475 } else {
476 $req['response']['headers'][$name] = $value;
477 }
478 return $length;
479 }
480 );
481
482 // This works with both file and php://temp handles (unlike CURLOPT_FILE)
483 $hasOutputStream = isset( $req['stream'] );
484 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
485 static function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
486 if ( $hasOutputStream ) {
487 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
488 return fwrite( $req['stream'], $data );
489 } else {
490 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
491 $req['response']['body'] .= $data;
492
493 return strlen( $data );
494 }
495 }
496 );
497
498 return $ch;
499 }
500
507 protected function getCurlMulti( array $opts ) {
508 if ( !$this->cmh ) {
509 $cmh = curl_multi_init();
510 // Limit the size of the idle connection cache such that consecutive parallel
511 // request batches to the same host can avoid having to keep making connections
512 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
513 $this->cmh = $cmh;
514 }
515
516 $curlVersion = curl_version()['version'];
517
518 // CURLMOPT_MAX_HOST_CONNECTIONS is available since PHP 7.0.7 and cURL 7.30.0
519 if ( version_compare( $curlVersion, '7.30.0', '>=' ) ) {
520 // Limit the number of in-flight requests for any given host
521 $maxHostConns = $opts['maxConnsPerHost'] ?? $this->maxConnsPerHost;
522 curl_multi_setopt( $this->cmh, CURLMOPT_MAX_HOST_CONNECTIONS, (int)$maxHostConns );
523 }
524
525 if ( $opts['usePipelining'] ?? $this->usePipelining ) {
526 if ( version_compare( $curlVersion, '7.43', '<' ) ) {
527 // The option is a boolean
528 $pipelining = 1;
529 } elseif ( version_compare( $curlVersion, '7.62', '<' ) ) {
530 // The option is a bitfield and HTTP/1.x pipelining is supported
531 $pipelining = CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX;
532 } else {
533 // The option is a bitfield but HTTP/1.x pipelining has been removed
534 $pipelining = CURLPIPE_MULTIPLEX;
535 }
536 // Suppress deprecation, we know already (T264735)
537 // phpcs:ignore Generic.PHP.NoSilencedErrors
538 @curl_multi_setopt( $this->cmh, CURLMOPT_PIPELINING, $pipelining );
539 }
540
541 return $this->cmh;
542 }
543
554 private function getCurlTime( $ch, $oldOption, $newConstName ): string {
555 if ( defined( $newConstName ) ) {
556 return sprintf( "%.6F", curl_getinfo( $ch, constant( $newConstName ) ) / 1e6 );
557 } else {
558 return (string)curl_getinfo( $ch, $oldOption );
559 }
560 }
561
577 private function runMultiHttp( array $reqs, array $opts = [] ) {
578 $httpOptions = [
579 'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
580 'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
581 'logger' => $this->logger,
582 'caInfo' => $this->caBundlePath,
583 ];
584 foreach ( $reqs as &$req ) {
585 $reqOptions = $httpOptions + [
586 'method' => $req['method'],
587 'proxy' => $req['proxy'] ?? $this->proxy,
588 'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
589 'postData' => $req['body'],
590 ];
591
592 $url = $req['url'];
593 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
594 if ( $query != '' ) {
595 $url .= !str_contains( $req['url'], '?' ) ? "?$query" : "&$query";
596 }
597
598 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
599 $url, $reqOptions, __METHOD__ );
600 $httpRequest->setLogger( $this->logger );
601 foreach ( $req['headers'] as $header => $value ) {
602 $httpRequest->setHeader( $header, $value );
603 }
604 $sv = $httpRequest->execute()->getStatusValue();
605
606 $respHeaders = array_map(
607 static function ( $v ) {
608 return implode( ', ', $v );
609 },
610 $httpRequest->getResponseHeaders() );
611
612 $req['response'] = [
613 'code' => $httpRequest->getStatus(),
614 'reason' => '',
615 'headers' => $respHeaders,
616 'body' => $httpRequest->getContent(),
617 'error' => '',
618 ];
619
620 if ( !$sv->isOK() ) {
621 $svErrors = $sv->getErrors();
622 if ( isset( $svErrors[0] ) ) {
623 $req['response']['error'] = $svErrors[0]['message'];
624
625 // param values vary per failure type (ex. unknown host vs unknown page)
626 if ( isset( $svErrors[0]['params'][0] ) ) {
627 if ( is_numeric( $svErrors[0]['params'][0] ) ) {
628 if ( isset( $svErrors[0]['params'][1] ) ) {
629 // @phan-suppress-next-line PhanTypeInvalidDimOffset
630 $req['response']['reason'] = $svErrors[0]['params'][1];
631 }
632 } else {
633 $req['response']['reason'] = $svErrors[0]['params'][0];
634 }
635 }
636 }
637 }
638
639 $req['response'][0] = $req['response']['code'];
640 $req['response'][1] = $req['response']['reason'];
641 $req['response'][2] = $req['response']['headers'];
642 $req['response'][3] = $req['response']['body'];
643 $req['response'][4] = $req['response']['error'];
644 }
645
646 return $reqs;
647 }
648
654 private function normalizeHeaders( array $headers ): array {
655 $normalized = [];
656 foreach ( $headers as $name => $value ) {
657 $normalized[strtolower( $name )] = $value;
658 }
659 return $normalized;
660 }
661
667 private function normalizeRequests( array &$reqs ) {
668 foreach ( $reqs as &$req ) {
669 $req['response'] = [
670 'code' => 0,
671 'reason' => '',
672 'headers' => [],
673 'body' => '',
674 'error' => ''
675 ];
676 if ( isset( $req[0] ) ) {
677 $req['method'] = $req[0]; // short-form
678 unset( $req[0] );
679 }
680 if ( isset( $req[1] ) ) {
681 $req['url'] = $req[1]; // short-form
682 unset( $req[1] );
683 }
684 if ( !isset( $req['method'] ) ) {
685 throw new InvalidArgumentException( "Request has no 'method' field set." );
686 } elseif ( !isset( $req['url'] ) ) {
687 throw new InvalidArgumentException( "Request has no 'url' field set." );
688 }
689 if ( $this->localProxy !== false && $this->isLocalURL( $req['url'] ) ) {
690 $this->useReverseProxy( $req, $this->localProxy );
691 }
692 $req['query'] ??= [];
693 $req['headers'] = $this->normalizeHeaders(
694 array_merge(
695 $this->headers,
696 $this->telemetry ? $this->telemetry->getRequestHeaders() : [],
697 $req['headers'] ?? []
698 )
699 );
700
701 if ( !isset( $req['body'] ) ) {
702 $req['body'] = '';
703 $req['headers']['content-length'] = 0;
704 }
705 // Redact some headers we know to have tokens before logging them
706 $logHeaders = $req['headers'];
707 foreach ( $logHeaders as $header => $value ) {
708 if ( preg_match( self::SENSITIVE_HEADERS, $header ) === 1 ) {
709 $logHeaders[$header] = '[redacted]';
710 }
711 }
712 $this->logger->debug( "HTTP start: {method} {url}",
713 [
714 'method' => $req['method'],
715 'url' => $req['url'],
716 'headers' => $logHeaders,
717 ]
718 );
719 $req['flags'] ??= [];
720 }
721 }
722
723 private function useReverseProxy( array &$req, string $proxy ) {
724 $parsedProxy = parse_url( $proxy );
725 if ( $parsedProxy === false ) {
726 throw new InvalidArgumentException( "Invalid reverseProxy configured: $proxy" );
727 }
728 $parsedUrl = parse_url( $req['url'] );
729 if ( $parsedUrl === false ) {
730 throw new InvalidArgumentException( "Invalid url specified: {$req['url']}" );
731 }
732 // Set the current host in the Host header
733 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
734 $req['headers']['Host'] = $parsedUrl['host'];
735 // Replace scheme, host and port in the request
736 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
737 $parsedUrl['scheme'] = $parsedProxy['scheme'];
738 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
739 $parsedUrl['host'] = $parsedProxy['host'];
740 if ( isset( $parsedProxy['port'] ) ) {
741 $parsedUrl['port'] = $parsedProxy['port'];
742 } else {
743 unset( $parsedUrl['port'] );
744 }
745 $req['url'] = self::assembleUrl( $parsedUrl );
746 // Explicitly disable use of another proxy by setting to false,
747 // since null will fallback to $this->proxy
748 $req['proxy'] = false;
749 }
750
761 private static function assembleUrl( array $urlParts ): string {
762 $result = isset( $urlParts['scheme'] ) ? $urlParts['scheme'] . '://' : '';
763
764 if ( isset( $urlParts['host'] ) ) {
765 if ( isset( $urlParts['user'] ) ) {
766 $result .= $urlParts['user'];
767 if ( isset( $urlParts['pass'] ) ) {
768 $result .= ':' . $urlParts['pass'];
769 }
770 $result .= '@';
771 }
772
773 $result .= $urlParts['host'];
774
775 if ( isset( $urlParts['port'] ) ) {
776 $result .= ':' . $urlParts['port'];
777 }
778 }
779
780 if ( isset( $urlParts['path'] ) ) {
781 $result .= $urlParts['path'];
782 }
783
784 if ( isset( $urlParts['query'] ) && $urlParts['query'] !== '' ) {
785 $result .= '?' . $urlParts['query'];
786 }
787
788 if ( isset( $urlParts['fragment'] ) ) {
789 $result .= '#' . $urlParts['fragment'];
790 }
791
792 return $result;
793 }
794
802 private function isLocalURL( $url ) {
803 if ( !$this->localVirtualHosts ) {
804 // Shortcut
805 return false;
806 }
807
808 // Extract host part
809 $matches = [];
810 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
811 $host = $matches[1];
812 // Split up dotwise
813 $domainParts = explode( '.', $host );
814 // Check if this domain or any superdomain is listed as a local virtual host
815 $domainParts = array_reverse( $domainParts );
816
817 $domain = '';
818 $countParts = count( $domainParts );
819 for ( $i = 0; $i < $countParts; $i++ ) {
820 $domainPart = $domainParts[$i];
821 if ( $i == 0 ) {
822 $domain = $domainPart;
823 } else {
824 $domain = $domainPart . '.' . $domain;
825 }
826
827 if ( in_array( $domain, $this->localVirtualHosts ) ) {
828 return true;
829 }
830 }
831 }
832
833 return false;
834 }
835
842 private function getSelectTimeout( $opts ) {
843 $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
844 $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
845 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
846 if ( count( $timeouts ) === 0 ) {
847 return 1;
848 }
849
850 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
851 // Minimum 10us
852 if ( $selectTimeout < 10e-6 ) {
853 $selectTimeout = 10e-6;
854 }
855 return $selectTimeout;
856 }
857
861 public function setLogger( LoggerInterface $logger ): void {
862 $this->logger = $logger;
863 }
864
865 public function __destruct() {
866 if ( $this->cmh ) {
867 curl_multi_close( $this->cmh );
868 $this->cmh = null;
869 }
870 }
871
872}
874class_alias( MultiHttpClient::class, 'MultiHttpClient' );
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:68
Service locator for MediaWiki core services.
Class to handle multiple HTTP requests.
resource object null $cmh
curl_multi_init() handle, initialized in getCurlMulti()
__construct(array $options)
Since 1.35, callers should use HttpRequestFactory::createMultiClient() to get a client object with ap...
runMulti(array $reqs, array $opts=[], string $caller=__METHOD__)
Execute a set of HTTP(S) requests.
string null $caBundlePath
SSL certificates path.
getCurlHandle(array &$req, array $opts)
setLogger(LoggerInterface $logger)
Register a logger.
isCurlEnabled()
Determines if the curl extension is available.
run(array $req, array $opts=[], string $caller=__METHOD__)
Execute an HTTP(S) request.
Provide Request Telemetry information.
Utility for parsing a HTTP Accept header value into a weight map.