Socket.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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 Zend_Config | array $config
  88. */
  89. public function setConfig($config = array())
  90. {
  91. if ($config instanceof Zend_Config) {
  92. $config = $config->toArray();
  93. } elseif (! is_array($config)) {
  94. require_once 'Zend/Http/Client/Adapter/Exception.php';
  95. throw new Zend_Http_Client_Adapter_Exception(
  96. 'Array or Zend_Config object expected, got ' . gettype($config)
  97. );
  98. }
  99. foreach ($config as $k => $v) {
  100. $this->config[strtolower($k)] = $v;
  101. }
  102. }
  103. /**
  104. * Retrieve the array of all configuration options
  105. *
  106. * @return array
  107. */
  108. public function getConfig()
  109. {
  110. return $this->config;
  111. }
  112. /**
  113. * Set the stream context for the TCP connection to the server
  114. *
  115. * Can accept either a pre-existing stream context resource, or an array
  116. * of stream options, similar to the options array passed to the
  117. * stream_context_create() PHP function. In such case a new stream context
  118. * will be created using the passed options.
  119. *
  120. * @since Zend Framework 1.9
  121. *
  122. * @param mixed $context Stream context or array of context options
  123. * @return Zend_Http_Client_Adapter_Socket
  124. */
  125. public function setStreamContext($context)
  126. {
  127. if (is_resource($context) && get_resource_type($context) == 'stream-context') {
  128. $this->_context = $context;
  129. } elseif (is_array($context)) {
  130. $this->_context = stream_context_create($context);
  131. } else {
  132. // Invalid parameter
  133. require_once 'Zend/Http/Client/Adapter/Exception.php';
  134. throw new Zend_Http_Client_Adapter_Exception(
  135. "Expecting either a stream context resource or array, got " . gettype($context)
  136. );
  137. }
  138. return $this;
  139. }
  140. /**
  141. * Get the stream context for the TCP connection to the server.
  142. *
  143. * If no stream context is set, will create a default one.
  144. *
  145. * @return resource
  146. */
  147. public function getStreamContext()
  148. {
  149. if (! $this->_context) {
  150. $this->_context = stream_context_create();
  151. }
  152. return $this->_context;
  153. }
  154. /**
  155. * Connect to the remote server
  156. *
  157. * @param string $host
  158. * @param int $port
  159. * @param boolean $secure
  160. */
  161. public function connect($host, $port = 80, $secure = false)
  162. {
  163. // If the URI should be accessed via SSL, prepend the Hostname with ssl://
  164. $host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  165. // If we are connected to the wrong host, disconnect first
  166. if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
  167. if (is_resource($this->socket)) $this->close();
  168. }
  169. // Now, if we are not connected, connect
  170. if (! is_resource($this->socket) || ! $this->config['keepalive']) {
  171. $context = $this->getStreamContext();
  172. if ($secure) {
  173. if ($this->config['sslcert'] !== null) {
  174. if (! stream_context_set_option($context, 'ssl', 'local_cert',
  175. $this->config['sslcert'])) {
  176. require_once 'Zend/Http/Client/Adapter/Exception.php';
  177. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option');
  178. }
  179. }
  180. if ($this->config['sslpassphrase'] !== null) {
  181. if (! stream_context_set_option($context, 'ssl', 'passphrase',
  182. $this->config['sslpassphrase'])) {
  183. require_once 'Zend/Http/Client/Adapter/Exception.php';
  184. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option');
  185. }
  186. }
  187. }
  188. $flags = STREAM_CLIENT_CONNECT;
  189. if ($this->config['persistent']) $flags |= STREAM_CLIENT_PERSISTENT;
  190. $this->socket = @stream_socket_client($host . ':' . $port,
  191. $errno,
  192. $errstr,
  193. (int) $this->config['timeout'],
  194. $flags,
  195. $context);
  196. if (! $this->socket) {
  197. $this->close();
  198. require_once 'Zend/Http/Client/Adapter/Exception.php';
  199. throw new Zend_Http_Client_Adapter_Exception(
  200. 'Unable to Connect to ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr);
  201. }
  202. // Set the stream timeout
  203. if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
  204. require_once 'Zend/Http/Client/Adapter/Exception.php';
  205. throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
  206. }
  207. // Update connected_to
  208. $this->connected_to = array($host, $port);
  209. }
  210. }
  211. /**
  212. * Send request to the remote server
  213. *
  214. * @param string $method
  215. * @param Zend_Uri_Http $uri
  216. * @param string $http_ver
  217. * @param array $headers
  218. * @param string $body
  219. * @return string Request as string
  220. */
  221. public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
  222. {
  223. // Make sure we're properly connected
  224. if (! $this->socket) {
  225. require_once 'Zend/Http/Client/Adapter/Exception.php';
  226. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are not connected');
  227. }
  228. $host = $uri->getHost();
  229. $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  230. if ($this->connected_to[0] != $host || $this->connected_to[1] != $uri->getPort()) {
  231. require_once 'Zend/Http/Client/Adapter/Exception.php';
  232. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are connected to the wrong host');
  233. }
  234. // Save request method for later
  235. $this->method = $method;
  236. // Build request headers
  237. $path = $uri->getPath();
  238. if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
  239. $request = "{$method} {$path} HTTP/{$http_ver}\r\n";
  240. foreach ($headers as $k => $v) {
  241. if (is_string($k)) $v = ucfirst($k) . ": $v";
  242. $request .= "$v\r\n";
  243. }
  244. // Add the request body
  245. $request .= "\r\n" . $body;
  246. // Send the request
  247. if (! @fwrite($this->socket, $request)) {
  248. require_once 'Zend/Http/Client/Adapter/Exception.php';
  249. throw new Zend_Http_Client_Adapter_Exception('Error writing request to server');
  250. }
  251. return $request;
  252. }
  253. /**
  254. * Read response from server
  255. *
  256. * @return string
  257. */
  258. public function read()
  259. {
  260. // First, read headers only
  261. $response = '';
  262. $gotStatus = false;
  263. while (($line = @fgets($this->socket)) !== false) {
  264. $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
  265. if ($gotStatus) {
  266. $response .= $line;
  267. if (rtrim($line) === '') break;
  268. }
  269. }
  270. $this->_checkSocketReadTimeout();
  271. $statusCode = Zend_Http_Response::extractCode($response);
  272. // Handle 100 and 101 responses internally by restarting the read again
  273. if ($statusCode == 100 || $statusCode == 101) return $this->read();
  274. // Check headers to see what kind of connection / transfer encoding we have
  275. $headers = Zend_Http_Response::extractHeaders($response);
  276. /**
  277. * Responses to HEAD requests and 204 or 304 responses are not expected
  278. * to have a body - stop reading here
  279. */
  280. if ($statusCode == 304 || $statusCode == 204 ||
  281. $this->method == Zend_Http_Client::HEAD) {
  282. // Close the connection if requested to do so by the server
  283. if (isset($headers['connection']) && $headers['connection'] == 'close') {
  284. $this->close();
  285. }
  286. return $response;
  287. }
  288. // If we got a 'transfer-encoding: chunked' header
  289. if (isset($headers['transfer-encoding'])) {
  290. if (strtolower($headers['transfer-encoding']) == 'chunked') {
  291. do {
  292. $line = @fgets($this->socket);
  293. $this->_checkSocketReadTimeout();
  294. $chunk = $line;
  295. // Figure out the next chunk size
  296. $chunksize = trim($line);
  297. if (! ctype_xdigit($chunksize)) {
  298. $this->close();
  299. require_once 'Zend/Http/Client/Adapter/Exception.php';
  300. throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' .
  301. $chunksize . '" unable to read chunked body');
  302. }
  303. // Convert the hexadecimal value to plain integer
  304. $chunksize = hexdec($chunksize);
  305. // Read next chunk
  306. $read_to = ftell($this->socket) + $chunksize;
  307. do {
  308. $current_pos = ftell($this->socket);
  309. if ($current_pos >= $read_to) break;
  310. $line = @fread($this->socket, $read_to - $current_pos);
  311. if ($line === false || strlen($line) === 0) {
  312. $this->_checkSocketReadTimeout();
  313. break;
  314. } else {
  315. $chunk .= $line;
  316. }
  317. } while (! feof($this->socket));
  318. $chunk .= @fgets($this->socket);
  319. $this->_checkSocketReadTimeout();
  320. $response .= $chunk;
  321. } while ($chunksize > 0);
  322. } else {
  323. $this->close();
  324. throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' .
  325. $headers['transfer-encoding'] . '" transfer encoding');
  326. }
  327. // Else, if we got the content-length header, read this number of bytes
  328. } elseif (isset($headers['content-length'])) {
  329. $current_pos = ftell($this->socket);
  330. $chunk = '';
  331. for ($read_to = $current_pos + $headers['content-length'];
  332. $read_to > $current_pos;
  333. $current_pos = ftell($this->socket)) {
  334. $chunk = @fread($this->socket, $read_to - $current_pos);
  335. if ($chunk === false || strlen($chunk) === 0) {
  336. $this->_checkSocketReadTimeout();
  337. break;
  338. }
  339. $response .= $chunk;
  340. // Break if the connection ended prematurely
  341. if (feof($this->socket)) break;
  342. }
  343. // Fallback: just read the response until EOF
  344. } else {
  345. do {
  346. $buff = @fread($this->socket, 8192);
  347. if ($buff === false || strlen($buff) === 0) {
  348. $this->_checkSocketReadTimeout();
  349. break;
  350. } else {
  351. $response .= $buff;
  352. }
  353. } while (feof($this->socket) === false);
  354. $this->close();
  355. }
  356. // Close the connection if requested to do so by the server
  357. if (isset($headers['connection']) && $headers['connection'] == 'close') {
  358. $this->close();
  359. }
  360. return $response;
  361. }
  362. /**
  363. * Close the connection to the server
  364. *
  365. */
  366. public function close()
  367. {
  368. if (is_resource($this->socket)) @fclose($this->socket);
  369. $this->socket = null;
  370. $this->connected_to = array(null, null);
  371. }
  372. /**
  373. * Check if the socket has timed out - if so close connection and throw
  374. * an exception
  375. *
  376. * @throws Zend_Http_Client_Adapter_Exception with READ_TIMEOUT code
  377. */
  378. protected function _checkSocketReadTimeout()
  379. {
  380. if ($this->socket) {
  381. $info = stream_get_meta_data($this->socket);
  382. $timedout = $info['timed_out'];
  383. if ($timedout) {
  384. $this->close();
  385. require_once 'Zend/Http/Client/Adapter/Exception.php';
  386. throw new Zend_Http_Client_Adapter_Exception(
  387. "Read timed out after {$this->config['timeout']} seconds",
  388. Zend_Http_Client_Adapter_Exception::READ_TIMEOUT
  389. );
  390. }
  391. }
  392. }
  393. /**
  394. * Destructor: make sure the socket is disconnected
  395. *
  396. * If we are in persistent TCP mode, will not close the connection
  397. *
  398. */
  399. public function __destruct()
  400. {
  401. if (! $this->config['persistent']) {
  402. if ($this->socket) $this->close();
  403. }
  404. }
  405. }