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