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