Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions crates/owly-airdrop/src/driver/mdns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,25 @@ pub struct Mdns {
burst: Option<Burst>,
}

/// A registered service, withdrawn when dropped.
/// A registered service. Dropping it asks the responder to stop; call
/// [`Registration::withdraw`] to send the goodbye before exiting, or the
/// records stay in peers' caches and they list a new device on every restart
/// (issue #125).
pub struct Registration {
_stop: oneshot::Sender<()>,
stop: Option<oneshot::Sender<()>>,
withdrawn: oneshot::Receiver<io::Result<()>>,
}

impl Registration {
/// Withdraw the records and wait for the socket to accept the goodbye.
pub async fn withdraw(mut self) -> io::Result<()> {
if let Some(stop) = self.stop.take() {
let _ = stop.send(());
}
self.withdrawn
.await
.map_err(|_| io::Error::other("mDNS responder stopped before withdrawal"))?
}
}

/// A running browse, which stops when dropped.
Expand Down Expand Up @@ -54,9 +70,13 @@ impl Mdns {
pub async fn register(&self, service: Service) -> io::Result<Registration> {
let socket = self.socket()?;
let (stop, stopped) = oneshot::channel::<()>();
let (withdrawn, done) = oneshot::channel();
let this = self.clone();
tokio::spawn(async move { this.respond(socket, service, stopped).await });
Ok(Registration { _stop: stop })
tokio::spawn(async move { this.respond(socket, service, stopped, withdrawn).await });
Ok(Registration {
stop: Some(stop),
withdrawn: done,
})
}

/// Browses `_airdrop._tcp` until the browse is dropped (MDNS-6).
Expand Down Expand Up @@ -107,6 +127,7 @@ impl Mdns {
socket: UdpSocket,
service: Service,
mut stopped: oneshot::Receiver<()>,
withdrawn: oneshot::Sender<io::Result<()>>,
) {
let group = self.group();
let announcement = service.announcement();
Expand Down Expand Up @@ -135,7 +156,8 @@ impl Mdns {
}
}
// Withdraw the records (RFC 6762 §10.1).
let _ = socket.send_to(&service.goodbye(), group).await;
let result = socket.send_to(&service.goodbye(), group).await;
let _ = withdrawn.send(result.map(|_| ()));
}

async fn browse_loop(
Expand Down
11 changes: 11 additions & 0 deletions crates/owly-airdrop/src/proto/mdns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1015,6 +1015,17 @@ mod tests {
assert_ne!(RECEIVER_FLAGS & SUPPORTS_URL, 0);
}

#[test]
fn goodbye_withdraws_every_record() {
let bye = Message::decode(&service().goodbye()).unwrap();
assert!(bye.response);
assert_eq!(bye.answers.len(), 4);
assert!(
bye.answers.iter().all(|r| r.ttl == 0),
"RFC 6762 10.1: a goodbye carries TTL 0"
);
}

#[test]
fn answers_queries() {
let query = |name: Name, qtype| Message {
Expand Down
4 changes: 1 addition & 3 deletions crates/owly-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,11 @@ owlyd = { path = "../owlyd" }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tempfile = "3"
tokio = { version = "1", features = ["io-std", "io-util", "macros", "process", "rt-multi-thread", "signal", "sync", "time"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
zbus = { version = "5", default-features = false, features = ["tokio"] }

[lints]
workspace = true

[dev-dependencies]
tempfile = "3"
103 changes: 97 additions & 6 deletions crates/owly-cli/src/airdrop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
use std::collections::BTreeSet;
use std::io;
use std::net::{Ipv6Addr, SocketAddrV6};
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;

Expand Down Expand Up @@ -370,6 +370,35 @@ fn random_service_id() -> io::Result<String> {
Ok(mdns::service_id(bytes))
}

/// Keep the same published receiver identity across restarts (issue #125).
fn receiver_service_id(state: &Path) -> io::Result<String> {
let path = state.join("receiver-id");
let read_id = || -> io::Result<String> {
let id = std::fs::read(&path)?.try_into().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"receiver-id must contain six bytes",
)
})?;
Ok(mdns::service_id(id))
};
match read_id() {
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
result => return result,
}

let mut id = [0; 6];
getrandom::fill(&mut id).map_err(|e| io::Error::other(e.to_string()))?;
std::fs::create_dir_all(state)?;
let mut file = tempfile::NamedTempFile::new_in(state)?;
std::io::Write::write_all(&mut file, &id)?;
match file.persist_noclobber(path.as_path()) {
Ok(_) => Ok(mdns::service_id(id)),
Err(e) if e.error.kind() == io::ErrorKind::AlreadyExists => read_id(),
Err(e) => Err(e.error),
}
}

/// BLE-5: a fresh tag per advert.
fn random_tag() -> io::Result<[u8; 3]> {
let mut tag = [0; 3];
Expand Down Expand Up @@ -663,17 +692,18 @@ async fn run_receiver(
let (receiver, mut events) = Receiver::bind(addr, &identity, Options::new(config, dir)).await?;
tokio::spawn(receiver.run());

let service_id = random_service_id()?;
let _registration = if no_mdns {
let registration = if no_mdns {
None
} else {
let service_id = receiver_service_id(&state)?;
let service = Service {
instance: service_id.clone(),
host: format!("owly-{service_id}"),
port,
addr: iface.addr,
flags,
};
eprintln!("mDNS instance {service_id}");
Some(
Mdns::new(iface.index)
.with_burst(burst)
Expand All @@ -682,18 +712,18 @@ async fn run_receiver(
)
};
eprintln!(
"receiving as {name:?} ({service_id}) on [{}]:{port}, flags {flags:#x}",
"receiving as {name:?} on [{}]:{port}, flags {flags:#x}",
iface.addr
);

let mut stdin = tokio::io::BufReader::new(tokio::io::stdin()).lines();
loop {
let event = tokio::select! {
event = events.recv() => event,
_ = tokio::signal::ctrl_c() => return Ok(ExitCode::SUCCESS),
_ = tokio::signal::ctrl_c() => break,
};
let Some(event) = event else {
return Ok(ExitCode::SUCCESS);
break;
};
match event {
ReceiverEvent::Discovered { peer, .. } => eprintln!("seen by {peer}"),
Expand Down Expand Up @@ -748,12 +778,73 @@ async fn run_receiver(
ReceiverEvent::Failed { reason, .. } => eprintln!("transfer failed: {reason}"),
}
}
// A detached responder would be killed with the runtime before its
// goodbye goes out, leaving stale records on Apple peers (#125).
if let Some(registration) = registration {
match tokio::time::timeout(Duration::from_secs(2), registration.withdraw()).await {
Ok(result) => result?,
Err(_) => {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"mDNS withdrawal timed out",
));
}
}
}
Ok(ExitCode::SUCCESS)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn the_receiver_keeps_its_identity_across_restarts() {
let state = tempfile::tempdir().unwrap();
let first = receiver_service_id(state.path()).unwrap();
assert_eq!(first.len(), 12, "a service id is 12 hex digits");
assert_eq!(
receiver_service_id(state.path()).unwrap(),
first,
"a restart reuses the published instance"
);
let other = tempfile::tempdir().unwrap();
assert_ne!(
receiver_service_id(other.path()).unwrap(),
first,
"different state directories are different receivers"
);
}

#[test]
fn concurrent_receivers_use_the_same_persisted_id() {
let state = tempfile::tempdir().unwrap();
let start = std::sync::Barrier::new(8);
std::thread::scope(|scope| {
let receivers: Vec<_> = (0..8)
.map(|_| {
scope.spawn(|| {
start.wait();
receiver_service_id(state.path()).unwrap()
})
})
.collect();
let ids: Vec<_> = receivers.into_iter().map(|r| r.join().unwrap()).collect();
let persisted = receiver_service_id(state.path()).unwrap();
assert!(ids.iter().all(|id| id == &persisted));
});
}

#[test]
fn malformed_receiver_id_is_preserved() {
let state = tempfile::tempdir().unwrap();
let path = state.path().join("receiver-id");
std::fs::write(&path, b"short").unwrap();
let error = receiver_service_id(state.path()).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(std::fs::read(path).unwrap(), b"short");
}

#[test]
fn straight_and_curly_apostrophes_name_the_same_receiver() {
assert!(same_name("Jane's iPhone", "Jane's iPhone"));
Expand Down
Loading