Merge "Move prefsection style to mediawiki.special.preferences.css"
[lhc/web/wiklou.git] / includes / HttpFunctions.php
1 <?php
2 /**
3 * Various HTTP related functions.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup HTTP
22 */
23
24 /**
25 * @defgroup HTTP HTTP
26 */
27
28 use MediaWiki\Logger\LoggerFactory;
29
30 /**
31 * Various HTTP related functions
32 * @ingroup HTTP
33 */
34 class Http {
35 static public $httpEngine = false;
36
37 /**
38 * Perform an HTTP request
39 *
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
62 */
63 public static function request( $method, $url, $options = array(), $caller = __METHOD__ ) {
64 wfDebug( "HTTP: $method: $url\n" );
65
66 $options['method'] = strtoupper( $method );
67
68 if ( !isset( $options['timeout'] ) ) {
69 $options['timeout'] = 'default';
70 }
71 if ( !isset( $options['connectTimeout'] ) ) {
72 $options['connectTimeout'] = 'default';
73 }
74
75 $req = MWHttpRequest::factory( $url, $options, $caller );
76 $status = $req->execute();
77
78 if ( $status->isOK() ) {
79 return $req->getContent();
80 } else {
81 $errors = $status->getErrorsByType( 'error' );
82 $logger = LoggerFactory::getInstance( 'http' );
83 $logger->warning( $status->getWikiText(), array( 'caller' => $caller ) );
84 return false;
85 }
86 }
87
88 /**
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'
93 *
94 * @param string $url
95 * @param array $options
96 * @param string $caller The method making this request, for profiling
97 * @return string
98 */
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] ) ?
106 $args[2] : array();
107 $options['timeout'] = $args[1];
108 $caller = __METHOD__;
109 }
110 return Http::request( 'GET', $url, $options, $caller );
111 }
112
113 /**
114 * Simple wrapper for Http::request( 'POST' )
115 * @see Http::request()
116 *
117 * @param string $url
118 * @param array $options
119 * @param string $caller The method making this request, for profiling
120 * @return string
121 */
122 public static function post( $url, $options = array(), $caller = __METHOD__ ) {
123 return Http::request( 'POST', $url, $options, $caller );
124 }
125
126 /**
127 * Check if the URL can be served by localhost
128 *
129 * @param string $url Full url to check
130 * @return bool
131 */
132 public static function isLocalURL( $url ) {
133 global $wgCommandLineMode, $wgLocalVirtualHosts, $wgConf;
134
135 if ( $wgCommandLineMode ) {
136 return false;
137 }
138
139 // Extract host part
140 $matches = array();
141 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
142 $host = $matches[1];
143 // Split up dotwise
144 $domainParts = explode( '.', $host );
145 // Check if this domain or any superdomain is listed as a local virtual host
146 $domainParts = array_reverse( $domainParts );
147
148 $domain = '';
149 $countParts = count( $domainParts );
150 for ( $i = 0; $i < $countParts; $i++ ) {
151 $domainPart = $domainParts[$i];
152 if ( $i == 0 ) {
153 $domain = $domainPart;
154 } else {
155 $domain = $domainPart . '.' . $domain;
156 }
157
158 if ( in_array( $domain, $wgLocalVirtualHosts )
159 || $wgConf->isLocalVHost( $domain )
160 ) {
161 return true;
162 }
163 }
164 }
165
166 return false;
167 }
168
169 /**
170 * A standard user-agent we can use for external requests.
171 * @return string
172 */
173 public static function userAgent() {
174 global $wgVersion;
175 return "MediaWiki/$wgVersion";
176 }
177
178 /**
179 * Checks that the given URI is a valid one. Hardcoding the
180 * protocols, because we only want protocols that both cURL
181 * and php support.
182 *
183 * file:// should not be allowed here for security purpose (r67684)
184 *
185 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
186 *
187 * @param string $uri URI to check for validity
188 * @return bool
189 */
190 public static function isValidURI( $uri ) {
191 return preg_match(
192 '/^https?:\/\/[^\/\s]\S*$/D',
193 $uri
194 );
195 }
196 }
197
198 /**
199 * This wrapper class will call out to curl (if available) or fallback
200 * to regular PHP if necessary for handling internal HTTP requests.
201 *
202 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
203 * PHP's HTTP extension.
204 */
205 class MWHttpRequest {
206 const SUPPORTS_FILE_POSTS = false;
207
208 protected $content;
209 protected $timeout = 'default';
210 protected $headersOnly = null;
211 protected $postData = null;
212 protected $proxy = null;
213 protected $noProxy = false;
214 protected $sslVerifyHost = true;
215 protected $sslVerifyCert = true;
216 protected $caInfo = null;
217 protected $method = "GET";
218 protected $reqHeaders = array();
219 protected $url;
220 protected $parsedUrl;
221 protected $callback;
222 protected $maxRedirects = 5;
223 protected $followRedirects = false;
224
225 /**
226 * @var CookieJar
227 */
228 protected $cookieJar;
229
230 protected $headerList = array();
231 protected $respVersion = "0.9";
232 protected $respStatus = "200 Ok";
233 protected $respHeaders = array();
234
235 public $status;
236
237 /**
238 * @var Profiler
239 */
240 protected $profiler;
241
242 /**
243 * @var string
244 */
245 protected $profileName;
246
247 /**
248 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
249 * @param array $options (optional) extra params to pass (see Http::request())
250 * @param string $caller The method making this request, for profiling
251 * @param Profiler $profiler An instance of the profiler for profiling, or null
252 */
253 protected function __construct( $url, $options = array(), $caller = __METHOD__, $profiler = null ) {
254 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
255
256 $this->url = wfExpandUrl( $url, PROTO_HTTP );
257 $this->parsedUrl = wfParseUrl( $this->url );
258
259 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
260 $this->status = Status::newFatal( 'http-invalid-url', $url );
261 } else {
262 $this->status = Status::newGood( 100 ); // continue
263 }
264
265 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
266 $this->timeout = $options['timeout'];
267 } else {
268 $this->timeout = $wgHTTPTimeout;
269 }
270 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
271 $this->connectTimeout = $options['connectTimeout'];
272 } else {
273 $this->connectTimeout = $wgHTTPConnectTimeout;
274 }
275 if ( isset( $options['userAgent'] ) ) {
276 $this->setUserAgent( $options['userAgent'] );
277 }
278
279 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
280 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
281
282 foreach ( $members as $o ) {
283 if ( isset( $options[$o] ) ) {
284 // ensure that MWHttpRequest::method is always
285 // uppercased. Bug 36137
286 if ( $o == 'method' ) {
287 $options[$o] = strtoupper( $options[$o] );
288 }
289 $this->$o = $options[$o];
290 }
291 }
292
293 if ( $this->noProxy ) {
294 $this->proxy = ''; // noProxy takes precedence
295 }
296
297 // Profile based on what's calling us
298 $this->profiler = $profiler;
299 $this->profileName = $caller;
300 }
301
302 /**
303 * Simple function to test if we can make any sort of requests at all, using
304 * cURL or fopen()
305 * @return bool
306 */
307 public static function canMakeRequests() {
308 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
309 }
310
311 /**
312 * Generate a new request object
313 * @param string $url Url to use
314 * @param array $options (optional) extra params to pass (see Http::request())
315 * @param string $caller The method making this request, for profiling
316 * @throws MWException
317 * @return CurlHttpRequest|PhpHttpRequest
318 * @see MWHttpRequest::__construct
319 */
320 public static function factory( $url, $options = null, $caller = __METHOD__ ) {
321 if ( !Http::$httpEngine ) {
322 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
323 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
324 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
325 ' Http::$httpEngine is set to "curl"' );
326 }
327
328 switch ( Http::$httpEngine ) {
329 case 'curl':
330 return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
331 case 'php':
332 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
333 throw new MWException( __METHOD__ . ': allow_url_fopen ' .
334 'needs to be enabled for pure PHP http requests to ' .
335 'work. If possible, curl should be used instead. See ' .
336 'http://php.net/curl.'
337 );
338 }
339 return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
340 default:
341 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
342 }
343 }
344
345 /**
346 * Get the body, or content, of the response to the request
347 *
348 * @return string
349 */
350 public function getContent() {
351 return $this->content;
352 }
353
354 /**
355 * Set the parameters of the request
356 *
357 * @param array $args
358 * @todo overload the args param
359 */
360 public function setData( $args ) {
361 $this->postData = $args;
362 }
363
364 /**
365 * Take care of setting up the proxy (do nothing if "noProxy" is set)
366 *
367 * @return void
368 */
369 public function proxySetup() {
370 global $wgHTTPProxy;
371
372 // If there is an explicit proxy set and proxies are not disabled, then use it
373 if ( $this->proxy && !$this->noProxy ) {
374 return;
375 }
376
377 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
378 // local URL and proxies are not disabled
379 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
380 $this->proxy = '';
381 } elseif ( $wgHTTPProxy ) {
382 $this->proxy = $wgHTTPProxy;
383 } elseif ( getenv( "http_proxy" ) ) {
384 $this->proxy = getenv( "http_proxy" );
385 }
386 }
387
388 /**
389 * Set the user agent
390 * @param string $UA
391 */
392 public function setUserAgent( $UA ) {
393 $this->setHeader( 'User-Agent', $UA );
394 }
395
396 /**
397 * Set an arbitrary header
398 * @param string $name
399 * @param string $value
400 */
401 public function setHeader( $name, $value ) {
402 // I feel like I should normalize the case here...
403 $this->reqHeaders[$name] = $value;
404 }
405
406 /**
407 * Get an array of the headers
408 * @return array
409 */
410 public function getHeaderList() {
411 $list = array();
412
413 if ( $this->cookieJar ) {
414 $this->reqHeaders['Cookie'] =
415 $this->cookieJar->serializeToHttpRequest(
416 $this->parsedUrl['path'],
417 $this->parsedUrl['host']
418 );
419 }
420
421 foreach ( $this->reqHeaders as $name => $value ) {
422 $list[] = "$name: $value";
423 }
424
425 return $list;
426 }
427
428 /**
429 * Set a read callback to accept data read from the HTTP request.
430 * By default, data is appended to an internal buffer which can be
431 * retrieved through $req->getContent().
432 *
433 * To handle data as it comes in -- especially for large files that
434 * would not fit in memory -- you can instead set your own callback,
435 * in the form function($resource, $buffer) where the first parameter
436 * is the low-level resource being read (implementation specific),
437 * and the second parameter is the data buffer.
438 *
439 * You MUST return the number of bytes handled in the buffer; if fewer
440 * bytes are reported handled than were passed to you, the HTTP fetch
441 * will be aborted.
442 *
443 * @param callable $callback
444 * @throws MWException
445 */
446 public function setCallback( $callback ) {
447 if ( !is_callable( $callback ) ) {
448 throw new MWException( 'Invalid MwHttpRequest callback' );
449 }
450 $this->callback = $callback;
451 }
452
453 /**
454 * A generic callback to read the body of the response from a remote
455 * server.
456 *
457 * @param resource $fh
458 * @param string $content
459 * @return int
460 */
461 public function read( $fh, $content ) {
462 $this->content .= $content;
463 return strlen( $content );
464 }
465
466 /**
467 * Take care of whatever is necessary to perform the URI request.
468 *
469 * @return Status
470 */
471 public function execute() {
472
473 $this->content = "";
474
475 if ( strtoupper( $this->method ) == "HEAD" ) {
476 $this->headersOnly = true;
477 }
478
479 $this->proxySetup(); // set up any proxy as needed
480
481 if ( !$this->callback ) {
482 $this->setCallback( array( $this, 'read' ) );
483 }
484
485 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
486 $this->setUserAgent( Http::userAgent() );
487 }
488
489 }
490
491 /**
492 * Parses the headers, including the HTTP status code and any
493 * Set-Cookie headers. This function expects the headers to be
494 * found in an array in the member variable headerList.
495 */
496 protected function parseHeader() {
497
498 $lastname = "";
499
500 foreach ( $this->headerList as $header ) {
501 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
502 $this->respVersion = $match[1];
503 $this->respStatus = $match[2];
504 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
505 $last = count( $this->respHeaders[$lastname] ) - 1;
506 $this->respHeaders[$lastname][$last] .= "\r\n$header";
507 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
508 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
509 $lastname = strtolower( $match[1] );
510 }
511 }
512
513 $this->parseCookies();
514
515 }
516
517 /**
518 * Sets HTTPRequest status member to a fatal value with the error
519 * message if the returned integer value of the status code was
520 * not successful (< 300) or a redirect (>=300 and < 400). (see
521 * RFC2616, section 10,
522 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
523 * list of status codes.)
524 */
525 protected function setStatus() {
526 if ( !$this->respHeaders ) {
527 $this->parseHeader();
528 }
529
530 if ( (int)$this->respStatus > 399 ) {
531 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
532 $this->status->fatal( "http-bad-status", $code, $message );
533 }
534 }
535
536 /**
537 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
538 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
539 * for a list of status codes.)
540 *
541 * @return int
542 */
543 public function getStatus() {
544 if ( !$this->respHeaders ) {
545 $this->parseHeader();
546 }
547
548 return (int)$this->respStatus;
549 }
550
551 /**
552 * Returns true if the last status code was a redirect.
553 *
554 * @return bool
555 */
556 public function isRedirect() {
557 if ( !$this->respHeaders ) {
558 $this->parseHeader();
559 }
560
561 $status = (int)$this->respStatus;
562
563 if ( $status >= 300 && $status <= 303 ) {
564 return true;
565 }
566
567 return false;
568 }
569
570 /**
571 * Returns an associative array of response headers after the
572 * request has been executed. Because some headers
573 * (e.g. Set-Cookie) can appear more than once the, each value of
574 * the associative array is an array of the values given.
575 *
576 * @return array
577 */
578 public function getResponseHeaders() {
579 if ( !$this->respHeaders ) {
580 $this->parseHeader();
581 }
582
583 return $this->respHeaders;
584 }
585
586 /**
587 * Returns the value of the given response header.
588 *
589 * @param string $header
590 * @return string
591 */
592 public function getResponseHeader( $header ) {
593 if ( !$this->respHeaders ) {
594 $this->parseHeader();
595 }
596
597 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
598 $v = $this->respHeaders[strtolower( $header )];
599 return $v[count( $v ) - 1];
600 }
601
602 return null;
603 }
604
605 /**
606 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
607 *
608 * @param CookieJar $jar
609 */
610 public function setCookieJar( $jar ) {
611 $this->cookieJar = $jar;
612 }
613
614 /**
615 * Returns the cookie jar in use.
616 *
617 * @return CookieJar
618 */
619 public function getCookieJar() {
620 if ( !$this->respHeaders ) {
621 $this->parseHeader();
622 }
623
624 return $this->cookieJar;
625 }
626
627 /**
628 * Sets a cookie. Used before a request to set up any individual
629 * cookies. Used internally after a request to parse the
630 * Set-Cookie headers.
631 * @see Cookie::set
632 * @param string $name
633 * @param mixed $value
634 * @param array $attr
635 */
636 public function setCookie( $name, $value = null, $attr = null ) {
637 if ( !$this->cookieJar ) {
638 $this->cookieJar = new CookieJar;
639 }
640
641 $this->cookieJar->setCookie( $name, $value, $attr );
642 }
643
644 /**
645 * Parse the cookies in the response headers and store them in the cookie jar.
646 */
647 protected function parseCookies() {
648
649 if ( !$this->cookieJar ) {
650 $this->cookieJar = new CookieJar;
651 }
652
653 if ( isset( $this->respHeaders['set-cookie'] ) ) {
654 $url = parse_url( $this->getFinalUrl() );
655 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
656 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
657 }
658 }
659
660 }
661
662 /**
663 * Returns the final URL after all redirections.
664 *
665 * Relative values of the "Location" header are incorrect as
666 * stated in RFC, however they do happen and modern browsers
667 * support them. This function loops backwards through all
668 * locations in order to build the proper absolute URI - Marooned
669 * at wikia-inc.com
670 *
671 * Note that the multiple Location: headers are an artifact of
672 * CURL -- they shouldn't actually get returned this way. Rewrite
673 * this when bug 29232 is taken care of (high-level redirect
674 * handling rewrite).
675 *
676 * @return string
677 */
678 public function getFinalUrl() {
679 $headers = $this->getResponseHeaders();
680
681 //return full url (fix for incorrect but handled relative location)
682 if ( isset( $headers['location'] ) ) {
683 $locations = $headers['location'];
684 $domain = '';
685 $foundRelativeURI = false;
686 $countLocations = count( $locations );
687
688 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
689 $url = parse_url( $locations[$i] );
690
691 if ( isset( $url['host'] ) ) {
692 $domain = $url['scheme'] . '://' . $url['host'];
693 break; //found correct URI (with host)
694 } else {
695 $foundRelativeURI = true;
696 }
697 }
698
699 if ( $foundRelativeURI ) {
700 if ( $domain ) {
701 return $domain . $locations[$countLocations - 1];
702 } else {
703 $url = parse_url( $this->url );
704 if ( isset( $url['host'] ) ) {
705 return $url['scheme'] . '://' . $url['host'] .
706 $locations[$countLocations - 1];
707 }
708 }
709 } else {
710 return $locations[$countLocations - 1];
711 }
712 }
713
714 return $this->url;
715 }
716
717 /**
718 * Returns true if the backend can follow redirects. Overridden by the
719 * child classes.
720 * @return bool
721 */
722 public function canFollowRedirects() {
723 return true;
724 }
725 }
726
727 /**
728 * MWHttpRequest implemented using internal curl compiled into PHP
729 */
730 class CurlHttpRequest extends MWHttpRequest {
731 const SUPPORTS_FILE_POSTS = true;
732
733 protected $curlOptions = array();
734 protected $headerText = "";
735
736 /**
737 * @param resource $fh
738 * @param string $content
739 * @return int
740 */
741 protected function readHeader( $fh, $content ) {
742 $this->headerText .= $content;
743 return strlen( $content );
744 }
745
746 public function execute() {
747
748 parent::execute();
749
750 if ( !$this->status->isOK() ) {
751 return $this->status;
752 }
753
754 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
755 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
756
757 // Only supported in curl >= 7.16.2
758 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
759 $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
760 }
761
762 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
763 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
764 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
765 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
766 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
767
768 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
769
770 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
771 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
772
773 if ( $this->caInfo ) {
774 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
775 }
776
777 if ( $this->headersOnly ) {
778 $this->curlOptions[CURLOPT_NOBODY] = true;
779 $this->curlOptions[CURLOPT_HEADER] = true;
780 } elseif ( $this->method == 'POST' ) {
781 $this->curlOptions[CURLOPT_POST] = true;
782 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
783 // Suppress 'Expect: 100-continue' header, as some servers
784 // will reject it with a 417 and Curl won't auto retry
785 // with HTTP 1.0 fallback
786 $this->reqHeaders['Expect'] = '';
787 } else {
788 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
789 }
790
791 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
792
793 $curlHandle = curl_init( $this->url );
794
795 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
796 throw new MWException( "Error setting curl options." );
797 }
798
799 if ( $this->followRedirects && $this->canFollowRedirects() ) {
800 MediaWiki\suppressWarnings();
801 if ( !curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
802 wfDebug( __METHOD__ . ": Couldn't set CURLOPT_FOLLOWLOCATION. " .
803 "Probably safe_mode or open_basedir is set.\n" );
804 // Continue the processing. If it were in curl_setopt_array,
805 // processing would have halted on its entry
806 }
807 MediaWiki\restoreWarnings();
808 }
809
810 if ( $this->profiler ) {
811 $profileSection = $this->profiler->scopedProfileIn(
812 __METHOD__ . '-' . $this->profileName
813 );
814 }
815
816 $curlRes = curl_exec( $curlHandle );
817 if ( curl_errno( $curlHandle ) == CURLE_OPERATION_TIMEOUTED ) {
818 $this->status->fatal( 'http-timed-out', $this->url );
819 } elseif ( $curlRes === false ) {
820 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
821 } else {
822 $this->headerList = explode( "\r\n", $this->headerText );
823 }
824
825 curl_close( $curlHandle );
826
827 if ( $this->profiler ) {
828 $this->profiler->scopedProfileOut( $profileSection );
829 }
830
831 $this->parseHeader();
832 $this->setStatus();
833
834 return $this->status;
835 }
836
837 /**
838 * @return bool
839 */
840 public function canFollowRedirects() {
841 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
842 wfDebug( "Cannot follow redirects in safe mode\n" );
843 return false;
844 }
845
846 $curlVersionInfo = curl_version();
847 if ( $curlVersionInfo['version_number'] < 0x071304 ) {
848 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
849 return false;
850 }
851
852 return true;
853 }
854 }
855
856 class PhpHttpRequest extends MWHttpRequest {
857
858 private $fopenErrors = array();
859
860 /**
861 * @param string $url
862 * @return string
863 */
864 protected function urlToTcp( $url ) {
865 $parsedUrl = parse_url( $url );
866
867 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
868 }
869
870 /**
871 * Returns an array with a 'capath' or 'cafile' key that is suitable to be merged into the 'ssl' sub-array of a
872 * stream context options array. Uses the 'caInfo' option of the class if it is provided, otherwise uses the system
873 * default CA bundle if PHP supports that, or searches a few standard locations.
874 * @return array
875 * @throws DomainException
876 */
877 protected function getCertOptions() {
878 $certOptions = array();
879 $certLocations = array();
880 if ( $this->caInfo ) {
881 $certLocations = array( 'manual' => $this->caInfo );
882 } elseif ( version_compare( PHP_VERSION, '5.6.0', '<' ) ) {
883 // Default locations, based on
884 // https://www.happyassassin.net/2015/01/12/a-note-about-ssltls-trusted-certificate-stores-and-platforms/
885 // PHP 5.5 and older doesn't have any defaults, so we try to guess ourselves. PHP 5.6+ gets the CA location
886 // from OpenSSL as long as it is not set manually, so we should leave capath/cafile empty there.
887 $certLocations = array_filter( array(
888 getenv( 'SSL_CERT_DIR' ),
889 getenv( 'SSL_CERT_PATH' ),
890 '/etc/pki/tls/certs/ca-bundle.crt', # Fedora et al
891 '/etc/ssl/certs', # Debian et al
892 '/etc/pki/tls/certs/ca-bundle.trust.crt',
893 '/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem',
894 '/System/Library/OpenSSL', # OSX
895 ) );
896 }
897
898 foreach( $certLocations as $key => $cert ) {
899 if ( is_dir( $cert ) ) {
900 $certOptions['capath'] = $cert;
901 break;
902 } elseif ( is_file( $cert ) ) {
903 $certOptions['cafile'] = $cert;
904 break;
905 } elseif ( $key === 'manual' ) {
906 // fail more loudly if a cert path was manually configured and it is not valid
907 throw new DomainException( "Invalid CA info passed: $cert" );
908 }
909 }
910
911 return $certOptions;
912 }
913
914 /**
915 * Custom error handler for dealing with fopen() errors. fopen() tends to fire multiple errors in succession, and the last one
916 * is completely useless (something like "fopen: failed to open stream") so normal methods of handling errors programmatically
917 * like get_last_error() don't work.
918 */
919 public function errorHandler( $errno, $errstr ) {
920 $n = count( $this->fopenErrors ) + 1;
921 $this->fopenErrors += array( "errno$n" => $errno, "errstr$n" => $errstr );
922 }
923
924 public function execute() {
925
926 parent::execute();
927
928 if ( is_array( $this->postData ) ) {
929 $this->postData = wfArrayToCgi( $this->postData );
930 }
931
932 if ( $this->parsedUrl['scheme'] != 'http'
933 && $this->parsedUrl['scheme'] != 'https' ) {
934 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
935 }
936
937 $this->reqHeaders['Accept'] = "*/*";
938 $this->reqHeaders['Connection'] = 'Close';
939 if ( $this->method == 'POST' ) {
940 // Required for HTTP 1.0 POSTs
941 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
942 if ( !isset( $this->reqHeaders['Content-Type'] ) ) {
943 $this->reqHeaders['Content-Type'] = "application/x-www-form-urlencoded";
944 }
945 }
946
947 // Set up PHP stream context
948 $options = array(
949 'http' => array(
950 'method' => $this->method,
951 'header' => implode( "\r\n", $this->getHeaderList() ),
952 'protocol_version' => '1.1',
953 'max_redirects' => $this->followRedirects ? $this->maxRedirects : 0,
954 'ignore_errors' => true,
955 'timeout' => $this->timeout,
956 // Curl options in case curlwrappers are installed
957 'curl_verify_ssl_host' => $this->sslVerifyHost ? 2 : 0,
958 'curl_verify_ssl_peer' => $this->sslVerifyCert,
959 ),
960 'ssl' => array(
961 'verify_peer' => $this->sslVerifyCert,
962 'SNI_enabled' => true,
963 ),
964 );
965
966 if ( $this->proxy ) {
967 $options['http']['proxy'] = $this->urlToTCP( $this->proxy );
968 $options['http']['request_fulluri'] = true;
969 }
970
971 if ( $this->postData ) {
972 $options['http']['content'] = $this->postData;
973 }
974
975 if ( $this->sslVerifyHost ) {
976 // PHP 5.6.0 deprecates CN_match, in favour of peer_name which
977 // actually checks SubjectAltName properly.
978 if ( version_compare( PHP_VERSION, '5.6.0', '>=' ) ) {
979 $options['ssl']['peer_name'] = $this->parsedUrl['host'];
980 } else {
981 $options['ssl']['CN_match'] = $this->parsedUrl['host'];
982 }
983 }
984
985 $options['ssl'] += $this->getCertOptions();
986
987 $context = stream_context_create( $options );
988
989 $this->headerList = array();
990 $reqCount = 0;
991 $url = $this->url;
992
993 $result = array();
994
995 if ( $this->profiler ) {
996 $profileSection = $this->profiler->scopedProfileIn(
997 __METHOD__ . '-' . $this->profileName
998 );
999 }
1000 do {
1001 $reqCount++;
1002 $this->fopenErrors = array();
1003 set_error_handler( array( $this, 'errorHandler' ) );
1004 $fh = fopen( $url, "r", false, $context );
1005 restore_error_handler();
1006
1007 if ( !$fh ) {
1008 // HACK for instant commons.
1009 // If we are contacting (commons|upload).wikimedia.org
1010 // try again with CN_match for en.wikipedia.org
1011 // as php does not handle SubjectAltName properly
1012 // prior to "peer_name" option in php 5.6
1013 if ( isset( $options['ssl']['CN_match'] )
1014 && ( $options['ssl']['CN_match'] === 'commons.wikimedia.org'
1015 || $options['ssl']['CN_match'] === 'upload.wikimedia.org' )
1016 ) {
1017 $options['ssl']['CN_match'] = 'en.wikipedia.org';
1018 $context = stream_context_create( $options );
1019 continue;
1020 }
1021 break;
1022 }
1023
1024 $result = stream_get_meta_data( $fh );
1025 $this->headerList = $result['wrapper_data'];
1026 $this->parseHeader();
1027
1028 if ( !$this->followRedirects ) {
1029 break;
1030 }
1031
1032 # Handle manual redirection
1033 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
1034 break;
1035 }
1036 # Check security of URL
1037 $url = $this->getResponseHeader( "Location" );
1038
1039 if ( !Http::isValidURI( $url ) ) {
1040 wfDebug( __METHOD__ . ": insecure redirection\n" );
1041 break;
1042 }
1043 } while ( true );
1044 if ( $this->profiler ) {
1045 $this->profiler->scopedProfileOut( $profileSection );
1046 }
1047
1048 $this->setStatus();
1049
1050 if ( $fh === false ) {
1051 if ( $this->fopenErrors ) {
1052 LoggerFactory::getInstance( 'http' )->warning( __CLASS__
1053 . ': error opening connection: {errstr1}', $this->fopenErrors );
1054 }
1055 $this->status->fatal( 'http-request-error' );
1056 return $this->status;
1057 }
1058
1059 if ( $result['timed_out'] ) {
1060 $this->status->fatal( 'http-timed-out', $this->url );
1061 return $this->status;
1062 }
1063
1064 // If everything went OK, or we received some error code
1065 // get the response body content.
1066 if ( $this->status->isOK() || (int)$this->respStatus >= 300 ) {
1067 while ( !feof( $fh ) ) {
1068 $buf = fread( $fh, 8192 );
1069
1070 if ( $buf === false ) {
1071 $this->status->fatal( 'http-read-error' );
1072 break;
1073 }
1074
1075 if ( strlen( $buf ) ) {
1076 call_user_func( $this->callback, $fh, $buf );
1077 }
1078 }
1079 }
1080 fclose( $fh );
1081
1082 return $this->status;
1083 }
1084 }