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 $this->logger ??=
new NullLogger;
156 public function run( array $req, array $opts = [] ) {
157 return $this->
runMulti( [ $req ], $opts )[0][
'response'];
191 public function runMulti( array $reqs, array $opts = [] ) {
192 $this->normalizeRequests( $reqs );
193 $opts += [
'connTimeout' => $this->connTimeout,
'reqTimeout' => $this->reqTimeout ];
195 if ( $this->maxConnTimeout && $opts[
'connTimeout'] > $this->maxConnTimeout ) {
196 $opts[
'connTimeout'] = $this->maxConnTimeout;
198 if ( $this->maxReqTimeout && $opts[
'reqTimeout'] > $this->maxReqTimeout ) {
199 $opts[
'reqTimeout'] = $this->maxReqTimeout;
203 switch ( $opts[
'httpVersion'] ??
null ) {
205 $opts[
'httpVersion'] = CURL_HTTP_VERSION_1_0;
208 $opts[
'httpVersion'] = CURL_HTTP_VERSION_1_1;
212 $opts[
'httpVersion'] = CURL_HTTP_VERSION_2_0;
215 $opts[
'httpVersion'] = CURL_HTTP_VERSION_NONE;
217 return $this->runMultiCurl( $reqs, $opts );
219 # TODO: Add handling for httpVersion option
220 return $this->runMultiHttp( $reqs, $opts );
232 return extension_loaded(
'curl' ) && function_exists(
'curl_multi_init' );
252 private function runMultiCurl( array $reqs, array $opts ) {
253 $chm = $this->getCurlMulti( $opts );
255 $selectTimeout = $this->getSelectTimeout( $opts );
259 foreach ( $reqs as $index => &$req ) {
260 $handles[$index] = $this->getCurlHandle( $req, $opts );
261 curl_multi_add_handle( $chm, $handles[$index] );
271 $mrc = curl_multi_exec( $chm, $active );
272 $info = curl_multi_info_read( $chm );
273 if ( $info !==
false ) {
277 $infos[(int)$info[
'handle']] = $info;
279 }
while ( $mrc == CURLM_CALL_MULTI_PERFORM );
281 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
285 }
while ( $active > 0 && $mrc == CURLM_OK );
288 foreach ( $reqs as $index => &$req ) {
289 $ch = $handles[$index];
290 curl_multi_remove_handle( $chm, $ch );
292 if ( isset( $infos[(
int)$ch] ) ) {
293 $info = $infos[(int)$ch];
294 $errno = $info[
'result'];
295 if ( $errno !== 0 ) {
296 $req[
'response'][
'error'] =
"(curl error: $errno)";
297 if ( function_exists(
'curl_strerror' ) ) {
298 $req[
'response'][
'error'] .=
" " . curl_strerror( $errno );
300 $this->logger->warning(
"Error fetching URL \"{$req['url']}\": " .
301 $req[
'response'][
'error'] );
303 $this->logger->debug(
304 "HTTP complete: {method} {url} code={response_code} size={size} " .
305 "total={total_time} connect={connect_time}",
307 'method' => $req[
'method'],
308 'url' => $req[
'url'],
309 'response_code' => $req[
'response'][
'code'],
310 'size' => curl_getinfo( $ch, CURLINFO_SIZE_DOWNLOAD ),
311 'total_time' => $this->getCurlTime(
312 $ch, CURLINFO_TOTAL_TIME,
'CURLINFO_TOTAL_TIME_T'
314 'connect_time' => $this->getCurlTime(
315 $ch, CURLINFO_CONNECT_TIME,
'CURLINFO_CONNECT_TIME_T'
321 $req[
'response'][
'error'] =
"(curl error: no status set)";
325 $req[
'response'][0] = $req[
'response'][
'code'];
326 $req[
'response'][1] = $req[
'response'][
'reason'];
327 $req[
'response'][2] = $req[
'response'][
'headers'];
328 $req[
'response'][3] = $req[
'response'][
'body'];
329 $req[
'response'][4] = $req[
'response'][
'error'];
332 if ( isset( $req[
'_closeHandle'] ) ) {
333 fclose( $req[
'_closeHandle'] );
334 unset( $req[
'_closeHandle'] );
357 curl_setopt( $ch, CURLOPT_PROXY, $req[
'proxy'] ?? $this->proxy );
358 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts[
'connTimeout'] * 1e3 ) );
359 curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts[
'reqTimeout'] * 1e3 ) );
360 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
361 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
362 curl_setopt( $ch, CURLOPT_HEADER, 0 );
363 if ( $this->caBundlePath !==
null ) {
364 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER,
true );
365 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
367 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
370 $query = http_build_query( $req[
'query'],
'',
'&', PHP_QUERY_RFC3986 );
371 if ( $query !=
'' ) {
372 $url .= strpos( $req[
'url'],
'?' ) ===
false ?
"?$query" :
"&$query";
374 curl_setopt( $ch, CURLOPT_URL, $url );
375 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req[
'method'] );
376 curl_setopt( $ch, CURLOPT_NOBODY, ( $req[
'method'] ===
'HEAD' ) );
377 curl_setopt( $ch, CURLOPT_HTTP_VERSION, $opts[
'httpVersion'] ?? CURL_HTTP_VERSION_NONE );
379 if ( $req[
'method'] ===
'PUT' ) {
380 curl_setopt( $ch, CURLOPT_PUT, 1 );
382 if ( is_resource( $req[
'body'] ) ) {
383 curl_setopt( $ch, CURLOPT_INFILE, $req[
'body'] );
384 if ( isset( $req[
'headers'][
'content-length'] ) ) {
385 curl_setopt( $ch, CURLOPT_INFILESIZE, $req[
'headers'][
'content-length'] );
386 } elseif ( isset( $req[
'headers'][
'transfer-encoding'] ) &&
387 $req[
'headers'][
'transfer-encoding'] ===
'chunks'
389 curl_setopt( $ch, CURLOPT_UPLOAD,
true );
391 throw new Exception(
"Missing 'Content-Length' or 'Transfer-Encoding' header." );
393 } elseif ( $req[
'body'] !==
'' ) {
394 $fp = fopen(
"php://temp",
"wb+" );
395 fwrite( $fp, $req[
'body'], strlen( $req[
'body'] ) );
397 curl_setopt( $ch, CURLOPT_INFILE, $fp );
398 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req[
'body'] ) );
399 $req[
'_closeHandle'] = $fp;
401 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
403 curl_setopt( $ch, CURLOPT_READFUNCTION,
404 static function ( $ch, $fd, $length ) {
405 return (
string)fread( $fd, $length );
408 } elseif ( $req[
'method'] ===
'POST' ) {
409 curl_setopt( $ch, CURLOPT_POST, 1 );
410 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req[
'body'] );
413 if ( is_resource( $req[
'body'] ) || $req[
'body'] !==
'' ) {
414 throw new Exception(
"HTTP body specified for a non PUT/POST request." );
416 $req[
'headers'][
'content-length'] = 0;
419 if ( !isset( $req[
'headers'][
'user-agent'] ) ) {
420 $req[
'headers'][
'user-agent'] = $this->userAgent;
424 foreach ( $req[
'headers'] as $name => $value ) {
425 if ( strpos( $name,
': ' ) ) {
426 throw new Exception(
"Headers cannot have ':' in the name." );
428 $headers[] = $name .
': ' . trim( $value );
430 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
432 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
433 static function ( $ch,
$header ) use ( &$req ) {
434 if ( !empty( $req[
'flags'][
'relayResponseHeaders'] ) && trim(
$header ) !==
'' ) {
439 if ( preg_match(
"/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/",
$header,
$matches ) ) {
440 $req[
'response'][
'code'] = (int)
$matches[2];
441 $req[
'response'][
'reason'] = trim(
$matches[3] );
444 $req[
'response'][
'headers'] = [];
447 if ( strpos(
$header,
":" ) ===
false ) {
450 [ $name, $value ] = explode(
":",
$header, 2 );
451 $name = strtolower( $name );
452 $value = trim( $value );
453 if ( isset( $req[
'response'][
'headers'][$name] ) ) {
454 $req[
'response'][
'headers'][$name] .=
', ' . $value;
456 $req[
'response'][
'headers'][$name] = $value;
463 $hasOutputStream = isset( $req[
'stream'] );
464 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
465 static function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
466 if ( $hasOutputStream ) {
468 return fwrite( $req[
'stream'], $data );
471 $req[
'response'][
'body'] .= $data;
473 return strlen( $data );
489 $cmh = curl_multi_init();
492 curl_multi_setopt(
$cmh, CURLMOPT_MAXCONNECTS, (
int)$this->maxConnsPerHost );
496 $curlVersion = curl_version()[
'version'];
499 if ( version_compare( $curlVersion,
'7.30.0',
'>=' ) ) {
501 $maxHostConns = $opts[
'maxConnsPerHost'] ?? $this->maxConnsPerHost;
502 curl_multi_setopt( $this->cmh, CURLMOPT_MAX_HOST_CONNECTIONS, (
int)$maxHostConns );
505 if ( $opts[
'usePipelining'] ?? $this->usePipelining ) {
506 if ( version_compare( $curlVersion,
'7.43',
'<' ) ) {
509 } elseif ( version_compare( $curlVersion,
'7.62',
'<' ) ) {
511 $pipelining = CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX;
514 $pipelining = CURLPIPE_MULTIPLEX;
518 @curl_multi_setopt( $this->cmh, CURLMOPT_PIPELINING, $pipelining );
534 private function getCurlTime( $ch, $oldOption, $newConstName ): string {
535 if ( defined( $newConstName ) ) {
536 return sprintf(
"%.6F", curl_getinfo( $ch, constant( $newConstName ) ) / 1e6 );
538 return (
string)curl_getinfo( $ch, $oldOption );
557 private function runMultiHttp( array $reqs, array $opts = [] ) {
559 'timeout' => $opts[
'reqTimeout'] ?? $this->reqTimeout,
560 'connectTimeout' => $opts[
'connTimeout'] ?? $this->connTimeout,
561 'logger' => $this->logger,
562 'caInfo' => $this->caBundlePath,
564 foreach ( $reqs as &$req ) {
565 $reqOptions = $httpOptions + [
566 'method' => $req[
'method'],
567 'proxy' => $req[
'proxy'] ?? $this->proxy,
568 'userAgent' => $req[
'headers'][
'user-agent'] ?? $this->userAgent,
569 'postData' => $req[
'body'],
573 $query = http_build_query( $req[
'query'],
'',
'&', PHP_QUERY_RFC3986 );
574 if ( $query !=
'' ) {
575 $url .= strpos( $req[
'url'],
'?' ) ===
false ?
"?$query" :
"&$query";
578 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
579 $url, $reqOptions, __METHOD__ );
580 $httpRequest->setLogger( $this->logger );
581 $sv = $httpRequest->execute()->getStatusValue();
583 $respHeaders = array_map(
584 static function ( $v ) {
585 return implode(
', ', $v );
587 $httpRequest->getResponseHeaders() );
590 'code' => $httpRequest->getStatus(),
592 'headers' => $respHeaders,
593 'body' => $httpRequest->getContent(),
597 if ( !$sv->isOK() ) {
598 $svErrors = $sv->getErrors();
599 if ( isset( $svErrors[0] ) ) {
600 $req[
'response'][
'error'] = $svErrors[0][
'message'];
603 if ( isset( $svErrors[0][
'params'][0] ) ) {
604 if ( is_numeric( $svErrors[0][
'params'][0] ) ) {
605 if ( isset( $svErrors[0][
'params'][1] ) ) {
607 $req[
'response'][
'reason'] = $svErrors[0][
'params'][1];
610 $req[
'response'][
'reason'] = $svErrors[0][
'params'][0];
616 $req[
'response'][0] = $req[
'response'][
'code'];
617 $req[
'response'][1] = $req[
'response'][
'reason'];
618 $req[
'response'][2] = $req[
'response'][
'headers'];
619 $req[
'response'][3] = $req[
'response'][
'body'];
620 $req[
'response'][4] = $req[
'response'][
'error'];
631 private function normalizeRequests( array &$reqs ) {
632 foreach ( $reqs as &$req ) {
640 if ( isset( $req[0] ) ) {
641 $req[
'method'] = $req[0];
644 if ( isset( $req[1] ) ) {
645 $req[
'url'] = $req[1];
648 if ( !isset( $req[
'method'] ) ) {
649 throw new Exception(
"Request has no 'method' field set." );
650 } elseif ( !isset( $req[
'url'] ) ) {
651 throw new Exception(
"Request has no 'url' field set." );
653 if ( $this->localProxy !==
false && $this->isLocalURL( $req[
'url'] ) ) {
654 $this->useReverseProxy( $req, $this->localProxy );
656 $req[
'query'] ??= [];
658 if ( isset( $req[
'headers'] ) ) {
659 foreach ( $req[
'headers'] as $name => $value ) {
660 $headers[strtolower( $name )] = $value;
663 $req[
'headers'] = $headers;
664 if ( !isset( $req[
'body'] ) ) {
666 $req[
'headers'][
'content-length'] = 0;
669 $logHeaders = $req[
'headers'];
670 foreach ( $logHeaders as
$header => $value ) {
671 if ( preg_match( self::SENSITIVE_HEADERS,
$header ) === 1 ) {
672 $logHeaders[
$header] =
'[redacted]';
675 $this->logger->debug(
"HTTP start: {method} {url}",
677 'method' => $req[
'method'],
678 'url' => $req[
'url'],
679 'headers' => $logHeaders,
682 $req[
'flags'] ??= [];
686 private function useReverseProxy( array &$req, $proxy ) {
688 if ( $parsedProxy ===
false ) {
689 throw new Exception(
"Invalid reverseProxy configured: $proxy" );
692 if ( $parsedUrl ===
false ) {
693 throw new Exception(
"Invalid url specified: {$req['url']}" );
696 $req[
'headers'][
'Host'] = $parsedUrl[
'host'];
698 $parsedUrl[
'scheme'] = $parsedProxy[
'scheme'];
699 $parsedUrl[
'host'] = $parsedProxy[
'host'];
700 if ( isset( $parsedProxy[
'port'] ) ) {
701 $parsedUrl[
'port'] = $parsedProxy[
'port'];
703 unset( $parsedUrl[
'port'] );
708 $req[
'proxy'] =
false;
718 private function isLocalURL( $url ) {
719 if ( !$this->localVirtualHosts ) {
726 if ( preg_match(
'!^https?://([\w.-]+)[/:].*$!', $url,
$matches ) ) {
729 $domainParts = explode(
'.', $host );
731 $domainParts = array_reverse( $domainParts );
734 $countParts = count( $domainParts );
735 for ( $i = 0; $i < $countParts; $i++ ) {
736 $domainPart = $domainParts[$i];
738 $domain = $domainPart;
740 $domain = $domainPart .
'.' . $domain;
743 if ( in_array( $domain, $this->localVirtualHosts ) ) {
758 private function getSelectTimeout( $opts ) {
759 $connTimeout = $opts[
'connTimeout'] ?? $this->connTimeout;
760 $reqTimeout = $opts[
'reqTimeout'] ?? $this->reqTimeout;
761 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
762 if ( count( $timeouts ) === 0 ) {
766 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
768 if ( $selectTimeout < 10e-6 ) {
769 $selectTimeout = 10e-6;
771 return $selectTimeout;
780 $this->logger = $logger;
785 curl_multi_close( $this->cmh );