Socket.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. * @see Zend_Http_Client_Adapter_Stream
  32. */
  33. require_once 'Zend/Http/Client/Adapter/Stream.php';
  34. /**
  35. * A sockets based (stream_socket_client) adapter class for Zend_Http_Client. Can be used
  36. * on almost every PHP environment, and does not require any special extensions.
  37. *
  38. * @category Zend
  39. * @package Zend_Http
  40. * @subpackage Client_Adapter
  41. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  42. * @license http://framework.zend.com/license/new-bsd New BSD License
  43. */
  44. class Zend_Http_Client_Adapter_Socket implements Zend_Http_Client_Adapter_Interface, Zend_Http_Client_Adapter_Stream
  45. {
  46. /**
  47. * The socket for server connection
  48. *
  49. * @var resource|null
  50. */
  51. protected $socket = null;
  52. /**
  53. * What host/port are we connected to?
  54. *
  55. * @var array
  56. */
  57. protected $connected_to = array(null, null);
  58. /**
  59. * Stream for storing output
  60. *
  61. * @var resource
  62. */
  63. protected $out_stream = null;
  64. /**
  65. * Parameters array
  66. *
  67. * @var array
  68. */
  69. protected $config = array(
  70. 'persistent' => false,
  71. 'ssltransport' => 'ssl',
  72. 'sslcert' => null,
  73. 'sslpassphrase' => null
  74. );
  75. /**
  76. * Request method - will be set by write() and might be used by read()
  77. *
  78. * @var string
  79. */
  80. protected $method = null;
  81. /**
  82. * Stream context
  83. *
  84. * @var resource
  85. */
  86. protected $_context = null;
  87. /**
  88. * Adapter constructor, currently empty. Config is set using setConfig()
  89. *
  90. */
  91. public function __construct()
  92. {
  93. }
  94. /**
  95. * Set the configuration array for the adapter
  96. *
  97. * @param Zend_Config | array $config
  98. */
  99. public function setConfig($config = array())
  100. {
  101. if ($config instanceof Zend_Config) {
  102. $config = $config->toArray();
  103. } elseif (! is_array($config)) {
  104. require_once 'Zend/Http/Client/Adapter/Exception.php';
  105. throw new Zend_Http_Client_Adapter_Exception(
  106. 'Array or Zend_Config object expected, got ' . gettype($config)
  107. );
  108. }
  109. foreach ($config as $k => $v) {
  110. $this->config[strtolower($k)] = $v;
  111. }
  112. }
  113. /**
  114. * Set the stream context for the TCP connection to the server
  115. *
  116. * Can accept either a pre-existing stream context resource, or an array
  117. * of stream options, similar to the options array passed to the
  118. * stream_context_create() PHP function. In such case a new stream context
  119. * will be created using the passed options.
  120. *
  121. * @since Zend Framework 1.9
  122. *
  123. * @param mixed $context Stream context or array of context options
  124. * @return Zend_Http_Client_Adapter_Socket
  125. */
  126. public function setStreamContext($context)
  127. {
  128. if (is_resource($context) && get_resource_type($context) == 'stream-context') {
  129. $this->_context = $context;
  130. } elseif (is_array($context)) {
  131. $this->_context = stream_context_create($context);
  132. } else {
  133. // Invalid parameter
  134. require_once 'Zend/Http/Client/Adapter/Exception.php';
  135. throw new Zend_Http_Client_Adapter_Exception(
  136. "Expecting either a stream context resource or array, got " . gettype($context)
  137. );
  138. }
  139. return $this;
  140. }
  141. /**
  142. * Get the stream context for the TCP connection to the server.
  143. *
  144. * If no stream context is set, will create a default one.
  145. *
  146. * @return resource
  147. */
  148. public function getStreamContext()
  149. {
  150. if (! $this->_context) {
  151. $this->_context = stream_context_create();
  152. }
  153. return $this->_context;
  154. }
  155. /**
  156. * Connect to the remote server
  157. *
  158. * @param string $host
  159. * @param int $port
  160. * @param boolean $secure
  161. */
  162. public function connect($host, $port = 80, $secure = false)
  163. {
  164. // If the URI should be accessed via SSL, prepend the Hostname with ssl://
  165. $host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  166. // If we are connected to the wrong host, disconnect first
  167. if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
  168. if (is_resource($this->socket)) $this->close();
  169. }
  170. // Now, if we are not connected, connect
  171. if (! is_resource($this->socket) || ! $this->config['keepalive']) {
  172. $context = $this->getStreamContext();
  173. if ($secure) {
  174. if ($this->config['sslcert'] !== null) {
  175. if (! stream_context_set_option($context, 'ssl', 'local_cert',
  176. $this->config['sslcert'])) {
  177. require_once 'Zend/Http/Client/Adapter/Exception.php';
  178. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option');
  179. }
  180. }
  181. if ($this->config['sslpassphrase'] !== null) {
  182. if (! stream_context_set_option($context, 'ssl', 'passphrase',
  183. $this->config['sslpassphrase'])) {
  184. require_once 'Zend/Http/Client/Adapter/Exception.php';
  185. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option');
  186. }
  187. }
  188. }
  189. $flags = STREAM_CLIENT_CONNECT;
  190. if ($this->config['persistent']) $flags |= STREAM_CLIENT_PERSISTENT;
  191. $this->socket = @stream_socket_client($host . ':' . $port,
  192. $errno,
  193. $errstr,
  194. (int) $this->config['timeout'],
  195. $flags,
  196. $context);
  197. if (! $this->socket) {
  198. $this->close();
  199. require_once 'Zend/Http/Client/Adapter/Exception.php';
  200. throw new Zend_Http_Client_Adapter_Exception(
  201. 'Unable to Connect to ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr);
  202. }
  203. // Set the stream timeout
  204. if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
  205. require_once 'Zend/Http/Client/Adapter/Exception.php';
  206. throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
  207. }
  208. // Update connected_to
  209. $this->connected_to = array($host, $port);
  210. }
  211. }
  212. /**
  213. * Send request to the remote server
  214. *
  215. * @param string $method
  216. * @param Zend_Uri_Http $uri
  217. * @param string $http_ver
  218. * @param array $headers
  219. * @param string $body
  220. * @return string Request as string
  221. */
  222. public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
  223. {
  224. // Make sure we're properly connected
  225. if (! $this->socket) {
  226. require_once 'Zend/Http/Client/Adapter/Exception.php';
  227. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are not connected');
  228. }
  229. $host = $uri->getHost();
  230. $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  231. if ($this->connected_to[0] != $host || $this->connected_to[1] != $uri->getPort()) {
  232. require_once 'Zend/Http/Client/Adapter/Exception.php';
  233. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are connected to the wrong host');
  234. }
  235. // Save request method for later
  236. $this->method = $method;
  237. // Build request headers
  238. $path = $uri->getPath();
  239. if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
  240. $request = "{$method} {$path} HTTP/{$http_ver}\r\n";
  241. foreach ($headers as $k => $v) {
  242. if (is_string($k)) $v = ucfirst($k) . ": $v";
  243. $request .= "$v\r\n";
  244. }
  245. if(is_resource($body)) {
  246. $request .= "\r\n";
  247. } else {
  248. // Add the request body
  249. $request .= "\r\n" . $body;
  250. }
  251. // Send the request
  252. if (! @fwrite($this->socket, $request)) {
  253. require_once 'Zend/Http/Client/Adapter/Exception.php';
  254. throw new Zend_Http_Client_Adapter_Exception('Error writing request to server');
  255. }
  256. if(is_resource($body)) {
  257. if(stream_copy_to_stream($body, $this->socket) == 0) {
  258. require_once 'Zend/Http/Client/Adapter/Exception.php';
  259. throw new Zend_Http_Client_Adapter_Exception('Error writing request to server');
  260. }
  261. }
  262. return $request;
  263. }
  264. /**
  265. * Read response from server
  266. *
  267. * @return string
  268. */
  269. public function read()
  270. {
  271. // First, read headers only
  272. $response = '';
  273. $gotStatus = false;
  274. $stream = !empty($this->config['stream']);
  275. while (($line = @fgets($this->socket)) !== false) {
  276. $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
  277. if ($gotStatus) {
  278. $response .= $line;
  279. if (rtrim($line) === '') break;
  280. }
  281. }
  282. $this->_checkSocketReadTimeout();
  283. $statusCode = Zend_Http_Response::extractCode($response);
  284. // Handle 100 and 101 responses internally by restarting the read again
  285. if ($statusCode == 100 || $statusCode == 101) return $this->read();
  286. // Check headers to see what kind of connection / transfer encoding we have
  287. $headers = Zend_Http_Response::extractHeaders($response);
  288. /**
  289. * Responses to HEAD requests and 204 or 304 responses are not expected
  290. * to have a body - stop reading here
  291. */
  292. if ($statusCode == 304 || $statusCode == 204 ||
  293. $this->method == Zend_Http_Client::HEAD) {
  294. // Close the connection if requested to do so by the server
  295. if (isset($headers['connection']) && $headers['connection'] == 'close') {
  296. $this->close();
  297. }
  298. return $response;
  299. }
  300. // If we got a 'transfer-encoding: chunked' header
  301. if (isset($headers['transfer-encoding'])) {
  302. if (strtolower($headers['transfer-encoding']) == 'chunked') {
  303. do {
  304. $line = @fgets($this->socket);
  305. $this->_checkSocketReadTimeout();
  306. $chunk = $line;
  307. // Figure out the next chunk size
  308. $chunksize = trim($line);
  309. if (! ctype_xdigit($chunksize)) {
  310. $this->close();
  311. require_once 'Zend/Http/Client/Adapter/Exception.php';
  312. throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' .
  313. $chunksize . '" unable to read chunked body');
  314. }
  315. // Convert the hexadecimal value to plain integer
  316. $chunksize = hexdec($chunksize);
  317. // Read next chunk
  318. $read_to = ftell($this->socket) + $chunksize;
  319. do {
  320. $current_pos = ftell($this->socket);
  321. if ($current_pos >= $read_to) break;
  322. if($this->out_stream) {
  323. if(stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) {
  324. $this->_checkSocketReadTimeout();
  325. break;
  326. }
  327. } else {
  328. $line = @fread($this->socket, $read_to - $current_pos);
  329. if ($line === false || strlen($line) === 0) {
  330. $this->_checkSocketReadTimeout();
  331. break;
  332. }
  333. $chunk .= $line;
  334. }
  335. } while (! feof($this->socket));
  336. $chunk .= @fgets($this->socket);
  337. $this->_checkSocketReadTimeout();
  338. if(!$this->out_stream) {
  339. $response .= $chunk;
  340. }
  341. } while ($chunksize > 0);
  342. } else {
  343. $this->close();
  344. throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' .
  345. $headers['transfer-encoding'] . '" transfer encoding');
  346. }
  347. // We automatically decode chunked-messages when writing to a stream
  348. // this means we have to disallow the Zend_Http_Response to do it again
  349. if ($this->out_stream) {
  350. $response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $response);
  351. }
  352. // Else, if we got the content-length header, read this number of bytes
  353. } elseif (isset($headers['content-length'])) {
  354. $current_pos = ftell($this->socket);
  355. $chunk = '';
  356. for ($read_to = $current_pos + $headers['content-length'];
  357. $read_to > $current_pos;
  358. $current_pos = ftell($this->socket)) {
  359. if($this->out_stream) {
  360. if(@stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) {
  361. $this->_checkSocketReadTimeout();
  362. break;
  363. }
  364. } else {
  365. $chunk = @fread($this->socket, $read_to - $current_pos);
  366. if ($chunk === false || strlen($chunk) === 0) {
  367. $this->_checkSocketReadTimeout();
  368. break;
  369. }
  370. $response .= $chunk;
  371. }
  372. // Break if the connection ended prematurely
  373. if (feof($this->socket)) break;
  374. }
  375. // Fallback: just read the response until EOF
  376. } else {
  377. do {
  378. if($this->out_stream) {
  379. if(@stream_copy_to_stream($this->socket, $this->out_stream) == 0) {
  380. $this->_checkSocketReadTimeout();
  381. break;
  382. }
  383. } else {
  384. $buff = @fread($this->socket, 8192);
  385. if ($buff === false || strlen($buff) === 0) {
  386. $this->_checkSocketReadTimeout();
  387. break;
  388. } else {
  389. $response .= $buff;
  390. }
  391. }
  392. } while (feof($this->socket) === false);
  393. $this->close();
  394. }
  395. // Close the connection if requested to do so by the server
  396. if (isset($headers['connection']) && $headers['connection'] == 'close') {
  397. $this->close();
  398. }
  399. return $response;
  400. }
  401. /**
  402. * Close the connection to the server
  403. *
  404. */
  405. public function close()
  406. {
  407. if (is_resource($this->socket)) @fclose($this->socket);
  408. $this->socket = null;
  409. $this->connected_to = array(null, null);
  410. }
  411. /**
  412. * Check if the socket has timed out - if so close connection and throw
  413. * an exception
  414. *
  415. * @throws Zend_Http_Client_Adapter_Exception with READ_TIMEOUT code
  416. */
  417. protected function _checkSocketReadTimeout()
  418. {
  419. if ($this->socket) {
  420. $info = stream_get_meta_data($this->socket);
  421. $timedout = $info['timed_out'];
  422. if ($timedout) {
  423. $this->close();
  424. require_once 'Zend/Http/Client/Adapter/Exception.php';
  425. throw new Zend_Http_Client_Adapter_Exception(
  426. "Read timed out after {$this->config['timeout']} seconds",
  427. Zend_Http_Client_Adapter_Exception::READ_TIMEOUT
  428. );
  429. }
  430. }
  431. }
  432. /**
  433. * Set output stream for the response
  434. *
  435. * @param resource $stream
  436. * @return Zend_Http_Client_Adapter_Socket
  437. */
  438. public function setOutputStream($stream)
  439. {
  440. $this->out_stream = $stream;
  441. return $this;
  442. }
  443. /**
  444. * Destructor: make sure the socket is disconnected
  445. *
  446. * If we are in persistent TCP mode, will not close the connection
  447. *
  448. */
  449. public function __destruct()
  450. {
  451. if (! $this->config['persistent']) {
  452. if ($this->socket) $this->close();
  453. }
  454. }
  455. }