发布网络质量探测 1.1.2:更新客户端探测与说明文件(一)

署名:言灸
This commit is contained in:
YanJiu committed 2026-11-20 18:59:35 +08:00
1 parent 4c6472a504
commit 3a6356f4d9
4 files changed
+713 -201

No files matched your search

+48 -1
View File
@@ -1,3 +1,5 @@
import 'latency.dart';
class Outcome {
const Outcome({
required this.status,
@@ -6,6 +8,7 @@ class Outcome {
this.note = '',
this.detail = const {},
this.reconnect = false,
this.selectionSkipped = 0,
});
final String status;
@@ -15,6 +18,10 @@ class Outcome {
final Map<String, String> detail;
final bool reconnect;
/// Candidate failures folded into this measured attempt. They are not
/// themselves samples.
final int selectionSkipped;
static const ok = 'ok';
static const timeout = 'timeout';
static const unknown = 'unknown';
@@ -48,6 +55,13 @@ class ProbeSummary {
required this.unknownPct,
required this.lastNote,
required this.detail,
this.minRttMs,
this.meanRttMs,
this.medianRttMs,
this.p95RttMs,
this.maxRttMs,
this.selectionSkipped = 0,
this.latencyStats = false,
});
final int sent;
@@ -68,6 +82,15 @@ class ProbeSummary {
final double? unknownPct;
final String lastNote;
final Map<String, String> detail;
final double? minRttMs;
final double? meanRttMs;
final double? medianRttMs;
final double? p95RttMs;
final double? maxRttMs;
final int selectionSkipped;
/// False when an older remote node omitted the latency distribution.
final bool latencyStats;
static const empty = ProbeSummary(
sent: 0,
@@ -110,6 +133,16 @@ class ProbeSummary {
unknownPct: _double(json['unknownPct']),
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
detail: _detail(json['detail']),
minRttMs: _double(json['minRttMs']),
meanRttMs: _double(json['meanRttMs']),
medianRttMs: _double(json['medianRttMs']),
p95RttMs: _double(json['p95RttMs']),
maxRttMs: _double(json['maxRttMs']),
selectionSkipped: _int(json['selectionSkipped']),
latencyStats:
json.containsKey('minRttMs') ||
json.containsKey('medianRttMs') ||
json.containsKey('p95RttMs'),
);
}
}
@@ -137,7 +170,9 @@ class ProbeSample {
factory ProbeSample.fromJson(Map<String, dynamic> json) {
final summary = json['summary'] is Map
? ProbeSummary.fromJson(Map<String, dynamic>.from(json['summary'] as Map))
? ProbeSummary.fromJson(
Map<String, dynamic>.from(json['summary'] as Map),
)
: ProbeSummary.empty;
return ProbeSample(
seq: _int(json['seq']),
@@ -171,12 +206,15 @@ class SampleBook {
double jitterMs = 0;
bool _hasJitter = false;
double _lastTransit = 0;
final List<double> _rtts = [];
int selectionSkipped = 0;
String lastNote = '';
Map<String, String> detail = {};
void add(Outcome outcome) {
sent += 1;
completed += 1;
selectionSkipped += outcome.selectionSkipped;
if (outcome.reconnect) {
reconnects += 1;
}
@@ -193,6 +231,7 @@ class SampleBook {
final rtt = outcome.rttMs;
if (rtt != null) {
lastRttMs = rtt;
_rtts.add(rtt);
if (_hasJitter) {
final delta = (rtt - _lastTransit).abs();
jitterMs += (delta - jitterMs) / 16;
@@ -250,6 +289,7 @@ class SampleBook {
}
}
}
final latency = LatencyStats.from(_rtts);
return ProbeSummary(
sent: sent,
completed: completed,
@@ -269,6 +309,13 @@ class SampleBook {
unknownPct: unknownPct,
lastNote: lastNote,
detail: detail,
minRttMs: latency?.min,
meanRttMs: latency?.mean,
medianRttMs: latency?.median,
p95RttMs: latency?.p95,
maxRttMs: latency?.max,
selectionSkipped: selectionSkipped,
latencyStats: true,
);
}
+340 -107
View File
@@ -1,22 +1,67 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import '../metrics/sample_book.dart';
import '../models/probe_profile.dart';
import '../models/session_config.dart';
import '../ui/address_text.dart';
import 'endpoint_picker.dart';
import 'probe_loop.dart';
import 'remote_client.dart';
class ChartSample {
const ChartSample({required this.sec, required this.rttMs, required this.ratePct});
const ChartSample({
required this.sec,
required this.rttMs,
required this.ratePct,
});
final double sec;
final double? rttMs;
final double? ratePct;
}
class SessionReport {
const SessionReport({
required this.startedAt,
required this.endedAt,
required this.elapsed,
required this.target,
required this.profileLabel,
required this.sourceLabel,
required this.profileId,
required this.summary,
required this.rateLabel,
required this.resolved,
required this.usedAddress,
required this.usedFamily,
required this.fallbackText,
required this.addressUnreported,
required this.usedIsFake,
});
final DateTime startedAt;
final DateTime endedAt;
final Duration elapsed;
final String target;
final String profileLabel;
final String sourceLabel;
final String profileId;
final ProbeSummary summary;
final String rateLabel;
final List<ResolvedAddress> resolved;
final String? usedAddress;
final String? usedFamily;
final String fallbackText;
final bool addressUnreported;
final bool usedIsFake;
}
class ProbeView {
const ProbeView({
required this.running,
@@ -28,8 +73,22 @@ class ProbeView {
required this.samples,
required this.rateLabel,
required this.sourceLabel,
this.targetAddress,
this.targetIsFake = false,
required this.sessionId,
this.profileId = '',
required this.elapsed,
this.targetHost = '',
this.profileLabel = '',
this.tryingAddress,
this.tryingFamily,
this.usedAddress,
this.usedFamily,
this.usedIsFake = false,
this.resolved = const [],
this.fallbackText = '',
this.addressUnreported = false,
this.report,
this.startedAt,
this.endedAt,
});
static const initial = ProbeView(
@@ -42,6 +101,8 @@ class ProbeView {
samples: [],
rateLabel: '探测无应答',
sourceLabel: '本机',
sessionId: 0,
elapsed: Duration.zero,
);
final bool running;
@@ -53,8 +114,22 @@ class ProbeView {
final List<ChartSample> samples;
final String rateLabel;
final String sourceLabel;
final String? targetAddress;
final bool targetIsFake;
final int sessionId;
final String profileId;
final Duration elapsed;
final String targetHost;
final String profileLabel;
final String? tryingAddress;
final String? tryingFamily;
final String? usedAddress;
final String? usedFamily;
final bool usedIsFake;
final List<ResolvedAddress> resolved;
final String fallbackText;
final bool addressUnreported;
final SessionReport? report;
final DateTime? startedAt;
final DateTime? endedAt;
ProbeView copyWith({
bool? running,
@@ -67,8 +142,24 @@ class ProbeView {
List<ChartSample>? samples,
String? rateLabel,
String? sourceLabel,
String? targetAddress,
bool? targetIsFake,
int? sessionId,
String? profileId,
Duration? elapsed,
String? targetHost,
String? profileLabel,
String? tryingAddress,
String? tryingFamily,
bool clearTrying = false,
String? usedAddress,
String? usedFamily,
bool? usedIsFake,
List<ResolvedAddress>? resolved,
String? fallbackText,
bool? addressUnreported,
SessionReport? report,
bool clearReport = false,
DateTime? startedAt,
DateTime? endedAt,
}) {
return ProbeView(
running: running ?? this.running,
@@ -80,8 +171,22 @@ class ProbeView {
samples: samples ?? this.samples,
rateLabel: rateLabel ?? this.rateLabel,
sourceLabel: sourceLabel ?? this.sourceLabel,
targetAddress: targetAddress ?? this.targetAddress,
targetIsFake: targetIsFake ?? this.targetIsFake,
sessionId: sessionId ?? this.sessionId,
profileId: profileId ?? this.profileId,
elapsed: elapsed ?? this.elapsed,
targetHost: targetHost ?? this.targetHost,
profileLabel: profileLabel ?? this.profileLabel,
tryingAddress: clearTrying ? null : tryingAddress ?? this.tryingAddress,
tryingFamily: clearTrying ? null : tryingFamily ?? this.tryingFamily,
usedAddress: usedAddress ?? this.usedAddress,
usedFamily: usedFamily ?? this.usedFamily,
usedIsFake: usedIsFake ?? this.usedIsFake,
resolved: resolved ?? this.resolved,
fallbackText: fallbackText ?? this.fallbackText,
addressUnreported: addressUnreported ?? this.addressUnreported,
report: clearReport ? null : report ?? this.report,
startedAt: startedAt ?? this.startedAt,
endedAt: endedAt ?? this.endedAt,
);
}
}
@@ -93,113 +198,154 @@ class ProbeController extends ChangeNotifier {
RemoteProbe? _remote;
String _nodeToken = '';
var _token = 0;
var _session = 0;
var _busy = false;
var _remoteMode = false;
DateTime? _startedAt;
Timer? _tick;
Future<void> start(SessionConfig config, {required String nodeToken, required String echoToken}) async {
final problem = config.validate();
if (problem != null) {
view = view.copyWith(banner: problem, phase: '无法开始');
notifyListeners();
Future<void> start(
SessionConfig config, {
required String nodeToken,
required String echoToken,
}) async {
if (_busy) {
return;
}
final echoProblem = _echoProblem(config.profileId, echoToken);
if (echoProblem != null) {
view = view.copyWith(banner: echoProblem, phase: '无法开始');
notifyListeners();
return;
}
await stop();
_nodeToken = nodeToken;
final generation = ++_token;
_clock
..reset()
..start();
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
view = ProbeView(
running: true,
phase: '探测中',
banner: null,
note: config.remote ? '正在让节点向目标发包' : '正在从本机向目标发包',
detail: const {},
summary: ProbeSummary.empty,
samples: const [],
rateLabel: rateLabelFor(config.profileId),
sourceLabel: source,
);
notifyListeners();
bool cancelled() => generation != _token;
_busy = true;
try {
if (config.remote) {
final remote = RemoteProbe();
_remote = remote;
await remote.run(
baseUrl: config.node!.baseUrl,
nodeToken: nodeToken,
body: ProbeBody(
target: config.host.trim(),
port: config.port,
profile: config.profileId,
intervalMs: config.intervalMs,
timeoutMs: config.timeoutMs,
durationSec: config.durationSec,
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
} else {
final loop = ProbeLoop(
onEndpoint: (address) {
if (generation != _token) {
return;
}
view = view.copyWith(
targetAddress: address.address,
targetIsFake: isClashFakeIp(address),
);
notifyListeners();
},
);
_local = loop;
await loop.run(
request: ProbeRequest(
host: config.host.trim(),
port: config.port,
profileId: config.profileId,
interval: Duration(milliseconds: config.intervalMs),
timeout: Duration(milliseconds: config.timeoutMs),
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
}
if (generation == _token) {
view = view.copyWith(running: false, phase: '已停止');
final problem = config.validate();
if (problem != null) {
view = view.copyWith(banner: problem, phase: '无法开始');
notifyListeners();
return;
}
} on RemoteException catch (error) {
if (generation == _token) {
view = view.copyWith(running: false, phase: '出错', banner: error.message);
final echoProblem = _echoProblem(config.profileId, echoToken);
if (echoProblem != null) {
view = view.copyWith(banner: echoProblem, phase: '无法开始');
notifyListeners();
return;
}
} on Object {
if (generation == _token) {
view = view.copyWith(running: false, phase: '出错', banner: '探测中断');
notifyListeners();
await stop();
_nodeToken = nodeToken;
_remoteMode = config.remote;
final generation = ++_token;
final session = ++_session;
_startedAt = DateTime.now();
_clock
..reset()
..start();
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
final profile = ProbeProfile.byId(config.profileId);
view = ProbeView(
running: true,
phase: '探测中',
banner: null,
note: config.remote ? '正在让节点向目标发包' : '正在从本机向目标发包',
detail: const {},
summary: ProbeSummary.empty,
samples: const [],
rateLabel: rateLabelFor(config.profileId),
sourceLabel: source,
sessionId: session,
profileId: config.profileId,
elapsed: Duration.zero,
targetHost: '${config.host.trim()}:${config.port}',
profileLabel: profile.label,
startedAt: _startedAt,
);
notifyListeners();
_armTick(generation);
bool cancelled() => generation != _token;
try {
if (config.remote) {
final remote = RemoteProbe();
_remote = remote;
await remote.run(
baseUrl: config.node!.baseUrl,
nodeToken: nodeToken,
body: ProbeBody(
target: config.host.trim(),
port: config.port,
profile: config.profileId,
intervalMs: config.intervalMs,
timeoutMs: config.timeoutMs,
durationSec: config.durationSec,
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
onResolved: (resolved) {
if (generation != _token) {
return;
}
view = view.copyWith(resolved: resolved);
notifyListeners();
},
cancelled: cancelled,
);
} else {
final loop = ProbeLoop(
onEndpoint: (address) {
if (generation != _token) {
return;
}
view = view.copyWith(
tryingAddress: address.address,
tryingFamily: addressFamily(address),
);
notifyListeners();
},
onResolved: (addresses) {
if (generation != _token) {
return;
}
view = view.copyWith(
resolved: [
for (final address in addresses)
ResolvedAddress(
address: address.address,
family: addressFamily(address),
),
],
);
notifyListeners();
},
);
_local = loop;
await loop.run(
request: ProbeRequest(
host: config.host.trim(),
port: config.port,
profileId: config.profileId,
interval: Duration(milliseconds: config.intervalMs),
timeout: Duration(milliseconds: config.timeoutMs),
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
}
_finish(generation, '已停止');
} on RemoteException catch (error) {
_finish(generation, '出错', banner: error.message);
} on Object {
_finish(generation, '出错', banner: '探测中断');
} finally {
if (generation == _token) {
_local = null;
_remote = null;
}
}
} finally {
if (generation == _token) {
_local = null;
_remote = null;
}
_busy = false;
}
}
@@ -217,11 +363,73 @@ class ProbeController extends ChangeNotifier {
_nodeToken = '';
}
if (view.running) {
view = view.copyWith(running: false, phase: '已停止');
_clock.stop();
_tick?.cancel();
final ended = DateTime.now();
view = view.copyWith(
running: false,
phase: '已停止',
elapsed: _clock.elapsed,
endedAt: ended,
report: _snapshot(ended),
);
notifyListeners();
}
}
void _finish(int generation, String phase, {String? banner}) {
if (generation != _token || !view.running) {
return;
}
_clock.stop();
_tick?.cancel();
final ended = DateTime.now();
view = view.copyWith(
running: false,
phase: phase,
banner: banner,
elapsed: _clock.elapsed,
endedAt: ended,
report: _snapshot(ended),
);
notifyListeners();
}
SessionReport? _snapshot(DateTime ended) {
final started = _startedAt;
if (started == null) {
return null;
}
return SessionReport(
startedAt: started,
endedAt: ended,
elapsed: _clock.elapsed,
target: view.targetHost,
profileLabel: view.profileLabel,
sourceLabel: view.sourceLabel,
profileId: view.profileId,
summary: view.summary,
rateLabel: view.rateLabel,
resolved: view.resolved,
usedAddress: view.usedAddress,
usedFamily: view.usedFamily,
fallbackText: view.fallbackText,
addressUnreported: view.addressUnreported,
usedIsFake: view.usedIsFake,
);
}
void _armTick(int generation) {
_tick?.cancel();
_tick = Timer.periodic(const Duration(seconds: 1), (_) {
if (generation != _token || !view.running) {
return;
}
view = view.copyWith(elapsed: _clock.elapsed);
notifyListeners();
});
}
void _accept(int generation, ProbeSample sample) {
if (generation != _token) {
return;
@@ -246,6 +454,16 @@ class ProbeController extends ChangeNotifier {
ratePct: rate,
),
);
final reported = sample.detail['address'];
final hasAddress = reported != null && reported.isNotEmpty;
final fallback = sample.detail['fallback'];
final parsed = hasAddress ? InternetAddress.tryParse(reported) : null;
final family = hasAddress
? ((sample.detail['family'] != null &&
sample.detail['family']!.isNotEmpty)
? sample.detail['family']
: familyOfAddress(reported))
: null;
view = view.copyWith(
phase: phaseFor(sample.status),
note: sample.note,
@@ -253,9 +471,24 @@ class ProbeController extends ChangeNotifier {
summary: sample.summary,
samples: samples,
clearBanner: true,
elapsed: _clock.elapsed,
usedAddress: hasAddress ? reported : view.usedAddress,
usedFamily: hasAddress ? family : view.usedFamily,
usedIsFake: hasAddress
? parsed != null && isClashFakeIp(parsed)
: view.usedIsFake,
clearTrying: hasAddress || (fallback != null && fallback.isNotEmpty),
fallbackText: (fallback != null && fallback.isNotEmpty) ? fallback : null,
addressUnreported: _remoteMode && !hasAddress,
);
notifyListeners();
}
@override
void dispose() {
_tick?.cancel();
super.dispose();
}
}
String? _echoProblem(String profileId, String echoToken) {
+324 -92
View File
@@ -3,7 +3,9 @@ import 'dart:io';
import 'dart:typed_data';
import '../metrics/sample_book.dart';
import '../metrics/selection_ledger.dart';
import '../protocol/probe_packet.dart';
import '../ui/address_text.dart';
import 'endpoint_picker.dart';
import 'game_codec.dart';
@@ -36,10 +38,7 @@ class ProbeRequest {
/// Sends one probe at a time from this device. A cancelled attempt is not
/// recorded, so stopping cannot paint a fake loss sample.
class ProbeLoop {
ProbeLoop({
this.lookup,
this.onEndpoint,
});
ProbeLoop({this.lookup, this.onEndpoint, this.onResolved});
/// Replaces [lookupAll] in tests.
final Future<List<InternetAddress>> Function(String host)? lookup;
@@ -47,10 +46,16 @@ class ProbeLoop {
/// Fires when the address about to be used is chosen or changed.
final void Function(InternetAddress address)? onEndpoint;
/// Fires once with the lookup result. This is not the address in use.
final void Function(List<InternetAddress> addresses)? onResolved;
_TcpPipe? _tcp;
_UdpPipe? _udp;
EndpointPicker? _picker;
SelectionLedger? _ledger;
InternetAddress? _announced;
InternetAddress? _tcpUsed;
List<InternetAddress>? _resolved;
int _seq = 0;
int _dnsId = 1;
final int _guid = DateTime.now().microsecondsSinceEpoch;
@@ -65,20 +70,32 @@ class ProbeLoop {
while (!cancelled()) {
final started = DateTime.now();
final outcome = await _once(request, cancelled);
if (cancelled() || outcome == null) {
if (!countsAfterStop(outcome, cancelled: cancelled())) {
break;
}
if (_usesDatagram(request.profileId)) {
final responded = outcome.status == Outcome.ok ||
outcome.status == Outcome.protocol ||
outcome.status == Outcome.refused;
if (_picker != null && _picker!.record(responded)) {
var commit = <Outcome>[outcome!];
if (_usesDatagram(request.profileId) && _picker != null) {
_ledger ??= SelectionLedger(_picker!.candidates.length);
final responded = selectionResponded(outcome);
final wasMeasuring = _ledger!.measuring;
final changed = _picker!.record(responded);
final decision = _ledger!.take(outcome, responded: responded);
if (wasMeasuring && changed) {
_ledger!.endMeasurement();
}
if (changed) {
await _dropUdp();
_announce(_picker!.current);
}
commit = decision.commit;
if (commit.isEmpty) {
continue;
}
}
for (final item in commit) {
book.add(item);
onSample(book.sample(book.sent, item));
}
book.add(outcome);
onSample(book.sample(book.sent, outcome));
final spent = DateTime.now().difference(started);
final rest = request.interval - spent;
if (!cancelled() && rest > Duration.zero) {
@@ -103,7 +120,10 @@ class ProbeLoop {
}
}
Future<Outcome?> _once(ProbeRequest request, bool Function() cancelled) async {
Future<Outcome?> _once(
ProbeRequest request,
bool Function() cancelled,
) async {
try {
final outcome = await _dispatch(request, cancelled);
final peer = _udp?.peer;
@@ -160,45 +180,58 @@ class ProbeLoop {
ProbeRequest request,
bool Function() cancelled,
) async {
final watch = Stopwatch()..start();
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
watch.stop();
final opened = await _openTcp(request, cancelled);
final failure = opened.failure;
if (failure != null) {
return failure;
}
final socket = opened.socket!;
opened.watch?.stop();
await socket.close();
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '已停止',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.connect,
rttMs: watch.elapsedMicroseconds / 1000,
note: 'TCP 已连通',
return _withUsed(
Outcome(
status: Outcome.ok,
kind: Outcome.connect,
rttMs: (opened.watch?.elapsedMicroseconds ?? 0) / 1000,
note: 'TCP 已连通',
),
opened.used,
opened.fallback,
opened.skipped,
);
}
Future<Outcome> _nqTcp(ProbeRequest request, bool Function() cancelled) async {
Future<Outcome> _nqTcp(
ProbeRequest request,
bool Function() cancelled,
) async {
var fallback = '';
var skipped = 0;
if (_tcp == null) {
try {
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
socket.setOption(SocketOption.tcpNoDelay, true);
_tcp = _TcpPipe(socket);
} on SocketException catch (error) {
return classifySocket(error, reconnect: true);
} on TimeoutException {
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
reconnect: true,
note: '连接超时,将重试',
final opened = await _openTcp(request, cancelled);
final failure = opened.failure;
if (failure != null) {
return Outcome(
status: failure.status,
kind: failure.kind,
note: failure.note,
reconnect: failure.note != '已停止',
detail: failure.detail,
);
}
final socket = opened.socket!;
socket.setOption(SocketOption.tcpNoDelay, true);
_tcp = _TcpPipe(socket);
_tcpUsed = opened.used;
fallback = opened.fallback;
skipped = opened.skipped;
}
final pipe = _tcp!;
_seq += 1;
@@ -232,21 +265,35 @@ class ProbeLoop {
}
});
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '已停止',
);
}
if (matched == null) {
await _dropTcp();
return const Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
return _withUsed(
const Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
),
_tcpUsed,
fallback,
skipped,
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.probe,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到回显',
return _withUsed(
Outcome(
status: Outcome.ok,
kind: Outcome.probe,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到回显',
),
_tcpUsed,
fallback,
skipped,
);
}
@@ -258,7 +305,10 @@ class ProbeLoop {
}
}
Future<Outcome> _nqUdp(ProbeRequest request, bool Function() cancelled) async {
Future<Outcome> _nqUdp(
ProbeRequest request,
bool Function() cancelled,
) async {
final pipe = await _datagram(request);
_seq += 1;
final seq = _seq;
@@ -286,7 +336,11 @@ class ProbeLoop {
}
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '已停止',
);
}
if (reply == null) {
if (sawInvalid) {
@@ -329,7 +383,11 @@ class ProbeLoop {
pipe.send(payload, request.port);
final reply = await pipe.waitMatch(request.timeout, (_) => true);
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '已停止',
);
}
if (reply == null) {
return const Outcome(
@@ -339,7 +397,8 @@ class ProbeLoop {
);
}
final wanted = expect;
if (wanted != null && (reply.length < wanted.length || !_prefix(reply, wanted))) {
if (wanted != null &&
(reply.length < wanted.length || !_prefix(reply, wanted))) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
@@ -358,7 +417,9 @@ class ProbeLoop {
final pipe = await _datagram(request);
_dnsId = _dnsId == 65535 ? 1 : _dnsId + 1;
final id = _dnsId;
final name = request.dnsName.trim().isEmpty ? 'example.com' : request.dnsName.trim();
final name = request.dnsName.trim().isEmpty
? 'example.com'
: request.dnsName.trim();
final watch = Stopwatch()..start();
pipe.send(dnsQuery(id, name), request.port);
var malformed = false;
@@ -378,7 +439,11 @@ class ProbeLoop {
return true;
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '已停止',
);
}
if (reply == null) {
if (malformed) {
@@ -422,7 +487,11 @@ class ProbeLoop {
return true;
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '已停止',
);
}
if (reply == null) {
if (sawInvalid) {
@@ -448,11 +517,12 @@ class ProbeLoop {
}
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
final opened = await _openTcp(request, cancelled);
final failure = opened.failure;
if (failure != null) {
return failure;
}
final socket = opened.socket!;
final reader = _BytePipe(socket);
try {
socket.add(javaHandshake(request.host, request.port));
@@ -460,18 +530,28 @@ class ProbeLoop {
await socket.flush();
final status = await reader.nextPacket(request.timeout);
if (status == null || status.isEmpty || status[0] != 0x00) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft 状态响应无效',
return _withUsed(
const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft 状态响应无效',
),
opened.used,
opened.fallback,
opened.skipped,
);
}
final jsonText = readMcString(status, 1);
if (jsonText == null) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft 状态内容无法解析',
return _withUsed(
const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft 状态内容无法解析',
),
opened.used,
opened.fallback,
opened.skipped,
);
}
final detail = minecraftStatusDetail(jsonText);
@@ -481,30 +561,49 @@ class ProbeLoop {
await socket.flush();
final pong = await reader.nextPacket(request.timeout);
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '已停止',
);
}
if (pong == null || pong.length != 9 || pong[0] != 0x01) {
return Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '没有收到有效的 Minecraft pong',
detail: detail,
return _withUsed(
Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '没有收到有效的 Minecraft pong',
detail: detail,
),
opened.used,
opened.fallback,
opened.skipped,
);
}
if (ByteData.sublistView(pong).getUint64(1) != nonce) {
return Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft pong 的时间戳不匹配',
detail: detail,
return _withUsed(
Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft pong 的时间戳不匹配',
detail: detail,
),
opened.used,
opened.fallback,
opened.skipped,
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 Minecraft 状态和 ping 应答',
detail: detail,
return _withUsed(
Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 Minecraft 状态和 ping 应答',
detail: detail,
),
opened.used,
opened.fallback,
opened.skipped,
);
} finally {
await reader.close();
@@ -513,7 +612,7 @@ class ProbeLoop {
}
Future<_UdpPipe> _datagram(ProbeRequest request) async {
_picker ??= EndpointPicker(await (lookup ?? lookupAll)(request.host));
_picker ??= EndpointPicker(await _addresses(request.host));
final want = _picker!.current;
final existing = _udp;
if (existing != null && existing.peer.address == want.address) {
@@ -550,6 +649,134 @@ class ProbeLoop {
await udp.close();
}
}
Future<List<InternetAddress>> _addresses(String host) async {
final cached = _resolved;
if (cached != null) {
return cached;
}
final found = await (lookup ?? lookupAll)(host);
_resolved = found;
onResolved?.call(found);
return found;
}
Future<_TcpOpen> _openTcp(
ProbeRequest request,
bool Function() cancelled,
) async {
List<InternetAddress> addresses;
try {
addresses = await _addresses(request.host);
} on SocketException catch (error) {
return _TcpOpen.fail(classifySocket(error));
}
final skipped = <String>[];
Object? last;
for (final address in addresses) {
if (cancelled()) {
return _TcpOpen.fail(
const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '已停止',
),
);
}
_announce(address);
final watch = Stopwatch()..start();
try {
final socket = await Socket.connect(
address,
request.port,
timeout: request.timeout,
);
watch.stop();
final fallback = skipped.isEmpty
? ''
: '候选未连通:${skipped.join(';')}。已改用 ${address.address}(${addressFamily(address)})。这些失败没有计入正式丢包或失败率。';
return _TcpOpen.ok(socket, address, watch, fallback, skipped.length);
} on SocketException catch (error) {
last = error;
skipped.add(
'${addressFamily(address)} ${address.address}:${classifySocket(error).note}',
);
} on TimeoutException {
last = TimeoutException('连接超时');
skipped.add('${addressFamily(address)} ${address.address}:连接超时');
}
}
final failure = last is SocketException
? classifySocket(last)
: const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '连接超时',
);
final attempted = skipped.join(';');
return _TcpOpen.fail(
Outcome(
status: failure.status,
kind: failure.kind,
note: skipped.length > 1 ? '没有地址连通。$attempted' : failure.note,
detail: attempted.isEmpty
? const {}
: {'fallback': '已尝试 $attempted。没有地址连通,这次记为失败。'},
),
);
}
}
class _TcpOpen {
const _TcpOpen.ok(
this.socket,
this.used,
this.watch,
this.fallback,
this.skipped,
) : failure = null;
const _TcpOpen.fail(this.failure)
: socket = null,
used = null,
watch = null,
fallback = '',
skipped = 0;
final Socket? socket;
final InternetAddress? used;
final Stopwatch? watch;
final Outcome? failure;
final String fallback;
final int skipped;
}
Outcome _withUsed(
Outcome outcome,
InternetAddress? used,
String fallback,
int skipped,
) {
if (used == null && fallback.isEmpty && skipped == 0) {
return outcome;
}
final detail = {...outcome.detail};
if (used != null) {
detail['address'] = used.address;
detail['family'] = addressFamily(used);
}
if (fallback.isNotEmpty) {
detail['fallback'] = fallback;
}
return Outcome(
status: outcome.status,
kind: outcome.kind,
rttMs: outcome.rttMs,
note: outcome.note,
reconnect: outcome.reconnect,
selectionSkipped: skipped,
detail: detail,
);
}
bool _usesDatagram(String profileId) {
@@ -572,7 +799,12 @@ Outcome _stampAddress(Outcome outcome, InternetAddress peer) {
rttMs: outcome.rttMs,
note: outcome.note,
reconnect: outcome.reconnect,
detail: {...outcome.detail, 'address': peer.address},
selectionSkipped: outcome.selectionSkipped,
detail: {
...outcome.detail,
'address': peer.address,
'family': addressFamily(peer),
},
);
}