An open-source cross-platform alternative to AirDrop
fix: auto restart dead http/multicast server
Tien Do Nam89303dcf6044
diff --git a/app/lib/provider/network/server/server_provider.dart b/app/lib/provider/network/server/server_provider.dartindex 80b6fb78..4d0b936d 100644--- a/app/lib/provider/network/server/server_provider.dart+++ b/app/lib/provider/network/server/server_provider.dart@@ -355,6 +355,33 @@ class ServerService extends Notifier<ServerState?> {case HttpServerWebFileDownloadEvent():// ignore: discarded_futures_sendController.onFileDownload(event);+ case HttpServerListenerFailedEvent():+ // ignore: discarded_futures+ _restartAfterListenerFailure(event.error);+ }+ }++ /// Restarts the server after its listening socket failed permanently,+ /// e.g. because iOS reclaimed it while the app was suspended.+ /// The Rust server has already stopped itself at this point.+ Future<void> _restartAfterListenerFailure(String error) async {+ _logger.warning('The server listener failed: $error. Restarting server.');+ final current = state;+ if (current == null) {+ return;+ }++ try {+ await restartServer(+ alias: current.alias,+ port: current.port,+ https: current.https,+ webSendState: current.webSendState?.copyWith(sessions: {}),+ webUpload: current.webUpload,+ webPin: current.webPin,+ );+ } catch (e) {+ _logger.severe('Failed to restart the server after its listener failed', e);}}diff --git a/cli/src/app/discovery.rs b/cli/src/app/discovery.rsindex 4e6f2734..7d9e80f4 100644--- a/cli/src/app/discovery.rs+++ b/cli/src/app/discovery.rs@@ -12,7 +12,16 @@ 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;+ let device = match &event {+ DiscoveryEvent::Discovered { device } | DiscoveryEvent::Updated { device } => device,+ DiscoveryEvent::MulticastFailed => {+ self.ui.log(+ Category::Discovery,+ "Multicast stopped, no longer hearing announcements",+ );+ return;+ }+ };self.refresh_paired_channels(&device.fingerprint);let DiscoveryEvent::Discovered { device } = event else {diff --git a/cli/src/app/receive.rs b/cli/src/app/receive.rsindex 2f6bc8f2..07ce94ef 100644--- a/cli/src/app/receive.rs+++ b/cli/src/app/receive.rs@@ -235,6 +235,12 @@ impl App {send.cancel.token.cancel();}}+ ServerEventV2::ListenerFailed { error } => {+ self.ui.log(+ Category::Receive,+ &format!("Server stopped, no longer receiving: {error}"),+ );+ }}}diff --git a/packages/core/Cargo.toml b/packages/core/Cargo.tomlindex 8e99dfae..c02f2305 100644--- a/packages/core/Cargo.toml+++ b/packages/core/Cargo.toml@@ -41,10 +41,10 @@ uuid = { version = "1.24.0", features = ["serde", "v4"] }webrtc = { version = "0.14.0", optional = true }x509-parser = { version = "0.18.1", features = ["verify"], optional = true }-[dev-dependencies]-# Lowers this process' descriptor limit in `accept_resilience`, to reproduce-# the exhaustion the accept loop has to survive. Already in the tree as a-# transitive dependency, so it costs no extra compilation.+[target.'cfg(unix)'.dependencies]+# Errno constants for classifying accept errors. Already in the tree as a+# transitive dependency, so it costs no extra compilation. Also used by the+# `accept_resilience` test to lower this process' descriptor limit.libc = "0.2"[[example]]diff --git a/packages/core/src/discovery/mod.rs b/packages/core/src/discovery/mod.rsindex b629058d..93b669fd 100644--- a/packages/core/src/discovery/mod.rs+++ b/packages/core/src/discovery/mod.rs@@ -77,7 +77,7 @@ pub struct DiscoveryConfig {pub event_tx: Option<mpsc::Sender<DiscoveryEvent>>,}-/// An event emitted by the discovery. Every event is also logged in+/// An event emitted by the discovery. Every confirmation is also logged in/// [`StatefulDevice::logs`]; the accumulated state is read from/// [`DiscoveryHandle::devices`].#[derive(Clone, Debug)]@@ -97,6 +97,13 @@ pub enum DiscoveryEvent {/// [`DiscoveryEvent::Discovered`].device: DiscoveredDevice,},++ /// 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 {@@ -466,18 +473,26 @@ pub async fn start(config: DiscoveryConfig, stop_rx: oneshot::Receiver<()>) -> Dlet state = state.clone();async move {while let Some(event) = multicast_rx.recv().await {- if !state.answering.load(Ordering::Relaxed) {- continue;+ 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);+ }+ }}- let MulticastEvent::Discovered {- ip,- scope_id,- message,- } = event;-- // 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));}}});diff --git a/packages/core/src/http/server/mod.rs b/packages/core/src/http/server/mod.rsindex f61e1d67..429c8ef0 100644--- a/packages/core/src/http/server/mod.rs+++ b/packages/core/src/http/server/mod.rs@@ -261,14 +261,29 @@ pub async fn start_with_port(let state = state.clone();let cancel = cancel.clone();let connections = connections.clone();+ let v2_event_tx = state.v2.as_ref().map(|v2| v2.event_tx.clone());async move {tokio::select! {- _ = start_server_with_listener(ipv4_listener, tls_config.clone(), state.clone(), cancel.clone(), connections.clone()) => {+ result = start_server_with_listener(ipv4_listener, tls_config.clone(), state.clone(), cancel.clone(), connections.clone()) => {+ if let Err(err) = result {+ tracing::error!("Server listener failed on {}: {err:#}", ipv4_socket_addr);+ // Tell the application, so it can restart the server.+ // `try_send` because this task must reach its end even+ // when nobody consumes events anymore, so that+ // `wait_stopped` cannot hang.+ if let Some(event_tx) = v2_event_tx {+ let _ = event_tx.try_send(ServerEventV2::ListenerFailed {+ error: format!("{err:#}"),+ });+ }+ }tracing::info!("Server stopped on: {}", ipv4_socket_addr);}_ = async {if let Some(listener) = ipv6_listener {- let _ = start_server_with_listener(listener, tls_config, state, cancel.clone(), connections.clone()).await;+ if let Err(err) = start_server_with_listener(listener, tls_config, state, cancel.clone(), connections.clone()).await {+ tracing::error!("IPv6 server listener failed on {}: {err:#}", ipv6_socket_addr);+ }}// Keep the future running forever, so we continue using "ipv4 only" even if ipv6 fails.@@ -323,6 +338,13 @@ pub struct TlsConfig {const ACCEPT_BACKOFF_MIN: std::time::Duration = std::time::Duration::from_millis(50);const ACCEPT_BACKOFF_MAX: std::time::Duration = std::time::Duration::from_secs(1);+/// How many times in a row accepting may fail with a per-connection error+/// before the listener itself is considered broken. A healthy listener+/// interleaves such errors with successful accepts; only a dead one (e.g. a+/// socket the OS invalidated during app suspension, whose exact error code is+/// OS-specific) produces them in an endless, immediate sequence.+const ACCEPT_FAILURE_LIMIT: u32 = 100;+/// Whether the failed accept concerned only the connection being accepted, so/// the next one can be attempted right away.fn is_transient_accept_error(err: &std::io::Error) -> bool {@@ -334,6 +356,27 @@ fn is_transient_accept_error(err: &std::io::Error) -> bool {)}+/// Whether the failed accept means the process momentarily ran out of+/// resources (a subnet scan opens a few hundred sockets), which resolves once+/// they are freed again.+fn is_resource_accept_error(err: &std::io::Error) -> bool {+ if err.kind() == std::io::ErrorKind::OutOfMemory {+ return true;+ }+ #[cfg(unix)]+ return matches!(+ err.raw_os_error(),+ Some(libc::EMFILE | libc::ENFILE | libc::ENOBUFS | libc::ENOMEM)+ );+ #[cfg(windows)]+ return matches!(+ err.raw_os_error(),+ Some(10024 /* WSAEMFILE */ | 10055 /* WSAENOBUFS */)+ );+ #[allow(unreachable_code)]+ false+}+async fn start_server_with_listener(incoming: tokio::net::TcpListener,tls_config: Option<TlsConfig>,@@ -361,32 +404,46 @@ async fn start_server_with_listener();let mut accept_backoff = ACCEPT_BACKOFF_MIN;+ let mut accept_failures = 0u32;loop {let (tcp_stream, remote_addr) = match incoming.accept().await {Ok(accepted) => {accept_backoff = ACCEPT_BACKOFF_MIN;+ accept_failures = 0;// Disable Nagle: it delays small responses (reqwest already does this on the client side).let _ = accepted.0.set_nodelay(true);accepted}- // Accepting fails for reasons that say nothing about the listener:- // the peer went away before the handshake completed, or the process- // momentarily ran out of file descriptors (a subnet scan opens a- // few hundred sockets). Giving up here would stop the server for- // good and the application would never learn that it can no longer- // receive anything, so keep accepting.+ // Accepting fails for two kinds of reasons that say nothing about+ // the listener, which must both keep the loop alive: the peer went+ // away before the handshake completed (retried right away, but+ // bounded by [ACCEPT_FAILURE_LIMIT] because a listener the OS+ // invalidated during app suspension may report an OS-specific+ // error that looks per-connection), or the process momentarily ran+ // out of resources (a subnet scan opens a few hundred sockets).+ // Exhaustion would otherwise spin: the pending connection stays in+ // the backlog and fails again immediately, so back off before+ // retrying, without a limit — it says nothing about the listener,+ // however long it lasts.//- // Descriptor exhaustion would otherwise spin: the pending- // connection stays in the backlog and fails again immediately, so- // back off before retrying.+ // Every other error means the listening socket itself is broken.+ // Retrying that forever would leave the application believing it+ // can still receive, so give up and let the caller report it.Err(err) => {- tracing::warn!("Could not accept a connection: {err:#}");- if is_transient_accept_error(&err) {+ if is_resource_accept_error(&err) {+ tracing::warn!("Could not accept a connection: {err:#}");+ tokio::time::sleep(accept_backoff).await;+ accept_backoff = (accept_backoff * 2).min(ACCEPT_BACKOFF_MAX);+ continue;+ }+ accept_failures += 1;+ if is_transient_accept_error(&err) && accept_failures < ACCEPT_FAILURE_LIMIT {+ tracing::warn!("Could not accept a connection: {err:#}");continue;}- tokio::time::sleep(accept_backoff).await;- accept_backoff = (accept_backoff * 2).min(ACCEPT_BACKOFF_MAX);- continue;+ return Err(anyhow::Error::from(err).context(format!(+ "accepting connections failed {accept_failures} time(s) in a row"+ )));}};diff --git a/packages/core/src/http/server/v2.rs b/packages/core/src/http/server/v2.rsindex 68a7ecdd..da66ad95 100644--- a/packages/core/src/http/server/v2.rs+++ b/packages/core/src/http/server/v2.rs@@ -119,6 +119,15 @@ pub enum ServerEventV2 {/// The session ID as known by the remote device.session_id: String,},++ /// The listening socket failed permanently, e.g. because the OS+ /// invalidated it while the application was suspended (iOS reclaims the+ /// sockets of suspended apps). The server has stopped itself; the+ /// application must restart it to become reachable again.+ ListenerFailed {+ /// Description of the failure.+ error: String,+ },}/// The application's decision for a prepare-upload request.diff --git a/packages/core/src/multicast/mod.rs b/packages/core/src/multicast/mod.rsindex 0401d964..df06a32a 100644--- a/packages/core/src/multicast/mod.rs+++ b/packages/core/src/multicast/mod.rs@@ -148,6 +148,12 @@ pub enum MulticastEvent {/// The message as it was received.message: MulticastMessageV2,},++ /// Every receive socket failed permanently, e.g. because the OS+ /// invalidated them while the application was suspended (iOS reclaims the+ /// sockets of suspended apps). Multicast has stopped itself; the+ /// application must restart it to hear and send announcements again.+ SocketsFailed,}/// A socket announcements are sent on, together with its target address.@@ -292,7 +298,14 @@ pub async fn start(tokio::select! {// All receive loops gave up on their socket.- _ = async { while receivers.join_next().await.is_some() {} } => {}+ _ = async { while receivers.join_next().await.is_some() {} } => {+ tracing::error!("All multicast sockets failed, stopping multicast discovery");+ // Tell the application, so it can restart discovery.+ // `try_send` because this task must reach its end even+ // when nobody consumes events anymore, so that+ // `wait_stopped` cannot hang.+ let _ = config.event_tx.try_send(MulticastEvent::SocketsFailed);+ }_ = stop_rx => {}}diff --git a/packages/core/tests/multicast.rs b/packages/core/tests/multicast.rsindex fcb2358e..f5a7ba94 100644--- a/packages/core/tests/multicast.rs+++ b/packages/core/tests/multicast.rs@@ -48,7 +48,10 @@ impl TestInstance {ip,scope_id,message,- } = event;+ } = event+ else {+ continue;+ };if message.fingerprint == fingerprint {return Some(MulticastMessage {source: ip,diff --git a/packages/core/tests/v2_server.rs b/packages/core/tests/v2_server.rsindex 3e9f38d3..2ffe20ff 100644--- a/packages/core/tests/v2_server.rs+++ b/packages/core/tests/v2_server.rs@@ -116,6 +116,7 @@ async fn start_test_server_with_verification(}ServerEventV2::PrepareUploadAborted { .. } => {}ServerEventV2::CancelReceived { .. } => {}+ ServerEventV2::ListenerFailed { .. } => {}}}}diff --git a/packages/localsend_isolates/lib/isolate.dart b/packages/localsend_isolates/lib/isolate.dartindex f4ed994f..b0a435f9 100644--- a/packages/localsend_isolates/lib/isolate.dart+++ b/packages/localsend_isolates/lib/isolate.dart@@ -5,6 +5,7 @@ export 'package:localsend_isolates/src/isolate/child/server_isolate.dart'HttpServerFileUploadEvent,HttpServerFileUploadProgressEvent,HttpServerFileUploadResultEvent,+ HttpServerListenerFailedEvent,HttpServerPrepareUploadAbortedEvent,HttpServerPrepareUploadEvent,HttpServerReceiveConfig,diff --git a/packages/localsend_isolates/lib/rust/api/discovery.dart b/packages/localsend_isolates/lib/rust/api/discovery.dartindex d5a4537b..401d2087 100644--- a/packages/localsend_isolates/lib/rust/api/discovery.dart+++ b/packages/localsend_isolates/lib/rust/api/discovery.dart@@ -104,6 +104,11 @@ abstract class RsDiscovery implements RustOpaqueInterface {/// Emits a [RsStoredDevice] for every device confirmation until the/// discovery is stopped. Can only be listened to once.///+ /// Also ends when the multicast sockets failed permanently (e.g. because+ /// the OS invalidated them while the application was suspended): the+ /// application reacts to the ended stream by starting a new discovery,+ /// which rebinds the sockets.+ ////// Also returns when the Dart side of the stream is gone (e.g. after a/// hot restart), so this call does not keep the discovery alive forever.Stream<RsStoredDevice> listen();diff --git a/packages/localsend_isolates/lib/rust/api/server.dart b/packages/localsend_isolates/lib/rust/api/server.dartindex 388444bc..a9c2d729 100644--- a/packages/localsend_isolates/lib/rust/api/server.dart+++ b/packages/localsend_isolates/lib/rust/api/server.dart@@ -252,6 +252,15 @@ sealed class RsServerEvent with _$RsServerEvent {/// Command-line arguments forwarded by the other application instance.required List<String> args,}) = RsServerEvent_Show;++ /// The listening socket failed permanently, e.g. because the OS+ /// invalidated it while the application was suspended (iOS reclaims the+ /// sockets of suspended apps). The server has stopped itself; the+ /// application must restart it to become reachable again.+ const factory RsServerEvent.listenerFailed({+ /// Description of the failure.+ required String error,+ }) = RsServerEvent_ListenerFailed;}enum SessionEndReasonV2 {diff --git a/packages/localsend_isolates/lib/rust/api/server.freezed.dart b/packages/localsend_isolates/lib/rust/api/server.freezed.dartindex fd837e10..c9906d8d 100644--- a/packages/localsend_isolates/lib/rust/api/server.freezed.dart+++ b/packages/localsend_isolates/lib/rust/api/server.freezed.dart@@ -55,7 +55,7 @@ extension RsServerEventPatterns on RsServerEvent {/// }/// ```-@optionalTypeArgs TResult maybeMap<TResult extends Object?>({TResult Function( RsServerEvent_Register value)? register,TResult Function( RsServerEvent_PrepareUpload value)? prepareUpload,TResult Function( RsServerEvent_FileUpload value)? fileUpload,TResult Function( RsServerEvent_SessionEnd value)? sessionEnd,TResult Function( RsServerEvent_PrepareUploadAborted value)? prepareUploadAborted,TResult Function( RsServerEvent_CancelReceived value)? cancelReceived,TResult Function( RsServerEvent_WebPrepareDownload value)? webPrepareDownload,TResult Function( RsServerEvent_WebFileDownload value)? webFileDownload,TResult Function( RsServerEvent_Show value)? show_,required TResult orElse(),}){+@optionalTypeArgs TResult maybeMap<TResult extends Object?>({TResult Function( RsServerEvent_Register value)? register,TResult Function( RsServerEvent_PrepareUpload value)? prepareUpload,TResult Function( RsServerEvent_FileUpload value)? fileUpload,TResult Function( RsServerEvent_SessionEnd value)? sessionEnd,TResult Function( RsServerEvent_PrepareUploadAborted value)? prepareUploadAborted,TResult Function( RsServerEvent_CancelReceived value)? cancelReceived,TResult Function( RsServerEvent_WebPrepareDownload value)? webPrepareDownload,TResult Function( RsServerEvent_WebFileDownload value)? webFileDownload,TResult Function( RsServerEvent_Show value)? show_,TResult Function( RsServerEvent_ListenerFailed value)? listenerFailed,required TResult orElse(),}){final _that = this;switch (_that) {case RsServerEvent_Register() when register != null:@@ -67,7 +67,8 @@ return prepareUploadAborted(_that);case RsServerEvent_CancelReceived() when cancreturn cancelReceived(_that);case RsServerEvent_WebPrepareDownload() when webPrepareDownload != null:return webPrepareDownload(_that);case RsServerEvent_WebFileDownload() when webFileDownload != null:return webFileDownload(_that);case RsServerEvent_Show() when show_ != null:-return show_(_that);case _:+return show_(_that);case RsServerEvent_ListenerFailed() when listenerFailed != null:+return listenerFailed(_that);case _:return orElse();}@@ -85,7 +86,7 @@ return show_(_that);case _:/// }/// ```-@optionalTypeArgs TResult map<TResult extends Object?>({required TResult Function( RsServerEvent_Register value) register,required TResult Function( RsServerEvent_PrepareUpload value) prepareUpload,required TResult Function( RsServerEvent_FileUpload value) fileUpload,required TResult Function( RsServerEvent_SessionEnd value) sessionEnd,required TResult Function( RsServerEvent_PrepareUploadAborted value) prepareUploadAborted,required TResult Function( RsServerEvent_CancelReceived value) cancelReceived,required TResult Function( RsServerEvent_WebPrepareDownload value) webPrepareDownload,required TResult Function( RsServerEvent_WebFileDownload value) webFileDownload,required TResult Function( RsServerEvent_Show value) show_,}){+@optionalTypeArgs TResult map<TResult extends Object?>({required TResult Function( RsServerEvent_Register value) register,required TResult Function( RsServerEvent_PrepareUpload value) prepareUpload,required TResult Function( RsServerEvent_FileUpload value) fileUpload,required TResult Function( RsServerEvent_SessionEnd value) sessionEnd,required TResult Function( RsServerEvent_PrepareUploadAborted value) prepareUploadAborted,required TResult Function( RsServerEvent_CancelReceived value) cancelReceived,required TResult Function( RsServerEvent_WebPrepareDownload value) webPrepareDownload,required TResult Function( RsServerEvent_WebFileDownload value) webFileDownload,required TResult Function( RsServerEvent_Show value) show_,required TResult Function( RsServerEvent_ListenerFailed value) listenerFailed,}){final _that = this;switch (_that) {case RsServerEvent_Register():@@ -97,7 +98,8 @@ return prepareUploadAborted(_that);case RsServerEvent_CancelReceived():return cancelReceived(_that);case RsServerEvent_WebPrepareDownload():return webPrepareDownload(_that);case RsServerEvent_WebFileDownload():return webFileDownload(_that);case RsServerEvent_Show():-return show_(_that);}+return show_(_that);case RsServerEvent_ListenerFailed():+return listenerFailed(_that);}}/// A variant of `map` that fallback to returning `null`.///@@ -111,7 +113,7 @@ return show_(_that);}/// }/// ```-@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({TResult? Function( RsServerEvent_Register value)? register,TResult? Function( RsServerEvent_PrepareUpload value)? prepareUpload,TResult? Function( RsServerEvent_FileUpload value)? fileUpload,TResult? Function( RsServerEvent_SessionEnd value)? sessionEnd,TResult? Function( RsServerEvent_PrepareUploadAborted value)? prepareUploadAborted,TResult? Function( RsServerEvent_CancelReceived value)? cancelReceived,TResult? Function( RsServerEvent_WebPrepareDownload value)? webPrepareDownload,TResult? Function( RsServerEvent_WebFileDownload value)? webFileDownload,TResult? Function( RsServerEvent_Show value)? show_,}){+@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({TResult? Function( RsServerEvent_Register value)? register,TResult? Function( RsServerEvent_PrepareUpload value)? prepareUpload,TResult? Function( RsServerEvent_FileUpload value)? fileUpload,TResult? Function( RsServerEvent_SessionEnd value)? sessionEnd,TResult? Function( RsServerEvent_PrepareUploadAborted value)? prepareUploadAborted,TResult? Function( RsServerEvent_CancelReceived value)? cancelReceived,TResult? Function( RsServerEvent_WebPrepareDownload value)? webPrepareDownload,TResult? Function( RsServerEvent_WebFileDownload value)? webFileDownload,TResult? Function( RsServerEvent_Show value)? show_,TResult? Function( RsServerEvent_ListenerFailed value)? listenerFailed,}){final _that = this;switch (_that) {case RsServerEvent_Register() when register != null:@@ -123,7 +125,8 @@ return prepareUploadAborted(_that);case RsServerEvent_CancelReceived() when cancreturn cancelReceived(_that);case RsServerEvent_WebPrepareDownload() when webPrepareDownload != null:return webPrepareDownload(_that);case RsServerEvent_WebFileDownload() when webFileDownload != null:return webFileDownload(_that);case RsServerEvent_Show() when show_ != null:-return show_(_that);case _:+return show_(_that);case RsServerEvent_ListenerFailed() when listenerFailed != null:+return listenerFailed(_that);case _:return null;}@@ -140,7 +143,7 @@ return show_(_that);case _:/// }/// ```-@optionalTypeArgs TResult maybeWhen<TResult extends Object?>({TResult Function( String ip, RegisterDtoV2 info)? register,TResult Function( String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files)? prepareUpload,TResult Function( String sessionId, String fileId, FileDto file)? fileUpload,TResult Function( String sessionId, SessionEndReasonV2 reason)? sessionEnd,TResult Function( String sessionId)? prepareUploadAborted,TResult Function( String ip, String sessionId)? cancelReceived,TResult Function( String ip, String sessionId, String? userAgent)? webPrepareDownload,TResult Function( String sessionId, String fileId, FileDto file)? webFileDownload,TResult Function( List<String> args)? show_,required TResult orElse(),}) {final _that = this;+@optionalTypeArgs TResult maybeWhen<TResult extends Object?>({TResult Function( String ip, RegisterDtoV2 info)? register,TResult Function( String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files)? prepareUpload,TResult Function( String sessionId, String fileId, FileDto file)? fileUpload,TResult Function( String sessionId, SessionEndReasonV2 reason)? sessionEnd,TResult Function( String sessionId)? prepareUploadAborted,TResult Function( String ip, String sessionId)? cancelReceived,TResult Function( String ip, String sessionId, String? userAgent)? webPrepareDownload,TResult Function( String sessionId, String fileId, FileDto file)? webFileDownload,TResult Function( List<String> args)? show_,TResult Function( String error)? listenerFailed,required TResult orElse(),}) {final _that = this;switch (_that) {case RsServerEvent_Register() when register != null:return register(_that.ip,_that.info);case RsServerEvent_PrepareUpload() when prepareUpload != null:@@ -151,7 +154,8 @@ return prepareUploadAborted(_that.sessionId);case RsServerEvent_CancelReceived()return cancelReceived(_that.ip,_that.sessionId);case RsServerEvent_WebPrepareDownload() when webPrepareDownload != null:return webPrepareDownload(_that.ip,_that.sessionId,_that.userAgent);case RsServerEvent_WebFileDownload() when webFileDownload != null:return webFileDownload(_that.sessionId,_that.fileId,_that.file);case RsServerEvent_Show() when show_ != null:-return show_(_that.args);case _:+return show_(_that.args);case RsServerEvent_ListenerFailed() when listenerFailed != null:+return listenerFailed(_that.error);case _:return orElse();}@@ -169,7 +173,7 @@ return show_(_that.args);case _:/// }/// ```-@optionalTypeArgs TResult when<TResult extends Object?>({required TResult Function( String ip, RegisterDtoV2 info) register,required TResult Function( String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files) prepareUpload,required TResult Function( String sessionId, String fileId, FileDto file) fileUpload,required TResult Function( String sessionId, SessionEndReasonV2 reason) sessionEnd,required TResult Function( String sessionId) prepareUploadAborted,required TResult Function( String ip, String sessionId) cancelReceived,required TResult Function( String ip, String sessionId, String? userAgent) webPrepareDownload,required TResult Function( String sessionId, String fileId, FileDto file) webFileDownload,required TResult Function( List<String> args) show_,}) {final _that = this;+@optionalTypeArgs TResult when<TResult extends Object?>({required TResult Function( String ip, RegisterDtoV2 info) register,required TResult Function( String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files) prepareUpload,required TResult Function( String sessionId, String fileId, FileDto file) fileUpload,required TResult Function( String sessionId, SessionEndReasonV2 reason) sessionEnd,required TResult Function( String sessionId) prepareUploadAborted,required TResult Function( String ip, String sessionId) cancelReceived,required TResult Function( String ip, String sessionId, String? userAgent) webPrepareDownload,required TResult Function( String sessionId, String fileId, FileDto file) webFileDownload,required TResult Function( List<String> args) show_,required TResult Function( String error) listenerFailed,}) {final _that = this;switch (_that) {case RsServerEvent_Register():return register(_that.ip,_that.info);case RsServerEvent_PrepareUpload():@@ -180,7 +184,8 @@ return prepareUploadAborted(_that.sessionId);case RsServerEvent_CancelReceived()return cancelReceived(_that.ip,_that.sessionId);case RsServerEvent_WebPrepareDownload():return webPrepareDownload(_that.ip,_that.sessionId,_that.userAgent);case RsServerEvent_WebFileDownload():return webFileDownload(_that.sessionId,_that.fileId,_that.file);case RsServerEvent_Show():-return show_(_that.args);}+return show_(_that.args);case RsServerEvent_ListenerFailed():+return listenerFailed(_that.error);}}/// A variant of `when` that fallback to returning `null`///@@ -194,7 +199,7 @@ return show_(_that.args);}/// }/// ```-@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({TResult? Function( String ip, RegisterDtoV2 info)? register,TResult? Function( String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files)? prepareUpload,TResult? Function( String sessionId, String fileId, FileDto file)? fileUpload,TResult? Function( String sessionId, SessionEndReasonV2 reason)? sessionEnd,TResult? Function( String sessionId)? prepareUploadAborted,TResult? Function( String ip, String sessionId)? cancelReceived,TResult? Function( String ip, String sessionId, String? userAgent)? webPrepareDownload,TResult? Function( String sessionId, String fileId, FileDto file)? webFileDownload,TResult? Function( List<String> args)? show_,}) {final _that = this;+@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({TResult? Function( String ip, RegisterDtoV2 info)? register,TResult? Function( String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files)? prepareUpload,TResult? Function( String sessionId, String fileId, FileDto file)? fileUpload,TResult? Function( String sessionId, SessionEndReasonV2 reason)? sessionEnd,TResult? Function( String sessionId)? prepareUploadAborted,TResult? Function( String ip, String sessionId)? cancelReceived,TResult? Function( String ip, String sessionId, String? userAgent)? webPrepareDownload,TResult? Function( String sessionId, String fileId, FileDto file)? webFileDownload,TResult? Function( List<String> args)? show_,TResult? Function( String error)? listenerFailed,}) {final _that = this;switch (_that) {case RsServerEvent_Register() when register != null:return register(_that.ip,_that.info);case RsServerEvent_PrepareUpload() when prepareUpload != null:@@ -205,7 +210,8 @@ return prepareUploadAborted(_that.sessionId);case RsServerEvent_CancelReceived()return cancelReceived(_that.ip,_that.sessionId);case RsServerEvent_WebPrepareDownload() when webPrepareDownload != null:return webPrepareDownload(_that.ip,_that.sessionId,_that.userAgent);case RsServerEvent_WebFileDownload() when webFileDownload != null:return webFileDownload(_that.sessionId,_that.fileId,_that.file);case RsServerEvent_Show() when show_ != null:-return show_(_that.args);case _:+return show_(_that.args);case RsServerEvent_ListenerFailed() when listenerFailed != null:+return listenerFailed(_that.error);case _:return null;}@@ -850,6 +856,73 @@ as List<String>,}+}++/// @nodoc+++class RsServerEvent_ListenerFailed extends RsServerEvent {+ const RsServerEvent_ListenerFailed({required this.error}): super._();+++/// Description of the failure.+ final String error;++/// Create a copy of RsServerEvent+/// with the given fields replaced by the non-null parameter values.+@JsonKey(includeFromJson: false, includeToJson: false)+@pragma('vm:prefer-inline')+$RsServerEvent_ListenerFailedCopyWith<RsServerEvent_ListenerFailed> get copyWith => _$RsServerEvent_ListenerFailedCopyWithImpl<RsServerEvent_ListenerFailed>(this, _$identity);++++@override+bool operator ==(Object other) {+ return identical(this, other) || (other.runtimeType == runtimeType&&other is RsServerEvent_ListenerFailed&&(identical(other.error, error) || other.error == error));+}+++@override+int get hashCode => Object.hash(runtimeType,error);++@override+String toString() {+ return 'RsServerEvent.listenerFailed(error: $error)';+}+++}++/// @nodoc+abstract mixin class $RsServerEvent_ListenerFailedCopyWith<$Res> implements $RsServerEventCopyWith<$Res> {+ factory $RsServerEvent_ListenerFailedCopyWith(RsServerEvent_ListenerFailed value, $Res Function(RsServerEvent_ListenerFailed) _then) = _$RsServerEvent_ListenerFailedCopyWithImpl;+@useResult+$Res call({+ String error+});+++++}+/// @nodoc+class _$RsServerEvent_ListenerFailedCopyWithImpl<$Res>+ implements $RsServerEvent_ListenerFailedCopyWith<$Res> {+ _$RsServerEvent_ListenerFailedCopyWithImpl(this._self, this._then);++ final RsServerEvent_ListenerFailed _self;+ final $Res Function(RsServerEvent_ListenerFailed) _then;++/// Create a copy of RsServerEvent+/// with the given fields replaced by the non-null parameter values.+@pragma('vm:prefer-inline') $Res call({Object? error = null,}) {+ return _then(RsServerEvent_ListenerFailed(+error: null == error ? _self.error : error // ignore: cast_nullable_to_non_nullable+as String,+ ));+}++}// dart format ondiff --git a/packages/localsend_isolates/lib/rust/frb_generated.dart b/packages/localsend_isolates/lib/rust/frb_generated.dartindex 32d3703d..a9d1c071 100644--- a/packages/localsend_isolates/lib/rust/frb_generated.dart+++ b/packages/localsend_isolates/lib/rust/frb_generated.dart@@ -3278,6 +3278,10 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {return RsServerEvent_Show(args: dco_decode_list_String(raw[1]),);+ case 9:+ return RsServerEvent_ListenerFailed(+ error: dco_decode_String(raw[1]),+ );default:throw Exception('unreachable');}@@ -4649,6 +4653,9 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {case 8:var var_args = sse_decode_list_String(deserializer);return RsServerEvent_Show(args: var_args);+ case 9:+ var var_error = sse_decode_String(deserializer);+ return RsServerEvent_ListenerFailed(error: var_error);default:throw UnimplementedError('');}@@ -6023,6 +6030,9 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {case RsServerEvent_Show(args: final args):sse_encode_i_32(8, serializer);sse_encode_list_String(args, serializer);+ case RsServerEvent_ListenerFailed(error: final error):+ sse_encode_i_32(9, serializer);+ sse_encode_String(error, serializer);}}@@ -6391,6 +6401,11 @@ class RsDiscoveryImpl extends RustOpaque implements RsDiscovery {/// Emits a [RsStoredDevice] for every device confirmation until the/// discovery is stopped. Can only be listened to once.///+ /// Also ends when the multicast sockets failed permanently (e.g. because+ /// the OS invalidated them while the application was suspended): the+ /// application reacts to the ended stream by starting a new discovery,+ /// which rebinds the sockets.+ ////// Also returns when the Dart side of the stream is gone (e.g. after a/// hot restart), so this call does not keep the discovery alive forever.Stream<RsStoredDevice> listen() => RustLib.instance.api.crateApiDiscoveryRsDiscoveryListen(diff --git a/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart b/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dartindex 452578e5..efa29084 100644--- a/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart+++ b/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart@@ -335,6 +335,19 @@ class HttpServerShowEvent extends HttpServerEvent {});}+/// The listening socket failed permanently, e.g. because the OS invalidated it+/// while the application was suspended (iOS reclaims the sockets of suspended+/// apps). The server has stopped itself; the application must restart it to+/// become reachable again.+class HttpServerListenerFailedEvent extends HttpServerEvent {+ /// Description of the failure.+ final String error;++ HttpServerListenerFailedEvent({+ required this.error,+ });+}+class _ReceiveSession {final HttpServerReceiveConfig config;@@ -529,6 +542,9 @@ Future<void> setupHttpServerIsolate();case RsServerEvent_Show(:final args):emit(HttpServerShowEvent(args: args));+ case RsServerEvent_ListenerFailed(:final error):+ ref.read(_receiveSessionProvider).session = null;+ emit(HttpServerListenerFailedEvent(error: error));}}} finally {diff --git a/packages/localsend_isolates/lib/src/task/discovery/discovery.dart b/packages/localsend_isolates/lib/src/task/discovery/discovery.dartindex 143814dd..d448719f 100644--- a/packages/localsend_isolates/lib/src/task/discovery/discovery.dart+++ b/packages/localsend_isolates/lib/src/task/discovery/discovery.dart@@ -27,6 +27,10 @@ class DiscoveryService {Completer<void> _retryCompleter = Completer();bool _listening = false;+ /// Whether the current discovery was stopped by [restartListener], as+ /// opposed to stopping itself because the multicast sockets failed.+ bool _restartRequested = false;+/// Starts the discovery and emits every device confirmation:/// answered announcements, scan results and devices fed in/// via [addDevice] all arrive on this one stream.@@ -101,8 +105,19 @@ class DiscoveryService {}}- // The stream ended because [restartListener] stopped the discovery._discovery = null;++ if (_restartRequested) {+ // The stream ended because [restartListener] stopped the discovery.+ _restartRequested = false;+ } else {+ // The stream ended because the multicast sockets failed permanently,+ // e.g. because iOS reclaimed them while the app was suspended.+ // The delay avoids hot-looping when binding keeps succeeding but the+ // sockets keep failing right away.+ _logger.warning('Discovery stopped unexpectedly (multicast sockets failed). Restarting discovery.');+ await Future<void>.delayed(const Duration(seconds: 1));+ }}}@@ -111,6 +126,7 @@ class DiscoveryService {final discovery = _discovery;if (discovery != null) {// Ends the listen stream, which makes [startListener] rebind.+ _restartRequested = true;unawaited(discovery.stop());} else if (!_retryCompleter.isCompleted) {// Starting failed previously; let [startListener] try again.@@ -179,7 +195,6 @@ class DiscoveryService {);}-/// The retained confirmations of a stored device, oldest first./// Empty when the fingerprint is unknown or the discovery is not running.Future<List<DeviceLog>> deviceLogs(String fingerprint) async {diff --git a/packages/localsend_isolates/rust/src/api/discovery.rs b/packages/localsend_isolates/rust/src/api/discovery.rsindex 310f1ab2..e153c221 100644--- a/packages/localsend_isolates/rust/src/api/discovery.rs+++ b/packages/localsend_isolates/rust/src/api/discovery.rs@@ -11,6 +11,7 @@ use localsend::util::interface::InterfaceFilter;use std::sync::Arc;use std::time::Duration;use tokio::sync::{Mutex, mpsc, oneshot};+use tokio_util::sync::CancellationToken;/// A single device confirmation over HTTP, fed into the store via/// [RsDiscovery::add_device]: the device's register request was accepted by@@ -115,6 +116,12 @@ pub struct RsDiscovery {struct DiscoveryInstance {handle: DiscoveryHandle,stop_tx: Mutex<Option<oneshot::Sender<()>>>,++ /// Ends the [RsDiscovery::listen] stream on stop. The discovery event+ /// sender lives in the handle itself, so the event channel never closes+ /// while this instance exists; without this signal the stream would+ /// outlive the stop.+ cancel: CancellationToken,}impl DiscoveryInstance {@@ -125,6 +132,7 @@ impl DiscoveryInstance {let _ = stop_tx.send(());self.handle.wait_stopped().await;}+ self.cancel.cancel();}}@@ -218,6 +226,7 @@ pub async fn start_discovery(let instance = Arc::new(DiscoveryInstance {handle,stop_tx: Mutex::new(Some(stop_tx)),+ cancel: CancellationToken::new(),});*running_discovery = Some(instance.clone());@@ -231,6 +240,11 @@ impl RsDiscovery {/// Emits a [RsStoredDevice] for every device confirmation until the/// discovery is stopped. Can only be listened to once.///+ /// Also ends when the multicast sockets failed permanently (e.g. because+ /// the OS invalidated them while the application was suspended): the+ /// application reacts to the ended stream by starting a new discovery,+ /// which rebinds the sockets.+ ////// Also returns when the Dart side of the stream is gone (e.g. after a/// hot restart), so this call does not keep the discovery alive forever.pub async fn listen(&self, sink: StreamSink<RsStoredDevice>) {@@ -239,9 +253,26 @@ impl RsDiscovery {return;};- while let Some(event) = event_rx.recv().await {- let (DiscoveryEvent::Discovered { device } | DiscoveryEvent::Updated { device }) =- event;+ loop {+ let event = tokio::select! {+ event = event_rx.recv() => event,+ // The event sender lives in the handle this instance holds,+ // so the channel never closes on its own; the stop signals+ // the end explicitly.+ _ = self.instance.cancel.cancelled() => break,+ };+ let device = match event {+ Some(+ DiscoveryEvent::Discovered { device } | DiscoveryEvent::Updated { device },+ ) => device,+ Some(DiscoveryEvent::MulticastFailed) => {+ tracing::error!(+ "Multicast sockets failed, ending the discovery event stream"+ );+ break;+ }+ None => break,+ };// The store is updated before the event is emitted, so the merged// state is at least as new as the confirmation.if let Some(stored) = selfdiff --git a/packages/localsend_isolates/rust/src/api/server.rs b/packages/localsend_isolates/rust/src/api/server.rsindex 72abd74b..10a3f05e 100644--- a/packages/localsend_isolates/rust/src/api/server.rs+++ b/packages/localsend_isolates/rust/src/api/server.rs@@ -96,6 +96,15 @@ pub enum RsServerEvent {/// Command-line arguments forwarded by the other application instance.args: Vec<String>,},++ /// The listening socket failed permanently, e.g. because the OS+ /// invalidated it while the application was suspended (iOS reclaims the+ /// sockets of suspended apps). The server has stopped itself; the+ /// application must restart it to become reachable again.+ ListenerFailed {+ /// Description of the failure.+ error: String,+ },}pub struct RsHttpServer {@@ -410,6 +419,9 @@ impl RsHttpServer {session_id,}).is_ok(),+ ServerEventV2::ListenerFailed { error } => {+ sink.add(RsServerEvent::ListenerFailed { error }).is_ok()+ }}}diff --git a/packages/localsend_isolates/rust/src/frb_generated.rs b/packages/localsend_isolates/rust/src/frb_generated.rsindex 5847ab74..131da6fe 100644--- a/packages/localsend_isolates/rust/src/frb_generated.rs+++ b/packages/localsend_isolates/rust/src/frb_generated.rs@@ -4791,6 +4791,10 @@ impl SseDecode for crate::api::server::RsServerEvent {let mut var_args = <Vec<String>>::sse_decode(deserializer);return crate::api::server::RsServerEvent::Show { args: var_args };}+ 9 => {+ let mut var_error = <String>::sse_decode(deserializer);+ return crate::api::server::RsServerEvent::ListenerFailed { error: var_error };+ }_ => {unimplemented!("");}@@ -6198,6 +6202,9 @@ impl flutter_rust_bridge::IntoDart for crate::api::server::RsServerEvent {crate::api::server::RsServerEvent::Show { args } => {[8.into_dart(), args.into_into_dart().into_dart()].into_dart()}+ crate::api::server::RsServerEvent::ListenerFailed { error } => {+ [9.into_dart(), error.into_into_dart().into_dart()].into_dart()+ }_ => {unimplemented!("");}@@ -7560,6 +7567,10 @@ impl SseEncode for crate::api::server::RsServerEvent {<i32>::sse_encode(8, serializer);<Vec<String>>::sse_encode(args, serializer);}+ crate::api::server::RsServerEvent::ListenerFailed { error } => {+ <i32>::sse_encode(9, serializer);+ <String>::sse_encode(error, serializer);+ }_ => {unimplemented!("");}