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
use crate::serialization::Packet;
use std::error::Error;
use mio::net::UdpSocket;
use std::thread;
use std::thread::JoinHandle;
use mio::{Poll, Token, Events, Ready, PollOpt};
use crate::configuration::Config;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use std::time::Duration;
use crate::networking::address::Address;
use rayon::scope_fifo;
pub mod address;
create_error!(SocketCreationError, "The socket creation failed");
create_error!(ListenError, "An error occured during the listening");
pub trait Receiver {
fn on_receive(&self, packet: Packet, address: Address);
}
pub struct NetworkSender {
socket: UdpSocket,
}
impl NetworkSender {
pub fn new(sending_address: &Address) -> Result<Self, Box<dyn Error>> {
let socket = UdpSocket::bind(&sending_address.0)?;
debug!("Starting, sending_address: {:?}", sending_address);
Ok(Self { socket })
}
pub fn send(&self, address: &Address, packet: Packet) -> Result<usize, Box<dyn Error>> {
Ok(self.socket.send_to(packet.raw(), &address.0)?)
}
}
pub struct NetworkReceiver {
receivers: Vec<Box<dyn Receiver + Send + Sync>>,
socket: UdpSocket,
}
impl NetworkReceiver {
pub fn new(receiving_address: &Address) -> Result<Self, Box<dyn Error>> {
let socket = UdpSocket::bind(&receiving_address.0)?;
debug!("Starting, receiving_address: {:?}", receiving_address);
let nm = Self {
receivers: vec![],
socket,
};
Ok(nm)
}
pub fn start(self, configuration: &Config) -> JoinHandle<()> {
let queuesize = configuration.queuesize.to_owned();
let buffersize = configuration.buffersize.to_owned();
let pollinterval = configuration.pollinterval.to_owned();
thread::spawn(move || {
self.listen(queuesize, buffersize, pollinterval)
.or_else(|i| {
error!("the listening thread crashed");
Err(i)
})
.unwrap();
})
}
#[doc(hidden)]
fn listen(
self,
queuesize: usize,
buffersize: usize,
pollinterval: Option<Duration>,
) -> Result<(), Box<dyn Error>> {
debug!("IPV8 is starting it's listener!");
let poll = Poll::new()?;
let mut events = Events::with_capacity(queuesize);
let mut tmp_buf = vec![0; buffersize];
let buffer = tmp_buf.as_mut_slice();
const RECEIVER: Token = Token(0);
poll.register(&self.socket, RECEIVER, Ready::readable(), PollOpt::edge())?;
loop {
poll.poll(&mut events, pollinterval)?;
trace!("checking poll");
for _ in events.iter() {
trace!("handling event");
let (recv_size, address) = self.socket.recv_from(buffer)?;
let packet = Packet(buffer[..recv_size].to_vec()).clone();
scope_fifo(|s| {
s.spawn_fifo(|_| {
self.receivers.par_iter().for_each(|r| {
r.on_receive(packet.clone(), Address(address));
});
})
});
}
}
}
pub fn add_receiver(&mut self, receiver: Box<dyn Receiver + Send + Sync>) {
self.receivers.push(receiver)
}
}
#[cfg(test)]
pub mod test_helper {
use std::net::{SocketAddr, Ipv4Addr, IpAddr};
use std::sync::atomic::Ordering::SeqCst;
use std::sync::atomic::{AtomicU16};
use crate::networking::address::Address;
const FIRST_PORT: u16 = 18080;
static NEXT_PORT: AtomicU16 = AtomicU16::new(FIRST_PORT);
pub const LOCALHOST_IP: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1);
fn next_port() -> u16 {
NEXT_PORT.fetch_add(1, SeqCst)
}
pub fn localhost() -> Address {
Address(localhost_socket())
}
pub fn localhost_socket() -> SocketAddr {
SocketAddr::new(IpAddr::V4(LOCALHOST_IP), next_port())
}
}
#[cfg(test)]
mod tests {
use lazy_static::lazy_static;
use crate::IPv8;
use crate::configuration::Config;
use mio::net::UdpSocket;
use std::net::{SocketAddr, IpAddr};
use crate::serialization::Packet;
use std::sync::Once;
use std::time::Duration;
use crate::networking::{Receiver, NetworkSender, NetworkReceiver};
use std::thread;
use std::sync::atomic::{AtomicUsize, Ordering, AtomicU16};
use crate::networking::address::Address;
use crate::networking::test_helper::{localhost, localhost_socket, LOCALHOST_IP};
static BEFORE: Once = Once::new();
fn before() {
BEFORE.call_once(|| {
simple_logger::init().unwrap();
})
}
#[test]
fn test_networkmanager() {
before();
let mut config = Config::default();
config.receiving_address = localhost();
config.sending_address = localhost();
config.buffersize = 2048;
let mut ipv8 = IPv8::new(config).unwrap();
let sender_socket = UdpSocket::bind(&localhost_socket()).unwrap();
static SEND_PORT: AtomicU16 = AtomicU16::new(0);
let recv_port: u16 = ipv8.network_receiver.socket.local_addr().unwrap().port();
let send_port: u16 = sender_socket.local_addr().unwrap().port();
SEND_PORT.store(send_port, Ordering::SeqCst);
lazy_static! {
static ref OGPACKET: Packet = Packet::new(create_test_header!()).unwrap();
}
static PACKET_COUNTER: AtomicUsize = AtomicUsize::new(0);
struct AReceiver;
impl Receiver for AReceiver {
fn on_receive(&self, packet: Packet, address: Address) {
assert_eq!(OGPACKET.raw(), packet.raw());
assert_eq!(SEND_PORT.load(Ordering::SeqCst), (address.0).port());
PACKET_COUNTER.fetch_add(1, Ordering::SeqCst);
}
}
ipv8.network_receiver.add_receiver(Box::new(AReceiver));
ipv8.start();
sender_socket
.connect(SocketAddr::new(IpAddr::V4(LOCALHOST_IP), recv_port))
.unwrap();
let a = sender_socket.send(OGPACKET.raw()).unwrap();
assert_eq!(a, OGPACKET.raw().len());
thread::sleep(Duration::from_millis(20));
let b = sender_socket.send(OGPACKET.raw()).unwrap();
assert_eq!(b, OGPACKET.raw().len());
thread::sleep(Duration::from_millis(20));
assert_eq!(2, PACKET_COUNTER.load(std::sync::atomic::Ordering::SeqCst));
}
#[test]
fn test_sending_networkmanager() {
before();
let mut config = Config::default();
config.receiving_address = localhost();
config.sending_address = localhost();
config.buffersize = 2048;
let ns = NetworkSender::new(&config.sending_address).unwrap();
let mut nr = NetworkReceiver::new(&config.receiving_address).unwrap();
static SEND_PORT: AtomicU16 = AtomicU16::new(0);
let recv_port: u16 = nr.socket.local_addr().unwrap().port();
let send_port: u16 = ns.socket.local_addr().unwrap().port();
SEND_PORT.store(send_port, Ordering::SeqCst);
lazy_static! {
static ref OGPACKET: Packet = Packet::new(create_test_header!()).unwrap();
}
static PACKET_COUNTER: AtomicUsize = AtomicUsize::new(0);
struct AReceiver;
impl Receiver for AReceiver {
fn on_receive(&self, packet: Packet, address: Address) {
assert_eq!(OGPACKET.raw(), packet.raw());
assert_eq!(SEND_PORT.load(Ordering::SeqCst), (address.0).port());
PACKET_COUNTER.fetch_add(1, Ordering::SeqCst);
}
}
nr.add_receiver(Box::new(AReceiver));
nr.start(&config);
let addr = Address(SocketAddr::new(IpAddr::V4(LOCALHOST_IP), recv_port));
ns.send(&addr, Packet(OGPACKET.raw().to_vec())).unwrap();
thread::sleep(Duration::from_millis(20));
assert_eq!(1, PACKET_COUNTER.load(std::sync::atomic::Ordering::SeqCst));
}
}