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 = [], $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(),
84 [ 'error' => $errors, 'caller' => $caller, 'content' => $req->getContent() ] );
90 * Simple wrapper for Http::request( 'GET' )
91 * @see Http::request()
92 * @since 1.25 Second parameter $timeout removed. Second parameter
93 * is now $options which can be given a 'timeout'
96 * @param array $options
97 * @param string $caller The method making this request, for profiling
98 * @return string|bool false on error
100 public static function get( $url, $options = [], $caller = __METHOD__
) {
101 $args = func_get_args();
102 if ( isset( $args[1] ) && ( is_string( $args[1] ) ||
is_numeric( $args[1] ) ) ) {
103 // Second was used to be the timeout
104 // And third parameter used to be $options
105 wfWarn( "Second parameter should not be a timeout.", 2 );
106 $options = isset( $args[2] ) && is_array( $args[2] ) ?
108 $options['timeout'] = $args[1];
109 $caller = __METHOD__
;
111 return Http
::request( 'GET', $url, $options, $caller );
115 * Simple wrapper for Http::request( 'POST' )
116 * @see Http::request()
119 * @param array $options
120 * @param string $caller The method making this request, for profiling
121 * @return string|bool false on error
123 public static function post( $url, $options = [], $caller = __METHOD__
) {
124 return Http
::request( 'POST', $url, $options, $caller );
128 * Check if the URL can be served by localhost
130 * @param string $url Full url to check
133 public static function isLocalURL( $url ) {
134 global $wgCommandLineMode, $wgLocalVirtualHosts;
136 if ( $wgCommandLineMode ) {
142 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
145 $domainParts = explode( '.', $host );
146 // Check if this domain or any superdomain is listed as a local virtual host
147 $domainParts = array_reverse( $domainParts );
150 $countParts = count( $domainParts );
151 for ( $i = 0; $i < $countParts; $i++
) {
152 $domainPart = $domainParts[$i];
154 $domain = $domainPart;
156 $domain = $domainPart . '.' . $domain;
159 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
169 * A standard user-agent we can use for external requests.
172 public static function userAgent() {
174 return "MediaWiki/$wgVersion";
178 * Checks that the given URI is a valid one. Hardcoding the
179 * protocols, because we only want protocols that both cURL
182 * file:// should not be allowed here for security purpose (r67684)
184 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
186 * @param string $uri URI to check for validity
189 public static function isValidURI( $uri ) {
191 '/^https?:\/\/[^\/\s]\S*$/D',
198 * This wrapper class will call out to curl (if available) or fallback
199 * to regular PHP if necessary for handling internal HTTP requests.
201 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
202 * PHP's HTTP extension.
204 class MWHttpRequest
{
205 const SUPPORTS_FILE_POSTS
= false;
208 protected $timeout = 'default';
209 protected $headersOnly = null;
210 protected $postData = null;
211 protected $proxy = null;
212 protected $noProxy = false;
213 protected $sslVerifyHost = true;
214 protected $sslVerifyCert = true;
215 protected $caInfo = null;
216 protected $method = "GET";
217 protected $reqHeaders = [];
219 protected $parsedUrl;
221 protected $maxRedirects = 5;
222 protected $followRedirects = false;
227 protected $cookieJar;
229 protected $headerList = [];
230 protected $respVersion = "0.9";
231 protected $respStatus = "200 Ok";
232 protected $respHeaders = [];
244 protected $profileName;
247 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
248 * @param array $options (optional) extra params to pass (see Http::request())
249 * @param string $caller The method making this request, for profiling
250 * @param Profiler $profiler An instance of the profiler for profiling, or null
252 protected function __construct(
253 $url, $options = [], $caller = __METHOD__
, $profiler = null
255 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
257 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
258 $this->parsedUrl
= wfParseUrl( $this->url
);
260 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
261 $this->status
= Status
::newFatal( 'http-invalid-url', $url );
263 $this->status
= Status
::newGood( 100 ); // continue
266 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
267 $this->timeout
= $options['timeout'];
269 $this->timeout
= $wgHTTPTimeout;
271 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
272 $this->connectTimeout
= $options['connectTimeout'];
274 $this->connectTimeout
= $wgHTTPConnectTimeout;
276 if ( isset( $options['userAgent'] ) ) {
277 $this->setUserAgent( $options['userAgent'] );
280 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
281 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
283 foreach ( $members as $o ) {
284 if ( isset( $options[$o] ) ) {
285 // ensure that MWHttpRequest::method is always
286 // uppercased. Bug 36137
287 if ( $o == 'method' ) {
288 $options[$o] = strtoupper( $options[$o] );
290 $this->$o = $options[$o];
294 if ( $this->noProxy
) {
295 $this->proxy
= ''; // noProxy takes precedence
298 // Profile based on what's calling us
299 $this->profiler
= $profiler;
300 $this->profileName
= $caller;
304 * Simple function to test if we can make any sort of requests at all, using
308 public static function canMakeRequests() {
309 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
313 * Generate a new request object
314 * @param string $url Url to use
315 * @param array $options (optional) extra params to pass (see Http::request())
316 * @param string $caller The method making this request, for profiling
317 * @throws MWException
318 * @return CurlHttpRequest|PhpHttpRequest
319 * @see MWHttpRequest::__construct
321 public static function factory( $url, $options = null, $caller = __METHOD__
) {
322 if ( !Http
::$httpEngine ) {
323 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
324 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
325 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
326 ' Http::$httpEngine is set to "curl"' );
329 switch ( Http
::$httpEngine ) {
331 return new CurlHttpRequest( $url, $options, $caller, Profiler
::instance() );
333 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
334 throw new MWException( __METHOD__
. ': allow_url_fopen ' .
335 'needs to be enabled for pure PHP http requests to ' .
336 'work. If possible, curl should be used instead. See ' .
337 'http://php.net/curl.'
340 return new PhpHttpRequest( $url, $options, $caller, Profiler
::instance() );
342 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
347 * Get the body, or content, of the response to the request
351 public function getContent() {
352 return $this->content
;
356 * Set the parameters of the request
359 * @todo overload the args param
361 public function setData( $args ) {
362 $this->postData
= $args;
366 * Take care of setting up the proxy (do nothing if "noProxy" is set)
370 public function proxySetup() {
373 // If there is an explicit proxy set and proxies are not disabled, then use it
374 if ( $this->proxy
&& !$this->noProxy
) {
378 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
379 // local URL and proxies are not disabled
380 if ( Http
::isLocalURL( $this->url
) ||
$this->noProxy
) {
382 } elseif ( $wgHTTPProxy ) {
383 $this->proxy
= $wgHTTPProxy;
384 } elseif ( getenv( "http_proxy" ) ) {
385 $this->proxy
= getenv( "http_proxy" );
393 public function setUserAgent( $UA ) {
394 $this->setHeader( 'User-Agent', $UA );
398 * Set an arbitrary header
399 * @param string $name
400 * @param string $value
402 public function setHeader( $name, $value ) {
403 // I feel like I should normalize the case here...
404 $this->reqHeaders
[$name] = $value;
408 * Get an array of the headers
411 public function getHeaderList() {
414 if ( $this->cookieJar
) {
415 $this->reqHeaders
['Cookie'] =
416 $this->cookieJar
->serializeToHttpRequest(
417 $this->parsedUrl
['path'],
418 $this->parsedUrl
['host']
422 foreach ( $this->reqHeaders
as $name => $value ) {
423 $list[] = "$name: $value";
430 * Set a read callback to accept data read from the HTTP request.
431 * By default, data is appended to an internal buffer which can be
432 * retrieved through $req->getContent().
434 * To handle data as it comes in -- especially for large files that
435 * would not fit in memory -- you can instead set your own callback,
436 * in the form function($resource, $buffer) where the first parameter
437 * is the low-level resource being read (implementation specific),
438 * and the second parameter is the data buffer.
440 * You MUST return the number of bytes handled in the buffer; if fewer
441 * bytes are reported handled than were passed to you, the HTTP fetch
444 * @param callable $callback
445 * @throws MWException
447 public function setCallback( $callback ) {
448 if ( !is_callable( $callback ) ) {
449 throw new MWException( 'Invalid MwHttpRequest callback' );
451 $this->callback
= $callback;
455 * A generic callback to read the body of the response from a remote
458 * @param resource $fh
459 * @param string $content
462 public function read( $fh, $content ) {
463 $this->content
.= $content;
464 return strlen( $content );
468 * Take care of whatever is necessary to perform the URI request.
472 public function execute() {
476 if ( strtoupper( $this->method
) == "HEAD" ) {
477 $this->headersOnly
= true;
480 $this->proxySetup(); // set up any proxy as needed
482 if ( !$this->callback
) {
483 $this->setCallback( [ $this, 'read' ] );
486 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
487 $this->setUserAgent( Http
::userAgent() );
493 * Parses the headers, including the HTTP status code and any
494 * Set-Cookie headers. This function expects the headers to be
495 * found in an array in the member variable headerList.
497 protected function parseHeader() {
501 foreach ( $this->headerList
as $header ) {
502 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
503 $this->respVersion
= $match[1];
504 $this->respStatus
= $match[2];
505 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
506 $last = count( $this->respHeaders
[$lastname] ) - 1;
507 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
508 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
509 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
510 $lastname = strtolower( $match[1] );
514 $this->parseCookies();
519 * Sets HTTPRequest status member to a fatal value with the error
520 * message if the returned integer value of the status code was
521 * not successful (< 300) or a redirect (>=300 and < 400). (see
522 * RFC2616, section 10,
523 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
524 * list of status codes.)
526 protected function setStatus() {
527 if ( !$this->respHeaders
) {
528 $this->parseHeader();
531 if ( (int)$this->respStatus
> 399 ) {
532 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
533 $this->status
->fatal( "http-bad-status", $code, $message );
538 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
539 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
540 * for a list of status codes.)
544 public function getStatus() {
545 if ( !$this->respHeaders
) {
546 $this->parseHeader();
549 return (int)$this->respStatus
;
553 * Returns true if the last status code was a redirect.
557 public function isRedirect() {
558 if ( !$this->respHeaders
) {
559 $this->parseHeader();
562 $status = (int)$this->respStatus
;
564 if ( $status >= 300 && $status <= 303 ) {
572 * Returns an associative array of response headers after the
573 * request has been executed. Because some headers
574 * (e.g. Set-Cookie) can appear more than once the, each value of
575 * the associative array is an array of the values given.
579 public function getResponseHeaders() {
580 if ( !$this->respHeaders
) {
581 $this->parseHeader();
584 return $this->respHeaders
;
588 * Returns the value of the given response header.
590 * @param string $header
593 public function getResponseHeader( $header ) {
594 if ( !$this->respHeaders
) {
595 $this->parseHeader();
598 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
599 $v = $this->respHeaders
[strtolower( $header )];
600 return $v[count( $v ) - 1];
607 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
609 * @param CookieJar $jar
611 public function setCookieJar( $jar ) {
612 $this->cookieJar
= $jar;
616 * Returns the cookie jar in use.
620 public function getCookieJar() {
621 if ( !$this->respHeaders
) {
622 $this->parseHeader();
625 return $this->cookieJar
;
629 * Sets a cookie. Used before a request to set up any individual
630 * cookies. Used internally after a request to parse the
631 * Set-Cookie headers.
633 * @param string $name
634 * @param mixed $value
637 public function setCookie( $name, $value = null, $attr = null ) {
638 if ( !$this->cookieJar
) {
639 $this->cookieJar
= new CookieJar
;
642 $this->cookieJar
->setCookie( $name, $value, $attr );
646 * Parse the cookies in the response headers and store them in the cookie jar.
648 protected function parseCookies() {
650 if ( !$this->cookieJar
) {
651 $this->cookieJar
= new CookieJar
;
654 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
655 $url = parse_url( $this->getFinalUrl() );
656 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
657 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
664 * Returns the final URL after all redirections.
666 * Relative values of the "Location" header are incorrect as
667 * stated in RFC, however they do happen and modern browsers
668 * support them. This function loops backwards through all
669 * locations in order to build the proper absolute URI - Marooned
672 * Note that the multiple Location: headers are an artifact of
673 * CURL -- they shouldn't actually get returned this way. Rewrite
674 * this when bug 29232 is taken care of (high-level redirect
679 public function getFinalUrl() {
680 $headers = $this->getResponseHeaders();
682 // return full url (fix for incorrect but handled relative location)
683 if ( isset( $headers['location'] ) ) {
684 $locations = $headers['location'];
686 $foundRelativeURI = false;
687 $countLocations = count( $locations );
689 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
690 $url = parse_url( $locations[$i] );
692 if ( isset( $url['host'] ) ) {
693 $domain = $url['scheme'] . '://' . $url['host'];
694 break; // found correct URI (with host)
696 $foundRelativeURI = true;
700 if ( $foundRelativeURI ) {
702 return $domain . $locations[$countLocations - 1];
704 $url = parse_url( $this->url
);
705 if ( isset( $url['host'] ) ) {
706 return $url['scheme'] . '://' . $url['host'] .
707 $locations[$countLocations - 1];
711 return $locations[$countLocations - 1];
719 * Returns true if the backend can follow redirects. Overridden by the
723 public function canFollowRedirects() {
729 * MWHttpRequest implemented using internal curl compiled into PHP
731 class CurlHttpRequest
extends MWHttpRequest
{
732 const SUPPORTS_FILE_POSTS
= true;
734 protected $curlOptions = [];
735 protected $headerText = "";
738 * @param resource $fh
739 * @param string $content
742 protected function readHeader( $fh, $content ) {
743 $this->headerText
.= $content;
744 return strlen( $content );
747 public function execute() {
751 if ( !$this->status
->isOK() ) {
752 return $this->status
;
755 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
756 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
758 // Only supported in curl >= 7.16.2
759 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
760 $this->curlOptions
[CURLOPT_CONNECTTIMEOUT_MS
] = $this->connectTimeout
* 1000;
763 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
764 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
765 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = [ $this, "readHeader" ];
766 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
767 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
769 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
771 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost ?
2 : 0;
772 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
774 if ( $this->caInfo
) {
775 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
778 if ( $this->headersOnly
) {
779 $this->curlOptions
[CURLOPT_NOBODY
] = true;
780 $this->curlOptions
[CURLOPT_HEADER
] = true;
781 } elseif ( $this->method
== 'POST' ) {
782 $this->curlOptions
[CURLOPT_POST
] = true;
783 $postData = $this->postData
;
784 // Don't interpret POST parameters starting with '@' as file uploads, because this
785 // makes it impossible to POST plain values starting with '@' (and causes security
786 // issues potentially exposing the contents of local files).
787 // The PHP manual says this option was introduced in PHP 5.5 defaults to true in PHP 5.6,
788 // but we support lower versions, and the option doesn't exist in HHVM 5.6.99.
789 if ( defined( 'CURLOPT_SAFE_UPLOAD' ) ) {
790 $this->curlOptions
[CURLOPT_SAFE_UPLOAD
] = true;
791 } elseif ( is_array( $postData ) ) {
792 // In PHP 5.2 and later, '@' is interpreted as a file upload if POSTFIELDS
793 // is an array, but not if it's a string. So convert $req['body'] to a string
795 $postData = wfArrayToCgi( $postData );
797 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $postData;
799 // Suppress 'Expect: 100-continue' header, as some servers
800 // will reject it with a 417 and Curl won't auto retry
801 // with HTTP 1.0 fallback
802 $this->reqHeaders
['Expect'] = '';
804 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
807 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
809 $curlHandle = curl_init( $this->url
);
811 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
812 throw new MWException( "Error setting curl options." );
815 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
816 MediaWiki\
suppressWarnings();
817 if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
818 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
819 "Probably open_basedir is set.\n" );
820 // Continue the processing. If it were in curl_setopt_array,
821 // processing would have halted on its entry
823 MediaWiki\restoreWarnings
();
826 if ( $this->profiler
) {
827 $profileSection = $this->profiler
->scopedProfileIn(
828 __METHOD__
. '-' . $this->profileName
832 $curlRes = curl_exec( $curlHandle );
833 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED
) {
834 $this->status
->fatal( 'http-timed-out', $this->url
);
835 } elseif ( $curlRes === false ) {
836 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
838 $this->headerList
= explode( "\r\n", $this->headerText
);
841 curl_close( $curlHandle );
843 if ( $this->profiler
) {
844 $this->profiler
->scopedProfileOut( $profileSection );
847 $this->parseHeader();
850 return $this->status
;
856 public function canFollowRedirects() {
857 $curlVersionInfo = curl_version();
858 if ( $curlVersionInfo['version_number'] < 0x071304 ) {
859 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
863 if ( version_compare( PHP_VERSION
, '5.6.0', '<' ) ) {
864 if ( strval( ini_get( 'open_basedir' ) ) !== '' ) {
865 wfDebug( "Cannot follow redirects when open_basedir is set\n" );
874 class PhpHttpRequest
extends MWHttpRequest
{
876 private $fopenErrors = [];
882 protected function urlToTcp( $url ) {
883 $parsedUrl = parse_url( $url );
885 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
889 * Returns an array with a 'capath' or 'cafile' key
890 * that is suitable to be merged into the 'ssl' sub-array of
891 * a stream context options array.
892 * Uses the 'caInfo' option of the class if it is provided, otherwise uses the system
893 * default CA bundle if PHP supports that, or searches a few standard locations.
895 * @throws DomainException
897 protected function getCertOptions() {
900 if ( $this->caInfo
) {
901 $certLocations = [ 'manual' => $this->caInfo
];
902 } elseif ( version_compare( PHP_VERSION
, '5.6.0', '<' ) ) {
903 // @codingStandardsIgnoreStart Generic.Files.LineLength
904 // Default locations, based on
905 // https://www.happyassassin.net/2015/01/12/a-note-about-ssltls-trusted-certificate-stores-and-platforms/
906 // PHP 5.5 and older doesn't have any defaults, so we try to guess ourselves.
907 // PHP 5.6+ gets the CA location from OpenSSL as long as it is not set manually,
908 // so we should leave capath/cafile empty there.
909 // @codingStandardsIgnoreEnd
910 $certLocations = array_filter( [
911 getenv( 'SSL_CERT_DIR' ),
912 getenv( 'SSL_CERT_PATH' ),
913 '/etc/pki/tls/certs/ca-bundle.crt', # Fedora et al
914 '/etc/ssl/certs', # Debian et al
915 '/etc/pki/tls/certs/ca-bundle.trust.crt',
916 '/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem',
917 '/System/Library/OpenSSL', # OSX
921 foreach ( $certLocations as $key => $cert ) {
922 if ( is_dir( $cert ) ) {
923 $certOptions['capath'] = $cert;
925 } elseif ( is_file( $cert ) ) {
926 $certOptions['cafile'] = $cert;
928 } elseif ( $key === 'manual' ) {
929 // fail more loudly if a cert path was manually configured and it is not valid
930 throw new DomainException( "Invalid CA info passed: $cert" );
938 * Custom error handler for dealing with fopen() errors.
939 * fopen() tends to fire multiple errors in succession, and the last one
940 * is completely useless (something like "fopen: failed to open stream")
941 * so normal methods of handling errors programmatically
942 * like get_last_error() don't work.
944 public function errorHandler( $errno, $errstr ) {
945 $n = count( $this->fopenErrors
) +
1;
946 $this->fopenErrors +
= [ "errno$n" => $errno, "errstr$n" => $errstr ];
949 public function execute() {
953 if ( is_array( $this->postData
) ) {
954 $this->postData
= wfArrayToCgi( $this->postData
);
957 if ( $this->parsedUrl
['scheme'] != 'http'
958 && $this->parsedUrl
['scheme'] != 'https' ) {
959 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
962 $this->reqHeaders
['Accept'] = "*/*";
963 $this->reqHeaders
['Connection'] = 'Close';
964 if ( $this->method
== 'POST' ) {
965 // Required for HTTP 1.0 POSTs
966 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
967 if ( !isset( $this->reqHeaders
['Content-Type'] ) ) {
968 $this->reqHeaders
['Content-Type'] = "application/x-www-form-urlencoded";
972 // Set up PHP stream context
975 'method' => $this->method
,
976 'header' => implode( "\r\n", $this->getHeaderList() ),
977 'protocol_version' => '1.1',
978 'max_redirects' => $this->followRedirects ?
$this->maxRedirects
: 0,
979 'ignore_errors' => true,
980 'timeout' => $this->timeout
,
981 // Curl options in case curlwrappers are installed
982 'curl_verify_ssl_host' => $this->sslVerifyHost ?
2 : 0,
983 'curl_verify_ssl_peer' => $this->sslVerifyCert
,
986 'verify_peer' => $this->sslVerifyCert
,
987 'SNI_enabled' => true,
988 'ciphers' => 'HIGH:!SSLv2:!SSLv3:-ADH:-kDH:-kECDH:-DSS',
989 'disable_compression' => true,
993 if ( $this->proxy
) {
994 $options['http']['proxy'] = $this->urlToTCP( $this->proxy
);
995 $options['http']['request_fulluri'] = true;
998 if ( $this->postData
) {
999 $options['http']['content'] = $this->postData
;
1002 if ( $this->sslVerifyHost
) {
1003 // PHP 5.6.0 deprecates CN_match, in favour of peer_name which
1004 // actually checks SubjectAltName properly.
1005 if ( version_compare( PHP_VERSION
, '5.6.0', '>=' ) ) {
1006 $options['ssl']['peer_name'] = $this->parsedUrl
['host'];
1008 $options['ssl']['CN_match'] = $this->parsedUrl
['host'];
1012 $options['ssl'] +
= $this->getCertOptions();
1014 $context = stream_context_create( $options );
1016 $this->headerList
= [];
1022 if ( $this->profiler
) {
1023 $profileSection = $this->profiler
->scopedProfileIn(
1024 __METHOD__
. '-' . $this->profileName
1029 $this->fopenErrors
= [];
1030 set_error_handler( [ $this, 'errorHandler' ] );
1031 $fh = fopen( $url, "r", false, $context );
1032 restore_error_handler();
1035 // HACK for instant commons.
1036 // If we are contacting (commons|upload).wikimedia.org
1037 // try again with CN_match for en.wikipedia.org
1038 // as php does not handle SubjectAltName properly
1039 // prior to "peer_name" option in php 5.6
1040 if ( isset( $options['ssl']['CN_match'] )
1041 && ( $options['ssl']['CN_match'] === 'commons.wikimedia.org'
1042 ||
$options['ssl']['CN_match'] === 'upload.wikimedia.org' )
1044 $options['ssl']['CN_match'] = 'en.wikipedia.org';
1045 $context = stream_context_create( $options );
1051 $result = stream_get_meta_data( $fh );
1052 $this->headerList
= $result['wrapper_data'];
1053 $this->parseHeader();
1055 if ( !$this->followRedirects
) {
1059 # Handle manual redirection
1060 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
1063 # Check security of URL
1064 $url = $this->getResponseHeader( "Location" );
1066 if ( !Http
::isValidURI( $url ) ) {
1067 wfDebug( __METHOD__
. ": insecure redirection\n" );
1071 if ( $this->profiler
) {
1072 $this->profiler
->scopedProfileOut( $profileSection );
1077 if ( $fh === false ) {
1078 if ( $this->fopenErrors
) {
1079 LoggerFactory
::getInstance( 'http' )->warning( __CLASS__
1080 . ': error opening connection: {errstr1}', $this->fopenErrors
);
1082 $this->status
->fatal( 'http-request-error' );
1083 return $this->status
;
1086 if ( $result['timed_out'] ) {
1087 $this->status
->fatal( 'http-timed-out', $this->url
);
1088 return $this->status
;
1091 // If everything went OK, or we received some error code
1092 // get the response body content.
1093 if ( $this->status
->isOK() ||
(int)$this->respStatus
>= 300 ) {
1094 while ( !feof( $fh ) ) {
1095 $buf = fread( $fh, 8192 );
1097 if ( $buf === false ) {
1098 $this->status
->fatal( 'http-read-error' );
1102 if ( strlen( $buf ) ) {
1103 call_user_func( $this->callback
, $fh, $buf );
1109 return $this->status
;