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 ) {
101 if ( isset( $options[$key] ) ) {
102 $this->$key = $options[$key];
105 if ( $this->logger ===
null ) {
106 $this->logger =
new NullLogger;
129 public function run( array $req, array $opts = [] ) {
130 return $this->
runMulti( [ $req ], $opts )[0][
'response'];
162 public function runMulti( array $reqs, array $opts = [] ) {
179 return extension_loaded(
'curl' );
207 foreach ( $reqs as $index => &$req ) {
209 if ( count( $reqs ) > 1 ) {
211 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE,
true );
216 $indexes = array_keys( $reqs );
217 if ( isset( $opts[
'usePipelining'] ) ) {
218 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (
int)$opts[
'usePipelining'] );
220 if ( isset( $opts[
'maxConnsPerHost'] ) ) {
222 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (
int)$opts[
'maxConnsPerHost'] );
226 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
229 foreach ( $batches as $batch ) {
231 foreach ( $batch as $index ) {
232 curl_multi_add_handle( $chm, $handles[$index] );
239 $mrc = curl_multi_exec( $chm, $active );
240 $info = curl_multi_info_read( $chm );
241 if ( $info !==
false ) {
242 $infos[(int)$info[
'handle']] = $info;
244 }
while ( $mrc == CURLM_CALL_MULTI_PERFORM );
246 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
250 }
while ( $active > 0 && $mrc == CURLM_OK );
254 foreach ( $reqs as $index => &$req ) {
255 $ch = $handles[$index];
256 curl_multi_remove_handle( $chm, $ch );
258 if ( isset( $infos[(
int)$ch] ) ) {
259 $info = $infos[(int)$ch];
260 $errno = $info[
'result'];
261 if ( $errno !== 0 ) {
262 $req[
'response'][
'error'] =
"(curl error: $errno)";
263 if ( function_exists(
'curl_strerror' ) ) {
264 $req[
'response'][
'error'] .=
" " . curl_strerror( $errno );
266 $this->logger->warning(
"Error fetching URL \"{$req['url']}\": " .
267 $req[
'response'][
'error'] );
270 $req[
'response'][
'error'] =
"(curl error: no status set)";
274 $req[
'response'][0] = $req[
'response'][
'code'];
275 $req[
'response'][1] = $req[
'response'][
'reason'];
276 $req[
'response'][2] = $req[
'response'][
'headers'];
277 $req[
'response'][3] = $req[
'response'][
'body'];
278 $req[
'response'][4] = $req[
'response'][
'error'];
281 if ( isset( $req[
'_closeHandle'] ) ) {
282 fclose( $req[
'_closeHandle'] );
283 unset( $req[
'_closeHandle'] );
289 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (
int)$this->usePipelining );
290 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (
int)$this->maxConnsPerHost );
309 curl_setopt( $ch, CURLOPT_PROXY, $req[
'proxy'] ?? $this->proxy );
310 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts[
'connTimeout'] * 1e3 ) );
311 curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts[
'reqTimeout'] * 1e3 ) );
312 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
313 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
314 curl_setopt( $ch, CURLOPT_HEADER, 0 );
315 if ( !is_null( $this->caBundlePath ) ) {
316 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER,
true );
317 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
319 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
322 $query = http_build_query( $req[
'query'],
'',
'&', PHP_QUERY_RFC3986 );
323 if ( $query !=
'' ) {
324 $url .= strpos( $req[
'url'],
'?' ) ===
false ?
"?$query" :
"&$query";
326 curl_setopt( $ch, CURLOPT_URL, $url );
327 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req[
'method'] );
328 curl_setopt( $ch, CURLOPT_NOBODY, ( $req[
'method'] ===
'HEAD' ) );
330 if ( $req[
'method'] ===
'PUT' ) {
331 curl_setopt( $ch, CURLOPT_PUT, 1 );
332 if ( is_resource( $req[
'body'] ) ) {
333 curl_setopt( $ch, CURLOPT_INFILE, $req[
'body'] );
334 if ( isset( $req[
'headers'][
'content-length'] ) ) {
335 curl_setopt( $ch, CURLOPT_INFILESIZE, $req[
'headers'][
'content-length'] );
336 } elseif ( isset( $req[
'headers'][
'transfer-encoding'] ) &&
337 $req[
'headers'][
'transfer-encoding'] ===
'chunks'
339 curl_setopt( $ch, CURLOPT_UPLOAD,
true );
341 throw new Exception(
"Missing 'Content-Length' or 'Transfer-Encoding' header." );
343 } elseif ( $req[
'body'] !==
'' ) {
344 $fp = fopen(
"php://temp",
"wb+" );
345 fwrite( $fp, $req[
'body'], strlen( $req[
'body'] ) );
347 curl_setopt( $ch, CURLOPT_INFILE, $fp );
348 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req[
'body'] ) );
349 $req[
'_closeHandle'] = $fp;
351 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
353 curl_setopt( $ch, CURLOPT_READFUNCTION,
354 function ( $ch, $fd, $length ) {
355 return (
string)fread( $fd, $length );
358 } elseif ( $req[
'method'] ===
'POST' ) {
359 curl_setopt( $ch, CURLOPT_POST, 1 );
360 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req[
'body'] );
362 if ( is_resource( $req[
'body'] ) || $req[
'body'] !==
'' ) {
363 throw new Exception(
"HTTP body specified for a non PUT/POST request." );
365 $req[
'headers'][
'content-length'] = 0;
368 if ( !isset( $req[
'headers'][
'user-agent'] ) ) {
373 foreach ( $req[
'headers'] as $name => $value ) {
374 if ( strpos( $name,
': ' ) ) {
375 throw new Exception(
"Headers cannot have ':' in the name." );
377 $headers[] = $name .
': ' . trim( $value );
379 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
381 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
382 function ( $ch,
$header ) use ( &$req ) {
383 if ( !empty( $req[
'flags'][
'relayResponseHeaders'] ) && trim(
$header ) !==
'' ) {
388 if ( preg_match(
"/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/",
$header,
$matches ) ) {
389 $req[
'response'][
'code'] = (int)
$matches[2];
390 $req[
'response'][
'reason'] = trim(
$matches[3] );
393 if ( strpos(
$header,
":" ) ===
false ) {
396 list( $name, $value ) = explode(
":",
$header, 2 );
397 $name = strtolower( $name );
398 $value = trim( $value );
399 if ( isset( $req[
'response'][
'headers'][$name] ) ) {
400 $req[
'response'][
'headers'][$name] .=
', ' . $value;
402 $req[
'response'][
'headers'][$name] = $value;
409 $hasOutputStream = isset( $req[
'stream'] );
410 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
411 function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
412 if ( $hasOutputStream ) {
413 return fwrite( $req[
'stream'], $data );
416 $req[
'response'][
'body'] .= $data;
418 return strlen( $data );
431 if ( !$this->multiHandle ) {
432 if ( !function_exists(
'curl_multi_init' ) ) {
433 throw new Exception(
"PHP cURL function curl_multi_init missing. " .
434 "Check https://www.mediawiki.org/wiki/Manual:CURL" );
436 $cmh = curl_multi_init();
437 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (
int)$this->usePipelining );
438 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (
int)$this->maxConnsPerHost );
439 $this->multiHandle = $cmh;
464 foreach ( $reqs as &$req ) {
465 $reqOptions = $httpOptions + [
466 'method' => $req[
'method'],
469 'postData' => $req[
'body'],
473 $query = http_build_query( $req[
'query'],
'',
'&', PHP_QUERY_RFC3986 );
474 if ( $query !=
'' ) {
475 $url .= strpos( $req[
'url'],
'?' ) ===
false ?
"?$query" :
"&$query";
478 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
480 $sv = $httpRequest->execute()->getStatusValue();
482 $respHeaders = array_map(
484 return implode(
', ', $v );
486 $httpRequest->getResponseHeaders() );
489 'code' => $httpRequest->getStatus(),
491 'headers' => $respHeaders,
492 'body' => $httpRequest->getContent(),
496 if ( !$sv->isOK() ) {
497 $svErrors = $sv->getErrors();
498 if ( isset( $svErrors[0] ) ) {
499 $req[
'response'][
'error'] = $svErrors[0][
'message'];
502 if ( isset( $svErrors[0][
'params'][0] ) ) {
503 if ( is_numeric( $svErrors[0][
'params'][0] ) ) {
504 if ( isset( $svErrors[0][
'params'][1] ) ) {
506 $req[
'response'][
'reason'] = $svErrors[0][
'params'][1];
509 $req[
'response'][
'reason'] = $svErrors[0][
'params'][0];
515 $req[
'response'][0] = $req[
'response'][
'code'];
516 $req[
'response'][1] = $req[
'response'][
'reason'];
517 $req[
'response'][2] = $req[
'response'][
'headers'];
518 $req[
'response'][3] = $req[
'response'][
'body'];
519 $req[
'response'][4] = $req[
'response'][
'error'];
531 foreach ( $reqs as &$req ) {
539 if ( isset( $req[0] ) ) {
540 $req[
'method'] = $req[0];
543 if ( isset( $req[1] ) ) {
544 $req[
'url'] = $req[1];
547 if ( !isset( $req[
'method'] ) ) {
548 throw new Exception(
"Request has no 'method' field set." );
549 } elseif ( !isset( $req[
'url'] ) ) {
550 throw new Exception(
"Request has no 'url' field set." );
552 $this->logger->debug(
"{$req['method']}: {$req['url']}" );
553 $req[
'query'] = $req[
'query'] ?? [];
555 if ( isset( $req[
'headers'] ) ) {
556 foreach ( $req[
'headers'] as $name => $value ) {
557 $headers[strtolower( $name )] = $value;
560 $req[
'headers'] = $headers;
561 if ( !isset( $req[
'body'] ) ) {
563 $req[
'headers'][
'content-length'] = 0;
565 $req[
'flags'] = $req[
'flags'] ?? [];
579 if ( count( $timeouts ) === 0 ) {
585 if ( $selectTimeout < 10e-6 ) {
586 $selectTimeout = 10e-6;
588 return $selectTimeout;
601 if ( $this->multiHandle ) {
602 curl_multi_close( $this->multiHandle );