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
//TODO: Use rust directly for port mapping natpmp (and eventually PCP) so we can avoid the need for FFI from nat-pmp
use std::time::Duration;
use futures::{
channel::mpsc::{unbounded, Receiver, UnboundedSender},
StreamExt,
};
#[cfg(feature = "tokio")]
use igd_next::aio::tokio as aio;
#[cfg(feature = "async-std")]
use igd_next::aio::async_std as aio;
use igd_next::SearchOptions;
use libp2p::{multiaddr::Protocol, swarm::derive_prelude::ListenerId, Multiaddr};
use crate::utils::multiaddr_to_socket_port;
#[derive(thiserror::Error, Debug)]
pub enum ForwardingError {
#[error("Address provided is either local or invalid")]
InvalidAddress {
listener_id: ListenerId,
address: Multiaddr,
},
#[error("Unable to port forward")]
PortForwardingFailed { listener_id: ListenerId },
#[error("Error")]
Any {
listener_id: ListenerId,
error: anyhow::Error,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NatType {
Igd,
#[cfg(feature = "nat_pmp_fallback")]
#[cfg(not(target_os = "ios"))]
Natpmp,
}
#[allow(dead_code)]
#[derive(Debug)]
pub enum NatCommands {
ForwardPort(ListenerId, Multiaddr),
DisableForwardPort(ListenerId, Multiaddr, NatType),
}
#[derive(Debug)]
pub enum NatResult {
PortForwardingEnabled {
listener_id: ListenerId,
local_addr: Multiaddr,
addr: Multiaddr,
nat_type: NatType,
timer: futures_timer::Delay,
},
PortForwardingDisabled {
listener_id: ListenerId,
},
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum QuicType {
Draft29,
V1,
}
impl From<QuicType> for Protocol<'_> {
fn from(qty: QuicType) -> Self {
match qty {
QuicType::Draft29 => Protocol::Quic,
QuicType::V1 => Protocol::QuicV1,
}
}
}
#[inline]
#[cfg(any(feature = "tokio", feature = "async-std"))]
pub fn port_forwarding_task(
renewal: Duration,
duration: Duration,
) -> (
UnboundedSender<NatCommands>,
Receiver<Result<NatResult, ForwardingError>>,
) {
use futures::{channel::mpsc::channel, SinkExt};
use futures_timer::Delay;
use crate::utils::to_multipaddr;
let (mut res, res_rx) = channel(20);
let (tx, mut rx) = unbounded();
let fut = async move {
while let Some(cmd) = rx.next().await {
match cmd {
NatCommands::ForwardPort(id, multiaddr) => {
let Some((addr, protocol, qty)) = multiaddr_to_socket_port(&multiaddr) else {
let _ = res.clone().send(Err(ForwardingError::InvalidAddress{ listener_id: id, address: multiaddr })).await;
continue;
};
let igd_fut = async {
let gateway = aio::search_gateway(SearchOptions::default()).await?;
gateway
.add_port(
protocol.into(),
addr.port(),
addr,
duration.as_secs() as _,
"libp2p",
)
.await?;
let ext_addr = gateway.get_external_ip().await?;
let multiaddr = to_multipaddr((ext_addr, addr.port()), protocol, qty);
Ok::<_, igd_next::Error>(multiaddr)
};
match igd_fut.await {
Ok(addr) => {
let _ = res
.send(Ok(NatResult::PortForwardingEnabled {
listener_id: id,
local_addr: multiaddr,
addr,
nat_type: NatType::Igd,
timer: Delay::new(renewal),
}))
.await;
continue;
}
Err(e) => {
log::error!("Error opening port with igd: {e}");
}
};
#[cfg(any(target_os = "ios", not(feature = "nat_pmp_fallback")))]
{
let _ = res
.send(Err(ForwardingError::PortForwardingFailed {
listener_id: id,
}))
.await;
continue;
}
#[cfg(feature = "nat_pmp_fallback")]
#[cfg(not(target_os = "ios"))]
{
#[cfg(feature = "tokio")]
let mut nat_handle = match natpmp::new_tokio_natpmp().await {
Ok(handle) => handle,
Err(e) => {
log::error!("Error obtaining nat-pmp handle: {e}");
let _ = res
.send(Err(ForwardingError::PortForwardingFailed {
listener_id: id,
}))
.await;
continue;
}
};
#[cfg(feature = "async-std")]
let mut nat_handle = match natpmp::new_async_std_natpmp().await {
Ok(handle) => handle,
Err(e) => {
log::error!("Error obtaining nat-pmp handle: {e}");
let _ = res
.send(Err(ForwardingError::PortForwardingFailed {
listener_id: id,
}))
.await;
continue;
}
};
// In case igd fails, we will attempt with nat-pmp before returning an error
// TODO: Determine if we should have it in separate events
if let Err(e) = nat_handle
.send_port_mapping_request(
protocol.into(),
addr.port(),
addr.port(),
duration.as_secs() as _,
)
.await
{
log::error!("Error opening port with nat-pmp: {e}");
let _ = res
.send(Err(ForwardingError::PortForwardingFailed {
listener_id: id,
}))
.await;
continue;
}
let response = match nat_handle.read_response_or_retry().await {
Ok(response) => response,
Err(e) => {
let _ = res
.send(Err(ForwardingError::Any {
listener_id: id,
error: anyhow::anyhow!("Error with nat pmp: {e}"),
}))
.await;
continue;
}
};
if !matches!(
response,
natpmp::Response::TCP(_) | natpmp::Response::UDP(_)
) {
let _ = res
.send(Err(ForwardingError::Any {
listener_id: id,
error: anyhow::anyhow!("Unsupported result"),
}))
.await;
continue;
}
if let Err(e) = nat_handle.send_public_address_request().await {
let _ = res
.send(Err(ForwardingError::Any {
listener_id: id,
error: anyhow::anyhow!("error sending request: {e}"),
}))
.await;
continue;
}
let gateway = match nat_handle.read_response_or_retry().await {
Ok(natpmp::Response::Gateway(gr)) => gr,
Ok(_) => {
let _ = res
.send(Err(ForwardingError::Any {
listener_id: id,
error: anyhow::anyhow!("Cannot get external address"),
}))
.await;
continue;
}
Err(e) => {
let _ = res
.send(Err(ForwardingError::Any {
listener_id: id,
error: anyhow::anyhow!("Error with nat pmp: {e}"),
}))
.await;
continue;
}
};
let ext_addr = *gateway.public_address();
let addr = to_multipaddr((ext_addr, addr.port()), protocol, qty);
let _ = res
.send(Ok(NatResult::PortForwardingEnabled {
listener_id: id,
local_addr: multiaddr,
addr,
nat_type: NatType::Natpmp,
timer: Delay::new(renewal),
}))
.await;
}
}
NatCommands::DisableForwardPort(id, addr, NatType::Igd) => {
let Some((addr, protocol, _)) = multiaddr_to_socket_port(&addr) else {
let _ = res.send(Err(ForwardingError::InvalidAddress{ listener_id: id, address: addr })).await;
continue;
};
let opts = SearchOptions {
timeout: Some(Duration::from_secs(2)),
..Default::default()
};
let gateway = match aio::search_gateway(opts).await {
Ok(gateway) => gateway,
Err(e) => {
log::warn!("Error with igd: {e}");
let _ = res
.send(Err(ForwardingError::Any {
listener_id: id,
error: anyhow::anyhow!("{e}"),
}))
.await;
continue;
}
};
let result = gateway
.remove_port(protocol.into(), addr.port())
.await
.map(|_| NatResult::PortForwardingDisabled { listener_id: id })
.map_err(|e| ForwardingError::Any {
listener_id: id,
error: anyhow::anyhow!("{e}"),
});
let _ = res.send(result).await;
}
#[cfg(feature = "nat_pmp_fallback")]
#[cfg(not(target_os = "ios"))]
NatCommands::DisableForwardPort(id, _, NatType::Natpmp) => {
//This implementation does not have a way to remove the port at this time
let _ = res
.send(Err(ForwardingError::Any {
listener_id: id,
error: anyhow::anyhow!(
"cannot disable port forwarding via nat-pmp at this time"
),
}))
.await;
}
}
}
};
#[cfg(feature = "tokio")]
tokio::spawn(fut);
#[cfg(feature = "async-std")]
async_std::task::spawn(fut);
(tx, res_rx)
}