Files
swiftcontrol/lib/services/debug_diagnostics.dart
Jonas Acker 7546f50485 Network diagnostics: tell BikeControl's own mDNS scans apart by service type
Support bundle: the query log is now read before the bundle's own discovery
scan. On a host with many network adapters that scan logs one copy per
interface and evicted everything the trainer app had asked before the bundle
was taken, leaving only our own scan in the report. Queries attributable to
our own scans (every question about a type we were browsing, from this
device's addresses) are summarised in one count line instead of listed.

Live connection test: own scans are tracked per service type. The Wi-Fi
trainer scan browses only the Wahoo type for as long as Bluetooth scans, and
the watch discarded every same-host query meanwhile, so a trainer app on the
same machine looking for OpenBikeControl could never be seen and the result
was always inconclusive. Now only questions about a type we were browsing are
discarded; the rest of the same packet still counts, and an own browse only
excuses silence when it covers a type the watch looks for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:50:57 +01:00

428 lines
18 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:bike_control/bluetooth/devices/openbikecontrol/obp_mdns_backend.dart';
import 'package:bike_control/main.dart' show recordError;
import 'package:bike_control/services/local_network_access.dart';
import 'package:bike_control/services/mdns_discovery_scan.dart';
import 'package:bike_control/services/mdns_query_privacy.dart';
import 'package:bike_control/services/network_recovery.dart';
import 'package:bike_control/utils/core.dart';
import 'package:flutter/foundation.dart';
import 'package:local_network_permission/local_network_permission.dart';
import 'package:prop/mdns/mdns_responder.dart' show MdnsQueryLogEntry;
import 'package:prop/mdns/dnssd_service_advertiser.dart';
import 'package:prop/mdns/service_advertiser.dart';
import 'package:prop/utils/advertised_service_registry.dart';
import 'package:prop/utils/network_address.dart';
import 'package:prop/utils/resilient_tcp_server.dart';
// Part of PermissionsSnapshot's surface — callers shouldn't need a second
// import to name the value they just read.
export 'package:local_network_permission/local_network_permission.dart' show LocalNetworkStatus;
/// A running TCP bridge server, for diagnostics.
class TcpServerInfo {
final String? label;
final int? port;
final bool listening;
final bool hasClient;
const TcpServerInfo({
required this.label,
required this.port,
required this.listening,
required this.hasClient,
});
}
/// Status of the permissions whose denial silently breaks WiFi/BLE bridging.
class PermissionsSnapshot {
/// Apple's Local Network permission, measured with a Bonjour round trip.
/// Null on the platforms that have no such permission.
final LocalNetworkStatus? localNetwork;
const PermissionsSnapshot({
required this.localNetwork,
});
/// [probe] runs a live check; a support bundle is worthless if it reports
/// what the UI happened to cache half an hour ago.
///
/// It must stay off for the crash handler, though: probing is what raises
/// the system prompt, so a background error would otherwise pop a Local
/// Network dialog at an arbitrary moment — including app launch, before
/// onboarding has explained anything. Without it, report what is already
/// known, or nothing.
static Future<PermissionsSnapshot> gather({required bool probe}) async {
if (!LocalNetworkPermission.isSupported) {
return const PermissionsSnapshot(localNetwork: null);
}
return PermissionsSnapshot(
localNetwork: probe ? await LocalNetworkAccess.status(force: true) : LocalNetworkAccess.cached,
);
}
}
/// The full diagnostics snapshot shown on the Logs page and embedded in
/// [debugText]. Build with [gather]; render with [toText].
class DebugDiagnostics {
final List<AdvertisedRecord> advertised;
final String backend;
final String? hostLabel;
final bool holdsMulticastLock;
final List<DiscoveredMdnsService> discovered;
final bool discoveryRan;
final AddressPickReport addressReport;
final List<TcpServerInfo> servers;
final PermissionsSnapshot permissions;
/// mDNS queries our responder saw. Empty on the nsd backend (iOS), where the
/// OS responder handles queries and never tells us about them.
final List<MdnsQueryLogEntry> recentQueries;
/// What clients did on our TCP ports lately: who connected, and whether
/// they hung up before sending anything.
final List<TcpConnectionLogEntry> connections;
/// When the app last left and returned, whether the process stood still
/// and what was repaired afterwards. Empty where that is not tracked.
final List<String> lifecycle;
/// Host name OpenBikeControl is published under when it goes out through
/// the operating system's responder instead of [backend]. Null when it
/// shares [backend] or is not running.
final String? obcOsResponderHost;
const DebugDiagnostics({
required this.advertised,
required this.backend,
required this.hostLabel,
required this.holdsMulticastLock,
required this.discovered,
required this.discoveryRan,
required this.addressReport,
required this.servers,
required this.permissions,
this.recentQueries = const [],
this.connections = const [],
this.lifecycle = const [],
this.obcOsResponderHost,
});
static Future<DebugDiagnostics> gather({
bool includeDiscovery = true,
Duration discoveryTimeout = const Duration(seconds: 4),
}) async {
final advertiser = ServiceAdvertiser.instance;
final isResponder = advertiser is ResponderServiceAdvertiser;
AddressPickReport addressReport;
try {
addressReport = await AdvertisedAddressPicker.report();
} catch (e, s) {
recordError(e, s, context: 'DebugDiagnostics.address');
addressReport = const AddressPickReport(chosen: null, candidates: []);
}
final servers = ResilientTcpServer.activeServers
.map(
(s) => TcpServerInfo(
label: s.label,
port: s.isRunning ? s.boundPort : null,
listening: s.isRunning,
hasClient: s.hasClient,
),
)
.toList();
final (:queries, :discovered) = await readQueriesThenDiscover(
readQueries: () => isResponder ? advertiser.recentQueries : const [],
discover: includeDiscovery && !kIsWeb ? () => MdnsDiscoveryScan().run(timeout: discoveryTimeout) : null,
);
// includeDiscovery is the existing "may do live network work" seam — the
// crash handler passes false. The permission probe belongs to it.
final permissions = await PermissionsSnapshot.gather(probe: includeDiscovery);
return DebugDiagnostics(
advertised: AdvertisedServiceRegistry.instance.records,
backend: switch (advertiser) {
ResponderServiceAdvertiser() => 'responder',
// No host label while registered means the native bridge refused
// the host and the services went out through nsd instead.
DnsSdServiceAdvertiser(:final hostLabel) =>
hostLabel != null || AdvertisedServiceRegistry.instance.records.isEmpty ? 'dnssd' : 'dnssd→nsd',
_ => 'nsd',
},
hostLabel: switch (advertiser) {
ResponderServiceAdvertiser(:final hostLabel) || DnsSdServiceAdvertiser(:final hostLabel) => hostLabel,
_ => null,
},
holdsMulticastLock: isResponder ? advertiser.holdsMulticastLock : false,
discovered: discovered ?? const [],
discoveryRan: discovered != null,
addressReport: addressReport,
servers: servers,
permissions: permissions,
recentQueries: queries,
connections: ResilientTcpServer.connectionLog,
lifecycle: NetworkRecovery.instance.diagnosticLines(),
obcOsResponderHost: _obcOsResponderHost(),
);
}
/// Reads the mDNS query log, THEN runs the bundle's own discovery scan.
///
/// The order is the point. The scan queries from this device's addresses
/// once per interface, and on a host with many adapters (a Windows PC with a
/// stack of VirtualBox/VMware host-only ones) a single scan wrote enough
/// entries to evict everything the trainer app had asked before the bundle
/// was taken — the bundle then showed only our own scan. [discover] null
/// skips the scan; a scan that fails leaves `discovered` null.
@visibleForTesting
static Future<({List<MdnsQueryLogEntry> queries, List<DiscoveredMdnsService>? discovered})> readQueriesThenDiscover({
required List<MdnsQueryLogEntry> Function() readQueries,
required Future<List<DiscoveredMdnsService>> Function()? discover,
}) async {
final queries = readQueries();
List<DiscoveredMdnsService>? discovered;
if (discover != null) {
try {
discovered = await discover();
} catch (e, s) {
recordError(e, s, context: 'DebugDiagnostics.discovery');
}
}
return (queries: queries, discovered: discovered);
}
static String? _obcOsResponderHost() {
final emulator = core.obpMdnsEmulator;
if (!emulator.isStarted.value || emulator.activeBackend != ObpMdnsBackend.osResponder) return null;
return emulator.advertisedHostname ?? '?';
}
/// Name fragments that mean "VPN tunnel" — the VPN subset of the address
/// picker's broader "virtual" set, which also covers docker bridges, the
/// Personal Hotspot bridge and cellular interfaces (none of them a VPN).
///
/// Matched case-insensitively, and partly as a substring, because on Windows
/// `NetworkInterface.name` is the adapter's FriendlyName ("NordLynx",
/// "ProtonVPN TUN", "TAP-Windows Adapter V9") rather than a unix device
/// name, so prefix matching alone would miss nearly every Windows VPN.
static final _tunnelNamePattern = RegExp(
r'^(utun|tun|tap|ipsec|ppp|wg|nordlynx|zt)'
r'|wireguard|openvpn|tailscale|zerotier|mullvad|proton|anyconnect|vpn|tunnel',
caseSensitive: false,
);
/// Mobile-data interfaces: iOS `pdp_ip`, Android `rmnet`/`ccmni` and the
/// 464XLAT `v4-`/`clat` ones. An address on one of them is the carrier's, and
/// no device on the rider's Wi-Fi can reach it.
static final cellularNamePattern = RegExp(r'^(pdp_ip|rmnet|ccmni|v4-|clat)', caseSensitive: false);
/// 169.254/16 is link-local and 192.0.0/24 is the 464XLAT CLAT dummy range;
/// neither is ever a VPN, and both show up on healthy devices.
static bool _isRoutable(String address) =>
!address.startsWith('169.254.') && !address.startsWith('192.0.0.');
/// 100.64/10, the CGNAT range mesh VPNs (Tailscale, ZeroTier) hand out.
static bool _isCgnat(String address) {
final parts = address.split('.').map(int.tryParse).toList();
if (parts.length != 4 || parts.any((p) => p == null)) return false;
return parts[0] == 100 && parts[1]! >= 64 && parts[1]! <= 127;
}
/// Tunnel interfaces that carry a real IPv4 — i.e. the ones a VPN actually
/// brought up.
///
/// Apple platforms always keep several idle `utun` devices around (iCloud
/// Private Relay, Continuity, Wi-Fi Calling, content filters). Those carry
/// only an IPv6 link-local, so they never become an [AddressCandidate] in
/// the first place — which is what stops this from firing on every iPhone.
List<AddressCandidate> get tunnelCandidates => tunnelCandidatesIn(addressReport.candidates);
/// [tunnelCandidates] over a bare picker report, for callers that have one
/// without a full snapshot — the home card re-reads the address on its own,
/// and must apply the same rule the self-test does.
///
/// A tunnel on the very address of a cellular interface is the carrier's own
/// IMS / Wi-Fi-calling tunnel (iOS `ipsec` next to `pdp_ip`), not a VPN — a
/// user VPN always gets a tunnel address of its own.
static List<AddressCandidate> tunnelCandidatesIn(List<AddressCandidate> candidates) {
final cellular = candidates
.where((c) => cellularNamePattern.hasMatch(c.interfaceName))
.map((c) => c.address)
.toSet();
return candidates
.where(
(c) =>
_tunnelNamePattern.hasMatch(c.interfaceName) && _isRoutable(c.address) && !cellular.contains(c.address),
)
.toList();
}
String _txt(Map<String, String> txt) {
final entries = txt.entries.toList()..sort((a, b) => a.key.compareTo(b.key));
return entries.map((e) => '${e.key}=${e.value}').join(', ');
}
String toText() {
final b = StringBuffer();
b.writeln('Diagnostics:');
b.writeln(' Advertised by this device:');
if (advertised.isEmpty) {
b.writeln(' (none)');
} else {
for (final a in advertised) {
b.writeln(' ${a.type} "${a.name}" ${a.address}:${a.port}');
if (a.txt.isNotEmpty) b.writeln(' txt: ${_txt(a.txt)}');
}
}
b.writeln(
' backend: $backend'
'${hostLabel != null ? ' · host: $hostLabel.local' : ''}'
'${backend == 'responder' ? ' · multicast-lock: ${holdsMulticastLock ? 'held' : 'not held'}' : ''}',
);
if (obcOsResponderHost != null) {
b.writeln(' _openbikecontrol._tcp: OS responder · host: $obcOsResponderHost');
}
b.writeln(' Discovered on network:');
if (!discoveryRan) {
b.writeln(' (skipped)');
} else if (discovered.isEmpty) {
b.writeln(' (none found)');
} else {
for (final d in discovered) {
b.writeln(' ${d.type} "${d.name}" ${d.host}:${d.port}${d.isSelf ? ' (this device)' : ''}');
if (d.txt.isNotEmpty) b.writeln(' txt: ${_txt(d.txt)}');
}
}
b.writeln(' Network interfaces (advertised = ${addressReport.chosen?.address ?? 'none'}):');
for (final c in addressReport.candidates) {
final tags = [
if (addressReport.chosen?.address == c.address) 'advertised',
if (c.isVirtual) 'virtual',
];
b.writeln(' ${c.interfaceName}/${c.address} = ${c.score}${tags.isEmpty ? '' : ' (${tags.join(', ')})'}');
}
// Its own line, spelled "VPN", because support reads this block at a
// glance and a "(virtual)" suffix on one of five interface rows does not
// survive that. A live VPN leaves mDNS working (multicast is not tunnelled)
// while blackholing the inbound TCP connection, so the rest of the block
// looks perfectly healthy — advertised, discovered, listening, no client.
final tunnels = tunnelCandidates;
if (tunnels.isEmpty) {
b.writeln(' VPN: none detected');
} else {
// Mesh VPNs route only their own overlay and leave the LAN path alone,
// so they are almost never why a trainer app cannot connect.
final meshOnly = tunnels.every((c) => _isCgnat(c.address));
b.writeln(
' VPN: likely active — ${tunnels.map((c) => '${c.interfaceName}/${c.address}').join(', ')}'
'${meshOnly ? ' (mesh/CGNAT range — usually harmless)' : ' (a full-tunnel VPN blocks inbound LAN connections — try turning it off)'}',
);
}
// "Did the trainer app on this machine ask us anything, and did we answer?"
// A same-host querier shows up with one of this host's addresses as its
// source. No entries at all means the failure is upstream of this
// responder (the app never browsed — Bonjour missing, firewall, VPN DNS);
// a browse and resolve answered followed by `A <host>.local` asked over
// and over is the Windows same-host resolution failure.
b.writeln(' mDNS queries received:');
if (recentQueries.isEmpty) {
b.writeln(' (none)');
} else {
// BikeControl's own scans (the Wi-Fi trainer scan, a discovery scan)
// query from this device's addresses exactly like a same-host trainer
// app, once per interface. Listed, they drowned the trainer app's lines
// and read as the trainer app asking; one count line is enough to show
// they happened. Only entries whose every question is about a type we
// were browsing qualify — the trainer app asking for anything else
// meanwhile stays listed.
final ownAddresses = {
'127.0.0.1',
...addressReport.candidates.map((c) => c.address),
...advertised.map((a) => a.address),
};
bool isOwnScan(MdnsQueryLogEntry q) =>
q.isOwnScanQuery && (q.fromThisHost || ownAddresses.contains(q.source));
final ownScan = recentQueries.where(isOwnScan).toList();
// Support bundles leave the device, so third-party hostnames/IPs a
// neighbouring device's browse happened to log are not ours to send —
// only queries naming something BikeControl itself advertises are
// listed verbatim; the rest is summarised as counts, no identifiers.
final relevant = relevantMdnsQueries(
recentQueries.where((q) => !isOwnScan(q)).toList(),
advertised: advertised,
hostLabel: hostLabel,
);
for (final q in relevant.kept) {
final at = q.at.toIso8601String().split('T').last.split('.').first;
// Repeats are folded; the count keeps a continuous poller visible as
// one line instead of hiding that it fired hundreds of times.
final repeats = q.count > 1 ? ' ×${q.count}' : '';
// A kept entry can still bundle third-party questions in the same
// packet (a real browser like an Apple TV asks for several services,
// or an unrelated host, in one query) — show only ours.
final shown = ourQuestions(q, advertised: advertised, hostLabel: hostLabel);
final hidden = q.questions.length - shown.length;
final hiddenNote = hidden > 0 ? ' (+$hidden other questions)' : '';
b.writeln(
' $at ${q.source}:${q.sourcePort} ${q.wantsUnicast ? 'QU' : 'QM'} '
'${shown.join(', ')}$hiddenNote → ${q.reply}$repeats',
);
}
if (ownScan.isNotEmpty) {
final count = ownScan.fold(0, (sum, q) => sum + q.count);
final addresses = {for (final q in ownScan) ...q.sources}.length;
b.writeln(' (own scan: $count queries from $addresses local addresses, not listed)');
}
if (relevant.droppedQueries > 0) {
b.writeln(' (+${relevant.droppedQueries} unrelated queries from ${relevant.droppedHosts} hosts, not listed)');
}
}
b.writeln(' TCP servers:');
if (servers.isEmpty) {
b.writeln(' (none)');
} else {
for (final s in servers) {
b.writeln(
' ${s.label ?? 'tcp'} :${s.port ?? '-'} '
'${s.listening ? 'listening' : 'down'} · ${s.hasClient ? '1 client' : 'no client'}',
);
}
}
// Without this a "no client" row cannot tell an app that never dialled
// from one that connected and hung up at once.
b.writeln(' TCP connections:');
if (connections.isEmpty) {
b.writeln(' (none since the app started)');
} else {
for (final c in connections) {
b.writeln(' ${c.at.toIso8601String().split('T').last.split('.').first} $c');
}
}
if (lifecycle.isNotEmpty) {
b.writeln(' Lifecycle:');
for (final line in lifecycle) {
b.writeln(' $line');
}
}
final localNetwork = permissions.localNetwork;
if (localNetwork != null) {
b.writeln(' Permissions: local-network=${localNetwork.name}');
}
return b.toString().trimRight();
}
}