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 Psr\Log\LoggerInterface
;
22 use Psr\Log\LoggerAwareInterface
;
23 use Psr\Log\NullLogger
;
26 * This wrapper class will call out to curl (if available) or fallback
27 * to regular PHP if necessary for handling internal HTTP requests.
29 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
30 * PHP's HTTP extension.
32 abstract class MWHttpRequest
implements LoggerAwareInterface
{
33 const SUPPORTS_FILE_POSTS
= false;
38 protected $timeout = 'default';
41 protected $headersOnly = null;
42 protected $postData = null;
43 protected $proxy = null;
44 protected $noProxy = false;
45 protected $sslVerifyHost = true;
46 protected $sslVerifyCert = true;
47 protected $caInfo = null;
48 protected $method = "GET";
50 protected $reqHeaders = [];
55 protected $maxRedirects = 5;
56 protected $followRedirects = false;
57 protected $connectTimeout;
64 protected $headerList = [];
65 protected $respVersion = "0.9";
66 protected $respStatus = "200 Ok";
67 /** @var string[][] */
68 protected $respHeaders = [];
70 /** @var StatusValue */
81 protected $profileName;
84 * @var LoggerInterface
89 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
90 * @param array $options (optional) extra params to pass (see HttpRequestFactory::create())
91 * @codingStandardsIgnoreStart
92 * @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
93 * @codingStandardsIgnoreEnd
94 * @param string $caller The method making this request, for profiling
95 * @param Profiler|null $profiler An instance of the profiler for profiling, or null
98 public function __construct(
99 $url, array $options = [], $caller = __METHOD__
, Profiler
$profiler = null
101 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
103 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
104 $this->parsedUrl
= wfParseUrl( $this->url
);
106 $this->logger
= $options['logger'] ??
new NullLogger();
108 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
109 $this->status
= StatusValue
::newFatal( 'http-invalid-url', $url );
111 $this->status
= StatusValue
::newGood( 100 ); // continue
114 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
115 $this->timeout
= $options['timeout'];
117 $this->timeout
= $wgHTTPTimeout;
119 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
120 $this->connectTimeout
= $options['connectTimeout'];
122 $this->connectTimeout
= $wgHTTPConnectTimeout;
124 if ( isset( $options['userAgent'] ) ) {
125 $this->setUserAgent( $options['userAgent'] );
127 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
130 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
133 if ( isset( $options['originalRequest'] ) ) {
134 $this->setOriginalRequest( $options['originalRequest'] );
137 $this->setHeader( 'X-Request-Id', WebRequest
::getRequestId() );
139 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
140 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
142 foreach ( $members as $o ) {
143 if ( isset( $options[$o] ) ) {
144 // ensure that MWHttpRequest::method is always
145 // uppercased. T38137
146 if ( $o == 'method' ) {
147 // @phan-suppress-next-line PhanTypeInvalidDimOffset
148 $options[$o] = strtoupper( $options[$o] );
150 $this->$o = $options[$o];
154 if ( $this->noProxy
) {
155 $this->proxy
= ''; // noProxy takes precedence
158 // Profile based on what's calling us
159 $this->profiler
= $profiler;
160 $this->profileName
= $caller;
164 * @param LoggerInterface $logger
166 public function setLogger( LoggerInterface
$logger ) {
167 $this->logger
= $logger;
171 * Simple function to test if we can make any sort of requests at all, using
175 public static function canMakeRequests() {
176 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
180 * Generate a new request object
181 * @deprecated since 1.34, use HttpRequestFactory instead
182 * @param string $url Url to use
183 * @param array|null $options (optional) extra params to pass (see HttpRequestFactory::create())
184 * @param string $caller The method making this request, for profiling
185 * @throws DomainException
186 * @return MWHttpRequest
187 * @see MWHttpRequest::__construct
189 public static function factory( $url, array $options = null, $caller = __METHOD__
) {
190 if ( $options === null ) {
193 return \MediaWiki\MediaWikiServices
::getInstance()
194 ->getHttpRequestFactory()
195 ->create( $url, $options, $caller );
199 * Get the body, or content, of the response to the request
203 public function getContent() {
204 return $this->content
;
208 * Set the parameters of the request
211 * @todo overload the args param
213 public function setData( array $args ) {
214 $this->postData
= $args;
218 * Take care of setting up the proxy (do nothing if "noProxy" is set)
222 protected function proxySetup() {
223 // If there is an explicit proxy set and proxies are not disabled, then use it
224 if ( $this->proxy
&& !$this->noProxy
) {
228 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
229 // local URL and proxies are not disabled
230 if ( self
::isLocalURL( $this->url
) ||
$this->noProxy
) {
234 $this->proxy
= (string)$wgHTTPProxy;
239 * Check if the URL can be served by localhost
241 * @param string $url Full url to check
244 private static function isLocalURL( $url ) {
245 global $wgCommandLineMode, $wgLocalVirtualHosts;
247 if ( $wgCommandLineMode ) {
253 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
256 $domainParts = explode( '.', $host );
257 // Check if this domain or any superdomain is listed as a local virtual host
258 $domainParts = array_reverse( $domainParts );
261 $countParts = count( $domainParts );
262 for ( $i = 0; $i < $countParts; $i++
) {
263 $domainPart = $domainParts[$i];
265 $domain = $domainPart;
267 $domain = $domainPart . '.' . $domain;
270 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
283 public function setUserAgent( $UA ) {
284 $this->setHeader( 'User-Agent', $UA );
288 * Set an arbitrary header
289 * @param string $name
290 * @param string $value
292 public function setHeader( $name, $value ) {
293 // I feel like I should normalize the case here...
294 $this->reqHeaders
[$name] = $value;
298 * Get an array of the headers
301 protected function getHeaderList() {
304 if ( $this->cookieJar
) {
305 $this->reqHeaders
['Cookie'] =
306 $this->cookieJar
->serializeToHttpRequest(
307 $this->parsedUrl
['path'],
308 $this->parsedUrl
['host']
312 foreach ( $this->reqHeaders
as $name => $value ) {
313 $list[] = "$name: $value";
320 * Set a read callback to accept data read from the HTTP request.
321 * By default, data is appended to an internal buffer which can be
322 * retrieved through $req->getContent().
324 * To handle data as it comes in -- especially for large files that
325 * would not fit in memory -- you can instead set your own callback,
326 * in the form function($resource, $buffer) where the first parameter
327 * is the low-level resource being read (implementation specific),
328 * and the second parameter is the data buffer.
330 * You MUST return the number of bytes handled in the buffer; if fewer
331 * bytes are reported handled than were passed to you, the HTTP fetch
334 * @param callable|null $callback
335 * @throws InvalidArgumentException
337 public function setCallback( $callback ) {
338 return $this->doSetCallback( $callback );
342 * Worker function for setting callbacks. Calls can originate both internally and externally
343 * via setCallback). Defaults to the internal read callback if $callback is null.
345 * @param callable|null $callback
346 * @throws InvalidArgumentException
348 protected function doSetCallback( $callback ) {
349 if ( is_null( $callback ) ) {
350 $callback = [ $this, 'read' ];
351 } elseif ( !is_callable( $callback ) ) {
352 $this->status
->fatal( 'http-internal-error' );
353 throw new InvalidArgumentException( __METHOD__
. ': invalid callback' );
355 $this->callback
= $callback;
359 * A generic callback to read the body of the response from a remote
362 * @param resource $fh
363 * @param string $content
367 public function read( $fh, $content ) {
368 $this->content
.= $content;
369 return strlen( $content );
373 * Take care of whatever is necessary to perform the URI request.
376 * @note currently returns Status for B/C
378 public function execute() {
379 throw new LogicException( 'children must override this' );
382 protected function prepare() {
385 if ( strtoupper( $this->method
) == "HEAD" ) {
386 $this->headersOnly
= true;
389 $this->proxySetup(); // set up any proxy as needed
391 if ( !$this->callback
) {
392 $this->doSetCallback( null );
395 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
396 $this->setUserAgent( Http
::userAgent() );
401 * Parses the headers, including the HTTP status code and any
402 * Set-Cookie headers. This function expects the headers to be
403 * found in an array in the member variable headerList.
405 protected function parseHeader() {
408 // Failure without (valid) headers gets a response status of zero
409 if ( !$this->status
->isOK() ) {
410 $this->respStatus
= '0 Error';
413 foreach ( $this->headerList
as $header ) {
414 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
415 $this->respVersion
= $match[1];
416 $this->respStatus
= $match[2];
417 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
418 $last = count( $this->respHeaders
[$lastname] ) - 1;
419 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
420 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
421 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
422 $lastname = strtolower( $match[1] );
426 $this->parseCookies();
430 * Sets HTTPRequest status member to a fatal value with the error
431 * message if the returned integer value of the status code was
432 * not successful (1-299) or a redirect (300-399).
433 * See RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
434 * for a list of status codes.
436 protected function setStatus() {
437 if ( !$this->respHeaders
) {
438 $this->parseHeader();
441 if ( ( (int)$this->respStatus
> 0 && (int)$this->respStatus
< 400 ) ) {
442 $this->status
->setResult( true, (int)$this->respStatus
);
444 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
445 $this->status
->setResult( false, (int)$this->respStatus
);
446 $this->status
->fatal( "http-bad-status", $code, $message );
451 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
452 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
453 * for a list of status codes.)
457 public function getStatus() {
458 if ( !$this->respHeaders
) {
459 $this->parseHeader();
462 return (int)$this->respStatus
;
466 * Returns true if the last status code was a redirect.
470 public function isRedirect() {
471 if ( !$this->respHeaders
) {
472 $this->parseHeader();
475 $status = (int)$this->respStatus
;
477 if ( $status >= 300 && $status <= 303 ) {
485 * Returns an associative array of response headers after the
486 * request has been executed. Because some headers
487 * (e.g. Set-Cookie) can appear more than once the, each value of
488 * the associative array is an array of the values given.
489 * Header names are always in lowercase.
493 public function getResponseHeaders() {
494 if ( !$this->respHeaders
) {
495 $this->parseHeader();
498 return $this->respHeaders
;
502 * Returns the value of the given response header.
504 * @param string $header case-insensitive
505 * @return string|null
507 public function getResponseHeader( $header ) {
508 if ( !$this->respHeaders
) {
509 $this->parseHeader();
512 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
513 $v = $this->respHeaders
[strtolower( $header )];
514 return $v[count( $v ) - 1];
521 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
523 * To read response cookies from the jar, getCookieJar must be called first.
525 * @param CookieJar $jar
527 public function setCookieJar( CookieJar
$jar ) {
528 $this->cookieJar
= $jar;
532 * Returns the cookie jar in use.
536 public function getCookieJar() {
537 if ( !$this->respHeaders
) {
538 $this->parseHeader();
541 return $this->cookieJar
;
545 * Sets a cookie. Used before a request to set up any individual
546 * cookies. Used internally after a request to parse the
547 * Set-Cookie headers.
549 * @param string $name
550 * @param string $value
553 public function setCookie( $name, $value, array $attr = [] ) {
554 if ( !$this->cookieJar
) {
555 $this->cookieJar
= new CookieJar
;
558 if ( $this->parsedUrl
&& !isset( $attr['domain'] ) ) {
559 $attr['domain'] = $this->parsedUrl
['host'];
562 $this->cookieJar
->setCookie( $name, $value, $attr );
566 * Parse the cookies in the response headers and store them in the cookie jar.
568 protected function parseCookies() {
569 if ( !$this->cookieJar
) {
570 $this->cookieJar
= new CookieJar
;
573 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
574 $url = parse_url( $this->getFinalUrl() );
575 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
576 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
582 * Returns the final URL after all redirections.
584 * Relative values of the "Location" header are incorrect as
585 * stated in RFC, however they do happen and modern browsers
586 * support them. This function loops backwards through all
587 * locations in order to build the proper absolute URI - Marooned
590 * Note that the multiple Location: headers are an artifact of
591 * CURL -- they shouldn't actually get returned this way. Rewrite
592 * this when T31232 is taken care of (high-level redirect
597 public function getFinalUrl() {
598 $headers = $this->getResponseHeaders();
600 // return full url (fix for incorrect but handled relative location)
601 if ( isset( $headers['location'] ) ) {
602 $locations = $headers['location'];
604 $foundRelativeURI = false;
605 $countLocations = count( $locations );
607 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
608 $url = parse_url( $locations[$i] );
610 if ( isset( $url['host'] ) ) {
611 $domain = $url['scheme'] . '://' . $url['host'];
612 break; // found correct URI (with host)
614 $foundRelativeURI = true;
618 if ( !$foundRelativeURI ) {
619 return $locations[$countLocations - 1];
622 return $domain . $locations[$countLocations - 1];
624 $url = parse_url( $this->url
);
625 if ( isset( $url['host'] ) ) {
626 return $url['scheme'] . '://' . $url['host'] .
627 $locations[$countLocations - 1];
635 * Returns true if the backend can follow redirects. Overridden by the
639 public function canFollowRedirects() {
644 * Set information about the original request. This can be useful for
645 * endpoints/API modules which act as a proxy for some service, and
646 * throttling etc. needs to happen in that service.
647 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
649 * @param WebRequest|array $originalRequest When in array form, it's
650 * expected to have the keys 'ip' and 'userAgent'.
651 * @note IP/user agent is personally identifiable information, and should
652 * only be set when the privacy policy of the request target is
653 * compatible with that of the MediaWiki installation.
655 public function setOriginalRequest( $originalRequest ) {
656 if ( $originalRequest instanceof WebRequest
) {
658 'ip' => $originalRequest->getIP(),
659 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
662 !is_array( $originalRequest )
663 ||
array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
665 throw new InvalidArgumentException( __METHOD__
. ': $originalRequest must be a '
666 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
669 $this->reqHeaders
['X-Forwarded-For'] = $originalRequest['ip'];
670 $this->reqHeaders
['X-Original-User-Agent'] = $originalRequest['userAgent'];
674 * Check that the given URI is a valid one.
676 * This hardcodes a small set of protocols only, because we want to
677 * deterministically reject protocols not supported by all HTTP-transport
680 * "file://" specifically must not be allowed, for security reasons
681 * (see <https://www.mediawiki.org/wiki/Special:Code/MediaWiki/r67684>).
683 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
686 * @param string $uri URI to check for validity
689 public static function isValidURI( $uri ) {
690 return (bool)preg_match(
691 '/^https?:\/\/[^\/\s]\S*$/D',