Connector.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. <?php
  2. namespace React\Socket;
  3. use React\Dns\Config\Config as DnsConfig;
  4. use React\Dns\Resolver\Factory as DnsFactory;
  5. use React\Dns\Resolver\ResolverInterface;
  6. use React\EventLoop\LoopInterface;
  7. /**
  8. * The `Connector` class is the main class in this package that implements the
  9. * `ConnectorInterface` and allows you to create streaming connections.
  10. *
  11. * You can use this connector to create any kind of streaming connections, such
  12. * as plaintext TCP/IP, secure TLS or local Unix connection streams.
  13. *
  14. * Under the hood, the `Connector` is implemented as a *higher-level facade*
  15. * for the lower-level connectors implemented in this package. This means it
  16. * also shares all of their features and implementation details.
  17. * If you want to typehint in your higher-level protocol implementation, you SHOULD
  18. * use the generic [`ConnectorInterface`](#connectorinterface) instead.
  19. *
  20. * @see ConnectorInterface for the base interface
  21. */
  22. final class Connector implements ConnectorInterface
  23. {
  24. private $connectors = array();
  25. /**
  26. * Instantiate new `Connector`
  27. *
  28. * ```php
  29. * $connector = new React\Socket\Connector();
  30. * ```
  31. *
  32. * This class takes two optional arguments for more advanced usage:
  33. *
  34. * ```php
  35. * // constructor signature as of v1.9.0
  36. * $connector = new React\Socket\Connector(array $context = [], ?LoopInterface $loop = null);
  37. *
  38. * // legacy constructor signature before v1.9.0
  39. * $connector = new React\Socket\Connector(?LoopInterface $loop = null, array $context = []);
  40. * ```
  41. *
  42. * This class takes an optional `LoopInterface|null $loop` parameter that can be used to
  43. * pass the event loop instance to use for this object. You can use a `null` value
  44. * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
  45. * This value SHOULD NOT be given unless you're sure you want to explicitly use a
  46. * given event loop instance.
  47. *
  48. * @param array|LoopInterface|null $context
  49. * @param null|LoopInterface|array $loop
  50. * @throws \InvalidArgumentException for invalid arguments
  51. */
  52. public function __construct($context = array(), $loop = null)
  53. {
  54. // swap arguments for legacy constructor signature
  55. if (($context instanceof LoopInterface || $context === null) && (\func_num_args() <= 1 || \is_array($loop))) {
  56. $swap = $loop === null ? array(): $loop;
  57. $loop = $context;
  58. $context = $swap;
  59. }
  60. if (!\is_array($context) || ($loop !== null && !$loop instanceof LoopInterface)) {
  61. throw new \InvalidArgumentException('Expected "array $context" and "?LoopInterface $loop" arguments');
  62. }
  63. // apply default options if not explicitly given
  64. $context += array(
  65. 'tcp' => true,
  66. 'tls' => true,
  67. 'unix' => true,
  68. 'dns' => true,
  69. 'timeout' => true,
  70. 'happy_eyeballs' => true,
  71. );
  72. if ($context['timeout'] === true) {
  73. $context['timeout'] = (float)\ini_get("default_socket_timeout");
  74. }
  75. if ($context['tcp'] instanceof ConnectorInterface) {
  76. $tcp = $context['tcp'];
  77. } else {
  78. $tcp = new TcpConnector(
  79. $loop,
  80. \is_array($context['tcp']) ? $context['tcp'] : array()
  81. );
  82. }
  83. if ($context['dns'] !== false) {
  84. if ($context['dns'] instanceof ResolverInterface) {
  85. $resolver = $context['dns'];
  86. } else {
  87. if ($context['dns'] !== true) {
  88. $config = $context['dns'];
  89. } else {
  90. // try to load nameservers from system config or default to Google's public DNS
  91. $config = DnsConfig::loadSystemConfigBlocking();
  92. if (!$config->nameservers) {
  93. $config->nameservers[] = '8.8.8.8'; // @codeCoverageIgnore
  94. }
  95. }
  96. $factory = new DnsFactory();
  97. $resolver = $factory->createCached(
  98. $config,
  99. $loop
  100. );
  101. }
  102. if ($context['happy_eyeballs'] === true) {
  103. $tcp = new HappyEyeBallsConnector($loop, $tcp, $resolver);
  104. } else {
  105. $tcp = new DnsConnector($tcp, $resolver);
  106. }
  107. }
  108. if ($context['tcp'] !== false) {
  109. $context['tcp'] = $tcp;
  110. if ($context['timeout'] !== false) {
  111. $context['tcp'] = new TimeoutConnector(
  112. $context['tcp'],
  113. $context['timeout'],
  114. $loop
  115. );
  116. }
  117. $this->connectors['tcp'] = $context['tcp'];
  118. }
  119. if ($context['tls'] !== false) {
  120. if (!$context['tls'] instanceof ConnectorInterface) {
  121. $context['tls'] = new SecureConnector(
  122. $tcp,
  123. $loop,
  124. \is_array($context['tls']) ? $context['tls'] : array()
  125. );
  126. }
  127. if ($context['timeout'] !== false) {
  128. $context['tls'] = new TimeoutConnector(
  129. $context['tls'],
  130. $context['timeout'],
  131. $loop
  132. );
  133. }
  134. $this->connectors['tls'] = $context['tls'];
  135. }
  136. if ($context['unix'] !== false) {
  137. if (!$context['unix'] instanceof ConnectorInterface) {
  138. $context['unix'] = new UnixConnector($loop);
  139. }
  140. $this->connectors['unix'] = $context['unix'];
  141. }
  142. }
  143. public function connect($uri)
  144. {
  145. $scheme = 'tcp';
  146. if (\strpos($uri, '://') !== false) {
  147. $scheme = (string)\substr($uri, 0, \strpos($uri, '://'));
  148. }
  149. if (!isset($this->connectors[$scheme])) {
  150. return \React\Promise\reject(new \RuntimeException(
  151. 'No connector available for URI scheme "' . $scheme . '" (EINVAL)',
  152. \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)
  153. ));
  154. }
  155. return $this->connectors[$scheme]->connect($uri);
  156. }
  157. /**
  158. * [internal] Builds on URI from the given URI parts and ip address with original hostname as query
  159. *
  160. * @param array $parts
  161. * @param string $host
  162. * @param string $ip
  163. * @return string
  164. * @internal
  165. */
  166. public static function uri(array $parts, $host, $ip)
  167. {
  168. $uri = '';
  169. // prepend original scheme if known
  170. if (isset($parts['scheme'])) {
  171. $uri .= $parts['scheme'] . '://';
  172. }
  173. if (\strpos($ip, ':') !== false) {
  174. // enclose IPv6 addresses in square brackets before appending port
  175. $uri .= '[' . $ip . ']';
  176. } else {
  177. $uri .= $ip;
  178. }
  179. // append original port if known
  180. if (isset($parts['port'])) {
  181. $uri .= ':' . $parts['port'];
  182. }
  183. // append orignal path if known
  184. if (isset($parts['path'])) {
  185. $uri .= $parts['path'];
  186. }
  187. // append original query if known
  188. if (isset($parts['query'])) {
  189. $uri .= '?' . $parts['query'];
  190. }
  191. // append original hostname as query if resolved via DNS and if
  192. // destination URI does not contain "hostname" query param already
  193. $args = array();
  194. \parse_str(isset($parts['query']) ? $parts['query'] : '', $args);
  195. if ($host !== $ip && !isset($args['hostname'])) {
  196. $uri .= (isset($parts['query']) ? '&' : '?') . 'hostname=' . \rawurlencode($host);
  197. }
  198. // append original fragment if known
  199. if (isset($parts['fragment'])) {
  200. $uri .= '#' . $parts['fragment'];
  201. }
  202. return $uri;
  203. }
  204. }