Debian Codegraph @

includes/libs/http/MultiHttpClient.php

raw symbols SCIP
1 <?php
2 /**
3 * HTTP service client
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 namespace Wikimedia\Http;
24
25 use InvalidArgumentException;
26 use MediaWiki\MediaWikiServices;
27 use Psr\Log\LoggerAwareInterface;
28 use Psr\Log\LoggerInterface;
29 use Psr\Log\NullLogger;
30
31 /**
32 * Class to handle multiple HTTP requests
33 *
34 * If curl is available, requests will be made concurrently.
35 * Otherwise, they will be made serially.
36 *
37 * HTTP request maps are arrays that use the following format:
38 * - method : GET/HEAD/PUT/POST/DELETE
39 * - url : HTTP/HTTPS URL
40 * - query : <query parameter field/value associative array> (uses RFC 3986)
41 * - headers : <header name/value associative array>
42 * - body : source to get the HTTP request body from;
43 * this can simply be a string (always), a resource for
44 * PUT requests, and a field/value array for POST request;
45 * array bodies are encoded as multipart/form-data and strings
46 * use application/x-www-form-urlencoded (headers sent automatically)
47 * - stream : resource to stream the HTTP response body to
48 * - proxy : HTTP proxy to use
49 * - flags : map of boolean flags which supports:
50 * - relayResponseHeaders : write out header via header()
51 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
52 *
53 * Since 1.35, callers should use HttpRequestFactory::createMultiClient() to get
54 * a client object with appropriately configured timeouts.
55 *
56 * @since 1.23
57 */
58 class MultiHttpClient implements LoggerAwareInterface {
59 /** Regex for headers likely to contain tokens, etc. that we want to redact from logs */
60 private const SENSITIVE_HEADERS = '/(^|-|_)(authorization|auth|password|cookie)($|-|_)/';
61 /**
62 * @phpcs:ignore MediaWiki.Commenting.PropertyDocumentation.ObjectTypeHintVar
63 * @var resource|object|null curl_multi_init() handle, initialized in getCurlMulti()
64 */
65 protected $cmh = null;
66 /** @var string|null SSL certificates path */
67 protected $caBundlePath;
68 /** @var float */
69 protected $connTimeout = 10;
70 /** @var float */
71 protected $maxConnTimeout = INF;
72 /** @var float */
73 protected $reqTimeout = 30;
74 /** @var float */
75 protected $maxReqTimeout = INF;
76 /** @var bool */
77 protected $usePipelining = false;
78 /** @var int */
79 protected $maxConnsPerHost = 50;
80 /** @var string|null proxy */
81 protected $proxy;
82 /** @var string|false */
83 protected $localProxy = false;
84 /** @var string[] */
85 protected $localVirtualHosts = [];
86 /** @var string */
87 protected $userAgent = 'wikimedia/multi-http-client v1.1';
88 /** @var LoggerInterface */
89 protected $logger;
90 /** @var array */
91 protected array $headers = [];
92
93 // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
94 // timeouts are periodically polled instead of being accurately respected.
95 // The select timeout is set to the minimum timeout multiplied by this factor.
96 private const TIMEOUT_ACCURACY_FACTOR = 0.1;
97
98 private ?TelemetryHeadersInterface $telemetry = null;
99
100 /**
101 * Since 1.35, callers should use HttpRequestFactory::createMultiClient() to get
102 * a client object with appropriately configured timeouts instead of constructing
103 * a MultiHttpClient directly.
104 *
105 * @param array $options
106 * - connTimeout : default connection timeout (seconds)
107 * - reqTimeout : default request timeout (seconds)
108 * - maxConnTimeout : maximum connection timeout (seconds)
109 * - maxReqTimeout : maximum request timeout (seconds)
110 * - proxy : HTTP proxy to use
111 * - localProxy : Reverse proxy to use for domains in localVirtualHosts
112 * - localVirtualHosts : Domains that are configured as virtual hosts on the same machine
113 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
114 * - maxConnsPerHost : maximum number of concurrent connections (per host)
115 * - userAgent : The User-Agent header value to send
116 * - logger : a \Psr\Log\LoggerInterface instance for debug logging
117 * - caBundlePath : path to specific Certificate Authority bundle (if any)
118 * - headers : an array of default headers to send with every request
119 * - telemetry : a \Wikimedia\Http\RequestTelemetry instance to track telemetry data
120 * @throws \Exception
121 */
122 public function __construct( array $options ) {
123 if ( isset( $options['caBundlePath'] ) ) {
124 $this->caBundlePath = $options['caBundlePath'];
125 if ( !file_exists( $this->caBundlePath ) ) {
126 throw new InvalidArgumentException( "Cannot find CA bundle: " . $this->caBundlePath );
127 }
128 }
129 static $opts = [
130 'connTimeout', 'maxConnTimeout', 'reqTimeout', 'maxReqTimeout',
131 'usePipelining', 'maxConnsPerHost', 'proxy', 'userAgent', 'logger',
132 'localProxy', 'localVirtualHosts', 'headers', 'telemetry'
133 ];
134 foreach ( $opts as $key ) {
135 if ( isset( $options[$key] ) ) {
136 $this->$key = $options[$key];
137 }
138 }
139 $this->logger ??= new NullLogger;
140 }
141
142 /**
143 * Execute an HTTP(S) request
144 *
145 * This method returns a response map of:
146 * - code : HTTP response code or 0 if there was a serious error
147 * - reason : HTTP response reason (empty if there was a serious error)
148 * - headers : <header name/value associative array>
149 * - body : HTTP response body or resource (if "stream" was set)
150 * - error : Any error string
151 * The map also stores integer-indexed copies of these values. This lets callers do:
152 * @code
153 * [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $http->run( $req );
154 * @endcode
155 * @param array $req HTTP request array
156 * @param array $opts
157 * - connTimeout : connection timeout per request (seconds)
158 * - reqTimeout : post-connection timeout per request (seconds)
159 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
160 * - maxConnsPerHost : maximum number of concurrent connections (per host)
161 * - httpVersion : One of 'v1.0', 'v1.1', 'v2', 'v2.0', 'v3' or 'v3.0'. Leave empty to use
162 * PHP/curl's default
163 * @return array Response array for request
164 */
165 public function run( array $req, array $opts = [] ) {
166 return $this->runMulti( [ $req ], $opts )[0]['response'];
167 }
168
169 /**
170 * Execute a set of HTTP(S) requests.
171 *
172 * If curl is available, requests will be made concurrently.
173 * Otherwise, they will be made serially.
174 *
175 * The maps are returned by this method with the 'response' field set to a map of:
176 * - code : HTTP response code or 0 if there was a serious error
177 * - reason : HTTP response reason (empty if there was a serious error)
178 * - headers : <header name/value associative array>
179 * - body : HTTP response body or resource (if "stream" was set)
180 * - error : Any error string
181 * The map also stores integer-indexed copies of these values. This lets callers do:
182 * @code
183 * [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $req['response'];
184 * @endcode
185 * All headers in the 'headers' field are normalized to use lower case names.
186 * This is true for the request headers and the response headers. Integer-indexed
187 * method/URL entries will also be changed to use the corresponding string keys.
188 *
189 * @param array[] $reqs Map of HTTP request arrays
190 * @param array $opts Options
191 * - connTimeout : connection timeout per request (seconds)
192 * - reqTimeout : post-connection timeout per request (seconds)
193 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
194 * - maxConnsPerHost : maximum number of concurrent connections (per host)
195 * - httpVersion : One of 'v1.0', 'v1.1', 'v2', 'v2.0', 'v3' or 'v3.0'. Leave empty to use
196 * PHP/curl's default
197 * @return array[] $reqs With response array populated for each
198 * @throws \Exception
199 */
200 public function runMulti( array $reqs, array $opts = [] ) {
201 $this->normalizeRequests( $reqs );
202 $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
203
204 if ( $this->maxConnTimeout && $opts['connTimeout'] > $this->maxConnTimeout ) {
205 $opts['connTimeout'] = $this->maxConnTimeout;
206 }
207 if ( $this->maxReqTimeout && $opts['reqTimeout'] > $this->maxReqTimeout ) {
208 $opts['reqTimeout'] = $this->maxReqTimeout;
209 }
210
211 if ( $this->isCurlEnabled() ) {
212 switch ( $opts['httpVersion'] ?? null ) {
213 case 'v1.0':
214 $opts['httpVersion'] = CURL_HTTP_VERSION_1_0;
215 break;
216 case 'v1.1':
217 $opts['httpVersion'] = CURL_HTTP_VERSION_1_1;
218 break;
219 case 'v2':
220 case 'v2.0':
221 $opts['httpVersion'] = CURL_HTTP_VERSION_2_0;
222 break;
223 case 'v3':
224 case 'v3.0':
225 $opts['httpVersion'] = CURL_HTTP_VERSION_3;
226 break;
227 default:
228 $opts['httpVersion'] = CURL_HTTP_VERSION_NONE;
229 }
230 return $this->runMultiCurl( $reqs, $opts );
231 } else {
232 # TODO: Add handling for httpVersion option
233 return $this->runMultiHttp( $reqs, $opts );
234 }
235 }
236
237 /**
238 * Determines if the curl extension is available
239 *
240 * @return bool true if curl is available, false otherwise.
241 */
242 protected function isCurlEnabled() {
243 // Explicitly test if curl_multi* is blocked, as some users' hosts provide
244 // them with a modified curl with the multi-threaded parts removed(!)
245 return extension_loaded( 'curl' ) && function_exists( 'curl_multi_init' );
246 }
247
248 /**
249 * Execute a set of HTTP(S) requests concurrently
250 *
251 * @see MultiHttpClient::runMulti()
252 *
253 * @param array[] $reqs Map of HTTP request arrays
254 * @param array $opts
255 * - connTimeout : connection timeout per request (seconds)
256 * - reqTimeout : post-connection timeout per request (seconds)
257 * - usePipelining : whether to use HTTP pipelining if possible
258 * - maxConnsPerHost : maximum number of concurrent connections (per host)
259 * - httpVersion: : HTTP version to use
260 * @phan-param array{connTimeout?:int,reqTimeout?:int,usePipelining?:bool,maxConnsPerHost?:int} $opts
261 * @return array $reqs With response array populated for each
262 * @throws \Exception
263 * @suppress PhanTypeInvalidDimOffset
264 */
265 private function runMultiCurl( array $reqs, array $opts ) {
266 $chm = $this->getCurlMulti( $opts );
267
268 $selectTimeout = $this->getSelectTimeout( $opts );
269
270 // Add all of the required cURL handles...
271 $handles = [];
272 foreach ( $reqs as $index => &$req ) {
273 $handles[$index] = $this->getCurlHandle( $req, $opts );
274 curl_multi_add_handle( $chm, $handles[$index] );
275 }
276 unset( $req ); // don't assign over this by accident
277
278 $infos = [];
279 // Execute the cURL handles concurrently...
280 $active = null; // handles still being processed
281 do {
282 // Do any available work...
283 do {
284 $mrc = curl_multi_exec( $chm, $active );
285 $info = curl_multi_info_read( $chm );
286 if ( $info !== false ) {
287 // Note: cast to integer even works on PHP 8.0+ despite the
288 // handle being an object not a resource, because CurlHandle
289 // has a backwards-compatible cast_object handler.
290 $infos[(int)$info['handle']] = $info;
291 }
292 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
293 // Wait (if possible) for available work...
294 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
295 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
296 usleep( 5000 ); // 5ms
297 }
298 } while ( $active > 0 && $mrc == CURLM_OK );
299
300 // Remove all of the added cURL handles and check for errors...
301 foreach ( $reqs as $index => &$req ) {
302 $ch = $handles[$index];
303 curl_multi_remove_handle( $chm, $ch );
304
305 if ( isset( $infos[(int)$ch] ) ) {
306 $info = $infos[(int)$ch];
307 $errno = $info['result'];
308 if ( $errno !== 0 ) {
309 $req['response']['error'] = "(curl error: $errno)";
310 if ( function_exists( 'curl_strerror' ) ) {
311 $req['response']['error'] .= " " . curl_strerror( $errno );
312 }
313 $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
314 $req['response']['error'] );
315 } else {
316 $this->logger->debug(
317 "HTTP complete: {method} {url} code={response_code} size={size} " .
318 "total={total_time} connect={connect_time}",
319 [
320 'method' => $req['method'],
321 'url' => $req['url'],
322 'response_code' => $req['response']['code'],
323 'size' => curl_getinfo( $ch, CURLINFO_SIZE_DOWNLOAD ),
324 'total_time' => $this->getCurlTime(
325 $ch, CURLINFO_TOTAL_TIME, 'CURLINFO_TOTAL_TIME_T'
326 ),
327 'connect_time' => $this->getCurlTime(
328 $ch, CURLINFO_CONNECT_TIME, 'CURLINFO_CONNECT_TIME_T'
329 ),
330 ]
331 );
332 }
333 } else {
334 $req['response']['error'] = "(curl error: no status set)";
335 }
336
337 // For convenience with array destructuring
338 $req['response'][0] = $req['response']['code'];
339 $req['response'][1] = $req['response']['reason'];
340 $req['response'][2] = $req['response']['headers'];
341 $req['response'][3] = $req['response']['body'];
342 $req['response'][4] = $req['response']['error'];
343 // Close any string wrapper file handles
344 if ( isset( $req['_closeHandle'] ) ) {
345 fclose( $req['_closeHandle'] );
346 unset( $req['_closeHandle'] );
347 }
348 }
349 unset( $req ); // don't assign over this by accident
350
351 return $reqs;
352 }
353
354 /**
355 * @param array &$req HTTP request map
356 * @phpcs:ignore Generic.Files.LineLength
357 * @phan-param array{url:string,proxy?:?string,query:mixed,method:string,body:string|resource,headers:array<string,string>,stream?:resource,flags:array} $req
358 * @param array $opts
359 * - connTimeout : default connection timeout
360 * - reqTimeout : default request timeout
361 * - httpVersion: default HTTP version
362 * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintReturn
363 * @return resource|object
364 * @throws \Exception
365 */
366 protected function getCurlHandle( array &$req, array $opts ) {
367 $ch = curl_init();
368
369 curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
370 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
371 curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
372 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
373 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
374 curl_setopt( $ch, CURLOPT_HEADER, 0 );
375 if ( $this->caBundlePath !== null ) {
376 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
377 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
378 }
379 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
380
381 $url = $req['url'];
382 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
383 if ( $query != '' ) {
384 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
385 }
386 curl_setopt( $ch, CURLOPT_URL, $url );
387 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
388 curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
389 curl_setopt( $ch, CURLOPT_HTTP_VERSION, $opts['httpVersion'] ?? CURL_HTTP_VERSION_NONE );
390
391 if ( $req['method'] === 'PUT' ) {
392 curl_setopt( $ch, CURLOPT_PUT, 1 );
393 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
394 if ( is_resource( $req['body'] ) ) {
395 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
396 if ( isset( $req['headers']['content-length'] ) ) {
397 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
398 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
399 $req['headers']['transfer-encoding'] === 'chunks'
400 ) {
401 curl_setopt( $ch, CURLOPT_UPLOAD, true );
402 } else {
403 throw new InvalidArgumentException( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
404 }
405 } elseif ( $req['body'] !== '' ) {
406 $fp = fopen( "php://temp", "wb+" );
407 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
408 rewind( $fp );
409 curl_setopt( $ch, CURLOPT_INFILE, $fp );
410 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
411 $req['_closeHandle'] = $fp; // remember to close this later
412 } else {
413 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
414 }
415 curl_setopt( $ch, CURLOPT_READFUNCTION,
416 static function ( $ch, $fd, $length ) {
417 return (string)fread( $fd, $length );
418 }
419 );
420 } elseif ( $req['method'] === 'POST' ) {
421 curl_setopt( $ch, CURLOPT_POST, 1 );
422 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
423 } else {
424 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
425 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
426 throw new InvalidArgumentException( "HTTP body specified for a non PUT/POST request." );
427 }
428 $req['headers']['content-length'] = 0;
429 }
430
431 if ( !isset( $req['headers']['user-agent'] ) ) {
432 $req['headers']['user-agent'] = $this->userAgent;
433 }
434
435 $headers = [];
436 foreach ( $req['headers'] as $name => $value ) {
437 if ( strpos( $name, ':' ) !== false ) {
438 throw new InvalidArgumentException( "Header name must not contain colon-space." );
439 }
440 $headers[] = $name . ': ' . trim( $value );
441 }
442 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
443
444 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
445 static function ( $ch, $header ) use ( &$req ) {
446 if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
447 header( $header );
448 }
449 $length = strlen( $header );
450 $matches = [];
451 if ( preg_match( "/^(HTTP\/(?:1\.[01]|2|3)) (\d{3}) (.*)/", $header, $matches ) ) {
452 $req['response']['code'] = (int)$matches[2];
453 $req['response']['reason'] = trim( $matches[3] );
454 // After a redirect we will receive this again, but we already stored headers
455 // that belonged to a redirect response. Start over.
456 $req['response']['headers'] = [];
457 return $length;
458 }
459 if ( strpos( $header, ":" ) === false ) {
460 return $length;
461 }
462 [ $name, $value ] = explode( ":", $header, 2 );
463 $name = strtolower( $name );
464 $value = trim( $value );
465 if ( isset( $req['response']['headers'][$name] ) ) {
466 $req['response']['headers'][$name] .= ', ' . $value;
467 } else {
468 $req['response']['headers'][$name] = $value;
469 }
470 return $length;
471 }
472 );
473
474 // This works with both file and php://temp handles (unlike CURLOPT_FILE)
475 $hasOutputStream = isset( $req['stream'] );
476 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
477 static function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
478 if ( $hasOutputStream ) {
479 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
480 return fwrite( $req['stream'], $data );
481 } else {
482 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
483 $req['response']['body'] .= $data;
484
485 return strlen( $data );
486 }
487 }
488 );
489
490 return $ch;
491 }
492
493 /**
494 * @param array $opts
495 * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintReturn
496 * @return resource|object
497 * @throws \Exception
498 */
499 protected function getCurlMulti( array $opts ) {
500 if ( !$this->cmh ) {
501 $cmh = curl_multi_init();
502 // Limit the size of the idle connection cache such that consecutive parallel
503 // request batches to the same host can avoid having to keep making connections
504 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
505 $this->cmh = $cmh;
506 }
507
508 $curlVersion = curl_version()['version'];
509
510 // CURLMOPT_MAX_HOST_CONNECTIONS is available since PHP 7.0.7 and cURL 7.30.0
511 if ( version_compare( $curlVersion, '7.30.0', '>=' ) ) {
512 // Limit the number of in-flight requests for any given host
513 $maxHostConns = $opts['maxConnsPerHost'] ?? $this->maxConnsPerHost;
514 curl_multi_setopt( $this->cmh, CURLMOPT_MAX_HOST_CONNECTIONS, (int)$maxHostConns );
515 }
516
517 if ( $opts['usePipelining'] ?? $this->usePipelining ) {
518 if ( version_compare( $curlVersion, '7.43', '<' ) ) {
519 // The option is a boolean
520 $pipelining = 1;
521 } elseif ( version_compare( $curlVersion, '7.62', '<' ) ) {
522 // The option is a bitfield and HTTP/1.x pipelining is supported
523 $pipelining = CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX;
524 } else {
525 // The option is a bitfield but HTTP/1.x pipelining has been removed
526 $pipelining = CURLPIPE_MULTIPLEX;
527 }
528 // Suppress deprecation, we know already (T264735)
529 // phpcs:ignore Generic.PHP.NoSilencedErrors
530 @curl_multi_setopt( $this->cmh, CURLMOPT_PIPELINING, $pipelining );
531 }
532
533 return $this->cmh;
534 }
535
536 /**
537 * Get a time in seconds, formatted with microsecond resolution, or fall back to second
538 * resolution on PHP 7.2
539 *
540 * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
541 * @param resource|object $ch
542 * @param int $oldOption
543 * @param string $newConstName
544 * @return string
545 */
546 private function getCurlTime( $ch, $oldOption, $newConstName ): string {
547 if ( defined( $newConstName ) ) {
548 return sprintf( "%.6F", curl_getinfo( $ch, constant( $newConstName ) ) / 1e6 );
549 } else {
550 return (string)curl_getinfo( $ch, $oldOption );
551 }
552 }
553
554 /**
555 * Execute a set of HTTP(S) requests sequentially.
556 *
557 * @see MultiHttpClient::runMulti()
558 * @todo Remove dependency on MediaWikiServices: rewrite using Guzzle T202352
559 * @param array $reqs Map of HTTP request arrays
560 * @phpcs:ignore Generic.Files.LineLength
561 * @phan-param array<int,array{url:string,query:array,method:string,body:string,headers:array<string,string>,proxy?:?string}> $reqs
562 * @param array $opts
563 * - connTimeout : connection timeout per request (seconds)
564 * - reqTimeout : post-connection timeout per request (seconds)
565 * @phan-param array{connTimeout:int,reqTimeout:int} $opts
566 * @return array $reqs With response array populated for each
567 * @throws \Exception
568 */
569 private function runMultiHttp( array $reqs, array $opts = [] ) {
570 $httpOptions = [
571 'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
572 'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
573 'logger' => $this->logger,
574 'caInfo' => $this->caBundlePath,
575 ];
576 foreach ( $reqs as &$req ) {
577 $reqOptions = $httpOptions + [
578 'method' => $req['method'],
579 'proxy' => $req['proxy'] ?? $this->proxy,
580 'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
581 'postData' => $req['body'],
582 ];
583
584 $url = $req['url'];
585 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
586 if ( $query != '' ) {
587 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
588 }
589
590 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
591 $url, $reqOptions, __METHOD__ );
592 $httpRequest->setLogger( $this->logger );
593 foreach ( $req['headers'] as $header => $value ) {
594 $httpRequest->setHeader( $header, $value );
595 }
596 $sv = $httpRequest->execute()->getStatusValue();
597
598 $respHeaders = array_map(
599 static function ( $v ) {
600 return implode( ', ', $v );
601 },
602 $httpRequest->getResponseHeaders() );
603
604 $req['response'] = [
605 'code' => $httpRequest->getStatus(),
606 'reason' => '',
607 'headers' => $respHeaders,
608 'body' => $httpRequest->getContent(),
609 'error' => '',
610 ];
611
612 if ( !$sv->isOK() ) {
613 $svErrors = $sv->getErrors();
614 if ( isset( $svErrors[0] ) ) {
615 $req['response']['error'] = $svErrors[0]['message'];
616
617 // param values vary per failure type (ex. unknown host vs unknown page)
618 if ( isset( $svErrors[0]['params'][0] ) ) {
619 if ( is_numeric( $svErrors[0]['params'][0] ) ) {
620 if ( isset( $svErrors[0]['params'][1] ) ) {
621 // @phan-suppress-next-line PhanTypeInvalidDimOffset
622 $req['response']['reason'] = $svErrors[0]['params'][1];
623 }
624 } else {
625 $req['response']['reason'] = $svErrors[0]['params'][0];
626 }
627 }
628 }
629 }
630
631 $req['response'][0] = $req['response']['code'];
632 $req['response'][1] = $req['response']['reason'];
633 $req['response'][2] = $req['response']['headers'];
634 $req['response'][3] = $req['response']['body'];
635 $req['response'][4] = $req['response']['error'];
636 }
637
638 return $reqs;
639 }
640
641 /**
642 * Normalize headers array
643 * @param array $headers
644 * @return array
645 */
646 private function normalizeHeaders( array $headers ): array {
647 $normalized = [];
648 foreach ( $headers as $name => $value ) {
649 $normalized[strtolower( $name )] = $value;
650 }
651 return $normalized;
652 }
653
654 /**
655 * Normalize request information
656 *
657 * @param array[] &$reqs the requests to normalize
658 */
659 private function normalizeRequests( array &$reqs ) {
660 foreach ( $reqs as &$req ) {
661 $req['response'] = [
662 'code' => 0,
663 'reason' => '',
664 'headers' => [],
665 'body' => '',
666 'error' => ''
667 ];
668 if ( isset( $req[0] ) ) {
669 $req['method'] = $req[0]; // short-form
670 unset( $req[0] );
671 }
672 if ( isset( $req[1] ) ) {
673 $req['url'] = $req[1]; // short-form
674 unset( $req[1] );
675 }
676 if ( !isset( $req['method'] ) ) {
677 throw new InvalidArgumentException( "Request has no 'method' field set." );
678 } elseif ( !isset( $req['url'] ) ) {
679 throw new InvalidArgumentException( "Request has no 'url' field set." );
680 }
681 if ( $this->localProxy !== false && $this->isLocalURL( $req['url'] ) ) {
682 $this->useReverseProxy( $req, $this->localProxy );
683 }
684 $req['query'] ??= [];
685 $req['headers'] = $this->normalizeHeaders(
686 array_merge(
687 $this->headers,
688 $this->telemetry ? $this->telemetry->getRequestHeaders() : [],
689 $req['headers'] ?? []
690 )
691 );
692
693 if ( !isset( $req['body'] ) ) {
694 $req['body'] = '';
695 $req['headers']['content-length'] = 0;
696 }
697 // Redact some headers we know to have tokens before logging them
698 $logHeaders = $req['headers'];
699 foreach ( $logHeaders as $header => $value ) {
700 if ( preg_match( self::SENSITIVE_HEADERS, $header ) === 1 ) {
701 $logHeaders[$header] = '[redacted]';
702 }
703 }
704 $this->logger->debug( "HTTP start: {method} {url}",
705 [
706 'method' => $req['method'],
707 'url' => $req['url'],
708 'headers' => $logHeaders,
709 ]
710 );
711 $req['flags'] ??= [];
712 }
713 }
714
715 private function useReverseProxy( array &$req, $proxy ) {
716 $parsedProxy = parse_url( $proxy );
717 if ( $parsedProxy === false ) {
718 throw new InvalidArgumentException( "Invalid reverseProxy configured: $proxy" );
719 }
720 $parsedUrl = parse_url( $req['url'] );
721 if ( $parsedUrl === false ) {
722 throw new InvalidArgumentException( "Invalid url specified: {$req['url']}" );
723 }
724 // Set the current host in the Host header
725 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
726 $req['headers']['Host'] = $parsedUrl['host'];
727 // Replace scheme, host and port in the request
728 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
729 $parsedUrl['scheme'] = $parsedProxy['scheme'];
730 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
731 $parsedUrl['host'] = $parsedProxy['host'];
732 if ( isset( $parsedProxy['port'] ) ) {
733 $parsedUrl['port'] = $parsedProxy['port'];
734 } else {
735 unset( $parsedUrl['port'] );
736 }
737 $req['url'] = self::assembleUrl( $parsedUrl );
738 // Explicitly disable use of another proxy by setting to false,
739 // since null will fallback to $this->proxy
740 $req['proxy'] = false;
741 }
742
743 /**
744 * This is derived from MediaWiki\Utils\UrlUtils::assemble but changed to work
745 * with parse_url's result so the delimiter is hardcoded.
746 *
747 * The basic structure used:
748 * [scheme://][[user][:pass]@][host][:port][path][?query][#fragment]
749 *
750 * @param array $urlParts URL parts, as output from parse_url()
751 * @return string URL assembled from its component parts
752 */
753 private static function assembleUrl( array $urlParts ): string {
754 $result = isset( $urlParts['scheme'] ) ? $urlParts['scheme'] . '://' : '';
755
756 if ( isset( $urlParts['host'] ) ) {
757 if ( isset( $urlParts['user'] ) ) {
758 $result .= $urlParts['user'];
759 if ( isset( $urlParts['pass'] ) ) {
760 $result .= ':' . $urlParts['pass'];
761 }
762 $result .= '@';
763 }
764
765 $result .= $urlParts['host'];
766
767 if ( isset( $urlParts['port'] ) ) {
768 $result .= ':' . $urlParts['port'];
769 }
770 }
771
772 if ( isset( $urlParts['path'] ) ) {
773 $result .= $urlParts['path'];
774 }
775
776 if ( isset( $urlParts['query'] ) && $urlParts['query'] !== '' ) {
777 $result .= '?' . $urlParts['query'];
778 }
779
780 if ( isset( $urlParts['fragment'] ) ) {
781 $result .= '#' . $urlParts['fragment'];
782 }
783
784 return $result;
785 }
786
787 /**
788 * Check if the URL can be served by localhost
789 *
790 * @note this is mostly a copy of MWHttpRequest::isLocalURL()
791 * @param string $url Full url to check
792 * @return bool
793 */
794 private function isLocalURL( $url ) {
795 if ( !$this->localVirtualHosts ) {
796 // Shortcut
797 return false;
798 }
799
800 // Extract host part
801 $matches = [];
802 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
803 $host = $matches[1];
804 // Split up dotwise
805 $domainParts = explode( '.', $host );
806 // Check if this domain or any superdomain is listed as a local virtual host
807 $domainParts = array_reverse( $domainParts );
808
809 $domain = '';
810 $countParts = count( $domainParts );
811 for ( $i = 0; $i < $countParts; $i++ ) {
812 $domainPart = $domainParts[$i];
813 if ( $i == 0 ) {
814 $domain = $domainPart;
815 } else {
816 $domain = $domainPart . '.' . $domain;
817 }
818
819 if ( in_array( $domain, $this->localVirtualHosts ) ) {
820 return true;
821 }
822 }
823 }
824
825 return false;
826 }
827
828 /**
829 * Get a suitable select timeout for the given options.
830 *
831 * @param array $opts
832 * @return float
833 */
834 private function getSelectTimeout( $opts ) {
835 $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
836 $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
837 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
838 if ( count( $timeouts ) === 0 ) {
839 return 1;
840 }
841
842 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
843 // Minimum 10us
844 if ( $selectTimeout < 10e-6 ) {
845 $selectTimeout = 10e-6;
846 }
847 return $selectTimeout;
848 }
849
850 /**
851 * Register a logger
852 *
853 * @param LoggerInterface $logger
854 */
855 public function setLogger( LoggerInterface $logger ) {
856 $this->logger = $logger;
857 }
858
859 public function __destruct() {
860 if ( $this->cmh ) {
861 curl_multi_close( $this->cmh );
862 $this->cmh = null;
863 }
864 }
865
866 }
867 /** @deprecated class alias since 1.43 */
868 class_alias( MultiHttpClient::class, 'MultiHttpClient' );