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