FdServer.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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, $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. if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1
  86. throw new \InvalidArgumentException('Argument #2 ($loop) expected null|React\EventLoop\LoopInterface');
  87. }
  88. $this->loop = $loop ?: Loop::get();
  89. $errno = 0;
  90. $errstr = '';
  91. \set_error_handler(function ($_, $error) use (&$errno, &$errstr) {
  92. // Match errstr from PHP's warning message.
  93. // fopen(php://fd/3): Failed to open stream: Error duping file descriptor 3; possibly it doesn't exist: [9]: Bad file descriptor
  94. \preg_match('/\[(\d+)\]: (.*)/', $error, $m);
  95. $errno = isset($m[1]) ? (int) $m[1] : 0;
  96. $errstr = isset($m[2]) ? $m[2] : $error;
  97. });
  98. $this->master = \fopen('php://fd/' . $fd, 'r+');
  99. \restore_error_handler();
  100. if (false === $this->master) {
  101. throw new \RuntimeException(
  102. 'Failed to listen on FD ' . $fd . ': ' . $errstr . SocketServer::errconst($errno),
  103. $errno
  104. );
  105. }
  106. $meta = \stream_get_meta_data($this->master);
  107. if (!isset($meta['stream_type']) || $meta['stream_type'] !== 'tcp_socket') {
  108. \fclose($this->master);
  109. $errno = \defined('SOCKET_ENOTSOCK') ? \SOCKET_ENOTSOCK : 88;
  110. $errstr = \function_exists('socket_strerror') ? \socket_strerror($errno) : 'Not a socket';
  111. throw new \RuntimeException(
  112. 'Failed to listen on FD ' . $fd . ': ' . $errstr . ' (ENOTSOCK)',
  113. $errno
  114. );
  115. }
  116. // Socket should not have a peer address if this is a listening socket.
  117. // Looks like this work-around is the closest we can get because PHP doesn't expose SO_ACCEPTCONN even with ext-sockets.
  118. if (\stream_socket_get_name($this->master, true) !== false) {
  119. \fclose($this->master);
  120. $errno = \defined('SOCKET_EISCONN') ? \SOCKET_EISCONN : 106;
  121. $errstr = \function_exists('socket_strerror') ? \socket_strerror($errno) : 'Socket is connected';
  122. throw new \RuntimeException(
  123. 'Failed to listen on FD ' . $fd . ': ' . $errstr . ' (EISCONN)',
  124. $errno
  125. );
  126. }
  127. // Assume this is a Unix domain socket (UDS) when its listening address doesn't parse as a valid URL with a port.
  128. // Looks like this work-around is the closest we can get because PHP doesn't expose SO_DOMAIN even with ext-sockets.
  129. $this->unix = \parse_url($this->getAddress(), \PHP_URL_PORT) === false;
  130. \stream_set_blocking($this->master, false);
  131. $this->resume();
  132. }
  133. public function getAddress()
  134. {
  135. if (!\is_resource($this->master)) {
  136. return null;
  137. }
  138. $address = \stream_socket_get_name($this->master, false);
  139. if ($this->unix === true) {
  140. return 'unix://' . $address;
  141. }
  142. // check if this is an IPv6 address which includes multiple colons but no square brackets
  143. $pos = \strrpos($address, ':');
  144. if ($pos !== false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') {
  145. $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); // @codeCoverageIgnore
  146. }
  147. return 'tcp://' . $address;
  148. }
  149. public function pause()
  150. {
  151. if (!$this->listening) {
  152. return;
  153. }
  154. $this->loop->removeReadStream($this->master);
  155. $this->listening = false;
  156. }
  157. public function resume()
  158. {
  159. if ($this->listening || !\is_resource($this->master)) {
  160. return;
  161. }
  162. $that = $this;
  163. $this->loop->addReadStream($this->master, function ($master) use ($that) {
  164. try {
  165. $newSocket = SocketServer::accept($master);
  166. } catch (\RuntimeException $e) {
  167. $that->emit('error', array($e));
  168. return;
  169. }
  170. $that->handleConnection($newSocket);
  171. });
  172. $this->listening = true;
  173. }
  174. public function close()
  175. {
  176. if (!\is_resource($this->master)) {
  177. return;
  178. }
  179. $this->pause();
  180. \fclose($this->master);
  181. $this->removeAllListeners();
  182. }
  183. /** @internal */
  184. public function handleConnection($socket)
  185. {
  186. $connection = new Connection($socket, $this->loop);
  187. $connection->unix = $this->unix;
  188. $this->emit('connection', array($connection));
  189. }
  190. }