1use std::io;
21use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
22use std::time::Duration;
23
24use crate::runtime::{AsyncUdpSocket, Runtime};
25
26pub const SERVER_PORT: u16 = 5351;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Protocol {
32 Udp,
34 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum MappingProtocol {
57 Pcp,
59 NatPmp,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct Mapping {
66 pub external: SocketAddr,
68 pub internal_port: u16,
70 pub lifetime: Duration,
72 pub protocol: MappingProtocol,
74}
75
76#[derive(Debug, Clone)]
78pub struct MappingConfig {
79 pub lifetime: Duration,
81 pub suggested_port: u16,
83 pub attempts: u32,
85 pub pcp_initial: Duration,
87 pub nat_pmp_initial: Duration,
89 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
106const 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
123pub 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); m.push(1); 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum PcpAnswer {
155 Mapped(Mapping),
157 Refused(u8),
159}
160
161pub 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 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
194pub fn nat_pmp_address_request() -> [u8; 2] {
196 [0, 0]
197}
198
199pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub enum NatPmpAnswer {
218 Address(Ipv4Addr),
220 Mapped(u16, u16, Duration),
222 Refused(u16),
224}
225
226pub 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
248fn answers_nat_pmp(data: &[u8]) -> bool {
251 data.len() >= 4 && data[0] == 0 && data[1] & 0x80 != 0
252}
253
254async 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 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
289pub 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
314async 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 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
402fn 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
422pub 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 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()); r.extend_from_slice(&[0; 12]);
478 r.extend_from_slice(&request[24..42]); r.extend_from_slice(&external.port().to_be_bytes());
480 r.extend_from_slice(&mapped_v6(external.ip()).octets());
481 r
482 }
483
484 #[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 #[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 #[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 #[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 #[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 (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 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 #[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(); 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}