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";
49 protected $reqHeaders = [];
54 protected $maxRedirects = 5;
55 protected $followRedirects = false;
56 protected $connectTimeout;
63 protected $headerList = [];
64 protected $respVersion = "0.9";
65 protected $respStatus = "200 Ok";
66 protected $respHeaders = [];
68 /** @var StatusValue */
79 protected $profileName;
82 * @var LoggerInterface
87 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
88 * @param array $options (optional) extra params to pass (see HttpRequestFactory::create())
89 * @param string $caller The method making this request, for profiling
90 * @param Profiler|null $profiler An instance of the profiler for profiling, or null
93 public function __construct(
94 $url, array $options = [], $caller = __METHOD__
, Profiler
$profiler = null
96 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
98 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
99 $this->parsedUrl
= wfParseUrl( $this->url
);
101 $this->logger
= $options['logger'] ??
new NullLogger();
103 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
104 $this->status
= StatusValue
::newFatal( 'http-invalid-url', $url );
106 $this->status
= StatusValue
::newGood( 100 ); // continue
109 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
110 $this->timeout
= $options['timeout'];
112 $this->timeout
= $wgHTTPTimeout;
114 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
115 $this->connectTimeout
= $options['connectTimeout'];
117 $this->connectTimeout
= $wgHTTPConnectTimeout;
119 if ( isset( $options['userAgent'] ) ) {
120 $this->setUserAgent( $options['userAgent'] );
122 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
125 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
128 if ( isset( $options['originalRequest'] ) ) {
129 $this->setOriginalRequest( $options['originalRequest'] );
132 $this->setHeader( 'X-Request-Id', WebRequest
::getRequestId() );
134 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
135 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
137 foreach ( $members as $o ) {
138 if ( isset( $options[$o] ) ) {
139 // ensure that MWHttpRequest::method is always
140 // uppercased. T38137
141 if ( $o == 'method' ) {
142 $options[$o] = strtoupper( $options[$o] );
144 $this->$o = $options[$o];
148 if ( $this->noProxy
) {
149 $this->proxy
= ''; // noProxy takes precedence
152 // Profile based on what's calling us
153 $this->profiler
= $profiler;
154 $this->profileName
= $caller;
158 * @param LoggerInterface $logger
160 public function setLogger( LoggerInterface
$logger ) {
161 $this->logger
= $logger;
165 * Simple function to test if we can make any sort of requests at all, using
169 public static function canMakeRequests() {
170 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
174 * Generate a new request object
175 * @deprecated since 1.34, use HttpRequestFactory instead
176 * @param string $url Url to use
177 * @param array|null $options (optional) extra params to pass (see HttpRequestFactory::create())
178 * @param string $caller The method making this request, for profiling
179 * @throws DomainException
180 * @return MWHttpRequest
181 * @see MWHttpRequest::__construct
183 public static function factory( $url, array $options = null, $caller = __METHOD__
) {
184 if ( $options === null ) {
187 return \MediaWiki\MediaWikiServices
::getInstance()
188 ->getHttpRequestFactory()
189 ->create( $url, $options, $caller );
193 * Get the body, or content, of the response to the request
197 public function getContent() {
198 return $this->content
;
202 * Set the parameters of the request
205 * @todo overload the args param
207 public function setData( array $args ) {
208 $this->postData
= $args;
212 * Take care of setting up the proxy (do nothing if "noProxy" is set)
216 protected function proxySetup() {
217 // If there is an explicit proxy set and proxies are not disabled, then use it
218 if ( $this->proxy
&& !$this->noProxy
) {
222 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
223 // local URL and proxies are not disabled
224 if ( self
::isLocalURL( $this->url
) ||
$this->noProxy
) {
228 $this->proxy
= (string)$wgHTTPProxy;
233 * Check if the URL can be served by localhost
235 * @param string $url Full url to check
238 private static function isLocalURL( $url ) {
239 global $wgCommandLineMode, $wgLocalVirtualHosts;
241 if ( $wgCommandLineMode ) {
247 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
250 $domainParts = explode( '.', $host );
251 // Check if this domain or any superdomain is listed as a local virtual host
252 $domainParts = array_reverse( $domainParts );
255 $countParts = count( $domainParts );
256 for ( $i = 0; $i < $countParts; $i++
) {
257 $domainPart = $domainParts[$i];
259 $domain = $domainPart;
261 $domain = $domainPart . '.' . $domain;
264 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
277 public function setUserAgent( $UA ) {
278 $this->setHeader( 'User-Agent', $UA );
282 * Set an arbitrary header
283 * @param string $name
284 * @param string $value
286 public function setHeader( $name, $value ) {
287 // I feel like I should normalize the case here...
288 $this->reqHeaders
[$name] = $value;
292 * Get an array of the headers
295 protected function getHeaderList() {
298 if ( $this->cookieJar
) {
299 $this->reqHeaders
['Cookie'] =
300 $this->cookieJar
->serializeToHttpRequest(
301 $this->parsedUrl
['path'],
302 $this->parsedUrl
['host']
306 foreach ( $this->reqHeaders
as $name => $value ) {
307 $list[] = "$name: $value";
314 * Set a read callback to accept data read from the HTTP request.
315 * By default, data is appended to an internal buffer which can be
316 * retrieved through $req->getContent().
318 * To handle data as it comes in -- especially for large files that
319 * would not fit in memory -- you can instead set your own callback,
320 * in the form function($resource, $buffer) where the first parameter
321 * is the low-level resource being read (implementation specific),
322 * and the second parameter is the data buffer.
324 * You MUST return the number of bytes handled in the buffer; if fewer
325 * bytes are reported handled than were passed to you, the HTTP fetch
328 * @param callable|null $callback
329 * @throws InvalidArgumentException
331 public function setCallback( $callback ) {
332 return $this->doSetCallback( $callback );
336 * Worker function for setting callbacks. Calls can originate both internally and externally
337 * via setCallback). Defaults to the internal read callback if $callback is null.
339 * @param callable|null $callback
340 * @throws InvalidArgumentException
342 protected function doSetCallback( $callback ) {
343 if ( is_null( $callback ) ) {
344 $callback = [ $this, 'read' ];
345 } elseif ( !is_callable( $callback ) ) {
346 $this->status
->fatal( 'http-internal-error' );
347 throw new InvalidArgumentException( __METHOD__
. ': invalid callback' );
349 $this->callback
= $callback;
353 * A generic callback to read the body of the response from a remote
356 * @param resource $fh
357 * @param string $content
361 public function read( $fh, $content ) {
362 $this->content
.= $content;
363 return strlen( $content );
367 * Take care of whatever is necessary to perform the URI request.
369 * @return StatusValue
370 * @note currently returns Status for B/C
372 public function execute() {
373 throw new LogicException( 'children must override this' );
376 protected function prepare() {
379 if ( strtoupper( $this->method
) == "HEAD" ) {
380 $this->headersOnly
= true;
383 $this->proxySetup(); // set up any proxy as needed
385 if ( !$this->callback
) {
386 $this->doSetCallback( null );
389 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
390 $this->setUserAgent( Http
::userAgent() );
395 * Parses the headers, including the HTTP status code and any
396 * Set-Cookie headers. This function expects the headers to be
397 * found in an array in the member variable headerList.
399 protected function parseHeader() {
402 // Failure without (valid) headers gets a response status of zero
403 if ( !$this->status
->isOK() ) {
404 $this->respStatus
= '0 Error';
407 foreach ( $this->headerList
as $header ) {
408 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
409 $this->respVersion
= $match[1];
410 $this->respStatus
= $match[2];
411 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
412 $last = count( $this->respHeaders
[$lastname] ) - 1;
413 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
414 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
415 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
416 $lastname = strtolower( $match[1] );
420 $this->parseCookies();
424 * Sets HTTPRequest status member to a fatal value with the error
425 * message if the returned integer value of the status code was
426 * not successful (1-299) or a redirect (300-399).
427 * See RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
428 * for a list of status codes.
430 protected function setStatus() {
431 if ( !$this->respHeaders
) {
432 $this->parseHeader();
435 if ( ( (int)$this->respStatus
> 0 && (int)$this->respStatus
< 400 ) ) {
436 $this->status
->setResult( true, (int)$this->respStatus
);
438 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
439 $this->status
->setResult( false, (int)$this->respStatus
);
440 $this->status
->fatal( "http-bad-status", $code, $message );
445 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
446 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
447 * for a list of status codes.)
451 public function getStatus() {
452 if ( !$this->respHeaders
) {
453 $this->parseHeader();
456 return (int)$this->respStatus
;
460 * Returns true if the last status code was a redirect.
464 public function isRedirect() {
465 if ( !$this->respHeaders
) {
466 $this->parseHeader();
469 $status = (int)$this->respStatus
;
471 if ( $status >= 300 && $status <= 303 ) {
479 * Returns an associative array of response headers after the
480 * request has been executed. Because some headers
481 * (e.g. Set-Cookie) can appear more than once the, each value of
482 * the associative array is an array of the values given.
483 * Header names are always in lowercase.
487 public function getResponseHeaders() {
488 if ( !$this->respHeaders
) {
489 $this->parseHeader();
492 return $this->respHeaders
;
496 * Returns the value of the given response header.
498 * @param string $header case-insensitive
499 * @return string|null
501 public function getResponseHeader( $header ) {
502 if ( !$this->respHeaders
) {
503 $this->parseHeader();
506 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
507 $v = $this->respHeaders
[strtolower( $header )];
508 return $v[count( $v ) - 1];
515 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
517 * To read response cookies from the jar, getCookieJar must be called first.
519 * @param CookieJar $jar
521 public function setCookieJar( CookieJar
$jar ) {
522 $this->cookieJar
= $jar;
526 * Returns the cookie jar in use.
530 public function getCookieJar() {
531 if ( !$this->respHeaders
) {
532 $this->parseHeader();
535 return $this->cookieJar
;
539 * Sets a cookie. Used before a request to set up any individual
540 * cookies. Used internally after a request to parse the
541 * Set-Cookie headers.
543 * @param string $name
544 * @param string $value
547 public function setCookie( $name, $value, array $attr = [] ) {
548 if ( !$this->cookieJar
) {
549 $this->cookieJar
= new CookieJar
;
552 if ( $this->parsedUrl
&& !isset( $attr['domain'] ) ) {
553 $attr['domain'] = $this->parsedUrl
['host'];
556 $this->cookieJar
->setCookie( $name, $value, $attr );
560 * Parse the cookies in the response headers and store them in the cookie jar.
562 protected function parseCookies() {
563 if ( !$this->cookieJar
) {
564 $this->cookieJar
= new CookieJar
;
567 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
568 $url = parse_url( $this->getFinalUrl() );
569 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
570 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
576 * Returns the final URL after all redirections.
578 * Relative values of the "Location" header are incorrect as
579 * stated in RFC, however they do happen and modern browsers
580 * support them. This function loops backwards through all
581 * locations in order to build the proper absolute URI - Marooned
584 * Note that the multiple Location: headers are an artifact of
585 * CURL -- they shouldn't actually get returned this way. Rewrite
586 * this when T31232 is taken care of (high-level redirect
591 public function getFinalUrl() {
592 $headers = $this->getResponseHeaders();
594 // return full url (fix for incorrect but handled relative location)
595 if ( isset( $headers['location'] ) ) {
596 $locations = $headers['location'];
598 $foundRelativeURI = false;
599 $countLocations = count( $locations );
601 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
602 $url = parse_url( $locations[$i] );
604 if ( isset( $url['host'] ) ) {
605 $domain = $url['scheme'] . '://' . $url['host'];
606 break; // found correct URI (with host)
608 $foundRelativeURI = true;
612 if ( !$foundRelativeURI ) {
613 return $locations[$countLocations - 1];
616 return $domain . $locations[$countLocations - 1];
618 $url = parse_url( $this->url
);
619 if ( isset( $url['host'] ) ) {
620 return $url['scheme'] . '://' . $url['host'] .
621 $locations[$countLocations - 1];
629 * Returns true if the backend can follow redirects. Overridden by the
633 public function canFollowRedirects() {
638 * Set information about the original request. This can be useful for
639 * endpoints/API modules which act as a proxy for some service, and
640 * throttling etc. needs to happen in that service.
641 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
643 * @param WebRequest|array $originalRequest When in array form, it's
644 * expected to have the keys 'ip' and 'userAgent'.
645 * @note IP/user agent is personally identifiable information, and should
646 * only be set when the privacy policy of the request target is
647 * compatible with that of the MediaWiki installation.
649 public function setOriginalRequest( $originalRequest ) {
650 if ( $originalRequest instanceof WebRequest
) {
652 'ip' => $originalRequest->getIP(),
653 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
656 !is_array( $originalRequest )
657 ||
array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
659 throw new InvalidArgumentException( __METHOD__
. ': $originalRequest must be a '
660 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
663 $this->reqHeaders
['X-Forwarded-For'] = $originalRequest['ip'];
664 $this->reqHeaders
['X-Original-User-Agent'] = $originalRequest['userAgent'];
668 * Check that the given URI is a valid one.
670 * This hardcodes a small set of protocols only, because we want to
671 * deterministically reject protocols not supported by all HTTP-transport
674 * "file://" specifically must not be allowed, for security reasons
675 * (see <https://www.mediawiki.org/wiki/Special:Code/MediaWiki/r67684>).
677 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
680 * @param string $uri URI to check for validity
683 public static function isValidURI( $uri ) {
684 return (bool)preg_match(
685 '/^https?:\/\/[^\/\s]\S*$/D',