FdServer.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. <?php
  2. namespace React\Socket;
  3. use Evenement\EventEmitter;
  4. use React\EventLoop\Loop;
  5. use React\EventLoop\LoopInterface;
  6. /**
  7. * [Internal] The `FdServer` class implements the `ServerInterface` and
  8. * is responsible for accepting connections from an existing file descriptor.
  9. *
  10. * ```php
  11. * $socket = new React\Socket\FdServer(3);
  12. * ```
  13. *
  14. * Whenever a client connects, it will emit a `connection` event with a connection
  15. * instance implementing `ConnectionInterface`:
  16. *
  17. * ```php
  18. * $socket->on('connection', function (ConnectionInterface $connection) {
  19. * echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL;
  20. * $connection->write('hello there!' . PHP_EOL);
  21. * …
  22. * });
  23. * ```
  24. *
  25. * See also the `ServerInterface` for more details.
  26. *
  27. * @see ServerInterface
  28. * @see ConnectionInterface
  29. * @internal
  30. */
  31. final class FdServer extends EventEmitter implements ServerInterface
  32. {
  33. private $master;
  34. private $loop;
  35. private $unix = false;
  36. private $listening = false;
  37. /**
  38. * Creates a socket server and starts listening on the given file descriptor
  39. *
  40. * This starts accepting new incoming connections on the given file descriptor.
  41. * See also the `connection event` documented in the `ServerInterface`
  42. * for more details.
  43. *
  44. * ```php
  45. * $socket = new React\Socket\FdServer(3);
  46. * ```
  47. *
  48. * If the given FD is invalid or out of range, it will throw an `InvalidArgumentException`:
  49. *
  50. * ```php
  51. * // throws InvalidArgumentException
  52. * $socket = new React\Socket\FdServer(-1);
  53. * ```
  54. *
  55. * If the given FD appears to be valid, but listening on it fails (such as
  56. * if the FD does not exist or does not refer to a socket server), it will
  57. * throw a `RuntimeException`:
  58. *
  59. * ```php
  60. * // throws RuntimeException because FD does not reference a socket server
  61. * $socket = new React\Socket\FdServer(0, $loop);
  62. * ```
  63. *
  64. * Note that these error conditions may vary depending on your system and/or
  65. * configuration.
  66. * See the exception message and code for more details about the actual error
  67. * condition.
  68. *
  69. * @param int|string $fd FD number such as `3` or as URL in the form of `php://fd/3`
  70. * @param ?LoopInterface $loop
  71. * @throws \InvalidArgumentException if the listening address is invalid
  72. * @throws \RuntimeException if listening on this address fails (already in use etc.)
  73. */
  74. public function __construct($fd, LoopInterface $loop = null)
  75. {
  76. if (\preg_match('#^php://fd/(\d+)$#', $fd, $m)) {
  77. $fd = (int) $m[1];
  78. }
  79. if (!\is_int($fd) || $fd < 0 || $fd >= \PHP_INT_MAX) {
  80. throw new \InvalidArgumentException(
  81. 'Invalid FD number given (EINVAL)',
  82. \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)
  83. );
  84. }
  85. $this->loop = $loop ?: Loop::get();
  86. $errno = 0;
  87. $errstr = '';
  88. \set_error_handler(function ($_, $error) use (&$errno, &$errstr) {
  89. // Match errstr from PHP's warning message.
  90. // fopen(php://fd/3): Failed to open stream: Error duping file descriptor 3; possibly it doesn't exist: [9]: Bad file descriptor
  91. \preg_match('/\[(\d+)\]: (.*)/', $error, $m);
  92. $errno = isset($m[1]) ? (int) $m[1] : 0;
  93. $errstr = isset($m[2]) ? $m[2] : $error;
  94. });
  95. $this->master = \fopen('php://fd/' . $fd, 'r+');
  96. \restore_error_handler();
  97. if (false === $this->master) {
  98. throw new \RuntimeException(
  99. 'Failed to listen on FD ' . $fd . ': ' . $errstr . SocketServer::errconst($errno),
  100. $errno
  101. );
  102. }
  103. $meta = \stream_get_meta_data($this->master);
  104. if (!isset($meta['stream_type']) || $meta['stream_type'] !== 'tcp_socket') {
  105. \fclose($this->master);
  106. $errno = \defined('SOCKET_ENOTSOCK') ? \SOCKET_ENOTSOCK : 88;
  107. $errstr = \function_exists('socket_strerror') ? \socket_strerror($errno) : 'Not a socket';
  108. throw new \RuntimeException(
  109. 'Failed to listen on FD ' . $fd . ': ' . $errstr . ' (ENOTSOCK)',
  110. $errno
  111. );
  112. }
  113. // Socket should not have a peer address if this is a listening socket.
  114. // Looks like this work-around is the closest we can get because PHP doesn't expose SO_ACCEPTCONN even with ext-sockets.
  115. if (\stream_socket_get_name($this->master, true) !== false) {
  116. \fclose($this->master);
  117. $errno = \defined('SOCKET_EISCONN') ? \SOCKET_EISCONN : 106;
  118. $errstr = \function_exists('socket_strerror') ? \socket_strerror($errno) : 'Socket is connected';
  119. throw new \RuntimeException(
  120. 'Failed to listen on FD ' . $fd . ': ' . $errstr . ' (EISCONN)',
  121. $errno
  122. );
  123. }
  124. // Assume this is a Unix domain socket (UDS) when its listening address doesn't parse as a valid URL with a port.
  125. // Looks like this work-around is the closest we can get because PHP doesn't expose SO_DOMAIN even with ext-sockets.
  126. $this->unix = \parse_url($this->getAddress(), \PHP_URL_PORT) === false;
  127. \stream_set_blocking($this->master, false);
  128. $this->resume();
  129. }
  130. public function getAddress()
  131. {
  132. if (!\is_resource($this->master)) {
  133. return null;
  134. }
  135. $address = \stream_socket_get_name($this->master, false);
  136. if ($this->unix === true) {
  137. return 'unix://' . $address;
  138. }
  139. // check if this is an IPv6 address which includes multiple colons but no square brackets
  140. $pos = \strrpos($address, ':');
  141. if ($pos !== false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') {
  142. $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); // @codeCoverageIgnore
  143. }
  144. return 'tcp://' . $address;
  145. }
  146. public function pause()
  147. {
  148. if (!$this->listening) {
  149. return;
  150. }
  151. $this->loop->removeReadStream($this->master);
  152. $this->listening = false;
  153. }
  154. public function resume()
  155. {
  156. if ($this->listening || !\is_resource($this->master)) {
  157. return;
  158. }
  159. $that = $this;
  160. $this->loop->addReadStream($this->master, function ($master) use ($that) {
  161. try {
  162. $newSocket = SocketServer::accept($master);
  163. } catch (\RuntimeException $e) {
  164. $that->emit('error', array($e));
  165. return;
  166. }
  167. $that->handleConnection($newSocket);
  168. });
  169. $this->listening = true;
  170. }
  171. public function close()
  172. {
  173. if (!\is_resource($this->master)) {
  174. return;
  175. }
  176. $this->pause();
  177. \fclose($this->master);
  178. $this->removeAllListeners();
  179. }
  180. /** @internal */
  181. public function handleConnection($socket)
  182. {
  183. $connection = new Connection($socket, $this->loop);
  184. $connection->unix = $this->unix;
  185. $this->emit('connection', array($connection));
  186. }
  187. }