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:
1 parent
948594e7c0
commit
f6ffbde518
93 files changed
+10570
-1
No files matched your search
@@ -0,0 +1,50 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'ui/home_page.dart';
|
||||
|
||||
void main() {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
runApp(const NetQualityApp());
|
||||
}
|
||||
|
||||
class NetQualityApp extends StatelessWidget {
|
||||
const NetQualityApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
const paper = Color(0xFFF3F1EC);
|
||||
final scheme = ColorScheme.fromSeed(
|
||||
seedColor: const Color(0xFF1F4E79),
|
||||
surface: paper,
|
||||
);
|
||||
return MaterialApp(
|
||||
title: '网络质量探测',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorScheme: scheme,
|
||||
scaffoldBackgroundColor: paper,
|
||||
useMaterial3: true,
|
||||
fontFamilyFallback: const [
|
||||
'NetQualityCJK',
|
||||
'Noto Sans CJK SC',
|
||||
'Noto Sans SC',
|
||||
'PingFang SC',
|
||||
'Microsoft YaHei',
|
||||
'Droid Sans Fallback',
|
||||
],
|
||||
inputDecorationTheme: const InputDecorationTheme(
|
||||
filled: true,
|
||||
fillColor: Color(0xFFFFFCF7),
|
||||
isDense: true,
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
cardTheme: const CardThemeData(
|
||||
elevation: 0,
|
||||
color: Color(0xFFFFFCF7),
|
||||
margin: EdgeInsets.zero,
|
||||
),
|
||||
),
|
||||
home: const HomePage(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
class Outcome {
|
||||
const Outcome({
|
||||
required this.status,
|
||||
required this.kind,
|
||||
this.rttMs,
|
||||
this.note = '',
|
||||
this.detail = const {},
|
||||
this.reconnect = false,
|
||||
});
|
||||
|
||||
final String status;
|
||||
final String kind;
|
||||
final double? rttMs;
|
||||
final String note;
|
||||
final Map<String, String> detail;
|
||||
final bool reconnect;
|
||||
|
||||
static const ok = 'ok';
|
||||
static const timeout = 'timeout';
|
||||
static const unknown = 'unknown';
|
||||
static const refused = 'refused';
|
||||
static const dns = 'dns';
|
||||
static const protocol = 'protocol';
|
||||
static const error = 'error';
|
||||
|
||||
static const connect = 'connect';
|
||||
static const probe = 'probe';
|
||||
static const query = 'query';
|
||||
}
|
||||
|
||||
class ProbeSummary {
|
||||
const ProbeSummary({
|
||||
required this.sent,
|
||||
required this.completed,
|
||||
required this.ok,
|
||||
required this.timeout,
|
||||
required this.unknown,
|
||||
required this.refused,
|
||||
required this.dns,
|
||||
required this.protocol,
|
||||
required this.other,
|
||||
required this.reconnects,
|
||||
required this.consecutiveFailures,
|
||||
required this.rttMs,
|
||||
required this.jitterMs,
|
||||
required this.probeLossPct,
|
||||
required this.failurePct,
|
||||
required this.unknownPct,
|
||||
required this.lastNote,
|
||||
required this.detail,
|
||||
});
|
||||
|
||||
final int sent;
|
||||
final int completed;
|
||||
final int ok;
|
||||
final int timeout;
|
||||
final int unknown;
|
||||
final int refused;
|
||||
final int dns;
|
||||
final int protocol;
|
||||
final int other;
|
||||
final int reconnects;
|
||||
final int consecutiveFailures;
|
||||
final double? rttMs;
|
||||
final double? jitterMs;
|
||||
final double? probeLossPct;
|
||||
final double? failurePct;
|
||||
final double? unknownPct;
|
||||
final String lastNote;
|
||||
final Map<String, String> detail;
|
||||
|
||||
static const empty = ProbeSummary(
|
||||
sent: 0,
|
||||
completed: 0,
|
||||
ok: 0,
|
||||
timeout: 0,
|
||||
unknown: 0,
|
||||
refused: 0,
|
||||
dns: 0,
|
||||
protocol: 0,
|
||||
other: 0,
|
||||
reconnects: 0,
|
||||
consecutiveFailures: 0,
|
||||
rttMs: null,
|
||||
jitterMs: null,
|
||||
probeLossPct: null,
|
||||
failurePct: null,
|
||||
unknownPct: null,
|
||||
lastNote: '',
|
||||
detail: {},
|
||||
);
|
||||
|
||||
factory ProbeSummary.fromJson(Map<String, dynamic> json) {
|
||||
return ProbeSummary(
|
||||
sent: _int(json['sent']),
|
||||
completed: _int(json['completed']),
|
||||
ok: _int(json['ok']),
|
||||
timeout: _int(json['timeout']),
|
||||
unknown: _int(json['unknown']),
|
||||
refused: _int(json['refused']),
|
||||
dns: _int(json['dns']),
|
||||
protocol: _int(json['protocol']),
|
||||
other: _int(json['other']),
|
||||
reconnects: _int(json['reconnects']),
|
||||
consecutiveFailures: _int(json['consecutiveFailures']),
|
||||
rttMs: _double(json['rttMs']),
|
||||
jitterMs: _double(json['jitterMs']),
|
||||
probeLossPct: _double(json['probeLossPct']),
|
||||
failurePct: _double(json['failurePct']),
|
||||
unknownPct: _double(json['unknownPct']),
|
||||
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
|
||||
detail: _detail(json['detail']),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ProbeSample {
|
||||
const ProbeSample({
|
||||
required this.seq,
|
||||
required this.status,
|
||||
required this.kind,
|
||||
required this.rttMs,
|
||||
required this.jitterMs,
|
||||
required this.note,
|
||||
required this.detail,
|
||||
required this.summary,
|
||||
});
|
||||
|
||||
final int seq;
|
||||
final String status;
|
||||
final String kind;
|
||||
final double? rttMs;
|
||||
final double? jitterMs;
|
||||
final String note;
|
||||
final Map<String, String> detail;
|
||||
final ProbeSummary summary;
|
||||
|
||||
factory ProbeSample.fromJson(Map<String, dynamic> json) {
|
||||
final summary = json['summary'] is Map
|
||||
? ProbeSummary.fromJson(Map<String, dynamic>.from(json['summary'] as Map))
|
||||
: ProbeSummary.empty;
|
||||
return ProbeSample(
|
||||
seq: _int(json['seq']),
|
||||
status: json['status'] is String ? json['status'] as String : '',
|
||||
kind: json['kind'] is String ? json['kind'] as String : '',
|
||||
rttMs: _double(json['rttMs']),
|
||||
jitterMs: _double(json['jitterMs']),
|
||||
note: json['note'] is String ? json['note'] as String : '',
|
||||
detail: _detail(json['detail']),
|
||||
summary: summary,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SampleBook {
|
||||
SampleBook(this.profile);
|
||||
|
||||
final String profile;
|
||||
int sent = 0;
|
||||
int completed = 0;
|
||||
int ok = 0;
|
||||
int timeout = 0;
|
||||
int unknown = 0;
|
||||
int refused = 0;
|
||||
int dns = 0;
|
||||
int protocol = 0;
|
||||
int other = 0;
|
||||
int reconnects = 0;
|
||||
int consecutive = 0;
|
||||
double? lastRttMs;
|
||||
double jitterMs = 0;
|
||||
bool _hasJitter = false;
|
||||
double _lastTransit = 0;
|
||||
String lastNote = '';
|
||||
Map<String, String> detail = {};
|
||||
|
||||
void add(Outcome outcome) {
|
||||
sent += 1;
|
||||
completed += 1;
|
||||
if (outcome.reconnect) {
|
||||
reconnects += 1;
|
||||
}
|
||||
if (outcome.note.isNotEmpty) {
|
||||
lastNote = outcome.note;
|
||||
}
|
||||
if (outcome.detail.isNotEmpty) {
|
||||
detail = {...detail, ...outcome.detail};
|
||||
}
|
||||
switch (outcome.status) {
|
||||
case Outcome.ok:
|
||||
ok += 1;
|
||||
consecutive = 0;
|
||||
final rtt = outcome.rttMs;
|
||||
if (rtt != null) {
|
||||
lastRttMs = rtt;
|
||||
if (_hasJitter) {
|
||||
final delta = (rtt - _lastTransit).abs();
|
||||
jitterMs += (delta - jitterMs) / 16;
|
||||
}
|
||||
_lastTransit = rtt;
|
||||
_hasJitter = true;
|
||||
}
|
||||
case Outcome.timeout:
|
||||
if (outcome.kind == Outcome.probe) {
|
||||
timeout += 1;
|
||||
} else {
|
||||
other += 1;
|
||||
}
|
||||
consecutive += 1;
|
||||
case Outcome.unknown:
|
||||
unknown += 1;
|
||||
case Outcome.refused:
|
||||
refused += 1;
|
||||
consecutive += 1;
|
||||
case Outcome.dns:
|
||||
dns += 1;
|
||||
consecutive += 1;
|
||||
case Outcome.protocol:
|
||||
protocol += 1;
|
||||
consecutive += 1;
|
||||
default:
|
||||
other += 1;
|
||||
consecutive += 1;
|
||||
}
|
||||
}
|
||||
|
||||
ProbeSummary summary() {
|
||||
double? probeLoss;
|
||||
double? failure;
|
||||
double? unknownPct;
|
||||
if (completed > 0) {
|
||||
if (profile == 'nq-tcp' || profile == 'nq-udp') {
|
||||
final denom = timeout + ok;
|
||||
if (denom > 0) {
|
||||
probeLoss = timeout * 100 / denom;
|
||||
}
|
||||
} else if (profile == 'tcp-connect' || profile == 'minecraft-java') {
|
||||
final denom = ok + timeout + refused + dns + protocol + other;
|
||||
if (denom > 0) {
|
||||
failure = (denom - ok) * 100 / denom;
|
||||
}
|
||||
} else {
|
||||
final denom = ok + protocol + refused + dns + other;
|
||||
if (denom > 0) {
|
||||
failure = (denom - ok) * 100 / denom;
|
||||
}
|
||||
final known = unknown + ok + protocol;
|
||||
if (known > 0) {
|
||||
unknownPct = unknown * 100 / completed;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ProbeSummary(
|
||||
sent: sent,
|
||||
completed: completed,
|
||||
ok: ok,
|
||||
timeout: timeout,
|
||||
unknown: unknown,
|
||||
refused: refused,
|
||||
dns: dns,
|
||||
protocol: protocol,
|
||||
other: other,
|
||||
reconnects: reconnects,
|
||||
consecutiveFailures: consecutive,
|
||||
rttMs: lastRttMs,
|
||||
jitterMs: _hasJitter ? jitterMs : null,
|
||||
probeLossPct: probeLoss,
|
||||
failurePct: failure,
|
||||
unknownPct: unknownPct,
|
||||
lastNote: lastNote,
|
||||
detail: detail,
|
||||
);
|
||||
}
|
||||
|
||||
ProbeSample sample(int seq, Outcome outcome) {
|
||||
final folded = summary();
|
||||
return ProbeSample(
|
||||
seq: seq,
|
||||
status: outcome.status,
|
||||
kind: outcome.kind,
|
||||
rttMs: outcome.rttMs,
|
||||
jitterMs: outcome.status == Outcome.ok ? folded.jitterMs : null,
|
||||
note: outcome.note,
|
||||
detail: outcome.detail,
|
||||
summary: folded,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
double? chartRate(String profile, ProbeSummary summary) {
|
||||
switch (profile) {
|
||||
case 'nq-tcp':
|
||||
case 'nq-udp':
|
||||
return summary.probeLossPct;
|
||||
case 'tcp-connect':
|
||||
case 'minecraft-java':
|
||||
return summary.failurePct;
|
||||
default:
|
||||
return summary.unknownPct;
|
||||
}
|
||||
}
|
||||
|
||||
int _int(Object? value) {
|
||||
if (value is int) {
|
||||
return value;
|
||||
}
|
||||
if (value is num) {
|
||||
return value.toInt();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
double? _double(Object? value) {
|
||||
if (value is num) {
|
||||
return value.toDouble();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Map<String, String> _detail(Object? value) {
|
||||
if (value is! Map) {
|
||||
return const {};
|
||||
}
|
||||
final out = <String, String>{};
|
||||
value.forEach((key, item) {
|
||||
if (key is String && item is String) {
|
||||
out[key] = item;
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
class ProbeProfile {
|
||||
const ProbeProfile({
|
||||
required this.id,
|
||||
required this.label,
|
||||
required this.port,
|
||||
required this.blurb,
|
||||
required this.rateLabel,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String label;
|
||||
final int port;
|
||||
final String blurb;
|
||||
|
||||
/// Name of the chart that is honest for this profile.
|
||||
final String rateLabel;
|
||||
|
||||
static const nqTcp = ProbeProfile(
|
||||
id: 'nq-tcp',
|
||||
label: '合作反射 TCP',
|
||||
port: 19090,
|
||||
blurb: '和 NetQuality 反射器保持一条 TCP 长连接,按回显计算往返时间。超时只表示探测没有应答,不是物理丢包。',
|
||||
rateLabel: '探测无应答',
|
||||
);
|
||||
static const nqUdp = ProbeProfile(
|
||||
id: 'nq-udp',
|
||||
label: '合作反射 UDP',
|
||||
port: 19091,
|
||||
blurb: '向 NetQuality 反射器发 UDP,收到对应序号的回显才算成功。',
|
||||
rateLabel: '探测无应答',
|
||||
);
|
||||
static const tcpConnect = ProbeProfile(
|
||||
id: 'tcp-connect',
|
||||
label: '普通 TCP 连通',
|
||||
port: 80,
|
||||
blurb: '只测量能否连上以及连接耗时,不发送自定义探测帧。',
|
||||
rateLabel: '失败率',
|
||||
);
|
||||
static const udpGeneric = ProbeProfile(
|
||||
id: 'udp-generic',
|
||||
label: '普通 UDP',
|
||||
port: 9,
|
||||
blurb: '发出 UDP 后如果没有协议应答,记为无应答/未知,不能当成丢包。',
|
||||
rateLabel: '无应答(未知)',
|
||||
);
|
||||
static const dns = ProbeProfile(
|
||||
id: 'dns',
|
||||
label: 'DNS',
|
||||
port: 53,
|
||||
blurb: '发送标准 DNS 查询,序号和应答标志都对上才算成功。',
|
||||
rateLabel: '无应答(未知)',
|
||||
);
|
||||
static const minecraftJava = ProbeProfile(
|
||||
id: 'minecraft-java',
|
||||
label: 'Minecraft Java',
|
||||
port: 25565,
|
||||
blurb: '按 Java 版状态握手读取 MOTD,再用 ping/pong 计算往返时间。',
|
||||
rateLabel: '失败率',
|
||||
);
|
||||
static const minecraftBedrock = ProbeProfile(
|
||||
id: 'minecraft-bedrock',
|
||||
label: 'Minecraft 基岩版',
|
||||
port: 19132,
|
||||
blurb: '发送 RakNet Unconnected Ping,校验 magic 和原时间戳。',
|
||||
rateLabel: '无应答(未知)',
|
||||
);
|
||||
static const customUdp = ProbeProfile(
|
||||
id: 'custom-udp',
|
||||
label: '自定义 UDP',
|
||||
port: 19132,
|
||||
blurb: '发送你填写的十六进制载荷。可以要求响应以前若干字节开头。',
|
||||
rateLabel: '无应答(未知)',
|
||||
);
|
||||
|
||||
static const all = <ProbeProfile>[
|
||||
nqTcp,
|
||||
nqUdp,
|
||||
tcpConnect,
|
||||
udpGeneric,
|
||||
dns,
|
||||
minecraftJava,
|
||||
minecraftBedrock,
|
||||
customUdp,
|
||||
];
|
||||
|
||||
static ProbeProfile byId(String id) {
|
||||
for (final profile in all) {
|
||||
if (profile.id == id) {
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
return nqTcp;
|
||||
}
|
||||
|
||||
bool get needsPacketSize =>
|
||||
id == 'nq-tcp' || id == 'nq-udp' || id == 'udp-generic';
|
||||
|
||||
bool get needsEchoToken => id == 'nq-tcp' || id == 'nq-udp';
|
||||
|
||||
bool get isNq => needsEchoToken;
|
||||
}
|
||||
|
||||
String rateLabelFor(String profileId) => ProbeProfile.byId(profileId).rateLabel;
|
||||
@@ -0,0 +1,291 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import '../protocol/probe_packet.dart';
|
||||
import 'probe_profile.dart';
|
||||
|
||||
class RemoteNode {
|
||||
const RemoteNode({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.baseUrl,
|
||||
this.visibility = '',
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String name;
|
||||
final String baseUrl;
|
||||
final String visibility;
|
||||
|
||||
RemoteNode copyWith({String? name, String? baseUrl, String? visibility}) {
|
||||
return RemoteNode(
|
||||
id: id,
|
||||
name: name ?? this.name,
|
||||
baseUrl: baseUrl ?? this.baseUrl,
|
||||
visibility: visibility ?? this.visibility,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'baseUrl': baseUrl,
|
||||
'visibility': visibility,
|
||||
};
|
||||
|
||||
factory RemoteNode.fromJson(Map<String, dynamic> json) {
|
||||
return RemoteNode(
|
||||
id: json['id'] is String ? json['id'] as String : '',
|
||||
name: json['name'] is String ? json['name'] as String : '未命名节点',
|
||||
baseUrl: json['baseUrl'] is String ? json['baseUrl'] as String : '',
|
||||
visibility: json['visibility'] is String ? json['visibility'] as String : '',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SessionConfig {
|
||||
const SessionConfig({
|
||||
required this.remote,
|
||||
required this.nodeId,
|
||||
required this.nodes,
|
||||
required this.host,
|
||||
required this.port,
|
||||
required this.profileId,
|
||||
required this.intervalMs,
|
||||
required this.timeoutMs,
|
||||
required this.durationSec,
|
||||
required this.packetSize,
|
||||
required this.dnsName,
|
||||
required this.payloadHex,
|
||||
required this.expectHex,
|
||||
});
|
||||
|
||||
static const defaults = SessionConfig(
|
||||
remote: false,
|
||||
nodeId: '',
|
||||
nodes: [],
|
||||
host: '127.0.0.1',
|
||||
port: 19090,
|
||||
profileId: 'nq-tcp',
|
||||
intervalMs: 300,
|
||||
timeoutMs: 1000,
|
||||
durationSec: 60,
|
||||
packetSize: 128,
|
||||
dnsName: 'example.com',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
);
|
||||
|
||||
final bool remote;
|
||||
final String nodeId;
|
||||
final List<RemoteNode> nodes;
|
||||
final String host;
|
||||
final int port;
|
||||
final String profileId;
|
||||
final int intervalMs;
|
||||
final int timeoutMs;
|
||||
final int durationSec;
|
||||
final int packetSize;
|
||||
final String dnsName;
|
||||
final String payloadHex;
|
||||
final String expectHex;
|
||||
|
||||
ProbeProfile get profile => ProbeProfile.byId(profileId);
|
||||
|
||||
RemoteNode? get node {
|
||||
for (final item in nodes) {
|
||||
if (item.id == nodeId) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String? validate() {
|
||||
if (host.trim().isEmpty) {
|
||||
return '请填写目标地址';
|
||||
}
|
||||
if (port < 1 || port > 65535) {
|
||||
return '端口需要在 1 到 65535 之间';
|
||||
}
|
||||
final minInterval = remote ? 200 : 100;
|
||||
if (intervalMs < minInterval || intervalMs > 30000) {
|
||||
return remote
|
||||
? '远程节点的发送间隔需要在 200 到 30000 毫秒之间'
|
||||
: '发送间隔需要在 100 到 30000 毫秒之间';
|
||||
}
|
||||
if (timeoutMs < 100 || timeoutMs > 15000) {
|
||||
return '超时需要在 100 到 15000 毫秒之间';
|
||||
}
|
||||
if (remote && (durationSec < 1 || durationSec > 300)) {
|
||||
return '远程探测时长需要在 1 到 300 秒之间,节点还会再加自己的上限';
|
||||
}
|
||||
if (profile.needsPacketSize &&
|
||||
(packetSize < ProbePacket.headerSize || packetSize > 1400)) {
|
||||
if (profileId == 'udp-generic' && (packetSize < 1 || packetSize > 1400)) {
|
||||
return '报文大小需要在 1 到 1400 字节之间';
|
||||
}
|
||||
if (profileId != 'udp-generic') {
|
||||
return '报文大小需要在 ${ProbePacket.headerSize} 到 1400 字节之间';
|
||||
}
|
||||
}
|
||||
if (profileId == 'dns' && dnsName.trim().isEmpty) {
|
||||
return '请填写要查询的域名';
|
||||
}
|
||||
if (profileId == 'custom-udp') {
|
||||
final payload = _hexError(payloadHex, allowEmpty: false);
|
||||
if (payload != null) {
|
||||
return '自定义载荷$payload';
|
||||
}
|
||||
final expect = _hexError(expectHex, allowEmpty: true);
|
||||
if (expect != null) {
|
||||
return '预期响应$expect';
|
||||
}
|
||||
}
|
||||
if (remote) {
|
||||
final selected = node;
|
||||
if (selected == null) {
|
||||
return '请先添加并选择一个远程节点';
|
||||
}
|
||||
if (normalizeNodeUrl(selected.baseUrl) == null) {
|
||||
return '节点地址需要是 http 或 https,且不能把口令写在地址里';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'remote': remote,
|
||||
'nodeId': nodeId,
|
||||
'nodes': nodes.map((node) => node.toJson()).toList(),
|
||||
'host': host,
|
||||
'port': port,
|
||||
'profileId': profileId,
|
||||
'intervalMs': intervalMs,
|
||||
'timeoutMs': timeoutMs,
|
||||
'durationSec': durationSec,
|
||||
'packetSize': packetSize,
|
||||
'dnsName': dnsName,
|
||||
'payloadHex': payloadHex,
|
||||
'expectHex': expectHex,
|
||||
};
|
||||
|
||||
factory SessionConfig.fromJson(Map<String, dynamic> json) {
|
||||
final rawNodes = json['nodes'];
|
||||
final nodes = <RemoteNode>[];
|
||||
if (rawNodes is List) {
|
||||
for (final item in rawNodes) {
|
||||
if (item is Map) {
|
||||
nodes.add(RemoteNode.fromJson(Map<String, dynamic>.from(item)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return SessionConfig(
|
||||
remote: json['remote'] == true,
|
||||
nodeId: json['nodeId'] is String ? json['nodeId'] as String : '',
|
||||
nodes: nodes,
|
||||
host: json['host'] is String ? json['host'] as String : defaults.host,
|
||||
port: _asInt(json['port'], defaults.port),
|
||||
profileId: json['profileId'] is String
|
||||
? json['profileId'] as String
|
||||
: defaults.profileId,
|
||||
intervalMs: _asInt(json['intervalMs'], defaults.intervalMs),
|
||||
timeoutMs: _asInt(json['timeoutMs'], defaults.timeoutMs),
|
||||
durationSec: _asInt(json['durationSec'], defaults.durationSec),
|
||||
packetSize: _asInt(json['packetSize'], defaults.packetSize),
|
||||
dnsName: json['dnsName'] is String
|
||||
? json['dnsName'] as String
|
||||
: defaults.dnsName,
|
||||
payloadHex: json['payloadHex'] is String ? json['payloadHex'] as String : '',
|
||||
expectHex: json['expectHex'] is String ? json['expectHex'] as String : '',
|
||||
);
|
||||
}
|
||||
|
||||
static int _asInt(Object? value, int fallback) {
|
||||
if (value is int) {
|
||||
return value;
|
||||
}
|
||||
if (value is num) {
|
||||
return value.toInt();
|
||||
}
|
||||
if (value is String) {
|
||||
return int.tryParse(value) ?? fallback;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
String? _hexError(String raw, {required bool allowEmpty}) {
|
||||
final text = raw.replaceAll(RegExp(r'\s'), '');
|
||||
if (text.isEmpty) {
|
||||
return allowEmpty ? null : '需要是十六进制';
|
||||
}
|
||||
if (text.length.isOdd || !RegExp(r'^[0-9a-fA-F]+$').hasMatch(text)) {
|
||||
return '需要是偶数位的十六进制';
|
||||
}
|
||||
if (text.length > 2800) {
|
||||
return '太长了';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Accepts an operator control URL and refuses credentials embedded in it.
|
||||
String? normalizeNodeUrl(String input) {
|
||||
final trimmed = input.trim();
|
||||
final uri = Uri.tryParse(trimmed);
|
||||
if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
if (uri.scheme != 'http' && uri.scheme != 'https') {
|
||||
return null;
|
||||
}
|
||||
if (uri.userInfo.isNotEmpty) {
|
||||
return null;
|
||||
}
|
||||
final port = uri.hasPort ? ':${uri.port}' : '';
|
||||
final path = uri.path.isEmpty || uri.path == '/' ? '' : uri.path;
|
||||
return '${uri.scheme}://${uri.host}$port$path';
|
||||
}
|
||||
|
||||
bool nodeUrlLooksPublic(String url) {
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null) {
|
||||
return false;
|
||||
}
|
||||
final host = uri.host.toLowerCase();
|
||||
return host != 'localhost' &&
|
||||
host != '127.0.0.1' &&
|
||||
host != '::1' &&
|
||||
uri.scheme == 'http';
|
||||
}
|
||||
|
||||
/// Legacy v1 settings stored the echo token beside the host. Migrate the
|
||||
/// non-secret fields and return the token so the caller can move it out.
|
||||
({SessionConfig config, String echoToken}) migrateV1(String raw) {
|
||||
final json = jsonDecode(raw);
|
||||
if (json is! Map) {
|
||||
return (config: SessionConfig.defaults, echoToken: '');
|
||||
}
|
||||
final map = Map<String, dynamic>.from(json);
|
||||
final token = map['token'] is String ? map['token'] as String : '';
|
||||
final tcp = SessionConfig._asInt(map['tcpPort'], 19090);
|
||||
final udp = SessionConfig._asInt(map['udpPort'], 19091);
|
||||
final enableTcp = map['enableTcp'] != false;
|
||||
return (
|
||||
config: SessionConfig(
|
||||
remote: false,
|
||||
nodeId: '',
|
||||
nodes: const [],
|
||||
host: map['host'] is String ? map['host'] as String : '127.0.0.1',
|
||||
port: enableTcp ? tcp : udp,
|
||||
profileId: enableTcp ? 'nq-tcp' : 'nq-udp',
|
||||
intervalMs: SessionConfig._asInt(map['intervalMs'], 300),
|
||||
timeoutMs: SessionConfig._asInt(map['timeoutMs'], 1000),
|
||||
durationSec: 60,
|
||||
packetSize: SessionConfig._asInt(map['packetSize'], 128),
|
||||
dnsName: 'example.com',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
),
|
||||
echoToken: token,
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 '出错';
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
/// Wire format shared by TCP frames and UDP datagrams.
|
||||
///
|
||||
/// See docs/PROTOCOL.md. Header is 62 bytes, little-endian.
|
||||
/// A TCP stream is a sequence of these frames. A UDP datagram is exactly one.
|
||||
class ProbePacket {
|
||||
ProbePacket({
|
||||
required this.type,
|
||||
required this.sequence,
|
||||
required this.clientSendUnixNano,
|
||||
this.serverUnixNano = 0,
|
||||
Uint8List? token,
|
||||
Uint8List? payload,
|
||||
this.version = version1,
|
||||
}) : token = token ?? Uint8List(tokenLength),
|
||||
payload = payload ?? Uint8List(0);
|
||||
|
||||
static const version1 = 1;
|
||||
static const headerSize = 62;
|
||||
static const tokenLength = 32;
|
||||
static const tokenOffset = 28;
|
||||
static const maxPayload = 2048;
|
||||
static const typeRequest = 1;
|
||||
static const typeReply = 2;
|
||||
|
||||
static const magic0 = 0x4e; // N
|
||||
static const magic1 = 0x51; // Q
|
||||
static const magic2 = 0x30; // 0
|
||||
static const magic3 = 0x31; // 1
|
||||
|
||||
final int version;
|
||||
final int type;
|
||||
final int sequence;
|
||||
final int clientSendUnixNano;
|
||||
final int serverUnixNano;
|
||||
final Uint8List token;
|
||||
final Uint8List payload;
|
||||
|
||||
bool get isReply => type == typeReply;
|
||||
|
||||
Uint8List encode() {
|
||||
if (token.length != tokenLength) {
|
||||
throw ProbePacketException('token must be $tokenLength bytes');
|
||||
}
|
||||
if (payload.length > maxPayload) {
|
||||
throw ProbePacketException('payload too large');
|
||||
}
|
||||
final out = Uint8List(headerSize + payload.length);
|
||||
final data = ByteData.sublistView(out);
|
||||
out[0] = magic0;
|
||||
out[1] = magic1;
|
||||
out[2] = magic2;
|
||||
out[3] = magic3;
|
||||
data.setUint8(4, version);
|
||||
data.setUint8(5, type);
|
||||
data.setUint8(6, 0);
|
||||
data.setUint8(7, 0);
|
||||
data.setUint32(8, sequence, Endian.little);
|
||||
data.setUint64(12, clientSendUnixNano, Endian.little);
|
||||
data.setUint64(20, serverUnixNano, Endian.little);
|
||||
out.setRange(tokenOffset, tokenOffset + tokenLength, token);
|
||||
data.setUint16(60, payload.length, Endian.little);
|
||||
out.setRange(headerSize, out.length, payload);
|
||||
return out;
|
||||
}
|
||||
|
||||
static ProbePacket decode(Uint8List bytes) {
|
||||
if (bytes.length < headerSize) {
|
||||
throw ProbePacketException('packet shorter than header');
|
||||
}
|
||||
if (bytes[0] != magic0 ||
|
||||
bytes[1] != magic1 ||
|
||||
bytes[2] != magic2 ||
|
||||
bytes[3] != magic3) {
|
||||
throw ProbePacketException('bad magic');
|
||||
}
|
||||
final data = ByteData.sublistView(bytes);
|
||||
final version = data.getUint8(4);
|
||||
if (version != version1) {
|
||||
throw ProbePacketException('unsupported version $version');
|
||||
}
|
||||
final type = data.getUint8(5);
|
||||
if (type != typeRequest && type != typeReply) {
|
||||
throw ProbePacketException('unsupported type $type');
|
||||
}
|
||||
final payloadLen = data.getUint16(60, Endian.little);
|
||||
if (payloadLen > maxPayload) {
|
||||
throw ProbePacketException('payload too large');
|
||||
}
|
||||
final total = headerSize + payloadLen;
|
||||
if (bytes.length != total) {
|
||||
throw ProbePacketException(
|
||||
'length mismatch: have ${bytes.length}, want $total',
|
||||
);
|
||||
}
|
||||
return ProbePacket(
|
||||
version: version,
|
||||
type: type,
|
||||
sequence: data.getUint32(8, Endian.little),
|
||||
clientSendUnixNano: data.getUint64(12, Endian.little),
|
||||
serverUnixNano: data.getUint64(20, Endian.little),
|
||||
token: Uint8List.sublistView(bytes, tokenOffset, tokenOffset + tokenLength),
|
||||
payload: payloadLen == 0
|
||||
? Uint8List(0)
|
||||
: Uint8List.sublistView(bytes, headerSize, total),
|
||||
);
|
||||
}
|
||||
|
||||
/// UTF-8 token padded with zeros. Empty string is 32 zero bytes.
|
||||
static Uint8List encodeToken(String token) {
|
||||
final raw = utf8.encode(token);
|
||||
if (raw.length > tokenLength) {
|
||||
throw ProbePacketException('口令最长 $tokenLength 字节');
|
||||
}
|
||||
final out = Uint8List(tokenLength);
|
||||
out.setRange(0, raw.length, raw);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
class ProbePacketException implements Exception {
|
||||
ProbePacketException(this.message);
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// Reassembles TCP frames. UDP datagrams are already one frame and do not
|
||||
/// need this buffer.
|
||||
class FrameBuffer {
|
||||
final BytesBuilder _buf = BytesBuilder(copy: false);
|
||||
|
||||
List<Uint8List> add(List<int> chunk) {
|
||||
_buf.add(chunk);
|
||||
final bytes = _buf.toBytes();
|
||||
var offset = 0;
|
||||
final frames = <Uint8List>[];
|
||||
while (bytes.length - offset >= ProbePacket.headerSize) {
|
||||
final view = ByteData.sublistView(bytes, offset);
|
||||
final payloadLen = view.getUint16(60, Endian.little);
|
||||
if (payloadLen > ProbePacket.maxPayload) {
|
||||
_buf.clear();
|
||||
throw ProbePacketException('payload too large');
|
||||
}
|
||||
final total = ProbePacket.headerSize + payloadLen;
|
||||
if (bytes.length - offset < total) {
|
||||
break;
|
||||
}
|
||||
frames.add(Uint8List.sublistView(bytes, offset, offset + total));
|
||||
offset += total;
|
||||
}
|
||||
_buf.clear();
|
||||
if (offset < bytes.length) {
|
||||
_buf.add(Uint8List.sublistView(bytes, offset));
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_buf.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../models/session_config.dart';
|
||||
import 'token_vault.dart';
|
||||
|
||||
class AppStore {
|
||||
static const _key = 'netquality.settings.v2';
|
||||
static const _legacy = 'netquality.settings.v1';
|
||||
|
||||
Future<({SessionConfig config, String legacyEcho})> load() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = prefs.getString(_key);
|
||||
if (raw != null && raw.isNotEmpty) {
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is Map) {
|
||||
return (
|
||||
config: SessionConfig.fromJson(Map<String, dynamic>.from(decoded)),
|
||||
legacyEcho: '',
|
||||
);
|
||||
}
|
||||
} on FormatException {
|
||||
return (config: SessionConfig.defaults, legacyEcho: '');
|
||||
}
|
||||
}
|
||||
final legacy = prefs.getString(_legacy);
|
||||
if (legacy != null && legacy.isNotEmpty) {
|
||||
try {
|
||||
final migrated = migrateV1(legacy);
|
||||
await save(migrated.config);
|
||||
await prefs.remove(_legacy);
|
||||
return (config: migrated.config, legacyEcho: migrated.echoToken);
|
||||
} on FormatException {
|
||||
return (config: SessionConfig.defaults, legacyEcho: '');
|
||||
}
|
||||
}
|
||||
return (config: SessionConfig.defaults, legacyEcho: '');
|
||||
}
|
||||
|
||||
Future<void> save(SessionConfig config) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_key, jsonEncode(config.toJson()));
|
||||
}
|
||||
}
|
||||
|
||||
Future<TokenVault> openTokenVault() async {
|
||||
try {
|
||||
final dir = await getApplicationSupportDirectory();
|
||||
final vault = FileTokenVault(File('${dir.path}/node-tokens.json'));
|
||||
await vault.load();
|
||||
return vault;
|
||||
} on Object {
|
||||
return MemoryTokenVault();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
/// Stores node-control tokens and the target echo token outside preferences.
|
||||
///
|
||||
/// The file lives in the app's private support directory. On Unix it is
|
||||
/// created with mode 0600. Tokens are never written into URLs or logs.
|
||||
abstract class TokenVault {
|
||||
Future<String?> read(String key);
|
||||
Future<void> write(String key, String value);
|
||||
Future<void> delete(String key);
|
||||
}
|
||||
|
||||
class MemoryTokenVault implements TokenVault {
|
||||
final Map<String, String> _values = {};
|
||||
|
||||
@override
|
||||
Future<void> delete(String key) async {
|
||||
_values.remove(key);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> read(String key) async => _values[key];
|
||||
|
||||
@override
|
||||
Future<void> write(String key, String value) async {
|
||||
if (value.isEmpty) {
|
||||
_values.remove(key);
|
||||
return;
|
||||
}
|
||||
_values[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
class FileTokenVault implements TokenVault {
|
||||
FileTokenVault(this.file);
|
||||
|
||||
final File file;
|
||||
final Map<String, String> _values = {};
|
||||
bool _loaded = false;
|
||||
|
||||
Future<void> load() async {
|
||||
if (_loaded) {
|
||||
return;
|
||||
}
|
||||
_loaded = true;
|
||||
if (!await file.exists()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final decoded = jsonDecode(await file.readAsString());
|
||||
if (decoded is Map) {
|
||||
decoded.forEach((key, value) {
|
||||
if (key is String && value is String && value.isNotEmpty) {
|
||||
_values[key] = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
} on FormatException {
|
||||
_values.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> delete(String key) async {
|
||||
await load();
|
||||
_values.remove(key);
|
||||
await _flush();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> read(String key) async {
|
||||
await load();
|
||||
return _values[key];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> write(String key, String value) async {
|
||||
await load();
|
||||
if (value.isEmpty) {
|
||||
_values.remove(key);
|
||||
} else {
|
||||
_values[key] = value;
|
||||
}
|
||||
await _flush();
|
||||
}
|
||||
|
||||
Future<void> _flush() async {
|
||||
await file.parent.create(recursive: true);
|
||||
await file.writeAsString(jsonEncode(_values), flush: true);
|
||||
if (!Platform.isWindows) {
|
||||
try {
|
||||
await Process.run('chmod', ['600', file.path]);
|
||||
} on ProcessException {
|
||||
// The app directory is already private on Android.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const echoTokenKey = 'target-echo-token';
|
||||
|
||||
String nodeTokenKey(String nodeId) => 'node-token.$nodeId';
|
||||
@@ -0,0 +1,76 @@
|
||||
import '../metrics/sample_book.dart';
|
||||
|
||||
String formatMs(double? ms) {
|
||||
if (ms == null) {
|
||||
return '—';
|
||||
}
|
||||
if (ms < 1) {
|
||||
return '${ms.toStringAsFixed(3)} ms';
|
||||
}
|
||||
if (ms < 10) {
|
||||
return '${ms.toStringAsFixed(2)} ms';
|
||||
}
|
||||
if (ms < 100) {
|
||||
return '${ms.toStringAsFixed(1)} ms';
|
||||
}
|
||||
return '${ms.toStringAsFixed(0)} ms';
|
||||
}
|
||||
|
||||
String formatPct(double? pct) {
|
||||
if (pct == null) {
|
||||
return '—';
|
||||
}
|
||||
if (pct == 0) {
|
||||
return '0%';
|
||||
}
|
||||
if (pct < 10) {
|
||||
return '${pct.toStringAsFixed(1)}%';
|
||||
}
|
||||
return '${pct.toStringAsFixed(0)}%';
|
||||
}
|
||||
|
||||
String visibilityLabel(String visibility) {
|
||||
switch (visibility) {
|
||||
case 'public':
|
||||
return '公开';
|
||||
case 'private':
|
||||
return '需要口令';
|
||||
default:
|
||||
return '未检查';
|
||||
}
|
||||
}
|
||||
|
||||
String summaryLine(ProbeSummary summary) {
|
||||
if (summary.completed == 0) {
|
||||
return '还没有完成的探测';
|
||||
}
|
||||
final parts = <String>[
|
||||
'完成 ${summary.completed}',
|
||||
'成功 ${summary.ok}',
|
||||
];
|
||||
if (summary.timeout > 0) {
|
||||
parts.add('超时 ${summary.timeout}');
|
||||
}
|
||||
if (summary.unknown > 0) {
|
||||
parts.add('无应答 ${summary.unknown}');
|
||||
}
|
||||
if (summary.refused > 0) {
|
||||
parts.add('拒绝 ${summary.refused}');
|
||||
}
|
||||
if (summary.dns > 0) {
|
||||
parts.add('域名 ${summary.dns}');
|
||||
}
|
||||
if (summary.protocol > 0) {
|
||||
parts.add('协议 ${summary.protocol}');
|
||||
}
|
||||
if (summary.other > 0) {
|
||||
parts.add('其他失败 ${summary.other}');
|
||||
}
|
||||
if (summary.reconnects > 0) {
|
||||
parts.add('重连 ${summary.reconnects}');
|
||||
}
|
||||
if (summary.consecutiveFailures > 0) {
|
||||
parts.add('连续失败 ${summary.consecutiveFailures}');
|
||||
}
|
||||
return parts.join(' · ');
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../models/probe_profile.dart';
|
||||
import '../models/session_config.dart';
|
||||
import '../probe/endpoint_picker.dart';
|
||||
import '../probe/probe_controller.dart';
|
||||
import '../probe/remote_client.dart';
|
||||
import '../storage/app_store.dart';
|
||||
import '../storage/token_vault.dart';
|
||||
import 'format.dart';
|
||||
import 'quality_charts.dart';
|
||||
|
||||
class HomePage extends StatefulWidget {
|
||||
const HomePage({super.key});
|
||||
|
||||
@override
|
||||
State<HomePage> createState() => _HomePageState();
|
||||
}
|
||||
|
||||
class _HomePageState extends State<HomePage> {
|
||||
final _controller = ProbeController();
|
||||
final _store = AppStore();
|
||||
TokenVault _vault = MemoryTokenVault();
|
||||
final _host = TextEditingController(text: SessionConfig.defaults.host);
|
||||
final _port = TextEditingController(text: '${SessionConfig.defaults.port}');
|
||||
final _interval = TextEditingController(text: '300');
|
||||
final _timeout = TextEditingController(text: '1000');
|
||||
final _duration = TextEditingController(text: '60');
|
||||
final _size = TextEditingController(text: '128');
|
||||
final _echo = TextEditingController();
|
||||
final _dns = TextEditingController(text: 'example.com');
|
||||
final _payload = TextEditingController();
|
||||
final _expect = TextEditingController();
|
||||
var _remote = false;
|
||||
var _profileId = ProbeProfile.nqTcp.id;
|
||||
var _nodeId = '';
|
||||
var _nodes = <RemoteNode>[];
|
||||
var _ready = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller.addListener(_rebuild);
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
_vault = await openTokenVault();
|
||||
final loaded = await _store.load();
|
||||
final echo = await _vault.read(echoTokenKey);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
final config = loaded.config;
|
||||
setState(() {
|
||||
_remote = config.remote;
|
||||
_nodeId = config.nodeId;
|
||||
_nodes = config.nodes;
|
||||
_profileId = config.profileId;
|
||||
_host.text = config.host;
|
||||
_port.text = '${config.port}';
|
||||
_interval.text = '${config.intervalMs}';
|
||||
_timeout.text = '${config.timeoutMs}';
|
||||
_duration.text = '${config.durationSec}';
|
||||
_size.text = '${config.packetSize}';
|
||||
_dns.text = config.dnsName;
|
||||
_payload.text = config.payloadHex;
|
||||
_expect.text = config.expectHex;
|
||||
_echo.text = (echo == null || echo.isEmpty) ? loaded.legacyEcho : echo;
|
||||
_ready = true;
|
||||
});
|
||||
if (loaded.legacyEcho.isNotEmpty && (echo == null || echo.isEmpty)) {
|
||||
await _vault.write(echoTokenKey, loaded.legacyEcho);
|
||||
}
|
||||
}
|
||||
|
||||
void _rebuild() {
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
unawaited(_controller.stop());
|
||||
unawaited(_persist());
|
||||
_controller.removeListener(_rebuild);
|
||||
_controller.dispose();
|
||||
for (final field in [
|
||||
_host,
|
||||
_port,
|
||||
_interval,
|
||||
_timeout,
|
||||
_duration,
|
||||
_size,
|
||||
_echo,
|
||||
_dns,
|
||||
_payload,
|
||||
_expect,
|
||||
]) {
|
||||
field.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
SessionConfig _config() {
|
||||
return SessionConfig(
|
||||
remote: _remote,
|
||||
nodeId: _nodeId,
|
||||
nodes: _nodes,
|
||||
host: _host.text.trim(),
|
||||
port: int.tryParse(_port.text.trim()) ?? 0,
|
||||
profileId: _profileId,
|
||||
intervalMs: int.tryParse(_interval.text.trim()) ?? 0,
|
||||
timeoutMs: int.tryParse(_timeout.text.trim()) ?? 0,
|
||||
durationSec: int.tryParse(_duration.text.trim()) ?? 0,
|
||||
packetSize: int.tryParse(_size.text.trim()) ?? 0,
|
||||
dnsName: _dns.text.trim(),
|
||||
payloadHex: _payload.text.trim(),
|
||||
expectHex: _expect.text.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _persist() async {
|
||||
await _store.save(_config());
|
||||
await _vault.write(echoTokenKey, _echo.text);
|
||||
}
|
||||
|
||||
Future<void> _start() async {
|
||||
await _persist();
|
||||
final config = _config();
|
||||
final nodeToken = config.node == null
|
||||
? ''
|
||||
: (await _vault.read(nodeTokenKey(config.node!.id)) ?? '');
|
||||
await _controller.start(config, nodeToken: nodeToken, echoToken: _echo.text);
|
||||
}
|
||||
|
||||
void _changeProfile(String? id) {
|
||||
if (id == null) {
|
||||
return;
|
||||
}
|
||||
final previous = ProbeProfile.byId(_profileId);
|
||||
final next = ProbeProfile.byId(id);
|
||||
setState(() {
|
||||
if (_port.text.trim() == '${previous.port}') {
|
||||
_port.text = '${next.port}';
|
||||
}
|
||||
_profileId = id;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final view = _controller.view;
|
||||
final profile = ProbeProfile.byId(_profileId);
|
||||
final wide = MediaQuery.sizeOf(context).width >= 720;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('网络质量探测'),
|
||||
backgroundColor: const Color(0xFFF3F1EC),
|
||||
),
|
||||
body: SafeArea(
|
||||
child: Align(
|
||||
alignment: Alignment.topCenter,
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 880),
|
||||
child: ListView(
|
||||
padding: EdgeInsets.fromLTRB(wide ? 24 : 12, 8, wide ? 24 : 12, 28),
|
||||
children: [
|
||||
_card(
|
||||
title: '探测来源',
|
||||
child: _source(view, wide),
|
||||
),
|
||||
_card(
|
||||
title: '目标',
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_pair(
|
||||
wide,
|
||||
_field(_host, '目标地址', '域名或 IP'),
|
||||
_field(_port, '端口', '1–65535'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
DropdownButtonFormField<String>(
|
||||
key: const Key('profile'),
|
||||
initialValue: _profileId,
|
||||
decoration: const InputDecoration(labelText: '探测类型'),
|
||||
items: [
|
||||
for (final item in ProbeProfile.all)
|
||||
DropdownMenuItem(value: item.id, child: Text(item.label)),
|
||||
],
|
||||
onChanged: view.running ? null : _changeProfile,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(profile.blurb, style: const TextStyle(color: muted, fontSize: 13)),
|
||||
],
|
||||
),
|
||||
),
|
||||
_card(
|
||||
title: '参数',
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_pair(
|
||||
wide,
|
||||
_field(_interval, '间隔(毫秒)', _remote ? '至少 200' : '至少 100'),
|
||||
_field(_timeout, '超时(毫秒)', '100–15000'),
|
||||
),
|
||||
if (profile.needsPacketSize) ...[
|
||||
const SizedBox(height: 12),
|
||||
_field(_size, '报文大小(字节)', '最大 1400'),
|
||||
],
|
||||
if (_remote) ...[
|
||||
const SizedBox(height: 12),
|
||||
_field(_duration, '时长(秒)', '到点后节点会停止'),
|
||||
],
|
||||
if (profile.needsEchoToken) ...[
|
||||
const SizedBox(height: 12),
|
||||
_field(
|
||||
_echo,
|
||||
'目标回显口令',
|
||||
'可选,只放进探测包,和节点口令不是同一个',
|
||||
secret: true,
|
||||
),
|
||||
],
|
||||
if (profile.id == 'dns') ...[
|
||||
const SizedBox(height: 12),
|
||||
_field(_dns, '查询域名', '例如 example.com'),
|
||||
],
|
||||
if (profile.id == 'custom-udp') ...[
|
||||
const SizedBox(height: 12),
|
||||
_field(_payload, '载荷(十六进制)', '例如 0102'),
|
||||
const SizedBox(height: 12),
|
||||
_field(_expect, '响应需以此开头(十六进制,可空)', '不填则任意响应都算成功'),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: !_ready
|
||||
? null
|
||||
: view.running
|
||||
? _controller.stop
|
||||
: _start,
|
||||
child: Text(view.running ? '停止探测' : '开始探测'),
|
||||
),
|
||||
if (view.banner != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
_banner(view.banner!),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
_card(title: '结果', child: _result(view)),
|
||||
QualityCharts(
|
||||
samples: view.samples,
|
||||
rateLabel: view.rateLabel,
|
||||
running: view.running,
|
||||
),
|
||||
const Text(
|
||||
'延迟用发包一侧的单调时钟计算。远程探测时,这个时间在节点上量好再传回来,不包含手机到节点的控制通道耗时。TCP 超时不是物理丢包。没有协议应答的 UDP 记为无应答/未知,不会在探测完成前显示 100%。',
|
||||
style: TextStyle(color: muted, fontSize: 12, height: 1.4),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _source(ProbeView view, bool wide) {
|
||||
final selected = _nodes.cast<RemoteNode?>().followedBy(const [null]).firstWhere(
|
||||
(node) => node?.id == _nodeId,
|
||||
orElse: () => null,
|
||||
);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
SegmentedButton<bool>(
|
||||
segments: const [
|
||||
ButtonSegment(value: false, label: Text('本机'), icon: Icon(Icons.phone_android)),
|
||||
ButtonSegment(value: true, label: Text('远程节点'), icon: Icon(Icons.dns_outlined)),
|
||||
],
|
||||
selected: {_remote},
|
||||
onSelectionChanged: view.running
|
||||
? null
|
||||
: (value) => setState(() => _remote = value.first),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_remote
|
||||
? '由选中的节点向目标发包,这台设备只负责控制和显示。'
|
||||
: '由这台设备直接向目标发包。可以探测本机上的反射器。',
|
||||
style: const TextStyle(color: muted, fontSize: 13),
|
||||
),
|
||||
if (_remote) ...[
|
||||
const SizedBox(height: 12),
|
||||
_pair(
|
||||
wide,
|
||||
DropdownButtonFormField<String>(
|
||||
key: const Key('node-selector'),
|
||||
initialValue: selected == null ? '' : selected.id,
|
||||
decoration: const InputDecoration(labelText: '节点'),
|
||||
items: [
|
||||
const DropdownMenuItem(value: '', child: Text('未选择')),
|
||||
for (final node in _nodes)
|
||||
DropdownMenuItem(
|
||||
value: node.id,
|
||||
child: Text(_nodeLabel(node)),
|
||||
),
|
||||
],
|
||||
onChanged: view.running
|
||||
? null
|
||||
: (value) => setState(() => _nodeId = value ?? ''),
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: view.running ? null : _manageNodes,
|
||||
child: const Text('管理节点'),
|
||||
),
|
||||
),
|
||||
if (selected != null && nodeUrlLooksPublic(selected.baseUrl))
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(top: 8),
|
||||
child: Text(
|
||||
'这个控制地址没有使用 HTTPS。口令会暴露在链路上,请改用 TLS 或 HTTPS 反向代理。',
|
||||
style: TextStyle(color: Color(0xFF9A3412), fontSize: 12),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _nodeLabel(RemoteNode node) {
|
||||
final vis = visibilityLabel(node.visibility);
|
||||
return '${node.name} · $vis';
|
||||
}
|
||||
|
||||
Widget _result(ProbeView view) {
|
||||
final summary = view.summary;
|
||||
final rate = view.rateLabel == '探测无应答'
|
||||
? summary.probeLossPct
|
||||
: view.rateLabel == '失败率'
|
||||
? summary.failurePct
|
||||
: summary.unknownPct;
|
||||
final motd = view.detail['motd'];
|
||||
final version = view.detail['version'];
|
||||
final players = view.detail['players'];
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_chip(view.phase),
|
||||
_chip('来源 ${view.sourceLabel}'),
|
||||
if (view.targetAddress != null) _chip('发往 ${view.targetAddress}'),
|
||||
_chip('延迟 ${formatMs(summary.rttMs)}'),
|
||||
_chip('抖动 ${formatMs(summary.jitterMs)}'),
|
||||
_chip('${view.rateLabel} ${formatPct(rate)}'),
|
||||
],
|
||||
),
|
||||
if (view.targetIsFake) ...[
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
clashFakeIpNote,
|
||||
style: TextStyle(color: Color(0xFF9A3412), fontSize: 13),
|
||||
),
|
||||
],
|
||||
if (view.note.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(view.note, style: const TextStyle(color: ink)),
|
||||
],
|
||||
if (motd != null || version != null || players != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
[
|
||||
if (motd != null) 'MOTD $motd',
|
||||
if (version != null) '版本 $version',
|
||||
if (players != null) '人数 $players',
|
||||
].join(' · '),
|
||||
style: const TextStyle(color: ink),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
Text(summaryLine(summary), style: const TextStyle(color: muted, fontSize: 13)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _manageNodes() async {
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (context) => _NodeDialog(
|
||||
nodes: _nodes,
|
||||
vault: _vault,
|
||||
onChanged: (nodes, selected) {
|
||||
setState(() {
|
||||
_nodes = nodes;
|
||||
if (selected != null) {
|
||||
_nodeId = selected;
|
||||
_remote = true;
|
||||
} else if (_nodes.every((node) => node.id != _nodeId)) {
|
||||
_nodeId = '';
|
||||
}
|
||||
});
|
||||
unawaited(_persist());
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _NodeDialog extends StatefulWidget {
|
||||
const _NodeDialog({
|
||||
required this.nodes,
|
||||
required this.vault,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final List<RemoteNode> nodes;
|
||||
final TokenVault vault;
|
||||
final void Function(List<RemoteNode> nodes, String? selected) onChanged;
|
||||
|
||||
@override
|
||||
State<_NodeDialog> createState() => _NodeDialogState();
|
||||
}
|
||||
|
||||
class _NodeDialogState extends State<_NodeDialog> {
|
||||
late List<RemoteNode> _nodes = [...widget.nodes];
|
||||
final _name = TextEditingController();
|
||||
final _url = TextEditingController();
|
||||
final _token = TextEditingController();
|
||||
String? _hint;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
_url.dispose();
|
||||
_token.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
final url = normalizeNodeUrl(_url.text);
|
||||
if (_name.text.trim().isEmpty || url == null) {
|
||||
setState(() => _hint = '请填写名称,以及不带口令的 http 或 https 地址');
|
||||
return;
|
||||
}
|
||||
final id = DateTime.now().microsecondsSinceEpoch.toString();
|
||||
final node = RemoteNode(id: id, name: _name.text.trim(), baseUrl: url);
|
||||
await widget.vault.write(nodeTokenKey(id), _token.text.trim());
|
||||
setState(() {
|
||||
_nodes = [..._nodes, node];
|
||||
_hint = '已保存。口令只留在本机。';
|
||||
_name.clear();
|
||||
_url.clear();
|
||||
_token.clear();
|
||||
});
|
||||
widget.onChanged(_nodes, id);
|
||||
}
|
||||
|
||||
Future<void> _check(RemoteNode node) async {
|
||||
try {
|
||||
final info = await fetchNodeInfo(node.baseUrl);
|
||||
final next = [
|
||||
for (final item in _nodes)
|
||||
if (item.id == node.id)
|
||||
item.copyWith(visibility: info.visibility)
|
||||
else
|
||||
item,
|
||||
];
|
||||
setState(() {
|
||||
_nodes = next;
|
||||
_hint = info.authRequired
|
||||
? '这个节点是私有的,请求必须带正确的节点口令,否则不会向目标发包。'
|
||||
: '这个节点是公开的,不需要口令。它仍然有并发、时长和带宽上限。';
|
||||
});
|
||||
widget.onChanged(next, node.id);
|
||||
} on RemoteException catch (error) {
|
||||
setState(() => _hint = error.message);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _delete(RemoteNode node) async {
|
||||
await widget.vault.delete(nodeTokenKey(node.id));
|
||||
final next = [for (final item in _nodes) if (item.id != node.id) item];
|
||||
setState(() => _nodes = next);
|
||||
widget.onChanged(next, null);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('远程节点'),
|
||||
content: SizedBox(
|
||||
width: 460,
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(
|
||||
'节点口令和目标回显口令是两回事。服务器没配置节点口令时,它是公开节点;配置了就必须校验,错误口令不会发出任何探测。',
|
||||
style: TextStyle(fontSize: 13, color: muted),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
for (final node in _nodes)
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(_nodes.isEmpty ? '' : '${node.name} · ${visibilityLabel(node.visibility)}'),
|
||||
subtitle: Text(node.baseUrl, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
trailing: Wrap(
|
||||
spacing: 4,
|
||||
children: [
|
||||
TextButton(onPressed: () => _check(node), child: const Text('检查')),
|
||||
TextButton(onPressed: () => _delete(node), child: const Text('删除')),
|
||||
],
|
||||
),
|
||||
),
|
||||
TextField(
|
||||
controller: _name,
|
||||
decoration: const InputDecoration(labelText: '名称'),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _url,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '节点地址',
|
||||
hintText: 'https://probe.example:8443',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _token,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '节点口令(公开节点留空)',
|
||||
),
|
||||
),
|
||||
if (_hint != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(_hint!, style: const TextStyle(fontSize: 13)),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: _save, child: const Text('添加节点')),
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('完成')),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _card({required String title, required Widget child}) {
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: const BorderSide(color: line),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(title, style: const TextStyle(fontWeight: FontWeight.w700, color: ink)),
|
||||
const SizedBox(height: 10),
|
||||
child,
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _field(
|
||||
TextEditingController controller,
|
||||
String label,
|
||||
String hint, {
|
||||
bool secret = false,
|
||||
}) {
|
||||
return TextField(
|
||||
controller: controller,
|
||||
obscureText: secret,
|
||||
decoration: InputDecoration(labelText: label, hintText: hint),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _pair(bool wide, Widget left, Widget right) {
|
||||
if (!wide) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [left, const SizedBox(height: 12), right],
|
||||
);
|
||||
}
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(child: left),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: right),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _chip(String text) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFE7EEF5),
|
||||
borderRadius: BorderRadius.circular(99),
|
||||
),
|
||||
child: Text(text, style: const TextStyle(fontSize: 12, color: ink)),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _banner(String text) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFFF1E8),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: const Color(0xFFF0C9B0)),
|
||||
),
|
||||
child: Text(text, style: const TextStyle(color: Color(0xFF9A3412))),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import 'package:fl_chart/fl_chart.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../probe/probe_controller.dart';
|
||||
|
||||
const rttColor = Color(0xFF1F4E79);
|
||||
const rateColor = Color(0xFF9A3412);
|
||||
const ink = Color(0xFF1C2430);
|
||||
const muted = Color(0xFF5E6872);
|
||||
const line = Color(0xFFE4DFD4);
|
||||
|
||||
class QualityCharts extends StatelessWidget {
|
||||
const QualityCharts({
|
||||
super.key,
|
||||
required this.samples,
|
||||
required this.rateLabel,
|
||||
required this.running,
|
||||
});
|
||||
|
||||
final List<ChartSample> samples;
|
||||
final String rateLabel;
|
||||
final bool running;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Row(
|
||||
children: [
|
||||
_Swatch(color: rttColor, label: '往返时间'),
|
||||
SizedBox(width: 16),
|
||||
_Swatch(color: rateColor, label: '比率'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_ChartCard(
|
||||
title: '延迟',
|
||||
unit: 'ms',
|
||||
samples: samples,
|
||||
read: (sample) => sample.rttMs,
|
||||
color: rttColor,
|
||||
floor: 1,
|
||||
running: running,
|
||||
),
|
||||
_ChartCard(
|
||||
title: rateLabel,
|
||||
unit: '%',
|
||||
samples: samples,
|
||||
read: (sample) => sample.ratePct,
|
||||
color: rateColor,
|
||||
floor: 10,
|
||||
running: running,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Swatch extends StatelessWidget {
|
||||
const _Swatch({required this.color, required this.label});
|
||||
|
||||
final Color color;
|
||||
final String label;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 14,
|
||||
height: 3,
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(label, style: const TextStyle(color: muted, fontSize: 12)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ChartCard extends StatelessWidget {
|
||||
const _ChartCard({
|
||||
required this.title,
|
||||
required this.unit,
|
||||
required this.samples,
|
||||
required this.read,
|
||||
required this.color,
|
||||
required this.floor,
|
||||
required this.running,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String unit;
|
||||
final List<ChartSample> samples;
|
||||
final double? Function(ChartSample sample) read;
|
||||
final Color color;
|
||||
final double floor;
|
||||
final bool running;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final spots = _spots();
|
||||
final hasData = spots.any((spot) => !spot.isNull());
|
||||
return Card(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
side: const BorderSide(color: line),
|
||||
),
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 12, 12, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'$title($unit)',
|
||||
style: const TextStyle(
|
||||
color: ink,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SizedBox(
|
||||
height: 168,
|
||||
child: hasData
|
||||
? _lineChart(spots)
|
||||
: Center(
|
||||
child: Text(
|
||||
running
|
||||
? '正在等待第一次完成的探测。未完成的不会画成 100%。'
|
||||
: '暂无已完成的探测',
|
||||
style: const TextStyle(color: muted),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<FlSpot> _spots() {
|
||||
final spots = <FlSpot>[];
|
||||
for (final sample in samples) {
|
||||
final value = read(sample);
|
||||
if (value == null) {
|
||||
if (spots.isNotEmpty && !spots.last.isNull()) {
|
||||
spots.add(FlSpot.nullSpot);
|
||||
}
|
||||
} else {
|
||||
spots.add(FlSpot(sample.sec, value));
|
||||
}
|
||||
}
|
||||
if (spots.isNotEmpty && spots.last.isNull()) {
|
||||
spots.removeLast();
|
||||
}
|
||||
return spots;
|
||||
}
|
||||
|
||||
Widget _lineChart(List<FlSpot> spots) {
|
||||
final minX = samples.first.sec;
|
||||
var maxX = samples.last.sec;
|
||||
if (maxX - minX < 1) {
|
||||
maxX = minX + 1;
|
||||
}
|
||||
var maxY = floor;
|
||||
for (final spot in spots) {
|
||||
if (!spot.isNull() && spot.y > maxY) {
|
||||
maxY = spot.y;
|
||||
}
|
||||
}
|
||||
maxY = maxY * 1.2;
|
||||
final yInterval = _yInterval(maxY);
|
||||
final xInterval = _xInterval(maxX - minX);
|
||||
return LineChart(
|
||||
LineChartData(
|
||||
minX: minX,
|
||||
maxX: maxX,
|
||||
minY: 0,
|
||||
maxY: maxY,
|
||||
clipData: const FlClipData.all(),
|
||||
gridData: FlGridData(
|
||||
show: true,
|
||||
drawVerticalLine: false,
|
||||
horizontalInterval: yInterval,
|
||||
getDrawingHorizontalLine: (_) => const FlLine(color: line, strokeWidth: 1),
|
||||
),
|
||||
borderData: FlBorderData(
|
||||
show: true,
|
||||
border: const Border(
|
||||
left: BorderSide(color: line),
|
||||
bottom: BorderSide(color: line),
|
||||
),
|
||||
),
|
||||
titlesData: FlTitlesData(
|
||||
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||
leftTitles: AxisTitles(
|
||||
sideTitles: SideTitles(
|
||||
showTitles: true,
|
||||
reservedSize: 40,
|
||||
interval: yInterval,
|
||||
getTitlesWidget: (value, meta) => _axisLabel(_formatTick(value, maxY)),
|
||||
),
|
||||
),
|
||||
bottomTitles: AxisTitles(
|
||||
sideTitles: SideTitles(
|
||||
showTitles: true,
|
||||
reservedSize: 26,
|
||||
interval: xInterval,
|
||||
getTitlesWidget: (value, meta) =>
|
||||
_axisLabel('${value.toStringAsFixed(0)}s'),
|
||||
),
|
||||
),
|
||||
),
|
||||
lineTouchData: const LineTouchData(handleBuiltInTouches: true),
|
||||
lineBarsData: [
|
||||
LineChartBarData(
|
||||
spots: spots,
|
||||
isCurved: false,
|
||||
color: color,
|
||||
barWidth: 2,
|
||||
dotData: const FlDotData(show: false),
|
||||
belowBarData: BarAreaData(show: true, color: color.withValues(alpha: 0.10)),
|
||||
),
|
||||
],
|
||||
),
|
||||
duration: Duration.zero,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _axisLabel(String text) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 4),
|
||||
child: Text(text, style: const TextStyle(color: muted, fontSize: 10)),
|
||||
);
|
||||
}
|
||||
|
||||
double _yInterval(double maxY) {
|
||||
if (maxY <= 1) {
|
||||
return 0.25;
|
||||
}
|
||||
if (maxY <= 5) {
|
||||
return 1;
|
||||
}
|
||||
if (maxY <= 20) {
|
||||
return 5;
|
||||
}
|
||||
if (maxY <= 50) {
|
||||
return 10;
|
||||
}
|
||||
if (maxY <= 120) {
|
||||
return 20;
|
||||
}
|
||||
if (maxY <= 300) {
|
||||
return 50;
|
||||
}
|
||||
return 100;
|
||||
}
|
||||
|
||||
double _xInterval(double span) {
|
||||
if (span <= 15) {
|
||||
return 5;
|
||||
}
|
||||
if (span <= 40) {
|
||||
return 10;
|
||||
}
|
||||
return 15;
|
||||
}
|
||||
|
||||
String _formatTick(double value, double maxY) {
|
||||
if (maxY < 5) {
|
||||
return value.toStringAsFixed(value < 1 ? 2 : 1);
|
||||
}
|
||||
return value.toStringAsFixed(0);
|
||||
}
|
||||
Reference in new issue
Block a user