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
use std::{
self,
net::{Ipv4Addr, SocketAddr, SocketAddrV4, ToSocketAddrs, UdpSocket},
thread::{sleep, yield_now},
time::{Duration, Instant},
};
use crossbeam_channel::{self, Receiver, Sender, TryRecvError};
use crate::{
config::Config,
error::Result,
net::{
events::SocketEvent, ConnectionManager, DatagramSocket, LinkConditioner, VirtualConnection,
},
packet::Packet,
};
#[derive(Debug)]
struct SocketWithConditioner {
is_blocking_mode: bool,
socket: UdpSocket,
link_conditioner: Option<LinkConditioner>,
}
impl SocketWithConditioner {
pub fn new(socket: UdpSocket, is_blocking_mode: bool) -> Result<Self> {
socket.set_nonblocking(!is_blocking_mode)?;
Ok(SocketWithConditioner {
is_blocking_mode,
socket,
link_conditioner: None,
})
}
#[cfg(feature = "tester")]
pub fn set_link_conditioner(&mut self, link_conditioner: Option<LinkConditioner>) {
self.link_conditioner = link_conditioner;
}
}
impl DatagramSocket for SocketWithConditioner {
fn send_packet(&mut self, addr: &SocketAddr, payload: &[u8]) -> std::io::Result<usize> {
if cfg!(feature = "tester") {
if let Some(ref mut link) = &mut self.link_conditioner {
if !link.should_send() {
return Ok(0);
}
}
}
self.socket.send_to(payload, addr)
}
fn receive_packet<'a>(
&mut self,
buffer: &'a mut [u8],
) -> std::io::Result<(&'a [u8], SocketAddr)> {
self.socket
.recv_from(buffer)
.map(move |(recv_len, address)| (&buffer[..recv_len], address))
}
fn local_addr(&self) -> std::io::Result<SocketAddr> {
self.socket.local_addr()
}
fn is_blocking_mode(&self) -> bool {
self.is_blocking_mode
}
}
#[derive(Debug)]
pub struct Socket {
handler: ConnectionManager<SocketWithConditioner, VirtualConnection>,
}
impl Socket {
pub fn bind<A: ToSocketAddrs>(addresses: A) -> Result<Self> {
Self::bind_with_config(addresses, Config::default())
}
pub fn bind_any() -> Result<Self> {
Self::bind_any_with_config(Config::default())
}
pub fn bind_any_with_config(config: Config) -> Result<Self> {
let loopback = Ipv4Addr::new(127, 0, 0, 1);
let address = SocketAddrV4::new(loopback, 0);
let socket = UdpSocket::bind(address)?;
Self::bind_internal(socket, config)
}
pub fn bind_with_config<A: ToSocketAddrs>(addresses: A, config: Config) -> Result<Self> {
let socket = UdpSocket::bind(addresses)?;
Self::bind_internal(socket, config)
}
fn bind_internal(socket: UdpSocket, config: Config) -> Result<Self> {
Ok(Socket {
handler: ConnectionManager::new(
SocketWithConditioner::new(socket, config.blocking_mode)?,
config,
),
})
}
pub fn get_packet_sender(&self) -> Sender<Packet> {
self.handler.event_sender().clone()
}
pub fn get_event_receiver(&self) -> Receiver<SocketEvent> {
self.handler.event_receiver().clone()
}
pub fn send(&mut self, packet: Packet) -> Result<()> {
self.handler
.event_sender()
.send(packet)
.expect("Receiver must exists.");
Ok(())
}
pub fn recv(&mut self) -> Option<SocketEvent> {
match self.handler.event_receiver().try_recv() {
Ok(pkt) => Some(pkt),
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Disconnected) => panic!["This can never happen"],
}
}
pub fn start_polling(&mut self) {
self.start_polling_with_duration(Some(Duration::from_millis(1)))
}
pub fn start_polling_with_duration(&mut self, sleep_duration: Option<Duration>) {
loop {
self.manual_poll(Instant::now());
match sleep_duration {
None => yield_now(),
Some(duration) => sleep(duration),
};
}
}
pub fn manual_poll(&mut self, time: Instant) {
self.handler.manual_poll(time);
}
pub fn local_addr(&self) -> Result<SocketAddr> {
Ok(self.handler.socket().local_addr()?)
}
#[cfg(feature = "tester")]
pub fn set_link_conditioner(&mut self, link_conditioner: Option<LinkConditioner>) {
self.handler
.socket_mut()
.set_link_conditioner(link_conditioner);
}
}