MediaWiki  master
MultiHttpClient.php
Go to the documentation of this file.
1 <?php
24 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\NullLogger;
27 
55 class MultiHttpClient implements LoggerAwareInterface {
57  protected $cmh;
59  protected $caBundlePath;
61  protected $connTimeout = 10;
63  protected $maxConnTimeout = INF;
65  protected $reqTimeout = 30;
67  protected $maxReqTimeout = INF;
69  protected $usePipelining = false;
71  protected $maxConnsPerHost = 50;
73  protected $proxy;
75  protected $userAgent = 'wikimedia/multi-http-client v1.0';
77  protected $logger;
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 
102  public function __construct( array $options ) {
103  if ( isset( $options['caBundlePath'] ) ) {
104  $this->caBundlePath = $options['caBundlePath'];
105  if ( !file_exists( $this->caBundlePath ) ) {
106  throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
107  }
108  }
109  static $opts = [
110  'connTimeout', 'maxConnTimeout', 'reqTimeout', 'maxReqTimeout',
111  'usePipelining', 'maxConnsPerHost', 'proxy', 'userAgent', 'logger'
112  ];
113  foreach ( $opts as $key ) {
114  if ( isset( $options[$key] ) ) {
115  $this->$key = $options[$key];
116  }
117  }
118  if ( $this->logger === null ) {
119  $this->logger = new NullLogger;
120  }
121  }
122 
144  public function run( array $req, array $opts = [] ) {
145  return $this->runMulti( [ $req ], $opts )[0]['response'];
146  }
147 
177  public function runMulti( array $reqs, array $opts = [] ) {
178  $this->normalizeRequests( $reqs );
179  $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
180 
181  if ( $opts['connTimeout'] > $this->maxConnTimeout ) {
182  $opts['connTimeout'] = $this->maxConnTimeout;
183  }
184  if ( $opts['reqTimeout'] > $this->maxReqTimeout ) {
185  $opts['reqTimeout'] = $this->maxReqTimeout;
186  }
187 
188  if ( $this->isCurlEnabled() ) {
189  return $this->runMultiCurl( $reqs, $opts );
190  } else {
191  return $this->runMultiHttp( $reqs, $opts );
192  }
193  }
194 
200  protected function isCurlEnabled() {
201  // Explicitly test if curl_multi* is blocked, as some users' hosts provide
202  // them with a modified curl with the multi-threaded parts removed(!)
203  return extension_loaded( 'curl' ) && function_exists( 'curl_multi_init' );
204  }
205 
222  private function runMultiCurl( array $reqs, array $opts ) {
223  $chm = $this->getCurlMulti( $opts );
224 
225  $selectTimeout = $this->getSelectTimeout( $opts );
226 
227  // Add all of the required cURL handles...
228  $handles = [];
229  foreach ( $reqs as $index => &$req ) {
230  $handles[$index] = $this->getCurlHandle( $req, $opts );
231  curl_multi_add_handle( $chm, $handles[$index] );
232  }
233  unset( $req ); // don't assign over this by accident
234 
235  $infos = [];
236  // Execute the cURL handles concurrently...
237  $active = null; // handles still being processed
238  do {
239  // Do any available work...
240  do {
241  $mrc = curl_multi_exec( $chm, $active );
242  $info = curl_multi_info_read( $chm );
243  if ( $info !== false ) {
244  $infos[(int)$info['handle']] = $info;
245  }
246  } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
247  // Wait (if possible) for available work...
248  if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
249  // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
250  usleep( 5000 ); // 5ms
251  }
252  } while ( $active > 0 && $mrc == CURLM_OK );
253 
254  // Remove all of the added cURL handles and check for errors...
255  foreach ( $reqs as $index => &$req ) {
256  $ch = $handles[$index];
257  curl_multi_remove_handle( $chm, $ch );
258 
259  if ( isset( $infos[(int)$ch] ) ) {
260  $info = $infos[(int)$ch];
261  $errno = $info['result'];
262  if ( $errno !== 0 ) {
263  $req['response']['error'] = "(curl error: $errno)";
264  if ( function_exists( 'curl_strerror' ) ) {
265  $req['response']['error'] .= " " . curl_strerror( $errno );
266  }
267  $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
268  $req['response']['error'] );
269  } else {
270  $this->logger->debug(
271  "HTTP complete: {method} {url} code={response_code} size={size} " .
272  "total={total_time} connect={connect_time}",
273  [
274  'method' => $req['method'],
275  'url' => $req['url'],
276  'response_code' => $req['response']['code'],
277  'size' => curl_getinfo( $ch, CURLINFO_SIZE_DOWNLOAD ),
278  'total_time' => $this->getCurlTime(
279  $ch, CURLINFO_TOTAL_TIME, 'CURLINFO_TOTAL_TIME_T'
280  ),
281  'connect_time' => $this->getCurlTime(
282  $ch, CURLINFO_CONNECT_TIME, 'CURLINFO_CONNECT_TIME_T'
283  ),
284  ]
285  );
286  }
287  } else {
288  $req['response']['error'] = "(curl error: no status set)";
289  }
290 
291  // For convenience with the list() operator
292  $req['response'][0] = $req['response']['code'];
293  $req['response'][1] = $req['response']['reason'];
294  $req['response'][2] = $req['response']['headers'];
295  $req['response'][3] = $req['response']['body'];
296  $req['response'][4] = $req['response']['error'];
297  curl_close( $ch );
298  // Close any string wrapper file handles
299  if ( isset( $req['_closeHandle'] ) ) {
300  fclose( $req['_closeHandle'] );
301  unset( $req['_closeHandle'] );
302  }
303  }
304  unset( $req ); // don't assign over this by accident
305 
306  return $reqs;
307  }
308 
319  protected function getCurlHandle( array &$req, array $opts ) {
320  $ch = curl_init();
321 
322  curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
323  curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
324  curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
325  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
326  curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
327  curl_setopt( $ch, CURLOPT_HEADER, 0 );
328  if ( $this->caBundlePath !== null ) {
329  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
330  curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
331  }
332  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
333 
334  $url = $req['url'];
335  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
336  if ( $query != '' ) {
337  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
338  }
339  curl_setopt( $ch, CURLOPT_URL, $url );
340  curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
341  curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
342 
343  if ( $req['method'] === 'PUT' ) {
344  curl_setopt( $ch, CURLOPT_PUT, 1 );
345  if ( is_resource( $req['body'] ) ) {
346  curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
347  if ( isset( $req['headers']['content-length'] ) ) {
348  curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
349  } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
350  $req['headers']['transfer-encoding'] === 'chunks'
351  ) {
352  curl_setopt( $ch, CURLOPT_UPLOAD, true );
353  } else {
354  throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
355  }
356  } elseif ( $req['body'] !== '' ) {
357  $fp = fopen( "php://temp", "wb+" );
358  fwrite( $fp, $req['body'], strlen( $req['body'] ) );
359  rewind( $fp );
360  curl_setopt( $ch, CURLOPT_INFILE, $fp );
361  curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
362  $req['_closeHandle'] = $fp; // remember to close this later
363  } else {
364  curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
365  }
366  curl_setopt( $ch, CURLOPT_READFUNCTION,
367  static function ( $ch, $fd, $length ) {
368  return (string)fread( $fd, $length );
369  }
370  );
371  } elseif ( $req['method'] === 'POST' ) {
372  curl_setopt( $ch, CURLOPT_POST, 1 );
373  curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
374  } else {
375  if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
376  throw new Exception( "HTTP body specified for a non PUT/POST request." );
377  }
378  $req['headers']['content-length'] = 0;
379  }
380 
381  if ( !isset( $req['headers']['user-agent'] ) ) {
382  $req['headers']['user-agent'] = $this->userAgent;
383  }
384 
385  $headers = [];
386  foreach ( $req['headers'] as $name => $value ) {
387  if ( strpos( $name, ': ' ) ) {
388  throw new Exception( "Headers cannot have ':' in the name." );
389  }
390  $headers[] = $name . ': ' . trim( $value );
391  }
392  curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
393 
394  curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
395  static function ( $ch, $header ) use ( &$req ) {
396  if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
397  header( $header );
398  }
399  $length = strlen( $header );
400  $matches = [];
401  if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
402  $req['response']['code'] = (int)$matches[2];
403  $req['response']['reason'] = trim( $matches[3] );
404  // After a redirect we will receive this again, but we already stored headers
405  // that belonged to a redirect response. Start over.
406  $req['response']['headers'] = [];
407  return $length;
408  }
409  if ( strpos( $header, ":" ) === false ) {
410  return $length;
411  }
412  list( $name, $value ) = explode( ":", $header, 2 );
413  $name = strtolower( $name );
414  $value = trim( $value );
415  if ( isset( $req['response']['headers'][$name] ) ) {
416  $req['response']['headers'][$name] .= ', ' . $value;
417  } else {
418  $req['response']['headers'][$name] = $value;
419  }
420  return $length;
421  }
422  );
423 
424  // This works with both file and php://temp handles (unlike CURLOPT_FILE)
425  $hasOutputStream = isset( $req['stream'] );
426  curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
427  static function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
428  if ( $hasOutputStream ) {
429  return fwrite( $req['stream'], $data );
430  } else {
431  // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
432  $req['response']['body'] .= $data;
433 
434  return strlen( $data );
435  }
436  }
437  );
438 
439  return $ch;
440  }
441 
447  protected function getCurlMulti( array $opts ) {
448  if ( !$this->cmh ) {
449  $cmh = curl_multi_init();
450  // Limit the size of the idle connection cache such that consecutive parallel
451  // request batches to the same host can avoid having to keep making connections
452  curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
453  $this->cmh = $cmh;
454  }
455 
456  // CURLMOPT_MAX_HOST_CONNECTIONS is available since PHP 7.0.7 and cURL 7.30.0
457  if ( version_compare( curl_version()['version'], '7.30.0', '>=' ) ) {
458  // Limit the number of in-flight requests for any given host
459  $maxHostConns = $opts['maxConnsPerHost'] ?? $this->maxConnsPerHost;
460  curl_multi_setopt( $this->cmh, CURLMOPT_MAX_HOST_CONNECTIONS, (int)$maxHostConns );
461  }
462 
463  // Configure when to multiplex multiple requests onto single TCP handles
464  $pipelining = $opts['usePipelining'] ?? $this->usePipelining;
465  curl_multi_setopt( $this->cmh, CURLMOPT_PIPELINING, $pipelining ? 3 : 0 );
466 
467  return $this->cmh;
468  }
469 
479  private function getCurlTime( $ch, $oldOption, $newConstName ): string {
480  if ( defined( $newConstName ) ) {
481  return sprintf( "%.6f", curl_getinfo( $ch, constant( $newConstName ) ) / 1e6 );
482  } else {
483  return (string)curl_getinfo( $ch, $oldOption );
484  }
485  }
486 
503  private function runMultiHttp( array $reqs, array $opts = [] ) {
504  $httpOptions = [
505  'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
506  'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
507  'logger' => $this->logger,
508  'caInfo' => $this->caBundlePath,
509  ];
510  foreach ( $reqs as &$req ) {
511  $reqOptions = $httpOptions + [
512  'method' => $req['method'],
513  'proxy' => $req['proxy'] ?? $this->proxy,
514  'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
515  'postData' => $req['body'],
516  ];
517 
518  $url = $req['url'];
519  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
520  if ( $query != '' ) {
521  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
522  }
523 
524  $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
525  $url, $reqOptions, __METHOD__ );
526  $httpRequest->setLogger( $this->logger );
527  $sv = $httpRequest->execute()->getStatusValue();
528 
529  $respHeaders = array_map(
530  static function ( $v ) {
531  return implode( ', ', $v );
532  },
533  $httpRequest->getResponseHeaders() );
534 
535  $req['response'] = [
536  'code' => $httpRequest->getStatus(),
537  'reason' => '',
538  'headers' => $respHeaders,
539  'body' => $httpRequest->getContent(),
540  'error' => '',
541  ];
542 
543  if ( !$sv->isOK() ) {
544  $svErrors = $sv->getErrors();
545  if ( isset( $svErrors[0] ) ) {
546  $req['response']['error'] = $svErrors[0]['message'];
547 
548  // param values vary per failure type (ex. unknown host vs unknown page)
549  if ( isset( $svErrors[0]['params'][0] ) ) {
550  if ( is_numeric( $svErrors[0]['params'][0] ) ) {
551  if ( isset( $svErrors[0]['params'][1] ) ) {
552  // @phan-suppress-next-line PhanTypeInvalidDimOffset
553  $req['response']['reason'] = $svErrors[0]['params'][1];
554  }
555  } else {
556  $req['response']['reason'] = $svErrors[0]['params'][0];
557  }
558  }
559  }
560  }
561 
562  $req['response'][0] = $req['response']['code'];
563  $req['response'][1] = $req['response']['reason'];
564  $req['response'][2] = $req['response']['headers'];
565  $req['response'][3] = $req['response']['body'];
566  $req['response'][4] = $req['response']['error'];
567  }
568 
569  return $reqs;
570  }
571 
577  private function normalizeRequests( array &$reqs ) {
578  foreach ( $reqs as &$req ) {
579  $req['response'] = [
580  'code' => 0,
581  'reason' => '',
582  'headers' => [],
583  'body' => '',
584  'error' => ''
585  ];
586  if ( isset( $req[0] ) ) {
587  $req['method'] = $req[0]; // short-form
588  unset( $req[0] );
589  }
590  if ( isset( $req[1] ) ) {
591  $req['url'] = $req[1]; // short-form
592  unset( $req[1] );
593  }
594  if ( !isset( $req['method'] ) ) {
595  throw new Exception( "Request has no 'method' field set." );
596  } elseif ( !isset( $req['url'] ) ) {
597  throw new Exception( "Request has no 'url' field set." );
598  }
599  $this->logger->debug( "HTTP start: {method} {url}",
600  [
601  'method' => $req['method'],
602  'url' => $req['url'],
603  ]
604  );
605  $req['query'] = $req['query'] ?? [];
606  $headers = []; // normalized headers
607  if ( isset( $req['headers'] ) ) {
608  foreach ( $req['headers'] as $name => $value ) {
609  $headers[strtolower( $name )] = $value;
610  }
611  }
612  $req['headers'] = $headers;
613  if ( !isset( $req['body'] ) ) {
614  $req['body'] = '';
615  $req['headers']['content-length'] = 0;
616  }
617  $req['flags'] = $req['flags'] ?? [];
618  }
619  }
620 
627  private function getSelectTimeout( $opts ) {
628  $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
629  $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
630  $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
631  if ( count( $timeouts ) === 0 ) {
632  return 1;
633  }
634 
635  $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
636  // Minimum 10us for sanity
637  if ( $selectTimeout < 10e-6 ) {
638  $selectTimeout = 10e-6;
639  }
640  return $selectTimeout;
641  }
642 
648  public function setLogger( LoggerInterface $logger ) {
649  $this->logger = $logger;
650  }
651 
652  public function __destruct() {
653  if ( $this->cmh ) {
654  curl_multi_close( $this->cmh );
655  }
656  }
657 }
MultiHttpClient
Class to handle multiple HTTP requests.
Definition: MultiHttpClient.php:55
MultiHttpClient\$usePipelining
bool $usePipelining
Definition: MultiHttpClient.php:69
MultiHttpClient\$maxConnsPerHost
int $maxConnsPerHost
Definition: MultiHttpClient.php:71
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:193
MultiHttpClient\$reqTimeout
float $reqTimeout
Definition: MultiHttpClient.php:65
MultiHttpClient\run
run(array $req, array $opts=[])
Execute an HTTP(S) request.
Definition: MultiHttpClient.php:144
MultiHttpClient\__destruct
__destruct()
Definition: MultiHttpClient.php:652
MultiHttpClient\$connTimeout
float $connTimeout
Definition: MultiHttpClient.php:61
MultiHttpClient\$maxReqTimeout
float $maxReqTimeout
Definition: MultiHttpClient.php:67
$matches
$matches
Definition: NoLocalSettings.php:24
MultiHttpClient\$caBundlePath
string null $caBundlePath
SSL certificates path.
Definition: MultiHttpClient.php:59
MultiHttpClient\getSelectTimeout
getSelectTimeout( $opts)
Get a suitable select timeout for the given options.
Definition: MultiHttpClient.php:627
MultiHttpClient\setLogger
setLogger(LoggerInterface $logger)
Register a logger.
Definition: MultiHttpClient.php:648
MultiHttpClient\runMultiHttp
runMultiHttp(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests sequentially.
Definition: MultiHttpClient.php:503
MultiHttpClient\getCurlHandle
getCurlHandle(array &$req, array $opts)
Definition: MultiHttpClient.php:319
$header
$header
Definition: updateCredits.php:37
MultiHttpClient\isCurlEnabled
isCurlEnabled()
Determines if the curl extension is available.
Definition: MultiHttpClient.php:200
MultiHttpClient\$userAgent
string $userAgent
Definition: MultiHttpClient.php:75
MultiHttpClient\runMulti
runMulti(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests.
Definition: MultiHttpClient.php:177
MultiHttpClient\$proxy
string null $proxy
proxy
Definition: MultiHttpClient.php:73
MultiHttpClient\runMultiCurl
runMultiCurl(array $reqs, array $opts)
Execute a set of HTTP(S) requests concurrently.
Definition: MultiHttpClient.php:222
MultiHttpClient\__construct
__construct(array $options)
Since 1.35, callers should use HttpRequestFactory::createMultiClient() to get a client object with ap...
Definition: MultiHttpClient.php:102
MultiHttpClient\TIMEOUT_ACCURACY_FACTOR
const TIMEOUT_ACCURACY_FACTOR
Definition: MultiHttpClient.php:82
MultiHttpClient\getCurlMulti
getCurlMulti(array $opts)
Definition: MultiHttpClient.php:447
MultiHttpClient\$maxConnTimeout
float $maxConnTimeout
Definition: MultiHttpClient.php:63
MultiHttpClient\normalizeRequests
normalizeRequests(array &$reqs)
Normalize request information.
Definition: MultiHttpClient.php:577
MultiHttpClient\getCurlTime
getCurlTime( $ch, $oldOption, $newConstName)
Get a time in seconds, formatted with microsecond resolution, or fall back to second resolution on PH...
Definition: MultiHttpClient.php:479
MultiHttpClient\$cmh
resource $cmh
curl_multi_init() handle
Definition: MultiHttpClient.php:57
MultiHttpClient\$logger
LoggerInterface $logger
Definition: MultiHttpClient.php:77