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
use std::io;
use std::marker::PhantomData;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::pin::Pin;
use std::task::{Context, Poll};
use async_trait::async_trait;
use futures_util::stream::Stream;
use futures_util::{future::Future, ready, TryFutureExt};
use rand;
use rand::distributions::{uniform::Uniform, Distribution};
use tracing::{debug, warn};
use crate::xfer::{BufDnsStreamHandle, SerialMessage, StreamReceiver};
use crate::Time;
#[async_trait]
pub trait UdpSocket
where
Self: Send + Sync + Sized + Unpin,
{
type Time: Time;
async fn connect(addr: SocketAddr) -> io::Result<Self>;
async fn connect_with_bind(addr: SocketAddr, bind_addr: SocketAddr) -> io::Result<Self>;
async fn bind(addr: SocketAddr) -> io::Result<Self>;
fn poll_recv_from(
&self,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<(usize, SocketAddr)>>;
async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
futures_util::future::poll_fn(|cx| self.poll_recv_from(cx, buf)).await
}
fn poll_send_to(
&self,
cx: &mut Context<'_>,
buf: &[u8],
target: SocketAddr,
) -> Poll<io::Result<usize>>;
async fn send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result<usize> {
futures_util::future::poll_fn(|cx| self.poll_send_to(cx, buf, target)).await
}
}
#[must_use = "futures do nothing unless polled"]
pub struct UdpStream<S: Send> {
socket: S,
outbound_messages: StreamReceiver,
}
impl<S: UdpSocket + Send + 'static> UdpStream<S> {
#[allow(clippy::type_complexity)]
pub fn new(
remote_addr: SocketAddr,
bind_addr: Option<SocketAddr>,
) -> (
Box<dyn Future<Output = Result<Self, io::Error>> + Send + Unpin>,
BufDnsStreamHandle,
) {
let (message_sender, outbound_messages) = BufDnsStreamHandle::new(remote_addr);
let next_socket = NextRandomUdpSocket::new(&remote_addr, &bind_addr);
let stream = Box::new(next_socket.map_ok(move |socket| Self {
socket,
outbound_messages,
}));
(stream, message_sender)
}
pub fn with_bound(socket: S, remote_addr: SocketAddr) -> (Self, BufDnsStreamHandle) {
let (message_sender, outbound_messages) = BufDnsStreamHandle::new(remote_addr);
let stream = Self {
socket,
outbound_messages,
};
(stream, message_sender)
}
#[allow(unused)]
pub(crate) fn from_parts(socket: S, outbound_messages: StreamReceiver) -> Self {
Self {
socket,
outbound_messages,
}
}
}
impl<S: Send> UdpStream<S> {
#[allow(clippy::type_complexity)]
fn pollable_split(&mut self) -> (&mut S, &mut StreamReceiver) {
(&mut self.socket, &mut self.outbound_messages)
}
}
impl<S: UdpSocket + Send + 'static> Stream for UdpStream<S> {
type Item = Result<SerialMessage, io::Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let (socket, outbound_messages) = self.pollable_split();
let socket = Pin::new(socket);
let mut outbound_messages = Pin::new(outbound_messages);
while let Poll::Ready(Some(message)) = outbound_messages.as_mut().poll_peek(cx) {
let addr = message.addr();
if let Err(e) = ready!(socket.poll_send_to(cx, message.bytes(), addr)) {
warn!(
"error sending message to {} on udp_socket, dropping response: {}",
addr, e
);
}
assert!(outbound_messages.as_mut().poll_next(cx).is_ready());
}
let mut buf = [0u8; 4096];
let (len, src) = ready!(socket.poll_recv_from(cx, &mut buf))?;
let serial_message = SerialMessage::new(buf.iter().take(len).cloned().collect(), src);
Poll::Ready(Some(Ok(serial_message)))
}
}
#[must_use = "futures do nothing unless polled"]
pub(crate) struct NextRandomUdpSocket<S> {
bind_address: SocketAddr,
marker: PhantomData<S>,
}
impl<S: UdpSocket> NextRandomUdpSocket<S> {
pub(crate) fn new(name_server: &SocketAddr, bind_addr: &Option<SocketAddr>) -> Self {
let bind_address = match bind_addr {
Some(ba) => *ba,
None => match *name_server {
SocketAddr::V4(..) => SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0),
SocketAddr::V6(..) => {
SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 0)
}
},
};
Self {
bind_address,
marker: PhantomData,
}
}
async fn bind(addr: SocketAddr) -> Result<S, io::Error> {
S::bind(addr).await
}
}
impl<S: UdpSocket> Future for NextRandomUdpSocket<S> {
type Output = Result<S, io::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.bind_address.port() == 0 {
let rand_port_range = Uniform::new_inclusive(49152_u16, u16::max_value());
let mut rand = rand::thread_rng();
for attempt in 0..10 {
let port = rand_port_range.sample(&mut rand);
let bind_addr = SocketAddr::new(self.bind_address.ip(), port);
match Box::pin(Self::bind(bind_addr)).as_mut().poll(cx) {
Poll::Ready(Ok(socket)) => {
debug!("created socket successfully");
return Poll::Ready(Ok(socket));
}
Poll::Ready(Err(err)) => match err.kind() {
io::ErrorKind::AddrInUse => {
debug!("unable to bind port, attempt: {}: {}", attempt, err);
}
_ => {
debug!("failed to bind port: {}", err);
return Poll::Ready(Err(err));
}
},
Poll::Pending => debug!("unable to bind port, attempt: {}", attempt),
}
}
debug!("could not get next random port, delaying");
cx.waker().wake_by_ref();
Poll::Pending
} else {
Box::pin(Self::bind(self.bind_address)).as_mut().poll(cx)
}
}
}
#[cfg(feature = "tokio-runtime")]
#[async_trait]
impl UdpSocket for tokio::net::UdpSocket {
type Time = crate::TokioTime;
async fn connect(addr: SocketAddr) -> io::Result<Self> {
let bind_addr: SocketAddr = match addr {
SocketAddr::V4(_addr) => (Ipv4Addr::UNSPECIFIED, 0).into(),
SocketAddr::V6(_addr) => (Ipv6Addr::UNSPECIFIED, 0).into(),
};
Self::connect_with_bind(addr, bind_addr).await
}
async fn connect_with_bind(_addr: SocketAddr, bind_addr: SocketAddr) -> io::Result<Self> {
let socket = Self::bind(bind_addr).await?;
Ok(socket)
}
async fn bind(addr: SocketAddr) -> io::Result<Self> {
Self::bind(addr).await
}
fn poll_recv_from(
&self,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<(usize, SocketAddr)>> {
let mut buf = tokio::io::ReadBuf::new(buf);
let addr = ready!(Self::poll_recv_from(self, cx, &mut buf))?;
let len = buf.filled().len();
Poll::Ready(Ok((len, addr)))
}
fn poll_send_to(
&self,
cx: &mut Context<'_>,
buf: &[u8],
target: SocketAddr,
) -> Poll<io::Result<usize>> {
Self::poll_send_to(self, cx, buf, target)
}
}
#[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::UdpSocket as TokioUdpSocket, runtime::Runtime};
#[test]
fn test_next_random_socket() {
use crate::tests::next_random_socket_test;
let io_loop = Runtime::new().expect("failed to create tokio runtime");
next_random_socket_test::<TokioUdpSocket, Runtime>(io_loop)
}
#[test]
fn test_udp_stream_ipv4() {
use crate::tests::udp_stream_test;
let io_loop = Runtime::new().expect("failed to create tokio runtime");
io_loop.block_on(udp_stream_test::<TokioUdpSocket>(IpAddr::V4(
Ipv4Addr::new(127, 0, 0, 1),
)));
}
#[test]
#[cfg(not(target_os = "linux"))] fn test_udp_stream_ipv6() {
use crate::tests::udp_stream_test;
let io_loop = Runtime::new().expect("failed to create tokio runtime");
io_loop.block_on(udp_stream_test::<TokioUdpSocket>(IpAddr::V6(
Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1),
)));
}
}