Subversion Repositories php-qbpwcf

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 liveuser 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\LoopInterface;
9
use React\Promise\Deferred;
10
 
11
/**
12
 * Send DNS queries over a TCP/IP stream transport.
13
 *
14
 * This is one of the main classes that send a DNS query to your DNS server.
15
 *
16
 * For more advanced usages one can utilize this class directly.
17
 * The following example looks up the `IPv6` address for `reactphp.org`.
18
 *
19
 * ```php
20
 * $loop = Factory::create();
21
 * $executor = new TcpTransportExecutor('8.8.8.8:53', $loop);
22
 *
23
 * $executor->query(
24
 *     new Query($name, Message::TYPE_AAAA, Message::CLASS_IN)
25
 * )->then(function (Message $message) {
26
 *     foreach ($message->answers as $answer) {
27
 *         echo 'IPv6: ' . $answer->data . PHP_EOL;
28
 *     }
29
 * }, 'printf');
30
 *
31
 * $loop->run();
32
 * ```
33
 *
34
 * See also [example #92](examples).
35
 *
36
 * Note that this executor does not implement a timeout, so you will very likely
37
 * want to use this in combination with a `TimeoutExecutor` like this:
38
 *
39
 * ```php
40
 * $executor = new TimeoutExecutor(
41
 *     new TcpTransportExecutor($nameserver, $loop),
42
 *     3.0,
43
 *     $loop
44
 * );
45
 * ```
46
 *
47
 * Unlike the `UdpTransportExecutor`, this class uses a reliable TCP/IP
48
 * transport, so you do not necessarily have to implement any retry logic.
49
 *
50
 * Note that this executor is entirely async and as such allows you to execute
51
 * queries concurrently. The first query will establish a TCP/IP socket
52
 * connection to the DNS server which will be kept open for a short period.
53
 * Additional queries will automatically reuse this existing socket connection
54
 * to the DNS server, will pipeline multiple requests over this single
55
 * connection and will keep an idle connection open for a short period. The
56
 * initial TCP/IP connection overhead may incur a slight delay if you only send
57
 * occasional queries – when sending a larger number of concurrent queries over
58
 * an existing connection, it becomes increasingly more efficient and avoids
59
 * creating many concurrent sockets like the UDP-based executor. You may still
60
 * want to limit the number of (concurrent) queries in your application or you
61
 * may be facing rate limitations and bans on the resolver end. For many common
62
 * applications, you may want to avoid sending the same query multiple times
63
 * when the first one is still pending, so you will likely want to use this in
64
 * combination with a `CoopExecutor` like this:
65
 *
66
 * ```php
67
 * $executor = new CoopExecutor(
68
 *     new TimeoutExecutor(
69
 *         new TcpTransportExecutor($nameserver, $loop),
70
 *         3.0,
71
 *         $loop
72
 *     )
73
 * );
74
 * ```
75
 *
76
 * > Internally, this class uses PHP's TCP/IP sockets and does not take advantage
77
 *   of [react/socket](https://github.com/reactphp/socket) purely for
78
 *   organizational reasons to avoid a cyclic dependency between the two
79
 *   packages. Higher-level components should take advantage of the Socket
80
 *   component instead of reimplementing this socket logic from scratch.
81
 */
82
class TcpTransportExecutor implements ExecutorInterface
83
{
84
    private $nameserver;
85
    private $loop;
86
    private $parser;
87
    private $dumper;
88
 
89
    /**
90
     * @var ?resource
91
     */
92
    private $socket;
93
 
94
    /**
95
     * @var Deferred[]
96
     */
97
    private $pending = array();
98
 
99
    /**
100
     * @var string[]
101
     */
102
    private $names = array();
103
 
104
    /**
105
     * Maximum idle time when socket is current unused (i.e. no pending queries outstanding)
106
     *
107
     * If a new query is to be sent during the idle period, we can reuse the
108
     * existing socket without having to wait for a new socket connection.
109
     * This uses a rather small, hard-coded value to not keep any unneeded
110
     * sockets open and to not keep the loop busy longer than needed.
111
     *
112
     * A future implementation may take advantage of `edns-tcp-keepalive` to keep
113
     * the socket open for longer periods. This will likely require explicit
114
     * configuration because this may consume additional resources and also keep
115
     * the loop busy for longer than expected in some applications.
116
     *
117
     * @var float
118
     * @link https://tools.ietf.org/html/rfc7766#section-6.2.1
119
     * @link https://tools.ietf.org/html/rfc7828
120
     */
121
    private $idlePeriod = 0.001;
122
 
123
    /**
124
     * @var ?\React\EventLoop\TimerInterface
125
     */
126
    private $idleTimer;
127
 
128
    private $writeBuffer = '';
129
    private $writePending = false;
130
 
131
    private $readBuffer = '';
132
    private $readPending = false;
133
 
134
    /**
135
     * @param string        $nameserver
136
     * @param LoopInterface $loop
137
     */
138
    public function __construct($nameserver, LoopInterface $loop)
139
    {
140
        if (\strpos($nameserver, '[') === false && \substr_count($nameserver, ':') >= 2 && \strpos($nameserver, '://') === false) {
141
            // several colons, but not enclosed in square brackets => enclose IPv6 address in square brackets
142
            $nameserver = '[' . $nameserver . ']';
143
        }
144
 
145
        $parts = \parse_url((\strpos($nameserver, '://') === false ? 'tcp://' : '') . $nameserver);
146
        if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'tcp' || !\filter_var(\trim($parts['host'], '[]'), \FILTER_VALIDATE_IP)) {
147
            throw new \InvalidArgumentException('Invalid nameserver address given');
148
        }
149
 
150
        $this->nameserver = $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 53);
151
        $this->loop = $loop;
152
        $this->parser = new Parser();
153
        $this->dumper = new BinaryDumper();
154
    }
155
 
156
    public function query(Query $query)
157
    {
158
        $request = Message::createRequestForQuery($query);
159
 
160
        // keep shuffing message ID to avoid using the same message ID for two pending queries at the same time
161
        while (isset($this->pending[$request->id])) {
162
            $request->id = \mt_rand(0, 0xffff); // @codeCoverageIgnore
163
        }
164
 
165
        $queryData = $this->dumper->toBinary($request);
166
        $length = \strlen($queryData);
167
        if ($length > 0xffff) {
168
            return \React\Promise\reject(new \RuntimeException(
169
                'DNS query for ' . $query->name . ' failed: Query too large for TCP transport'
170
            ));
171
        }
172
 
173
        $queryData = \pack('n', $length) . $queryData;
174
 
175
        if ($this->socket === null) {
176
            // create async TCP/IP connection (may take a while)
177
            $socket = @\stream_socket_client($this->nameserver, $errno, $errstr, 0, \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT);
178
            if ($socket === false) {
179
                return \React\Promise\reject(new \RuntimeException(
180
                    'DNS query for ' . $query->name . ' failed: Unable to connect to DNS server ('  . $errstr . ')',
181
                    $errno
182
                ));
183
            }
184
 
185
            // set socket to non-blocking and wait for it to become writable (connection success/rejected)
186
            \stream_set_blocking($socket, false);
187
            $this->socket = $socket;
188
        }
189
 
190
        if ($this->idleTimer !== null) {
191
            $this->loop->cancelTimer($this->idleTimer);
192
            $this->idleTimer = null;
193
        }
194
 
195
        // wait for socket to become writable to actually write out data
196
        $this->writeBuffer .= $queryData;
197
        if (!$this->writePending) {
198
            $this->writePending = true;
199
            $this->loop->addWriteStream($this->socket, array($this, 'handleWritable'));
200
        }
201
 
202
        $names =& $this->names;
203
        $that = $this;
204
        $deferred = new Deferred(function () use ($that, &$names, $request) {
205
            // remove from list of pending names, but remember pending query
206
            $name = $names[$request->id];
207
            unset($names[$request->id]);
208
            $that->checkIdle();
209
 
210
            throw new CancellationException('DNS query for ' . $name . ' has been cancelled');
211
        });
212
 
213
        $this->pending[$request->id] = $deferred;
214
        $this->names[$request->id] = $query->name;
215
 
216
        return $deferred->promise();
217
    }
218
 
219
    /**
220
     * @internal
221
     */
222
    public function handleWritable()
223
    {
224
        if ($this->readPending === false) {
225
            $name = @\stream_socket_get_name($this->socket, true);
226
            if ($name === false) {
227
                $this->closeError('Connection to DNS server rejected');
228
                return;
229
            }
230
 
231
            $this->readPending = true;
232
            $this->loop->addReadStream($this->socket, array($this, 'handleRead'));
233
        }
234
 
235
        $written = @\fwrite($this->socket, $this->writeBuffer);
236
        if ($written === false || $written === 0) {
237
            $this->closeError('Unable to write to closed socket');
238
            return;
239
        }
240
 
241
        if (isset($this->writeBuffer[$written])) {
242
            $this->writeBuffer = \substr($this->writeBuffer, $written);
243
        } else {
244
            $this->loop->removeWriteStream($this->socket);
245
            $this->writePending = false;
246
            $this->writeBuffer = '';
247
        }
248
    }
249
 
250
    /**
251
     * @internal
252
     */
253
    public function handleRead()
254
    {
255
        // read one chunk of data from the DNS server
256
        // any error is fatal, this is a stream of TCP/IP data
257
        $chunk = @\fread($this->socket, 65536);
258
        if ($chunk === false || $chunk === '') {
259
            $this->closeError('Connection to DNS server lost');
260
            return;
261
        }
262
 
263
        // reassemble complete message by concatenating all chunks.
264
        $this->readBuffer .= $chunk;
265
 
266
        // response message header contains at least 12 bytes
267
        while (isset($this->readBuffer[11])) {
268
            // read response message length from first 2 bytes and ensure we have length + data in buffer
269
            list(, $length) = \unpack('n', $this->readBuffer);
270
            if (!isset($this->readBuffer[$length + 1])) {
271
                return;
272
            }
273
 
274
            $data = \substr($this->readBuffer, 2, $length);
275
            $this->readBuffer = (string)substr($this->readBuffer, $length + 2);
276
 
277
            try {
278
                $response = $this->parser->parseMessage($data);
279
            } catch (\Exception $e) {
280
                // reject all pending queries if we received an invalid message from remote server
281
                $this->closeError('Invalid message received from DNS server');
282
                return;
283
            }
284
 
285
            // reject all pending queries if we received an unexpected response ID or truncated response
286
            if (!isset($this->pending[$response->id]) || $response->tc) {
287
                $this->closeError('Invalid response message received from DNS server');
288
                return;
289
            }
290
 
291
            $deferred = $this->pending[$response->id];
292
            unset($this->pending[$response->id], $this->names[$response->id]);
293
 
294
            $deferred->resolve($response);
295
 
296
            $this->checkIdle();
297
        }
298
    }
299
 
300
    /**
301
     * @internal
302
     * @param string $reason
303
     */
304
    public function closeError($reason)
305
    {
306
        $this->readBuffer = '';
307
        if ($this->readPending) {
308
            $this->loop->removeReadStream($this->socket);
309
            $this->readPending = false;
310
        }
311
 
312
        $this->writeBuffer = '';
313
        if ($this->writePending) {
314
            $this->loop->removeWriteStream($this->socket);
315
            $this->writePending = false;
316
        }
317
 
318
        if ($this->idleTimer !== null) {
319
            $this->loop->cancelTimer($this->idleTimer);
320
            $this->idleTimer = null;
321
        }
322
 
323
        @\fclose($this->socket);
324
        $this->socket = null;
325
 
326
        foreach ($this->names as $id => $name) {
327
            $this->pending[$id]->reject(new \RuntimeException(
328
                'DNS query for ' . $name . ' failed: ' . $reason
329
            ));
330
        }
331
        $this->pending = $this->names = array();
332
    }
333
 
334
    /**
335
     * @internal
336
     */
337
    public function checkIdle()
338
    {
339
        if ($this->idleTimer === null && !$this->names) {
340
            $that = $this;
341
            $this->idleTimer = $this->loop->addTimer($this->idlePeriod, function () use ($that) {
342
                $that->closeError('Idle timeout');
343
            });
344
        }
345
    }
346
}