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',
198 * Gets the relevant proxy from $wgHTTPProxy/http_proxy (when set).
200 * @return mixed The proxy address or an empty string if not set.
202 public static function getProxy() {
205 if ( $wgHTTPProxy ) {
209 $envHttpProxy = getenv( "http_proxy" );
210 if ( $envHttpProxy ) {
211 return $envHttpProxy;
219 * This wrapper class will call out to curl (if available) or fallback
220 * to regular PHP if necessary for handling internal HTTP requests.
222 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
223 * PHP's HTTP extension.
225 class MWHttpRequest
{
226 const SUPPORTS_FILE_POSTS
= false;
229 protected $timeout = 'default';
230 protected $headersOnly = null;
231 protected $postData = null;
232 protected $proxy = null;
233 protected $noProxy = false;
234 protected $sslVerifyHost = true;
235 protected $sslVerifyCert = true;
236 protected $caInfo = null;
237 protected $method = "GET";
238 protected $reqHeaders = array();
240 protected $parsedUrl;
242 protected $maxRedirects = 5;
243 protected $followRedirects = false;
248 protected $cookieJar;
250 protected $headerList = array();
251 protected $respVersion = "0.9";
252 protected $respStatus = "200 Ok";
253 protected $respHeaders = array();
265 protected $profileName;
268 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
269 * @param array $options (optional) extra params to pass (see Http::request())
270 * @param string $caller The method making this request, for profiling
271 * @param Profiler $profiler An instance of the profiler for profiling, or null
273 protected function __construct(
274 $url, $options = array(), $caller = __METHOD__
, $profiler = null
276 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
278 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
279 $this->parsedUrl
= wfParseUrl( $this->url
);
281 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
282 $this->status
= Status
::newFatal( 'http-invalid-url', $url );
284 $this->status
= Status
::newGood( 100 ); // continue
287 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
288 $this->timeout
= $options['timeout'];
290 $this->timeout
= $wgHTTPTimeout;
292 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
293 $this->connectTimeout
= $options['connectTimeout'];
295 $this->connectTimeout
= $wgHTTPConnectTimeout;
297 if ( isset( $options['userAgent'] ) ) {
298 $this->setUserAgent( $options['userAgent'] );
301 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
302 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
304 foreach ( $members as $o ) {
305 if ( isset( $options[$o] ) ) {
306 // ensure that MWHttpRequest::method is always
307 // uppercased. Bug 36137
308 if ( $o == 'method' ) {
309 $options[$o] = strtoupper( $options[$o] );
311 $this->$o = $options[$o];
315 if ( $this->noProxy
) {
316 $this->proxy
= ''; // noProxy takes precedence
319 // Profile based on what's calling us
320 $this->profiler
= $profiler;
321 $this->profileName
= $caller;
325 * Simple function to test if we can make any sort of requests at all, using
329 public static function canMakeRequests() {
330 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
334 * Generate a new request object
335 * @param string $url Url to use
336 * @param array $options (optional) extra params to pass (see Http::request())
337 * @param string $caller The method making this request, for profiling
338 * @throws MWException
339 * @return CurlHttpRequest|PhpHttpRequest
340 * @see MWHttpRequest::__construct
342 public static function factory( $url, $options = null, $caller = __METHOD__
) {
343 if ( !Http
::$httpEngine ) {
344 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
345 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
346 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
347 ' Http::$httpEngine is set to "curl"' );
350 switch ( Http
::$httpEngine ) {
352 return new CurlHttpRequest( $url, $options, $caller, Profiler
::instance() );
354 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
355 throw new MWException( __METHOD__
. ': allow_url_fopen ' .
356 'needs to be enabled for pure PHP http requests to ' .
357 'work. If possible, curl should be used instead. See ' .
358 'http://php.net/curl.'
361 return new PhpHttpRequest( $url, $options, $caller, Profiler
::instance() );
363 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
368 * Get the body, or content, of the response to the request
372 public function getContent() {
373 return $this->content
;
377 * Set the parameters of the request
380 * @todo overload the args param
382 public function setData( $args ) {
383 $this->postData
= $args;
387 * Take care of setting up the proxy (do nothing if "noProxy" is set)
391 public function proxySetup() {
392 // If there is an explicit proxy set and proxies are not disabled, then use it
393 if ( $this->proxy
&& !$this->noProxy
) {
397 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
398 // local URL and proxies are not disabled
399 if ( Http
::isLocalURL( $this->url
) ||
$this->noProxy
) {
402 $this->proxy
= Http
::getProxy();
410 public function setUserAgent( $UA ) {
411 $this->setHeader( 'User-Agent', $UA );
415 * Set an arbitrary header
416 * @param string $name
417 * @param string $value
419 public function setHeader( $name, $value ) {
420 // I feel like I should normalize the case here...
421 $this->reqHeaders
[$name] = $value;
425 * Get an array of the headers
428 public function getHeaderList() {
431 if ( $this->cookieJar
) {
432 $this->reqHeaders
['Cookie'] =
433 $this->cookieJar
->serializeToHttpRequest(
434 $this->parsedUrl
['path'],
435 $this->parsedUrl
['host']
439 foreach ( $this->reqHeaders
as $name => $value ) {
440 $list[] = "$name: $value";
447 * Set a read callback to accept data read from the HTTP request.
448 * By default, data is appended to an internal buffer which can be
449 * retrieved through $req->getContent().
451 * To handle data as it comes in -- especially for large files that
452 * would not fit in memory -- you can instead set your own callback,
453 * in the form function($resource, $buffer) where the first parameter
454 * is the low-level resource being read (implementation specific),
455 * and the second parameter is the data buffer.
457 * You MUST return the number of bytes handled in the buffer; if fewer
458 * bytes are reported handled than were passed to you, the HTTP fetch
461 * @param callable $callback
462 * @throws MWException
464 public function setCallback( $callback ) {
465 if ( !is_callable( $callback ) ) {
466 throw new MWException( 'Invalid MwHttpRequest callback' );
468 $this->callback
= $callback;
472 * A generic callback to read the body of the response from a remote
475 * @param resource $fh
476 * @param string $content
479 public function read( $fh, $content ) {
480 $this->content
.= $content;
481 return strlen( $content );
485 * Take care of whatever is necessary to perform the URI request.
489 public function execute() {
493 if ( strtoupper( $this->method
) == "HEAD" ) {
494 $this->headersOnly
= true;
497 $this->proxySetup(); // set up any proxy as needed
499 if ( !$this->callback
) {
500 $this->setCallback( array( $this, 'read' ) );
503 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
504 $this->setUserAgent( Http
::userAgent() );
510 * Parses the headers, including the HTTP status code and any
511 * Set-Cookie headers. This function expects the headers to be
512 * found in an array in the member variable headerList.
514 protected function parseHeader() {
518 foreach ( $this->headerList
as $header ) {
519 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
520 $this->respVersion
= $match[1];
521 $this->respStatus
= $match[2];
522 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
523 $last = count( $this->respHeaders
[$lastname] ) - 1;
524 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
525 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
526 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
527 $lastname = strtolower( $match[1] );
531 $this->parseCookies();
536 * Sets HTTPRequest status member to a fatal value with the error
537 * message if the returned integer value of the status code was
538 * not successful (< 300) or a redirect (>=300 and < 400). (see
539 * RFC2616, section 10,
540 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
541 * list of status codes.)
543 protected function setStatus() {
544 if ( !$this->respHeaders
) {
545 $this->parseHeader();
548 if ( (int)$this->respStatus
> 399 ) {
549 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
550 $this->status
->fatal( "http-bad-status", $code, $message );
555 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
556 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
557 * for a list of status codes.)
561 public function getStatus() {
562 if ( !$this->respHeaders
) {
563 $this->parseHeader();
566 return (int)$this->respStatus
;
570 * Returns true if the last status code was a redirect.
574 public function isRedirect() {
575 if ( !$this->respHeaders
) {
576 $this->parseHeader();
579 $status = (int)$this->respStatus
;
581 if ( $status >= 300 && $status <= 303 ) {
589 * Returns an associative array of response headers after the
590 * request has been executed. Because some headers
591 * (e.g. Set-Cookie) can appear more than once the, each value of
592 * the associative array is an array of the values given.
596 public function getResponseHeaders() {
597 if ( !$this->respHeaders
) {
598 $this->parseHeader();
601 return $this->respHeaders
;
605 * Returns the value of the given response header.
607 * @param string $header
610 public function getResponseHeader( $header ) {
611 if ( !$this->respHeaders
) {
612 $this->parseHeader();
615 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
616 $v = $this->respHeaders
[strtolower( $header )];
617 return $v[count( $v ) - 1];
624 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
626 * @param CookieJar $jar
628 public function setCookieJar( $jar ) {
629 $this->cookieJar
= $jar;
633 * Returns the cookie jar in use.
637 public function getCookieJar() {
638 if ( !$this->respHeaders
) {
639 $this->parseHeader();
642 return $this->cookieJar
;
646 * Sets a cookie. Used before a request to set up any individual
647 * cookies. Used internally after a request to parse the
648 * Set-Cookie headers.
650 * @param string $name
651 * @param mixed $value
654 public function setCookie( $name, $value = null, $attr = null ) {
655 if ( !$this->cookieJar
) {
656 $this->cookieJar
= new CookieJar
;
659 $this->cookieJar
->setCookie( $name, $value, $attr );
663 * Parse the cookies in the response headers and store them in the cookie jar.
665 protected function parseCookies() {
667 if ( !$this->cookieJar
) {
668 $this->cookieJar
= new CookieJar
;
671 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
672 $url = parse_url( $this->getFinalUrl() );
673 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
674 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
681 * Returns the final URL after all redirections.
683 * Relative values of the "Location" header are incorrect as
684 * stated in RFC, however they do happen and modern browsers
685 * support them. This function loops backwards through all
686 * locations in order to build the proper absolute URI - Marooned
689 * Note that the multiple Location: headers are an artifact of
690 * CURL -- they shouldn't actually get returned this way. Rewrite
691 * this when bug 29232 is taken care of (high-level redirect
696 public function getFinalUrl() {
697 $headers = $this->getResponseHeaders();
699 // return full url (fix for incorrect but handled relative location)
700 if ( isset( $headers['location'] ) ) {
701 $locations = $headers['location'];
703 $foundRelativeURI = false;
704 $countLocations = count( $locations );
706 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
707 $url = parse_url( $locations[$i] );
709 if ( isset( $url['host'] ) ) {
710 $domain = $url['scheme'] . '://' . $url['host'];
711 break; // found correct URI (with host)
713 $foundRelativeURI = true;
717 if ( $foundRelativeURI ) {
719 return $domain . $locations[$countLocations - 1];
721 $url = parse_url( $this->url
);
722 if ( isset( $url['host'] ) ) {
723 return $url['scheme'] . '://' . $url['host'] .
724 $locations[$countLocations - 1];
728 return $locations[$countLocations - 1];
736 * Returns true if the backend can follow redirects. Overridden by the
740 public function canFollowRedirects() {
746 * MWHttpRequest implemented using internal curl compiled into PHP
748 class CurlHttpRequest
extends MWHttpRequest
{
749 const SUPPORTS_FILE_POSTS
= true;
751 protected $curlOptions = array();
752 protected $headerText = "";
755 * @param resource $fh
756 * @param string $content
759 protected function readHeader( $fh, $content ) {
760 $this->headerText
.= $content;
761 return strlen( $content );
764 public function execute() {
768 if ( !$this->status
->isOK() ) {
769 return $this->status
;
772 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
773 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
775 // Only supported in curl >= 7.16.2
776 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
777 $this->curlOptions
[CURLOPT_CONNECTTIMEOUT_MS
] = $this->connectTimeout
* 1000;
780 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
781 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
782 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
783 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
784 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
786 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
788 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost ?
2 : 0;
789 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
791 if ( $this->caInfo
) {
792 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
795 if ( $this->headersOnly
) {
796 $this->curlOptions
[CURLOPT_NOBODY
] = true;
797 $this->curlOptions
[CURLOPT_HEADER
] = true;
798 } elseif ( $this->method
== 'POST' ) {
799 $this->curlOptions
[CURLOPT_POST
] = true;
800 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
801 // Suppress 'Expect: 100-continue' header, as some servers
802 // will reject it with a 417 and Curl won't auto retry
803 // with HTTP 1.0 fallback
804 $this->reqHeaders
['Expect'] = '';
806 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
809 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
811 $curlHandle = curl_init( $this->url
);
813 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
814 throw new MWException( "Error setting curl options." );
817 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
818 MediaWiki\
suppressWarnings();
819 if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
820 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
821 "Probably safe_mode or open_basedir is set.\n" );
822 // Continue the processing. If it were in curl_setopt_array,
823 // processing would have halted on its entry
825 MediaWiki\restoreWarnings
();
828 if ( $this->profiler
) {
829 $profileSection = $this->profiler
->scopedProfileIn(
830 __METHOD__
. '-' . $this->profileName
834 $curlRes = curl_exec( $curlHandle );
835 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED
) {
836 $this->status
->fatal( 'http-timed-out', $this->url
);
837 } elseif ( $curlRes === false ) {
838 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
840 $this->headerList
= explode( "\r\n", $this->headerText
);
843 curl_close( $curlHandle );
845 if ( $this->profiler
) {
846 $this->profiler
->scopedProfileOut( $profileSection );
849 $this->parseHeader();
852 return $this->status
;
858 public function canFollowRedirects() {
859 $curlVersionInfo = curl_version();
860 if ( $curlVersionInfo['version_number'] < 0x071304 ) {
861 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
865 if ( version_compare( PHP_VERSION
, '5.6.0', '<' ) ) {
866 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
867 wfDebug( "Cannot follow redirects in safe mode\n" );
876 class PhpHttpRequest
extends MWHttpRequest
{
878 private $fopenErrors = array();
884 protected function urlToTcp( $url ) {
885 $parsedUrl = parse_url( $url );
887 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
891 * Returns an array with a 'capath' or 'cafile' key
892 * that is suitable to be merged into the 'ssl' sub-array of
893 * a stream context options array.
894 * Uses the 'caInfo' option of the class if it is provided, otherwise uses the system
895 * default CA bundle if PHP supports that, or searches a few standard locations.
897 * @throws DomainException
899 protected function getCertOptions() {
900 $certOptions = array();
901 $certLocations = array();
902 if ( $this->caInfo
) {
903 $certLocations = array( 'manual' => $this->caInfo
);
904 } elseif ( version_compare( PHP_VERSION
, '5.6.0', '<' ) ) {
905 // @codingStandardsIgnoreStart Generic.Files.LineLength
906 // Default locations, based on
907 // https://www.happyassassin.net/2015/01/12/a-note-about-ssltls-trusted-certificate-stores-and-platforms/
908 // PHP 5.5 and older doesn't have any defaults, so we try to guess ourselves.
909 // PHP 5.6+ gets the CA location from OpenSSL as long as it is not set manually,
910 // so we should leave capath/cafile empty there.
911 // @codingStandardsIgnoreEnd
912 $certLocations = array_filter( array(
913 getenv( 'SSL_CERT_DIR' ),
914 getenv( 'SSL_CERT_PATH' ),
915 '/etc/pki/tls/certs/ca-bundle.crt', # Fedora et al
916 '/etc/ssl/certs', # Debian et al
917 '/etc/pki/tls/certs/ca-bundle.trust.crt',
918 '/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem',
919 '/System/Library/OpenSSL', # OSX
923 foreach ( $certLocations as $key => $cert ) {
924 if ( is_dir( $cert ) ) {
925 $certOptions['capath'] = $cert;
927 } elseif ( is_file( $cert ) ) {
928 $certOptions['cafile'] = $cert;
930 } elseif ( $key === 'manual' ) {
931 // fail more loudly if a cert path was manually configured and it is not valid
932 throw new DomainException( "Invalid CA info passed: $cert" );
940 * Custom error handler for dealing with fopen() errors.
941 * fopen() tends to fire multiple errors in succession, and the last one
942 * is completely useless (something like "fopen: failed to open stream")
943 * so normal methods of handling errors programmatically
944 * like get_last_error() don't work.
946 public function errorHandler( $errno, $errstr ) {
947 $n = count( $this->fopenErrors
) +
1;
948 $this->fopenErrors +
= array( "errno$n" => $errno, "errstr$n" => $errstr );
951 public function execute() {
955 if ( is_array( $this->postData
) ) {
956 $this->postData
= wfArrayToCgi( $this->postData
);
959 if ( $this->parsedUrl
['scheme'] != 'http'
960 && $this->parsedUrl
['scheme'] != 'https' ) {
961 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
964 $this->reqHeaders
['Accept'] = "*/*";
965 $this->reqHeaders
['Connection'] = 'Close';
966 if ( $this->method
== 'POST' ) {
967 // Required for HTTP 1.0 POSTs
968 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
969 if ( !isset( $this->reqHeaders
['Content-Type'] ) ) {
970 $this->reqHeaders
['Content-Type'] = "application/x-www-form-urlencoded";
974 // Set up PHP stream context
977 'method' => $this->method
,
978 'header' => implode( "\r\n", $this->getHeaderList() ),
979 'protocol_version' => '1.1',
980 'max_redirects' => $this->followRedirects ?
$this->maxRedirects
: 0,
981 'ignore_errors' => true,
982 'timeout' => $this->timeout
,
983 // Curl options in case curlwrappers are installed
984 'curl_verify_ssl_host' => $this->sslVerifyHost ?
2 : 0,
985 'curl_verify_ssl_peer' => $this->sslVerifyCert
,
988 'verify_peer' => $this->sslVerifyCert
,
989 'SNI_enabled' => true,
990 'ciphers' => 'HIGH:!SSLv2:!SSLv3:-ADH:-kDH:-kECDH:-DSS',
991 'disable_compression' => true,
995 if ( $this->proxy
) {
996 $options['http']['proxy'] = $this->urlToTCP( $this->proxy
);
997 $options['http']['request_fulluri'] = true;
1000 if ( $this->postData
) {
1001 $options['http']['content'] = $this->postData
;
1004 if ( $this->sslVerifyHost
) {
1005 // PHP 5.6.0 deprecates CN_match, in favour of peer_name which
1006 // actually checks SubjectAltName properly.
1007 if ( version_compare( PHP_VERSION
, '5.6.0', '>=' ) ) {
1008 $options['ssl']['peer_name'] = $this->parsedUrl
['host'];
1010 $options['ssl']['CN_match'] = $this->parsedUrl
['host'];
1014 $options['ssl'] +
= $this->getCertOptions();
1016 $context = stream_context_create( $options );
1018 $this->headerList
= array();
1024 if ( $this->profiler
) {
1025 $profileSection = $this->profiler
->scopedProfileIn(
1026 __METHOD__
. '-' . $this->profileName
1031 $this->fopenErrors
= array();
1032 set_error_handler( array( $this, 'errorHandler' ) );
1033 $fh = fopen( $url, "r", false, $context );
1034 restore_error_handler();
1037 // HACK for instant commons.
1038 // If we are contacting (commons|upload).wikimedia.org
1039 // try again with CN_match for en.wikipedia.org
1040 // as php does not handle SubjectAltName properly
1041 // prior to "peer_name" option in php 5.6
1042 if ( isset( $options['ssl']['CN_match'] )
1043 && ( $options['ssl']['CN_match'] === 'commons.wikimedia.org'
1044 ||
$options['ssl']['CN_match'] === 'upload.wikimedia.org' )
1046 $options['ssl']['CN_match'] = 'en.wikipedia.org';
1047 $context = stream_context_create( $options );
1053 $result = stream_get_meta_data( $fh );
1054 $this->headerList
= $result['wrapper_data'];
1055 $this->parseHeader();
1057 if ( !$this->followRedirects
) {
1061 # Handle manual redirection
1062 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
1065 # Check security of URL
1066 $url = $this->getResponseHeader( "Location" );
1068 if ( !Http
::isValidURI( $url ) ) {
1069 wfDebug( __METHOD__
. ": insecure redirection\n" );
1073 if ( $this->profiler
) {
1074 $this->profiler
->scopedProfileOut( $profileSection );
1079 if ( $fh === false ) {
1080 if ( $this->fopenErrors
) {
1081 LoggerFactory
::getInstance( 'http' )->warning( __CLASS__
1082 . ': error opening connection: {errstr1}', $this->fopenErrors
);
1084 $this->status
->fatal( 'http-request-error' );
1085 return $this->status
;
1088 if ( $result['timed_out'] ) {
1089 $this->status
->fatal( 'http-timed-out', $this->url
);
1090 return $this->status
;
1093 // If everything went OK, or we received some error code
1094 // get the response body content.
1095 if ( $this->status
->isOK() ||
(int)$this->respStatus
>= 300 ) {
1096 while ( !feof( $fh ) ) {
1097 $buf = fread( $fh, 8192 );
1099 if ( $buf === false ) {
1100 $this->status
->fatal( 'http-read-error' );
1104 if ( strlen( $buf ) ) {
1105 call_user_func( $this->callback
, $fh, $buf );
1111 return $this->status
;