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
29 * Various HTTP related functions
33 static $httpEngine = false;
36 * Perform an HTTP request
38 * @param $method String: HTTP method. Usually GET/POST
39 * @param $url String: full URL to act on. If protocol-relative, will be expanded to an http:// URL
40 * @param $options Array: options to pass to MWHttpRequest object.
41 * Possible keys for the array:
42 * - timeout Timeout length in seconds
43 * - postData An array of key-value pairs or a url-encoded form data
44 * - proxy The proxy to use.
45 * Otherwise it will use $wgHTTPProxy (if set)
46 * Otherwise it will use the environment variable "http_proxy" (if set)
47 * - noProxy Don't use any proxy at all. Takes precedence over proxy value(s).
48 * - sslVerifyHost (curl only) Verify hostname against certificate
49 * - sslVerifyCert (curl only) Verify SSL certificate
50 * - caInfo (curl only) Provide CA information
51 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
52 * - followRedirects Whether to follow redirects (defaults to false).
53 * Note: this should only be used when the target URL is trusted,
54 * to avoid attacks on intranet services accessible by HTTP.
55 * - userAgent A user agent, if you want to override the default
56 * MediaWiki/$wgVersion
57 * @return Mixed: (bool)false on failure or a string on success
59 public static function request( $method, $url, $options = array() ) {
60 wfDebug( "HTTP: $method: $url\n" );
61 $options['method'] = strtoupper( $method );
63 if ( !isset( $options['timeout'] ) ) {
64 $options['timeout'] = 'default';
67 $req = MWHttpRequest
::factory( $url, $options );
68 $status = $req->execute();
70 if ( $status->isOK() ) {
71 return $req->getContent();
78 * Simple wrapper for Http::request( 'GET' )
79 * @see Http::request()
82 * @param $timeout string
83 * @param $options array
86 public static function get( $url, $timeout = 'default', $options = array() ) {
87 $options['timeout'] = $timeout;
88 return Http
::request( 'GET', $url, $options );
92 * Simple wrapper for Http::request( 'POST' )
93 * @see Http::request()
96 * @param $options array
99 public static function post( $url, $options = array() ) {
100 return Http
::request( 'POST', $url, $options );
104 * Check if the URL can be served by localhost
106 * @param $url String: full url to check
109 public static function isLocalURL( $url ) {
110 global $wgCommandLineMode, $wgConf;
112 if ( $wgCommandLineMode ) {
118 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
121 $domainParts = explode( '.', $host );
122 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
123 $domainParts = array_reverse( $domainParts );
126 for ( $i = 0; $i < count( $domainParts ); $i++
) {
127 $domainPart = $domainParts[$i];
129 $domain = $domainPart;
131 $domain = $domainPart . '.' . $domain;
134 if ( $wgConf->isLocalVHost( $domain ) ) {
144 * A standard user-agent we can use for external requests.
147 public static function userAgent() {
149 return "MediaWiki/$wgVersion";
153 * Checks that the given URI is a valid one. Hardcoding the
154 * protocols, because we only want protocols that both cURL
157 * file:// should not be allowed here for security purpose (r67684)
159 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
161 * @param $uri Mixed: URI to check for validity
164 public static function isValidURI( $uri ) {
166 '/^https?:\/\/[^\/\s]\S*$/D',
173 * This wrapper class will call out to curl (if available) or fallback
174 * to regular PHP if necessary for handling internal HTTP requests.
176 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
177 * PHP's HTTP extension.
179 class MWHttpRequest
{
180 const SUPPORTS_FILE_POSTS
= false;
183 protected $timeout = 'default';
184 protected $headersOnly = null;
185 protected $postData = null;
186 protected $proxy = null;
187 protected $noProxy = false;
188 protected $sslVerifyHost = true;
189 protected $sslVerifyCert = true;
190 protected $caInfo = null;
191 protected $method = "GET";
192 protected $reqHeaders = array();
194 protected $parsedUrl;
196 protected $maxRedirects = 5;
197 protected $followRedirects = false;
202 protected $cookieJar;
204 protected $headerList = array();
205 protected $respVersion = "0.9";
206 protected $respStatus = "200 Ok";
207 protected $respHeaders = array();
212 * @param $url String: url to use. If protocol-relative, will be expanded to an http:// URL
213 * @param $options Array: (optional) extra params to pass (see Http::request())
215 protected function __construct( $url, $options = array() ) {
216 global $wgHTTPTimeout;
218 $this->url
= wfExpandUrl( $url, PROTO_HTTP
);
219 $this->parsedUrl
= wfParseUrl( $this->url
);
221 if ( !$this->parsedUrl ||
!Http
::isValidURI( $this->url
) ) {
222 $this->status
= Status
::newFatal( 'http-invalid-url' );
224 $this->status
= Status
::newGood( 100 ); // continue
227 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
228 $this->timeout
= $options['timeout'];
230 $this->timeout
= $wgHTTPTimeout;
232 if( isset( $options['userAgent'] ) ) {
233 $this->setUserAgent( $options['userAgent'] );
236 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
237 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
239 foreach ( $members as $o ) {
240 if ( isset( $options[$o] ) ) {
241 // ensure that MWHttpRequest::method is always
242 // uppercased. Bug 36137
243 if ( $o == 'method' ) {
244 $options[$o] = strtoupper( $options[$o] );
246 $this->$o = $options[$o];
250 if ( $this->noProxy
) {
251 $this->proxy
= ''; // noProxy takes precedence
256 * Simple function to test if we can make any sort of requests at all, using
260 public static function canMakeRequests() {
261 return function_exists( 'curl_init' ) ||
wfIniGetBool( 'allow_url_fopen' );
265 * Generate a new request object
266 * @param $url String: url to use
267 * @param $options Array: (optional) extra params to pass (see Http::request())
268 * @throws MWException
269 * @return CurlHttpRequest|PhpHttpRequest
270 * @see MWHttpRequest::__construct
272 public static function factory( $url, $options = null ) {
273 if ( !Http
::$httpEngine ) {
274 Http
::$httpEngine = function_exists( 'curl_init' ) ?
'curl' : 'php';
275 } elseif ( Http
::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
276 throw new MWException( __METHOD__
. ': curl (http://php.net/curl) is not installed, but' .
277 ' Http::$httpEngine is set to "curl"' );
280 switch( Http
::$httpEngine ) {
282 return new CurlHttpRequest( $url, $options );
284 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
285 throw new MWException( __METHOD__
. ': allow_url_fopen needs to be enabled for pure PHP' .
286 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
288 return new PhpHttpRequest( $url, $options );
290 throw new MWException( __METHOD__
. ': The setting of Http::$httpEngine is not valid.' );
295 * Get the body, or content, of the response to the request
299 public function getContent() {
300 return $this->content
;
304 * Set the parameters of the request
307 * @todo overload the args param
309 public function setData( $args ) {
310 $this->postData
= $args;
314 * Take care of setting up the proxy (do nothing if "noProxy" is set)
318 public function proxySetup() {
321 if ( $this->proxy ||
!$this->noProxy
) {
325 if ( Http
::isLocalURL( $this->url
) ||
$this->noProxy
) {
327 } elseif ( $wgHTTPProxy ) {
328 $this->proxy
= $wgHTTPProxy ;
329 } elseif ( getenv( "http_proxy" ) ) {
330 $this->proxy
= getenv( "http_proxy" );
335 * Set the refererer header
337 public function setReferer( $url ) {
338 $this->setHeader( 'Referer', $url );
345 public function setUserAgent( $UA ) {
346 $this->setHeader( 'User-Agent', $UA );
350 * Set an arbitrary header
354 public function setHeader( $name, $value ) {
355 // I feel like I should normalize the case here...
356 $this->reqHeaders
[$name] = $value;
360 * Get an array of the headers
363 public function getHeaderList() {
366 if ( $this->cookieJar
) {
367 $this->reqHeaders
['Cookie'] =
368 $this->cookieJar
->serializeToHttpRequest(
369 $this->parsedUrl
['path'],
370 $this->parsedUrl
['host']
374 foreach ( $this->reqHeaders
as $name => $value ) {
375 $list[] = "$name: $value";
382 * Set a read callback to accept data read from the HTTP request.
383 * By default, data is appended to an internal buffer which can be
384 * retrieved through $req->getContent().
386 * To handle data as it comes in -- especially for large files that
387 * would not fit in memory -- you can instead set your own callback,
388 * in the form function($resource, $buffer) where the first parameter
389 * is the low-level resource being read (implementation specific),
390 * and the second parameter is the data buffer.
392 * You MUST return the number of bytes handled in the buffer; if fewer
393 * bytes are reported handled than were passed to you, the HTTP fetch
396 * @param $callback Callback
397 * @throws MWException
399 public function setCallback( $callback ) {
400 if ( !is_callable( $callback ) ) {
401 throw new MWException( 'Invalid MwHttpRequest callback' );
403 $this->callback
= $callback;
407 * A generic callback to read the body of the response from a remote
411 * @param $content String
414 public function read( $fh, $content ) {
415 $this->content
.= $content;
416 return strlen( $content );
420 * Take care of whatever is necessary to perform the URI request.
424 public function execute() {
429 if ( strtoupper( $this->method
) == "HEAD" ) {
430 $this->headersOnly
= true;
433 if ( is_object( $wgTitle ) && !isset( $this->reqHeaders
['Referer'] ) ) {
434 $this->setReferer( wfExpandUrl( $wgTitle->getFullURL(), PROTO_CURRENT
) );
437 $this->proxySetup(); // set up any proxy as needed
439 if ( !$this->callback
) {
440 $this->setCallback( array( $this, 'read' ) );
443 if ( !isset( $this->reqHeaders
['User-Agent'] ) ) {
444 $this->setUserAgent( Http
::userAgent() );
449 * Parses the headers, including the HTTP status code and any
450 * Set-Cookie headers. This function expectes the headers to be
451 * found in an array in the member variable headerList.
453 protected function parseHeader() {
456 foreach ( $this->headerList
as $header ) {
457 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
458 $this->respVersion
= $match[1];
459 $this->respStatus
= $match[2];
460 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
461 $last = count( $this->respHeaders
[$lastname] ) - 1;
462 $this->respHeaders
[$lastname][$last] .= "\r\n$header";
463 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
464 $this->respHeaders
[strtolower( $match[1] )][] = $match[2];
465 $lastname = strtolower( $match[1] );
469 $this->parseCookies();
473 * Sets HTTPRequest status member to a fatal value with the error
474 * message if the returned integer value of the status code was
475 * not successful (< 300) or a redirect (>=300 and < 400). (see
476 * RFC2616, section 10,
477 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
478 * list of status codes.)
480 protected function setStatus() {
481 if ( !$this->respHeaders
) {
482 $this->parseHeader();
485 if ( (int)$this->respStatus
> 399 ) {
486 list( $code, $message ) = explode( " ", $this->respStatus
, 2 );
487 $this->status
->fatal( "http-bad-status", $code, $message );
492 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
493 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
494 * for a list of status codes.)
498 public function getStatus() {
499 if ( !$this->respHeaders
) {
500 $this->parseHeader();
503 return (int)$this->respStatus
;
508 * Returns true if the last status code was a redirect.
512 public function isRedirect() {
513 if ( !$this->respHeaders
) {
514 $this->parseHeader();
517 $status = (int)$this->respStatus
;
519 if ( $status >= 300 && $status <= 303 ) {
527 * Returns an associative array of response headers after the
528 * request has been executed. Because some headers
529 * (e.g. Set-Cookie) can appear more than once the, each value of
530 * the associative array is an array of the values given.
534 public function getResponseHeaders() {
535 if ( !$this->respHeaders
) {
536 $this->parseHeader();
539 return $this->respHeaders
;
543 * Returns the value of the given response header.
545 * @param $header String
548 public function getResponseHeader( $header ) {
549 if ( !$this->respHeaders
) {
550 $this->parseHeader();
553 if ( isset( $this->respHeaders
[strtolower ( $header ) ] ) ) {
554 $v = $this->respHeaders
[strtolower ( $header ) ];
555 return $v[count( $v ) - 1];
562 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
564 * @param $jar CookieJar
566 public function setCookieJar( $jar ) {
567 $this->cookieJar
= $jar;
571 * Returns the cookie jar in use.
575 public function getCookieJar() {
576 if ( !$this->respHeaders
) {
577 $this->parseHeader();
580 return $this->cookieJar
;
584 * Sets a cookie. Used before a request to set up any individual
585 * cookies. Used internally after a request to parse the
586 * Set-Cookie headers.
592 public function setCookie( $name, $value = null, $attr = null ) {
593 if ( !$this->cookieJar
) {
594 $this->cookieJar
= new CookieJar
;
597 $this->cookieJar
->setCookie( $name, $value, $attr );
601 * Parse the cookies in the response headers and store them in the cookie jar.
603 protected function parseCookies() {
604 if ( !$this->cookieJar
) {
605 $this->cookieJar
= new CookieJar
;
608 if ( isset( $this->respHeaders
['set-cookie'] ) ) {
609 $url = parse_url( $this->getFinalUrl() );
610 foreach ( $this->respHeaders
['set-cookie'] as $cookie ) {
611 $this->cookieJar
->parseCookieResponseHeader( $cookie, $url['host'] );
617 * Returns the final URL after all redirections.
619 * Relative values of the "Location" header are incorrect as stated in RFC, however they do happen and modern browsers support them.
620 * This function loops backwards through all locations in order to build the proper absolute URI - Marooned at wikia-inc.com
622 * Note that the multiple Location: headers are an artifact of CURL -- they
623 * shouldn't actually get returned this way. Rewrite this when bug 29232 is
624 * taken care of (high-level redirect handling rewrite).
628 public function getFinalUrl() {
629 $headers = $this->getResponseHeaders();
631 //return full url (fix for incorrect but handled relative location)
632 if ( isset( $headers[ 'location' ] ) ) {
633 $locations = $headers[ 'location' ];
635 $foundRelativeURI = false;
636 $countLocations = count($locations);
638 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
639 $url = parse_url( $locations[ $i ] );
641 if ( isset($url[ 'host' ]) ) {
642 $domain = $url[ 'scheme' ] . '://' . $url[ 'host' ];
643 break; //found correct URI (with host)
645 $foundRelativeURI = true;
649 if ( $foundRelativeURI ) {
651 return $domain . $locations[ $countLocations - 1 ];
653 $url = parse_url( $this->url
);
654 if ( isset($url[ 'host' ]) ) {
655 return $url[ 'scheme' ] . '://' . $url[ 'host' ] . $locations[ $countLocations - 1 ];
659 return $locations[ $countLocations - 1 ];
667 * Returns true if the backend can follow redirects. Overridden by the
671 public function canFollowRedirects() {
677 * MWHttpRequest implemented using internal curl compiled into PHP
679 class CurlHttpRequest
extends MWHttpRequest
{
680 const SUPPORTS_FILE_POSTS
= true;
682 static $curlMessageMap = array(
683 6 => 'http-host-unreachable',
684 28 => 'http-timed-out'
687 protected $curlOptions = array();
688 protected $headerText = "";
695 protected function readHeader( $fh, $content ) {
696 $this->headerText
.= $content;
697 return strlen( $content );
700 public function execute() {
703 if ( !$this->status
->isOK() ) {
704 return $this->status
;
707 $this->curlOptions
[CURLOPT_PROXY
] = $this->proxy
;
708 $this->curlOptions
[CURLOPT_TIMEOUT
] = $this->timeout
;
709 $this->curlOptions
[CURLOPT_HTTP_VERSION
] = CURL_HTTP_VERSION_1_0
;
710 $this->curlOptions
[CURLOPT_WRITEFUNCTION
] = $this->callback
;
711 $this->curlOptions
[CURLOPT_HEADERFUNCTION
] = array( $this, "readHeader" );
712 $this->curlOptions
[CURLOPT_MAXREDIRS
] = $this->maxRedirects
;
713 $this->curlOptions
[CURLOPT_ENCODING
] = ""; # Enable compression
715 /* not sure these two are actually necessary */
716 if ( isset( $this->reqHeaders
['Referer'] ) ) {
717 $this->curlOptions
[CURLOPT_REFERER
] = $this->reqHeaders
['Referer'];
719 $this->curlOptions
[CURLOPT_USERAGENT
] = $this->reqHeaders
['User-Agent'];
721 if ( isset( $this->sslVerifyHost
) ) {
722 $this->curlOptions
[CURLOPT_SSL_VERIFYHOST
] = $this->sslVerifyHost
;
725 if ( isset( $this->sslVerifyCert
) ) {
726 $this->curlOptions
[CURLOPT_SSL_VERIFYPEER
] = $this->sslVerifyCert
;
729 if ( $this->caInfo
) {
730 $this->curlOptions
[CURLOPT_CAINFO
] = $this->caInfo
;
733 if ( $this->headersOnly
) {
734 $this->curlOptions
[CURLOPT_NOBODY
] = true;
735 $this->curlOptions
[CURLOPT_HEADER
] = true;
736 } elseif ( $this->method
== 'POST' ) {
737 $this->curlOptions
[CURLOPT_POST
] = true;
738 $this->curlOptions
[CURLOPT_POSTFIELDS
] = $this->postData
;
739 // Suppress 'Expect: 100-continue' header, as some servers
740 // will reject it with a 417 and Curl won't auto retry
741 // with HTTP 1.0 fallback
742 $this->reqHeaders
['Expect'] = '';
744 $this->curlOptions
[CURLOPT_CUSTOMREQUEST
] = $this->method
;
747 $this->curlOptions
[CURLOPT_HTTPHEADER
] = $this->getHeaderList();
749 $curlHandle = curl_init( $this->url
);
751 if ( !curl_setopt_array( $curlHandle, $this->curlOptions
) ) {
752 throw new MWException( "Error setting curl options." );
755 if ( $this->followRedirects
&& $this->canFollowRedirects() ) {
756 wfSuppressWarnings();
757 if ( ! curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION
, true ) ) {
758 wfDebug( __METHOD__
. ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
759 "Probably safe_mode or open_basedir is set.\n" );
760 // Continue the processing. If it were in curl_setopt_array,
761 // processing would have halted on its entry
766 if ( false === curl_exec( $curlHandle ) ) {
767 $code = curl_error( $curlHandle );
769 if ( isset( self
::$curlMessageMap[$code] ) ) {
770 $this->status
->fatal( self
::$curlMessageMap[$code] );
772 $this->status
->fatal( 'http-curl-error', curl_error( $curlHandle ) );
775 $this->headerList
= explode( "\r\n", $this->headerText
);
778 curl_close( $curlHandle );
780 $this->parseHeader();
783 return $this->status
;
789 public function canFollowRedirects() {
790 if ( strval( ini_get( 'open_basedir' ) ) !== '' ||
wfIniGetBool( 'safe_mode' ) ) {
791 wfDebug( "Cannot follow redirects in safe mode\n" );
795 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
796 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
804 class PhpHttpRequest
extends MWHttpRequest
{
810 protected function urlToTcp( $url ) {
811 $parsedUrl = parse_url( $url );
813 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
816 public function execute() {
819 if ( is_array( $this->postData
) ) {
820 $this->postData
= wfArrayToCGI( $this->postData
);
823 if ( $this->parsedUrl
['scheme'] != 'http' &&
824 $this->parsedUrl
['scheme'] != 'https' ) {
825 $this->status
->fatal( 'http-invalid-scheme', $this->parsedUrl
['scheme'] );
828 $this->reqHeaders
['Accept'] = "*/*";
829 if ( $this->method
== 'POST' ) {
830 // Required for HTTP 1.0 POSTs
831 $this->reqHeaders
['Content-Length'] = strlen( $this->postData
);
832 if( !isset( $this->reqHeaders
['Content-Type'] ) ) {
833 $this->reqHeaders
['Content-Type'] = "application/x-www-form-urlencoded";
838 if ( $this->proxy
) {
839 $options['proxy'] = $this->urlToTCP( $this->proxy
);
840 $options['request_fulluri'] = true;
843 if ( !$this->followRedirects
) {
844 $options['max_redirects'] = 0;
846 $options['max_redirects'] = $this->maxRedirects
;
849 $options['method'] = $this->method
;
850 $options['header'] = implode( "\r\n", $this->getHeaderList() );
851 // Note that at some future point we may want to support
852 // HTTP/1.1, but we'd have to write support for chunking
853 // in version of PHP < 5.3.1
854 $options['protocol_version'] = "1.0";
856 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
857 // Only works on 5.2.10+
858 $options['ignore_errors'] = true;
860 if ( $this->postData
) {
861 $options['content'] = $this->postData
;
864 $options['timeout'] = $this->timeout
;
866 $context = stream_context_create( array( 'http' => $options ) );
868 $this->headerList
= array();
876 wfSuppressWarnings();
877 $fh = fopen( $url, "r", false, $context );
884 $result = stream_get_meta_data( $fh );
885 $this->headerList
= $result['wrapper_data'];
886 $this->parseHeader();
888 if ( !$this->followRedirects
) {
892 # Handle manual redirection
893 if ( !$this->isRedirect() ||
$reqCount > $this->maxRedirects
) {
896 # Check security of URL
897 $url = $this->getResponseHeader( "Location" );
899 if ( !Http
::isValidURI( $url ) ) {
900 wfDebug( __METHOD__
. ": insecure redirection\n" );
907 if ( $fh === false ) {
908 $this->status
->fatal( 'http-request-error' );
909 return $this->status
;
912 if ( $result['timed_out'] ) {
913 $this->status
->fatal( 'http-timed-out', $this->url
);
914 return $this->status
;
917 // If everything went OK, or we received some error code
918 // get the response body content.
919 if ( $this->status
->isOK()
920 ||
(int)$this->respStatus
>= 300) {
921 while ( !feof( $fh ) ) {
922 $buf = fread( $fh, 8192 );
924 if ( $buf === false ) {
925 $this->status
->fatal( 'http-read-error' );
929 if ( strlen( $buf ) ) {
930 call_user_func( $this->callback
, $fh, $buf );
936 return $this->status
;