An open-source cross-platform alternative to AirDrop
mod store;
pub use store::{
ChannelState, DeviceChannel, DeviceLog, DeviceLogEvent, DiscoveredDevice, HttpChannel,
Outbound, StatefulDevice,
};
use crate::http::client::{ClientError, LsHttpClientV2};
use crate::http::dto_v2::{RegisterDtoV2, RegisterResponseDtoV2};
use crate::http::server::PeerIp;
use crate::model::discovery::{MulticastMessageV2, ProtocolType};
use crate::multicast::{self, MulticastConfig, MulticastDevice, MulticastEvent, MulticastHandle};
use crate::util::error::ErrorChain;
use crate::util::interface::InterfaceFilter;
use futures_util::StreamExt;
use std::collections::HashSet;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use store::{Announcement, DeviceStore, Observation};
use tokio::sync::{mpsc, oneshot};
/// The default timeout of the register requests sent by discovery, matching
/// the Flutter app's default discovery timeout. Discovery only talks to LAN
/// peers, which answer quickly or not at all.
pub const DEFAULT_DISCOVERY_TIMEOUT: Duration = Duration::from_millis(500);
/// Capacity of the internal multicast event channel.
const MULTICAST_CHANNEL_SIZE: usize = 64;
/// How many hosts a subnet scan probes at once, matching the Flutter app's
/// legacy HTTP discovery.
const SCAN_CONCURRENCY: usize = 50;
/// This device's TLS identity, sent as client certificate with every register
/// request (client certificates are mandatory in HTTPS mode).
///
/// Its fingerprint is the one carried in [`MulticastDevice::fingerprint`].
#[derive(Clone)]
pub struct DeviceIdentity {
/// PEM-encoded certificate.
pub cert_pem: String,
/// PEM-encoded private key.
pub private_key_pem: String,
}
/// Configuration of the discovery.
pub struct DiscoveryConfig {
/// The multicast group to join, usually [`multicast::DEFAULT_MULTICAST_GROUP`].
pub group: Ipv4Addr,
/// The IPv6 multicast group to additionally join, usually
/// [`multicast::DEFAULT_MULTICAST_GROUP_V6`]. `None` disables IPv6 discovery.
pub group_v6: Option<Ipv6Addr>,
/// The multicast port to bind, usually [`multicast::DEFAULT_PORT`].
pub port: u16,
/// Restricts the network interfaces that are used.
pub interface_filter: InterfaceFilter,
/// The device information announced to the network and sent in register
/// requests.
pub device: MulticastDevice,
/// The TLS identity used for the register requests.
pub identity: DeviceIdentity,
/// Timeout of each register request sent by discovery, usually
/// [`DEFAULT_DISCOVERY_TIMEOUT`]. Bounds how long an unresponsive host
/// stalls a subnet scan, so keep it short.
pub timeout: Duration,
/// Channel on which discovery events are emitted. `None` when the
/// application only polls [`DiscoveryHandle::devices`].
pub event_tx: Option<mpsc::Sender<DiscoveryEvent>>,
}
/// An event emitted by the discovery. Every observation is also logged in
/// [`StatefulDevice::logs`]; the accumulated state is read from
/// [`DiscoveryHandle::devices`].
///
/// A confirmation is an HTTP request exchanged with the device in either
/// direction: the device answered a request of this device, or it sent one
/// to this device's server. Which direction a channel was confirmed in is
/// kept in [`StatefulDevice::channels`].
#[derive(Clone, Debug)]
pub enum DiscoveryEvent {
/// A device was confirmed over one of its channels for the first time
/// in this run.
Discovered {
/// The device as it was confirmed, i.e. carrying only the channel
/// the confirmation happened on.
device: DiscoveredDevice,
},
/// An already confirmed device was observed again: it re-announced
/// itself or was re-discovered, at a known or a new address, or a
/// request to it failed (which only changes the ranking of its
/// channels).
Updated {
/// The device as it was observed, carrying only the channel the
/// observation happened on.
device: DiscoveredDevice,
},
/// A device that was never confirmed could not be reached: it was heard
/// announcing itself but the register request got no response. Such a
/// device is only listed in [`DiscoveryHandle::unconfirmed_devices`].
Unreachable {
/// The device carrying the channel that failed. Unverified: it is
/// what the announcement claimed.
device: DiscoveredDevice,
/// Why the request failed, for display.
error: String,
},
/// The multicast sockets failed permanently, e.g. because the OS
/// invalidated them while the application was suspended (iOS reclaims the
/// sockets of suspended apps). Announcements are no longer heard or sent;
/// the application should restart discovery to rebind the sockets.
/// HTTP-based discovery (probes and subnet scans) keeps working.
MulticastFailed,
}
struct DiscoveryState {
device: MulticastDevice,
identity: DeviceIdentity,
timeout: Duration,
store: DeviceStore,
event_tx: Option<mpsc::Sender<DiscoveryEvent>>,
/// Whether announcements of other devices are answered, see
/// [`DiscoveryHandle::set_answer_announcements`].
answering: AtomicBool,
/// The interface addresses a subnet scan is currently running for.
scanning: std::sync::Mutex<HashSet<Ipv4Addr>>,
/// The devices (by fingerprint) and channels a dial-back is currently
/// running for, see [`dial_back`].
dialing_back: std::sync::Mutex<HashSet<(String, DeviceChannel)>>,
/// Number of confirmations in this run, on which
/// [`DiscoveryHandle::discover_staged`] decides whether to escalate.
confirmations: AtomicU64,
}
impl DiscoveryState {
fn register_dto(&self) -> RegisterDtoV2 {
RegisterDtoV2 {
alias: self.device.alias.clone(),
version: self.device.version.clone(),
device_model: self.device.device_model.clone(),
device_type: self.device.device_type.clone(),
fingerprint: self.device.fingerprint.clone(),
port: self.device.port,
protocol: self.device.protocol,
download: self.device.download,
}
}
/// A client accepting any valid certificate, for peers whose fingerprint
/// is not known before they answer. The fingerprint is then read off the
/// handshake and pinned by connections that transfer data.
fn unpinned_client(&self) -> Result<LsHttpClientV2, ClientError> {
LsHttpClientV2::try_new(
&self.identity.private_key_pem,
&self.identity.cert_pem,
None,
Some(self.timeout),
)
}
/// Registers with `host:port` and, when a device answers, puts it into
/// the store. Returns the device's stored state after the merge, or
/// `None` when the answer carried this device's own fingerprint.
async fn probe(
&self,
client: &LsHttpClientV2,
host: &str,
port: u16,
protocol: ProtocolType,
) -> Result<Option<StatefulDevice>, ClientError> {
let response = client
.register(protocol, host, port, self.register_dto())
.await?;
// In HTTPS mode the certificate is the peer's identity; the
// fingerprint claimed in the body only counts without encryption.
let fingerprint = match protocol {
ProtocolType::Https => response
.cert_fingerprint
.clone()
.ok_or_else(|| anyhow::anyhow!("HTTPS response carried no peer certificate"))?,
ProtocolType::Http => response.body.fingerprint.clone(),
};
if fingerprint == self.device.fingerprint {
return Ok(None);
}
let device = confirmed_device(response.body, host.to_string(), port, protocol, fingerprint);
let (_, merged) = self.observed(device, Observation::Reached, None);
Ok(Some(merged))
}
/// Puts an observation of a device (made on `device.channel`), after
/// hearing `announcement` when that is what led to it — into the store,
/// logging it on the device, and emits the resulting event. Returns
/// whether the device is new, and its stored state after the merge.
fn observed(
&self,
device: DiscoveredDevice,
observation: Observation,
announcement: Option<Announcement>,
) -> (bool, StatefulDevice) {
if !matches!(observation, Observation::Failed(_)) {
self.confirmations.fetch_add(1, Ordering::Relaxed);
}
let (event, merged) =
self.store
.observe(device, observation, announcement, SystemTime::now());
let is_new = matches!(event, Some(DiscoveryEvent::Discovered { .. }));
if let Some(event) = event {
self.emit(event);
}
(is_new, merged)
}
fn emit(&self, event: DiscoveryEvent) {
if let Some(event_tx) = &self.event_tx {
// Never wait for the application here. A subnet scan confirms up to
// 255 devices in a burst, far more than the channel holds, and
// every confirmation runs inside the scan's own concurrency limit:
// blocking on a full channel would stall the scan for good and
// leave its `ScanGuard` held, so the interface could never be
// scanned again.
//
// Dropping an event only costs a refresh. The device is in the
// store before the event is emitted, so it is still returned by
// the scan and by `devices()`.
if let Err(err) = event_tx.try_send(event) {
tracing::debug!("Dropped a discovery event: {err}");
}
}
}
}
/// A handle to a running discovery: the store of discovered devices and the
/// application-initiated operations.
pub struct DiscoveryHandle {
/// The multicast side, or the reason it could not be started; discovery
/// keeps working without it, see [`DiscoveryHandle::multicast_error`].
multicast: Result<MulticastHandle, anyhow::Error>,
state: Arc<DiscoveryState>,
}
impl DiscoveryHandle {
/// Announces this device to the network, which makes every other LocalSend
/// device on it register with this device over HTTP.
///
/// Devices registering in response arrive at the application as server
/// events, not here: discovery only learns about peers that announce
/// themselves. Feed them back via [`DiscoveryHandle::observe_inbound`].
///
/// Returns once the whole announcement burst has been sent, which takes a
/// few seconds, or immediately once discovery has been stopped or
/// multicast is unavailable.
pub async fn announce(&self) {
if let Ok(multicast) = &self.multicast {
multicast.announce().await;
}
}
/// The reason the multicast sockets could not be bound (e.g. the port is
/// taken, or there is no usable network interface), when they could not.
///
/// Discovery then neither hears nor sends announcements; it still learns
/// about devices through [`DiscoveryHandle::discover`],
/// [`DiscoveryHandle::scan_subnet`] and
/// [`DiscoveryHandle::observe_inbound`].
pub fn multicast_error(&self) -> Option<&anyhow::Error> {
self.multicast.as_ref().err()
}
/// Discovers a device at a known address, e.g. a favorite or a peer that
/// multicast does not reach, by sending it a register request.
///
/// On success the device is put into the store (and emitted, as
/// `Discovered` or `Updated`), and its full stored state — all known
/// channels and logs — is returned.
/// Returns `None` when the address answered with this device's own
/// fingerprint, i.e. the device discovered itself.
pub async fn discover(
&self,
host: &str,
port: u16,
protocol: ProtocolType,
) -> Result<Option<StatefulDevice>, ClientError> {
let client = self.state.unpinned_client()?;
self.state.probe(&client, host, port, protocol).await
}
/// Discovers devices at known addresses, e.g. the favorites, by sending
/// each channel a register request: [`DiscoveryHandle::discover`] for a
/// whole list, probed concurrently.
///
/// Channels that do not answer are skipped; returns the stored state of
/// the devices that answered, in completion order.
pub async fn discover_known_http_channels(
&self,
channels: Vec<HttpChannel>,
) -> Result<Vec<StatefulDevice>, ClientError> {
let client = self.state.unpinned_client()?;
let state = &self.state;
let client = &client;
let found = futures_util::stream::iter(channels)
.map(|channel| async move {
state
.probe(client, &channel.host, channel.port, channel.protocol)
.await
.ok()
.flatten()
})
.buffer_unordered(SCAN_CONCURRENCY)
.filter_map(std::future::ready)
.collect()
.await;
Ok(found)
}
/// Discovers devices in stages, cheapest first: announces this device to
/// the network and probes `known_channels` (e.g. the favorites), then
/// falls back to scanning the `/24` subnets of the local interface
/// addresses `interface_ips`, for networks that do not carry multicast.
///
/// The fallback only runs when nothing was confirmed until `grace` after
/// the known channels have been probed: any confirmation — a new device
/// or a known one — proves that the cheap stages work on this network.
///
/// The found devices are put into the store (and emitted) as they answer;
/// returns once every stage has finished, including the whole
/// announcement burst.
pub async fn discover_staged(
&self,
known_channels: Vec<HttpChannel>,
interface_ips: Vec<Ipv4Addr>,
port: u16,
protocol: ProtocolType,
grace: Duration,
) -> Result<(), ClientError> {
let confirmations = self.state.confirmations.load(Ordering::Relaxed);
let escalate = async {
self.discover_known_http_channels(known_channels).await?;
tokio::time::sleep(grace).await;
if self.state.confirmations.load(Ordering::Relaxed) == confirmations {
futures_util::future::try_join_all(
interface_ips
.into_iter()
.map(|ip| self.scan_subnet(ip, port, protocol)),
)
.await?;
}
Ok(())
};
let (_, escalated) = tokio::join!(self.announce(), escalate);
escalated
}
/// Scans the `/24` subnet of the local interface address `interface_ip`
/// by sending every other host a register request,
/// for networks that do not carry multicast.
///
/// At most one scan runs per interface: a call for an address that is
/// still being scanned returns an empty list immediately.
pub async fn scan_subnet(
&self,
interface_ip: Ipv4Addr,
port: u16,
protocol: ProtocolType,
) -> Result<Vec<StatefulDevice>, ClientError> {
if !self.state.scanning.lock().unwrap().insert(interface_ip) {
return Ok(Vec::new());
}
let _guard = ScanGuard {
state: &self.state,
interface_ip,
};
let client = self.state.unpinned_client()?;
let base = interface_ip.octets();
let state = &self.state;
let client = &client;
let found = futures_util::stream::iter(
(0..=255u8)
.map(|host| Ipv4Addr::new(base[0], base[1], base[2], host))
.filter(|ip| *ip != interface_ip),
)
.map(|ip| async move {
state
.probe(client, &ip.to_string(), port, protocol)
.await
.ok()
.flatten()
})
.buffer_unordered(SCAN_CONCURRENCY)
.filter_map(std::future::ready)
.collect()
.await;
Ok(found)
}
/// Sets whether announcements of other devices are answered with a
/// register request (the answer is what makes the announcing device
/// enter the store). On by default.
///
/// An application whose server is not running turns this off: the answer
/// would advertise an HTTP port that nobody listens on.
pub fn set_answer_announcements(&self, answer: bool) {
self.state.answering.store(answer, Ordering::Relaxed);
}
/// Puts a device that reached this device's HTTP server into the store,
/// e.g. one that answered an announcement by registering. The
/// confirmation is emitted as `Discovered` or `Updated`; returns `true`
/// when the device is new.
///
/// `device.channel` is the address the request came from, with the port
/// the device claims to serve on. Only the inbound direction of that
/// channel is confirmed: a device new to the address is stored with
/// [`Outbound::Untested`], because its request says nothing about
/// whether it can be dialed back.
///
/// An untested channel is therefore dialed back in the background, with
/// a register request: the outcome makes it [`Outbound::Reachable`] or
/// [`Outbound::Failed`] and is emitted as `Updated`.
/// A channel that was dialed before is not dialed again, so two devices
/// running this do not keep answering each other.
pub async fn observe_inbound(&self, device: DiscoveredDevice) -> bool {
let (is_new, merged) = self
.state
.observed(device.clone(), Observation::ReachedUs, None);
let untested = merged
.channels
.get(&device.channel)
.is_some_and(|channel| channel.outbound == Outbound::Untested);
if untested {
dial_back(self.state.clone(), device);
}
is_new
}
/// Records the outcome of a request the application sent to a stored
/// device over `channel`, e.g. a transfer: `Ok` makes the channel
/// [`Outbound::Reachable`], `Err` — carrying the reason, for display —
/// makes it [`Outbound::Failed`], which ranks it behind the device's
/// other channels. Emitted as `Updated` for a confirmed device.
///
/// Only report failures to reach the device at all
/// ([`ClientError::is_unreachable`]), not requests that the device
/// answered with an error.
///
/// A request over HTTPS must have been pinned to `fingerprint`: its
/// success verifies the device ([`StatefulDevice::verified`]).
///
/// Returns `false` when no device has the fingerprint.
pub fn report_outbound(
&self,
fingerprint: &str,
channel: DeviceChannel,
result: Result<(), String>,
) -> bool {
let event =
self.state
.store
.report_outbound(fingerprint, channel, result, SystemTime::now());
match event {
Some(event) => {
if let Some(event) = event {
self.state.emit(event);
}
true
}
None => false,
}
}
/// All confirmed devices in the order they were first observed.
pub fn devices(&self) -> Vec<StatefulDevice> {
self.state.store.devices()
}
/// The devices that were heard announcing themselves but did not answer
/// the register request, in the order they were first heard.
///
/// Nothing about them is verified (announcements are unauthenticated),
/// so they are for diagnostics only — e.g. to tell the user that a
/// device is around but blocked by a firewall — and not transfer
/// targets. A device leaves this list with its first confirmation.
pub fn unconfirmed_devices(&self) -> Vec<StatefulDevice> {
self.state.store.unconfirmed_devices()
}
/// The confirmed device with the given fingerprint.
pub fn device_by_fingerprint(&self, fingerprint: &str) -> Option<StatefulDevice> {
self.state.store.by_fingerprint(fingerprint)
}
/// Waits until discovery has terminated and the multicast sockets have
/// been closed, so that the port can be bound again.
/// Must be called after requesting a stop via the stop channel.
/// Returns immediately when multicast is unavailable.
pub async fn wait_stopped(&self) {
if let Ok(multicast) = &self.multicast {
multicast.wait_stopped().await;
}
}
}
/// Releases the interface of a finished subnet scan, also when the scan is
/// cancelled by dropping its future.
struct ScanGuard<'a> {
state: &'a DiscoveryState,
interface_ip: Ipv4Addr,
}
impl Drop for ScanGuard<'_> {
fn drop(&mut self) {
self.state
.scanning
.lock()
.unwrap()
.remove(&self.interface_ip);
}
}
/// Binds the multicast sockets and starts answering announcements of other
/// devices. Nothing is announced until [`DiscoveryHandle::announce`] is called.
///
/// Starting cannot fail: when no multicast socket could be bound, e.g. because
/// the port is already bound by another process or because there is no network
/// at all, discovery runs without multicast.
pub async fn start(config: DiscoveryConfig, stop_rx: oneshot::Receiver<()>) -> DiscoveryHandle {
let (multicast_tx, mut multicast_rx) = mpsc::channel(MULTICAST_CHANNEL_SIZE);
// On failure `multicast_tx` is dropped, which ends the answering task.
let multicast = multicast::start(
MulticastConfig {
group: config.group,
group_v6: config.group_v6,
port: config.port,
interface_filter: config.interface_filter,
device: config.device.clone(),
event_tx: multicast_tx,
},
stop_rx,
)
.await;
let state = Arc::new(DiscoveryState {
device: config.device,
identity: config.identity,
timeout: config.timeout,
store: DeviceStore::new(),
event_tx: config.event_tx,
answering: AtomicBool::new(true),
scanning: std::sync::Mutex::new(HashSet::new()),
dialing_back: std::sync::Mutex::new(HashSet::new()),
confirmations: AtomicU64::new(0),
});
// Ends once discovery is stopped: the multicast side then drops its
// sender and the channel closes.
tokio::spawn({
let state = state.clone();
async move {
while let Some(event) = multicast_rx.recv().await {
match event {
MulticastEvent::Discovered {
ip,
scope_id,
message,
} => {
if !state.answering.load(Ordering::Relaxed) {
continue;
}
// The register request may take a while (up to the timeout),
// so announcements are answered concurrently.
tokio::spawn(answer_announcement(state.clone(), ip, scope_id, message));
}
MulticastEvent::SocketsFailed => {
if let Some(event_tx) = &state.event_tx {
let _ = event_tx.try_send(DiscoveryEvent::MulticastFailed);
}
}
}
}
}
});
DiscoveryHandle { multicast, state }
}
/// Answers an announcement with a register request, as the protocol requires.
/// The device is confirmed only once that request succeeded; a device that
/// cannot be reached is stored unconfirmed, with the channel marked as failed.
async fn answer_announcement(
state: Arc<DiscoveryState>,
ip: IpAddr,
scope_id: Option<u32>,
message: MulticastMessageV2,
) {
let announcement = Announcement {
ip: PeerIp { ip, scope_id },
timestamp: SystemTime::now(),
};
let host = announcement.ip.to_string();
// Nothing but the announcement is known about the device so far.
let device = DiscoveredDevice {
alias: message.alias,
version: message.version,
device_model: message.device_model,
device_type: message.device_type,
fingerprint: message.fingerprint,
channel: DeviceChannel::Http(HttpChannel {
host,
port: message.port,
protocol: message.protocol,
}),
download: message.download,
};
dial(&state, device, Some(announcement)).await;
}
/// Dials a device that reached this device's server back on the channel its
/// request came from, to learn whether that channel also works in the
/// outbound direction. Runs in the background.
///
/// At most one dial-back runs per device and channel: a peer typically sends
/// several requests in a row, e.g. one for every message of an announcement
/// burst.
fn dial_back(state: Arc<DiscoveryState>, device: DiscoveredDevice) {
let key = (device.fingerprint.clone(), device.channel.clone());
if !state.dialing_back.lock().unwrap().insert(key.clone()) {
return;
}
tokio::spawn(async move {
dial(&state, device, None).await;
state.dialing_back.lock().unwrap().remove(&key);
});
}
/// Sends a register request to a device whose identity is already claimed —
/// by its announcement, heard as `announcement`, or by a request it sent to
/// this device's server — over `device.channel`, and puts the outcome into
/// the store: the channel is reachable when the device answered, failed when
/// it could not be reached.
async fn dial(
state: &DiscoveryState,
device: DiscoveredDevice,
announcement: Option<Announcement>,
) {
let Some(HttpChannel {
host,
port,
protocol,
}) = device.http().cloned()
else {
return;
};
// Pin the claimed fingerprint, so nothing is sent to a device that does
// not hold the matching certificate.
let expected_fingerprint = match protocol {
ProtocolType::Https => Some(device.fingerprint.clone()),
ProtocolType::Http => None,
};
let client = match LsHttpClientV2::try_new(
&state.identity.private_key_pem,
&state.identity.cert_pem,
expected_fingerprint,
Some(state.timeout),
) {
Ok(client) => client,
Err(err) => {
tracing::error!(
"Could not create the client to register with {host}: {}",
ErrorChain(&err)
);
return;
}
};
let result = client
.register(protocol, &host, port, state.register_dto())
.await;
match result {
Ok(response) => {
// The pinned certificate identifies the peer, so the fingerprint
// is the claimed one, not the one from the response body.
let device = confirmed_device(response.body, host, port, protocol, device.fingerprint);
state.observed(device, Observation::Reached, announcement);
}
Err(err) => {
let error = ErrorChain(&err).to_string();
let url = format!("{}://{host}:{port}", protocol.as_str());
tracing::debug!(
"Could not register with device {} ({url}): {error}",
device.alias,
);
if !err.is_unreachable() {
// The device answered, just not with its registration.
// A device dialed back already confirmed itself with its
// request, so the answer shows the channel works outbound.
// An announcing device stays unconfirmed: nothing it
// claimed is verified.
if announcement.is_none() {
state.observed(device, Observation::Reached, None);
}
return;
}
// The device is around but cannot be dialed, typically because
// a firewall blocks its server.
state.observed(device, Observation::Failed(error), announcement);
}
}
}
/// Builds the stored device from the register response of a peer confirmed
/// over HTTP.
fn confirmed_device(
response: RegisterResponseDtoV2,
host: String,
port: u16,
protocol: ProtocolType,
fingerprint: String,
) -> DiscoveredDevice {
DiscoveredDevice {
alias: response.alias,
version: response.version,
device_model: response.device_model,
device_type: response.device_type,
fingerprint,
channel: DeviceChannel::Http(HttpChannel {
host,
port,
protocol,
}),
download: response.download,
}
}