Merge "$wgHttpsPort should only be used in very special cases"
[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 */
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|null $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 = null, $caller = __METHOD__ ) {
185 if ( $options === null ) {
186 $options = [];
187 }
188 return \MediaWiki\MediaWikiServices::getInstance()
189 ->getHttpRequestFactory()
190 ->create( $url, $options, $caller );
191 }
192
193 /**
194 * Get the body, or content, of the response to the request
195 *
196 * @return string
197 */
198 public function getContent() {
199 return $this->content;
200 }
201
202 /**
203 * Set the parameters of the request
204 *
205 * @param array $args
206 * @todo overload the args param
207 */
208 public function setData( $args ) {
209 $this->postData = $args;
210 }
211
212 /**
213 * Take care of setting up the proxy (do nothing if "noProxy" is set)
214 *
215 * @return void
216 */
217 protected function proxySetup() {
218 // If there is an explicit proxy set and proxies are not disabled, then use it
219 if ( $this->proxy && !$this->noProxy ) {
220 return;
221 }
222
223 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
224 // local URL and proxies are not disabled
225 if ( self::isLocalURL( $this->url ) || $this->noProxy ) {
226 $this->proxy = '';
227 } else {
228 $this->proxy = Http::getProxy();
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 if ( is_null( $callback ) ) {
333 $callback = [ $this, 'read' ];
334 } elseif ( !is_callable( $callback ) ) {
335 $this->status->fatal( 'http-internal-error' );
336 throw new InvalidArgumentException( __METHOD__ . ': invalid callback' );
337 }
338 $this->callback = $callback;
339 }
340
341 /**
342 * A generic callback to read the body of the response from a remote
343 * server.
344 *
345 * @param resource $fh
346 * @param string $content
347 * @return int
348 * @internal
349 */
350 public function read( $fh, $content ) {
351 $this->content .= $content;
352 return strlen( $content );
353 }
354
355 /**
356 * Take care of whatever is necessary to perform the URI request.
357 *
358 * @return StatusValue
359 * @note currently returns Status for B/C
360 */
361 public function execute() {
362 throw new LogicException( 'children must override this' );
363 }
364
365 protected function prepare() {
366 $this->content = "";
367
368 if ( strtoupper( $this->method ) == "HEAD" ) {
369 $this->headersOnly = true;
370 }
371
372 $this->proxySetup(); // set up any proxy as needed
373
374 if ( !$this->callback ) {
375 $this->setCallback( null );
376 }
377
378 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
379 $this->setUserAgent( Http::userAgent() );
380 }
381 }
382
383 /**
384 * Parses the headers, including the HTTP status code and any
385 * Set-Cookie headers. This function expects the headers to be
386 * found in an array in the member variable headerList.
387 */
388 protected function parseHeader() {
389 $lastname = "";
390
391 // Failure without (valid) headers gets a response status of zero
392 if ( !$this->status->isOK() ) {
393 $this->respStatus = '0';
394 }
395
396 foreach ( $this->headerList as $header ) {
397 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
398 $this->respVersion = $match[1];
399 $this->respStatus = $match[2];
400 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
401 $last = count( $this->respHeaders[$lastname] ) - 1;
402 $this->respHeaders[$lastname][$last] .= "\r\n$header";
403 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
404 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
405 $lastname = strtolower( $match[1] );
406 }
407 }
408
409 $this->parseCookies();
410 }
411
412 /**
413 * Sets HTTPRequest status member to a fatal value with the error
414 * message if the returned integer value of the status code was
415 * not successful (< 300) or a redirect (>=300 and < 400). (see
416 * RFC2616, section 10,
417 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
418 * list of status codes.)
419 */
420 protected function setStatus() {
421 if ( !$this->respHeaders ) {
422 $this->parseHeader();
423 }
424
425 if ( (int)$this->respStatus > 399 ) {
426 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
427 $this->status->fatal( "http-bad-status", $code, $message );
428 }
429 }
430
431 /**
432 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
433 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
434 * for a list of status codes.)
435 *
436 * @return int
437 */
438 public function getStatus() {
439 if ( !$this->respHeaders ) {
440 $this->parseHeader();
441 }
442
443 return (int)$this->respStatus;
444 }
445
446 /**
447 * Returns true if the last status code was a redirect.
448 *
449 * @return bool
450 */
451 public function isRedirect() {
452 if ( !$this->respHeaders ) {
453 $this->parseHeader();
454 }
455
456 $status = (int)$this->respStatus;
457
458 if ( $status >= 300 && $status <= 303 ) {
459 return true;
460 }
461
462 return false;
463 }
464
465 /**
466 * Returns an associative array of response headers after the
467 * request has been executed. Because some headers
468 * (e.g. Set-Cookie) can appear more than once the, each value of
469 * the associative array is an array of the values given.
470 *
471 * @return array
472 */
473 public function getResponseHeaders() {
474 if ( !$this->respHeaders ) {
475 $this->parseHeader();
476 }
477
478 return $this->respHeaders;
479 }
480
481 /**
482 * Returns the value of the given response header.
483 *
484 * @param string $header
485 * @return string|null
486 */
487 public function getResponseHeader( $header ) {
488 if ( !$this->respHeaders ) {
489 $this->parseHeader();
490 }
491
492 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
493 $v = $this->respHeaders[strtolower( $header )];
494 return $v[count( $v ) - 1];
495 }
496
497 return null;
498 }
499
500 /**
501 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
502 *
503 * To read response cookies from the jar, getCookieJar must be called first.
504 *
505 * @param CookieJar $jar
506 */
507 public function setCookieJar( $jar ) {
508 $this->cookieJar = $jar;
509 }
510
511 /**
512 * Returns the cookie jar in use.
513 *
514 * @return CookieJar
515 */
516 public function getCookieJar() {
517 if ( !$this->respHeaders ) {
518 $this->parseHeader();
519 }
520
521 return $this->cookieJar;
522 }
523
524 /**
525 * Sets a cookie. Used before a request to set up any individual
526 * cookies. Used internally after a request to parse the
527 * Set-Cookie headers.
528 * @see Cookie::set
529 * @param string $name
530 * @param string $value
531 * @param array $attr
532 */
533 public function setCookie( $name, $value, $attr = [] ) {
534 if ( !$this->cookieJar ) {
535 $this->cookieJar = new CookieJar;
536 }
537
538 if ( $this->parsedUrl && !isset( $attr['domain'] ) ) {
539 $attr['domain'] = $this->parsedUrl['host'];
540 }
541
542 $this->cookieJar->setCookie( $name, $value, $attr );
543 }
544
545 /**
546 * Parse the cookies in the response headers and store them in the cookie jar.
547 */
548 protected function parseCookies() {
549 if ( !$this->cookieJar ) {
550 $this->cookieJar = new CookieJar;
551 }
552
553 if ( isset( $this->respHeaders['set-cookie'] ) ) {
554 $url = parse_url( $this->getFinalUrl() );
555 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
556 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
557 }
558 }
559 }
560
561 /**
562 * Returns the final URL after all redirections.
563 *
564 * Relative values of the "Location" header are incorrect as
565 * stated in RFC, however they do happen and modern browsers
566 * support them. This function loops backwards through all
567 * locations in order to build the proper absolute URI - Marooned
568 * at wikia-inc.com
569 *
570 * Note that the multiple Location: headers are an artifact of
571 * CURL -- they shouldn't actually get returned this way. Rewrite
572 * this when T31232 is taken care of (high-level redirect
573 * handling rewrite).
574 *
575 * @return string
576 */
577 public function getFinalUrl() {
578 $headers = $this->getResponseHeaders();
579
580 // return full url (fix for incorrect but handled relative location)
581 if ( isset( $headers['location'] ) ) {
582 $locations = $headers['location'];
583 $domain = '';
584 $foundRelativeURI = false;
585 $countLocations = count( $locations );
586
587 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
588 $url = parse_url( $locations[$i] );
589
590 if ( isset( $url['host'] ) ) {
591 $domain = $url['scheme'] . '://' . $url['host'];
592 break; // found correct URI (with host)
593 } else {
594 $foundRelativeURI = true;
595 }
596 }
597
598 if ( !$foundRelativeURI ) {
599 return $locations[$countLocations - 1];
600 }
601 if ( $domain ) {
602 return $domain . $locations[$countLocations - 1];
603 }
604 $url = parse_url( $this->url );
605 if ( isset( $url['host'] ) ) {
606 return $url['scheme'] . '://' . $url['host'] .
607 $locations[$countLocations - 1];
608 }
609 }
610
611 return $this->url;
612 }
613
614 /**
615 * Returns true if the backend can follow redirects. Overridden by the
616 * child classes.
617 * @return bool
618 */
619 public function canFollowRedirects() {
620 return true;
621 }
622
623 /**
624 * Set information about the original request. This can be useful for
625 * endpoints/API modules which act as a proxy for some service, and
626 * throttling etc. needs to happen in that service.
627 * Calling this will result in the X-Forwarded-For and X-Original-User-Agent
628 * headers being set.
629 * @param WebRequest|array $originalRequest When in array form, it's
630 * expected to have the keys 'ip' and 'userAgent'.
631 * @note IP/user agent is personally identifiable information, and should
632 * only be set when the privacy policy of the request target is
633 * compatible with that of the MediaWiki installation.
634 */
635 public function setOriginalRequest( $originalRequest ) {
636 if ( $originalRequest instanceof WebRequest ) {
637 $originalRequest = [
638 'ip' => $originalRequest->getIP(),
639 'userAgent' => $originalRequest->getHeader( 'User-Agent' ),
640 ];
641 } elseif (
642 !is_array( $originalRequest )
643 || array_diff( [ 'ip', 'userAgent' ], array_keys( $originalRequest ) )
644 ) {
645 throw new InvalidArgumentException( __METHOD__ . ': $originalRequest must be a '
646 . "WebRequest or an array with 'ip' and 'userAgent' keys" );
647 }
648
649 $this->reqHeaders['X-Forwarded-For'] = $originalRequest['ip'];
650 $this->reqHeaders['X-Original-User-Agent'] = $originalRequest['userAgent'];
651 }
652 }