23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
68 protected $userAgent =
'wikimedia/multi-http-client v1.0';
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 );
97 'connTimeout',
'reqTimeout',
'usePipelining',
'maxConnsPerHost',
98 'proxy',
'userAgent',
'logger'
100 foreach ( $opts
as $key ) {
105 if ( $this->logger ===
null ) {
106 $this->logger =
new NullLogger;
130 return $this->
runMulti( [ $req ], $opts )[0][
'response'];
177 return extension_loaded(
'curl' );
201 foreach ( $reqs
as $index => &
$req ) {
203 if (
count( $reqs ) > 1 ) {
205 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE,
true );
210 $indexes = array_keys( $reqs );
211 if ( isset( $opts[
'usePipelining'] ) ) {
212 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (
int)$opts[
'usePipelining'] );
214 if ( isset( $opts[
'maxConnsPerHost'] ) ) {
216 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (
int)$opts[
'maxConnsPerHost'] );
220 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
226 curl_multi_add_handle( $chm, $handles[$index] );
233 $mrc = curl_multi_exec( $chm, $active );
234 $info = curl_multi_info_read( $chm );
235 if ( $info !==
false ) {
236 $infos[(int)$info[
'handle']] = $info;
238 }
while ( $mrc == CURLM_CALL_MULTI_PERFORM );
240 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
244 }
while ( $active > 0 && $mrc == CURLM_OK );
248 foreach ( $reqs
as $index => &
$req ) {
249 $ch = $handles[$index];
250 curl_multi_remove_handle( $chm, $ch );
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 );
260 $this->logger->warning(
"Error fetching URL \"{$req['url']}\": " .
261 $req[
'response'][
'error'] );
264 $req[
'response'][
'error'] =
"(curl error: no status set)";
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'];
275 if ( isset(
$req[
'_closeHandle'] ) ) {
276 fclose(
$req[
'_closeHandle'] );
277 unset(
$req[
'_closeHandle'] );
283 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (
int)$this->usePipelining );
284 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (
int)$this->maxConnsPerHost );
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 );
312 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
315 $query = http_build_query(
$req[
'query'],
'',
'&', PHP_QUERY_RFC3986 );
317 $url .= strpos(
$req[
'url'],
'?' ) ===
false ?
"?$query" :
"&$query";
319 curl_setopt( $ch, CURLOPT_URL, $url );
321 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST,
$req[
'method'] );
322 if (
$req[
'method'] ===
'HEAD' ) {
323 curl_setopt( $ch, CURLOPT_NOBODY, 1 );
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'
335 curl_setopt( $ch, CURLOPT_UPLOAD,
true );
337 throw new Exception(
"Missing 'Content-Length' or 'Transfer-Encoding' header." );
339 } elseif (
$req[
'body'] !==
'' ) {
340 $fp = fopen(
"php://temp",
"wb+" );
341 fwrite( $fp,
$req[
'body'], strlen(
$req[
'body'] ) );
343 curl_setopt( $ch, CURLOPT_INFILE, $fp );
344 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen(
$req[
'body'] ) );
345 $req[
'_closeHandle'] = $fp;
347 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
349 curl_setopt( $ch, CURLOPT_READFUNCTION,
350 function ( $ch, $fd, $length ) {
351 $data = fread( $fd, $length );
352 $len = strlen(
$data );
356 } elseif (
$req[
'method'] ===
'POST' ) {
357 curl_setopt( $ch, CURLOPT_POST, 1 );
361 curl_setopt( $ch, CURLOPT_SAFE_UPLOAD,
true );
362 curl_setopt( $ch, CURLOPT_POSTFIELDS,
$req[
'body'] );
364 if ( is_resource(
$req[
'body'] ) ||
$req[
'body'] !==
'' ) {
365 throw new Exception(
"HTTP body specified for a non PUT/POST request." );
367 $req[
'headers'][
'content-length'] = 0;
370 if ( !isset(
$req[
'headers'][
'user-agent'] ) ) {
376 if ( strpos(
$name,
': ' ) ) {
377 throw new Exception(
"Headers cannot have ':' in the name." );
381 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
383 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
385 if ( !empty(
$req[
'flags'][
'relayResponseHeaders'] ) && trim(
$header ) !==
'' ) {
390 if ( preg_match(
"/^(HTTP\/1\.[01]) (\d{3}) (.*)/",
$header,
$matches ) ) {
395 if ( strpos(
$header,
":" ) ===
false ) {
401 if ( isset(
$req[
'response'][
'headers'][
$name] ) ) {
410 if ( isset(
$req[
'stream'] ) ) {
414 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
420 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
423 return strlen(
$data );
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" );
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;
469 foreach ( $reqs
as &
$req ) {
470 $reqOptions = $httpOptions + [
471 'method' =>
$req[
'method'],
474 'postData' =>
$req[
'body'],
478 $query = http_build_query(
$req[
'query'],
'',
'&', PHP_QUERY_RFC3986 );
480 $url .= strpos(
$req[
'url'],
'?' ) ===
false ?
"?$query" :
"&$query";
483 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
485 $sv = $httpRequest->execute()->getStatusValue();
487 $respHeaders = array_map(
489 return implode(
', ', $v );
491 $httpRequest->getResponseHeaders() );
494 'code' => $httpRequest->getStatus(),
496 'headers' => $respHeaders,
497 'body' => $httpRequest->getContent(),
501 if ( !$sv->isOk() ) {
502 $svErrors = $sv->getErrors();
503 if ( isset( $svErrors[0] ) ) {
504 $req[
'response'][
'error'] = $svErrors[0][
'message'];
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];
513 $req[
'response'][
'reason'] = $svErrors[0][
'params'][0];
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'];
535 foreach ( $reqs
as &
$req ) {
543 if ( isset(
$req[0] ) ) {
547 if ( isset(
$req[1] ) ) {
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." );
556 $this->logger->debug(
"{$req['method']}: {$req['url']}" );
557 $req[
'query'] =
$req[
'query'] ?? [];
559 if ( isset(
$req[
'headers'] ) ) {
564 $req[
'headers'] = $headers;
565 if ( !isset(
$req[
'body'] ) ) {
567 $req[
'headers'][
'content-length'] = 0;
569 $req[
'flags'] =
$req[
'flags'] ?? [];
583 if (
count( $timeouts ) === 0 ) {
589 if ( $selectTimeout < 10
e-6 ) {
590 $selectTimeout = 10
e-6;
592 return $selectTimeout;
605 if ( $this->multiHandle ) {
606 curl_multi_close( $this->multiHandle );