57 private const SENSITIVE_HEADERS =
'/(^|-|_)(authorization|auth|password|cookie)($|-|_)/';
84 protected $userAgent =
'wikimedia/multi-http-client v1.0';
91 private const TIMEOUT_ACCURACY_FACTOR = 0.1;
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 );
121 'connTimeout',
'maxConnTimeout',
'reqTimeout',
'maxReqTimeout',
122 'usePipelining',
'maxConnsPerHost',
'proxy',
'userAgent',
'logger',
123 'localProxy',
'localVirtualHosts',
125 foreach ( $opts as $key ) {
126 if ( isset( $options[$key] ) ) {
127 $this->$key = $options[$key];
130 if ( $this->logger ===
null ) {
131 $this->logger =
new NullLogger;
158 public function run( array $req, array $opts = [] ) {
159 return $this->
runMulti( [ $req ], $opts )[0][
'response'];
193 public function runMulti( array $reqs, array $opts = [] ) {
194 $this->normalizeRequests( $reqs );
195 $opts += [
'connTimeout' => $this->connTimeout,
'reqTimeout' => $this->reqTimeout ];
197 if ( $this->maxConnTimeout && $opts[
'connTimeout'] > $this->maxConnTimeout ) {
198 $opts[
'connTimeout'] = $this->maxConnTimeout;
200 if ( $this->maxReqTimeout && $opts[
'reqTimeout'] > $this->maxReqTimeout ) {
201 $opts[
'reqTimeout'] = $this->maxReqTimeout;
205 switch ( $opts[
'httpVersion'] ??
null ) {
207 $opts[
'httpVersion'] = CURL_HTTP_VERSION_1_0;
210 $opts[
'httpVersion'] = CURL_HTTP_VERSION_1_1;
214 $opts[
'httpVersion'] = CURL_HTTP_VERSION_2_0;
217 $opts[
'httpVersion'] = CURL_HTTP_VERSION_NONE;
219 return $this->runMultiCurl( $reqs, $opts );
221 # TODO: Add handling for httpVersion option
222 return $this->runMultiHttp( $reqs, $opts );
234 return extension_loaded(
'curl' ) && function_exists(
'curl_multi_init' );
254 private function runMultiCurl( array $reqs, array $opts ) {
255 $chm = $this->getCurlMulti( $opts );
257 $selectTimeout = $this->getSelectTimeout( $opts );
261 foreach ( $reqs as $index => &$req ) {
262 $handles[$index] = $this->getCurlHandle( $req, $opts );
263 curl_multi_add_handle( $chm, $handles[$index] );
273 $mrc = curl_multi_exec( $chm, $active );
274 $info = curl_multi_info_read( $chm );
275 if ( $info !==
false ) {
279 $infos[(int)$info[
'handle']] = $info;
281 }
while ( $mrc == CURLM_CALL_MULTI_PERFORM );
283 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
287 }
while ( $active > 0 && $mrc == CURLM_OK );
290 foreach ( $reqs as $index => &$req ) {
291 $ch = $handles[$index];
292 curl_multi_remove_handle( $chm, $ch );
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 );
302 $this->logger->warning(
"Error fetching URL \"{$req['url']}\": " .
303 $req[
'response'][
'error'] );
305 $this->logger->debug(
306 "HTTP complete: {method} {url} code={response_code} size={size} " .
307 "total={total_time} connect={connect_time}",
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'
316 'connect_time' => $this->getCurlTime(
317 $ch, CURLINFO_CONNECT_TIME,
'CURLINFO_CONNECT_TIME_T'
323 $req[
'response'][
'error'] =
"(curl error: no status set)";
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'];
334 if ( isset( $req[
'_closeHandle'] ) ) {
335 fclose( $req[
'_closeHandle'] );
336 unset( $req[
'_closeHandle'] );
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 );
369 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
372 $query = http_build_query( $req[
'query'],
'',
'&', PHP_QUERY_RFC3986 );
373 if ( $query !=
'' ) {
374 $url .= strpos( $req[
'url'],
'?' ) ===
false ?
"?$query" :
"&$query";
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 );
381 if ( $req[
'method'] ===
'PUT' ) {
382 curl_setopt( $ch, CURLOPT_PUT, 1 );
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'
391 curl_setopt( $ch, CURLOPT_UPLOAD,
true );
393 throw new Exception(
"Missing 'Content-Length' or 'Transfer-Encoding' header." );
395 } elseif ( $req[
'body'] !==
'' ) {
396 $fp = fopen(
"php://temp",
"wb+" );
397 fwrite( $fp, $req[
'body'], strlen( $req[
'body'] ) );
399 curl_setopt( $ch, CURLOPT_INFILE, $fp );
400 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req[
'body'] ) );
401 $req[
'_closeHandle'] = $fp;
403 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
405 curl_setopt( $ch, CURLOPT_READFUNCTION,
406 static function ( $ch, $fd, $length ) {
407 return (
string)fread( $fd, $length );
410 } elseif ( $req[
'method'] ===
'POST' ) {
411 curl_setopt( $ch, CURLOPT_POST, 1 );
412 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req[
'body'] );
415 if ( is_resource( $req[
'body'] ) || $req[
'body'] !==
'' ) {
416 throw new Exception(
"HTTP body specified for a non PUT/POST request." );
418 $req[
'headers'][
'content-length'] = 0;
421 if ( !isset( $req[
'headers'][
'user-agent'] ) ) {
422 $req[
'headers'][
'user-agent'] = $this->userAgent;
426 foreach ( $req[
'headers'] as $name => $value ) {
427 if ( strpos( $name,
': ' ) ) {
428 throw new Exception(
"Headers cannot have ':' in the name." );
430 $headers[] = $name .
': ' . trim( $value );
432 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
434 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
435 static function ( $ch,
$header ) use ( &$req ) {
436 if ( !empty( $req[
'flags'][
'relayResponseHeaders'] ) && trim(
$header ) !==
'' ) {
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] );
446 $req[
'response'][
'headers'] = [];
449 if ( strpos(
$header,
":" ) ===
false ) {
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;
458 $req[
'response'][
'headers'][$name] = $value;
465 $hasOutputStream = isset( $req[
'stream'] );
466 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
467 static function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
468 if ( $hasOutputStream ) {
470 return fwrite( $req[
'stream'], $data );
473 $req[
'response'][
'body'] .= $data;
475 return strlen( $data );
491 $cmh = curl_multi_init();
494 curl_multi_setopt(
$cmh, CURLMOPT_MAXCONNECTS, (
int)$this->maxConnsPerHost );
498 $curlVersion = curl_version()[
'version'];
501 if ( version_compare( $curlVersion,
'7.30.0',
'>=' ) ) {
503 $maxHostConns = $opts[
'maxConnsPerHost'] ?? $this->maxConnsPerHost;
504 curl_multi_setopt( $this->cmh, CURLMOPT_MAX_HOST_CONNECTIONS, (
int)$maxHostConns );
507 if ( $opts[
'usePipelining'] ?? $this->usePipelining ) {
508 if ( version_compare( $curlVersion,
'7.43',
'<' ) ) {
511 } elseif ( version_compare( $curlVersion,
'7.62',
'<' ) ) {
513 $pipelining = CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX;
516 $pipelining = CURLPIPE_MULTIPLEX;
520 @curl_multi_setopt( $this->cmh, CURLMOPT_PIPELINING, $pipelining );
536 private function getCurlTime( $ch, $oldOption, $newConstName ): string {
537 if ( defined( $newConstName ) ) {
538 return sprintf(
"%.6F", curl_getinfo( $ch, constant( $newConstName ) ) / 1e6 );
540 return (
string)curl_getinfo( $ch, $oldOption );
559 private function runMultiHttp( array $reqs, array $opts = [] ) {
561 'timeout' => $opts[
'reqTimeout'] ?? $this->reqTimeout,
562 'connectTimeout' => $opts[
'connTimeout'] ?? $this->connTimeout,
563 'logger' => $this->logger,
564 'caInfo' => $this->caBundlePath,
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'],
575 $query = http_build_query( $req[
'query'],
'',
'&', PHP_QUERY_RFC3986 );
576 if ( $query !=
'' ) {
577 $url .= strpos( $req[
'url'],
'?' ) ===
false ?
"?$query" :
"&$query";
580 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
581 $url, $reqOptions, __METHOD__ );
582 $httpRequest->setLogger( $this->logger );
583 $sv = $httpRequest->execute()->getStatusValue();
585 $respHeaders = array_map(
586 static function ( $v ) {
587 return implode(
', ', $v );
589 $httpRequest->getResponseHeaders() );
592 'code' => $httpRequest->getStatus(),
594 'headers' => $respHeaders,
595 'body' => $httpRequest->getContent(),
599 if ( !$sv->isOK() ) {
600 $svErrors = $sv->getErrors();
601 if ( isset( $svErrors[0] ) ) {
602 $req[
'response'][
'error'] = $svErrors[0][
'message'];
605 if ( isset( $svErrors[0][
'params'][0] ) ) {
606 if ( is_numeric( $svErrors[0][
'params'][0] ) ) {
607 if ( isset( $svErrors[0][
'params'][1] ) ) {
609 $req[
'response'][
'reason'] = $svErrors[0][
'params'][1];
612 $req[
'response'][
'reason'] = $svErrors[0][
'params'][0];
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'];
633 private function normalizeRequests( array &$reqs ) {
634 foreach ( $reqs as &$req ) {
642 if ( isset( $req[0] ) ) {
643 $req[
'method'] = $req[0];
646 if ( isset( $req[1] ) ) {
647 $req[
'url'] = $req[1];
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." );
655 if ( $this->localProxy !==
false && $this->isLocalURL( $req[
'url'] ) ) {
656 $this->useReverseProxy( $req, $this->localProxy );
658 $req[
'query'] = $req[
'query'] ?? [];
660 if ( isset( $req[
'headers'] ) ) {
661 foreach ( $req[
'headers'] as $name => $value ) {
662 $headers[strtolower( $name )] = $value;
665 $req[
'headers'] = $headers;
666 if ( !isset( $req[
'body'] ) ) {
668 $req[
'headers'][
'content-length'] = 0;
671 $logHeaders = $req[
'headers'];
672 foreach ( $logHeaders as
$header => $value ) {
673 if ( preg_match( self::SENSITIVE_HEADERS,
$header ) === 1 ) {
674 $logHeaders[
$header] =
'[redacted]';
677 $this->logger->debug(
"HTTP start: {method} {url}",
679 'method' => $req[
'method'],
680 'url' => $req[
'url'],
681 'headers' => $logHeaders,
684 $req[
'flags'] = $req[
'flags'] ?? [];
688 private function useReverseProxy( array &$req, $proxy ) {
690 if ( $parsedProxy ===
false ) {
691 throw new Exception(
"Invalid reverseProxy configured: $proxy" );
694 if ( $parsedUrl ===
false ) {
695 throw new Exception(
"Invalid url specified: {$req['url']}" );
698 $req[
'headers'][
'Host'] = $parsedUrl[
'host'];
700 $parsedUrl[
'scheme'] = $parsedProxy[
'scheme'];
701 $parsedUrl[
'host'] = $parsedProxy[
'host'];
702 if ( isset( $parsedProxy[
'port'] ) ) {
703 $parsedUrl[
'port'] = $parsedProxy[
'port'];
705 unset( $parsedUrl[
'port'] );
710 $req[
'proxy'] =
false;
720 private function isLocalURL( $url ) {
721 if ( !$this->localVirtualHosts ) {
728 if ( preg_match(
'!^https?://([\w.-]+)[/:].*$!', $url,
$matches ) ) {
731 $domainParts = explode(
'.', $host );
733 $domainParts = array_reverse( $domainParts );
736 $countParts = count( $domainParts );
737 for ( $i = 0; $i < $countParts; $i++ ) {
738 $domainPart = $domainParts[$i];
740 $domain = $domainPart;
742 $domain = $domainPart .
'.' . $domain;
745 if ( in_array( $domain, $this->localVirtualHosts ) ) {
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 ) {
768 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
770 if ( $selectTimeout < 10e-6 ) {
771 $selectTimeout = 10e-6;
773 return $selectTimeout;
782 $this->logger = $logger;
787 curl_multi_close( $this->cmh );