LAN discovery: server advertises _pipelines._tcp over mDNS; app finds servers on the connect screen
Server: internal/discovery publishes a DNS-SD record (hashicorp/mdns) with the port LAN clients dial (the web proxy via -mdns-port, which the supervisor passes, or a non-loopback -addr) and TXT v, name, path, tls, auth. On by default; -mdns=false or PIPELINES_MDNS=off disables it. Failures are logged and never block startup; the advert is withdrawn on shutdown. App: the Connect to Pipelines screen gets 'Find servers on this network' behind a ServerDiscovery interface (Bonsoir: Android NSD with multicast lock, iOS Bonjour with NSLocalNetworkUsageDescription and NSBonjourServices). Tapping a server fills the address and connects; manual entry stays. Web has no scan.
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:bonsoir/bonsoir.dart';
|
||||
|
||||
import 'discovered_server.dart';
|
||||
import 'server_discovery.dart';
|
||||
|
||||
/// DNS-SD browsing through the platform service: Android NSD (Bonsoir holds
|
||||
/// the Wi-Fi multicast lock while browsing) and Apple's Network framework
|
||||
/// (needs NSLocalNetworkUsageDescription and NSBonjourServices).
|
||||
class BonsoirServerDiscovery implements ServerDiscovery {
|
||||
BonsoirServerDiscovery({this.type = pipelinesServiceType});
|
||||
|
||||
final String type;
|
||||
|
||||
@override
|
||||
Stream<List<DiscoveredServer>> scan() {
|
||||
late final StreamController<List<DiscoveredServer>> controller;
|
||||
BonsoirDiscovery? discovery;
|
||||
StreamSubscription<BonsoirDiscoveryEvent>? events;
|
||||
final found = <String, DiscoveredServer>{};
|
||||
|
||||
void publish() {
|
||||
if (!controller.isClosed) controller.add(found.values.toList());
|
||||
}
|
||||
|
||||
Future<void> start() async {
|
||||
try {
|
||||
final browser = BonsoirDiscovery(type: type);
|
||||
discovery = browser;
|
||||
await browser.initialize();
|
||||
if (controller.isClosed) return;
|
||||
events = browser.eventStream?.listen(
|
||||
(event) {
|
||||
switch (event) {
|
||||
case BonsoirDiscoveryServiceFoundEvent(:final service):
|
||||
unawaited(service.resolve(browser.serviceResolver));
|
||||
case BonsoirDiscoveryServiceResolvedEvent(:final service) ||
|
||||
BonsoirDiscoveryServiceUpdatedEvent(:final service):
|
||||
final server = DiscoveredServer.fromRecord(
|
||||
instance: service.name,
|
||||
addresses: service.hostAddresses,
|
||||
hostname: service.hostname,
|
||||
port: service.port,
|
||||
attributes: service.attributes,
|
||||
);
|
||||
if (server != null) {
|
||||
found[service.name] = server;
|
||||
publish();
|
||||
}
|
||||
case BonsoirDiscoveryServiceLostEvent(:final service):
|
||||
if (found.remove(service.name) != null) publish();
|
||||
default:
|
||||
break;
|
||||
}
|
||||
},
|
||||
onError: (Object error) {
|
||||
if (!controller.isClosed) controller.addError(error);
|
||||
},
|
||||
);
|
||||
await browser.start();
|
||||
publish();
|
||||
} catch (error, stack) {
|
||||
if (!controller.isClosed) controller.addError(error, stack);
|
||||
}
|
||||
}
|
||||
|
||||
controller = StreamController<List<DiscoveredServer>>(
|
||||
onListen: () => unawaited(start()),
|
||||
onCancel: () async {
|
||||
await events?.cancel();
|
||||
final browser = discovery;
|
||||
if (browser != null && !browser.isStopped) {
|
||||
try {
|
||||
await browser.stop();
|
||||
} catch (_) {
|
||||
// Already stopped by the platform; nothing else to release.
|
||||
}
|
||||
}
|
||||
await controller.close();
|
||||
},
|
||||
);
|
||||
return controller.stream;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/// The DNS-SD service type the server advertises (internal/discovery).
|
||||
const pipelinesServiceType = '_pipelines._tcp';
|
||||
|
||||
/// A Pipelines server found on the local network.
|
||||
class DiscoveredServer {
|
||||
const DiscoveredServer({
|
||||
required this.name,
|
||||
required this.host,
|
||||
required this.port,
|
||||
this.secure = false,
|
||||
this.path = '/connect',
|
||||
this.passwordRequired = true,
|
||||
this.version,
|
||||
});
|
||||
|
||||
/// Builds a server from a resolved DNS-SD record: the service [instance]
|
||||
/// name, the resolved [addresses] (and SRV [hostname] when no address is
|
||||
/// usable), the SRV [port] and the TXT [attributes]. Returns null when there
|
||||
/// is nothing to dial.
|
||||
static DiscoveredServer? fromRecord({
|
||||
required String instance,
|
||||
required List<String> addresses,
|
||||
String? hostname,
|
||||
required int port,
|
||||
Map<String, String> attributes = const {},
|
||||
}) {
|
||||
final host = preferredHost(addresses) ?? _bare(hostname);
|
||||
if (host == null || port <= 0 || port > 65535) return null;
|
||||
final path = attributes['path'] ?? '';
|
||||
final name = attributes['name'] ?? '';
|
||||
return DiscoveredServer(
|
||||
name: name.isEmpty ? instance : name,
|
||||
host: host,
|
||||
port: port,
|
||||
secure: attributes['tls'] == '1',
|
||||
path: path.startsWith('/') ? path : '/connect',
|
||||
passwordRequired: attributes['auth'] != 'none',
|
||||
version: attributes['v'],
|
||||
);
|
||||
}
|
||||
|
||||
final String name;
|
||||
final String host;
|
||||
final int port;
|
||||
final bool secure;
|
||||
final String path;
|
||||
final bool passwordRequired;
|
||||
final String? version;
|
||||
|
||||
/// The websocket endpoint the connect screen dials.
|
||||
Uri get endpoint =>
|
||||
Uri(scheme: secure ? 'wss' : 'ws', host: host, port: port, path: path);
|
||||
|
||||
/// "host:port" as shown under the name.
|
||||
String get address => endpoint.authority;
|
||||
|
||||
/// Picks the address a phone can dial: IPv4 first, then a routable IPv6
|
||||
/// address. Link-local IPv6 needs a zone the URL cannot carry.
|
||||
static String? preferredHost(List<String> addresses) {
|
||||
final values = [for (final value in addresses) value.trim()];
|
||||
for (final value in values) {
|
||||
final bytes = _ipv4(value);
|
||||
if (bytes != null && bytes[0] != 127) return value;
|
||||
}
|
||||
for (final value in values) {
|
||||
final bytes = _ipv6(value);
|
||||
if (bytes == null) continue;
|
||||
final loopback =
|
||||
bytes.sublist(0, 15).every((byte) => byte == 0) && bytes[15] == 1;
|
||||
final linkLocal = bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80;
|
||||
if (!loopback && !linkLocal) return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static List<int>? _ipv4(String value) {
|
||||
if (!RegExp(r'^\d{1,3}(\.\d{1,3}){3}$').hasMatch(value)) return null;
|
||||
try {
|
||||
return Uri.parseIPv4Address(value);
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static List<int>? _ipv6(String value) {
|
||||
if (!value.contains(':') || value.contains('%')) return null;
|
||||
try {
|
||||
return Uri.parseIPv6Address(value);
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static String? _bare(String? hostname) {
|
||||
final value = hostname?.trim().replaceFirst(RegExp(r'\.$'), '') ?? '';
|
||||
return value.isEmpty ? null : value;
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is DiscoveredServer &&
|
||||
other.name == name &&
|
||||
other.endpoint == endpoint &&
|
||||
other.passwordRequired == passwordRequired &&
|
||||
other.version == version;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(name, endpoint, passwordRequired, version);
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import 'discovered_server.dart';
|
||||
import 'server_discovery.dart';
|
||||
|
||||
enum _Phase { idle, scanning, done, failed }
|
||||
|
||||
/// "Find servers on this network": browses for a while, lists what answered
|
||||
/// and hands a tapped server to [onSelect]. Manual entry stays beside it.
|
||||
class DiscoveryPanel extends StatefulWidget {
|
||||
const DiscoveryPanel({
|
||||
super.key,
|
||||
required this.discovery,
|
||||
required this.onSelect,
|
||||
this.enabled = true,
|
||||
this.scanFor = const Duration(seconds: 8),
|
||||
});
|
||||
|
||||
final ServerDiscovery discovery;
|
||||
final ValueChanged<DiscoveredServer> onSelect;
|
||||
final bool enabled;
|
||||
|
||||
/// How long one scan browses before it settles on its results.
|
||||
final Duration scanFor;
|
||||
|
||||
@override
|
||||
State<DiscoveryPanel> createState() => _DiscoveryPanelState();
|
||||
}
|
||||
|
||||
class _DiscoveryPanelState extends State<DiscoveryPanel> {
|
||||
_Phase _phase = _Phase.idle;
|
||||
List<DiscoveredServer> _servers = const [];
|
||||
String? _error;
|
||||
StreamSubscription<List<DiscoveredServer>>? _scan;
|
||||
Timer? _timer;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_stop();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _stop() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
unawaited(_scan?.cancel());
|
||||
_scan = null;
|
||||
}
|
||||
|
||||
void _start() {
|
||||
_stop();
|
||||
setState(() {
|
||||
_phase = _Phase.scanning;
|
||||
_servers = const [];
|
||||
_error = null;
|
||||
});
|
||||
_scan = widget.discovery.scan().listen(
|
||||
(servers) {
|
||||
if (mounted) setState(() => _servers = servers);
|
||||
},
|
||||
onError: (Object error) {
|
||||
_stop();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_phase = _Phase.failed;
|
||||
_error = '$error';
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
_timer = Timer(widget.scanFor, () {
|
||||
_stop();
|
||||
if (mounted) setState(() => _phase = _Phase.done);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino = usesCupertinoHost(context);
|
||||
final scanning = _phase == _Phase.scanning;
|
||||
final label = _phase == _Phase.idle
|
||||
? 'Find servers on this network'
|
||||
: 'Search again';
|
||||
final enabled = widget.enabled && !scanning;
|
||||
final button = cupertino
|
||||
? CupertinoButton(
|
||||
key: const Key('discovery-scan'),
|
||||
onPressed: enabled ? _start : null,
|
||||
child: Text(label),
|
||||
)
|
||||
: OutlinedButton.icon(
|
||||
key: const Key('discovery-scan'),
|
||||
onPressed: enabled ? _start : null,
|
||||
icon: const Icon(Icons.wifi_find),
|
||||
label: Text(label),
|
||||
);
|
||||
final status = switch (_phase) {
|
||||
_Phase.scanning => _status(
|
||||
context,
|
||||
cupertino,
|
||||
const Key('discovery-scanning'),
|
||||
'Looking for Pipelines servers…',
|
||||
busy: true,
|
||||
),
|
||||
_Phase.done when _servers.isEmpty => _status(
|
||||
context,
|
||||
cupertino,
|
||||
const Key('discovery-empty'),
|
||||
'No Pipelines servers answered on this network. '
|
||||
'Enter the address instead.',
|
||||
),
|
||||
_Phase.failed => _status(
|
||||
context,
|
||||
cupertino,
|
||||
const Key('discovery-error'),
|
||||
'Could not search this network: $_error',
|
||||
error: true,
|
||||
),
|
||||
_ => null,
|
||||
};
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
button,
|
||||
?status,
|
||||
for (final server in _servers) _row(context, cupertino, server),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _status(
|
||||
BuildContext context,
|
||||
bool cupertino,
|
||||
Key key,
|
||||
String text, {
|
||||
bool busy = false,
|
||||
bool error = false,
|
||||
}) {
|
||||
final color = !error
|
||||
? null
|
||||
: cupertino
|
||||
? CupertinoColors.systemRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error;
|
||||
return Padding(
|
||||
key: key,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
if (busy) ...[
|
||||
cupertino
|
||||
? const CupertinoActivityIndicator()
|
||||
: const SizedBox.square(
|
||||
dimension: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
],
|
||||
Expanded(
|
||||
child: Text(text, style: TextStyle(color: color)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _row(BuildContext context, bool cupertino, DiscoveredServer server) {
|
||||
final key = Key('discovered-${server.address}');
|
||||
final subtitle = Text(
|
||||
server.passwordRequired ? '${server.address} · password' : server.address,
|
||||
);
|
||||
void tap() => widget.onSelect(server);
|
||||
final onTap = widget.enabled ? tap : null;
|
||||
if (cupertino) {
|
||||
return CupertinoListTile(
|
||||
key: key,
|
||||
leading: const Icon(CupertinoIcons.desktopcomputer),
|
||||
title: Text(server.name),
|
||||
subtitle: subtitle,
|
||||
trailing: const CupertinoListTileChevron(),
|
||||
onTap: onTap,
|
||||
);
|
||||
}
|
||||
return ListTile(
|
||||
key: key,
|
||||
leading: const Icon(Icons.dns_outlined),
|
||||
title: Text(server.name),
|
||||
subtitle: subtitle,
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
enabled: widget.enabled,
|
||||
onTap: onTap,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'bonsoir_server_discovery.dart';
|
||||
import 'discovered_server.dart';
|
||||
|
||||
/// Finds Pipelines servers on the local network.
|
||||
abstract interface class ServerDiscovery {
|
||||
/// Browses while listened to. Each event is every server currently known;
|
||||
/// a failure to browse is a stream error. Cancelling stops the browse.
|
||||
Stream<List<DiscoveredServer>> scan();
|
||||
}
|
||||
|
||||
/// The discovery this platform supports, or null where there is none.
|
||||
///
|
||||
/// Browsers cannot send mDNS, and the web app is served by the server it
|
||||
/// talks to, so web has no scan.
|
||||
ServerDiscovery? platformServerDiscovery({bool web = kIsWeb}) =>
|
||||
web ? null : BonsoirServerDiscovery();
|
||||
@@ -5,6 +5,9 @@ import '../../core/session/server_session.dart';
|
||||
import '../../core/transport/server_url.dart';
|
||||
import '../../core/servers/server_probe.dart';
|
||||
import '../../ui/adaptive/host.dart';
|
||||
import 'discovery/discovered_server.dart';
|
||||
import 'discovery/discovery_panel.dart';
|
||||
import 'discovery/server_discovery.dart';
|
||||
|
||||
/// Reaches a server and reports what it says about this device's session.
|
||||
typedef ServerCheck = Future<SessionState> Function(Uri endpoint);
|
||||
@@ -25,6 +28,7 @@ class OnboardingFlow extends StatefulWidget {
|
||||
this.saveServer,
|
||||
this.savedServers,
|
||||
this.serverAddresses = const [],
|
||||
this.discovery,
|
||||
});
|
||||
|
||||
/// Called with the signed-in server's endpoint.
|
||||
@@ -41,6 +45,9 @@ class OnboardingFlow extends StatefulWidget {
|
||||
final Widget? savedServers;
|
||||
final List<Uri> serverAddresses;
|
||||
|
||||
/// LAN discovery; null hides the scan (web, or no platform support).
|
||||
final ServerDiscovery? discovery;
|
||||
|
||||
@override
|
||||
State<OnboardingFlow> createState() => _OnboardingFlowState();
|
||||
}
|
||||
@@ -135,6 +142,11 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
|
||||
});
|
||||
}
|
||||
|
||||
void _useDiscovered(DiscoveredServer server) {
|
||||
_server.text = server.endpoint.toString();
|
||||
_continue();
|
||||
}
|
||||
|
||||
Future<void> _signIn() async {
|
||||
final endpoint = _endpoint;
|
||||
if (endpoint == null || _password.text.isEmpty) return;
|
||||
@@ -239,6 +251,14 @@ class _OnboardingFlowState extends State<OnboardingFlow> {
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
button,
|
||||
if (!_passwordStep && widget.discovery != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
DiscoveryPanel(
|
||||
discovery: widget.discovery!,
|
||||
enabled: !_busy,
|
||||
onSelect: _useDiscovered,
|
||||
),
|
||||
],
|
||||
if (_passwordStep && !widget.startAtPassword) ...[
|
||||
const SizedBox(height: 8),
|
||||
cupertino
|
||||
|
||||
Reference in New Issue
Block a user