An open-source cross-platform alternative to AirDrop
fix(app): repair the single-instance show handover (#3246)
antheducationae0d2c868c56
diff --git a/app/lib/config/init.dart b/app/lib/config/init.dartindex a1685b08..e0794ffe 100644--- a/app/lib/config/init.dart+++ b/app/lib/config/init.dart@@ -1,5 +1,4 @@import 'dart:async';-import 'dart:convert';import 'dart:io';import 'package:dart_mappable/dart_mappable.dart';@@ -39,14 +38,13 @@ import 'package:localsend_app/util/native/tray_helper.dart';import 'package:localsend_app/util/notification_strings.dart';import 'package:localsend_app/util/ui/dynamic_colors.dart';import 'package:localsend_app/util/ui/snackbar.dart';-import 'package:localsend_isolates/api_route_builder.dart';-import 'package:localsend_isolates/constants.dart';import 'package:localsend_isolates/isolate.dart';import 'package:localsend_isolates/model/dto/file_dto.dart';import 'package:localsend_isolates/model/dto/multicast_dto.dart';import 'package:localsend_isolates/rust/api/logging.dart' as rust_logging;import 'package:localsend_isolates/rust/frb_generated.dart';import 'package:localsend_isolates/util/logger.dart';+import 'package:localsend_isolates/util/show_instance.dart';import 'package:localsend_isolates/util/transfer_notification.dart';import 'package:logging/logging.dart';import 'package:refena_flutter/addons.dart';@@ -93,35 +91,15 @@ Future<RefenaContainer> preInit(List<String> args) async {// Check if this app is already open and let it "show up".// If this is the case, then exit the current instance.- final client = HttpClient();- client.connectionTimeout = const Duration(milliseconds: 100);- client.badCertificateCallback = (cert, host, port) => true;-- try {- final uri =- Uri.parse(- ApiRoute.show.targetRaw(- '127.0.0.1',- persistenceService.getPort(),- persistenceService.isHttps(),- peerProtocolVersion,- ),- ).replace(- queryParameters: {- 'token': persistenceService.getShowToken(),- },- );-- final request = await client.postUrl(uri);- request.headers.contentType = ContentType.json;- request.write(jsonEncode({'args': args}));- final response = await request.close().timeout(const Duration(milliseconds: 500));- if (response.statusCode == 200) {- exit(0); // Another instance does exist- }- } catch (_) {- } finally {- client.close(force: true);+ final handedOver = await notifyRunningInstance(+ securityContext: persistenceService.getSecurityContext(),+ port: persistenceService.getPort(),+ https: persistenceService.isHttps(),+ showToken: persistenceService.getShowToken(),+ args: args,+ );+ if (handedOver) {+ exit(0); // Another instance does exist}// initialize tray AFTER i18n has been initializeddiff --git a/packages/localsend_isolates/lib/util/show_instance.dart b/packages/localsend_isolates/lib/util/show_instance.dartnew file mode 100644index 00000000..e7641f3b--- /dev/null+++ b/packages/localsend_isolates/lib/util/show_instance.dart@@ -0,0 +1,90 @@+import 'dart:convert';+import 'dart:io';++import 'package:localsend_isolates/api_route_builder.dart';+import 'package:localsend_isolates/model/stored_security_context.dart';+import 'package:logging/logging.dart';++final _logger = Logger('ShowInstance');++/// Asks an app instance that is already running on this machine to show itself+/// and to take over [args].+///+/// Returns `true` when a running instance accepted the handover, so the caller+/// can exit instead of starting a second instance.+///+/// The server demands a client certificate whenever the web pages are not+/// served, so this client must present the device's own certificate. Without+/// it, the TLS handshake is rejected before the request is ever sent and the+/// running instance is never reached.+Future<bool> notifyRunningInstance({+ required StoredSecurityContext securityContext,+ required int port,+ required bool https,+ required String showToken,+ required List<String> args,+ Duration connectionTimeout = const Duration(milliseconds: 100),+ Duration responseTimeout = const Duration(milliseconds: 500),+}) async {+ final client = HttpClient(context: https ? _clientContext(securityContext) : null);+ client.connectionTimeout = connectionTimeout;++ // The peer is this device itself; its certificate is self-signed by design.+ client.badCertificateCallback = (cert, host, port) => true;++ try {+ // `show` is an internal endpoint that is only served on the v2 path, so the+ // route must not be negotiated like a peer's protocol version.+ final uri = Uri(+ scheme: https ? 'https' : 'http',+ host: '127.0.0.1',+ port: port,+ path: ApiRoute.show.v2,+ queryParameters: {+ 'token': showToken,+ },+ );++ final request = await client.postUrl(uri);+ request.headers.contentType = ContentType.json;+ request.write(jsonEncode({'args': args}));+ final response = await request.close().timeout(responseTimeout);+ final statusCode = response.statusCode;++ // Read the (empty) body so the connection is not left half-read, but never+ // wait longer than the response timeout for it: the status is already known+ // and startup must not hang on whatever is holding the port.+ try {+ await response.drain<void>().timeout(responseTimeout);+ } catch (_) {+ // A body that never arrives does not change the answer above.+ }++ if (statusCode != 200) {+ // Something answered on the port but refused the handover. That is never+ // normal, and it is exactly what silently degrades into a second instance+ // fighting over the port, so it must not be swallowed.+ _logger.warning('The running instance refused to take over the arguments: HTTP $statusCode');+ return false;+ }+ return true;+ } on HandshakeException catch (e) {+ // An instance is listening but the TLS handshake did not complete, e.g.+ // because it did not accept this device's certificate. Also never normal.+ _logger.warning('TLS handshake with the running instance failed: $e');+ return false;+ } catch (e) {+ // Nothing is listening - the normal case on a regular app start.+ _logger.fine('No running instance took over the arguments: $e');+ return false;+ } finally {+ client.close(force: true);+ }+}++/// Presents the device's own certificate, which the server verifies.+SecurityContext _clientContext(StoredSecurityContext securityContext) {+ return SecurityContext(withTrustedRoots: false)+ ..useCertificateChainBytes(utf8.encode(securityContext.certificate))+ ..usePrivateKeyBytes(utf8.encode(securityContext.privateKey));+}diff --git a/packages/localsend_isolates/test/util/show_instance_test.dart b/packages/localsend_isolates/test/util/show_instance_test.dartnew file mode 100644index 00000000..5182d901--- /dev/null+++ b/packages/localsend_isolates/test/util/show_instance_test.dart@@ -0,0 +1,185 @@+// Regression test for https://github.com/localsend/localsend/issues/3165+//+// "Send to -> LocalSend" starts a second process with the file paths as+// arguments. Only the internal `show` handover keeps that process from becoming+// a duplicate instance that then collides on port 53317.+//+// Two things made the handover fail:+// * it was addressed with `peerProtocolVersion` ('1.0'), which builds the v1+// path, while the server only serves `show` on the v2 path, and+// * it presented no client certificate, while the server demands one whenever+// the web pages are not served (`mandatory_client_auth` in+// `packages/core/src/http/server/mod.rs`), so the TLS handshake was+// rejected before the request was sent.+//+// The stub server below stands in for the running instance: a real one cannot+// be started in-process here, because the Rust TLS stack and the client's+// BoringSSL deadlock inside `flutter_tester`.+@Timeout(Duration(minutes: 1))+library;++import 'dart:convert';+import 'dart:io';++import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart' show ExternalLibrary;+import 'package:flutter_test/flutter_test.dart';+import 'package:localsend_isolates/model/stored_security_context.dart';+import 'package:localsend_isolates/rust/api/crypto.dart' hide SecurityContext;+import 'package:localsend_isolates/rust/frb_generated.dart';+import 'package:localsend_isolates/util/show_instance.dart';++const _token = 'show-token-3165';++/// Cargo writes the library under a different name per platform.+File _findDylib() {+ final base = '${Directory.current.path}/../../target/debug';+ return [+ File('$base/librust_lib_localsend_app.dylib'),+ File('$base/librust_lib_localsend_app.so'),+ File('$base/rust_lib_localsend_app.dll'),+ ].firstWhere((f) => f.existsSync(), orElse: () => File('$base/librust_lib_localsend_app.dylib'));+}++/// What the stub server saw of a handover request.+class _Received {+ String? path;+ String? token;+ String? body;+ X509Certificate? clientCertificate;+}++void main() {+ late StoredSecurityContext identity;++ setUpAll(() async {+ final dylib = _findDylib();+ if (!dylib.existsSync()) {+ return;+ }+ await RustLib.init(externalLibrary: ExternalLibrary.open(dylib.path));+ final generated = await generateSecurityContext();+ identity = StoredSecurityContext(+ privateKey: generated.privateKey,+ publicKey: generated.publicKey,+ certificate: generated.certificate,+ certificateHash: generated.certificateHash,+ );+ });++ /// Serves the `show` endpoint like a running instance would, over TLS with+ /// client certificates requested, and answers with [statusCode].+ Future<(HttpServer, _Received)> startStub({int statusCode = 200}) async {+ final context = SecurityContext(withTrustedRoots: false)+ ..useCertificateChainBytes(utf8.encode(identity.certificate))+ ..usePrivateKeyBytes(utf8.encode(identity.privateKey))+ // The client presents this same self-signed identity.+ ..setTrustedCertificatesBytes(utf8.encode(identity.certificate));++ final server = await HttpServer.bindSecure(+ InternetAddress.loopbackIPv4,+ 0,+ context,+ requestClientCertificate: true,+ );++ final received = _Received();+ server.listen((request) async {+ received+ ..path = request.uri.path+ ..token = request.uri.queryParameters['token']+ ..body = await utf8.decodeStream(request)+ ..clientCertificate = request.certificate;++ // Mirrors what the real server does: `show` exists on the v2 path only,+ // it is guarded by the token, and it is unreachable without a client+ // certificate (there the handshake itself is refused, which a Dart server+ // cannot express, so an unauthorized answer stands in for it).+ request.response.statusCode = switch (received) {+ _Received(clientCertificate: null) => HttpStatus.unauthorized,+ _Received(path: != '/api/localsend/v2/show') => HttpStatus.notFound,+ _Received(token: != _token) => HttpStatus.forbidden,+ _ => statusCode,+ };+ await request.response.close();+ });++ return (server, received);+ }++ test('hands the arguments to the running instance over TLS', () async {+ if (!_findDylib().existsSync()) {+ markTestSkipped('Rust dylib not built (cargo build -p rust_lib_localsend_app)');+ return;+ }+ final (server, received) = await startStub();+ addTearDown(() => server.close(force: true));++ const args = [r'C:\Users\Test\holiday.png'];+ final handedOver = await notifyRunningInstance(+ securityContext: identity,+ port: server.port,+ https: true,+ showToken: _token,+ args: args,+ connectionTimeout: const Duration(seconds: 10),+ responseTimeout: const Duration(seconds: 10),+ );++ expect(handedOver, isTrue, reason: 'the running instance accepted the handover');++ // Regression: '1.0' used to select the v1 path, which the server does not serve.+ expect(received.path, '/api/localsend/v2/show');+ expect(received.token, _token);+ expect(jsonDecode(received.body!), {'args': args});++ // Regression: without this the server rejects the handshake and the second+ // instance starts anyway, fighting over the port.+ expect(+ received.clientCertificate,+ isNotNull,+ reason: 'the device certificate must be presented, the server requires one',+ );+ });++ test('does not exit when the running instance rejects the request', () async {+ if (!_findDylib().existsSync()) {+ markTestSkipped('Rust dylib not built (cargo build -p rust_lib_localsend_app)');+ return;+ }+ final (server, _) = await startStub();+ addTearDown(() => server.close(force: true));++ final handedOver = await notifyRunningInstance(+ securityContext: identity,+ port: server.port,+ https: true,+ showToken: 'wrong-token',+ args: const [],+ connectionTimeout: const Duration(seconds: 10),+ responseTimeout: const Duration(seconds: 10),+ );++ expect(handedOver, isFalse);+ });++ test('reports no running instance when nothing listens', () async {+ if (!_findDylib().existsSync()) {+ markTestSkipped('Rust dylib not built (cargo build -p rust_lib_localsend_app)');+ return;+ }+ // Bind and immediately release a port so that nothing answers on it.+ final probe = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);+ final closedPort = probe.port;+ await probe.close();++ final handedOver = await notifyRunningInstance(+ securityContext: identity,+ port: closedPort,+ https: true,+ showToken: _token,+ args: const [],+ );++ expect(handedOver, isFalse);+ });+}