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