Socket.php 18 KB

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