3 * Various HTTP related functions.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
28 use MediaWiki\Logger\LoggerFactory
;
31 * Various HTTP related functions
35 static public $httpEngine = false;
38 * Perform an HTTP request
40 * @param string $method HTTP method. Usually GET/POST
41 * @param string $url Full URL to act on. If protocol-relative, will be expanded to an http:// URL
42 * @param array $options Options to pass to MWHttpRequest object.
43 * Possible keys for the array:
44 * - timeout Timeout length in seconds
45 * - connectTimeout Timeout for connection, in seconds (curl only)
46 * - postData An array of key-value pairs or a url-encoded form data
47 * - proxy The proxy to use.
48 * Otherwise it will use $wgHTTPProxy (if set)
49 * Otherwise it will use the environment variable "http_proxy" (if set)
50 * - noProxy Don't use any proxy at all. Takes precedence over proxy value(s).
51 * - sslVerifyHost Verify hostname against certificate
52 * - sslVerifyCert Verify SSL certificate
53 * - caInfo Provide CA information
54 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
55 * - followRedirects Whether to follow redirects (defaults to false).
56 * Note: this should only be used when the target URL is trusted,
57 * to avoid attacks on intranet services accessible by HTTP.
58 * - userAgent A user agent, if you want to override the default
59 * MediaWiki/$wgVersion
60 * @param string $caller The method making this request, for profiling
61 * @return string|bool (bool)false on failure or a string on success
63 public static function request( $method, $url, $options = array(), $caller = __METHOD__
) {
64 wfDebug( "HTTP: $method: $url\n" );
66 $options['method'] = strtoupper( $method );
68 if ( !isset( $options['timeout'] ) ) {
69 $options['timeout'] = 'default';
71 if ( !isset( $options['connectTimeout'] ) ) {
72 $options['connectTimeout'] = 'default';
75 $req = MWHttpRequest
::factory( $url, $options, $caller );
76 $status = $req->execute();
78 if ( $status->isOK() ) {
79 return $req->getContent();
81 $errors = $status->getErrorsByType( 'error' );
82 $logger = LoggerFactory
::getInstance( 'http' );
83 $logger->warning( $status->getWikiText(), array( 'caller' => $caller ) );
89 * Simple wrapper for Http::request( 'GET' )
90 * @see Http::request()
91 * @since 1.25 Second parameter $timeout removed. Second parameter
92 * is now $options which can be given a 'timeout'
95 * @param array $options
96 * @param string $caller The method making this request, for profiling
99 public static function get( $url, $options = array(), $caller = __METHOD__
) {
100 $args = func_get_args();
101 if ( isset( $args[1] ) && ( is_string( $args[1] ) ||
is_numeric( $args[1] ) ) ) {
102 // Second was used to be the timeout
103 // And third parameter used to be $options
104 wfWarn( "Second parameter should not be a timeout.", 2 );
105 $options = isset( $args[2] ) && is_array( $args[2] ) ?
107 $options['timeout'] = $args[1];
108 $caller = __METHOD__
;
110 return Http
::request( 'GET', $url, $options, $caller );
114 * Simple wrapper for Http::request( 'POST' )
115 * @see Http::request()
118 * @param array $options
119 * @param string $caller The method making this request, for profiling
122 public static function post( $url, $options = array(), $caller = __METHOD__
) {
123 return Http
::request( 'POST', $url, $options, $caller );
127 * Check if the URL can be served by localhost
129 * @param string $url Full url to check
132 public static function isLocalURL( $url ) {
133 global $wgCommandLineMode, $wgLocalVirtualHosts, $wgConf;
135 if ( $wgCommandLineMode ) {
141 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
144 $domainParts = explode( '.', $host );
145 // Check if this domain or any superdomain is listed as a local virtual host
146 $domainParts = array_reverse( $domainParts );
149 $countParts = count( $domainParts );
150 for ( $i = 0; $i < $countParts; $i++
) {
151 $domainPart = $domainParts[$i];
153 $domain = $domainPart;
155 $domain = $domainPart . '.' . $domain;
158 if ( in_array( $domain, $wgLocalVirtualHosts )
159 ||
$wgConf->isLocalVHost( $domain )
170 * A standard user-agent we can use for external requests.
173 public static function userAgent() {
175 return "MediaWiki/$wgVersion";
179 * Checks that the given URI is a valid one. Hardcoding the
180 * protocols, because we only want protocols that both cURL
183 * file:// should not be allowed here for security purpose (r67684)
185 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
187 * @param string $uri URI to check for validity
190 public static function isValidURI( $uri ) {
192 '/^https?:\/\/[^\/\s]\S*$/D',
199 * This wrapper class will call out to curl (if available) or fallback
200 * to regular PHP if necessary for handling internal HTTP requests.
202 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
203 * PHP's HTTP extension.
205 class MWHttpRequest
{
206 const SUPPORTS_FILE_POSTS
= false;
209 protected $timeout = 'default';
210 protected $headersOnly = null;
211 protected $postData = null;
212 protected $proxy = null;
213 protected $noProxy = false;
214 protected $sslVerifyHost = true;
215 protected $sslVerifyCert = true;
216 protected $caInfo = null;
217 protected $method = "GET";
218 protected $reqHeaders = array();
220 protected $parsedUrl;
222 protected $maxRedirects = 5;
223 protected $followRedirects = false;
228 protected $cookieJar;
230 protected $headerList = array();
231 protected $respVersion = "0.9";
232 protected $respStatus = "200 Ok";
233 protected $respHeaders = array();
245 protected $profileName;
248 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
249 * @param array $options (optional) extra params to pass (see Http::request())
250 * @param string $caller The method making this request, for profiling
251 * @param Profiler $profiler An instance of the profiler for profiling, or null
253 protected function __construct( $url, $options = array(), $caller = __METHOD__
, $profiler = null ) {
254 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
256 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
257 $this->parsedUrl
= wfParseUrl( $this->url
);
259 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
260 $this->status
= Status
::newFatal( 'http-invalid-url', $url );
262 $this->status
= Status
::newGood( 100 ); // continue
265 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
266 $this->timeout
= $options['timeout'];
268 $this->timeout
= $wgHTTPTimeout;
270 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
271 $this->connectTimeout
= $options['connectTimeout'];
273 $this->connectTimeout
= $wgHTTPConnectTimeout;
275 if ( isset( $options['userAgent'] ) ) {
276 $this->setUserAgent( $options['userAgent'] );
279 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
280 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
282 foreach ( $members as $o ) {
283 if ( isset( $options[$o] ) ) {
284 // ensure that MWHttpRequest::method is always
285 // uppercased. Bug 36137
286 if ( $o == 'method' ) {
287 $options[$o] = strtoupper( $options[$o] );
289 $this->$o = $options[$o];
293 if ( $this->noProxy
) {
294 $this->proxy
= ''; // noProxy takes precedence
297 // Profile based on what's calling us
298 $this->profiler
= $profiler;
299 $this->profileName
= $caller;
303 * Simple function to test if we can make any sort of requests at all, using
307 public static function canMakeRequests() {
308 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
312 * Generate a new request object
313 * @param string $url Url to use
314 * @param array $options (optional) extra params to pass (see Http::request())
315 * @param string $caller The method making this request, for profiling
316 * @throws MWException
317 * @return CurlHttpRequest|PhpHttpRequest
318 * @see MWHttpRequest::__construct
320 public static function factory( $url, $options = null, $caller = __METHOD__
) {
321 if ( !Http
::$httpEngine ) {
322 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
323 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
324 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
325 ' Http::$httpEngine is set to "curl"' );
328 switch ( Http
::$httpEngine ) {
330 return new CurlHttpRequest( $url, $options, $caller, Profiler
::instance() );
332 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
333 throw new MWException( __METHOD__
. ': allow_url_fopen ' .
334 'needs to be enabled for pure PHP http requests to ' .
335 'work. If possible, curl should be used instead. See ' .
336 'http://php.net/curl.'
339 return new PhpHttpRequest( $url, $options, $caller, Profiler
::instance() );
341 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
346 * Get the body, or content, of the response to the request
350 public function getContent() {
351 return $this->content
;
355 * Set the parameters of the request
358 * @todo overload the args param
360 public function setData( $args ) {
361 $this->postData
= $args;
365 * Take care of setting up the proxy (do nothing if "noProxy" is set)
369 public function proxySetup() {
372 // If there is an explicit proxy set and proxies are not disabled, then use it
373 if ( $this->proxy
&& !$this->noProxy
) {
377 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
378 // local URL and proxies are not disabled
379 if ( Http
::isLocalURL( $this->url
) ||
$this->noProxy
) {
381 } elseif ( $wgHTTPProxy ) {
382 $this->proxy
= $wgHTTPProxy;
383 } elseif ( getenv( "http_proxy" ) ) {
384 $this->proxy
= getenv( "http_proxy" );
392 public function setUserAgent( $UA ) {
393 $this->setHeader( 'User-Agent', $UA );
397 * Set an arbitrary header
398 * @param string $name
399 * @param string $value
401 public function setHeader( $name, $value ) {
402 // I feel like I should normalize the case here...
403 $this->reqHeaders
[$name] = $value;
407 * Get an array of the headers
410 public function getHeaderList() {
413 if ( $this->cookieJar
) {
414 $this->reqHeaders
['Cookie'] =
415 $this->cookieJar
->serializeToHttpRequest(
416 $this->parsedUrl
['path'],
417 $this->parsedUrl
['host']
421 foreach ( $this->reqHeaders
as $name => $value ) {
422 $list[] = "$name: $value";
429 * Set a read callback to accept data read from the HTTP request.
430 * By default, data is appended to an internal buffer which can be
431 * retrieved through $req->getContent().
433 * To handle data as it comes in -- especially for large files that
434 * would not fit in memory -- you can instead set your own callback,
435 * in the form function($resource, $buffer) where the first parameter
436 * is the low-level resource being read (implementation specific),
437 * and the second parameter is the data buffer.
439 * You MUST return the number of bytes handled in the buffer; if fewer
440 * bytes are reported handled than were passed to you, the HTTP fetch
443 * @param callable $callback
444 * @throws MWException
446 public function setCallback( $callback ) {
447 if ( !is_callable( $callback ) ) {
448 throw new MWException( 'Invalid MwHttpRequest callback' );
450 $this->callback
= $callback;
454 * A generic callback to read the body of the response from a remote
457 * @param resource $fh
458 * @param string $content
461 public function read( $fh, $content ) {
462 $this->content
.= $content;
463 return strlen( $content );
467 * Take care of whatever is necessary to perform the URI request.
471 public function execute() {
475 if ( strtoupper( $this->method
) == "HEAD" ) {
476 $this->headersOnly
= true;
479 $this->proxySetup(); // set up any proxy as needed
481 if ( !$this->callback
) {
482 $this->setCallback( array( $this, 'read' ) );
485 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
486 $this->setUserAgent( Http
::userAgent() );
492 * Parses the headers, including the HTTP status code and any
493 * Set-Cookie headers. This function expects the headers to be
494 * found in an array in the member variable headerList.
496 protected function parseHeader() {
500 foreach ( $this->headerList
as $header ) {
501 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
502 $this->respVersion
= $match[1];
503 $this->respStatus
= $match[2];
504 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
505 $last = count( $this->respHeaders
[$lastname] ) - 1;
506 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
507 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
508 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
509 $lastname = strtolower( $match[1] );
513 $this->parseCookies();
518 * Sets HTTPRequest status member to a fatal value with the error
519 * message if the returned integer value of the status code was
520 * not successful (< 300) or a redirect (>=300 and < 400). (see
521 * RFC2616, section 10,
522 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
523 * list of status codes.)
525 protected function setStatus() {
526 if ( !$this->respHeaders
) {
527 $this->parseHeader();
530 if ( (int)$this->respStatus
> 399 ) {
531 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
532 $this->status
->fatal( "http-bad-status", $code, $message );
537 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
538 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
539 * for a list of status codes.)
543 public function getStatus() {
544 if ( !$this->respHeaders
) {
545 $this->parseHeader();
548 return (int)$this->respStatus
;
552 * Returns true if the last status code was a redirect.
556 public function isRedirect() {
557 if ( !$this->respHeaders
) {
558 $this->parseHeader();
561 $status = (int)$this->respStatus
;
563 if ( $status >= 300 && $status <= 303 ) {
571 * Returns an associative array of response headers after the
572 * request has been executed. Because some headers
573 * (e.g. Set-Cookie) can appear more than once the, each value of
574 * the associative array is an array of the values given.
578 public function getResponseHeaders() {
579 if ( !$this->respHeaders
) {
580 $this->parseHeader();
583 return $this->respHeaders
;
587 * Returns the value of the given response header.
589 * @param string $header
592 public function getResponseHeader( $header ) {
593 if ( !$this->respHeaders
) {
594 $this->parseHeader();
597 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
598 $v = $this->respHeaders
[strtolower( $header )];
599 return $v[count( $v ) - 1];
606 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
608 * @param CookieJar $jar
610 public function setCookieJar( $jar ) {
611 $this->cookieJar
= $jar;
615 * Returns the cookie jar in use.
619 public function getCookieJar() {
620 if ( !$this->respHeaders
) {
621 $this->parseHeader();
624 return $this->cookieJar
;
628 * Sets a cookie. Used before a request to set up any individual
629 * cookies. Used internally after a request to parse the
630 * Set-Cookie headers.
632 * @param string $name
633 * @param mixed $value
636 public function setCookie( $name, $value = null, $attr = null ) {
637 if ( !$this->cookieJar
) {
638 $this->cookieJar
= new CookieJar
;
641 $this->cookieJar
->setCookie( $name, $value, $attr );
645 * Parse the cookies in the response headers and store them in the cookie jar.
647 protected function parseCookies() {
649 if ( !$this->cookieJar
) {
650 $this->cookieJar
= new CookieJar
;
653 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
654 $url = parse_url( $this->getFinalUrl() );
655 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
656 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
663 * Returns the final URL after all redirections.
665 * Relative values of the "Location" header are incorrect as
666 * stated in RFC, however they do happen and modern browsers
667 * support them. This function loops backwards through all
668 * locations in order to build the proper absolute URI - Marooned
671 * Note that the multiple Location: headers are an artifact of
672 * CURL -- they shouldn't actually get returned this way. Rewrite
673 * this when bug 29232 is taken care of (high-level redirect
678 public function getFinalUrl() {
679 $headers = $this->getResponseHeaders();
681 //return full url (fix for incorrect but handled relative location)
682 if ( isset( $headers['location'] ) ) {
683 $locations = $headers['location'];
685 $foundRelativeURI = false;
686 $countLocations = count( $locations );
688 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
689 $url = parse_url( $locations[$i] );
691 if ( isset( $url['host'] ) ) {
692 $domain = $url['scheme'] . '://' . $url['host'];
693 break; //found correct URI (with host)
695 $foundRelativeURI = true;
699 if ( $foundRelativeURI ) {
701 return $domain . $locations[$countLocations - 1];
703 $url = parse_url( $this->url
);
704 if ( isset( $url['host'] ) ) {
705 return $url['scheme'] . '://' . $url['host'] .
706 $locations[$countLocations - 1];
710 return $locations[$countLocations - 1];
718 * Returns true if the backend can follow redirects. Overridden by the
722 public function canFollowRedirects() {
728 * MWHttpRequest implemented using internal curl compiled into PHP
730 class CurlHttpRequest
extends MWHttpRequest
{
731 const SUPPORTS_FILE_POSTS
= true;
733 protected $curlOptions = array();
734 protected $headerText = "";
737 * @param resource $fh
738 * @param string $content
741 protected function readHeader( $fh, $content ) {
742 $this->headerText
.= $content;
743 return strlen( $content );
746 public function execute() {
750 if ( !$this->status
->isOK() ) {
751 return $this->status
;
754 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
755 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
757 // Only supported in curl >= 7.16.2
758 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
759 $this->curlOptions
[CURLOPT_CONNECTTIMEOUT_MS
] = $this->connectTimeout
* 1000;
762 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
763 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
764 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
765 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
766 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
768 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
770 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost ?
2 : 0;
771 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
773 if ( $this->caInfo
) {
774 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
777 if ( $this->headersOnly
) {
778 $this->curlOptions
[CURLOPT_NOBODY
] = true;
779 $this->curlOptions
[CURLOPT_HEADER
] = true;
780 } elseif ( $this->method
== 'POST' ) {
781 $this->curlOptions
[CURLOPT_POST
] = true;
782 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
783 // Suppress 'Expect: 100-continue' header, as some servers
784 // will reject it with a 417 and Curl won't auto retry
785 // with HTTP 1.0 fallback
786 $this->reqHeaders
['Expect'] = '';
788 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
791 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
793 $curlHandle = curl_init( $this->url
);
795 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
796 throw new MWException( "Error setting curl options." );
799 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
800 MediaWiki\
suppressWarnings();
801 if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
802 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
803 "Probably safe_mode or open_basedir is set.\n" );
804 // Continue the processing. If it were in curl_setopt_array,
805 // processing would have halted on its entry
807 MediaWiki\restoreWarnings
();
810 if ( $this->profiler
) {
811 $profileSection = $this->profiler
->scopedProfileIn(
812 __METHOD__
. '-' . $this->profileName
816 $curlRes = curl_exec( $curlHandle );
817 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED
) {
818 $this->status
->fatal( 'http-timed-out', $this->url
);
819 } elseif ( $curlRes === false ) {
820 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
822 $this->headerList
= explode( "\r\n", $this->headerText
);
825 curl_close( $curlHandle );
827 if ( $this->profiler
) {
828 $this->profiler
->scopedProfileOut( $profileSection );
831 $this->parseHeader();
834 return $this->status
;
840 public function canFollowRedirects() {
841 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
842 wfDebug( "Cannot follow redirects in safe mode\n" );
846 $curlVersionInfo = curl_version();
847 if ( $curlVersionInfo['version_number'] < 0x071304 ) {
848 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
856 class PhpHttpRequest
extends MWHttpRequest
{
862 protected function urlToTcp( $url ) {
863 $parsedUrl = parse_url( $url );
865 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
868 public function execute() {
872 if ( is_array( $this->postData
) ) {
873 $this->postData
= wfArrayToCgi( $this->postData
);
876 if ( $this->parsedUrl
['scheme'] != 'http'
877 && $this->parsedUrl
['scheme'] != 'https' ) {
878 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
881 $this->reqHeaders
['Accept'] = "*/*";
882 $this->reqHeaders
['Connection'] = 'Close';
883 if ( $this->method
== 'POST' ) {
884 // Required for HTTP 1.0 POSTs
885 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
886 if ( !isset( $this->reqHeaders
['Content-Type'] ) ) {
887 $this->reqHeaders
['Content-Type'] = "application/x-www-form-urlencoded";
891 // Set up PHP stream context
894 'method' => $this->method
,
895 'header' => implode( "\r\n", $this->getHeaderList() ),
896 'protocol_version' => '1.1',
897 'max_redirects' => $this->followRedirects ?
$this->maxRedirects
: 0,
898 'ignore_errors' => true,
899 'timeout' => $this->timeout
,
900 // Curl options in case curlwrappers are installed
901 'curl_verify_ssl_host' => $this->sslVerifyHost ?
2 : 0,
902 'curl_verify_ssl_peer' => $this->sslVerifyCert
,
905 'verify_peer' => $this->sslVerifyCert
,
906 'SNI_enabled' => true,
910 if ( $this->proxy
) {
911 $options['http']['proxy'] = $this->urlToTCP( $this->proxy
);
912 $options['http']['request_fulluri'] = true;
915 if ( $this->postData
) {
916 $options['http']['content'] = $this->postData
;
919 if ( $this->sslVerifyHost
) {
920 // PHP 5.6.0 deprecates CN_match, in favour of peer_name which
921 // actually checks SubjectAltName properly.
922 if ( version_compare( PHP_VERSION
, '5.6.0', '>=' ) ) {
923 $options['ssl']['peer_name'] = $this->parsedUrl
['host'];
925 $options['ssl']['CN_match'] = $this->parsedUrl
['host'];
929 if ( is_dir( $this->caInfo
) ) {
930 $options['ssl']['capath'] = $this->caInfo
;
931 } elseif ( is_file( $this->caInfo
) ) {
932 $options['ssl']['cafile'] = $this->caInfo
;
933 } elseif ( $this->caInfo
) {
934 throw new MWException( "Invalid CA info passed: {$this->caInfo}" );
937 $context = stream_context_create( $options );
939 $this->headerList
= array();
945 if ( $this->profiler
) {
946 $profileSection = $this->profiler
->scopedProfileIn(
947 __METHOD__
. '-' . $this->profileName
952 MediaWiki\
suppressWarnings();
953 $fh = fopen( $url, "r", false, $context );
954 MediaWiki\restoreWarnings
();
957 // HACK for instant commons.
958 // If we are contacting (commons|upload).wikimedia.org
959 // try again with CN_match for en.wikipedia.org
960 // as php does not handle SubjectAltName properly
961 // prior to "peer_name" option in php 5.6
962 if ( isset( $options['ssl']['CN_match'] )
963 && ( $options['ssl']['CN_match'] === 'commons.wikimedia.org'
964 ||
$options['ssl']['CN_match'] === 'upload.wikimedia.org' )
966 $options['ssl']['CN_match'] = 'en.wikipedia.org';
967 $context = stream_context_create( $options );
973 $result = stream_get_meta_data( $fh );
974 $this->headerList
= $result['wrapper_data'];
975 $this->parseHeader();
977 if ( !$this->followRedirects
) {
981 # Handle manual redirection
982 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
985 # Check security of URL
986 $url = $this->getResponseHeader( "Location" );
988 if ( !Http
::isValidURI( $url ) ) {
989 wfDebug( __METHOD__
. ": insecure redirection\n" );
993 if ( $this->profiler
) {
994 $this->profiler
->scopedProfileOut( $profileSection );
999 if ( $fh === false ) {
1000 $this->status
->fatal( 'http-request-error' );
1001 return $this->status
;
1004 if ( $result['timed_out'] ) {
1005 $this->status
->fatal( 'http-timed-out', $this->url
);
1006 return $this->status
;
1009 // If everything went OK, or we received some error code
1010 // get the response body content.
1011 if ( $this->status
->isOK() ||
(int)$this->respStatus
>= 300 ) {
1012 while ( !feof( $fh ) ) {
1013 $buf = fread( $fh, 8192 );
1015 if ( $buf === false ) {
1016 $this->status
->fatal( 'http-read-error' );
1020 if ( strlen( $buf ) ) {
1021 call_user_func( $this->callback
, $fh, $buf );
1027 return $this->status
;