Import netquality 1.1.1

Initial import of the 1.1.1 source tree. Corresponds to Origin commit f9d97e368818acfe7dd44fa9fe5088b9629d0dff.

Co-authored-by: yanjiu0721 <yanjiu0721@users.noreply.github.com>
This commit is contained in:
Cursor Agentandyanjiu0721 committed 2026-11-09 23:06:30 +00:00
1 parent 948594e7c0
commit f6ffbde518
93 files changed
+10570 -1

No files matched your search

+76
View File
@@ -0,0 +1,76 @@
import 'dart:io';
/// How many misses a working address may have before another address is tried.
const stickyMissThreshold = 3;
const clashFakeIpNote = '这是 VPN 的假地址,只有这个 VPN 开着时才能用';
/// Clash and similar VPNs hand out addresses in 198.18.0.0/15.
bool isClashFakeIp(InternetAddress address) {
final raw = address.rawAddress;
if (raw.length != 4) {
return false;
}
return raw[0] == 198 && (raw[1] == 18 || raw[1] == 19);
}
/// Picks which resolved address to send to.
///
/// Before any address has answered, one miss is enough to try the next.
/// After an address has answered, it is kept until [stickyMissThreshold]
/// misses in a row. The list is the one resolved at the start of the run;
/// nothing here looks the name up again.
class EndpointPicker {
EndpointPicker(this.candidates, {this.stickyMisses = stickyMissThreshold}) {
if (candidates.isEmpty) {
throw ArgumentError.value(candidates, 'candidates', 'empty');
}
}
final List<InternetAddress> candidates;
final int stickyMisses;
var _index = 0;
var _misses = 0;
var _locked = false;
InternetAddress get current => candidates[_index];
bool get hasAnswered => _locked;
/// Records one finished attempt. Returns true when [current] changed.
bool record(bool gotResponse) {
if (gotResponse) {
_locked = true;
_misses = 0;
return false;
}
_misses += 1;
final limit = _locked ? stickyMisses : 1;
if (candidates.length < 2 || _misses < limit) {
return false;
}
_misses = 0;
_locked = false;
_index = (_index + 1) % candidates.length;
return true;
}
}
Future<List<InternetAddress>> lookupAll(String host) async {
final parsed = InternetAddress.tryParse(host.trim());
if (parsed != null) {
return [parsed];
}
final found = await InternetAddress.lookup(host.trim());
if (found.isEmpty) {
throw const SocketException('Failed host lookup');
}
final seen = <String>{};
final unique = <InternetAddress>[];
for (final address in found) {
if (seen.add('${address.type.name} ${address.address}')) {
unique.add(address);
}
}
return unique;
}
+243
View File
@@ -0,0 +1,243 @@
import 'dart:convert';
import 'dart:typed_data';
const rakMagic = <int>[
0x00,
0xff,
0xff,
0x00,
0xfe,
0xfe,
0xfe,
0xfe,
0xfd,
0xfd,
0xfd,
0xfd,
0x12,
0x34,
0x56,
0x78,
];
Uint8List encodeVarInt(int value) {
final out = <int>[];
var u = value;
while (true) {
if ((u & ~0x7f) == 0) {
out.add(u);
return Uint8List.fromList(out);
}
out.add((u & 0x7f) | 0x80);
u >>= 7;
}
}
int? decodeVarInt(Uint8List bytes, int offset, void Function(int next) onNext) {
var n = 0;
for (var i = 0; i < 5; i++) {
if (offset + i >= bytes.length) {
return null;
}
final by = bytes[offset + i];
n |= (by & 0x7f) << (7 * i);
if ((by & 0x80) == 0) {
onNext(offset + i + 1);
return n;
}
}
throw const FormatException('varint');
}
Uint8List mcString(String value) {
final raw = utf8.encode(value);
final out = BytesBuilder(copy: false);
out.add(encodeVarInt(raw.length));
out.add(raw);
return out.toBytes();
}
Uint8List mcPacket(List<int> payload) {
final out = BytesBuilder(copy: false);
out.add(encodeVarInt(payload.length));
out.add(payload);
return out.toBytes();
}
/// Handshake for status state. Protocol 767 is Minecraft 1.21.x.
Uint8List javaHandshake(String host, int port) {
final payload = BytesBuilder(copy: false);
payload.addByte(0x00);
payload.add(encodeVarInt(767));
payload.add(mcString(host));
final data = ByteData(2)..setUint16(0, port);
payload.add(data.buffer.asUint8List());
payload.add(encodeVarInt(1));
return mcPacket(payload.toBytes());
}
Uint8List javaStatusRequest() => mcPacket(const [0x00]);
Uint8List javaPing(int nonce) {
final data = ByteData(9);
data.setUint8(0, 0x01);
data.setUint64(1, nonce);
return mcPacket(data.buffer.asUint8List());
}
/// Returns the payload of one length-prefixed packet, and how many bytes it used.
({Uint8List payload, int used})? takeMcPacket(Uint8List bytes) {
var offset = 0;
final length = decodeVarInt(bytes, 0, (next) => offset = next);
if (length == null || length < 1 || length > 1 << 20) {
return null;
}
if (bytes.length < offset + length) {
return null;
}
return (
payload: Uint8List.sublistView(bytes, offset, offset + length),
used: offset + length,
);
}
Map<String, String> minecraftStatusDetail(String raw) {
final decoded = jsonDecode(raw);
if (decoded is! Map) {
return const {};
}
final out = <String, String>{};
final version = decoded['version'];
if (version is Map && version['name'] is String) {
out['version'] = version['name'] as String;
}
final players = decoded['players'];
if (players is Map) {
final online = players['online'];
final max = players['max'];
if (online is num && max is num) {
out['players'] = '${online.toInt()}/${max.toInt()}';
}
}
final description = decoded['description'];
final text = motdText(description);
if (text.isNotEmpty) {
out['motd'] = text;
}
return out;
}
String motdText(Object? value) {
if (value is String) {
return value;
}
if (value is Map) {
final buf = StringBuffer();
if (value['text'] is String) {
buf.write(value['text']);
}
final extra = value['extra'];
if (extra is List) {
for (final item in extra) {
buf.write(motdText(item));
}
}
return buf.toString();
}
return '';
}
String? readMcString(Uint8List payload, int offset) {
var next = offset;
final length = decodeVarInt(payload, offset, (value) => next = value);
if (length == null || length < 0 || next + length > payload.length) {
return null;
}
return utf8.decode(payload.sublist(next, next + length), allowMalformed: true);
}
Uint8List bedrockPing(int timestamp, int guid) {
final data = ByteData(1 + 8 + 16 + 8);
data.setUint8(0, 0x01);
data.setUint64(1, timestamp);
final bytes = data.buffer.asUint8List();
bytes.setRange(9, 25, rakMagic);
data.setUint64(25, guid);
return bytes;
}
Map<String, String>? parseRakPong(Uint8List packet, int timestamp) {
if (packet.length < 35 || packet[0] != 0x1c) {
return null;
}
final data = ByteData.sublistView(packet);
if (data.getUint64(1) != timestamp) {
return null;
}
for (var i = 0; i < rakMagic.length; i++) {
if (packet[17 + i] != rakMagic[i]) {
return null;
}
}
final strlen = data.getUint16(33);
if (35 + strlen > packet.length) {
return null;
}
final text = utf8.decode(packet.sublist(35, 35 + strlen), allowMalformed: true);
final parts = text.split(';');
final detail = <String, String>{};
if (parts.length > 1) {
detail['motd'] = parts[1];
}
if (parts.length > 3) {
detail['version'] = parts[3];
}
if (parts.length > 5) {
detail['players'] = '${parts[4]}/${parts[5]}';
}
return detail;
}
Uint8List dnsQuery(int id, String name) {
final body = BytesBuilder(copy: false);
for (final label in name.split('.')) {
if (label.isEmpty) {
continue;
}
final raw = utf8.encode(label);
if (raw.length > 63) {
throw const FormatException('label');
}
body.addByte(raw.length);
body.add(raw);
}
body.add(const [0, 0, 1, 0, 1]);
final question = body.toBytes();
final msg = Uint8List(12 + question.length);
final data = ByteData.sublistView(msg);
data.setUint16(0, id);
data.setUint16(2, 0x0100);
data.setUint16(4, 1);
msg.setRange(12, msg.length, question);
return msg;
}
bool dnsResponseMatches(Uint8List packet, int id) {
if (packet.length < 12) {
return false;
}
final data = ByteData.sublistView(packet);
return data.getUint16(0) == id && (packet[2] & 0x80) != 0;
}
Uint8List decodeHex(String raw) {
final text = raw.replaceAll(RegExp(r'\s'), '');
if (text.isEmpty || text.length.isOdd) {
throw const FormatException('hex');
}
final out = Uint8List(text.length ~/ 2);
for (var i = 0; i < out.length; i++) {
out[i] = int.parse(text.substring(i * 2, i * 2 + 2), radix: 16);
}
return out;
}
+288
View File
@@ -0,0 +1,288 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../metrics/sample_book.dart';
import '../models/probe_profile.dart';
import '../models/session_config.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});
final double sec;
final double? rttMs;
final double? ratePct;
}
class ProbeView {
const ProbeView({
required this.running,
required this.phase,
required this.banner,
required this.note,
required this.detail,
required this.summary,
required this.samples,
required this.rateLabel,
required this.sourceLabel,
this.targetAddress,
this.targetIsFake = false,
});
static const initial = ProbeView(
running: false,
phase: '未开始',
banner: null,
note: '',
detail: {},
summary: ProbeSummary.empty,
samples: [],
rateLabel: '探测无应答',
sourceLabel: '本机',
);
final bool running;
final String phase;
final String? banner;
final String note;
final Map<String, String> detail;
final ProbeSummary summary;
final List<ChartSample> samples;
final String rateLabel;
final String sourceLabel;
final String? targetAddress;
final bool targetIsFake;
ProbeView copyWith({
bool? running,
String? phase,
String? banner,
bool clearBanner = false,
String? note,
Map<String, String>? detail,
ProbeSummary? summary,
List<ChartSample>? samples,
String? rateLabel,
String? sourceLabel,
String? targetAddress,
bool? targetIsFake,
}) {
return ProbeView(
running: running ?? this.running,
phase: phase ?? this.phase,
banner: clearBanner ? null : banner ?? this.banner,
note: note ?? this.note,
detail: detail ?? this.detail,
summary: summary ?? this.summary,
samples: samples ?? this.samples,
rateLabel: rateLabel ?? this.rateLabel,
sourceLabel: sourceLabel ?? this.sourceLabel,
targetAddress: targetAddress ?? this.targetAddress,
targetIsFake: targetIsFake ?? this.targetIsFake,
);
}
}
class ProbeController extends ChangeNotifier {
ProbeView view = ProbeView.initial;
final Stopwatch _clock = Stopwatch();
ProbeLoop? _local;
RemoteProbe? _remote;
String _nodeToken = '';
var _token = 0;
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();
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;
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: '已停止');
notifyListeners();
}
} on RemoteException catch (error) {
if (generation == _token) {
view = view.copyWith(running: false, phase: '出错', banner: error.message);
notifyListeners();
}
} on Object {
if (generation == _token) {
view = view.copyWith(running: false, phase: '出错', banner: '探测中断');
notifyListeners();
}
} finally {
if (generation == _token) {
_local = null;
_remote = null;
}
}
}
Future<void> stop() async {
_token += 1;
final local = _local;
final remote = _remote;
_local = null;
_remote = null;
if (local != null) {
await local.close();
}
if (remote != null) {
await remote.stop(_nodeToken);
_nodeToken = '';
}
if (view.running) {
view = view.copyWith(running: false, phase: '已停止');
notifyListeners();
}
}
void _accept(int generation, ProbeSample sample) {
if (generation != _token) {
return;
}
final samples = [...view.samples];
if (samples.length >= 180) {
samples.removeAt(0);
}
final double? rate;
switch (view.rateLabel) {
case '探测无应答':
rate = sample.summary.probeLossPct;
case '失败率':
rate = sample.summary.failurePct;
default:
rate = sample.summary.unknownPct;
}
samples.add(
ChartSample(
sec: _clock.elapsedMilliseconds / 1000,
rttMs: sample.status == Outcome.ok ? sample.rttMs : null,
ratePct: rate,
),
);
view = view.copyWith(
phase: phaseFor(sample.status),
note: sample.note,
detail: sample.detail.isEmpty ? sample.summary.detail : sample.detail,
summary: sample.summary,
samples: samples,
clearBanner: true,
);
notifyListeners();
}
}
String? _echoProblem(String profileId, String echoToken) {
if (profileId != 'nq-tcp' && profileId != 'nq-udp') {
return null;
}
if (echoToken.length > 32) {
return '目标回显口令最长 32 字节';
}
return null;
}
String phaseFor(String status) {
switch (status) {
case Outcome.ok:
return '有应答';
case Outcome.timeout:
return '超时';
case Outcome.unknown:
return '无应答';
case Outcome.refused:
return '被拒绝';
case Outcome.dns:
return '域名失败';
case Outcome.protocol:
return '协议不符';
default:
return '出错';
}
}
+841
View File
@@ -0,0 +1,841 @@
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import '../metrics/sample_book.dart';
import '../protocol/probe_packet.dart';
import 'endpoint_picker.dart';
import 'game_codec.dart';
class ProbeRequest {
const ProbeRequest({
required this.host,
required this.port,
required this.profileId,
required this.interval,
required this.timeout,
required this.packetSize,
required this.echoToken,
required this.dnsName,
required this.payloadHex,
required this.expectHex,
});
final String host;
final int port;
final String profileId;
final Duration interval;
final Duration timeout;
final int packetSize;
final String echoToken;
final String dnsName;
final String payloadHex;
final String expectHex;
}
/// 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,
});
/// Replaces [lookupAll] in tests.
final Future<List<InternetAddress>> Function(String host)? lookup;
/// Fires when the address about to be used is chosen or changed.
final void Function(InternetAddress address)? onEndpoint;
_TcpPipe? _tcp;
_UdpPipe? _udp;
EndpointPicker? _picker;
InternetAddress? _announced;
int _seq = 0;
int _dnsId = 1;
final int _guid = DateTime.now().microsecondsSinceEpoch;
Future<void> run({
required ProbeRequest request,
required void Function(ProbeSample sample) onSample,
required bool Function() cancelled,
}) async {
final book = SampleBook(request.profileId);
try {
while (!cancelled()) {
final started = DateTime.now();
final outcome = await _once(request, cancelled);
if (cancelled() || outcome == null) {
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)) {
await _dropUdp();
_announce(_picker!.current);
}
}
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) {
await Future<void>.delayed(rest);
}
}
} finally {
await close();
}
}
Future<void> close() async {
final tcp = _tcp;
_tcp = null;
if (tcp != null) {
await tcp.close();
}
final udp = _udp;
_udp = null;
if (udp != null) {
await udp.close();
}
}
Future<Outcome?> _once(ProbeRequest request, bool Function() cancelled) async {
try {
final outcome = await _dispatch(request, cancelled);
final peer = _udp?.peer;
if (peer != null && _usesDatagram(request.profileId)) {
return _stampAddress(outcome, peer);
}
return outcome;
} on SocketException catch (error) {
if (cancelled()) {
return null;
}
return classifySocket(error);
} on TimeoutException {
if (cancelled()) {
return null;
}
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '连接超时',
);
}
}
Future<Outcome> _dispatch(ProbeRequest request, bool Function() cancelled) {
switch (request.profileId) {
case 'nq-tcp':
return _nqTcp(request, cancelled);
case 'nq-udp':
return _nqUdp(request, cancelled);
case 'tcp-connect':
return _tcpConnect(request, cancelled);
case 'udp-generic':
case 'custom-udp':
return _udpQuery(request, cancelled);
case 'dns':
return _dns(request, cancelled);
case 'minecraft-java':
return _java(request, cancelled);
case 'minecraft-bedrock':
return _bedrock(request, cancelled);
default:
return Future.value(
const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: '不支持的探测类型',
),
);
}
}
Future<Outcome> _tcpConnect(
ProbeRequest request,
bool Function() cancelled,
) async {
final watch = Stopwatch()..start();
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
watch.stop();
await socket.close();
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
}
return Outcome(
status: Outcome.ok,
kind: Outcome.connect,
rttMs: watch.elapsedMicroseconds / 1000,
note: 'TCP 已连通',
);
}
Future<Outcome> _nqTcp(ProbeRequest request, bool Function() cancelled) async {
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 pipe = _tcp!;
_seq += 1;
final seq = _seq;
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: seq,
clientSendUnixNano: DateTime.now().microsecondsSinceEpoch * 1000,
token: ProbePacket.encodeToken(request.echoToken),
payload: Uint8List(request.packetSize - ProbePacket.headerSize),
);
pipe.socket.add(packet.encode());
try {
await pipe.socket.flush();
} on SocketException {
await _dropTcp();
return const Outcome(
status: Outcome.error,
kind: Outcome.connect,
reconnect: true,
note: '发送失败,连接将重连',
);
}
final watch = Stopwatch()..start();
final matched = await pipe.waitMatch(request.timeout, (frame) {
try {
final reply = ProbePacket.decode(frame);
return reply.isReply && reply.sequence == seq;
} on ProbePacketException {
return false;
}
});
if (cancelled()) {
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 Outcome(
status: Outcome.ok,
kind: Outcome.probe,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到回显',
);
}
Future<void> _dropTcp() async {
final tcp = _tcp;
_tcp = null;
if (tcp != null) {
await tcp.close();
}
}
Future<Outcome> _nqUdp(ProbeRequest request, bool Function() cancelled) async {
final pipe = await _datagram(request);
_seq += 1;
final seq = _seq;
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: seq,
clientSendUnixNano: DateTime.now().microsecondsSinceEpoch * 1000,
token: ProbePacket.encodeToken(request.echoToken),
payload: Uint8List(request.packetSize - ProbePacket.headerSize),
);
final watch = Stopwatch()..start();
pipe.send(packet.encode(), request.port);
var sawInvalid = false;
final reply = await pipe.waitMatch(request.timeout, (data) {
try {
final parsed = ProbePacket.decode(data);
if (!parsed.isReply) {
sawInvalid = true;
return false;
}
return parsed.sequence == seq;
} on ProbePacketException {
sawInvalid = true;
return false;
}
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
if (sawInvalid) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.probe,
note: '收到的 UDP 包不是有效回显',
);
}
return const Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '未收到回显。这是探测没有应答,不是网卡上的物理丢包计数',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.probe,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到回显',
);
}
Future<Outcome> _udpQuery(
ProbeRequest request,
bool Function() cancelled,
) async {
final pipe = await _datagram(request);
late final Uint8List payload;
Uint8List? expect;
if (request.profileId == 'udp-generic') {
payload = Uint8List(request.packetSize.clamp(1, 1400));
} else {
payload = decodeHex(request.payloadHex);
if (request.expectHex.trim().isNotEmpty) {
expect = decodeHex(request.expectHex);
}
}
final watch = Stopwatch()..start();
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: '已停止');
}
if (reply == null) {
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '没有收到 UDP 应答,不能据此断定物理丢包',
);
}
final wanted = expect;
if (wanted != null && (reply.length < wanted.length || !_prefix(reply, wanted))) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '收到了数据,但和预期的响应不一致',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 UDP 响应',
);
}
Future<Outcome> _dns(ProbeRequest request, bool Function() cancelled) async {
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 watch = Stopwatch()..start();
pipe.send(dnsQuery(id, name), request.port);
var malformed = false;
final reply = await pipe.waitMatch(request.timeout, (data) {
if (data.length < 12) {
malformed = true;
return false;
}
final got = ByteData.sublistView(data).getUint16(0);
if (got != id) {
return false;
}
if ((data[2] & 0x80) == 0) {
malformed = true;
return false;
}
return true;
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
if (malformed) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '收到的包不是 DNS 应答',
);
}
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '没有收到 DNS 应答,不能据此断定物理丢包',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 DNS 应答',
);
}
Future<Outcome> _bedrock(
ProbeRequest request,
bool Function() cancelled,
) async {
final pipe = await _datagram(request);
final timestamp = DateTime.now().microsecondsSinceEpoch;
final watch = Stopwatch()..start();
pipe.send(bedrockPing(timestamp, _guid), request.port);
Map<String, String>? detail;
var sawInvalid = false;
final reply = await pipe.waitMatch(request.timeout, (data) {
final parsed = parseRakPong(data, timestamp);
if (parsed == null) {
sawInvalid = true;
return false;
}
detail = parsed;
return true;
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
if (sawInvalid) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '收到的包不是有效的 RakNet Pong',
);
}
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '未收到 RakNet 应答,不能据此断定物理丢包',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 Bedrock 应答',
detail: detail ?? const {},
);
}
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
final reader = _BytePipe(socket);
try {
socket.add(javaHandshake(request.host, request.port));
socket.add(javaStatusRequest());
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 状态响应无效',
);
}
final jsonText = readMcString(status, 1);
if (jsonText == null) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft 状态内容无法解析',
);
}
final detail = minecraftStatusDetail(jsonText);
final nonce = DateTime.now().microsecondsSinceEpoch;
final watch = Stopwatch()..start();
socket.add(javaPing(nonce));
await socket.flush();
final pong = await reader.nextPacket(request.timeout);
if (cancelled()) {
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,
);
}
if (ByteData.sublistView(pong).getUint64(1) != nonce) {
return Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft pong 的时间戳不匹配',
detail: detail,
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 Minecraft 状态和 ping 应答',
detail: detail,
);
} finally {
await reader.close();
await socket.close();
}
}
Future<_UdpPipe> _datagram(ProbeRequest request) async {
_picker ??= EndpointPicker(await (lookup ?? lookupAll)(request.host));
final want = _picker!.current;
final existing = _udp;
if (existing != null && existing.peer.address == want.address) {
return existing;
}
if (existing != null) {
await existing.close();
_udp = null;
}
final socket = await RawDatagramSocket.bind(
want.type == InternetAddressType.IPv6
? InternetAddress.anyIPv6
: InternetAddress.anyIPv4,
0,
);
final pipe = _UdpPipe(socket, want);
_udp = pipe;
_announce(want);
return pipe;
}
void _announce(InternetAddress address) {
if (_announced != null && _announced!.address == address.address) {
return;
}
_announced = address;
onEndpoint?.call(address);
}
Future<void> _dropUdp() async {
final udp = _udp;
_udp = null;
if (udp != null) {
await udp.close();
}
}
}
bool _usesDatagram(String profileId) {
switch (profileId) {
case 'nq-udp':
case 'udp-generic':
case 'custom-udp':
case 'dns':
case 'minecraft-bedrock':
return true;
default:
return false;
}
}
Outcome _stampAddress(Outcome outcome, InternetAddress peer) {
return Outcome(
status: outcome.status,
kind: outcome.kind,
rttMs: outcome.rttMs,
note: outcome.note,
reconnect: outcome.reconnect,
detail: {...outcome.detail, 'address': peer.address},
);
}
Outcome classifySocket(SocketException error, {bool reconnect = false}) {
final text = '${error.message} ${error.osError?.message ?? ''}'.toLowerCase();
final code = error.osError?.errorCode;
if (text.contains('timed out') || text.contains('timeout')) {
return Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
reconnect: reconnect,
note: reconnect ? '连接超时,将重试' : '连接超时',
);
}
if (text.contains('failed host lookup') ||
text.contains('name or service not known') ||
text.contains('nodename nor servname') ||
text.contains('no address associated')) {
return const Outcome(
status: Outcome.dns,
kind: Outcome.connect,
note: '域名无法解析',
);
}
if (code == 111 ||
code == 61 ||
code == 10061 ||
text.contains('connection refused') ||
text.contains('actively refused')) {
return Outcome(
status: Outcome.refused,
kind: Outcome.connect,
reconnect: reconnect,
note: '连接被拒绝',
);
}
return Outcome(
status: Outcome.error,
kind: Outcome.connect,
reconnect: reconnect,
note: '连接失败',
);
}
bool _prefix(Uint8List data, Uint8List prefix) {
for (var i = 0; i < prefix.length; i++) {
if (data[i] != prefix[i]) {
return false;
}
}
return true;
}
class _TcpPipe {
_TcpPipe(this.socket) {
_sub = socket.listen(
(data) {
try {
_frames.addAll(_buffer.add(data));
} on ProbePacketException {
_failed = true;
}
_signal();
},
onError: (Object _) {
_failed = true;
_signal();
},
onDone: () {
_failed = true;
_signal();
},
cancelOnError: true,
);
}
final Socket socket;
final FrameBuffer _buffer = FrameBuffer();
final List<Uint8List> _frames = [];
late final StreamSubscription<Uint8List> _sub;
Completer<void>? _pending;
bool _failed = false;
var _cursor = 0;
void _signal() {
final pending = _pending;
_pending = null;
if (pending != null && !pending.isCompleted) {
pending.complete();
}
}
Future<Uint8List?> waitMatch(
Duration timeout,
bool Function(Uint8List frame) match,
) async {
final deadline = DateTime.now().add(timeout);
while (true) {
while (_cursor < _frames.length) {
final frame = _frames[_cursor];
_cursor += 1;
if (match(frame)) {
return frame;
}
}
if (_failed) {
return null;
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (_cursor < _frames.length || _failed) {
_signal();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
if (identical(_pending, waiter)) {
_pending = null;
}
return null;
}
}
}
Future<void> close() async {
await _sub.cancel();
await socket.close();
_signal();
}
}
class _UdpPipe {
_UdpPipe(this.socket, this.peer) {
_sub = socket.listen((event) {
if (event != RawSocketEvent.read) {
return;
}
while (true) {
final datagram = socket.receive();
if (datagram == null) {
return;
}
_queue.add(Uint8List.fromList(datagram.data));
_signal();
}
});
}
final RawDatagramSocket socket;
final InternetAddress peer;
final List<Uint8List> _queue = [];
late final StreamSubscription<RawSocketEvent> _sub;
Completer<void>? _pending;
var _cursor = 0;
void send(List<int> bytes, int port) {
socket.send(bytes, peer, port);
}
void _signal() {
final pending = _pending;
_pending = null;
if (pending != null && !pending.isCompleted) {
pending.complete();
}
}
Future<Uint8List?> waitMatch(
Duration timeout,
bool Function(Uint8List data) match,
) async {
final deadline = DateTime.now().add(timeout);
while (true) {
while (_cursor < _queue.length) {
final data = _queue[_cursor];
_cursor += 1;
if (match(data)) {
return data;
}
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (_cursor < _queue.length) {
_signal();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
if (identical(_pending, waiter)) {
_pending = null;
}
return null;
}
}
}
Future<void> close() async {
await _sub.cancel();
socket.close();
_signal();
}
}
class _BytePipe {
_BytePipe(this.socket) {
_sub = socket.listen((data) {
_buf.add(data);
_signal();
});
}
final Socket socket;
final BytesBuilder _buf = BytesBuilder(copy: false);
late final StreamSubscription<Uint8List> _sub;
Completer<void>? _pending;
void _signal() {
final pending = _pending;
_pending = null;
if (pending != null && !pending.isCompleted) {
pending.complete();
}
}
Future<Uint8List?> nextPacket(Duration timeout) async {
final deadline = DateTime.now().add(timeout);
while (true) {
final bytes = _buf.toBytes();
final packet = takeMcPacket(bytes);
if (packet != null) {
_buf.clear();
if (packet.used < bytes.length) {
_buf.add(Uint8List.sublistView(bytes, packet.used));
}
return packet.payload;
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (takeMcPacket(_buf.toBytes()) != null) {
_signal();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
if (identical(_pending, waiter)) {
_pending = null;
}
return null;
}
}
}
Future<void> close() => _sub.cancel();
}
+281
View File
@@ -0,0 +1,281 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import '../metrics/sample_book.dart';
import '../models/session_config.dart';
class RemoteProbe {
HttpClient? _client;
String? _jobId;
Uri? _base;
Future<void> run({
required String baseUrl,
required String nodeToken,
required ProbeBody body,
required void Function(ProbeSample sample) onSample,
required bool Function() cancelled,
}) async {
final normalized = normalizeNodeUrl(baseUrl);
if (normalized == null) {
throw RemoteException('节点地址需要是 http 或 https,且不能把口令写在地址里');
}
_base = Uri.parse(normalized);
final client = HttpClient();
_client = client;
try {
final created = await _send(
client,
'POST',
_base!.resolve('/v1/jobs'),
nodeToken,
utf8.encode(jsonEncode(body.toJson())),
);
if (created.status >= 300 && created.status < 400) {
throw RemoteException('节点地址发生了跳转。请填写最终地址,不要在地址里带口令');
}
if (created.status == 401) {
throw RemoteException('节点口令不正确或未提供');
}
if (created.status == 429) {
throw RemoteException('节点同时探测的任务已达上限');
}
if (created.status == 403 || created.status == 400) {
throw RemoteException(_message(created.body) ?? '节点拒绝了这次探测');
}
if (created.status != 201) {
throw RemoteException('节点没有接受探测(${created.status})');
}
final parsed = jsonDecode(created.body);
if (parsed is! Map || parsed['jobId'] is! String) {
throw RemoteException('节点返回的任务无效');
}
_jobId = parsed['jobId'] as String;
if (cancelled()) {
return;
}
await _stream(client, nodeToken, onSample, cancelled);
} on RemoteException {
rethrow;
} on SocketException {
if (!cancelled()) {
throw RemoteException('连不上节点。请检查地址、端口和防火墙');
}
} on HandshakeException {
throw RemoteException('TLS 握手失败。请检查证书,或改用正确的 HTTPS 地址');
} on RedirectException {
throw RemoteException('节点地址发生了跳转。请填写最终地址,不要在地址里带口令');
} on HttpException {
if (!cancelled()) {
throw RemoteException('节点连接中断');
}
} on TimeoutException {
if (!cancelled()) {
throw RemoteException('节点没有及时响应');
}
} finally {
await stop(nodeToken);
}
}
Future<void> stop(String nodeToken) async {
final client = _client;
final id = _jobId;
final base = _base;
_jobId = null;
if (client != null && id != null && base != null) {
try {
await _send(client, 'DELETE', base.resolve('/v1/jobs/$id'), nodeToken, const []);
} on Object {
// The stream ending already asks the node to drop the job.
}
}
client?.close(force: true);
_client = null;
}
Future<void> _stream(
HttpClient client,
String nodeToken,
void Function(ProbeSample sample) onSample,
bool Function() cancelled,
) async {
final request = await client.getUrl(_base!.resolve('/v1/jobs/$_jobId/stream'));
request.followRedirects = false;
_auth(request, nodeToken);
final response = await request.close().timeout(const Duration(seconds: 20));
if (response.statusCode == 401) {
throw RemoteException('节点口令不正确或未提供');
}
if (response.statusCode != 200) {
throw RemoteException('无法接收节点上的探测结果');
}
var buffer = '';
await for (final chunk in response.transform(utf8.decoder)) {
if (cancelled()) {
return;
}
buffer += chunk;
while (buffer.contains('\n\n')) {
final split = buffer.indexOf('\n\n');
final block = buffer.substring(0, split);
buffer = buffer.substring(split + 2);
final sample = _sampleFromBlock(block);
if (sample != null) {
onSample(sample);
}
}
}
}
}
class ProbeBody {
const ProbeBody({
required this.target,
required this.port,
required this.profile,
required this.intervalMs,
required this.timeoutMs,
required this.durationSec,
required this.packetSize,
required this.echoToken,
required this.dnsName,
required this.payloadHex,
required this.expectHex,
});
final String target;
final int port;
final String profile;
final int intervalMs;
final int timeoutMs;
final int durationSec;
final int packetSize;
final String echoToken;
final String dnsName;
final String payloadHex;
final String expectHex;
Map<String, Object?> toJson() => {
'target': target,
'port': port,
'profile': profile,
'intervalMs': intervalMs,
'timeoutMs': timeoutMs,
'durationSec': durationSec,
'packetSize': packetSize,
'echoToken': echoToken,
'dnsName': dnsName,
'payloadHex': payloadHex,
'expectHex': expectHex,
};
}
class RemoteException implements Exception {
RemoteException(this.message);
final String message;
@override
String toString() => message;
}
class NodeInfo {
const NodeInfo({required this.visibility, required this.authRequired});
final String visibility;
final bool authRequired;
}
Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
final normalized = normalizeNodeUrl(baseUrl);
if (normalized == null) {
throw RemoteException('节点地址需要是 http 或 https,且不能把口令写在地址里');
}
final client = HttpClient();
try {
final request = await client.getUrl(Uri.parse(normalized).resolve('/v1/info'));
request.followRedirects = false;
final response = await request.close().timeout(const Duration(seconds: 8));
final body = await response.transform(utf8.decoder).join();
if (response.statusCode != 200) {
throw RemoteException('读不到节点信息');
}
final json = jsonDecode(body);
if (json is! Map) {
throw RemoteException('节点信息无效');
}
return NodeInfo(
visibility: json['visibility'] is String ? json['visibility'] as String : '',
authRequired: json['authRequired'] == true,
);
} on RemoteException {
rethrow;
} on SocketException {
throw RemoteException('连不上节点');
} on HandshakeException {
throw RemoteException('TLS 握手失败');
} finally {
client.close(force: true);
}
}
Future<({int status, String body})> _send(
HttpClient client,
String method,
Uri uri,
String nodeToken,
List<int> bytes,
) async {
final request = await client.openUrl(method, uri);
request.followRedirects = false;
request.headers.contentType = ContentType.json;
_auth(request, nodeToken);
request.add(bytes);
final response = await request.close().timeout(const Duration(seconds: 15));
final body = await response.transform(utf8.decoder).join();
return (status: response.statusCode, body: body);
}
void _auth(HttpClientRequest request, String nodeToken) {
if (nodeToken.isNotEmpty) {
request.headers.set(HttpHeaders.authorizationHeader, 'Bearer $nodeToken');
}
}
String? _message(String body) {
try {
final json = jsonDecode(body);
if (json is Map && json['message'] is String) {
return json['message'] as String;
}
} on FormatException {
return null;
}
return null;
}
ProbeSample? _sampleFromBlock(String block) {
String? data;
for (final line in block.split('\n')) {
if (line.startsWith('data: ')) {
data = line.substring(6);
}
}
if (data == null || data == '{}') {
return null;
}
try {
final json = jsonDecode(data);
if (json is! Map) {
return null;
}
final sample = ProbeSample.fromJson(Map<String, dynamic>.from(json));
if (sample.status.isEmpty || sample.status == 'pending') {
return null;
}
return sample;
} on FormatException {
return null;
}
}