MediaWiki  1.34.0
MultiHttpClient.php
Go to the documentation of this file.
1 <?php
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
27 
52 class MultiHttpClient implements LoggerAwareInterface {
54  protected $multiHandle = null; // curl_multi handle
56  protected $caBundlePath;
58  protected $connTimeout = 10;
60  protected $reqTimeout = 900;
62  protected $usePipelining = false;
64  protected $maxConnsPerHost = 50;
66  protected $proxy;
68  protected $userAgent = 'wikimedia/multi-http-client v1.0';
70  protected $logger;
71 
72  // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
73  // timeouts are periodically polled instead of being accurately respected.
74  // The select timeout is set to the minimum timeout multiplied by this factor.
76 
89  public function __construct( array $options ) {
90  if ( isset( $options['caBundlePath'] ) ) {
91  $this->caBundlePath = $options['caBundlePath'];
92  if ( !file_exists( $this->caBundlePath ) ) {
93  throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
94  }
95  }
96  static $opts = [
97  'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost',
98  'proxy', 'userAgent', 'logger'
99  ];
100  foreach ( $opts as $key ) {
101  if ( isset( $options[$key] ) ) {
102  $this->$key = $options[$key];
103  }
104  }
105  if ( $this->logger === null ) {
106  $this->logger = new NullLogger;
107  }
108  }
109 
129  public function run( array $req, array $opts = [] ) {
130  return $this->runMulti( [ $req ], $opts )[0]['response'];
131  }
132 
162  public function runMulti( array $reqs, array $opts = [] ) {
163  $this->normalizeRequests( $reqs );
164  $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
165 
166  if ( $this->isCurlEnabled() ) {
167  return $this->runMultiCurl( $reqs, $opts );
168  } else {
169  return $this->runMultiHttp( $reqs, $opts );
170  }
171  }
172 
178  protected function isCurlEnabled() {
179  return extension_loaded( 'curl' );
180  }
181 
200  private function runMultiCurl( array $reqs, array $opts ) {
201  $chm = $this->getCurlMulti();
202 
203  $selectTimeout = $this->getSelectTimeout( $opts );
204 
205  // Add all of the required cURL handles...
206  $handles = [];
207  foreach ( $reqs as $index => &$req ) {
208  $handles[$index] = $this->getCurlHandle( $req, $opts );
209  if ( count( $reqs ) > 1 ) {
210  // https://github.com/guzzle/guzzle/issues/349
211  curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
212  }
213  }
214  unset( $req ); // don't assign over this by accident
215 
216  $indexes = array_keys( $reqs );
217  if ( isset( $opts['usePipelining'] ) ) {
218  curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
219  }
220  if ( isset( $opts['maxConnsPerHost'] ) ) {
221  // Keep these sockets around as they may be needed later in the request
222  curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
223  }
224 
225  // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
226  $batches = array_chunk( $indexes, $this->maxConnsPerHost );
227  $infos = [];
228 
229  foreach ( $batches as $batch ) {
230  // Attach all cURL handles for this batch
231  foreach ( $batch as $index ) {
232  curl_multi_add_handle( $chm, $handles[$index] );
233  }
234  // Execute the cURL handles concurrently...
235  $active = null; // handles still being processed
236  do {
237  // Do any available work...
238  do {
239  $mrc = curl_multi_exec( $chm, $active );
240  $info = curl_multi_info_read( $chm );
241  if ( $info !== false ) {
242  $infos[(int)$info['handle']] = $info;
243  }
244  } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
245  // Wait (if possible) for available work...
246  if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
247  // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
248  usleep( 5000 ); // 5ms
249  }
250  } while ( $active > 0 && $mrc == CURLM_OK );
251  }
252 
253  // Remove all of the added cURL handles and check for errors...
254  foreach ( $reqs as $index => &$req ) {
255  $ch = $handles[$index];
256  curl_multi_remove_handle( $chm, $ch );
257 
258  if ( isset( $infos[(int)$ch] ) ) {
259  $info = $infos[(int)$ch];
260  $errno = $info['result'];
261  if ( $errno !== 0 ) {
262  $req['response']['error'] = "(curl error: $errno)";
263  if ( function_exists( 'curl_strerror' ) ) {
264  $req['response']['error'] .= " " . curl_strerror( $errno );
265  }
266  $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
267  $req['response']['error'] );
268  }
269  } else {
270  $req['response']['error'] = "(curl error: no status set)";
271  }
272 
273  // For convenience with the list() operator
274  $req['response'][0] = $req['response']['code'];
275  $req['response'][1] = $req['response']['reason'];
276  $req['response'][2] = $req['response']['headers'];
277  $req['response'][3] = $req['response']['body'];
278  $req['response'][4] = $req['response']['error'];
279  curl_close( $ch );
280  // Close any string wrapper file handles
281  if ( isset( $req['_closeHandle'] ) ) {
282  fclose( $req['_closeHandle'] );
283  unset( $req['_closeHandle'] );
284  }
285  }
286  unset( $req ); // don't assign over this by accident
287 
288  // Restore the default settings
289  curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
290  curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
291 
292  return $reqs;
293  }
294 
306  protected function getCurlHandle( array &$req, array $opts ) {
307  $ch = curl_init();
308 
309  curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
310  curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
311  curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
312  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
313  curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
314  curl_setopt( $ch, CURLOPT_HEADER, 0 );
315  if ( !is_null( $this->caBundlePath ) ) {
316  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
317  curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
318  }
319  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
320 
321  $url = $req['url'];
322  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
323  if ( $query != '' ) {
324  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
325  }
326  curl_setopt( $ch, CURLOPT_URL, $url );
327  curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
328  curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
329 
330  if ( $req['method'] === 'PUT' ) {
331  curl_setopt( $ch, CURLOPT_PUT, 1 );
332  if ( is_resource( $req['body'] ) ) {
333  curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
334  if ( isset( $req['headers']['content-length'] ) ) {
335  curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
336  } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
337  $req['headers']['transfer-encoding'] === 'chunks'
338  ) {
339  curl_setopt( $ch, CURLOPT_UPLOAD, true );
340  } else {
341  throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
342  }
343  } elseif ( $req['body'] !== '' ) {
344  $fp = fopen( "php://temp", "wb+" );
345  fwrite( $fp, $req['body'], strlen( $req['body'] ) );
346  rewind( $fp );
347  curl_setopt( $ch, CURLOPT_INFILE, $fp );
348  curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
349  $req['_closeHandle'] = $fp; // remember to close this later
350  } else {
351  curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
352  }
353  curl_setopt( $ch, CURLOPT_READFUNCTION,
354  function ( $ch, $fd, $length ) {
355  return (string)fread( $fd, $length );
356  }
357  );
358  } elseif ( $req['method'] === 'POST' ) {
359  curl_setopt( $ch, CURLOPT_POST, 1 );
360  curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
361  } else {
362  if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
363  throw new Exception( "HTTP body specified for a non PUT/POST request." );
364  }
365  $req['headers']['content-length'] = 0;
366  }
367 
368  if ( !isset( $req['headers']['user-agent'] ) ) {
369  $req['headers']['user-agent'] = $this->userAgent;
370  }
371 
372  $headers = [];
373  foreach ( $req['headers'] as $name => $value ) {
374  if ( strpos( $name, ': ' ) ) {
375  throw new Exception( "Headers cannot have ':' in the name." );
376  }
377  $headers[] = $name . ': ' . trim( $value );
378  }
379  curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
380 
381  curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
382  function ( $ch, $header ) use ( &$req ) {
383  if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
384  header( $header );
385  }
386  $length = strlen( $header );
387  $matches = [];
388  if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
389  $req['response']['code'] = (int)$matches[2];
390  $req['response']['reason'] = trim( $matches[3] );
391  return $length;
392  }
393  if ( strpos( $header, ":" ) === false ) {
394  return $length;
395  }
396  list( $name, $value ) = explode( ":", $header, 2 );
397  $name = strtolower( $name );
398  $value = trim( $value );
399  if ( isset( $req['response']['headers'][$name] ) ) {
400  $req['response']['headers'][$name] .= ', ' . $value;
401  } else {
402  $req['response']['headers'][$name] = $value;
403  }
404  return $length;
405  }
406  );
407 
408  // This works with both file and php://temp handles (unlike CURLOPT_FILE)
409  $hasOutputStream = isset( $req['stream'] );
410  curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
411  function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
412  if ( $hasOutputStream ) {
413  return fwrite( $req['stream'], $data );
414  } else {
415  // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
416  $req['response']['body'] .= $data;
417 
418  return strlen( $data );
419  }
420  }
421  );
422 
423  return $ch;
424  }
425 
430  protected function getCurlMulti() {
431  if ( !$this->multiHandle ) {
432  if ( !function_exists( 'curl_multi_init' ) ) {
433  throw new Exception( "PHP cURL function curl_multi_init missing. " .
434  "Check https://www.mediawiki.org/wiki/Manual:CURL" );
435  }
436  $cmh = curl_multi_init();
437  curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
438  curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
439  $this->multiHandle = $cmh;
440  }
441  return $this->multiHandle;
442  }
443 
457  private function runMultiHttp( array $reqs, array $opts = [] ) {
458  $httpOptions = [
459  'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
460  'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
461  'logger' => $this->logger,
462  'caInfo' => $this->caBundlePath,
463  ];
464  foreach ( $reqs as &$req ) {
465  $reqOptions = $httpOptions + [
466  'method' => $req['method'],
467  'proxy' => $req['proxy'] ?? $this->proxy,
468  'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
469  'postData' => $req['body'],
470  ];
471 
472  $url = $req['url'];
473  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
474  if ( $query != '' ) {
475  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
476  }
477 
478  $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
479  $url, $reqOptions );
480  $sv = $httpRequest->execute()->getStatusValue();
481 
482  $respHeaders = array_map(
483  function ( $v ) {
484  return implode( ', ', $v );
485  },
486  $httpRequest->getResponseHeaders() );
487 
488  $req['response'] = [
489  'code' => $httpRequest->getStatus(),
490  'reason' => '',
491  'headers' => $respHeaders,
492  'body' => $httpRequest->getContent(),
493  'error' => '',
494  ];
495 
496  if ( !$sv->isOK() ) {
497  $svErrors = $sv->getErrors();
498  if ( isset( $svErrors[0] ) ) {
499  $req['response']['error'] = $svErrors[0]['message'];
500 
501  // param values vary per failure type (ex. unknown host vs unknown page)
502  if ( isset( $svErrors[0]['params'][0] ) ) {
503  if ( is_numeric( $svErrors[0]['params'][0] ) ) {
504  if ( isset( $svErrors[0]['params'][1] ) ) {
505  // @phan-suppress-next-line PhanTypeInvalidDimOffset
506  $req['response']['reason'] = $svErrors[0]['params'][1];
507  }
508  } else {
509  $req['response']['reason'] = $svErrors[0]['params'][0];
510  }
511  }
512  }
513  }
514 
515  $req['response'][0] = $req['response']['code'];
516  $req['response'][1] = $req['response']['reason'];
517  $req['response'][2] = $req['response']['headers'];
518  $req['response'][3] = $req['response']['body'];
519  $req['response'][4] = $req['response']['error'];
520  }
521 
522  return $reqs;
523  }
524 
530  private function normalizeRequests( array &$reqs ) {
531  foreach ( $reqs as &$req ) {
532  $req['response'] = [
533  'code' => 0,
534  'reason' => '',
535  'headers' => [],
536  'body' => '',
537  'error' => ''
538  ];
539  if ( isset( $req[0] ) ) {
540  $req['method'] = $req[0]; // short-form
541  unset( $req[0] );
542  }
543  if ( isset( $req[1] ) ) {
544  $req['url'] = $req[1]; // short-form
545  unset( $req[1] );
546  }
547  if ( !isset( $req['method'] ) ) {
548  throw new Exception( "Request has no 'method' field set." );
549  } elseif ( !isset( $req['url'] ) ) {
550  throw new Exception( "Request has no 'url' field set." );
551  }
552  $this->logger->debug( "{$req['method']}: {$req['url']}" );
553  $req['query'] = $req['query'] ?? [];
554  $headers = []; // normalized headers
555  if ( isset( $req['headers'] ) ) {
556  foreach ( $req['headers'] as $name => $value ) {
557  $headers[strtolower( $name )] = $value;
558  }
559  }
560  $req['headers'] = $headers;
561  if ( !isset( $req['body'] ) ) {
562  $req['body'] = '';
563  $req['headers']['content-length'] = 0;
564  }
565  $req['flags'] = $req['flags'] ?? [];
566  }
567  }
568 
575  private function getSelectTimeout( $opts ) {
576  $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
577  $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
578  $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
579  if ( count( $timeouts ) === 0 ) {
580  return 1;
581  }
582 
583  $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
584  // Minimum 10us for sanity
585  if ( $selectTimeout < 10e-6 ) {
586  $selectTimeout = 10e-6;
587  }
588  return $selectTimeout;
589  }
590 
596  public function setLogger( LoggerInterface $logger ) {
597  $this->logger = $logger;
598  }
599 
600  function __destruct() {
601  if ( $this->multiHandle ) {
602  curl_multi_close( $this->multiHandle );
603  }
604  }
605 }
MultiHttpClient
Class to handle multiple HTTP requests.
Definition: MultiHttpClient.php:52
MultiHttpClient\$usePipelining
bool $usePipelining
Definition: MultiHttpClient.php:62
MultiHttpClient\$maxConnsPerHost
int $maxConnsPerHost
Definition: MultiHttpClient.php:64
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:117
MultiHttpClient\$reqTimeout
float $reqTimeout
Definition: MultiHttpClient.php:60
MultiHttpClient\run
run(array $req, array $opts=[])
Execute an HTTP(S) request.
Definition: MultiHttpClient.php:129
MultiHttpClient\__destruct
__destruct()
Definition: MultiHttpClient.php:600
MultiHttpClient\$connTimeout
float $connTimeout
Definition: MultiHttpClient.php:58
$matches
$matches
Definition: NoLocalSettings.php:24
MultiHttpClient\$caBundlePath
string null $caBundlePath
SSL certificates path.
Definition: MultiHttpClient.php:56
MultiHttpClient\getSelectTimeout
getSelectTimeout( $opts)
Get a suitable select timeout for the given options.
Definition: MultiHttpClient.php:575
MultiHttpClient\setLogger
setLogger(LoggerInterface $logger)
Register a logger.
Definition: MultiHttpClient.php:596
MultiHttpClient\runMultiHttp
runMultiHttp(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests sequentially.
Definition: MultiHttpClient.php:457
MultiHttpClient\getCurlHandle
getCurlHandle(array &$req, array $opts)
Definition: MultiHttpClient.php:306
$header
$header
Definition: updateCredits.php:41
MultiHttpClient\isCurlEnabled
isCurlEnabled()
Determines if the curl extension is available.
Definition: MultiHttpClient.php:178
MultiHttpClient\$userAgent
string $userAgent
Definition: MultiHttpClient.php:68
MultiHttpClient\$multiHandle
resource $multiHandle
Definition: MultiHttpClient.php:54
MultiHttpClient\runMulti
runMulti(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests.
Definition: MultiHttpClient.php:162
MultiHttpClient\$proxy
string null $proxy
proxy
Definition: MultiHttpClient.php:66
MultiHttpClient\runMultiCurl
runMultiCurl(array $reqs, array $opts)
Execute a set of HTTP(S) requests concurrently.
Definition: MultiHttpClient.php:200
MultiHttpClient\getCurlMulti
getCurlMulti()
Definition: MultiHttpClient.php:430
MultiHttpClient\__construct
__construct(array $options)
Definition: MultiHttpClient.php:89
MultiHttpClient\TIMEOUT_ACCURACY_FACTOR
const TIMEOUT_ACCURACY_FACTOR
Definition: MultiHttpClient.php:75
MultiHttpClient\normalizeRequests
normalizeRequests(array &$reqs)
Normalize request information.
Definition: MultiHttpClient.php:530
MultiHttpClient\$logger
LoggerInterface $logger
Definition: MultiHttpClient.php:70