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