Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

A fixed UDP port for direct connections, set per machine (#127)

Sawa690f07189e1c
diff --git a/README.md b/README.md
index 6cbfb92..31eb26b 100644
--- a/README.md
+++ b/README.md
@@ -96,6 +96,19 @@ Teammates see your name, your computers, and what your agent sessions are workin
Signed in with Reason, your name shows as verified: Reason signs that the computer is yours, every teammate's computer
checks that itself, and nobody else can take the name. State lives in `~/.reason/network`. Details: [DESIGN.md](DESIGN.md).
+Direct connections use a random UDP port each time the daemon starts. To open or forward one port in a firewall or
+router instead, set it in `~/.reason/network/config.toml` (per computer; the daemon reads it when it starts):
+
+```toml
+port = 41641
+```
+
+Put `port` at the top of the file, above any `[table]` section such as `[inbound]`. The daemon ignores it under a table.
+
+It is bound on IPv4 and IPv6 (IPv4 alone on a computer without IPv6). If another program holds it on either, the
+daemon logs that and uses a random port, as without it; `port = 0` is the same as leaving it out.
+`reason-network doctor` shows the port in use. Relays work the same either way.
+
## Uninstall
```sh
diff --git a/src/config.rs b/src/config.rs
index 39f0af7..f91ff20 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -20,6 +20,10 @@ pub struct Config {
pub reason: bool,
/// Install new releases when they come out (the daemon checks every few hours).
pub auto_update: bool,
+ /// The UDP port teammates reach this machine on directly, e.g. `41641` for a firewall or router rule. None: a
+ /// random one each start. Taken by something else, a random one is used.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub port: Option<u16>,
pub inbound: Inbound,
/// Folders whose sessions stay off the network, e.g. `"~/personal" = "off"` (`reason-network folder`). The deepest
/// entry that holds a session's folder decides; `off` is the only value so far.
@@ -63,6 +67,7 @@ impl Default for Config {
tray: true,
reason: false,
auto_update: true,
+ port: None,
inbound: Inbound::default(),
folders: BTreeMap::new(),
}
@@ -115,6 +120,11 @@ impl Config {
self.lan && crate::paths::env_var_os("NO_MDNS").is_none()
}
+ /// The fixed UDP port, if one is set; `0` (any port) is the same as none.
+ pub fn port(&self) -> Option<u16> {
+ self.port.filter(|&p| p != 0)
+ }
+
pub fn tray(&self) -> bool {
cfg!(target_os = "macos") && self.tray && crate::paths::env_var_os("NO_TRAY").is_none()
}
@@ -315,6 +325,22 @@ mod tests {
assert!(parsed.off_in(&format!("{}/personal/x", home())));
}
+ #[test]
+ fn a_fixed_port_is_optional() {
+ let parsed: Config = toml::from_str("lan = true\n").unwrap();
+ assert_eq!(parsed.port, None);
+ assert!(!toml::to_string_pretty(&parsed).unwrap().contains("port"), "unset: not written");
+ let parsed: Config = toml::from_str("port = 41641\n").unwrap();
+ assert_eq!(parsed.port, Some(41641));
+ assert!(toml::to_string_pretty(&parsed).unwrap().contains("port = 41641"));
+ assert_eq!(parsed.port(), Some(41641));
+ let parsed: Config = toml::from_str("port = 0\n").unwrap();
+ assert_eq!(parsed.port(), None, "0: random, as unset");
+ for bad in ["port = 70000", "port = -1", "port = \"41641\""] {
+ assert!(toml::from_str::<Config>(bad).is_err(), "{bad}");
+ }
+ }
+
fn temp() -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("reason-network-folders-{}", ulid::Ulid::generate()));
std::fs::create_dir_all(d.join("real").join("personal").join("sub")).unwrap();
diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rs
index fe5fbaf..7b31656 100644
--- a/src/daemon/teamops.rs
+++ b/src/daemon/teamops.rs
@@ -80,7 +80,7 @@ impl Daemon {
let team = self.team_state().ok_or_else(|| anyhow!("not in a team"))?;
self.stop_net_now().await;
let relay = team.meta.body.relay.as_deref();
- let endpoint = net::bind(self.key.clone(), relay, self.cfg.lan()).await?;
+ let endpoint = net::bind(self.key.clone(), relay, self.cfg.lan(), self.cfg.port()).await?;
// Last known presence of each machine, so `who --all` shows offline teammates after a restart.
let mut remote = HashMap::new();
{
@@ -251,6 +251,7 @@ impl Daemon {
machines: Vec::new(),
features: vec![crate::files::FEATURE.into()],
messages: Vec::new(),
+ udp: None,
})
}
@@ -368,6 +369,7 @@ impl Daemon {
machines: Vec::new(),
features: vec![crate::files::FEATURE.into()],
messages: Vec::new(),
+ udp: None,
};
{
let mut g = self.inner.lock().unwrap();
@@ -510,6 +512,7 @@ impl Daemon {
machines: self.machines(),
features: vec![crate::files::FEATURE.into()],
messages: self.inner.lock().unwrap().store.counts(util::now_ms()).unwrap_or_default(),
+ udp: self.net().map(|n| n.udp()),
})
}
diff --git a/src/main.rs b/src/main.rs
index 2541bab..83128f6 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -917,6 +917,7 @@ mod tests {
machines: vec![me],
features: vec![],
messages: vec![],
+ udp: None,
};
let l = LinkInfo { team: "vibes".into(), url: join_url("rn1-AAAA"), ticket: "rn1-AAAA".into() };
assert!(team_value(&t, &l, None).unwrap_err().to_string().contains("restart the Reason Network daemon"));
diff --git a/src/net.rs b/src/net.rs
index 8506ed3..6fb0371 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -4,7 +4,7 @@
use crate::{
daemon::Daemon,
- proto::{Message, SessionInfo},
+ proto::{Message, SessionInfo, UdpPort},
team::TeamState,
util,
};
@@ -13,13 +13,14 @@ use futures_lite::{StreamExt, stream::Boxed};
use iroh::{
Endpoint, EndpointAddr, EndpointId, RelayMode, RelayUrl, SecretKey, Watcher,
address_lookup::{self, AddressLookup, EndpointData, EndpointInfo, Item},
- endpoint::{ConnectError, ConnectWithOptsError, Connection, RecvStream, SendStream, presets},
+ endpoint::{Builder, ConnectError, ConnectWithOptsError, Connection, RecvStream, SendStream, presets},
protocol::{AcceptError, ProtocolHandler, Router},
};
use iroh_mdns_address_lookup::MdnsAddressLookup;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::{
collections::{HashMap, HashSet},
+ net::{Ipv4Addr, Ipv6Addr},
sync::{
Arc, Mutex, Weak,
atomic::{AtomicU64, Ordering},
@@ -130,6 +131,7 @@ pub struct Net {
proxy: Option<RelayUrl>,
/// The proxy's address as looked up for the endpoint.
at: Option<RelayUrl>,
+ udp: UdpPort,
router: Mutex<Option<Router>>,
/// Endpoints listening for joins on behalf of invite codes, by their (code-derived) id.
invites: Mutex<HashMap<EndpointId, Router>>,
@@ -208,13 +210,15 @@ pub struct Bound {
pub endpoint: Endpoint,
proxy: Option<RelayUrl>,
at: Option<RelayUrl>,
+ udp: UdpPort,
}
/// An endpoint on the team's own relay (`relay`) or the default ones, the way that last got through, at once. A
-/// running network that stays off its relays tries the other way itself (see `route_loop`).
-pub async fn bind(key: SecretKey, relay: Option<&str>, lan: bool) -> Result<Bound> {
+/// running network that stays off its relays tries the other way itself (see `route_loop`). On UDP `port` if one is
+/// set and free (the network's own endpoint; anything else would take it from that one).
+pub async fn bind(key: SecretKey, relay: Option<&str>, lan: bool, port: Option<u16>) -> Result<Bound> {
let relays = relays_for(relay).await?;
- endpoint(&key, &relays, relay.is_some(), lan, route(&relays)).await
+ endpoint(&key, &relays, relay.is_some(), lan, route(&relays), port).await
}
/// The same, for something a person waits on anyway (a join, checking a relay): if no relay answers the usual way
@@ -223,7 +227,7 @@ pub async fn bind_settled(key: SecretKey, relay: Option<&str>, lan: bool) -> Res
let relays = relays_for(relay).await?;
let own = relay.is_some();
let first = route(&relays);
- let endpoint = self::endpoint(&key, &relays, own, lan, first.clone()).await?.endpoint;
+ let endpoint = self::endpoint(&key, &relays, own, lan, first.clone(), None).await?.endpoint;
let Some(proxy) = proxy_for(&relays) else { return Ok((endpoint, relays)) };
if tokio::time::timeout(FIRST_WAY, endpoint.online()).await.is_ok() {
return Ok((endpoint, relays));
@@ -237,13 +241,14 @@ pub async fn bind_settled(key: SecretKey, relay: Option<&str>, lan: bool) -> Res
endpoint.close().await;
keep_route(&other, &relays);
log(&format!("on a relay {}", way(&other)));
- Ok((self::endpoint(&key, &relays, own, lan, other).await?.endpoint, relays))
+ Ok((self::endpoint(&key, &relays, own, lan, other, None).await?.endpoint, relays))
}
/// Whether a relay answers the `proxy` way, asked by a throwaway endpoint that publishes nothing (this machine's own
/// stays as it is).
async fn reaches(relays: &[RelayUrl], proxy: &Option<RelayUrl>) -> bool {
- let Ok(Bound { endpoint: probe, .. }) = endpoint(&SecretKey::generate(), relays, true, false, proxy.clone()).await
+ let Ok(Bound { endpoint: probe, .. }) =
+ endpoint(&SecretKey::generate(), relays, true, false, proxy.clone(), None).await
else {
return false;
};
@@ -258,27 +263,71 @@ async fn endpoint(
own: bool,
lan: bool,
proxy: Option<RelayUrl>,
+ port: Option<u16>,
) -> Result<Bound> {
+ let at = match &proxy {
+ Some(p) => Some(looked_up(p.clone()).await),
+ None => None,
+ };
// The default relays, with n0's address lookup still: that is how a teammate on an older Reason Network (on n0's
// relays) and this machine find each other, and what four-word codes need. The team's own relay and nothing of
// n0's: none of its relays, no publishing or looking up addresses in its DNS; teammates are dialed through it.
- let relay_mode = RelayMode::custom(relays.to_vec());
- let mut b = if own { Endpoint::builder(presets::Minimal) } else { Endpoint::builder(presets::N0) }
- .secret_key(key.clone())
- .relay_mode(relay_mode);
- let at = match &proxy {
- Some(p) => Some(looked_up(p.clone()).await),
+ let builder = || -> Result<Builder> {
+ let relay_mode = RelayMode::custom(relays.to_vec());
+ let mut b = if own { Endpoint::builder(presets::Minimal) } else { Endpoint::builder(presets::N0) }
+ .secret_key(key.clone())
+ .relay_mode(relay_mode);
+ if let Some(at) = &at {
+ b = b.proxy_url(at.clone().into());
+ }
+ if lan && own {
+ b = b.address_lookup(NoRelays(MdnsAddressLookup::builder().build(key.public())?));
+ } else if lan {
+ b = b.address_lookup(MdnsAddressLookup::builder());
+ }
+ Ok(b)
+ };
+ let fixed = match port {
+ Some(p) => {
+ // IPv6 that works here at all gets the port too, else (taken, refused) a random port on both, as without
+ // one: neither no network nor no IPv6.
+ let v6 = ipv6_works();
+ if !v6 {
+ log(&format!("no IPv6 here: UDP port {p} on IPv4 only"));
+ }
+ match on_port(builder()?, p, v6)?.bind().await {
+ Ok(e) => Some(e),
+ Err(e) => {
+ log(&format!("couldn't bind UDP port {p} ({e:#}): using a random one"));
+ None
+ }
+ }
+ }
None => None,
};
- if let Some(at) = &at {
- b = b.proxy_url(at.clone().into());
- }
- if lan && own {
- b = b.address_lookup(NoRelays(MdnsAddressLookup::builder().build(key.public())?));
- } else if lan {
- b = b.address_lookup(MdnsAddressLookup::builder());
- }
- Ok(Bound { endpoint: b.bind().await?, proxy, at })
+ let fell_back = port.is_some() && fixed.is_none();
+ let endpoint = match fixed {
+ Some(e) => e,
+ None => builder()?.bind().await?,
+ };
+ Ok(Bound { udp: UdpPort { port: udp_port(&endpoint), fixed: port, fell_back }, endpoint, proxy, at })
+}
+
+/// `b`, on UDP `port` on IPv4, and IPv6 if `v6`, in place of a random port.
+fn on_port(b: Builder, port: u16, v6: bool) -> Result<Builder> {
+ let b = b.bind_addr((Ipv4Addr::UNSPECIFIED, port))?;
+ Ok(if v6 { b.bind_addr((Ipv6Addr::UNSPECIFIED, port))? } else { b })
+}
+
+/// Whether this machine can open an IPv6 UDP socket at all.
+fn ipv6_works() -> bool {
+ std::net::UdpSocket::bind((Ipv6Addr::UNSPECIFIED, 0)).is_ok()
+}
+
+/// The UDP port `endpoint` is on: IPv4's, which it always binds.
+fn udp_port(endpoint: &Endpoint) -> u16 {
+ let socks = endpoint.bound_sockets();
+ socks.iter().find(|a| a.is_ipv4()).or(socks.first()).map_or(0, |a| a.port())
}
/// An http proxy's name looked up the way curl and everything else on this machine looks it up (hosts file, the
@@ -460,6 +509,24 @@ async fn log_relay(endpoint: Endpoint) {
}
}
+/// Says in the log when a connection to a teammate moves between a direct path and the relay, and the new one's rtt.
+async fn log_paths(conn: Connection) {
+ let peer = conn.remote_id().fmt_short().to_string();
+ let kind = |relay: bool| if relay { "relay" } else { "direct" };
+ let mut lists = conn.paths_stream();
+ let mut was = None;
+ while let Some(list) = lists.next().await {
+ let Some(p) = list.iter().find(|p| p.is_selected()) else { continue };
+ let relay = p.is_relay();
+ if let Some(from) = was
+ && from != relay
+ {
+ log(&format!("{peer}: path {} -> {} (rtt {} ms)", kind(from), kind(relay), p.rtt().as_millis()));
+ }
+ was = Some(relay);
+ }
+}
+
/// mDNS, minus the relay a neighbour advertises: a teammate still on n0's relays (it missed a switch, or runs an older
/// Reason Network) must not draw this machine onto them.
#[derive(Debug)]
@@ -701,7 +768,7 @@ impl Net {
remote: HashMap<EndpointId, Remote>,
) -> Arc<Net> {
let relays: Vec<RelayUrl> = relay.map_or_else(crate::relays::current, |u| u.parse().into_iter().collect());
- let Bound { endpoint, proxy, at } = bound;
+ let Bound { endpoint, proxy, at, udp } = bound;
let net = Arc::new_cyclic(|weak: &Weak<Net>| Net {
me: endpoint.id(),
router: Mutex::new(Some(
@@ -715,6 +782,7 @@ impl Net {
relays,
proxy,
at,
+ udp,
daemon: Arc::downgrade(daemon),
links: Default::default(),
// Saved by an older build, maybe, which tidied less.
@@ -742,6 +810,10 @@ impl Net {
self.endpoint.addr()
}
+ pub fn udp(&self) -> UdpPort {
+ self.udp
+ }
+
/// Waits (up to `limit`) until this machine has a home relay, so addresses handed out include it.
pub async fn online(&self, limit: Duration) {
let _ = tokio::time::timeout(limit, self.endpoint.online()).await;
@@ -771,7 +843,7 @@ impl Net {
relay: Option<&str>,
lan: bool,
) -> Result<()> {
- let endpoint = bind(key, relay, lan).await?.endpoint;
+ let endpoint = bind(key, relay, lan, None).await?.endpoint;
let id = endpoint.id();
let router = Router::builder(endpoint).accept(JOIN_ALPN, JoinProto(Arc::downgrade(self), Some(id))).spawn();
self.invites.lock().unwrap().insert(id, router);
@@ -980,6 +1052,7 @@ impl Net {
links.insert(peer, Link { id, tx: tx.clone(), conn: conn.clone(), dialer, since: Instant::now() });
}
log(&format!("connected to {} ({})", peer.fmt_short(), if outgoing { "out" } else { "in" }));
+ let paths = tokio::spawn(log_paths(conn.clone()));
let writer = tokio::spawn(async move {
while let Some(w) = rx.recv().await {
@@ -1022,6 +1095,7 @@ impl Net {
r.last_seen = util::now_ms();
}
writer.abort();
+ paths.abort();
conn.close(0u32.into(), b"bye");
res
}
@@ -1273,7 +1347,7 @@ mod tests {
#[tokio::test]
async fn a_link_naming_only_this_machine_says_so() {
let key = SecretKey::generate();
- let endpoint = bind(key.clone(), Some("https://relay.example.com"), false).await.unwrap().endpoint;
+ let endpoint = bind(key.clone(), Some("https://relay.example.com"), false, None).await.unwrap().endpoint;
let req = JoinRequest {
team: String::new(),
secret: String::new(),
@@ -1292,7 +1366,7 @@ mod tests {
#[tokio::test]
async fn a_link_naming_this_machine_and_offline_ones_says_to_ask_an_online_teammate() {
let key = SecretKey::generate();
- let endpoint = bind(key.clone(), Some("https://relay.example.com"), false).await.unwrap().endpoint;
+ let endpoint = bind(key.clone(), Some("https://relay.example.com"), false, None).await.unwrap().endpoint;
let req = JoinRequest {
team: String::new(),
secret: String::new(),
@@ -1310,6 +1384,71 @@ mod tests {
assert!(joined.unreachable);
}
+ #[tokio::test]
+ async fn a_fixed_port_is_used_and_a_taken_one_falls_back_to_a_random_one() {
+ let relay = Some("https://relay.example.com");
+ let free = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap().local_addr().unwrap().port();
+ let b = bind(SecretKey::generate(), relay, false, Some(free)).await.unwrap();
+ assert_eq!(b.udp, UdpPort { port: free, fixed: Some(free), fell_back: false });
+ assert!(b.endpoint.bound_sockets().iter().all(|a| a.port() == free), "{:?}", b.endpoint.bound_sockets());
+ assert_eq!(b.endpoint.bound_sockets().iter().any(|a| a.is_ipv6()), ipv6_works());
+ b.endpoint.close().await;
+ // Something else holds it: the network still starts, on a random port, and says what it wanted.
+ let taken = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
+ let port = taken.local_addr().unwrap().port();
+ let b = bind(SecretKey::generate(), relay, false, Some(port)).await.unwrap();
+ assert!(b.udp.port != port && b.udp.port != 0 && b.udp.fixed == Some(port) && b.udp.fell_back, "{:?}", b.udp);
+ b.endpoint.close().await;
+ // None set: random, as before.
+ let b = bind(SecretKey::generate(), relay, false, None).await.unwrap();
+ assert!(b.udp.port != 0 && b.udp.fixed.is_none() && !b.udp.fell_back);
+ b.endpoint.close().await;
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_fixed_port_taken_on_ipv6_alone_falls_back_and_keeps_ipv6() {
+ let Some(taken) = v6_only_udp() else {
+ eprintln!("skipped: no IPv6 here");
+ return;
+ };
+ let port = taken.local_addr().unwrap().port();
+ // IPv4 has it free (else the case isn't the one under test).
+ drop(std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, port)).expect("IPv4 side free"));
+ let b = bind(SecretKey::generate(), Some("https://relay.example.com"), false, Some(port)).await.unwrap();
+ let socks = b.endpoint.bound_sockets();
+ assert!(b.udp.fell_back && b.udp.port != port && b.udp.fixed == Some(port), "{:?}", b.udp);
+ assert!(socks.iter().any(|a| a.is_ipv6()) && socks.iter().all(|a| a.port() != port), "{socks:?}");
+ b.endpoint.close().await;
+ }
+
+ /// A UDP socket on a random port of IPv6 alone (`IPV6_V6ONLY`), or None without IPv6.
+ #[cfg(unix)]
+ fn v6_only_udp() -> Option<std::net::UdpSocket> {
+ use std::os::fd::FromRawFd;
+ // SAFETY: a fresh socket, owned (and closed) by the UdpSocket made from it; the option and address are
+ // initialised values of the sizes passed.
+ unsafe {
+ let fd = libc::socket(libc::AF_INET6, libc::SOCK_DGRAM, 0);
+ if fd < 0 {
+ return None;
+ }
+ let sock = std::net::UdpSocket::from_raw_fd(fd);
+ let on: libc::c_int = 1;
+ let len = std::mem::size_of_val(&on) as libc::socklen_t;
+ if libc::setsockopt(fd, libc::IPPROTO_IPV6, libc::IPV6_V6ONLY, (&raw const on).cast(), len) != 0 {
+ return None;
+ }
+ let mut addr: libc::sockaddr_in6 = std::mem::zeroed();
+ addr.sin6_family = libc::AF_INET6 as libc::sa_family_t;
+ let len = std::mem::size_of_val(&addr) as libc::socklen_t;
+ if libc::bind(fd, (&raw const addr).cast(), len) != 0 {
+ return None;
+ }
+ Some(sock)
+ }
+ }
+
#[test]
fn the_default_relay_is_reasons_and_none_of_n0s() {
let relays = default_relays();
diff --git a/src/proto.rs b/src/proto.rs
index 9d66319..82dd589 100644
--- a/src/proto.rs
+++ b/src/proto.rs
@@ -407,6 +407,20 @@ pub struct TeamInfo {
/// (UTC) from six before today to tomorrow that had any. Older engines leave it out.
#[serde(default)]
pub messages: Vec<DayCount>,
+ /// The UDP port the network is on (`None` while it isn't up). Older engines leave it out.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub udp: Option<UdpPort>,
+}
+
+/// The UDP port direct paths come in on, and the one `port` in the config asked for, if any.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct UdpPort {
+ pub port: u16,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub fixed: Option<u16>,
+ /// `fixed` couldn't be bound, so `port` is a random one.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub fell_back: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -509,6 +523,7 @@ mod tests {
machines: vec![],
features: vec![],
messages: vec![DayCount { day: "2026-10-20".into(), sent: 3, received: 1 }],
+ udp: Some(UdpPort { port: 41641, fixed: Some(41641), fell_back: false }),
};
let v = serde_json::to_value(&t).unwrap();
assert_eq!(v["team_id"], "00112233445566778899aabbccddeeff");
@@ -521,6 +536,8 @@ mod tests {
.unwrap();
assert_eq!((old.id.as_str(), old.name.as_str()), ("", "vibes"));
assert!(old.messages.is_empty());
+ assert_eq!(v["udp"], serde_json::json!({"port": 41641, "fixed": 41641}));
+ assert!(old.udp.is_none());
}
#[test]
diff --git a/src/render.rs b/src/render.rs
index d199f4a..c6cdd8b 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -225,6 +225,15 @@ pub fn team(t: &TeamInfo) -> String {
out
}
+/// The UDP port the network is on, and whether it is the one `port` in the config asked for.
+pub fn udp_port(u: &crate::proto::UdpPort) -> String {
+ match u.fixed {
+ Some(f) if u.fell_back => format!("UDP port {} (random; fixed {f} couldn't be bound)", u.port),
+ Some(_) => format!("UDP port {} (fixed)", u.port),
+ None => format!("UDP port {} (random)", u.port),
+ }
+}
+
pub fn send_result(r: &SendResult) -> String {
let mut out = String::new();
for rc in &r.recipients {
@@ -433,12 +442,25 @@ mod tests {
machines: Vec::new(),
features: Vec::new(),
messages: Vec::new(),
+ udp: None,
};
assert_eq!(team(&t), "team vibes · relay: Reason's (the default)\n");
t.relay = Some("https://relay.example.com".into());
assert_eq!(team(&t), "team vibes · relay: https://relay.example.com\n");
}
+ #[test]
+ fn doctor_says_which_udp_port_and_why() {
+ use crate::proto::UdpPort;
+ let u = |port, fixed, fell_back| udp_port(&UdpPort { port, fixed, fell_back });
+ assert_eq!(u(41641, Some(41641), false), "UDP port 41641 (fixed)");
+ assert_eq!(u(53211, None, false), "UDP port 53211 (random)");
+ assert_eq!(u(53211, Some(41641), true), "UDP port 53211 (random; fixed 41641 couldn't be bound)");
+ // `port = 0` reaches the daemon as no port: random, not a missed fixed one.
+ let zero: crate::config::Config = toml::from_str("port = 0\n").unwrap();
+ assert_eq!(u(53211, zero.port(), false), "UDP port 53211 (random)");
+ }
+
/// A directory of one teammate's session, with these fields as its machine and presence gave them.
fn bobs(team: &str, person: &str, repo: &str, branch: &str, doing: &str) -> Directory {
let machine = MachineInfo {
diff --git a/src/setup.rs b/src/setup.rs
index 85999cf..cb94173 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -1451,6 +1451,9 @@ pub async fn doctor() -> Result<()> {
let team = crate::shown(&t.name);
println!("✓ daemon running; team {team} with {others} other machine(s), {online} connected");
print!("{}", crate::shown(&render::team(&t)).lines().skip(1).map(|l| format!("{l}\n")).collect::<String>());
+ if let Some(u) = &t.udp {
+ println!(" {}", render::udp_port(u));
+ }
if t.relay_connected == Some(false) {
let relay = crate::shown(&t.relay.clone().unwrap_or_else(render::default_relays));
println!(