UnixServer.php 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. <?php
  2. namespace React\Socket;
  3. use Evenement\EventEmitter;
  4. use React\EventLoop\Loop;
  5. use React\EventLoop\LoopInterface;
  6. use InvalidArgumentException;
  7. use RuntimeException;
  8. /**
  9. * The `UnixServer` class implements the `ServerInterface` and
  10. * is responsible for accepting plaintext connections on unix domain sockets.
  11. *
  12. * ```php
  13. * $server = new React\Socket\UnixServer('unix:///tmp/app.sock');
  14. * ```
  15. *
  16. * See also the `ServerInterface` for more details.
  17. *
  18. * @see ServerInterface
  19. * @see ConnectionInterface
  20. */
  21. final class UnixServer extends EventEmitter implements ServerInterface
  22. {
  23. private $master;
  24. private $loop;
  25. private $listening = false;
  26. /**
  27. * Creates a plaintext socket server and starts listening on the given unix socket
  28. *
  29. * This starts accepting new incoming connections on the given address.
  30. * See also the `connection event` documented in the `ServerInterface`
  31. * for more details.
  32. *
  33. * ```php
  34. * $server = new React\Socket\UnixServer('unix:///tmp/app.sock');
  35. * ```
  36. *
  37. * This class takes an optional `LoopInterface|null $loop` parameter that can be used to
  38. * pass the event loop instance to use for this object. You can use a `null` value
  39. * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
  40. * This value SHOULD NOT be given unless you're sure you want to explicitly use a
  41. * given event loop instance.
  42. *
  43. * @param string $path
  44. * @param ?LoopInterface $loop
  45. * @param array $context
  46. * @throws InvalidArgumentException if the listening address is invalid
  47. * @throws RuntimeException if listening on this address fails (already in use etc.)
  48. */
  49. public function __construct($path, LoopInterface $loop = null, array $context = array())
  50. {
  51. $this->loop = $loop ?: Loop::get();
  52. if (\strpos($path, '://') === false) {
  53. $path = 'unix://' . $path;
  54. } elseif (\substr($path, 0, 7) !== 'unix://') {
  55. throw new \InvalidArgumentException(
  56. 'Given URI "' . $path . '" is invalid (EINVAL)',
  57. \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)
  58. );
  59. }
  60. $errno = 0;
  61. $errstr = '';
  62. \set_error_handler(function ($_, $error) use (&$errno, &$errstr) {
  63. // PHP does not seem to report errno/errstr for Unix domain sockets (UDS) right now.
  64. // This only applies to UDS server sockets, see also https://3v4l.org/NAhpr.
  65. // Parse PHP warning message containing unknown error, HHVM reports proper info at least.
  66. if (\preg_match('/\(([^\)]+)\)|\[(\d+)\]: (.*)/', $error, $match)) {
  67. $errstr = isset($match[3]) ? $match['3'] : $match[1];
  68. $errno = isset($match[2]) ? (int)$match[2] : 0;
  69. }
  70. });
  71. $this->master = \stream_socket_server(
  72. $path,
  73. $errno,
  74. $errstr,
  75. \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN,
  76. \stream_context_create(array('socket' => $context))
  77. );
  78. \restore_error_handler();
  79. if (false === $this->master) {
  80. throw new \RuntimeException(
  81. 'Failed to listen on Unix domain socket "' . $path . '": ' . $errstr . SocketServer::errconst($errno),
  82. $errno
  83. );
  84. }
  85. \stream_set_blocking($this->master, 0);
  86. $this->resume();
  87. }
  88. public function getAddress()
  89. {
  90. if (!\is_resource($this->master)) {
  91. return null;
  92. }
  93. return 'unix://' . \stream_socket_get_name($this->master, false);
  94. }
  95. public function pause()
  96. {
  97. if (!$this->listening) {
  98. return;
  99. }
  100. $this->loop->removeReadStream($this->master);
  101. $this->listening = false;
  102. }
  103. public function resume()
  104. {
  105. if ($this->listening || !is_resource($this->master)) {
  106. return;
  107. }
  108. $that = $this;
  109. $this->loop->addReadStream($this->master, function ($master) use ($that) {
  110. try {
  111. $newSocket = SocketServer::accept($master);
  112. } catch (\RuntimeException $e) {
  113. $that->emit('error', array($e));
  114. return;
  115. }
  116. $that->handleConnection($newSocket);
  117. });
  118. $this->listening = true;
  119. }
  120. public function close()
  121. {
  122. if (!\is_resource($this->master)) {
  123. return;
  124. }
  125. $this->pause();
  126. \fclose($this->master);
  127. $this->removeAllListeners();
  128. }
  129. /** @internal */
  130. public function handleConnection($socket)
  131. {
  132. $connection = new Connection($socket, $this->loop);
  133. $connection->unix = true;
  134. $this->emit('connection', array(
  135. $connection
  136. ));
  137. }
  138. }