Debian Codegraph @

vendor/react/dns/src/Query/UdpTransportExecutor.php

raw
1 <?php
2
3 namespace React\Dns\Query;
4
5 use React\Dns\Model\Message;
6 use React\Dns\Protocol\BinaryDumper;
7 use React\Dns\Protocol\Parser;
8 use React\EventLoop\Loop;
9 use React\EventLoop\LoopInterface;
10 use React\Promise\Deferred;
11
12 /**
13 * Send DNS queries over a UDP transport.
14 *
15 * This is the main class that sends a DNS query to your DNS server and is used
16 * internally by the `Resolver` for the actual message transport.
17 *
18 * For more advanced usages one can utilize this class directly.
19 * The following example looks up the `IPv6` address for `igor.io`.
20 *
21 * ```php
22 * $executor = new UdpTransportExecutor('8.8.8.8:53');
23 *
24 * $executor->query(
25 * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN)
26 * )->then(function (Message $message) {
27 * foreach ($message->answers as $answer) {
28 * echo 'IPv6: ' . $answer->data . PHP_EOL;
29 * }
30 * }, 'printf');
31 * ```
32 *
33 * See also the [fourth example](examples).
34 *
35 * Note that this executor does not implement a timeout, so you will very likely
36 * want to use this in combination with a `TimeoutExecutor` like this:
37 *
38 * ```php
39 * $executor = new TimeoutExecutor(
40 * new UdpTransportExecutor($nameserver),
41 * 3.0
42 * );
43 * ```
44 *
45 * Also note that this executor uses an unreliable UDP transport and that it
46 * does not implement any retry logic, so you will likely want to use this in
47 * combination with a `RetryExecutor` like this:
48 *
49 * ```php
50 * $executor = new RetryExecutor(
51 * new TimeoutExecutor(
52 * new UdpTransportExecutor($nameserver),
53 * 3.0
54 * )
55 * );
56 * ```
57 *
58 * Note that this executor is entirely async and as such allows you to execute
59 * any number of queries concurrently. You should probably limit the number of
60 * concurrent queries in your application or you're very likely going to face
61 * rate limitations and bans on the resolver end. For many common applications,
62 * you may want to avoid sending the same query multiple times when the first
63 * one is still pending, so you will likely want to use this in combination with
64 * a `CoopExecutor` like this:
65 *
66 * ```php
67 * $executor = new CoopExecutor(
68 * new RetryExecutor(
69 * new TimeoutExecutor(
70 * new UdpTransportExecutor($nameserver),
71 * 3.0
72 * )
73 * )
74 * );
75 * ```
76 *
77 * > Internally, this class uses PHP's UDP sockets and does not take advantage
78 * of [react/datagram](https://github.com/reactphp/datagram) purely for
79 * organizational reasons to avoid a cyclic dependency between the two
80 * packages. Higher-level components should take advantage of the Datagram
81 * component instead of reimplementing this socket logic from scratch.
82 */
83 final class UdpTransportExecutor implements ExecutorInterface
84 {
85 private $nameserver;
86 private $loop;
87 private $parser;
88 private $dumper;
89
90 /**
91 * maximum UDP packet size to send and receive
92 *
93 * @var int
94 */
95 private $maxPacketSize = 512;
96
97 /**
98 * @param string $nameserver
99 * @param ?LoopInterface $loop
100 */
101 public function __construct($nameserver, $loop = null)
102 {
103 if (\strpos($nameserver, '[') === false && \substr_count($nameserver, ':') >= 2 && \strpos($nameserver, '://') === false) {
104 // several colons, but not enclosed in square brackets => enclose IPv6 address in square brackets
105 $nameserver = '[' . $nameserver . ']';
106 }
107
108 $parts = \parse_url((\strpos($nameserver, '://') === false ? 'udp://' : '') . $nameserver);
109 if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'udp' || @\inet_pton(\trim($parts['host'], '[]')) === false) {
110 throw new \InvalidArgumentException('Invalid nameserver address given');
111 }
112
113 if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1
114 throw new \InvalidArgumentException('Argument #2 ($loop) expected null|React\EventLoop\LoopInterface');
115 }
116
117 $this->nameserver = 'udp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 53);
118 $this->loop = $loop ?: Loop::get();
119 $this->parser = new Parser();
120 $this->dumper = new BinaryDumper();
121 }
122
123 public function query(Query $query)
124 {
125 $request = Message::createRequestForQuery($query);
126
127 $queryData = $this->dumper->toBinary($request);
128 if (isset($queryData[$this->maxPacketSize])) {
129 return \React\Promise\reject(new \RuntimeException(
130 'DNS query for ' . $query->describe() . ' failed: Query too large for UDP transport',
131 \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90
132 ));
133 }
134
135 // UDP connections are instant, so try connection without a loop or timeout
136 $errno = 0;
137 $errstr = '';
138 $socket = @\stream_socket_client($this->nameserver, $errno, $errstr, 0);
139 if ($socket === false) {
140 return \React\Promise\reject(new \RuntimeException(
141 'DNS query for ' . $query->describe() . ' failed: Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')',
142 $errno
143 ));
144 }
145
146 // set socket to non-blocking and immediately try to send (fill write buffer)
147 \stream_set_blocking($socket, false);
148
149 \set_error_handler(function ($_, $error) use (&$errno, &$errstr) {
150 // Write may potentially fail, but most common errors are already caught by connection check above.
151 // Among others, macOS is known to report here when trying to send to broadcast address.
152 // This can also be reproduced by writing data exceeding `stream_set_chunk_size()` to a server refusing UDP data.
153 // fwrite(): send of 8192 bytes failed with errno=111 Connection refused
154 \preg_match('/errno=(\d+) (.+)/', $error, $m);
155 $errno = isset($m[1]) ? (int) $m[1] : 0;
156 $errstr = isset($m[2]) ? $m[2] : $error;
157 });
158
159 $written = \fwrite($socket, $queryData);
160
161 \restore_error_handler();
162
163 if ($written !== \strlen($queryData)) {
164 return \React\Promise\reject(new \RuntimeException(
165 'DNS query for ' . $query->describe() . ' failed: Unable to send query to DNS server ' . $this->nameserver . ' (' . $errstr . ')',
166 $errno
167 ));
168 }
169
170 $loop = $this->loop;
171 $deferred = new Deferred(function () use ($loop, $socket, $query) {
172 // cancellation should remove socket from loop and close socket
173 $loop->removeReadStream($socket);
174 \fclose($socket);
175
176 throw new CancellationException('DNS query for ' . $query->describe() . ' has been cancelled');
177 });
178
179 $max = $this->maxPacketSize;
180 $parser = $this->parser;
181 $nameserver = $this->nameserver;
182 $loop->addReadStream($socket, function ($socket) use ($loop, $deferred, $query, $parser, $request, $max, $nameserver) {
183 // try to read a single data packet from the DNS server
184 // ignoring any errors, this is uses UDP packets and not a stream of data
185 $data = @\fread($socket, $max);
186 if ($data === false) {
187 return;
188 }
189
190 try {
191 $response = $parser->parseMessage($data);
192 } catch (\Exception $e) {
193 // ignore and await next if we received an invalid message from remote server
194 // this may as well be a fake response from an attacker (possible DOS)
195 return;
196 }
197
198 // ignore and await next if we received an unexpected response ID
199 // this may as well be a fake response from an attacker (possible cache poisoning)
200 if ($response->id !== $request->id) {
201 return;
202 }
203
204 // we only react to the first valid message, so remove socket from loop and close
205 $loop->removeReadStream($socket);
206 \fclose($socket);
207
208 if ($response->tc) {
209 $deferred->reject(new \RuntimeException(
210 'DNS query for ' . $query->describe() . ' failed: The DNS server ' . $nameserver . ' returned a truncated result for a UDP query',
211 \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90
212 ));
213 return;
214 }
215
216 $deferred->resolve($response);
217 });
218
219 return $deferred->promise();
220 }
221 }