Revert "Support iOS wireless debugging (#118104)" (#118826)

This reverts commit 5cd2d4c61e.
This commit is contained in:
Jenn Magder
2023-01-19 12:31:53 -08:00
committed by GitHub
parent 5cd2d4c61e
commit cbf2e16892
15 changed files with 348 additions and 1763 deletions

View File

@@ -16,7 +16,7 @@ import '../base/logger.dart';
import '../base/platform.dart';
import '../base/signals.dart';
import '../base/terminal.dart';
import '../build_info.dart';
import '../build_info.dart';
import '../commands/daemon.dart';
import '../compile.dart';
import '../daemon.dart';
@@ -24,7 +24,6 @@ import '../device.dart';
import '../device_port_forwarder.dart';
import '../fuchsia/fuchsia_device.dart';
import '../ios/devices.dart';
import '../ios/iproxy.dart';
import '../ios/simulators.dart';
import '../macos/macos_ipad_device.dart';
import '../mdns_discovery.dart';
@@ -230,7 +229,7 @@ known, it can be explicitly provided to attach via the command-line, e.g.
}
if (debugPort != null && debugUri != null) {
throwToolExit(
'Either --debug-port or --debug-url can be provided, not both.');
'Either --debugPort or --debugUri can be provided, not both.');
}
if (userIdentifier != null) {
@@ -283,9 +282,8 @@ known, it can be explicitly provided to attach via the command-line, e.g.
final String ipv6Loopback = InternetAddress.loopbackIPv6.address;
final String ipv4Loopback = InternetAddress.loopbackIPv4.address;
final String hostname = usesIpv6 ? ipv6Loopback : ipv4Loopback;
final bool isNetworkDevice = (device is IOSDevice) && device.interfaceType == IOSDeviceConnectionInterface.network;
if ((debugPort == null && debugUri == null) || isNetworkDevice) {
if (debugPort == null && debugUri == null) {
if (device is FuchsiaDevice) {
final String module = stringArgDeprecated('module')!;
if (module == null) {
@@ -305,73 +303,16 @@ known, it can be explicitly provided to attach via the command-line, e.g.
rethrow;
}
} else if ((device is IOSDevice) || (device is IOSSimulator) || (device is MacOSDesignedForIPadDevice)) {
// Protocol Discovery relies on logging. On iOS earlier than 13, logging is gathered using syslog.
// syslog is not available for iOS 13+. For iOS 13+, Protocol Discovery gathers logs from the VMService.
// Since we don't have access to the VMService yet, Protocol Discovery cannot be used for iOS 13+.
// Also, network devices must be found using mDNS and cannot use Protocol Discovery.
final bool compatibleWithProtocolDiscovery = (device is IOSDevice) &&
device.majorSdkVersion < IOSDeviceLogReader.minimumUniversalLoggingSdkVersion &&
!isNetworkDevice;
_logger.printStatus('Waiting for a connection from Flutter on ${device.name}...');
final Status discoveryStatus = _logger.startSpinner(
timeout: const Duration(seconds: 30),
slowWarningCallback: () {
// If relying on mDNS to find Dart VM Service, remind the user to allow local network permissions.
if (!compatibleWithProtocolDiscovery) {
return 'The Dart VM Service was not discovered after 30 seconds. This is taking much longer than expected...\n\n'
'Click "Allow" to the prompt asking if you would like to find and connect devices on your local network. '
'If you selected "Don\'t Allow", you can turn it on in Settings > Your App Name > Local Network. '
"If you don't see your app in the Settings, uninstall the app and rerun to see the prompt again.\n";
}
return 'The Dart VM Service was not discovered after 30 seconds. This is taking much longer than expected...\n';
},
);
int? devicePort;
if (debugPort != null) {
devicePort = debugPort;
} else if (debugUri != null) {
devicePort = debugUri?.port;
} else if (deviceVmservicePort != null) {
devicePort = deviceVmservicePort;
}
final Future<Uri?> mDNSDiscoveryFuture = MDnsVmServiceDiscovery.instance!.getVMServiceUriForAttach(
appId,
device,
usesIpv6: usesIpv6,
isNetworkDevice: isNetworkDevice,
deviceVmservicePort: devicePort,
);
Future<Uri?>? protocolDiscoveryFuture;
if (compatibleWithProtocolDiscovery) {
final ProtocolDiscovery vmServiceDiscovery = ProtocolDiscovery.observatory(
device.getLogReader(),
portForwarder: device.portForwarder,
ipv6: ipv6!,
devicePort: devicePort,
hostPort: hostVmservicePort,
logger: _logger,
final Uri? uriFromMdns =
await MDnsObservatoryDiscovery.instance!.getObservatoryUri(
appId,
device,
usesIpv6: usesIpv6,
deviceVmservicePort: deviceVmservicePort,
);
protocolDiscoveryFuture = vmServiceDiscovery.uri;
}
final Uri? foundUrl;
if (protocolDiscoveryFuture == null) {
foundUrl = await mDNSDiscoveryFuture;
} else {
foundUrl = await Future.any(
<Future<Uri?>>[mDNSDiscoveryFuture, protocolDiscoveryFuture]
);
}
discoveryStatus.stop();
observatoryUri = foundUrl == null
observatoryUri = uriFromMdns == null
? null
: Stream<Uri>.value(foundUrl).asBroadcastStream();
: Stream<Uri>.value(uriFromMdns).asBroadcastStream();
}
// If MDNS discovery fails or we're not on iOS, fallback to ProtocolDiscovery.
if (observatoryUri == null) {
@@ -394,7 +335,7 @@ known, it can be explicitly provided to attach via the command-line, e.g.
} else {
observatoryUri = Stream<Uri>
.fromFuture(
buildVMServiceUri(
buildObservatoryUri(
device,
debugUri?.host ?? hostname,
debugPort ?? debugUri!.port,

View File

@@ -4,7 +4,6 @@
import 'dart:async';
import 'package:args/args.dart';
import 'package:meta/meta.dart';
import 'package:package_config/package_config_types.dart';
@@ -22,8 +21,6 @@ import '../dart/package_map.dart';
import '../device.dart';
import '../drive/drive_service.dart';
import '../globals.dart' as globals;
import '../ios/devices.dart';
import '../ios/iproxy.dart';
import '../resident_runner.dart';
import '../runner/flutter_command.dart' show FlutterCommandCategory, FlutterCommandResult, FlutterOptions;
import '../web/web_device.dart';
@@ -206,27 +203,6 @@ class DriveCommand extends RunCommandBase {
@override
bool get cachePubGet => false;
String? get applicationBinaryPath => stringArgDeprecated(FlutterOptions.kUseApplicationBinary);
Future<Device?> get targetedDevice async {
return findTargetDevice(includeUnsupportedDevices: applicationBinaryPath == null);
}
// Network devices need `publish-port` to be enabled because it requires mDNS.
// If the flag wasn't provided as an actual argument and it's a network device,
// change it to be enabled.
@override
Future<bool> get disablePortPublication async {
final ArgResults? localArgResults = argResults;
final Device? device = await targetedDevice;
final bool isNetworkDevice = device is IOSDevice && device.interfaceType == IOSDeviceConnectionInterface.network;
if (isNetworkDevice && localArgResults != null && !localArgResults.wasParsed('publish-port')) {
_logger.printTrace('Network device is being used. Changing `publish-port` to be enabled.');
return false;
}
return !boolArgDeprecated('publish-port');
}
@override
Future<void> validateCommand() async {
if (userIdentifier != null) {
@@ -247,7 +223,8 @@ class DriveCommand extends RunCommandBase {
if (await _fileSystem.type(testFile) != FileSystemEntityType.file) {
throwToolExit('Test file not found: $testFile');
}
final Device? device = await targetedDevice;
final String? applicationBinaryPath = stringArgDeprecated(FlutterOptions.kUseApplicationBinary);
final Device? device = await findTargetDevice(includeUnsupportedDevices: applicationBinaryPath == null);
if (device == null) {
throwToolExit(null);
}

View File

@@ -254,7 +254,7 @@ abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopment
purgePersistentCache: purgePersistentCache,
deviceVmServicePort: deviceVmservicePort,
hostVmServicePort: hostVmservicePort,
disablePortPublication: await disablePortPublication,
disablePortPublication: disablePortPublication,
ddsPort: ddsPort,
devToolsServerAddress: devToolsServerAddress,
verboseSystemLogs: boolArgDeprecated('verbose-system-logs'),

View File

@@ -275,7 +275,7 @@ Future<T> runInContext<T>(
featureFlags: featureFlags,
platform: globals.platform,
),
MDnsVmServiceDiscovery: () => MDnsVmServiceDiscovery(
MDnsObservatoryDiscovery: () => MDnsObservatoryDiscovery(
logger: globals.logger,
flutterUsage: globals.flutterUsage,
),

View File

@@ -17,7 +17,6 @@ import 'base/utils.dart';
import 'build_info.dart';
import 'devfs.dart';
import 'device_port_forwarder.dart';
import 'ios/iproxy.dart';
import 'project.dart';
import 'vmservice.dart';
@@ -918,13 +917,7 @@ class DebuggingOptions {
/// * https://github.com/dart-lang/sdk/blob/main/sdk/lib/html/doc/NATIVE_NULL_ASSERTIONS.md
final bool nativeNullAssertions;
List<String> getIOSLaunchArguments(
EnvironmentType environmentType,
String? route,
Map<String, Object?> platformArgs, {
bool ipv6 = false,
IOSDeviceConnectionInterface interfaceType = IOSDeviceConnectionInterface.none
}) {
List<String> getIOSLaunchArguments(EnvironmentType environmentType, String? route, Map<String, Object?> platformArgs) {
final String dartVmFlags = computeDartVmFlags(this);
return <String>[
if (enableDartProfiling) '--enable-dart-profiling',
@@ -961,9 +954,6 @@ class DebuggingOptions {
// Use the suggested host port.
if (environmentType == EnvironmentType.simulator && hostVmServicePort != null)
'--observatory-port=$hostVmServicePort',
// Tell the observatory to listen on all interfaces, don't restrict to the loopback.
if (interfaceType == IOSDeviceConnectionInterface.network)
'--observatory-host=${ipv6 ? '::0' : '0.0.0.0'}',
];
}

View File

@@ -9,7 +9,6 @@ import 'package:process/process.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
import '../application_package.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
@@ -22,7 +21,6 @@ import '../device.dart';
import '../device_port_forwarder.dart';
import '../globals.dart' as globals;
import '../macos/xcdevice.dart';
import '../mdns_discovery.dart';
import '../project.dart';
import '../protocol_discovery.dart';
import '../vmservice.dart';
@@ -191,6 +189,15 @@ class IOSDevice extends Device {
return majorVersionString != null ? int.tryParse(majorVersionString) ?? 0 : 0;
}
@override
bool get supportsHotReload => interfaceType == IOSDeviceConnectionInterface.usb;
@override
bool get supportsHotRestart => interfaceType == IOSDeviceConnectionInterface.usb;
@override
bool get supportsFlutterExit => interfaceType == IOSDeviceConnectionInterface.usb;
@override
final String name;
@@ -311,11 +318,7 @@ class IOSDevice extends Device {
@visibleForTesting Duration? discoveryTimeout,
}) async {
String? packageId;
if (interfaceType == IOSDeviceConnectionInterface.network &&
debuggingOptions.debuggingEnabled &&
debuggingOptions.disablePortPublication) {
throwToolExit('Cannot start app on wirelessly tethered iOS device. Try running again with the --publish-port flag');
}
if (!prebuiltApplication) {
_logger.printTrace('Building ${package.name} for $id');
@@ -350,10 +353,8 @@ class IOSDevice extends Device {
EnvironmentType.physical,
route,
platformArgs,
ipv6: ipv6,
interfaceType: interfaceType,
);
Status startAppStatus = _logger.startProgress(
final Status installStatus = _logger.startProgress(
'Installing and launching...',
);
try {
@@ -378,10 +379,9 @@ class IOSDevice extends Device {
deviceLogReader.debuggerStream = iosDeployDebugger;
}
}
// Don't port foward if debugging with a network device.
observatoryDiscovery = ProtocolDiscovery.observatory(
deviceLogReader,
portForwarder: interfaceType == IOSDeviceConnectionInterface.network ? null : portForwarder,
portForwarder: portForwarder,
hostPort: debuggingOptions.hostVmServicePort,
devicePort: debuggingOptions.deviceVmServicePort,
ipv6: ipv6,
@@ -412,59 +412,12 @@ class IOSDevice extends Device {
return LaunchResult.succeeded();
}
_logger.printTrace('Application launched on the device. Waiting for Dart VM Service url.');
final int defaultTimeout = interfaceType == IOSDeviceConnectionInterface.network ? 45 : 30;
final Timer timer = Timer(discoveryTimeout ?? Duration(seconds: defaultTimeout), () {
_logger.printError('The Dart VM Service was not discovered after $defaultTimeout seconds. This is taking much longer than expected...');
// If debugging with a wireless device and the timeout is reached, remind the
// user to allow local network permissions.
if (interfaceType == IOSDeviceConnectionInterface.network) {
_logger.printError(
'\nClick "Allow" to the prompt asking if you would like to find and connect devices on your local network. '
'This is required for wireless debugging. If you selected "Don\'t Allow", '
'you can turn it on in Settings > Your App Name > Local Network. '
"If you don't see your app in the Settings, uninstall the app and rerun to see the prompt again."
);
} else {
iosDeployDebugger?.pauseDumpBacktraceResume();
}
_logger.printTrace('Application launched on the device. Waiting for observatory url.');
final Timer timer = Timer(discoveryTimeout ?? const Duration(seconds: 30), () {
_logger.printError('iOS Observatory not discovered after 30 seconds. This is taking much longer than expected...');
iosDeployDebugger?.pauseDumpBacktraceResume();
});
Uri? localUri;
if (interfaceType == IOSDeviceConnectionInterface.network) {
// Wait for Dart VM Service to start up.
final Uri? serviceURL = await observatoryDiscovery?.uri;
if (serviceURL == null) {
await iosDeployDebugger?.stopAndDumpBacktrace();
return LaunchResult.failed();
}
// If Dart VM Service URL with the device IP is not found within 5 seconds,
// change the status message to prompt users to click Allow. Wait 5 seconds because it
// should only show this message if they have not already approved the permissions.
// MDnsVmServiceDiscovery usually takes less than 5 seconds to find it.
final Timer mDNSLookupTimer = Timer(const Duration(seconds: 5), () {
startAppStatus.stop();
startAppStatus = _logger.startProgress(
'Waiting for approval of local network permissions...',
);
});
// Get Dart VM Service URL with the device IP as the host.
localUri = await MDnsVmServiceDiscovery.instance!.getVMServiceUriForLaunch(
packageId,
this,
usesIpv6: ipv6,
deviceVmservicePort: serviceURL.port,
isNetworkDevice: true,
);
mDNSLookupTimer.cancel();
} else {
localUri = await observatoryDiscovery?.uri;
}
final Uri? localUri = await observatoryDiscovery?.uri;
timer.cancel();
if (localUri == null) {
await iosDeployDebugger?.stopAndDumpBacktrace();
@@ -476,7 +429,7 @@ class IOSDevice extends Device {
_logger.printError(e.message);
return LaunchResult.failed();
} finally {
startAppStatus.stop();
installStatus.stop();
}
}
@@ -616,6 +569,7 @@ String decodeSyslog(String line) {
}
}
@visibleForTesting
class IOSDeviceLogReader extends DeviceLogReader {
IOSDeviceLogReader._(
this._iMobileDevice,

View File

@@ -227,16 +227,8 @@ class XCDevice {
/// [timeout] defaults to 2 seconds.
Future<List<IOSDevice>> getAvailableIOSDevices({ Duration? timeout }) async {
Status? loadDevicesStatus;
if (timeout != null && timeout.inSeconds > 2) {
loadDevicesStatus = _logger.startProgress(
'Loading devices...',
);
}
final List<Object>? allAvailableDevices = await _getAllDevices(timeout: timeout ?? const Duration(seconds: 2));
if (loadDevicesStatus != null) {
loadDevicesStatus.stop();
}
if (allAvailableDevices == null) {
return const <IOSDevice>[];
}
@@ -313,6 +305,12 @@ class XCDevice {
final IOSDeviceConnectionInterface interface = _interfaceType(device);
// Only support USB devices, skip "network" interface (Xcode > Window > Devices and Simulators > Connect via network).
// TODO(jmagman): Remove this check once wirelessly detected devices can be observed and attached, https://github.com/flutter/flutter/issues/15072.
if (interface != IOSDeviceConnectionInterface.usb) {
continue;
}
String? sdkVersion = _sdkVersion(device);
if (sdkVersion != null) {

View File

@@ -13,427 +13,161 @@ import 'build_info.dart';
import 'device.dart';
import 'reporting/reporting.dart';
/// A wrapper around [MDnsClient] to find a Dart VM Service instance.
class MDnsVmServiceDiscovery {
/// Creates a new [MDnsVmServiceDiscovery] object.
/// A wrapper around [MDnsClient] to find a Dart observatory instance.
class MDnsObservatoryDiscovery {
/// Creates a new [MDnsObservatoryDiscovery] object.
///
/// The [_client] parameter will be defaulted to a new [MDnsClient] if null.
MDnsVmServiceDiscovery({
/// The [applicationId] parameter may be null, and can be used to
/// automatically select which application to use if multiple are advertising
/// Dart observatory ports.
MDnsObservatoryDiscovery({
MDnsClient? mdnsClient,
MDnsClient? preliminaryMDnsClient,
required Logger logger,
required Usage flutterUsage,
}) : _client = mdnsClient ?? MDnsClient(),
_preliminaryClient = preliminaryMDnsClient,
_logger = logger,
_flutterUsage = flutterUsage;
}): _client = mdnsClient ?? MDnsClient(),
_logger = logger,
_flutterUsage = flutterUsage;
final MDnsClient _client;
// Used when discovering VM services with `queryForAttach` to do a preliminary
// check for already running services so that results are not cached in _client.
final MDnsClient? _preliminaryClient;
final Logger _logger;
final Usage _flutterUsage;
@visibleForTesting
static const String dartVmServiceName = '_dartobservatory._tcp.local';
static const String dartObservatoryName = '_dartobservatory._tcp.local';
static MDnsVmServiceDiscovery? get instance => context.get<MDnsVmServiceDiscovery>();
static MDnsObservatoryDiscovery? get instance => context.get<MDnsObservatoryDiscovery>();
/// Executes an mDNS query for Dart VM Services.
/// Checks for services that have already been launched.
/// If none are found, it will listen for new services to become active
/// and return the first it finds that match the parameters.
/// Executes an mDNS query for a Dart Observatory.
///
/// The [applicationId] parameter may be used to specify which application
/// to find. For Android, it refers to the package name; on iOS, it refers to
/// the bundle ID.
///
/// The [deviceVmservicePort] parameter may be used to specify which port
/// to find.
/// If it is not null, this method will find the port and authentication code
/// of the Dart Observatory for that application. If it cannot find a Dart
/// Observatory matching that application identifier, it will call
/// [throwToolExit].
///
/// The [isNetworkDevice] parameter flags whether to get the device IP
/// and the [ipv6] parameter flags whether to get an iPv6 address
/// (otherwise it will get iPv4).
/// If it is null and there are multiple ports available, the user will be
/// prompted with a list of available observatory ports and asked to select
/// one.
///
/// The [timeout] parameter determines how long to continue to wait for
/// services to become active.
///
/// If [applicationId] is not null, this method will find the port and authentication code
/// of the Dart VM Service for that application. If it cannot find a service matching
/// that application identifier after the [timeout], it will call [throwToolExit].
///
/// If [applicationId] is null and there are multiple Dart VM Services available,
/// the user will be prompted with a list of available services with the respective
/// app-id and device-vmservice-port to use and asked to select one.
///
/// If it is null and there is only one available or it's the first found instance
/// of Dart VM Service, it will return that instance's information regardless of
/// what application the service instance is for.
/// If it is null and there is only one available instance of Observatory,
/// it will return that instance's information regardless of what application
/// the Observatory instance is for.
@visibleForTesting
Future<MDnsVmServiceDiscoveryResult?> queryForAttach({
String? applicationId,
int? deviceVmservicePort,
bool ipv6 = false,
bool isNetworkDevice = false,
Duration timeout = const Duration(minutes: 10),
}) async {
// Poll for 5 seconds to see if there are already services running.
// Use a new instance of MDnsClient so results don't get cached in _client.
// If no results are found, poll for a longer duration to wait for connections.
// If more than 1 result is found, throw an error since it can't be determined which to pick.
// If only one is found, return it.
final List<MDnsVmServiceDiscoveryResult> results = await _pollingVmService(
_preliminaryClient ?? MDnsClient(),
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
ipv6: ipv6,
isNetworkDevice: isNetworkDevice,
timeout: const Duration(seconds: 5),
);
if (results.isEmpty) {
return firstMatchingVmService(
_client,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
ipv6: ipv6,
isNetworkDevice: isNetworkDevice,
timeout: timeout,
);
} else if (results.length > 1) {
final StringBuffer buffer = StringBuffer();
buffer.writeln('There are multiple Dart VM Services available.');
buffer.writeln('Rerun this command with one of the following passed in as the app-id and device-vmservice-port:');
buffer.writeln();
for (final MDnsVmServiceDiscoveryResult result in results) {
buffer.writeln(
' flutter attach --app-id "${result.domainName.replaceAll('.$dartVmServiceName', '')}" --device-vmservice-port ${result.port}');
}
throwToolExit(buffer.toString());
}
return results.first;
}
/// Executes an mDNS query for Dart VM Services.
/// Listens for new services to become active and returns the first it finds that
/// match the parameters.
///
/// The [applicationId] parameter must be set to specify which application
/// to find. For Android, it refers to the package name; on iOS, it refers to
/// the bundle ID.
///
/// The [deviceVmservicePort] parameter must be set to specify which port
/// to find.
///
/// [applicationId] and [deviceVmservicePort] are required for launch so that
/// if multiple flutter apps are running on different devices, it will
/// only match with the device running the desired app.
///
/// The [isNetworkDevice] parameter flags whether to get the device IP
/// and the [ipv6] parameter flags whether to get an iPv6 address
/// (otherwise it will get iPv4).
///
/// The [timeout] parameter determines how long to continue to wait for
/// services to become active.
///
/// If a Dart VM Service matching the [applicationId] and [deviceVmservicePort]
/// cannot be found after the [timeout], it will call [throwToolExit].
@visibleForTesting
Future<MDnsVmServiceDiscoveryResult?> queryForLaunch({
required String applicationId,
required int deviceVmservicePort,
bool ipv6 = false,
bool isNetworkDevice = false,
Duration timeout = const Duration(minutes: 10),
}) async {
// Query for a specific application and device port.
return firstMatchingVmService(
_client,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
ipv6: ipv6,
isNetworkDevice: isNetworkDevice,
timeout: timeout,
);
}
/// Polls for Dart VM Services and returns the first it finds that match
/// the [applicationId]/[deviceVmservicePort] (if applicable).
/// Returns null if no results are found.
@visibleForTesting
Future<MDnsVmServiceDiscoveryResult?> firstMatchingVmService(
MDnsClient client, {
String? applicationId,
int? deviceVmservicePort,
bool ipv6 = false,
bool isNetworkDevice = false,
Duration timeout = const Duration(minutes: 10),
}) async {
final List<MDnsVmServiceDiscoveryResult> results = await _pollingVmService(
client,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
ipv6: ipv6,
isNetworkDevice: isNetworkDevice,
timeout: timeout,
quitOnFind: true,
);
if (results.isEmpty) {
return null;
}
return results.first;
}
Future<List<MDnsVmServiceDiscoveryResult>> _pollingVmService(
MDnsClient client, {
String? applicationId,
int? deviceVmservicePort,
bool ipv6 = false,
bool isNetworkDevice = false,
required Duration timeout,
bool quitOnFind = false,
}) async {
_logger.printTrace('Checking for advertised Dart VM Services...');
Future<MDnsObservatoryDiscoveryResult?> query({String? applicationId, int? deviceVmservicePort}) async {
_logger.printTrace('Checking for advertised Dart observatories...');
try {
await client.start();
await _client.start();
final List<PtrResourceRecord> pointerRecords = await _client
.lookup<PtrResourceRecord>(
ResourceRecordQuery.serverPointer(dartObservatoryName),
)
.toList();
if (pointerRecords.isEmpty) {
_logger.printTrace('No pointer records found.');
return null;
}
// We have no guarantee that we won't get multiple hits from the same
// service on this.
final Set<String> uniqueDomainNames = pointerRecords
.map<String>((PtrResourceRecord record) => record.domainName)
.toSet();
final List<MDnsVmServiceDiscoveryResult> results =
<MDnsVmServiceDiscoveryResult>[];
final Set<String> uniqueDomainNames = <String>{};
// Listen for mDNS connections until timeout.
final Stream<PtrResourceRecord> ptrResourceStream = client.lookup<PtrResourceRecord>(
ResourceRecordQuery.serverPointer(dartVmServiceName),
timeout: timeout
);
await for (final PtrResourceRecord ptr in ptrResourceStream) {
uniqueDomainNames.add(ptr.domainName);
String? domainName;
if (applicationId != null) {
// If applicationId is set, only use records that match it
if (ptr.domainName.toLowerCase().startsWith(applicationId.toLowerCase())) {
domainName = ptr.domainName;
} else {
continue;
}
} else {
domainName = ptr.domainName;
}
_logger.printTrace('Checking for available port on $domainName');
final List<SrvResourceRecord> srvRecords = await client
.lookup<SrvResourceRecord>(
ResourceRecordQuery.service(domainName),
)
.toList();
if (srvRecords.isEmpty) {
continue;
}
// If more than one SrvResourceRecord found, it should just be a duplicate.
final SrvResourceRecord srvRecord = srvRecords.first;
if (srvRecords.length > 1) {
_logger.printWarning(
'Unexpectedly found more than one Dart VM Service report for $domainName '
'- using first one (${srvRecord.port}).');
}
// If deviceVmservicePort is set, only use records that match it
if (deviceVmservicePort != null && srvRecord.port != deviceVmservicePort) {
continue;
}
// Get the IP address of the service if using a network device.
InternetAddress? ipAddress;
if (isNetworkDevice) {
List<IPAddressResourceRecord> ipAddresses = await client
.lookup<IPAddressResourceRecord>(
ipv6
? ResourceRecordQuery.addressIPv6(srvRecord.target)
: ResourceRecordQuery.addressIPv4(srvRecord.target),
)
.toList();
if (ipAddresses.isEmpty) {
throwToolExit('Did not find IP for service ${srvRecord.target}.');
}
// Filter out link-local addresses.
if (ipAddresses.length > 1) {
ipAddresses = ipAddresses.where((IPAddressResourceRecord element) => !element.address.isLinkLocal).toList();
}
ipAddress = ipAddresses.first.address;
if (ipAddresses.length > 1) {
_logger.printWarning(
'Unexpectedly found more than one IP for Dart VM Service ${srvRecord.target} '
'- using first one ($ipAddress).');
}
}
_logger.printTrace('Checking for authentication code for $domainName');
final List<TxtResourceRecord> txt = await client
.lookup<TxtResourceRecord>(
ResourceRecordQuery.text(domainName),
)
.toList();
if (txt == null || txt.isEmpty) {
results.add(MDnsVmServiceDiscoveryResult(domainName, srvRecord.port, ''));
if (quitOnFind) {
return results;
}
continue;
}
const String authCodePrefix = 'authCode=';
String? raw;
for (final String record in txt.first.text.split('\n')) {
if (record.startsWith(authCodePrefix)) {
raw = record;
String? domainName;
if (applicationId != null) {
for (final String name in uniqueDomainNames) {
if (name.toLowerCase().startsWith(applicationId.toLowerCase())) {
domainName = name;
break;
}
}
if (raw == null) {
results.add(MDnsVmServiceDiscoveryResult(domainName, srvRecord.port, ''));
if (quitOnFind) {
return results;
}
continue;
if (domainName == null) {
throwToolExit('Did not find a observatory port advertised for $applicationId.');
}
String authCode = raw.substring(authCodePrefix.length);
// The Dart VM Service currently expects a trailing '/' as part of the
// URI, otherwise an invalid authentication code response is given.
if (!authCode.endsWith('/')) {
authCode += '/';
} else if (uniqueDomainNames.length > 1) {
final StringBuffer buffer = StringBuffer();
buffer.writeln('There are multiple observatory ports available.');
buffer.writeln('Rerun this command with one of the following passed in as the appId:');
buffer.writeln();
for (final String uniqueDomainName in uniqueDomainNames) {
buffer.writeln(' flutter attach --app-id ${uniqueDomainName.replaceAll('.$dartObservatoryName', '')}');
}
results.add(MDnsVmServiceDiscoveryResult(
domainName,
srvRecord.port,
authCode,
ipAddress: ipAddress
));
if (quitOnFind) {
return results;
throwToolExit(buffer.toString());
} else {
domainName = pointerRecords[0].domainName;
}
_logger.printTrace('Checking for available port on $domainName');
// Here, if we get more than one, it should just be a duplicate.
final List<SrvResourceRecord> srv = await _client
.lookup<SrvResourceRecord>(
ResourceRecordQuery.service(domainName),
)
.toList();
if (srv.isEmpty) {
return null;
}
if (srv.length > 1) {
_logger.printWarning('Unexpectedly found more than one observatory report for $domainName '
'- using first one (${srv.first.port}).');
}
_logger.printTrace('Checking for authentication code for $domainName');
final List<TxtResourceRecord> txt = await _client
.lookup<TxtResourceRecord>(
ResourceRecordQuery.text(domainName),
)
.toList();
if (txt == null || txt.isEmpty) {
return MDnsObservatoryDiscoveryResult(srv.first.port, '');
}
const String authCodePrefix = 'authCode=';
String? raw;
for (final String record in txt.first.text.split('\n')) {
if (record.startsWith(authCodePrefix)) {
raw = record;
break;
}
}
// If applicationId is set and quitOnFind is true and no results matching
// 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';
}
throwToolExit('$message.');
if (raw == null) {
return MDnsObservatoryDiscoveryResult(srv.first.port, '');
}
return results;
String authCode = raw.substring(authCodePrefix.length);
// The Observatory currently expects a trailing '/' as part of the
// URI, otherwise an invalid authentication code response is given.
if (!authCode.endsWith('/')) {
authCode += '/';
}
return MDnsObservatoryDiscoveryResult(srv.first.port, authCode);
} finally {
client.stop();
_client.stop();
}
}
/// Gets Dart VM Service Uri for `flutter attach`.
/// Executes an mDNS query and waits until a Dart VM Service is found.
///
/// Differs from `getVMServiceUriForLaunch` because it can search for any available Dart VM Service.
/// Since [applicationId] and [deviceVmservicePort] are optional, it can either look for any service
/// or a specific service matching [applicationId]/[deviceVmservicePort].
/// It may find more than one service, which will throw an error listing the found services.
Future<Uri?> getVMServiceUriForAttach(
String? applicationId,
Device device, {
Future<Uri?> getObservatoryUri(String? applicationId, Device device, {
bool usesIpv6 = false,
int? hostVmservicePort,
int? deviceVmservicePort,
bool isNetworkDevice = false,
Duration timeout = const Duration(minutes: 10),
}) async {
final MDnsVmServiceDiscoveryResult? result = await queryForAttach(
final MDnsObservatoryDiscoveryResult? result = await query(
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
ipv6: usesIpv6,
isNetworkDevice: isNetworkDevice,
timeout: timeout,
);
return _handleResult(
result,
device,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
hostVmservicePort: hostVmservicePort,
usesIpv6: usesIpv6,
isNetworkDevice: isNetworkDevice
);
}
/// Gets Dart VM Service Uri for `flutter run`.
/// Executes an mDNS query and waits until the Dart VM Service service is found.
///
/// Differs from `getVMServiceUriForAttach` because it only searches for a specific service.
/// This is enforced by [applicationId] and [deviceVmservicePort] being required.
Future<Uri?> getVMServiceUriForLaunch(
String applicationId,
Device device, {
bool usesIpv6 = false,
int? hostVmservicePort,
required int deviceVmservicePort,
bool isNetworkDevice = false,
Duration timeout = const Duration(minutes: 10),
}) async {
final MDnsVmServiceDiscoveryResult? result = await queryForLaunch(
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
ipv6: usesIpv6,
isNetworkDevice: isNetworkDevice,
timeout: timeout,
);
return _handleResult(
result,
device,
applicationId: applicationId,
deviceVmservicePort: deviceVmservicePort,
hostVmservicePort: hostVmservicePort,
usesIpv6: usesIpv6,
isNetworkDevice: isNetworkDevice
);
}
Future<Uri?> _handleResult(
MDnsVmServiceDiscoveryResult? result,
Device device, {
String? applicationId,
int? deviceVmservicePort,
int? hostVmservicePort,
bool usesIpv6 = false,
bool isNetworkDevice = false,
}) async {
if (result == null) {
await _checkForIPv4LinkLocal(device);
return null;
}
final String host;
final InternetAddress? ipAddress = result.ipAddress;
if (isNetworkDevice && ipAddress != null) {
host = ipAddress.address;
} else {
host = usesIpv6
final String host = usesIpv6
? InternetAddress.loopbackIPv6.address
: InternetAddress.loopbackIPv4.address;
}
return buildVMServiceUri(
return buildObservatoryUri(
device,
host,
result.port,
hostVmservicePort,
result.authCode,
isNetworkDevice,
);
}
@@ -502,26 +236,18 @@ class MDnsVmServiceDiscovery {
}
}
class MDnsVmServiceDiscoveryResult {
MDnsVmServiceDiscoveryResult(
this.domainName,
this.port,
this.authCode, {
this.ipAddress
});
final String domainName;
class MDnsObservatoryDiscoveryResult {
MDnsObservatoryDiscoveryResult(this.port, this.authCode);
final int port;
final String authCode;
final InternetAddress? ipAddress;
}
Future<Uri> buildVMServiceUri(
Future<Uri> buildObservatoryUri(
Device device,
String host,
int devicePort, [
int? hostVmservicePort,
String? authCode,
bool isNetworkDevice = false,
]) async {
String path = '/';
if (authCode != null) {
@@ -533,16 +259,8 @@ Future<Uri> buildVMServiceUri(
path += '/';
}
hostVmservicePort ??= 0;
final int? actualHostPort;
if (isNetworkDevice) {
// When debugging with a network device, port forwarding is not required
// so just use the device's port.
actualHostPort = devicePort;
} else {
actualHostPort = hostVmservicePort == 0 ?
final int? actualHostPort = hostVmservicePort == 0 ?
await device.portForwarder?.forward(devicePort) :
hostVmservicePort;
}
return Uri(scheme: 'http', host: host, port: actualHostPort, path: path);
}

View File

@@ -569,7 +569,7 @@ abstract class FlutterCommand extends Command<void> {
);
}
Future<bool> get disablePortPublication async => !boolArgDeprecated('publish-port');
bool get disablePortPublication => !boolArgDeprecated('publish-port');
void usesIpv6Flag({required bool verboseHelp}) {
argParser.addFlag(ipv6Flag,