Socket.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Http
  17. * @subpackage Client_Adapter
  18. * @version $Id$
  19. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  20. * @license http://framework.zend.com/license/new-bsd New BSD License
  21. */
  22. /**
  23. * @see Zend_Uri_Http
  24. */
  25. require_once 'Zend/Uri/Http.php';
  26. /**
  27. * @see Zend_Http_Client_Adapter_Interface
  28. */
  29. require_once 'Zend/Http/Client/Adapter/Interface.php';
  30. /**
  31. * A sockets based (stream_socket_client) adapter class for Zend_Http_Client. Can be used
  32. * on almost every PHP environment, and does not require any special extensions.
  33. *
  34. * @category Zend
  35. * @package Zend_Http
  36. * @subpackage Client_Adapter
  37. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  38. * @license http://framework.zend.com/license/new-bsd New BSD License
  39. */
  40. class Zend_Http_Client_Adapter_Socket implements Zend_Http_Client_Adapter_Interface
  41. {
  42. /**
  43. * The socket for server connection
  44. *
  45. * @var resource|null
  46. */
  47. protected $socket = null;
  48. /**
  49. * What host/port are we connected to?
  50. *
  51. * @var array
  52. */
  53. protected $connected_to = array(null, null);
  54. /**
  55. * Parameters array
  56. *
  57. * @var array
  58. */
  59. protected $config = array(
  60. 'persistent' => false,
  61. 'ssltransport' => 'ssl',
  62. 'sslcert' => null,
  63. 'sslpassphrase' => null
  64. );
  65. /**
  66. * Request method - will be set by write() and might be used by read()
  67. *
  68. * @var string
  69. */
  70. protected $method = null;
  71. /**
  72. * Stream context
  73. *
  74. * @var resource
  75. */
  76. protected $_context = null;
  77. /**
  78. * Adapter constructor, currently empty. Config is set using setConfig()
  79. *
  80. */
  81. public function __construct()
  82. {
  83. }
  84. /**
  85. * Set the configuration array for the adapter
  86. *
  87. * @param array $config
  88. */
  89. public function setConfig($config = array())
  90. {
  91. if (! is_array($config)) {
  92. require_once 'Zend/Http/Client/Adapter/Exception.php';
  93. throw new Zend_Http_Client_Adapter_Exception(
  94. '$concig expects an array, ' . gettype($config) . ' recieved.');
  95. }
  96. foreach ($config as $k => $v) {
  97. $this->config[strtolower($k)] = $v;
  98. }
  99. }
  100. /**
  101. * Set the stream context for the TCP connection to the server
  102. *
  103. * Can accept either a pre-existing stream context resource, or an array
  104. * of stream options, similar to the options array passed to the
  105. * stream_context_create() PHP function. In such case a new stream context
  106. * will be created using the passed options.
  107. *
  108. * @since Zend Framework 1.9
  109. *
  110. * @param mixed $context Stream context or array of context options
  111. * @return Zend_Http_Client_Adapter_Socket
  112. */
  113. public function setStreamContext($context)
  114. {
  115. if (is_resource($context) && get_resource_type($context) == 'stream-context') {
  116. $this->_context = $context;
  117. } elseif (is_array($context)) {
  118. $this->_context = stream_context_create($context);
  119. } else {
  120. // Invalid parameter
  121. require_once 'Zend/Http/Client/Adapter/Exception.php';
  122. throw new Zend_Http_Client_Adapter_Exception(
  123. "Expecting either a stream context resource or array, got " . gettype($context)
  124. );
  125. }
  126. return $this;
  127. }
  128. /**
  129. * Get the stream context for the TCP connection to the server.
  130. *
  131. * If no stream context is set, will create a default one.
  132. *
  133. * @return resource
  134. */
  135. public function getStreamContext()
  136. {
  137. if (! $this->_context) {
  138. $this->_context = stream_context_create();
  139. }
  140. return $this->_context;
  141. }
  142. /**
  143. * Connect to the remote server
  144. *
  145. * @param string $host
  146. * @param int $port
  147. * @param boolean $secure
  148. * @param int $timeout
  149. */
  150. public function connect($host, $port = 80, $secure = false)
  151. {
  152. // If the URI should be accessed via SSL, prepend the Hostname with ssl://
  153. $host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  154. // If we are connected to the wrong host, disconnect first
  155. if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
  156. if (is_resource($this->socket)) $this->close();
  157. }
  158. // Now, if we are not connected, connect
  159. if (! is_resource($this->socket) || ! $this->config['keepalive']) {
  160. $context = $this->getStreamContext();
  161. if ($secure) {
  162. if ($this->config['sslcert'] !== null) {
  163. if (! stream_context_set_option($context, 'ssl', 'local_cert',
  164. $this->config['sslcert'])) {
  165. require_once 'Zend/Http/Client/Adapter/Exception.php';
  166. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option');
  167. }
  168. }
  169. if ($this->config['sslpassphrase'] !== null) {
  170. if (! stream_context_set_option($context, 'ssl', 'passphrase',
  171. $this->config['sslpassphrase'])) {
  172. require_once 'Zend/Http/Client/Adapter/Exception.php';
  173. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option');
  174. }
  175. }
  176. }
  177. $flags = STREAM_CLIENT_CONNECT;
  178. if ($this->config['persistent']) $flags |= STREAM_CLIENT_PERSISTENT;
  179. $this->socket = @stream_socket_client($host . ':' . $port,
  180. $errno,
  181. $errstr,
  182. (int) $this->config['timeout'],
  183. $flags,
  184. $context);
  185. if (! $this->socket) {
  186. $this->close();
  187. require_once 'Zend/Http/Client/Adapter/Exception.php';
  188. throw new Zend_Http_Client_Adapter_Exception(
  189. 'Unable to Connect to ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr);
  190. }
  191. // Set the stream timeout
  192. if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
  193. require_once 'Zend/Http/Client/Adapter/Exception.php';
  194. throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
  195. }
  196. // Update connected_to
  197. $this->connected_to = array($host, $port);
  198. }
  199. }
  200. /**
  201. * Send request to the remote server
  202. *
  203. * @param string $method
  204. * @param Zend_Uri_Http $uri
  205. * @param string $http_ver
  206. * @param array $headers
  207. * @param string $body
  208. * @return string Request as string
  209. */
  210. public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
  211. {
  212. // Make sure we're properly connected
  213. if (! $this->socket) {
  214. require_once 'Zend/Http/Client/Adapter/Exception.php';
  215. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are not connected');
  216. }
  217. $host = $uri->getHost();
  218. $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  219. if ($this->connected_to[0] != $host || $this->connected_to[1] != $uri->getPort()) {
  220. require_once 'Zend/Http/Client/Adapter/Exception.php';
  221. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are connected to the wrong host');
  222. }
  223. // Save request method for later
  224. $this->method = $method;
  225. // Build request headers
  226. $path = $uri->getPath();
  227. if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
  228. $request = "{$method} {$path} HTTP/{$http_ver}\r\n";
  229. foreach ($headers as $k => $v) {
  230. if (is_string($k)) $v = ucfirst($k) . ": $v";
  231. $request .= "$v\r\n";
  232. }
  233. // Add the request body
  234. $request .= "\r\n" . $body;
  235. // Send the request
  236. if (! @fwrite($this->socket, $request)) {
  237. require_once 'Zend/Http/Client/Adapter/Exception.php';
  238. throw new Zend_Http_Client_Adapter_Exception('Error writing request to server');
  239. }
  240. return $request;
  241. }
  242. /**
  243. * Read response from server
  244. *
  245. * @return string
  246. */
  247. public function read()
  248. {
  249. // First, read headers only
  250. $response = '';
  251. $gotStatus = false;
  252. while (($line = @fgets($this->socket)) !== false) {
  253. $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
  254. if ($gotStatus) {
  255. $response .= $line;
  256. if (rtrim($line) === '') break;
  257. }
  258. }
  259. $statusCode = Zend_Http_Response::extractCode($response);
  260. // Handle 100 and 101 responses internally by restarting the read again
  261. if ($statusCode == 100 || $statusCode == 101) return $this->read();
  262. /**
  263. * Responses to HEAD requests and 204 or 304 responses are not expected
  264. * to have a body - stop reading here
  265. */
  266. if ($statusCode == 304 || $statusCode == 204 ||
  267. $this->method == Zend_Http_Client::HEAD) return $response;
  268. // Check headers to see what kind of connection / transfer encoding we have
  269. $headers = Zend_Http_Response::extractHeaders($response);
  270. // If we got a 'transfer-encoding: chunked' header
  271. if (isset($headers['transfer-encoding'])) {
  272. if ($headers['transfer-encoding'] == 'chunked') {
  273. do {
  274. $line = @fgets($this->socket);
  275. $chunk = $line;
  276. // Figure out the next chunk size
  277. $chunksize = trim($line);
  278. if (! ctype_xdigit($chunksize)) {
  279. $this->close();
  280. require_once 'Zend/Http/Client/Adapter/Exception.php';
  281. throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' .
  282. $chunksize . '" unable to read chunked body');
  283. }
  284. // Convert the hexadecimal value to plain integer
  285. $chunksize = hexdec($chunksize);
  286. // Read chunk
  287. $left_to_read = $chunksize;
  288. while ($left_to_read > 0) {
  289. $line = @fread($this->socket, $left_to_read);
  290. if ($line === false || strlen($line) === 0)
  291. {
  292. break;
  293. } else {
  294. $chunk .= $line;
  295. $left_to_read -= strlen($line);
  296. }
  297. // Break if the connection ended prematurely
  298. if (feof($this->socket)) break;
  299. }
  300. $chunk .= @fgets($this->socket);
  301. $response .= $chunk;
  302. } while ($chunksize > 0);
  303. } else {
  304. throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' .
  305. $headers['transfer-encoding'] . '" transfer encoding');
  306. }
  307. // Else, if we got the content-length header, read this number of bytes
  308. } elseif (isset($headers['content-length'])) {
  309. $left_to_read = $headers['content-length'];
  310. $chunk = '';
  311. while ($left_to_read > 0) {
  312. $chunk = @fread($this->socket, $left_to_read);
  313. if ($chunk === false || strlen($chunk) === 0)
  314. {
  315. break;
  316. } else {
  317. $left_to_read -= strlen($chunk);
  318. $response .= $chunk;
  319. }
  320. // Break if the connection ended prematurely
  321. if (feof($this->socket)) break;
  322. }
  323. // Fallback: just read the response until EOF
  324. } else {
  325. do {
  326. $buff = @fread($this->socket, 8192);
  327. if ($buff === false || strlen($buff) === 0)
  328. {
  329. break;
  330. } else {
  331. $response .= $buff;
  332. }
  333. } while (feof($this->socket) === false);
  334. $this->close();
  335. }
  336. // Close the connection if requested to do so by the server
  337. if (isset($headers['connection']) && $headers['connection'] == 'close') {
  338. $this->close();
  339. }
  340. return $response;
  341. }
  342. /**
  343. * Close the connection to the server
  344. *
  345. */
  346. public function close()
  347. {
  348. if (is_resource($this->socket)) @fclose($this->socket);
  349. $this->socket = null;
  350. $this->connected_to = array(null, null);
  351. }
  352. /**
  353. * Destructor: make sure the socket is disconnected
  354. *
  355. * If we are in persistent TCP mode, will not close the connection
  356. *
  357. */
  358. public function __destruct()
  359. {
  360. if (! $this->config['persistent']) {
  361. if ($this->socket) $this->close();
  362. }
  363. }
  364. }