Browse Source

Merge pull request #947 from cakephp/2.3-http-socket

2.3 HttpSocket enhancements
Mark Story 13 years ago
parent
commit
bfbd05576b

File diff suppressed because it is too large
+ 3920 - 0
lib/Cake/Config/cacert.pem


+ 58 - 4
lib/Cake/Network/CakeSocket.php

@@ -102,6 +102,14 @@ class CakeSocket {
 	);
 
 /**
+ * Used to capture connection warnings which can happen when there are
+ * SSL errors for example.
+ *
+ * @var array
+ */
+	protected $_connectionErrors = array();
+
+/**
  * Constructor.
  *
  * @param array $config Socket configuration, which will be merged with the base configuration
@@ -126,21 +134,42 @@ class CakeSocket {
 		}
 
 		$scheme = null;
-		if (isset($this->config['request']) && $this->config['request']['uri']['scheme'] == 'https') {
+		if (isset($this->config['request']['uri']) && $this->config['request']['uri']['scheme'] == 'https') {
 			$scheme = 'ssl://';
 		}
 
-		if ($this->config['persistent']) {
-			$this->connection = @pfsockopen($scheme . $this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
+		if (!empty($this->config['context'])) {
+			$context = stream_context_create($this->config['context']);
 		} else {
-			$this->connection = @fsockopen($scheme . $this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
+			$context = stream_context_create();
 		}
 
+		$connectAs = STREAM_CLIENT_CONNECT;
+		if ($this->config['persistent']) {
+			$connectAs |= STREAM_CLIENT_PERSISTENT;
+		}
+
+		set_error_handler(array($this, '_connectionErrorHandler'));
+		$this->connection = stream_socket_client(
+			$scheme . $this->config['host'] . ':' . $this->config['port'],
+			$errNum,
+			$errStr,
+			$this->config['timeout'],
+			$connectAs,
+			$context
+		);
+		restore_error_handler();
+
 		if (!empty($errNum) || !empty($errStr)) {
 			$this->setLastError($errNum, $errStr);
 			throw new SocketException($errStr, $errNum);
 		}
 
+		if (!$this->connection && $this->_connectionErrors) {
+			$message = implode("\n", $this->_connectionErrors);
+			throw new SocketException($message, E_WARNING);
+		}
+
 		$this->connected = is_resource($this->connection);
 		if ($this->connected) {
 			stream_set_timeout($this->connection, $this->config['timeout']);
@@ -149,6 +178,31 @@ class CakeSocket {
 	}
 
 /**
+ * socket_stream_client() does not populate errNum, or $errStr when there are
+ * connection errors, as in the case of SSL verification failure.
+ *
+ * Instead we need to handle those errors manually.
+ *
+ * @param int $code
+ * @param string $message
+ */
+	protected function _connectionErrorHandler($code, $message) {
+		$this->_connectionErrors[] = $message;
+	}
+
+/**
+ * Get the connection context.
+ *
+ * @return null|array Null when there is no connnection, an array when there is.
+ */
+	public function context() {
+		if (!$this->connection) {
+			return;
+		}
+		return stream_context_get_options($this->connection);
+	}
+
+/**
  * Get the host name of the current connection.
  *
  * @return string Host name

+ 10 - 423
lib/Cake/Network/Http/HttpResponse.php

@@ -12,437 +12,24 @@
  *
  * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  * @link          http://cakephp.org CakePHP(tm) Project
- * @package       Cake.Network.Http
  * @since         CakePHP(tm) v 2.0.0
  * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
  */
+App::uses('HttpSocketResponse', 'Network/Http');
+
+if (class_exists('HttpResponse')) {
+	trigger_error(__d(
+		'cake_dev',
+		"HttpResponse is deprecated due to naming conflicts. Use HttpSocketResponse instead."
+	), E_USER_ERROR);
+}
 
 /**
  * HTTP Response from HttpSocket.
  *
  * @package       Cake.Network.Http
+ * @deprecated This class is deprecated as it has naming conflicts with pecl/http
  */
-class HttpResponse implements ArrayAccess {
-
-/**
- * Body content
- *
- * @var string
- */
-	public $body = '';
-
-/**
- * Headers
- *
- * @var array
- */
-	public $headers = array();
-
-/**
- * Cookies
- *
- * @var array
- */
-	public $cookies = array();
-
-/**
- * HTTP version
- *
- * @var string
- */
-	public $httpVersion = 'HTTP/1.1';
-
-/**
- * Response code
- *
- * @var integer
- */
-	public $code = 0;
-
-/**
- * Reason phrase
- *
- * @var string
- */
-	public $reasonPhrase = '';
-
-/**
- * Pure raw content
- *
- * @var string
- */
-	public $raw = '';
-
-/**
- * Constructor
- *
- * @param string $message
- */
-	public function __construct($message = null) {
-		if ($message !== null) {
-			$this->parseResponse($message);
-		}
-	}
-
-/**
- * Body content
- *
- * @return string
- */
-	public function body() {
-		return (string)$this->body;
-	}
-
-/**
- * Get header in case insensitive
- *
- * @param string $name Header name
- * @param array $headers
- * @return mixed String if header exists or null
- */
-	public function getHeader($name, $headers = null) {
-		if (!is_array($headers)) {
-			$headers =& $this->headers;
-		}
-		if (isset($headers[$name])) {
-			return $headers[$name];
-		}
-		foreach ($headers as $key => $value) {
-			if (strcasecmp($key, $name) === 0) {
-				return $value;
-			}
-		}
-		return null;
-	}
-
-/**
- * If return is 200 (OK)
- *
- * @return boolean
- */
-	public function isOk() {
-		return $this->code == 200;
-	}
-
-/**
- * If return is a valid 3xx (Redirection)
- *
- * @return boolean
- */
-	public function isRedirect() {
-		return in_array($this->code, array(301, 302, 303, 307)) && !is_null($this->getHeader('Location'));
-	}
-
-/**
- * Parses the given message and breaks it down in parts.
- *
- * @param string $message Message to parse
- * @return void
- * @throws SocketException
- */
-	public function parseResponse($message) {
-		if (!is_string($message)) {
-			throw new SocketException(__d('cake_dev', 'Invalid response.'));
-		}
-
-		if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
-			throw new SocketException(__d('cake_dev', 'Invalid HTTP response.'));
-		}
-
-		list(, $statusLine, $header) = $match;
-		$this->raw = $message;
-		$this->body = (string)substr($message, strlen($match[0]));
-
-		if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $statusLine, $match)) {
-			$this->httpVersion = $match[1];
-			$this->code = $match[2];
-			$this->reasonPhrase = $match[3];
-		}
-
-		$this->headers = $this->_parseHeader($header);
-		$transferEncoding = $this->getHeader('Transfer-Encoding');
-		$decoded = $this->_decodeBody($this->body, $transferEncoding);
-		$this->body = $decoded['body'];
-
-		if (!empty($decoded['header'])) {
-			$this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header']));
-		}
-
-		if (!empty($this->headers)) {
-			$this->cookies = $this->parseCookies($this->headers);
-		}
-	}
-
-/**
- * Generic function to decode a $body with a given $encoding. Returns either an array with the keys
- * 'body' and 'header' or false on failure.
- *
- * @param string $body A string containing the body to decode.
- * @param string|boolean $encoding Can be false in case no encoding is being used, or a string representing the encoding.
- * @return mixed Array of response headers and body or false.
- */
-	protected function _decodeBody($body, $encoding = 'chunked') {
-		if (!is_string($body)) {
-			return false;
-		}
-		if (empty($encoding)) {
-			return array('body' => $body, 'header' => false);
-		}
-		$decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body';
-
-		if (!is_callable(array(&$this, $decodeMethod))) {
-			return array('body' => $body, 'header' => false);
-		}
-		return $this->{$decodeMethod}($body);
-	}
-
-/**
- * Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
- * a result.
- *
- * @param string $body A string containing the chunked body to decode.
- * @return mixed Array of response headers and body or false.
- * @throws SocketException
- */
-	protected function _decodeChunkedBody($body) {
-		if (!is_string($body)) {
-			return false;
-		}
-
-		$decodedBody = null;
-		$chunkLength = null;
-
-		while ($chunkLength !== 0) {
-			if (!preg_match('/^([0-9a-f]+) *(?:;(.+)=(.+))?(?:\r\n|\n)/iU', $body, $match)) {
-				throw new SocketException(__d('cake_dev', 'HttpSocket::_decodeChunkedBody - Could not parse malformed chunk.'));
-			}
-
-			$chunkSize = 0;
-			$hexLength = 0;
-			$chunkExtensionName = '';
-			$chunkExtensionValue = '';
-			if (isset($match[0])) {
-				$chunkSize = $match[0];
-			}
-			if (isset($match[1])) {
-				$hexLength = $match[1];
-			}
-			if (isset($match[2])) {
-				$chunkExtensionName = $match[2];
-			}
-			if (isset($match[3])) {
-				$chunkExtensionValue = $match[3];
-			}
-
-			$body = substr($body, strlen($chunkSize));
-			$chunkLength = hexdec($hexLength);
-			$chunk = substr($body, 0, $chunkLength);
-			if (!empty($chunkExtensionName)) {
-				 // @todo See if there are popular chunk extensions we should implement
-			}
-			$decodedBody .= $chunk;
-			if ($chunkLength !== 0) {
-				$body = substr($body, $chunkLength + strlen("\r\n"));
-			}
-		}
-
-		$entityHeader = false;
-		if (!empty($body)) {
-			$entityHeader = $this->_parseHeader($body);
-		}
-		return array('body' => $decodedBody, 'header' => $entityHeader);
-	}
-
-/**
- * Parses an array based header.
- *
- * @param array $header Header as an indexed array (field => value)
- * @return array Parsed header
- */
-	protected function _parseHeader($header) {
-		if (is_array($header)) {
-			return $header;
-		} elseif (!is_string($header)) {
-			return false;
-		}
-
-		preg_match_all("/(.+):(.+)(?:(?<![\t ])\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER);
-
-		$header = array();
-		foreach ($matches as $match) {
-			list(, $field, $value) = $match;
-
-			$value = trim($value);
-			$value = preg_replace("/[\t ]\r\n/", "\r\n", $value);
-
-			$field = $this->_unescapeToken($field);
-
-			if (!isset($header[$field])) {
-				$header[$field] = $value;
-			} else {
-				$header[$field] = array_merge((array)$header[$field], (array)$value);
-			}
-		}
-		return $header;
-	}
-
-/**
- * Parses cookies in response headers.
- *
- * @param array $header Header array containing one ore more 'Set-Cookie' headers.
- * @return mixed Either false on no cookies, or an array of cookies received.
- * @todo Make this 100% RFC 2965 confirm
- */
-	public function parseCookies($header) {
-		$cookieHeader = $this->getHeader('Set-Cookie', $header);
-		if (!$cookieHeader) {
-			return false;
-		}
-
-		$cookies = array();
-		foreach ((array)$cookieHeader as $cookie) {
-			if (strpos($cookie, '";"') !== false) {
-				$cookie = str_replace('";"', "{__cookie_replace__}", $cookie);
-				$parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie));
-			} else {
-				$parts = preg_split('/\;[ \t]*/', $cookie);
-			}
-
-			list($name, $value) = explode('=', array_shift($parts), 2);
-			$cookies[$name] = compact('value');
-
-			foreach ($parts as $part) {
-				if (strpos($part, '=') !== false) {
-					list($key, $value) = explode('=', $part);
-				} else {
-					$key = $part;
-					$value = true;
-				}
-
-				$key = strtolower($key);
-				if (!isset($cookies[$name][$key])) {
-					$cookies[$name][$key] = $value;
-				}
-			}
-		}
-		return $cookies;
-	}
-
-/**
- * Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
- *
- * @param string $token Token to unescape
- * @param array $chars
- * @return string Unescaped token
- * @todo Test $chars parameter
- */
-	protected function _unescapeToken($token, $chars = null) {
-		$regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/';
-		$token = preg_replace($regex, '\\1', $token);
-		return $token;
-	}
-
-/**
- * Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
- *
- * @param boolean $hex true to get them as HEX values, false otherwise
- * @param array $chars
- * @return array Escape chars
- * @todo Test $chars parameter
- */
-	protected function _tokenEscapeChars($hex = true, $chars = null) {
-		if (!empty($chars)) {
-			$escape = $chars;
-		} else {
-			$escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
-			for ($i = 0; $i <= 31; $i++) {
-				$escape[] = chr($i);
-			}
-			$escape[] = chr(127);
-		}
-
-		if (!$hex) {
-			return $escape;
-		}
-		foreach ($escape as $key => $char) {
-			$escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
-		}
-		return $escape;
-	}
-
-/**
- * ArrayAccess - Offset Exists
- *
- * @param string $offset
- * @return boolean
- */
-	public function offsetExists($offset) {
-		return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies'));
-	}
-
-/**
- * ArrayAccess - Offset Get
- *
- * @param string $offset
- * @return mixed
- */
-	public function offsetGet($offset) {
-		switch ($offset) {
-			case 'raw':
-				$firstLineLength = strpos($this->raw, "\r\n") + 2;
-				if ($this->raw[$firstLineLength] === "\r") {
-					$header = null;
-				} else {
-					$header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n";
-				}
-				return array(
-					'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n",
-					'header' => $header,
-					'body' => $this->body,
-					'response' => $this->raw
-				);
-			case 'status':
-				return array(
-					'http-version' => $this->httpVersion,
-					'code' => $this->code,
-					'reason-phrase' => $this->reasonPhrase
-				);
-			case 'header':
-				return $this->headers;
-			case 'body':
-				return $this->body;
-			case 'cookies':
-				return $this->cookies;
-		}
-		return null;
-	}
-
-/**
- * ArrayAccess - Offset Set
- *
- * @param string $offset
- * @param mixed $value
- * @return void
- */
-	public function offsetSet($offset, $value) {
-	}
-
-/**
- * ArrayAccess - Offset Unset
- *
- * @param string $offset
- * @return void
- */
-	public function offsetUnset($offset) {
-	}
-
-/**
- * Instance as string
- *
- * @return string
- */
-	public function __toString() {
-		return $this->body();
-	}
+class HttpResponse extends HttpSocketResponse {
 
 }

+ 38 - 4
lib/Cake/Network/Http/HttpSocket.php

@@ -18,6 +18,7 @@
  */
 App::uses('CakeSocket', 'Network');
 App::uses('Router', 'Routing');
+App::uses('Hash', 'Utility');
 
 /**
  * Cake network socket connection class.
@@ -64,7 +65,7 @@ class HttpSocket extends CakeSocket {
 		),
 		'raw' => null,
 		'redirect' => false,
-		'cookies' => array()
+		'cookies' => array(),
 	);
 
 /**
@@ -79,7 +80,7 @@ class HttpSocket extends CakeSocket {
  *
  * @var string
  */
-	public $responseClass = 'HttpResponse';
+	public $responseClass = 'HttpSocketResponse';
 
 /**
  * Configuration settings for the HttpSocket and the requests
@@ -92,6 +93,9 @@ class HttpSocket extends CakeSocket {
 		'protocol' => 'tcp',
 		'port' => 80,
 		'timeout' => 30,
+		'ssl_verify_peer' => true,
+		'ssl_verify_depth' => 5,
+		'ssl_verify_host' => true,
 		'request' => array(
 			'uri' => array(
 				'scheme' => array('http', 'https'),
@@ -99,7 +103,7 @@ class HttpSocket extends CakeSocket {
 				'port' => array(80, 443)
 			),
 			'redirect' => false,
-			'cookies' => array()
+			'cookies' => array(),
 		)
 	);
 
@@ -246,7 +250,7 @@ class HttpSocket extends CakeSocket {
  * method and provide a more granular interface.
  *
  * @param string|array $request Either an URI string, or an array defining host/uri
- * @return mixed false on error, HttpResponse on success
+ * @return mixed false on error, HttpSocketResponse on success
  * @throws SocketException
  */
 	public function request($request = array()) {
@@ -348,6 +352,8 @@ class HttpSocket extends CakeSocket {
 			return false;
 		}
 
+		$this->_configContext($this->request['uri']['host']);
+
 		$this->request['raw'] = '';
 		if ($this->request['line'] !== false) {
 			$this->request['raw'] = $this->request['line'];
@@ -395,6 +401,7 @@ class HttpSocket extends CakeSocket {
 			throw new SocketException(__d('cake_dev', 'Class %s not found.', $this->responseClass));
 		}
 		$this->response = new $responseClass($response);
+
 		if (!empty($this->response->cookies)) {
 			if (!isset($this->config['request']['cookies'][$Host])) {
 				$this->config['request']['cookies'][$Host] = array();
@@ -644,6 +651,33 @@ class HttpSocket extends CakeSocket {
 	}
 
 /**
+ * Configure the socket's context.  Adds in configuration
+ * that can not be declared in the class definition.
+ *
+ * @param string $host The host you're connecting to.
+ * @return void
+ */
+	protected function _configContext($host) {
+		foreach ($this->config as $key => $value) {
+			if (substr($key, 0, 4) !== 'ssl_') {
+				continue;
+			}
+			$contextKey = substr($key, 4);
+			if (empty($this->config['context']['ssl'][$contextKey])) {
+				$this->config['context']['ssl'][$contextKey] = $value;
+			}
+			unset($this->config[$key]);
+		}
+		if (empty($this->_context['ssl']['cafile'])) {
+			$this->config['context']['ssl']['cafile'] = CAKE . 'Config' . DS . 'cacert.pem';
+		}
+		if (!empty($this->config['context']['ssl']['verify_host'])) {
+			$this->config['context']['ssl']['CN_match'] = $host;
+			unset($this->config['context']['ssl']['verify_host']);
+		}
+	}
+
+/**
  * Takes a $uri array and turns it into a fully qualified URL string
  *
  * @param string|array $uri Either A $uri array, or a request string. Will use $this->config if left empty.

+ 455 - 0
lib/Cake/Network/Http/HttpSocketResponse.php

@@ -0,0 +1,455 @@
+<?php
+/**
+ * HTTP Response from HttpSocket.
+ *
+ * PHP 5
+ *
+ * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
+ * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ *
+ * Licensed under The MIT License
+ * Redistributions of files must retain the above copyright notice.
+ *
+ * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
+ * @link          http://cakephp.org CakePHP(tm) Project
+ * @since         CakePHP(tm) v 2.0.0
+ * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
+ */
+
+/**
+ * HTTP Response from HttpSocket.
+ *
+ * @package       Cake.Network.Http
+ */
+class HttpSocketResponse implements ArrayAccess {
+
+/**
+ * Body content
+ *
+ * @var string
+ */
+	public $body = '';
+
+/**
+ * Headers
+ *
+ * @var array
+ */
+	public $headers = array();
+
+/**
+ * Cookies
+ *
+ * @var array
+ */
+	public $cookies = array();
+
+/**
+ * HTTP version
+ *
+ * @var string
+ */
+	public $httpVersion = 'HTTP/1.1';
+
+/**
+ * Response code
+ *
+ * @var integer
+ */
+	public $code = 0;
+
+/**
+ * Reason phrase
+ *
+ * @var string
+ */
+	public $reasonPhrase = '';
+
+/**
+ * Pure raw content
+ *
+ * @var string
+ */
+	public $raw = '';
+
+/**
+ * Context data in the response.
+ * Contains SSL certificates for example.
+ *
+ * @var array
+ */
+	public $context = array();
+
+/**
+ * Constructor
+ *
+ * @param string $message
+ */
+	public function __construct($message = null) {
+		if ($message !== null) {
+			$this->parseResponse($message);
+		}
+	}
+
+/**
+ * Body content
+ *
+ * @return string
+ */
+	public function body() {
+		return (string)$this->body;
+	}
+
+/**
+ * Get header in case insensitive
+ *
+ * @param string $name Header name
+ * @param array $headers
+ * @return mixed String if header exists or null
+ */
+	public function getHeader($name, $headers = null) {
+		if (!is_array($headers)) {
+			$headers =& $this->headers;
+		}
+		if (isset($headers[$name])) {
+			return $headers[$name];
+		}
+		foreach ($headers as $key => $value) {
+			if (strcasecmp($key, $name) === 0) {
+				return $value;
+			}
+		}
+		return null;
+	}
+
+/**
+ * If return is 200 (OK)
+ *
+ * @return boolean
+ */
+	public function isOk() {
+		return $this->code == 200;
+	}
+
+/**
+ * If return is a valid 3xx (Redirection)
+ *
+ * @return boolean
+ */
+	public function isRedirect() {
+		return in_array($this->code, array(301, 302, 303, 307)) && !is_null($this->getHeader('Location'));
+	}
+
+/**
+ * Parses the given message and breaks it down in parts.
+ *
+ * @param string $message Message to parse
+ * @return void
+ * @throws SocketException
+ */
+	public function parseResponse($message) {
+		if (!is_string($message)) {
+			throw new SocketException(__d('cake_dev', 'Invalid response.'));
+		}
+
+		if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
+			throw new SocketException(__d('cake_dev', 'Invalid HTTP response.'));
+		}
+
+		list(, $statusLine, $header) = $match;
+		$this->raw = $message;
+		$this->body = (string)substr($message, strlen($match[0]));
+
+		if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $statusLine, $match)) {
+			$this->httpVersion = $match[1];
+			$this->code = $match[2];
+			$this->reasonPhrase = $match[3];
+		}
+
+		$this->headers = $this->_parseHeader($header);
+		$transferEncoding = $this->getHeader('Transfer-Encoding');
+		$decoded = $this->_decodeBody($this->body, $transferEncoding);
+		$this->body = $decoded['body'];
+
+		if (!empty($decoded['header'])) {
+			$this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header']));
+		}
+
+		if (!empty($this->headers)) {
+			$this->cookies = $this->parseCookies($this->headers);
+		}
+	}
+
+/**
+ * Generic function to decode a $body with a given $encoding. Returns either an array with the keys
+ * 'body' and 'header' or false on failure.
+ *
+ * @param string $body A string containing the body to decode.
+ * @param string|boolean $encoding Can be false in case no encoding is being used, or a string representing the encoding.
+ * @return mixed Array of response headers and body or false.
+ */
+	protected function _decodeBody($body, $encoding = 'chunked') {
+		if (!is_string($body)) {
+			return false;
+		}
+		if (empty($encoding)) {
+			return array('body' => $body, 'header' => false);
+		}
+		$decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body';
+
+		if (!is_callable(array(&$this, $decodeMethod))) {
+			return array('body' => $body, 'header' => false);
+		}
+		return $this->{$decodeMethod}($body);
+	}
+
+/**
+ * Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
+ * a result.
+ *
+ * @param string $body A string containing the chunked body to decode.
+ * @return mixed Array of response headers and body or false.
+ * @throws SocketException
+ */
+	protected function _decodeChunkedBody($body) {
+		if (!is_string($body)) {
+			return false;
+		}
+
+		$decodedBody = null;
+		$chunkLength = null;
+
+		while ($chunkLength !== 0) {
+			if (!preg_match('/^([0-9a-f]+) *(?:;(.+)=(.+))?(?:\r\n|\n)/iU', $body, $match)) {
+				throw new SocketException(__d('cake_dev', 'HttpSocket::_decodeChunkedBody - Could not parse malformed chunk.'));
+			}
+
+			$chunkSize = 0;
+			$hexLength = 0;
+			$chunkExtensionName = '';
+			$chunkExtensionValue = '';
+			if (isset($match[0])) {
+				$chunkSize = $match[0];
+			}
+			if (isset($match[1])) {
+				$hexLength = $match[1];
+			}
+			if (isset($match[2])) {
+				$chunkExtensionName = $match[2];
+			}
+			if (isset($match[3])) {
+				$chunkExtensionValue = $match[3];
+			}
+
+			$body = substr($body, strlen($chunkSize));
+			$chunkLength = hexdec($hexLength);
+			$chunk = substr($body, 0, $chunkLength);
+			if (!empty($chunkExtensionName)) {
+				 // @todo See if there are popular chunk extensions we should implement
+			}
+			$decodedBody .= $chunk;
+			if ($chunkLength !== 0) {
+				$body = substr($body, $chunkLength + strlen("\r\n"));
+			}
+		}
+
+		$entityHeader = false;
+		if (!empty($body)) {
+			$entityHeader = $this->_parseHeader($body);
+		}
+		return array('body' => $decodedBody, 'header' => $entityHeader);
+	}
+
+/**
+ * Parses an array based header.
+ *
+ * @param array $header Header as an indexed array (field => value)
+ * @return array Parsed header
+ */
+	protected function _parseHeader($header) {
+		if (is_array($header)) {
+			return $header;
+		} elseif (!is_string($header)) {
+			return false;
+		}
+
+		preg_match_all("/(.+):(.+)(?:(?<![\t ])\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER);
+
+		$header = array();
+		foreach ($matches as $match) {
+			list(, $field, $value) = $match;
+
+			$value = trim($value);
+			$value = preg_replace("/[\t ]\r\n/", "\r\n", $value);
+
+			$field = $this->_unescapeToken($field);
+
+			if (!isset($header[$field])) {
+				$header[$field] = $value;
+			} else {
+				$header[$field] = array_merge((array)$header[$field], (array)$value);
+			}
+		}
+		return $header;
+	}
+
+/**
+ * Parses cookies in response headers.
+ *
+ * @param array $header Header array containing one ore more 'Set-Cookie' headers.
+ * @return mixed Either false on no cookies, or an array of cookies received.
+ * @todo Make this 100% RFC 2965 confirm
+ */
+	public function parseCookies($header) {
+		$cookieHeader = $this->getHeader('Set-Cookie', $header);
+		if (!$cookieHeader) {
+			return false;
+		}
+
+		$cookies = array();
+		foreach ((array)$cookieHeader as $cookie) {
+			if (strpos($cookie, '";"') !== false) {
+				$cookie = str_replace('";"', "{__cookie_replace__}", $cookie);
+				$parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie));
+			} else {
+				$parts = preg_split('/\;[ \t]*/', $cookie);
+			}
+
+			list($name, $value) = explode('=', array_shift($parts), 2);
+			$cookies[$name] = compact('value');
+
+			foreach ($parts as $part) {
+				if (strpos($part, '=') !== false) {
+					list($key, $value) = explode('=', $part);
+				} else {
+					$key = $part;
+					$value = true;
+				}
+
+				$key = strtolower($key);
+				if (!isset($cookies[$name][$key])) {
+					$cookies[$name][$key] = $value;
+				}
+			}
+		}
+		return $cookies;
+	}
+
+/**
+ * Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
+ *
+ * @param string $token Token to unescape
+ * @param array $chars
+ * @return string Unescaped token
+ * @todo Test $chars parameter
+ */
+	protected function _unescapeToken($token, $chars = null) {
+		$regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/';
+		$token = preg_replace($regex, '\\1', $token);
+		return $token;
+	}
+
+/**
+ * Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
+ *
+ * @param boolean $hex true to get them as HEX values, false otherwise
+ * @param array $chars
+ * @return array Escape chars
+ * @todo Test $chars parameter
+ */
+	protected function _tokenEscapeChars($hex = true, $chars = null) {
+		if (!empty($chars)) {
+			$escape = $chars;
+		} else {
+			$escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
+			for ($i = 0; $i <= 31; $i++) {
+				$escape[] = chr($i);
+			}
+			$escape[] = chr(127);
+		}
+
+		if (!$hex) {
+			return $escape;
+		}
+		foreach ($escape as $key => $char) {
+			$escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
+		}
+		return $escape;
+	}
+
+/**
+ * ArrayAccess - Offset Exists
+ *
+ * @param string $offset
+ * @return boolean
+ */
+	public function offsetExists($offset) {
+		return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies'));
+	}
+
+/**
+ * ArrayAccess - Offset Get
+ *
+ * @param string $offset
+ * @return mixed
+ */
+	public function offsetGet($offset) {
+		switch ($offset) {
+			case 'raw':
+				$firstLineLength = strpos($this->raw, "\r\n") + 2;
+				if ($this->raw[$firstLineLength] === "\r") {
+					$header = null;
+				} else {
+					$header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n";
+				}
+				return array(
+					'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n",
+					'header' => $header,
+					'body' => $this->body,
+					'response' => $this->raw
+				);
+			case 'status':
+				return array(
+					'http-version' => $this->httpVersion,
+					'code' => $this->code,
+					'reason-phrase' => $this->reasonPhrase
+				);
+			case 'header':
+				return $this->headers;
+			case 'body':
+				return $this->body;
+			case 'cookies':
+				return $this->cookies;
+		}
+		return null;
+	}
+
+/**
+ * ArrayAccess - Offset Set
+ *
+ * @param string $offset
+ * @param mixed $value
+ * @return void
+ */
+	public function offsetSet($offset, $value) {
+	}
+
+/**
+ * ArrayAccess - Offset Unset
+ *
+ * @param string $offset
+ * @return void
+ */
+	public function offsetUnset($offset) {
+	}
+
+/**
+ * Instance as string
+ *
+ * @return string
+ */
+	public function __toString() {
+		return $this->body();
+	}
+
+}

+ 21 - 0
lib/Cake/Test/Case/Network/CakeSocketTest.php

@@ -326,4 +326,25 @@ class CakeSocketTest extends CakeTestCase {
 		$this->assertTrue($this->Socket->encrypted);
 	}
 
+/**
+ * test getting the context for a socket.
+ *
+ * @return void
+ */
+	public function testGetContext() {
+		$this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
+		$config = array(
+			'host' => 'smtp.gmail.com',
+			'port' => 465,
+			'timeout' => 5,
+			'context' => array(
+				'ssl' => array('capture_peer' => true)
+			)
+		);
+		$this->Socket = new CakeSocket($config);
+		$this->Socket->connect();
+		$result = $this->Socket->context();
+		$this->assertEquals($config['context'], $result);
+	}
+
 }

+ 52 - 2
lib/Cake/Test/Case/Network/Http/HttpSocketTest.php

@@ -253,6 +253,9 @@ class HttpSocketTest extends CakeTestCase {
 			'protocol' => 'tcp',
 			'port' => 23,
 			'timeout' => 30,
+			'ssl_verify_peer' => true,
+			'ssl_verify_depth' => 5,
+			'ssl_verify_host' => true,
 			'request' => array(
 				'uri' => array(
 					'scheme' => 'https',
@@ -260,7 +263,7 @@ class HttpSocketTest extends CakeTestCase {
 					'port' => 23
 				),
 				'redirect' => false,
-				'cookies' => array()
+				'cookies' => array(),
 			)
 		);
 		$this->assertEquals($expected, $this->Socket->config);
@@ -278,6 +281,9 @@ class HttpSocketTest extends CakeTestCase {
 			'protocol' => 'tcp',
 			'port' => 80,
 			'timeout' => 30,
+			'ssl_verify_peer' => true,
+			'ssl_verify_depth' => 5,
+			'ssl_verify_host' => true,
 			'request' => array(
 				'uri' => array(
 					'scheme' => 'http',
@@ -285,7 +291,7 @@ class HttpSocketTest extends CakeTestCase {
 					'port' => 80
 				),
 				'redirect' => false,
-				'cookies' => array()
+				'cookies' => array(),
 			)
 		);
 		$this->assertEquals($expected, $this->Socket->config);
@@ -311,6 +317,15 @@ class HttpSocketTest extends CakeTestCase {
 		$response = $this->Socket->request(true);
 		$this->assertFalse($response);
 
+		$context = array(
+			'ssl' => array(
+				'verify_peer' => true,
+				'verify_depth' => 5,
+				'CN_match' => 'www.cakephp.org',
+				'cafile' => CAKE . 'Config' . DS . 'cacert.pem'
+			)
+		);
+
 		$tests = array(
 			array(
 				'request' => 'http://www.cakephp.org/?foo=bar',
@@ -321,6 +336,7 @@ class HttpSocketTest extends CakeTestCase {
 						'protocol' => 'tcp',
 						'port' => 80,
 						'timeout' => 30,
+						'context' => $context,
 						'request' => array(
 							'uri' => array(
 								'scheme' => 'http',
@@ -1668,4 +1684,38 @@ class HttpSocketTest extends CakeTestCase {
 		}
 		$this->assertEquals(true, $return);
 	}
+
+/**
+ * test configuring the context from the flat keys.
+ *
+ * @return void
+ */
+	public function testConfigContext() {
+		$this->Socket->reset();
+		$this->Socket->request('http://example.com');
+		$this->assertTrue($this->Socket->config['context']['ssl']['verify_peer']);
+		$this->assertEquals(5, $this->Socket->config['context']['ssl']['verify_depth']);
+		$this->assertEquals('example.com', $this->Socket->config['context']['ssl']['CN_match']);
+		$this->assertArrayNotHasKey('ssl_verify_peer', $this->Socket->config);
+		$this->assertArrayNotHasKey('ssl_verify_host', $this->Socket->config);
+		$this->assertArrayNotHasKey('ssl_verify_depth', $this->Socket->config);
+	}
+
+/**
+ * Test that requests fail when peer verification fails.
+ *
+ * @return void
+ */
+	public function testVerifyPeer() {
+		$this->skipIf(!extension_loaded('openssl'), 'OpenSSL is not enabled cannot test SSL.');
+		$socket = new HttpSocket();
+		try {
+			$result = $socket->get('https://typography.com');
+			$this->markTestSkipped('Found valid certificate, was expecting invalid certificate.');
+		} catch (SocketException $e) {
+			$message = $e->getMessage();
+			$this->assertContains('Peer certificate CN', $message);
+			$this->assertContains('Failed to enable crypto', $message);
+		}
+	}
 }

+ 1 - 1
lib/Cake/Test/Case/Utility/FolderTest.php

@@ -640,7 +640,7 @@ class FolderTest extends CakeTestCase {
 		$this->assertSame(array_diff($expected, $result), array());
 
 		$result = $Folder->find('.*', true);
-		$expected = array('config.php', 'routes.php');
+		$expected = array('cacert.pem', 'config.php', 'routes.php');
 		$this->assertSame($expected, $result);
 
 		$result = $Folder->find('.*\.php');