Let CookieJar work for hostnames without dots in them, so that ApiTest can work on...
[lhc/web/wiklou.git] / includes / HttpFunctions.php
1 <?php
2 /**
3 * @defgroup HTTP HTTP
4 */
5
6 /**
7 * Various HTTP related functions
8 * @ingroup HTTP
9 */
10 class Http {
11 static $httpEngine = false;
12
13 /**
14 * Perform an HTTP request
15 * @param $method string HTTP method. Usually GET/POST
16 * @param $url string Full URL to act on
17 * @param $options options to pass to HttpRequest object.
18 * Possible keys for the array:
19 * - timeout Timeout length in seconds
20 * - postData An array of key-value pairs or a url-encoded form data
21 * - proxy The proxy to use.
22 * Will use $wgHTTPProxy (if set) otherwise.
23 * - noProxy Override $wgHTTPProxy (if set) and don't use any proxy at all.
24 * - sslVerifyHost (curl only) Verify hostname against certificate
25 * - sslVerifyCert (curl only) Verify SSL certificate
26 * - caInfo (curl only) Provide CA information
27 * - maxRedirects Maximum number of redirects to follow (defaults to 5)
28 * - followRedirects Whether to follow redirects (defaults to false).
29 * Note: this should only be used when the target URL is trusted,
30 * to avoid attacks on intranet services accessible by HTTP.
31 * @returns mixed (bool)false on failure or a string on success
32 */
33 public static function request( $method, $url, $options = array() ) {
34 $url = wfExpandUrl( $url );
35 wfDebug( "HTTP: $method: $url\n" );
36 $options['method'] = strtoupper( $method );
37 if ( !isset( $options['timeout'] ) ) {
38 $options['timeout'] = 'default';
39 }
40 $req = HttpRequest::factory( $url, $options );
41 $status = $req->execute();
42 if ( $status->isOK() ) {
43 return $req->getContent();
44 } else {
45 return false;
46 }
47 }
48
49 /**
50 * Simple wrapper for Http::request( 'GET' )
51 * @see Http::request()
52 */
53 public static function get( $url, $timeout = 'default', $options = array() ) {
54 $options['timeout'] = $timeout;
55 return Http::request( 'GET', $url, $options );
56 }
57
58 /**
59 * Simple wrapper for Http::request( 'POST' )
60 * @see Http::request()
61 */
62 public static function post( $url, $options = array() ) {
63 return Http::request( 'POST', $url, $options );
64 }
65
66 /**
67 * Check if the URL can be served by localhost
68 * @param $url string Full url to check
69 * @return bool
70 */
71 public static function isLocalURL( $url ) {
72 global $wgCommandLineMode, $wgConf;
73 if ( $wgCommandLineMode ) {
74 return false;
75 }
76
77 // Extract host part
78 $matches = array();
79 if ( preg_match( '!^http://([\w.-]+)[/:].*$!', $url, $matches ) ) {
80 $host = $matches[1];
81 // Split up dotwise
82 $domainParts = explode( '.', $host );
83 // Check if this domain or any superdomain is listed in $wgConf as a local virtual host
84 $domainParts = array_reverse( $domainParts );
85 for ( $i = 0; $i < count( $domainParts ); $i++ ) {
86 $domainPart = $domainParts[$i];
87 if ( $i == 0 ) {
88 $domain = $domainPart;
89 } else {
90 $domain = $domainPart . '.' . $domain;
91 }
92 if ( $wgConf->isLocalVHost( $domain ) ) {
93 return true;
94 }
95 }
96 }
97 return false;
98 }
99
100 /**
101 * A standard user-agent we can use for external requests.
102 * @returns string
103 */
104 public static function userAgent() {
105 global $wgVersion;
106 return "MediaWiki/$wgVersion";
107 }
108
109 /**
110 * Checks that the given URI is a valid one
111 * @param $uri Mixed: URI to check for validity
112 * @returns bool
113 */
114 public static function isValidURI( $uri ) {
115 return preg_match(
116 '/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/',
117 $uri,
118 $matches
119 );
120 }
121 }
122
123 /**
124 * This wrapper class will call out to curl (if available) or fallback
125 * to regular PHP if necessary for handling internal HTTP requests.
126 */
127 class HttpRequest {
128 protected $content;
129 protected $timeout = 'default';
130 protected $headersOnly = null;
131 protected $postData = null;
132 protected $proxy = null;
133 protected $noProxy = false;
134 protected $sslVerifyHost = true;
135 protected $sslVerifyCert = true;
136 protected $caInfo = null;
137 protected $method = "GET";
138 protected $reqHeaders = array();
139 protected $url;
140 protected $parsedUrl;
141 protected $callback;
142 protected $maxRedirects = 5;
143 protected $followRedirects = false;
144
145 protected $cookieJar;
146
147 protected $headerList = array();
148 protected $respVersion = "0.9";
149 protected $respStatus = "200 Ok";
150 protected $respHeaders = array();
151
152 public $status;
153
154 /**
155 * @param $url string url to use
156 * @param $options array (optional) extra params to pass (see Http::request())
157 */
158 function __construct( $url, $options = array() ) {
159 global $wgHTTPTimeout;
160
161 $this->url = $url;
162 $this->parsedUrl = parse_url( $url );
163
164 if ( !Http::isValidURI( $this->url ) ) {
165 $this->status = Status::newFatal('http-invalid-url');
166 } else {
167 $this->status = Status::newGood( 100 ); // continue
168 }
169
170 if ( isset($options['timeout']) && $options['timeout'] != 'default' ) {
171 $this->timeout = $options['timeout'];
172 } else {
173 $this->timeout = $wgHTTPTimeout;
174 }
175
176 $members = array( "postData", "proxy", "noProxy", "sslVerifyHost", "caInfo",
177 "method", "followRedirects", "maxRedirects", "sslVerifyCert" );
178 foreach ( $members as $o ) {
179 if ( isset($options[$o]) ) {
180 $this->$o = $options[$o];
181 }
182 }
183 }
184
185 /**
186 * Generate a new request object
187 * @see HttpRequest::__construct
188 */
189 public static function factory( $url, $options = null ) {
190 if ( !Http::$httpEngine ) {
191 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
192 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
193 throw new MWException( __METHOD__.': curl (http://php.net/curl) is not installed, but'.
194 ' Http::$httpEngine is set to "curl"' );
195 }
196
197 switch( Http::$httpEngine ) {
198 case 'curl':
199 return new CurlHttpRequest( $url, $options );
200 case 'php':
201 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
202 throw new MWException( __METHOD__.': allow_url_fopen needs to be enabled for pure PHP'.
203 ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.' );
204 }
205 return new PhpHttpRequest( $url, $options );
206 default:
207 throw new MWException( __METHOD__.': The setting of Http::$httpEngine is not valid.' );
208 }
209 }
210
211 /**
212 * Get the body, or content, of the response to the request
213 * @return string
214 */
215 public function getContent() {
216 return $this->content;
217 }
218
219 /**
220 * Set the parameters of the request
221 * @param $params array
222 * @todo overload the args param
223 */
224 public function setData($args) {
225 $this->postData = $args;
226 }
227
228 /**
229 * Take care of setting up the proxy
230 * (override in subclass)
231 * @return string
232 */
233 public function proxySetup() {
234 global $wgHTTPProxy;
235
236 if ( $this->proxy ) {
237 return;
238 }
239 if ( Http::isLocalURL( $this->url ) ) {
240 $this->proxy = 'http://localhost:80/';
241 } elseif ( $wgHTTPProxy ) {
242 $this->proxy = $wgHTTPProxy ;
243 } elseif ( getenv( "http_proxy" ) ) {
244 $this->proxy = getenv( "http_proxy" );
245 }
246 }
247
248 /**
249 * Set the refererer header
250 */
251 public function setReferer( $url ) {
252 $this->setHeader('Referer', $url);
253 }
254
255 /**
256 * Set the user agent
257 */
258 public function setUserAgent( $UA ) {
259 $this->setHeader('User-Agent', $UA);
260 }
261
262 /**
263 * Set an arbitrary header
264 */
265 public function setHeader($name, $value) {
266 // I feel like I should normalize the case here...
267 $this->reqHeaders[$name] = $value;
268 }
269
270 /**
271 * Get an array of the headers
272 */
273 public function getHeaderList() {
274 $list = array();
275
276 if( $this->cookieJar ) {
277 $this->reqHeaders['Cookie'] =
278 $this->cookieJar->serializeToHttpRequest($this->parsedUrl['path'],
279 $this->parsedUrl['host']);
280 }
281 foreach($this->reqHeaders as $name => $value) {
282 $list[] = "$name: $value";
283 }
284 return $list;
285 }
286
287 /**
288 * Set the callback
289 * @param $callback callback
290 */
291 public function setCallback( $callback ) {
292 $this->callback = $callback;
293 }
294
295 /**
296 * A generic callback to read the body of the response from a remote
297 * server.
298 * @param $fh handle
299 * @param $content string
300 */
301 public function read( $fh, $content ) {
302 $this->content .= $content;
303 return strlen( $content );
304 }
305
306 /**
307 * Take care of whatever is necessary to perform the URI request.
308 * @return Status
309 */
310 public function execute() {
311 global $wgTitle;
312
313 $this->content = "";
314
315 if( strtoupper($this->method) == "HEAD" ) {
316 $this->headersOnly = true;
317 }
318
319 if ( is_array( $this->postData ) ) {
320 $this->postData = wfArrayToCGI( $this->postData );
321 }
322
323 if ( is_object( $wgTitle ) && !isset($this->reqHeaders['Referer']) ) {
324 $this->setReferer( $wgTitle->getFullURL() );
325 }
326
327 if ( !$this->noProxy ) {
328 $this->proxySetup();
329 }
330
331 if ( !$this->callback ) {
332 $this->setCallback( array( $this, 'read' ) );
333 }
334
335 if ( !isset($this->reqHeaders['User-Agent']) ) {
336 $this->setUserAgent(Http::userAgent());
337 }
338 }
339
340 /**
341 * Parses the headers, including the HTTP status code and any
342 * Set-Cookie headers. This function expectes the headers to be
343 * found in an array in the member variable headerList.
344 * @returns nothing
345 */
346 protected function parseHeader() {
347 $lastname = "";
348 foreach( $this->headerList as $header ) {
349 if( preg_match( "#^HTTP/([0-9.]+) (.*)#", $header, $match ) ) {
350 $this->respVersion = $match[1];
351 $this->respStatus = $match[2];
352 } elseif( preg_match( "#^[ \t]#", $header ) ) {
353 $last = count($this->respHeaders[$lastname]) - 1;
354 $this->respHeaders[$lastname][$last] .= "\r\n$header";
355 } elseif( preg_match( "#^([^:]*):[\t ]*(.*)#", $header, $match ) ) {
356 $this->respHeaders[strtolower( $match[1] )][] = $match[2];
357 $lastname = strtolower( $match[1] );
358 }
359 }
360
361 $this->parseCookies();
362 }
363
364 /**
365 * Sets the member variable status to a fatal status if the HTTP
366 * status code was not 200.
367 * @returns nothing
368 */
369 protected function setStatus() {
370 if( !$this->respHeaders ) {
371 $this->parseHeader();
372 }
373
374 if((int)$this->respStatus !== 200) {
375 list( $code, $message ) = explode(" ", $this->respStatus, 2);
376 $this->status->fatal("http-bad-status", $code, $message );
377 }
378 }
379
380
381 /**
382 * Returns true if the last status code was a redirect.
383 * @return bool
384 */
385 public function isRedirect() {
386 if( !$this->respHeaders ) {
387 $this->parseHeader();
388 }
389
390 $status = (int)$this->respStatus;
391 if ( $status >= 300 && $status <= 303 ) {
392 return true;
393 }
394 return false;
395 }
396
397 /**
398 * Returns an associative array of response headers after the
399 * request has been executed. Because some headers
400 * (e.g. Set-Cookie) can appear more than once the, each value of
401 * the associative array is an array of the values given.
402 * @return array
403 */
404 public function getResponseHeaders() {
405 if( !$this->respHeaders ) {
406 $this->parseHeader();
407 }
408 return $this->respHeaders;
409 }
410
411 /**
412 * Returns the value of the given response header.
413 * @param $header string
414 * @return string
415 */
416 public function getResponseHeader($header) {
417 if( !$this->respHeaders ) {
418 $this->parseHeader();
419 }
420 if ( isset( $this->respHeaders[strtolower ( $header ) ] ) ) {
421 $v = $this->respHeaders[strtolower ( $header ) ];
422 return $v[count( $v ) - 1];
423 }
424 return null;
425 }
426
427 /**
428 * Tells the HttpRequest object to use this pre-loaded CookieJar.
429 * @param $jar CookieJar
430 */
431 public function setCookieJar( $jar ) {
432 $this->cookieJar = $jar;
433 }
434
435 /**
436 * Returns the cookie jar in use.
437 * @returns CookieJar
438 */
439 public function getCookieJar() {
440 if( !$this->respHeaders ) {
441 $this->parseHeader();
442 }
443 return $this->cookieJar;
444 }
445
446 /**
447 * Sets a cookie. Used before a request to set up any individual
448 * cookies. Used internally after a request to parse the
449 * Set-Cookie headers.
450 * @see Cookie::set
451 */
452 public function setCookie( $name, $value = null, $attr = null) {
453 if( !$this->cookieJar ) {
454 $this->cookieJar = new CookieJar;
455 }
456 $this->cookieJar->setCookie($name, $value, $attr);
457 }
458
459 /**
460 * Parse the cookies in the response headers and store them in the cookie jar.
461 */
462 protected function parseCookies() {
463 if( !$this->cookieJar ) {
464 $this->cookieJar = new CookieJar;
465 }
466 if( isset( $this->respHeaders['set-cookie'] ) ) {
467 $url = parse_url( $this->getFinalUrl() );
468 foreach( $this->respHeaders['set-cookie'] as $cookie ) {
469 $this->cookieJar->parseCookieResponseHeader( $cookie, $url['host'] );
470 }
471 }
472 }
473
474 /**
475 * Returns the final URL after all redirections.
476 * @returns string
477 */
478 public function getFinalUrl() {
479 $location = $this->getResponseHeader("Location");
480 if ( $location ) {
481 return $location;
482 }
483
484 return $this->url;
485 }
486
487 /**
488 * Returns true if the backend can follow redirects. Overridden by the
489 * child classes.
490 */
491 public function canFollowRedirects() {
492 return true;
493 }
494 }
495
496
497 class Cookie {
498 protected $name;
499 protected $value;
500 protected $expires;
501 protected $path;
502 protected $domain;
503 protected $isSessionKey = true;
504 // TO IMPLEMENT protected $secure
505 // TO IMPLEMENT? protected $maxAge (add onto expires)
506 // TO IMPLEMENT? protected $version
507 // TO IMPLEMENT? protected $comment
508
509 function __construct( $name, $value, $attr ) {
510 $this->name = $name;
511 $this->set( $value, $attr );
512 }
513
514 /**
515 * Sets a cookie. Used before a request to set up any individual
516 * cookies. Used internally after a request to parse the
517 * Set-Cookie headers.
518 *
519 * @param $value string the value of the cookie
520 * @param $attr array possible key/values:
521 * expires A date string
522 * path The path this cookie is used on
523 * domain Domain this cookie is used on
524 */
525 public function set( $value, $attr ) {
526 $this->value = $value;
527 if( isset( $attr['expires'] ) ) {
528 $this->isSessionKey = false;
529 $this->expires = strtotime( $attr['expires'] );
530 }
531 if( isset( $attr['path'] ) ) {
532 $this->path = $attr['path'];
533 } else {
534 $this->path = "/";
535 }
536 if( isset( $attr['domain'] ) ) {
537 if( self::validateCookieDomain( $attr['domain'] ) ) {
538 $this->domain = $attr['domain'];
539 }
540 } else {
541 throw new MWException("You must specify a domain.");
542 }
543 }
544
545 /**
546 * Return the true if the cookie is valid is valid. Otherwise,
547 * false. The uses a method similar to IE cookie security
548 * described here:
549 * http://kuza55.blogspot.com/2008/02/understanding-cookie-security.html
550 * A better method might be to use a blacklist like
551 * http://publicsuffix.org/
552 *
553 * @param $domain string the domain to validate
554 * @param $originDomain string (optional) the domain the cookie originates from
555 * @return bool
556 */
557 public static function validateCookieDomain( $domain, $originDomain = null) {
558 // Don't allow a trailing dot
559 if( substr( $domain, -1 ) == "." ) return false;
560
561 $dc = explode(".", $domain);
562
563 // Only allow full, valid IP addresses
564 if( preg_match( '/^[0-9.]+$/', $domain ) ) {
565 if( count( $dc ) != 4 ) return false;
566
567 if( ip2long( $domain ) === false ) return false;
568
569 if( $originDomain == null || $originDomain == $domain ) return true;
570
571 }
572
573 // Don't allow cookies for "co.uk" or "gov.uk", etc, but allow "supermarket.uk"
574 if( strrpos( $domain, "." ) - strlen( $domain ) == -3 ) {
575 if( (count($dc) == 2 && strlen( $dc[0] ) <= 2 )
576 || (count($dc) == 3 && strlen( $dc[0] ) == "" && strlen( $dc[1] ) <= 2 ) ) {
577 return false;
578 }
579 if( (count($dc) == 2 || (count($dc) == 3 && $dc[0] == "") )
580 && preg_match( '/(com|net|org|gov|edu)\...$/', $domain) ) {
581 return false;
582 }
583 }
584
585 if( $originDomain != null ) {
586 if( substr( $domain, 0, 1 ) != "." && $domain != $originDomain ) {
587 return false;
588 }
589 if( substr( $domain, 0, 1 ) == "."
590 && substr_compare( $originDomain, $domain, -strlen( $domain ),
591 strlen( $domain ), TRUE ) != 0 ) {
592 return false;
593 }
594 }
595
596 return true;
597 }
598
599 /**
600 * Serialize the cookie jar into a format useful for HTTP Request headers.
601 * @param $path string the path that will be used. Required.
602 * @param $domain string the domain that will be used. Required.
603 * @return string
604 */
605 public function serializeToHttpRequest( $path, $domain ) {
606 $ret = "";
607
608 if( $this->canServeDomain( $domain )
609 && $this->canServePath( $path )
610 && $this->isUnExpired() ) {
611 $ret = $this->name ."=". $this->value;
612 }
613
614 return $ret;
615 }
616
617 protected function canServeDomain( $domain ) {
618 if( $domain == $this->domain
619 || ( strlen( $domain) > strlen( $this->domain )
620 && substr( $this->domain, 0, 1) == "."
621 && substr_compare( $domain, $this->domain, -strlen( $this->domain ),
622 strlen( $this->domain ), TRUE ) == 0 ) ) {
623 return true;
624 }
625 return false;
626 }
627
628 protected function canServePath( $path ) {
629 if( $this->path && substr_compare( $this->path, $path, 0, strlen( $this->path ) ) == 0 ) {
630 return true;
631 }
632 return false;
633 }
634
635 protected function isUnExpired() {
636 if( $this->isSessionKey || $this->expires > time() ) {
637 return true;
638 }
639 return false;
640 }
641
642 }
643
644 class CookieJar {
645 private $cookie = array();
646
647 /**
648 * Set a cookie in the cookie jar. Make sure only one cookie per-name exists.
649 * @see Cookie::set()
650 */
651 public function setCookie ($name, $value, $attr) {
652 /* cookies: case insensitive, so this should work.
653 * We'll still send the cookies back in the same case we got them, though.
654 */
655 $index = strtoupper($name);
656 if( isset( $this->cookie[$index] ) ) {
657 $this->cookie[$index]->set( $value, $attr );
658 } else {
659 $this->cookie[$index] = new Cookie( $name, $value, $attr );
660 }
661 }
662
663 /**
664 * @see Cookie::serializeToHttpRequest
665 */
666 public function serializeToHttpRequest( $path, $domain ) {
667 $cookies = array();
668
669 foreach( $this->cookie as $c ) {
670 $serialized = $c->serializeToHttpRequest( $path, $domain );
671 if ( $serialized ) $cookies[] = $serialized;
672 }
673
674 return implode("; ", $cookies);
675 }
676
677 /**
678 * Parse the content of an Set-Cookie HTTP Response header.
679 *
680 * @param $cookie String
681 * @param $domain String: cookie's domain
682 */
683 public function parseCookieResponseHeader ( $cookie, $domain ) {
684 $len = strlen( "Set-Cookie:" );
685 if ( substr_compare( "Set-Cookie:", $cookie, 0, $len, TRUE ) === 0 ) {
686 $cookie = substr( $cookie, $len );
687 }
688
689 $bit = array_map( 'trim', explode( ";", $cookie ) );
690 if ( count($bit) >= 1 ) {
691 list($name, $value) = explode( "=", array_shift( $bit ), 2 );
692 $attr = array();
693 foreach( $bit as $piece ) {
694 $parts = explode( "=", $piece );
695 if( count( $parts ) > 1 ) {
696 $attr[strtolower( $parts[0] )] = $parts[1];
697 } else {
698 $attr[strtolower( $parts[0] )] = true;
699 }
700 }
701
702 if( !isset( $attr['domain'] ) ) {
703 $attr['domain'] = $domain;
704 } elseif ( !Cookie::validateCookieDomain( $attr['domain'], $domain ) ) {
705 return null;
706 }
707 $this->setCookie( $name, $value, $attr );
708 }
709 }
710 }
711
712
713 /**
714 * HttpRequest implemented using internal curl compiled into PHP
715 */
716 class CurlHttpRequest extends HttpRequest {
717 static $curlMessageMap = array(
718 6 => 'http-host-unreachable',
719 28 => 'http-timed-out'
720 );
721
722 protected $curlOptions = array();
723 protected $headerText = "";
724
725 protected function readHeader( $fh, $content ) {
726 $this->headerText .= $content;
727 return strlen( $content );
728 }
729
730 public function execute() {
731 parent::execute();
732 if ( !$this->status->isOK() ) {
733 return $this->status;
734 }
735 $this->curlOptions[CURLOPT_PROXY] = $this->proxy;
736 $this->curlOptions[CURLOPT_TIMEOUT] = $this->timeout;
737 $this->curlOptions[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
738 $this->curlOptions[CURLOPT_WRITEFUNCTION] = $this->callback;
739 $this->curlOptions[CURLOPT_HEADERFUNCTION] = array($this, "readHeader");
740 $this->curlOptions[CURLOPT_MAXREDIRS] = $this->maxRedirects;
741 $this->curlOptions[CURLOPT_ENCODING] = ""; # Enable compression
742
743 /* not sure these two are actually necessary */
744 if(isset($this->reqHeaders['Referer'])) {
745 $this->curlOptions[CURLOPT_REFERER] = $this->reqHeaders['Referer'];
746 }
747 $this->curlOptions[CURLOPT_USERAGENT] = $this->reqHeaders['User-Agent'];
748
749 if ( isset( $this->sslVerifyHost ) ) {
750 $this->curlOptions[CURLOPT_SSL_VERIFYHOST] = $this->sslVerifyHost;
751 }
752
753 if ( isset( $this->sslVerifyCert ) ) {
754 $this->curlOptions[CURLOPT_SSL_VERIFYPEER] = $this->sslVerifyCert;
755 }
756
757 if ( $this->caInfo ) {
758 $this->curlOptions[CURLOPT_CAINFO] = $this->caInfo;
759 }
760
761 if ( $this->headersOnly ) {
762 $this->curlOptions[CURLOPT_NOBODY] = true;
763 $this->curlOptions[CURLOPT_HEADER] = true;
764 } elseif ( $this->method == 'POST' ) {
765 $this->curlOptions[CURLOPT_POST] = true;
766 $this->curlOptions[CURLOPT_POSTFIELDS] = $this->postData;
767 // Suppress 'Expect: 100-continue' header, as some servers
768 // will reject it with a 417 and Curl won't auto retry
769 // with HTTP 1.0 fallback
770 $this->reqHeaders['Expect'] = '';
771 } else {
772 $this->curlOptions[CURLOPT_CUSTOMREQUEST] = $this->method;
773 }
774
775 $this->curlOptions[CURLOPT_HTTPHEADER] = $this->getHeaderList();
776
777 $curlHandle = curl_init( $this->url );
778 if ( !curl_setopt_array( $curlHandle, $this->curlOptions ) ) {
779 throw new MWException("Error setting curl options.");
780 }
781 if ( $this->followRedirects && $this->canFollowRedirects() ) {
782 if ( ! @curl_setopt( $curlHandle, CURLOPT_FOLLOWLOCATION, true ) ) {
783 wfDebug( __METHOD__.": Couldn't set CURLOPT_FOLLOWLOCATION. " .
784 "Probably safe_mode or open_basedir is set.\n");
785 // Continue the processing. If it were in curl_setopt_array,
786 // processing would have halted on its entry
787 }
788 }
789
790 if ( false === curl_exec( $curlHandle ) ) {
791 $code = curl_error( $curlHandle );
792
793 if ( isset( self::$curlMessageMap[$code] ) ) {
794 $this->status->fatal( self::$curlMessageMap[$code] );
795 } else {
796 $this->status->fatal( 'http-curl-error', curl_error( $curlHandle ) );
797 }
798 } else {
799 $this->headerList = explode("\r\n", $this->headerText);
800 }
801
802 curl_close( $curlHandle );
803
804 $this->parseHeader();
805 $this->setStatus();
806 return $this->status;
807 }
808
809 public function canFollowRedirects() {
810 if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
811 wfDebug( "Cannot follow redirects in safe mode\n" );
812 return false;
813 }
814 if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
815 wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
816 return false;
817 }
818 return true;
819 }
820 }
821
822 class PhpHttpRequest extends HttpRequest {
823 protected function urlToTcp( $url ) {
824 $parsedUrl = parse_url( $url );
825
826 return 'tcp://' . $parsedUrl['host'] . ':' . $parsedUrl['port'];
827 }
828
829 public function execute() {
830 parent::execute();
831
832 // At least on Centos 4.8 with PHP 5.1.6, using max_redirects to follow redirects
833 // causes a segfault
834 $manuallyRedirect = version_compare( phpversion(), '5.1.7', '<' );
835
836 if ( $this->parsedUrl['scheme'] != 'http' ) {
837 $this->status->fatal( 'http-invalid-scheme', $this->parsedUrl['scheme'] );
838 }
839
840 $this->reqHeaders['Accept'] = "*/*";
841 if ( $this->method == 'POST' ) {
842 // Required for HTTP 1.0 POSTs
843 $this->reqHeaders['Content-Length'] = strlen( $this->postData );
844 $this->reqHeaders['Content-type'] = "application/x-www-form-urlencoded";
845 }
846
847 $options = array();
848 if ( $this->proxy && !$this->noProxy ) {
849 $options['proxy'] = $this->urlToTCP( $this->proxy );
850 $options['request_fulluri'] = true;
851 }
852
853 if ( !$this->followRedirects || $manuallyRedirect ) {
854 $options['max_redirects'] = 0;
855 } else {
856 $options['max_redirects'] = $this->maxRedirects;
857 }
858
859 $options['method'] = $this->method;
860 $options['header'] = implode("\r\n", $this->getHeaderList());
861 // Note that at some future point we may want to support
862 // HTTP/1.1, but we'd have to write support for chunking
863 // in version of PHP < 5.3.1
864 $options['protocol_version'] = "1.0";
865
866 // This is how we tell PHP we want to deal with 404s (for example) ourselves.
867 // Only works on 5.2.10+
868 $options['ignore_errors'] = true;
869
870 if ( $this->postData ) {
871 $options['content'] = $this->postData;
872 }
873
874 $oldTimeout = false;
875 if ( version_compare( '5.2.1', phpversion(), '>' ) ) {
876 $oldTimeout = ini_set('default_socket_timeout', $this->timeout);
877 } else {
878 $options['timeout'] = $this->timeout;
879 }
880
881 $context = stream_context_create( array( 'http' => $options ) );
882
883 $this->headerList = array();
884 $reqCount = 0;
885 $url = $this->url;
886 do {
887 $reqCount++;
888 wfSuppressWarnings();
889 $fh = fopen( $url, "r", false, $context );
890 wfRestoreWarnings();
891 if ( !$fh ) {
892 break;
893 }
894 $result = stream_get_meta_data( $fh );
895 $this->headerList = $result['wrapper_data'];
896 $this->parseHeader();
897 if ( !$manuallyRedirect || !$this->followRedirects ) {
898 break;
899 }
900
901 # Handle manual redirection
902 if ( !$this->isRedirect() || $reqCount > $this->maxRedirects ) {
903 break;
904 }
905 # Check security of URL
906 $url = $this->getResponseHeader("Location");
907 if ( substr( $url, 0, 7 ) !== 'http://' ) {
908 wfDebug( __METHOD__.": insecure redirection\n" );
909 break;
910 }
911 } while ( true );
912
913 if ( $oldTimeout !== false ) {
914 ini_set('default_socket_timeout', $oldTimeout);
915 }
916 $this->setStatus();
917
918 if ( $fh === false ) {
919 $this->status->fatal( 'http-request-error' );
920 return $this->status;
921 }
922
923 if ( $result['timed_out'] ) {
924 $this->status->fatal( 'http-timed-out', $this->url );
925 return $this->status;
926 }
927
928 if($this->status->isOK()) {
929 while ( !feof( $fh ) ) {
930 $buf = fread( $fh, 8192 );
931 if ( $buf === false ) {
932 $this->status->fatal( 'http-read-error' );
933 break;
934 }
935 if ( strlen( $buf ) ) {
936 call_user_func( $this->callback, $fh, $buf );
937 }
938 }
939 }
940 fclose( $fh );
941
942 return $this->status;
943 }
944 }