SecureConnector.php 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. <?php
  2. namespace React\Socket;
  3. use React\EventLoop\Loop;
  4. use React\EventLoop\LoopInterface;
  5. use React\Promise;
  6. use BadMethodCallException;
  7. use InvalidArgumentException;
  8. use UnexpectedValueException;
  9. final class SecureConnector implements ConnectorInterface
  10. {
  11. private $connector;
  12. private $streamEncryption;
  13. private $context;
  14. public function __construct(ConnectorInterface $connector, LoopInterface $loop = null, array $context = array())
  15. {
  16. $this->connector = $connector;
  17. $this->streamEncryption = new StreamEncryption($loop ?: Loop::get(), false);
  18. $this->context = $context;
  19. }
  20. public function connect($uri)
  21. {
  22. if (!\function_exists('stream_socket_enable_crypto')) {
  23. return Promise\reject(new \BadMethodCallException('Encryption not supported on your platform (HHVM < 3.8?)')); // @codeCoverageIgnore
  24. }
  25. if (\strpos($uri, '://') === false) {
  26. $uri = 'tls://' . $uri;
  27. }
  28. $parts = \parse_url($uri);
  29. if (!$parts || !isset($parts['scheme']) || $parts['scheme'] !== 'tls') {
  30. return Promise\reject(new \InvalidArgumentException(
  31. 'Given URI "' . $uri . '" is invalid (EINVAL)',
  32. \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)
  33. ));
  34. }
  35. $context = $this->context;
  36. $encryption = $this->streamEncryption;
  37. $connected = false;
  38. /** @var \React\Promise\PromiseInterface<ConnectionInterface> $promise */
  39. $promise = $this->connector->connect(
  40. \str_replace('tls://', '', $uri)
  41. )->then(function (ConnectionInterface $connection) use ($context, $encryption, $uri, &$promise, &$connected) {
  42. // (unencrypted) TCP/IP connection succeeded
  43. $connected = true;
  44. if (!$connection instanceof Connection) {
  45. $connection->close();
  46. throw new \UnexpectedValueException('Base connector does not use internal Connection class exposing stream resource');
  47. }
  48. // set required SSL/TLS context options
  49. foreach ($context as $name => $value) {
  50. \stream_context_set_option($connection->stream, 'ssl', $name, $value);
  51. }
  52. // try to enable encryption
  53. return $promise = $encryption->enable($connection)->then(null, function ($error) use ($connection, $uri) {
  54. // establishing encryption failed => close invalid connection and return error
  55. $connection->close();
  56. throw new \RuntimeException(
  57. 'Connection to ' . $uri . ' failed during TLS handshake: ' . $error->getMessage(),
  58. $error->getCode()
  59. );
  60. });
  61. }, function (\Exception $e) use ($uri) {
  62. if ($e instanceof \RuntimeException) {
  63. $message = \preg_replace('/^Connection to [^ ]+/', '', $e->getMessage());
  64. $e = new \RuntimeException(
  65. 'Connection to ' . $uri . $message,
  66. $e->getCode(),
  67. $e
  68. );
  69. // avoid garbage references by replacing all closures in call stack.
  70. // what a lovely piece of code!
  71. $r = new \ReflectionProperty('Exception', 'trace');
  72. $r->setAccessible(true);
  73. $trace = $r->getValue($e);
  74. // Exception trace arguments are not available on some PHP 7.4 installs
  75. // @codeCoverageIgnoreStart
  76. foreach ($trace as $ti => $one) {
  77. if (isset($one['args'])) {
  78. foreach ($one['args'] as $ai => $arg) {
  79. if ($arg instanceof \Closure) {
  80. $trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')';
  81. }
  82. }
  83. }
  84. }
  85. // @codeCoverageIgnoreEnd
  86. $r->setValue($e, $trace);
  87. }
  88. throw $e;
  89. });
  90. return new \React\Promise\Promise(
  91. function ($resolve, $reject) use ($promise) {
  92. $promise->then($resolve, $reject);
  93. },
  94. function ($_, $reject) use (&$promise, $uri, &$connected) {
  95. if ($connected) {
  96. $reject(new \RuntimeException(
  97. 'Connection to ' . $uri . ' cancelled during TLS handshake (ECONNABORTED)',
  98. \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103
  99. ));
  100. }
  101. $promise->cancel();
  102. $promise = null;
  103. }
  104. );
  105. }
  106. }