Skip to main content

rtci_stream_driver/
nat_mapping.rs

1//! NAT-assisted candidates (RFC 6544 section 5.3, RFC 8445 section 5.1.1.2): an opt-in client of
2//! the Port Control Protocol (PCP, RFC 6887) with a fallback to NAT-PMP (RFC 6886), asking the
3//! gateway for a port mapping. Nothing here runs unless the application calls it, and it
4//! adds no dependency: one UDP socket on tokio.
5//!
6//! The engine needs nothing new: the mapped address is a candidate the application adds
7//! itself, a server-reflexive one whose related address is the base (RFC 6544 section 5.3
8//! calls it NAT-assisted; [`candidate_line`] writes it with the type preference 105 RFC 6544
9//! section 4.2 recommends). Finding the gateway is the application's: this module does not
10//! read routing tables (that would need a platform dependency); the default gateway's address
11//! is passed in.
12//!
13//! [`map_port`] sends a PCP MAP request (RFC 6887 section 11) to `gateway:5351`, retransmitted
14//! as section 8.1.1 says (3 s first, doubling, here up to [`MappingConfig::attempts`] times);
15//! a gateway that answers with UNSUPP_VERSION, or with a NAT-PMP response, is asked again with
16//! NAT-PMP (RFC 6886 section 3.3, retransmitted from 250 ms doubling, at most nine times,
17//! section 3.1). Mappings expire: renew them with [`map_port`] again before half their
18//! lifetime has passed, and delete one with a lifetime of 0.
19
20use std::io;
21use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
22use std::time::Duration;
23use tokio::net::UdpSocket;
24
25/// The port PCP and NAT-PMP servers listen on (RFC 6887 section 19.1, RFC 6886 section 3).
26pub const SERVER_PORT: u16 = 5351;
27
28/// The transport a mapping is for.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum Protocol {
31    /// UDP (IANA protocol 17; NAT-PMP opcode 1).
32    Udp,
33    /// TCP (IANA protocol 6; NAT-PMP opcode 2).
34    Tcp,
35}
36
37impl Protocol {
38    fn iana(self) -> u8 {
39        match self {
40            Self::Udp => 17,
41            Self::Tcp => 6,
42        }
43    }
44
45    fn nat_pmp_opcode(self) -> u8 {
46        match self {
47            Self::Udp => 1,
48            Self::Tcp => 2,
49        }
50    }
51}
52
53/// Which protocol answered.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum MappingProtocol {
56    /// PCP (RFC 6887).
57    Pcp,
58    /// NAT-PMP (RFC 6886).
59    NatPmp,
60}
61
62/// A mapping the gateway granted.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct Mapping {
65    /// The external address and port: the NAT-assisted candidate's address.
66    pub external: SocketAddr,
67    /// The internal port it maps to.
68    pub internal_port: u16,
69    /// How long it lasts.
70    pub lifetime: Duration,
71    /// Which protocol granted it.
72    pub protocol: MappingProtocol,
73}
74
75/// How [`map_port`] asks.
76#[derive(Debug, Clone)]
77pub struct MappingConfig {
78    /// The lifetime asked for (RFC 6886 section 3.3 recommends 7200 s; 0 deletes).
79    pub lifetime: Duration,
80    /// The external port suggested (0: none).
81    pub suggested_port: u16,
82    /// Requests sent per protocol before giving up.
83    pub attempts: u32,
84    /// The first PCP retransmission interval (RFC 6887 section 8.1.1: 3 s).
85    pub pcp_initial: Duration,
86    /// The first NAT-PMP retransmission interval (RFC 6886 section 3.1: 250 ms).
87    pub nat_pmp_initial: Duration,
88    /// Skip PCP and ask with NAT-PMP only.
89    pub nat_pmp_only: bool,
90}
91
92impl Default for MappingConfig {
93    fn default() -> Self {
94        Self {
95            lifetime: Duration::from_secs(7200),
96            suggested_port: 0,
97            attempts: 4,
98            pcp_initial: Duration::from_secs(3),
99            nat_pmp_initial: Duration::from_millis(250),
100            nat_pmp_only: false,
101        }
102    }
103}
104
105/// PCP result code UNSUPP_VERSION (RFC 6887 section 7.4); NAT-PMP's is 1 too.
106const UNSUPP_VERSION: u8 = 1;
107
108fn mapped_v6(ip: IpAddr) -> Ipv6Addr {
109    match ip {
110        IpAddr::V4(v4) => v4.to_ipv6_mapped(),
111        IpAddr::V6(v6) => v6,
112    }
113}
114
115fn unmapped(ip: Ipv6Addr) -> IpAddr {
116    match ip.to_ipv4_mapped() {
117        Some(v4) => IpAddr::V4(v4),
118        None => IpAddr::V6(ip),
119    }
120}
121
122/// A PCP MAP request (RFC 6887 sections 7.1 and 11.1): 24-byte header, 36-byte MAP opcode.
123pub fn pcp_map_request(
124    client: IpAddr,
125    nonce: [u8; 12],
126    protocol: Protocol,
127    internal_port: u16,
128    config: &MappingConfig,
129) -> Vec<u8> {
130    let mut m = Vec::with_capacity(60);
131    m.push(2); // version
132    m.push(1); // R = 0, opcode MAP
133    m.extend_from_slice(&[0, 0]);
134    m.extend_from_slice(&(config.lifetime.as_secs().min(u64::from(u32::MAX)) as u32).to_be_bytes());
135    m.extend_from_slice(&mapped_v6(client).octets());
136    m.extend_from_slice(&nonce);
137    m.push(protocol.iana());
138    m.extend_from_slice(&[0, 0, 0]);
139    m.extend_from_slice(&internal_port.to_be_bytes());
140    m.extend_from_slice(&config.suggested_port.to_be_bytes());
141    // Suggested external address: none (the IPv4-mapped all-zeros address for IPv4).
142    let none = if client.is_ipv4() {
143        Ipv4Addr::UNSPECIFIED.to_ipv6_mapped()
144    } else {
145        Ipv6Addr::UNSPECIFIED
146    };
147    m.extend_from_slice(&none.octets());
148    m
149}
150
151/// What a PCP response says.
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub enum PcpAnswer {
154    /// SUCCESS with the mapping.
155    Mapped(Mapping),
156    /// Another result code.
157    Refused(u8),
158}
159
160/// Parses a PCP MAP response to the request with `nonce` (RFC 6887 sections 7.2 and 11.1).
161/// `None` for anything else (not PCP, not a MAP response, another nonce).
162pub fn parse_pcp_map_response(
163    data: &[u8],
164    nonce: [u8; 12],
165    protocol: Protocol,
166) -> Option<PcpAnswer> {
167    if data.len() < 60 || data[0] != 2 || data[1] != 0x81 {
168        // A version-1-or-2 error answer to an unknown version is shorter; see `answers_nat_pmp`.
169        if data.len() >= 4 && data[0] == 2 && data[1] & 0x80 != 0 && data[3] == UNSUPP_VERSION {
170            return Some(PcpAnswer::Refused(UNSUPP_VERSION));
171        }
172        return None;
173    }
174    let result = data[3];
175    if result != 0 {
176        return Some(PcpAnswer::Refused(result));
177    }
178    if data[24..36] != nonce || data[36] != protocol.iana() {
179        return None;
180    }
181    let lifetime = u32::from_be_bytes(data[4..8].try_into().ok()?);
182    let internal_port = u16::from_be_bytes([data[40], data[41]]);
183    let external_port = u16::from_be_bytes([data[42], data[43]]);
184    let ip: [u8; 16] = data[44..60].try_into().ok()?;
185    Some(PcpAnswer::Mapped(Mapping {
186        external: SocketAddr::new(unmapped(Ipv6Addr::from(ip)), external_port),
187        internal_port,
188        lifetime: Duration::from_secs(u64::from(lifetime)),
189        protocol: MappingProtocol::Pcp,
190    }))
191}
192
193/// A NAT-PMP external address request (RFC 6886 section 3.2).
194pub fn nat_pmp_address_request() -> [u8; 2] {
195    [0, 0]
196}
197
198/// A NAT-PMP mapping request (RFC 6886 section 3.3).
199pub fn nat_pmp_map_request(
200    protocol: Protocol,
201    internal_port: u16,
202    config: &MappingConfig,
203) -> [u8; 12] {
204    let mut m = [0u8; 12];
205    m[1] = protocol.nat_pmp_opcode();
206    m[4..6].copy_from_slice(&internal_port.to_be_bytes());
207    m[6..8].copy_from_slice(&config.suggested_port.to_be_bytes());
208    m[8..12].copy_from_slice(
209        &(config.lifetime.as_secs().min(u64::from(u32::MAX)) as u32).to_be_bytes(),
210    );
211    m
212}
213
214/// A NAT-PMP answer.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub enum NatPmpAnswer {
217    /// The external IPv4 address (opcode 128).
218    Address(Ipv4Addr),
219    /// A mapping (opcode 129 or 130): internal port, external port, lifetime.
220    Mapped(u16, u16, Duration),
221    /// A result code other than success.
222    Refused(u16),
223}
224
225/// Parses a NAT-PMP response to `opcode` (RFC 6886 sections 3.2, 3.3, 3.5).
226pub fn parse_nat_pmp_response(data: &[u8], opcode: u8) -> Option<NatPmpAnswer> {
227    if data.len() < 8 || data[0] != 0 || data[1] != 128 + opcode {
228        return None;
229    }
230    let result = u16::from_be_bytes([data[2], data[3]]);
231    if result != 0 {
232        return Some(NatPmpAnswer::Refused(result));
233    }
234    match opcode {
235        0 if data.len() >= 12 => Some(NatPmpAnswer::Address(Ipv4Addr::new(
236            data[8], data[9], data[10], data[11],
237        ))),
238        1 | 2 if data.len() >= 16 => Some(NatPmpAnswer::Mapped(
239            u16::from_be_bytes([data[8], data[9]]),
240            u16::from_be_bytes([data[10], data[11]]),
241            Duration::from_secs(u64::from(u32::from_be_bytes(data[12..16].try_into().ok()?))),
242        )),
243        _ => None,
244    }
245}
246
247/// Whether `data` is a NAT-PMP response (version 0, a response opcode): a gateway that speaks
248/// NAT-PMP only answering a PCP request (RFC 6887 section 9).
249fn answers_nat_pmp(data: &[u8]) -> bool {
250    data.len() >= 4 && data[0] == 0 && data[1] & 0x80 != 0
251}
252
253/// Sends `request` to `to`, retransmitted from `initial` doubling, `attempts` times, and
254/// returns the first answer `accept` takes.
255async fn exchange<T>(
256    socket: &UdpSocket,
257    to: SocketAddr,
258    request: &[u8],
259    initial: Duration,
260    attempts: u32,
261    mut accept: impl FnMut(&[u8]) -> Option<T>,
262) -> io::Result<Option<T>> {
263    let mut wait = initial;
264    let mut buf = [0u8; 1100];
265    for _ in 0..attempts {
266        socket.send_to(request, to).await?;
267        let deadline = tokio::time::Instant::now() + wait;
268        loop {
269            match tokio::time::timeout_at(deadline, socket.recv_from(&mut buf)).await {
270                Err(_) => break,
271                Ok(Err(e)) if e.kind() == io::ErrorKind::ConnectionRefused => break,
272                Ok(Err(e)) => return Err(e),
273                // RFC 6887 section 8.3 / RFC 6886 section 3.1: only answers from the server.
274                Ok(Ok((n, from))) if from == to => {
275                    if let Some(t) = accept(&buf[..n]) {
276                        return Ok(Some(t));
277                    }
278                }
279                Ok(Ok(_)) => {}
280            }
281        }
282        wait *= 2;
283    }
284    Ok(None)
285}
286
287/// Asks the gateway at `gateway` for a mapping of `internal_port` on `local_ip` (the
288/// interface the gateway is reached from): PCP first, NAT-PMP when the gateway does not speak
289/// PCP. `Ok(None)` when no gateway answered; an error when it refused.
290pub async fn map_port(
291    gateway: IpAddr,
292    local_ip: IpAddr,
293    protocol: Protocol,
294    internal_port: u16,
295    config: &MappingConfig,
296) -> io::Result<Option<Mapping>> {
297    let socket = UdpSocket::bind(SocketAddr::new(local_ip, 0)).await?;
298    let server = SocketAddr::new(gateway, SERVER_PORT);
299    map_port_at(&socket, server, local_ip, protocol, internal_port, config).await
300}
301
302/// [`map_port`] from `socket` to the server at `server`.
303async fn map_port_at(
304    socket: &UdpSocket,
305    server: SocketAddr,
306    local_ip: IpAddr,
307    protocol: Protocol,
308    internal_port: u16,
309    config: &MappingConfig,
310) -> io::Result<Option<Mapping>> {
311    let gateway = server.ip();
312    if !config.nat_pmp_only {
313        let nonce: [u8; 12] = rand_nonce();
314        let request = pcp_map_request(local_ip, nonce, protocol, internal_port, config);
315        let mut nat_pmp = false;
316        let answer = exchange(
317            socket,
318            server,
319            &request,
320            config.pcp_initial,
321            config.attempts,
322            |data| {
323                if answers_nat_pmp(data) {
324                    nat_pmp = true;
325                    return Some(None);
326                }
327                parse_pcp_map_response(data, nonce, protocol).map(Some)
328            },
329        )
330        .await?;
331        match answer.flatten() {
332            Some(PcpAnswer::Mapped(mapping)) => return Ok(Some(mapping)),
333            Some(PcpAnswer::Refused(UNSUPP_VERSION)) => {}
334            Some(PcpAnswer::Refused(code)) => {
335                return Err(io::Error::other(format!("PCP MAP refused: result {code}")));
336            }
337            None if nat_pmp => {}
338            None => return Ok(None),
339        }
340    }
341    // NAT-PMP is IPv4 only (RFC 6886 section 1).
342    if !gateway.is_ipv4() {
343        return Ok(None);
344    }
345    let attempts = config.attempts.min(9);
346    let address = exchange(
347        socket,
348        server,
349        &nat_pmp_address_request(),
350        config.nat_pmp_initial,
351        attempts,
352        |data| parse_nat_pmp_response(data, 0),
353    )
354    .await?;
355    let external_ip = match address {
356        Some(NatPmpAnswer::Address(ip)) => ip,
357        Some(NatPmpAnswer::Refused(code)) => {
358            return Err(io::Error::other(format!("NAT-PMP refused: result {code}")));
359        }
360        _ => return Ok(None),
361    };
362    let opcode = protocol.nat_pmp_opcode();
363    let mapped = exchange(
364        socket,
365        server,
366        &nat_pmp_map_request(protocol, internal_port, config),
367        config.nat_pmp_initial,
368        attempts,
369        |data| parse_nat_pmp_response(data, opcode),
370    )
371    .await?;
372    match mapped {
373        Some(NatPmpAnswer::Mapped(internal, external, lifetime)) => Ok(Some(Mapping {
374            external: SocketAddr::new(IpAddr::V4(external_ip), external),
375            internal_port: internal,
376            lifetime,
377            protocol: MappingProtocol::NatPmp,
378        })),
379        Some(NatPmpAnswer::Refused(code)) => Err(io::Error::other(format!(
380            "NAT-PMP mapping refused: result {code}"
381        ))),
382        _ => Ok(None),
383    }
384}
385
386/// A nonce for a PCP MAP request (RFC 6887 section 11.1: random, kept for renewals). From the
387/// standard library's hasher seed: no random-number dependency.
388fn rand_nonce() -> [u8; 12] {
389    use std::collections::hash_map::RandomState;
390    use std::hash::{BuildHasher, Hasher};
391    let mut out = [0u8; 12];
392    for chunk in out.chunks_mut(8) {
393        let mut h = RandomState::new().build_hasher();
394        h.write_u64(
395            std::time::SystemTime::now()
396                .duration_since(std::time::UNIX_EPOCH)
397                .map(|d| d.as_nanos() as u64)
398                .unwrap_or_default(),
399        );
400        let v = h.finish().to_be_bytes();
401        chunk.copy_from_slice(&v[..chunk.len()]);
402    }
403    out
404}
405
406/// The NAT-assisted candidate of `mapping` for the local `base` (RFC 6544 sections 4.2 and
407/// 5.3): a server-reflexive candidate with the type preference 105, for the application to add
408/// with `add_local_candidate`. Over TCP `tcp_type` names its direction (RFC 6544 section 4.2:
409/// for NAT-assisted candidates simultaneous-open 6, active 4, passive 2; an active one is
410/// signalled on port 9).
411pub fn candidate_line(
412    mapping: &Mapping,
413    base: SocketAddr,
414    tcp_type: Option<&str>,
415    foundation: u32,
416) -> String {
417    let (transport, direction) = match tcp_type {
418        None => ("udp", None),
419        Some(t) => (
420            "tcp",
421            Some(match t {
422                "so" => 6u32,
423                "active" => 4,
424                _ => 2,
425            }),
426        ),
427    };
428    let local_preference = match direction {
429        Some(d) => (d << 13) + 8191,
430        None => 65535,
431    };
432    let priority = (105u32 << 24) + (local_preference << 8) + 255;
433    let port = if tcp_type == Some("active") {
434        9
435    } else {
436        mapping.external.port()
437    };
438    let mut line = format!(
439        "candidate:{foundation} 1 {transport} {priority} {} {port} typ srflx raddr {} rport {}",
440        mapping.external.ip(),
441        base.ip(),
442        base.port()
443    );
444    if let Some(t) = tcp_type {
445        line.push_str(&format!(" tcptype {t}"));
446    }
447    line
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    const NONCE: [u8; 12] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
455
456    /// A PCP MAP response (RFC 6887 sections 7.2, 11.1) to `request`.
457    fn pcp_response(request: &[u8], result: u8, external: SocketAddr, lifetime: u32) -> Vec<u8> {
458        let mut r = vec![2, 0x81, 0, result];
459        r.extend_from_slice(&lifetime.to_be_bytes());
460        r.extend_from_slice(&7u32.to_be_bytes()); // epoch
461        r.extend_from_slice(&[0; 12]);
462        r.extend_from_slice(&request[24..42]); // nonce, protocol, reserved, internal port
463        r.extend_from_slice(&external.port().to_be_bytes());
464        r.extend_from_slice(&mapped_v6(external.ip()).octets());
465        r
466    }
467
468    /// RFC 6887 sections 7.1 and 11.1: the MAP request is 60 bytes, version 2, opcode 1, the
469    /// lifetime, the client's address IPv4-mapped, the nonce, the protocol and ports, and the
470    /// all-zeros IPv4-mapped suggested address.
471    #[test]
472    fn a_pcp_map_request_has_the_rfc_6887_layout() {
473        let config = MappingConfig {
474            lifetime: Duration::from_secs(7200),
475            suggested_port: 40000,
476            ..Default::default()
477        };
478        let m = pcp_map_request(
479            "192.168.1.20".parse().unwrap(),
480            NONCE,
481            Protocol::Tcp,
482            7000,
483            &config,
484        );
485        assert_eq!(m.len(), 60);
486        assert_eq!(&m[0..4], &[2, 1, 0, 0]);
487        assert_eq!(&m[4..8], &7200u32.to_be_bytes());
488        assert_eq!(
489            &m[8..24],
490            &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 168, 1, 20]
491        );
492        assert_eq!(&m[24..36], &NONCE);
493        assert_eq!(m[36], 6, "TCP");
494        assert_eq!(&m[40..42], &7000u16.to_be_bytes());
495        assert_eq!(&m[42..44], &40000u16.to_be_bytes());
496        assert_eq!(
497            &m[44..60],
498            &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0]
499        );
500    }
501
502    /// RFC 6887 section 11.1: a response is taken only for the request's nonce; its assigned
503    /// address and port are the mapping's.
504    #[test]
505    fn a_pcp_response_is_taken_for_its_nonce_only() {
506        let request = pcp_map_request(
507            "192.168.1.20".parse().unwrap(),
508            NONCE,
509            Protocol::Udp,
510            4000,
511            &MappingConfig::default(),
512        );
513        let external: SocketAddr = "203.0.113.4:41000".parse().unwrap();
514        let response = pcp_response(&request, 0, external, 3600);
515        assert_eq!(
516            parse_pcp_map_response(&response, NONCE, Protocol::Udp),
517            Some(PcpAnswer::Mapped(Mapping {
518                external,
519                internal_port: 4000,
520                lifetime: Duration::from_secs(3600),
521                protocol: MappingProtocol::Pcp,
522            }))
523        );
524        assert_eq!(
525            parse_pcp_map_response(&response, [0; 12], Protocol::Udp),
526            None
527        );
528        let refused = pcp_response(&request, 8, external, 0);
529        assert_eq!(
530            parse_pcp_map_response(&refused, NONCE, Protocol::Udp),
531            Some(PcpAnswer::Refused(8))
532        );
533    }
534
535    /// RFC 6886 sections 3.2 and 3.3: the request layouts and their responses.
536    #[test]
537    fn nat_pmp_requests_and_responses_have_the_rfc_6886_layout() {
538        assert_eq!(nat_pmp_address_request(), [0, 0]);
539        let config = MappingConfig {
540            lifetime: Duration::from_secs(7200),
541            suggested_port: 0,
542            ..Default::default()
543        };
544        assert_eq!(
545            nat_pmp_map_request(Protocol::Udp, 4000, &config),
546            [0, 1, 0, 0, 0x0f, 0xa0, 0, 0, 0, 0, 0x1c, 0x20]
547        );
548        let address = [0, 128, 0, 0, 0, 0, 0, 9, 203, 0, 113, 4];
549        assert_eq!(
550            parse_nat_pmp_response(&address, 0),
551            Some(NatPmpAnswer::Address("203.0.113.4".parse().unwrap()))
552        );
553        let mapped = [
554            0, 130, 0, 0, 0, 0, 0, 9, 0x1b, 0x58, 0xa0, 0x28, 0, 0, 0x0e, 0x10,
555        ];
556        assert_eq!(
557            parse_nat_pmp_response(&mapped, 2),
558            Some(NatPmpAnswer::Mapped(7000, 41000, Duration::from_secs(3600)))
559        );
560        assert_eq!(parse_nat_pmp_response(&mapped, 1), None, "another opcode's");
561        let refused = [0, 129, 0, 2, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0];
562        assert_eq!(
563            parse_nat_pmp_response(&refused, 1),
564            Some(NatPmpAnswer::Refused(2))
565        );
566    }
567
568    /// RFC 6544 sections 4.2 and 5.3: the NAT-assisted candidate is server-reflexive with the
569    /// type preference 105, related to the base; an active one is on port 9.
570    #[test]
571    fn a_nat_assisted_candidate_has_type_preference_105() {
572        let mapping = Mapping {
573            external: "203.0.113.4:41000".parse().unwrap(),
574            internal_port: 7000,
575            lifetime: Duration::from_secs(3600),
576            protocol: MappingProtocol::Pcp,
577        };
578        let base: SocketAddr = "192.168.1.20:7000".parse().unwrap();
579        let line = candidate_line(&mapping, base, Some("passive"), 3);
580        let priority: u32 = line.split(' ').nth(3).unwrap().parse().unwrap();
581        assert_eq!(priority >> 24, 105);
582        assert_eq!((priority >> 8) & 0xffff, (2 << 13) + 8191);
583        assert!(
584            line.ends_with(
585                "203.0.113.4 41000 typ srflx raddr 192.168.1.20 rport 7000 tcptype passive"
586            ),
587            "{line}"
588        );
589        let active = candidate_line(&mapping, base, Some("active"), 3);
590        assert!(active.contains("203.0.113.4 9 typ srflx"), "{active}");
591        let udp = candidate_line(&mapping, base, None, 4);
592        assert!(udp.contains(" udp "), "{udp}");
593    }
594
595    /// RFC 6887 section 9 and RFC 6886: a gateway that answers a PCP request with a NAT-PMP
596    /// response (it speaks NAT-PMP only) is asked with NAT-PMP: the external address, then the
597    /// mapping. A gateway on loopback, scripted.
598    #[tokio::test]
599    async fn a_nat_pmp_gateway_is_asked_again_with_nat_pmp() -> io::Result<()> {
600        let gateway = UdpSocket::bind("127.0.0.1:0").await?;
601        let at = gateway.local_addr()?;
602        let task = tokio::spawn(async move {
603            let mut buf = [0u8; 100];
604            let mut seen = vec![];
605            for _ in 0..3 {
606                let (n, from) = gateway.recv_from(&mut buf).await.unwrap();
607                seen.push(buf[..n].to_vec());
608                let reply: Vec<u8> = match (buf[0], buf[1]) {
609                    // PCP: NAT-PMP's "unsupported version" answer (RFC 6886 section 3.5).
610                    (2, _) => vec![0, 128 + 1, 0, 1, 0, 0, 0, 0],
611                    (0, 0) => vec![0, 128, 0, 0, 0, 0, 0, 1, 203, 0, 113, 4],
612                    _ => vec![
613                        0, 129, 0, 0, 0, 0, 0, 1, 0x0f, 0xa0, 0xa0, 0x28, 0, 0, 0x0e, 0x10,
614                    ],
615                };
616                gateway.send_to(&reply, from).await.unwrap();
617            }
618            seen
619        });
620        // The test's gateway listens on an ephemeral port: ask through `exchange` the way
621        // `map_port` does, against it.
622        let socket = UdpSocket::bind("127.0.0.1:0").await?;
623        let config = MappingConfig {
624            pcp_initial: Duration::from_millis(50),
625            nat_pmp_initial: Duration::from_millis(50),
626            ..Default::default()
627        };
628        let mapping = map_port_at(
629            &socket,
630            at,
631            "127.0.0.1".parse().unwrap(),
632            Protocol::Udp,
633            4000,
634            &config,
635        )
636        .await?;
637        let seen = task.await.unwrap();
638        assert_eq!(seen[0][0], 2, "PCP first");
639        assert_eq!(seen[1], vec![0, 0], "then the NAT-PMP external address");
640        assert_eq!(seen[2][1], 1, "then the NAT-PMP UDP mapping");
641        assert_eq!(
642            mapping,
643            Some(Mapping {
644                external: "203.0.113.4:41000".parse().unwrap(),
645                internal_port: 4000,
646                lifetime: Duration::from_secs(3600),
647                protocol: MappingProtocol::NatPmp,
648            })
649        );
650        Ok(())
651    }
652
653    /// RFC 6887 section 8.1.1: an unanswered request is sent again; a PCP gateway's answer to
654    /// the retransmission is taken.
655    #[tokio::test]
656    async fn an_unanswered_pcp_request_is_retransmitted() -> io::Result<()> {
657        let gateway = UdpSocket::bind("127.0.0.1:0").await?;
658        let at = gateway.local_addr()?;
659        let task = tokio::spawn(async move {
660            let mut buf = [0u8; 100];
661            let (_, _) = gateway.recv_from(&mut buf).await.unwrap(); // dropped
662            let (n, from) = gateway.recv_from(&mut buf).await.unwrap();
663            let external: SocketAddr = "203.0.113.4:41000".parse().unwrap();
664            gateway
665                .send_to(&pcp_response(&buf[..n], 0, external, 600), from)
666                .await
667                .unwrap();
668        });
669        let socket = UdpSocket::bind("127.0.0.1:0").await?;
670        let config = MappingConfig {
671            pcp_initial: Duration::from_millis(50),
672            ..Default::default()
673        };
674        let mapping = map_port_at(
675            &socket,
676            at,
677            "127.0.0.1".parse().unwrap(),
678            Protocol::Tcp,
679            7000,
680            &config,
681        )
682        .await?;
683        task.await.unwrap();
684        assert_eq!(
685            mapping.map(|m| (m.external.port(), m.protocol)),
686            Some((41000, MappingProtocol::Pcp))
687        );
688        Ok(())
689    }
690}