1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use std::io;
use std::mem;
use std::net::SocketAddr;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use async_trait::async_trait;
use futures_io::{AsyncRead, AsyncWrite};
use futures_util::stream::Stream;
use futures_util::{self, future::Future, ready, FutureExt};
use tracing::debug;
use crate::error::*;
use crate::xfer::{SerialMessage, StreamReceiver};
use crate::BufDnsStreamHandle;
use crate::Time;
pub trait DnsTcpStream: AsyncRead + AsyncWrite + Unpin + Send + Sync + Sized + 'static {
type Time: Time;
}
#[async_trait]
pub trait Connect: DnsTcpStream {
async fn connect(addr: SocketAddr) -> io::Result<Self> {
Self::connect_with_bind(addr, None).await
}
async fn connect_with_bind(addr: SocketAddr, bind_addr: Option<SocketAddr>)
-> io::Result<Self>;
}
enum WriteTcpState {
LenBytes {
pos: usize,
length: [u8; 2],
bytes: Vec<u8>,
},
Bytes {
pos: usize,
bytes: Vec<u8>,
},
Flushing,
}
pub(crate) enum ReadTcpState {
LenBytes {
pos: usize,
bytes: [u8; 2],
},
Bytes {
pos: usize,
bytes: Vec<u8>,
},
}
#[must_use = "futures do nothing unless polled"]
pub struct TcpStream<S: DnsTcpStream> {
socket: S,
outbound_messages: StreamReceiver,
send_state: Option<WriteTcpState>,
read_state: ReadTcpState,
peer_addr: SocketAddr,
}
impl<S: Connect> TcpStream<S> {
#[allow(clippy::new_ret_no_self, clippy::type_complexity)]
pub fn new<E>(
name_server: SocketAddr,
) -> (
impl Future<Output = Result<Self, io::Error>> + Send,
BufDnsStreamHandle,
)
where
E: FromProtoError,
{
Self::with_timeout(name_server, Duration::from_secs(5))
}
#[allow(clippy::type_complexity)]
pub fn with_timeout(
name_server: SocketAddr,
timeout: Duration,
) -> (
impl Future<Output = Result<Self, io::Error>> + Send,
BufDnsStreamHandle,
) {
let (message_sender, outbound_messages) = BufDnsStreamHandle::new(name_server);
let stream_fut = Self::connect(name_server, None, timeout, outbound_messages);
(stream_fut, message_sender)
}
#[allow(clippy::type_complexity)]
pub fn with_bind_addr_and_timeout(
name_server: SocketAddr,
bind_addr: Option<SocketAddr>,
timeout: Duration,
) -> (
impl Future<Output = Result<Self, io::Error>> + Send,
BufDnsStreamHandle,
) {
let (message_sender, outbound_messages) = BufDnsStreamHandle::new(name_server);
let stream_fut = Self::connect(name_server, bind_addr, timeout, outbound_messages);
(stream_fut, message_sender)
}
async fn connect(
name_server: SocketAddr,
bind_addr: Option<SocketAddr>,
timeout: Duration,
outbound_messages: StreamReceiver,
) -> Result<Self, io::Error> {
let tcp = S::connect_with_bind(name_server, bind_addr);
S::Time::timeout(timeout, tcp)
.map(move |tcp_stream: Result<Result<S, io::Error>, _>| {
tcp_stream
.and_then(|tcp_stream| tcp_stream)
.map(|tcp_stream| {
debug!("TCP connection established to: {}", name_server);
Self {
socket: tcp_stream,
outbound_messages,
send_state: None,
read_state: ReadTcpState::LenBytes {
pos: 0,
bytes: [0u8; 2],
},
peer_addr: name_server,
}
})
})
.await
}
}
impl<S: DnsTcpStream> TcpStream<S> {
pub fn peer_addr(&self) -> SocketAddr {
self.peer_addr
}
fn pollable_split(
&mut self,
) -> (
&mut S,
&mut StreamReceiver,
&mut Option<WriteTcpState>,
&mut ReadTcpState,
) {
(
&mut self.socket,
&mut self.outbound_messages,
&mut self.send_state,
&mut self.read_state,
)
}
pub fn from_stream(stream: S, peer_addr: SocketAddr) -> (Self, BufDnsStreamHandle) {
let (message_sender, outbound_messages) = BufDnsStreamHandle::new(peer_addr);
let stream = Self::from_stream_with_receiver(stream, peer_addr, outbound_messages);
(stream, message_sender)
}
pub fn from_stream_with_receiver(
socket: S,
peer_addr: SocketAddr,
outbound_messages: StreamReceiver,
) -> Self {
Self {
socket,
outbound_messages,
send_state: None,
read_state: ReadTcpState::LenBytes {
pos: 0,
bytes: [0u8; 2],
},
peer_addr,
}
}
}
impl<S: DnsTcpStream> Stream for TcpStream<S> {
type Item = io::Result<SerialMessage>;
#[allow(clippy::cognitive_complexity)]
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let peer = self.peer_addr;
let (socket, outbound_messages, send_state, read_state) = self.pollable_split();
let mut socket = Pin::new(socket);
let mut outbound_messages = Pin::new(outbound_messages);
loop {
if send_state.is_some() {
match send_state {
Some(WriteTcpState::LenBytes {
ref mut pos,
ref length,
..
}) => {
let wrote = ready!(socket.as_mut().poll_write(cx, &length[*pos..]))?;
*pos += wrote;
}
Some(WriteTcpState::Bytes {
ref mut pos,
ref bytes,
}) => {
let wrote = ready!(socket.as_mut().poll_write(cx, &bytes[*pos..]))?;
*pos += wrote;
}
Some(WriteTcpState::Flushing) => {
ready!(socket.as_mut().poll_flush(cx))?;
}
_ => (),
}
let current_state = send_state.take();
match current_state {
Some(WriteTcpState::LenBytes { pos, length, bytes }) => {
if pos < length.len() {
*send_state = Some(WriteTcpState::LenBytes { pos, length, bytes });
} else {
*send_state = Some(WriteTcpState::Bytes { pos: 0, bytes });
}
}
Some(WriteTcpState::Bytes { pos, bytes }) => {
if pos < bytes.len() {
*send_state = Some(WriteTcpState::Bytes { pos, bytes });
} else {
*send_state = Some(WriteTcpState::Flushing);
}
}
Some(WriteTcpState::Flushing) => {
send_state.take();
}
None => (),
};
} else {
match outbound_messages.as_mut().poll_next(cx)
{
Poll::Ready(Some(message)) => {
let (buffer, dst) = message.into();
if peer != dst {
return Poll::Ready(Some(Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("mismatched peer: {} and dst: {}", peer, dst),
))));
}
let len = u16::to_be_bytes(buffer.len() as u16);
debug!("sending message len: {} to: {}", buffer.len(), dst);
*send_state = Some(WriteTcpState::LenBytes {
pos: 0,
length: len,
bytes: buffer,
});
}
Poll::Pending => break,
Poll::Ready(None) => {
debug!("no messages to send");
break;
}
}
}
}
let mut ret_buf: Option<Vec<u8>> = None;
while ret_buf.is_none() {
let new_state: Option<ReadTcpState> = match read_state {
ReadTcpState::LenBytes {
ref mut pos,
ref mut bytes,
} => {
let read = ready!(socket.as_mut().poll_read(cx, &mut bytes[*pos..]))?;
if read == 0 {
debug!("zero bytes read, stream closed?");
if *pos == 0 {
return Poll::Ready(None);
} else {
return Poll::Ready(Some(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"closed while reading length",
))));
}
}
debug!("in ReadTcpState::LenBytes: {}", pos);
*pos += read;
if *pos < bytes.len() {
debug!("remain ReadTcpState::LenBytes: {}", pos);
None
} else {
let length = u16::from_be_bytes(*bytes);
debug!("got length: {}", length);
let mut bytes = vec![0; length as usize];
bytes.resize(length as usize, 0);
debug!("move ReadTcpState::Bytes: {}", bytes.len());
Some(ReadTcpState::Bytes { pos: 0, bytes })
}
}
ReadTcpState::Bytes {
ref mut pos,
ref mut bytes,
} => {
let read = ready!(socket.as_mut().poll_read(cx, &mut bytes[*pos..]))?;
if read == 0 {
debug!("zero bytes read for message, stream closed?");
return Poll::Ready(Some(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"closed while reading message",
))));
}
debug!("in ReadTcpState::Bytes: {}", bytes.len());
*pos += read;
if *pos < bytes.len() {
debug!("remain ReadTcpState::Bytes: {}", bytes.len());
None
} else {
debug!("reset ReadTcpState::LenBytes: {}", 0);
Some(ReadTcpState::LenBytes {
pos: 0,
bytes: [0u8; 2],
})
}
}
};
if let Some(state) = new_state {
if let ReadTcpState::Bytes { pos, bytes } = mem::replace(read_state, state) {
debug!("returning bytes");
assert_eq!(pos, bytes.len());
ret_buf = Some(bytes);
}
}
}
if let Some(buffer) = ret_buf {
debug!("returning buffer");
let src_addr = self.peer_addr;
Poll::Ready(Some(Ok(SerialMessage::new(buffer, src_addr))))
} else {
debug!("bottomed out");
Poll::Pending
}
}
}
#[cfg(test)]
#[cfg(feature = "tokio-runtime")]
mod tests {
#[cfg(not(target_os = "linux"))]
use std::net::Ipv6Addr;
use std::net::{IpAddr, Ipv4Addr};
use tokio::net::TcpStream as TokioTcpStream;
use tokio::runtime::Runtime;
use crate::iocompat::AsyncIoTokioAsStd;
use crate::TokioTime;
use crate::tests::tcp_stream_test;
#[test]
fn test_tcp_stream_ipv4() {
let io_loop = Runtime::new().expect("failed to create tokio runtime");
tcp_stream_test::<AsyncIoTokioAsStd<TokioTcpStream>, Runtime, TokioTime>(
IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
io_loop,
)
}
#[test]
#[cfg(not(target_os = "linux"))] fn test_tcp_stream_ipv6() {
let io_loop = Runtime::new().expect("failed to create tokio runtime");
tcp_stream_test::<AsyncIoTokioAsStd<TokioTcpStream>, Runtime, TokioTime>(
IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
io_loop,
)
}
}