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