697391b6d020b27c52ca490d24257b8d25561292
[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 * Gets the relevant proxy from $wgHTTPProxy/http_proxy (when set).
199 *
200 * @return mixed The proxy address or an empty string if not set.
201 */
202 public static function getProxy() {
203 global $wgHTTPProxy;
204
205 if ( $wgHTTPProxy ) {
206 return $wgHTTPProxy;
207 }
208
209 $envHttpProxy = getenv( "http_proxy" );
210 if ( $envHttpProxy ) {
211 return $envHttpProxy;
212 }
213
214 return "";
215 }
216 }
217
218 /**
219 * This wrapper class will call out to curl (if available) or fallback
220 * to regular PHP if necessary for handling internal HTTP requests.
221 *
222 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
223 * PHP's HTTP extension.
224 */
225 class MWHttpRequest {
226 const SUPPORTS_FILE_POSTS = false;
227
228 protected $content;
229 protected $timeout = 'default';
230 protected $headersOnly = null;
231 protected $postData = null;
232 protected $proxy = null;
233 protected $noProxy = false;
234 protected $sslVerifyHost = true;
235 protected $sslVerifyCert = true;
236 protected $caInfo = null;
237 protected $method = "GET";
238 protected $reqHeaders = array();
239 protected $url;
240 protected $parsedUrl;
241 protected $callback;
242 protected $maxRedirects = 5;
243 protected $followRedirects = false;
244
245 /**
246 * @var CookieJar
247 */
248 protected $cookieJar;
249
250 protected $headerList = array();
251 protected $respVersion = "0.9";
252 protected $respStatus = "200 Ok";
253 protected $respHeaders = array();
254
255 public $status;
256
257 /**
258 * @var Profiler
259 */
260 protected $profiler;
261
262 /**
263 * @var string
264 */
265 protected $profileName;
266
267 /**
268 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
269 * @param array $options (optional) extra params to pass (see Http::request())
270 * @param string $caller The method making this request, for profiling
271 * @param Profiler $profiler An instance of the profiler for profiling, or null
272 */
273 protected function __construct(
274 $url, $options = array(), $caller = __METHOD__, $profiler = null
275 ) {
276 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
277
278 $this->url = wfExpandUrl( $url, PROTO_HTTP );
279 $this->parsedUrl = wfParseUrl( $this->url );
280
281 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
282 $this->status = Status::newFatal( 'http-invalid-url', $url );
283 } else {
284 $this->status = Status::newGood( 100 ); // continue
285 }
286
287 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
288 $this->timeout = $options['timeout'];
289 } else {
290 $this->timeout = $wgHTTPTimeout;
291 }
292 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
293 $this->connectTimeout = $options['connectTimeout'];
294 } else {
295 $this->connectTimeout = $wgHTTPConnectTimeout;
296 }
297 if ( isset( $options['userAgent'] ) ) {
298 $this->setUserAgent( $options['userAgent'] );
299 }
300
301 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
302 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" );
303
304 foreach ( $members as $o ) {
305 if ( isset( $options[$o] ) ) {
306 // ensure that MWHttpRequest::method is always
307 // uppercased. Bug 36137
308 if ( $o == 'method' ) {
309 $options[$o] = strtoupper( $options[$o] );
310 }
311 $this->$o = $options[$o];
312 }
313 }
314
315 if ( $this->noProxy ) {
316 $this->proxy = ''; // noProxy takes precedence
317 }
318
319 // Profile based on what's calling us
320 $this->profiler = $profiler;
321 $this->profileName = $caller;
322 }
323
324 /**
325 * Simple function to test if we can make any sort of requests at all, using
326 * cURL or fopen()
327 * @return bool
328 */
329 public static function canMakeRequests() {
330 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
331 }
332
333 /**
334 * Generate a new request object
335 * @param string $url Url to use
336 * @param array $options (optional) extra params to pass (see Http::request())
337 * @param string $caller The method making this request, for profiling
338 * @throws MWException
339 * @return CurlHttpRequest|PhpHttpRequest
340 * @see MWHttpRequest::__construct
341 */
342 public static function factory( $url, $options = null, $caller = __METHOD__ ) {
343 if ( !Http::$httpEngine ) {
344 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
345 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
346 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
347 ' Http::$httpEngine is set to "curl"' );
348 }
349
350 switch ( Http::$httpEngine ) {
351 case 'curl':
352 return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
353 case 'php':
354 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
355 throw new MWException( __METHOD__ . ': allow_url_fopen ' .
356 'needs to be enabled for pure PHP http requests to ' .
357 'work. If possible, curl should be used instead. See ' .
358 'http://php.net/curl.'
359 );
360 }
361 return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
362 default:
363 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
364 }
365 }
366
367 /**
368 * Get the body, or content, of the response to the request
369 *
370 * @return string
371 */
372 public function getContent() {
373 return $this->content;
374 }
375
376 /**
377 * Set the parameters of the request
378 *
379 * @param array $args
380 * @todo overload the args param
381 */
382 public function setData( $args ) {
383 $this->postData = $args;
384 }
385
386 /**
387 * Take care of setting up the proxy (do nothing if "noProxy" is set)
388 *
389 * @return void
390 */
391 public function proxySetup() {
392 // If there is an explicit proxy set and proxies are not disabled, then use it
393 if ( $this->proxy && !$this->noProxy ) {
394 return;
395 }
396
397 // Otherwise, fallback to $wgHTTPProxy/http_proxy (when set) if this is not a machine
398 // local URL and proxies are not disabled
399 if ( Http::isLocalURL( $this->url ) || $this->noProxy ) {
400 $this->proxy = '';
401 } else {
402 $this->proxy = Http::getProxy();
403 }
404 }
405
406 /**
407 * Set the user agent
408 * @param string $UA
409 */
410 public function setUserAgent( $UA ) {
411 $this->setHeader( 'User-Agent', $UA );
412 }
413
414 /**
415 * Set an arbitrary header
416 * @param string $name
417 * @param string $value
418 */
419 public function setHeader( $name, $value ) {
420 // I feel like I should normalize the case here...
421 $this->reqHeaders[$name] = $value;
422 }
423
424 /**
425 * Get an array of the headers
426 * @return array
427 */
428 public function getHeaderList() {
429 $list = array();
430
431 if ( $this->cookieJar ) {
432 $this->reqHeaders['Cookie'] =
433 $this->cookieJar->serializeToHttpRequest(
434 $this->parsedUrl['path'],
435 $this->parsedUrl['host']
436 );
437 }
438
439 foreach ( $this->reqHeaders as $name => $value ) {
440 $list[] = "$name: $value";
441 }
442
443 return $list;
444 }
445
446 /**
447 * Set a read callback to accept data read from the HTTP request.
448 * By default, data is appended to an internal buffer which can be
449 * retrieved through $req->getContent().
450 *
451 * To handle data as it comes in -- especially for large files that
452 * would not fit in memory -- you can instead set your own callback,
453 * in the form function($resource, $buffer) where the first parameter
454 * is the low-level resource being read (implementation specific),
455 * and the second parameter is the data buffer.
456 *
457 * You MUST return the number of bytes handled in the buffer; if fewer
458 * bytes are reported handled than were passed to you, the HTTP fetch
459 * will be aborted.
460 *
461 * @param callable $callback
462 * @throws MWException
463 */
464 public function setCallback( $callback ) {
465 if ( !is_callable( $callback ) ) {
466 throw new MWException( 'Invalid MwHttpRequest callback' );
467 }
468 $this->callback = $callback;
469 }
470
471 /**
472 * A generic callback to read the body of the response from a remote
473 * server.
474 *
475 * @param resource $fh
476 * @param string $content
477 * @return int
478 */
479 public function read( $fh, $content ) {
480 $this->content .= $content;
481 return strlen( $content );
482 }
483
484 /**
485 * Take care of whatever is necessary to perform the URI request.
486 *
487 * @return Status
488 */
489 public function execute() {
490
491 $this->content = "";
492
493 if ( strtoupper( $this->method ) == "HEAD" ) {
494 $this->headersOnly = true;
495 }
496
497 $this->proxySetup(); // set up any proxy as needed
498
499 if ( !$this->callback ) {
500 $this->setCallback( array( $this, 'read' ) );
501 }
502
503 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
504 $this->setUserAgent( Http::userAgent() );
505 }
506
507 }
508
509 /**
510 * Parses the headers, including the HTTP status code and any
511 * Set-Cookie headers. This function expects the headers to be
512 * found in an array in the member variable headerList.
513 */
514 protected function parseHeader() {
515
516 $lastname = "";
517
518 foreach ( $this->headerList as $header ) {
519 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
520 $this->respVersion = $match[1];
521 $this->respStatus = $match[2];
522 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
523 $last = count( $this->respHeaders[$lastname] ) - 1;
524 $this->respHeaders[$lastname][$last] .= "\r\n$header";
525 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
526 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
527 $lastname = strtolower( $match[1] );
528 }
529 }
530
531 $this->parseCookies();
532
533 }
534
535 /**
536 * Sets HTTPRequest status member to a fatal value with the error
537 * message if the returned integer value of the status code was
538 * not successful (< 300) or a redirect (>=300 and < 400). (see
539 * RFC2616, section 10,
540 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
541 * list of status codes.)
542 */
543 protected function setStatus() {
544 if ( !$this->respHeaders ) {
545 $this->parseHeader();
546 }
547
548 if ( (int)$this->respStatus > 399 ) {
549 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
550 $this->status->fatal( "http-bad-status", $code, $message );
551 }
552 }
553
554 /**
555 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
556 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
557 * for a list of status codes.)
558 *
559 * @return int
560 */
561 public function getStatus() {
562 if ( !$this->respHeaders ) {
563 $this->parseHeader();
564 }
565
566 return (int)$this->respStatus;
567 }
568
569 /**
570 * Returns true if the last status code was a redirect.
571 *
572 * @return bool
573 */
574 public function isRedirect() {
575 if ( !$this->respHeaders ) {
576 $this->parseHeader();
577 }
578
579 $status = (int)$this->respStatus;
580
581 if ( $status >= 300 && $status <= 303 ) {
582 return true;
583 }
584
585 return false;
586 }
587
588 /**
589 * Returns an associative array of response headers after the
590 * request has been executed. Because some headers
591 * (e.g. Set-Cookie) can appear more than once the, each value of
592 * the associative array is an array of the values given.
593 *
594 * @return array
595 */
596 public function getResponseHeaders() {
597 if ( !$this->respHeaders ) {
598 $this->parseHeader();
599 }
600
601 return $this->respHeaders;
602 }
603
604 /**
605 * Returns the value of the given response header.
606 *
607 * @param string $header
608 * @return string
609 */
610 public function getResponseHeader( $header ) {
611 if ( !$this->respHeaders ) {
612 $this->parseHeader();
613 }
614
615 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
616 $v = $this->respHeaders[strtolower( $header )];
617 return $v[count( $v ) - 1];
618 }
619
620 return null;
621 }
622
623 /**
624 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
625 *
626 * @param CookieJar $jar
627 */
628 public function setCookieJar( $jar ) {
629 $this->cookieJar = $jar;
630 }
631
632 /**
633 * Returns the cookie jar in use.
634 *
635 * @return CookieJar
636 */
637 public function getCookieJar() {
638 if ( !$this->respHeaders ) {
639 $this->parseHeader();
640 }
641
642 return $this->cookieJar;
643 }
644
645 /**
646 * Sets a cookie. Used before a request to set up any individual
647 * cookies. Used internally after a request to parse the
648 * Set-Cookie headers.
649 * @see Cookie::set
650 * @param string $name
651 * @param mixed $value
652 * @param array $attr
653 */
654 public function setCookie( $name, $value = null, $attr = null ) {
655 if ( !$this->cookieJar ) {
656 $this->cookieJar = new CookieJar;
657 }
658
659 $this->cookieJar->setCookie( $name, $value, $attr );
660 }
661
662 /**
663 * Parse the cookies in the response headers and store them in the cookie jar.
664 */
665 protected function parseCookies() {
666
667 if ( !$this->cookieJar ) {
668 $this->cookieJar = new CookieJar;
669 }
670
671 if ( isset( $this->respHeaders['set-cookie'] ) ) {
672 $url = parse_url( $this->getFinalUrl() );
673 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
674 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
675 }
676 }
677
678 }
679
680 /**
681 * Returns the final URL after all redirections.
682 *
683 * Relative values of the "Location" header are incorrect as
684 * stated in RFC, however they do happen and modern browsers
685 * support them. This function loops backwards through all
686 * locations in order to build the proper absolute URI - Marooned
687 * at wikia-inc.com
688 *
689 * Note that the multiple Location: headers are an artifact of
690 * CURL -- they shouldn't actually get returned this way. Rewrite
691 * this when bug 29232 is taken care of (high-level redirect
692 * handling rewrite).
693 *
694 * @return string
695 */
696 public function getFinalUrl() {
697 $headers = $this->getResponseHeaders();
698
699 // return full url (fix for incorrect but handled relative location)
700 if ( isset( $headers['location'] ) ) {
701 $locations = $headers['location'];
702 $domain = '';
703 $foundRelativeURI = false;
704 $countLocations = count( $locations );
705
706 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
707 $url = parse_url( $locations[$i] );
708
709 if ( isset( $url['host'] ) ) {
710 $domain = $url['scheme'] . '://' . $url['host'];
711 break; // found correct URI (with host)
712 } else {
713 $foundRelativeURI = true;
714 }
715 }
716
717 if ( $foundRelativeURI ) {
718 if ( $domain ) {
719 return $domain . $locations[$countLocations - 1];
720 } else {
721 $url = parse_url( $this->url );
722 if ( isset( $url['host'] ) ) {
723 return $url['scheme'] . '://' . $url['host'] .
724 $locations[$countLocations - 1];
725 }
726 }
727 } else {
728 return $locations[$countLocations - 1];
729 }
730 }
731
732 return $this->url;
733 }
734
735 /**
736 * Returns true if the backend can follow redirects. Overridden by the
737 * child classes.
738 * @return bool
739 */
740 public function canFollowRedirects() {
741 return true;
742 }
743 }
744
745 /**
746 * MWHttpRequest implemented using internal curl compiled into PHP
747 */
748 class CurlHttpRequest extends MWHttpRequest {
749 const SUPPORTS_FILE_POSTS = true;
750
751 protected $curlOptions = array();
752 protected $headerText = "";
753
754 /**
755 * @param resource $fh
756 * @param string $content
757 * @return int
758 */
759 protected function readHeader( $fh, $content ) {
760 $this->headerText .= $content;
761 return strlen( $content );
762 }
763
764 public function execute() {
765
766 parent::execute();
767
768 if ( !$this->status->isOK() ) {
769 return $this->status;
770 }
771
772 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
773 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
774
775 // Only supported in curl >= 7.16.2
776 if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) {
777 $this->curlOptions[CURLOPT_CONNECTTIMEOUT_MS] = $this->connectTimeout * 1000;
778 }
779
780 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
781 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
782 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array( $this, "readHeader" );
783 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
784 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
785
786 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
787
788 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost ? 2 : 0;
789 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
790
791 if ( $this->caInfo ) {
792 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
793 }
794
795 if ( $this->headersOnly ) {
796 $this->curlOptions[CURLOPT_NOBODY] = true;
797 $this->curlOptions[CURLOPT_HEADER] = true;
798 } elseif ( $this->method == 'POST' ) {
799 $this->curlOptions[CURLOPT_POST] = true;
800 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
801 // Suppress 'Expect: 100-continue' header, as some servers
802 // will reject it with a 417 and Curl won't auto retry
803 // with HTTP 1.0 fallback
804 $this->reqHeaders['Expect'] = '';
805 } else {
806 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
807 }
808
809 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
810
811 $curlHandle = curl_init( $this->url );
812
813 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
814 throw new MWException( "Error setting curl options." );
815 }
816
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
824 }
825 MediaWiki\restoreWarnings();
826 }
827
828 if ( $this->profiler ) {
829 $profileSection = $this->profiler->scopedProfileIn(
830 __METHOD__ . '-' . $this->profileName
831 );
832 }
833
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 ) );
839 } else {
840 $this->headerList = explode( "\r\n", $this->headerText );
841 }
842
843 curl_close( $curlHandle );
844
845 if ( $this->profiler ) {
846 $this->profiler->scopedProfileOut( $profileSection );
847 }
848
849 $this->parseHeader();
850 $this->setStatus();
851
852 return $this->status;
853 }
854
855 /**
856 * @return bool
857 */
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" );
862 return false;
863 }
864
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" );
868 return false;
869 }
870 }
871
872 return true;
873 }
874 }
875
876 class PhpHttpRequest extends MWHttpRequest {
877
878 private $fopenErrors = array();
879
880 /**
881 * @param string $url
882 * @return string
883 */
884 protected function urlToTcp( $url ) {
885 $parsedUrl = parse_url( $url );
886
887 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
888 }
889
890 /**
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.
896 * @return array
897 * @throws DomainException
898 */
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
920 ) );
921 }
922
923 foreach ( $certLocations as $key => $cert ) {
924 if ( is_dir( $cert ) ) {
925 $certOptions['capath'] = $cert;
926 break;
927 } elseif ( is_file( $cert ) ) {
928 $certOptions['cafile'] = $cert;
929 break;
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" );
933 }
934 }
935
936 return $certOptions;
937 }
938
939 /**
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.
945 */
946 public function errorHandler( $errno, $errstr ) {
947 $n = count( $this->fopenErrors ) + 1;
948 $this->fopenErrors += array( "errno$n" => $errno, "errstr$n" => $errstr );
949 }
950
951 public function execute() {
952
953 parent::execute();
954
955 if ( is_array( $this->postData ) ) {
956 $this->postData = wfArrayToCgi( $this->postData );
957 }
958
959 if ( $this->parsedUrl['scheme'] != 'http'
960 && $this->parsedUrl['scheme'] != 'https' ) {
961 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
962 }
963
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";
971 }
972 }
973
974 // Set up PHP stream context
975 $options = array(
976 'http' => array(
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,
986 ),
987 'ssl' => array(
988 'verify_peer' => $this->sslVerifyCert,
989 'SNI_enabled' => true,
990 'ciphers' => 'HIGH:!SSLv2:!SSLv3:-ADH:-kDH:-kECDH:-DSS',
991 'disable_compression' => true,
992 ),
993 );
994
995 if ( $this->proxy ) {
996 $options['http']['proxy'] = $this->urlToTCP( $this->proxy );
997 $options['http']['request_fulluri'] = true;
998 }
999
1000 if ( $this->postData ) {
1001 $options['http']['content'] = $this->postData;
1002 }
1003
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'];
1009 } else {
1010 $options['ssl']['CN_match'] = $this->parsedUrl['host'];
1011 }
1012 }
1013
1014 $options['ssl'] += $this->getCertOptions();
1015
1016 $context = stream_context_create( $options );
1017
1018 $this->headerList = array();
1019 $reqCount = 0;
1020 $url = $this->url;
1021
1022 $result = array();
1023
1024 if ( $this->profiler ) {
1025 $profileSection = $this->profiler->scopedProfileIn(
1026 __METHOD__ . '-' . $this->profileName
1027 );
1028 }
1029 do {
1030 $reqCount++;
1031 $this->fopenErrors = array();
1032 set_error_handler( array( $this, 'errorHandler' ) );
1033 $fh = fopen( $url, "r", false, $context );
1034 restore_error_handler();
1035
1036 if ( !$fh ) {
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' )
1045 ) {
1046 $options['ssl']['CN_match'] = 'en.wikipedia.org';
1047 $context = stream_context_create( $options );
1048 continue;
1049 }
1050 break;
1051 }
1052
1053 $result = stream_get_meta_data( $fh );
1054 $this->headerList = $result['wrapper_data'];
1055 $this->parseHeader();
1056
1057 if ( !$this->followRedirects ) {
1058 break;
1059 }
1060
1061 # Handle manual redirection
1062 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
1063 break;
1064 }
1065 # Check security of URL
1066 $url = $this->getResponseHeader( "Location" );
1067
1068 if ( !Http::isValidURI( $url ) ) {
1069 wfDebug( __METHOD__ . ": insecure redirection\n" );
1070 break;
1071 }
1072 } while ( true );
1073 if ( $this->profiler ) {
1074 $this->profiler->scopedProfileOut( $profileSection );
1075 }
1076
1077 $this->setStatus();
1078
1079 if ( $fh === false ) {
1080 if ( $this->fopenErrors ) {
1081 LoggerFactory::getInstance( 'http' )->warning( __CLASS__
1082 . ': error opening connection: {errstr1}', $this->fopenErrors );
1083 }
1084 $this->status->fatal( 'http-request-error' );
1085 return $this->status;
1086 }
1087
1088 if ( $result['timed_out'] ) {
1089 $this->status->fatal( 'http-timed-out', $this->url );
1090 return $this->status;
1091 }
1092
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 );
1098
1099 if ( $buf === false ) {
1100 $this->status->fatal( 'http-read-error' );
1101 break;
1102 }
1103
1104 if ( strlen( $buf ) ) {
1105 call_user_func( $this->callback, $fh, $buf );
1106 }
1107 }
1108 }
1109 fclose( $fh );
1110
1111 return $this->status;
1112 }
1113 }