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