SocketWrapper.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <?php
  2. /**
  3. * Socket wrapper class used by Socket Adapter
  4. *
  5. * PHP version 5
  6. *
  7. * LICENSE
  8. *
  9. * This source file is subject to BSD 3-Clause License that is bundled
  10. * with this package in the file LICENSE and available at the URL
  11. * https://raw.github.com/pear/HTTP_Request2/trunk/docs/LICENSE
  12. *
  13. * @category HTTP
  14. * @package HTTP_Request2
  15. * @author Alexey Borzov <avb@php.net>
  16. * @copyright 2008-2014 Alexey Borzov <avb@php.net>
  17. * @license http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
  18. * @link http://pear.php.net/package/HTTP_Request2
  19. */
  20. /** Exception classes for HTTP_Request2 package */
  21. require_once 'HTTP/Request2/Exception.php';
  22. /**
  23. * Socket wrapper class used by Socket Adapter
  24. *
  25. * Needed to properly handle connection errors, global timeout support and
  26. * similar things. Loosely based on Net_Socket used by older HTTP_Request.
  27. *
  28. * @category HTTP
  29. * @package HTTP_Request2
  30. * @author Alexey Borzov <avb@php.net>
  31. * @license http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
  32. * @version Release: 2.2.1
  33. * @link http://pear.php.net/package/HTTP_Request2
  34. * @link http://pear.php.net/bugs/bug.php?id=19332
  35. * @link http://tools.ietf.org/html/rfc1928
  36. */
  37. class HTTP_Request2_SocketWrapper
  38. {
  39. /**
  40. * PHP warning messages raised during stream_socket_client() call
  41. * @var array
  42. */
  43. protected $connectionWarnings = array();
  44. /**
  45. * Connected socket
  46. * @var resource
  47. */
  48. protected $socket;
  49. /**
  50. * Sum of start time and global timeout, exception will be thrown if request continues past this time
  51. * @var integer
  52. */
  53. protected $deadline;
  54. /**
  55. * Global timeout value, mostly for exception messages
  56. * @var integer
  57. */
  58. protected $timeout;
  59. /**
  60. * Class constructor, tries to establish connection
  61. *
  62. * @param string $address Address for stream_socket_client() call,
  63. * e.g. 'tcp://localhost:80'
  64. * @param int $timeout Connection timeout (seconds)
  65. * @param array $contextOptions Context options
  66. *
  67. * @throws HTTP_Request2_LogicException
  68. * @throws HTTP_Request2_ConnectionException
  69. */
  70. public function __construct($address, $timeout, array $contextOptions = array())
  71. {
  72. if (!empty($contextOptions)
  73. && !isset($contextOptions['socket']) && !isset($contextOptions['ssl'])
  74. ) {
  75. // Backwards compatibility with 2.1.0 and 2.1.1 releases
  76. $contextOptions = array('ssl' => $contextOptions);
  77. }
  78. $context = stream_context_create();
  79. foreach ($contextOptions as $wrapper => $options) {
  80. foreach ($options as $name => $value) {
  81. if (!stream_context_set_option($context, $wrapper, $name, $value)) {
  82. throw new HTTP_Request2_LogicException(
  83. "Error setting '{$wrapper}' wrapper context option '{$name}'"
  84. );
  85. }
  86. }
  87. }
  88. set_error_handler(array($this, 'connectionWarningsHandler'));
  89. $this->socket = stream_socket_client(
  90. $address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context
  91. );
  92. restore_error_handler();
  93. // if we fail to bind to a specified local address (see request #19515),
  94. // connection still succeeds, albeit with a warning. Throw an Exception
  95. // with the warning text in this case as that connection is unlikely
  96. // to be what user wants and as Curl throws an error in similar case.
  97. if ($this->connectionWarnings) {
  98. if ($this->socket) {
  99. fclose($this->socket);
  100. }
  101. $error = $errstr ? $errstr : implode("\n", $this->connectionWarnings);
  102. throw new HTTP_Request2_ConnectionException(
  103. "Unable to connect to {$address}. Error: {$error}", 0, $errno
  104. );
  105. }
  106. }
  107. /**
  108. * Destructor, disconnects socket
  109. */
  110. public function __destruct()
  111. {
  112. fclose($this->socket);
  113. }
  114. /**
  115. * Wrapper around fread(), handles global request timeout
  116. *
  117. * @param int $length Reads up to this number of bytes
  118. *
  119. * @return string Data read from socket
  120. * @throws HTTP_Request2_MessageException In case of timeout
  121. */
  122. public function read($length)
  123. {
  124. if ($this->deadline) {
  125. stream_set_timeout($this->socket, max($this->deadline - time(), 1));
  126. }
  127. $data = fread($this->socket, $length);
  128. $this->checkTimeout();
  129. return $data;
  130. }
  131. /**
  132. * Reads until either the end of the socket or a newline, whichever comes first
  133. *
  134. * Strips the trailing newline from the returned data, handles global
  135. * request timeout. Method idea borrowed from Net_Socket PEAR package.
  136. *
  137. * @param int $bufferSize buffer size to use for reading
  138. * @param int $localTimeout timeout value to use just for this call
  139. * (used when waiting for "100 Continue" response)
  140. *
  141. * @return string Available data up to the newline (not including newline)
  142. * @throws HTTP_Request2_MessageException In case of timeout
  143. */
  144. public function readLine($bufferSize, $localTimeout = null)
  145. {
  146. $line = '';
  147. while (!feof($this->socket)) {
  148. if (null !== $localTimeout) {
  149. stream_set_timeout($this->socket, $localTimeout);
  150. } elseif ($this->deadline) {
  151. stream_set_timeout($this->socket, max($this->deadline - time(), 1));
  152. }
  153. $line .= @fgets($this->socket, $bufferSize);
  154. if (null === $localTimeout) {
  155. $this->checkTimeout();
  156. } else {
  157. $info = stream_get_meta_data($this->socket);
  158. // reset socket timeout if we don't have request timeout specified,
  159. // prevents further calls failing with a bogus Exception
  160. if (!$this->deadline) {
  161. $default = (int)@ini_get('default_socket_timeout');
  162. stream_set_timeout($this->socket, $default > 0 ? $default : PHP_INT_MAX);
  163. }
  164. if ($info['timed_out']) {
  165. throw new HTTP_Request2_MessageException(
  166. "readLine() call timed out", HTTP_Request2_Exception::TIMEOUT
  167. );
  168. }
  169. }
  170. if (substr($line, -1) == "\n") {
  171. return rtrim($line, "\r\n");
  172. }
  173. }
  174. return $line;
  175. }
  176. /**
  177. * Wrapper around fwrite(), handles global request timeout
  178. *
  179. * @param string $data String to be written
  180. *
  181. * @return int
  182. * @throws HTTP_Request2_MessageException
  183. */
  184. public function write($data)
  185. {
  186. if ($this->deadline) {
  187. stream_set_timeout($this->socket, max($this->deadline - time(), 1));
  188. }
  189. $written = fwrite($this->socket, $data);
  190. $this->checkTimeout();
  191. // http://www.php.net/manual/en/function.fwrite.php#96951
  192. if ($written < strlen($data)) {
  193. throw new HTTP_Request2_MessageException('Error writing request');
  194. }
  195. return $written;
  196. }
  197. /**
  198. * Tests for end-of-file on a socket
  199. *
  200. * @return bool
  201. */
  202. public function eof()
  203. {
  204. return feof($this->socket);
  205. }
  206. /**
  207. * Sets request deadline
  208. *
  209. * @param int $deadline Exception will be thrown if request continues
  210. * past this time
  211. * @param int $timeout Original request timeout value, to use in
  212. * Exception message
  213. */
  214. public function setDeadline($deadline, $timeout)
  215. {
  216. $this->deadline = $deadline;
  217. $this->timeout = $timeout;
  218. }
  219. /**
  220. * Turns on encryption on a socket
  221. *
  222. * @throws HTTP_Request2_ConnectionException
  223. */
  224. public function enableCrypto()
  225. {
  226. $modes = array(
  227. STREAM_CRYPTO_METHOD_TLS_CLIENT,
  228. STREAM_CRYPTO_METHOD_SSLv3_CLIENT,
  229. STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
  230. STREAM_CRYPTO_METHOD_SSLv2_CLIENT
  231. );
  232. foreach ($modes as $mode) {
  233. if (stream_socket_enable_crypto($this->socket, true, $mode)) {
  234. return;
  235. }
  236. }
  237. throw new HTTP_Request2_ConnectionException(
  238. 'Failed to enable secure connection when connecting through proxy'
  239. );
  240. }
  241. /**
  242. * Throws an Exception if stream timed out
  243. *
  244. * @throws HTTP_Request2_MessageException
  245. */
  246. protected function checkTimeout()
  247. {
  248. $info = stream_get_meta_data($this->socket);
  249. if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
  250. $reason = $this->deadline
  251. ? "after {$this->timeout} second(s)"
  252. : 'due to default_socket_timeout php.ini setting';
  253. throw new HTTP_Request2_MessageException(
  254. "Request timed out {$reason}", HTTP_Request2_Exception::TIMEOUT
  255. );
  256. }
  257. }
  258. /**
  259. * Error handler to use during stream_socket_client() call
  260. *
  261. * One stream_socket_client() call may produce *multiple* PHP warnings
  262. * (especially OpenSSL-related), we keep them in an array to later use for
  263. * the message of HTTP_Request2_ConnectionException
  264. *
  265. * @param int $errno error level
  266. * @param string $errstr error message
  267. *
  268. * @return bool
  269. */
  270. protected function connectionWarningsHandler($errno, $errstr)
  271. {
  272. if ($errno & E_WARNING) {
  273. array_unshift($this->connectionWarnings, $errstr);
  274. }
  275. return true;
  276. }
  277. }
  278. ?>