Compare commits
35
Commits
No files matched your search
@@ -0,0 +1 @@
|
||||
/target
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "piik-nat"
|
||||
version = "0.5.5"
|
||||
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "piik-nat"
|
||||
version = "0.5.5"
|
||||
edition = "2021"
|
||||
rust-version = "1.91"
|
||||
publish = false
|
||||
description = "A NAT's port allocator read from a survey, the search it allows, and a small tool that measures both in the field."
|
||||
|
||||
# No dependencies: the model is pure arithmetic and the tool needs only the standard library's sockets.
|
||||
[dependencies]
|
||||
|
||||
[lib]
|
||||
name = "piik_nat"
|
||||
|
||||
[[bin]]
|
||||
name = "piik-nat-lab"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "piik-nat-observer"
|
||||
path = "src/bin/observer.rs"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z"
|
||||
lto = true
|
||||
strip = true
|
||||
panic = "abort"
|
||||
@@ -0,0 +1,41 @@
|
||||
# piik-nat-lab
|
||||
|
||||
一个很小的命令行工具:看看你所在的网络怎样给向外的连接分配端口。两个人能不能直接连上,很大程度取决于这一点。
|
||||
|
||||
## 它做什么,不做什么
|
||||
|
||||
- 向十几个公共 STUN 服务器和我们自己的一台服务器各发几个很小的 UDP 询问包,问“你看到我从哪个地址和端口来”,然后把结果打印出来。通常不到一分钟;最坏情况下所有等待加起来约三分钟,域名解析另计。
|
||||
- 我们自己的那台服务器还会被请求“换一个端口回我一个包”,报告只记录这一次从哪些来源收到了回复,不给你的网络下结论。
|
||||
- 除了这些询问包,不发送任何东西;不扫描,不上传,不改动任何设置。服务器那边不记录谁问过它。
|
||||
- 报告里你的公网地址只显示一半,本机地址只显示类别(私有地址、运营商地址等)。
|
||||
|
||||
## 怎么运行
|
||||
|
||||
- Windows:解压后双击 `运行.bat`。结果显示在窗口里,同时存成同一文件夹下的 `report.txt`。第一次运行时 Windows 可能提示“已保护你的电脑”,点“更多信息”再点“仍要运行”。也可以在终端里直接运行 `piik-nat-lab.exe`,它自己不写任何文件。
|
||||
- macOS、Linux:`chmod +x piik-nat-lab`,然后 `./piik-nat-lab`。
|
||||
|
||||
不要加 `--full`,它会打印完整的公网地址。
|
||||
|
||||
如果开着 VPN 或代理,测到的可能是它的出口而不是你的网络;工具看到多个公网地址时会在报告里写明,并分别判读。能关就关掉再跑一次,不方便关就在回传时说明。不要为了测试去改你无权改动的网络设置。
|
||||
|
||||
## 回传什么
|
||||
|
||||
把 `report.txt` 发给请你测试的人(或者把 `==== report (copy from here) ====` 到 `==== end of report ====` 之间的整段文字复制下来),并写一句这是什么网络:家里宽带、校园网、手机热点、公司网络,哪家运营商。同一个网络跑一次就够;换一个网络欢迎再跑。
|
||||
|
||||
## In English
|
||||
|
||||
`piik-nat-lab` asks public STUN servers and a server of our own which address and port they see for this machine, asks ours to answer once from another of its ports, and prints which answers came in and what the mappings say about the NAT in front of it. It sends nothing else, uploads nothing and changes no setting, and the server keeps no record of who asked. The report shows half of the public address. Run it without arguments (on Windows, `运行.bat` also keeps a copy in `report.txt`), and send the report with one line saying what kind of network it was. Do not pass `--full`.
|
||||
|
||||
## For whoever reads the reports
|
||||
|
||||
`cargo run --example replay -- [--drop <text in an observer's name>] [--only <address letter>] report.txt...` replays pasted reports offline: how often the aim read from earlier mappings would have held each new one, at several packet budgets. No packet is sent. A report says which of its observers are one address by number (`observer address groups`), since names alone do not: the replay reads its destinations from that line.
|
||||
|
||||
## The server of our own
|
||||
|
||||
`piik-nat-observer <first port> <count> [address to bind]` answers STUN Binding requests on a run of UDP ports, and answers from the next port of the run when a request asks for another port. It has one address, keeps nothing and prints nothing about who asked. `OWN_OBSERVER` in `src/main.rs` names the one the tool asks; `--observer <host>:<first port>-<last port>` asks another in its place. A report names its ports `own1:<port>`, and those of a second address `own2:<port>`. A run whose first port does not answer is not asked further, so a server that is down costs one wait and not sixteen; the report counts those ports as not asked.
|
||||
|
||||
A run that leaves this machine nowhere: start `piik-nat-observer 41000 16 127.0.0.1` and `piik-nat-observer 41100 4 127.0.0.2`, then `piik-nat-lab --own-only --observer 127.0.0.1:41000-41015 --observer 127.0.0.2:41100-41103`.
|
||||
|
||||
## Building
|
||||
|
||||
No dependencies. `cargo build --release` in this directory gives `target/release/piik-nat-lab` and `target/release/piik-nat-observer`; `cargo test` runs the model's tests against the simulator. `package/windows/run.bat` is the Windows launcher, shipped beside the executable as `运行.bat`.
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Replays pasted `piik-nat-lab` reports offline: no packet is sent.
|
||||
//!
|
||||
//! cargo run --example replay -- [--drop <text in an observer's name>]... [--only <address letter>] report.txt...
|
||||
//!
|
||||
//! A report masks its addresses, so each address letter and each observer address gets a
|
||||
//! stand-in address. Which observers are one address comes from the report's own line of
|
||||
//! address groups, and from the hosts in the observers' names where a report has no such line.
|
||||
use piik_nat::mapping::{replay, Allocator, Holdout, Model, Sample};
|
||||
use std::{collections::BTreeMap, net::{Ipv4Addr, SocketAddrV4}};
|
||||
|
||||
fn main() {
|
||||
let mut arguments = std::env::args().skip(1);
|
||||
let (mut dropped, mut only, mut files) = (Vec::new(), None, Vec::new());
|
||||
while let Some(argument) = arguments.next() {
|
||||
match argument.as_str() {
|
||||
"--drop" => dropped.extend(arguments.next()),
|
||||
"--only" => only = arguments.next(),
|
||||
_ => files.push(argument),
|
||||
}
|
||||
}
|
||||
for file in files {
|
||||
let text = std::fs::read_to_string(&file).unwrap_or_else(|error| panic!("{file}: {error}"));
|
||||
// "observers: 0=stun.example.com:3478 1=..." names each observer index.
|
||||
let mut observers = BTreeMap::new();
|
||||
let mut hosts: Vec<String> = Vec::new();
|
||||
// "observer address groups: 1 2 2 3 ..." says which observers are one address. Reports
|
||||
// made before that line existed are grouped by the host in an observer's name.
|
||||
let groups: Option<Vec<u8>> =
|
||||
text.lines().find_map(|line| line.trim().strip_prefix("observer address groups: ")?.split_whitespace().map(|group| group.parse().ok()).collect());
|
||||
for line in text.lines().filter_map(|line| line.trim().strip_prefix("observers: ")) {
|
||||
for entry in line.split_whitespace() {
|
||||
let Some((index, name)) = entry.split_once('=') else { continue };
|
||||
let Some((host, port)) = name.rsplit_once(':') else { continue };
|
||||
let (Ok(index), Ok(port)) = (index.parse::<u16>(), port.parse::<u16>()) else { continue };
|
||||
let group = match &groups {
|
||||
Some(groups) => {
|
||||
let Some(group) = groups.get(usize::from(index)) else { continue };
|
||||
*group
|
||||
}
|
||||
None => {
|
||||
let host_index = hosts.iter().position(|known| known == host).unwrap_or_else(|| {
|
||||
hosts.push(host.to_owned());
|
||||
hosts.len() - 1
|
||||
});
|
||||
host_index as u8 + 1
|
||||
}
|
||||
};
|
||||
observers.insert(index, (name.to_owned(), SocketAddrV4::new(Ipv4Addr::new(203, 0, 113, group), port)));
|
||||
}
|
||||
}
|
||||
let mut groups = BTreeMap::<&str, Vec<Sample>>::new();
|
||||
for line in text.lines() {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
let [socket, observer, sent_ms, letter, mapped, local] = fields[..] else { continue };
|
||||
let (Ok(socket), Ok(observer), Ok(sent_ms), Ok(mapped), Ok(local)) =
|
||||
(socket.parse(), observer.parse::<u16>(), sent_ms.parse(), mapped.parse(), local.parse()) else { continue };
|
||||
if !letter.starts_with(|c: char| c.is_ascii_uppercase()) { continue }
|
||||
let Some((name, address)) = observers.get(&observer) else { continue };
|
||||
if dropped.iter().any(|text| name.contains(text.as_str())) || only.as_deref().is_some_and(|wanted| wanted != letter) {
|
||||
continue;
|
||||
}
|
||||
groups.entry(letter).or_default().push(Sample {
|
||||
socket,
|
||||
local_port: local,
|
||||
observer: *address,
|
||||
sent_ms,
|
||||
mapped: SocketAddrV4::new(Ipv4Addr::new(198, 51, 100, 1), mapped),
|
||||
});
|
||||
}
|
||||
println!("\n{file}: offline replay assumes the target's public address is known");
|
||||
for (letter, samples) in groups {
|
||||
read_address(letter, &samples);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_address(letter: &str, samples: &[Sample]) {
|
||||
// A socket that shows a port again is reading the mapping it already has.
|
||||
let mut made: Vec<Sample> = Vec::new();
|
||||
for sample in samples {
|
||||
if !made.iter().any(|earlier| earlier.socket == sample.socket && earlier.mapped == sample.mapped) {
|
||||
made.push(*sample);
|
||||
}
|
||||
}
|
||||
println!("address {letter}: {} samples, {} mappings made", samples.len(), made.len());
|
||||
match Model::read(samples).map(|model| model.allocator) {
|
||||
Err(unusable) => println!(" model: unusable ({unusable:?})"),
|
||||
Ok(Allocator::Point { port, preserved }) => println!(" model: point, port {port}, local port kept: {preserved}"),
|
||||
Ok(Allocator::Cursors(cursors)) => println!(
|
||||
" model: {} cursor(s): {}",
|
||||
cursors.len(),
|
||||
cursors.iter().map(|cursor| format!("{} step {} x{} ({:.1}/s)", cursor.last, cursor.step, cursor.landings, cursor.per_second())).collect::<Vec<_>>().join(", ")
|
||||
),
|
||||
Ok(Allocator::Drawn { low, high }) => println!(" model: drawn between {low} and {high}"),
|
||||
}
|
||||
for (reading, holdout) in [("all earlier mappings", Holdout::Nothing), ("other destinations only", Holdout::Destination), ("other addresses only", Holdout::Address)] {
|
||||
let line: Vec<String> = [8u16, 16, 64, 256, 1024]
|
||||
.iter()
|
||||
.map(|&packets| {
|
||||
let replayed = replay(&made, 8, holdout, packets);
|
||||
format!("{packets}: {}/{} ({} warm-up)", replayed.held, replayed.held + replayed.missed + replayed.no_aim, replayed.too_early)
|
||||
})
|
||||
.collect();
|
||||
println!(" held with packets, reading {reading}: {}", line.join(" "));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
rem Runs piik-nat-lab beside this file, shows its report and keeps a copy in report.txt.
|
||||
chcp 65001 >nul
|
||||
cd /d "%~dp0"
|
||||
echo 正在测试,一般十几秒,网络不通时最多一两分钟,请稍候……
|
||||
piik-nat-lab.exe > report.txt 2>&1
|
||||
type report.txt
|
||||
echo.
|
||||
echo 报告已保存在本文件夹的 report.txt,把这个文件发回即可。
|
||||
pause
|
||||
@@ -0,0 +1,60 @@
|
||||
//! The answering side of a survey, for a server of our own: STUN Binding on a run of UDP ports.
|
||||
//!
|
||||
//! piik-nat-observer <first port> <count> [address to bind]
|
||||
//!
|
||||
//! Each port answers a Binding request with the address it saw. Asked to answer from another
|
||||
//! port, it answers from the next port of the run; it has one address, so a request to answer
|
||||
//! from another address gets no answer. It keeps nothing and prints nothing about who asked.
|
||||
use piik_nat::stun;
|
||||
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
|
||||
use std::sync::Arc;
|
||||
|
||||
const USAGE: &str = "usage: piik-nat-observer <first port> <count> [address to bind]";
|
||||
|
||||
fn main() {
|
||||
let arguments: Vec<String> = std::env::args().skip(1).collect();
|
||||
let parsed = (|| {
|
||||
let first: u16 = arguments.first()?.parse().ok()?;
|
||||
let count: u16 = arguments.get(1)?.parse().ok().filter(|count| *count >= 2)?;
|
||||
let address: Ipv4Addr = arguments.get(2).map_or(Some(Ipv4Addr::UNSPECIFIED), |text| text.parse().ok())?;
|
||||
first.checked_add(count - 1)?;
|
||||
Some((first, count, address))
|
||||
})();
|
||||
let Some((first, count, address)) = parsed else {
|
||||
eprintln!("{USAGE}");
|
||||
std::process::exit(2);
|
||||
};
|
||||
let sockets: Vec<UdpSocket> = (0..count)
|
||||
.map(|index| {
|
||||
UdpSocket::bind((address, first + index)).unwrap_or_else(|error| {
|
||||
eprintln!("cannot bind {address}:{}: {error}", first + index);
|
||||
std::process::exit(1);
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let sockets = Arc::new(sockets);
|
||||
println!("piik-nat-observer {}: answering on {address}:{first} to {}", env!("CARGO_PKG_VERSION"), first + count - 1);
|
||||
let workers: Vec<_> = (0..sockets.len())
|
||||
.map(|index| {
|
||||
let sockets = Arc::clone(&sockets);
|
||||
std::thread::spawn(move || serve(&sockets, index, SocketAddrV4::new(address, first + ((index + 1) % sockets.len()) as u16)))
|
||||
})
|
||||
.collect();
|
||||
for worker in workers {
|
||||
let _ = worker.join();
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers on one port for good. `other` is the port that answers when another port is asked for.
|
||||
fn serve(sockets: &[UdpSocket], index: usize, other: SocketAddrV4) {
|
||||
let mut packet = [0; 64];
|
||||
loop {
|
||||
let Ok((length, SocketAddr::V4(source))) = sockets[index].recv_from(&mut packet) else { continue };
|
||||
let Some(asked) = stun::asked(&packet[..length]) else { continue };
|
||||
if asked.from_other_address {
|
||||
continue;
|
||||
}
|
||||
let from = if asked.from_other_port { &sockets[(index + 1) % sockets.len()] } else { &sockets[index] };
|
||||
let _ = from.send_to(&stun::success(asked.transaction, source, Some(other)), source);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Hole punching through NATs that are hard without being random.
|
||||
//!
|
||||
//! [`mapping`] reads a NAT's port allocator from a survey and gives the ports a peer should send
|
||||
//! to. It is pure arithmetic. [`stun`] is the little of RFC 8489 that a survey needs. The binary `piik-nat-lab`
|
||||
//! runs a survey on a real network and prints what the model reads from it. [`sim`] is a NAT in memory,
|
||||
//! for trying a plan against a kind of NAT without sending anything. [`search`] is the order in
|
||||
//! which one side sends to the other's ports when no port can be named.
|
||||
pub mod mapping;
|
||||
pub mod search;
|
||||
pub mod sim;
|
||||
pub mod stun;
|
||||
@@ -0,0 +1,654 @@
|
||||
//! Measures the NAT in front of this machine and prints what the model reads from it.
|
||||
//!
|
||||
//! It asks a few public STUN servers and a server of our own which address they see, from two
|
||||
//! sockets and then from more when the answers differ, one request at a time, and prints a report
|
||||
//! to copy. It sends nothing else anywhere, and the report shows only half of the public address
|
||||
//! unless `--full` is given.
|
||||
use piik_nat::mapping::{replay, Allocator, Cursor, Holdout, Model, Sample};
|
||||
use piik_nat::stun;
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, ToSocketAddrs, UdpSocket};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Public observers. The first [`PRODUCT_DEFAULTS`] are the servers the product asks by default,
|
||||
/// in its order: its observation needs every one of them to answer, so a report says how many
|
||||
/// did from this network. Several of the others answer on two ports of one address, which shows
|
||||
/// whether a mapping follows the destination's port.
|
||||
/// `stun.chat.bilibili.com:3479` is left out: in seven field surveys it alone reported an address
|
||||
/// other than the one every other observer saw, the port being the same. `stun.qq.com:3478` is
|
||||
/// left out: it answered none of thirty-five surveys.
|
||||
const OBSERVERS: [&str; 11] = [
|
||||
"stun.cloudflare.com:3478",
|
||||
"stun.l.google.com:19302",
|
||||
"stun.nextcloud.com:443",
|
||||
"stun.miwifi.com:3478",
|
||||
"stun.chat.bilibili.com:3478",
|
||||
"stun.cloudflare.com:53",
|
||||
"stun.l.google.com:3478",
|
||||
"stun.hitv.com:3478",
|
||||
"stun.douyucdn.cn:18000",
|
||||
"stun.miwifi.com:3479",
|
||||
"stun.douyucdn.cn:18001",
|
||||
];
|
||||
/// How many of [`OBSERVERS`], from the first, the product asks by default.
|
||||
const PRODUCT_DEFAULTS: usize = 3;
|
||||
/// A server of our own, `piik-nat-observer` on a run of ports of one address. The public servers
|
||||
/// do not answer from elsewhere (six networks, none let such an answer in, open ones among them),
|
||||
/// and none offers many ports of one address: this one answers from its next port when asked,
|
||||
/// and its run shows whether a mapping follows the destination's port or only its address.
|
||||
const OWN_OBSERVER: &str = "stun.piik.tv:3481-3496";
|
||||
/// An observer answers this many requests to answer from elsewhere per address of its own.
|
||||
const FILTERING_PER_ADDRESS: usize = 2;
|
||||
/// One answer is waited for this long, twice.
|
||||
const ANSWER: Duration = Duration::from_millis(700);
|
||||
/// Mappings made from new sockets when the first answers differ, to see the allocator at work.
|
||||
const EXTRA_MAPPINGS: usize = 24;
|
||||
/// A replay judges a mapping once this many were made before it, against the aims a peer allowed
|
||||
/// each of these numbers of packets would be given.
|
||||
const REPLAY_AFTER: usize = 8;
|
||||
const REPLAY_PACKETS: [u16; 3] = [16, 64, 1024];
|
||||
/// Brackets tried where mappings come from an allocator at work.
|
||||
const BRACKETS: usize = 12;
|
||||
|
||||
struct Survey {
|
||||
answered: u32,
|
||||
bracket_attempts: usize,
|
||||
addresses: Vec<Ipv4Addr>,
|
||||
started: Instant,
|
||||
samples: Vec<Sample>,
|
||||
/// Requests that got no answer.
|
||||
unanswered: u32,
|
||||
/// The local port of each socket, by its number.
|
||||
local_ports: Vec<u16>,
|
||||
/// The answers of each bracket: first, middle, last.
|
||||
brackets: Vec<[Sample; 3]>,
|
||||
/// For each observer that can answer from elsewhere: whether its answer from another address
|
||||
/// came in (`None` where it has no other address), and whether its answer from another port
|
||||
/// of the same address did.
|
||||
filtering: Vec<(SocketAddrV4, Option<bool>, bool)>,
|
||||
}
|
||||
impl Survey {
|
||||
fn record_answer(&mut self, mapped: SocketAddrV4) {
|
||||
self.answered += 1;
|
||||
if !self.addresses.contains(mapped.ip()) {
|
||||
self.addresses.push(*mapped.ip());
|
||||
}
|
||||
}
|
||||
|
||||
fn socket(&mut self) -> Option<(UdpSocket, u16)> {
|
||||
let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).ok()?;
|
||||
self.local_ports.push(socket.local_addr().ok()?.port());
|
||||
Some((socket, (self.local_ports.len() - 1) as u16))
|
||||
}
|
||||
/// Asks `observer` from `socket`, waits for the answer and records it under `number`.
|
||||
fn ask(&mut self, socket: &UdpSocket, number: u16, observer: SocketAddrV4) -> Option<SocketAddrV4> {
|
||||
let sent_ms = self.started.elapsed().as_millis() as u32;
|
||||
let transaction = transaction();
|
||||
// The mapping exists once the request has left, so asking again reads the same one.
|
||||
let answer = (0..2).find_map(|_| {
|
||||
socket.send_to(&stun::request(transaction), observer).ok()?;
|
||||
receive(socket, observer, transaction)
|
||||
});
|
||||
let Some((mapped, _)) = answer else {
|
||||
self.unanswered += 1;
|
||||
return None;
|
||||
};
|
||||
self.record_answer(mapped);
|
||||
self.samples.push(Sample { socket: number, local_port: self.local_ports[usize::from(number)], observer, sent_ms, mapped });
|
||||
Some(mapped)
|
||||
}
|
||||
/// Whether this NAT lets in a packet from somewhere a socket never sent to. A new socket asks
|
||||
/// `observer`, which opens its mapping toward that one address and port, and then asks it
|
||||
/// to answer from the sources it names: its other address and port, where it has another
|
||||
/// address, and its other port on the address asked (RFC 5780, section 7.2). Only an answer
|
||||
/// from the source asked for counts, so an observer that ignores the request and answers
|
||||
/// as usual shows nothing. `None` when it names no other port.
|
||||
fn filtering(&mut self, observer: SocketAddrV4) -> Option<(Option<bool>, bool)> {
|
||||
let (socket, _) = self.socket()?;
|
||||
let first = transaction();
|
||||
socket.send_to(&stun::request(first), observer).ok()?;
|
||||
let (_, Some(SocketAddr::V4(elsewhere))) = receive(&socket, observer, first)? else { return None };
|
||||
if elsewhere.port() == 0 || elsewhere.port() == observer.port() {
|
||||
return None;
|
||||
}
|
||||
let answered = |address: bool, from: SocketAddrV4| {
|
||||
let transaction = transaction();
|
||||
let request = stun::request_from_elsewhere(transaction, address, true);
|
||||
(0..2).any(|_| socket.send_to(&request, observer).is_ok() && receive(&socket, from, transaction).is_some())
|
||||
};
|
||||
// An observer whose other address is its own, or none in particular, has another port only.
|
||||
let another_address = !elsewhere.ip().is_unspecified() && elsewhere.ip() != observer.ip();
|
||||
let outcome = (another_address.then(|| answered(true, elsewhere)), answered(false, SocketAddrV4::new(*observer.ip(), elsewhere.port())));
|
||||
self.filtering.push((observer, outcome.0, outcome.1));
|
||||
Some(outcome)
|
||||
}
|
||||
/// Sends from three new sockets in a row, the outer two to `outer` and the middle one to
|
||||
/// `middle`, and only then reads the answers. Where a NAT takes ports from a counter, the
|
||||
/// middle mapping lies between the outer two however fast other traffic moves the counter:
|
||||
/// that is what a peer could be told in place of a guess.
|
||||
fn bracket(&mut self, outer: SocketAddrV4, middle: SocketAddrV4) -> Option<[Sample; 3]> {
|
||||
self.bracket_attempts += 1;
|
||||
let mut asked = Vec::with_capacity(3);
|
||||
for observer in [outer, middle, outer] {
|
||||
let (socket, number) = self.socket()?;
|
||||
asked.push((socket, number, observer, transaction()));
|
||||
}
|
||||
let sent_ms = self.started.elapsed().as_millis() as u32;
|
||||
for (socket, _, observer, transaction) in &asked {
|
||||
socket.send_to(&stun::request(*transaction), observer).ok()?;
|
||||
}
|
||||
let mut answers = Vec::with_capacity(3);
|
||||
for (socket, number, observer, transaction) in &asked {
|
||||
let Some((mapped, _)) = receive(socket, *observer, *transaction) else {
|
||||
self.unanswered += 1;
|
||||
continue;
|
||||
};
|
||||
self.record_answer(mapped);
|
||||
answers.push(Sample { socket: *number, local_port: self.local_ports[usize::from(*number)], observer: *observer, sent_ms, mapped });
|
||||
}
|
||||
let bracket: [Sample; 3] = answers.try_into().ok()?;
|
||||
self.brackets.push(bracket);
|
||||
Some(bracket)
|
||||
}
|
||||
}
|
||||
|
||||
/// A transaction identifier nobody else can guess.
|
||||
fn transaction() -> [u8; 12] {
|
||||
let mut transaction = [0; 12];
|
||||
for chunk in transaction.chunks_mut(8) {
|
||||
chunk.copy_from_slice(&random().to_ne_bytes()[..chunk.len()]);
|
||||
}
|
||||
transaction
|
||||
}
|
||||
|
||||
/// The answer to `transaction` that comes from `from`: the address it reports and the other
|
||||
/// address its server names. A reply from any other source does not count.
|
||||
fn receive(socket: &UdpSocket, from: SocketAddrV4, transaction: [u8; 12]) -> Option<(SocketAddrV4, Option<SocketAddr>)> {
|
||||
let deadline = Instant::now() + ANSWER;
|
||||
let mut packet = [0; 512];
|
||||
loop {
|
||||
// The socket waits only for what is left of the deadline, so a stray packet does not renew it.
|
||||
let left = deadline.checked_duration_since(Instant::now()).filter(|left| !left.is_zero())?;
|
||||
socket.set_read_timeout(Some(left)).ok()?;
|
||||
let Ok((length, source)) = socket.recv_from(&mut packet) else { return None };
|
||||
if source != SocketAddr::V4(from) {
|
||||
continue;
|
||||
}
|
||||
if let Some(stun::Answer { mapped: SocketAddr::V4(mapped), elsewhere }) = stun::answer(&packet[..length], transaction) {
|
||||
return Some((mapped, elsewhere));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A random number from the standard library's hasher, which is keyed from the system's randomness.
|
||||
fn random() -> u64 {
|
||||
RandomState::new().build_hasher().finish()
|
||||
}
|
||||
|
||||
/// The numbers below `count` in a random order.
|
||||
fn shuffled(count: usize) -> Vec<usize> {
|
||||
let mut order: Vec<usize> = (0..count).collect();
|
||||
for index in (1..count).rev() {
|
||||
order.swap(index, (random() % (index as u64 + 1)) as usize);
|
||||
}
|
||||
order
|
||||
}
|
||||
|
||||
/// The address this machine would send from toward `target`; no packet is sent to learn it.
|
||||
fn local_address(target: &str) -> Option<IpAddr> {
|
||||
let socket = UdpSocket::bind(if target.starts_with('[') { "[::]:0" } else { "0.0.0.0:0" }).ok()?;
|
||||
socket.connect(target).ok()?;
|
||||
Some(socket.local_addr().ok()?.ip())
|
||||
}
|
||||
|
||||
const USAGE: &str = "usage: piik-nat-lab [--full] [--own-only] [--observer <host>:<first port>-<last port>]\n\nAsks public STUN servers and a server of our own which address they see for this machine and\nprints what that says about the NAT in front of it. Nothing else is sent anywhere.\n\n --full show the whole public address in the report (it shows half by default)\n --observer ask this server of our own, on each port of the run, in place of the built-in\n one; may be given more than once. The report calls each port own1:<port>\n --own-only ask no public server\n --help show this text";
|
||||
|
||||
fn main() {
|
||||
// Arguments are read before any name is resolved or any socket opened.
|
||||
let arguments: Vec<String> = std::env::args().skip(1).collect();
|
||||
if arguments.iter().any(|argument| argument == "--help" || argument == "-h") {
|
||||
return println!("{USAGE}");
|
||||
}
|
||||
let (mut full, mut public, mut own) = (false, true, Vec::new());
|
||||
let mut rest = arguments.iter();
|
||||
while let Some(argument) = rest.next() {
|
||||
match (argument.as_str(), rest.clone().next()) {
|
||||
("--full", _) => full = true,
|
||||
("--own-only", _) => public = false,
|
||||
("--observer", Some(run)) => {
|
||||
own.push(run.clone());
|
||||
rest.next();
|
||||
}
|
||||
_ => {
|
||||
eprintln!("unknown argument: {argument}\n\n{USAGE}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
if own.is_empty() {
|
||||
own.push(OWN_OBSERVER.to_string());
|
||||
}
|
||||
println!("piik-nat-lab {}: asking STUN servers which address they see.", env!("CARGO_PKG_VERSION"));
|
||||
let mut survey = Survey { answered: 0, bracket_attempts: 0, addresses: Vec::new(), started: Instant::now(), samples: Vec::new(), unanswered: 0, local_ports: Vec::new(), brackets: Vec::new(), filtering: Vec::new() };
|
||||
let (Some((first, first_number)), Some((second, second_number))) = (survey.socket(), survey.socket()) else {
|
||||
return println!("Could not open a UDP socket.");
|
||||
};
|
||||
// Each observer that resolves and answers the first socket takes part. A server of our own
|
||||
// is asked on every port of its run and named by its address's number and its port, so a
|
||||
// report does not carry its host. A run whose first port does not answer is not asked further.
|
||||
let resolve = |name: &str| {
|
||||
name.to_socket_addrs().ok()?.find_map(|address| match address {
|
||||
SocketAddr::V4(address) => Some(address),
|
||||
SocketAddr::V6(_) => None,
|
||||
})
|
||||
};
|
||||
let mut candidates: Vec<(String, SocketAddrV4, Option<SocketAddrV4>)> =
|
||||
OBSERVERS.iter().filter(|_| public).filter_map(|name| Some((name.to_string(), resolve(name)?, None))).collect();
|
||||
let mut own_addresses: Vec<Ipv4Addr> = Vec::new();
|
||||
for run in &own {
|
||||
let ports = run.rsplit_once(':').and_then(|(host, ports)| {
|
||||
let (low, high) = ports.split_once('-')?;
|
||||
Some((host, low.parse::<u16>().ok()?, high.parse::<u16>().ok()?))
|
||||
});
|
||||
let Some((host, low, high)) = ports.filter(|(_, low, high)| low <= high) else {
|
||||
eprintln!("--observer takes <host>:<first port>-<last port>\n\n{USAGE}");
|
||||
std::process::exit(2);
|
||||
};
|
||||
if let Some(address) = resolve(&format!("{host}:{low}")) {
|
||||
let gate = SocketAddrV4::new(*address.ip(), low);
|
||||
let group = own_addresses.iter().position(|known| known == address.ip()).unwrap_or_else(|| {
|
||||
own_addresses.push(*address.ip());
|
||||
own_addresses.len() - 1
|
||||
});
|
||||
candidates.extend((low..=high).map(|port| (format!("own{}:{port}", group + 1), SocketAddrV4::new(*address.ip(), port), Some(gate))));
|
||||
}
|
||||
}
|
||||
let (mut asked, mut unasked) = (0, 0);
|
||||
let mut observers: Vec<(String, SocketAddrV4)> = Vec::new();
|
||||
for (name, address, gate) in candidates {
|
||||
if gate.is_some_and(|gate| gate != address && observers.iter().all(|(_, known)| *known != gate)) {
|
||||
unasked += 1;
|
||||
continue;
|
||||
}
|
||||
asked += 1;
|
||||
if observers.iter().all(|(_, known)| *known != address) && survey.ask(&first, first_number, address).is_some() {
|
||||
observers.push((name, address));
|
||||
}
|
||||
}
|
||||
let questions = Asked { asked, unasked, defaults_silent: public.then(|| silent_defaults(&observers)) };
|
||||
// Two observers are the least that can be compared, on one address or on two. Who stayed
|
||||
// silent is then all such a network has to tell, so the report still says it.
|
||||
if observers.len() < 2 {
|
||||
print!("{}", opening(&survey, &observers, &questions));
|
||||
println!("too few observers answered to read a mapping; UDP may be blocked on this network");
|
||||
return closing(&observers);
|
||||
}
|
||||
for index in shuffled(observers.len()) {
|
||||
survey.ask(&second, second_number, observers[index].1);
|
||||
}
|
||||
// Where a mapping depends on its destination, new sockets show the allocator at work: each
|
||||
// makes one mapping, toward the observers in turn.
|
||||
if !matches!(Model::read(&survey.samples), Ok(Model { allocator: Allocator::Point { .. }, .. })) {
|
||||
for index in 0..EXTRA_MAPPINGS.max(observers.len()) {
|
||||
if let Some((socket, number)) = survey.socket() {
|
||||
survey.ask(&socket, number, observers[index % observers.len()].1);
|
||||
}
|
||||
}
|
||||
// A bracket's two observers are different hosts that saw one public address from the
|
||||
// first socket, so the three mappings are made on one way out.
|
||||
let seen: Vec<(SocketAddrV4, Ipv4Addr)> = observers
|
||||
.iter()
|
||||
.filter_map(|(_, observer)| survey.samples.iter().find(|sample| sample.socket == first_number && sample.observer == *observer).map(|sample| (*observer, *sample.mapped.ip())))
|
||||
.collect();
|
||||
for round in 0..BRACKETS {
|
||||
let (outer, public) = seen[round % seen.len()];
|
||||
let mut others = seen.iter().cycle().skip(round % seen.len() + 1).take(seen.len());
|
||||
if let Some((middle, _)) = others.find(|(other, address)| *address == public && other.ip() != outer.ip()) {
|
||||
survey.bracket(outer, *middle);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A few observers of each address are asked to answer from elsewhere: one that never does
|
||||
// costs its whole wait.
|
||||
let mut elsewhere: Vec<Ipv4Addr> = Vec::new();
|
||||
for (_, observer) in &observers {
|
||||
if elsewhere.iter().filter(|address| *address == observer.ip()).count() < FILTERING_PER_ADDRESS && survey.filtering(*observer).is_some() {
|
||||
elsewhere.push(*observer.ip());
|
||||
}
|
||||
}
|
||||
report(&survey, &observers, &questions, first_number, full);
|
||||
}
|
||||
|
||||
/// The first lines of a report: what was asked and who answered.
|
||||
fn opening(survey: &Survey, observers: &[(String, SocketAddrV4)], Asked { asked, unasked, defaults_silent }: &Asked) -> String {
|
||||
// A silent first port shows only that it did not answer: the rest of its run was not asked.
|
||||
let left = if *unasked > 0 { format!(", {unasked} more not asked after their run's first port stayed silent") } else { String::new() };
|
||||
let mut lines = format!(
|
||||
"\n==== report (copy from here) ====\ntool: piik-nat-lab {}\nobservers answered: {} of {asked} asked{left}; requests answered {}, unanswered {}\n",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
observers.len(),
|
||||
survey.answered,
|
||||
survey.unanswered
|
||||
);
|
||||
if let Some(silent) = defaults_silent {
|
||||
let missing = if silent.is_empty() { String::new() } else { format!("; no answer from {}", silent.join(", ")) };
|
||||
lines += &format!("product's default servers answered: {} of {PRODUCT_DEFAULTS}{missing}\n", PRODUCT_DEFAULTS - silent.len());
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// The last lines of a report: the observers by number.
|
||||
fn closing(observers: &[(String, SocketAddrV4)]) {
|
||||
println!("observers: {}", observers.iter().enumerate().map(|(index, (name, _))| format!("{index}={name}")).collect::<Vec<_>>().join(" "));
|
||||
println!("==== end of report ====");
|
||||
}
|
||||
|
||||
/// The product's default servers that are not among the observers that answered. A name that did
|
||||
/// not resolve and a server that stayed silent both end the product's observation, so they are
|
||||
/// counted together.
|
||||
fn silent_defaults(observers: &[(String, SocketAddrV4)]) -> Vec<&'static str> {
|
||||
OBSERVERS[..PRODUCT_DEFAULTS].iter().copied().filter(|name| observers.iter().all(|(known, _)| known != name)).collect()
|
||||
}
|
||||
|
||||
/// What the first socket's questions came to, beside the observers that answered.
|
||||
struct Asked {
|
||||
asked: usize,
|
||||
/// Ports of our own server left alone after their run's first port stayed silent.
|
||||
unasked: usize,
|
||||
/// The product's default servers that gave no answer; `None` when no public server was asked.
|
||||
defaults_silent: Option<Vec<&'static str>>,
|
||||
}
|
||||
|
||||
/// The cursors of an allocator in one line: each with its last port, its step and how many mappings landed on it.
|
||||
fn cursors_line(cursors: &[Cursor]) -> String {
|
||||
let each: Vec<String> = cursors.iter().map(|cursor| format!("{} step {} x{} ({:.1}/s)", cursor.last, cursor.step, cursor.landings, cursor.per_second())).collect();
|
||||
format!("CURSORS. {} counter(s), next mapping one step past one of: {}", cursors.len(), each.join(", "))
|
||||
}
|
||||
|
||||
/// What the answers that show one public address say, read by themselves.
|
||||
fn read_address(samples: &[Sample], observers: &[(String, SocketAddrV4)]) {
|
||||
match Model::read(samples).map(|model| model.allocator) {
|
||||
Err(unusable) => println!("model: unusable ({unusable:?})"),
|
||||
Ok(Allocator::Point { port, preserved }) => println!("model: POINT. One mapping per socket whatever the destination (port {port}); local port kept: {}", if preserved { "yes" } else { "no" }),
|
||||
Ok(Allocator::Cursors(cursors)) => println!("model: {}", cursors_line(&cursors)),
|
||||
Ok(Allocator::Drawn { low, high }) => println!("model: DRAWN. No port follows another; seen between {low} and {high}"),
|
||||
}
|
||||
// A socket that shows a port again is reading the mapping it already has.
|
||||
let mut made: Vec<Sample> = Vec::new();
|
||||
for sample in samples {
|
||||
if !made.iter().any(|earlier| earlier.socket == sample.socket && earlier.mapped == sample.mapped) {
|
||||
made.push(*sample);
|
||||
}
|
||||
}
|
||||
println!("mappings made: {}", made.len());
|
||||
// The cursors that the mappings toward each observer used: a peer is one more destination.
|
||||
for (index, (_, observer)) in observers.iter().enumerate() {
|
||||
let toward: Vec<(u32, u16)> = made.iter().filter(|sample| sample.observer == *observer).map(|sample| (sample.sent_ms, sample.mapped.port())).collect();
|
||||
if let Allocator::Cursors(cursors) = Allocator::of(&toward) {
|
||||
let each: Vec<String> = cursors.iter().take(6).map(|cursor| format!("{}x{}", cursor.last, cursor.landings)).collect();
|
||||
println!("toward observer {index}: {} mappings on {} cursor(s): {}", toward.len(), cursors.len(), each.join(" "));
|
||||
}
|
||||
}
|
||||
// The survey judged by itself: each mapping against the aim read from the mappings before it.
|
||||
for (reading, holdout) in [("all earlier mappings", Holdout::Nothing), ("other destinations", Holdout::Destination), ("other addresses", Holdout::Address)] {
|
||||
let each: Vec<String> = REPLAY_PACKETS
|
||||
.iter()
|
||||
.map(|&packets| {
|
||||
let replayed = replay(&made, REPLAY_AFTER, holdout, packets);
|
||||
format!("{packets} packets held {} of {} ({} warm-up)", replayed.held, replayed.held + replayed.missed + replayed.no_aim, replayed.too_early)
|
||||
})
|
||||
.collect();
|
||||
println!("replay reading {reading}: {}", each.join("; "));
|
||||
}
|
||||
}
|
||||
|
||||
fn report(survey: &Survey, observers: &[(String, SocketAddrV4)], questions: &Asked, first: u16, full: bool) {
|
||||
// Each public address seen gets a letter, in the order seen.
|
||||
let addresses = &survey.addresses;
|
||||
let letter = |address: &Ipv4Addr| {
|
||||
let index = addresses.iter().position(|known| known == address).expect("recorded answer");
|
||||
if index < 26 { ((b'A' + index as u8) as char).to_string() } else { format!("A{}", index + 1) }
|
||||
};
|
||||
let shown = |address: Ipv4Addr| match full {
|
||||
true => address.to_string(),
|
||||
false => format!("{}.{}.x.x", address.octets()[0], address.octets()[1]),
|
||||
};
|
||||
let local = local_address("1.1.1.1:53");
|
||||
let network = match local {
|
||||
Some(IpAddr::V4(address)) if addresses.contains(&address) => "no NAT: this machine holds the public address",
|
||||
Some(IpAddr::V4(address)) if address.octets()[0] == 100 && address.octets()[1] & 0xc0 == 64 => "carrier address (100.64.0.0/10) on this machine",
|
||||
Some(IpAddr::V4(address)) if address.is_private() => "private address on this machine",
|
||||
Some(_) => "public address on this machine that differs from the one seen",
|
||||
None => "no IPv4 route",
|
||||
};
|
||||
let ipv6 = matches!(local_address("[2606:4700:4700::1111]:53"), Some(IpAddr::V6(address)) if address.segments()[0] & 0xe000 == 0x2000);
|
||||
print!("{}", opening(survey, observers, questions));
|
||||
// Which observers are one address, by number: names alone do not say, since two names can be
|
||||
// one address and one name can be two. The replay reads its destinations from this line.
|
||||
let mut grouped: Vec<Ipv4Addr> = Vec::new();
|
||||
let groups: Vec<String> = observers
|
||||
.iter()
|
||||
.map(|(_, observer)| {
|
||||
let group = grouped.iter().position(|known| known == observer.ip()).unwrap_or_else(|| {
|
||||
grouped.push(*observer.ip());
|
||||
grouped.len() - 1
|
||||
});
|
||||
(group + 1).to_string()
|
||||
})
|
||||
.collect();
|
||||
println!("observer address groups: {}", groups.join(" "));
|
||||
println!("local: {network}; global IPv6: {}", if ipv6 { "yes" } else { "no" });
|
||||
println!("public addresses: {}", addresses.iter().map(|address| format!("{} {}", letter(address), shown(*address))).collect::<Vec<_>>().join(", "));
|
||||
// Whether the mapping follows the destination's port: the same socket, the same address, two ports.
|
||||
let seen = |observer: &SocketAddrV4| survey.samples.iter().find(|sample| sample.socket == first && sample.observer == *observer).map(|sample| sample.mapped);
|
||||
let by_port = observers.iter().enumerate().find_map(|(index, (_, one))| {
|
||||
let (_, other) = observers[index + 1..].iter().find(|(_, other)| other.ip() == one.ip())?;
|
||||
Some(seen(one)? != seen(other)?)
|
||||
});
|
||||
if let Some(by_port) = by_port {
|
||||
println!("same address, other port: {}", if by_port { "another mapping (depends on address and port)" } else { "the same mapping" });
|
||||
}
|
||||
if addresses.len() == 1 {
|
||||
read_address(&survey.samples, observers);
|
||||
} else {
|
||||
// One socket that shows two addresses was sent out by its destination; otherwise each
|
||||
// socket keeps to one way out.
|
||||
let by_destination = survey.samples.iter().any(|one| survey.samples.iter().any(|other| other.socket == one.socket && other.mapped.ip() != one.mapped.ip()));
|
||||
println!(
|
||||
"note: {} public addresses observed, chosen by the {}. A carrier or a router with several lines does this, and so does a proxy or VPN that carries part of the traffic. Each replay assumes the target's public address is known.",
|
||||
addresses.len(),
|
||||
if by_destination { "destination" } else { "socket" }
|
||||
);
|
||||
for address in addresses {
|
||||
let on_address: Vec<Sample> = survey.samples.iter().copied().filter(|sample| sample.mapped.ip() == address).collect();
|
||||
if on_address.is_empty() {
|
||||
println!("-- address {} {}: seen only in brackets", letter(address), shown(*address));
|
||||
continue;
|
||||
}
|
||||
let mut toward: Vec<usize> = on_address.iter().filter_map(|sample| observers.iter().position(|(_, observer)| *observer == sample.observer)).collect();
|
||||
toward.sort();
|
||||
toward.dedup();
|
||||
println!("-- address {} {}: seen by observers {}", letter(address), shown(*address), toward.iter().map(usize::to_string).collect::<Vec<_>>().join(" "));
|
||||
read_address(&on_address, observers);
|
||||
}
|
||||
}
|
||||
// What came in on this run, from which source. It is not a class of NAT: one run through one
|
||||
// observer cannot show that.
|
||||
if survey.filtering.is_empty() {
|
||||
println!("filtering: not measured, no observer here named another port to answer from");
|
||||
} else {
|
||||
println!("filtering: answers asked for from another source, on a socket that had sent only to the observer");
|
||||
for (observer, address, port) in &survey.filtering {
|
||||
let index = observers.iter().position(|(_, known)| known == observer).unwrap_or(99);
|
||||
let came = |came: bool| if came { "came in" } else { "nothing" };
|
||||
println!(" observer {index}: from its other address and port {}; from its other port on the same address {}", address.map_or("not asked, it has one address", came), came(*port));
|
||||
}
|
||||
}
|
||||
if survey.bracket_attempts > 0 {
|
||||
let (mut held, mut widths, mut crossed) = (0, Vec::new(), 0);
|
||||
for [first, middle, last] in &survey.brackets {
|
||||
if first.mapped.ip() != middle.mapped.ip() || last.mapped.ip() != middle.mapped.ip() {
|
||||
crossed += 1;
|
||||
continue;
|
||||
}
|
||||
let (low, high) = (first.mapped.port().min(last.mapped.port()), first.mapped.port().max(last.mapped.port()));
|
||||
widths.push(high - low);
|
||||
held += u32::from(low < middle.mapped.port() && middle.mapped.port() < high);
|
||||
}
|
||||
widths.sort();
|
||||
println!(
|
||||
"brackets: {} attempted, {} incomplete, {crossed} crossed exits, {} complete on one exit, {held} held between the outer ports",
|
||||
survey.bracket_attempts, survey.bracket_attempts - survey.brackets.len(), widths.len()
|
||||
);
|
||||
if let (Some(low), Some(high)) = (widths.first(), widths.last()) {
|
||||
println!("same-exit outer port separation: {low} to {high}, median {}", widths[widths.len() / 2]);
|
||||
}
|
||||
if !survey.brackets.is_empty() {
|
||||
println!("bracket samples (outer observer, middle observer, ms, then address and port of first, middle, last):");
|
||||
}
|
||||
for [first, middle, last] in &survey.brackets {
|
||||
let index = |sample: &Sample| observers.iter().position(|(_, address)| *address == sample.observer).unwrap_or(99);
|
||||
println!(
|
||||
" {:>2} {:>2} {:>5} {} {:>5} {} {:>5} {} {:>5}",
|
||||
index(first),
|
||||
index(middle),
|
||||
first.sent_ms,
|
||||
letter(first.mapped.ip()),
|
||||
first.mapped.port(),
|
||||
letter(middle.mapped.ip()),
|
||||
middle.mapped.port(),
|
||||
letter(last.mapped.ip()),
|
||||
last.mapped.port()
|
||||
);
|
||||
}
|
||||
}
|
||||
println!("samples (socket, observer, ms, address, mapped port, local port):");
|
||||
for sample in &survey.samples {
|
||||
let observer = observers.iter().position(|(_, address)| *address == sample.observer).unwrap_or(99);
|
||||
println!(" {:>2} {:>2} {:>5} {} {:>5} {:>5}", sample.socket, observer, sample.sent_ms, letter(sample.mapped.ip()), sample.mapped.port(), survey.local_ports[usize::from(sample.socket)]);
|
||||
}
|
||||
closing(observers);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A STUN server on the loopback that answers `answers` requests with the address it saw.
|
||||
fn observer(host: Ipv4Addr, answers: usize) -> SocketAddrV4 {
|
||||
let socket = UdpSocket::bind((host, 0)).unwrap();
|
||||
let SocketAddr::V4(address) = socket.local_addr().unwrap() else { unreachable!() };
|
||||
std::thread::spawn(move || {
|
||||
let mut packet = [0; 64];
|
||||
for _ in 0..answers {
|
||||
let Ok((_, SocketAddr::V4(source))) = socket.recv_from(&mut packet) else { return };
|
||||
let mut answer = vec![0x01, 0x01, 0, 12];
|
||||
answer.extend_from_slice(&packet[4..20]);
|
||||
answer.extend_from_slice(&[0x00, 0x20, 0, 8, 0, 0x01]);
|
||||
answer.extend(source.port().to_be_bytes().iter().zip(&packet[4..6]).map(|(byte, mask)| byte ^ mask));
|
||||
answer.extend(source.ip().octets().iter().zip(&packet[4..8]).map(|(byte, mask)| byte ^ mask));
|
||||
socket.send_to(&answer, source).unwrap();
|
||||
}
|
||||
});
|
||||
address
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_names_the_silent_defaults_when_nobody_answered() {
|
||||
let survey = Survey { answered: 0, bracket_attempts: 0, addresses: Vec::new(), started: Instant::now(), samples: Vec::new(), unanswered: 22, local_ports: Vec::new(), brackets: Vec::new(), filtering: Vec::new() };
|
||||
let lines = opening(&survey, &[], &Asked { asked: 11, unasked: 0, defaults_silent: Some(silent_defaults(&[])) });
|
||||
assert!(lines.contains("observers answered: 0 of 11 asked; requests answered 0, unanswered 22\n"), "{lines}");
|
||||
assert!(lines.contains("product's default servers answered: 0 of 3; no answer from stun.cloudflare.com:3478, stun.l.google.com:19302, stun.nextcloud.com:443\n"), "{lines}");
|
||||
// With only our own server asked, the product's servers are not spoken of.
|
||||
assert!(!opening(&survey, &[], &Asked { asked: 16, unasked: 0, defaults_silent: None }).contains("default"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_server_that_did_not_answer_is_named() {
|
||||
let answered = |names: &[&str]| -> Vec<(String, SocketAddrV4)> { names.iter().map(|name| (name.to_string(), SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1))).collect() };
|
||||
assert!(silent_defaults(&answered(&OBSERVERS)).is_empty());
|
||||
assert_eq!(silent_defaults(&answered(&[OBSERVERS[0], OBSERVERS[1], OBSERVERS[4]])), [OBSERVERS[2]]);
|
||||
assert_eq!(silent_defaults(&answered(&["own1:3481"])).len(), PRODUCT_DEFAULTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bracket_is_three_sockets_whose_answers_are_read_after_all_three_have_sent() {
|
||||
let (outer, middle) = (observer(Ipv4Addr::new(127, 0, 0, 1), 2), observer(Ipv4Addr::new(127, 0, 0, 2), 1));
|
||||
let mut survey = Survey { answered: 0, bracket_attempts: 0, addresses: Vec::new(), started: Instant::now(), samples: Vec::new(), unanswered: 0, local_ports: Vec::new(), brackets: Vec::new(), filtering: Vec::new() };
|
||||
let [first, between, last] = survey.bracket(outer, middle).expect("three answers");
|
||||
assert_eq!([first.observer, between.observer, last.observer], [outer, middle, outer]);
|
||||
// No NAT on the loopback: each answer shows its own socket's port.
|
||||
for sample in [first, between, last] {
|
||||
assert_eq!(sample.mapped.port(), sample.local_port);
|
||||
}
|
||||
assert_eq!((survey.bracket_attempts, survey.brackets.len(), survey.answered, survey.unanswered), (1, 1, 3, 0));
|
||||
|
||||
let silent = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let SocketAddr::V4(silent_address) = silent.local_addr().unwrap() else { unreachable!() };
|
||||
assert!(survey.bracket(observer(Ipv4Addr::LOCALHOST, 2), silent_address).is_none());
|
||||
assert_eq!((survey.bracket_attempts, survey.brackets.len(), survey.answered, survey.unanswered), (2, 1, 5, 1));
|
||||
}
|
||||
|
||||
/// A STUN server on the loopback with a second address: it names it in each answer, and
|
||||
/// answers from it, or from another port of its own, when asked to.
|
||||
fn observer_with_another_address(honours: bool) -> SocketAddrV4 {
|
||||
let bind = |host: [u8; 4]| UdpSocket::bind((Ipv4Addr::from(host), 0)).unwrap();
|
||||
let (main, other_port) = (bind([127, 0, 0, 1]), bind([127, 0, 0, 1]));
|
||||
// The other address answers on the number of the other port, as RFC 5780 has it.
|
||||
let other_address = UdpSocket::bind((Ipv4Addr::new(127, 0, 0, 2), other_port.local_addr().unwrap().port())).unwrap();
|
||||
let SocketAddr::V4(address) = main.local_addr().unwrap() else { unreachable!() };
|
||||
let SocketAddr::V4(elsewhere) = other_address.local_addr().unwrap() else { unreachable!() };
|
||||
std::thread::spawn(move || {
|
||||
let mut packet = [0; 64];
|
||||
// One plain request, then two requests to answer from elsewhere, each sent twice when
|
||||
// the answer does not come from where it was asked.
|
||||
for _ in 0..if honours { 3 } else { 5 } {
|
||||
let Ok((length, SocketAddr::V4(source))) = main.recv_from(&mut packet) else { return };
|
||||
let mut answer = vec![0x01, 0x01, 0, 24];
|
||||
answer.extend_from_slice(&packet[4..20]);
|
||||
answer.extend_from_slice(&[0x00, 0x20, 0, 8, 0, 0x01]);
|
||||
answer.extend(source.port().to_be_bytes().iter().zip(&packet[4..6]).map(|(byte, mask)| byte ^ mask));
|
||||
answer.extend(source.ip().octets().iter().zip(&packet[4..8]).map(|(byte, mask)| byte ^ mask));
|
||||
answer.extend_from_slice(&[0x80, 0x2c, 0, 8, 0, 0x01]);
|
||||
answer.extend(elsewhere.port().to_be_bytes());
|
||||
answer.extend(elsewhere.ip().octets());
|
||||
// The flags of a CHANGE-REQUEST, when the request carries one.
|
||||
let from = match (length == 28 && honours).then(|| packet[27]) {
|
||||
Some(flags) if flags & 4 != 0 => &other_address,
|
||||
Some(_) => &other_port,
|
||||
None => &main,
|
||||
};
|
||||
from.send_to(&answer, source).unwrap();
|
||||
}
|
||||
});
|
||||
address
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtering_is_read_from_answers_that_come_from_elsewhere() {
|
||||
let mut survey = Survey { answered: 0, bracket_attempts: 0, addresses: Vec::new(), started: Instant::now(), samples: Vec::new(), unanswered: 0, local_ports: Vec::new(), brackets: Vec::new(), filtering: Vec::new() };
|
||||
// Nothing filters on the loopback: both answers come in.
|
||||
let able = observer_with_another_address(true);
|
||||
assert_eq!(survey.filtering(able), Some((Some(true), true)));
|
||||
assert_eq!(survey.filtering, [(able, Some(true), true)]);
|
||||
// An observer of our own names another port of its one address: only that is asked.
|
||||
let run = [UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(), UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap()];
|
||||
let (SocketAddr::V4(own), SocketAddr::V4(next)) = (run[0].local_addr().unwrap(), run[1].local_addr().unwrap()) else { unreachable!() };
|
||||
std::thread::spawn(move || {
|
||||
let mut packet = [0; 64];
|
||||
for _ in 0..2 {
|
||||
let Ok((length, SocketAddr::V4(source))) = run[0].recv_from(&mut packet) else { return };
|
||||
let asked = stun::asked(&packet[..length]).unwrap();
|
||||
let from = if asked.from_other_port { &run[1] } else { &run[0] };
|
||||
from.send_to(&stun::success(asked.transaction, source, Some(next)), source).unwrap();
|
||||
}
|
||||
});
|
||||
assert_eq!(survey.filtering(own), Some((None, true)));
|
||||
// An observer that names no other address is not asked.
|
||||
assert_eq!(survey.filtering(observer(Ipv4Addr::LOCALHOST, 1)), None);
|
||||
assert_eq!(survey.filtering.len(), 2);
|
||||
// One that names another address and answers as usual all the same shows nothing.
|
||||
assert_eq!(survey.filtering(observer_with_another_address(false)), Some((Some(false), false)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,584 @@
|
||||
//! What a survey tells about a NAT's port allocator, and where its next mappings will be.
|
||||
//!
|
||||
//! A survey is a table of samples: which socket asked which observer when, and the address the
|
||||
//! observer saw. This module reads one of three allocators from it: a point (one mapping whatever
|
||||
//! the destination), cursors (a new mapping lands one step past one of a few counters, which other
|
||||
//! traffic advances too), or draws. For cursors [`Model::aim`] gives the ports a peer should send
|
||||
//! to, and [`replay`] says how often such aims would have held the survey's own mappings.
|
||||
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||
|
||||
/// The lowest port a mapping is expected on; lower ports are not aimed at.
|
||||
pub const LOWEST_PORT: u16 = 1024;
|
||||
/// A cursor's step is at most this.
|
||||
const MAX_STEP: u32 = 16;
|
||||
/// A port joins a run when it lies at most this far past one of the run's ends.
|
||||
const MAX_GAP: i32 = 32;
|
||||
/// A run of this many ports is taken at its word for its step and its traffic; a port seen once
|
||||
/// borrows both from such runs.
|
||||
const BELIEVED: usize = 3;
|
||||
/// The fewest ports a NAT that draws is taken to draw from: the smallest block a carrier hands
|
||||
/// one subscriber. Without it three ports in a row would pass for draws from a set of three.
|
||||
const SMALLEST_SET: f64 = 64.0;
|
||||
/// How often a mapping begins a cursor not seen before, as far as anything is known beforehand.
|
||||
const NEW_CURSOR: f64 = 0.5;
|
||||
/// How often a follower turns up among a run's ports and not past one of its ends: mappings made
|
||||
/// close together reach the NAT in any order.
|
||||
const LATE: f64 = 0.1;
|
||||
/// A cursor's ports leave this much of its predicted traffic outside at each end.
|
||||
const TAIL: f64 = 0.0005;
|
||||
/// A cursor whose traffic could carry it over more ports than this has no ports to aim at.
|
||||
const WIDEST_WINDOW: u32 = 512;
|
||||
|
||||
/// One answer of a survey.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Sample {
|
||||
pub socket: u16,
|
||||
/// The port the socket is bound to on this machine.
|
||||
pub local_port: u16,
|
||||
pub observer: SocketAddrV4,
|
||||
/// Milliseconds since the survey began.
|
||||
pub sent_ms: u32,
|
||||
pub mapped: SocketAddrV4,
|
||||
}
|
||||
|
||||
/// One counter of an allocator: the next mapping that lands on it takes `last + step`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Cursor {
|
||||
pub last: u16,
|
||||
/// When `last` was seen, in milliseconds since the survey began.
|
||||
pub at_ms: u32,
|
||||
pub step: i16,
|
||||
/// How many of the survey's mappings landed on it.
|
||||
pub landings: u16,
|
||||
/// Ports it passed that the survey did not get, over `watched_ms`: other traffic.
|
||||
pub foreign: u16,
|
||||
pub watched_ms: u32,
|
||||
}
|
||||
impl Cursor {
|
||||
/// The port `steps` allocations past the last one seen, when it is a port that is aimed at.
|
||||
fn port(&self, steps: u32) -> Option<u16> {
|
||||
u16::try_from(i64::from(self.last) + i64::from(self.step) * i64::from(steps)).ok().filter(|port| *port >= LOWEST_PORT)
|
||||
}
|
||||
/// The traffic the survey saw, in mappings a second.
|
||||
pub fn per_second(&self) -> f64 {
|
||||
f64::from(self.foreign) * 1000.0 / f64::from(self.watched_ms.max(1))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Allocator {
|
||||
/// One mapping whatever the destination, on the socket's own port when `preserved`.
|
||||
Point { port: u16, preserved: bool },
|
||||
/// Each new mapping lands one step past one of these, the most used first.
|
||||
Cursors(Vec<Cursor>),
|
||||
/// Each new mapping is a draw; these are the lowest and highest ports seen.
|
||||
Drawn { low: u16, high: u16 },
|
||||
}
|
||||
impl Allocator {
|
||||
/// The allocator behind new mappings, each given as its time in milliseconds and its port, in
|
||||
/// the order they were made.
|
||||
pub fn of(allocations: &[(u32, u16)]) -> Self {
|
||||
let ports = || allocations.iter().map(|&(_, port)| port);
|
||||
cursors(allocations).map_or_else(|| Self::Drawn { low: ports().min().unwrap_or(LOWEST_PORT), high: ports().max().unwrap_or(u16::MAX) }, Self::Cursors)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Model {
|
||||
pub address: Ipv4Addr,
|
||||
pub allocator: Allocator,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Unusable {
|
||||
/// No socket asked two observers, so nothing shows whether the mapping depends on them.
|
||||
TooFew,
|
||||
/// The observers saw different addresses.
|
||||
AddressesDiffer,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
/// Reads the allocator from a survey. Samples may come in any order.
|
||||
pub fn read(samples: &[Sample]) -> Result<Self, Unusable> {
|
||||
let first = samples.first().ok_or(Unusable::TooFew)?;
|
||||
let address = *first.mapped.ip();
|
||||
if samples.iter().any(|sample| *sample.mapped.ip() != address) {
|
||||
return Err(Unusable::AddressesDiffer);
|
||||
}
|
||||
let compared = samples.iter().any(|sample| samples.iter().any(|other| other.socket == sample.socket && other.observer != sample.observer));
|
||||
if !compared {
|
||||
return Err(Unusable::TooFew);
|
||||
}
|
||||
let mut ordered = samples.to_vec();
|
||||
ordered.sort_by_key(|sample| sample.sent_ms);
|
||||
// A socket that shows one port to every observer has one mapping. The model speaks for
|
||||
// the earliest socket; the caller keeps that socket.
|
||||
let independent = ordered.iter().all(|sample| ordered.iter().all(|other| other.socket != sample.socket || other.mapped == sample.mapped));
|
||||
if independent {
|
||||
let preserved = ordered.iter().all(|sample| sample.mapped.port() == sample.local_port);
|
||||
return Ok(Self { address, allocator: Allocator::Point { port: ordered[0].mapped.port(), preserved } });
|
||||
}
|
||||
// What remains is one new mapping for each port not seen before on its socket.
|
||||
let mut allocations: Vec<(u32, u16)> = Vec::with_capacity(ordered.len());
|
||||
for (index, sample) in ordered.iter().enumerate() {
|
||||
if !ordered[..index].iter().any(|earlier| earlier.socket == sample.socket && earlier.mapped == sample.mapped) {
|
||||
allocations.push((sample.sent_ms, sample.mapped.port()));
|
||||
}
|
||||
}
|
||||
Ok(Self { address, allocator: Allocator::of(&allocations) })
|
||||
}
|
||||
|
||||
/// The ports a peer allowed `packets` should send to for a mapping made `lead_ms` after the
|
||||
/// survey began, one window for each cursor that gets any. Empty when nothing can be aimed at.
|
||||
///
|
||||
/// A port's worth is its cursor's share of landings times the chance that other traffic
|
||||
/// carries the cursor exactly there, and the worthiest are taken first. So a cursor whose
|
||||
/// traffic could carry it further than the packets reach still gets the ports around its
|
||||
/// likeliest one.
|
||||
///
|
||||
/// Draws seen within a few ports are a block a carrier gave this subscriber: the next mapping
|
||||
/// is somewhere in it, so the aim is the block, and packets left over reach past both ends of
|
||||
/// what was seen, where the block may go on.
|
||||
pub fn aim(&self, lead_ms: u32, packets: u16) -> Vec<Window> {
|
||||
let cursors = match &self.allocator {
|
||||
Allocator::Cursors(cursors) => cursors,
|
||||
Allocator::Drawn { low, high } => {
|
||||
let (seen, packets) = (u32::from(high - low) + 1, u32::from(packets));
|
||||
if seen > WIDEST_WINDOW || packets == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let (first, last) = match packets.checked_sub(seen) {
|
||||
Some(spare) => (u32::from(*low).saturating_sub(spare / 2), u32::from(*high) + spare / 2),
|
||||
None => (u32::from(*low) + (seen - packets) / 2, u32::from(*low) + (seen - packets) / 2 + packets - 1),
|
||||
};
|
||||
let first = first.max(u32::from(LOWEST_PORT));
|
||||
let last = last.min(u32::from(u16::MAX));
|
||||
if first > last {
|
||||
return Vec::new();
|
||||
}
|
||||
return vec![Window { first: first as u16, step: 1, count: (last - first + 1) as u16 }];
|
||||
}
|
||||
Allocator::Point { .. } => return Vec::new(),
|
||||
};
|
||||
let total: f64 = cursors.iter().map(|cursor| f64::from(cursor.landings)).sum();
|
||||
/// One cursor that can be aimed at: its share of landings, the least count of foreign
|
||||
/// allocations, the chance of each count from there, and the counts taken so far.
|
||||
struct Reach {
|
||||
share: f64,
|
||||
low: u32,
|
||||
terms: Vec<f64>,
|
||||
taken: Option<(usize, usize)>,
|
||||
}
|
||||
let mut reaches: Vec<Option<Reach>> = cursors
|
||||
.iter()
|
||||
.map(|cursor| {
|
||||
let (low, terms) = spread(cursor.foreign, cursor.watched_ms, lead_ms.saturating_sub(cursor.at_ms))?;
|
||||
cursor.port(low + 1)?;
|
||||
cursor.port(low + terms.len() as u32)?;
|
||||
Some(Reach { share: f64::from(cursor.landings) / total, low, terms, taken: None })
|
||||
})
|
||||
.collect();
|
||||
for _ in 0..packets {
|
||||
// The worthiest port not yet taken is the likeliest count of a cursor, or a neighbour
|
||||
// of the counts already taken on it: the chances fall away on both sides.
|
||||
let best = reaches
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, reach)| {
|
||||
let reach = reach.as_ref()?;
|
||||
let candidates = match reach.taken {
|
||||
None => [reach.terms.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)).map(|(at, _)| at), None],
|
||||
Some((first, last)) => [first.checked_sub(1), (last + 1 < reach.terms.len()).then_some(last + 1)],
|
||||
};
|
||||
candidates.into_iter().flatten().map(|at| (reach.share * reach.terms[at], index, at)).max_by(|a, b| a.0.total_cmp(&b.0))
|
||||
})
|
||||
.max_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let Some((_, index, at)) = best else { break };
|
||||
let taken = &mut reaches[index].as_mut().unwrap().taken;
|
||||
*taken = Some(taken.map_or((at, at), |(first, last)| (first.min(at), last.max(at))));
|
||||
}
|
||||
cursors
|
||||
.iter()
|
||||
.zip(reaches)
|
||||
.filter_map(|(cursor, reach)| {
|
||||
let reach = reach?;
|
||||
let (first, last) = reach.taken?;
|
||||
Some(Window { first: cursor.port(reach.low + first as u32 + 1)?, step: cursor.step, count: (last - first + 1) as u16 })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// `count` ports from `first` in steps of `step`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Window {
|
||||
pub first: u16,
|
||||
pub step: i16,
|
||||
pub count: u16,
|
||||
}
|
||||
impl Window {
|
||||
pub fn holds(&self, port: u16) -> bool {
|
||||
let distance = i32::from(port) - i32::from(self.first);
|
||||
let step = i32::from(self.step);
|
||||
distance % step == 0 && (0..i32::from(self.count)).contains(&(distance / step))
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of the mappings made before a target a replayed aim may read.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Holdout {
|
||||
/// All of them.
|
||||
Nothing,
|
||||
/// Those toward other destinations, an address and a port being one destination.
|
||||
Destination,
|
||||
/// Those toward other addresses, which is what is known about a peer never sent to.
|
||||
Address,
|
||||
}
|
||||
|
||||
/// How a survey's own mappings fare against the aims read from the mappings before them.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Replay {
|
||||
/// The aim held the mapping's port.
|
||||
pub held: u16,
|
||||
pub missed: u16,
|
||||
/// The mappings before it gave no ports to aim at.
|
||||
pub no_aim: u16,
|
||||
/// Fewer mappings came before it than a reading is asked to have.
|
||||
pub too_early: u16,
|
||||
}
|
||||
|
||||
/// Replays a survey: for each new mapping, would the aim read from the mappings before it, for a
|
||||
/// peer allowed `packets`, have held its port? `made` are the new mappings in the order made, each
|
||||
/// made after the answer to the one before it was read.
|
||||
pub fn replay(made: &[Sample], least: usize, holdout: Holdout, packets: u16) -> Replay {
|
||||
let mut replay = Replay::default();
|
||||
for (index, target) in made.iter().enumerate() {
|
||||
let known: Vec<(u32, u16)> = made[..index]
|
||||
.iter()
|
||||
.filter(|earlier| match holdout {
|
||||
Holdout::Nothing => true,
|
||||
Holdout::Destination => earlier.observer != target.observer,
|
||||
Holdout::Address => earlier.observer.ip() != target.observer.ip(),
|
||||
})
|
||||
.map(|earlier| (earlier.sent_ms, earlier.mapped.port()))
|
||||
.collect();
|
||||
let aim = Model { address: *target.mapped.ip(), allocator: Allocator::of(&known) }.aim(target.sent_ms, packets);
|
||||
let outcome = match () {
|
||||
() if known.len() < least => &mut replay.too_early,
|
||||
() if aim.is_empty() => &mut replay.no_aim,
|
||||
() if aim.iter().any(|window| window.holds(target.mapped.port())) => &mut replay.held,
|
||||
() => &mut replay.missed,
|
||||
};
|
||||
*outcome += 1;
|
||||
}
|
||||
replay
|
||||
}
|
||||
|
||||
/// The cursors behind allocations in the order they were made, the most used first, or `None`
|
||||
/// when the ports are likelier draws.
|
||||
fn cursors(allocations: &[(u32, u16)]) -> Option<Vec<Cursor>> {
|
||||
let (runs, odds) = runs(allocations);
|
||||
if odds <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let mut cursors: Vec<Cursor> = runs.iter().map(|run| cursor(run)).collect();
|
||||
// A port seen once may be a cursor of its own. It is kept with the step the believed ones
|
||||
// have and the traffic they showed together.
|
||||
let believed = |cursor: &&Cursor| usize::from(cursor.landings) >= BELIEVED;
|
||||
let step = cursors.iter().find(believed).map_or(1, |cursor| cursor.step);
|
||||
let (foreign, watched_ms) = cursors.iter().filter(believed).fold((0u16, 0u32), |(foreign, watched), cursor| (foreign.saturating_add(cursor.foreign), watched + cursor.watched_ms));
|
||||
for lone in cursors.iter_mut().filter(|cursor| cursor.landings == 1) {
|
||||
(lone.step, lone.foreign, lone.watched_ms) = (step, foreign, watched_ms);
|
||||
}
|
||||
cursors.sort_by(|a, b| b.landings.cmp(&a.landings).then(b.at_ms.cmp(&a.at_ms)));
|
||||
Some(cursors)
|
||||
}
|
||||
|
||||
/// The runs of ports that follow one another, and the logarithm of how many times likelier the
|
||||
/// ports are as followers of cursors than as draws.
|
||||
///
|
||||
/// As a follower a port belongs to one of the runs so far, each as likely as another. Most often
|
||||
/// it lies past one of the run's two ends, `g` ports out with a chance that falls as `1/g` up to
|
||||
/// [`MAX_GAP`], which favours no step and no direction; now and then ([`LATE`]) it is a port
|
||||
/// between the ends that no mapping holds yet. As the first of a cursor it may be any port. A
|
||||
/// port joins the run that gives it the larger chance. As a draw, a port is one of those left in
|
||||
/// a set as large as the span the ports cover, and no smaller than [`SMALLEST_SET`].
|
||||
fn runs(allocations: &[(u32, u16)]) -> (Vec<Vec<(u32, u16)>>, f64) {
|
||||
let ports = || allocations.iter().map(|&(_, port)| f64::from(port));
|
||||
let set = (ports().fold(f64::MIN, f64::max) - ports().fold(f64::MAX, f64::min) + 1.0).max(SMALLEST_SET);
|
||||
let every = f64::from(u16::MAX - LOWEST_PORT) + 1.0;
|
||||
let gaps: f64 = (1..=MAX_GAP).map(|gap| 1.0 / f64::from(gap)).sum();
|
||||
let mut runs: Vec<Vec<(u32, u16)>> = Vec::new();
|
||||
let mut odds = 0.0;
|
||||
for (index, &(at_ms, port)) in allocations.iter().enumerate() {
|
||||
// The chance of this port as a follower of each run, and the run that gives the most.
|
||||
let follows = runs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(run_index, run)| {
|
||||
let members = || run.iter().map(|&(_, member)| i32::from(member));
|
||||
let (low, high, port) = (members().min()?, members().max()?, i32::from(port));
|
||||
let beyond = (low - port).max(port - high);
|
||||
let chance = match beyond {
|
||||
1..=MAX_GAP => (1.0 - LATE) / 2.0 / (f64::from(beyond) * gaps),
|
||||
// A port a mapping already holds cannot be given again.
|
||||
_ if beyond < 0 && members().all(|member| member != port) => LATE / f64::from(high - low + 1),
|
||||
_ => return None,
|
||||
};
|
||||
Some((chance, run_index))
|
||||
})
|
||||
.max_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let drawn = 1.0 / (set - index as f64).max(1.0);
|
||||
match follows {
|
||||
Some((chance, run_index)) => {
|
||||
odds += ((1.0 - NEW_CURSOR) / runs.len() as f64 * chance / drawn).ln();
|
||||
runs[run_index].push((at_ms, port));
|
||||
}
|
||||
None => {
|
||||
if !runs.is_empty() {
|
||||
odds += (NEW_CURSOR / every / drawn).ln();
|
||||
}
|
||||
// A port seen twice stays with the run that has it; any other begins one.
|
||||
match runs.iter().position(|run| run.iter().any(|&(_, member)| member == port)) {
|
||||
Some(held) => runs[held].push((at_ms, port)),
|
||||
None => runs.push(vec![(at_ms, port)]),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(runs, odds)
|
||||
}
|
||||
|
||||
/// The cursor a run of ports shows. It moves the way its ports did between the earliest and the
|
||||
/// latest of them, upward when they do not say, and it stands on the port furthest that way.
|
||||
fn cursor(run: &[(u32, u16)]) -> Cursor {
|
||||
let times = || run.iter().map(|&(at_ms, _)| at_ms);
|
||||
let (first_ms, at_ms) = (times().min().unwrap_or(0), times().max().unwrap_or(0));
|
||||
let earliest = run.iter().filter(|(at, _)| *at == first_ms).map(|&(_, port)| port).min().unwrap_or(0);
|
||||
let latest = run.iter().filter(|(at, _)| *at == at_ms).map(|&(_, port)| port).max().unwrap_or(0);
|
||||
let mut ports: Vec<u16> = run.iter().map(|&(_, port)| port).collect();
|
||||
ports.sort_unstable();
|
||||
ports.dedup();
|
||||
let divisor = ports.windows(2).fold(0, |divisor, pair| gcd(divisor, u32::from(pair[1] - pair[0])));
|
||||
let step = if (1..=MAX_STEP).contains(&divisor) { divisor as i32 } else { 1 };
|
||||
let (low, high) = (ports[0], ports[ports.len() - 1]);
|
||||
let foreign = u32::from(high - low) / step as u32 + 1 - ports.len() as u32;
|
||||
let downward = latest < earliest;
|
||||
Cursor {
|
||||
last: if downward { low } else { high },
|
||||
at_ms,
|
||||
step: if downward { -step } else { step } as i16,
|
||||
landings: run.len() as u16,
|
||||
foreign: foreign.min(u32::from(u16::MAX)) as u16,
|
||||
watched_ms: at_ms - first_ms,
|
||||
}
|
||||
}
|
||||
|
||||
/// The chance of each count of foreign allocations `lead_ms` after a cursor showed `foreign` of
|
||||
/// them in `watched_ms`: the least count worth considering, and the chances from there up to the
|
||||
/// greatest, leaving [`TAIL`] outside at each end. The count is negative binomial, which is a
|
||||
/// Poisson count whose rate is known only through the watch (Jeffreys' prior on the rate), so a
|
||||
/// short watch gives a wide range. `None` when the range would pass [`WIDEST_WINDOW`].
|
||||
fn spread(foreign: u16, watched_ms: u32, lead_ms: u32) -> Option<(u32, Vec<f64>)> {
|
||||
if lead_ms == 0 {
|
||||
return Some((0, vec![1.0]));
|
||||
}
|
||||
let shape = f64::from(foreign) + 0.5;
|
||||
let watched = f64::from(watched_ms.max(1));
|
||||
let stay = watched / (watched + f64::from(lead_ms));
|
||||
let mut log_term = shape * stay.ln();
|
||||
let (mut total, mut low, mut terms) = (0.0, None, Vec::new());
|
||||
for count in 0..=WIDEST_WINDOW {
|
||||
let term = log_term.exp();
|
||||
if low.is_none() && total + term > TAIL {
|
||||
low = Some(count);
|
||||
}
|
||||
if low.is_some() {
|
||||
terms.push(term);
|
||||
}
|
||||
total += term;
|
||||
if total >= 1.0 - TAIL {
|
||||
return Some((low?, terms));
|
||||
}
|
||||
log_term += ((f64::from(count) + shape) / f64::from(count + 1)).ln() + (1.0 - stay).ln();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn gcd(a: u32, b: u32) -> u32 {
|
||||
if b == 0 { a } else { gcd(b, a % b) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const WAN: Ipv4Addr = Ipv4Addr::new(203, 0, 113, 7);
|
||||
/// The surveys of these tests ask every 400 ms, and their mappings are made 300 ms after the last.
|
||||
const EVERY_MS: u32 = 400;
|
||||
|
||||
fn timed(ports: &[u16]) -> Vec<(u32, u16)> {
|
||||
ports.iter().enumerate().map(|(index, port)| (index as u32 * EVERY_MS, *port)).collect()
|
||||
}
|
||||
/// One sample for each port, from sockets and observers in turn.
|
||||
fn survey(sockets: u8, ports: &[u16]) -> Vec<Sample> {
|
||||
ports
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, port)| Sample {
|
||||
socket: u16::from(index as u8 % sockets),
|
||||
local_port: 50_000 + index as u16 % u16::from(sockets),
|
||||
observer: SocketAddrV4::new(Ipv4Addr::new(198, 51, 100, 1 + (index / sockets as usize) as u8), 3478),
|
||||
sent_ms: index as u32 * EVERY_MS,
|
||||
mapped: SocketAddrV4::new(WAN, *port),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn model(sockets: u8, ports: &[u16]) -> Model {
|
||||
Model::read(&survey(sockets, ports)).unwrap()
|
||||
}
|
||||
fn lead(ports: usize) -> u32 {
|
||||
(ports as u32 - 1) * EVERY_MS + 300
|
||||
}
|
||||
fn counter(last: u16, at_ms: u32, step: i16, landings: u16, foreign: u16) -> Allocator {
|
||||
Allocator::Cursors(vec![Cursor { last, at_ms, step, landings, foreign, watched_ms: at_ms }])
|
||||
}
|
||||
/// The least and greatest count of foreign allocations worth considering.
|
||||
fn range(foreign: u16, watched_ms: u32, lead_ms: u32) -> Option<(u32, u32)> {
|
||||
spread(foreign, watched_ms, lead_ms).map(|(low, terms)| (low, low + terms.len() as u32 - 1))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_a_point_a_counter_and_draws() {
|
||||
assert_eq!(model(1, &[40_000, 40_000, 40_000]).allocator, Allocator::Point { port: 40_000, preserved: false });
|
||||
assert_eq!(model(1, &[50_000, 50_000, 50_000]).allocator, Allocator::Point { port: 50_000, preserved: true });
|
||||
assert_eq!(model(1, &[40_000, 40_002, 40_004]).allocator, counter(40_004, 800, 2, 3, 0));
|
||||
assert_eq!(model(1, &[40_000, 39_999, 39_998]).allocator, counter(39_998, 800, -1, 3, 0));
|
||||
// Other traffic took 2, 0, 3, 1 and 1 allocations between six of ours.
|
||||
assert_eq!(model(2, &[40_000, 40_003, 40_004, 40_008, 40_010, 40_012]).allocator, counter(40_012, 2_000, 1, 6, 7));
|
||||
assert_eq!(model(2, &[51_200, 60_011, 50_333, 64_100, 57_000, 52_048]).allocator, Allocator::Drawn { low: 50_333, high: 64_100 });
|
||||
// One observer says nothing about dependence, and two addresses are not one NAT.
|
||||
let mut one = survey(1, &[40_000, 40_001]);
|
||||
one[1].observer = one[0].observer;
|
||||
assert_eq!(Model::read(&one), Err(Unusable::TooFew));
|
||||
let mut two = survey(1, &[40_000, 40_001]);
|
||||
two[1].mapped = SocketAddrV4::new(Ipv4Addr::new(203, 0, 113, 8), 40_001);
|
||||
assert_eq!(Model::read(&two), Err(Unusable::AddressesDiffer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_several_cursors_and_keeps_draws_apart() {
|
||||
// A survey from the field: one cursor read four times, two read twice and three ports alone.
|
||||
let field = timed(&[14_194, 35_377, 8_225, 14_195, 35_379, 8_226, 14_197, 55_758, 14_198, 30_277, 14_418]);
|
||||
let Allocator::Cursors(cursors) = Allocator::of(&field) else { panic!("not cursors") };
|
||||
assert_eq!(cursors.iter().map(|cursor| (cursor.last, cursor.landings)).collect::<Vec<_>>(), [(14_198, 4), (8_226, 2), (35_379, 2), (14_418, 1), (30_277, 1), (55_758, 1)]);
|
||||
// Mappings that reached the NAT in another order than they were made are the same cursor.
|
||||
assert_eq!(Allocator::of(&[(0, 30_001), (0, 30_000), (500, 30_003), (500, 30_002)]), Allocator::Cursors(vec![Cursor { last: 30_003, at_ms: 500, step: 1, landings: 4, foreign: 0, watched_ms: 500 }]));
|
||||
// Eighteen draws from the whole range with two that fell close together are still draws.
|
||||
let wide = timed(&[51_200, 60_011, 50_333, 64_100, 57_000, 52_048, 9_100, 23_456, 31_000, 44_777, 12_345, 38_080, 60_020, 27_001, 5_150, 47_900, 19_090, 35_555]);
|
||||
assert_eq!(Allocator::of(&wide), Allocator::Drawn { low: 5_150, high: 64_100 });
|
||||
// So is a crowd inside a carrier's block of a thousand ports, where many come close by chance.
|
||||
let block = timed(&[20_512, 20_101, 20_877, 20_530, 20_120, 20_333, 20_890, 20_050, 20_700, 20_345, 20_990, 20_560, 20_222, 20_130, 20_640, 20_015, 20_800, 20_410]);
|
||||
assert!(matches!(Allocator::of(&block), Allocator::Drawn { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_is_aimed_at_whole_and_draws_from_everywhere_not_at_all() {
|
||||
// A field survey: forty-two mappings toward nine destinations, all inside fifty-seven ports.
|
||||
let block = Model { address: Ipv4Addr::LOCALHOST, allocator: Allocator::Drawn { low: 60_523, high: 60_579 } };
|
||||
// Packets to spare reach equally past both ends of what was seen.
|
||||
assert_eq!(block.aim(0, 64), [Window { first: 60_520, step: 1, count: 63 }]);
|
||||
// Fewer packets than ports seen take the middle.
|
||||
assert_eq!(block.aim(0, 16), [Window { first: 60_543, step: 1, count: 16 }]);
|
||||
// The model only aims at ports from LOWEST_PORT up, even when a draw was below it.
|
||||
let low = model(1, &[900, 940, 910, 935, 920, 930, 905, 925]);
|
||||
for (packets, count) in [(64, 0), (16, 0), (256, 24)] {
|
||||
let windows = low.aim(0, packets);
|
||||
let aimed: u32 = windows.iter().map(|window| u32::from(window.count)).sum();
|
||||
assert!(aimed <= u32::from(packets));
|
||||
assert_eq!(aimed, count);
|
||||
assert!(windows.iter().all(|window| window.first >= LOWEST_PORT));
|
||||
}
|
||||
let everywhere = Model { address: Ipv4Addr::LOCALHOST, allocator: Allocator::Drawn { low: 5_150, high: 64_100 } };
|
||||
assert!(everywhere.aim(0, 1024).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draws_seldom_pass_for_cursors() {
|
||||
// Draws from `set` ports in a row, with or without giving a port twice, from a seed.
|
||||
let draws = |seed: u64, set: u64, count: usize, again: bool| {
|
||||
let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
|
||||
let mut ports: Vec<u16> = Vec::new();
|
||||
while ports.len() < count {
|
||||
state ^= state >> 12;
|
||||
state ^= state << 25;
|
||||
state ^= state >> 27;
|
||||
let port = (20_000 + (state.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 33) % set) as u16;
|
||||
if again || !ports.contains(&port) {
|
||||
ports.push(port);
|
||||
}
|
||||
}
|
||||
timed(&ports)
|
||||
};
|
||||
for (set, count, again) in [(64, 18, true), (64, 32, true), (64, 18, false), (1_000, 18, false), (64_000, 18, false), (64_000, 40, false)] {
|
||||
let surveys = 4_000;
|
||||
let read = (0..surveys).filter(|seed| matches!(Allocator::of(&draws(*seed, set, count, again)), Allocator::Cursors(_))).count();
|
||||
assert!(read * 20 <= surveys as usize, "{read} of {surveys} surveys of {count} draws from {set} were read as cursors");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_aim_follows_the_traffic_and_fits_the_packets() {
|
||||
// Nothing foreign in six seconds: 300 ms on, the next port or one of the two after it.
|
||||
assert_eq!(range(0, 6_000, 300), Some((0, 2)));
|
||||
// Fourteen in two seconds is seven a second: about two in 300 ms.
|
||||
let (low, high) = range(14, 2_000, 300).unwrap();
|
||||
assert!(low == 0 && (8..=11).contains(&high));
|
||||
// Nothing is predicted for no time, and heavy unknown traffic has no range.
|
||||
assert_eq!(range(40, 100, 0), Some((0, 0)));
|
||||
assert_eq!(range(2_000, 1_000, 2_000), None);
|
||||
|
||||
let busy = model(2, &[40_000, 40_003, 40_004, 40_008, 40_010, 40_012]);
|
||||
let (low, high) = range(7, 2_000, 300).unwrap();
|
||||
assert_eq!(busy.aim(lead(6), 1_024), [Window { first: 40_012 + 1 + low as u16, step: 1, count: (high - low + 1) as u16 }]);
|
||||
// A counter that would run past the last port, and draws, give nothing to aim at.
|
||||
assert!(model(1, &[65_533, 65_534, 65_535]).aim(lead(3), 1_024).is_empty());
|
||||
assert!(model(2, &[51_200, 60_011, 50_333, 64_100, 57_000, 52_048]).aim(lead(6), 1_024).is_empty());
|
||||
|
||||
// Sixty foreign allocations in a tenth of a second: a tenth of a second on, the cursor may
|
||||
// stand anywhere over more ports than 64 packets reach. The peer gets the 64 around the
|
||||
// likeliest, sixty past the cursor.
|
||||
let heavy = |last, landings| Cursor { last, at_ms: 1_000, step: 1, landings, foreign: 60, watched_ms: 100 };
|
||||
let (low, high) = range(60, 100, 100).unwrap();
|
||||
assert!(high - low + 1 > 64);
|
||||
let windows = Model { address: WAN, allocator: Allocator::Cursors(vec![heavy(40_000, 5)]) }.aim(1_100, 64);
|
||||
assert_eq!((windows.len(), windows[0].count), (1, 64));
|
||||
assert!(windows[0].holds(40_060) && !windows[0].holds(40_001));
|
||||
// Two cursors share the packets by what each port is worth: the one used more gets more.
|
||||
let shared = Model { address: WAN, allocator: Allocator::Cursors(vec![heavy(40_000, 9), heavy(50_000, 3)]) }.aim(1_100, 64);
|
||||
assert_eq!(shared.iter().map(|window| window.count).sum::<u16>(), 64);
|
||||
assert!(shared[0].count > shared[1].count && shared[1].count > 0);
|
||||
// A window counts its ports in its own direction.
|
||||
let down = Window { first: 39_997, step: -1, count: 3 };
|
||||
assert!(down.holds(39_997) && down.holds(39_995) && !down.holds(39_994) && !down.holds(39_998));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replay_judges_each_mapping_by_what_came_before_it() {
|
||||
let observer = |index: u8| SocketAddrV4::new(Ipv4Addr::new(198, 51, 100, 1 + index / 2), 3478 + u16::from(index % 2));
|
||||
let sample = |index: u32, port: u16| Sample { socket: index as u16, local_port: 50_000, observer: observer(index as u8 % 4), sent_ms: index * 100, mapped: SocketAddrV4::new(WAN, port) };
|
||||
// One counter read eight times toward four destinations on two addresses, then a ninth.
|
||||
let mut made: Vec<Sample> = (0..9).map(|index| sample(index, 40_000 + index as u16)).collect();
|
||||
// The first eight have too little before them, which is not a miss; the ninth is held.
|
||||
assert_eq!(replay(&made, 8, Holdout::Nothing, 1_024), Replay { held: 1, too_early: 8, ..Replay::default() });
|
||||
// Asked for four before it, more are judged, whichever the aim may read: other
|
||||
// destinations, or other addresses, which leaves fewer.
|
||||
assert_eq!(replay(&made, 4, Holdout::Destination, 1_024), Replay { held: 4, too_early: 5, ..Replay::default() });
|
||||
assert_eq!(replay(&made, 4, Holdout::Address, 1_024), Replay { held: 3, too_early: 6, ..Replay::default() });
|
||||
// A tenth on a counter nothing showed is missed, and one after draws has nothing to be held by.
|
||||
made.push(sample(9, 45_000));
|
||||
assert_eq!(replay(&made, 8, Holdout::Nothing, 1_024), Replay { held: 1, missed: 1, too_early: 8, ..Replay::default() });
|
||||
let drawn: Vec<Sample> = [51_200, 60_011, 50_333, 64_100, 57_000].iter().enumerate().map(|(index, port)| sample(index as u32, *port)).collect();
|
||||
assert_eq!(replay(&drawn, 4, Holdout::Nothing, 1_024), Replay { no_aim: 1, too_early: 4, ..Replay::default() });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! The order in which one side sends to the ports of the other's address when it cannot be told
|
||||
//! which port a mapping took.
|
||||
//!
|
||||
//! The side that cannot say opens a pool of sockets and sends from each to the one endpoint of
|
||||
//! the side that can. The side that can then sends to ports of the pool's address until a packet
|
||||
//! reaches a pool mapping. Which ports it sends to, and in which order, is this module.
|
||||
//!
|
||||
//! The product owns the order (`stratified_targets` in `channel-native/src/peer/preparation.rs`).
|
||||
//! This copy serves the simulator and follows it.
|
||||
use crate::mapping::LOWEST_PORT;
|
||||
|
||||
/// `parts` ports, one drawn from `draw` inside each of `parts` equal parts of the range from
|
||||
/// [`LOWEST_PORT`] up. The parts are taken in the order of their number with its bits reversed,
|
||||
/// turned by `start`, so every beginning of the order combs the whole range evenly. `parts` is a
|
||||
/// power of two above one.
|
||||
///
|
||||
/// Where a NAT gives neighbouring ports to the mappings made toward one destination, a pool of
|
||||
/// `n` sockets is a run of about `n` ports, and the comb reaches it within about 65,536 / `n`
|
||||
/// packets whatever port the run began at. The draw inside each part keeps the ports off any
|
||||
/// fixed remainder. The count with its bits reversed, which this replaced, has its first 1,024
|
||||
/// ports 64 apart: a pool on every second port was missed by half of its starts, and one on
|
||||
/// every 64th by nearly all.
|
||||
pub fn order(parts: u32, start: u32, mut draw: impl FnMut() -> u64) -> impl Iterator<Item = u16> {
|
||||
assert!(parts.is_power_of_two() && parts > 1, "{parts} parts");
|
||||
let span = u64::from(u16::MAX - LOWEST_PORT) + 1;
|
||||
let shift = u32::BITS - parts.trailing_zeros();
|
||||
(0..parts).map(move |index| {
|
||||
let part = u64::from((index.reverse_bits() >> shift).wrapping_add(start) % parts);
|
||||
let lower = span * part / u64::from(parts);
|
||||
let width = span * (part + 1) / u64::from(parts) - lower;
|
||||
// A 64-bit draw leaves the remainder's bias far below what a simulation can see.
|
||||
LOWEST_PORT + (lower + draw() % width) as u16
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::sim::{Nat, Ports, Scope};
|
||||
use std::collections::HashSet;
|
||||
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||
|
||||
/// What the product sends: 1,024 packets.
|
||||
const PACKETS: u32 = 1024;
|
||||
const POOL: u32 = 256;
|
||||
const SPAN: usize = (u16::MAX - LOWEST_PORT) as usize + 1;
|
||||
|
||||
/// The order for one seed: a start and a sequence of draws that depend on nothing else.
|
||||
fn seeded(seed: u64) -> impl Iterator<Item = u16> {
|
||||
let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
|
||||
let mut draw = move || {
|
||||
// xorshift64: enough for a draw inside a part.
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
state
|
||||
};
|
||||
let start = draw() as u32;
|
||||
order(PACKETS, start, draw)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_part_gets_one_port() {
|
||||
let ports: Vec<u16> = seeded(7).collect();
|
||||
assert_eq!(ports.len(), PACKETS as usize);
|
||||
let parts: HashSet<usize> = ports.iter().map(|port| usize::from(port - LOWEST_PORT) * PACKETS as usize / SPAN).collect();
|
||||
assert_eq!(parts.len(), PACKETS as usize);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_of_the_packets_reach_every_run_as_long_as_the_pool() {
|
||||
for seed in 0..50 {
|
||||
let mut sent = vec![false; 65_536];
|
||||
for port in seeded(seed).take(PACKETS as usize / 2) {
|
||||
sent[usize::from(port)] = true;
|
||||
}
|
||||
let run = POOL as usize;
|
||||
let reached = (usize::from(LOWEST_PORT)..=65_536 - run).all(|first| sent[first..first + run].iter().any(|sent| *sent));
|
||||
assert!(reached, "seed {seed}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pool_at_a_fixed_distance_is_not_missed_by_its_remainder() {
|
||||
// The count with its bits reversed reached 50, 25, 13 and 4 in 100 of these pools.
|
||||
for stride in [2usize, 4, 8, 64] {
|
||||
let reached = (0..400u64)
|
||||
.filter(|seed| {
|
||||
let first = (seed.wrapping_mul(0xD1B5_4A32_D192_ED03) >> 40) as usize % SPAN;
|
||||
let pool: HashSet<u16> = (0..POOL as usize).map(|index| LOWEST_PORT + ((first + stride * index) % SPAN) as u16).collect();
|
||||
seeded(*seed).any(|port| pool.contains(&port))
|
||||
})
|
||||
.count();
|
||||
assert!(reached >= 380, "stride {stride}: {reached} of 400");
|
||||
}
|
||||
}
|
||||
|
||||
const PEER: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::new(203, 0, 113, 9), 40_123);
|
||||
|
||||
/// How many packets the side with one endpoint sends before one reaches a pool mapping, where
|
||||
/// the pool's NAT lets a packet in only from the endpoint its socket sent to.
|
||||
fn packets_until_reached(seed: u64, ports: Ports, foreign_per_second: f64) -> Option<usize> {
|
||||
let mut nat = Nat::new(seed, Ipv4Addr::new(198, 51, 100, 7), Scope::AddressAndPort, Scope::AddressAndPort, ports, foreign_per_second);
|
||||
// The pool is made at one socket every two milliseconds, as the product makes it.
|
||||
for socket in 0..POOL {
|
||||
nat.send(socket, PEER, socket * 2);
|
||||
}
|
||||
seeded(seed).position(|port| nat.receive(port, PEER).is_some()).map(|index| index + 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pool_on_one_destinations_counter_is_reached_by_half_of_the_packets() {
|
||||
// What a campus network showed: a counter for each destination, counting up by one, with
|
||||
// nobody else sending to that destination.
|
||||
for seed in 0..200 {
|
||||
let packets = packets_until_reached(seed, Ports::Destinations { counters: 4096 }, 0.0);
|
||||
assert!(packets.is_some_and(|packets| packets <= PACKETS as usize / 2), "seed {seed}: {packets:?}");
|
||||
}
|
||||
// Other subscribers taking fifty ports a second from the same counter stretch the run,
|
||||
// and a longer run is no harder to reach.
|
||||
for seed in 0..200 {
|
||||
assert!(packets_until_reached(seed, Ports::Destinations { counters: 4096 }, 50.0).is_some(), "seed {seed}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pool_drawn_at_random_is_reached_as_often_as_by_distinct_random_ports() {
|
||||
// 256 mappings and 1,024 ports among 64,512: about 98 in 100 whatever the ports.
|
||||
let reached = (0..400).filter(|seed| packets_until_reached(*seed, Ports::Drawn, 0.0).is_some()).count();
|
||||
assert!(reached >= 380, "{reached} of 400");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! A NAT in memory, for trying plans without a network.
|
||||
//!
|
||||
//! It gives public ports to outgoing packets the way a chosen kind of NAT does, lets other
|
||||
//! subscribers take ports meanwhile, and decides what may come back in. Nothing here opens a
|
||||
//! socket or sends a packet: a test asks it where a packet would leave from, and whether one
|
||||
//! arriving would get through.
|
||||
use crate::mapping::LOWEST_PORT;
|
||||
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||
|
||||
/// How much of a destination a mapping or a filter is tied to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
/// Nothing: one mapping per socket, or packets let in from anywhere.
|
||||
Any,
|
||||
/// The destination's address.
|
||||
Address,
|
||||
/// Its address and port.
|
||||
AddressAndPort,
|
||||
}
|
||||
|
||||
/// How a new mapping gets its port.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Ports {
|
||||
/// The socket's own port.
|
||||
Kept,
|
||||
/// One counter for every mapping.
|
||||
Counter { step: u16 },
|
||||
/// Several counters. Each walks a block of `block` ports and moves on `stride` blocks at the
|
||||
/// block's end. A destination uses a few of them, the first half the time, the second a
|
||||
/// quarter and so on, and which one a mapping takes does not follow its socket from one
|
||||
/// destination to another.
|
||||
Lanes { counters: u16, block: u16, stride: u16 },
|
||||
/// A counter for each of `counters` groups of destinations, counting up by one. A
|
||||
/// destination's address and its port without the lowest bit choose its group, so with many
|
||||
/// groups a destination nobody else sends to has a counter to itself. A campus network showed
|
||||
/// this: toward sixteen ports of one address, each even port and the odd one above it shared
|
||||
/// a counter, and 33 of 34 mappings took the port after the last.
|
||||
Destinations { counters: u16 },
|
||||
/// A draw from all ports.
|
||||
Drawn,
|
||||
}
|
||||
|
||||
struct Mapped {
|
||||
socket: u32,
|
||||
to: SocketAddrV4,
|
||||
port: u16,
|
||||
sent: Vec<SocketAddrV4>,
|
||||
}
|
||||
|
||||
pub struct Nat {
|
||||
pub address: Ipv4Addr,
|
||||
mapping: Scope,
|
||||
filtering: Scope,
|
||||
ports: Ports,
|
||||
/// Mappings that other subscribers make on each counter in a second.
|
||||
foreign_per_second: f64,
|
||||
secret: u64,
|
||||
random: u64,
|
||||
/// The port each counter gives next.
|
||||
counters: Vec<u16>,
|
||||
now_ms: u32,
|
||||
mappings: Vec<Mapped>,
|
||||
}
|
||||
|
||||
const SPAN: u32 = u16::MAX as u32 - LOWEST_PORT as u32 + 1;
|
||||
/// The local port of socket `socket`, which a NAT that keeps ports shows.
|
||||
pub fn local_port(socket: u32) -> u16 {
|
||||
50_000 + (socket % 10_000) as u16
|
||||
}
|
||||
|
||||
fn mix(value: u64) -> u64 {
|
||||
let value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
let value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
value ^ (value >> 31)
|
||||
}
|
||||
|
||||
impl Nat {
|
||||
pub fn new(seed: u64, address: Ipv4Addr, mapping: Scope, filtering: Scope, ports: Ports, foreign_per_second: f64) -> Self {
|
||||
let mut nat = Self {
|
||||
address,
|
||||
mapping,
|
||||
filtering,
|
||||
ports,
|
||||
foreign_per_second,
|
||||
secret: mix(seed),
|
||||
random: mix(seed.wrapping_add(1)) | 1,
|
||||
counters: Vec::new(),
|
||||
now_ms: 0,
|
||||
mappings: Vec::new(),
|
||||
};
|
||||
let counters = match ports {
|
||||
Ports::Lanes { counters, .. } | Ports::Destinations { counters } => counters,
|
||||
_ => 1,
|
||||
};
|
||||
nat.counters = (0..counters).map(|_| LOWEST_PORT + (nat.draw() % u64::from(SPAN)) as u16).collect();
|
||||
nat
|
||||
}
|
||||
|
||||
fn draw(&mut self) -> u64 {
|
||||
self.random ^= self.random >> 12;
|
||||
self.random ^= self.random << 25;
|
||||
self.random ^= self.random >> 27;
|
||||
self.random.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
|
||||
/// The port a counter gives after `port`.
|
||||
fn after(&self, port: u16) -> u16 {
|
||||
let next = match self.ports {
|
||||
Ports::Counter { step } => u32::from(port) + u32::from(step),
|
||||
Ports::Lanes { block, stride, .. } => {
|
||||
let offset = (u32::from(port) - u32::from(LOWEST_PORT)) % u32::from(block);
|
||||
match offset + 1 < u32::from(block) {
|
||||
true => u32::from(port) + 1,
|
||||
false => u32::from(port) + 1 + u32::from(stride - 1) * u32::from(block),
|
||||
}
|
||||
}
|
||||
Ports::Kept | Ports::Drawn | Ports::Destinations { .. } => u32::from(port) + 1,
|
||||
};
|
||||
(u32::from(LOWEST_PORT) + (next - u32::from(LOWEST_PORT)) % SPAN) as u16
|
||||
}
|
||||
|
||||
fn take(&mut self, counter: usize) -> u16 {
|
||||
let port = self.counters[counter];
|
||||
self.counters[counter] = self.after(port);
|
||||
port
|
||||
}
|
||||
|
||||
/// Lets time pass: other subscribers take ports from every counter.
|
||||
fn pass(&mut self, now_ms: u32) {
|
||||
let mean = self.foreign_per_second * f64::from(now_ms.saturating_sub(self.now_ms)) / 1000.0;
|
||||
self.now_ms = self.now_ms.max(now_ms);
|
||||
if mean <= 0.0 {
|
||||
return;
|
||||
}
|
||||
for counter in 0..self.counters.len() {
|
||||
// A Poisson count by multiplying uniform draws down to its floor.
|
||||
let (floor, mut product) = ((-mean).exp(), 1.0);
|
||||
loop {
|
||||
product *= (self.draw() >> 11) as f64 / (1u64 << 53) as f64;
|
||||
if product <= floor {
|
||||
break;
|
||||
}
|
||||
self.take(counter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The counter a new mapping from `socket` to `to` takes.
|
||||
fn lane(&self, socket: u32, to: SocketAddrV4, counters: u16) -> usize {
|
||||
let destination = mix(self.secret ^ (u64::from(u32::from(*to.ip())) << 16) ^ u64::from(to.port()));
|
||||
let rank = mix(destination ^ u64::from(socket).wrapping_mul(0x9E37_79B9_7F4A_7C15)).trailing_ones().min(5);
|
||||
(mix(destination.wrapping_add(u64::from(rank))) % u64::from(counters)) as usize
|
||||
}
|
||||
|
||||
/// A packet leaves `socket` for `to` at `now_ms`. Returns the public port it leaves from.
|
||||
pub fn send(&mut self, socket: u32, to: SocketAddrV4, now_ms: u32) -> u16 {
|
||||
self.pass(now_ms);
|
||||
let mapping = self.mapping;
|
||||
let shares = |mapped: &Mapped| {
|
||||
mapped.socket == socket
|
||||
&& match mapping {
|
||||
Scope::Any => true,
|
||||
Scope::Address => mapped.to.ip() == to.ip(),
|
||||
Scope::AddressAndPort => mapped.to == to,
|
||||
}
|
||||
};
|
||||
if let Some(mapped) = self.mappings.iter_mut().find(|mapped| shares(mapped)) {
|
||||
if !mapped.sent.contains(&to) {
|
||||
mapped.sent.push(to);
|
||||
}
|
||||
return mapped.port;
|
||||
}
|
||||
let port = match self.ports {
|
||||
Ports::Kept => local_port(socket),
|
||||
Ports::Counter { .. } => self.take(0),
|
||||
Ports::Lanes { counters, .. } => self.take(self.lane(socket, to, counters)),
|
||||
Ports::Destinations { counters } => {
|
||||
let group = mix(self.secret ^ (u64::from(u32::from(*to.ip())) << 16) ^ u64::from(to.port() >> 1)) % u64::from(counters);
|
||||
self.take(group as usize)
|
||||
}
|
||||
Ports::Drawn => LOWEST_PORT + (self.draw() % u64::from(SPAN)) as u16,
|
||||
};
|
||||
self.mappings.push(Mapped { socket, to, port, sent: vec![to] });
|
||||
port
|
||||
}
|
||||
|
||||
/// A packet arrives at public port `port` from `from`. Returns the socket it reaches, when the
|
||||
/// NAT lets it in.
|
||||
pub fn receive(&self, port: u16, from: SocketAddrV4) -> Option<u32> {
|
||||
let filtering = self.filtering;
|
||||
self.mappings
|
||||
.iter()
|
||||
.find(|mapped| {
|
||||
mapped.port == port
|
||||
&& match filtering {
|
||||
Scope::Any => true,
|
||||
Scope::Address => mapped.sent.iter().any(|sent| sent.ip() == from.ip()),
|
||||
Scope::AddressAndPort => mapped.sent.contains(&from),
|
||||
}
|
||||
})
|
||||
.map(|mapped| mapped.socket)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::mapping::{Allocator, Model, Sample};
|
||||
|
||||
const LANES: Ports = Ports::Lanes { counters: 32, block: 31, stride: 8 };
|
||||
const HARD: Ipv4Addr = Ipv4Addr::new(203, 0, 113, 7);
|
||||
const EASY: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 9);
|
||||
|
||||
fn observer(index: u32) -> SocketAddrV4 {
|
||||
// Two ports on each of several addresses, as public servers offer.
|
||||
SocketAddrV4::new(Ipv4Addr::new(198, 51, 100, 1 + (index / 2) as u8), 3478 + (index % 2) as u16)
|
||||
}
|
||||
|
||||
/// A survey as the tool makes it: two sockets ask every observer, then `extra` new sockets ask
|
||||
/// one observer each, a tenth of a second apart. Returns the samples and the time it ended.
|
||||
fn survey(nat: &mut Nat, observers: u32, extra: u32) -> (Vec<Sample>, u32) {
|
||||
let (mut samples, mut now_ms) = (Vec::new(), 0);
|
||||
let asks = (0..2).flat_map(|socket| (0..observers).map(move |index| (socket, index))).chain((2..2 + extra).map(|socket| (socket, socket % observers)));
|
||||
for (socket, index) in asks {
|
||||
now_ms += 100;
|
||||
let mapped = SocketAddrV4::new(nat.address, nat.send(socket, observer(index), now_ms));
|
||||
samples.push(Sample { socket: socket as u16, local_port: local_port(socket), observer: observer(index), sent_ms: now_ms, mapped });
|
||||
}
|
||||
(samples, now_ms)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_model_reads_each_kind_of_nat() {
|
||||
let read = |mapping, ports| {
|
||||
let mut nat = Nat::new(7, HARD, mapping, Scope::AddressAndPort, ports, 0.2);
|
||||
Model::read(&survey(&mut nat, 6, 24).0).unwrap().allocator
|
||||
};
|
||||
assert_eq!(read(Scope::Any, Ports::Kept), Allocator::Point { port: local_port(0), preserved: true });
|
||||
assert!(matches!(read(Scope::Any, Ports::Drawn), Allocator::Point { preserved: false, .. }));
|
||||
assert!(matches!(read(Scope::AddressAndPort, Ports::Counter { step: 1 }), Allocator::Cursors(cursors) if cursors.len() == 1));
|
||||
assert!(matches!(read(Scope::AddressAndPort, LANES), Allocator::Cursors(cursors) if cursors.len() > 3));
|
||||
assert!(matches!(read(Scope::AddressAndPort, Ports::Drawn), Allocator::Drawn { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filter_lets_in_what_its_scope_allows() {
|
||||
let peer = SocketAddrV4::new(EASY, 40_000);
|
||||
let other_port = SocketAddrV4::new(EASY, 40_001);
|
||||
let stranger = SocketAddrV4::new(Ipv4Addr::new(198, 51, 100, 77), 40_000);
|
||||
let admits = |filtering| {
|
||||
let mut nat = Nat::new(1, HARD, Scope::AddressAndPort, filtering, Ports::Counter { step: 1 }, 0.0);
|
||||
let port = nat.send(3, peer, 10);
|
||||
[peer, other_port, stranger].map(|from| nat.receive(port, from) == Some(3))
|
||||
};
|
||||
assert_eq!(admits(Scope::Any), [true, true, true]);
|
||||
assert_eq!(admits(Scope::Address), [true, true, false]);
|
||||
assert_eq!(admits(Scope::AddressAndPort), [true, false, false]);
|
||||
}
|
||||
|
||||
/// A NAT with one mapping per socket against one with lanes: the hard side opens `sockets`
|
||||
/// toward the easy side's mapping, and the easy side sends to the ports the model aims at.
|
||||
/// Returns how many of `trials` pairs met.
|
||||
fn point_meets_lanes(observers: u32, extra: u32, sockets: u32, trials: u64) -> u64 {
|
||||
(0..trials)
|
||||
.filter(|&seed| {
|
||||
let mut hard = Nat::new(seed, HARD, Scope::AddressAndPort, Scope::AddressAndPort, LANES, 0.5);
|
||||
let mut easy = Nat::new(seed + 9_000, EASY, Scope::Any, Scope::AddressAndPort, Ports::Kept, 0.0);
|
||||
let (samples, ended_ms) = survey(&mut hard, observers, extra);
|
||||
let peer = SocketAddrV4::new(EASY, easy.send(0, observer(0), 0));
|
||||
let open_ms = ended_ms + 300;
|
||||
let windows = Model::read(&samples).unwrap().aim(open_ms, 1_024);
|
||||
let opened: Vec<u16> = (0..sockets).map(|socket| hard.send(1_000 + socket, peer, open_ms)).collect();
|
||||
windows.iter().any(|window| {
|
||||
(0..window.count).any(|index| {
|
||||
let port = (i32::from(window.first) + i32::from(window.step) * i32::from(index)) as u16;
|
||||
easy.send(0, SocketAddrV4::new(HARD, port), open_ms + 50);
|
||||
// A packet that finds a mapping of the hard side gets in, and its answer comes back.
|
||||
opened.contains(&port) && hard.receive(port, peer).is_some() && easy.receive(peer.port(), SocketAddrV4::new(HARD, port)) == Some(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
.count() as u64
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_destinations_read_and_more_sockets_opened_meet_more_often() {
|
||||
const TRIALS: u64 = 400;
|
||||
let few = [point_meets_lanes(4, 10, 1, TRIALS), point_meets_lanes(4, 10, 8, TRIALS)];
|
||||
let many = [point_meets_lanes(12, 36, 1, TRIALS), point_meets_lanes(12, 36, 8, TRIALS)];
|
||||
eprintln!("point x lanes, met of {TRIALS} with one and with eight sockets: four destinations read {few:?}, twelve read {many:?}");
|
||||
assert!(few[1] > few[0] && many[1] > many[0] && many[0] > few[0] && many[1] > few[1]);
|
||||
assert!(many[1] * 2 > TRIALS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! The Binding request and the mapped address of its answer (RFC 8489, sections 5, 14.1 and 14.2),
|
||||
//! and the request that asks a server to answer from elsewhere (RFC 5780, sections 7.2 and 7.4).
|
||||
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4};
|
||||
|
||||
const BINDING_REQUEST: u16 = 0x0001;
|
||||
const BINDING_SUCCESS: u16 = 0x0101;
|
||||
const MAGIC_COOKIE: [u8; 4] = [0x21, 0x12, 0xa4, 0x42];
|
||||
const MAPPED_ADDRESS: u16 = 0x0001;
|
||||
const XOR_MAPPED_ADDRESS: u16 = 0x0020;
|
||||
const CHANGE_REQUEST: u16 = 0x0003;
|
||||
/// The server's other address and port: CHANGED-ADDRESS in RFC 3489, OTHER-ADDRESS in RFC 5780.
|
||||
const CHANGED_ADDRESS: u16 = 0x0005;
|
||||
const OTHER_ADDRESS: u16 = 0x802c;
|
||||
|
||||
/// A Binding request without attributes.
|
||||
pub fn request(transaction: [u8; 12]) -> [u8; 20] {
|
||||
let mut packet = [0; 20];
|
||||
packet[..2].copy_from_slice(&BINDING_REQUEST.to_be_bytes());
|
||||
packet[4..8].copy_from_slice(&MAGIC_COOKIE);
|
||||
packet[8..].copy_from_slice(&transaction);
|
||||
packet
|
||||
}
|
||||
|
||||
/// A Binding request that asks the server to answer from its other address, its other port, or
|
||||
/// both. A NAT that lets such an answer in does not filter by where a packet comes from.
|
||||
pub fn request_from_elsewhere(transaction: [u8; 12], address: bool, port: bool) -> [u8; 28] {
|
||||
let mut packet = [0; 28];
|
||||
packet[..20].copy_from_slice(&request(transaction));
|
||||
packet[3] = 8;
|
||||
packet[20..24].copy_from_slice(&[(CHANGE_REQUEST >> 8) as u8, CHANGE_REQUEST as u8, 0, 4]);
|
||||
packet[27] = u8::from(address) << 2 | u8::from(port) << 1;
|
||||
packet
|
||||
}
|
||||
|
||||
/// What a Binding request asks for, as a server reads it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Asked {
|
||||
pub transaction: [u8; 12],
|
||||
pub from_other_address: bool,
|
||||
pub from_other_port: bool,
|
||||
}
|
||||
|
||||
/// A Binding request, or `None` for any other packet.
|
||||
pub fn asked(packet: &[u8]) -> Option<Asked> {
|
||||
let header = packet.get(..20)?;
|
||||
if header[..2] != BINDING_REQUEST.to_be_bytes() || header[4..8] != MAGIC_COOKIE {
|
||||
return None;
|
||||
}
|
||||
let mut attributes = &packet[20..];
|
||||
if attributes.len() != usize::from(u16::from_be_bytes([header[2], header[3]])) {
|
||||
return None;
|
||||
}
|
||||
let mut flags = 0;
|
||||
while !attributes.is_empty() {
|
||||
let [kind_high, kind_low, length_high, length_low, rest @ ..] = attributes else { return None };
|
||||
let length = usize::from(u16::from_be_bytes([*length_high, *length_low]));
|
||||
let value = rest.get(..length)?;
|
||||
if u16::from_be_bytes([*kind_high, *kind_low]) == CHANGE_REQUEST {
|
||||
flags = *value.get(3)?;
|
||||
}
|
||||
attributes = rest.get(length.div_ceil(4) * 4..)?;
|
||||
}
|
||||
Some(Asked { transaction: header[8..].try_into().ok()?, from_other_address: flags & 4 != 0, from_other_port: flags & 2 != 0 })
|
||||
}
|
||||
|
||||
/// A Binding success that reports `mapped` and, when given, names the server's other address.
|
||||
pub fn success(transaction: [u8; 12], mapped: SocketAddrV4, elsewhere: Option<SocketAddrV4>) -> Vec<u8> {
|
||||
let mut packet = Vec::from(BINDING_SUCCESS.to_be_bytes());
|
||||
packet.extend([0, if elsewhere.is_some() { 24 } else { 12 }]);
|
||||
packet.extend(MAGIC_COOKIE);
|
||||
packet.extend(transaction);
|
||||
packet.extend([(XOR_MAPPED_ADDRESS >> 8) as u8, XOR_MAPPED_ADDRESS as u8, 0, 8, 0, 1]);
|
||||
packet.extend(mapped.port().to_be_bytes().iter().zip(MAGIC_COOKIE).map(|(byte, mask)| byte ^ mask));
|
||||
packet.extend(mapped.ip().octets().iter().zip(MAGIC_COOKIE).map(|(byte, mask)| byte ^ mask));
|
||||
if let Some(elsewhere) = elsewhere {
|
||||
packet.extend([(OTHER_ADDRESS >> 8) as u8, OTHER_ADDRESS as u8, 0, 8, 0, 1]);
|
||||
packet.extend(elsewhere.port().to_be_bytes());
|
||||
packet.extend(elsewhere.ip().octets());
|
||||
}
|
||||
packet
|
||||
}
|
||||
|
||||
/// What a Binding success says: the address it saw, and the other address the server can answer
|
||||
/// from when it names one.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Answer {
|
||||
pub mapped: SocketAddr,
|
||||
pub elsewhere: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
/// The address a Binding success reports for `transaction`, or `None` for any other packet.
|
||||
pub fn mapped(packet: &[u8], transaction: [u8; 12]) -> Option<SocketAddr> {
|
||||
Some(answer(packet, transaction)?.mapped)
|
||||
}
|
||||
|
||||
/// A Binding success for `transaction`, or `None` for any other packet.
|
||||
pub fn answer(packet: &[u8], transaction: [u8; 12]) -> Option<Answer> {
|
||||
let header = packet.get(..20)?;
|
||||
if header[..2] != BINDING_SUCCESS.to_be_bytes() || header[4..8] != MAGIC_COOKIE || header[8..] != transaction {
|
||||
return None;
|
||||
}
|
||||
// The length in the header is the whole of what follows it, and every attribute lies inside it
|
||||
// with its padding (RFC 8489, section 6.3): a packet that says otherwise is not an answer.
|
||||
let mut attributes = &packet[20..];
|
||||
if attributes.len() != usize::from(u16::from_be_bytes([header[2], header[3]])) {
|
||||
return None;
|
||||
}
|
||||
let (mut masked, mut plain, mut elsewhere) = (None, None, None);
|
||||
while !attributes.is_empty() {
|
||||
let [kind_high, kind_low, length_high, length_low, rest @ ..] = attributes else { return None };
|
||||
let length = usize::from(u16::from_be_bytes([*length_high, *length_low]));
|
||||
let value = rest.get(..length)?;
|
||||
match u16::from_be_bytes([*kind_high, *kind_low]) {
|
||||
XOR_MAPPED_ADDRESS => masked = Some(address(value, Some(&header[4..20]))?),
|
||||
MAPPED_ADDRESS => plain = Some(address(value, None)?),
|
||||
CHANGED_ADDRESS | OTHER_ADDRESS => elsewhere = address(value, None).or(elsewhere),
|
||||
_ => {}
|
||||
}
|
||||
attributes = rest.get(length.div_ceil(4) * 4..)?;
|
||||
}
|
||||
Some(Answer { mapped: masked.or(plain)?, elsewhere })
|
||||
}
|
||||
|
||||
/// A MAPPED-ADDRESS value, or an XOR-MAPPED-ADDRESS value with the cookie and transaction that mask it.
|
||||
fn address(value: &[u8], mask: Option<&[u8]>) -> Option<SocketAddr> {
|
||||
let mask = mask.unwrap_or(&[0; 16]);
|
||||
let port = u16::from_be_bytes([*value.get(2)? ^ mask[0], *value.get(3)? ^ mask[1]]);
|
||||
match (value[1], value.len()) {
|
||||
(0x01, 8) => {
|
||||
let ip = Ipv4Addr::new(value[4] ^ mask[0], value[5] ^ mask[1], value[6] ^ mask[2], value[7] ^ mask[3]);
|
||||
Some(SocketAddr::new(ip.into(), port))
|
||||
}
|
||||
(0x02, 20) => {
|
||||
let mut ip = [0; 16];
|
||||
for (index, byte) in ip.iter_mut().enumerate() {
|
||||
*byte = value[4 + index] ^ mask[index];
|
||||
}
|
||||
Some(SocketAddr::new(Ipv6Addr::from(ip).into(), port))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TRANSACTION: [u8; 12] = [0xb7, 0xe7, 0xa7, 0x01, 0xbc, 0x34, 0xd6, 0x86, 0xfa, 0x87, 0xdf, 0xae];
|
||||
|
||||
fn success(attributes: &[u8]) -> Vec<u8> {
|
||||
let mut packet = Vec::from(BINDING_SUCCESS.to_be_bytes());
|
||||
packet.extend((attributes.len() as u16).to_be_bytes());
|
||||
packet.extend(MAGIC_COOKIE);
|
||||
packet.extend(TRANSACTION);
|
||||
packet.extend(attributes);
|
||||
packet
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_is_twenty_bytes_with_the_cookie_and_the_transaction() {
|
||||
let packet = request(TRANSACTION);
|
||||
assert_eq!(packet[..8], [0, 1, 0, 0, 0x21, 0x12, 0xa4, 0x42]);
|
||||
assert_eq!(packet[8..], TRANSACTION);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_to_answer_from_elsewhere_carries_one_attribute_with_the_two_flags() {
|
||||
let packet = request_from_elsewhere(TRANSACTION, true, true);
|
||||
assert_eq!(packet[..8], [0, 1, 0, 8, 0x21, 0x12, 0xa4, 0x42]);
|
||||
assert_eq!(packet[20..], [0, 3, 0, 4, 0, 0, 0, 6]);
|
||||
assert_eq!(request_from_elsewhere(TRANSACTION, false, true)[27], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_reads_what_is_asked_and_its_answer_reads_back() {
|
||||
assert_eq!(asked(&request(TRANSACTION)), Some(Asked { transaction: TRANSACTION, from_other_address: false, from_other_port: false }));
|
||||
assert_eq!(asked(&request_from_elsewhere(TRANSACTION, false, true)), Some(Asked { transaction: TRANSACTION, from_other_address: false, from_other_port: true }));
|
||||
assert_eq!(asked(&request_from_elsewhere(TRANSACTION, true, true)).map(|asked| asked.from_other_address), Some(true));
|
||||
assert_eq!(asked(&super::success(TRANSACTION, "192.0.2.1:32853".parse().unwrap(), None)), None);
|
||||
let (mapped, elsewhere): (SocketAddrV4, SocketAddrV4) = ("192.0.2.1:32853".parse().unwrap(), "198.51.100.7:3479".parse().unwrap());
|
||||
assert_eq!(answer(&super::success(TRANSACTION, mapped, Some(elsewhere)), TRANSACTION), Some(Answer { mapped: mapped.into(), elsewhere: Some(elsewhere.into()) }));
|
||||
assert_eq!(answer(&super::success(TRANSACTION, mapped, None), TRANSACTION), Some(Answer { mapped: mapped.into(), elsewhere: None }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_other_address_a_server_names() {
|
||||
// MAPPED-ADDRESS 192.0.2.1:32853 and CHANGED-ADDRESS 198.51.100.7:3479, as an RFC 3489 server sends them.
|
||||
let attributes = [0, 1, 0, 8, 0, 1, 0x80, 0x55, 192, 0, 2, 1, 0, 5, 0, 8, 0, 1, 0x0d, 0x97, 198, 51, 100, 7];
|
||||
assert_eq!(
|
||||
answer(&success(&attributes), TRANSACTION),
|
||||
Some(Answer { mapped: "192.0.2.1:32853".parse().unwrap(), elsewhere: Some("198.51.100.7:3479".parse().unwrap()) })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_masked_address_of_rfc_5769() {
|
||||
// RFC 5769 section 2.2: 192.0.2.1:32853, after a SOFTWARE attribute that is padded.
|
||||
let mut attributes = vec![0x80, 0x22, 0x00, 0x0b];
|
||||
attributes.extend(b"test vector ");
|
||||
attributes.extend([0x00, 0x20, 0x00, 0x08, 0x00, 0x01, 0xa1, 0x47, 0xe1, 0x12, 0xa6, 0x43]);
|
||||
assert_eq!(mapped(&success(&attributes), TRANSACTION), Some("192.0.2.1:32853".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_masked_ipv6_address_of_rfc_5769() {
|
||||
// RFC 5769 section 2.3: [2001:db8:1234:5678:11:2233:4455:6677]:32853.
|
||||
let attributes = [
|
||||
0x00, 0x20, 0x00, 0x14, 0x00, 0x02, 0xa1, 0x47, 0x01, 0x13, 0xa9, 0xfa, 0xa5, 0xd3, 0xf1, 0x79, 0xbc, 0x25,
|
||||
0xf4, 0xb5, 0xbe, 0xd2, 0xb9, 0xd9,
|
||||
];
|
||||
assert_eq!(
|
||||
mapped(&success(&attributes), TRANSACTION),
|
||||
Some("[2001:db8:1234:5678:11:2233:4455:6677]:32853".parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_the_plain_address_and_refuses_other_packets() {
|
||||
let plain = [0x00, 0x01, 0x00, 0x08, 0x00, 0x01, 0x80, 0x55, 192, 0, 2, 1];
|
||||
assert_eq!(mapped(&success(&plain), TRANSACTION), Some("192.0.2.1:32853".parse().unwrap()));
|
||||
assert_eq!(mapped(&success(&plain), [0; 12]), None);
|
||||
assert_eq!(mapped(&request(TRANSACTION), TRANSACTION), None);
|
||||
assert_eq!(mapped(&success(&plain)[..25], TRANSACTION), None);
|
||||
// Bytes past the declared length, an attribute that runs past the end, and padding that is
|
||||
// missing are all refused.
|
||||
let mut longer = success(&plain);
|
||||
longer.push(0);
|
||||
assert_eq!(mapped(&longer, TRANSACTION), None);
|
||||
assert_eq!(mapped(&success(&[0x00, 0x01, 0x00, 0x08, 0x00, 0x01]), TRANSACTION), None);
|
||||
assert_eq!(mapped(&success(&[0x80, 0x22, 0x00, 0x01, b'x']), TRANSACTION), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user