3 * Socket-based adapter for HTTP_Request2
\r
9 * Copyright (c) 2008-2011, 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 SVN: $Id: Socket.php 309921 2011-04-03 16:43:02Z 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: 2.0.0RC1
\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 * Sum of start time and global timeout, exception will be thrown if request continues past this time
\r
116 protected $deadline = null;
\r
119 * Remaining length of the current chunk, when reading chunked response
\r
121 * @see readChunked()
\r
123 protected $chunkLength = 0;
\r
126 * Remaining amount of redirections to follow
\r
128 * Starts at 'max_redirects' configuration parameter and is reduced on each
\r
129 * subsequent redirect. An Exception will be thrown once it reaches zero.
\r
133 protected $redirectCountdown = null;
\r
136 * Sends request to the remote server and returns its response
\r
138 * @param HTTP_Request2
\r
139 * @return HTTP_Request2_Response
\r
140 * @throws HTTP_Request2_Exception
\r
142 public function sendRequest(HTTP_Request2 $request)
\r
144 $this->request = $request;
\r
146 // Use global request timeout if given, see feature requests #5735, #8964
\r
147 if ($timeout = $request->getConfig('timeout')) {
\r
148 $this->deadline = time() + $timeout;
\r
150 $this->deadline = null;
\r
154 $keepAlive = $this->connect();
\r
155 $headers = $this->prepareHeaders();
\r
156 if (false === @fwrite($this->socket, $headers, strlen($headers))) {
\r
157 throw new HTTP_Request2_MessageException('Error writing request');
\r
159 // provide request headers to the observer, see request #7633
\r
160 $this->request->setLastEvent('sentHeaders', $headers);
\r
161 $this->writeBody();
\r
163 if ($this->deadline && time() > $this->deadline) {
\r
164 throw new HTTP_Request2_MessageException(
\r
165 'Request timed out after ' .
\r
166 $request->getConfig('timeout') . ' second(s)',
\r
167 HTTP_Request2_Exception::TIMEOUT
\r
171 $response = $this->readResponse();
\r
173 if ($jar = $request->getCookieJar()) {
\r
174 $jar->addCookiesFromResponse($response, $request->getUrl());
\r
177 if (!$this->canKeepAlive($keepAlive, $response)) {
\r
178 $this->disconnect();
\r
181 if ($this->shouldUseProxyDigestAuth($response)) {
\r
182 return $this->sendRequest($request);
\r
184 if ($this->shouldUseServerDigestAuth($response)) {
\r
185 return $this->sendRequest($request);
\r
187 if ($authInfo = $response->getHeader('authentication-info')) {
\r
188 $this->updateChallenge($this->serverChallenge, $authInfo);
\r
190 if ($proxyInfo = $response->getHeader('proxy-authentication-info')) {
\r
191 $this->updateChallenge($this->proxyChallenge, $proxyInfo);
\r
194 } catch (Exception $e) {
\r
195 $this->disconnect();
\r
198 unset($this->request, $this->requestBody);
\r
201 $this->redirectCountdown = null;
\r
205 if (!$request->getConfig('follow_redirects') || !$response->isRedirect()) {
\r
206 $this->redirectCountdown = null;
\r
209 return $this->handleRedirect($request, $response);
\r
214 * Connects to the remote server
\r
216 * @return bool whether the connection can be persistent
\r
217 * @throws HTTP_Request2_Exception
\r
219 protected function connect()
\r
221 $secure = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');
\r
222 $tunnel = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
\r
223 $headers = $this->request->getHeaders();
\r
224 $reqHost = $this->request->getUrl()->getHost();
\r
225 if (!($reqPort = $this->request->getUrl()->getPort())) {
\r
226 $reqPort = $secure? 443: 80;
\r
229 if ($host = $this->request->getConfig('proxy_host')) {
\r
230 if (!($port = $this->request->getConfig('proxy_port'))) {
\r
231 throw new HTTP_Request2_LogicException(
\r
232 'Proxy port not provided',
\r
233 HTTP_Request2_Exception::MISSING_VALUE
\r
243 if ($tunnel && !$proxy) {
\r
244 throw new HTTP_Request2_LogicException(
\r
245 "Trying to perform CONNECT request without proxy",
\r
246 HTTP_Request2_Exception::MISSING_VALUE
\r
249 if ($secure && !in_array('ssl', stream_get_transports())) {
\r
250 throw new HTTP_Request2_LogicException(
\r
251 'Need OpenSSL support for https:// requests',
\r
252 HTTP_Request2_Exception::MISCONFIGURATION
\r
256 // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
\r
257 // connection token to a proxy server...
\r
258 if ($proxy && !$secure &&
\r
259 !empty($headers['connection']) && 'Keep-Alive' == $headers['connection']
\r
261 $this->request->setHeader('connection');
\r
264 $keepAlive = ('1.1' == $this->request->getConfig('protocol_version') &&
\r
265 empty($headers['connection'])) ||
\r
266 (!empty($headers['connection']) &&
\r
267 'Keep-Alive' == $headers['connection']);
\r
268 $host = ((!$secure || $proxy)? 'tcp://': 'ssl://') . $host;
\r
270 $options = array();
\r
271 if ($secure || $tunnel) {
\r
272 foreach ($this->request->getConfig() as $name => $value) {
\r
273 if ('ssl_' == substr($name, 0, 4) && null !== $value) {
\r
274 if ('ssl_verify_host' == $name) {
\r
276 $options['CN_match'] = $reqHost;
\r
279 $options[substr($name, 4)] = $value;
\r
286 // Changing SSL context options after connection is established does *not*
\r
287 // work, we need a new connection if options change
\r
288 $remote = $host . ':' . $port;
\r
289 $socketKey = $remote . (($secure && $proxy)? "->{$reqHost}:{$reqPort}": '') .
\r
290 (empty($options)? '': ':' . serialize($options));
\r
291 unset($this->socket);
\r
293 // We use persistent connections and have a connected socket?
\r
294 // Ensure that the socket is still connected, see bug #16149
\r
295 if ($keepAlive && !empty(self::$sockets[$socketKey]) &&
\r
296 !feof(self::$sockets[$socketKey])
\r
298 $this->socket =& self::$sockets[$socketKey];
\r
300 } elseif ($secure && $proxy && !$tunnel) {
\r
301 $this->establishTunnel();
\r
302 $this->request->setLastEvent(
\r
303 'connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}"
\r
305 self::$sockets[$socketKey] =& $this->socket;
\r
308 // Set SSL context options if doing HTTPS request or creating a tunnel
\r
309 $context = stream_context_create();
\r
310 foreach ($options as $name => $value) {
\r
311 if (!stream_context_set_option($context, 'ssl', $name, $value)) {
\r
312 throw new HTTP_Request2_LogicException(
\r
313 "Error setting SSL context option '{$name}'"
\r
317 $track = @ini_set('track_errors', 1);
\r
318 $this->socket = @stream_socket_client(
\r
319 $remote, $errno, $errstr,
\r
320 $this->request->getConfig('connect_timeout'),
\r
321 STREAM_CLIENT_CONNECT, $context
\r
323 if (!$this->socket) {
\r
324 $e = new HTTP_Request2_ConnectionException(
\r
325 "Unable to connect to {$remote}. Error: "
\r
326 . (empty($errstr)? $php_errormsg: $errstr), 0, $errno
\r
329 @ini_set('track_errors', $track);
\r
333 $this->request->setLastEvent('connect', $remote);
\r
334 self::$sockets[$socketKey] =& $this->socket;
\r
340 * Establishes a tunnel to a secure remote server via HTTP CONNECT request
\r
342 * This method will fail if 'ssl_verify_peer' is enabled. Probably because PHP
\r
343 * sees that we are connected to a proxy server (duh!) rather than the server
\r
344 * that presents its certificate.
\r
346 * @link http://tools.ietf.org/html/rfc2817#section-5.2
\r
347 * @throws HTTP_Request2_Exception
\r
349 protected function establishTunnel()
\r
352 $connect = new HTTP_Request2(
\r
353 $this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,
\r
354 array_merge($this->request->getConfig(),
\r
355 array('adapter' => $donor))
\r
357 $response = $connect->send();
\r
358 // Need any successful (2XX) response
\r
359 if (200 > $response->getStatus() || 300 <= $response->getStatus()) {
\r
360 throw new HTTP_Request2_ConnectionException(
\r
361 'Failed to connect via HTTPS proxy. Proxy response: ' .
\r
362 $response->getStatus() . ' ' . $response->getReasonPhrase()
\r
365 $this->socket = $donor->socket;
\r
368 STREAM_CRYPTO_METHOD_TLS_CLIENT,
\r
369 STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
\r
370 STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
\r
371 STREAM_CRYPTO_METHOD_SSLv2_CLIENT
\r
374 foreach ($modes as $mode) {
\r
375 if (stream_socket_enable_crypto($this->socket, true, $mode)) {
\r
379 throw new HTTP_Request2_ConnectionException(
\r
380 'Failed to enable secure connection when connecting through proxy'
\r
385 * Checks whether current connection may be reused or should be closed
\r
387 * @param boolean whether connection could be persistent
\r
388 * in the first place
\r
389 * @param HTTP_Request2_Response response object to check
\r
392 protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)
\r
394 // Do not close socket on successful CONNECT request
\r
395 if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
\r
396 200 <= $response->getStatus() && 300 > $response->getStatus()
\r
401 $lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding'))
\r
402 || null !== $response->getHeader('content-length')
\r
403 // no body possible for such responses, see also request #17031
\r
404 || HTTP_Request2::METHOD_HEAD == $this->request->getMethod()
\r
405 || in_array($response->getStatus(), array(204, 304));
\r
406 $persistent = 'keep-alive' == strtolower($response->getHeader('connection')) ||
\r
407 (null === $response->getHeader('connection') &&
\r
408 '1.1' == $response->getVersion());
\r
409 return $requestKeepAlive && $lengthKnown && $persistent;
\r
413 * Disconnects from the remote server
\r
415 protected function disconnect()
\r
417 if (is_resource($this->socket)) {
\r
418 fclose($this->socket);
\r
419 $this->socket = null;
\r
420 $this->request->setLastEvent('disconnect');
\r
425 * Handles HTTP redirection
\r
427 * This method will throw an Exception if redirect to a non-HTTP(S) location
\r
428 * is attempted, also if number of redirects performed already is equal to
\r
429 * 'max_redirects' configuration parameter.
\r
431 * @param HTTP_Request2 Original request
\r
432 * @param HTTP_Request2_Response Response containing redirect
\r
433 * @return HTTP_Request2_Response Response from a new location
\r
434 * @throws HTTP_Request2_Exception
\r
436 protected function handleRedirect(HTTP_Request2 $request,
\r
437 HTTP_Request2_Response $response)
\r
439 if (is_null($this->redirectCountdown)) {
\r
440 $this->redirectCountdown = $request->getConfig('max_redirects');
\r
442 if (0 == $this->redirectCountdown) {
\r
443 $this->redirectCountdown = null;
\r
444 // Copying cURL behaviour
\r
445 throw new HTTP_Request2_MessageException (
\r
446 'Maximum (' . $request->getConfig('max_redirects') . ') redirects followed',
\r
447 HTTP_Request2_Exception::TOO_MANY_REDIRECTS
\r
450 $redirectUrl = new Net_URL2(
\r
451 $response->getHeader('location'),
\r
452 array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))
\r
454 // refuse non-HTTP redirect
\r
455 if ($redirectUrl->isAbsolute()
\r
456 && !in_array($redirectUrl->getScheme(), array('http', 'https'))
\r
458 $this->redirectCountdown = null;
\r
459 throw new HTTP_Request2_MessageException(
\r
460 'Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString(),
\r
461 HTTP_Request2_Exception::NON_HTTP_REDIRECT
\r
464 // Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30),
\r
465 // but in practice it is often not
\r
466 if (!$redirectUrl->isAbsolute()) {
\r
467 $redirectUrl = $request->getUrl()->resolve($redirectUrl);
\r
469 $redirect = clone $request;
\r
470 $redirect->setUrl($redirectUrl);
\r
471 if (303 == $response->getStatus() || (!$request->getConfig('strict_redirects')
\r
472 && in_array($response->getStatus(), array(301, 302)))
\r
474 $redirect->setMethod(HTTP_Request2::METHOD_GET);
\r
475 $redirect->setBody('');
\r
478 if (0 < $this->redirectCountdown) {
\r
479 $this->redirectCountdown--;
\r
481 return $this->sendRequest($redirect);
\r
485 * Checks whether another request should be performed with server digest auth
\r
487 * Several conditions should be satisfied for it to return true:
\r
488 * - response status should be 401
\r
489 * - auth credentials should be set in the request object
\r
490 * - response should contain WWW-Authenticate header with digest challenge
\r
491 * - there is either no challenge stored for this URL or new challenge
\r
492 * contains stale=true parameter (in other case we probably just failed
\r
493 * due to invalid username / password)
\r
495 * The method stores challenge values in $challenges static property
\r
497 * @param HTTP_Request2_Response response to check
\r
498 * @return boolean whether another request should be performed
\r
499 * @throws HTTP_Request2_Exception in case of unsupported challenge parameters
\r
501 protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)
\r
503 // no sense repeating a request if we don't have credentials
\r
504 if (401 != $response->getStatus() || !$this->request->getAuth()) {
\r
507 if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {
\r
511 $url = $this->request->getUrl();
\r
512 $scheme = $url->getScheme();
\r
513 $host = $scheme . '://' . $url->getHost();
\r
514 if ($port = $url->getPort()) {
\r
515 if ((0 == strcasecmp($scheme, 'http') && 80 != $port) ||
\r
516 (0 == strcasecmp($scheme, 'https') && 443 != $port)
\r
518 $host .= ':' . $port;
\r
522 if (!empty($challenge['domain'])) {
\r
523 $prefixes = array();
\r
524 foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {
\r
525 // don't bother with different servers
\r
526 if ('/' == substr($prefix, 0, 1)) {
\r
527 $prefixes[] = $host . $prefix;
\r
531 if (empty($prefixes)) {
\r
532 $prefixes = array($host . '/');
\r
536 foreach ($prefixes as $prefix) {
\r
537 if (!empty(self::$challenges[$prefix]) &&
\r
538 (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
\r
540 // probably credentials are invalid
\r
543 self::$challenges[$prefix] =& $challenge;
\r
549 * Checks whether another request should be performed with proxy digest auth
\r
551 * Several conditions should be satisfied for it to return true:
\r
552 * - response status should be 407
\r
553 * - proxy auth credentials should be set in the request object
\r
554 * - response should contain Proxy-Authenticate header with digest challenge
\r
555 * - there is either no challenge stored for this proxy or new challenge
\r
556 * contains stale=true parameter (in other case we probably just failed
\r
557 * due to invalid username / password)
\r
559 * The method stores challenge values in $challenges static property
\r
561 * @param HTTP_Request2_Response response to check
\r
562 * @return boolean whether another request should be performed
\r
563 * @throws HTTP_Request2_Exception in case of unsupported challenge parameters
\r
565 protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)
\r
567 if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
\r
570 if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
\r
574 $key = 'proxy://' . $this->request->getConfig('proxy_host') .
\r
575 ':' . $this->request->getConfig('proxy_port');
\r
577 if (!empty(self::$challenges[$key]) &&
\r
578 (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
\r
584 self::$challenges[$key] = $challenge;
\r
589 * Extracts digest method challenge from (WWW|Proxy)-Authenticate header value
\r
591 * There is a problem with implementation of RFC 2617: several of the parameters
\r
592 * are defined as quoted-string there and thus may contain backslash escaped
\r
593 * double quotes (RFC 2616, section 2.2). However, RFC 2617 defines unq(X) as
\r
594 * just value of quoted-string X without surrounding quotes, it doesn't speak
\r
595 * about removing backslash escaping.
\r
597 * Now realm parameter is user-defined and human-readable, strange things
\r
598 * happen when it contains quotes:
\r
599 * - Apache allows quotes in realm, but apparently uses realm value without
\r
600 * backslashes for digest computation
\r
601 * - Squid allows (manually escaped) quotes there, but it is impossible to
\r
602 * authorize with either escaped or unescaped quotes used in digest,
\r
603 * probably it can't parse the response (?)
\r
604 * - Both IE and Firefox display realm value with backslashes in
\r
605 * the password popup and apparently use the same value for digest
\r
607 * HTTP_Request2 follows IE and Firefox (and hopefully RFC 2617) in
\r
608 * quoted-string handling, unfortunately that means failure to authorize
\r
611 * @param string value of WWW-Authenticate or Proxy-Authenticate header
\r
612 * @return mixed associative array with challenge parameters, false if
\r
613 * no challenge is present in header value
\r
614 * @throws HTTP_Request2_NotImplementedException in case of unsupported challenge parameters
\r
616 protected function parseDigestChallenge($headerValue)
\r
618 $authParam = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
\r
619 self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';
\r
620 $challenge = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";
\r
621 if (!preg_match($challenge, $headerValue, $matches)) {
\r
625 preg_match_all('!' . $authParam . '!', $matches[0], $params);
\r
626 $paramsAry = array();
\r
627 $knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',
\r
628 'algorithm', 'qop');
\r
629 for ($i = 0; $i < count($params[0]); $i++) {
\r
630 // section 3.2.1: Any unrecognized directive MUST be ignored.
\r
631 if (in_array($params[1][$i], $knownParams)) {
\r
632 if ('"' == substr($params[2][$i], 0, 1)) {
\r
633 $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
\r
635 $paramsAry[$params[1][$i]] = $params[2][$i];
\r
639 // we only support qop=auth
\r
640 if (!empty($paramsAry['qop']) &&
\r
641 !in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))
\r
643 throw new HTTP_Request2_NotImplementedException(
\r
644 "Only 'auth' qop is currently supported in digest authentication, " .
\r
645 "server requested '{$paramsAry['qop']}'"
\r
648 // we only support algorithm=MD5
\r
649 if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {
\r
650 throw new HTTP_Request2_NotImplementedException(
\r
651 "Only 'MD5' algorithm is currently supported in digest authentication, " .
\r
652 "server requested '{$paramsAry['algorithm']}'"
\r
660 * Parses [Proxy-]Authentication-Info header value and updates challenge
\r
662 * @param array challenge to update
\r
663 * @param string value of [Proxy-]Authentication-Info header
\r
664 * @todo validate server rspauth response
\r
666 protected function updateChallenge(&$challenge, $headerValue)
\r
668 $authParam = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
\r
669 self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';
\r
670 $paramsAry = array();
\r
672 preg_match_all($authParam, $headerValue, $params);
\r
673 for ($i = 0; $i < count($params[0]); $i++) {
\r
674 if ('"' == substr($params[2][$i], 0, 1)) {
\r
675 $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
\r
677 $paramsAry[$params[1][$i]] = $params[2][$i];
\r
680 // for now, just update the nonce value
\r
681 if (!empty($paramsAry['nextnonce'])) {
\r
682 $challenge['nonce'] = $paramsAry['nextnonce'];
\r
683 $challenge['nc'] = 1;
\r
688 * Creates a value for [Proxy-]Authorization header when using digest authentication
\r
690 * @param string user name
\r
691 * @param string password
\r
692 * @param string request URL
\r
693 * @param array digest challenge parameters
\r
694 * @return string value of [Proxy-]Authorization request header
\r
695 * @link http://tools.ietf.org/html/rfc2617#section-3.2.2
\r
697 protected function createDigestResponse($user, $password, $url, &$challenge)
\r
699 if (false !== ($q = strpos($url, '?')) &&
\r
700 $this->request->getConfig('digest_compat_ie')
\r
702 $url = substr($url, 0, $q);
\r
705 $a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);
\r
706 $a2 = md5($this->request->getMethod() . ':' . $url);
\r
708 if (empty($challenge['qop'])) {
\r
709 $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);
\r
711 $challenge['cnonce'] = 'Req2.' . rand();
\r
712 if (empty($challenge['nc'])) {
\r
713 $challenge['nc'] = 1;
\r
715 $nc = sprintf('%08x', $challenge['nc']++);
\r
716 $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .
\r
717 $challenge['cnonce'] . ':auth:' . $a2);
\r
719 return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .
\r
720 'realm="' . $challenge['realm'] . '", ' .
\r
721 'nonce="' . $challenge['nonce'] . '", ' .
\r
722 'uri="' . $url . '", ' .
\r
723 'response="' . $digest . '"' .
\r
724 (!empty($challenge['opaque'])?
\r
725 ', opaque="' . $challenge['opaque'] . '"':
\r
727 (!empty($challenge['qop'])?
\r
728 ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':
\r
733 * Adds 'Authorization' header (if needed) to request headers array
\r
735 * @param array request headers
\r
736 * @param string request host (needed for digest authentication)
\r
737 * @param string request URL (needed for digest authentication)
\r
738 * @throws HTTP_Request2_NotImplementedException
\r
740 protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)
\r
742 if (!($auth = $this->request->getAuth())) {
\r
745 switch ($auth['scheme']) {
\r
746 case HTTP_Request2::AUTH_BASIC:
\r
747 $headers['authorization'] =
\r
748 'Basic ' . base64_encode($auth['user'] . ':' . $auth['password']);
\r
751 case HTTP_Request2::AUTH_DIGEST:
\r
752 unset($this->serverChallenge);
\r
753 $fullUrl = ('/' == $requestUrl[0])?
\r
754 $this->request->getUrl()->getScheme() . '://' .
\r
755 $requestHost . $requestUrl:
\r
757 foreach (array_keys(self::$challenges) as $key) {
\r
758 if ($key == substr($fullUrl, 0, strlen($key))) {
\r
759 $headers['authorization'] = $this->createDigestResponse(
\r
760 $auth['user'], $auth['password'],
\r
761 $requestUrl, self::$challenges[$key]
\r
763 $this->serverChallenge =& self::$challenges[$key];
\r
770 throw new HTTP_Request2_NotImplementedException(
\r
771 "Unknown HTTP authentication scheme '{$auth['scheme']}'"
\r
777 * Adds 'Proxy-Authorization' header (if needed) to request headers array
\r
779 * @param array request headers
\r
780 * @param string request URL (needed for digest authentication)
\r
781 * @throws HTTP_Request2_NotImplementedException
\r
783 protected function addProxyAuthorizationHeader(&$headers, $requestUrl)
\r
785 if (!$this->request->getConfig('proxy_host') ||
\r
786 !($user = $this->request->getConfig('proxy_user')) ||
\r
787 (0 == strcasecmp('https', $this->request->getUrl()->getScheme()) &&
\r
788 HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())
\r
793 $password = $this->request->getConfig('proxy_password');
\r
794 switch ($this->request->getConfig('proxy_auth_scheme')) {
\r
795 case HTTP_Request2::AUTH_BASIC:
\r
796 $headers['proxy-authorization'] =
\r
797 'Basic ' . base64_encode($user . ':' . $password);
\r
800 case HTTP_Request2::AUTH_DIGEST:
\r
801 unset($this->proxyChallenge);
\r
802 $proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .
\r
803 ':' . $this->request->getConfig('proxy_port');
\r
804 if (!empty(self::$challenges[$proxyUrl])) {
\r
805 $headers['proxy-authorization'] = $this->createDigestResponse(
\r
807 $requestUrl, self::$challenges[$proxyUrl]
\r
809 $this->proxyChallenge =& self::$challenges[$proxyUrl];
\r
814 throw new HTTP_Request2_NotImplementedException(
\r
815 "Unknown HTTP authentication scheme '" .
\r
816 $this->request->getConfig('proxy_auth_scheme') . "'"
\r
823 * Creates the string with the Request-Line and request headers
\r
826 * @throws HTTP_Request2_Exception
\r
828 protected function prepareHeaders()
\r
830 $headers = $this->request->getHeaders();
\r
831 $url = $this->request->getUrl();
\r
832 $connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
\r
833 $host = $url->getHost();
\r
835 $defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;
\r
836 if (($port = $url->getPort()) && $port != $defaultPort || $connect) {
\r
837 $host .= ':' . (empty($port)? $defaultPort: $port);
\r
839 // Do not overwrite explicitly set 'Host' header, see bug #16146
\r
840 if (!isset($headers['host'])) {
\r
841 $headers['host'] = $host;
\r
845 $requestUrl = $host;
\r
848 if (!$this->request->getConfig('proxy_host') ||
\r
849 0 == strcasecmp($url->getScheme(), 'https')
\r
853 $requestUrl = $url->getScheme() . '://' . $host;
\r
855 $path = $url->getPath();
\r
856 $query = $url->getQuery();
\r
857 $requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);
\r
860 if ('1.1' == $this->request->getConfig('protocol_version') &&
\r
861 extension_loaded('zlib') && !isset($headers['accept-encoding'])
\r
863 $headers['accept-encoding'] = 'gzip, deflate';
\r
865 if (($jar = $this->request->getCookieJar())
\r
866 && ($cookies = $jar->getMatching($this->request->getUrl(), true))
\r
868 $headers['cookie'] = (empty($headers['cookie'])? '': $headers['cookie'] . '; ') . $cookies;
\r
871 $this->addAuthorizationHeader($headers, $host, $requestUrl);
\r
872 $this->addProxyAuthorizationHeader($headers, $requestUrl);
\r
873 $this->calculateRequestLength($headers);
\r
875 $headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .
\r
876 $this->request->getConfig('protocol_version') . "\r\n";
\r
877 foreach ($headers as $name => $value) {
\r
878 $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
\r
879 $headersStr .= $canonicalName . ': ' . $value . "\r\n";
\r
881 return $headersStr . "\r\n";
\r
885 * Sends the request body
\r
887 * @throws HTTP_Request2_MessageException
\r
889 protected function writeBody()
\r
891 if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||
\r
892 0 == $this->contentLength
\r
898 $bufferSize = $this->request->getConfig('buffer_size');
\r
899 while ($position < $this->contentLength) {
\r
900 if (is_string($this->requestBody)) {
\r
901 $str = substr($this->requestBody, $position, $bufferSize);
\r
902 } elseif (is_resource($this->requestBody)) {
\r
903 $str = fread($this->requestBody, $bufferSize);
\r
905 $str = $this->requestBody->read($bufferSize);
\r
907 if (false === @fwrite($this->socket, $str, strlen($str))) {
\r
908 throw new HTTP_Request2_MessageException('Error writing request');
\r
910 // Provide the length of written string to the observer, request #7630
\r
911 $this->request->setLastEvent('sentBodyPart', strlen($str));
\r
912 $position += strlen($str);
\r
914 $this->request->setLastEvent('sentBody', $this->contentLength);
\r
918 * Reads the remote server's response
\r
920 * @return HTTP_Request2_Response
\r
921 * @throws HTTP_Request2_Exception
\r
923 protected function readResponse()
\r
925 $bufferSize = $this->request->getConfig('buffer_size');
\r
928 $response = new HTTP_Request2_Response(
\r
929 $this->readLine($bufferSize), true, $this->request->getUrl()
\r
932 $headerLine = $this->readLine($bufferSize);
\r
933 $response->parseHeaderLine($headerLine);
\r
934 } while ('' != $headerLine);
\r
935 } while (in_array($response->getStatus(), array(100, 101)));
\r
937 $this->request->setLastEvent('receivedHeaders', $response);
\r
939 // No body possible in such responses
\r
940 if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod() ||
\r
941 (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&
\r
942 200 <= $response->getStatus() && 300 > $response->getStatus()) ||
\r
943 in_array($response->getStatus(), array(204, 304))
\r
948 $chunked = 'chunked' == $response->getHeader('transfer-encoding');
\r
949 $length = $response->getHeader('content-length');
\r
951 if ($chunked || null === $length || 0 < intval($length)) {
\r
952 // RFC 2616, section 4.4:
\r
953 // 3. ... If a message is received with both a
\r
954 // Transfer-Encoding header field and a Content-Length header field,
\r
955 // the latter MUST be ignored.
\r
956 $toRead = ($chunked || null === $length)? null: $length;
\r
957 $this->chunkLength = 0;
\r
959 while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {
\r
961 $data = $this->readChunked($bufferSize);
\r
962 } elseif (is_null($toRead)) {
\r
963 $data = $this->fread($bufferSize);
\r
965 $data = $this->fread(min($toRead, $bufferSize));
\r
966 $toRead -= strlen($data);
\r
968 if ('' == $data && (!$this->chunkLength || feof($this->socket))) {
\r
973 if ($this->request->getConfig('store_body')) {
\r
974 $response->appendBody($data);
\r
976 if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {
\r
977 $this->request->setLastEvent('receivedEncodedBodyPart', $data);
\r
979 $this->request->setLastEvent('receivedBodyPart', $data);
\r
985 $this->request->setLastEvent('receivedBody', $response);
\r
991 * Reads until either the end of the socket or a newline, whichever comes first
\r
993 * Strips the trailing newline from the returned data, handles global
\r
994 * request timeout. Method idea borrowed from Net_Socket PEAR package.
\r
996 * @param int buffer size to use for reading
\r
997 * @return Available data up to the newline (not including newline)
\r
998 * @throws HTTP_Request2_MessageException In case of timeout
\r
1000 protected function readLine($bufferSize)
\r
1003 while (!feof($this->socket)) {
\r
1004 if ($this->deadline) {
\r
1005 stream_set_timeout($this->socket, max($this->deadline - time(), 1));
\r
1007 $line .= @fgets($this->socket, $bufferSize);
\r
1008 $info = stream_get_meta_data($this->socket);
\r
1009 if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
\r
1010 $reason = $this->deadline
\r
1011 ? 'after ' . $this->request->getConfig('timeout') . ' second(s)'
\r
1012 : 'due to default_socket_timeout php.ini setting';
\r
1013 throw new HTTP_Request2_MessageException(
\r
1014 "Request timed out {$reason}", HTTP_Request2_Exception::TIMEOUT
\r
1017 if (substr($line, -1) == "\n") {
\r
1018 return rtrim($line, "\r\n");
\r
1025 * Wrapper around fread(), handles global request timeout
\r
1027 * @param int Reads up to this number of bytes
\r
1028 * @return Data read from socket
\r
1029 * @throws HTTP_Request2_MessageException In case of timeout
\r
1031 protected function fread($length)
\r
1033 if ($this->deadline) {
\r
1034 stream_set_timeout($this->socket, max($this->deadline - time(), 1));
\r
1036 $data = fread($this->socket, $length);
\r
1037 $info = stream_get_meta_data($this->socket);
\r
1038 if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
\r
1039 $reason = $this->deadline
\r
1040 ? 'after ' . $this->request->getConfig('timeout') . ' second(s)'
\r
1041 : 'due to default_socket_timeout php.ini setting';
\r
1042 throw new HTTP_Request2_MessageException(
\r
1043 "Request timed out {$reason}", HTTP_Request2_Exception::TIMEOUT
\r
1050 * Reads a part of response body encoded with chunked Transfer-Encoding
\r
1052 * @param int buffer size to use for reading
\r
1054 * @throws HTTP_Request2_MessageException
\r
1056 protected function readChunked($bufferSize)
\r
1058 // at start of the next chunk?
\r
1059 if (0 == $this->chunkLength) {
\r
1060 $line = $this->readLine($bufferSize);
\r
1061 if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
\r
1062 throw new HTTP_Request2_MessageException(
\r
1063 "Cannot decode chunked response, invalid chunk length '{$line}'",
\r
1064 HTTP_Request2_Exception::DECODE_ERROR
\r
1067 $this->chunkLength = hexdec($matches[1]);
\r
1068 // Chunk with zero length indicates the end
\r
1069 if (0 == $this->chunkLength) {
\r
1070 $this->readLine($bufferSize);
\r
1075 $data = $this->fread(min($this->chunkLength, $bufferSize));
\r
1076 $this->chunkLength -= strlen($data);
\r
1077 if (0 == $this->chunkLength) {
\r
1078 $this->readLine($bufferSize); // Trailing CRLF
\r