MediaWiki  master
MultiHttpClient.php
Go to the documentation of this file.
1 <?php
27 
52 class MultiHttpClient implements LoggerAwareInterface {
54  protected $multiHandle = null; // curl_multi handle
56  protected $caBundlePath;
58  protected $connTimeout = 10;
60  protected $reqTimeout = 300;
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  if ( $this->isCurlEnabled() ) {
165  return $this->runMultiCurl( $reqs, $opts );
166  } else {
167  return $this->runMultiHttp( $reqs, $opts );
168  }
169  }
170 
176  protected function isCurlEnabled() {
177  return extension_loaded( 'curl' );
178  }
179 
194  private function runMultiCurl( array $reqs, array $opts = [] ) {
195  $chm = $this->getCurlMulti();
196 
197  $selectTimeout = $this->getSelectTimeout( $opts );
198 
199  // Add all of the required cURL handles...
200  $handles = [];
201  foreach ( $reqs as $index => &$req ) {
202  $handles[$index] = $this->getCurlHandle( $req, $opts );
203  if ( count( $reqs ) > 1 ) {
204  // https://github.com/guzzle/guzzle/issues/349
205  curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
206  }
207  }
208  unset( $req ); // don't assign over this by accident
209 
210  $indexes = array_keys( $reqs );
211  if ( isset( $opts['usePipelining'] ) ) {
212  curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
213  }
214  if ( isset( $opts['maxConnsPerHost'] ) ) {
215  // Keep these sockets around as they may be needed later in the request
216  curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
217  }
218 
219  // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
220  $batches = array_chunk( $indexes, $this->maxConnsPerHost );
221  $infos = [];
222 
223  foreach ( $batches as $batch ) {
224  // Attach all cURL handles for this batch
225  foreach ( $batch as $index ) {
226  curl_multi_add_handle( $chm, $handles[$index] );
227  }
228  // Execute the cURL handles concurrently...
229  $active = null; // handles still being processed
230  do {
231  // Do any available work...
232  do {
233  $mrc = curl_multi_exec( $chm, $active );
234  $info = curl_multi_info_read( $chm );
235  if ( $info !== false ) {
236  $infos[(int)$info['handle']] = $info;
237  }
238  } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
239  // Wait (if possible) for available work...
240  if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
241  // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
242  usleep( 5000 ); // 5ms
243  }
244  } while ( $active > 0 && $mrc == CURLM_OK );
245  }
246 
247  // Remove all of the added cURL handles and check for errors...
248  foreach ( $reqs as $index => &$req ) {
249  $ch = $handles[$index];
250  curl_multi_remove_handle( $chm, $ch );
251 
252  if ( isset( $infos[(int)$ch] ) ) {
253  $info = $infos[(int)$ch];
254  $errno = $info['result'];
255  if ( $errno !== 0 ) {
256  $req['response']['error'] = "(curl error: $errno)";
257  if ( function_exists( 'curl_strerror' ) ) {
258  $req['response']['error'] .= " " . curl_strerror( $errno );
259  }
260  $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
261  $req['response']['error'] );
262  }
263  } else {
264  $req['response']['error'] = "(curl error: no status set)";
265  }
266 
267  // For convenience with the list() operator
268  $req['response'][0] = $req['response']['code'];
269  $req['response'][1] = $req['response']['reason'];
270  $req['response'][2] = $req['response']['headers'];
271  $req['response'][3] = $req['response']['body'];
272  $req['response'][4] = $req['response']['error'];
273  curl_close( $ch );
274  // Close any string wrapper file handles
275  if ( isset( $req['_closeHandle'] ) ) {
276  fclose( $req['_closeHandle'] );
277  unset( $req['_closeHandle'] );
278  }
279  }
280  unset( $req ); // don't assign over this by accident
281 
282  // Restore the default settings
283  curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
284  curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
285 
286  return $reqs;
287  }
288 
297  protected function getCurlHandle( array &$req, array $opts = [] ) {
298  $ch = curl_init();
299 
300  curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS,
301  ( $opts['connTimeout'] ?? $this->connTimeout ) * 1000 );
302  curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
303  curl_setopt( $ch, CURLOPT_TIMEOUT_MS,
304  ( $opts['reqTimeout'] ?? $this->reqTimeout ) * 1000 );
305  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
306  curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
307  curl_setopt( $ch, CURLOPT_HEADER, 0 );
308  if ( !is_null( $this->caBundlePath ) ) {
309  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
310  curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
311  }
312  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
313 
314  $url = $req['url'];
315  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
316  if ( $query != '' ) {
317  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
318  }
319  curl_setopt( $ch, CURLOPT_URL, $url );
320 
321  curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
322  if ( $req['method'] === 'HEAD' ) {
323  curl_setopt( $ch, CURLOPT_NOBODY, 1 );
324  }
325 
326  if ( $req['method'] === 'PUT' ) {
327  curl_setopt( $ch, CURLOPT_PUT, 1 );
328  if ( is_resource( $req['body'] ) ) {
329  curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
330  if ( isset( $req['headers']['content-length'] ) ) {
331  curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
332  } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
333  $req['headers']['transfer-encoding'] === 'chunks'
334  ) {
335  curl_setopt( $ch, CURLOPT_UPLOAD, true );
336  } else {
337  throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
338  }
339  } elseif ( $req['body'] !== '' ) {
340  $fp = fopen( "php://temp", "wb+" );
341  fwrite( $fp, $req['body'], strlen( $req['body'] ) );
342  rewind( $fp );
343  curl_setopt( $ch, CURLOPT_INFILE, $fp );
344  curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
345  $req['_closeHandle'] = $fp; // remember to close this later
346  } else {
347  curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
348  }
349  curl_setopt( $ch, CURLOPT_READFUNCTION,
350  function ( $ch, $fd, $length ) {
351  $data = fread( $fd, $length );
352  $len = strlen( $data );
353  return $data;
354  }
355  );
356  } elseif ( $req['method'] === 'POST' ) {
357  curl_setopt( $ch, CURLOPT_POST, 1 );
358  // Don't interpret POST parameters starting with '@' as file uploads, because this
359  // makes it impossible to POST plain values starting with '@' (and causes security
360  // issues potentially exposing the contents of local files).
361  curl_setopt( $ch, CURLOPT_SAFE_UPLOAD, true );
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]) (\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  if ( isset( $req['stream'] ) ) {
411  // Don't just use CURLOPT_FILE as that might give:
412  // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
413  // The callback here handles both normal files and php://temp handles.
414  curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
415  function ( $ch, $data ) use ( &$req ) {
416  return fwrite( $req['stream'], $data );
417  }
418  );
419  } else {
420  curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
421  function ( $ch, $data ) use ( &$req ) {
422  $req['response']['body'] .= $data;
423  return strlen( $data );
424  }
425  );
426  }
427 
428  return $ch;
429  }
430 
435  protected function getCurlMulti() {
436  if ( !$this->multiHandle ) {
437  if ( !function_exists( 'curl_multi_init' ) ) {
438  throw new Exception( "PHP cURL function curl_multi_init missing. " .
439  "Check https://www.mediawiki.org/wiki/Manual:CURL" );
440  }
441  $cmh = curl_multi_init();
442  curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
443  curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
444  $this->multiHandle = $cmh;
445  }
446  return $this->multiHandle;
447  }
448 
462  private function runMultiHttp( array $reqs, array $opts = [] ) {
463  $httpOptions = [
464  'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
465  'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
466  'logger' => $this->logger,
467  'caInfo' => $this->caBundlePath,
468  ];
469  foreach ( $reqs as &$req ) {
470  $reqOptions = $httpOptions + [
471  'method' => $req['method'],
472  'proxy' => $req['proxy'] ?? $this->proxy,
473  'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
474  'postData' => $req['body'],
475  ];
476 
477  $url = $req['url'];
478  $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
479  if ( $query != '' ) {
480  $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
481  }
482 
483  $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
484  $url, $reqOptions );
485  $sv = $httpRequest->execute()->getStatusValue();
486 
487  $respHeaders = array_map(
488  function ( $v ) {
489  return implode( ', ', $v );
490  },
491  $httpRequest->getResponseHeaders() );
492 
493  $req['response'] = [
494  'code' => $httpRequest->getStatus(),
495  'reason' => '',
496  'headers' => $respHeaders,
497  'body' => $httpRequest->getContent(),
498  'error' => '',
499  ];
500 
501  if ( !$sv->isOk() ) {
502  $svErrors = $sv->getErrors();
503  if ( isset( $svErrors[0] ) ) {
504  $req['response']['error'] = $svErrors[0]['message'];
505 
506  // param values vary per failure type (ex. unknown host vs unknown page)
507  if ( isset( $svErrors[0]['params'][0] ) ) {
508  if ( is_numeric( $svErrors[0]['params'][0] ) ) {
509  if ( isset( $svErrors[0]['params'][1] ) ) {
510  $req['response']['reason'] = $svErrors[0]['params'][1];
511  }
512  } else {
513  $req['response']['reason'] = $svErrors[0]['params'][0];
514  }
515  }
516  }
517  }
518 
519  $req['response'][0] = $req['response']['code'];
520  $req['response'][1] = $req['response']['reason'];
521  $req['response'][2] = $req['response']['headers'];
522  $req['response'][3] = $req['response']['body'];
523  $req['response'][4] = $req['response']['error'];
524  }
525 
526  return $reqs;
527  }
528 
534  private function normalizeRequests( array &$reqs ) {
535  foreach ( $reqs as &$req ) {
536  $req['response'] = [
537  'code' => 0,
538  'reason' => '',
539  'headers' => [],
540  'body' => '',
541  'error' => ''
542  ];
543  if ( isset( $req[0] ) ) {
544  $req['method'] = $req[0]; // short-form
545  unset( $req[0] );
546  }
547  if ( isset( $req[1] ) ) {
548  $req['url'] = $req[1]; // short-form
549  unset( $req[1] );
550  }
551  if ( !isset( $req['method'] ) ) {
552  throw new Exception( "Request has no 'method' field set." );
553  } elseif ( !isset( $req['url'] ) ) {
554  throw new Exception( "Request has no 'url' field set." );
555  }
556  $this->logger->debug( "{$req['method']}: {$req['url']}" );
557  $req['query'] = $req['query'] ?? [];
558  $headers = []; // normalized headers
559  if ( isset( $req['headers'] ) ) {
560  foreach ( $req['headers'] as $name => $value ) {
561  $headers[strtolower( $name )] = $value;
562  }
563  }
564  $req['headers'] = $headers;
565  if ( !isset( $req['body'] ) ) {
566  $req['body'] = '';
567  $req['headers']['content-length'] = 0;
568  }
569  $req['flags'] = $req['flags'] ?? [];
570  }
571  }
572 
579  private function getSelectTimeout( $opts ) {
580  $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
581  $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
582  $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
583  if ( count( $timeouts ) === 0 ) {
584  return 1;
585  }
586 
587  $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
588  // Minimum 10us for sanity
589  if ( $selectTimeout < 10e-6 ) {
590  $selectTimeout = 10e-6;
591  }
592  return $selectTimeout;
593  }
594 
600  public function setLogger( LoggerInterface $logger ) {
601  $this->logger = $logger;
602  }
603 
604  function __destruct() {
605  if ( $this->multiHandle ) {
606  curl_multi_close( $this->multiHandle );
607  }
608  }
609 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
LoggerInterface $logger
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
string null $caBundlePath
SSL certificates path.
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1585
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$value
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
in this case you re responsible for computing and outputting the entire conflict i e
Definition: hooks.txt:1420
runMultiCurl(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests concurrently.
__construct(array $options)
$batch
Definition: linkcache.txt:23
normalizeRequests(array &$reqs)
Normalize request information.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
const TIMEOUT_ACCURACY_FACTOR
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
getSelectTimeout( $opts)
Get a suitable select timeout for the given options.
setLogger(LoggerInterface $logger)
Register a logger.
$header
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
isCurlEnabled()
Determines if the curl extension is available.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
this hook is for auditing only $req
Definition: hooks.txt:979
string null $proxy
proxy
getCurlHandle(array &$req, array $opts=[])
run(array $req, array $opts=[])
Execute an HTTP(S) request.
runMultiHttp(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests sequentially.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
Class to handle multiple HTTP requests.
runMulti(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests.
$matches