Debian Codegraph @

includes/http/MWHttpRequest.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use MediaWiki\MainConfigNames;
22 use MediaWiki\MediaWikiServices;
23 use MediaWiki\Request\WebRequest;
24 use MediaWiki\Status\Status;
25 use MediaWiki\Utils\UrlUtils;
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28 use Psr\Log\NullLogger;
29 use Wikimedia\Http\TelemetryHeadersInterface;
30
31 /**
32 * This wrapper class will call out to curl (if available) or fallback
33 * to regular PHP if necessary for handling internal HTTP requests.
34 *
35 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
36 * PHP's HTTP extension.
37 */
38 abstract class MWHttpRequest implements LoggerAwareInterface {
39 public const SUPPORTS_FILE_POSTS = false;
40
41 /**
42 * @var int|string
43 */
44 protected $timeout = 'default';
45
46 /** @var string|null */
47 protected $content;
48 /** @var bool|null */
49 protected $headersOnly = null;
50 /** @var array|null */
51 protected $postData = null;
52 /** @var string|null */
53 protected $proxy = null;
54 /** @var bool */
55 protected $noProxy = false;
56 /** @var bool */
57 protected $sslVerifyHost = true;
58 /** @var bool */
59 protected $sslVerifyCert = true;
60 /** @var string|null */
61 protected $caInfo = null;
62 /** @var string */
63 protected $method = "GET";
64 /** @var array */
65 protected $reqHeaders = [];
66 /** @var string */
67 protected $url;
68 /** @var array|false */
69 protected $parsedUrl;
70 /** @var callable */
71 protected $callback;
72 /** @var int */
73 protected $maxRedirects = 5;
74 /** @var bool */
75 protected $followRedirects = false;
76 /** @var int */
77 protected $connectTimeout;
78
79 /**
80 * @var CookieJar
81 */
82 protected $cookieJar;
83
84 /** @var array */
85 protected $headerList = [];
86 /** @var string */
87 protected $respVersion = "0.9";
88 /** @var string */
89 protected $respStatus = "200 Ok";
90 /** @var string[][] */
91 protected $respHeaders = [];
92
93 /** @var StatusValue */
94 protected $status;
95
96 /**
97 * @var Profiler
98 */
99 protected $profiler;
100
101 /**
102 * @var string
103 */
104 protected $profileName;
105
106 /**
107 * @var LoggerInterface
108 */
109 protected $logger;
110
111 private UrlUtils $urlUtils;
112
113 /**
114 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
115 * @param array $options extra params to pass (see HttpRequestFactory::create())
116 * @phpcs:ignore Generic.Files.LineLength
117 * @phan-param array{timeout?:int|string,connectTimeout?:int|string,postData?:array,proxy?:string,noProxy?:bool,sslVerifyHost?:bool,sslVerifyCert?:bool,caInfo?:string,maxRedirects?:int,followRedirects?:bool,userAgent?:string,logger?:LoggerInterface,username?:string,password?:string,originalRequest?:WebRequest|array{ip:string,userAgent:string},method?:string} $options
118 * @param string $caller The method making this request, for profiling @phan-mandatory-param
119 * @param Profiler|null $profiler An instance of the profiler for profiling, or null
120 * @throws Exception
121 */
122 public function __construct(
123 $url, array $options, $caller = __METHOD__, ?Profiler $profiler = null
124 ) {
125 $this->urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
126 if ( !array_key_exists( 'timeout', $options )
127 || !array_key_exists( 'connectTimeout', $options ) ) {
128 throw new InvalidArgumentException( "timeout and connectionTimeout options are required" );
129 }
130 $this->url = $this->urlUtils->expand( $url, PROTO_HTTP ) ?? false;
131 $this->parsedUrl = $this->urlUtils->parse( (string)$this->url ) ?? false;
132
133 $this->logger = $options['logger'] ?? new NullLogger();
134 $this->timeout = $options['timeout'];
135 $this->connectTimeout = $options['connectTimeout'];
136
137 if ( !$this->parsedUrl || !self::isValidURI( $this->url ) ) {
138 $this->status = StatusValue::newFatal( 'http-invalid-url', $url );
139 } else {
140 $this->status = StatusValue::newGood( 100 ); // continue
141 }
142
143 if ( isset( $options['userAgent'] ) ) {
144 $this->setUserAgent( $options['userAgent'] );
145 }
146 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
147 $this->setHeader(
148 'Authorization',
149 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
150 );
151 }
152 if ( isset( $options['originalRequest'] ) ) {
153 $this->setOriginalRequest( $options['originalRequest'] );
154 }
155
156 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
157 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
158
159 foreach ( $members as $o ) {
160 if ( isset( $options[$o] ) ) {
161 // ensure that MWHttpRequest::method is always
162 // uppercased. T38137
163 if ( $o == 'method' ) {
164 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
165 $options[$o] = strtoupper( $options[$o] );
166 }
167 $this->$o = $options[$o];
168 }
169 }
170
171 if ( $this->noProxy ) {
172 $this->proxy = ''; // noProxy takes precedence
173 }
174
175 // Profile based on what's calling us
176 $this->profiler = $profiler;
177 $this->profileName = $caller;
178 }
179
180 /**
181 * @param LoggerInterface $logger
182 */
183 public function setLogger( LoggerInterface $logger ) {
184 $this->logger = $logger;
185 }
186
187 /**
188 * Simple function to test if we can make any sort of requests at all, using
189 * cURL or fopen()
190 * @return bool
191 */
192 public static function canMakeRequests() {
193 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
194 }
195
196 /**
197 * Get the body, or content, of the response to the request
198 *
199 * @return string
200 */
201 public function getContent() {
202 return $this->content;
203 }
204
205 /**
206 * Set the parameters of the request
207 *
208 * @param array $args
209 * @todo overload the args param
210 */
211 public function setData( array $args ) {
212 $this->postData = $args;
213 }
214
215 /**
216 * Add Telemetry information to the request
217 *
218 * @param TelemetryHeadersInterface $telemetry
219 * @return void
220 */
221 public function addTelemetry( TelemetryHeadersInterface $telemetry ): void {
222 foreach ( $telemetry->getRequestHeaders() as $header => $value ) {
223 $this->setHeader( $header, $value );
224 }
225 }
226
227 /**
228 * Take care of setting up the proxy (do nothing if "noProxy" is set)
229 *
230 * @return void
231 */
232 protected function proxySetup() {
233 $httpProxy = MediaWikiServices::getInstance()->getMainConfig()->get(
234 MainConfigNames::HTTPProxy );
235 $localHTTPProxy = MediaWikiServices::getInstance()->getMainConfig()->get(
236 MainConfigNames::LocalHTTPProxy );
237 // If proxies are disabled, clear any other proxy
238 if ( $this->noProxy ) {
239 $this->proxy = '';
240 return;
241 }
242
243 // If there is an explicit proxy already set, use it
244 if ( $this->proxy ) {
245 return;
246 }
247
248 // Otherwise, fallback to $wgLocalHTTPProxy for local URLs
249 // or $wgHTTPProxy for everything else
250 if ( self::isLocalURL( $this->url ) ) {
251 if ( $localHTTPProxy !== false ) {
252 $this->setReverseProxy( $localHTTPProxy );
253 }
254 } else {
255 $this->proxy = (string)$httpProxy;
256 }
257 }
258
259 /**
260 * Enable use of a reverse proxy in which the hostname is
261 * passed as a "Host" header, and the request is sent to the
262 * proxy's host:port instead.
263 *
264 * Note that any custom port in the request URL will be lost
265 * and cookies and redirects may not work properly.
266 *
267 * @param string $proxy URL of proxy
268 */
269 protected function setReverseProxy( string $proxy ) {
270 $parsedProxy = $this->urlUtils->parse( $proxy );
271 if ( $parsedProxy === null ) {
272 throw new InvalidArgumentException( "Invalid reverseProxy configured: $proxy" );
273 }
274 // Set the current host in the Host header
275 $this->setHeader( 'Host', $this->parsedUrl['host'] );
276 // Replace scheme, host and port in the request
277 $this->parsedUrl['scheme'] = $parsedProxy['scheme'];
278 $this->parsedUrl['host'] = $parsedProxy['host'];
279 if ( isset( $parsedProxy['port'] ) ) {
280 $this->parsedUrl['port'] = $parsedProxy['port'];
281 } else {
282 unset( $this->parsedUrl['port'] );
283 }
284 $this->url = UrlUtils::assemble( $this->parsedUrl );
285 // Mark that we're already using a proxy
286 $this->noProxy = true;
287 }
288
289 /**
290 * Check if the URL can be served by localhost
291 *
292 * @param string $url Full url to check
293 * @return bool
294 */
295 private static function isLocalURL( $url ) {
296 if ( MW_ENTRY_POINT === 'cli' ) {
297 return false;
298 }
299 $localVirtualHosts = MediaWikiServices::getInstance()->getMainConfig()->get(
300 MainConfigNames::LocalVirtualHosts );
301
302 // Extract host part
303 $matches = [];
304 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
305 $host = $matches[1];
306 // Split up dotwise
307 $domainParts = explode( '.', $host );
308 // Check if this domain or any superdomain is listed as a local virtual host
309 $domainParts = array_reverse( $domainParts );
310
311 $domain = '';
312 $countParts = count( $domainParts );
313 for ( $i = 0; $i < $countParts; $i++ ) {
314 $domainPart = $domainParts[$i];
315 if ( $i == 0 ) {
316 $domain = $domainPart;
317 } else {
318 $domain = $domainPart . '.' . $domain;
319 }
320
321 if ( in_array( $domain, $localVirtualHosts ) ) {
322 return true;
323 }
324 }
325 }
326
327 return false;
328 }
329
330 /**
331 * @param string $UA
332 */
333 public function setUserAgent( $UA ) {
334 $this->setHeader( 'User-Agent', $UA );
335 }
336
337 /**
338 * Set an arbitrary header
339 * @param string $name
340 * @param string $value
341 */
342 public function setHeader( $name, $value ) {
343 // I feel like I should normalize the case here...
344 $this->reqHeaders[$name] = $value;
345 }
346
347 /**
348 * Get an array of the headers
349 * @return array
350 */
351 protected function getHeaderList() {
352 $list = [];
353
354 if ( $this->cookieJar ) {
355 $this->reqHeaders['Cookie'] =
356 $this->cookieJar->serializeToHttpRequest(
357 $this->parsedUrl['path'],
358 $this->parsedUrl['host']
359 );
360 }
361
362 foreach ( $this->reqHeaders as $name => $value ) {
363 $list[] = "$name: $value";
364 }
365
366 return $list;
367 }
368
369 /**
370 * Set a read callback to accept data read from the HTTP request.
371 * By default, data is appended to an internal buffer which can be
372 * retrieved through $req->getContent().
373 *
374 * To handle data as it comes in -- especially for large files that
375 * would not fit in memory -- you can instead set your own callback,
376 * in the form function($resource, $buffer) where the first parameter
377 * is the low-level resource being read (implementation specific),
378 * and the second parameter is the data buffer.
379 *
380 * You MUST return the number of bytes handled in the buffer; if fewer
381 * bytes are reported handled than were passed to you, the HTTP fetch
382 * will be aborted.
383 *
384 * @param callable|null $callback
385 * @throws InvalidArgumentException
386 */
387 public function setCallback( $callback ) {
388 $this->doSetCallback( $callback );
389 }
390
391 /**
392 * Worker function for setting callbacks. Calls can originate both internally and externally
393 * via setCallback). Defaults to the internal read callback if $callback is null.
394 *
395 * @param callable|null $callback
396 * @throws InvalidArgumentException
397 */
398 protected function doSetCallback( $callback ) {
399 if ( $callback === null ) {
400 $callback = [ $this, 'read' ];
401 } elseif ( !is_callable( $callback ) ) {
402 $this->status->fatal( 'http-internal-error' );
403 throw new InvalidArgumentException( __METHOD__ . ': invalid callback' );
404 }
405 $this->callback = $callback;
406 }
407
408 /**
409 * A generic callback to read the body of the response from a remote
410 * server.
411 *
412 * @param resource $fh
413 * @param string $content
414 * @return int
415 * @internal
416 */
417 public function read( $fh, $content ) {
418 $this->content .= $content;
419 return strlen( $content );
420 }
421
422 /**
423 * Take care of whatever is necessary to perform the URI request.
424 *
425 * @return Status
426 * @note currently returns Status for B/C
427 */
428 public function execute() {
429 throw new LogicException( 'children must override this' );
430 }
431
432 protected function prepare() {
433 $this->content = "";
434
435 if ( strtoupper( $this->method ) == "HEAD" ) {
436 $this->headersOnly = true;
437 }
438
439 $this->proxySetup(); // set up any proxy as needed
440
441 if ( !$this->callback ) {
442 $this->doSetCallback( null );
443 }
444
445 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
446 $http = MediaWikiServices::getInstance()->getHttpRequestFactory();
447 $this->setUserAgent( $http->getUserAgent() );
448 }
449 }
450
451 /**
452 * Parses the headers, including the HTTP status code and any
453 * Set-Cookie headers. This function expects the headers to be
454 * found in an array in the member variable headerList.
455 */
456 protected function parseHeader() {
457 $lastname = "";
458
459 // Failure without (valid) headers gets a response status of zero
460 if ( !$this->status->isOK() ) {
461 $this->respStatus = '0 Error';
462 }
463
464 foreach ( $this->headerList as $header ) {
465 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
466 $this->respVersion = $match[1];
467 $this->respStatus = $match[2];
468 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
469 $last = count( $this->respHeaders[$lastname] ) - 1;
470 $this->respHeaders[$lastname][$last] .= "\r\n$header";
471 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
472 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
473 $lastname = strtolower( $match[1] );
474 }
475 }
476
477 $this->parseCookies();
478 }
479
480 /**
481 * Sets HTTPRequest status member to a fatal value with the error
482 * message if the returned integer value of the status code was
483 * not successful (1-299) or a redirect (300-399).
484 * See RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
485 * for a list of status codes.
486 */
487 protected function setStatus() {
488 if ( !$this->respHeaders ) {
489 $this->parseHeader();
490 }
491
492 if ( (int)$this->respStatus > 0 && (int)$this->respStatus < 400 ) {
493 $this->status->setResult( true, (int)$this->respStatus );
494 } else {
495 [ $code, $message ] = explode( " ", $this->respStatus, 2 );
496 $this->status->setResult( false, (int)$this->respStatus );
497 $this->status->fatal( "http-bad-status", $code, $message );
498 }
499 }
500
501 /**
502 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
503 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
504 * for a list of status codes.)
505 *
506 * @return int
507 */
508 public function getStatus() {
509 if ( !$this->respHeaders ) {
510 $this->parseHeader();
511 }
512
513 return (int)$this->respStatus;
514 }
515
516 /**
517 * Returns true if the last status code was a redirect.
518 *
519 * @return bool
520 */
521 public function isRedirect() {
522 if ( !$this->respHeaders ) {
523 $this->parseHeader();
524 }
525
526 $status = (int)$this->respStatus;
527
528 if ( $status >= 300 && $status <= 303 ) {
529 return true;
530 }
531
532 return false;
533 }
534
535 /**
536 * Returns an associative array of response headers after the
537 * request has been executed. Because some headers
538 * (e.g. Set-Cookie) can appear more than once the, each value of
539 * the associative array is an array of the values given.
540 * Header names are always in lowercase.
541 *
542 * @return array
543 */
544 public function getResponseHeaders() {
545 if ( !$this->respHeaders ) {
546 $this->parseHeader();
547 }
548
549 return $this->respHeaders;
550 }
551
552 /**
553 * Returns the value of the given response header.
554 *
555 * @param string $header case-insensitive
556 * @return string|null
557 */
558 public function getResponseHeader( $header ) {
559 if ( !$this->respHeaders ) {
560 $this->parseHeader();
561 }
562
563 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
564 $v = $this->respHeaders[strtolower( $header )];
565 return $v[count( $v ) - 1];
566 }
567
568 return null;
569 }
570
571 /**
572 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
573 *
574 * To read response cookies from the jar, getCookieJar must be called first.
575 *
576 * @param CookieJar $jar
577 */
578 public function setCookieJar( CookieJar $jar ) {
579 $this->cookieJar = $jar;
580 }
581
582 /**
583 * Returns the cookie jar in use.
584 *
585 * @return CookieJar
586 */
587 public function getCookieJar() {
588 if ( !$this->respHeaders ) {
589 $this->parseHeader();
590 }
591
592 return $this->cookieJar;
593 }
594
595 /**
596 * Sets a cookie. Used before a request to set up any individual
597 * cookies. Used internally after a request to parse the
598 * Set-Cookie headers.
599 * @see Cookie::set
600 * @param string $name
601 * @param string $value
602 * @param array $attr
603 */
604 public function setCookie( $name, $value, array $attr = [] ) {
605 if ( !$this->cookieJar ) {
606 $this->cookieJar = new CookieJar;
607 }
608
609 if ( $this->parsedUrl && !isset( $attr['domain'] ) ) {
610 $attr['domain'] = $this->parsedUrl['host'];
611 }
612
613 $this->cookieJar->setCookie( $name, $value, $attr );
614 }
615
616 /**
617 * Parse the cookies in the response headers and store them in the cookie jar.
618 */
619 protected function parseCookies() {
620 if ( !$this->cookieJar ) {
621 $this->cookieJar = new CookieJar;
622 }
623
624 if ( isset( $this->respHeaders['set-cookie'] ) ) {
625 $url = parse_url( $this->getFinalUrl() );
626 if ( !isset( $url['host'] ) ) {
627 $this->status->fatal( 'http-invalid-url', $url );
628 } else {
629 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
630 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
631 }
632 }
633 }
634 }
635
636 /**
637 * Returns the final URL after all redirections.
638 *
639 * Relative values of the "Location" header are incorrect as
640 * stated in RFC, however they do happen and modern browsers
641 * support them. This function loops backwards through all
642 * locations in order to build the proper absolute URI - Marooned
643 * at wikia-inc.com
644 *
645 * Note that the multiple Location: headers are an artifact of
646 * CURL -- they shouldn't actually get returned this way. Rewrite
647 * this when T31232 is taken care of (high-level redirect
648 * handling rewrite).
649 *
650 * @return string
651 */
652 public function getFinalUrl() {
653 $headers = $this->getResponseHeaders();
654
655 // return full url (fix for incorrect but handled relative location)
656 if ( isset( $headers['location'] ) ) {
657 $locations = $headers['location'];
658 $domain = '';
659 $foundRelativeURI = false;
660 $countLocations = count( $locations );
661
662 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
663 $url = parse_url( $locations[$i] );
664
665 if ( isset( $url['scheme'] ) && isset( $url['host'] ) ) {
666 $domain = $url['scheme'] . '://' . $url['host'];
667 break; // found correct URI (with host)
668 } else {
669 $foundRelativeURI = true;
670 }
671 }
672
673 if ( !$foundRelativeURI ) {
674 return $locations[$countLocations - 1];
675 }
676 if ( $domain ) {
677 return $domain . $locations[$countLocations - 1];
678 }
679 $url = parse_url( $this->url );
680 if ( isset( $url['scheme'] ) && isset( $url['host'] ) ) {
681 return $url['scheme'] . '://' . $url['host'] .
682 $locations[$countLocations - 1];
683 }
684 }
685
686 return $this->url;
687 }
688
689 /**
690 * Returns true if the backend can follow redirects. Overridden by the
691 * child classes.
692 * @return bool
693 */
694 public function canFollowRedirects() {
695 return true;
696 }
697
698 /**
699 * Set information about the original request. This can be useful for
700 * endpoints/API modules which act as a proxy for some service, and
701 * throttling etc. needs to happen in that service.
702 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
703 * headers being set.
704 * @param WebRequest|array $originalRequest When in array form, it's
705 * expected to have the keys 'ip' and 'userAgent'.
706 * @note IP/user agent is personally identifiable information, and should
707 * only be set when the privacy policy of the request target is
708 * compatible with that of the MediaWiki installation.
709 */
710 public function setOriginalRequest( $originalRequest ) {
711 if ( $originalRequest instanceof WebRequest ) {
712 $originalRequest = [
713 'ip' => $originalRequest->getIP(),
714 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
715 ];
716 } elseif (
717 !is_array( $originalRequest )
718 || array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
719 ) {
720 throw new InvalidArgumentException( __METHOD__ . ': $originalRequest must be a '
721 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
722 }
723
724 $this->reqHeaders['X-Forwarded-For'] = $originalRequest['ip'];
725 $this->reqHeaders['X-Original-User-Agent'] = $originalRequest['userAgent'];
726 }
727
728 /**
729 * Check that the given URI is a valid one.
730 *
731 * This hardcodes a small set of protocols only, because we want to
732 * deterministically reject protocols not supported by all HTTP-transport
733 * methods.
734 *
735 * "file://" specifically must not be allowed, for security reasons
736 * (see <https://www.mediawiki.org/wiki/Special:Code/MediaWiki/r67684>).
737 *
738 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
739 *
740 * @since 1.34
741 * @param string $uri URI to check for validity
742 * @return bool
743 */
744 public static function isValidURI( $uri ) {
745 return (bool)preg_match(
746 '/^https?:\/\/[^\/\s]\S*$/D',
747 $uri
748 );
749 }
750 }