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\Logger\LoggerFactory
;
22 use Psr\Log\LoggerInterface
;
23 use Psr\Log\LoggerAwareInterface
;
24 use Psr\Log\NullLogger
;
27 * This wrapper class will call out to curl (if available) or fallback
28 * to regular PHP if necessary for handling internal HTTP requests.
30 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
31 * PHP's HTTP extension.
33 class MWHttpRequest
implements LoggerAwareInterface
{
34 const SUPPORTS_FILE_POSTS
= false;
37 protected $timeout = 'default';
38 protected $headersOnly = null;
39 protected $postData = null;
40 protected $proxy = null;
41 protected $noProxy = false;
42 protected $sslVerifyHost = true;
43 protected $sslVerifyCert = true;
44 protected $caInfo = null;
45 protected $method = "GET";
46 protected $reqHeaders = [];
51 protected $maxRedirects = 5;
52 protected $followRedirects = false;
53 protected $connectTimeout;
60 protected $headerList = [];
61 protected $respVersion = "0.9";
62 protected $respStatus = "200 Ok";
63 protected $respHeaders = [];
65 /** @var StatusValue */
76 protected $profileName;
79 * @var LoggerInterface;
84 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
85 * @param array $options (optional) extra params to pass (see Http::request())
86 * @param string $caller The method making this request, for profiling
87 * @param Profiler $profiler An instance of the profiler for profiling, or null
89 protected function __construct(
90 $url, $options = [], $caller = __METHOD__
, $profiler = null
92 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
94 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
95 $this->parsedUrl
= wfParseUrl( $this->url
);
97 if ( isset( $options['logger'] ) ) {
98 $this->logger
= $options['logger'];
100 $this->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 * @param string $url Url to use
174 * @param array $options (optional) extra params to pass (see Http::request())
175 * @param string $caller The method making this request, for profiling
176 * @throws DomainException
177 * @return CurlHttpRequest|PhpHttpRequest
178 * @see MWHttpRequest::__construct
180 public static function factory( $url, $options = null, $caller = __METHOD__
) {
181 if ( !Http
::$httpEngine ) {
182 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
183 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
184 throw new DomainException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
185 ' Http::$httpEngine is set to "curl"' );
188 if ( !is_array( $options ) ) {
192 if ( !isset( $options['logger'] ) ) {
193 $options['logger'] = LoggerFactory
::getInstance( 'http' );
196 switch ( Http
::$httpEngine ) {
198 return new CurlHttpRequest( $url, $options, $caller, Profiler
::instance() );
200 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
201 throw new DomainException( __METHOD__
. ': allow_url_fopen ' .
202 'needs to be enabled for pure PHP http requests to ' .
203 'work. If possible, curl should be used instead. See ' .
204 'http://php.net/curl.'
207 return new PhpHttpRequest( $url, $options, $caller, Profiler
::instance() );
209 throw new DomainException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
214 * Get the body, or content, of the response to the request
218 public function getContent() {
219 return $this->content
;
223 * Set the parameters of the request
226 * @todo overload the args param
228 public function setData( $args ) {
229 $this->postData
= $args;
233 * Take care of setting up the proxy (do nothing if "noProxy" is set)
237 protected function proxySetup() {
238 // If there is an explicit proxy set and proxies are not disabled, then use it
239 if ( $this->proxy
&& !$this->noProxy
) {
243 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
244 // local URL and proxies are not disabled
245 if ( self
::isLocalURL( $this->url
) ||
$this->noProxy
) {
248 $this->proxy
= Http
::getProxy();
253 * Check if the URL can be served by localhost
255 * @param string $url Full url to check
258 private static function isLocalURL( $url ) {
259 global $wgCommandLineMode, $wgLocalVirtualHosts;
261 if ( $wgCommandLineMode ) {
267 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
270 $domainParts = explode( '.', $host );
271 // Check if this domain or any superdomain is listed as a local virtual host
272 $domainParts = array_reverse( $domainParts );
275 $countParts = count( $domainParts );
276 for ( $i = 0; $i < $countParts; $i++
) {
277 $domainPart = $domainParts[$i];
279 $domain = $domainPart;
281 $domain = $domainPart . '.' . $domain;
284 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
297 public function setUserAgent( $UA ) {
298 $this->setHeader( 'User-Agent', $UA );
302 * Set an arbitrary header
303 * @param string $name
304 * @param string $value
306 public function setHeader( $name, $value ) {
307 // I feel like I should normalize the case here...
308 $this->reqHeaders
[$name] = $value;
312 * Get an array of the headers
315 protected function getHeaderList() {
318 if ( $this->cookieJar
) {
319 $this->reqHeaders
['Cookie'] =
320 $this->cookieJar
->serializeToHttpRequest(
321 $this->parsedUrl
['path'],
322 $this->parsedUrl
['host']
326 foreach ( $this->reqHeaders
as $name => $value ) {
327 $list[] = "$name: $value";
334 * Set a read callback to accept data read from the HTTP request.
335 * By default, data is appended to an internal buffer which can be
336 * retrieved through $req->getContent().
338 * To handle data as it comes in -- especially for large files that
339 * would not fit in memory -- you can instead set your own callback,
340 * in the form function($resource, $buffer) where the first parameter
341 * is the low-level resource being read (implementation specific),
342 * and the second parameter is the data buffer.
344 * You MUST return the number of bytes handled in the buffer; if fewer
345 * bytes are reported handled than were passed to you, the HTTP fetch
348 * @param callable|null $callback
349 * @throws InvalidArgumentException
351 public function setCallback( $callback ) {
352 if ( is_null( $callback ) ) {
353 $callback = [ $this, 'read' ];
354 } elseif ( !is_callable( $callback ) ) {
355 throw new InvalidArgumentException( __METHOD__
. ': invalid callback' );
357 $this->callback
= $callback;
361 * A generic callback to read the body of the response from a remote
364 * @param resource $fh
365 * @param string $content
369 public function read( $fh, $content ) {
370 $this->content
.= $content;
371 return strlen( $content );
375 * Take care of whatever is necessary to perform the URI request.
377 * @return StatusValue
378 * @note currently returns Status for B/C
380 public function execute() {
381 throw new LogicException( 'children must override this' );
384 protected function prepare() {
387 if ( strtoupper( $this->method
) == "HEAD" ) {
388 $this->headersOnly
= true;
391 $this->proxySetup(); // set up any proxy as needed
393 if ( !$this->callback
) {
394 $this->setCallback( null );
397 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
398 $this->setUserAgent( Http
::userAgent() );
403 * Parses the headers, including the HTTP status code and any
404 * Set-Cookie headers. This function expects the headers to be
405 * found in an array in the member variable headerList.
407 protected function parseHeader() {
410 foreach ( $this->headerList
as $header ) {
411 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
412 $this->respVersion
= $match[1];
413 $this->respStatus
= $match[2];
414 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
415 $last = count( $this->respHeaders
[$lastname] ) - 1;
416 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
417 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
418 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
419 $lastname = strtolower( $match[1] );
423 $this->parseCookies();
427 * Sets HTTPRequest status member to a fatal value with the error
428 * message if the returned integer value of the status code was
429 * not successful (< 300) or a redirect (>=300 and < 400). (see
430 * RFC2616, section 10,
431 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
432 * list of status codes.)
434 protected function setStatus() {
435 if ( !$this->respHeaders
) {
436 $this->parseHeader();
439 if ( (int)$this->respStatus
> 399 ) {
440 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
441 $this->status
->fatal( "http-bad-status", $code, $message );
446 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
447 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
448 * for a list of status codes.)
452 public function getStatus() {
453 if ( !$this->respHeaders
) {
454 $this->parseHeader();
457 return (int)$this->respStatus
;
461 * Returns true if the last status code was a redirect.
465 public function isRedirect() {
466 if ( !$this->respHeaders
) {
467 $this->parseHeader();
470 $status = (int)$this->respStatus
;
472 if ( $status >= 300 && $status <= 303 ) {
480 * Returns an associative array of response headers after the
481 * request has been executed. Because some headers
482 * (e.g. Set-Cookie) can appear more than once the, each value of
483 * the associative array is an array of the values given.
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
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( $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, $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 ) {
614 return $domain . $locations[$countLocations - 1];
616 $url = parse_url( $this->url
);
617 if ( isset( $url['host'] ) ) {
618 return $url['scheme'] . '://' . $url['host'] .
619 $locations[$countLocations - 1];
623 return $locations[$countLocations - 1];
631 * Returns true if the backend can follow redirects. Overridden by the
635 public function canFollowRedirects() {
640 * Set information about the original request. This can be useful for
641 * endpoints/API modules which act as a proxy for some service, and
642 * throttling etc. needs to happen in that service.
643 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
645 * @param WebRequest|array $originalRequest When in array form, it's
646 * expected to have the keys 'ip' and 'userAgent'.
647 * @note IP/user agent is personally identifiable information, and should
648 * only be set when the privacy policy of the request target is
649 * compatible with that of the MediaWiki installation.
651 public function setOriginalRequest( $originalRequest ) {
652 if ( $originalRequest instanceof WebRequest
) {
654 'ip' => $originalRequest->getIP(),
655 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
658 !is_array( $originalRequest )
659 ||
array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
661 throw new InvalidArgumentException( __METHOD__
. ': $originalRequest must be a '
662 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
665 $this->reqHeaders
['X-Forwarded-For'] = $originalRequest['ip'];
666 $this->reqHeaders
['X-Original-User-Agent'] = $originalRequest['userAgent'];