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 Http::request())
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 = 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 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
133 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
135 foreach ( $members as $o ) {
136 if ( isset( $options[$o] ) ) {
137 // ensure that MWHttpRequest::method is always
138 // uppercased. T38137
139 if ( $o == 'method' ) {
140 $options[$o] = strtoupper( $options[$o] );
142 $this->$o = $options[$o];
146 if ( $this->noProxy
) {
147 $this->proxy
= ''; // noProxy takes precedence
150 // Profile based on what's calling us
151 $this->profiler
= $profiler;
152 $this->profileName
= $caller;
156 * @param LoggerInterface $logger
158 public function setLogger( LoggerInterface
$logger ) {
159 $this->logger
= $logger;
163 * Simple function to test if we can make any sort of requests at all, using
167 public static function canMakeRequests() {
168 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
172 * Generate a new request object
173 * Deprecated: @see HttpRequestFactory::create
174 * @param string $url Url to use
175 * @param array|null $options (optional) extra params to pass (see Http::request())
176 * @param string $caller The method making this request, for profiling
177 * @throws DomainException
178 * @return MWHttpRequest
179 * @see MWHttpRequest::__construct
181 public static function factory( $url, array $options = null, $caller = __METHOD__
) {
182 if ( $options === null ) {
185 return \MediaWiki\MediaWikiServices
::getInstance()
186 ->getHttpRequestFactory()
187 ->create( $url, $options, $caller );
191 * Get the body, or content, of the response to the request
195 public function getContent() {
196 return $this->content
;
200 * Set the parameters of the request
203 * @todo overload the args param
205 public function setData( $args ) {
206 $this->postData
= $args;
210 * Take care of setting up the proxy (do nothing if "noProxy" is set)
214 protected function proxySetup() {
215 // If there is an explicit proxy set and proxies are not disabled, then use it
216 if ( $this->proxy
&& !$this->noProxy
) {
220 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
221 // local URL and proxies are not disabled
222 if ( self
::isLocalURL( $this->url
) ||
$this->noProxy
) {
225 $this->proxy
= Http
::getProxy();
230 * Check if the URL can be served by localhost
232 * @param string $url Full url to check
235 private static function isLocalURL( $url ) {
236 global $wgCommandLineMode, $wgLocalVirtualHosts;
238 if ( $wgCommandLineMode ) {
244 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
247 $domainParts = explode( '.', $host );
248 // Check if this domain or any superdomain is listed as a local virtual host
249 $domainParts = array_reverse( $domainParts );
252 $countParts = count( $domainParts );
253 for ( $i = 0; $i < $countParts; $i++
) {
254 $domainPart = $domainParts[$i];
256 $domain = $domainPart;
258 $domain = $domainPart . '.' . $domain;
261 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
274 public function setUserAgent( $UA ) {
275 $this->setHeader( 'User-Agent', $UA );
279 * Set an arbitrary header
280 * @param string $name
281 * @param string $value
283 public function setHeader( $name, $value ) {
284 // I feel like I should normalize the case here...
285 $this->reqHeaders
[$name] = $value;
289 * Get an array of the headers
292 protected function getHeaderList() {
295 if ( $this->cookieJar
) {
296 $this->reqHeaders
['Cookie'] =
297 $this->cookieJar
->serializeToHttpRequest(
298 $this->parsedUrl
['path'],
299 $this->parsedUrl
['host']
303 foreach ( $this->reqHeaders
as $name => $value ) {
304 $list[] = "$name: $value";
311 * Set a read callback to accept data read from the HTTP request.
312 * By default, data is appended to an internal buffer which can be
313 * retrieved through $req->getContent().
315 * To handle data as it comes in -- especially for large files that
316 * would not fit in memory -- you can instead set your own callback,
317 * in the form function($resource, $buffer) where the first parameter
318 * is the low-level resource being read (implementation specific),
319 * and the second parameter is the data buffer.
321 * You MUST return the number of bytes handled in the buffer; if fewer
322 * bytes are reported handled than were passed to you, the HTTP fetch
325 * @param callable|null $callback
326 * @throws InvalidArgumentException
328 public function setCallback( $callback ) {
329 if ( is_null( $callback ) ) {
330 $callback = [ $this, 'read' ];
331 } elseif ( !is_callable( $callback ) ) {
332 $this->status
->fatal( 'http-internal-error' );
333 throw new InvalidArgumentException( __METHOD__
. ': invalid callback' );
335 $this->callback
= $callback;
339 * A generic callback to read the body of the response from a remote
342 * @param resource $fh
343 * @param string $content
347 public function read( $fh, $content ) {
348 $this->content
.= $content;
349 return strlen( $content );
353 * Take care of whatever is necessary to perform the URI request.
355 * @return StatusValue
356 * @note currently returns Status for B/C
358 public function execute() {
359 throw new LogicException( 'children must override this' );
362 protected function prepare() {
365 if ( strtoupper( $this->method
) == "HEAD" ) {
366 $this->headersOnly
= true;
369 $this->proxySetup(); // set up any proxy as needed
371 if ( !$this->callback
) {
372 $this->setCallback( null );
375 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
376 $this->setUserAgent( Http
::userAgent() );
381 * Parses the headers, including the HTTP status code and any
382 * Set-Cookie headers. This function expects the headers to be
383 * found in an array in the member variable headerList.
385 protected function parseHeader() {
388 // Failure without (valid) headers gets a response status of zero
389 if ( !$this->status
->isOK() ) {
390 $this->respStatus
= '0 Error';
393 foreach ( $this->headerList
as $header ) {
394 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
395 $this->respVersion
= $match[1];
396 $this->respStatus
= $match[2];
397 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
398 $last = count( $this->respHeaders
[$lastname] ) - 1;
399 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
400 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
401 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
402 $lastname = strtolower( $match[1] );
406 $this->parseCookies();
410 * Sets HTTPRequest status member to a fatal value with the error
411 * message if the returned integer value of the status code was
412 * not successful (1-299) or a redirect (300-399).
413 * See RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
414 * for a list of status codes.
416 protected function setStatus() {
417 if ( !$this->respHeaders
) {
418 $this->parseHeader();
421 if ( ( (int)$this->respStatus
> 0 && (int)$this->respStatus
< 400 ) ) {
422 $this->status
->setResult( true, (int)$this->respStatus
);
424 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
425 $this->status
->setResult( false, (int)$this->respStatus
);
426 $this->status
->fatal( "http-bad-status", $code, $message );
431 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
432 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
433 * for a list of status codes.)
437 public function getStatus() {
438 if ( !$this->respHeaders
) {
439 $this->parseHeader();
442 return (int)$this->respStatus
;
446 * Returns true if the last status code was a redirect.
450 public function isRedirect() {
451 if ( !$this->respHeaders
) {
452 $this->parseHeader();
455 $status = (int)$this->respStatus
;
457 if ( $status >= 300 && $status <= 303 ) {
465 * Returns an associative array of response headers after the
466 * request has been executed. Because some headers
467 * (e.g. Set-Cookie) can appear more than once the, each value of
468 * the associative array is an array of the values given.
472 public function getResponseHeaders() {
473 if ( !$this->respHeaders
) {
474 $this->parseHeader();
477 return $this->respHeaders
;
481 * Returns the value of the given response header.
483 * @param string $header
484 * @return string|null
486 public function getResponseHeader( $header ) {
487 if ( !$this->respHeaders
) {
488 $this->parseHeader();
491 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
492 $v = $this->respHeaders
[strtolower( $header )];
493 return $v[count( $v ) - 1];
500 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
502 * To read response cookies from the jar, getCookieJar must be called first.
504 * @param CookieJar $jar
506 public function setCookieJar( $jar ) {
507 $this->cookieJar
= $jar;
511 * Returns the cookie jar in use.
515 public function getCookieJar() {
516 if ( !$this->respHeaders
) {
517 $this->parseHeader();
520 return $this->cookieJar
;
524 * Sets a cookie. Used before a request to set up any individual
525 * cookies. Used internally after a request to parse the
526 * Set-Cookie headers.
528 * @param string $name
529 * @param string $value
532 public function setCookie( $name, $value, $attr = [] ) {
533 if ( !$this->cookieJar
) {
534 $this->cookieJar
= new CookieJar
;
537 if ( $this->parsedUrl
&& !isset( $attr['domain'] ) ) {
538 $attr['domain'] = $this->parsedUrl
['host'];
541 $this->cookieJar
->setCookie( $name, $value, $attr );
545 * Parse the cookies in the response headers and store them in the cookie jar.
547 protected function parseCookies() {
548 if ( !$this->cookieJar
) {
549 $this->cookieJar
= new CookieJar
;
552 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
553 $url = parse_url( $this->getFinalUrl() );
554 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
555 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
561 * Returns the final URL after all redirections.
563 * Relative values of the "Location" header are incorrect as
564 * stated in RFC, however they do happen and modern browsers
565 * support them. This function loops backwards through all
566 * locations in order to build the proper absolute URI - Marooned
569 * Note that the multiple Location: headers are an artifact of
570 * CURL -- they shouldn't actually get returned this way. Rewrite
571 * this when T31232 is taken care of (high-level redirect
576 public function getFinalUrl() {
577 $headers = $this->getResponseHeaders();
579 // return full url (fix for incorrect but handled relative location)
580 if ( isset( $headers['location'] ) ) {
581 $locations = $headers['location'];
583 $foundRelativeURI = false;
584 $countLocations = count( $locations );
586 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
587 $url = parse_url( $locations[$i] );
589 if ( isset( $url['host'] ) ) {
590 $domain = $url['scheme'] . '://' . $url['host'];
591 break; // found correct URI (with host)
593 $foundRelativeURI = true;
597 if ( !$foundRelativeURI ) {
598 return $locations[$countLocations - 1];
601 return $domain . $locations[$countLocations - 1];
603 $url = parse_url( $this->url
);
604 if ( isset( $url['host'] ) ) {
605 return $url['scheme'] . '://' . $url['host'] .
606 $locations[$countLocations - 1];
614 * Returns true if the backend can follow redirects. Overridden by the
618 public function canFollowRedirects() {
623 * Set information about the original request. This can be useful for
624 * endpoints/API modules which act as a proxy for some service, and
625 * throttling etc. needs to happen in that service.
626 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
628 * @param WebRequest|array $originalRequest When in array form, it's
629 * expected to have the keys 'ip' and 'userAgent'.
630 * @note IP/user agent is personally identifiable information, and should
631 * only be set when the privacy policy of the request target is
632 * compatible with that of the MediaWiki installation.
634 public function setOriginalRequest( $originalRequest ) {
635 if ( $originalRequest instanceof WebRequest
) {
637 'ip' => $originalRequest->getIP(),
638 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
641 !is_array( $originalRequest )
642 ||
array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
644 throw new InvalidArgumentException( __METHOD__
. ': $originalRequest must be a '
645 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
648 $this->reqHeaders
['X-Forwarded-For'] = $originalRequest['ip'];
649 $this->reqHeaders
['X-Original-User-Agent'] = $originalRequest['userAgent'];