458854ab2d8d4a1adab49cabf4411e4e4003671d
[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 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 protected $content;
37 protected $timeout = 'default';
38 protected $headersOnly = null;
39 protected $postData = null;
40 protected $proxy = null;
41 protected $noProxy = false;
42 protected $sslVerifyHost = true;
43 protected $sslVerifyCert = true;
44 protected $caInfo = null;
45 protected $method = "GET";
46 protected $reqHeaders = [];
47 protected $url;
48 protected $parsedUrl;
49 protected $callback;
50 protected $maxRedirects = 5;
51 protected $followRedirects = false;
52
53 /**
54 * @var CookieJar
55 */
56 protected $cookieJar;
57
58 protected $headerList = [];
59 protected $respVersion = "0.9";
60 protected $respStatus = "200 Ok";
61 protected $respHeaders = [];
62
63 public $status;
64
65 /**
66 * @var Profiler
67 */
68 protected $profiler;
69
70 /**
71 * @var string
72 */
73 protected $profileName;
74
75 /**
76 * @var LoggerInterface;
77 */
78 protected $logger;
79
80 /**
81 * @param string $url Url to use. If protocol-relative, will be expanded to an http:// URL
82 * @param array $options (optional) extra params to pass (see Http::request())
83 * @param string $caller The method making this request, for profiling
84 * @param Profiler $profiler An instance of the profiler for profiling, or null
85 */
86 protected function __construct(
87 $url, $options = [], $caller = __METHOD__, $profiler = null
88 ) {
89 global $wgHTTPTimeout, $wgHTTPConnectTimeout;
90
91 $this->url = wfExpandUrl( $url, PROTO_HTTP );
92 $this->parsedUrl = wfParseUrl( $this->url );
93
94 if ( isset( $options['logger'] ) ) {
95 $this->logger = $options['logger'];
96 } else {
97 $this->logger = new NullLogger();
98 }
99
100 if ( !$this->parsedUrl || !Http::isValidURI( $this->url ) ) {
101 $this->status = Status::newFatal( 'http-invalid-url', $url );
102 } else {
103 $this->status = Status::newGood( 100 ); // continue
104 }
105
106 if ( isset( $options['timeout'] ) && $options['timeout'] != 'default' ) {
107 $this->timeout = $options['timeout'];
108 } else {
109 $this->timeout = $wgHTTPTimeout;
110 }
111 if ( isset( $options['connectTimeout'] ) && $options['connectTimeout'] != 'default' ) {
112 $this->connectTimeout = $options['connectTimeout'];
113 } else {
114 $this->connectTimeout = $wgHTTPConnectTimeout;
115 }
116 if ( isset( $options['userAgent'] ) ) {
117 $this->setUserAgent( $options['userAgent'] );
118 }
119
120 $members = [ "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
121 "method", "followRedirects", "maxRedirects", "sslVerifyCert", "callback" ];
122
123 foreach ( $members as $o ) {
124 if ( isset( $options[$o] ) ) {
125 // ensure that MWHttpRequest::method is always
126 // uppercased. Bug 36137
127 if ( $o == 'method' ) {
128 $options[$o] = strtoupper( $options[$o] );
129 }
130 $this->$o = $options[$o];
131 }
132 }
133
134 if ( $this->noProxy ) {
135 $this->proxy = ''; // noProxy takes precedence
136 }
137
138 // Profile based on what's calling us
139 $this->profiler = $profiler;
140 $this->profileName = $caller;
141 }
142
143 /**
144 * @param LoggerInterface $logger
145 */
146 public function setLogger( LoggerInterface $logger ) {
147 $this->logger = $logger;
148 }
149
150 /**
151 * Simple function to test if we can make any sort of requests at all, using
152 * cURL or fopen()
153 * @return bool
154 */
155 public static function canMakeRequests() {
156 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
157 }
158
159 /**
160 * Generate a new request object
161 * @param string $url Url to use
162 * @param array $options (optional) extra params to pass (see Http::request())
163 * @param string $caller The method making this request, for profiling
164 * @throws MWException
165 * @return CurlHttpRequest|PhpHttpRequest
166 * @see MWHttpRequest::__construct
167 */
168 public static function factory( $url, $options = null, $caller = __METHOD__ ) {
169 if ( !Http::$httpEngine ) {
170 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
171 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
172 throw new MWException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
173 ' Http::$httpEngine is set to "curl"' );
174 }
175
176 if ( !is_array( $options ) ) {
177 $options = [];
178 }
179
180 if ( !isset( $options['logger'] ) ) {
181 $options['logger'] = LoggerFactory::getInstance( 'http' );
182 }
183
184 switch ( Http::$httpEngine ) {
185 case 'curl':
186 return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
187 case 'php':
188 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
189 throw new MWException( __METHOD__ . ': allow_url_fopen ' .
190 'needs to be enabled for pure PHP http requests to ' .
191 'work. If possible, curl should be used instead. See ' .
192 'http://php.net/curl.'
193 );
194 }
195 return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
196 default:
197 throw new MWException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
198 }
199 }
200
201 /**
202 * Get the body, or content, of the response to the request
203 *
204 * @return string
205 */
206 public function getContent() {
207 return $this->content;
208 }
209
210 /**
211 * Set the parameters of the request
212 *
213 * @param array $args
214 * @todo overload the args param
215 */
216 public function setData( $args ) {
217 $this->postData = $args;
218 }
219
220 /**
221 * Take care of setting up the proxy (do nothing if "noProxy" is set)
222 *
223 * @return void
224 */
225 public function proxySetup() {
226 // If there is an explicit proxy set and proxies are not disabled, then use it
227 if ( $this->proxy && !$this->noProxy ) {
228 return;
229 }
230
231 // Otherwise, fallback to $wgHTTPProxy if this is not a machine
232 // local URL and proxies are not disabled
233 if ( self::isLocalURL( $this->url ) || $this->noProxy ) {
234 $this->proxy = '';
235 } else {
236 $this->proxy = Http::getProxy();
237 }
238 }
239
240 /**
241 * Check if the URL can be served by localhost
242 *
243 * @param string $url Full url to check
244 * @return bool
245 */
246 private static function isLocalURL( $url ) {
247 global $wgCommandLineMode, $wgLocalVirtualHosts;
248
249 if ( $wgCommandLineMode ) {
250 return false;
251 }
252
253 // Extract host part
254 $matches = [];
255 if ( preg_match( '!^https?://([\w.-]+)[/:].*$!', $url, $matches ) ) {
256 $host = $matches[1];
257 // Split up dotwise
258 $domainParts = explode( '.', $host );
259 // Check if this domain or any superdomain is listed as a local virtual host
260 $domainParts = array_reverse( $domainParts );
261
262 $domain = '';
263 $countParts = count( $domainParts );
264 for ( $i = 0; $i < $countParts; $i++ ) {
265 $domainPart = $domainParts[$i];
266 if ( $i == 0 ) {
267 $domain = $domainPart;
268 } else {
269 $domain = $domainPart . '.' . $domain;
270 }
271
272 if ( in_array( $domain, $wgLocalVirtualHosts ) ) {
273 return true;
274 }
275 }
276 }
277
278 return false;
279 }
280
281 /**
282 * Set the user agent
283 * @param string $UA
284 */
285 public function setUserAgent( $UA ) {
286 $this->setHeader( 'User-Agent', $UA );
287 }
288
289 /**
290 * Set an arbitrary header
291 * @param string $name
292 * @param string $value
293 */
294 public function setHeader( $name, $value ) {
295 // I feel like I should normalize the case here...
296 $this->reqHeaders[$name] = $value;
297 }
298
299 /**
300 * Get an array of the headers
301 * @return array
302 */
303 public function getHeaderList() {
304 $list = [];
305
306 if ( $this->cookieJar ) {
307 $this->reqHeaders['Cookie'] =
308 $this->cookieJar->serializeToHttpRequest(
309 $this->parsedUrl['path'],
310 $this->parsedUrl['host']
311 );
312 }
313
314 foreach ( $this->reqHeaders as $name => $value ) {
315 $list[] = "$name: $value";
316 }
317
318 return $list;
319 }
320
321 /**
322 * Set a read callback to accept data read from the HTTP request.
323 * By default, data is appended to an internal buffer which can be
324 * retrieved through $req->getContent().
325 *
326 * To handle data as it comes in -- especially for large files that
327 * would not fit in memory -- you can instead set your own callback,
328 * in the form function($resource, $buffer) where the first parameter
329 * is the low-level resource being read (implementation specific),
330 * and the second parameter is the data buffer.
331 *
332 * You MUST return the number of bytes handled in the buffer; if fewer
333 * bytes are reported handled than were passed to you, the HTTP fetch
334 * will be aborted.
335 *
336 * @param callable $callback
337 * @throws MWException
338 */
339 public function setCallback( $callback ) {
340 if ( !is_callable( $callback ) ) {
341 throw new MWException( 'Invalid MwHttpRequest callback' );
342 }
343 $this->callback = $callback;
344 }
345
346 /**
347 * A generic callback to read the body of the response from a remote
348 * server.
349 *
350 * @param resource $fh
351 * @param string $content
352 * @return int
353 */
354 public function read( $fh, $content ) {
355 $this->content .= $content;
356 return strlen( $content );
357 }
358
359 /**
360 * Take care of whatever is necessary to perform the URI request.
361 *
362 * @return Status
363 */
364 public function execute() {
365
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( [ $this, 'read' ] );
376 }
377
378 if ( !isset( $this->reqHeaders['User-Agent'] ) ) {
379 $this->setUserAgent( Http::userAgent() );
380 }
381
382 }
383
384 /**
385 * Parses the headers, including the HTTP status code and any
386 * Set-Cookie headers. This function expects the headers to be
387 * found in an array in the member variable headerList.
388 */
389 protected function parseHeader() {
390
391 $lastname = "";
392
393 foreach ( $this->headerList as $header ) {
394 if ( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
395 $this->respVersion = $match[1];
396 $this->respStatus = $match[2];
397 } elseif ( preg_match( "#^[ \t]#", $header ) ) {
398 $last = count( $this->respHeaders[$lastname] ) - 1;
399 $this->respHeaders[$lastname][$last] .= "\r\n$header";
400 } elseif ( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
401 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
402 $lastname = strtolower( $match[1] );
403 }
404 }
405
406 $this->parseCookies();
407
408 }
409
410 /**
411 * Sets HTTPRequest status member to a fatal value with the error
412 * message if the returned integer value of the status code was
413 * not successful (< 300) or a redirect (>=300 and < 400). (see
414 * RFC2616, section 10,
415 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a
416 * list of status codes.)
417 */
418 protected function setStatus() {
419 if ( !$this->respHeaders ) {
420 $this->parseHeader();
421 }
422
423 if ( (int)$this->respStatus > 399 ) {
424 list( $code, $message ) = explode( " ", $this->respStatus, 2 );
425 $this->status->fatal( "http-bad-status", $code, $message );
426 }
427 }
428
429 /**
430 * Get the integer value of the HTTP status code (e.g. 200 for "200 Ok")
431 * (see RFC2616, section 10, http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
432 * for a list of status codes.)
433 *
434 * @return int
435 */
436 public function getStatus() {
437 if ( !$this->respHeaders ) {
438 $this->parseHeader();
439 }
440
441 return (int)$this->respStatus;
442 }
443
444 /**
445 * Returns true if the last status code was a redirect.
446 *
447 * @return bool
448 */
449 public function isRedirect() {
450 if ( !$this->respHeaders ) {
451 $this->parseHeader();
452 }
453
454 $status = (int)$this->respStatus;
455
456 if ( $status >= 300 && $status <= 303 ) {
457 return true;
458 }
459
460 return false;
461 }
462
463 /**
464 * Returns an associative array of response headers after the
465 * request has been executed. Because some headers
466 * (e.g. Set-Cookie) can appear more than once the, each value of
467 * the associative array is an array of the values given.
468 *
469 * @return array
470 */
471 public function getResponseHeaders() {
472 if ( !$this->respHeaders ) {
473 $this->parseHeader();
474 }
475
476 return $this->respHeaders;
477 }
478
479 /**
480 * Returns the value of the given response header.
481 *
482 * @param string $header
483 * @return string|null
484 */
485 public function getResponseHeader( $header ) {
486 if ( !$this->respHeaders ) {
487 $this->parseHeader();
488 }
489
490 if ( isset( $this->respHeaders[strtolower( $header )] ) ) {
491 $v = $this->respHeaders[strtolower( $header )];
492 return $v[count( $v ) - 1];
493 }
494
495 return null;
496 }
497
498 /**
499 * Tells the MWHttpRequest object to use this pre-loaded CookieJar.
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 mixed $value
527 * @param array $attr
528 */
529 public function setCookie( $name, $value = null, $attr = null ) {
530 if ( !$this->cookieJar ) {
531 $this->cookieJar = new CookieJar;
532 }
533
534 $this->cookieJar->setCookie( $name, $value, $attr );
535 }
536
537 /**
538 * Parse the cookies in the response headers and store them in the cookie jar.
539 */
540 protected function parseCookies() {
541
542 if ( !$this->cookieJar ) {
543 $this->cookieJar = new CookieJar;
544 }
545
546 if ( isset( $this->respHeaders['set-cookie'] ) ) {
547 $url = parse_url( $this->getFinalUrl() );
548 foreach ( $this->respHeaders['set-cookie'] as $cookie ) {
549 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
550 }
551 }
552
553 }
554
555 /**
556 * Returns the final URL after all redirections.
557 *
558 * Relative values of the "Location" header are incorrect as
559 * stated in RFC, however they do happen and modern browsers
560 * support them. This function loops backwards through all
561 * locations in order to build the proper absolute URI - Marooned
562 * at wikia-inc.com
563 *
564 * Note that the multiple Location: headers are an artifact of
565 * CURL -- they shouldn't actually get returned this way. Rewrite
566 * this when bug 29232 is taken care of (high-level redirect
567 * handling rewrite).
568 *
569 * @return string
570 */
571 public function getFinalUrl() {
572 $headers = $this->getResponseHeaders();
573
574 // return full url (fix for incorrect but handled relative location)
575 if ( isset( $headers['location'] ) ) {
576 $locations = $headers['location'];
577 $domain = '';
578 $foundRelativeURI = false;
579 $countLocations = count( $locations );
580
581 for ( $i = $countLocations - 1; $i >= 0; $i-- ) {
582 $url = parse_url( $locations[$i] );
583
584 if ( isset( $url['host'] ) ) {
585 $domain = $url['scheme'] . '://' . $url['host'];
586 break; // found correct URI (with host)
587 } else {
588 $foundRelativeURI = true;
589 }
590 }
591
592 if ( $foundRelativeURI ) {
593 if ( $domain ) {
594 return $domain . $locations[$countLocations - 1];
595 } else {
596 $url = parse_url( $this->url );
597 if ( isset( $url['host'] ) ) {
598 return $url['scheme'] . '://' . $url['host'] .
599 $locations[$countLocations - 1];
600 }
601 }
602 } else {
603 return $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 }