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
use std::{
io,
mem,
net::SocketAddr,
sync::{Arc, Mutex},
};
use tokio::net::UdpSocket;
use futures::{try_ready, Async, Future, Poll, Stream};
pub mod dns;
pub mod local;
pub mod server;
mod crypto_io;
pub const MAXIMUM_UDP_PAYLOAD_SIZE: usize = 65536;
type SharedUdpSocket = Arc<Mutex<UdpSocket>>;
pub struct PacketStream {
udp: SharedUdpSocket,
buf: [u8; MAXIMUM_UDP_PAYLOAD_SIZE],
}
impl PacketStream {
pub fn new(udp: SharedUdpSocket) -> PacketStream {
PacketStream {
udp,
buf: [0u8; MAXIMUM_UDP_PAYLOAD_SIZE],
}
}
}
impl Stream for PacketStream {
type Error = io::Error;
type Item = (Vec<u8>, SocketAddr);
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let (n, addr) = try_ready!(self.udp.lock().unwrap().poll_recv_from(&mut self.buf));
Ok(Async::Ready(Some((self.buf[..n].to_vec(), addr))))
}
}
enum SendDgramStat<B: AsRef<[u8]>> {
Pending {
udp: SharedUdpSocket,
buf: B,
addr: SocketAddr,
},
Empty,
}
pub struct SendDgramRc<B: AsRef<[u8]>> {
stat: SendDgramStat<B>,
}
impl<B: AsRef<[u8]>> SendDgramRc<B> {
pub fn new(udp: SharedUdpSocket, buf: B, addr: SocketAddr) -> SendDgramRc<B> {
SendDgramRc {
stat: SendDgramStat::Pending { udp, buf, addr },
}
}
}
impl<B: AsRef<[u8]>> Future for SendDgramRc<B> {
type Error = io::Error;
type Item = (SharedUdpSocket, usize, B);
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let n = match self.stat {
SendDgramStat::Pending {
ref udp,
ref buf,
ref addr,
} => try_ready!(udp.lock().unwrap().poll_send_to(buf.as_ref(), addr)),
SendDgramStat::Empty => unreachable!(),
};
match mem::replace(&mut self.stat, SendDgramStat::Empty) {
SendDgramStat::Pending { udp, buf, .. } => Ok(Async::Ready((udp, n, buf))),
SendDgramStat::Empty => unreachable!(),
}
}
}