MediaWiki  1.34.4
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  // Explicitly test if curl_multi* is blocked, as some users' hosts provide
180  // them with a modified curl with the multi-threaded parts removed(!)
181  return extension_loaded( 'curl' ) && function_exists( 'curl_multi_init' );
182  }
183 
202  private function runMultiCurl( array $reqs, array $opts ) {
203  $chm = $this->getCurlMulti();
204 
205  $selectTimeout = $this->getSelectTimeout( $opts );
206 
207  // Add all of the required cURL handles...
208  $handles = [];
209  foreach ( $reqs as $index => &$req ) {
210  $handles[$index] = $this->getCurlHandle( $req, $opts );
211  if ( count( $reqs ) > 1 ) {
212  // https://github.com/guzzle/guzzle/issues/349
213  curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
214  }
215  }
216  unset( $req ); // don't assign over this by accident
217 
218  $indexes = array_keys( $reqs );
219  if ( isset( $opts['usePipelining'] ) ) {
220  curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
221  }
222  if ( isset( $opts['maxConnsPerHost'] ) ) {
223  // Keep these sockets around as they may be needed later in the request
224  curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
225  }
226 
227  // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
228  $batches = array_chunk( $indexes, $this->maxConnsPerHost );
229  $infos = [];
230 
231  foreach ( $batches as $batch ) {
232  // Attach all cURL handles for this batch
233  foreach ( $batch as $index ) {
234  curl_multi_add_handle( $chm, $handles[$index] );
235  }
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 
255  // Remove all of the added cURL handles and check for errors...
256  foreach ( $reqs as $index => &$req ) {
257  $ch = $handles[$index];
258  curl_multi_remove_handle( $chm, $ch );
259 
260  if ( isset( $infos[(int)$ch] ) ) {
261  $info = $infos[(int)$ch];
262  $errno = $info['result'];
263  if ( $errno !== 0 ) {
264  $req['response']['error'] = "(curl error: $errno)";
265  if ( function_exists( 'curl_strerror' ) ) {
266  $req['response']['error'] .= " " . curl_strerror( $errno );
267  }
268  $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
269  $req['response']['error'] );
270  }
271  } else {
272  $req['response']['error'] = "(curl error: no status set)";
273  }
274 
275  // For convenience with the list() operator
276  $req['response'][0] = $req['response']['code'];
277  $req['response'][1] = $req['response']['reason'];
278  $req['response'][2] = $req['response']['headers'];
279  $req['response'][3] = $req['response']['body'];
280  $req['response'][4] = $req['response']['error'];
281  curl_close( $ch );
282  // Close any string wrapper file handles
283  if ( isset( $req['_closeHandle'] ) ) {
284  fclose( $req['_closeHandle'] );
285  unset( $req['_closeHandle'] );
286  }
287  }
288  unset( $req ); // don't assign over this by accident
289 
290  // Restore the default settings
291  curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
292  curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
293 
294  return $reqs;
295  }
296 
308  protected function getCurlHandle( array &$req, array $opts ) {
309  $ch = curl_init();
310 
311  curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
312  curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
313  curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
314  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
315  curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
316  curl_setopt( $ch, CURLOPT_HEADER, 0 );
317  if ( !is_null( $this->caBundlePath ) ) {
318  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
319  curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
320  }
321  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
322 
323  $url = $req['url'];
324  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
325  if ( $query != '' ) {
326  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
327  }
328  curl_setopt( $ch, CURLOPT_URL, $url );
329  curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
330  curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
331 
332  if ( $req['method'] === 'PUT' ) {
333  curl_setopt( $ch, CURLOPT_PUT, 1 );
334  if ( is_resource( $req['body'] ) ) {
335  curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
336  if ( isset( $req['headers']['content-length'] ) ) {
337  curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
338  } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
339  $req['headers']['transfer-encoding'] === 'chunks'
340  ) {
341  curl_setopt( $ch, CURLOPT_UPLOAD, true );
342  } else {
343  throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
344  }
345  } elseif ( $req['body'] !== '' ) {
346  $fp = fopen( "php://temp", "wb+" );
347  fwrite( $fp, $req['body'], strlen( $req['body'] ) );
348  rewind( $fp );
349  curl_setopt( $ch, CURLOPT_INFILE, $fp );
350  curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
351  $req['_closeHandle'] = $fp; // remember to close this later
352  } else {
353  curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
354  }
355  curl_setopt( $ch, CURLOPT_READFUNCTION,
356  function ( $ch, $fd, $length ) {
357  return (string)fread( $fd, $length );
358  }
359  );
360  } elseif ( $req['method'] === 'POST' ) {
361  curl_setopt( $ch, CURLOPT_POST, 1 );
362  curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
363  } else {
364  if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
365  throw new Exception( "HTTP body specified for a non PUT/POST request." );
366  }
367  $req['headers']['content-length'] = 0;
368  }
369 
370  if ( !isset( $req['headers']['user-agent'] ) ) {
371  $req['headers']['user-agent'] = $this->userAgent;
372  }
373 
374  $headers = [];
375  foreach ( $req['headers'] as $name => $value ) {
376  if ( strpos( $name, ': ' ) ) {
377  throw new Exception( "Headers cannot have ':' in the name." );
378  }
379  $headers[] = $name . ': ' . trim( $value );
380  }
381  curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
382 
383  curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
384  function ( $ch, $header ) use ( &$req ) {
385  if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
386  header( $header );
387  }
388  $length = strlen( $header );
389  $matches = [];
390  if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
391  $req['response']['code'] = (int)$matches[2];
392  $req['response']['reason'] = trim( $matches[3] );
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  $req['response']['body'] .= $data;
418 
419  return strlen( $data );
420  }
421  }
422  );
423 
424  return $ch;
425  }
426 
431  protected function getCurlMulti() {
432  if ( !$this->multiHandle ) {
433  if ( !function_exists( 'curl_multi_init' ) ) {
434  throw new Exception( "PHP cURL function curl_multi_init missing. " .
435  "Check https://www.mediawiki.org/wiki/Manual:CURL" );
436  }
437  $cmh = curl_multi_init();
438  curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
439  curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
440  $this->multiHandle = $cmh;
441  }
442  return $this->multiHandle;
443  }
444 
458  private function runMultiHttp( array $reqs, array $opts = [] ) {
459  $httpOptions = [
460  'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
461  'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
462  'logger' => $this->logger,
463  'caInfo' => $this->caBundlePath,
464  ];
465  foreach ( $reqs as &$req ) {
466  $reqOptions = $httpOptions + [
467  'method' => $req['method'],
468  'proxy' => $req['proxy'] ?? $this->proxy,
469  'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
470  'postData' => $req['body'],
471  ];
472 
473  $url = $req['url'];
474  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
475  if ( $query != '' ) {
476  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
477  }
478 
479  $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
480  $url, $reqOptions );
481  $sv = $httpRequest->execute()->getStatusValue();
482 
483  $respHeaders = array_map(
484  function ( $v ) {
485  return implode( ', ', $v );
486  },
487  $httpRequest->getResponseHeaders() );
488 
489  $req['response'] = [
490  'code' => $httpRequest->getStatus(),
491  'reason' => '',
492  'headers' => $respHeaders,
493  'body' => $httpRequest->getContent(),
494  'error' => '',
495  ];
496 
497  if ( !$sv->isOK() ) {
498  $svErrors = $sv->getErrors();
499  if ( isset( $svErrors[0] ) ) {
500  $req['response']['error'] = $svErrors[0]['message'];
501 
502  // param values vary per failure type (ex. unknown host vs unknown page)
503  if ( isset( $svErrors[0]['params'][0] ) ) {
504  if ( is_numeric( $svErrors[0]['params'][0] ) ) {
505  if ( isset( $svErrors[0]['params'][1] ) ) {
506  // @phan-suppress-next-line PhanTypeInvalidDimOffset
507  $req['response']['reason'] = $svErrors[0]['params'][1];
508  }
509  } else {
510  $req['response']['reason'] = $svErrors[0]['params'][0];
511  }
512  }
513  }
514  }
515 
516  $req['response'][0] = $req['response']['code'];
517  $req['response'][1] = $req['response']['reason'];
518  $req['response'][2] = $req['response']['headers'];
519  $req['response'][3] = $req['response']['body'];
520  $req['response'][4] = $req['response']['error'];
521  }
522 
523  return $reqs;
524  }
525 
531  private function normalizeRequests( array &$reqs ) {
532  foreach ( $reqs as &$req ) {
533  $req['response'] = [
534  'code' => 0,
535  'reason' => '',
536  'headers' => [],
537  'body' => '',
538  'error' => ''
539  ];
540  if ( isset( $req[0] ) ) {
541  $req['method'] = $req[0]; // short-form
542  unset( $req[0] );
543  }
544  if ( isset( $req[1] ) ) {
545  $req['url'] = $req[1]; // short-form
546  unset( $req[1] );
547  }
548  if ( !isset( $req['method'] ) ) {
549  throw new Exception( "Request has no 'method' field set." );
550  } elseif ( !isset( $req['url'] ) ) {
551  throw new Exception( "Request has no 'url' field set." );
552  }
553  $this->logger->debug( "{$req['method']}: {$req['url']}" );
554  $req['query'] = $req['query'] ?? [];
555  $headers = []; // normalized headers
556  if ( isset( $req['headers'] ) ) {
557  foreach ( $req['headers'] as $name => $value ) {
558  $headers[strtolower( $name )] = $value;
559  }
560  }
561  $req['headers'] = $headers;
562  if ( !isset( $req['body'] ) ) {
563  $req['body'] = '';
564  $req['headers']['content-length'] = 0;
565  }
566  $req['flags'] = $req['flags'] ?? [];
567  }
568  }
569 
576  private function getSelectTimeout( $opts ) {
577  $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
578  $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
579  $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
580  if ( count( $timeouts ) === 0 ) {
581  return 1;
582  }
583 
584  $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
585  // Minimum 10us for sanity
586  if ( $selectTimeout < 10e-6 ) {
587  $selectTimeout = 10e-6;
588  }
589  return $selectTimeout;
590  }
591 
597  public function setLogger( LoggerInterface $logger ) {
598  $this->logger = $logger;
599  }
600 
601  function __destruct() {
602  if ( $this->multiHandle ) {
603  curl_multi_close( $this->multiHandle );
604  }
605  }
606 }
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:601
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:576
MultiHttpClient\setLogger
setLogger(LoggerInterface $logger)
Register a logger.
Definition: MultiHttpClient.php:597
MultiHttpClient\runMultiHttp
runMultiHttp(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests sequentially.
Definition: MultiHttpClient.php:458
MultiHttpClient\getCurlHandle
getCurlHandle(array &$req, array $opts)
Definition: MultiHttpClient.php:308
$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:202
MultiHttpClient\getCurlMulti
getCurlMulti()
Definition: MultiHttpClient.php:431
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:531
MultiHttpClient\$logger
LoggerInterface $logger
Definition: MultiHttpClient.php:70