Merge "maintenance: Script to rename titles for Unicode uppercasing changes"
[lhc/web/wiklou.git] / includes / http / MWHttpRequest.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 use Psr\Log\LoggerInterface;
22 use Psr\Log\LoggerAwareInterface;
23 use Psr\Log\NullLogger;
24
25 /**
26 * This wrapper class will call out to curl (if available) or fallback
27 * to regular PHP if necessary for handling internal HTTP requests.
28 *
29 * Renamed from HttpRequest to MWHttpRequest to avoid conflict with
30 * PHP's HTTP extension.
31 */
32 abstract class MWHttpRequest implements LoggerAwareInterface {
33 const SUPPORTS_FILE_POSTS = false;
34
35 /**
36 * @var int|string
37 */
38 protected $timeout = 'default';
39
40 protected $content;
41 protected $headersOnly = null;
42 protected $postData = null;
43 protected $proxy = null;
44 protected $noProxy = false;
45 protected $sslVerifyHost = true;
46 protected $sslVerifyCert = true;
47 protected $caInfo = null;
48 protected $method = "GET";
49 protected $reqHeaders = [];
50 protected $url;
51 protected $parsedUrl;
52 /** @var callable */
53 protected $callback;
54 protected $maxRedirects = 5;
55 protected $followRedirects = false;
56 protected $connectTimeout;
57
58 /**
59 * @var CookieJar
60 */
61 protected $cookieJar;
62
63 protected $headerList = [];
64 protected $respVersion = "0.9";
65 protected $respStatus = "200 Ok";
66 protected $respHeaders = [];
67
68 /** @var StatusValue */
69 protected $status;
70
71 /**
72 * @var Profiler
73 */
74 protected $profiler;
75
76 /**
77 * @var string
78 */
79 protected $profileName;
80
81 /**
82 * @var LoggerInterface
83 */
84 protected $logger;
85
86 /**
87 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
88 * @param array $options (optional) extra params to pass (see HttpRequestFactory::create())
89 * @param string $caller The method making this request, for profiling
90 * @param Profiler|null $profiler An instance of the profiler for profiling, or null
91 * @throws Exception
92 */
93 public function __construct(
94 $url, array $options = [], $caller = __METHOD__, Profiler $profiler = null
95 ) {
96 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
97
98 $this->url = wfExpandUrl( $url, PROTO_HTTP );
99 $this->parsedUrl = wfParseUrl( $this->url );
100
101 $this->logger = $options['logger'] ?? new NullLogger();
102
103 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
104 $this->status = StatusValue::newFatal( 'http-invalid-url', $url );
105 } else {
106 $this->status = StatusValue::newGood( 100 ); // continue
107 }
108
109 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
110 $this->timeout = $options['timeout'];
111 } else {
112 $this->timeout = $wgHTTPTimeout;
113 }
114 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
115 $this->connectTimeout = $options['connectTimeout'];
116 } else {
117 $this->connectTimeout = $wgHTTPConnectTimeout;
118 }
119 if ( isset( $options['userAgent'] ) ) {
120 $this->setUserAgent( $options['userAgent'] );
121 }
122 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
123 $this->setHeader(
124 'Authorization',
125 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
126 );
127 }
128 if ( isset( $options['originalRequest'] ) ) {
129 $this->setOriginalRequest( $options['originalRequest'] );
130 }
131
132 $this->setHeader( 'X-Request-Id', WebRequest::getRequestId() );
133
134 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
135 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
136
137 foreach ( $members as $o ) {
138 if ( isset( $options[$o] ) ) {
139 // ensure that MWHttpRequest::method is always
140 // uppercased. T38137
141 if ( $o == 'method' ) {
142 $options[$o] = strtoupper( $options[$o] );
143 }
144 $this->$o = $options[$o];
145 }
146 }
147
148 if ( $this->noProxy ) {
149 $this->proxy = ''; // noProxy takes precedence
150 }
151
152 // Profile based on what's calling us
153 $this->profiler = $profiler;
154 $this->profileName = $caller;
155 }
156
157 /**
158 * @param LoggerInterface $logger
159 */
160 public function setLogger( LoggerInterface $logger ) {
161 $this->logger = $logger;
162 }
163
164 /**
165 * Simple function to test if we can make any sort of requests at all, using
166 * cURL or fopen()
167 * @return bool
168 */
169 public static function canMakeRequests() {
170 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
171 }
172
173 /**
174 * Generate a new request object
175 * @deprecated since 1.34, use HttpRequestFactory instead
176 * @param string $url Url to use
177 * @param array|null $options (optional) extra params to pass (see HttpRequestFactory::create())
178 * @param string $caller The method making this request, for profiling
179 * @throws DomainException
180 * @return MWHttpRequest
181 * @see MWHttpRequest::__construct
182 */
183 public static function factory( $url, array $options = null, $caller = __METHOD__ ) {
184 if ( $options === null ) {
185 $options = [];
186 }
187 return \MediaWiki\MediaWikiServices::getInstance()
188 ->getHttpRequestFactory()
189 ->create( $url, $options, $caller );
190 }
191
192 /**
193 * Get the body, or content, of the response to the request
194 *
195 * @return string
196 */
197 public function getContent() {
198 return $this->content;
199 }
200
201 /**
202 * Set the parameters of the request
203 *
204 * @param array $args
205 * @todo overload the args param
206 */
207 public function setData( array $args ) {
208 $this->postData = $args;
209 }
210
211 /**
212 * Take care of setting up the proxy (do nothing if "noProxy" is set)
213 *
214 * @return void
215 */
216 protected function proxySetup() {
217 // If there is an explicit proxy set and proxies are not disabled, then use it
218 if ( $this->proxy && !$this->noProxy ) {
219 return;
220 }
221
222 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
223 // local URL and proxies are not disabled
224 if ( self::isLocalURL( $this->url ) || $this->noProxy ) {
225 $this->proxy = '';
226 } else {
227 global $wgHTTPProxy;
228 $this->proxy = (string)$wgHTTPProxy;
229 }
230 }
231
232 /**
233 * Check if the URL can be served by localhost
234 *
235 * @param string $url Full url to check
236 * @return bool
237 */
238 private static function isLocalURL( $url ) {
239 global $wgCommandLineMode, $wgLocalVirtualHosts;
240
241 if ( $wgCommandLineMode ) {
242 return false;
243 }
244
245 // Extract host part
246 $matches = [];
247 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
248 $host = $matches[1];
249 // Split up dotwise
250 $domainParts = explode( '.', $host );
251 // Check if this domain or any superdomain is listed as a local virtual host
252 $domainParts = array_reverse( $domainParts );
253
254 $domain = '';
255 $countParts = count( $domainParts );
256 for ( $i = 0; $i < $countParts; $i++ ) {
257 $domainPart = $domainParts[$i];
258 if ( $i == 0 ) {
259 $domain = $domainPart;
260 } else {
261 $domain = $domainPart . '.' . $domain;
262 }
263
264 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
265 return true;
266 }
267 }
268 }
269
270 return false;
271 }
272
273 /**
274 * Set the user agent
275 * @param string $UA
276 */
277 public function setUserAgent( $UA ) {
278 $this->setHeader( 'User-Agent', $UA );
279 }
280
281 /**
282 * Set an arbitrary header
283 * @param string $name
284 * @param string $value
285 */
286 public function setHeader( $name, $value ) {
287 // I feel like I should normalize the case here...
288 $this->reqHeaders[$name] = $value;
289 }
290
291 /**
292 * Get an array of the headers
293 * @return array
294 */
295 protected function getHeaderList() {
296 $list = [];
297
298 if ( $this->cookieJar ) {
299 $this->reqHeaders['Cookie'] =
300 $this->cookieJar->serializeToHttpRequest(
301 $this->parsedUrl['path'],
302 $this->parsedUrl['host']
303 );
304 }
305
306 foreach ( $this->reqHeaders as $name => $value ) {
307 $list[] = "$name: $value";
308 }
309
310 return $list;
311 }
312
313 /**
314 * Set a read callback to accept data read from the HTTP request.
315 * By default, data is appended to an internal buffer which can be
316 * retrieved through $req->getContent().
317 *
318 * To handle data as it comes in -- especially for large files that
319 * would not fit in memory -- you can instead set your own callback,
320 * in the form function($resource, $buffer) where the first parameter
321 * is the low-level resource being read (implementation specific),
322 * and the second parameter is the data buffer.
323 *
324 * You MUST return the number of bytes handled in the buffer; if fewer
325 * bytes are reported handled than were passed to you, the HTTP fetch
326 * will be aborted.
327 *
328 * @param callable|null $callback
329 * @throws InvalidArgumentException
330 */
331 public function setCallback( $callback ) {
332 return $this->doSetCallback( $callback );
333 }
334
335 /**
336 * Worker function for setting callbacks. Calls can originate both internally and externally
337 * via setCallback). Defaults to the internal read callback if $callback is null.
338 *
339 * @param callable|null $callback
340 * @throws InvalidArgumentException
341 */
342 protected function doSetCallback( $callback ) {
343 if ( is_null( $callback ) ) {
344 $callback = [ $this, 'read' ];
345 } elseif ( !is_callable( $callback ) ) {
346 $this->status->fatal( 'http-internal-error' );
347 throw new InvalidArgumentException( __METHOD__ . ': invalid callback' );
348 }
349 $this->callback = $callback;
350 }
351
352 /**
353 * A generic callback to read the body of the response from a remote
354 * server.
355 *
356 * @param resource $fh
357 * @param string $content
358 * @return int
359 * @internal
360 */
361 public function read( $fh, $content ) {
362 $this->content .= $content;
363 return strlen( $content );
364 }
365
366 /**
367 * Take care of whatever is necessary to perform the URI request.
368 *
369 * @return StatusValue
370 * @note currently returns Status for B/C
371 */
372 public function execute() {
373 throw new LogicException( 'children must override this' );
374 }
375
376 protected function prepare() {
377 $this->content = "";
378
379 if ( strtoupper( $this->method ) == "HEAD" ) {
380 $this->headersOnly = true;
381 }
382
383 $this->proxySetup(); // set up any proxy as needed
384
385 if ( !$this->callback ) {
386 $this->doSetCallback( null );
387 }
388
389 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
390 $this->setUserAgent( Http::userAgent() );
391 }
392 }
393
394 /**
395 * Parses the headers, including the HTTP status code and any
396 * Set-Cookie headers. This function expects the headers to be
397 * found in an array in the member variable headerList.
398 */
399 protected function parseHeader() {
400 $lastname = "";
401
402 // Failure without (valid) headers gets a response status of zero
403 if ( !$this->status->isOK() ) {
404 $this->respStatus = '0 Error';
405 }
406
407 foreach ( $this->headerList as $header ) {
408 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
409 $this->respVersion = $match[1];
410 $this->respStatus = $match[2];
411 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
412 $last = count( $this->respHeaders[$lastname] ) - 1;
413 $this->respHeaders[$lastname][$last] .= "\r\n$header";
414 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
415 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
416 $lastname = strtolower( $match[1] );
417 }
418 }
419
420 $this->parseCookies();
421 }
422
423 /**
424 * Sets HTTPRequest status member to a fatal value with the error
425 * message if the returned integer value of the status code was
426 * not successful (1-299) or a redirect (300-399).
427 * See RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
428 * for a list of status codes.
429 */
430 protected function setStatus() {
431 if ( !$this->respHeaders ) {
432 $this->parseHeader();
433 }
434
435 if ( ( (int)$this->respStatus > 0 && (int)$this->respStatus < 400 ) ) {
436 $this->status->setResult( true, (int)$this->respStatus );
437 } else {
438 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
439 $this->status->setResult( false, (int)$this->respStatus );
440 $this->status->fatal( "http-bad-status", $code, $message );
441 }
442 }
443
444 /**
445 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
446 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
447 * for a list of status codes.)
448 *
449 * @return int
450 */
451 public function getStatus() {
452 if ( !$this->respHeaders ) {
453 $this->parseHeader();
454 }
455
456 return (int)$this->respStatus;
457 }
458
459 /**
460 * Returns true if the last status code was a redirect.
461 *
462 * @return bool
463 */
464 public function isRedirect() {
465 if ( !$this->respHeaders ) {
466 $this->parseHeader();
467 }
468
469 $status = (int)$this->respStatus;
470
471 if ( $status >= 300 && $status <= 303 ) {
472 return true;
473 }
474
475 return false;
476 }
477
478 /**
479 * Returns an associative array of response headers after the
480 * request has been executed. Because some headers
481 * (e.g. Set-Cookie) can appear more than once the, each value of
482 * the associative array is an array of the values given.
483 * Header names are always in lowercase.
484 *
485 * @return array
486 */
487 public function getResponseHeaders() {
488 if ( !$this->respHeaders ) {
489 $this->parseHeader();
490 }
491
492 return $this->respHeaders;
493 }
494
495 /**
496 * Returns the value of the given response header.
497 *
498 * @param string $header case-insensitive
499 * @return string|null
500 */
501 public function getResponseHeader( $header ) {
502 if ( !$this->respHeaders ) {
503 $this->parseHeader();
504 }
505
506 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
507 $v = $this->respHeaders[strtolower( $header )];
508 return $v[count( $v ) - 1];
509 }
510
511 return null;
512 }
513
514 /**
515 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
516 *
517 * To read response cookies from the jar, getCookieJar must be called first.
518 *
519 * @param CookieJar $jar
520 */
521 public function setCookieJar( CookieJar $jar ) {
522 $this->cookieJar = $jar;
523 }
524
525 /**
526 * Returns the cookie jar in use.
527 *
528 * @return CookieJar
529 */
530 public function getCookieJar() {
531 if ( !$this->respHeaders ) {
532 $this->parseHeader();
533 }
534
535 return $this->cookieJar;
536 }
537
538 /**
539 * Sets a cookie. Used before a request to set up any individual
540 * cookies. Used internally after a request to parse the
541 * Set-Cookie headers.
542 * @see Cookie::set
543 * @param string $name
544 * @param string $value
545 * @param array $attr
546 */
547 public function setCookie( $name, $value, array $attr = [] ) {
548 if ( !$this->cookieJar ) {
549 $this->cookieJar = new CookieJar;
550 }
551
552 if ( $this->parsedUrl && !isset( $attr['domain'] ) ) {
553 $attr['domain'] = $this->parsedUrl['host'];
554 }
555
556 $this->cookieJar->setCookie( $name, $value, $attr );
557 }
558
559 /**
560 * Parse the cookies in the response headers and store them in the cookie jar.
561 */
562 protected function parseCookies() {
563 if ( !$this->cookieJar ) {
564 $this->cookieJar = new CookieJar;
565 }
566
567 if ( isset( $this->respHeaders['set-cookie'] ) ) {
568 $url = parse_url( $this->getFinalUrl() );
569 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
570 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
571 }
572 }
573 }
574
575 /**
576 * Returns the final URL after all redirections.
577 *
578 * Relative values of the "Location" header are incorrect as
579 * stated in RFC, however they do happen and modern browsers
580 * support them. This function loops backwards through all
581 * locations in order to build the proper absolute URI - Marooned
582 * at wikia-inc.com
583 *
584 * Note that the multiple Location: headers are an artifact of
585 * CURL -- they shouldn't actually get returned this way. Rewrite
586 * this when T31232 is taken care of (high-level redirect
587 * handling rewrite).
588 *
589 * @return string
590 */
591 public function getFinalUrl() {
592 $headers = $this->getResponseHeaders();
593
594 // return full url (fix for incorrect but handled relative location)
595 if ( isset( $headers['location'] ) ) {
596 $locations = $headers['location'];
597 $domain = '';
598 $foundRelativeURI = false;
599 $countLocations = count( $locations );
600
601 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
602 $url = parse_url( $locations[$i] );
603
604 if ( isset( $url['host'] ) ) {
605 $domain = $url['scheme'] . '://' . $url['host'];
606 break; // found correct URI (with host)
607 } else {
608 $foundRelativeURI = true;
609 }
610 }
611
612 if ( !$foundRelativeURI ) {
613 return $locations[$countLocations - 1];
614 }
615 if ( $domain ) {
616 return $domain . $locations[$countLocations - 1];
617 }
618 $url = parse_url( $this->url );
619 if ( isset( $url['host'] ) ) {
620 return $url['scheme'] . '://' . $url['host'] .
621 $locations[$countLocations - 1];
622 }
623 }
624
625 return $this->url;
626 }
627
628 /**
629 * Returns true if the backend can follow redirects. Overridden by the
630 * child classes.
631 * @return bool
632 */
633 public function canFollowRedirects() {
634 return true;
635 }
636
637 /**
638 * Set information about the original request. This can be useful for
639 * endpoints/API modules which act as a proxy for some service, and
640 * throttling etc. needs to happen in that service.
641 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
642 * headers being set.
643 * @param WebRequest|array $originalRequest When in array form, it's
644 * expected to have the keys 'ip' and 'userAgent'.
645 * @note IP/user agent is personally identifiable information, and should
646 * only be set when the privacy policy of the request target is
647 * compatible with that of the MediaWiki installation.
648 */
649 public function setOriginalRequest( $originalRequest ) {
650 if ( $originalRequest instanceof WebRequest ) {
651 $originalRequest = [
652 'ip' => $originalRequest->getIP(),
653 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
654 ];
655 } elseif (
656 !is_array( $originalRequest )
657 || array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
658 ) {
659 throw new InvalidArgumentException( __METHOD__ . ': $originalRequest must be a '
660 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
661 }
662
663 $this->reqHeaders['X-Forwarded-For'] = $originalRequest['ip'];
664 $this->reqHeaders['X-Original-User-Agent'] = $originalRequest['userAgent'];
665 }
666
667 /**
668 * Check that the given URI is a valid one.
669 *
670 * This hardcodes a small set of protocols only, because we want to
671 * deterministically reject protocols not supported by all HTTP-transport
672 * methods.
673 *
674 * "file://" specifically must not be allowed, for security reasons
675 * (see <https://www.mediawiki.org/wiki/Special:Code/MediaWiki/r67684>).
676 *
677 * @todo FIXME this is wildly inaccurate and fails to actually check most stuff
678 *
679 * @since 1.34
680 * @param string $uri URI to check for validity
681 * @return bool
682 */
683 public static function isValidURI( $uri ) {
684 return (bool)preg_match(
685 '/^https?:\/\/[^\/\s]\S*$/D',
686 $uri
687 );
688 }
689 }