From f94b33e2dc3743ce25f7a9c524daf64db609c9e4 Mon Sep 17 00:00:00 2001 From: Nived Chandran <182140860+NivedV1@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:38:32 +0530 Subject: [PATCH 1/2] fix: keep one AirDrop device across receive restarts Publish a stable mDNS instance id from the state directory so Apple peers don't list a new receiver on every 'owly receive' (#125), and await the TTL-0 goodbye on exit so stale records are withdrawn before the runtime is dropped. Tests: id persistence across restarts and goodbye with TTL 0. --- crates/owly-airdrop/src/driver/mdns.rs | 28 +++++++++++-- crates/owly-airdrop/src/proto/mdns.rs | 11 +++++ crates/owly-cli/src/airdrop.rs | 57 +++++++++++++++++++++++--- 3 files changed, 87 insertions(+), 9 deletions(-) diff --git a/crates/owly-airdrop/src/driver/mdns.rs b/crates/owly-airdrop/src/driver/mdns.rs index 4d44c73..da41fc6 100644 --- a/crates/owly-airdrop/src/driver/mdns.rs +++ b/crates/owly-airdrop/src/driver/mdns.rs @@ -22,9 +22,23 @@ pub struct Mdns { burst: Option, } -/// 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>, + withdrawn: oneshot::Receiver<()>, +} + +impl Registration { + /// Withdraw the records and wait for the goodbye to reach the link. + pub async fn withdraw(mut self) { + if let Some(stop) = self.stop.take() { + let _ = stop.send(()); + } + let _ = self.withdrawn.await; + } } /// A running browse, which stops when dropped. @@ -54,9 +68,13 @@ impl Mdns { pub async fn register(&self, service: Service) -> io::Result { 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). @@ -107,6 +125,7 @@ impl Mdns { socket: UdpSocket, service: Service, mut stopped: oneshot::Receiver<()>, + withdrawn: oneshot::Sender<()>, ) { let group = self.group(); let announcement = service.announcement(); @@ -136,6 +155,7 @@ impl Mdns { } // Withdraw the records (RFC 6762 §10.1). let _ = socket.send_to(&service.goodbye(), group).await; + let _ = withdrawn.send(()); } async fn browse_loop( diff --git a/crates/owly-airdrop/src/proto/mdns.rs b/crates/owly-airdrop/src/proto/mdns.rs index f0cc257..dc98903 100644 --- a/crates/owly-airdrop/src/proto/mdns.rs +++ b/crates/owly-airdrop/src/proto/mdns.rs @@ -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 { diff --git a/crates/owly-cli/src/airdrop.rs b/crates/owly-cli/src/airdrop.rs index e36ee90..0fac76f 100644 --- a/crates/owly-cli/src/airdrop.rs +++ b/crates/owly-cli/src/airdrop.rs @@ -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; @@ -370,6 +370,29 @@ fn random_service_id() -> io::Result { Ok(mdns::service_id(bytes)) } +/// MDNS-1: a receiver's instance name must survive restarts. Publishing a +/// fresh random ID on every run makes Apple peers list a new AirDrop device +/// each time (issue #125), so keep the six bytes in the state directory that +/// already holds our TLS identity. +fn receiver_service_id(state: &Path) -> io::Result { + let path = state.join("receiver-id"); + let bytes = match std::fs::read(&path) { + Ok(bytes) if bytes.len() == 6 => { + let mut id = [0; 6]; + id.copy_from_slice(&bytes); + id + } + _ => { + let mut id = [0; 6]; + getrandom::fill(&mut id).map_err(|e| io::Error::other(e.to_string()))?; + std::fs::create_dir_all(state)?; + std::fs::write(&path, id)?; + id + } + }; + Ok(mdns::service_id(bytes)) +} + /// BLE-5: a fresh tag per advert. fn random_tag() -> io::Result<[u8; 3]> { let mut tag = [0; 3]; @@ -663,8 +686,8 @@ 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 service_id = receiver_service_id(&state)?; + let mut registration = if no_mdns { None } else { let service = Service { @@ -690,10 +713,10 @@ async fn run_receiver( 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}"), @@ -748,12 +771,36 @@ 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.take() { + let _ = tokio::time::timeout(Duration::from_secs(2), registration.withdraw()).await; + } + 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 straight_and_curly_apostrophes_name_the_same_receiver() { assert!(same_name("Jane's iPhone", "Jane's iPhone")); From 2d496b6da6781e15f97ad2a554c04f0119f81b7b Mon Sep 17 00:00:00 2001 From: Nived Chandran <182140860+NivedV1@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:02:09 +0530 Subject: [PATCH 2/2] fix: make receiver ID creation atomic and report mDNS withdrawal errors --- crates/owly-airdrop/src/driver/mdns.rs | 18 +++--- crates/owly-cli/Cargo.toml | 4 +- crates/owly-cli/src/airdrop.rs | 90 +++++++++++++++++++------- 3 files changed, 78 insertions(+), 34 deletions(-) diff --git a/crates/owly-airdrop/src/driver/mdns.rs b/crates/owly-airdrop/src/driver/mdns.rs index da41fc6..ac6c619 100644 --- a/crates/owly-airdrop/src/driver/mdns.rs +++ b/crates/owly-airdrop/src/driver/mdns.rs @@ -28,16 +28,18 @@ pub struct Mdns { /// (issue #125). pub struct Registration { stop: Option>, - withdrawn: oneshot::Receiver<()>, + withdrawn: oneshot::Receiver>, } impl Registration { - /// Withdraw the records and wait for the goodbye to reach the link. - pub async fn withdraw(mut self) { + /// 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(()); } - let _ = self.withdrawn.await; + self.withdrawn + .await + .map_err(|_| io::Error::other("mDNS responder stopped before withdrawal"))? } } @@ -68,7 +70,7 @@ impl Mdns { pub async fn register(&self, service: Service) -> io::Result { let socket = self.socket()?; let (stop, stopped) = oneshot::channel::<()>(); - let (withdrawn, done) = oneshot::channel::<()>(); + let (withdrawn, done) = oneshot::channel(); let this = self.clone(); tokio::spawn(async move { this.respond(socket, service, stopped, withdrawn).await }); Ok(Registration { @@ -125,7 +127,7 @@ impl Mdns { socket: UdpSocket, service: Service, mut stopped: oneshot::Receiver<()>, - withdrawn: oneshot::Sender<()>, + withdrawn: oneshot::Sender>, ) { let group = self.group(); let announcement = service.announcement(); @@ -154,8 +156,8 @@ impl Mdns { } } // Withdraw the records (RFC 6762 §10.1). - let _ = socket.send_to(&service.goodbye(), group).await; - let _ = withdrawn.send(()); + let result = socket.send_to(&service.goodbye(), group).await; + let _ = withdrawn.send(result.map(|_| ())); } async fn browse_loop( diff --git a/crates/owly-cli/Cargo.toml b/crates/owly-cli/Cargo.toml index 045d0d4..e547551 100644 --- a/crates/owly-cli/Cargo.toml +++ b/crates/owly-cli/Cargo.toml @@ -24,6 +24,7 @@ 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"] } @@ -31,6 +32,3 @@ zbus = { version = "5", default-features = false, features = ["tokio"] } [lints] workspace = true - -[dev-dependencies] -tempfile = "3" diff --git a/crates/owly-cli/src/airdrop.rs b/crates/owly-cli/src/airdrop.rs index 0fac76f..c3881ad 100644 --- a/crates/owly-cli/src/airdrop.rs +++ b/crates/owly-cli/src/airdrop.rs @@ -370,27 +370,33 @@ fn random_service_id() -> io::Result { Ok(mdns::service_id(bytes)) } -/// MDNS-1: a receiver's instance name must survive restarts. Publishing a -/// fresh random ID on every run makes Apple peers list a new AirDrop device -/// each time (issue #125), so keep the six bytes in the state directory that -/// already holds our TLS identity. +/// Keep the same published receiver identity across restarts (issue #125). fn receiver_service_id(state: &Path) -> io::Result { let path = state.join("receiver-id"); - let bytes = match std::fs::read(&path) { - Ok(bytes) if bytes.len() == 6 => { - let mut id = [0; 6]; - id.copy_from_slice(&bytes); - id - } - _ => { - let mut id = [0; 6]; - getrandom::fill(&mut id).map_err(|e| io::Error::other(e.to_string()))?; - std::fs::create_dir_all(state)?; - std::fs::write(&path, id)?; - id - } + let read_id = || -> io::Result { + 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)) }; - Ok(mdns::service_id(bytes)) + 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. @@ -686,10 +692,10 @@ async fn run_receiver( let (receiver, mut events) = Receiver::bind(addr, &identity, Options::new(config, dir)).await?; tokio::spawn(receiver.run()); - let service_id = receiver_service_id(&state)?; - let mut 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}"), @@ -697,6 +703,7 @@ async fn run_receiver( addr: iface.addr, flags, }; + eprintln!("mDNS instance {service_id}"); Some( Mdns::new(iface.index) .with_burst(burst) @@ -705,7 +712,7 @@ 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 ); @@ -773,8 +780,16 @@ async fn run_receiver( } // 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.take() { - let _ = tokio::time::timeout(Duration::from_secs(2), registration.withdraw()).await; + 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) } @@ -801,6 +816,35 @@ mod tests { ); } + #[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"));