SocketServer.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. <?php
  2. namespace React\Socket;
  3. use Evenement\EventEmitter;
  4. use React\EventLoop\LoopInterface;
  5. final class SocketServer extends EventEmitter implements ServerInterface
  6. {
  7. private $server;
  8. /**
  9. * The `SocketServer` class is the main class in this package that implements the `ServerInterface` and
  10. * allows you to accept incoming streaming connections, such as plaintext TCP/IP or secure TLS connection streams.
  11. *
  12. * ```php
  13. * $socket = new React\Socket\SocketServer('127.0.0.1:0');
  14. * $socket = new React\Socket\SocketServer('127.0.0.1:8000');
  15. * $socket = new React\Socket\SocketServer('127.0.0.1:8000', $context);
  16. * ```
  17. *
  18. * This class takes an optional `LoopInterface|null $loop` parameter that can be used to
  19. * pass the event loop instance to use for this object. You can use a `null` value
  20. * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
  21. * This value SHOULD NOT be given unless you're sure you want to explicitly use a
  22. * given event loop instance.
  23. *
  24. * @param string $uri
  25. * @param array $context
  26. * @param ?LoopInterface $loop
  27. * @throws \InvalidArgumentException if the listening address is invalid
  28. * @throws \RuntimeException if listening on this address fails (already in use etc.)
  29. */
  30. public function __construct($uri, array $context = array(), LoopInterface $loop = null)
  31. {
  32. // apply default options if not explicitly given
  33. $context += array(
  34. 'tcp' => array(),
  35. 'tls' => array(),
  36. 'unix' => array()
  37. );
  38. $scheme = 'tcp';
  39. $pos = \strpos($uri, '://');
  40. if ($pos !== false) {
  41. $scheme = \substr($uri, 0, $pos);
  42. }
  43. if ($scheme === 'unix') {
  44. $server = new UnixServer($uri, $loop, $context['unix']);
  45. } elseif ($scheme === 'php') {
  46. $server = new FdServer($uri, $loop);
  47. } else {
  48. if (preg_match('#^(?:\w+://)?\d+$#', $uri)) {
  49. throw new \InvalidArgumentException(
  50. 'Invalid URI given (EINVAL)',
  51. \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)
  52. );
  53. }
  54. $server = new TcpServer(str_replace('tls://', '', $uri), $loop, $context['tcp']);
  55. if ($scheme === 'tls') {
  56. $server = new SecureServer($server, $loop, $context['tls']);
  57. }
  58. }
  59. $this->server = $server;
  60. $that = $this;
  61. $server->on('connection', function (ConnectionInterface $conn) use ($that) {
  62. $that->emit('connection', array($conn));
  63. });
  64. $server->on('error', function (\Exception $error) use ($that) {
  65. $that->emit('error', array($error));
  66. });
  67. }
  68. public function getAddress()
  69. {
  70. return $this->server->getAddress();
  71. }
  72. public function pause()
  73. {
  74. $this->server->pause();
  75. }
  76. public function resume()
  77. {
  78. $this->server->resume();
  79. }
  80. public function close()
  81. {
  82. $this->server->close();
  83. }
  84. /**
  85. * [internal] Internal helper method to accept new connection from given server socket
  86. *
  87. * @param resource $socket server socket to accept connection from
  88. * @return resource new client socket if any
  89. * @throws \RuntimeException if accepting fails
  90. * @internal
  91. */
  92. public static function accept($socket)
  93. {
  94. $errno = 0;
  95. $errstr = '';
  96. \set_error_handler(function ($_, $error) use (&$errno, &$errstr) {
  97. // Match errstr from PHP's warning message.
  98. // stream_socket_accept(): accept failed: Connection timed out
  99. $errstr = \preg_replace('#.*: #', '', $error);
  100. $errno = SocketServer::errno($errstr);
  101. });
  102. $newSocket = \stream_socket_accept($socket, 0);
  103. \restore_error_handler();
  104. if (false === $newSocket) {
  105. throw new \RuntimeException(
  106. 'Unable to accept new connection: ' . $errstr . self::errconst($errno),
  107. $errno
  108. );
  109. }
  110. return $newSocket;
  111. }
  112. /**
  113. * [Internal] Returns errno value for given errstr
  114. *
  115. * The errno and errstr values describes the type of error that has been
  116. * encountered. This method tries to look up the given errstr and find a
  117. * matching errno value which can be useful to provide more context to error
  118. * messages. It goes through the list of known errno constants when either
  119. * `ext-sockets`, `ext-posix` or `ext-pcntl` is available to find an errno
  120. * matching the given errstr.
  121. *
  122. * @param string $errstr
  123. * @return int errno value (e.g. value of `SOCKET_ECONNREFUSED`) or 0 if not found
  124. * @internal
  125. * @copyright Copyright (c) 2023 Christian Lück, taken from https://github.com/clue/errno with permission
  126. * @codeCoverageIgnore
  127. */
  128. public static function errno($errstr)
  129. {
  130. // PHP defines the required `strerror()` function through either `ext-sockets`, `ext-posix` or `ext-pcntl`
  131. $strerror = \function_exists('socket_strerror') ? 'socket_strerror' : (\function_exists('posix_strerror') ? 'posix_strerror' : (\function_exists('pcntl_strerror') ? 'pcntl_strerror' : null));
  132. if ($strerror !== null) {
  133. assert(\is_string($strerror) && \is_callable($strerror));
  134. // PHP defines most useful errno constants like `ECONNREFUSED` through constants in `ext-sockets` like `SOCKET_ECONNREFUSED`
  135. // PHP also defines a hand full of errno constants like `EMFILE` through constants in `ext-pcntl` like `PCNTL_EMFILE`
  136. // go through list of all defined constants like `SOCKET_E*` and `PCNTL_E*` and see if they match the given `$errstr`
  137. foreach (\get_defined_constants(false) as $name => $value) {
  138. if (\is_int($value) && (\strpos($name, 'SOCKET_E') === 0 || \strpos($name, 'PCNTL_E') === 0) && $strerror($value) === $errstr) {
  139. return $value;
  140. }
  141. }
  142. // if we reach this, no matching errno constant could be found (unlikely when `ext-sockets` is available)
  143. // go through list of all possible errno values from 1 to `MAX_ERRNO` and see if they match the given `$errstr`
  144. for ($errno = 1, $max = \defined('MAX_ERRNO') ? \MAX_ERRNO : 4095; $errno <= $max; ++$errno) {
  145. if ($strerror($errno) === $errstr) {
  146. return $errno;
  147. }
  148. }
  149. }
  150. // if we reach this, no matching errno value could be found (unlikely when either `ext-sockets`, `ext-posix` or `ext-pcntl` is available)
  151. return 0;
  152. }
  153. /**
  154. * [Internal] Returns errno constant name for given errno value
  155. *
  156. * The errno value describes the type of error that has been encountered.
  157. * This method tries to look up the given errno value and find a matching
  158. * errno constant name which can be useful to provide more context and more
  159. * descriptive error messages. It goes through the list of known errno
  160. * constants when either `ext-sockets` or `ext-pcntl` is available to find
  161. * the matching errno constant name.
  162. *
  163. * Because this method is used to append more context to error messages, the
  164. * constant name will be prefixed with a space and put between parenthesis
  165. * when found.
  166. *
  167. * @param int $errno
  168. * @return string e.g. ` (ECONNREFUSED)` or empty string if no matching const for the given errno could be found
  169. * @internal
  170. * @copyright Copyright (c) 2023 Christian Lück, taken from https://github.com/clue/errno with permission
  171. * @codeCoverageIgnore
  172. */
  173. public static function errconst($errno)
  174. {
  175. // PHP defines most useful errno constants like `ECONNREFUSED` through constants in `ext-sockets` like `SOCKET_ECONNREFUSED`
  176. // PHP also defines a hand full of errno constants like `EMFILE` through constants in `ext-pcntl` like `PCNTL_EMFILE`
  177. // go through list of all defined constants like `SOCKET_E*` and `PCNTL_E*` and see if they match the given `$errno`
  178. foreach (\get_defined_constants(false) as $name => $value) {
  179. if ($value === $errno && (\strpos($name, 'SOCKET_E') === 0 || \strpos($name, 'PCNTL_E') === 0)) {
  180. return ' (' . \substr($name, \strpos($name, '_') + 1) . ')';
  181. }
  182. }
  183. // if we reach this, no matching errno constant could be found (unlikely when `ext-sockets` is available)
  184. return '';
  185. }
  186. }