Socket.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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-2015 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-2015 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. 'sslusecontext' => false
  75. );
  76. /**
  77. * Request method - will be set by write() and might be used by read()
  78. *
  79. * @var string
  80. */
  81. protected $method = null;
  82. /**
  83. * Stream context
  84. *
  85. * @var resource
  86. */
  87. protected $_context = null;
  88. /**
  89. * Adapter constructor, currently empty. Config is set using setConfig()
  90. *
  91. */
  92. public function __construct()
  93. {
  94. }
  95. /**
  96. * Set the configuration array for the adapter
  97. *
  98. * @param Zend_Config | array $config
  99. */
  100. public function setConfig($config = array())
  101. {
  102. if ($config instanceof Zend_Config) {
  103. $config = $config->toArray();
  104. } elseif (! is_array($config)) {
  105. require_once 'Zend/Http/Client/Adapter/Exception.php';
  106. throw new Zend_Http_Client_Adapter_Exception(
  107. 'Array or Zend_Config object expected, got ' . gettype($config)
  108. );
  109. }
  110. foreach ($config as $k => $v) {
  111. $this->config[strtolower($k)] = $v;
  112. }
  113. }
  114. /**
  115. * Retrieve the array of all configuration options
  116. *
  117. * @return array
  118. */
  119. public function getConfig()
  120. {
  121. return $this->config;
  122. }
  123. /**
  124. * Set the stream context for the TCP connection to the server
  125. *
  126. * Can accept either a pre-existing stream context resource, or an array
  127. * of stream options, similar to the options array passed to the
  128. * stream_context_create() PHP function. In such case a new stream context
  129. * will be created using the passed options.
  130. *
  131. * @since Zend Framework 1.9
  132. *
  133. * @param mixed $context Stream context or array of context options
  134. * @return Zend_Http_Client_Adapter_Socket
  135. */
  136. public function setStreamContext($context)
  137. {
  138. if (is_resource($context) && get_resource_type($context) == 'stream-context') {
  139. $this->_context = $context;
  140. } elseif (is_array($context)) {
  141. $this->_context = stream_context_create($context);
  142. } else {
  143. // Invalid parameter
  144. require_once 'Zend/Http/Client/Adapter/Exception.php';
  145. throw new Zend_Http_Client_Adapter_Exception(
  146. "Expecting either a stream context resource or array, got " . gettype($context)
  147. );
  148. }
  149. return $this;
  150. }
  151. /**
  152. * Get the stream context for the TCP connection to the server.
  153. *
  154. * If no stream context is set, will create a default one.
  155. *
  156. * @return resource
  157. */
  158. public function getStreamContext()
  159. {
  160. if (! $this->_context) {
  161. $this->_context = stream_context_create();
  162. }
  163. return $this->_context;
  164. }
  165. /**
  166. * Connect to the remote server
  167. *
  168. * @param string $host
  169. * @param int $port
  170. * @param boolean $secure
  171. */
  172. public function connect($host, $port = 80, $secure = false)
  173. {
  174. // If the URI should be accessed via SSL, prepend the Hostname with ssl://
  175. $host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  176. // If we are connected to the wrong host, disconnect first
  177. if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
  178. if (is_resource($this->socket)) $this->close();
  179. }
  180. // Now, if we are not connected, connect
  181. if (! is_resource($this->socket) || ! $this->config['keepalive']) {
  182. $context = $this->getStreamContext();
  183. if ($secure || $this->config['sslusecontext']) {
  184. if ($this->config['sslcert'] !== null) {
  185. if (! stream_context_set_option($context, 'ssl', 'local_cert',
  186. $this->config['sslcert'])) {
  187. require_once 'Zend/Http/Client/Adapter/Exception.php';
  188. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option');
  189. }
  190. }
  191. if ($this->config['sslpassphrase'] !== null) {
  192. if (! stream_context_set_option($context, 'ssl', 'passphrase',
  193. $this->config['sslpassphrase'])) {
  194. require_once 'Zend/Http/Client/Adapter/Exception.php';
  195. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option');
  196. }
  197. }
  198. }
  199. $flags = STREAM_CLIENT_CONNECT;
  200. if ($this->config['persistent']) $flags |= STREAM_CLIENT_PERSISTENT;
  201. $this->socket = @stream_socket_client($host . ':' . $port,
  202. $errno,
  203. $errstr,
  204. (int) $this->config['timeout'],
  205. $flags,
  206. $context);
  207. if (! $this->socket) {
  208. $this->close();
  209. require_once 'Zend/Http/Client/Adapter/Exception.php';
  210. throw new Zend_Http_Client_Adapter_Exception(
  211. 'Unable to Connect to ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr);
  212. }
  213. // Set the stream timeout
  214. if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
  215. require_once 'Zend/Http/Client/Adapter/Exception.php';
  216. throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
  217. }
  218. // Update connected_to
  219. $this->connected_to = array($host, $port);
  220. }
  221. }
  222. /**
  223. * Send request to the remote server
  224. *
  225. * @param string $method
  226. * @param Zend_Uri_Http $uri
  227. * @param string $http_ver
  228. * @param array $headers
  229. * @param string $body
  230. * @return string Request as string
  231. */
  232. public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
  233. {
  234. // Make sure we're properly connected
  235. if (! $this->socket) {
  236. require_once 'Zend/Http/Client/Adapter/Exception.php';
  237. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are not connected');
  238. }
  239. $host = $uri->getHost();
  240. $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  241. if ($this->connected_to[0] != $host || $this->connected_to[1] != $uri->getPort()) {
  242. require_once 'Zend/Http/Client/Adapter/Exception.php';
  243. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are connected to the wrong host');
  244. }
  245. // Save request method for later
  246. $this->method = $method;
  247. // Build request headers
  248. $path = $uri->getPath();
  249. if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
  250. $request = "{$method} {$path} HTTP/{$http_ver}\r\n";
  251. foreach ($headers as $k => $v) {
  252. if (is_string($k)) $v = ucfirst($k) . ": $v";
  253. $request .= "$v\r\n";
  254. }
  255. if(is_resource($body)) {
  256. $request .= "\r\n";
  257. } else {
  258. // Add the request body
  259. $request .= "\r\n" . $body;
  260. }
  261. // Send the request
  262. if (! @fwrite($this->socket, $request)) {
  263. require_once 'Zend/Http/Client/Adapter/Exception.php';
  264. throw new Zend_Http_Client_Adapter_Exception('Error writing request to server');
  265. }
  266. if(is_resource($body)) {
  267. if(stream_copy_to_stream($body, $this->socket) == 0) {
  268. require_once 'Zend/Http/Client/Adapter/Exception.php';
  269. throw new Zend_Http_Client_Adapter_Exception('Error writing request to server');
  270. }
  271. }
  272. return $request;
  273. }
  274. /**
  275. * Read response from server
  276. *
  277. * @return string
  278. */
  279. public function read()
  280. {
  281. // First, read headers only
  282. $response = '';
  283. $gotStatus = false;
  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. require_once 'Zend/Http/Client/Adapter/Exception.php';
  354. throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' .
  355. $headers['transfer-encoding'] . '" transfer encoding');
  356. }
  357. // We automatically decode chunked-messages when writing to a stream
  358. // this means we have to disallow the Zend_Http_Response to do it again
  359. if ($this->out_stream) {
  360. $response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $response);
  361. }
  362. // Else, if we got the content-length header, read this number of bytes
  363. } elseif (isset($headers['content-length'])) {
  364. // If we got more than one Content-Length header (see ZF-9404) use
  365. // the last value sent
  366. if (is_array($headers['content-length'])) {
  367. $contentLength = $headers['content-length'][count($headers['content-length']) - 1];
  368. } else {
  369. $contentLength = $headers['content-length'];
  370. }
  371. $current_pos = ftell($this->socket);
  372. $chunk = '';
  373. for ($read_to = $current_pos + $contentLength;
  374. $read_to > $current_pos;
  375. $current_pos = ftell($this->socket)) {
  376. if($this->out_stream) {
  377. if(@stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) {
  378. $this->_checkSocketReadTimeout();
  379. break;
  380. }
  381. } else {
  382. $chunk = @fread($this->socket, $read_to - $current_pos);
  383. if ($chunk === false || strlen($chunk) === 0) {
  384. $this->_checkSocketReadTimeout();
  385. break;
  386. }
  387. $response .= $chunk;
  388. }
  389. // Break if the connection ended prematurely
  390. if (feof($this->socket)) break;
  391. }
  392. // Fallback: just read the response until EOF
  393. } else {
  394. do {
  395. if($this->out_stream) {
  396. if(@stream_copy_to_stream($this->socket, $this->out_stream) == 0) {
  397. $this->_checkSocketReadTimeout();
  398. break;
  399. }
  400. } else {
  401. $buff = @fread($this->socket, 8192);
  402. if ($buff === false || strlen($buff) === 0) {
  403. $this->_checkSocketReadTimeout();
  404. break;
  405. } else {
  406. $response .= $buff;
  407. }
  408. }
  409. } while (feof($this->socket) === false);
  410. $this->close();
  411. }
  412. // Close the connection if requested to do so by the server
  413. if (isset($headers['connection']) && $headers['connection'] == 'close') {
  414. $this->close();
  415. }
  416. return $response;
  417. }
  418. /**
  419. * Close the connection to the server
  420. *
  421. */
  422. public function close()
  423. {
  424. if (is_resource($this->socket)) @fclose($this->socket);
  425. $this->socket = null;
  426. $this->connected_to = array(null, null);
  427. }
  428. /**
  429. * Check if the socket has timed out - if so close connection and throw
  430. * an exception
  431. *
  432. * @throws Zend_Http_Client_Adapter_Exception with READ_TIMEOUT code
  433. */
  434. protected function _checkSocketReadTimeout()
  435. {
  436. if ($this->socket) {
  437. $info = stream_get_meta_data($this->socket);
  438. $timedout = $info['timed_out'];
  439. if ($timedout) {
  440. $this->close();
  441. require_once 'Zend/Http/Client/Adapter/Exception.php';
  442. throw new Zend_Http_Client_Adapter_Exception(
  443. "Read timed out after {$this->config['timeout']} seconds",
  444. Zend_Http_Client_Adapter_Exception::READ_TIMEOUT
  445. );
  446. }
  447. }
  448. }
  449. /**
  450. * Set output stream for the response
  451. *
  452. * @param resource $stream
  453. * @return Zend_Http_Client_Adapter_Socket
  454. */
  455. public function setOutputStream($stream)
  456. {
  457. $this->out_stream = $stream;
  458. return $this;
  459. }
  460. /**
  461. * Destructor: make sure the socket is disconnected
  462. *
  463. * If we are in persistent TCP mode, will not close the connection
  464. *
  465. */
  466. public function __destruct()
  467. {
  468. if (! $this->config['persistent']) {
  469. if ($this->socket) $this->close();
  470. }
  471. }
  472. }