feat(net): nom local rustscreen.local annoncé en mDNS
CI / Formatting, tests and builds (push) Successful in 6m15s
CI / Formatting, tests and builds (push) Successful in 6m15s
L'hôte annonce rustscreen.local et un service _http._tcp sur la seule interface partagée, avec mdns-sd. Une collision renomme en rustscreen-2.local et le nom affiché suit. L'annonce suit l'adresse partagée, comme le QR code, qui garde l'IP (ADR 0005). La coque ne met le nom en avant qu'une fois qu'une autre machine a répondu en mDNS: le multicast passe alors sur ce réseau. Sinon elle affiche l'adresse d'abord et présente le nom comme un essai. Vérifié sur la machine de développement: getent résout rustscreen.local vers l'adresse LAN, /health répond par le nom. Refs #25 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1b4a153d4a
commit
a4211778d5
17 files changed
+438
-8
No files matched your search
@@ -15,7 +15,8 @@ Ce qui tourne: capture Linux réelle (portail et PipeWire sous Wayland, X11 en r
|
||||
moniteur RandR, une fenêtre seule), écran virtuel par le portail (GNOME 46, KDE), conversion BGRA
|
||||
vers I420, encodage VP8 ou VP9 temps réel qui suit les changements de résolution, session str0m par
|
||||
spectateur, serveur local avec jeton qui expire et code court, appareils de confiance qui reviennent sans lien
|
||||
par une clé Ed25519 (ADR 0011), changement de source en plein partage sans reconnexion, viewer React qui reprend seul après
|
||||
par une clé Ed25519 (ADR 0011), changement de source en plein partage sans reconnexion, nom
|
||||
local `rustscreen.local` en mDNS, viewer React qui reprend seul après
|
||||
une coupure ou une veille, tourne l'image et suit le thème, coque desktop Tauri avec icône de
|
||||
barre système, réglages persistants, interface en français et en anglais, inhibition de veille,
|
||||
journal JSON local et archive de diagnostics.
|
||||
@@ -193,7 +194,8 @@ Le journal JSON (`~/.local/state/rustscreen/logs`) nomme les étapes d'une sessi
|
||||
`share_ended`, `share_interrupted`, `viewer_disconnected`, `resolution_changed`, `sleep_inhibited`,
|
||||
`sleep_released`, `wake_detected`, `capture_restarted`, `address_changed`, `settings_changed`,
|
||||
`access_regenerated`, `code_accepted`, `code_rejected`, `trust_changed`, `source_switched`,
|
||||
`source_switch_failed`, et côté serveur `trusted_device_admitted`. Avant la 0.6, ces noms étaient en français
|
||||
`source_switch_failed`, `local_name_failed`, et côté serveur `trusted_device_admitted`,
|
||||
`local_name_announced`, `local_name_renamed`, `local_name_confirmed`. Avant la 0.6, ces noms étaient en français
|
||||
(champ `evenement`). Ne jamais y écrire un titre de fenêtre ni une image (ADR 0008).
|
||||
|
||||
Le spike historique `spikes/str0m-mire` reste pour comparer les mesures:
|
||||
|
||||
Generated
+60
@@ -782,6 +782,15 @@ dependencies = [
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flume"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
|
||||
dependencies = [
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -1237,6 +1246,15 @@ version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
@@ -1267,6 +1285,20 @@ version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "mdns-sd"
|
||||
version = "0.21.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8562654710f72a9cbce4b0d5b7c366a2f94330ba1ce3740f15e932ea2d37b161"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"flume",
|
||||
"if-addrs",
|
||||
"mio",
|
||||
"socket-pktinfo",
|
||||
"socket2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -1331,6 +1363,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -1808,6 +1841,7 @@ dependencies = [
|
||||
"ed25519-dalek",
|
||||
"hex",
|
||||
"image",
|
||||
"mdns-sd",
|
||||
"qrcode",
|
||||
"rand 0.10.3",
|
||||
"rcgen",
|
||||
@@ -1921,6 +1955,12 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "sctp-proto"
|
||||
version = "0.10.7"
|
||||
@@ -2134,6 +2174,17 @@ version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
|
||||
[[package]]
|
||||
name = "socket-pktinfo"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"socket2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
@@ -2144,6 +2195,15 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
|
||||
Generated
+45
@@ -1341,6 +1341,15 @@ dependencies = [
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flume"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"
|
||||
dependencies = [
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -2515,6 +2524,20 @@ version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "mdns-sd"
|
||||
version = "0.21.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8562654710f72a9cbce4b0d5b7c366a2f94330ba1ce3740f15e932ea2d37b161"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"flume",
|
||||
"if-addrs",
|
||||
"mio",
|
||||
"socket-pktinfo",
|
||||
"socket2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -2579,6 +2602,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -3605,6 +3629,7 @@ dependencies = [
|
||||
"axum-server",
|
||||
"ed25519-dalek",
|
||||
"hex",
|
||||
"mdns-sd",
|
||||
"qrcode",
|
||||
"rand 0.10.3",
|
||||
"rcgen",
|
||||
@@ -4135,6 +4160,17 @@ version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
|
||||
[[package]]
|
||||
name = "socket-pktinfo"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"socket2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
@@ -4193,6 +4229,15 @@ dependencies = [
|
||||
"system-deps 6.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spin"
|
||||
version = "0.9.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* The local name of the host, as the interface shows it (#25).
|
||||
*/
|
||||
export type LocalNameInfo = {
|
||||
/**
|
||||
* `rustscreen.local`, or `rustscreen-2.local` if the name was taken.
|
||||
*/
|
||||
host: string,
|
||||
/**
|
||||
* Home page by name, to type the short code: `http://rustscreen.local:8099/`.
|
||||
*/
|
||||
url: string,
|
||||
/**
|
||||
* Another machine answers over mDNS: the name most likely works. Until
|
||||
* then the interface puts the address first and says the name is a try.
|
||||
*/
|
||||
confirmed: boolean, };
|
||||
@@ -1,4 +1,5 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { LocalNameInfo } from "./LocalNameInfo";
|
||||
import type { Refusal } from "./Refusal";
|
||||
import type { SharedSource } from "./SharedSource";
|
||||
import type { ViewerDevice } from "./ViewerDevice";
|
||||
@@ -45,4 +46,9 @@ interface: string | null, devices: Array<ViewerDevice>,
|
||||
* Connections refused since the share started, newest first (#35): who
|
||||
* tried, from where, and why it did not work.
|
||||
*/
|
||||
refusals: Array<Refusal>, limit: number, started_ms: number, };
|
||||
refusals: Array<Refusal>,
|
||||
/**
|
||||
* `rustscreen.local`, when announced (#25). The QR code keeps the
|
||||
* address: the name is for whoever types.
|
||||
*/
|
||||
local_name: LocalNameInfo | null, limit: number, started_ms: number, };
|
||||
@@ -26,7 +26,11 @@ export function SharePanel({ share, onDisconnect, onNewCode, onTrust }: Props) {
|
||||
};
|
||||
|
||||
const [address] = share.listen.split(':');
|
||||
const home = share.url.split('/r/')[0] ?? share.url;
|
||||
const byAddress = share.url.split('/r/')[0] ?? share.url;
|
||||
// The name is offered first only once another machine answered over mDNS
|
||||
// (#25): otherwise the address, which always works, comes first.
|
||||
const named = share.local_name;
|
||||
const home = named?.confirmed ? named.url.replace(/\/$/, '') : byAddress;
|
||||
const remaining = expiry(share.expires_ms, now, t);
|
||||
return (
|
||||
<section className='share'>
|
||||
@@ -53,6 +57,13 @@ export function SharePanel({ share, onDisconnect, onNewCode, onTrust }: Props) {
|
||||
<span className='muted'>
|
||||
{t('code')} {t('codeHelp', { home })}
|
||||
</span>
|
||||
{named && (
|
||||
<span className='muted local-name'>
|
||||
{named.confirmed
|
||||
? t('localNameAddress', { address: byAddress })
|
||||
: t('localNameUnconfirmed', { url: named.url.replace(/\/$/, '') })}
|
||||
</span>
|
||||
)}
|
||||
<strong className='code-value' aria-live='polite'>
|
||||
{displayCode(share.code)}
|
||||
</strong>
|
||||
|
||||
@@ -548,6 +548,11 @@ h2 {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
|
||||
.short-code > .local-name {
|
||||
flex-basis: 100%;
|
||||
order: 1;
|
||||
}
|
||||
|
||||
.code-value {
|
||||
font:
|
||||
700 1.6rem / 1.1 ui-monospace,
|
||||
|
||||
@@ -303,6 +303,12 @@ async fn main() -> Result<(), Error> {
|
||||
" code : {} (no camera: open {home}/ and type it)",
|
||||
displayed_code(&share.code)
|
||||
);
|
||||
if let Some(name) = &share.local_name {
|
||||
println!(
|
||||
" name : {} (mDNS; if it does not answer, use the address)",
|
||||
name.url
|
||||
);
|
||||
}
|
||||
if let Some(end) = share.expires_ms {
|
||||
let minutes = end.saturating_sub(now_ms()).div_ceil(60_000);
|
||||
println!(" valid {minutes} min for a new device");
|
||||
|
||||
@@ -27,8 +27,8 @@ use crate::capture::{self, StartedCapture};
|
||||
use crate::diagnostics::DiagnosticsContext;
|
||||
use crate::media::{Switchable, SwitchableMedia};
|
||||
use crate::state::{
|
||||
Capabilities, HostState, InterfaceOption, Phase, SettingsOutcome, Share, SharedSource,
|
||||
SourceChoice, SourceOption, Stop, ViewerDevice,
|
||||
Capabilities, HostState, InterfaceOption, LocalNameInfo, Phase, SettingsOutcome, Share,
|
||||
SharedSource, SourceChoice, SourceOption, Stop, ViewerDevice,
|
||||
};
|
||||
|
||||
/// Interval of a share's watch: capture end, network.
|
||||
@@ -114,6 +114,9 @@ struct View {
|
||||
/// Last rendered QR and the URL it carries: the state is recomposed every
|
||||
/// second, the QR only when the URL changes.
|
||||
qr: Option<(String, String)>,
|
||||
/// `rustscreen.local` (#25), announced on this address. `None` inside:
|
||||
/// the announcement failed on it, and is not retried until it changes.
|
||||
local_name: Option<(IpAddr, Option<rs_signaling::LocalName>)>,
|
||||
}
|
||||
|
||||
struct Server {
|
||||
@@ -616,6 +619,7 @@ impl Host {
|
||||
fingerprint: tls.as_ref().map(TlsMaterial::fingerprint_pairs),
|
||||
started_ms,
|
||||
qr: None,
|
||||
local_name: None,
|
||||
});
|
||||
self.update_base(|b| b.sleep_inhibited = sleep_inhibited);
|
||||
|
||||
@@ -882,7 +886,38 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps `rustscreen.local` on the address viewers reach: it follows a new
|
||||
/// DHCP lease or a change of interface, like the QR code.
|
||||
fn local_name(view: &mut View) -> Option<LocalNameInfo> {
|
||||
let address = Some(view.listen.ip())
|
||||
.filter(|ip| !ip.is_unspecified())
|
||||
.or_else(rs_rtc::local_candidate_address)
|
||||
.filter(|ip| !ip.is_loopback())?;
|
||||
if view
|
||||
.local_name
|
||||
.as_ref()
|
||||
.is_none_or(|(on, _)| *on != address)
|
||||
{
|
||||
// The old announcement goes first: two daemons would fight over it.
|
||||
view.local_name = None;
|
||||
let announced = rs_signaling::LocalName::announce(address, view.listen.port())
|
||||
.inspect_err(|error| {
|
||||
tracing::warn!(event = "local_name_failed", %error, "local name not announced");
|
||||
})
|
||||
.ok();
|
||||
view.local_name = Some((address, announced));
|
||||
}
|
||||
let name = view.local_name.as_ref()?.1.as_ref()?;
|
||||
let host = name.host();
|
||||
Some(LocalNameInfo {
|
||||
url: format!("{}://{host}:{}/", view.scheme, view.listen.port()),
|
||||
host,
|
||||
confirmed: name.confirmed(),
|
||||
})
|
||||
}
|
||||
|
||||
fn describe(view: &mut View) -> Share {
|
||||
let local_name = local_name(view);
|
||||
let advertised = (!view.listen.ip().is_unspecified()).then_some(view.listen.ip());
|
||||
let url = rs_signaling::session_url(
|
||||
view.scheme,
|
||||
@@ -939,6 +974,7 @@ fn describe(view: &mut View) -> Share {
|
||||
})
|
||||
.collect(),
|
||||
refusals: view.room.refusals(),
|
||||
local_name,
|
||||
limit: view.room.limit(),
|
||||
started_ms: view.started_ms,
|
||||
}
|
||||
|
||||
@@ -24,6 +24,6 @@ pub use host::{Config, Host, Overrides};
|
||||
/// depend on `rs-codec`.
|
||||
pub use rs_codec::VideoCodec;
|
||||
pub use state::{
|
||||
Capabilities, HostState, InterfaceOption, Label, Phase, SettingsOutcome, Share, SharedSource,
|
||||
SourceChoice, SourceNote, SourceOption, Stop, ViewerDevice,
|
||||
Capabilities, HostState, InterfaceOption, Label, LocalNameInfo, Phase, SettingsOutcome, Share,
|
||||
SharedSource, SourceChoice, SourceNote, SourceOption, Stop, ViewerDevice,
|
||||
};
|
||||
@@ -201,11 +201,27 @@ pub struct Share {
|
||||
/// Connections refused since the share started, newest first (#35): who
|
||||
/// tried, from where, and why it did not work.
|
||||
pub refusals: Vec<rs_signaling::Refusal>,
|
||||
/// `rustscreen.local`, when announced (#25). The QR code keeps the
|
||||
/// address: the name is for whoever types.
|
||||
pub local_name: Option<LocalNameInfo>,
|
||||
pub limit: u8,
|
||||
#[ts(type = "number")]
|
||||
pub started_ms: u64,
|
||||
}
|
||||
|
||||
/// The local name of the host, as the interface shows it (#25).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[ts(export, export_to = "../../../desktop/src/bindings/")]
|
||||
pub struct LocalNameInfo {
|
||||
/// `rustscreen.local`, or `rustscreen-2.local` if the name was taken.
|
||||
pub host: String,
|
||||
/// Home page by name, to type the short code: `http://rustscreen.local:8099/`.
|
||||
pub url: String,
|
||||
/// Another machine answers over mDNS: the name most likely works. Until
|
||||
/// then the interface puts the address first and says the name is a try.
|
||||
pub confirmed: bool,
|
||||
}
|
||||
|
||||
/// Why the last share stopped, when it was not the user.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[ts(export, export_to = "../../../desktop/src/bindings/")]
|
||||
|
||||
@@ -20,6 +20,7 @@ axum = { version = "0.8.9", features = ["ws"] }
|
||||
axum-server = { version = "0.8.0", features = ["tls-rustls"] }
|
||||
ed25519-dalek = { version = "3.0.0", default-features = false, features = ["fast"] }
|
||||
hex = "0.4.3"
|
||||
mdns-sd = { version = "0.21.6", default-features = false }
|
||||
rand = "0.10.3"
|
||||
rcgen = "0.14.10"
|
||||
sha2 = "0.11.1"
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
//! Responsibilities, split into modules:
|
||||
//!
|
||||
//! - [`room`]: room identifier, token, short code, number of seats.
|
||||
//! - [`local_name`]: `rustscreen.local` over mDNS (#25).
|
||||
//! - [`locales`]: embedded translations, served to the viewer.
|
||||
//! - [`tls`]: persistent self-signed certificate and pinnable fingerprint.
|
||||
//! - [`qr`]: QR code of the session, to join from a phone.
|
||||
//! - [`trust`]: trusted devices and the check of their signature (#34).
|
||||
//! - [`server`]: HTTP, signaling WebSocket, status API.
|
||||
|
||||
pub mod local_name;
|
||||
pub mod locales;
|
||||
pub mod qr;
|
||||
pub mod room;
|
||||
@@ -17,6 +19,7 @@ pub mod server;
|
||||
pub mod tls;
|
||||
pub mod trust;
|
||||
|
||||
pub use local_name::LocalName;
|
||||
pub use room::{CodeExchange, Device, Refusal, RefusalCause, Registration, Room, RoomError};
|
||||
pub use server::{
|
||||
Diagnostics, HostConfig, ServerError, SharedMediaSource, bind_listener, serve, serve_listener,
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
//! The local name of the host, `rustscreen.local`, announced over mDNS (#25).
|
||||
//!
|
||||
//! An IP address changes and nobody remembers it; a name is dictated. The host
|
||||
//! announces `rustscreen.local` on the address it shares, plus an `_http._tcp`
|
||||
//! service for the browsers and tools that list them. On a name conflict
|
||||
//! (another host already called `rustscreen`), the library probes and moves to
|
||||
//! `rustscreen-2.local`; the name shown follows.
|
||||
//!
|
||||
//! The name never replaces the address (ADR 0005): the QR code keeps the IP,
|
||||
//! and the interface says whether the name was **confirmed**. The host cannot
|
||||
//! hear its own announcement fail, but it can hear others: as soon as another
|
||||
//! machine answers over mDNS, multicast passes on this network and the name has
|
||||
//! every chance to work. Until then, the name is shown as a try, the address
|
||||
//! first.
|
||||
//!
|
||||
//! mDNS stays on the local link (224.0.0.251 and ff02::fb, port 5353): no
|
||||
//! packet leaves the network, in line with the "no outbound call" rule.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use mdns_sd::{DaemonEvent, IfKind, ServiceDaemon, ServiceEvent, ServiceInfo};
|
||||
|
||||
/// The name announced, without the `.local` suffix.
|
||||
pub const BASE_NAME: &str = "rustscreen";
|
||||
const SERVICE_TYPE: &str = "_http._tcp.local.";
|
||||
/// How many service types to look at to hear another machine: enough to find
|
||||
/// one on an ordinary network, few enough not to chatter.
|
||||
const TYPES_PROBED: usize = 8;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LocalNameError {
|
||||
#[error("mDNS: {0}")]
|
||||
Mdns(#[from] mdns_sd::Error),
|
||||
}
|
||||
|
||||
/// The announcement, alive as long as this value: dropping it withdraws the
|
||||
/// name from the network.
|
||||
pub struct LocalName {
|
||||
daemon: ServiceDaemon,
|
||||
fullname: String,
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
/// Current host name, `rustscreen.local` or its renamed form.
|
||||
host: Mutex<String>,
|
||||
/// Another machine answered over mDNS: multicast passes here.
|
||||
confirmed: AtomicBool,
|
||||
}
|
||||
|
||||
impl LocalName {
|
||||
/// Announces the name on `address`, the one viewers reach, for `port`.
|
||||
pub fn announce(address: IpAddr, port: u16) -> Result<Self, LocalNameError> {
|
||||
let daemon = ServiceDaemon::new()?;
|
||||
// Only the shared interface: a VPN or a container bridge must not get
|
||||
// the name of an address it cannot reach.
|
||||
daemon.disable_interface(IfKind::All)?;
|
||||
daemon.enable_interface(IfKind::Addr(address))?;
|
||||
let host = format!("{BASE_NAME}.local.");
|
||||
let service = ServiceInfo::new(
|
||||
SERVICE_TYPE,
|
||||
BASE_NAME,
|
||||
&host,
|
||||
address,
|
||||
port,
|
||||
&[("path", "/")][..],
|
||||
)?;
|
||||
let fullname = service.get_fullname().to_string();
|
||||
let monitor = daemon.monitor()?;
|
||||
daemon.register(service)?;
|
||||
let shared = Arc::new(Shared {
|
||||
host: Mutex::new(host),
|
||||
confirmed: AtomicBool::new(false),
|
||||
});
|
||||
let meta = daemon.browse("_services._dns-sd._udp.local.")?;
|
||||
spawn_watch(daemon.clone(), monitor, meta, address, shared.clone());
|
||||
tracing::info!(event = "local_name_announced", %address, port, "local name announced");
|
||||
Ok(Self {
|
||||
daemon,
|
||||
fullname,
|
||||
shared,
|
||||
})
|
||||
}
|
||||
|
||||
/// The name to type, `rustscreen.local` (or `rustscreen-2.local`).
|
||||
pub fn host(&self) -> String {
|
||||
lock(&self.shared.host).trim_end_matches('.').to_string()
|
||||
}
|
||||
|
||||
/// Has another machine answered over mDNS? Then the name most likely
|
||||
/// resolves for viewers too.
|
||||
pub fn confirmed(&self) -> bool {
|
||||
self.shared.confirmed.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LocalName {
|
||||
fn drop(&mut self) {
|
||||
// Says goodbye on the network, then stops the daemon thread; neither
|
||||
// waits for an answer.
|
||||
let _ = self.daemon.unregister(&self.fullname);
|
||||
let _ = self.daemon.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
/// Follows renames, and listens for any other machine answering. Ends when
|
||||
/// the daemon stops: its channels close.
|
||||
fn spawn_watch(
|
||||
daemon: ServiceDaemon,
|
||||
monitor: mdns_sd::Receiver<DaemonEvent>,
|
||||
meta: mdns_sd::Receiver<ServiceEvent>,
|
||||
ours: IpAddr,
|
||||
shared: Arc<Shared>,
|
||||
) {
|
||||
let renames = shared.clone();
|
||||
std::thread::spawn(move || {
|
||||
while let Ok(event) = monitor.recv() {
|
||||
if let DaemonEvent::NameChange(change) = event
|
||||
&& change.original.ends_with(".local.")
|
||||
&& !change.original.contains("._")
|
||||
{
|
||||
tracing::info!(
|
||||
event = "local_name_renamed",
|
||||
from = %change.original,
|
||||
to = %change.new_name,
|
||||
"name taken on the network"
|
||||
);
|
||||
*lock(&renames.host) = change.new_name;
|
||||
}
|
||||
}
|
||||
});
|
||||
std::thread::spawn(move || {
|
||||
let mut probed = HashSet::new();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
loop {
|
||||
// Service types announced by anyone, ourselves included: the
|
||||
// addresses of their instances tell who.
|
||||
while let Ok(ServiceEvent::ServiceFound(_, kind)) =
|
||||
meta.recv_timeout(Duration::from_millis(200))
|
||||
{
|
||||
if probed.len() < TYPES_PROBED
|
||||
&& probed.insert(kind.clone())
|
||||
&& let Ok(receiver) = daemon.browse(&kind)
|
||||
{
|
||||
let tx = tx.clone();
|
||||
std::thread::spawn(move || {
|
||||
while let Ok(event) = receiver.recv() {
|
||||
if tx.send(event).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
while let Ok(event) = rx.try_recv() {
|
||||
if let ServiceEvent::ServiceResolved(service) = event
|
||||
&& service
|
||||
.get_addresses()
|
||||
.iter()
|
||||
.any(|a| a.to_ip_addr() != ours)
|
||||
&& !shared.confirmed.swap(true, Ordering::Relaxed)
|
||||
{
|
||||
tracing::info!(
|
||||
event = "local_name_confirmed",
|
||||
"another machine answers over mDNS"
|
||||
);
|
||||
}
|
||||
}
|
||||
if meta.is_disconnected() || shared.confirmed.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
mutex.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The announced name resolves on this machine, to the announced address.
|
||||
/// Without a network route (Nix sandbox), there is nothing to announce on.
|
||||
#[test]
|
||||
fn the_name_resolves_to_the_shared_address() {
|
||||
let Some(address) = rs_rtc::local_candidate_address() else {
|
||||
eprintln!("no network route: test skipped");
|
||||
return;
|
||||
};
|
||||
let name = LocalName::announce(address, 8099).expect("announce");
|
||||
assert_eq!(name.host(), "rustscreen.local");
|
||||
let client = ServiceDaemon::new().unwrap();
|
||||
let events = client
|
||||
.resolve_hostname("rustscreen.local.", Some(3000))
|
||||
.unwrap();
|
||||
let mut found = false;
|
||||
while let Ok(event) = events.recv_timeout(Duration::from_secs(4)) {
|
||||
if let mdns_sd::HostnameResolutionEvent::AddressesFound(_, addresses) = event {
|
||||
found = addresses.iter().any(|a| a.to_ip_addr() == address);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = client.shutdown();
|
||||
assert!(found, "rustscreen.local did not resolve to {address}");
|
||||
}
|
||||
}
|
||||
@@ -140,6 +140,10 @@ système, prévention d'une fermeture accidentelle.
|
||||
- Appareils de confiance (ADR 0011) : l'hôte garde la clé publique Ed25519 d'un appareil auquel il
|
||||
fait confiance; l'appareil revient sans lien en signant un nonce neuf à chaque connexion. La
|
||||
révocation renvoie l'appareil sur-le-champ et reste locale.
|
||||
- Nom local (#25): l'hôte annonce `rustscreen.local` en mDNS sur la seule interface partagée
|
||||
(`rustscreen-2.local` si le nom est pris). Le QR code garde l'adresse IP; l'interface ne met le
|
||||
nom en avant qu'une fois qu'une autre machine a répondu en mDNS, preuve que le multicast passe.
|
||||
Le mDNS reste sur le lien local (224.0.0.251, port 5353).
|
||||
- Aucune télémétrie, aucun appel sortant. Un test d'intégration vérifie l'absence de connexion
|
||||
externe pendant une session.
|
||||
|
||||
|
||||
@@ -101,6 +101,8 @@
|
||||
"fingerprint": "Certificate fingerprint",
|
||||
"code": "Without a camera, type the code",
|
||||
"codeHelp": "at {home}",
|
||||
"localNameAddress": "or at {address} if the name does not answer",
|
||||
"localNameUnconfirmed": "{url} may also work: no other device has answered by name on this network yet",
|
||||
"codeExpiresIn": "valid for {duration} more for a new device",
|
||||
"codeExpired": "Code expired: no new device can join. Viewers who already came can return.",
|
||||
"newCode": "New code",
|
||||
|
||||
@@ -101,6 +101,8 @@
|
||||
"fingerprint": "Empreinte du certificat",
|
||||
"code": "Sans caméra, taper le code",
|
||||
"codeHelp": "sur {home}",
|
||||
"localNameAddress": "ou sur {address} si le nom ne répond pas",
|
||||
"localNameUnconfirmed": "{url} peut aussi marcher : aucun autre appareil n'a encore répondu par nom sur ce réseau",
|
||||
"codeExpiresIn": "valable encore {duration} pour un nouvel appareil",
|
||||
"codeExpired": "Code expiré: aucun nouvel appareil n’entre. Les spectateurs déjà venus peuvent revenir.",
|
||||
"newCode": "Nouveau code",
|
||||
|
||||
Reference in new issue
Block a user