Socket.php 15 KB

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