MediaWiki REL1_33
MultiHttpClient.php
Go to the documentation of this file.
1<?php
23use Psr\Log\LoggerAwareInterface;
24use Psr\Log\LoggerInterface;
25use Psr\Log\NullLogger;
27
52class 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 // Explicitly test if curl_multi* is blocked, as some users' hosts provide
178 // them with a modified curl with the multi-threaded parts removed(!)
179 return extension_loaded( 'curl' ) && function_exists( 'curl_multi_init' );
180 }
181
196 private function runMultiCurl( array $reqs, array $opts = [] ) {
197 $chm = $this->getCurlMulti();
198
199 $selectTimeout = $this->getSelectTimeout( $opts );
200
201 // Add all of the required cURL handles...
202 $handles = [];
203 foreach ( $reqs as $index => &$req ) {
204 $handles[$index] = $this->getCurlHandle( $req, $opts );
205 if ( count( $reqs ) > 1 ) {
206 // https://github.com/guzzle/guzzle/issues/349
207 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
208 }
209 }
210 unset( $req ); // don't assign over this by accident
211
212 $indexes = array_keys( $reqs );
213 if ( isset( $opts['usePipelining'] ) ) {
214 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
215 }
216 if ( isset( $opts['maxConnsPerHost'] ) ) {
217 // Keep these sockets around as they may be needed later in the request
218 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
219 }
220
221 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
222 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
223 $infos = [];
224
225 foreach ( $batches as $batch ) {
226 // Attach all cURL handles for this batch
227 foreach ( $batch as $index ) {
228 curl_multi_add_handle( $chm, $handles[$index] );
229 }
230 // Execute the cURL handles concurrently...
231 $active = null; // handles still being processed
232 do {
233 // Do any available work...
234 do {
235 $mrc = curl_multi_exec( $chm, $active );
236 $info = curl_multi_info_read( $chm );
237 if ( $info !== false ) {
238 $infos[(int)$info['handle']] = $info;
239 }
240 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
241 // Wait (if possible) for available work...
242 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
243 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
244 usleep( 5000 ); // 5ms
245 }
246 } while ( $active > 0 && $mrc == CURLM_OK );
247 }
248
249 // Remove all of the added cURL handles and check for errors...
250 foreach ( $reqs as $index => &$req ) {
251 $ch = $handles[$index];
252 curl_multi_remove_handle( $chm, $ch );
253
254 if ( isset( $infos[(int)$ch] ) ) {
255 $info = $infos[(int)$ch];
256 $errno = $info['result'];
257 if ( $errno !== 0 ) {
258 $req['response']['error'] = "(curl error: $errno)";
259 if ( function_exists( 'curl_strerror' ) ) {
260 $req['response']['error'] .= " " . curl_strerror( $errno );
261 }
262 $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
263 $req['response']['error'] );
264 }
265 } else {
266 $req['response']['error'] = "(curl error: no status set)";
267 }
268
269 // For convenience with the list() operator
270 $req['response'][0] = $req['response']['code'];
271 $req['response'][1] = $req['response']['reason'];
272 $req['response'][2] = $req['response']['headers'];
273 $req['response'][3] = $req['response']['body'];
274 $req['response'][4] = $req['response']['error'];
275 curl_close( $ch );
276 // Close any string wrapper file handles
277 if ( isset( $req['_closeHandle'] ) ) {
278 fclose( $req['_closeHandle'] );
279 unset( $req['_closeHandle'] );
280 }
281 }
282 unset( $req ); // don't assign over this by accident
283
284 // Restore the default settings
285 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
286 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
287
288 return $reqs;
289 }
290
299 protected function getCurlHandle( array &$req, array $opts = [] ) {
300 $ch = curl_init();
301
302 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS,
303 ( $opts['connTimeout'] ?? $this->connTimeout ) * 1000 );
304 curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
305 curl_setopt( $ch, CURLOPT_TIMEOUT_MS,
306 ( $opts['reqTimeout'] ?? $this->reqTimeout ) * 1000 );
307 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
308 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
309 curl_setopt( $ch, CURLOPT_HEADER, 0 );
310 if ( !is_null( $this->caBundlePath ) ) {
311 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
312 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
313 }
314 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
315
316 $url = $req['url'];
317 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
318 if ( $query != '' ) {
319 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
320 }
321 curl_setopt( $ch, CURLOPT_URL, $url );
322
323 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
324 if ( $req['method'] === 'HEAD' ) {
325 curl_setopt( $ch, CURLOPT_NOBODY, 1 );
326 }
327
328 if ( $req['method'] === 'PUT' ) {
329 curl_setopt( $ch, CURLOPT_PUT, 1 );
330 if ( is_resource( $req['body'] ) ) {
331 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
332 if ( isset( $req['headers']['content-length'] ) ) {
333 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
334 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
335 $req['headers']['transfer-encoding'] === 'chunks'
336 ) {
337 curl_setopt( $ch, CURLOPT_UPLOAD, true );
338 } else {
339 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
340 }
341 } elseif ( $req['body'] !== '' ) {
342 $fp = fopen( "php://temp", "wb+" );
343 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
344 rewind( $fp );
345 curl_setopt( $ch, CURLOPT_INFILE, $fp );
346 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
347 $req['_closeHandle'] = $fp; // remember to close this later
348 } else {
349 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
350 }
351 curl_setopt( $ch, CURLOPT_READFUNCTION,
352 function ( $ch, $fd, $length ) {
353 $data = fread( $fd, $length );
354 $len = strlen( $data );
355 return $data;
356 }
357 );
358 } elseif ( $req['method'] === 'POST' ) {
359 curl_setopt( $ch, CURLOPT_POST, 1 );
360 // Don't interpret POST parameters starting with '@' as file uploads, because this
361 // makes it impossible to POST plain values starting with '@' (and causes security
362 // issues potentially exposing the contents of local files).
363 curl_setopt( $ch, CURLOPT_SAFE_UPLOAD, true );
364 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
365 } else {
366 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
367 throw new Exception( "HTTP body specified for a non PUT/POST request." );
368 }
369 $req['headers']['content-length'] = 0;
370 }
371
372 if ( !isset( $req['headers']['user-agent'] ) ) {
373 $req['headers']['user-agent'] = $this->userAgent;
374 }
375
376 $headers = [];
377 foreach ( $req['headers'] as $name => $value ) {
378 if ( strpos( $name, ': ' ) ) {
379 throw new Exception( "Headers cannot have ':' in the name." );
380 }
381 $headers[] = $name . ': ' . trim( $value );
382 }
383 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
384
385 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
386 function ( $ch, $header ) use ( &$req ) {
387 if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
388 header( $header );
389 }
390 $length = strlen( $header );
391 $matches = [];
392 if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
393 $req['response']['code'] = (int)$matches[2];
394 $req['response']['reason'] = trim( $matches[3] );
395 return $length;
396 }
397 if ( strpos( $header, ":" ) === false ) {
398 return $length;
399 }
400 list( $name, $value ) = explode( ":", $header, 2 );
401 $name = strtolower( $name );
402 $value = trim( $value );
403 if ( isset( $req['response']['headers'][$name] ) ) {
404 $req['response']['headers'][$name] .= ', ' . $value;
405 } else {
406 $req['response']['headers'][$name] = $value;
407 }
408 return $length;
409 }
410 );
411
412 if ( isset( $req['stream'] ) ) {
413 // Don't just use CURLOPT_FILE as that might give:
414 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
415 // The callback here handles both normal files and php://temp handles.
416 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
417 function ( $ch, $data ) use ( &$req ) {
418 return fwrite( $req['stream'], $data );
419 }
420 );
421 } else {
422 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
423 function ( $ch, $data ) use ( &$req ) {
424 $req['response']['body'] .= $data;
425 return strlen( $data );
426 }
427 );
428 }
429
430 return $ch;
431 }
432
437 protected function getCurlMulti() {
438 if ( !$this->multiHandle ) {
439 if ( !function_exists( 'curl_multi_init' ) ) {
440 throw new Exception( "PHP cURL function curl_multi_init missing. " .
441 "Check https://www.mediawiki.org/wiki/Manual:CURL" );
442 }
443 $cmh = curl_multi_init();
444 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
445 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
446 $this->multiHandle = $cmh;
447 }
448 return $this->multiHandle;
449 }
450
464 private function runMultiHttp( array $reqs, array $opts = [] ) {
465 $httpOptions = [
466 'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
467 'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
468 'logger' => $this->logger,
469 'caInfo' => $this->caBundlePath,
470 ];
471 foreach ( $reqs as &$req ) {
472 $reqOptions = $httpOptions + [
473 'method' => $req['method'],
474 'proxy' => $req['proxy'] ?? $this->proxy,
475 'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
476 'postData' => $req['body'],
477 ];
478
479 $url = $req['url'];
480 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
481 if ( $query != '' ) {
482 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
483 }
484
485 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
486 $url, $reqOptions );
487 $sv = $httpRequest->execute()->getStatusValue();
488
489 $respHeaders = array_map(
490 function ( $v ) {
491 return implode( ', ', $v );
492 },
493 $httpRequest->getResponseHeaders() );
494
495 $req['response'] = [
496 'code' => $httpRequest->getStatus(),
497 'reason' => '',
498 'headers' => $respHeaders,
499 'body' => $httpRequest->getContent(),
500 'error' => '',
501 ];
502
503 if ( !$sv->isOk() ) {
504 $svErrors = $sv->getErrors();
505 if ( isset( $svErrors[0] ) ) {
506 $req['response']['error'] = $svErrors[0]['message'];
507
508 // param values vary per failure type (ex. unknown host vs unknown page)
509 if ( isset( $svErrors[0]['params'][0] ) ) {
510 if ( is_numeric( $svErrors[0]['params'][0] ) ) {
511 if ( isset( $svErrors[0]['params'][1] ) ) {
512 $req['response']['reason'] = $svErrors[0]['params'][1];
513 }
514 } else {
515 $req['response']['reason'] = $svErrors[0]['params'][0];
516 }
517 }
518 }
519 }
520
521 $req['response'][0] = $req['response']['code'];
522 $req['response'][1] = $req['response']['reason'];
523 $req['response'][2] = $req['response']['headers'];
524 $req['response'][3] = $req['response']['body'];
525 $req['response'][4] = $req['response']['error'];
526 }
527
528 return $reqs;
529 }
530
536 private function normalizeRequests( array &$reqs ) {
537 foreach ( $reqs as &$req ) {
538 $req['response'] = [
539 'code' => 0,
540 'reason' => '',
541 'headers' => [],
542 'body' => '',
543 'error' => ''
544 ];
545 if ( isset( $req[0] ) ) {
546 $req['method'] = $req[0]; // short-form
547 unset( $req[0] );
548 }
549 if ( isset( $req[1] ) ) {
550 $req['url'] = $req[1]; // short-form
551 unset( $req[1] );
552 }
553 if ( !isset( $req['method'] ) ) {
554 throw new Exception( "Request has no 'method' field set." );
555 } elseif ( !isset( $req['url'] ) ) {
556 throw new Exception( "Request has no 'url' field set." );
557 }
558 $this->logger->debug( "{$req['method']}: {$req['url']}" );
559 $req['query'] = $req['query'] ?? [];
560 $headers = []; // normalized headers
561 if ( isset( $req['headers'] ) ) {
562 foreach ( $req['headers'] as $name => $value ) {
563 $headers[strtolower( $name )] = $value;
564 }
565 }
566 $req['headers'] = $headers;
567 if ( !isset( $req['body'] ) ) {
568 $req['body'] = '';
569 $req['headers']['content-length'] = 0;
570 }
571 $req['flags'] = $req['flags'] ?? [];
572 }
573 }
574
581 private function getSelectTimeout( $opts ) {
582 $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
583 $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
584 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
585 if ( count( $timeouts ) === 0 ) {
586 return 1;
587 }
588
589 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
590 // Minimum 10us for sanity
591 if ( $selectTimeout < 10e-6 ) {
592 $selectTimeout = 10e-6;
593 }
594 return $selectTimeout;
595 }
596
602 public function setLogger( LoggerInterface $logger ) {
603 $this->logger = $logger;
604 }
605
606 function __destruct() {
607 if ( $this->multiHandle ) {
608 curl_multi_close( $this->multiHandle );
609 }
610 }
611}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
MediaWikiServices is the service locator for the application scope of MediaWiki.
Class to handle multiple HTTP requests.
runMultiHttp(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests sequentially.
runMulti(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests.
getSelectTimeout( $opts)
Get a suitable select timeout for the given options.
normalizeRequests(array &$reqs)
Normalize request information.
__construct(array $options)
string null $proxy
proxy
string null $caBundlePath
SSL certificates path.
LoggerInterface $logger
setLogger(LoggerInterface $logger)
Register a logger.
run(array $req, array $opts=[])
Execute an HTTP(S) request.
runMultiCurl(array $reqs, array $opts=[])
Execute a set of HTTP(S) requests concurrently.
isCurlEnabled()
Determines if the curl extension is available.
getCurlHandle(array &$req, array $opts=[])
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
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
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
this hook is for auditing only $req
Definition hooks.txt:979
in this case you re responsible for computing and outputting the entire conflict i e
Definition hooks.txt:1423
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:1999
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:271
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:1617
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:37
$batch
Definition linkcache.txt:23
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))
$header