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.
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.
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
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
;
32 * This wrapper class will call out to curl (if available) or fallback
33 * to regular PHP if necessary for handling internal HTTP requests.
35 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
36 * PHP's HTTP extension.
38 abstract class MWHttpRequest
implements LoggerAwareInterface
{
39 public const SUPPORTS_FILE_POSTS
= false;
44 protected $timeout = 'default';
46 /** @var string|null */
49 protected $headersOnly = null;
50 /** @var array|null */
51 protected $postData = null;
52 /** @var string|null */
53 protected $proxy = null;
55 protected $noProxy = false;
57 protected $sslVerifyHost = true;
59 protected $sslVerifyCert = true;
60 /** @var string|null */
61 protected $caInfo = null;
63 protected $method = "GET";
65 protected $reqHeaders = [];
68 /** @var array|false */
73 protected $maxRedirects = 5;
75 protected $followRedirects = false;
77 protected $connectTimeout;
85 protected $headerList = [];
87 protected $respVersion = "0.9";
89 protected $respStatus = "200 Ok";
90 /** @var string[][] */
91 protected $respHeaders = [];
93 /** @var StatusValue */
104 protected $profileName;
107 * @var LoggerInterface
111 private UrlUtils
$urlUtils;
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
122 public function __construct(
123 $url, array $options, $caller = __METHOD__
, ?Profiler
$profiler = null
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" );
130 $this->url
= $this->urlUtils
->expand( $url, PROTO_HTTP
) ??
false;
131 $this->parsedUrl
= $this->urlUtils
->parse( (string)$this->url
) ??
false;
133 $this->logger
= $options['logger'] ??
new NullLogger();
134 $this->timeout
= $options['timeout'];
135 $this->connectTimeout
= $options['connectTimeout'];
137 if ( !$this->parsedUrl ||
!self
::isValidURI( $this->url
) ) {
138 $this->status
= StatusValue
::newFatal( 'http-invalid-url', $url );
140 $this->status
= StatusValue
::newGood( 100 ); // continue
143 if ( isset( $options['userAgent'] ) ) {
144 $this->setUserAgent( $options['userAgent'] );
146 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
149 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
152 if ( isset( $options['originalRequest'] ) ) {
153 $this->setOriginalRequest( $options['originalRequest'] );
156 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
157 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
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] );
167 $this->$o = $options[$o];
171 if ( $this->noProxy
) {
172 $this->proxy
= ''; // noProxy takes precedence
175 // Profile based on what's calling us
176 $this->profiler
= $profiler;
177 $this->profileName
= $caller;
181 * @param LoggerInterface $logger
183 public function setLogger( LoggerInterface
$logger ) {
184 $this->logger
= $logger;
188 * Simple function to test if we can make any sort of requests at all, using
192 public static function canMakeRequests() {
193 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
197 * Get the body, or content, of the response to the request
201 public function getContent() {
202 return $this->content
;
206 * Set the parameters of the request
209 * @todo overload the args param
211 public function setData( array $args ) {
212 $this->postData
= $args;
216 * Add Telemetry information to the request
218 * @param TelemetryHeadersInterface $telemetry
221 public function addTelemetry( TelemetryHeadersInterface
$telemetry ): void
{
222 foreach ( $telemetry->getRequestHeaders() as $header => $value ) {
223 $this->setHeader( $header, $value );
228 * Take care of setting up the proxy (do nothing if "noProxy" is set)
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
) {
243 // If there is an explicit proxy already set, use it
244 if ( $this->proxy
) {
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 );
255 $this->proxy
= (string)$httpProxy;
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.
264 * Note that any custom port in the request URL will be lost
265 * and cookies and redirects may not work properly.
267 * @param string $proxy URL of proxy
269 protected function setReverseProxy( string $proxy ) {
270 $parsedProxy = $this->urlUtils
->parse( $proxy );
271 if ( $parsedProxy === null ) {
272 throw new InvalidArgumentException( "Invalid reverseProxy configured: $proxy" );
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'];
282 unset( $this->parsedUrl
['port'] );
284 $this->url
= UrlUtils
::assemble( $this->parsedUrl
);
285 // Mark that we're already using a proxy
286 $this->noProxy
= true;
290 * Check if the URL can be served by a local endpoint
292 * @param string $url Full url to check
295 private static function isLocalURL( $url ) {
296 $localVirtualHosts = MediaWikiServices
::getInstance()->getMainConfig()->get(
297 MainConfigNames
::LocalVirtualHosts
);
301 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
304 $domainParts = explode( '.', $host );
305 // Check if this domain or any superdomain is listed as a local virtual host
306 $domainParts = array_reverse( $domainParts );
309 $countParts = count( $domainParts );
310 for ( $i = 0; $i < $countParts; $i++
) {
311 $domainPart = $domainParts[$i];
313 $domain = $domainPart;
315 $domain = $domainPart . '.' . $domain;
318 if ( in_array( $domain, $localVirtualHosts ) ) {
330 public function setUserAgent( $UA ) {
331 $this->setHeader( 'User-Agent', $UA );
335 * Set an arbitrary header
336 * @param string $name
337 * @param string $value
339 public function setHeader( $name, $value ) {
340 // I feel like I should normalize the case here...
341 $this->reqHeaders
[$name] = $value;
345 * Get an array of the headers
348 protected function getHeaderList() {
351 if ( $this->cookieJar
) {
352 $this->reqHeaders
['Cookie'] =
353 $this->cookieJar
->serializeToHttpRequest(
354 $this->parsedUrl
['path'],
355 $this->parsedUrl
['host']
359 foreach ( $this->reqHeaders
as $name => $value ) {
360 $list[] = "$name: $value";
367 * Set a read callback to accept data read from the HTTP request.
368 * By default, data is appended to an internal buffer which can be
369 * retrieved through $req->getContent().
371 * To handle data as it comes in -- especially for large files that
372 * would not fit in memory -- you can instead set your own callback,
373 * in the form function($resource, $buffer) where the first parameter
374 * is the low-level resource being read (implementation specific),
375 * and the second parameter is the data buffer.
377 * You MUST return the number of bytes handled in the buffer; if fewer
378 * bytes are reported handled than were passed to you, the HTTP fetch
381 * @param callable|null $callback
382 * @throws InvalidArgumentException
384 public function setCallback( $callback ) {
385 $this->doSetCallback( $callback );
389 * Worker function for setting callbacks. Calls can originate both internally and externally
390 * via setCallback). Defaults to the internal read callback if $callback is null.
392 * @param callable|null $callback
393 * @throws InvalidArgumentException
395 protected function doSetCallback( $callback ) {
396 if ( $callback === null ) {
397 $callback = [ $this, 'read' ];
398 } elseif ( !is_callable( $callback ) ) {
399 $this->status
->fatal( 'http-internal-error' );
400 throw new InvalidArgumentException( __METHOD__
. ': invalid callback' );
402 $this->callback
= $callback;
406 * A generic callback to read the body of the response from a remote
409 * @param resource $fh
410 * @param string $content
414 public function read( $fh, $content ) {
415 $this->content
.= $content;
416 return strlen( $content );
420 * Take care of whatever is necessary to perform the URI request.
423 * @note currently returns Status for B/C
425 public function execute() {
426 throw new LogicException( 'children must override this' );
429 protected function prepare() {
432 if ( strtoupper( $this->method
) == "HEAD" ) {
433 $this->headersOnly
= true;
436 $this->proxySetup(); // set up any proxy as needed
438 if ( !$this->callback
) {
439 $this->doSetCallback( null );
442 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
443 $http = MediaWikiServices
::getInstance()->getHttpRequestFactory();
444 $this->setUserAgent( $http->getUserAgent() );
449 * Parses the headers, including the HTTP status code and any
450 * Set-Cookie headers. This function expects the headers to be
451 * found in an array in the member variable headerList.
453 protected function parseHeader() {
456 // Failure without (valid) headers gets a response status of zero
457 if ( !$this->status
->isOK() ) {
458 $this->respStatus
= '0 Error';
461 foreach ( $this->headerList
as $header ) {
462 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
463 $this->respVersion
= $match[1];
464 $this->respStatus
= $match[2];
465 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
466 $last = count( $this->respHeaders
[$lastname] ) - 1;
467 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
468 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
469 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
470 $lastname = strtolower( $match[1] );
474 $this->parseCookies();
478 * Sets HTTPRequest status member to a fatal value with the error
479 * message if the returned integer value of the status code was
480 * not successful (1-299) or a redirect (300-399).
481 * See RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
482 * for a list of status codes.
484 protected function setStatus() {
485 if ( !$this->respHeaders
) {
486 $this->parseHeader();
489 if ( (int)$this->respStatus
> 0 && (int)$this->respStatus
< 400 ) {
490 $this->status
->setResult( true, (int)$this->respStatus
);
492 [ $code, $message ] = explode( " ", $this->respStatus
, 2 );
493 $this->status
->setResult( false, (int)$this->respStatus
);
494 $this->status
->fatal( "http-bad-status", $code, $message );
499 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
500 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
501 * for a list of status codes.)
505 public function getStatus() {
506 if ( !$this->respHeaders
) {
507 $this->parseHeader();
510 return (int)$this->respStatus
;
514 * Returns true if the last status code was a redirect.
518 public function isRedirect() {
519 if ( !$this->respHeaders
) {
520 $this->parseHeader();
523 $status = (int)$this->respStatus
;
525 if ( $status >= 300 && $status <= 303 ) {
533 * Returns an associative array of response headers after the
534 * request has been executed. Because some headers
535 * (e.g. Set-Cookie) can appear more than once the, each value of
536 * the associative array is an array of the values given.
537 * Header names are always in lowercase.
541 public function getResponseHeaders() {
542 if ( !$this->respHeaders
) {
543 $this->parseHeader();
546 return $this->respHeaders
;
550 * Returns the value of the given response header.
552 * @param string $header case-insensitive
553 * @return string|null
555 public function getResponseHeader( $header ) {
556 if ( !$this->respHeaders
) {
557 $this->parseHeader();
560 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
561 $v = $this->respHeaders
[strtolower( $header )];
562 return $v[count( $v ) - 1];
569 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
571 * To read response cookies from the jar, getCookieJar must be called first.
573 * @param CookieJar $jar
575 public function setCookieJar( CookieJar
$jar ) {
576 $this->cookieJar
= $jar;
580 * Returns the cookie jar in use.
584 public function getCookieJar() {
585 if ( !$this->respHeaders
) {
586 $this->parseHeader();
589 return $this->cookieJar
;
593 * Sets a cookie. Used before a request to set up any individual
594 * cookies. Used internally after a request to parse the
595 * Set-Cookie headers.
597 * @param string $name
598 * @param string $value
601 public function setCookie( $name, $value, array $attr = [] ) {
602 if ( !$this->cookieJar
) {
603 $this->cookieJar
= new CookieJar
;
606 if ( $this->parsedUrl
&& !isset( $attr['domain'] ) ) {
607 $attr['domain'] = $this->parsedUrl
['host'];
610 $this->cookieJar
->setCookie( $name, $value, $attr );
614 * Parse the cookies in the response headers and store them in the cookie jar.
616 protected function parseCookies() {
617 if ( !$this->cookieJar
) {
618 $this->cookieJar
= new CookieJar
;
621 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
622 $url = parse_url( $this->getFinalUrl() );
623 if ( !isset( $url['host'] ) ) {
624 $this->status
->fatal( 'http-invalid-url', $this->getFinalUrl() );
626 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
627 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
634 * Returns the final URL after all redirections.
636 * Relative values of the "Location" header are incorrect as
637 * stated in RFC, however they do happen and modern browsers
638 * support them. This function loops backwards through all
639 * locations in order to build the proper absolute URI - Marooned
642 * Note that the multiple Location: headers are an artifact of
643 * CURL -- they shouldn't actually get returned this way. Rewrite
644 * this when T31232 is taken care of (high-level redirect
649 public function getFinalUrl() {
650 $headers = $this->getResponseHeaders();
652 // return full url (fix for incorrect but handled relative location)
653 if ( isset( $headers['location'] ) ) {
654 $locations = $headers['location'];
656 $foundRelativeURI = false;
657 $countLocations = count( $locations );
659 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
660 $url = parse_url( $locations[$i] );
662 if ( isset( $url['scheme'] ) && isset( $url['host'] ) ) {
663 $domain = $url['scheme'] . '://' . $url['host'];
664 break; // found correct URI (with host)
666 $foundRelativeURI = true;
670 if ( !$foundRelativeURI ) {
671 return $locations[$countLocations - 1];
674 return $domain . $locations[$countLocations - 1];
676 $url = parse_url( $this->url
);
677 if ( isset( $url['scheme'] ) && isset( $url['host'] ) ) {
678 return $url['scheme'] . '://' . $url['host'] .
679 $locations[$countLocations - 1];
687 * Returns true if the backend can follow redirects. Overridden by the
691 public function canFollowRedirects() {
696 * Set information about the original request. This can be useful for
697 * endpoints/API modules which act as a proxy for some service, and
698 * throttling etc. needs to happen in that service.
699 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
701 * @param WebRequest|array $originalRequest When in array form, it's
702 * expected to have the keys 'ip' and 'userAgent'.
703 * @note IP/user agent is personally identifiable information, and should
704 * only be set when the privacy policy of the request target is
705 * compatible with that of the MediaWiki installation.
707 public function setOriginalRequest( $originalRequest ) {
708 if ( $originalRequest instanceof WebRequest
) {
710 'ip' => $originalRequest->getIP(),
711 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
714 !is_array( $originalRequest )
715 ||
array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
717 throw new InvalidArgumentException( __METHOD__
. ': $originalRequest must be a '
718 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
721 $this->reqHeaders
['X-Forwarded-For'] = $originalRequest['ip'];
722 $this->reqHeaders
['X-Original-User-Agent'] = $originalRequest['userAgent'];
726 * Check that the given URI is a valid one.
728 * This hardcodes a small set of protocols only, because we want to
729 * deterministically reject protocols not supported by all HTTP-transport
732 * "file://" specifically must not be allowed, for security reasons
733 * (see <https://www.mediawiki.org/wiki/Special:Code/MediaWiki/r67684>).
735 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
738 * @param string $uri URI to check for validity
741 public static function isValidURI( $uri ) {
742 return (bool)preg_match(
743 '/^https?:\/\/[^\/\s]\S*$/D',