Skip to content

An open-source cross-platform alternative to AirDrop

feat: CLI should also save the list of http channels so that it can trigger discover_staged

Tien Do Nam0bcece572d24
diff --git a/cli/src/app/devices.rs b/cli/src/app/devices.rs
index 6aa02890..4d97ae30 100644
--- a/cli/src/app/devices.rs
+++ b/cli/src/app/devices.rs
@@ -3,6 +3,7 @@
use super::App;
use crate::device_list::{DeviceList, DeviceListOutcome, DeviceRow, Row};
+use crate::storage::PairedChannel;
use crate::ui::Category;
use crossterm::event::KeyEvent;
use localsend::discovery::StatefulDevice;
@@ -113,12 +114,12 @@ impl App {
let Some(stored) = self.discovery.device_by_fingerprint(fingerprint) else {
return;
};
- let alias = stored.device.alias;
- match self
- .storage
- .paired
- .insert(fingerprint.to_string(), alias.clone())
- {
+ let alias = stored.device.alias.clone();
+ match self.storage.paired.insert(
+ fingerprint.to_string(),
+ alias.clone(),
+ PairedChannel::channels_of(&stored),
+ ) {
Ok(()) => self.ui.log(
Category::Discovery,
&format!("{alias}: Paired. Future requests are auto-accepted."),
diff --git a/cli/src/app/discovery.rs b/cli/src/app/discovery.rs
index 5bf389e9..a0fe4ee8 100644
--- a/cli/src/app/discovery.rs
+++ b/cli/src/app/discovery.rs
@@ -4,12 +4,16 @@
use super::App;
use crate::slots::slot_label;
+use crate::storage::PairedChannel;
use crate::ui::Category;
use localsend::discovery::{DeviceChannel, DiscoveredDevice, DiscoveryEvent, HttpChannel};
use localsend::http::dto_v2::RegisterDtoV2;
impl App {
pub(super) fn handle_discovery(&mut self, event: DiscoveryEvent) {
+ let (DiscoveryEvent::Discovered { device } | DiscoveryEvent::Updated { device }) = &event;
+ self.refresh_paired_channels(&device.fingerprint);
+
let DiscoveryEvent::Discovered { device } = event else {
// Re-confirmations update the store silently; multi-homed peers
// re-announce with a different address all the time.
@@ -26,6 +30,28 @@ impl App {
);
}
+ /// Keeps a paired device's stored alias and channels in sync with the
+ /// discovery store, so the next run probes the addresses that worked last.
+ fn refresh_paired_channels(&mut self, fingerprint: &str) {
+ if !self.storage.paired.contains(fingerprint) {
+ return;
+ }
+ let Some(stored) = self.discovery.device_by_fingerprint(fingerprint) else {
+ return;
+ };
+ let result = self.storage.paired.update(
+ fingerprint,
+ &stored.device.alias,
+ PairedChannel::channels_of(&stored),
+ );
+ if let Err(err) = result {
+ self.ui.log(
+ Category::Discovery,
+ &format!("Could not save the paired devices: {err:#}"),
+ );
+ }
+ }
+
/// Feeds a device confirmed outside of discovery — it registered with our
/// HTTP server, or it sent a transfer request — into the discovery store;
/// a device new to the store comes back as a `Discovered` event.
diff --git a/cli/src/app/mod.rs b/cli/src/app/mod.rs
index 8b23dcd8..81c237be 100644
--- a/cli/src/app/mod.rs
+++ b/cli/src/app/mod.rs
@@ -16,9 +16,9 @@ use localsend::discovery::{
};
use localsend::http::server::v2::ServerEventV2;
use localsend::http::server::{ServerConfigV2, ServerHandle, start_with_port};
-use localsend::multicast::{
- DEFAULT_MULTICAST_GROUP, DEFAULT_MULTICAST_GROUP_V6, DEFAULT_PORT, InterfaceFilter,
-};
+use localsend::model::discovery::ProtocolType;
+use localsend::multicast::{DEFAULT_MULTICAST_GROUP, DEFAULT_MULTICAST_GROUP_V6, DEFAULT_PORT};
+use localsend::util::interface::{InterfaceFilter, local_interface_addresses};
use receive::{Answer, PendingReceive, ReceiveSession};
use sending::SendState;
use std::path::PathBuf;
@@ -132,9 +132,34 @@ pub async fn run(args: Args) -> anyhow::Result<()> {
eprintln!("Multicast unavailable: {err:#}");
}
{
- // Announce this device; peers answer with an HTTP register request.
+ // Discover in stages: announce this device (peers answer with an HTTP
+ // register request), probe the paired devices' stored addresses, and
+ // fall back to scanning the local subnets when nothing was confirmed.
let discovery = discovery.clone();
- tokio::spawn(async move { discovery.announce().await });
+ let events_tx = events_tx.clone();
+ let port = identity.port;
+ let known_channels = storage.paired.known_http_channels();
+ let interface_ips =
+ local_interface_addresses(&InterfaceFilter::default()).unwrap_or_default();
+ tokio::spawn(async move {
+ let result = discovery
+ .discover_staged(
+ known_channels,
+ interface_ips,
+ port,
+ ProtocolType::Https,
+ Duration::from_secs(1),
+ )
+ .await;
+ if let Err(err) = result {
+ let _ = events_tx
+ .send(AppEvent::Log {
+ category: Category::Discovery,
+ text: format!("Discovery failed: {err}"),
+ })
+ .await;
+ }
+ });
}
crossterm::terminal::enable_raw_mode()?;
diff --git a/cli/src/app/receive.rs b/cli/src/app/receive.rs
index 41cec168..cdd565d9 100644
--- a/cli/src/app/receive.rs
+++ b/cli/src/app/receive.rs
@@ -423,11 +423,16 @@ impl App {
self.ui
.log(Category::Receive, &format!("{}: You accepted", pending.alias));
if matches!(answer, Answer::AcceptAndPair) {
- match self
- .storage
- .paired
- .insert(pending.sender.fingerprint.clone(), pending.alias.clone())
- {
+ let channels = self
+ .discovery
+ .device_by_fingerprint(&pending.sender.fingerprint)
+ .map(|stored| crate::storage::PairedChannel::channels_of(&stored))
+ .unwrap_or_default();
+ match self.storage.paired.insert(
+ pending.sender.fingerprint.clone(),
+ pending.alias.clone(),
+ channels,
+ ) {
Ok(()) => self.ui.log(
Category::Receive,
&format!(
diff --git a/cli/src/storage/mod.rs b/cli/src/storage/mod.rs
index 16e0fd5f..b03e8a9c 100644
--- a/cli/src/storage/mod.rs
+++ b/cli/src/storage/mod.rs
@@ -13,7 +13,7 @@ mod identity;
mod paired;
pub use identity::Identity;
-pub use paired::PairedDevices;
+pub use paired::{PairedChannel, PairedDevices};
use crate::Args;
use anyhow::Context;
diff --git a/cli/src/storage/paired.rs b/cli/src/storage/paired.rs
index 29093e6d..aec92962 100644
--- a/cli/src/storage/paired.rs
+++ b/cli/src/storage/paired.rs
@@ -1,4 +1,6 @@
use anyhow::Context;
+use localsend::discovery::{HttpChannel, StatefulDevice};
+use localsend::model::discovery::ProtocolType;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::io::ErrorKind;
@@ -18,6 +20,49 @@ const PAIRED_DEVICES_VERSION: u32 = 1;
#[derive(Serialize, Deserialize)]
pub struct PairedDevice {
pub alias: String,
+
+ /// The HTTP addresses the device was reachable at, best first; probed
+ /// as known channels by the startup discovery.
+ pub channels: Vec<PairedChannel>,
+}
+
+/// An [`HttpChannel`] in on-disk form.
+#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
+pub struct PairedChannel {
+ pub host: String,
+ pub port: u16,
+ pub protocol: ProtocolType,
+}
+
+impl PairedChannel {
+ /// The device's HTTP channels in on-disk form, best first.
+ pub fn channels_of(stored: &StatefulDevice) -> Vec<PairedChannel> {
+ stored
+ .get_ranked_channels()
+ .into_iter()
+ .filter_map(|channel| channel.http())
+ .map(PairedChannel::from)
+ .collect()
+ }
+
+ /// The channel as discovery dials it.
+ pub fn http_channel(&self) -> HttpChannel {
+ HttpChannel {
+ host: self.host.clone(),
+ port: self.port,
+ protocol: self.protocol,
+ }
+ }
+}
+
+impl From<&HttpChannel> for PairedChannel {
+ fn from(channel: &HttpChannel) -> Self {
+ Self {
+ host: channel.host.clone(),
+ port: channel.port,
+ protocol: channel.protocol,
+ }
+ }
}
/// The on-disk format of `paired-v2.json`,
@@ -77,10 +122,34 @@ impl PairedDevices {
/// Adds a device and saves the file. The device stays paired for this
/// run even when saving fails.
- pub fn insert(&mut self, fingerprint: String, alias: String) -> anyhow::Result<()> {
+ pub fn insert(
+ &mut self,
+ fingerprint: String,
+ alias: String,
+ channels: Vec<PairedChannel>,
+ ) -> anyhow::Result<()> {
self.file
.devices
- .insert(fingerprint, PairedDevice { alias });
+ .insert(fingerprint, PairedDevice { alias, channels });
+ self.save()
+ }
+
+ /// Refreshes a paired device's alias and channels after a confirmation,
+ /// saving only when something changed. Unpaired fingerprints are ignored.
+ pub fn update(
+ &mut self,
+ fingerprint: &str,
+ alias: &str,
+ channels: Vec<PairedChannel>,
+ ) -> anyhow::Result<()> {
+ let Some(device) = self.file.devices.get_mut(fingerprint) else {
+ return Ok(());
+ };
+ if device.alias == alias && device.channels == channels {
+ return Ok(());
+ }
+ device.alias = alias.to_string();
+ device.channels = channels;
self.save()
}
@@ -98,6 +167,16 @@ impl PairedDevices {
self.file.devices.iter()
}
+ /// The stored channels of every paired device, for the known-address
+ /// stage of the startup discovery.
+ pub fn known_http_channels(&self) -> Vec<HttpChannel> {
+ self.file
+ .devices
+ .values()
+ .flat_map(|device| device.channels.iter().map(PairedChannel::http_channel))
+ .collect()
+ }
+
fn save(&self) -> anyhow::Result<()> {
// Write-then-rename so a crash cannot leave a truncated file.
let temp = self.path.with_extension("json.tmp");
@@ -107,3 +186,51 @@ impl PairedDevices {
.with_context(|| format!("Could not write {}", self.path.display()))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A fresh directory per test (`name` disambiguates tests, the process
+ /// id parallel `cargo test` processes).
+ fn temp_dir(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "localsend-cli-paired-{name}-{}",
+ std::process::id()
+ ));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ fn channel(host: &str) -> PairedChannel {
+ PairedChannel {
+ host: host.to_string(),
+ port: 53317,
+ protocol: ProtocolType::Https,
+ }
+ }
+
+ #[test]
+ fn test_channels_round_trip() {
+ let dir = temp_dir("round-trip");
+
+ let mut paired = PairedDevices::load(&dir).unwrap();
+ paired
+ .insert(
+ "FP".to_string(),
+ "Alias".to_string(),
+ vec![channel("fe80::1%3"), channel("192.168.0.10")],
+ )
+ .unwrap();
+
+ let paired = PairedDevices::load(&dir).unwrap();
+ let hosts: Vec<String> = paired
+ .known_http_channels()
+ .into_iter()
+ .map(|channel| channel.host)
+ .collect();
+ assert_eq!(hosts, ["fe80::1%3", "192.168.0.10"]);
+ }
+
+}
diff --git a/packages/core/src/discovery/mod.rs b/packages/core/src/discovery/mod.rs
index 20cb3900..b629058d 100644
--- a/packages/core/src/discovery/mod.rs
+++ b/packages/core/src/discovery/mod.rs
@@ -8,10 +8,9 @@ pub use store::{
use crate::http::client::{ClientError, LsHttpClientV2};
use crate::http::dto_v2::{RegisterDtoV2, RegisterResponseDtoV2};
use crate::model::discovery::{MulticastMessageV2, ProtocolType};
-use crate::multicast::{
- self, InterfaceFilter, MulticastConfig, MulticastDevice, MulticastEvent, MulticastHandle,
-};
+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};
diff --git a/packages/core/src/multicast/mod.rs b/packages/core/src/multicast/mod.rs
index 760c3e1f..0401d964 100644
--- a/packages/core/src/multicast/mod.rs
+++ b/packages/core/src/multicast/mod.rs
@@ -8,12 +8,10 @@
//! [`start`] binds the sockets and emits a [`MulticastEvent`] per announcement;
//! the returned [`MulticastHandle`] drives the application-initiated side.
-mod interface;
mod socket;
-pub use interface::InterfaceFilter;
-
use crate::model::discovery::{DeviceType, MulticastMessageV2, ProtocolType};
+use crate::util::interface::InterfaceFilter;
use serde::Serialize;
use socket::MulticastSocket;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
diff --git a/packages/core/src/multicast/socket.rs b/packages/core/src/multicast/socket.rs
index c1255af3..8eaac75b 100644
--- a/packages/core/src/multicast/socket.rs
+++ b/packages/core/src/multicast/socket.rs
@@ -1,6 +1,6 @@
//! Binding of the UDP sockets that carry the multicast discovery traffic.
-use crate::multicast::interface::{local_interfaces, InterfaceFilter};
+use crate::util::interface::{local_interfaces, InterfaceFilter};
use socket2::{Domain, Protocol, Socket, Type};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::sync::Arc;
diff --git a/packages/core/src/multicast/interface.rs b/packages/core/src/util/interface.rs
similarity index 94%
rename from packages/core/src/multicast/interface.rs
rename to packages/core/src/util/interface.rs
index 33263bfa..3093d607 100644
--- a/packages/core/src/multicast/interface.rs
+++ b/packages/core/src/util/interface.rs
@@ -1,8 +1,8 @@
-//! Enumeration and filtering of the local network interfaces used for multicast.
+//! Enumeration and filtering of the local network interfaces.
use std::net::{IpAddr, Ipv4Addr};
-/// Restricts the network interfaces that multicast sockets are bound to.
+/// Restricts the network interfaces that are used.
///
/// Filters are matched against every address of an interface. A `*` matches one
/// or more characters that are not a `.`, so `192.168.1.*` matches
@@ -173,6 +173,16 @@ pub(crate) fn local_interfaces(filter: &InterfaceFilter) -> std::io::Result<Loca
Ok(result)
}
+/// The IPv4 addresses of all usable (non-loopback, unfiltered) local
+/// interfaces, e.g. the subnets to fall back-scan when multicast is silent.
+pub fn local_interface_addresses(filter: &InterfaceFilter) -> std::io::Result<Vec<Ipv4Addr>> {
+ Ok(local_interfaces(filter)?
+ .v4
+ .into_iter()
+ .map(|interface| interface.address)
+ .collect())
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/packages/core/src/util/mod.rs b/packages/core/src/util/mod.rs
index 0db99ebf..c0d982c8 100644
--- a/packages/core/src/util/mod.rs
+++ b/packages/core/src/util/mod.rs
@@ -1,4 +1,6 @@
pub mod base64;
pub mod error;
pub mod filename;
+#[cfg(feature = "if-addrs")]
+pub mod interface;
pub(crate) mod time;
diff --git a/packages/core/tests/discovery.rs b/packages/core/tests/discovery.rs
index f3da4bc1..dcc4b9c4 100644
--- a/packages/core/tests/discovery.rs
+++ b/packages/core/tests/discovery.rs
@@ -15,7 +15,8 @@ use localsend::discovery::{
use localsend::http::server::{start_with_port, ServerConfigV2, TlsConfig};
use localsend::http::state::ClientInfo;
use localsend::model::discovery::{DeviceType, ProtocolType, PROTOCOL_VERSION_V2};
-use localsend::multicast::{InterfaceFilter, MulticastDevice};
+use localsend::multicast::MulticastDevice;
+use localsend::util::interface::InterfaceFilter;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::sync::atomic::{AtomicU16, Ordering};
use std::time::Duration;
diff --git a/packages/localsend_isolates/rust/src/api/discovery.rs b/packages/localsend_isolates/rust/src/api/discovery.rs
index e1380f21..310f1ab2 100644
--- a/packages/localsend_isolates/rust/src/api/discovery.rs
+++ b/packages/localsend_isolates/rust/src/api/discovery.rs
@@ -6,7 +6,8 @@ use localsend::discovery::{
DiscoveryHandle, HttpChannel, StatefulDevice,
};
use localsend::model::discovery::{DeviceType, ProtocolType};
-use localsend::multicast::{DEFAULT_MULTICAST_GROUP_V6, InterfaceFilter, MulticastDevice};
+use localsend::multicast::{DEFAULT_MULTICAST_GROUP_V6, MulticastDevice};
+use localsend::util::interface::InterfaceFilter;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{Mutex, mpsc, oneshot};