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
use std::io;
use std::net::UdpSocket;
use std::net;
use std::net::IpAddr;
use std::time::Duration;
use std::collections::HashSet;
use igd;
use time;
use maidsafe_utilities::serialisation::deserialise;
use socket_addr::SocketAddr;
use w_result::{WResult, WOk, WErr};
use listener_message;
use mapping_context;
use mapping_context::MappingContext;
use mapped_socket_addr::MappedSocketAddr;
use socket_utils;
use socket_utils::RecvUntil;
pub struct MappedUdpSocket {
pub socket: UdpSocket,
pub endpoints: Vec<MappedSocketAddr>
}
quick_error! {
#[derive(Debug)]
pub enum MappedUdpSocketMapError {
SocketLocalAddr {
err: io::Error
} {
description("Error getting local address of socket \
(have you called bind() on the socket?)")
display("Error getting local address of socket. \
UdpSocket::local_addr returned an error: {}
(have you called bind() on the socket?).",
err)
cause(err)
}
RecvError {
err: io::Error
} {
description("IO error receiving data on socket")
display("IO error receiving data on socket: {}", err)
cause(err)
}
SendError {
err: io::Error
} {
description("IO error sending data on socket")
display("IO error sending data on socket: {}", err)
cause(err)
}
}
}
impl From<MappedUdpSocketMapError> for io::Error {
fn from(e: MappedUdpSocketMapError) -> io::Error {
let err_str = format!("{}", e);
let kind = match e {
MappedUdpSocketMapError::SocketLocalAddr { err } => err.kind(),
MappedUdpSocketMapError::RecvError { err } => err.kind(),
MappedUdpSocketMapError::SendError { err } => err.kind(),
};
io::Error::new(kind, err_str)
}
}
quick_error! {
#[derive(Debug)]
pub enum MappedUdpSocketMapWarning {
FindGateway {
err: igd::SearchError
} {
description("Error searching for IGD gateway")
display("Error searching for IGD gateway. \
igd::search_gateway_from_timeout returned an error: {}",
err)
cause(err)
}
GetExternalPort {
gateway_addr: net::SocketAddrV4,
err: igd::AddAnyPortError,
} {
description("Error mapping external address and port through IGD \
gateway")
display("Error mapping external address and port through IGD \
gateway at address {}. igd::Gateway::get_any_address \
returned an error: {}", gateway_addr, err)
cause(err)
}
}
}
quick_error! {
#[derive(Debug)]
pub enum MappedUdpSocketNewError {
CreateSocket {
err: io::Error
} {
description("Error creating a new udp socket bound to 0.0.0.0:0")
display("Error creating a new udp socket bound to 0.0.0.0:0. \
UdpSocket::bind returned an IO error: {}", err)
cause(err)
}
MapSocket {
err: MappedUdpSocketMapError
} {
description("Error mapping udp socket")
display("Error mapping udp socket. MappedUdpSocket::map returned \
an error: {}", err)
cause(err)
}
}
}
impl From<MappedUdpSocketNewError> for io::Error {
fn from(e: MappedUdpSocketNewError) -> io::Error {
let err_str = format!("{}", e);
let kind = match e {
MappedUdpSocketNewError::CreateSocket { err } => err.kind(),
MappedUdpSocketNewError::MapSocket { err } => {
let err: io::Error = From::from(err);
err.kind()
},
};
io::Error::new(kind, err_str)
}
}
impl MappedUdpSocket {
pub fn map(socket: UdpSocket, mc: &MappingContext)
-> WResult<MappedUdpSocket, MappedUdpSocketMapWarning, MappedUdpSocketMapError>
{
let mut endpoints = Vec::new();
let mut warnings = Vec::new();
let local_addr = match socket.local_addr() {
Ok(local_addr) => local_addr,
Err(e) => return WErr(MappedUdpSocketMapError::SocketLocalAddr { err: e })
};
match local_addr.ip() {
IpAddr::V4(ipv4_addr) => {
if socket_utils::ipv4_is_unspecified(&ipv4_addr) {
for iface_v4 in mapping_context::interfaces_v4(&mc) {
let local_iface_addr = net::SocketAddrV4::new(iface_v4.addr, local_addr.port());
endpoints.push(MappedSocketAddr {
addr: SocketAddr(net::SocketAddr::V4(local_iface_addr)),
nat_restricted: false,
});
if let Some(gateway) = iface_v4.gateway {
match gateway.get_any_address(igd::PortMappingProtocol::UDP,
local_iface_addr, 0,
"rust nat_traversal")
{
Ok(external_addr) => {
endpoints.push(MappedSocketAddr {
addr: SocketAddr(net::SocketAddr::V4(external_addr)),
nat_restricted: false,
});
},
Err(e) => {
warnings.push(MappedUdpSocketMapWarning::GetExternalPort {
gateway_addr: gateway.addr,
err: e,
});
}
}
};
};
}
else {
let local_addr_v4 = net::SocketAddrV4::new(ipv4_addr, local_addr.port());
endpoints.push(MappedSocketAddr {
addr: SocketAddr(net::SocketAddr::V4(local_addr_v4)),
nat_restricted: false,
});
let mut gateway_opt_opt = None;
for iface_v4 in mapping_context::interfaces_v4(&mc) {
if iface_v4.addr == ipv4_addr {
gateway_opt_opt = Some(iface_v4.gateway);
break;
}
};
let gateway_opt = match gateway_opt_opt {
Some(gateway_opt) => gateway_opt,
None => {
match igd::search_gateway_from_timeout(ipv4_addr, Duration::from_secs(1)) {
Ok(gateway) => Some(gateway),
Err(e) => {
warnings.push(MappedUdpSocketMapWarning::FindGateway {
err: e
});
None
}
}
}
};
if let Some(gateway) = gateway_opt {
match gateway.get_any_address(igd::PortMappingProtocol::UDP,
local_addr_v4, 0,
"rust nat_traversal")
{
Ok(external_addr) => {
endpoints.push(MappedSocketAddr {
addr: SocketAddr(net::SocketAddr::V4(external_addr)),
nat_restricted: false,
});
},
Err(e) => {
warnings.push(MappedUdpSocketMapWarning::GetExternalPort {
gateway_addr: gateway.addr,
err: e,
});
}
}
};
};
},
IpAddr::V6(ipv6_addr) => {
if socket_utils::ipv6_is_unspecified(&ipv6_addr) {
for iface_v6 in mapping_context::interfaces_v6(&mc) {
let local_iface_addr = net::SocketAddr::V6(net::SocketAddrV6::new(iface_v6.addr, local_addr.port(), 0, 0));
endpoints.push(MappedSocketAddr {
addr: SocketAddr(local_iface_addr),
nat_restricted: false,
});
};
}
else {
endpoints.push(MappedSocketAddr {
addr: SocketAddr(net::SocketAddr::V6(net::SocketAddrV6::new(ipv6_addr, local_addr.port(), 0, 0))),
nat_restricted: false,
});
}
},
};
const MAX_DATAGRAM_SIZE: usize = 256;
let send_data = listener_message::REQUEST_MAGIC_CONSTANT;
let mut simple_servers: HashSet<SocketAddr> = mapping_context::simple_udp_servers(&mc)
.into_iter().collect();
let start_time = time::SteadyTime::now();
let mut deadline = start_time;
let mut final_deadline = start_time + time::Duration::seconds(2);
while deadline < final_deadline && simple_servers.len() > 0 {
deadline = deadline + time::Duration::milliseconds(250);
for simple_server in &simple_servers {
let _ = match socket.send_to(&send_data[..], &**simple_server) {
Ok(n) => n,
Err(e) => return WErr(MappedUdpSocketMapError::SendError { err: e }),
};
};
let mut recv_data = [0u8; MAX_DATAGRAM_SIZE];
loop {
let (read_size, recv_addr) = match socket.recv_until(&mut recv_data[..], deadline) {
Ok(Some(res)) => res,
Ok(None) => break,
Err(e) => return WErr(MappedUdpSocketMapError::RecvError { err: e }),
};
if let Ok(listener_message::EchoExternalAddr { external_addr }) =
deserialise::<listener_message::EchoExternalAddr>(&recv_data[..read_size]) {
simple_servers.remove(&recv_addr);
let is_global = false;
if is_global {
final_deadline = start_time + time::Duration::seconds(1);
};
if endpoints.iter().all(|e| e.addr != external_addr) {
endpoints.push(MappedSocketAddr {
addr: external_addr,
nat_restricted: true,
});
}
}
}
}
WOk(MappedUdpSocket {
socket: socket,
endpoints: endpoints,
}, warnings)
}
pub fn new(mc: &MappingContext)
-> WResult<MappedUdpSocket, MappedUdpSocketMapWarning, MappedUdpSocketNewError>
{
let mut attempt = 0;
'attempt: loop {
attempt += 1;
let socket = match UdpSocket::bind("0.0.0.0:0") {
Ok(socket) => socket,
Err(e) => return WErr(MappedUdpSocketNewError::CreateSocket { err: e }),
};
let (socket, warnings) = match Self::map(socket, mc) {
WOk(s, ws) => (s, ws),
WErr(e) => return WErr(MappedUdpSocketNewError::MapSocket { err: e }),
};
if attempt < 3 {
for warning in &warnings {
match *warning {
MappedUdpSocketMapWarning::GetExternalPort {
err: igd::AddAnyPortError::ExternalPortInUse,
..
} => continue 'attempt,
_ => (),
}
}
}
return WOk(socket, warnings);
}
}
}