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 
224  private function runMultiCurl( array $reqs, array $opts ) {
225  $chm = $this->getCurlMulti( $opts );
226 
227  $selectTimeout = $this->getSelectTimeout( $opts );
228 
229  // Add all of the required cURL handles...
230  $handles = [];
231  foreach ( $reqs as $index => &$req ) {
232  $handles[$index] = $this->getCurlHandle( $req, $opts );
233  curl_multi_add_handle( $chm, $handles[$index] );
234  }
235  unset( $req ); // don't assign over this by accident
236 
237  $infos = [];
238  // Execute the cURL handles concurrently...
239  $active = null; // handles still being processed
240  do {
241  // Do any available work...
242  do {
243  $mrc = curl_multi_exec( $chm, $active );
244  $info = curl_multi_info_read( $chm );
245  if ( $info !== false ) {
246  $infos[(int)$info['handle']] = $info;
247  }
248  } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
249  // Wait (if possible) for available work...
250  if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
251  // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
252  usleep( 5000 ); // 5ms
253  }
254  } while ( $active > 0 && $mrc == CURLM_OK );
255 
256  // Remove all of the added cURL handles and check for errors...
257  foreach ( $reqs as $index => &$req ) {
258  $ch = $handles[$index];
259  curl_multi_remove_handle( $chm, $ch );
260 
261  if ( isset( $infos[(int)$ch] ) ) {
262  $info = $infos[(int)$ch];
263  $errno = $info['result'];
264  if ( $errno !== 0 ) {
265  $req['response']['error'] = "(curl error: $errno)";
266  if ( function_exists( 'curl_strerror' ) ) {
267  $req['response']['error'] .= " " . curl_strerror( $errno );
268  }
269  $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
270  $req['response']['error'] );
271  }
272  } else {
273  $req['response']['error'] = "(curl error: no status set)";
274  }
275 
276  // For convenience with the list() operator
277  $req['response'][0] = $req['response']['code'];
278  $req['response'][1] = $req['response']['reason'];
279  $req['response'][2] = $req['response']['headers'];
280  $req['response'][3] = $req['response']['body'];
281  $req['response'][4] = $req['response']['error'];
282  curl_close( $ch );
283  // Close any string wrapper file handles
284  if ( isset( $req['_closeHandle'] ) ) {
285  fclose( $req['_closeHandle'] );
286  unset( $req['_closeHandle'] );
287  }
288  }
289  unset( $req ); // don't assign over this by accident
290 
291  return $reqs;
292  }
293 
305  protected function getCurlHandle( array &$req, array $opts ) {
306  $ch = curl_init();
307 
308  curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
309  curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
310  curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
311  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
312  curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
313  curl_setopt( $ch, CURLOPT_HEADER, 0 );
314  if ( $this->caBundlePath !== null ) {
315  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
316  curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
317  }
318  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
319 
320  $url = $req['url'];
321  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
322  if ( $query != '' ) {
323  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
324  }
325  curl_setopt( $ch, CURLOPT_URL, $url );
326  curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
327  curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
328 
329  if ( $req['method'] === 'PUT' ) {
330  curl_setopt( $ch, CURLOPT_PUT, 1 );
331  if ( is_resource( $req['body'] ) ) {
332  curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
333  if ( isset( $req['headers']['content-length'] ) ) {
334  curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
335  } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
336  $req['headers']['transfer-encoding'] === 'chunks'
337  ) {
338  curl_setopt( $ch, CURLOPT_UPLOAD, true );
339  } else {
340  throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
341  }
342  } elseif ( $req['body'] !== '' ) {
343  $fp = fopen( "php://temp", "wb+" );
344  fwrite( $fp, $req['body'], strlen( $req['body'] ) );
345  rewind( $fp );
346  curl_setopt( $ch, CURLOPT_INFILE, $fp );
347  curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
348  $req['_closeHandle'] = $fp; // remember to close this later
349  } else {
350  curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
351  }
352  curl_setopt( $ch, CURLOPT_READFUNCTION,
353  function ( $ch, $fd, $length ) {
354  return (string)fread( $fd, $length );
355  }
356  );
357  } elseif ( $req['method'] === 'POST' ) {
358  curl_setopt( $ch, CURLOPT_POST, 1 );
359  curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
360  } else {
361  if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
362  throw new Exception( "HTTP body specified for a non PUT/POST request." );
363  }
364  $req['headers']['content-length'] = 0;
365  }
366 
367  if ( !isset( $req['headers']['user-agent'] ) ) {
368  $req['headers']['user-agent'] = $this->userAgent;
369  }
370 
371  $headers = [];
372  foreach ( $req['headers'] as $name => $value ) {
373  if ( strpos( $name, ': ' ) ) {
374  throw new Exception( "Headers cannot have ':' in the name." );
375  }
376  $headers[] = $name . ': ' . trim( $value );
377  }
378  curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
379 
380  curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
381  function ( $ch, $header ) use ( &$req ) {
382  if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
383  header( $header );
384  }
385  $length = strlen( $header );
386  $matches = [];
387  if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
388  $req['response']['code'] = (int)$matches[2];
389  $req['response']['reason'] = trim( $matches[3] );
390  // After a redirect we will receive this again, but we already stored headers
391  // that belonged to a redirect response. Start over.
392  $req['response']['headers'] = [];
393  return $length;
394  }
395  if ( strpos( $header, ":" ) === false ) {
396  return $length;
397  }
398  list( $name, $value ) = explode( ":", $header, 2 );
399  $name = strtolower( $name );
400  $value = trim( $value );
401  if ( isset( $req['response']['headers'][$name] ) ) {
402  $req['response']['headers'][$name] .= ', ' . $value;
403  } else {
404  $req['response']['headers'][$name] = $value;
405  }
406  return $length;
407  }
408  );
409 
410  // This works with both file and php://temp handles (unlike CURLOPT_FILE)
411  $hasOutputStream = isset( $req['stream'] );
412  curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
413  function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
414  if ( $hasOutputStream ) {
415  return fwrite( $req['stream'], $data );
416  } else {
417  // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
418  $req['response']['body'] .= $data;
419 
420  return strlen( $data );
421  }
422  }
423  );
424 
425  return $ch;
426  }
427 
433  protected function getCurlMulti( array $opts ) {
434  if ( !$this->cmh ) {
435  if ( !function_exists( 'curl_multi_init' ) ) {
436  throw new Exception( "PHP cURL function curl_multi_init missing. " .
437  "Check https://www.mediawiki.org/wiki/Manual:CURL" );
438  }
439  $cmh = curl_multi_init();
440  // Limit the size of the idle connection cache such that consecutive parallel
441  // request batches to the same host can avoid having to keep making connections
442  curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
443  $this->cmh = $cmh;
444  }
445 
446  // Limit the number of in-flight requests for any given host
447  $maxHostConns = $opts['maxConnsPerHost'] ?? $this->maxConnsPerHost;
448  curl_multi_setopt( $this->cmh, CURLMOPT_MAX_HOST_CONNECTIONS, (int)$maxHostConns );
449  // Configure when to multiplex multiple requests onto single TCP handles
450  $pipelining = $opts['usePipelining'] ?? $this->usePipelining;
451  curl_multi_setopt( $this->cmh, CURLMOPT_PIPELINING, $pipelining ? 3 : 0 );
452 
453  return $this->cmh;
454  }
455 
473  private function runMultiHttp( array $reqs, array $opts = [] ) {
474  $httpOptions = [
475  'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
476  'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
477  'logger' => $this->logger,
478  'caInfo' => $this->caBundlePath,
479  ];
480  foreach ( $reqs as &$req ) {
481  $reqOptions = $httpOptions + [
482  'method' => $req['method'],
483  'proxy' => $req['proxy'] ?? $this->proxy,
484  'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
485  'postData' => $req['body'],
486  ];
487 
488  $url = $req['url'];
489  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
490  if ( $query != '' ) {
491  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
492  }
493 
494  $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
495  $url, $reqOptions, __METHOD__ );
496  $sv = $httpRequest->execute()->getStatusValue();
497 
498  $respHeaders = array_map(
499  function ( $v ) {
500  return implode( ', ', $v );
501  },
502  $httpRequest->getResponseHeaders() );
503 
504  $req['response'] = [
505  'code' => $httpRequest->getStatus(),
506  'reason' => '',
507  'headers' => $respHeaders,
508  'body' => $httpRequest->getContent(),
509  'error' => '',
510  ];
511 
512  if ( !$sv->isOK() ) {
513  $svErrors = $sv->getErrors();
514  if ( isset( $svErrors[0] ) ) {
515  $req['response']['error'] = $svErrors[0]['message'];
516 
517  // param values vary per failure type (ex. unknown host vs unknown page)
518  if ( isset( $svErrors[0]['params'][0] ) ) {
519  if ( is_numeric( $svErrors[0]['params'][0] ) ) {
520  if ( isset( $svErrors[0]['params'][1] ) ) {
521  // @phan-suppress-next-line PhanTypeInvalidDimOffset
522  $req['response']['reason'] = $svErrors[0]['params'][1];
523  }
524  } else {
525  $req['response']['reason'] = $svErrors[0]['params'][0];
526  }
527  }
528  }
529  }
530 
531  $req['response'][0] = $req['response']['code'];
532  $req['response'][1] = $req['response']['reason'];
533  $req['response'][2] = $req['response']['headers'];
534  $req['response'][3] = $req['response']['body'];
535  $req['response'][4] = $req['response']['error'];
536  }
537 
538  return $reqs;
539  }
540 
546  private function normalizeRequests( array &$reqs ) {
547  foreach ( $reqs as &$req ) {
548  $req['response'] = [
549  'code' => 0,
550  'reason' => '',
551  'headers' => [],
552  'body' => '',
553  'error' => ''
554  ];
555  if ( isset( $req[0] ) ) {
556  $req['method'] = $req[0]; // short-form
557  unset( $req[0] );
558  }
559  if ( isset( $req[1] ) ) {
560  $req['url'] = $req[1]; // short-form
561  unset( $req[1] );
562  }
563  if ( !isset( $req['method'] ) ) {
564  throw new Exception( "Request has no 'method' field set." );
565  } elseif ( !isset( $req['url'] ) ) {
566  throw new Exception( "Request has no 'url' field set." );
567  }
568  $this->logger->debug( "{$req['method']}: {$req['url']}" );
569  $req['query'] = $req['query'] ?? [];
570  $headers = []; // normalized headers
571  if ( isset( $req['headers'] ) ) {
572  foreach ( $req['headers'] as $name => $value ) {
573  $headers[strtolower( $name )] = $value;
574  }
575  }
576  $req['headers'] = $headers;
577  if ( !isset( $req['body'] ) ) {
578  $req['body'] = '';
579  $req['headers']['content-length'] = 0;
580  }
581  $req['flags'] = $req['flags'] ?? [];
582  }
583  }
584 
591  private function getSelectTimeout( $opts ) {
592  $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
593  $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
594  $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
595  if ( count( $timeouts ) === 0 ) {
596  return 1;
597  }
598 
599  $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
600  // Minimum 10us for sanity
601  if ( $selectTimeout < 10e-6 ) {
602  $selectTimeout = 10e-6;
603  }
604  return $selectTimeout;
605  }
606 
612  public function setLogger( LoggerInterface $logger ) {
613  $this->logger = $logger;
614  }
615 
616  public function __destruct() {
617  if ( $this->cmh ) {
618  curl_multi_close( $this->cmh );
619  }
620  }
621 }
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:152
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:616
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:591
MultiHttpClient\setLogger
setLogger(LoggerInterface $logger)
Register a logger.
Definition: MultiHttpClient.php:612
MultiHttpClient\runMultiHttp
runMultiHttp(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests sequentially.
Definition: MultiHttpClient.php:473
MultiHttpClient\getCurlHandle
getCurlHandle(array &$req, array $opts)
Definition: MultiHttpClient.php:305
$header
$header
Definition: updateCredits.php:41
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:224
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:433
MultiHttpClient\$maxConnTimeout
float $maxConnTimeout
Definition: MultiHttpClient.php:63
MultiHttpClient\normalizeRequests
normalizeRequests(array &$reqs)
Normalize request information.
Definition: MultiHttpClient.php:546
MultiHttpClient\$cmh
resource $cmh
curl_multi_init() handle
Definition: MultiHttpClient.php:57
MultiHttpClient\$logger
LoggerInterface $logger
Definition: MultiHttpClient.php:77