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,connectTimeout?:int,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 // @phan-suppress-next-line PhanTypeInvalidDimOffset
107 $this->logger
= $options['logger'] ??
new NullLogger();
109 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
110 $this->status
= StatusValue
::newFatal( 'http-invalid-url', $url );
112 $this->status
= StatusValue
::newGood( 100 ); // continue
115 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
116 $this->timeout
= $options['timeout'];
118 $this->timeout
= $wgHTTPTimeout;
120 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
121 $this->connectTimeout
= $options['connectTimeout'];
123 $this->connectTimeout
= $wgHTTPConnectTimeout;
125 if ( isset( $options['userAgent'] ) ) {
126 $this->setUserAgent( $options['userAgent'] );
128 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
131 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
134 if ( isset( $options['originalRequest'] ) ) {
135 $this->setOriginalRequest( $options['originalRequest'] );
138 $this->setHeader( 'X-Request-Id', WebRequest
::getRequestId() );
140 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
141 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
143 foreach ( $members as $o ) {
144 if ( isset( $options[$o] ) ) {
145 // ensure that MWHttpRequest::method is always
146 // uppercased. T38137
147 if ( $o == 'method' ) {
148 // @phan-suppress-next-line PhanTypeInvalidDimOffset
149 $options[$o] = strtoupper( $options[$o] );
151 $this->$o = $options[$o];
155 if ( $this->noProxy
) {
156 $this->proxy
= ''; // noProxy takes precedence
159 // Profile based on what's calling us
160 $this->profiler
= $profiler;
161 $this->profileName
= $caller;
165 * @param LoggerInterface $logger
167 public function setLogger( LoggerInterface
$logger ) {
168 $this->logger
= $logger;
172 * Simple function to test if we can make any sort of requests at all, using
176 public static function canMakeRequests() {
177 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
181 * Generate a new request object
182 * @deprecated since 1.34, use HttpRequestFactory instead
183 * @param string $url Url to use
184 * @param array|null $options (optional) extra params to pass (see HttpRequestFactory::create())
185 * @param string $caller The method making this request, for profiling
186 * @throws DomainException
187 * @return MWHttpRequest
188 * @see MWHttpRequest::__construct
190 public static function factory( $url, array $options = null, $caller = __METHOD__
) {
191 if ( $options === null ) {
194 return \MediaWiki\MediaWikiServices
::getInstance()
195 ->getHttpRequestFactory()
196 ->create( $url, $options, $caller );
200 * Get the body, or content, of the response to the request
204 public function getContent() {
205 return $this->content
;
209 * Set the parameters of the request
212 * @todo overload the args param
214 public function setData( array $args ) {
215 $this->postData
= $args;
219 * Take care of setting up the proxy (do nothing if "noProxy" is set)
223 protected function proxySetup() {
224 // If there is an explicit proxy set and proxies are not disabled, then use it
225 if ( $this->proxy
&& !$this->noProxy
) {
229 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
230 // local URL and proxies are not disabled
231 if ( self
::isLocalURL( $this->url
) ||
$this->noProxy
) {
235 $this->proxy
= (string)$wgHTTPProxy;
240 * Check if the URL can be served by localhost
242 * @param string $url Full url to check
245 private static function isLocalURL( $url ) {
246 global $wgCommandLineMode, $wgLocalVirtualHosts;
248 if ( $wgCommandLineMode ) {
254 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
257 $domainParts = explode( '.', $host );
258 // Check if this domain or any superdomain is listed as a local virtual host
259 $domainParts = array_reverse( $domainParts );
262 $countParts = count( $domainParts );
263 for ( $i = 0; $i < $countParts; $i++
) {
264 $domainPart = $domainParts[$i];
266 $domain = $domainPart;
268 $domain = $domainPart . '.' . $domain;
271 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
284 public function setUserAgent( $UA ) {
285 $this->setHeader( 'User-Agent', $UA );
289 * Set an arbitrary header
290 * @param string $name
291 * @param string $value
293 public function setHeader( $name, $value ) {
294 // I feel like I should normalize the case here...
295 $this->reqHeaders
[$name] = $value;
299 * Get an array of the headers
302 protected function getHeaderList() {
305 if ( $this->cookieJar
) {
306 $this->reqHeaders
['Cookie'] =
307 $this->cookieJar
->serializeToHttpRequest(
308 $this->parsedUrl
['path'],
309 $this->parsedUrl
['host']
313 foreach ( $this->reqHeaders
as $name => $value ) {
314 $list[] = "$name: $value";
321 * Set a read callback to accept data read from the HTTP request.
322 * By default, data is appended to an internal buffer which can be
323 * retrieved through $req->getContent().
325 * To handle data as it comes in -- especially for large files that
326 * would not fit in memory -- you can instead set your own callback,
327 * in the form function($resource, $buffer) where the first parameter
328 * is the low-level resource being read (implementation specific),
329 * and the second parameter is the data buffer.
331 * You MUST return the number of bytes handled in the buffer; if fewer
332 * bytes are reported handled than were passed to you, the HTTP fetch
335 * @param callable|null $callback
336 * @throws InvalidArgumentException
338 public function setCallback( $callback ) {
339 return $this->doSetCallback( $callback );
343 * Worker function for setting callbacks. Calls can originate both internally and externally
344 * via setCallback). Defaults to the internal read callback if $callback is null.
346 * @param callable|null $callback
347 * @throws InvalidArgumentException
349 protected function doSetCallback( $callback ) {
350 if ( is_null( $callback ) ) {
351 $callback = [ $this, 'read' ];
352 } elseif ( !is_callable( $callback ) ) {
353 $this->status
->fatal( 'http-internal-error' );
354 throw new InvalidArgumentException( __METHOD__
. ': invalid callback' );
356 $this->callback
= $callback;
360 * A generic callback to read the body of the response from a remote
363 * @param resource $fh
364 * @param string $content
368 public function read( $fh, $content ) {
369 $this->content
.= $content;
370 return strlen( $content );
374 * Take care of whatever is necessary to perform the URI request.
377 * @note currently returns Status for B/C
379 public function execute() {
380 throw new LogicException( 'children must override this' );
383 protected function prepare() {
386 if ( strtoupper( $this->method
) == "HEAD" ) {
387 $this->headersOnly
= true;
390 $this->proxySetup(); // set up any proxy as needed
392 if ( !$this->callback
) {
393 $this->doSetCallback( null );
396 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
397 $this->setUserAgent( Http
::userAgent() );
402 * Parses the headers, including the HTTP status code and any
403 * Set-Cookie headers. This function expects the headers to be
404 * found in an array in the member variable headerList.
406 protected function parseHeader() {
409 // Failure without (valid) headers gets a response status of zero
410 if ( !$this->status
->isOK() ) {
411 $this->respStatus
= '0 Error';
414 foreach ( $this->headerList
as $header ) {
415 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
416 $this->respVersion
= $match[1];
417 $this->respStatus
= $match[2];
418 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
419 $last = count( $this->respHeaders
[$lastname] ) - 1;
420 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
421 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
422 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
423 $lastname = strtolower( $match[1] );
427 $this->parseCookies();
431 * Sets HTTPRequest status member to a fatal value with the error
432 * message if the returned integer value of the status code was
433 * not successful (1-299) or a redirect (300-399).
434 * See RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
435 * for a list of status codes.
437 protected function setStatus() {
438 if ( !$this->respHeaders
) {
439 $this->parseHeader();
442 if ( ( (int)$this->respStatus
> 0 && (int)$this->respStatus
< 400 ) ) {
443 $this->status
->setResult( true, (int)$this->respStatus
);
445 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
446 $this->status
->setResult( false, (int)$this->respStatus
);
447 $this->status
->fatal( "http-bad-status", $code, $message );
452 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
453 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
454 * for a list of status codes.)
458 public function getStatus() {
459 if ( !$this->respHeaders
) {
460 $this->parseHeader();
463 return (int)$this->respStatus
;
467 * Returns true if the last status code was a redirect.
471 public function isRedirect() {
472 if ( !$this->respHeaders
) {
473 $this->parseHeader();
476 $status = (int)$this->respStatus
;
478 if ( $status >= 300 && $status <= 303 ) {
486 * Returns an associative array of response headers after the
487 * request has been executed. Because some headers
488 * (e.g. Set-Cookie) can appear more than once the, each value of
489 * the associative array is an array of the values given.
490 * Header names are always in lowercase.
494 public function getResponseHeaders() {
495 if ( !$this->respHeaders
) {
496 $this->parseHeader();
499 return $this->respHeaders
;
503 * Returns the value of the given response header.
505 * @param string $header case-insensitive
506 * @return string|null
508 public function getResponseHeader( $header ) {
509 if ( !$this->respHeaders
) {
510 $this->parseHeader();
513 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
514 $v = $this->respHeaders
[strtolower( $header )];
515 return $v[count( $v ) - 1];
522 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
524 * To read response cookies from the jar, getCookieJar must be called first.
526 * @param CookieJar $jar
528 public function setCookieJar( CookieJar
$jar ) {
529 $this->cookieJar
= $jar;
533 * Returns the cookie jar in use.
537 public function getCookieJar() {
538 if ( !$this->respHeaders
) {
539 $this->parseHeader();
542 return $this->cookieJar
;
546 * Sets a cookie. Used before a request to set up any individual
547 * cookies. Used internally after a request to parse the
548 * Set-Cookie headers.
550 * @param string $name
551 * @param string $value
554 public function setCookie( $name, $value, array $attr = [] ) {
555 if ( !$this->cookieJar
) {
556 $this->cookieJar
= new CookieJar
;
559 if ( $this->parsedUrl
&& !isset( $attr['domain'] ) ) {
560 $attr['domain'] = $this->parsedUrl
['host'];
563 $this->cookieJar
->setCookie( $name, $value, $attr );
567 * Parse the cookies in the response headers and store them in the cookie jar.
569 protected function parseCookies() {
570 if ( !$this->cookieJar
) {
571 $this->cookieJar
= new CookieJar
;
574 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
575 $url = parse_url( $this->getFinalUrl() );
576 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
577 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
583 * Returns the final URL after all redirections.
585 * Relative values of the "Location" header are incorrect as
586 * stated in RFC, however they do happen and modern browsers
587 * support them. This function loops backwards through all
588 * locations in order to build the proper absolute URI - Marooned
591 * Note that the multiple Location: headers are an artifact of
592 * CURL -- they shouldn't actually get returned this way. Rewrite
593 * this when T31232 is taken care of (high-level redirect
598 public function getFinalUrl() {
599 $headers = $this->getResponseHeaders();
601 // return full url (fix for incorrect but handled relative location)
602 if ( isset( $headers['location'] ) ) {
603 $locations = $headers['location'];
605 $foundRelativeURI = false;
606 $countLocations = count( $locations );
608 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
609 $url = parse_url( $locations[$i] );
611 if ( isset( $url['host'] ) ) {
612 $domain = $url['scheme'] . '://' . $url['host'];
613 break; // found correct URI (with host)
615 $foundRelativeURI = true;
619 if ( !$foundRelativeURI ) {
620 return $locations[$countLocations - 1];
623 return $domain . $locations[$countLocations - 1];
625 $url = parse_url( $this->url
);
626 if ( isset( $url['host'] ) ) {
627 return $url['scheme'] . '://' . $url['host'] .
628 $locations[$countLocations - 1];
636 * Returns true if the backend can follow redirects. Overridden by the
640 public function canFollowRedirects() {
645 * Set information about the original request. This can be useful for
646 * endpoints/API modules which act as a proxy for some service, and
647 * throttling etc. needs to happen in that service.
648 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
650 * @param WebRequest|array $originalRequest When in array form, it's
651 * expected to have the keys 'ip' and 'userAgent'.
652 * @note IP/user agent is personally identifiable information, and should
653 * only be set when the privacy policy of the request target is
654 * compatible with that of the MediaWiki installation.
656 public function setOriginalRequest( $originalRequest ) {
657 if ( $originalRequest instanceof WebRequest
) {
659 'ip' => $originalRequest->getIP(),
660 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
663 !is_array( $originalRequest )
664 ||
array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
666 throw new InvalidArgumentException( __METHOD__
. ': $originalRequest must be a '
667 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
670 $this->reqHeaders
['X-Forwarded-For'] = $originalRequest['ip'];
671 $this->reqHeaders
['X-Original-User-Agent'] = $originalRequest['userAgent'];
675 * Check that the given URI is a valid one.
677 * This hardcodes a small set of protocols only, because we want to
678 * deterministically reject protocols not supported by all HTTP-transport
681 * "file://" specifically must not be allowed, for security reasons
682 * (see <https://www.mediawiki.org/wiki/Special:Code/MediaWiki/r67684>).
684 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
687 * @param string $uri URI to check for validity
690 public static function isValidURI( $uri ) {
691 return (bool)preg_match(
692 '/^https?:\/\/[^\/\s]\S*$/D',