MediaWiki  master
MultiHttpClient.php
Go to the documentation of this file.
1 <?php
27 
52 class MultiHttpClient implements LoggerAwareInterface {
54  protected $cmh;
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 
131  public function run( array $req, array $opts = [] ) {
132  return $this->runMulti( [ $req ], $opts )[0]['response'];
133  }
134 
164  public function runMulti( array $reqs, array $opts = [] ) {
165  $this->normalizeRequests( $reqs );
166  $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
167 
168  if ( $this->isCurlEnabled() ) {
169  return $this->runMultiCurl( $reqs, $opts );
170  } else {
171  return $this->runMultiHttp( $reqs, $opts );
172  }
173  }
174 
180  protected function isCurlEnabled() {
181  return extension_loaded( 'curl' );
182  }
183 
202  private function runMultiCurl( array $reqs, array $opts ) {
203  $chm = $this->getCurlMulti( $opts );
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  curl_multi_add_handle( $chm, $handles[$index] );
212  }
213  unset( $req ); // don't assign over this by accident
214 
215  $infos = [];
216  // Execute the cURL handles concurrently...
217  $active = null; // handles still being processed
218  do {
219  // Do any available work...
220  do {
221  $mrc = curl_multi_exec( $chm, $active );
222  $info = curl_multi_info_read( $chm );
223  if ( $info !== false ) {
224  $infos[(int)$info['handle']] = $info;
225  }
226  } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
227  // Wait (if possible) for available work...
228  if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
229  // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
230  usleep( 5000 ); // 5ms
231  }
232  } while ( $active > 0 && $mrc == CURLM_OK );
233 
234  // Remove all of the added cURL handles and check for errors...
235  foreach ( $reqs as $index => &$req ) {
236  $ch = $handles[$index];
237  curl_multi_remove_handle( $chm, $ch );
238 
239  if ( isset( $infos[(int)$ch] ) ) {
240  $info = $infos[(int)$ch];
241  $errno = $info['result'];
242  if ( $errno !== 0 ) {
243  $req['response']['error'] = "(curl error: $errno)";
244  if ( function_exists( 'curl_strerror' ) ) {
245  $req['response']['error'] .= " " . curl_strerror( $errno );
246  }
247  $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
248  $req['response']['error'] );
249  }
250  } else {
251  $req['response']['error'] = "(curl error: no status set)";
252  }
253 
254  // For convenience with the list() operator
255  $req['response'][0] = $req['response']['code'];
256  $req['response'][1] = $req['response']['reason'];
257  $req['response'][2] = $req['response']['headers'];
258  $req['response'][3] = $req['response']['body'];
259  $req['response'][4] = $req['response']['error'];
260  curl_close( $ch );
261  // Close any string wrapper file handles
262  if ( isset( $req['_closeHandle'] ) ) {
263  fclose( $req['_closeHandle'] );
264  unset( $req['_closeHandle'] );
265  }
266  }
267  unset( $req ); // don't assign over this by accident
268 
269  return $reqs;
270  }
271 
283  protected function getCurlHandle( array &$req, array $opts ) {
284  $ch = curl_init();
285 
286  curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
287  curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
288  curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
289  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
290  curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
291  curl_setopt( $ch, CURLOPT_HEADER, 0 );
292  if ( !is_null( $this->caBundlePath ) ) {
293  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
294  curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
295  }
296  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
297 
298  $url = $req['url'];
299  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
300  if ( $query != '' ) {
301  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
302  }
303  curl_setopt( $ch, CURLOPT_URL, $url );
304  curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
305  curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
306 
307  if ( $req['method'] === 'PUT' ) {
308  curl_setopt( $ch, CURLOPT_PUT, 1 );
309  if ( is_resource( $req['body'] ) ) {
310  curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
311  if ( isset( $req['headers']['content-length'] ) ) {
312  curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
313  } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
314  $req['headers']['transfer-encoding'] === 'chunks'
315  ) {
316  curl_setopt( $ch, CURLOPT_UPLOAD, true );
317  } else {
318  throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
319  }
320  } elseif ( $req['body'] !== '' ) {
321  $fp = fopen( "php://temp", "wb+" );
322  fwrite( $fp, $req['body'], strlen( $req['body'] ) );
323  rewind( $fp );
324  curl_setopt( $ch, CURLOPT_INFILE, $fp );
325  curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
326  $req['_closeHandle'] = $fp; // remember to close this later
327  } else {
328  curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
329  }
330  curl_setopt( $ch, CURLOPT_READFUNCTION,
331  function ( $ch, $fd, $length ) {
332  return (string)fread( $fd, $length );
333  }
334  );
335  } elseif ( $req['method'] === 'POST' ) {
336  curl_setopt( $ch, CURLOPT_POST, 1 );
337  curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
338  } else {
339  if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
340  throw new Exception( "HTTP body specified for a non PUT/POST request." );
341  }
342  $req['headers']['content-length'] = 0;
343  }
344 
345  if ( !isset( $req['headers']['user-agent'] ) ) {
346  $req['headers']['user-agent'] = $this->userAgent;
347  }
348 
349  $headers = [];
350  foreach ( $req['headers'] as $name => $value ) {
351  if ( strpos( $name, ': ' ) ) {
352  throw new Exception( "Headers cannot have ':' in the name." );
353  }
354  $headers[] = $name . ': ' . trim( $value );
355  }
356  curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
357 
358  curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
359  function ( $ch, $header ) use ( &$req ) {
360  if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
361  header( $header );
362  }
363  $length = strlen( $header );
364  $matches = [];
365  if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
366  $req['response']['code'] = (int)$matches[2];
367  $req['response']['reason'] = trim( $matches[3] );
368  return $length;
369  }
370  if ( strpos( $header, ":" ) === false ) {
371  return $length;
372  }
373  list( $name, $value ) = explode( ":", $header, 2 );
374  $name = strtolower( $name );
375  $value = trim( $value );
376  if ( isset( $req['response']['headers'][$name] ) ) {
377  $req['response']['headers'][$name] .= ', ' . $value;
378  } else {
379  $req['response']['headers'][$name] = $value;
380  }
381  return $length;
382  }
383  );
384 
385  // This works with both file and php://temp handles (unlike CURLOPT_FILE)
386  $hasOutputStream = isset( $req['stream'] );
387  curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
388  function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
389  if ( $hasOutputStream ) {
390  return fwrite( $req['stream'], $data );
391  } else {
392  // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
393  $req['response']['body'] .= $data;
394 
395  return strlen( $data );
396  }
397  }
398  );
399 
400  return $ch;
401  }
402 
408  protected function getCurlMulti( array $opts ) {
409  if ( !$this->cmh ) {
410  if ( !function_exists( 'curl_multi_init' ) ) {
411  throw new Exception( "PHP cURL function curl_multi_init missing. " .
412  "Check https://www.mediawiki.org/wiki/Manual:CURL" );
413  }
414  $cmh = curl_multi_init();
415  // Limit the size of the idle connection cache such that consecutive parallel
416  // request batches to the same host can avoid having to keep making connections
417  curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
418  $this->cmh = $cmh;
419  }
420 
421  // Limit the number of in-flight requests for any given host
422  $maxHostConns = $opts['maxConnsPerHost'] ?? $this->maxConnsPerHost;
423  curl_multi_setopt( $this->cmh, CURLMOPT_MAX_HOST_CONNECTIONS, (int)$maxHostConns );
424  // Configure when to multiplex multiple requests onto single TCP handles
425  $pipelining = $opts['usePipelining'] ?? $this->usePipelining;
426  curl_multi_setopt( $this->cmh, CURLMOPT_PIPELINING, $pipelining ? 3 : 0 );
427 
428  return $this->cmh;
429  }
430 
448  private function runMultiHttp( array $reqs, array $opts = [] ) {
449  $httpOptions = [
450  'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
451  'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
452  'logger' => $this->logger,
453  'caInfo' => $this->caBundlePath,
454  ];
455  foreach ( $reqs as &$req ) {
456  $reqOptions = $httpOptions + [
457  'method' => $req['method'],
458  'proxy' => $req['proxy'] ?? $this->proxy,
459  'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
460  'postData' => $req['body'],
461  ];
462 
463  $url = $req['url'];
464  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
465  if ( $query != '' ) {
466  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
467  }
468 
469  $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
470  $url, $reqOptions );
471  $sv = $httpRequest->execute()->getStatusValue();
472 
473  $respHeaders = array_map(
474  function ( $v ) {
475  return implode( ', ', $v );
476  },
477  $httpRequest->getResponseHeaders() );
478 
479  $req['response'] = [
480  'code' => $httpRequest->getStatus(),
481  'reason' => '',
482  'headers' => $respHeaders,
483  'body' => $httpRequest->getContent(),
484  'error' => '',
485  ];
486 
487  if ( !$sv->isOK() ) {
488  $svErrors = $sv->getErrors();
489  if ( isset( $svErrors[0] ) ) {
490  $req['response']['error'] = $svErrors[0]['message'];
491 
492  // param values vary per failure type (ex. unknown host vs unknown page)
493  if ( isset( $svErrors[0]['params'][0] ) ) {
494  if ( is_numeric( $svErrors[0]['params'][0] ) ) {
495  if ( isset( $svErrors[0]['params'][1] ) ) {
496  $req['response']['reason'] = $svErrors[0]['params'][1];
497  }
498  } else {
499  $req['response']['reason'] = $svErrors[0]['params'][0];
500  }
501  }
502  }
503  }
504 
505  $req['response'][0] = $req['response']['code'];
506  $req['response'][1] = $req['response']['reason'];
507  $req['response'][2] = $req['response']['headers'];
508  $req['response'][3] = $req['response']['body'];
509  $req['response'][4] = $req['response']['error'];
510  }
511 
512  return $reqs;
513  }
514 
520  private function normalizeRequests( array &$reqs ) {
521  foreach ( $reqs as &$req ) {
522  $req['response'] = [
523  'code' => 0,
524  'reason' => '',
525  'headers' => [],
526  'body' => '',
527  'error' => ''
528  ];
529  if ( isset( $req[0] ) ) {
530  $req['method'] = $req[0]; // short-form
531  unset( $req[0] );
532  }
533  if ( isset( $req[1] ) ) {
534  $req['url'] = $req[1]; // short-form
535  unset( $req[1] );
536  }
537  if ( !isset( $req['method'] ) ) {
538  throw new Exception( "Request has no 'method' field set." );
539  } elseif ( !isset( $req['url'] ) ) {
540  throw new Exception( "Request has no 'url' field set." );
541  }
542  $this->logger->debug( "{$req['method']}: {$req['url']}" );
543  $req['query'] = $req['query'] ?? [];
544  $headers = []; // normalized headers
545  if ( isset( $req['headers'] ) ) {
546  foreach ( $req['headers'] as $name => $value ) {
547  $headers[strtolower( $name )] = $value;
548  }
549  }
550  $req['headers'] = $headers;
551  if ( !isset( $req['body'] ) ) {
552  $req['body'] = '';
553  $req['headers']['content-length'] = 0;
554  }
555  $req['flags'] = $req['flags'] ?? [];
556  }
557  }
558 
565  private function getSelectTimeout( $opts ) {
566  $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
567  $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
568  $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
569  if ( count( $timeouts ) === 0 ) {
570  return 1;
571  }
572 
573  $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
574  // Minimum 10us for sanity
575  if ( $selectTimeout < 10e-6 ) {
576  $selectTimeout = 10e-6;
577  }
578  return $selectTimeout;
579  }
580 
586  public function setLogger( LoggerInterface $logger ) {
587  $this->logger = $logger;
588  }
589 
590  public function __destruct() {
591  if ( $this->cmh ) {
592  curl_multi_close( $this->cmh );
593  }
594  }
595 }
LoggerInterface $logger
string null $caBundlePath
SSL certificates path.
__construct(array $options)
getCurlMulti(array $opts)
normalizeRequests(array &$reqs)
Normalize request information.
const TIMEOUT_ACCURACY_FACTOR
getSelectTimeout( $opts)
Get a suitable select timeout for the given options.
setLogger(LoggerInterface $logger)
Register a logger.
$header
isCurlEnabled()
Determines if the curl extension is available.
getCurlHandle(array &$req, array $opts)
string null $proxy
proxy
runMultiCurl(array $reqs, array $opts)
Execute a set of HTTP(S) requests concurrently.
run(array $req, array $opts=[])
Execute an HTTP(S) request.
runMultiHttp(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests sequentially.
Class to handle multiple HTTP requests.
resource $cmh
curl_multi_init() handle
runMulti(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests.
$matches