Merge "Warn if stateful ParserOutput transforms are used"
[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 $profiler An instance of the profiler for profiling, or null
91 */
92 public function __construct(
93 $url, array $options = [], $caller = __METHOD__, $profiler = null
94 ) {
95 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
96
97 $this->url = wfExpandUrl( $url, PROTO_HTTP );
98 $this->parsedUrl = wfParseUrl( $this->url );
99
100 if ( isset( $options['logger'] ) ) {
101 $this->logger = $options['logger'];
102 } else {
103 $this->logger = new NullLogger();
104 }
105
106 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
107 $this->status = StatusValue::newFatal( 'http-invalid-url', $url );
108 } else {
109 $this->status = StatusValue::newGood( 100 ); // continue
110 }
111
112 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
113 $this->timeout = $options['timeout'];
114 } else {
115 $this->timeout = $wgHTTPTimeout;
116 }
117 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
118 $this->connectTimeout = $options['connectTimeout'];
119 } else {
120 $this->connectTimeout = $wgHTTPConnectTimeout;
121 }
122 if ( isset( $options['userAgent'] ) ) {
123 $this->setUserAgent( $options['userAgent'] );
124 }
125 if ( isset( $options['username'] ) && isset( $options['password'] ) ) {
126 $this->setHeader(
127 'Authorization',
128 'Basic ' . base64_encode( $options['username'] . ':' . $options['password'] )
129 );
130 }
131 if ( isset( $options['originalRequest'] ) ) {
132 $this->setOriginalRequest( $options['originalRequest'] );
133 }
134
135 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
136 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
137
138 foreach ( $members as $o ) {
139 if ( isset( $options[$o] ) ) {
140 // ensure that MWHttpRequest::method is always
141 // uppercased. T38137
142 if ( $o == 'method' ) {
143 $options[$o] = strtoupper( $options[$o] );
144 }
145 $this->$o = $options[$o];
146 }
147 }
148
149 if ( $this->noProxy ) {
150 $this->proxy = ''; // noProxy takes precedence
151 }
152
153 // Profile based on what's calling us
154 $this->profiler = $profiler;
155 $this->profileName = $caller;
156 }
157
158 /**
159 * @param LoggerInterface $logger
160 */
161 public function setLogger( LoggerInterface $logger ) {
162 $this->logger = $logger;
163 }
164
165 /**
166 * Simple function to test if we can make any sort of requests at all, using
167 * cURL or fopen()
168 * @return bool
169 */
170 public static function canMakeRequests() {
171 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
172 }
173
174 /**
175 * Generate a new request object
176 * Deprecated: @see HttpRequestFactory::create
177 * @param string $url Url to use
178 * @param array $options (optional) extra params to pass (see Http::request())
179 * @param string $caller The method making this request, for profiling
180 * @throws DomainException
181 * @return MWHttpRequest
182 * @see MWHttpRequest::__construct
183 */
184 public static function factory( $url, array $options = [], $caller = __METHOD__ ) {
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( $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 if ( is_null( $callback ) ) {
330 $callback = [ $this, 'read' ];
331 } elseif ( !is_callable( $callback ) ) {
332 throw new InvalidArgumentException( __METHOD__ . ': invalid callback' );
333 }
334 $this->callback = $callback;
335 }
336
337 /**
338 * A generic callback to read the body of the response from a remote
339 * server.
340 *
341 * @param resource $fh
342 * @param string $content
343 * @return int
344 * @internal
345 */
346 public function read( $fh, $content ) {
347 $this->content .= $content;
348 return strlen( $content );
349 }
350
351 /**
352 * Take care of whatever is necessary to perform the URI request.
353 *
354 * @return StatusValue
355 * @note currently returns Status for B/C
356 */
357 public function execute() {
358 throw new LogicException( 'children must override this' );
359 }
360
361 protected function prepare() {
362 $this->content = "";
363
364 if ( strtoupper( $this->method ) == "HEAD" ) {
365 $this->headersOnly = true;
366 }
367
368 $this->proxySetup(); // set up any proxy as needed
369
370 if ( !$this->callback ) {
371 $this->setCallback( null );
372 }
373
374 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
375 $this->setUserAgent( Http::userAgent() );
376 }
377 }
378
379 /**
380 * Parses the headers, including the HTTP status code and any
381 * Set-Cookie headers. This function expects the headers to be
382 * found in an array in the member variable headerList.
383 */
384 protected function parseHeader() {
385 $lastname = "";
386
387 foreach ( $this->headerList as $header ) {
388 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
389 $this->respVersion = $match[1];
390 $this->respStatus = $match[2];
391 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
392 $last = count( $this->respHeaders[$lastname] ) - 1;
393 $this->respHeaders[$lastname][$last] .= "\r\n$header";
394 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
395 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
396 $lastname = strtolower( $match[1] );
397 }
398 }
399
400 $this->parseCookies();
401 }
402
403 /**
404 * Sets HTTPRequest status member to a fatal value with the error
405 * message if the returned integer value of the status code was
406 * not successful (< 300) or a redirect (>=300 and < 400). (see
407 * RFC2616, section 10,
408 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
409 * list of status codes.)
410 */
411 protected function setStatus() {
412 if ( !$this->respHeaders ) {
413 $this->parseHeader();
414 }
415
416 if ( (int)$this->respStatus > 399 ) {
417 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
418 $this->status->fatal( "http-bad-status", $code, $message );
419 }
420 }
421
422 /**
423 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
424 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
425 * for a list of status codes.)
426 *
427 * @return int
428 */
429 public function getStatus() {
430 if ( !$this->respHeaders ) {
431 $this->parseHeader();
432 }
433
434 return (int)$this->respStatus;
435 }
436
437 /**
438 * Returns true if the last status code was a redirect.
439 *
440 * @return bool
441 */
442 public function isRedirect() {
443 if ( !$this->respHeaders ) {
444 $this->parseHeader();
445 }
446
447 $status = (int)$this->respStatus;
448
449 if ( $status >= 300 && $status <= 303 ) {
450 return true;
451 }
452
453 return false;
454 }
455
456 /**
457 * Returns an associative array of response headers after the
458 * request has been executed. Because some headers
459 * (e.g. Set-Cookie) can appear more than once the, each value of
460 * the associative array is an array of the values given.
461 *
462 * @return array
463 */
464 public function getResponseHeaders() {
465 if ( !$this->respHeaders ) {
466 $this->parseHeader();
467 }
468
469 return $this->respHeaders;
470 }
471
472 /**
473 * Returns the value of the given response header.
474 *
475 * @param string $header
476 * @return string|null
477 */
478 public function getResponseHeader( $header ) {
479 if ( !$this->respHeaders ) {
480 $this->parseHeader();
481 }
482
483 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
484 $v = $this->respHeaders[strtolower( $header )];
485 return $v[count( $v ) - 1];
486 }
487
488 return null;
489 }
490
491 /**
492 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
493 *
494 * To read response cookies from the jar, getCookieJar must be called first.
495 *
496 * @param CookieJar $jar
497 */
498 public function setCookieJar( $jar ) {
499 $this->cookieJar = $jar;
500 }
501
502 /**
503 * Returns the cookie jar in use.
504 *
505 * @return CookieJar
506 */
507 public function getCookieJar() {
508 if ( !$this->respHeaders ) {
509 $this->parseHeader();
510 }
511
512 return $this->cookieJar;
513 }
514
515 /**
516 * Sets a cookie. Used before a request to set up any individual
517 * cookies. Used internally after a request to parse the
518 * Set-Cookie headers.
519 * @see Cookie::set
520 * @param string $name
521 * @param string $value
522 * @param array $attr
523 */
524 public function setCookie( $name, $value, $attr = [] ) {
525 if ( !$this->cookieJar ) {
526 $this->cookieJar = new CookieJar;
527 }
528
529 if ( $this->parsedUrl && !isset( $attr['domain'] ) ) {
530 $attr['domain'] = $this->parsedUrl['host'];
531 }
532
533 $this->cookieJar->setCookie( $name, $value, $attr );
534 }
535
536 /**
537 * Parse the cookies in the response headers and store them in the cookie jar.
538 */
539 protected function parseCookies() {
540 if ( !$this->cookieJar ) {
541 $this->cookieJar = new CookieJar;
542 }
543
544 if ( isset( $this->respHeaders['set-cookie'] ) ) {
545 $url = parse_url( $this->getFinalUrl() );
546 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
547 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
548 }
549 }
550 }
551
552 /**
553 * Returns the final URL after all redirections.
554 *
555 * Relative values of the "Location" header are incorrect as
556 * stated in RFC, however they do happen and modern browsers
557 * support them. This function loops backwards through all
558 * locations in order to build the proper absolute URI - Marooned
559 * at wikia-inc.com
560 *
561 * Note that the multiple Location: headers are an artifact of
562 * CURL -- they shouldn't actually get returned this way. Rewrite
563 * this when T31232 is taken care of (high-level redirect
564 * handling rewrite).
565 *
566 * @return string
567 */
568 public function getFinalUrl() {
569 $headers = $this->getResponseHeaders();
570
571 // return full url (fix for incorrect but handled relative location)
572 if ( isset( $headers['location'] ) ) {
573 $locations = $headers['location'];
574 $domain = '';
575 $foundRelativeURI = false;
576 $countLocations = count( $locations );
577
578 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
579 $url = parse_url( $locations[$i] );
580
581 if ( isset( $url['host'] ) ) {
582 $domain = $url['scheme'] . '://' . $url['host'];
583 break; // found correct URI (with host)
584 } else {
585 $foundRelativeURI = true;
586 }
587 }
588
589 if ( !$foundRelativeURI ) {
590 return $locations[$countLocations - 1];
591 }
592 if ( $domain ) {
593 return $domain . $locations[$countLocations - 1];
594 }
595 $url = parse_url( $this->url );
596 if ( isset( $url['host'] ) ) {
597 return $url['scheme'] . '://' . $url['host'] .
598 $locations[$countLocations - 1];
599 }
600 }
601
602 return $this->url;
603 }
604
605 /**
606 * Returns true if the backend can follow redirects. Overridden by the
607 * child classes.
608 * @return bool
609 */
610 public function canFollowRedirects() {
611 return true;
612 }
613
614 /**
615 * Set information about the original request. This can be useful for
616 * endpoints/API modules which act as a proxy for some service, and
617 * throttling etc. needs to happen in that service.
618 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
619 * headers being set.
620 * @param WebRequest|array $originalRequest When in array form, it's
621 * expected to have the keys 'ip' and 'userAgent'.
622 * @note IP/user agent is personally identifiable information, and should
623 * only be set when the privacy policy of the request target is
624 * compatible with that of the MediaWiki installation.
625 */
626 public function setOriginalRequest( $originalRequest ) {
627 if ( $originalRequest instanceof WebRequest ) {
628 $originalRequest = [
629 'ip' => $originalRequest->getIP(),
630 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
631 ];
632 } elseif (
633 !is_array( $originalRequest )
634 || array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
635 ) {
636 throw new InvalidArgumentException( __METHOD__ . ': $originalRequest must be a '
637 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
638 }
639
640 $this->reqHeaders['X-Forwarded-For'] = $originalRequest['ip'];
641 $this->reqHeaders['X-Original-User-Agent'] = $originalRequest['userAgent'];
642 }
643 }