TcpConnector.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. <?php
  2. namespace React\Socket;
  3. use React\EventLoop\Loop;
  4. use React\EventLoop\LoopInterface;
  5. use React\Promise;
  6. use InvalidArgumentException;
  7. use RuntimeException;
  8. final class TcpConnector implements ConnectorInterface
  9. {
  10. private $loop;
  11. private $context;
  12. public function __construct(LoopInterface $loop = null, array $context = array())
  13. {
  14. $this->loop = $loop ?: Loop::get();
  15. $this->context = $context;
  16. }
  17. public function connect($uri)
  18. {
  19. if (\strpos($uri, '://') === false) {
  20. $uri = 'tcp://' . $uri;
  21. }
  22. $parts = \parse_url($uri);
  23. if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') {
  24. return Promise\reject(new \InvalidArgumentException(
  25. 'Given URI "' . $uri . '" is invalid (EINVAL)',
  26. \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)
  27. ));
  28. }
  29. $ip = \trim($parts['host'], '[]');
  30. if (@\inet_pton($ip) === false) {
  31. return Promise\reject(new \InvalidArgumentException(
  32. 'Given URI "' . $uri . '" does not contain a valid host IP (EINVAL)',
  33. \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)
  34. ));
  35. }
  36. // use context given in constructor
  37. $context = array(
  38. 'socket' => $this->context
  39. );
  40. // parse arguments from query component of URI
  41. $args = array();
  42. if (isset($parts['query'])) {
  43. \parse_str($parts['query'], $args);
  44. }
  45. // If an original hostname has been given, use this for TLS setup.
  46. // This can happen due to layers of nested connectors, such as a
  47. // DnsConnector reporting its original hostname.
  48. // These context options are here in case TLS is enabled later on this stream.
  49. // If TLS is not enabled later, this doesn't hurt either.
  50. if (isset($args['hostname'])) {
  51. $context['ssl'] = array(
  52. 'SNI_enabled' => true,
  53. 'peer_name' => $args['hostname']
  54. );
  55. // Legacy PHP < 5.6 ignores peer_name and requires legacy context options instead.
  56. // The SNI_server_name context option has to be set here during construction,
  57. // as legacy PHP ignores any values set later.
  58. // @codeCoverageIgnoreStart
  59. if (\PHP_VERSION_ID < 50600) {
  60. $context['ssl'] += array(
  61. 'SNI_server_name' => $args['hostname'],
  62. 'CN_match' => $args['hostname']
  63. );
  64. }
  65. // @codeCoverageIgnoreEnd
  66. }
  67. // latest versions of PHP no longer accept any other URI components and
  68. // HHVM fails to parse URIs with a query but no path, so let's simplify our URI here
  69. $remote = 'tcp://' . $parts['host'] . ':' . $parts['port'];
  70. $stream = @\stream_socket_client(
  71. $remote,
  72. $errno,
  73. $errstr,
  74. 0,
  75. \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT,
  76. \stream_context_create($context)
  77. );
  78. if (false === $stream) {
  79. return Promise\reject(new \RuntimeException(
  80. 'Connection to ' . $uri . ' failed: ' . $errstr . SocketServer::errconst($errno),
  81. $errno
  82. ));
  83. }
  84. // wait for connection
  85. $loop = $this->loop;
  86. return new Promise\Promise(function ($resolve, $reject) use ($loop, $stream, $uri) {
  87. $loop->addWriteStream($stream, function ($stream) use ($loop, $resolve, $reject, $uri) {
  88. $loop->removeWriteStream($stream);
  89. // The following hack looks like the only way to
  90. // detect connection refused errors with PHP's stream sockets.
  91. if (false === \stream_socket_get_name($stream, true)) {
  92. // If we reach this point, we know the connection is dead, but we don't know the underlying error condition.
  93. // @codeCoverageIgnoreStart
  94. if (\function_exists('socket_import_stream')) {
  95. // actual socket errno and errstr can be retrieved with ext-sockets on PHP 5.4+
  96. $socket = \socket_import_stream($stream);
  97. $errno = \socket_get_option($socket, \SOL_SOCKET, \SO_ERROR);
  98. $errstr = \socket_strerror($errno);
  99. } elseif (\PHP_OS === 'Linux') {
  100. // Linux reports socket errno and errstr again when trying to write to the dead socket.
  101. // Suppress error reporting to get error message below and close dead socket before rejecting.
  102. // This is only known to work on Linux, Mac and Windows are known to not support this.
  103. $errno = 0;
  104. $errstr = '';
  105. \set_error_handler(function ($_, $error) use (&$errno, &$errstr) {
  106. // Match errstr from PHP's warning message.
  107. // fwrite(): send of 1 bytes failed with errno=111 Connection refused
  108. \preg_match('/errno=(\d+) (.+)/', $error, $m);
  109. $errno = isset($m[1]) ? (int) $m[1] : 0;
  110. $errstr = isset($m[2]) ? $m[2] : $error;
  111. });
  112. \fwrite($stream, \PHP_EOL);
  113. \restore_error_handler();
  114. } else {
  115. // Not on Linux and ext-sockets not available? Too bad.
  116. $errno = \defined('SOCKET_ECONNREFUSED') ? \SOCKET_ECONNREFUSED : 111;
  117. $errstr = 'Connection refused?';
  118. }
  119. // @codeCoverageIgnoreEnd
  120. \fclose($stream);
  121. $reject(new \RuntimeException(
  122. 'Connection to ' . $uri . ' failed: ' . $errstr . SocketServer::errconst($errno),
  123. $errno
  124. ));
  125. } else {
  126. $resolve(new Connection($stream, $loop));
  127. }
  128. });
  129. }, function () use ($loop, $stream, $uri) {
  130. $loop->removeWriteStream($stream);
  131. \fclose($stream);
  132. // @codeCoverageIgnoreStart
  133. // legacy PHP 5.3 sometimes requires a second close call (see tests)
  134. if (\PHP_VERSION_ID < 50400 && \is_resource($stream)) {
  135. \fclose($stream);
  136. }
  137. // @codeCoverageIgnoreEnd
  138. throw new \RuntimeException(
  139. 'Connection to ' . $uri . ' cancelled during TCP/IP handshake (ECONNABORTED)',
  140. \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103
  141. );
  142. });
  143. }
  144. }