Socket.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. * Adapter constructor, currently empty. Config is set using setConfig()
  73. *
  74. */
  75. public function __construct()
  76. {
  77. }
  78. /**
  79. * Set the configuration array for the adapter
  80. *
  81. * @param array $config
  82. */
  83. public function setConfig($config = array())
  84. {
  85. if (! is_array($config)) {
  86. require_once 'Zend/Http/Client/Adapter/Exception.php';
  87. throw new Zend_Http_Client_Adapter_Exception(
  88. '$concig expects an array, ' . gettype($config) . ' recieved.');
  89. }
  90. foreach ($config as $k => $v) {
  91. $this->config[strtolower($k)] = $v;
  92. }
  93. }
  94. /**
  95. * Connect to the remote server
  96. *
  97. * @param string $host
  98. * @param int $port
  99. * @param boolean $secure
  100. * @param int $timeout
  101. */
  102. public function connect($host, $port = 80, $secure = false)
  103. {
  104. // If the URI should be accessed via SSL, prepend the Hostname with ssl://
  105. $host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  106. // If we are connected to the wrong host, disconnect first
  107. if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
  108. if (is_resource($this->socket)) $this->close();
  109. }
  110. // Now, if we are not connected, connect
  111. if (! is_resource($this->socket) || ! $this->config['keepalive']) {
  112. $context = stream_context_create();
  113. if ($secure) {
  114. if ($this->config['sslcert'] !== null) {
  115. if (! stream_context_set_option($context, 'ssl', 'local_cert',
  116. $this->config['sslcert'])) {
  117. require_once 'Zend/Http/Client/Adapter/Exception.php';
  118. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option');
  119. }
  120. }
  121. if ($this->config['sslpassphrase'] !== null) {
  122. if (! stream_context_set_option($context, 'ssl', 'passphrase',
  123. $this->config['sslpassphrase'])) {
  124. require_once 'Zend/Http/Client/Adapter/Exception.php';
  125. throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option');
  126. }
  127. }
  128. }
  129. $flags = STREAM_CLIENT_CONNECT;
  130. if ($this->config['persistent']) $flags |= STREAM_CLIENT_PERSISTENT;
  131. $this->socket = @stream_socket_client($host . ':' . $port,
  132. $errno,
  133. $errstr,
  134. (int) $this->config['timeout'],
  135. $flags,
  136. $context);
  137. if (! $this->socket) {
  138. $this->close();
  139. require_once 'Zend/Http/Client/Adapter/Exception.php';
  140. throw new Zend_Http_Client_Adapter_Exception(
  141. 'Unable to Connect to ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr);
  142. }
  143. // Set the stream timeout
  144. if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
  145. require_once 'Zend/Http/Client/Adapter/Exception.php';
  146. throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
  147. }
  148. // Update connected_to
  149. $this->connected_to = array($host, $port);
  150. }
  151. }
  152. /**
  153. * Send request to the remote server
  154. *
  155. * @param string $method
  156. * @param Zend_Uri_Http $uri
  157. * @param string $http_ver
  158. * @param array $headers
  159. * @param string $body
  160. * @return string Request as string
  161. */
  162. public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
  163. {
  164. // Make sure we're properly connected
  165. if (! $this->socket) {
  166. require_once 'Zend/Http/Client/Adapter/Exception.php';
  167. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are not connected');
  168. }
  169. $host = $uri->getHost();
  170. $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
  171. if ($this->connected_to[0] != $host || $this->connected_to[1] != $uri->getPort()) {
  172. require_once 'Zend/Http/Client/Adapter/Exception.php';
  173. throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are connected to the wrong host');
  174. }
  175. // Save request method for later
  176. $this->method = $method;
  177. // Build request headers
  178. $path = $uri->getPath();
  179. if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
  180. $request = "{$method} {$path} HTTP/{$http_ver}\r\n";
  181. foreach ($headers as $k => $v) {
  182. if (is_string($k)) $v = ucfirst($k) . ": $v";
  183. $request .= "$v\r\n";
  184. }
  185. // Add the request body
  186. $request .= "\r\n" . $body;
  187. // Send the request
  188. if (! @fwrite($this->socket, $request)) {
  189. require_once 'Zend/Http/Client/Adapter/Exception.php';
  190. throw new Zend_Http_Client_Adapter_Exception('Error writing request to server');
  191. }
  192. return $request;
  193. }
  194. /**
  195. * Read response from server
  196. *
  197. * @return string
  198. */
  199. public function read()
  200. {
  201. // First, read headers only
  202. $response = '';
  203. $gotStatus = false;
  204. while (($line = @fgets($this->socket)) !== false) {
  205. $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
  206. if ($gotStatus) {
  207. $response .= $line;
  208. if (rtrim($line) === '') break;
  209. }
  210. }
  211. $statusCode = Zend_Http_Response::extractCode($response);
  212. // Handle 100 and 101 responses internally by restarting the read again
  213. if ($statusCode == 100 || $statusCode == 101) return $this->read();
  214. /**
  215. * Responses to HEAD requests and 204 or 304 responses are not expected
  216. * to have a body - stop reading here
  217. */
  218. if ($statusCode == 304 || $statusCode == 204 ||
  219. $this->method == Zend_Http_Client::HEAD) return $response;
  220. // Check headers to see what kind of connection / transfer encoding we have
  221. $headers = Zend_Http_Response::extractHeaders($response);
  222. // If we got a 'transfer-encoding: chunked' header
  223. if (isset($headers['transfer-encoding'])) {
  224. if ($headers['transfer-encoding'] == 'chunked') {
  225. do {
  226. $line = @fgets($this->socket);
  227. $chunk = $line;
  228. // Figure out the next chunk size
  229. $chunksize = trim($line);
  230. if (! ctype_xdigit($chunksize)) {
  231. $this->close();
  232. require_once 'Zend/Http/Client/Adapter/Exception.php';
  233. throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' .
  234. $chunksize . '" unable to read chunked body');
  235. }
  236. // Convert the hexadecimal value to plain integer
  237. $chunksize = hexdec($chunksize);
  238. // Read chunk
  239. $left_to_read = $chunksize;
  240. while ($left_to_read > 0) {
  241. $line = @fread($this->socket, $left_to_read);
  242. if ($line === false || strlen($line) === 0)
  243. {
  244. break;
  245. } else {
  246. $chunk .= $line;
  247. $left_to_read -= strlen($line);
  248. }
  249. // Break if the connection ended prematurely
  250. if (feof($this->socket)) break;
  251. }
  252. $chunk .= @fgets($this->socket);
  253. $response .= $chunk;
  254. } while ($chunksize > 0);
  255. } else {
  256. throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' .
  257. $headers['transfer-encoding'] . '" transfer encoding');
  258. }
  259. // Else, if we got the content-length header, read this number of bytes
  260. } elseif (isset($headers['content-length'])) {
  261. $left_to_read = $headers['content-length'];
  262. $chunk = '';
  263. while ($left_to_read > 0) {
  264. $chunk = @fread($this->socket, $left_to_read);
  265. if ($chunk === false || strlen($chunk) === 0)
  266. {
  267. break;
  268. } else {
  269. $left_to_read -= strlen($chunk);
  270. $response .= $chunk;
  271. }
  272. // Break if the connection ended prematurely
  273. if (feof($this->socket)) break;
  274. }
  275. // Fallback: just read the response until EOF
  276. } else {
  277. do {
  278. $buff = @fread($this->socket, 8192);
  279. if ($buff === false || strlen($buff) === 0)
  280. {
  281. break;
  282. } else {
  283. $response .= $buff;
  284. }
  285. } while (feof($this->socket) === false);
  286. $this->close();
  287. }
  288. // Close the connection if requested to do so by the server
  289. if (isset($headers['connection']) && $headers['connection'] == 'close') {
  290. $this->close();
  291. }
  292. return $response;
  293. }
  294. /**
  295. * Close the connection to the server
  296. *
  297. */
  298. public function close()
  299. {
  300. if (is_resource($this->socket)) @fclose($this->socket);
  301. $this->socket = null;
  302. $this->connected_to = array(null, null);
  303. }
  304. /**
  305. * Destructor: make sure the socket is disconnected
  306. *
  307. * If we are in persistent TCP mode, will not close the connection
  308. *
  309. */
  310. public function __destruct()
  311. {
  312. if (! $this->config['persistent']) {
  313. if ($this->socket) $this->close();
  314. }
  315. }
  316. }