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(),
84 array( '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
100 public static function get( $url, $options = array(), $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
123 public static function post( $url, $options = array(), $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, $wgConf;
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 )
160 ||
$wgConf->isLocalVHost( $domain )
171 * A standard user-agent we can use for external requests.
174 public static function userAgent() {
176 return "MediaWiki/$wgVersion";
180 * Checks that the given URI is a valid one. Hardcoding the
181 * protocols, because we only want protocols that both cURL
184 * file:// should not be allowed here for security purpose (r67684)
186 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
188 * @param string $uri URI to check for validity
191 public static function isValidURI( $uri ) {
193 '/^https?:\/\/[^\/\s]\S*$/D',
200 * This wrapper class will call out to curl (if available) or fallback
201 * to regular PHP if necessary for handling internal HTTP requests.
203 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
204 * PHP's HTTP extension.
206 class MWHttpRequest
{
207 const SUPPORTS_FILE_POSTS
= false;
210 protected $timeout = 'default';
211 protected $headersOnly = null;
212 protected $postData = null;
213 protected $proxy = null;
214 protected $noProxy = false;
215 protected $sslVerifyHost = true;
216 protected $sslVerifyCert = true;
217 protected $caInfo = null;
218 protected $method = "GET";
219 protected $reqHeaders = array();
221 protected $parsedUrl;
223 protected $maxRedirects = 5;
224 protected $followRedirects = false;
229 protected $cookieJar;
231 protected $headerList = array();
232 protected $respVersion = "0.9";
233 protected $respStatus = "200 Ok";
234 protected $respHeaders = array();
246 protected $profileName;
249 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
250 * @param array $options (optional) extra params to pass (see Http::request())
251 * @param string $caller The method making this request, for profiling
252 * @param Profiler $profiler An instance of the profiler for profiling, or null
254 protected function __construct(
255 $url, $options = array(), $caller = __METHOD__
, $profiler = null
257 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
259 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
260 $this->parsedUrl
= wfParseUrl( $this->url
);
262 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
263 $this->status
= Status
::newFatal( 'http-invalid-url', $url );
265 $this->status
= Status
::newGood( 100 ); // continue
268 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
269 $this->timeout
= $options['timeout'];
271 $this->timeout
= $wgHTTPTimeout;
273 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
274 $this->connectTimeout
= $options['connectTimeout'];
276 $this->connectTimeout
= $wgHTTPConnectTimeout;
278 if ( isset( $options['userAgent'] ) ) {
279 $this->setUserAgent( $options['userAgent'] );
282 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
283 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
285 foreach ( $members as $o ) {
286 if ( isset( $options[$o] ) ) {
287 // ensure that MWHttpRequest::method is always
288 // uppercased. Bug 36137
289 if ( $o == 'method' ) {
290 $options[$o] = strtoupper( $options[$o] );
292 $this->$o = $options[$o];
296 if ( $this->noProxy
) {
297 $this->proxy
= ''; // noProxy takes precedence
300 // Profile based on what's calling us
301 $this->profiler
= $profiler;
302 $this->profileName
= $caller;
306 * Simple function to test if we can make any sort of requests at all, using
310 public static function canMakeRequests() {
311 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
315 * Generate a new request object
316 * @param string $url Url to use
317 * @param array $options (optional) extra params to pass (see Http::request())
318 * @param string $caller The method making this request, for profiling
319 * @throws MWException
320 * @return CurlHttpRequest|PhpHttpRequest
321 * @see MWHttpRequest::__construct
323 public static function factory( $url, $options = null, $caller = __METHOD__
) {
324 if ( !Http
::$httpEngine ) {
325 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
326 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
327 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
328 ' Http::$httpEngine is set to "curl"' );
331 switch ( Http
::$httpEngine ) {
333 return new CurlHttpRequest( $url, $options, $caller, Profiler
::instance() );
335 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
336 throw new MWException( __METHOD__
. ': allow_url_fopen ' .
337 'needs to be enabled for pure PHP http requests to ' .
338 'work. If possible, curl should be used instead. See ' .
339 'http://php.net/curl.'
342 return new PhpHttpRequest( $url, $options, $caller, Profiler
::instance() );
344 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
349 * Get the body, or content, of the response to the request
353 public function getContent() {
354 return $this->content
;
358 * Set the parameters of the request
361 * @todo overload the args param
363 public function setData( $args ) {
364 $this->postData
= $args;
368 * Take care of setting up the proxy (do nothing if "noProxy" is set)
372 public function proxySetup() {
375 // If there is an explicit proxy set and proxies are not disabled, then use it
376 if ( $this->proxy
&& !$this->noProxy
) {
380 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
381 // local URL and proxies are not disabled
382 if ( Http
::isLocalURL( $this->url
) ||
$this->noProxy
) {
384 } elseif ( $wgHTTPProxy ) {
385 $this->proxy
= $wgHTTPProxy;
386 } elseif ( getenv( "http_proxy" ) ) {
387 $this->proxy
= getenv( "http_proxy" );
395 public function setUserAgent( $UA ) {
396 $this->setHeader( 'User-Agent', $UA );
400 * Set an arbitrary header
401 * @param string $name
402 * @param string $value
404 public function setHeader( $name, $value ) {
405 // I feel like I should normalize the case here...
406 $this->reqHeaders
[$name] = $value;
410 * Get an array of the headers
413 public function getHeaderList() {
416 if ( $this->cookieJar
) {
417 $this->reqHeaders
['Cookie'] =
418 $this->cookieJar
->serializeToHttpRequest(
419 $this->parsedUrl
['path'],
420 $this->parsedUrl
['host']
424 foreach ( $this->reqHeaders
as $name => $value ) {
425 $list[] = "$name: $value";
432 * Set a read callback to accept data read from the HTTP request.
433 * By default, data is appended to an internal buffer which can be
434 * retrieved through $req->getContent().
436 * To handle data as it comes in -- especially for large files that
437 * would not fit in memory -- you can instead set your own callback,
438 * in the form function($resource, $buffer) where the first parameter
439 * is the low-level resource being read (implementation specific),
440 * and the second parameter is the data buffer.
442 * You MUST return the number of bytes handled in the buffer; if fewer
443 * bytes are reported handled than were passed to you, the HTTP fetch
446 * @param callable $callback
447 * @throws MWException
449 public function setCallback( $callback ) {
450 if ( !is_callable( $callback ) ) {
451 throw new MWException( 'Invalid MwHttpRequest callback' );
453 $this->callback
= $callback;
457 * A generic callback to read the body of the response from a remote
460 * @param resource $fh
461 * @param string $content
464 public function read( $fh, $content ) {
465 $this->content
.= $content;
466 return strlen( $content );
470 * Take care of whatever is necessary to perform the URI request.
474 public function execute() {
478 if ( strtoupper( $this->method
) == "HEAD" ) {
479 $this->headersOnly
= true;
482 $this->proxySetup(); // set up any proxy as needed
484 if ( !$this->callback
) {
485 $this->setCallback( array( $this, 'read' ) );
488 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
489 $this->setUserAgent( Http
::userAgent() );
495 * Parses the headers, including the HTTP status code and any
496 * Set-Cookie headers. This function expects the headers to be
497 * found in an array in the member variable headerList.
499 protected function parseHeader() {
503 foreach ( $this->headerList
as $header ) {
504 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
505 $this->respVersion
= $match[1];
506 $this->respStatus
= $match[2];
507 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
508 $last = count( $this->respHeaders
[$lastname] ) - 1;
509 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
510 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
511 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
512 $lastname = strtolower( $match[1] );
516 $this->parseCookies();
521 * Sets HTTPRequest status member to a fatal value with the error
522 * message if the returned integer value of the status code was
523 * not successful (< 300) or a redirect (>=300 and < 400). (see
524 * RFC2616, section 10,
525 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
526 * list of status codes.)
528 protected function setStatus() {
529 if ( !$this->respHeaders
) {
530 $this->parseHeader();
533 if ( (int)$this->respStatus
> 399 ) {
534 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
535 $this->status
->fatal( "http-bad-status", $code, $message );
540 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
541 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
542 * for a list of status codes.)
546 public function getStatus() {
547 if ( !$this->respHeaders
) {
548 $this->parseHeader();
551 return (int)$this->respStatus
;
555 * Returns true if the last status code was a redirect.
559 public function isRedirect() {
560 if ( !$this->respHeaders
) {
561 $this->parseHeader();
564 $status = (int)$this->respStatus
;
566 if ( $status >= 300 && $status <= 303 ) {
574 * Returns an associative array of response headers after the
575 * request has been executed. Because some headers
576 * (e.g. Set-Cookie) can appear more than once the, each value of
577 * the associative array is an array of the values given.
581 public function getResponseHeaders() {
582 if ( !$this->respHeaders
) {
583 $this->parseHeader();
586 return $this->respHeaders
;
590 * Returns the value of the given response header.
592 * @param string $header
595 public function getResponseHeader( $header ) {
596 if ( !$this->respHeaders
) {
597 $this->parseHeader();
600 if ( isset( $this->respHeaders
[strtolower( $header )] ) ) {
601 $v = $this->respHeaders
[strtolower( $header )];
602 return $v[count( $v ) - 1];
609 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
611 * @param CookieJar $jar
613 public function setCookieJar( $jar ) {
614 $this->cookieJar
= $jar;
618 * Returns the cookie jar in use.
622 public function getCookieJar() {
623 if ( !$this->respHeaders
) {
624 $this->parseHeader();
627 return $this->cookieJar
;
631 * Sets a cookie. Used before a request to set up any individual
632 * cookies. Used internally after a request to parse the
633 * Set-Cookie headers.
635 * @param string $name
636 * @param mixed $value
639 public function setCookie( $name, $value = null, $attr = null ) {
640 if ( !$this->cookieJar
) {
641 $this->cookieJar
= new CookieJar
;
644 $this->cookieJar
->setCookie( $name, $value, $attr );
648 * Parse the cookies in the response headers and store them in the cookie jar.
650 protected function parseCookies() {
652 if ( !$this->cookieJar
) {
653 $this->cookieJar
= new CookieJar
;
656 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
657 $url = parse_url( $this->getFinalUrl() );
658 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
659 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
666 * Returns the final URL after all redirections.
668 * Relative values of the "Location" header are incorrect as
669 * stated in RFC, however they do happen and modern browsers
670 * support them. This function loops backwards through all
671 * locations in order to build the proper absolute URI - Marooned
674 * Note that the multiple Location: headers are an artifact of
675 * CURL -- they shouldn't actually get returned this way. Rewrite
676 * this when bug 29232 is taken care of (high-level redirect
681 public function getFinalUrl() {
682 $headers = $this->getResponseHeaders();
684 // return full url (fix for incorrect but handled relative location)
685 if ( isset( $headers['location'] ) ) {
686 $locations = $headers['location'];
688 $foundRelativeURI = false;
689 $countLocations = count( $locations );
691 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
692 $url = parse_url( $locations[$i] );
694 if ( isset( $url['host'] ) ) {
695 $domain = $url['scheme'] . '://' . $url['host'];
696 break; // found correct URI (with host)
698 $foundRelativeURI = true;
702 if ( $foundRelativeURI ) {
704 return $domain . $locations[$countLocations - 1];
706 $url = parse_url( $this->url
);
707 if ( isset( $url['host'] ) ) {
708 return $url['scheme'] . '://' . $url['host'] .
709 $locations[$countLocations - 1];
713 return $locations[$countLocations - 1];
721 * Returns true if the backend can follow redirects. Overridden by the
725 public function canFollowRedirects() {
731 * MWHttpRequest implemented using internal curl compiled into PHP
733 class CurlHttpRequest
extends MWHttpRequest
{
734 const SUPPORTS_FILE_POSTS
= true;
736 protected $curlOptions = array();
737 protected $headerText = "";
740 * @param resource $fh
741 * @param string $content
744 protected function readHeader( $fh, $content ) {
745 $this->headerText
.= $content;
746 return strlen( $content );
749 public function execute() {
753 if ( !$this->status
->isOK() ) {
754 return $this->status
;
757 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
758 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
760 // Only supported in curl >= 7.16.2
761 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
762 $this->curlOptions
[CURLOPT_CONNECTTIMEOUT_MS
] = $this->connectTimeout
* 1000;
765 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
766 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
767 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
768 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
769 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
771 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
773 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost ?
2 : 0;
774 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
776 if ( $this->caInfo
) {
777 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
780 if ( $this->headersOnly
) {
781 $this->curlOptions
[CURLOPT_NOBODY
] = true;
782 $this->curlOptions
[CURLOPT_HEADER
] = true;
783 } elseif ( $this->method
== 'POST' ) {
784 $this->curlOptions
[CURLOPT_POST
] = true;
785 $postData = $this->postData
;
786 // Don't interpret POST parameters starting with '@' as file uploads, because this
787 // makes it impossible to POST plain values starting with '@' (and causes security
788 // issues potentially exposing the contents of local files).
789 // The PHP manual says this option was introduced in PHP 5.5 defaults to true in PHP 5.6,
790 // but we support lower versions, and the option doesn't exist in HHVM 5.6.99.
791 if ( defined( 'CURLOPT_SAFE_UPLOAD' ) ) {
792 $this->curlOptions
[CURLOPT_SAFE_UPLOAD
] = true;
793 } elseif ( is_array( $postData ) ) {
794 // In PHP 5.2 and later, '@' is interpreted as a file upload if POSTFIELDS
795 // is an array, but not if it's a string. So convert $req['body'] to a string
797 $postData = wfArrayToCgi( $postData );
799 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $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
;