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
use maidsafe_utilities::serialisation::{deserialise, SerialisationError, serialise};
use std::io;
use std::net::UdpSocket;
use std;
use std::thread;
use time;
use socket_addr::SocketAddr;
use w_result::{WResult, WOk, WErr};
use rendezvous_info::{PrivRendezvousInfo, PubRendezvousInfo};
use rendezvous_info;
use socket_utils::RecvUntil;
use mapped_socket_addr::MappedSocketAddr;
#[derive(Debug, RustcEncodable, RustcDecodable)]
struct HolePunch {
pub secret: [u8; 4],
pub ack: bool,
}
#[derive(Debug)]
pub struct HolePunchPacketData {
data: HolePunch,
}
pub struct PunchedUdpSocket {
pub socket: UdpSocket,
pub peer_addr: SocketAddr,
}
quick_error! {
#[derive(Debug)]
#[allow(variant_size_differences)]
pub enum UdpPunchHoleWarning {
UnexpectedHolePunchPacket {
hole_punch: HolePunchPacketData,
} {
description("Received a hole punch packet that does correspond to the \
connection we are trying to make. Possibly, hole punch packets \
from an unrelated connection or arriving on this socket.")
display("Received a hole punch packet that does correspond to the \
connection we are trying to make. Possibly, hole punch packets \
from an unrelated connection or arriving on this socket. Debug \
info: {:#?}", hole_punch)
}
InvalidHolePunchPacket {
err: SerialisationError,
} {
description("Received invalid data on the udp socket while hole punching")
display("Received invalid data on the udp socket while hole punching. \
deserialisation produced the error: {}", err)
cause(err)
}
MsgEndpoint {
endpoint: MappedSocketAddr,
err: io::Error,
} {
description("IO error trying to send a message to one of the peer's potential endpoints.")
display("IO error trying to send a message to endpoint {:?}. {}", endpoint, err)
cause(err)
}
}
}
quick_error! {
#[derive(Debug)]
pub enum UdpPunchHoleError {
TimedOut {
description("Timed out waiting for a response from the peer.")
}
Io {
err: io::Error,
} {
description("IO error when using socket")
display("IO error when using socket: {}", err)
cause(err)
}
SendCompleteAck {
description("Error sending ACK to peer. Kept getting partial writes.")
display("Error sending ACK to peer. Kept getting partial writes.")
}
}
}
impl From<UdpPunchHoleError> for io::Error {
fn from(e: UdpPunchHoleError) -> io::Error {
let err_str = format!("{}", e);
let kind = match e {
UdpPunchHoleError::TimedOut => io::ErrorKind::TimedOut,
UdpPunchHoleError::Io { err } => err.kind(),
UdpPunchHoleError::SendCompleteAck => io::ErrorKind::Other,
};
io::Error::new(kind, err_str)
}
}
impl PunchedUdpSocket {
pub fn punch_hole(socket: UdpSocket,
our_priv_rendezvous_info: PrivRendezvousInfo,
their_pub_rendezvous_info: PubRendezvousInfo)
-> WResult<PunchedUdpSocket, UdpPunchHoleWarning, UdpPunchHoleError>
{
let mut warnings = Vec::new();
let (mut endpoints, their_secret)
= rendezvous_info::decompose(their_pub_rendezvous_info);
let our_secret
= rendezvous_info::get_priv_secret(our_priv_rendezvous_info);
const MAX_DATAGRAM_SIZE: usize = 128;
let send_data = {
let hole_punch = HolePunch {
secret: our_secret,
ack: false,
};
serialise(&hole_punch).unwrap()
};
assert!(send_data.len() <= MAX_DATAGRAM_SIZE,
format!("Data exceed MAX_DATAGRAM_SIZE in blocking_udp_punch_hole: {} > {}",
send_data.len(),
MAX_DATAGRAM_SIZE));
let mut recv_data = [0u8; MAX_DATAGRAM_SIZE];
const DELAY_BETWEEN_RESENDS_MS: i64 = 600;
const TOTAL_TIMEOUT_MS: i64 = 10000;
let start_time = time::SteadyTime::now();
let mut deadline = start_time;
let total_deadline = start_time + time::Duration::milliseconds(TOTAL_TIMEOUT_MS);
while deadline < total_deadline {
deadline = deadline + time::Duration::milliseconds(DELAY_BETWEEN_RESENDS_MS);
let mut i = 0;
while i < endpoints.len() {
let _ = match socket.send_to(&send_data[..], &*endpoints[i].addr) {
Ok(n) => n,
Err(e) => {
warnings.push(UdpPunchHoleWarning::MsgEndpoint {
endpoint: endpoints.swap_remove(i),
err: e,
});
continue;
}
};
i += 1;
}
loop {
let (read_size, addr) = match socket.recv_until(&mut recv_data[..], deadline) {
Ok(Some(x)) => x,
Ok(None) => break,
Err(e) => return WErr(UdpPunchHoleError::Io { err: e }),
};
match deserialise::<HolePunch>(&recv_data[..read_size]) {
Ok(hp) => {
if hp.secret == our_secret && hp.ack {
return WOk(PunchedUdpSocket {
socket: socket,
peer_addr: addr,
}, warnings);
}
if hp.secret == their_secret {
let send_data = {
let hole_punch = HolePunch {
secret: their_secret,
ack: true,
};
serialise(&hole_punch).unwrap()
};
assert!(send_data.len() <= MAX_DATAGRAM_SIZE,
format!("Data exceed MAX_DATAGRAM_SIZE in blocking_udp_punch_hole: {} > {}",
send_data.len(),
MAX_DATAGRAM_SIZE));
let mut attempts = 0;
let mut successful_attempts = 0;
let mut error = None;
while attempts < 2 || time::SteadyTime::now() < total_deadline {
attempts += 1;
match socket.send_to(&send_data[..], &*addr) {
Ok(n) => {
if n == send_data.len() {
successful_attempts += 1;
if successful_attempts == 2 {
break;
}
}
}
Err(e) => {
if error.is_none() {
error = Some(e);
}
}
};
thread::sleep(std::time::Duration::from_millis(100));
}
if successful_attempts == 0 {
let ret = match error {
Some(e) => UdpPunchHoleError::Io { err: e },
None => UdpPunchHoleError::SendCompleteAck,
};
return WErr(ret);
}
else {
return WOk(PunchedUdpSocket {
socket: socket,
peer_addr: addr,
}, warnings);
}
}
if warnings.len() < 10 {
warnings.push(UdpPunchHoleWarning::UnexpectedHolePunchPacket {
hole_punch: HolePunchPacketData {
data: hp,
},
});
}
}
Err(e) => {
if warnings.len() < 10 {
warnings.push(UdpPunchHoleWarning::InvalidHolePunchPacket {
err: e,
});
}
}
};
}
}
WErr(UdpPunchHoleError::TimedOut)
}
}
pub fn filter_udp_hole_punch_packet(data: &[u8]) -> Option<&[u8]> {
match deserialise::<HolePunch>(data){
Ok(_) => None,
_ => Some(data),
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use rand;
use mapping_context::MappingContext;
use mapped_udp_socket::MappedUdpSocket;
use punched_udp_socket::{PunchedUdpSocket, filter_udp_hole_punch_packet};
use rendezvous_info::gen_rendezvous_info;
#[test]
fn two_peers_udp_hole_punch_over_loopback() {
let mapping_context = unwrap_result!(MappingContext::new().result_discard());
let mapped_socket_0 = unwrap_result!(MappedUdpSocket::new(&mapping_context).result_discard());
let mapped_socket_1 = unwrap_result!(MappedUdpSocket::new(&mapping_context).result_discard());
let socket_0 = mapped_socket_0.socket;
let socket_1 = mapped_socket_1.socket;
let (priv_info_0, pub_info_0) = gen_rendezvous_info(mapped_socket_0.endpoints);
let (priv_info_1, pub_info_1) = gen_rendezvous_info(mapped_socket_1.endpoints);
let (tx_0, rx_0) = mpsc::channel();
let (tx_1, rx_1) = mpsc::channel();
let jh_0 = thread!("two_peers_hole_punch_over_loopback punch socket 0", move || {
let res = PunchedUdpSocket::punch_hole(socket_0,
priv_info_0,
pub_info_1);
unwrap_result!(tx_0.send(res));
});
let jh_1 = thread!("two_peers_hole_punch_over_loopback punch socket 1", move || {
let res = PunchedUdpSocket::punch_hole(socket_1,
priv_info_1,
pub_info_0);
unwrap_result!(tx_1.send(res));
});
thread::sleep(Duration::from_millis(500));
let punched_socket_0 = unwrap_result!(unwrap_result!(rx_0.try_recv()).result_discard());
let punched_socket_1 = unwrap_result!(unwrap_result!(rx_1.try_recv()).result_discard());
const DATA_LEN: usize = 8;
let data_send: [u8; DATA_LEN] = rand::random();
let mut data_recv;
data_recv = [0u8; 1024];
let n = unwrap_result!(punched_socket_0.socket.send_to(&data_send[..], &*punched_socket_0.peer_addr));
assert_eq!(n, DATA_LEN);
loop {
let (n, _) = unwrap_result!(punched_socket_1.socket.recv_from(&mut data_recv[..]));
match filter_udp_hole_punch_packet(&data_recv[..n]) {
Some(d) => {
assert_eq!(data_send, d);
break;
},
None => continue,
}
}
data_recv = [0u8; 1024];
let n = unwrap_result!(punched_socket_1.socket.send_to(&data_send[..], &*punched_socket_1.peer_addr));
assert_eq!(n, DATA_LEN);
loop {
let (n, _) = unwrap_result!(punched_socket_0.socket.recv_from(&mut data_recv[..]));
match filter_udp_hole_punch_packet(&data_recv[..n]) {
Some(d) => {
assert_eq!(data_send, d);
break;
},
None => continue,
}
}
unwrap_result!(jh_0.join());
unwrap_result!(jh_1.join());
}
}