diff --git a/packages/flutter_tools/lib/src/mdns_discovery.dart b/packages/flutter_tools/lib/src/mdns_discovery.dart index 474f14652e..ea9b82a1ea 100644 --- a/packages/flutter_tools/lib/src/mdns_discovery.dart +++ b/packages/flutter_tools/lib/src/mdns_discovery.dart @@ -96,7 +96,7 @@ class MDnsVmServiceDiscovery { final List results = await _pollingVmService( _preliminaryClient ?? MDnsClient(), applicationId: applicationId, - deviceVmservicePort: deviceVmservicePort, + deviceVmServicePort: deviceVmservicePort, ipv6: ipv6, useDeviceIPAsHost: useDeviceIPAsHost, timeout: const Duration(seconds: 5), @@ -192,7 +192,7 @@ class MDnsVmServiceDiscovery { final List results = await _pollingVmService( client, applicationId: applicationId, - deviceVmservicePort: deviceVmservicePort, + deviceVmServicePort: deviceVmservicePort, deviceName: deviceName, ipv6: ipv6, useDeviceIPAsHost: useDeviceIPAsHost, @@ -208,7 +208,74 @@ class MDnsVmServiceDiscovery { Future> _pollingVmService( MDnsClient client, { String? applicationId, - int? deviceVmservicePort, + int? deviceVmServicePort, + String? deviceName, + bool ipv6 = false, + bool useDeviceIPAsHost = false, + required Duration timeout, + bool quitOnFind = false, + }) async { + // macOS blocks mDNS unless the app has Local Network permissions. + // Since the mDNS client does not handle errors from the socket's stream, + // socket exceptions are routed to the current zone. Create an error zone to + // catch the socket exception. + // See: https://github.com/flutter/flutter/issues/150131 + final Completer> completer = + Completer>(); + unawaited( + runZonedGuarded( + () async { + final List results = await _doPollingVmService( + client, + applicationId: applicationId, + deviceVmServicePort: deviceVmServicePort, + deviceName: deviceName, + ipv6: ipv6, + useDeviceIPAsHost: useDeviceIPAsHost, + timeout: timeout, + quitOnFind: quitOnFind, + ); + + if (!completer.isCompleted) { + completer.complete(results); + } + }, + (Object error, StackTrace stackTrace) { + if (!completer.isCompleted) { + completer.completeError(error, stackTrace); + } + }, + ), + ); + + try { + return await completer.future; + } on SocketException catch (e, stackTrace) { + if (!globals.platform.isMacOS) { + rethrow; + } + + _logger.printTrace(stackTrace.toString()); + + throwToolExit( + 'Flutter could not connect to the Dart VM service.\n' + '\n' + 'Please ensure your IDE or terminal app has permission to access ' + 'devices on the local network. This allows Flutter to connect to ' + 'the Dart VM.\n' + '\n' + 'You can grant this permission in System Settings > Privacy & ' + 'Security > Local Network.\n' + '\n' + '$e', + ); + } + } + + Future> _doPollingVmService( + MDnsClient client, { + String? applicationId, + int? deviceVmServicePort, String? deviceName, bool ipv6 = false, bool useDeviceIPAsHost = false, @@ -232,27 +299,10 @@ class MDnsVmServiceDiscovery { final Set uniqueDomainNamesInResults = {}; // Listen for mDNS connections until timeout. - final Stream ptrResourceStream; - - try { - ptrResourceStream = client.lookup( - ResourceRecordQuery.serverPointer(dartVmServiceName), - timeout: timeout, - ); - } on SocketException catch (e, stacktrace) { - _logger.printError(e.message); - _logger.printTrace(stacktrace.toString()); - if (globals.platform.isMacOS) { - throwToolExit( - 'You might be having a permissions issue with your IDE. ' - 'Please try going to ' - 'System Settings -> Privacy & Security -> Local Network -> ' - '[Find your IDE] -> Toggle ON, then restart your phone.', - ); - } else { - rethrow; - } - } + final Stream ptrResourceStream = client.lookup( + ResourceRecordQuery.serverPointer(dartVmServiceName), + timeout: timeout, + ); await for (final PtrResourceRecord ptr in ptrResourceStream) { uniqueDomainNames.add(ptr.domainName); @@ -292,8 +342,8 @@ class MDnsVmServiceDiscovery { ); } - // If deviceVmservicePort is set, only use records that match it - if (deviceVmservicePort != null && srvRecord.port != deviceVmservicePort) { + // If deviceVmServicePort is set, only use records that match it + if (deviceVmServicePort != null && srvRecord.port != deviceVmServicePort) { continue; } @@ -355,8 +405,8 @@ class MDnsVmServiceDiscovery { // the applicationId were found but other results were found, throw an error. if (applicationId != null && quitOnFind && results.isEmpty && uniqueDomainNames.isNotEmpty) { String message = 'Did not find a Dart VM Service advertised for $applicationId'; - if (deviceVmservicePort != null) { - message += ' on port $deviceVmservicePort'; + if (deviceVmServicePort != null) { + message += ' on port $deviceVmServicePort'; } throwToolExit('$message.'); } diff --git a/packages/flutter_tools/test/general.shard/mdns_discovery_test.dart b/packages/flutter_tools/test/general.shard/mdns_discovery_test.dart index 1c2ccf9620..97fbc7189f 100644 --- a/packages/flutter_tools/test/general.shard/mdns_discovery_test.dart +++ b/packages/flutter_tools/test/general.shard/mdns_discovery_test.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:async'; + import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/logger.dart'; @@ -610,13 +612,16 @@ void main() { ); }); + // On macOS, the mDNS client's socket stream creates a SocketException if + // the app running the tool does not have Local Network permissions. + // See: https://github.com/flutter/flutter/issues/150131 test( - 'On macOS, throw tool exit with a helpful message when client throws a SocketException on lookup', + 'On macOS, tool exits with a helpful message when mDNS lookup throws a SocketException', () async { final MDnsClient client = FakeMDnsClient( [], >{}, - socketExceptionOnStart: true, + socketExceptionOnLookup: true, ); final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( @@ -627,13 +632,55 @@ void main() { ); expect( - portDiscovery.firstMatchingVmService(client), + () async => portDiscovery.firstMatchingVmService(client), throwsToolExit( message: - 'You might be having a permissions issue with your IDE. ' - 'Please try going to ' - 'System Settings -> Privacy & Security -> Local Network -> ' - '[Find your IDE] -> Toggle ON, then restart your phone.', + 'Flutter could not connect to the Dart VM service.\n' + '\n' + 'Please ensure your IDE or terminal app has permission to access ' + 'devices on the local network. This allows Flutter to connect to ' + 'the Dart VM.\n' + '\n' + 'You can grant this permission in System Settings > Privacy & ' + 'Security > Local Network.\n', + ), + ); + }, + // [intended] This tool exit message only works for macOS + skip: !globals.platform.isMacOS, + ); + + // On macOS, the mDNS client's socket stream creates a SocketException if + // the app running the tool does not have Local Network permissions. + // See: https://github.com/flutter/flutter/issues/150131 + test( + 'On macOS, tool exits with a helpful message when mDNS lookup throws an uncaught SocketException', + () async { + final MDnsClient client = FakeMDnsClient( + [], + >{}, + uncaughtSocketExceptionOnLookup: true, + ); + + final MDnsVmServiceDiscovery portDiscovery = MDnsVmServiceDiscovery( + mdnsClient: client, + logger: BufferLogger.test(), + flutterUsage: TestUsage(), + analytics: const NoOpAnalytics(), + ); + + expect( + () async => portDiscovery.firstMatchingVmService(client), + throwsToolExit( + message: + 'Flutter could not connect to the Dart VM service.\n' + '\n' + 'Please ensure your IDE or terminal app has permission to access ' + 'devices on the local network. This allows Flutter to connect to ' + 'the Dart VM.\n' + '\n' + 'You can grant this permission in System Settings > Privacy & ' + 'Security > Local Network.\n', ), ); }, @@ -1155,7 +1202,8 @@ class FakeMDnsClient extends Fake implements MDnsClient { this.txtResponse = const >{}, this.ipResponse = const >{}, this.osErrorOnStart = false, - this.socketExceptionOnStart = false, + this.socketExceptionOnLookup = false, + this.uncaughtSocketExceptionOnLookup = false, }); final List ptrRecords; @@ -1163,7 +1211,8 @@ class FakeMDnsClient extends Fake implements MDnsClient { final Map> txtResponse; final Map> ipResponse; final bool osErrorOnStart; - final bool socketExceptionOnStart; + final bool socketExceptionOnLookup; + final bool uncaughtSocketExceptionOnLookup; @override Future start({ @@ -1182,9 +1231,17 @@ class FakeMDnsClient extends Fake implements MDnsClient { ResourceRecordQuery query, { Duration timeout = const Duration(seconds: 5), }) { - if (socketExceptionOnStart) { + if (socketExceptionOnLookup) { throw const SocketException('Socket Exception'); } + + if (uncaughtSocketExceptionOnLookup) { + Zone.current.handleUncaughtError( + const SocketException('Socket Exception'), + StackTrace.current, + ); + } + if (T == PtrResourceRecord && query.fullyQualifiedName == MDnsVmServiceDiscovery.dartVmServiceName) { return Stream.fromIterable(ptrRecords) as Stream;