3 * Socket-based adapter for HTTP_Request2
\r
9 * Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>
\r
10 * All rights reserved.
\r
12 * Redistribution and use in source and binary forms, with or without
\r
13 * modification, are permitted provided that the following conditions
\r
16 * * Redistributions of source code must retain the above copyright
\r
17 * notice, this list of conditions and the following disclaimer.
\r
18 * * Redistributions in binary form must reproduce the above copyright
\r
19 * notice, this list of conditions and the following disclaimer in the
\r
20 * documentation and/or other materials provided with the distribution.
\r
21 * * The names of the authors may not be used to endorse or promote products
\r
22 * derived from this software without specific prior written permission.
\r
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
\r
25 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
\r
26 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
\r
27 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
\r
28 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
\r
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
\r
30 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
\r
31 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
\r
32 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
\r
33 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
\r
34 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\r
37 * @package HTTP_Request2
\r
38 * @author Alexey Borzov <avb@php.net>
\r
39 * @license http://opensource.org/licenses/bsd-license.php New BSD License
\r
40 * @version CVS: $Id: Socket.php 279760 2009-05-03 10:46:42Z avb $
\r
41 * @link http://pear.php.net/package/HTTP_Request2
\r
45 * Base class for HTTP_Request2 adapters
\r
47 require_once 'HTTP/Request2/Adapter.php';
\r
50 * Socket-based adapter for HTTP_Request2
\r
52 * This adapter uses only PHP sockets and will work on almost any PHP
\r
53 * environment. Code is based on original HTTP_Request PEAR package.
\r
56 * @package HTTP_Request2
\r
57 * @author Alexey Borzov <avb@php.net>
\r
58 * @version Release: 0.4.1
\r
60 class HTTP_Request2_Adapter_Socket extends HTTP_Request2_Adapter
\r
63 * Regular expression for 'token' rule from RFC 2616
\r
65 const REGEXP_TOKEN = '[^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+';
\r
68 * Regular expression for 'quoted-string' rule from RFC 2616
\r
70 const REGEXP_QUOTED_STRING = '"(?:\\\\.|[^\\\\"])*"';
\r
73 * Connected sockets, needed for Keep-Alive support
\r
77 protected static $sockets = array();
\r
80 * Data for digest authentication scheme
\r
82 * The keys for the array are URL prefixes.
\r
84 * The values are associative arrays with data (realm, nonce, nonce-count,
\r
85 * opaque...) needed for digest authentication. Stored here to prevent making
\r
86 * duplicate requests to digest-protected resources after we have already
\r
87 * received the challenge.
\r
91 protected static $challenges = array();
\r
101 * Challenge used for server digest authentication
\r
104 protected $serverChallenge;
\r
107 * Challenge used for proxy digest authentication
\r
110 protected $proxyChallenge;
\r
113 * Global timeout, exception will be raised if request continues past this time
\r
116 protected $timeout = null;
\r
119 * Remaining length of the current chunk, when reading chunked response
\r
121 * @see readChunked()
\r
123 protected $chunkLength = 0;
\r
126 * Sends request to the remote server and returns its response
\r
128 * @param HTTP_Request2
\r
129 * @return HTTP_Request2_Response
\r
130 * @throws HTTP_Request2_Exception
\r
132 public function sendRequest(HTTP_Request2 $request)
\r
134 $this->request = $request;
\r
135 $keepAlive = $this->connect();
\r
136 $headers = $this->prepareHeaders();
\r
138 // Use global request timeout if given, see feature requests #5735, #8964
\r
139 if ($timeout = $request->getConfig('timeout')) {
\r
140 $this->timeout = time() + $timeout;
\r
142 $this->timeout = null;
\r
146 if (false === @fwrite($this->socket, $headers, strlen($headers))) {
\r
147 throw new HTTP_Request2_Exception('Error writing request');
\r
149 // provide request headers to the observer, see request #7633
\r
150 $this->request->setLastEvent('sentHeaders', $headers);
\r
151 $this->writeBody();
\r
153 if ($this->timeout && time() > $this->timeout) {
\r
154 throw new HTTP_Request2_Exception(
\r
155 'Request timed out after ' .
\r
156 $request->getConfig('timeout') . ' second(s)'
\r
160 $response = $this->readResponse();
\r
162 if (!$this->canKeepAlive($keepAlive, $response)) {
\r
163 $this->disconnect();
\r
166 if ($this->shouldUseProxyDigestAuth($response)) {
\r
167 return $this->sendRequest($request);
\r
169 if ($this->shouldUseServerDigestAuth($response)) {
\r
170 return $this->sendRequest($request);
\r
172 if ($authInfo = $response->getHeader('authentication-info')) {
\r
173 $this->updateChallenge($this->serverChallenge, $authInfo);
\r
175 if ($proxyInfo = $response->getHeader('proxy-authentication-info')) {
\r
176 $this->updateChallenge($this->proxyChallenge, $proxyInfo);
\r
179 } catch (Exception $e) {
\r
180 $this->disconnect();
\r
188 * Connects to the remote server
\r
190 * @return bool whether the connection can be persistent
\r
191 * @throws HTTP_Request2_Exception
\r
193 protected function connect()
\r
195 $secure = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');
\r
196 $tunnel = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
\r
197 $headers = $this->request->getHeaders();
\r
198 $reqHost = $this->request->getUrl()->getHost();
\r
199 if (!($reqPort = $this->request->getUrl()->getPort())) {
\r
200 $reqPort = $secure? 443: 80;
\r
203 if ($host = $this->request->getConfig('proxy_host')) {
\r
204 if (!($port = $this->request->getConfig('proxy_port'))) {
\r
205 throw new HTTP_Request2_Exception('Proxy port not provided');
\r
214 if ($tunnel && !$proxy) {
\r
215 throw new HTTP_Request2_Exception(
\r
216 "Trying to perform CONNECT request without proxy"
\r
219 if ($secure && !in_array('ssl', stream_get_transports())) {
\r
220 throw new HTTP_Request2_Exception(
\r
221 'Need OpenSSL support for https:// requests'
\r
225 // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
\r
226 // connection token to a proxy server...
\r
227 if ($proxy && !$secure &&
\r
228 !empty($headers['connection']) && 'Keep-Alive' == $headers['connection']
\r
230 $this->request->setHeader('connection');
\r
233 $keepAlive = ('1.1' == $this->request->getConfig('protocol_version') &&
\r
234 empty($headers['connection'])) ||
\r
235 (!empty($headers['connection']) &&
\r
236 'Keep-Alive' == $headers['connection']);
\r
237 $host = ((!$secure || $proxy)? 'tcp://': 'ssl://') . $host;
\r
239 $options = array();
\r
240 if ($secure || $tunnel) {
\r
241 foreach ($this->request->getConfig() as $name => $value) {
\r
242 if ('ssl_' == substr($name, 0, 4) && null !== $value) {
\r
243 if ('ssl_verify_host' == $name) {
\r
245 $options['CN_match'] = $reqHost;
\r
248 $options[substr($name, 4)] = $value;
\r
255 // Changing SSL context options after connection is established does *not*
\r
256 // work, we need a new connection if options change
\r
257 $remote = $host . ':' . $port;
\r
258 $socketKey = $remote . (($secure && $proxy)? "->{$reqHost}:{$reqPort}": '') .
\r
259 (empty($options)? '': ':' . serialize($options));
\r
260 unset($this->socket);
\r
262 // We use persistent connections and have a connected socket?
\r
263 // Ensure that the socket is still connected, see bug #16149
\r
264 if ($keepAlive && !empty(self::$sockets[$socketKey]) &&
\r
265 !feof(self::$sockets[$socketKey])
\r
267 $this->socket =& self::$sockets[$socketKey];
\r
269 } elseif ($secure && $proxy && !$tunnel) {
\r
270 $this->establishTunnel();
\r
271 $this->request->setLastEvent(
\r
272 'connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}"
\r
274 self::$sockets[$socketKey] =& $this->socket;
\r
277 // Set SSL context options if doing HTTPS request or creating a tunnel
\r
278 $context = stream_context_create();
\r
279 foreach ($options as $name => $value) {
\r
280 if (!stream_context_set_option($context, 'ssl', $name, $value)) {
\r
281 throw new HTTP_Request2_Exception(
\r
282 "Error setting SSL context option '{$name}'"
\r
286 $this->socket = @stream_socket_client(
\r
287 $remote, $errno, $errstr,
\r
288 $this->request->getConfig('connect_timeout'),
\r
289 STREAM_CLIENT_CONNECT, $context
\r
291 if (!$this->socket) {
\r
292 throw new HTTP_Request2_Exception(
\r
293 "Unable to connect to {$remote}. Error #{$errno}: {$errstr}"
\r
296 $this->request->setLastEvent('connect', $remote);
\r
297 self::$sockets[$socketKey] =& $this->socket;
\r
303 * Establishes a tunnel to a secure remote server via HTTP CONNECT request
\r
305 * This method will fail if 'ssl_verify_peer' is enabled. Probably because PHP
\r
306 * sees that we are connected to a proxy server (duh!) rather than the server
\r
307 * that presents its certificate.
\r
309 * @link http://tools.ietf.org/html/rfc2817#section-5.2
\r
310 * @throws HTTP_Request2_Exception
\r
312 protected function establishTunnel()
\r
315 $connect = new HTTP_Request2(
\r
316 $this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,
\r
317 array_merge($this->request->getConfig(),
\r
318 array('adapter' => $donor))
\r
320 $response = $connect->send();
\r
321 // Need any successful (2XX) response
\r
322 if (200 > $response->getStatus() || 300 <= $response->getStatus()) {
\r
323 throw new HTTP_Request2_Exception(
\r
324 'Failed to connect via HTTPS proxy. Proxy response: ' .
\r
325 $response->getStatus() . ' ' . $response->getReasonPhrase()
\r
328 $this->socket = $donor->socket;
\r
331 STREAM_CRYPTO_METHOD_TLS_CLIENT,
\r
332 STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
\r
333 STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
\r
334 STREAM_CRYPTO_METHOD_SSLv2_CLIENT
\r
337 foreach ($modes as $mode) {
\r
338 if (stream_socket_enable_crypto($this->socket, true, $mode)) {
\r
342 throw new HTTP_Request2_Exception(
\r
343 'Failed to enable secure connection when connecting through proxy'
\r
348 * Checks whether current connection may be reused or should be closed
\r
350 * @param boolean whether connection could be persistent
\r
351 * in the first place
\r
352 * @param HTTP_Request2_Response response object to check
\r
355 protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)
\r
357 // Do not close socket on successful CONNECT request
\r
358 if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
\r
359 200 <= $response->getStatus() && 300 > $response->getStatus()
\r
364 $lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding')) ||
\r
365 null !== $response->getHeader('content-length');
\r
366 $persistent = 'keep-alive' == strtolower($response->getHeader('connection')) ||
\r
367 (null === $response->getHeader('connection') &&
\r
368 '1.1' == $response->getVersion());
\r
369 return $requestKeepAlive && $lengthKnown && $persistent;
\r
373 * Disconnects from the remote server
\r
375 protected function disconnect()
\r
377 if (is_resource($this->socket)) {
\r
378 fclose($this->socket);
\r
379 $this->socket = null;
\r
380 $this->request->setLastEvent('disconnect');
\r
385 * Checks whether another request should be performed with server digest auth
\r
387 * Several conditions should be satisfied for it to return true:
\r
388 * - response status should be 401
\r
389 * - auth credentials should be set in the request object
\r
390 * - response should contain WWW-Authenticate header with digest challenge
\r
391 * - there is either no challenge stored for this URL or new challenge
\r
392 * contains stale=true parameter (in other case we probably just failed
\r
393 * due to invalid username / password)
\r
395 * The method stores challenge values in $challenges static property
\r
397 * @param HTTP_Request2_Response response to check
\r
398 * @return boolean whether another request should be performed
\r
399 * @throws HTTP_Request2_Exception in case of unsupported challenge parameters
\r
401 protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)
\r
403 // no sense repeating a request if we don't have credentials
\r
404 if (401 != $response->getStatus() || !$this->request->getAuth()) {
\r
407 if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {
\r
411 $url = $this->request->getUrl();
\r
412 $scheme = $url->getScheme();
\r
413 $host = $scheme . '://' . $url->getHost();
\r
414 if ($port = $url->getPort()) {
\r
415 if ((0 == strcasecmp($scheme, 'http') && 80 != $port) ||
\r
416 (0 == strcasecmp($scheme, 'https') && 443 != $port)
\r
418 $host .= ':' . $port;
\r
422 if (!empty($challenge['domain'])) {
\r
423 $prefixes = array();
\r
424 foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {
\r
425 // don't bother with different servers
\r
426 if ('/' == substr($prefix, 0, 1)) {
\r
427 $prefixes[] = $host . $prefix;
\r
431 if (empty($prefixes)) {
\r
432 $prefixes = array($host . '/');
\r
436 foreach ($prefixes as $prefix) {
\r
437 if (!empty(self::$challenges[$prefix]) &&
\r
438 (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
\r
440 // probably credentials are invalid
\r
443 self::$challenges[$prefix] =& $challenge;
\r
449 * Checks whether another request should be performed with proxy digest auth
\r
451 * Several conditions should be satisfied for it to return true:
\r
452 * - response status should be 407
\r
453 * - proxy auth credentials should be set in the request object
\r
454 * - response should contain Proxy-Authenticate header with digest challenge
\r
455 * - there is either no challenge stored for this proxy or new challenge
\r
456 * contains stale=true parameter (in other case we probably just failed
\r
457 * due to invalid username / password)
\r
459 * The method stores challenge values in $challenges static property
\r
461 * @param HTTP_Request2_Response response to check
\r
462 * @return boolean whether another request should be performed
\r
463 * @throws HTTP_Request2_Exception in case of unsupported challenge parameters
\r
465 protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)
\r
467 if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
\r
470 if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
\r
474 $key = 'proxy://' . $this->request->getConfig('proxy_host') .
\r
475 ':' . $this->request->getConfig('proxy_port');
\r
477 if (!empty(self::$challenges[$key]) &&
\r
478 (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
\r
484 self::$challenges[$key] = $challenge;
\r
489 * Extracts digest method challenge from (WWW|Proxy)-Authenticate header value
\r
491 * There is a problem with implementation of RFC 2617: several of the parameters
\r
492 * here are defined as quoted-string and thus may contain backslash escaped
\r
493 * double quotes (RFC 2616, section 2.2). However, RFC 2617 defines unq(X) as
\r
494 * just value of quoted-string X without surrounding quotes, it doesn't speak
\r
495 * about removing backslash escaping.
\r
497 * Now realm parameter is user-defined and human-readable, strange things
\r
498 * happen when it contains quotes:
\r
499 * - Apache allows quotes in realm, but apparently uses realm value without
\r
500 * backslashes for digest computation
\r
501 * - Squid allows (manually escaped) quotes there, but it is impossible to
\r
502 * authorize with either escaped or unescaped quotes used in digest,
\r
503 * probably it can't parse the response (?)
\r
504 * - Both IE and Firefox display realm value with backslashes in
\r
505 * the password popup and apparently use the same value for digest
\r
507 * HTTP_Request2 follows IE and Firefox (and hopefully RFC 2617) in
\r
508 * quoted-string handling, unfortunately that means failure to authorize
\r
511 * @param string value of WWW-Authenticate or Proxy-Authenticate header
\r
512 * @return mixed associative array with challenge parameters, false if
\r
513 * no challenge is present in header value
\r
514 * @throws HTTP_Request2_Exception in case of unsupported challenge parameters
\r
516 protected function parseDigestChallenge($headerValue)
\r
518 $authParam = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
\r
519 self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';
\r
520 $challenge = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";
\r
521 if (!preg_match($challenge, $headerValue, $matches)) {
\r
525 preg_match_all('!' . $authParam . '!', $matches[0], $params);
\r
526 $paramsAry = array();
\r
527 $knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',
\r
528 'algorithm', 'qop');
\r
529 for ($i = 0; $i < count($params[0]); $i++) {
\r
530 // section 3.2.1: Any unrecognized directive MUST be ignored.
\r
531 if (in_array($params[1][$i], $knownParams)) {
\r
532 if ('"' == substr($params[2][$i], 0, 1)) {
\r
533 $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
\r
535 $paramsAry[$params[1][$i]] = $params[2][$i];
\r
539 // we only support qop=auth
\r
540 if (!empty($paramsAry['qop']) &&
\r
541 !in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))
\r
543 throw new HTTP_Request2_Exception(
\r
544 "Only 'auth' qop is currently supported in digest authentication, " .
\r
545 "server requested '{$paramsAry['qop']}'"
\r
548 // we only support algorithm=MD5
\r
549 if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {
\r
550 throw new HTTP_Request2_Exception(
\r
551 "Only 'MD5' algorithm is currently supported in digest authentication, " .
\r
552 "server requested '{$paramsAry['algorithm']}'"
\r
556 return $paramsAry;
\r
560 * Parses [Proxy-]Authentication-Info header value and updates challenge
\r
562 * @param array challenge to update
\r
563 * @param string value of [Proxy-]Authentication-Info header
\r
564 * @todo validate server rspauth response
\r
566 protected function updateChallenge(&$challenge, $headerValue)
\r
568 $authParam = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
\r
569 self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';
\r
570 $paramsAry = array();
\r
572 preg_match_all($authParam, $headerValue, $params);
\r
573 for ($i = 0; $i < count($params[0]); $i++) {
\r
574 if ('"' == substr($params[2][$i], 0, 1)) {
\r
575 $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
\r
577 $paramsAry[$params[1][$i]] = $params[2][$i];
\r
580 // for now, just update the nonce value
\r
581 if (!empty($paramsAry['nextnonce'])) {
\r
582 $challenge['nonce'] = $paramsAry['nextnonce'];
\r
583 $challenge['nc'] = 1;
\r
588 * Creates a value for [Proxy-]Authorization header when using digest authentication
\r
590 * @param string user name
\r
591 * @param string password
\r
592 * @param string request URL
\r
593 * @param array digest challenge parameters
\r
594 * @return string value of [Proxy-]Authorization request header
\r
595 * @link http://tools.ietf.org/html/rfc2617#section-3.2.2
\r
597 protected function createDigestResponse($user, $password, $url, &$challenge)
\r
599 if (false !== ($q = strpos($url, '?')) &&
\r
600 $this->request->getConfig('digest_compat_ie')
\r
602 $url = substr($url, 0, $q);
\r
605 $a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);
\r
606 $a2 = md5($this->request->getMethod() . ':' . $url);
\r
608 if (empty($challenge['qop'])) {
\r
609 $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);
\r
611 $challenge['cnonce'] = 'Req2.' . rand();
\r
612 if (empty($challenge['nc'])) {
\r
613 $challenge['nc'] = 1;
\r
615 $nc = sprintf('%08x', $challenge['nc']++);
\r
616 $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .
\r
617 $challenge['cnonce'] . ':auth:' . $a2);
\r
619 return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .
\r
620 'realm="' . $challenge['realm'] . '", ' .
\r
621 'nonce="' . $challenge['nonce'] . '", ' .
\r
622 'uri="' . $url . '", ' .
\r
623 'response="' . $digest . '"' .
\r
624 (!empty($challenge['opaque'])?
\r
625 ', opaque="' . $challenge['opaque'] . '"':
\r
627 (!empty($challenge['qop'])?
\r
628 ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':
\r
633 * Adds 'Authorization' header (if needed) to request headers array
\r
635 * @param array request headers
\r
636 * @param string request host (needed for digest authentication)
\r
637 * @param string request URL (needed for digest authentication)
\r
638 * @throws HTTP_Request2_Exception
\r
640 protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)
\r
642 if (!($auth = $this->request->getAuth())) {
\r
645 switch ($auth['scheme']) {
\r
646 case HTTP_Request2::AUTH_BASIC:
\r
647 $headers['authorization'] =
\r
648 'Basic ' . base64_encode($auth['user'] . ':' . $auth['password']);
\r
651 case HTTP_Request2::AUTH_DIGEST:
\r
652 unset($this->serverChallenge);
\r
653 $fullUrl = ('/' == $requestUrl[0])?
\r
654 $this->request->getUrl()->getScheme() . '://' .
\r
655 $requestHost . $requestUrl:
\r
657 foreach (array_keys(self::$challenges) as $key) {
\r
658 if ($key == substr($fullUrl, 0, strlen($key))) {
\r
659 $headers['authorization'] = $this->createDigestResponse(
\r
660 $auth['user'], $auth['password'],
\r
661 $requestUrl, self::$challenges[$key]
\r
663 $this->serverChallenge =& self::$challenges[$key];
\r
670 throw new HTTP_Request2_Exception(
\r
671 "Unknown HTTP authentication scheme '{$auth['scheme']}'"
\r
677 * Adds 'Proxy-Authorization' header (if needed) to request headers array
\r
679 * @param array request headers
\r
680 * @param string request URL (needed for digest authentication)
\r
681 * @throws HTTP_Request2_Exception
\r
683 protected function addProxyAuthorizationHeader(&$headers, $requestUrl)
\r
685 if (!$this->request->getConfig('proxy_host') ||
\r
686 !($user = $this->request->getConfig('proxy_user')) ||
\r
687 (0 == strcasecmp('https', $this->request->getUrl()->getScheme()) &&
\r
688 HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())
\r
693 $password = $this->request->getConfig('proxy_password');
\r
694 switch ($this->request->getConfig('proxy_auth_scheme')) {
\r
695 case HTTP_Request2::AUTH_BASIC:
\r
696 $headers['proxy-authorization'] =
\r
697 'Basic ' . base64_encode($user . ':' . $password);
\r
700 case HTTP_Request2::AUTH_DIGEST:
\r
701 unset($this->proxyChallenge);
\r
702 $proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .
\r
703 ':' . $this->request->getConfig('proxy_port');
\r
704 if (!empty(self::$challenges[$proxyUrl])) {
\r
705 $headers['proxy-authorization'] = $this->createDigestResponse(
\r
707 $requestUrl, self::$challenges[$proxyUrl]
\r
709 $this->proxyChallenge =& self::$challenges[$proxyUrl];
\r
714 throw new HTTP_Request2_Exception(
\r
715 "Unknown HTTP authentication scheme '" .
\r
716 $this->request->getConfig('proxy_auth_scheme') . "'"
\r
723 * Creates the string with the Request-Line and request headers
\r
726 * @throws HTTP_Request2_Exception
\r
728 protected function prepareHeaders()
\r
730 $headers = $this->request->getHeaders();
\r
731 $url = $this->request->getUrl();
\r
732 $connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
\r
733 $host = $url->getHost();
\r
735 $defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;
\r
736 if (($port = $url->getPort()) && $port != $defaultPort || $connect) {
\r
737 $host .= ':' . (empty($port)? $defaultPort: $port);
\r
739 // Do not overwrite explicitly set 'Host' header, see bug #16146
\r
740 if (!isset($headers['host'])) {
\r
741 $headers['host'] = $host;
\r
745 $requestUrl = $host;
\r
748 if (!$this->request->getConfig('proxy_host') ||
\r
749 0 == strcasecmp($url->getScheme(), 'https')
\r
753 $requestUrl = $url->getScheme() . '://' . $host;
\r
755 $path = $url->getPath();
\r
756 $query = $url->getQuery();
\r
757 $requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);
\r
760 if ('1.1' == $this->request->getConfig('protocol_version') &&
\r
761 extension_loaded('zlib') && !isset($headers['accept-encoding'])
\r
763 $headers['accept-encoding'] = 'gzip, deflate';
\r
766 $this->addAuthorizationHeader($headers, $host, $requestUrl);
\r
767 $this->addProxyAuthorizationHeader($headers, $requestUrl);
\r
768 $this->calculateRequestLength($headers);
\r
770 $headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .
\r
771 $this->request->getConfig('protocol_version') . "\r\n";
\r
772 foreach ($headers as $name => $value) {
\r
773 $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
\r
774 $headersStr .= $canonicalName . ': ' . $value . "\r\n";
\r
776 return $headersStr . "\r\n";
\r
780 * Sends the request body
\r
782 * @throws HTTP_Request2_Exception
\r
784 protected function writeBody()
\r
786 if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||
\r
787 0 == $this->contentLength
\r
793 $bufferSize = $this->request->getConfig('buffer_size');
\r
794 while ($position < $this->contentLength) {
\r
795 if (is_string($this->requestBody)) {
\r
796 $str = substr($this->requestBody, $position, $bufferSize);
\r
797 } elseif (is_resource($this->requestBody)) {
\r
798 $str = fread($this->requestBody, $bufferSize);
\r
800 $str = $this->requestBody->read($bufferSize);
\r
802 if (false === @fwrite($this->socket, $str, strlen($str))) {
\r
803 throw new HTTP_Request2_Exception('Error writing request');
\r
805 // Provide the length of written string to the observer, request #7630
\r
806 $this->request->setLastEvent('sentBodyPart', strlen($str));
\r
807 $position += strlen($str);
\r
812 * Reads the remote server's response
\r
814 * @return HTTP_Request2_Response
\r
815 * @throws HTTP_Request2_Exception
\r
817 protected function readResponse()
\r
819 $bufferSize = $this->request->getConfig('buffer_size');
\r
822 $response = new HTTP_Request2_Response($this->readLine($bufferSize), true);
\r
824 $headerLine = $this->readLine($bufferSize);
\r
825 $response->parseHeaderLine($headerLine);
\r
826 } while ('' != $headerLine);
\r
827 } while (in_array($response->getStatus(), array(100, 101)));
\r
829 $this->request->setLastEvent('receivedHeaders', $response);
\r
831 // No body possible in such responses
\r
832 if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod() ||
\r
833 (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
\r
834 200 <= $response->getStatus() && 300 > $response->getStatus()) ||
\r
835 in_array($response->getStatus(), array(204, 304))
\r
840 $chunked = 'chunked' == $response->getHeader('transfer-encoding');
\r
841 $length = $response->getHeader('content-length');
\r
843 if ($chunked || null === $length || 0 < intval($length)) {
\r
844 // RFC 2616, section 4.4:
\r
845 // 3. ... If a message is received with both a
\r
846 // Transfer-Encoding header field and a Content-Length header field,
\r
847 // the latter MUST be ignored.
\r
848 $toRead = ($chunked || null === $length)? null: $length;
\r
849 $this->chunkLength = 0;
\r
851 while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {
\r
853 $data = $this->readChunked($bufferSize);
\r
854 } elseif (is_null($toRead)) {
\r
855 $data = $this->fread($bufferSize);
\r
857 $data = $this->fread(min($toRead, $bufferSize));
\r
858 $toRead -= strlen($data);
\r
860 if ('' == $data && (!$this->chunkLength || feof($this->socket))) {
\r
865 if ($this->request->getConfig('store_body')) {
\r
866 $response->appendBody($data);
\r
868 if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {
\r
869 $this->request->setLastEvent('receivedEncodedBodyPart', $data);
\r
871 $this->request->setLastEvent('receivedBodyPart', $data);
\r
877 $this->request->setLastEvent('receivedBody', $response);
\r
883 * Reads until either the end of the socket or a newline, whichever comes first
\r
885 * Strips the trailing newline from the returned data, handles global
\r
886 * request timeout. Method idea borrowed from Net_Socket PEAR package.
\r
888 * @param int buffer size to use for reading
\r
889 * @return Available data up to the newline (not including newline)
\r
890 * @throws HTTP_Request2_Exception In case of timeout
\r
892 protected function readLine($bufferSize)
\r
895 while (!feof($this->socket)) {
\r
896 if ($this->timeout) {
\r
897 stream_set_timeout($this->socket, max($this->timeout - time(), 1));
\r
899 $line .= @fgets($this->socket, $bufferSize);
\r
900 $info = stream_get_meta_data($this->socket);
\r
901 if ($info['timed_out'] || $this->timeout && time() > $this->timeout) {
\r
902 throw new HTTP_Request2_Exception(
\r
903 'Request timed out after ' .
\r
904 $this->request->getConfig('timeout') . ' second(s)'
\r
907 if (substr($line, -1) == "\n") {
\r
908 return rtrim($line, "\r\n");
\r
915 * Wrapper around fread(), handles global request timeout
\r
917 * @param int Reads up to this number of bytes
\r
918 * @return Data read from socket
\r
919 * @throws HTTP_Request2_Exception In case of timeout
\r
921 protected function fread($length)
\r
923 if ($this->timeout) {
\r
924 stream_set_timeout($this->socket, max($this->timeout - time(), 1));
\r
926 $data = fread($this->socket, $length);
\r
927 $info = stream_get_meta_data($this->socket);
\r
928 if ($info['timed_out'] || $this->timeout && time() > $this->timeout) {
\r
929 throw new HTTP_Request2_Exception(
\r
930 'Request timed out after ' .
\r
931 $this->request->getConfig('timeout') . ' second(s)'
\r
938 * Reads a part of response body encoded with chunked Transfer-Encoding
\r
940 * @param int buffer size to use for reading
\r
942 * @throws HTTP_Request2_Exception
\r
944 protected function readChunked($bufferSize)
\r
946 // at start of the next chunk?
\r
947 if (0 == $this->chunkLength) {
\r
948 $line = $this->readLine($bufferSize);
\r
949 if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
\r
950 throw new HTTP_Request2_Exception(
\r
951 "Cannot decode chunked response, invalid chunk length '{$line}'"
\r
954 $this->chunkLength = hexdec($matches[1]);
\r
955 // Chunk with zero length indicates the end
\r
956 if (0 == $this->chunkLength) {
\r
957 $this->readLine($bufferSize);
\r
962 $data = $this->fread(min($this->chunkLength, $bufferSize));
\r
963 $this->chunkLength -= strlen($data);
\r
964 if (0 == $this->chunkLength) {
\r
965 $this->readLine($bufferSize); // Trailing CRLF
\r