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